]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
* textmodes/org-export-latex.el (org-export-latex-cleaned-string):
[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 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.13i
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 (require 'easymenu)
81
82 ;;;; Customization variables
83
84 ;;; Version
85
86 (defconst org-version "5.13i"
87 "The version number of the file org.el.")
88 (defun org-version ()
89 (interactive)
90 (message "Org-mode version %s" org-version))
91
92 ;;; Compatibility constants
93 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
94 (defconst org-format-transports-properties-p
95 (let ((x "a"))
96 (add-text-properties 0 1 '(test t) x)
97 (get-text-property 0 'test (format "%s" x)))
98 "Does format transport text properties?")
99
100 (defmacro org-unmodified (&rest body)
101 "Execute body without changing buffer-modified-p."
102 `(set-buffer-modified-p
103 (prog1 (buffer-modified-p) ,@body)))
104
105 (defmacro org-re (s)
106 "Replace posix classes in regular expression."
107 (if (featurep 'xemacs)
108 (let ((ss s))
109 (save-match-data
110 (while (string-match "\\[:alnum:\\]" ss)
111 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
112 (while (string-match "\\[:alpha:\\]" ss)
113 (setq ss (replace-match "a-zA-Z" t t ss)))
114 ss))
115 s))
116
117 (defmacro org-preserve-lc (&rest body)
118 `(let ((_line (org-current-line))
119 (_col (current-column)))
120 (unwind-protect
121 (progn ,@body)
122 (goto-line _line)
123 (move-to-column _col))))
124
125 (defmacro org-without-partial-completion (&rest body)
126 `(let ((pc-mode (and (boundp 'partial-completion-mode)
127 partial-completion-mode)))
128 (unwind-protect
129 (progn
130 (if pc-mode (partial-completion-mode -1))
131 ,@body)
132 (if pc-mode (partial-completion-mode 1)))))
133
134 ;;; The custom variables
135
136 (defgroup org nil
137 "Outline-based notes management and organizer."
138 :tag "Org"
139 :group 'outlines
140 :group 'hypermedia
141 :group 'calendar)
142
143 ;; FIXME: Needs a separate group...
144 (defcustom org-completion-fallback-command 'hippie-expand
145 "The expansion command called by \\[org-complete] in normal context.
146 Normal means, no org-mode-specific context."
147 :group 'org
148 :type 'function)
149
150 (defgroup org-startup nil
151 "Options concerning startup of Org-mode."
152 :tag "Org Startup"
153 :group 'org)
154
155 (defcustom org-startup-folded t
156 "Non-nil means, entering Org-mode will switch to OVERVIEW.
157 This can also be configured on a per-file basis by adding one of
158 the following lines anywhere in the buffer:
159
160 #+STARTUP: fold
161 #+STARTUP: nofold
162 #+STARTUP: content"
163 :group 'org-startup
164 :type '(choice
165 (const :tag "nofold: show all" nil)
166 (const :tag "fold: overview" t)
167 (const :tag "content: all headlines" content)))
168
169 (defcustom org-startup-truncated t
170 "Non-nil means, entering Org-mode will set `truncate-lines'.
171 This is useful since some lines containing links can be very long and
172 uninteresting. Also tables look terrible when wrapped."
173 :group 'org-startup
174 :type 'boolean)
175
176 (defcustom org-startup-align-all-tables nil
177 "Non-nil means, align all tables when visiting a file.
178 This is useful when the column width in tables is forced with <N> cookies
179 in table fields. Such tables will look correct only after the first re-align.
180 This can also be configured on a per-file basis by adding one of
181 the following lines anywhere in the buffer:
182 #+STARTUP: align
183 #+STARTUP: noalign"
184 :group 'org-startup
185 :type 'boolean)
186
187 (defcustom org-insert-mode-line-in-empty-file nil
188 "Non-nil means insert the first line setting Org-mode in empty files.
189 When the function `org-mode' is called interactively in an empty file, this
190 normally means that the file name does not automatically trigger Org-mode.
191 To ensure that the file will always be in Org-mode in the future, a
192 line enforcing Org-mode will be inserted into the buffer, if this option
193 has been set."
194 :group 'org-startup
195 :type 'boolean)
196
197 (defcustom org-replace-disputed-keys nil
198 "Non-nil means use alternative key bindings for some keys.
199 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
200 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
201 If you want to use Org-mode together with one of these other modes,
202 or more generally if you would like to move some Org-mode commands to
203 other keys, set this variable and configure the keys with the variable
204 `org-disputed-keys'.
205
206 This option is only relevant at load-time of Org-mode, and must be set
207 *before* org.el is loaded. Changing it requires a restart of Emacs to
208 become effective."
209 :group 'org-startup
210 :type 'boolean)
211
212 (if (fboundp 'defvaralias)
213 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
214
215 (defcustom org-disputed-keys
216 '(([(shift up)] . [(meta p)])
217 ([(shift down)] . [(meta n)])
218 ([(shift left)] . [(meta -)])
219 ([(shift right)] . [(meta +)])
220 ([(control shift right)] . [(meta shift +)])
221 ([(control shift left)] . [(meta shift -)]))
222 "Keys for which Org-mode and other modes compete.
223 This is an alist, cars are the default keys, second element specifies
224 the alternative to use when `org-replace-disputed-keys' is t.
225
226 Keys can be specified in any syntax supported by `define-key'.
227 The value of this option takes effect only at Org-mode's startup,
228 therefore you'll have to restart Emacs to apply it after changing."
229 :group 'org-startup
230 :type 'alist)
231
232 (defun org-key (key)
233 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
234 Or return the original if not disputed."
235 (if org-replace-disputed-keys
236 (let* ((nkey (key-description key))
237 (x (org-find-if (lambda (x)
238 (equal (key-description (car x)) nkey))
239 org-disputed-keys)))
240 (if x (cdr x) key))
241 key))
242
243 (defun org-find-if (predicate seq)
244 (catch 'exit
245 (while seq
246 (if (funcall predicate (car seq))
247 (throw 'exit (car seq))
248 (pop seq)))))
249
250 (defun org-defkey (keymap key def)
251 "Define a key, possibly translated, as returned by `org-key'."
252 (define-key keymap (org-key key) def))
253
254 (defcustom org-ellipsis 'org-ellipsis
255 "The ellipsis to use in the Org-mode outline.
256 When nil, just use the standard three dots. When a string, use that instead,
257 When a face, use the standart 3 dots, but with the specified face.
258 The change affects only Org-mode (which will then use its own display table).
259 Changing this requires executing `M-x org-mode' in a buffer to become
260 effective."
261 :group 'org-startup
262 :type '(choice (const :tag "Default" nil)
263 (face :tag "Face" :value org-warning)
264 (string :tag "String" :value "...#")))
265
266 (defvar org-display-table nil
267 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
268
269 (defgroup org-keywords nil
270 "Keywords in Org-mode."
271 :tag "Org Keywords"
272 :group 'org)
273
274 (defcustom org-deadline-string "DEADLINE:"
275 "String to mark deadline entries.
276 A deadline is this string, followed by a time stamp. Should be a word,
277 terminated by a colon. You can insert a schedule keyword and
278 a timestamp with \\[org-deadline].
279 Changes become only effective after restarting Emacs."
280 :group 'org-keywords
281 :type 'string)
282
283 (defcustom org-scheduled-string "SCHEDULED:"
284 "String to mark scheduled TODO entries.
285 A schedule is this string, followed by a time stamp. Should be a word,
286 terminated by a colon. You can insert a schedule keyword and
287 a timestamp with \\[org-schedule].
288 Changes become only effective after restarting Emacs."
289 :group 'org-keywords
290 :type 'string)
291
292 (defcustom org-closed-string "CLOSED:"
293 "String used as the prefix for timestamps logging closing a TODO entry."
294 :group 'org-keywords
295 :type 'string)
296
297 (defcustom org-clock-string "CLOCK:"
298 "String used as prefix for timestamps clocking work hours on an item."
299 :group 'org-keywords
300 :type 'string)
301
302 (defcustom org-comment-string "COMMENT"
303 "Entries starting with this keyword will never be exported.
304 An entry can be toggled between COMMENT and normal with
305 \\[org-toggle-comment].
306 Changes become only effective after restarting Emacs."
307 :group 'org-keywords
308 :type 'string)
309
310 (defcustom org-quote-string "QUOTE"
311 "Entries starting with this keyword will be exported in fixed-width font.
312 Quoting applies only to the text in the entry following the headline, and does
313 not extend beyond the next headline, even if that is lower level.
314 An entry can be toggled between QUOTE and normal with
315 \\[org-toggle-fixed-width-section]."
316 :group 'org-keywords
317 :type 'string)
318
319 (defconst org-repeat-re
320 (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
321 " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
322 "Regular expression for specifying repeated events.
323 After a match, group 1 contains the repeat expression.")
324
325 (defgroup org-structure nil
326 "Options concerning the general structure of Org-mode files."
327 :tag "Org Structure"
328 :group 'org)
329
330 (defgroup org-reveal-location nil
331 "Options about how to make context of a location visible."
332 :tag "Org Reveal Location"
333 :group 'org-structure)
334
335 (defcustom org-show-hierarchy-above '((default . t))
336 "Non-nil means, show full hierarchy when revealing a location.
337 Org-mode often shows locations in an org-mode file which might have
338 been invisible before. When this is set, the hierarchy of headings
339 above the exposed location is shown.
340 Turning this off for example for sparse trees makes them very compact.
341 Instead of t, this can also be an alist specifying this option for different
342 contexts. Valid contexts are
343 agenda when exposing an entry from the agenda
344 org-goto when using the command `org-goto' on key C-c C-j
345 occur-tree when using the command `org-occur' on key C-c /
346 tags-tree when constructing a sparse tree based on tags matches
347 link-search when exposing search matches associated with a link
348 mark-goto when exposing the jump goal of a mark
349 bookmark-jump when exposing a bookmark location
350 isearch when exiting from an incremental search
351 default default for all contexts not set explicitly"
352 :group 'org-reveal-location
353 :type '(choice
354 (const :tag "Always" t)
355 (const :tag "Never" nil)
356 (repeat :greedy t :tag "Individual contexts"
357 (cons
358 (choice :tag "Context"
359 (const agenda)
360 (const org-goto)
361 (const occur-tree)
362 (const tags-tree)
363 (const link-search)
364 (const mark-goto)
365 (const bookmark-jump)
366 (const isearch)
367 (const default))
368 (boolean)))))
369
370 (defcustom org-show-following-heading '((default . nil))
371 "Non-nil means, show following heading when revealing a location.
372 Org-mode often shows locations in an org-mode file which might have
373 been invisible before. When this is set, the heading following the
374 match is shown.
375 Turning this off for example for sparse trees makes them very compact,
376 but makes it harder to edit the location of the match. In such a case,
377 use the command \\[org-reveal] to show more context.
378 Instead of t, this can also be an alist specifying this option for different
379 contexts. See `org-show-hierarchy-above' for valid contexts."
380 :group 'org-reveal-location
381 :type '(choice
382 (const :tag "Always" t)
383 (const :tag "Never" nil)
384 (repeat :greedy t :tag "Individual contexts"
385 (cons
386 (choice :tag "Context"
387 (const agenda)
388 (const org-goto)
389 (const occur-tree)
390 (const tags-tree)
391 (const link-search)
392 (const mark-goto)
393 (const bookmark-jump)
394 (const isearch)
395 (const default))
396 (boolean)))))
397
398 (defcustom org-show-siblings '((default . nil) (isearch t))
399 "Non-nil means, show all sibling heading when revealing a location.
400 Org-mode often shows locations in an org-mode file which might have
401 been invisible before. When this is set, the sibling of the current entry
402 heading are all made visible. If `org-show-hierarchy-above' is t,
403 the same happens on each level of the hierarchy above the current entry.
404
405 By default this is on for the isearch context, off for all other contexts.
406 Turning this off for example for sparse trees makes them very compact,
407 but makes it harder to edit the location of the match. In such a case,
408 use the command \\[org-reveal] to show more context.
409 Instead of t, this can also be an alist specifying this option for different
410 contexts. See `org-show-hierarchy-above' for valid contexts."
411 :group 'org-reveal-location
412 :type '(choice
413 (const :tag "Always" t)
414 (const :tag "Never" nil)
415 (repeat :greedy t :tag "Individual contexts"
416 (cons
417 (choice :tag "Context"
418 (const agenda)
419 (const org-goto)
420 (const occur-tree)
421 (const tags-tree)
422 (const link-search)
423 (const mark-goto)
424 (const bookmark-jump)
425 (const isearch)
426 (const default))
427 (boolean)))))
428
429 (defgroup org-cycle nil
430 "Options concerning visibility cycling in Org-mode."
431 :tag "Org Cycle"
432 :group 'org-structure)
433
434 (defcustom org-drawers '("PROPERTIES" "CLOCK")
435 "Names of drawers. Drawers are not opened by cycling on the headline above.
436 Drawers only open with a TAB on the drawer line itself. A drawer looks like
437 this:
438 :DRAWERNAME:
439 .....
440 :END:
441 The drawer \"PROPERTIES\" is special for capturing properties through
442 the property API.
443
444 Drawers can be defined on the per-file basis with a line like:
445
446 #+DRAWERS: HIDDEN STATE PROPERTIES"
447 :group 'org-structure
448 :type '(repeat (string :tag "Drawer Name")))
449
450 (defcustom org-cycle-global-at-bob nil
451 "Cycle globally if cursor is at beginning of buffer and not at a headline.
452 This makes it possible to do global cycling without having to use S-TAB or
453 C-u TAB. For this special case to work, the first line of the buffer
454 must not be a headline - it may be empty ot some other text. When used in
455 this way, `org-cycle-hook' is disables temporarily, to make sure the
456 cursor stays at the beginning of the buffer.
457 When this option is nil, don't do anything special at the beginning
458 of the buffer."
459 :group 'org-cycle
460 :type 'boolean)
461
462 (defcustom org-cycle-emulate-tab t
463 "Where should `org-cycle' emulate TAB.
464 nil Never
465 white Only in completely white lines
466 whitestart Only at the beginning of lines, before the first non-white char.
467 t Everywhere except in headlines
468 exc-hl-bol Everywhere except at the start of a headline
469 If TAB is used in a place where it does not emulate TAB, the current subtree
470 visibility is cycled."
471 :group 'org-cycle
472 :type '(choice (const :tag "Never" nil)
473 (const :tag "Only in completely white lines" white)
474 (const :tag "Before first char in a line" whitestart)
475 (const :tag "Everywhere except in headlines" t)
476 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
477 ))
478
479 (defcustom org-cycle-separator-lines 2
480 "Number of empty lines needed to keep an empty line between collapsed trees.
481 If you leave an empty line between the end of a subtree and the following
482 headline, this empty line is hidden when the subtree is folded.
483 Org-mode will leave (exactly) one empty line visible if the number of
484 empty lines is equal or larger to the number given in this variable.
485 So the default 2 means, at least 2 empty lines after the end of a subtree
486 are needed to produce free space between a collapsed subtree and the
487 following headline.
488
489 Special case: when 0, never leave empty lines in collapsed view."
490 :group 'org-cycle
491 :type 'integer)
492
493 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
494 org-cycle-hide-drawers
495 org-cycle-show-empty-lines
496 org-optimize-window-after-visibility-change)
497 "Hook that is run after `org-cycle' has changed the buffer visibility.
498 The function(s) in this hook must accept a single argument which indicates
499 the new state that was set by the most recent `org-cycle' command. The
500 argument is a symbol. After a global state change, it can have the values
501 `overview', `content', or `all'. After a local state change, it can have
502 the values `folded', `children', or `subtree'."
503 :group 'org-cycle
504 :type 'hook)
505
506 (defgroup org-edit-structure nil
507 "Options concerning structure editing in Org-mode."
508 :tag "Org Edit Structure"
509 :group 'org-structure)
510
511 (defcustom org-special-ctrl-a/e nil
512 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
513 When t, `C-a' will bring back the cursor to the beginning of the
514 headline text, i.e. after the stars and after a possible TODO keyword.
515 In an item, this will be the position after the bullet.
516 When the cursor is already at that position, another `C-a' will bring
517 it to the beginning of the line.
518 `C-e' will jump to the end of the headline, ignoring the presence of tags
519 in the headline. A second `C-e' will then jump to the true end of the
520 line, after any tags.
521 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
522 and only a directly following, identical keypress will bring the cursor
523 to the special positions."
524 :group 'org-edit-structure
525 :type '(choice
526 (const :tag "off" nil)
527 (const :tag "after bullet first" t)
528 (const :tag "border first" reversed)))
529
530 (if (fboundp 'defvaralias)
531 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
532
533 (defcustom org-odd-levels-only nil
534 "Non-nil means, skip even levels and only use odd levels for the outline.
535 This has the effect that two stars are being added/taken away in
536 promotion/demotion commands. It also influences how levels are
537 handled by the exporters.
538 Changing it requires restart of `font-lock-mode' to become effective
539 for fontification also in regions already fontified.
540 You may also set this on a per-file basis by adding one of the following
541 lines to the buffer:
542
543 #+STARTUP: odd
544 #+STARTUP: oddeven"
545 :group 'org-edit-structure
546 :group 'org-font-lock
547 :type 'boolean)
548
549 (defcustom org-adapt-indentation t
550 "Non-nil means, adapt indentation when promoting and demoting.
551 When this is set and the *entire* text in an entry is indented, the
552 indentation is increased by one space in a demotion command, and
553 decreased by one in a promotion command. If any line in the entry
554 body starts at column 0, indentation is not changed at all."
555 :group 'org-edit-structure
556 :type 'boolean)
557
558 (defcustom org-blank-before-new-entry '((heading . nil)
559 (plain-list-item . nil))
560 "Should `org-insert-heading' leave a blank line before new heading/item?
561 The value is an alist, with `heading' and `plain-list-item' as car,
562 and a boolean flag as cdr."
563 :group 'org-edit-structure
564 :type '(list
565 (cons (const heading) (boolean))
566 (cons (const plain-list-item) (boolean))))
567
568 (defcustom org-insert-heading-hook nil
569 "Hook being run after inserting a new heading."
570 :group 'org-edit-structure
571 :type 'boolean)
572
573 (defcustom org-enable-fixed-width-editor t
574 "Non-nil means, lines starting with \":\" are treated as fixed-width.
575 This currently only means, they are never auto-wrapped.
576 When nil, such lines will be treated like ordinary lines.
577 See also the QUOTE keyword."
578 :group 'org-edit-structure
579 :type 'boolean)
580
581 (defgroup org-sparse-trees nil
582 "Options concerning sparse trees in Org-mode."
583 :tag "Org Sparse Trees"
584 :group 'org-structure)
585
586 (defcustom org-highlight-sparse-tree-matches t
587 "Non-nil means, highlight all matches that define a sparse tree.
588 The highlights will automatically disappear the next time the buffer is
589 changed by an edit command."
590 :group 'org-sparse-trees
591 :type 'boolean)
592
593 (defcustom org-remove-highlights-with-change t
594 "Non-nil means, any change to the buffer will remove temporary highlights.
595 Such highlights are created by `org-occur' and `org-clock-display'.
596 When nil, `C-c C-c needs to be used to get rid of the highlights.
597 The highlights created by `org-preview-latex-fragment' always need
598 `C-c C-c' to be removed."
599 :group 'org-sparse-trees
600 :group 'org-time
601 :type 'boolean)
602
603
604 (defcustom org-occur-hook '(org-first-headline-recenter)
605 "Hook that is run after `org-occur' has constructed a sparse tree.
606 This can be used to recenter the window to show as much of the structure
607 as possible."
608 :group 'org-sparse-trees
609 :type 'hook)
610
611 (defgroup org-plain-lists nil
612 "Options concerning plain lists in Org-mode."
613 :tag "Org Plain lists"
614 :group 'org-structure)
615
616 (defcustom org-cycle-include-plain-lists nil
617 "Non-nil means, include plain lists into visibility cycling.
618 This means that during cycling, plain list items will *temporarily* be
619 interpreted as outline headlines with a level given by 1000+i where i is the
620 indentation of the bullet. In all other operations, plain list items are
621 not seen as headlines. For example, you cannot assign a TODO keyword to
622 such an item."
623 :group 'org-plain-lists
624 :type 'boolean)
625
626 (defcustom org-plain-list-ordered-item-terminator t
627 "The character that makes a line with leading number an ordered list item.
628 Valid values are ?. and ?\). To get both terminators, use t. While
629 ?. may look nicer, it creates the danger that a line with leading
630 number may be incorrectly interpreted as an item. ?\) therefore is
631 the safe choice."
632 :group 'org-plain-lists
633 :type '(choice (const :tag "dot like in \"2.\"" ?.)
634 (const :tag "paren like in \"2)\"" ?\))
635 (const :tab "both" t)))
636
637 (defcustom org-auto-renumber-ordered-lists t
638 "Non-nil means, automatically renumber ordered plain lists.
639 Renumbering happens when the sequence have been changed with
640 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
641 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
642 :group 'org-plain-lists
643 :type 'boolean)
644
645 (defcustom org-provide-checkbox-statistics t
646 "Non-nil means, update checkbox statistics after insert and toggle.
647 When this is set, checkbox statistics is updated each time you either insert
648 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
649 with \\[org-ctrl-c-ctrl-c\\]."
650 :group 'org-plain-lists
651 :type 'boolean)
652
653 (defgroup org-archive nil
654 "Options concerning archiving in Org-mode."
655 :tag "Org Archive"
656 :group 'org-structure)
657
658 (defcustom org-archive-tag "ARCHIVE"
659 "The tag that marks a subtree as archived.
660 An archived subtree does not open during visibility cycling, and does
661 not contribute to the agenda listings."
662 :group 'org-archive
663 :group 'org-keywords
664 :type 'string)
665
666 (defcustom org-agenda-skip-archived-trees t
667 "Non-nil means, the agenda will skip any items located in archived trees.
668 An archived tree is a tree marked with the tag ARCHIVE."
669 :group 'org-archive
670 :group 'org-agenda-skip
671 :type 'boolean)
672
673 (defcustom org-cycle-open-archived-trees nil
674 "Non-nil means, `org-cycle' will open archived trees.
675 An archived tree is a tree marked with the tag ARCHIVE.
676 When nil, archived trees will stay folded. You can still open them with
677 normal outline commands like `show-all', but not with the cycling commands."
678 :group 'org-archive
679 :group 'org-cycle
680 :type 'boolean)
681
682 (defcustom org-sparse-tree-open-archived-trees nil
683 "Non-nil means sparse tree construction shows matches in archived trees.
684 When nil, matches in these trees are highlighted, but the trees are kept in
685 collapsed state."
686 :group 'org-archive
687 :group 'org-sparse-trees
688 :type 'boolean)
689
690 (defcustom org-archive-location "%s_archive::"
691 "The location where subtrees should be archived.
692 This string consists of two parts, separated by a double-colon.
693
694 The first part is a file name - when omitted, archiving happens in the same
695 file. %s will be replaced by the current file name (without directory part).
696 Archiving to a different file is useful to keep archived entries from
697 contributing to the Org-mode Agenda.
698
699 The part after the double colon is a headline. The archived entries will be
700 filed under that headline. When omitted, the subtrees are simply filed away
701 at the end of the file, as top-level entries.
702
703 Here are a few examples:
704 \"%s_archive::\"
705 If the current file is Projects.org, archive in file
706 Projects.org_archive, as top-level trees. This is the default.
707
708 \"::* Archived Tasks\"
709 Archive in the current file, under the top-level headline
710 \"* Archived Tasks\".
711
712 \"~/org/archive.org::\"
713 Archive in file ~/org/archive.org (absolute path), as top-level trees.
714
715 \"basement::** Finished Tasks\"
716 Archive in file ./basement (relative path), as level 3 trees
717 below the level 2 heading \"** Finished Tasks\".
718
719 You may set this option on a per-file basis by adding to the buffer a
720 line like
721
722 #+ARCHIVE: basement::** Finished Tasks"
723 :group 'org-archive
724 :type 'string)
725
726 (defcustom org-archive-mark-done t
727 "Non-nil means, mark entries as DONE when they are moved to the archive file.
728 This can be a string to set the keyword to use. When t, Org-mode will
729 use the first keyword in its list that means done."
730 :group 'org-archive
731 :type '(choice
732 (const :tag "No" nil)
733 (const :tag "Yes" t)
734 (string :tag "Use this keyword")))
735
736 (defcustom org-archive-stamp-time t
737 "Non-nil means, add a time stamp to entries moved to an archive file.
738 This variable is obsolete and has no effect anymore, instead add ot remove
739 `time' from the variablle `org-archive-save-context-info'."
740 :group 'org-archive
741 :type 'boolean)
742
743 (defcustom org-archive-save-context-info '(time file category todo itags)
744 "Parts of context info that should be stored as properties when archiving.
745 When a subtree is moved to an archive file, it looses information given by
746 context, like inherited tags, the category, and possibly also the TODO
747 state (depending on the variable `org-archive-mark-done').
748 This variable can be a list of any of the following symbols:
749
750 time The time of archiving.
751 file The file where the entry originates.
752 itags The local tags, in the headline of the subtree.
753 ltags The tags the subtree inherits from further up the hierarchy.
754 todo The pre-archive TODO state.
755 category The category, taken from file name or #+CATEGORY lines.
756
757 For each symbol present in the list, a property will be created in
758 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
759 information."
760 :group 'org-archive
761 :type '(set :greedy t
762 (const :tag "Time" time)
763 (const :tag "File" file)
764 (const :tag "Category" category)
765 (const :tag "TODO state" todo)
766 (const :tag "TODO state" priority)
767 (const :tag "Inherited tags" itags)
768 (const :tag "Local tags" ltags)))
769
770 (defgroup org-table nil
771 "Options concerning tables in Org-mode."
772 :tag "Org Table"
773 :group 'org)
774
775 (defcustom org-enable-table-editor 'optimized
776 "Non-nil means, lines starting with \"|\" are handled by the table editor.
777 When nil, such lines will be treated like ordinary lines.
778
779 When equal to the symbol `optimized', the table editor will be optimized to
780 do the following:
781 - Automatic overwrite mode in front of whitespace in table fields.
782 This makes the structure of the table stay in tact as long as the edited
783 field does not exceed the column width.
784 - Minimize the number of realigns. Normally, the table is aligned each time
785 TAB or RET are pressed to move to another field. With optimization this
786 happens only if changes to a field might have changed the column width.
787 Optimization requires replacing the functions `self-insert-command',
788 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
789 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
790 very good at guessing when a re-align will be necessary, but you can always
791 force one with \\[org-ctrl-c-ctrl-c].
792
793 If you would like to use the optimized version in Org-mode, but the
794 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
795
796 This variable can be used to turn on and off the table editor during a session,
797 but in order to toggle optimization, a restart is required.
798
799 See also the variable `org-table-auto-blank-field'."
800 :group 'org-table
801 :type '(choice
802 (const :tag "off" nil)
803 (const :tag "on" t)
804 (const :tag "on, optimized" optimized)))
805
806 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
807 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
808 In the optimized version, the table editor takes over all simple keys that
809 normally just insert a character. In tables, the characters are inserted
810 in a way to minimize disturbing the table structure (i.e. in overwrite mode
811 for empty fields). Outside tables, the correct binding of the keys is
812 restored.
813
814 The default for this option is t if the optimized version is also used in
815 Org-mode. See the variable `org-enable-table-editor' for details. Changing
816 this variable requires a restart of Emacs to become effective."
817 :group 'org-table
818 :type 'boolean)
819
820 (defcustom orgtbl-radio-table-templates
821 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
822 % END RECEIVE ORGTBL %n
823 \\begin{comment}
824 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
825 | | |
826 \\end{comment}\n")
827 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
828 @c END RECEIVE ORGTBL %n
829 @ignore
830 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
831 | | |
832 @end ignore\n")
833 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
834 <!-- END RECEIVE ORGTBL %n -->
835 <!--
836 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
837 | | |
838 -->\n"))
839 "Templates for radio tables in different major modes.
840 All occurrences of %n in a template will be replaced with the name of the
841 table, obtained by prompting the user."
842 :group 'org-table
843 :type '(repeat
844 (list (symbol :tag "Major mode")
845 (string :tag "Format"))))
846
847 (defgroup org-table-settings nil
848 "Settings for tables in Org-mode."
849 :tag "Org Table Settings"
850 :group 'org-table)
851
852 (defcustom org-table-default-size "5x2"
853 "The default size for newly created tables, Columns x Rows."
854 :group 'org-table-settings
855 :type 'string)
856
857 (defcustom org-table-number-regexp
858 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
859 "Regular expression for recognizing numbers in table columns.
860 If a table column contains mostly numbers, it will be aligned to the
861 right. If not, it will be aligned to the left.
862
863 The default value of this option is a regular expression which allows
864 anything which looks remotely like a number as used in scientific
865 context. For example, all of the following will be considered a
866 number:
867 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
868
869 Other options offered by the customize interface are more restrictive."
870 :group 'org-table-settings
871 :type '(choice
872 (const :tag "Positive Integers"
873 "^[0-9]+$")
874 (const :tag "Integers"
875 "^[-+]?[0-9]+$")
876 (const :tag "Floating Point Numbers"
877 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
878 (const :tag "Floating Point Number or Integer"
879 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
880 (const :tag "Exponential, Floating point, Integer"
881 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
882 (const :tag "Very General Number-Like, including hex"
883 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
884 (string :tag "Regexp:")))
885
886 (defcustom org-table-number-fraction 0.5
887 "Fraction of numbers in a column required to make the column align right.
888 In a column all non-white fields are considered. If at least this
889 fraction of fields is matched by `org-table-number-fraction',
890 alignment to the right border applies."
891 :group 'org-table-settings
892 :type 'number)
893
894 (defgroup org-table-editing nil
895 "Bahavior of tables during editing in Org-mode."
896 :tag "Org Table Editing"
897 :group 'org-table)
898
899 (defcustom org-table-automatic-realign t
900 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
901 When nil, aligning is only done with \\[org-table-align], or after column
902 removal/insertion."
903 :group 'org-table-editing
904 :type 'boolean)
905
906 (defcustom org-table-auto-blank-field t
907 "Non-nil means, automatically blank table field when starting to type into it.
908 This only happens when typing immediately after a field motion
909 command (TAB, S-TAB or RET).
910 Only relevant when `org-enable-table-editor' is equal to `optimized'."
911 :group 'org-table-editing
912 :type 'boolean)
913
914 (defcustom org-table-tab-jumps-over-hlines t
915 "Non-nil means, tab in the last column of a table with jump over a hline.
916 If a horizontal separator line is following the current line,
917 `org-table-next-field' can either create a new row before that line, or jump
918 over the line. When this option is nil, a new line will be created before
919 this line."
920 :group 'org-table-editing
921 :type 'boolean)
922
923 (defcustom org-table-tab-recognizes-table.el t
924 "Non-nil means, TAB will automatically notice a table.el table.
925 When it sees such a table, it moves point into it and - if necessary -
926 calls `table-recognize-table'."
927 :group 'org-table-editing
928 :type 'boolean)
929
930 (defgroup org-table-calculation nil
931 "Options concerning tables in Org-mode."
932 :tag "Org Table Calculation"
933 :group 'org-table)
934
935 (defcustom org-table-use-standard-references t
936 "Should org-mode work with table refrences like B3 instead of @3$2?
937 Possible values are:
938 nil never use them
939 from accept as input, do not present for editing
940 t: accept as input and present for editing"
941 :group 'org-table-calculation
942 :type '(choice
943 (const :tag "Never, don't even check unser input for them" nil)
944 (const :tag "Always, both as user input, and when editing" t)
945 (const :tag "Convert user input, don't offer during editing" 'from)))
946
947 (defcustom org-table-copy-increment t
948 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
949 :group 'org-table-calculation
950 :type 'boolean)
951
952 (defcustom org-calc-default-modes
953 '(calc-internal-prec 12
954 calc-float-format (float 5)
955 calc-angle-mode deg
956 calc-prefer-frac nil
957 calc-symbolic-mode nil
958 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
959 calc-display-working-message t
960 )
961 "List with Calc mode settings for use in calc-eval for table formulas.
962 The list must contain alternating symbols (Calc modes variables and values).
963 Don't remove any of the default settings, just change the values. Org-mode
964 relies on the variables to be present in the list."
965 :group 'org-table-calculation
966 :type 'plist)
967
968 (defcustom org-table-formula-evaluate-inline t
969 "Non-nil means, TAB and RET evaluate a formula in current table field.
970 If the current field starts with an equal sign, it is assumed to be a formula
971 which should be evaluated as described in the manual and in the documentation
972 string of the command `org-table-eval-formula'. This feature requires the
973 Emacs calc package.
974 When this variable is nil, formula calculation is only available through
975 the command \\[org-table-eval-formula]."
976 :group 'org-table-calculation
977 :type 'boolean)
978
979 (defcustom org-table-formula-use-constants t
980 "Non-nil means, interpret constants in formulas in tables.
981 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
982 by the value given in `org-table-formula-constants', or by a value obtained
983 from the `constants.el' package."
984 :group 'org-table-calculation
985 :type 'boolean)
986
987 (defcustom org-table-formula-constants nil
988 "Alist with constant names and values, for use in table formulas.
989 The car of each element is a name of a constant, without the `$' before it.
990 The cdr is the value as a string. For example, if you'd like to use the
991 speed of light in a formula, you would configure
992
993 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
994
995 and then use it in an equation like `$1*$c'.
996
997 Constants can also be defined on a per-file basis using a line like
998
999 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1000 :group 'org-table-calculation
1001 :type '(repeat
1002 (cons (string :tag "name")
1003 (string :tag "value"))))
1004
1005 (defvar org-table-formula-constants-local nil
1006 "Local version of `org-table-formula-constants'.")
1007 (make-variable-buffer-local 'org-table-formula-constants-local)
1008
1009 (defcustom org-table-allow-automatic-line-recalculation t
1010 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1011 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1012 :group 'org-table-calculation
1013 :type 'boolean)
1014
1015 (defgroup org-link nil
1016 "Options concerning links in Org-mode."
1017 :tag "Org Link"
1018 :group 'org)
1019
1020 (defvar org-link-abbrev-alist-local nil
1021 "Buffer-local version of `org-link-abbrev-alist', which see.
1022 The value of this is taken from the #+LINK lines.")
1023 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1024
1025 (defcustom org-link-abbrev-alist nil
1026 "Alist of link abbreviations.
1027 The car of each element is a string, to be replaced at the start of a link.
1028 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1029 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1030
1031 [[linkkey:tag][description]]
1032
1033 If REPLACE is a string, the tag will simply be appended to create the link.
1034 If the string contains \"%s\", the tag will be inserted there. REPLACE may
1035 also be a function that will be called with the tag as the only argument to
1036 create the link. See the manual for examples."
1037 :group 'org-link
1038 :type 'alist)
1039
1040 (defcustom org-descriptive-links t
1041 "Non-nil means, hide link part and only show description of bracket links.
1042 Bracket links are like [[link][descritpion]]. This variable sets the initial
1043 state in new org-mode buffers. The setting can then be toggled on a
1044 per-buffer basis from the Org->Hyperlinks menu."
1045 :group 'org-link
1046 :type 'boolean)
1047
1048 (defcustom org-link-file-path-type 'adaptive
1049 "How the path name in file links should be stored.
1050 Valid values are:
1051
1052 relative relative to the current directory, i.e. the directory of the file
1053 into which the link is being inserted.
1054 absolute absolute path, if possible with ~ for home directory.
1055 noabbrev absolute path, no abbreviation of home directory.
1056 adaptive Use relative path for files in the current directory and sub-
1057 directories of it. For other files, use an absolute path."
1058 :group 'org-link
1059 :type '(choice
1060 (const relative)
1061 (const absolute)
1062 (const noabbrev)
1063 (const adaptive)))
1064
1065 (defcustom org-activate-links '(bracket angle plain radio tag date)
1066 "Types of links that should be activated in Org-mode files.
1067 This is a list of symbols, each leading to the activation of a certain link
1068 type. In principle, it does not hurt to turn on most link types - there may
1069 be a small gain when turning off unused link types. The types are:
1070
1071 bracket The recommended [[link][description]] or [[link]] links with hiding.
1072 angular Links in angular brackes that may contain whitespace like
1073 <bbdb:Carsten Dominik>.
1074 plain Plain links in normal text, no whitespace, like http://google.com.
1075 radio Text that is matched by a radio target, see manual for details.
1076 tag Tag settings in a headline (link to tag search).
1077 date Time stamps (link to calendar).
1078
1079 Changing this variable requires a restart of Emacs to become effective."
1080 :group 'org-link
1081 :type '(set (const :tag "Double bracket links (new style)" bracket)
1082 (const :tag "Angular bracket links (old style)" angular)
1083 (const :tag "plain text links" plain)
1084 (const :tag "Radio target matches" radio)
1085 (const :tag "Tags" tag)
1086 (const :tag "Tags" target)
1087 (const :tag "Timestamps" date)))
1088
1089 (defgroup org-link-store nil
1090 "Options concerning storing links in Org-mode"
1091 :tag "Org Store Link"
1092 :group 'org-link)
1093
1094 (defcustom org-email-link-description-format "Email %c: %.30s"
1095 "Format of the description part of a link to an email or usenet message.
1096 The following %-excapes will be replaced by corresponding information:
1097
1098 %F full \"From\" field
1099 %f name, taken from \"From\" field, address if no name
1100 %T full \"To\" field
1101 %t first name in \"To\" field, address if no name
1102 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1103 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1104 %s subject
1105 %m message-id.
1106
1107 You may use normal field width specification between the % and the letter.
1108 This is for example useful to limit the length of the subject.
1109
1110 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1111 :group 'org-link-store
1112 :type 'string)
1113
1114 (defcustom org-from-is-user-regexp
1115 (let (r1 r2)
1116 (when (and user-mail-address (not (string= user-mail-address "")))
1117 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1118 (when (and user-full-name (not (string= user-full-name "")))
1119 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1120 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1121 "Regexp mached against the \"From:\" header of an email or usenet message.
1122 It should match if the message is from the user him/herself."
1123 :group 'org-link-store
1124 :type 'regexp)
1125
1126 (defcustom org-context-in-file-links t
1127 "Non-nil means, file links from `org-store-link' contain context.
1128 A search string will be added to the file name with :: as separator and
1129 used to find the context when the link is activated by the command
1130 `org-open-at-point'.
1131 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1132 negates this setting for the duration of the command."
1133 :group 'org-link-store
1134 :type 'boolean)
1135
1136 (defcustom org-keep-stored-link-after-insertion nil
1137 "Non-nil means, keep link in list for entire session.
1138
1139 The command `org-store-link' adds a link pointing to the current
1140 location to an internal list. These links accumulate during a session.
1141 The command `org-insert-link' can be used to insert links into any
1142 Org-mode file (offering completion for all stored links). When this
1143 option is nil, every link which has been inserted once using \\[org-insert-link]
1144 will be removed from the list, to make completing the unused links
1145 more efficient."
1146 :group 'org-link-store
1147 :type 'boolean)
1148
1149 (defcustom org-usenet-links-prefer-google nil
1150 "Non-nil means, `org-store-link' will create web links to Google groups.
1151 When nil, Gnus will be used for such links.
1152 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1153 negates this setting for the duration of the command."
1154 :group 'org-link-store
1155 :type 'boolean)
1156
1157 (defgroup org-link-follow nil
1158 "Options concerning following links in Org-mode"
1159 :tag "Org Follow Link"
1160 :group 'org-link)
1161
1162 (defcustom org-tab-follows-link nil
1163 "Non-nil means, on links TAB will follow the link.
1164 Needs to be set before org.el is loaded."
1165 :group 'org-link-follow
1166 :type 'boolean)
1167
1168 (defcustom org-return-follows-link nil
1169 "Non-nil means, on links RET will follow the link.
1170 Needs to be set before org.el is loaded."
1171 :group 'org-link-follow
1172 :type 'boolean)
1173
1174 (defcustom org-mouse-1-follows-link t
1175 "Non-nil means, mouse-1 on a link will follow the link.
1176 A longer mouse click will still set point. Does not wortk on XEmacs.
1177 Needs to be set before org.el is loaded."
1178 :group 'org-link-follow
1179 :type 'boolean)
1180
1181 (defcustom org-mark-ring-length 4
1182 "Number of different positions to be recorded in the ring
1183 Changing this requires a restart of Emacs to work correctly."
1184 :group 'org-link-follow
1185 :type 'interger)
1186
1187 (defcustom org-link-frame-setup
1188 '((vm . vm-visit-folder-other-frame)
1189 (gnus . gnus-other-frame)
1190 (file . find-file-other-window))
1191 "Setup the frame configuration for following links.
1192 When following a link with Emacs, it may often be useful to display
1193 this link in another window or frame. This variable can be used to
1194 set this up for the different types of links.
1195 For VM, use any of
1196 `vm-visit-folder'
1197 `vm-visit-folder-other-frame'
1198 For Gnus, use any of
1199 `gnus'
1200 `gnus-other-frame'
1201 For FILE, use any of
1202 `find-file'
1203 `find-file-other-window'
1204 `find-file-other-frame'
1205 For the calendar, use the variable `calendar-setup'.
1206 For BBDB, it is currently only possible to display the matches in
1207 another window."
1208 :group 'org-link-follow
1209 :type '(list
1210 (cons (const vm)
1211 (choice
1212 (const vm-visit-folder)
1213 (const vm-visit-folder-other-window)
1214 (const vm-visit-folder-other-frame)))
1215 (cons (const gnus)
1216 (choice
1217 (const gnus)
1218 (const gnus-other-frame)))
1219 (cons (const file)
1220 (choice
1221 (const find-file)
1222 (const find-file-other-window)
1223 (const find-file-other-frame)))))
1224
1225 (defcustom org-display-internal-link-with-indirect-buffer nil
1226 "Non-nil means, use indirect buffer to display infile links.
1227 Activating internal links (from one location in a file to another location
1228 in the same file) normally just jumps to the location. When the link is
1229 activated with a C-u prefix (or with mouse-3), the link is displayed in
1230 another window. When this option is set, the other window actually displays
1231 an indirect buffer clone of the current buffer, to avoid any visibility
1232 changes to the current buffer."
1233 :group 'org-link-follow
1234 :type 'boolean)
1235
1236 (defcustom org-open-non-existing-files nil
1237 "Non-nil means, `org-open-file' will open non-existing files.
1238 When nil, an error will be generated."
1239 :group 'org-link-follow
1240 :type 'boolean)
1241
1242 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1243 "Function and arguments to call for following mailto links.
1244 This is a list with the first element being a lisp function, and the
1245 remaining elements being arguments to the function. In string arguments,
1246 %a will be replaced by the address, and %s will be replaced by the subject
1247 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1248 :group 'org-link-follow
1249 :type '(choice
1250 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1251 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1252 (const :tag "message-mail" (message-mail "%a" "%s"))
1253 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1254
1255 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1256 "Non-nil means, ask for confirmation before executing shell links.
1257 Shell links can be dangerous: just think about a link
1258
1259 [[shell:rm -rf ~/*][Google Search]]
1260
1261 This link would show up in your Org-mode document as \"Google Search\",
1262 but really it would remove your entire home directory.
1263 Therefore we advise against setting this variable to nil.
1264 Just change it to `y-or-n-p' of you want to confirm with a
1265 single keystroke rather than having to type \"yes\"."
1266 :group 'org-link-follow
1267 :type '(choice
1268 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1269 (const :tag "with y-or-n (faster)" y-or-n-p)
1270 (const :tag "no confirmation (dangerous)" nil)))
1271
1272 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1273 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1274 Elisp links can be dangerous: just think about a link
1275
1276 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1277
1278 This link would show up in your Org-mode document as \"Google Search\",
1279 but really it would remove your entire home directory.
1280 Therefore we advise against setting this variable to nil.
1281 Just change it to `y-or-n-p' of you want to confirm with a
1282 single keystroke rather than having to type \"yes\"."
1283 :group 'org-link-follow
1284 :type '(choice
1285 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1286 (const :tag "with y-or-n (faster)" y-or-n-p)
1287 (const :tag "no confirmation (dangerous)" nil)))
1288
1289 (defconst org-file-apps-defaults-gnu
1290 '((remote . emacs)
1291 (t . mailcap))
1292 "Default file applications on a UNIX or GNU/Linux system.
1293 See `org-file-apps'.")
1294
1295 (defconst org-file-apps-defaults-macosx
1296 '((remote . emacs)
1297 (t . "open %s")
1298 ("ps" . "gv %s")
1299 ("ps.gz" . "gv %s")
1300 ("eps" . "gv %s")
1301 ("eps.gz" . "gv %s")
1302 ("dvi" . "xdvi %s")
1303 ("fig" . "xfig %s"))
1304 "Default file applications on a MacOS X system.
1305 The system \"open\" is known as a default, but we use X11 applications
1306 for some files for which the OS does not have a good default.
1307 See `org-file-apps'.")
1308
1309 (defconst org-file-apps-defaults-windowsnt
1310 (list
1311 '(remote . emacs)
1312 (cons t
1313 (list (if (featurep 'xemacs)
1314 'mswindows-shell-execute
1315 'w32-shell-execute)
1316 "open" 'file)))
1317 "Default file applications on a Windows NT system.
1318 The system \"open\" is used for most files.
1319 See `org-file-apps'.")
1320
1321 (defcustom org-file-apps
1322 '(
1323 ("txt" . emacs)
1324 ("tex" . emacs)
1325 ("ltx" . emacs)
1326 ("org" . emacs)
1327 ("el" . emacs)
1328 ("bib" . emacs)
1329 )
1330 "External applications for opening `file:path' items in a document.
1331 Org-mode uses system defaults for different file types, but
1332 you can use this variable to set the application for a given file
1333 extension. The entries in this list are cons cells where the car identifies
1334 files and the cdr the corresponding command. Possible values for the
1335 file identifier are
1336 \"ext\" A string identifying an extension
1337 `directory' Matches a directory
1338 `remote' Matches a remote file, accessible through tramp or efs.
1339 Remote files most likely should be visited through Emacs
1340 because external applications cannot handle such paths.
1341 t Default for all remaining files
1342
1343 Possible values for the command are:
1344 `emacs' The file will be visited by the current Emacs process.
1345 `default' Use the default application for this file type.
1346 string A command to be executed by a shell; %s will be replaced
1347 by the path to the file.
1348 sexp A Lisp form which will be evaluated. The file path will
1349 be available in the Lisp variable `file'.
1350 For more examples, see the system specific constants
1351 `org-file-apps-defaults-macosx'
1352 `org-file-apps-defaults-windowsnt'
1353 `org-file-apps-defaults-gnu'."
1354 :group 'org-link-follow
1355 :type '(repeat
1356 (cons (choice :value ""
1357 (string :tag "Extension")
1358 (const :tag "Default for unrecognized files" t)
1359 (const :tag "Remote file" remote)
1360 (const :tag "Links to a directory" directory))
1361 (choice :value ""
1362 (const :tag "Visit with Emacs" emacs)
1363 (const :tag "Use system default" default)
1364 (string :tag "Command")
1365 (sexp :tag "Lisp form")))))
1366
1367 (defcustom org-mhe-search-all-folders nil
1368 "Non-nil means, that the search for the mh-message will be extended to
1369 all folders if the message cannot be found in the folder given in the link.
1370 Searching all folders is very efficient with one of the search engines
1371 supported by MH-E, but will be slow with pick."
1372 :group 'org-link-follow
1373 :type 'boolean)
1374
1375 (defgroup org-remember nil
1376 "Options concerning interaction with remember.el."
1377 :tag "Org Remember"
1378 :group 'org)
1379
1380 (defcustom org-directory "~/org"
1381 "Directory with org files.
1382 This directory will be used as default to prompt for org files.
1383 Used by the hooks for remember.el."
1384 :group 'org-remember
1385 :type 'directory)
1386
1387 (defcustom org-default-notes-file "~/.notes"
1388 "Default target for storing notes.
1389 Used by the hooks for remember.el. This can be a string, or nil to mean
1390 the value of `remember-data-file'.
1391 You can set this on a per-template basis with the variable
1392 `org-remember-templates'."
1393 :group 'org-remember
1394 :type '(choice
1395 (const :tag "Default from remember-data-file" nil)
1396 file))
1397
1398 (defcustom org-remember-store-without-prompt t
1399 "Non-nil means, `C-c C-c' stores remember note without further promts.
1400 In this case, you need `C-u C-c C-c' to get the prompts for
1401 note file and headline.
1402 When this variable is nil, `C-c C-c' give you the prompts, and
1403 `C-u C-c C-c' trigger the fasttrack."
1404 :group 'org-remember
1405 :type 'boolean)
1406
1407 (defcustom org-remember-default-headline ""
1408 "The headline that should be the default location in the notes file.
1409 When filing remember notes, the cursor will start at that position.
1410 You can set this on a per-template basis with the variable
1411 `org-remember-templates'."
1412 :group 'org-remember
1413 :type 'string)
1414
1415 (defcustom org-remember-templates nil
1416 "Templates for the creation of remember buffers.
1417 When nil, just let remember make the buffer.
1418 When not nil, this is a list of 5-element lists. In each entry, the first
1419 element is a the name of the template, It should be a single short word.
1420 The second element is a character, a unique key to select this template.
1421 The third element is the template. The forth element is optional and can
1422 specify a destination file for remember items created with this template.
1423 The default file is given by `org-default-notes-file'. An optional fifth
1424 element can specify the headline in that file that should be offered
1425 first when the user is asked to file the entry. The default headline is
1426 given in the variable `org-remember-default-headline'.
1427
1428 The template specifies the structure of the remember buffer. It should have
1429 a first line starting with a star, to act as the org-mode headline.
1430 Furthermore, the following %-escapes will be replaced with content:
1431
1432 %^{prompt} prompt the user for a string and replace this sequence with it.
1433 %t time stamp, date only
1434 %T time stamp with date and time
1435 %u, %U like the above, but inactive time stamps
1436 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1437 You may define a prompt like %^{Please specify birthday}t
1438 %n user name (taken from `user-full-name')
1439 %a annotation, normally the link created with org-store-link
1440 %i initial content, the region when remember is called with C-u.
1441 If %i is indented, the entire inserted text will be indented
1442 as well.
1443
1444 %? After completing the template, position cursor here.
1445
1446 Apart from these general escapes, you can access information specific to the
1447 link type that is created. For example, calling `remember' in emails or gnus
1448 will record the author and the subject of the message, which you can access
1449 with %:author and %:subject, respectively. Here is a complete list of what
1450 is recorded for each link type.
1451
1452 Link type | Available information
1453 -------------------+------------------------------------------------------
1454 bbdb | %:type %:name %:company
1455 vm, wl, mh, rmail | %:type %:subject %:message-id
1456 | %:from %:fromname %:fromaddress
1457 | %:to %:toname %:toaddress
1458 | %:fromto (either \"to NAME\" or \"from NAME\")
1459 gnus | %:group, for messages also all email fields
1460 w3, w3m | %:type %:url
1461 info | %:type %:file %:node
1462 calendar | %:type %:date"
1463 :group 'org-remember
1464 :get (lambda (var) ; Make sure all entries have 5 elements
1465 (mapcar (lambda (x)
1466 (if (not (stringp (car x))) (setq x (cons "" x)))
1467 (cond ((= (length x) 4) (append x '("")))
1468 ((= (length x) 3) (append x '("" "")))
1469 (t x)))
1470 (default-value var)))
1471 :type '(repeat
1472 :tag "enabled"
1473 (list :value ("" ?a "\n" nil nil)
1474 (string :tag "Name")
1475 (character :tag "Selection Key")
1476 (string :tag "Template")
1477 (choice
1478 (file :tag "Destination file")
1479 (const :tag "Prompt for file" nil))
1480 (choice
1481 (string :tag "Destination headline")
1482 (const :tag "Selection interface for heading")))))
1483
1484 (defcustom org-reverse-note-order nil
1485 "Non-nil means, store new notes at the beginning of a file or entry.
1486 When nil, new notes will be filed to the end of a file or entry."
1487 :group 'org-remember
1488 :type '(choice
1489 (const :tag "Reverse always" t)
1490 (const :tag "Reverse never" nil)
1491 (repeat :tag "By file name regexp"
1492 (cons regexp boolean))))
1493
1494 (defgroup org-todo nil
1495 "Options concerning TODO items in Org-mode."
1496 :tag "Org TODO"
1497 :group 'org)
1498
1499 (defgroup org-progress nil
1500 "Options concerning Progress logging in Org-mode."
1501 :tag "Org Progress"
1502 :group 'org-time)
1503
1504 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1505 "List of TODO entry keyword sequences and their interpretation.
1506 \\<org-mode-map>This is a list of sequences.
1507
1508 Each sequence starts with a symbol, either `sequence' or `type',
1509 indicating if the keywords should be interpreted as a sequence of
1510 action steps, or as different types of TODO items. The first
1511 keywords are states requiring action - these states will select a headline
1512 for inclusion into the global TODO list Org-mode produces. If one of
1513 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1514 signify that no further action is necessary. If \"|\" is not found,
1515 the last keyword is treated as the only DONE state of the sequence.
1516
1517 The command \\[org-todo] cycles an entry through these states, and one
1518 additional state where no keyword is present. For details about this
1519 cycling, see the manual.
1520
1521 TODO keywords and interpretation can also be set on a per-file basis with
1522 the special #+SEQ_TODO and #+TYP_TODO lines.
1523
1524 For backward compatibility, this variable may also be just a list
1525 of keywords - in this case the interptetation (sequence or type) will be
1526 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1527 :group 'org-todo
1528 :group 'org-keywords
1529 :type '(choice
1530 (repeat :tag "Old syntax, just keywords"
1531 (string :tag "Keyword"))
1532 (repeat :tag "New syntax"
1533 (cons
1534 (choice
1535 :tag "Interpretation"
1536 (const :tag "Sequence (cycling hits every state)" sequence)
1537 (const :tag "Type (cycling directly to DONE)" type))
1538 (repeat
1539 (string :tag "Keyword"))))))
1540
1541 (defvar org-todo-keywords-1 nil)
1542 (make-variable-buffer-local 'org-todo-keywords-1)
1543 (defvar org-todo-keywords-for-agenda nil)
1544 (defvar org-done-keywords-for-agenda nil)
1545 (defvar org-not-done-keywords nil)
1546 (make-variable-buffer-local 'org-not-done-keywords)
1547 (defvar org-done-keywords nil)
1548 (make-variable-buffer-local 'org-done-keywords)
1549 (defvar org-todo-heads nil)
1550 (make-variable-buffer-local 'org-todo-heads)
1551 (defvar org-todo-sets nil)
1552 (make-variable-buffer-local 'org-todo-sets)
1553 (defvar org-todo-log-states nil)
1554 (make-variable-buffer-local 'org-todo-log-states)
1555 (defvar org-todo-kwd-alist nil)
1556 (make-variable-buffer-local 'org-todo-kwd-alist)
1557 (defvar org-todo-key-alist nil)
1558 (make-variable-buffer-local 'org-todo-key-alist)
1559 (defvar org-todo-key-trigger nil)
1560 (make-variable-buffer-local 'org-todo-key-trigger)
1561
1562 (defcustom org-todo-interpretation 'sequence
1563 "Controls how TODO keywords are interpreted.
1564 This variable is in principle obsolete and is only used for
1565 backward compatibility, if the interpretation of todo keywords is
1566 not given already in `org-todo-keywords'. See that variable for
1567 more information."
1568 :group 'org-todo
1569 :group 'org-keywords
1570 :type '(choice (const sequence)
1571 (const type)))
1572
1573 (defcustom org-use-fast-todo-selection 'prefix
1574 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1575 This variable describes if and under what circumstances the cycling
1576 mechanism for TODO keywords will be replaced by a single-key, direct
1577 selection scheme.
1578
1579 When nil, fast selection is never used.
1580
1581 When the symbol `prefix', it will be used when `org-todo' is called with
1582 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1583 in an agenda buffer.
1584
1585 When t, fast selection is used by default. In this case, the prefix
1586 argument forces cycling instead.
1587
1588 In all cases, the special interface is only used if access keys have actually
1589 been assigned by the user, i.e. if keywords in the configuration are followed
1590 by a letter in parenthesis, like TODO(t)."
1591 :group 'org-todo
1592 :type '(choice
1593 (const :tag "Never" nil)
1594 (const :tag "By default" t)
1595 (const :tag "Only with C-u C-c C-t" prefix)))
1596
1597 (defcustom org-after-todo-state-change-hook nil
1598 "Hook which is run after the state of a TODO item was changed.
1599 The new state (a string with a TODO keyword, or nil) is available in the
1600 Lisp variable `state'."
1601 :group 'org-todo
1602 :type 'hook)
1603
1604 (defcustom org-log-done nil
1605 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1606 When the state of an entry is changed from nothing or a DONE state to
1607 a not-done TODO state, remove a previous closing date.
1608
1609 This can also be a list of symbols indicating under which conditions
1610 the time stamp recording the action should be annotated with a short note.
1611 Valid members of this list are
1612
1613 done Offer to record a note when marking entries done
1614 state Offer to record a note whenever changing the TODO state
1615 of an item. This is only relevant if TODO keywords are
1616 interpreted as sequence, see variable `org-todo-interpretation'.
1617 When `state' is set, this includes tracking `done'.
1618 clock-out Offer to record a note when clocking out of an item.
1619
1620 A separate window will then pop up and allow you to type a note.
1621 After finishing with C-c C-c, the note will be added directly after the
1622 timestamp, as a plain list item. See also the variable
1623 `org-log-note-headings'.
1624
1625 Logging can also be configured on a per-file basis by adding one of
1626 the following lines anywhere in the buffer:
1627
1628 #+STARTUP: logdone
1629 #+STARTUP: nologging
1630 #+STARTUP: lognotedone
1631 #+STARTUP: lognotestate
1632 #+STARTUP: lognoteclock-out
1633
1634 You can have local logging settings for a subtree by setting the LOGGING
1635 property to one or more of these keywords."
1636 :group 'org-todo
1637 :group 'org-progress
1638 :type '(choice
1639 (const :tag "off" nil)
1640 (const :tag "on" t)
1641 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1642 (const :tag "when item is marked DONE" done)
1643 (const :tag "when TODO state changes" state)
1644 (const :tag "when clocking out" clock-out))))
1645
1646 (defcustom org-log-done-with-time t
1647 "Non-nil means, the CLOSED time stamp will contain date and time.
1648 When nil, only the date will be recorded."
1649 :group 'org-progress
1650 :type 'boolean)
1651
1652 (defcustom org-log-note-headings
1653 '((done . "CLOSING NOTE %t")
1654 (state . "State %-12s %t")
1655 (clock-out . ""))
1656 "Headings for notes added when clocking out or closing TODO items.
1657 The value is an alist, with the car being a symbol indicating the note
1658 context, and the cdr is the heading to be used. The heading may also be the
1659 empty string.
1660 %t in the heading will be replaced by a time stamp.
1661 %s will be replaced by the new TODO state, in double quotes.
1662 %u will be replaced by the user name.
1663 %U will be replaced by the full user name."
1664 :group 'org-todo
1665 :group 'org-progress
1666 :type '(list :greedy t
1667 (cons (const :tag "Heading when closing an item" done) string)
1668 (cons (const :tag
1669 "Heading when changing todo state (todo sequence only)"
1670 state) string)
1671 (cons (const :tag "Heading when clocking out" clock-out) string)))
1672
1673 (defcustom org-log-states-order-reversed t
1674 "Non-nil means, the latest state change note will be directly after heading.
1675 When nil, the notes will be orderer according to time."
1676 :group 'org-todo
1677 :group 'org-progress
1678 :type 'boolean)
1679
1680 (defcustom org-log-repeat t
1681 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1682 When nil, no note will be taken.
1683 This option can also be set with on a per-file-basis with
1684
1685 #+STARTUP: logrepeat
1686 #+STARTUP: nologrepeat
1687
1688 You can have local logging settings for a subtree by setting the LOGGING
1689 property to one or more of these keywords."
1690 :group 'org-todo
1691 :group 'org-progress
1692 :type 'boolean)
1693
1694 (defcustom org-clock-into-drawer 2
1695 "Should clocking info be wrapped into a drawer?
1696 When t, clocking info will always be inserted into a :CLOCK: drawer.
1697 If necessary, the drawer will be created.
1698 When nil, the drawer will not be created, but used when present.
1699 When an integer and the number of clocking entries in an item
1700 reaches or exceeds this number, a drawer will be created."
1701 :group 'org-todo
1702 :group 'org-progress
1703 :type '(choice
1704 (const :tag "Always" t)
1705 (const :tag "Only when drawer exists" nil)
1706 (integer :tag "When at least N clock entries")))
1707
1708 (defcustom org-clock-out-when-done t
1709 "When t, the clock will be stopped when the relevant entry is marked DONE.
1710 Nil means, clock will keep running until stopped explicitly with
1711 `C-c C-x C-o', or until the clock is started in a different item."
1712 :group 'org-progress
1713 :type 'boolean)
1714
1715 (defgroup org-priorities nil
1716 "Priorities in Org-mode."
1717 :tag "Org Priorities"
1718 :group 'org-todo)
1719
1720 (defcustom org-highest-priority ?A
1721 "The highest priority of TODO items. A character like ?A, ?B etc.
1722 Must have a smaller ASCII number than `org-lowest-priority'."
1723 :group 'org-priorities
1724 :type 'character)
1725
1726 (defcustom org-lowest-priority ?C
1727 "The lowest priority of TODO items. A character like ?A, ?B etc.
1728 Must have a larger ASCII number than `org-highest-priority'."
1729 :group 'org-priorities
1730 :type 'character)
1731
1732 (defcustom org-default-priority ?B
1733 "The default priority of TODO items.
1734 This is the priority an item get if no explicit priority is given."
1735 :group 'org-priorities
1736 :type 'character)
1737
1738 (defcustom org-priority-start-cycle-with-default t
1739 "Non-nil means, start with default priority when starting to cycle.
1740 When this is nil, the first step in the cycle will be (depending on the
1741 command used) one higher or lower that the default priority."
1742 :group 'org-priorities
1743 :type 'boolean)
1744
1745 (defgroup org-time nil
1746 "Options concerning time stamps and deadlines in Org-mode."
1747 :tag "Org Time"
1748 :group 'org)
1749
1750 (defcustom org-insert-labeled-timestamps-at-point nil
1751 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1752 When nil, these labeled time stamps are forces into the second line of an
1753 entry, just after the headline. When scheduling from the global TODO list,
1754 the time stamp will always be forced into the second line."
1755 :group 'org-time
1756 :type 'boolean)
1757
1758 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1759 "Formats for `format-time-string' which are used for time stamps.
1760 It is not recommended to change this constant.")
1761
1762 (defcustom org-time-stamp-rounding-minutes 0
1763 "Number of minutes to round time stamps to upon insertion.
1764 When zero, insert the time unmodified. Useful rounding numbers
1765 should be factors of 60, so for example 5, 10, 15.
1766 When this is not zero, you can still force an exact time-stamp by using
1767 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1768 :group 'org-time
1769 :type 'integer)
1770
1771 (defcustom org-display-custom-times nil
1772 "Non-nil means, overlay custom formats over all time stamps.
1773 The formats are defined through the variable `org-time-stamp-custom-formats'.
1774 To turn this on on a per-file basis, insert anywhere in the file:
1775 #+STARTUP: customtime"
1776 :group 'org-time
1777 :set 'set-default
1778 :type 'sexp)
1779 (make-variable-buffer-local 'org-display-custom-times)
1780
1781 (defcustom org-time-stamp-custom-formats
1782 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1783 "Custom formats for time stamps. See `format-time-string' for the syntax.
1784 These are overlayed over the default ISO format if the variable
1785 `org-display-custom-times' is set. Time like %H:%M should be at the
1786 end of the second format."
1787 :group 'org-time
1788 :type 'sexp)
1789
1790 (defun org-time-stamp-format (&optional long inactive)
1791 "Get the right format for a time string."
1792 (let ((f (if long (cdr org-time-stamp-formats)
1793 (car org-time-stamp-formats))))
1794 (if inactive
1795 (concat "[" (substring f 1 -1) "]")
1796 f)))
1797
1798 (defcustom org-popup-calendar-for-date-prompt t
1799 "Non-nil means, pop up a calendar when prompting for a date.
1800 In the calendar, the date can be selected with mouse-1. However, the
1801 minibuffer will also be active, and you can simply enter the date as well.
1802 When nil, only the minibuffer will be available."
1803 :group 'org-time
1804 :type 'boolean)
1805
1806 (defcustom org-edit-timestamp-down-means-later nil
1807 "Non-nil means, S-down will increase the time in a time stamp.
1808 When nil, S-up will increase."
1809 :group 'org-time
1810 :type 'boolean)
1811
1812 (defcustom org-calendar-follow-timestamp-change t
1813 "Non-nil means, make the calendar window follow timestamp changes.
1814 When a timestamp is modified and the calendar window is visible, it will be
1815 moved to the new date."
1816 :group 'org-time
1817 :type 'boolean)
1818
1819 (defgroup org-tags nil
1820 "Options concerning tags in Org-mode."
1821 :tag "Org Tags"
1822 :group 'org)
1823
1824 (defcustom org-tag-alist nil
1825 "List of tags allowed in Org-mode files.
1826 When this list is nil, Org-mode will base TAG input on what is already in the
1827 buffer.
1828 The value of this variable is an alist, the car of each entry must be a
1829 keyword as a string, the cdr may be a character that is used to select
1830 that tag through the fast-tag-selection interface.
1831 See the manual for details."
1832 :group 'org-tags
1833 :type '(repeat
1834 (choice
1835 (cons (string :tag "Tag name")
1836 (character :tag "Access char"))
1837 (const :tag "Start radio group" (:startgroup))
1838 (const :tag "End radio group" (:endgroup)))))
1839
1840 (defcustom org-use-fast-tag-selection 'auto
1841 "Non-nil means, use fast tag selection scheme.
1842 This is a special interface to select and deselect tags with single keys.
1843 When nil, fast selection is never used.
1844 When the symbol `auto', fast selection is used if and only if selection
1845 characters for tags have been configured, either through the variable
1846 `org-tag-alist' or through a #+TAGS line in the buffer.
1847 When t, fast selection is always used and selection keys are assigned
1848 automatically if necessary."
1849 :group 'org-tags
1850 :type '(choice
1851 (const :tag "Always" t)
1852 (const :tag "Never" nil)
1853 (const :tag "When selection characters are configured" 'auto)))
1854
1855 (defcustom org-fast-tag-selection-single-key nil
1856 "Non-nil means, fast tag selection exits after first change.
1857 When nil, you have to press RET to exit it.
1858 During fast tag selection, you can toggle this flag with `C-c'.
1859 This variable can also have the value `expert'. In this case, the window
1860 displaying the tags menu is not even shown, until you press C-c again."
1861 :group 'org-tags
1862 :type '(choice
1863 (const :tag "No" nil)
1864 (const :tag "Yes" t)
1865 (const :tag "Expert" expert)))
1866
1867 (defvar org-fast-tag-selection-include-todo nil
1868 "Non-nil means, fast tags selection interface will also offer TODO states.
1869 This is an undocumented feature, you should not rely on it.")
1870
1871 (defcustom org-tags-column -80
1872 "The column to which tags should be indented in a headline.
1873 If this number is positive, it specifies the column. If it is negative,
1874 it means that the tags should be flushright to that column. For example,
1875 -80 works well for a normal 80 character screen."
1876 :group 'org-tags
1877 :type 'integer)
1878
1879 (defcustom org-auto-align-tags t
1880 "Non-nil means, realign tags after pro/demotion of TODO state change.
1881 These operations change the length of a headline and therefore shift
1882 the tags around. With this options turned on, after each such operation
1883 the tags are again aligned to `org-tags-column'."
1884 :group 'org-tags
1885 :type 'boolean)
1886
1887 (defcustom org-use-tag-inheritance t
1888 "Non-nil means, tags in levels apply also for sublevels.
1889 When nil, only the tags directly given in a specific line apply there.
1890 If you turn off this option, you very likely want to turn on the
1891 companion option `org-tags-match-list-sublevels'."
1892 :group 'org-tags
1893 :type 'boolean)
1894
1895 (defcustom org-tags-match-list-sublevels nil
1896 "Non-nil means list also sublevels of headlines matching tag search.
1897 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1898 the sublevels of a headline matching a tag search often also match
1899 the same search. Listing all of them can create very long lists.
1900 Setting this variable to nil causes subtrees of a match to be skipped.
1901 This option is off by default, because inheritance in on. If you turn
1902 inheritance off, you very likely want to turn this option on.
1903
1904 As a special case, if the tag search is restricted to TODO items, the
1905 value of this variable is ignored and sublevels are always checked, to
1906 make sure all corresponding TODO items find their way into the list."
1907 :group 'org-tags
1908 :type 'boolean)
1909
1910 (defvar org-tags-history nil
1911 "History of minibuffer reads for tags.")
1912 (defvar org-last-tags-completion-table nil
1913 "The last used completion table for tags.")
1914 (defvar org-after-tags-change-hook nil
1915 "Hook that is run after the tags in a line have changed.")
1916
1917 (defgroup org-properties nil
1918 "Options concerning properties in Org-mode."
1919 :tag "Org Properties"
1920 :group 'org)
1921
1922 (defcustom org-property-format "%-10s %s"
1923 "How property key/value pairs should be formatted by `indent-line'.
1924 When `indent-line' hits a property definition, it will format the line
1925 according to this format, mainly to make sure that the values are
1926 lined-up with respect to each other."
1927 :group 'org-properties
1928 :type 'string)
1929
1930 (defcustom org-use-property-inheritance nil
1931 "Non-nil means, properties apply also for sublevels.
1932 This can cause significant overhead when doing a search, so this is turned
1933 off by default.
1934 When nil, only the properties directly given in the current entry count.
1935
1936 However, note that some special properties use inheritance under special
1937 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1938 and the properties ending in \"_ALL\" when they are used as descriptor
1939 for valid values of a property."
1940 :group 'org-properties
1941 :type 'boolean)
1942
1943 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1944 "The default column format, if no other format has been defined.
1945 This variable can be set on the per-file basis by inserting a line
1946
1947 #+COLUMNS: %25ITEM ....."
1948 :group 'org-properties
1949 :type 'string)
1950
1951 (defcustom org-global-properties nil
1952 "List of property/value pairs that can be inherited by any entry.
1953 You can set buffer-local values for this by adding lines like
1954
1955 #+PROPERTY: NAME VALUE"
1956 :group 'org-properties
1957 :type '(repeat
1958 (cons (string :tag "Property")
1959 (string :tag "Value"))))
1960
1961 (defvar org-local-properties nil
1962 "List of property/value pairs that can be inherited by any entry.
1963 Valid for the current buffer.
1964 This variable is populated from #+PROPERTY lines.")
1965
1966 (defgroup org-agenda nil
1967 "Options concerning agenda views in Org-mode."
1968 :tag "Org Agenda"
1969 :group 'org)
1970
1971 (defvar org-category nil
1972 "Variable used by org files to set a category for agenda display.
1973 Such files should use a file variable to set it, for example
1974
1975 # -*- mode: org; org-category: \"ELisp\"
1976
1977 or contain a special line
1978
1979 #+CATEGORY: ELisp
1980
1981 If the file does not specify a category, then file's base name
1982 is used instead.")
1983 (make-variable-buffer-local 'org-category)
1984
1985 (defcustom org-agenda-files nil
1986 "The files to be used for agenda display.
1987 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1988 \\[org-remove-file]. You can also use customize to edit the list.
1989
1990 If an entry is a directory, all files in that directory that are matched by
1991 `org-agenda-file-regexp' will be part of the file list.
1992
1993 If the value of the variable is not a list but a single file name, then
1994 the list of agenda files is actually stored and maintained in that file, one
1995 agenda file per line."
1996 :group 'org-agenda
1997 :type '(choice
1998 (repeat :tag "List of files and directories" file)
1999 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2000
2001 (defcustom org-agenda-file-regexp "\\.org\\'"
2002 "Regular expression to match files for `org-agenda-files'.
2003 If any element in the list in that variable contains a directory instead
2004 of a normal file, all files in that directory that are matched by this
2005 regular expression will be included."
2006 :group 'org-agenda
2007 :type 'regexp)
2008
2009 (defcustom org-agenda-skip-unavailable-files nil
2010 "t means to just skip non-reachable files in `org-agenda-files'.
2011 Nil means to remove them, after a query, from the list."
2012 :group 'org-agenda
2013 :type 'boolean)
2014
2015 (defcustom org-agenda-multi-occur-extra-files nil
2016 "List of extra files to be searched by `org-occur-in-agenda-files'.
2017 The files in `org-agenda-files' are always searched."
2018 :group 'org-agenda
2019 :type '(repeat file))
2020
2021 (defcustom org-agenda-confirm-kill 1
2022 "When set, remote killing from the agenda buffer needs confirmation.
2023 When t, a confirmation is always needed. When a number N, confirmation is
2024 only needed when the text to be killed contains more than N non-white lines."
2025 :group 'org-agenda
2026 :type '(choice
2027 (const :tag "Never" nil)
2028 (const :tag "Always" t)
2029 (number :tag "When more than N lines")))
2030
2031 (defcustom org-calendar-to-agenda-key [?c]
2032 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2033 The command `org-calendar-goto-agenda' will be bound to this key. The
2034 default is the character `c' because then `c' can be used to switch back and
2035 forth between agenda and calendar."
2036 :group 'org-agenda
2037 :type 'sexp)
2038
2039 (defcustom org-agenda-compact-blocks nil
2040 "Non-nil means, make the block agenda more compact.
2041 This is done by leaving out unnecessary lines."
2042 :group 'org-agenda
2043 :type nil)
2044
2045 (defgroup org-agenda-export nil
2046 "Options concerning exporting agenda views in Org-mode."
2047 :tag "Org Agenda Export"
2048 :group 'org-agenda)
2049
2050 (defcustom org-agenda-with-colors t
2051 "Non-nil means, use colors in agenda views."
2052 :group 'org-agenda-export
2053 :type 'boolean)
2054
2055 (defcustom org-agenda-exporter-settings nil
2056 "Alist of variable/value pairs that should be active during agenda export.
2057 This is a good place to set uptions for ps-print and for htmlize."
2058 :group 'org-agenda-export
2059 :type '(repeat
2060 (list
2061 (variable)
2062 (sexp :tag "Value"))))
2063
2064 (defcustom org-agenda-export-html-style ""
2065 "The style specification for exported HTML Agenda files.
2066 If this variable contains a string, it will replace the default <style>
2067 section as produced by `htmlize'.
2068 Since there are different ways of setting style information, this variable
2069 needs to contain the full HTML structure to provide a style, including the
2070 surrounding HTML tags. The style specifications should include definitions
2071 the fonts used by the agenda, here is an example:
2072
2073 <style type=\"text/css\">
2074 p { font-weight: normal; color: gray; }
2075 .org-agenda-structure {
2076 font-size: 110%;
2077 color: #003399;
2078 font-weight: 600;
2079 }
2080 .org-todo {
2081 color: #cc6666;Week-agenda:
2082 font-weight: bold;
2083 }
2084 .org-done {
2085 color: #339933;
2086 }
2087 .title { text-align: center; }
2088 .todo, .deadline { color: red; }
2089 .done { color: green; }
2090 </style>
2091
2092 or, if you want to keep the style in a file,
2093
2094 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2095
2096 As the value of this option simply gets inserted into the HTML <head> header,
2097 you can \"misuse\" it to also add other text to the header. However,
2098 <style>...</style> is required, if not present the variable will be ignored."
2099 :group 'org-agenda-export
2100 :group 'org-export-html
2101 :type 'string)
2102
2103 (defgroup org-agenda-custom-commands nil
2104 "Options concerning agenda views in Org-mode."
2105 :tag "Org Agenda Custom Commands"
2106 :group 'org-agenda)
2107
2108 (defcustom org-agenda-custom-commands nil
2109 "Custom commands for the agenda.
2110 These commands will be offered on the splash screen displayed by the
2111 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2112
2113 (key desc type match options files)
2114
2115 key The key (one or more characters as a string) to be associated
2116 with the command.
2117 desc A description of the commend, when omitted or nil, a default
2118 description is built using MATCH.
2119 type The command type, any of the following symbols:
2120 todo Entries with a specific TODO keyword, in all agenda files.
2121 tags Tags match in all agenda files.
2122 tags-todo Tags match in all agenda files, TODO entries only.
2123 todo-tree Sparse tree of specific TODO keyword in *current* file.
2124 tags-tree Sparse tree with all tags matches in *current* file.
2125 occur-tree Occur sparse tree for *current* file.
2126 ... A user-defined function.
2127 match What to search for:
2128 - a single keyword for TODO keyword searches
2129 - a tags match expression for tags searches
2130 - a regular expression for occur searches
2131 options A list of option settings, similar to that in a let form, so like
2132 this: ((opt1 val1) (opt2 val2) ...)
2133 files A list of files file to write the produced agenda buffer to
2134 with the command `org-store-agenda-views'.
2135 If a file name ends in \".html\", an HTML version of the buffer
2136 is written out. If it ends in \".ps\", a postscript version is
2137 produced. Otherwide, only the plain text is written to the file.
2138
2139 You can also define a set of commands, to create a composite agenda buffer.
2140 In this case, an entry looks like this:
2141
2142 (key desc (cmd1 cmd2 ...) general-options file)
2143
2144 where
2145
2146 desc A description string to be displayed in the dispatcher menu.
2147 cmd An agenda command, similar to the above. However, tree commands
2148 are no allowed, but instead you can get agenda and global todo list.
2149 So valid commands for a set are:
2150 (agenda)
2151 (alltodo)
2152 (stuck)
2153 (todo \"match\" options files)
2154 (tags \"match\" options files)
2155 (tags-todo \"match\" options files)
2156
2157 Each command can carry a list of options, and another set of options can be
2158 given for the whole set of commands. Individual command options take
2159 precedence over the general options.
2160
2161 When using several characters as key to a command, the first characters
2162 are prefix commands. For the dispatcher to display useful information, you
2163 should provide a description for the prefix, like
2164
2165 (setq org-agenda-custom-commands
2166 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2167 (\"hl\" tags \"+HOME+Lisa\")
2168 (\"hp\" tags \"+HOME+Peter\")
2169 (\"hk\" tags \"+HOME+Kim\")))"
2170 :group 'org-agenda-custom-commands
2171 :type '(repeat
2172 (choice :value ("a" "" tags "" nil)
2173 (list :tag "Single command"
2174 (string :tag "Access Key(s) ")
2175 (option (string :tag "Description"))
2176 (choice
2177 (const :tag "Agenda" agenda)
2178 (const :tag "TODO list" alltodo)
2179 (const :tag "Stuck projects" stuck)
2180 (const :tag "Tags search (all agenda files)" tags)
2181 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2182 (const :tag "TODO keyword search (all agenda files)" todo)
2183 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2184 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2185 (const :tag "Occur tree (current buffer)" occur-tree)
2186 (sexp :tag "Other, user-defined function"))
2187 (string :tag "Match")
2188 (repeat :tag "Local options"
2189 (list (variable :tag "Option") (sexp :tag "Value")))
2190 (option (repeat :tag "Export" (file :tag "Export to"))))
2191 (list :tag "Command series, all agenda files"
2192 (string :tag "Access Key(s)")
2193 (string :tag "Description ")
2194 (repeat
2195 (choice
2196 (const :tag "Agenda" (agenda))
2197 (const :tag "TODO list" (alltodo))
2198 (const :tag "Stuck projects" (stuck))
2199 (list :tag "Tags search"
2200 (const :format "" tags)
2201 (string :tag "Match")
2202 (repeat :tag "Local options"
2203 (list (variable :tag "Option")
2204 (sexp :tag "Value"))))
2205
2206 (list :tag "Tags search, TODO entries only"
2207 (const :format "" tags-todo)
2208 (string :tag "Match")
2209 (repeat :tag "Local options"
2210 (list (variable :tag "Option")
2211 (sexp :tag "Value"))))
2212
2213 (list :tag "TODO keyword search"
2214 (const :format "" todo)
2215 (string :tag "Match")
2216 (repeat :tag "Local options"
2217 (list (variable :tag "Option")
2218 (sexp :tag "Value"))))
2219
2220 (list :tag "Other, user-defined function"
2221 (symbol :tag "function")
2222 (string :tag "Match")
2223 (repeat :tag "Local options"
2224 (list (variable :tag "Option")
2225 (sexp :tag "Value"))))))
2226
2227 (repeat :tag "General options"
2228 (list (variable :tag "Option")
2229 (sexp :tag "Value")))
2230 (option (repeat :tag "Export" (file :tag "Export to"))))
2231 (cons :tag "Prefix key documentation"
2232 (string :tag "Access Key(s)")
2233 (string :tag "Description ")))))
2234
2235 (defcustom org-stuck-projects
2236 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2237 "How to identify stuck projects.
2238 This is a list of four items:
2239 1. A tags/todo matcher string that is used to identify a project.
2240 The entire tree below a headline matched by this is considered one project.
2241 2. A list of TODO keywords identifying non-stuck projects.
2242 If the project subtree contains any headline with one of these todo
2243 keywords, the project is considered to be not stuck. If you specify
2244 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2245 3. A list of tags identifying non-stuck projects.
2246 If the project subtree contains any headline with one of these tags,
2247 the project is considered to be not stuck. If you specify \"*\" as
2248 a tag, any tag will mark the project unstuck.
2249 4. An arbitrary regular expression matching non-stuck projects.
2250
2251 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2252 or `C-c a #' to produce the list."
2253 :group 'org-agenda-custom-commands
2254 :type '(list
2255 (string :tag "Tags/TODO match to identify a project")
2256 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2257 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2258 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2259
2260
2261 (defgroup org-agenda-skip nil
2262 "Options concerning skipping parts of agenda files."
2263 :tag "Org Agenda Skip"
2264 :group 'org-agenda)
2265
2266 (defcustom org-agenda-todo-list-sublevels t
2267 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2268 When nil, the sublevels of a TODO entry are not checked, resulting in
2269 potentially much shorter TODO lists."
2270 :group 'org-agenda-skip
2271 :group 'org-todo
2272 :type 'boolean)
2273
2274 (defcustom org-agenda-todo-ignore-with-date nil
2275 "Non-nil means, don't show entries with a date in the global todo list.
2276 You can use this if you prefer to mark mere appointments with a TODO keyword,
2277 but don't want them to show up in the TODO list.
2278 When this is set, it also covers deadlines and scheduled items, the settings
2279 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2280 will be ignored."
2281 :group 'org-agenda-skip
2282 :group 'org-todo
2283 :type 'boolean)
2284
2285 (defcustom org-agenda-todo-ignore-scheduled nil
2286 "Non-nil means, don't show scheduled entries in the global todo list.
2287 The idea behind this is that by scheduling it, you have already taken care
2288 of this item.
2289 See also `org-agenda-todo-ignore-with-date'."
2290 :group 'org-agenda-skip
2291 :group 'org-todo
2292 :type 'boolean)
2293
2294 (defcustom org-agenda-todo-ignore-deadlines nil
2295 "Non-nil means, don't show near deadline entries in the global todo list.
2296 Near means closer than `org-deadline-warning-days' days.
2297 The idea behind this is that such items will appear in the agenda anyway.
2298 See also `org-agenda-todo-ignore-with-date'."
2299 :group 'org-agenda-skip
2300 :group 'org-todo
2301 :type 'boolean)
2302
2303 (defcustom org-agenda-skip-scheduled-if-done nil
2304 "Non-nil means don't show scheduled items in agenda when they are done.
2305 This is relevant for the daily/weekly agenda, not for the TODO list. And
2306 it applies only to the actual date of the scheduling. Warnings about
2307 an item with a past scheduling dates are always turned off when the item
2308 is DONE."
2309 :group 'org-agenda-skip
2310 :type 'boolean)
2311
2312 (defcustom org-agenda-skip-deadline-if-done nil
2313 "Non-nil means don't show deadines when the corresponding item is done.
2314 When nil, the deadline is still shown and should give you a happy feeling.
2315 This is relevant for the daily/weekly agenda. And it applied only to the
2316 actualy date of the deadline. Warnings about approching and past-due
2317 deadlines are always turned off when the item is DONE."
2318 :group 'org-agenda-skip
2319 :type 'boolean)
2320
2321 (defcustom org-timeline-show-empty-dates 3
2322 "Non-nil means, `org-timeline' also shows dates without an entry.
2323 When nil, only the days which actually have entries are shown.
2324 When t, all days between the first and the last date are shown.
2325 When an integer, show also empty dates, but if there is a gap of more than
2326 N days, just insert a special line indicating the size of the gap."
2327 :group 'org-agenda-skip
2328 :type '(choice
2329 (const :tag "None" nil)
2330 (const :tag "All" t)
2331 (number :tag "at most")))
2332
2333
2334 (defgroup org-agenda-startup nil
2335 "Options concerning initial settings in the Agenda in Org Mode."
2336 :tag "Org Agenda Startup"
2337 :group 'org-agenda)
2338
2339 (defcustom org-finalize-agenda-hook nil
2340 "Hook run just before displaying an agenda buffer."
2341 :group 'org-agenda-startup
2342 :type 'hook)
2343
2344 (defcustom org-agenda-mouse-1-follows-link nil
2345 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2346 A longer mouse click will still set point. Does not wortk on XEmacs.
2347 Needs to be set before org.el is loaded."
2348 :group 'org-agenda-startup
2349 :type 'boolean)
2350
2351 (defcustom org-agenda-start-with-follow-mode nil
2352 "The initial value of follow-mode in a newly created agenda window."
2353 :group 'org-agenda-startup
2354 :type 'boolean)
2355
2356 (defgroup org-agenda-windows nil
2357 "Options concerning the windows used by the Agenda in Org Mode."
2358 :tag "Org Agenda Windows"
2359 :group 'org-agenda)
2360
2361 (defcustom org-agenda-window-setup 'reorganize-frame
2362 "How the agenda buffer should be displayed.
2363 Possible values for this option are:
2364
2365 current-window Show agenda in the current window, keeping all other windows.
2366 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2367 other-window Use `switch-to-buffer-other-window' to display agenda.
2368 reorganize-frame Show only two windows on the current frame, the current
2369 window and the agenda.
2370 See also the variable `org-agenda-restore-windows-after-quit'."
2371 :group 'org-agenda-windows
2372 :type '(choice
2373 (const current-window)
2374 (const other-frame)
2375 (const other-window)
2376 (const reorganize-frame)))
2377
2378 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2379 "The min and max height of the agenda window as a fraction of frame height.
2380 The value of the variable is a cons cell with two numbers between 0 and 1.
2381 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2382 :group 'org-agenda-windows
2383 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2384
2385 (defcustom org-agenda-restore-windows-after-quit nil
2386 "Non-nil means, restore window configuration open exiting agenda.
2387 Before the window configuration is changed for displaying the agenda,
2388 the current status is recorded. When the agenda is exited with
2389 `q' or `x' and this option is set, the old state is restored. If
2390 `org-agenda-window-setup' is `other-frame', the value of this
2391 option will be ignored.."
2392 :group 'org-agenda-windows
2393 :type 'boolean)
2394
2395 (defcustom org-indirect-buffer-display 'other-window
2396 "How should indirect tree buffers be displayed?
2397 This applies to indirect buffers created with the commands
2398 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2399 Valid values are:
2400 current-window Display in the current window
2401 other-window Just display in another window.
2402 dedicated-frame Create one new frame, and re-use it each time.
2403 new-frame Make a new frame each time."
2404 :group 'org-structure
2405 :group 'org-agenda-windows
2406 :type '(choice
2407 (const :tag "In current window" current-window)
2408 (const :tag "In current frame, other window" other-window)
2409 (const :tag "Each time a new frame" new-frame)
2410 (const :tag "One dedicated frame" dedicated-frame)))
2411
2412 (defgroup org-agenda-daily/weekly nil
2413 "Options concerning the daily/weekly agenda."
2414 :tag "Org Agenda Daily/Weekly"
2415 :group 'org-agenda)
2416
2417 (defcustom org-agenda-ndays 7
2418 "Number of days to include in overview display.
2419 Should be 1 or 7."
2420 :group 'org-agenda-daily/weekly
2421 :type 'number)
2422
2423 (defcustom org-agenda-start-on-weekday 1
2424 "Non-nil means, start the overview always on the specified weekday.
2425 0 denotes Sunday, 1 denotes Monday etc.
2426 When nil, always start on the current day."
2427 :group 'org-agenda-daily/weekly
2428 :type '(choice (const :tag "Today" nil)
2429 (number :tag "Weekday No.")))
2430
2431 (defcustom org-agenda-show-all-dates t
2432 "Non-nil means, `org-agenda' shows every day in the selected range.
2433 When nil, only the days which actually have entries are shown."
2434 :group 'org-agenda-daily/weekly
2435 :type 'boolean)
2436
2437 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2438 "Format string for displaying dates in the agenda.
2439 Used by the daily/weekly agenda and by the timeline. This should be
2440 a format string understood by `format-time-string', or a function returning
2441 the formatted date as a string. The function must take a single argument,
2442 a calendar-style date list like (month day year)."
2443 :group 'org-agenda-daily/weekly
2444 :type '(choice
2445 (string :tag "Format string")
2446 (function :tag "Function")))
2447
2448 (defun org-agenda-format-date-aligned (date)
2449 "Format a date string for display in the daily/weekly agenda, or timeline.
2450 This function makes sure that dates are aligned for easy reading."
2451 (format "%-9s %2d %s %4d"
2452 (calendar-day-name date)
2453 (extract-calendar-day date)
2454 (calendar-month-name (extract-calendar-month date))
2455 (extract-calendar-year date)))
2456
2457 (defcustom org-agenda-include-diary nil
2458 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2459 :group 'org-agenda-daily/weekly
2460 :type 'boolean)
2461
2462 (defcustom org-agenda-include-all-todo nil
2463 "Set means weekly/daily agenda will always contain all TODO entries.
2464 The TODO entries will be listed at the top of the agenda, before
2465 the entries for specific days."
2466 :group 'org-agenda-daily/weekly
2467 :type 'boolean)
2468
2469 (defcustom org-agenda-repeating-timestamp-show-all t
2470 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2471 When nil, only one occurence is shown, either today or the
2472 nearest into the future."
2473 :group 'org-agenda-daily/weekly
2474 :type 'boolean)
2475
2476 (defcustom org-deadline-warning-days 14
2477 "No. of days before expiration during which a deadline becomes active.
2478 This variable governs the display in sparse trees and in the agenda.
2479 When negative, it means use this number (the absolute value of it)
2480 even if a deadline has a different individual lead time specified."
2481 :group 'org-time
2482 :group 'org-agenda-daily/weekly
2483 :type 'number)
2484
2485 (defcustom org-scheduled-past-days 10000
2486 "No. of days to continue listing scheduled items that are not marked DONE.
2487 When an item is scheduled on a date, it shows up in the agenda on this
2488 day and will be listed until it is marked done for the number of days
2489 given here."
2490 :group 'org-agenda-daily/weekly
2491 :type 'number)
2492
2493 (defgroup org-agenda-time-grid nil
2494 "Options concerning the time grid in the Org-mode Agenda."
2495 :tag "Org Agenda Time Grid"
2496 :group 'org-agenda)
2497
2498 (defcustom org-agenda-use-time-grid t
2499 "Non-nil means, show a time grid in the agenda schedule.
2500 A time grid is a set of lines for specific times (like every two hours between
2501 8:00 and 20:00). The items scheduled for a day at specific times are
2502 sorted in between these lines.
2503 For details about when the grid will be shown, and what it will look like, see
2504 the variable `org-agenda-time-grid'."
2505 :group 'org-agenda-time-grid
2506 :type 'boolean)
2507
2508 (defcustom org-agenda-time-grid
2509 '((daily today require-timed)
2510 "----------------"
2511 (800 1000 1200 1400 1600 1800 2000))
2512
2513 "The settings for time grid for agenda display.
2514 This is a list of three items. The first item is again a list. It contains
2515 symbols specifying conditions when the grid should be displayed:
2516
2517 daily if the agenda shows a single day
2518 weekly if the agenda shows an entire week
2519 today show grid on current date, independent of daily/weekly display
2520 require-timed show grid only if at least one item has a time specification
2521
2522 The second item is a string which will be places behing the grid time.
2523
2524 The third item is a list of integers, indicating the times that should have
2525 a grid line."
2526 :group 'org-agenda-time-grid
2527 :type
2528 '(list
2529 (set :greedy t :tag "Grid Display Options"
2530 (const :tag "Show grid in single day agenda display" daily)
2531 (const :tag "Show grid in weekly agenda display" weekly)
2532 (const :tag "Always show grid for today" today)
2533 (const :tag "Show grid only if any timed entries are present"
2534 require-timed)
2535 (const :tag "Skip grid times already present in an entry"
2536 remove-match))
2537 (string :tag "Grid String")
2538 (repeat :tag "Grid Times" (integer :tag "Time"))))
2539
2540 (defgroup org-agenda-sorting nil
2541 "Options concerning sorting in the Org-mode Agenda."
2542 :tag "Org Agenda Sorting"
2543 :group 'org-agenda)
2544
2545 (let ((sorting-choice
2546 '(choice
2547 (const time-up) (const time-down)
2548 (const category-keep) (const category-up) (const category-down)
2549 (const tag-down) (const tag-up)
2550 (const priority-up) (const priority-down))))
2551
2552 (defcustom org-agenda-sorting-strategy
2553 '((agenda time-up category-keep priority-down)
2554 (todo category-keep priority-down)
2555 (tags category-keep priority-down))
2556 "Sorting structure for the agenda items of a single day.
2557 This is a list of symbols which will be used in sequence to determine
2558 if an entry should be listed before another entry. The following
2559 symbols are recognized:
2560
2561 time-up Put entries with time-of-day indications first, early first
2562 time-down Put entries with time-of-day indications first, late first
2563 category-keep Keep the default order of categories, corresponding to the
2564 sequence in `org-agenda-files'.
2565 category-up Sort alphabetically by category, A-Z.
2566 category-down Sort alphabetically by category, Z-A.
2567 tag-up Sort alphabetically by last tag, A-Z.
2568 tag-down Sort alphabetically by last tag, Z-A.
2569 priority-up Sort numerically by priority, high priority last.
2570 priority-down Sort numerically by priority, high priority first.
2571
2572 The different possibilities will be tried in sequence, and testing stops
2573 if one comparison returns a \"not-equal\". For example, the default
2574 '(time-up category-keep priority-down)
2575 means: Pull out all entries having a specified time of day and sort them,
2576 in order to make a time schedule for the current day the first thing in the
2577 agenda listing for the day. Of the entries without a time indication, keep
2578 the grouped in categories, don't sort the categories, but keep them in
2579 the sequence given in `org-agenda-files'. Within each category sort by
2580 priority.
2581
2582 Leaving out `category-keep' would mean that items will be sorted across
2583 categories by priority."
2584 :group 'org-agenda-sorting
2585 :type `(choice
2586 (repeat :tag "General" ,sorting-choice)
2587 (list :tag "Individually"
2588 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2589 (repeat ,sorting-choice))
2590 (cons (const :tag "Strategy for TODO lists" todo)
2591 (repeat ,sorting-choice))
2592 (cons (const :tag "Strategy for Tags matches" tags)
2593 (repeat ,sorting-choice))))))
2594
2595 (defcustom org-sort-agenda-notime-is-late t
2596 "Non-nil means, items without time are considered late.
2597 This is only relevant for sorting. When t, items which have no explicit
2598 time like 15:30 will be considered as 99:01, i.e. later than any items which
2599 do have a time. When nil, the default time is before 0:00. You can use this
2600 option to decide if the schedule for today should come before or after timeless
2601 agenda entries."
2602 :group 'org-agenda-sorting
2603 :type 'boolean)
2604
2605 (defgroup org-agenda-line-format nil
2606 "Options concerning the entry prefix in the Org-mode agenda display."
2607 :tag "Org Agenda Line Format"
2608 :group 'org-agenda)
2609
2610 (defcustom org-agenda-prefix-format
2611 '((agenda . " %-12:c%?-12t% s")
2612 (timeline . " % s")
2613 (todo . " %-12:c")
2614 (tags . " %-12:c"))
2615 "Format specifications for the prefix of items in the agenda views.
2616 An alist with four entries, for the different agenda types. The keys to the
2617 sublists are `agenda', `timeline', `todo', and `tags'. The values
2618 are format strings.
2619 This format works similar to a printf format, with the following meaning:
2620
2621 %c the category of the item, \"Diary\" for entries from the diary, or
2622 as given by the CATEGORY keyword or derived from the file name.
2623 %T the *last* tag of the item. Last because inherited tags come
2624 first in the list.
2625 %t the time-of-day specification if one applies to the entry, in the
2626 format HH:MM
2627 %s Scheduling/Deadline information, a short string
2628
2629 All specifiers work basically like the standard `%s' of printf, but may
2630 contain two additional characters: A question mark just after the `%' and
2631 a whitespace/punctuation character just before the final letter.
2632
2633 If the first character after `%' is a question mark, the entire field
2634 will only be included if the corresponding value applies to the
2635 current entry. This is useful for fields which should have fixed
2636 width when present, but zero width when absent. For example,
2637 \"%?-12t\" will result in a 12 character time field if a time of the
2638 day is specified, but will completely disappear in entries which do
2639 not contain a time.
2640
2641 If there is punctuation or whitespace character just before the final
2642 format letter, this character will be appended to the field value if
2643 the value is not empty. For example, the format \"%-12:c\" leads to
2644 \"Diary: \" if the category is \"Diary\". If the category were be
2645 empty, no additional colon would be interted.
2646
2647 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2648 - Indent the line with two space characters
2649 - Give the category in a 12 chars wide field, padded with whitespace on
2650 the right (because of `-'). Append a colon if there is a category
2651 (because of `:').
2652 - If there is a time-of-day, put it into a 12 chars wide field. If no
2653 time, don't put in an empty field, just skip it (because of '?').
2654 - Finally, put the scheduling information and append a whitespace.
2655
2656 As another example, if you don't want the time-of-day of entries in
2657 the prefix, you could use:
2658
2659 (setq org-agenda-prefix-format \" %-11:c% s\")
2660
2661 See also the variables `org-agenda-remove-times-when-in-prefix' and
2662 `org-agenda-remove-tags'."
2663 :type '(choice
2664 (string :tag "General format")
2665 (list :greedy t :tag "View dependent"
2666 (cons (const agenda) (string :tag "Format"))
2667 (cons (const timeline) (string :tag "Format"))
2668 (cons (const todo) (string :tag "Format"))
2669 (cons (const tags) (string :tag "Format"))))
2670 :group 'org-agenda-line-format)
2671
2672 (defvar org-prefix-format-compiled nil
2673 "The compiled version of the most recently used prefix format.
2674 See the variable `org-agenda-prefix-format'.")
2675
2676 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2677 "Text preceeding scheduled items in the agenda view.
2678 THis is a list with two strings. The first applies when the item is
2679 scheduled on the current day. The second applies when it has been scheduled
2680 previously, it may contain a %d to capture how many days ago the item was
2681 scheduled."
2682 :group 'org-agenda-line-format
2683 :type '(list
2684 (string :tag "Scheduled today ")
2685 (string :tag "Scheduled previously")))
2686
2687 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2688 "Text preceeding deadline items in the agenda view.
2689 This is a list with two strings. The first applies when the item has its
2690 deadline on the current day. The second applies when it is in the past or
2691 in the future, it may contain %d to capture how many days away the deadline
2692 is (was)."
2693 :group 'org-agenda-line-format
2694 :type '(list
2695 (string :tag "Deadline today ")
2696 (string :tag "Deadline relative")))
2697
2698 (defcustom org-agenda-remove-times-when-in-prefix t
2699 "Non-nil means, remove duplicate time specifications in agenda items.
2700 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2701 time-of-day specification in a headline or diary entry is extracted and
2702 placed into the prefix. If this option is non-nil, the original specification
2703 \(a timestamp or -range, or just a plain time(range) specification like
2704 11:30-4pm) will be removed for agenda display. This makes the agenda less
2705 cluttered.
2706 The option can be t or nil. It may also be the symbol `beg', indicating
2707 that the time should only be removed what it is located at the beginning of
2708 the headline/diary entry."
2709 :group 'org-agenda-line-format
2710 :type '(choice
2711 (const :tag "Always" t)
2712 (const :tag "Never" nil)
2713 (const :tag "When at beginning of entry" beg)))
2714
2715
2716 (defcustom org-agenda-default-appointment-duration nil
2717 "Default duration for appointments that only have a starting time.
2718 When nil, no duration is specified in such cases.
2719 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2720 :group 'org-agenda-line-format
2721 :type '(choice
2722 (integer :tag "Minutes")
2723 (const :tag "No default duration")))
2724
2725
2726 (defcustom org-agenda-remove-tags nil
2727 "Non-nil means, remove the tags from the headline copy in the agenda.
2728 When this is the symbol `prefix', only remove tags when
2729 `org-agenda-prefix-format' contains a `%T' specifier."
2730 :group 'org-agenda-line-format
2731 :type '(choice
2732 (const :tag "Always" t)
2733 (const :tag "Never" nil)
2734 (const :tag "When prefix format contains %T" prefix)))
2735
2736 (if (fboundp 'defvaralias)
2737 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2738 'org-agenda-remove-tags))
2739
2740 (defcustom org-agenda-tags-column -80
2741 "Shift tags in agenda items to this column.
2742 If this number is positive, it specifies the column. If it is negative,
2743 it means that the tags should be flushright to that column. For example,
2744 -80 works well for a normal 80 character screen."
2745 :group 'org-agenda-line-format
2746 :type 'integer)
2747
2748 (if (fboundp 'defvaralias)
2749 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2750
2751 (defcustom org-agenda-fontify-priorities t
2752 "Non-nil means, highlight low and high priorities in agenda.
2753 When t, the highest priority entries are bold, lowest priority italic.
2754 This may also be an association list of priority faces. The face may be
2755 a names face, or a list like `(:background \"Red\")'."
2756 :group 'org-agenda-line-format
2757 :type '(choice
2758 (const :tag "Never" nil)
2759 (const :tag "Defaults" t)
2760 (repeat :tag "Specify"
2761 (list (character :tag "Priority" :value ?A)
2762 (sexp :tag "face")))))
2763
2764 (defgroup org-latex nil
2765 "Options for embedding LaTeX code into Org-mode"
2766 :tag "Org LaTeX"
2767 :group 'org)
2768
2769 (defcustom org-format-latex-options
2770 '(:foreground default :background default :scale 1.0
2771 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2772 :matchers ("begin" "$" "$$" "\\(" "\\["))
2773 "Options for creating images from LaTeX fragments.
2774 This is a property list with the following properties:
2775 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2776 `default' means use the forground of the default face.
2777 :background the background color, or \"Transparent\".
2778 `default' means use the background of the default face.
2779 :scale a scaling factor for the size of the images
2780 :html-foreground, :html-background, :html-scale
2781 The same numbers for HTML export.
2782 :matchers a list indicating which matchers should be used to
2783 find LaTeX fragments. Valid members of this list are:
2784 \"begin\" find environments
2785 \"$\" find math expressions surrounded by $...$
2786 \"$$\" find math expressions surrounded by $$....$$
2787 \"\\(\" find math expressions surrounded by \\(...\\)
2788 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2789 :group 'org-latex
2790 :type 'plist)
2791
2792 (defcustom org-format-latex-header "\\documentclass{article}
2793 \\usepackage{fullpage} % do not remove
2794 \\usepackage{amssymb}
2795 \\usepackage[usenames]{color}
2796 \\usepackage{amsmath}
2797 \\usepackage{latexsym}
2798 \\usepackage[mathscr]{eucal}
2799 \\pagestyle{empty} % do not remove"
2800 "The document header used for processing LaTeX fragments."
2801 :group 'org-latex
2802 :type 'string)
2803
2804 (defgroup org-export nil
2805 "Options for exporting org-listings."
2806 :tag "Org Export"
2807 :group 'org)
2808
2809 (defgroup org-export-general nil
2810 "General options for exporting Org-mode files."
2811 :tag "Org Export General"
2812 :group 'org-export)
2813
2814 (defcustom org-export-publishing-directory "."
2815 "Path to the location where exported files should be located.
2816 This path may be relative to the directory where the Org-mode file lives.
2817 The default is to put them into the same directory as the Org-mode file.
2818 The variable may also be an alist with export types `:html', `:ascii',
2819 `:ical', `:LaTeX', or `:xoxo' and the corresponding directories.
2820 If a directory path is relative, it is interpreted relative to the
2821 directory where the exported Org-mode files lives."
2822 :group 'org-export-general
2823 :type '(choice
2824 (directory)
2825 (repeat
2826 (cons
2827 (choice :tag "Type"
2828 (const :html) (const :LaTeX)
2829 (const :ascii) (const :ical) (const :xoxo))
2830 (directory)))))
2831
2832 (defcustom org-export-language-setup
2833 '(("en" "Author" "Date" "Table of Contents")
2834 ("cs" "Autor" "Datum" "Obsah")
2835 ("da" "Ophavsmand" "Dato" "Indhold")
2836 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2837 ("es" "Autor" "Fecha" "\xcdndice")
2838 ("fr" "Auteur" "Date" "Table des mati\xe8res")
2839 ("it" "Autore" "Data" "Indice")
2840 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2841 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2842 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2843 "Terms used in export text, translated to different languages.
2844 Use the variable `org-export-default-language' to set the language,
2845 or use the +OPTION lines for a per-file setting."
2846 :group 'org-export-general
2847 :type '(repeat
2848 (list
2849 (string :tag "HTML language tag")
2850 (string :tag "Author")
2851 (string :tag "Date")
2852 (string :tag "Table of Contents"))))
2853
2854 (defcustom org-export-default-language "en"
2855 "The default language of HTML export, as a string.
2856 This should have an association in `org-export-language-setup'."
2857 :group 'org-export-general
2858 :type 'string)
2859
2860 (defcustom org-export-skip-text-before-1st-heading t
2861 "Non-nil means, skip all text before the first headline when exporting.
2862 When nil, that text is exported as well."
2863 :group 'org-export-general
2864 :type 'boolean)
2865
2866 (defcustom org-export-headline-levels 3
2867 "The last level which is still exported as a headline.
2868 Inferior levels will produce itemize lists when exported.
2869 Note that a numeric prefix argument to an exporter function overrides
2870 this setting.
2871
2872 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2873 :group 'org-export-general
2874 :type 'number)
2875
2876 (defcustom org-export-with-section-numbers t
2877 "Non-nil means, add section numbers to headlines when exporting.
2878
2879 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2880 :group 'org-export-general
2881 :type 'boolean)
2882
2883 (defcustom org-export-with-toc t
2884 "Non-nil means, create a table of contents in exported files.
2885 The TOC contains headlines with levels up to`org-export-headline-levels'.
2886 When an integer, include levels up to N in the toc, this may then be
2887 different from `org-export-headline-levels', but it will not be allowed
2888 to be larger than the number of headline levels.
2889 When nil, no table of contents is made.
2890
2891 Headlines which contain any TODO items will be marked with \"(*)\" in
2892 ASCII export, and with red color in HTML output, if the option
2893 `org-export-mark-todo-in-toc' is set.
2894
2895 In HTML output, the TOC will be clickable.
2896
2897 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2898 or \"toc:3\"."
2899 :group 'org-export-general
2900 :type '(choice
2901 (const :tag "No Table of Contents" nil)
2902 (const :tag "Full Table of Contents" t)
2903 (integer :tag "TOC to level")))
2904
2905 (defcustom org-export-mark-todo-in-toc nil
2906 "Non-nil means, mark TOC lines that contain any open TODO items."
2907 :group 'org-export-general
2908 :type 'boolean)
2909
2910 (defcustom org-export-preserve-breaks nil
2911 "Non-nil means, preserve all line breaks when exporting.
2912 Normally, in HTML output paragraphs will be reformatted. In ASCII
2913 export, line breaks will always be preserved, regardless of this variable.
2914
2915 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2916 :group 'org-export-general
2917 :type 'boolean)
2918
2919 (defcustom org-export-with-archived-trees 'headline
2920 "Whether subtrees with the ARCHIVE tag should be exported.
2921 This can have three different values
2922 nil Do not export, pretend this tree is not present
2923 t Do export the entire tree
2924 headline Only export the headline, but skip the tree below it."
2925 :group 'org-export-general
2926 :group 'org-archive
2927 :type '(choice
2928 (const :tag "not at all" nil)
2929 (const :tag "headline only" 'headline)
2930 (const :tag "entirely" t)))
2931
2932 (defcustom org-export-author-info t
2933 "Non-nil means, insert author name and email into the exported file.
2934
2935 This option can also be set with the +OPTIONS line,
2936 e.g. \"author-info:nil\"."
2937 :group 'org-export-general
2938 :type 'boolean)
2939
2940 (defcustom org-export-time-stamp-file t
2941 "Non-nil means, insert a time stamp into the exported file.
2942 The time stamp shows when the file was created.
2943
2944 This option can also be set with the +OPTIONS line,
2945 e.g. \"timestamp:nil\"."
2946 :group 'org-export-general
2947 :type 'boolean)
2948
2949 (defcustom org-export-with-timestamps t
2950 "If nil, do not export time stamps and associated keywords."
2951 :group 'org-export-general
2952 :type 'boolean)
2953
2954 (defcustom org-export-remove-timestamps-from-toc t
2955 "If nil, remove timestamps from the table of contents entries."
2956 :group 'org-export-general
2957 :type 'boolean)
2958
2959 (defcustom org-export-with-tags 'not-in-toc
2960 "If nil, do not export tags, just remove them from headlines.
2961 If this is the symbol `not-in-toc', tags will be removed from table of
2962 contents entries, but still be shown in the headlines of the document.
2963
2964 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
2965 :group 'org-export-general
2966 :type '(choice
2967 (const :tag "Off" nil)
2968 (const :tag "Not in TOC" not-in-toc)
2969 (const :tag "On" t)))
2970
2971 (defcustom org-export-with-drawers nil
2972 "Non-nil means, export with drawers like the property drawer.
2973 When t, all drawers are exported. This may also be a list of
2974 drawer names to export."
2975 :group 'org-export-general
2976 :type '(choice
2977 (const :tag "All drawers" t)
2978 (const :tag "None" nil)
2979 (repeat :tag "Selected drawers"
2980 (string :tag "Drawer name"))))
2981
2982 (defgroup org-export-translation nil
2983 "Options for translating special ascii sequences for the export backends."
2984 :tag "Org Export Translation"
2985 :group 'org-export)
2986
2987 (defcustom org-export-with-emphasize t
2988 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2989 If the export target supports emphasizing text, the word will be
2990 typeset in bold, italic, or underlined, respectively. Works only for
2991 single words, but you can say: I *really* *mean* *this*.
2992 Not all export backends support this.
2993
2994 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2995 :group 'org-export-translation
2996 :type 'boolean)
2997
2998 (defcustom org-export-with-footnotes t
2999 "If nil, export [1] as a footnote marker.
3000 Lines starting with [1] will be formatted as footnotes.
3001
3002 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3003 :group 'org-export-translation
3004 :type 'boolean)
3005
3006 (defcustom org-export-with-sub-superscripts t
3007 "Non-nil means, interpret \"_\" and \"^\" for export.
3008 When this option is turned on, you can use TeX-like syntax for sub- and
3009 superscripts. Several characters after \"_\" or \"^\" will be
3010 considered as a single item - so grouping with {} is normally not
3011 needed. For example, the following things will be parsed as single
3012 sub- or superscripts.
3013
3014 10^24 or 10^tau several digits will be considered 1 item.
3015 10^-12 or 10^-tau a leading sign with digits or a word
3016 x^2-y^3 will be read as x^2 - y^3, because items are
3017 terminated by almost any nonword/nondigit char.
3018 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3019
3020 Still, ambiguity is possible - so when in doubt use {} to enclose the
3021 sub/superscript. If you set this variable to the symbol `{}',
3022 the braces are *required* in order to trigger interpretations as
3023 sub/superscript. This can be helpful in documents that need \"_\"
3024 frequently in plain text.
3025
3026 Not all export backends support this, but HTML does.
3027
3028 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3029 :group 'org-export-translation
3030 :type '(choice
3031 (const :tag "Always interpret" t)
3032 (const :tag "Only with braces" {})
3033 (const :tag "Never interpret" nil)))
3034
3035 (defcustom org-export-with-TeX-macros t
3036 "Non-nil means, interpret simple TeX-like macros when exporting.
3037 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3038 No only real TeX macros will work here, but the standard HTML entities
3039 for math can be used as macro names as well. For a list of supported
3040 names in HTML export, see the constant `org-html-entities'.
3041 Not all export backends support this.
3042
3043 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3044 :group 'org-export-translation
3045 :group 'org-export-latex
3046 :type 'boolean)
3047
3048 (defcustom org-export-with-LaTeX-fragments nil
3049 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3050 When set, the exporter will find LaTeX environments if the \\begin line is
3051 the first non-white thing on a line. It will also find the math delimiters
3052 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3053 display math.
3054
3055 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3056 :group 'org-export-translation
3057 :group 'org-export-latex
3058 :type 'boolean)
3059
3060 (defcustom org-export-with-fixed-width t
3061 "Non-nil means, lines starting with \":\" will be in fixed width font.
3062 This can be used to have pre-formatted text, fragments of code etc. For
3063 example:
3064 : ;; Some Lisp examples
3065 : (while (defc cnt)
3066 : (ding))
3067 will be looking just like this in also HTML. See also the QUOTE keyword.
3068 Not all export backends support this.
3069
3070 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3071 :group 'org-export-translation
3072 :type 'boolean)
3073
3074 (defcustom org-match-sexp-depth 3
3075 "Number of stacked braces for sub/superscript matching.
3076 This has to be set before loading org.el to be effective."
3077 :group 'org-export-translation
3078 :type 'integer)
3079
3080 (defgroup org-export-tables nil
3081 "Options for exporting tables in Org-mode."
3082 :tag "Org Export Tables"
3083 :group 'org-export)
3084
3085 (defcustom org-export-with-tables t
3086 "If non-nil, lines starting with \"|\" define a table.
3087 For example:
3088
3089 | Name | Address | Birthday |
3090 |-------------+----------+-----------|
3091 | Arthur Dent | England | 29.2.2100 |
3092
3093 Not all export backends support this.
3094
3095 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3096 :group 'org-export-tables
3097 :type 'boolean)
3098
3099 (defcustom org-export-highlight-first-table-line t
3100 "Non-nil means, highlight the first table line.
3101 In HTML export, this means use <th> instead of <td>.
3102 In tables created with table.el, this applies to the first table line.
3103 In Org-mode tables, all lines before the first horizontal separator
3104 line will be formatted with <th> tags."
3105 :group 'org-export-tables
3106 :type 'boolean)
3107
3108 (defcustom org-export-table-remove-special-lines t
3109 "Remove special lines and marking characters in calculating tables.
3110 This removes the special marking character column from tables that are set
3111 up for spreadsheet calculations. It also removes the entire lines
3112 marked with `!', `_', or `^'. The lines with `$' are kept, because
3113 the values of constants may be useful to have."
3114 :group 'org-export-tables
3115 :type 'boolean)
3116
3117 (defcustom org-export-prefer-native-exporter-for-tables nil
3118 "Non-nil means, always export tables created with table.el natively.
3119 Natively means, use the HTML code generator in table.el.
3120 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3121 the table does not use row- or column-spanning). This has the
3122 advantage, that the automatic HTML conversions for math symbols and
3123 sub/superscripts can be applied. Org-mode's HTML generator is also
3124 much faster."
3125 :group 'org-export-tables
3126 :type 'boolean)
3127
3128 (defgroup org-export-ascii nil
3129 "Options specific for ASCII export of Org-mode files."
3130 :tag "Org Export ASCII"
3131 :group 'org-export)
3132
3133 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3134 "Characters for underlining headings in ASCII export.
3135 In the given sequence, these characters will be used for level 1, 2, ..."
3136 :group 'org-export-ascii
3137 :type '(repeat character))
3138
3139 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3140 "Bullet characters for headlines converted to lists in ASCII export.
3141 The first character is is used for the first lest level generated in this
3142 way, and so on. If there are more levels than characters given here,
3143 the list will be repeated.
3144 Note that plain lists will keep the same bullets as the have in the
3145 Org-mode file."
3146 :group 'org-export-ascii
3147 :type '(repeat character))
3148
3149 (defgroup org-export-xml nil
3150 "Options specific for XML export of Org-mode files."
3151 :tag "Org Export XML"
3152 :group 'org-export)
3153
3154 (defgroup org-export-html nil
3155 "Options specific for HTML export of Org-mode files."
3156 :tag "Org Export HTML"
3157 :group 'org-export)
3158
3159 (defcustom org-export-html-coding-system nil
3160 ""
3161 :group 'org-export-html
3162 :type 'coding-system)
3163
3164 (defcustom org-export-html-extension "html"
3165 "The extension for exported HTML files."
3166 :group 'org-export-html
3167 :type 'string)
3168
3169 (defcustom org-export-html-style
3170 "<style type=\"text/css\">
3171 html {
3172 font-family: Times, serif;
3173 font-size: 12pt;
3174 }
3175 .title { text-align: center; }
3176 .todo { color: red; }
3177 .done { color: green; }
3178 .timestamp { color: grey }
3179 .timestamp-kwd { color: CadetBlue }
3180 .tag { background-color:lightblue; font-weight:normal }
3181 .target { background-color: lavender; }
3182 pre {
3183 border: 1pt solid #AEBDCC;
3184 background-color: #F3F5F7;
3185 padding: 5pt;
3186 font-family: courier, monospace;
3187 }
3188 table { border-collapse: collapse; }
3189 td, th {
3190 vertical-align: top;
3191 <!--border: 1pt solid #ADB9CC;-->
3192 }
3193 </style>"
3194 "The default style specification for exported HTML files.
3195 Since there are different ways of setting style information, this variable
3196 needs to contain the full HTML structure to provide a style, including the
3197 surrounding HTML tags. The style specifications should include definitions
3198 for new classes todo, done, title, and deadline. For example, legal values
3199 would be:
3200
3201 <style type=\"text/css\">
3202 p { font-weight: normal; color: gray; }
3203 h1 { color: black; }
3204 .title { text-align: center; }
3205 .todo, .deadline { color: red; }
3206 .done { color: green; }
3207 </style>
3208
3209 or, if you want to keep the style in a file,
3210
3211 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3212
3213 As the value of this option simply gets inserted into the HTML <head> header,
3214 you can \"misuse\" it to add arbitrary text to the header."
3215 :group 'org-export-html
3216 :type 'string)
3217
3218
3219 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3220 "Format for typesetting the document title in HTML export."
3221 :group 'org-export-html
3222 :type 'string)
3223
3224 (defcustom org-export-html-toplevel-hlevel 2
3225 "The <H> level for level 1 headings in HTML export."
3226 :group 'org-export-html
3227 :type 'string)
3228
3229 (defcustom org-export-html-link-org-files-as-html t
3230 "Non-nil means, make file links to `file.org' point to `file.html'.
3231 When org-mode is exporting an org-mode file to HTML, links to
3232 non-html files are directly put into a href tag in HTML.
3233 However, links to other Org-mode files (recognized by the
3234 extension `.org.) should become links to the corresponding html
3235 file, assuming that the linked org-mode file will also be
3236 converted to HTML.
3237 When nil, the links still point to the plain `.org' file."
3238 :group 'org-export-html
3239 :type 'boolean)
3240
3241 (defcustom org-export-html-inline-images 'maybe
3242 "Non-nil means, inline images into exported HTML pages.
3243 This is done using an <img> tag. When nil, an anchor with href is used to
3244 link to the image. If this option is `maybe', then images in links with
3245 an empty description will be inlined, while images with a description will
3246 be linked only."
3247 :group 'org-export-html
3248 :type '(choice (const :tag "Never" nil)
3249 (const :tag "Always" t)
3250 (const :tag "When there is no description" maybe)))
3251
3252 ;; FIXME: rename
3253 (defcustom org-export-html-expand t
3254 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3255 When nil, these tags will be exported as plain text and therefore
3256 not be interpreted by a browser.
3257
3258 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3259 :group 'org-export-html
3260 :type 'boolean)
3261
3262 (defcustom org-export-html-table-tag
3263 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3264 "The HTML tag that is used to start a table.
3265 This must be a <table> tag, but you may change the options like
3266 borders and spacing."
3267 :group 'org-export-html
3268 :type 'string)
3269
3270 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3271 "The opening tag for table header fields.
3272 This is customizable so that alignment options can be specified."
3273 :group 'org-export-tables
3274 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3275
3276 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3277 "The opening tag for table data fields.
3278 This is customizable so that alignment options can be specified."
3279 :group 'org-export-tables
3280 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3281
3282 (defcustom org-export-html-with-timestamp nil
3283 "If non-nil, write `org-export-html-html-helper-timestamp'
3284 into the exported HTML text. Otherwise, the buffer will just be saved
3285 to a file."
3286 :group 'org-export-html
3287 :type 'boolean)
3288
3289 (defcustom org-export-html-html-helper-timestamp
3290 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3291 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3292 :group 'org-export-html
3293 :type 'string)
3294
3295 (defgroup org-export-icalendar nil
3296 "Options specific for iCalendar export of Org-mode files."
3297 :tag "Org Export iCalendar"
3298 :group 'org-export)
3299
3300 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3301 "The file name for the iCalendar file covering all agenda files.
3302 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3303 The file name should be absolute, the file will be overwritten without warning."
3304 :group 'org-export-icalendar
3305 :type 'file)
3306
3307 (defcustom org-icalendar-include-todo nil
3308 "Non-nil means, export to iCalendar files should also cover TODO items."
3309 :group 'org-export-icalendar
3310 :type '(choice
3311 (const :tag "None" nil)
3312 (const :tag "Unfinished" t)
3313 (const :tag "All" all)))
3314
3315 (defcustom org-icalendar-include-sexps t
3316 "Non-nil means, export to iCalendar files should also cover sexp entries.
3317 These are entries like in the diary, but directly in an Org-mode file."
3318 :group 'org-export-icalendar
3319 :type 'boolean)
3320
3321 (defcustom org-icalendar-include-body 100
3322 "Amount of text below headline to be included in iCalendar export.
3323 This is a number of characters that should maximally be included.
3324 Properties, scheduling and clocking lines will always be removed.
3325 The text will be inserted into the DESCRIPTION field."
3326 :group 'org-export-icalendar
3327 :type '(choice
3328 (const :tag "Nothing" nil)
3329 (const :tag "Everything" t)
3330 (integer :tag "Max characters")))
3331
3332 (defcustom org-icalendar-combined-name "OrgMode"
3333 "Calendar name for the combined iCalendar representing all agenda files."
3334 :group 'org-export-icalendar
3335 :type 'string)
3336
3337 (defgroup org-font-lock nil
3338 "Font-lock settings for highlighting in Org-mode."
3339 :tag "Org Font Lock"
3340 :group 'org)
3341
3342 (defcustom org-level-color-stars-only nil
3343 "Non-nil means fontify only the stars in each headline.
3344 When nil, the entire headline is fontified.
3345 Changing it requires restart of `font-lock-mode' to become effective
3346 also in regions already fontified."
3347 :group 'org-font-lock
3348 :type 'boolean)
3349
3350 (defcustom org-hide-leading-stars nil
3351 "Non-nil means, hide the first N-1 stars in a headline.
3352 This works by using the face `org-hide' for these stars. This
3353 face is white for a light background, and black for a dark
3354 background. You may have to customize the face `org-hide' to
3355 make this work.
3356 Changing it requires restart of `font-lock-mode' to become effective
3357 also in regions already fontified.
3358 You may also set this on a per-file basis by adding one of the following
3359 lines to the buffer:
3360
3361 #+STARTUP: hidestars
3362 #+STARTUP: showstars"
3363 :group 'org-font-lock
3364 :type 'boolean)
3365
3366 (defcustom org-fontify-done-headline nil
3367 "Non-nil means, change the face of a headline if it is marked DONE.
3368 Normally, only the TODO/DONE keyword indicates the state of a headline.
3369 When this is non-nil, the headline after the keyword is set to the
3370 `org-headline-done' as an additional indication."
3371 :group 'org-font-lock
3372 :type 'boolean)
3373
3374 (defcustom org-fontify-emphasized-text t
3375 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3376 Changing this variable requires a restart of Emacs to take effect."
3377 :group 'org-font-lock
3378 :type 'boolean)
3379
3380 (defvar org-emph-re nil
3381 "Regular expression for matching emphasis.")
3382 (defvar org-emphasis-regexp-components) ; defined just below
3383 (defvar org-emphasis-alist) ; defined just below
3384 (defun org-set-emph-re (var val)
3385 "Set variable and compute the emphasis regular expression."
3386 (set var val)
3387 (when (and (boundp 'org-emphasis-alist)
3388 (boundp 'org-emphasis-regexp-components)
3389 org-emphasis-alist org-emphasis-regexp-components)
3390 (let* ((e org-emphasis-regexp-components)
3391 (pre (car e))
3392 (post (nth 1 e))
3393 (border (nth 2 e))
3394 (body (nth 3 e))
3395 (nl (nth 4 e))
3396 (stacked (nth 5 e))
3397 (body1 (concat body "*?"))
3398 (markers (mapconcat 'car org-emphasis-alist "")))
3399 ;; make sure special characters appear at the right position in the class
3400 (if (string-match "\\^" markers)
3401 (setq markers (concat (replace-match "" t t markers) "^")))
3402 (if (string-match "-" markers)
3403 (setq markers (concat (replace-match "" t t markers) "-")))
3404 (if (> nl 0)
3405 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3406 (int-to-string nl) "\\}")))
3407 ;; Make the regexp
3408 (setq org-emph-re
3409 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
3410 "\\("
3411 "\\([" markers "]\\)"
3412 "\\("
3413 "[^" border (if (and nil stacked) markers) "]"
3414 body1
3415 "[^" border (if (and nil stacked) markers) "]"
3416 "\\)"
3417 "\\3\\)"
3418 "\\([" post (if stacked markers) "]\\|$\\)")))))
3419
3420 (defcustom org-emphasis-regexp-components
3421 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1 nil)
3422 "Components used to build the reqular expression for emphasis.
3423 This is a list with 6 entries. Terminology: In an emphasis string
3424 like \" *strong word* \", we call the initial space PREMATCH, the final
3425 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3426 and \"trong wor\" is the body. The different components in this variable
3427 specify what is allowed/forbidden in each part:
3428
3429 pre Chars allowed as prematch. Beginning of line will be allowed too.
3430 post Chars allowed as postmatch. End of line will be allowed too.
3431 border The chars *forbidden* as border characters.
3432 body-regexp A regexp like \".\" to match a body character. Don't use
3433 non-shy groups here, and don't allow newline here.
3434 newline The maximum number of newlines allowed in an emphasis exp.
3435 stacked Non-nil means, allow stacked styles. This works only in HTML
3436 export. When this is set, all marker characters (as given in
3437 `org-emphasis-alist') will be allowed as pre/post, aiding
3438 inside-out matching.
3439 Use customize to modify this, or restart Emacs after changing it."
3440 :group 'org-font-lock
3441 :set 'org-set-emph-re
3442 :type '(list
3443 (sexp :tag "Allowed chars in pre ")
3444 (sexp :tag "Allowed chars in post ")
3445 (sexp :tag "Forbidden chars in border ")
3446 (sexp :tag "Regexp for body ")
3447 (integer :tag "number of newlines allowed")
3448 (boolean :tag "Stacking allowed ")))
3449
3450 (defcustom org-emphasis-alist
3451 '(("*" bold "<b>" "</b>")
3452 ("/" italic "<i>" "</i>")
3453 ("_" underline "<u>" "</u>")
3454 ("=" org-code "<code>" "</code>")
3455 ("+" (:strike-through t) "<del>" "</del>")
3456 )
3457 "Special syntax for emphasized text.
3458 Text starting and ending with a special character will be emphasized, for
3459 example *bold*, _underlined_ and /italic/. This variable sets the marker
3460 characters, the face to be used by font-lock for highlighting in Org-mode
3461 Emacs buffers, and the HTML tags to be used for this.
3462 Use customize to modify this, or restart Emacs after changing it."
3463 :group 'org-font-lock
3464 :set 'org-set-emph-re
3465 :type '(repeat
3466 (list
3467 (string :tag "Marker character")
3468 (choice
3469 (face :tag "Font-lock-face")
3470 (plist :tag "Face property list"))
3471 (string :tag "HTML start tag")
3472 (string :tag "HTML end tag"))))
3473
3474 ;;; The faces
3475
3476 (defgroup org-faces nil
3477 "Faces in Org-mode."
3478 :tag "Org Faces"
3479 :group 'org-font-lock)
3480
3481 (defun org-compatible-face (inherits specs)
3482 "Make a compatible face specification.
3483 If INHERITS is an existing face and if the Emacs version supports it,
3484 just inherit the face. If not, use SPECS to define the face.
3485 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3486 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3487 to the top of the list. The `min-colors' attribute will be removed from
3488 any other entries, and any resulting duplicates will be removed entirely."
3489 (cond
3490 ((and inherits (facep inherits)
3491 (not (featurep 'xemacs)) (> emacs-major-version 22))
3492 ;; In Emacs 23, we use inheritance where possible.
3493 ;; We only do this in Emacs 23, because only there the outline
3494 ;; faces have been changed to the original org-mode-level-faces.
3495 (list (list t :inherit inherits)))
3496 ((or (featurep 'xemacs) (< emacs-major-version 22))
3497 ;; These do not understand the `min-colors' attribute.
3498 (let (r e a)
3499 (while (setq e (pop specs))
3500 (cond
3501 ((memq (car e) '(t default)) (push e r))
3502 ((setq a (member '(min-colors 8) (car e)))
3503 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3504 (cdr e)))))
3505 ((setq a (assq 'min-colors (car e)))
3506 (setq e (cons (delq a (car e)) (cdr e)))
3507 (or (assoc (car e) r) (push e r)))
3508 (t (or (assoc (car e) r) (push e r)))))
3509 (nreverse r)))
3510 (t specs)))
3511
3512 (defface org-hide
3513 '((((background light)) (:foreground "white"))
3514 (((background dark)) (:foreground "black")))
3515 "Face used to hide leading stars in headlines.
3516 The forground color of this face should be equal to the background
3517 color of the frame."
3518 :group 'org-faces)
3519
3520 (defface org-level-1 ;; font-lock-function-name-face
3521 (org-compatible-face
3522 'outline-1
3523 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3524 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3525 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3526 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3527 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3528 (t (:bold t))))
3529 "Face used for level 1 headlines."
3530 :group 'org-faces)
3531
3532 (defface org-level-2 ;; font-lock-variable-name-face
3533 (org-compatible-face
3534 'outline-2
3535 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3536 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3537 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3538 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3539 (t (:bold t))))
3540 "Face used for level 2 headlines."
3541 :group 'org-faces)
3542
3543 (defface org-level-3 ;; font-lock-keyword-face
3544 (org-compatible-face
3545 'outline-3
3546 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3547 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3548 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3549 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3550 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3551 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3552 (t (:bold t))))
3553 "Face used for level 3 headlines."
3554 :group 'org-faces)
3555
3556 (defface org-level-4 ;; font-lock-comment-face
3557 (org-compatible-face
3558 'outline-4
3559 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3560 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3561 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3562 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3563 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3564 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3565 (t (:bold t))))
3566 "Face used for level 4 headlines."
3567 :group 'org-faces)
3568
3569 (defface org-level-5 ;; font-lock-type-face
3570 (org-compatible-face
3571 'outline-5
3572 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3573 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3574 (((class color) (min-colors 8)) (:foreground "green"))))
3575 "Face used for level 5 headlines."
3576 :group 'org-faces)
3577
3578 (defface org-level-6 ;; font-lock-constant-face
3579 (org-compatible-face
3580 'outline-6
3581 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3582 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3583 (((class color) (min-colors 8)) (:foreground "magenta"))))
3584 "Face used for level 6 headlines."
3585 :group 'org-faces)
3586
3587 (defface org-level-7 ;; font-lock-builtin-face
3588 (org-compatible-face
3589 'outline-7
3590 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3591 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3592 (((class color) (min-colors 8)) (:foreground "blue"))))
3593 "Face used for level 7 headlines."
3594 :group 'org-faces)
3595
3596 (defface org-level-8 ;; font-lock-string-face
3597 (org-compatible-face
3598 'outline-8
3599 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3600 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3601 (((class color) (min-colors 8)) (:foreground "green"))))
3602 "Face used for level 8 headlines."
3603 :group 'org-faces)
3604
3605 (defface org-special-keyword ;; font-lock-string-face
3606 (org-compatible-face
3607 nil
3608 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3609 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3610 (t (:italic t))))
3611 "Face used for special keywords."
3612 :group 'org-faces)
3613
3614 (defface org-drawer ;; font-lock-function-name-face
3615 (org-compatible-face
3616 nil
3617 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3618 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3619 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3620 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3621 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3622 (t (:bold t))))
3623 "Face used for drawers."
3624 :group 'org-faces)
3625
3626 (defface org-property-value nil
3627 "Face used for the value of a property."
3628 :group 'org-faces)
3629
3630 (defface org-column
3631 (org-compatible-face
3632 nil
3633 '((((class color) (min-colors 16) (background light))
3634 (:background "grey90"))
3635 (((class color) (min-colors 16) (background dark))
3636 (:background "grey30"))
3637 (((class color) (min-colors 8))
3638 (:background "cyan" :foreground "black"))
3639 (t (:inverse-video t))))
3640 "Face for column display of entry properties."
3641 :group 'org-faces)
3642
3643 (when (fboundp 'set-face-attribute)
3644 ;; Make sure that a fixed-width face is used when we have a column table.
3645 (set-face-attribute 'org-column nil
3646 :height (face-attribute 'default :height)
3647 :family (face-attribute 'default :family)))
3648
3649 (defface org-warning
3650 (org-compatible-face
3651 'font-lock-warning-face
3652 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3653 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3654 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3655 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3656 (t (:bold t))))
3657 "Face for deadlines and TODO keywords."
3658 :group 'org-faces)
3659
3660 (defface org-archived ; similar to shadow
3661 (org-compatible-face
3662 'shadow
3663 '((((class color grayscale) (min-colors 88) (background light))
3664 (:foreground "grey50"))
3665 (((class color grayscale) (min-colors 88) (background dark))
3666 (:foreground "grey70"))
3667 (((class color) (min-colors 8) (background light))
3668 (:foreground "green"))
3669 (((class color) (min-colors 8) (background dark))
3670 (:foreground "yellow"))))
3671 "Face for headline with the ARCHIVE tag."
3672 :group 'org-faces)
3673
3674 (defface org-link
3675 '((((class color) (background light)) (:foreground "Purple" :underline t))
3676 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3677 (t (:underline t)))
3678 "Face for links."
3679 :group 'org-faces)
3680
3681 (defface org-ellipsis
3682 '((((class color) (background light)) (:foreground "DarkGoldenrod" :strike-through t))
3683 (((class color) (background dark)) (:foreground "LightGoldenrod" :strike-through t))
3684 (t (:strike-through t)))
3685 "Face for the ellipsis in folded text."
3686 :group 'org-faces)
3687
3688 (defface org-target
3689 '((((class color) (background light)) (:underline t))
3690 (((class color) (background dark)) (:underline t))
3691 (t (:underline t)))
3692 "Face for links."
3693 :group 'org-faces)
3694
3695 (defface org-date
3696 '((((class color) (background light)) (:foreground "Purple" :underline t))
3697 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3698 (t (:underline t)))
3699 "Face for links."
3700 :group 'org-faces)
3701
3702 (defface org-sexp-date
3703 '((((class color) (background light)) (:foreground "Purple"))
3704 (((class color) (background dark)) (:foreground "Cyan"))
3705 (t (:underline t)))
3706 "Face for links."
3707 :group 'org-faces)
3708
3709 (defface org-tag
3710 '((t (:bold t)))
3711 "Face for tags."
3712 :group 'org-faces)
3713
3714 (defface org-todo ; font-lock-warning-face
3715 (org-compatible-face
3716 nil
3717 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3718 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3719 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3720 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3721 (t (:inverse-video t :bold t))))
3722 "Face for TODO keywords."
3723 :group 'org-faces)
3724
3725 (defface org-done ;; font-lock-type-face
3726 (org-compatible-face
3727 nil
3728 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3729 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3730 (((class color) (min-colors 8)) (:foreground "green"))
3731 (t (:bold t))))
3732 "Face used for todo keywords that indicate DONE items."
3733 :group 'org-faces)
3734
3735 (defface org-headline-done ;; font-lock-string-face
3736 (org-compatible-face
3737 nil
3738 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3739 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3740 (((class color) (min-colors 8) (background light)) (:bold nil))))
3741 "Face used to indicate that a headline is DONE.
3742 This face is only used if `org-fontify-done-headline' is set. If applies
3743 to the part of the headline after the DONE keyword."
3744 :group 'org-faces)
3745
3746 (defcustom org-todo-keyword-faces nil
3747 "Faces for specific TODO keywords.
3748 This is a list of cons cells, with TODO keywords in the car
3749 and faces in the cdr. The face can be a symbol, or a property
3750 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3751 :group 'org-faces
3752 :group 'org-todo
3753 :type '(repeat
3754 (cons
3755 (string :tag "keyword")
3756 (sexp :tag "face"))))
3757
3758 (defface org-table ;; font-lock-function-name-face
3759 (org-compatible-face
3760 nil
3761 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3762 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3763 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3764 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3765 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3766 (((class color) (min-colors 8) (background dark)))))
3767 "Face used for tables."
3768 :group 'org-faces)
3769
3770 (defface org-formula
3771 (org-compatible-face
3772 nil
3773 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3774 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3775 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3776 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3777 (t (:bold t :italic t))))
3778 "Face for formulas."
3779 :group 'org-faces)
3780
3781 (defface org-code
3782 (org-compatible-face
3783 nil
3784 '((((class color grayscale) (min-colors 88) (background light))
3785 (:foreground "grey50"))
3786 (((class color grayscale) (min-colors 88) (background dark))
3787 (:foreground "grey70"))
3788 (((class color) (min-colors 8) (background light))
3789 (:foreground "green"))
3790 (((class color) (min-colors 8) (background dark))
3791 (:foreground "yellow"))))
3792 "Face for fixed-with text like code snippets."
3793 :group 'org-faces
3794 :version "22.1")
3795
3796 (defface org-agenda-structure ;; font-lock-function-name-face
3797 (org-compatible-face
3798 nil
3799 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3800 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3801 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3802 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3803 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3804 (t (:bold t))))
3805 "Face used in agenda for captions and dates."
3806 :group 'org-faces)
3807
3808 (defface org-scheduled-today
3809 (org-compatible-face
3810 nil
3811 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3812 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3813 (((class color) (min-colors 8)) (:foreground "green"))
3814 (t (:bold t :italic t))))
3815 "Face for items scheduled for a certain day."
3816 :group 'org-faces)
3817
3818 (defface org-scheduled-previously
3819 (org-compatible-face
3820 nil
3821 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3822 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3823 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3824 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3825 (t (:bold t))))
3826 "Face for items scheduled previously, and not yet done."
3827 :group 'org-faces)
3828
3829 (defface org-upcoming-deadline
3830 (org-compatible-face
3831 nil
3832 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3833 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3834 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3835 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3836 (t (:bold t))))
3837 "Face for items scheduled previously, and not yet done."
3838 :group 'org-faces)
3839
3840 (defcustom org-agenda-deadline-faces
3841 '((1.0 . org-warning)
3842 (0.5 . org-upcoming-deadline)
3843 (0.0 . default))
3844 "Faces for showing deadlines in the agenda.
3845 This is a list of cons cells. The cdr of each cess is a face to be used,
3846 and it can also just be a like like '(:foreground \"yellow\").
3847 Each car is a fraction of the head-warning time that must have passed for
3848 this the face in the cdr to be used for display. The numbers must be
3849 given in descending order. The head-warning time is normally taken
3850 from `org-deadline-warning-days', but can also be specified in the deadline
3851 timestamp itself, like this:
3852
3853 DEADLINE: <2007-08-13 Mon -8d>
3854
3855 You may use d for days, w for weeks, m for months and y for years. Months
3856 and years will only be treated in an approximate fashion (30.4 days for a
3857 month and 365.24 days for a year)."
3858 :group 'org-faces
3859 :group 'org-agenda-daily/weekly
3860 :type '(repeat
3861 (cons
3862 (number :tag "Fraction of head-warning time passed")
3863 (sexp :tag "Face"))))
3864
3865 (defface org-time-grid ;; font-lock-variable-name-face
3866 (org-compatible-face
3867 nil
3868 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3869 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3870 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3871 "Face used for time grids."
3872 :group 'org-faces)
3873
3874 (defconst org-level-faces
3875 '(org-level-1 org-level-2 org-level-3 org-level-4
3876 org-level-5 org-level-6 org-level-7 org-level-8
3877 ))
3878
3879 (defcustom org-n-level-faces (length org-level-faces)
3880 "The number different faces to be used for headlines.
3881 Org-mode defines 8 different headline faces, so this can be at most 8.
3882 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
3883 :type 'number
3884 :group 'org-faces)
3885
3886 ;;; Function declarations.
3887 (declare-function add-to-diary-list "diary-lib"
3888 (date string specifier &optional marker globcolor literal))
3889 (declare-function table--at-cell-p "table" (position &optional object at-column))
3890 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
3891 (declare-function bbdb "ext:bbdb-com" (string elidep))
3892 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
3893 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
3894 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
3895 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
3896 (declare-function bbdb-record-name "ext:bbdb" (record))
3897 (declare-function bibtex-beginning-of-entry "bibtex" ())
3898 (declare-function bibtex-generate-autokey "bibtex" ())
3899 (declare-function bibtex-parse-entry "bibtex" (&optional content))
3900 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
3901 (declare-function cdlatex-tab "ext:cdlatex" ())
3902 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3903 (declare-function gnus-article-show-summary "gnus-art" ())
3904 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
3905 (declare-function mh-find-path "mh-utils" ())
3906 (declare-function mh-get-header-field "mh-utils" (field))
3907 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
3908 (declare-function mh-header-display "mh-show" ())
3909 (declare-function mh-index-previous-folder "mh-search" ())
3910 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
3911 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
3912 (declare-function mh-search-choose "mh-search" (&optional searcher))
3913 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
3914 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
3915 (declare-function mh-show-header-display "mh-show" t t)
3916 (declare-function mh-show-msg "mh-show" (msg))
3917 (declare-function mh-show-show "mh-show" t t)
3918 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
3919 (declare-function org-export-latex-cleaned-string "org-export-latex" (&optional commentsp))
3920 (declare-function remember "remember" (&optional initial))
3921 (declare-function remember-buffer-desc "remember" ())
3922 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
3923 (declare-function rmail-what-message "rmail" ())
3924 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
3925 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
3926 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
3927 (declare-function vm-beginning-of-message "ext:vm-page" ())
3928 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
3929 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
3930 (declare-function vm-isearch-narrow "ext:vm-search" ())
3931 (declare-function vm-isearch-update "ext:vm-search" ())
3932 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
3933 (declare-function vm-su-message-id "ext:vm-summary" (m))
3934 (declare-function vm-su-subject "ext:vm-summary" (m))
3935 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
3936 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
3937 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
3938 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
3939 (declare-function wl-summary-line-from "ext:wl-summary" ())
3940 (declare-function wl-summary-line-subject "ext:wl-summary" ())
3941 (declare-function wl-summary-message-number "ext:wl-summary" ())
3942 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
3943
3944 ;;; Variables for pre-computed regular expressions, all buffer local
3945
3946 (defvar org-drawer-regexp nil
3947 "Matches first line of a hidden block.")
3948 (make-variable-buffer-local 'org-drawer-regexp)
3949 (defvar org-todo-regexp nil
3950 "Matches any of the TODO state keywords.")
3951 (make-variable-buffer-local 'org-todo-regexp)
3952 (defvar org-not-done-regexp nil
3953 "Matches any of the TODO state keywords except the last one.")
3954 (make-variable-buffer-local 'org-not-done-regexp)
3955 (defvar org-todo-line-regexp nil
3956 "Matches a headline and puts TODO state into group 2 if present.")
3957 (make-variable-buffer-local 'org-todo-line-regexp)
3958 (defvar org-complex-heading-regexp nil
3959 "Matches a headline and puts everything into groups:
3960 group 1: the stars
3961 group 2: The todo keyword, maybe
3962 group 3: Priority cookie
3963 group 4: True headline
3964 group 5: Tags")
3965 (make-variable-buffer-local 'org-complex-heading-regexp)
3966 (defvar org-todo-line-tags-regexp nil
3967 "Matches a headline and puts TODO state into group 2 if present.
3968 Also put tags into group 4 if tags are present.")
3969 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3970 (defvar org-nl-done-regexp nil
3971 "Matches newline followed by a headline with the DONE keyword.")
3972 (make-variable-buffer-local 'org-nl-done-regexp)
3973 (defvar org-looking-at-done-regexp nil
3974 "Matches the DONE keyword a point.")
3975 (make-variable-buffer-local 'org-looking-at-done-regexp)
3976 (defvar org-ds-keyword-length 12
3977 "Maximum length of the Deadline and SCHEDULED keywords.")
3978 (make-variable-buffer-local 'org-ds-keyword-length)
3979 (defvar org-deadline-regexp nil
3980 "Matches the DEADLINE keyword.")
3981 (make-variable-buffer-local 'org-deadline-regexp)
3982 (defvar org-deadline-time-regexp nil
3983 "Matches the DEADLINE keyword together with a time stamp.")
3984 (make-variable-buffer-local 'org-deadline-time-regexp)
3985 (defvar org-deadline-line-regexp nil
3986 "Matches the DEADLINE keyword and the rest of the line.")
3987 (make-variable-buffer-local 'org-deadline-line-regexp)
3988 (defvar org-scheduled-regexp nil
3989 "Matches the SCHEDULED keyword.")
3990 (make-variable-buffer-local 'org-scheduled-regexp)
3991 (defvar org-scheduled-time-regexp nil
3992 "Matches the SCHEDULED keyword together with a time stamp.")
3993 (make-variable-buffer-local 'org-scheduled-time-regexp)
3994 (defvar org-closed-time-regexp nil
3995 "Matches the CLOSED keyword together with a time stamp.")
3996 (make-variable-buffer-local 'org-closed-time-regexp)
3997
3998 (defvar org-keyword-time-regexp nil
3999 "Matches any of the 4 keywords, together with the time stamp.")
4000 (make-variable-buffer-local 'org-keyword-time-regexp)
4001 (defvar org-keyword-time-not-clock-regexp nil
4002 "Matches any of the 3 keywords, together with the time stamp.")
4003 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4004 (defvar org-maybe-keyword-time-regexp nil
4005 "Matches a timestamp, possibly preceeded by a keyword.")
4006 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4007 (defvar org-planning-or-clock-line-re nil
4008 "Matches a line with planning or clock info.")
4009 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4010
4011 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4012 rear-nonsticky t mouse-map t fontified t)
4013 "Properties to remove when a string without properties is wanted.")
4014
4015 (defsubst org-match-string-no-properties (num &optional string)
4016 (if (featurep 'xemacs)
4017 (let ((s (match-string num string)))
4018 (remove-text-properties 0 (length s) org-rm-props s)
4019 s)
4020 (match-string-no-properties num string)))
4021
4022 (defsubst org-no-properties (s)
4023 (if (fboundp 'set-text-properties)
4024 (set-text-properties 0 (length s) nil s)
4025 (remove-text-properties 0 (length s) org-rm-props s))
4026 s)
4027
4028 (defsubst org-get-alist-option (option key)
4029 (cond ((eq key t) t)
4030 ((eq option t) t)
4031 ((assoc key option) (cdr (assoc key option)))
4032 (t (cdr (assq 'default option)))))
4033
4034 (defsubst org-inhibit-invisibility ()
4035 "Modified `buffer-invisibility-spec' for Emacs 21.
4036 Some ops with invisible text do not work correctly on Emacs 21. For these
4037 we turn off invisibility temporarily. Use this in a `let' form."
4038 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4039
4040 (defsubst org-set-local (var value)
4041 "Make VAR local in current buffer and set it to VALUE."
4042 (set (make-variable-buffer-local var) value))
4043
4044 (defsubst org-mode-p ()
4045 "Check if the current buffer is in Org-mode."
4046 (eq major-mode 'org-mode))
4047
4048 (defsubst org-last (list)
4049 "Return the last element of LIST."
4050 (car (last list)))
4051
4052 (defun org-let (list &rest body)
4053 (eval (cons 'let (cons list body))))
4054 (put 'org-let 'lisp-indent-function 1)
4055
4056 (defun org-let2 (list1 list2 &rest body)
4057 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4058 (put 'org-let2 'lisp-indent-function 2)
4059 (defconst org-startup-options
4060 '(("fold" org-startup-folded t)
4061 ("overview" org-startup-folded t)
4062 ("nofold" org-startup-folded nil)
4063 ("showall" org-startup-folded nil)
4064 ("content" org-startup-folded content)
4065 ("hidestars" org-hide-leading-stars t)
4066 ("showstars" org-hide-leading-stars nil)
4067 ("odd" org-odd-levels-only t)
4068 ("oddeven" org-odd-levels-only nil)
4069 ("align" org-startup-align-all-tables t)
4070 ("noalign" org-startup-align-all-tables nil)
4071 ("customtime" org-display-custom-times t)
4072 ("logging" org-log-done t)
4073 ("logdone" org-log-done t)
4074 ("nologging" org-log-done nil)
4075 ("lognotedone" org-log-done done push)
4076 ("lognotestate" org-log-done state push)
4077 ("lognoteclock-out" org-log-done clock-out push)
4078 ("logrepeat" org-log-repeat t)
4079 ("nologrepeat" org-log-repeat nil)
4080 ("constcgs" constants-unit-system cgs)
4081 ("constSI" constants-unit-system SI))
4082 "Variable associated with STARTUP options for org-mode.
4083 Each element is a list of three items: The startup options as written
4084 in the #+STARTUP line, the corresponding variable, and the value to
4085 set this variable to if the option is found. An optional forth element PUSH
4086 means to push this value onto the list in the variable.")
4087
4088 (defun org-set-regexps-and-options ()
4089 "Precompute regular expressions for current buffer."
4090 (when (org-mode-p)
4091 (org-set-local 'org-todo-kwd-alist nil)
4092 (org-set-local 'org-todo-key-alist nil)
4093 (org-set-local 'org-todo-key-trigger nil)
4094 (org-set-local 'org-todo-keywords-1 nil)
4095 (org-set-local 'org-done-keywords nil)
4096 (org-set-local 'org-todo-heads nil)
4097 (org-set-local 'org-todo-sets nil)
4098 (org-set-local 'org-todo-log-states nil)
4099 (let ((re (org-make-options-regexp
4100 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4101 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4102 "CONSTANTS" "PROPERTY" "DRAWERS")))
4103 (splitre "[ \t]+")
4104 kwds kws0 kwsa key value cat arch tags const links hw dws
4105 tail sep kws1 prio props drawers
4106 ex log)
4107 (save-excursion
4108 (save-restriction
4109 (widen)
4110 (goto-char (point-min))
4111 (while (re-search-forward re nil t)
4112 (setq key (match-string 1) value (org-match-string-no-properties 2))
4113 (cond
4114 ((equal key "CATEGORY")
4115 (if (string-match "[ \t]+$" value)
4116 (setq value (replace-match "" t t value)))
4117 (setq cat (intern value)))
4118 ((member key '("SEQ_TODO" "TODO"))
4119 (push (cons 'sequence (org-split-string value splitre)) kwds))
4120 ((equal key "TYP_TODO")
4121 (push (cons 'type (org-split-string value splitre)) kwds))
4122 ((equal key "TAGS")
4123 (setq tags (append tags (org-split-string value splitre))))
4124 ((equal key "COLUMNS")
4125 (org-set-local 'org-columns-default-format value))
4126 ((equal key "LINK")
4127 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4128 (push (cons (match-string 1 value)
4129 (org-trim (match-string 2 value)))
4130 links)))
4131 ((equal key "PRIORITIES")
4132 (setq prio (org-split-string value " +")))
4133 ((equal key "PROPERTY")
4134 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4135 (push (cons (match-string 1 value) (match-string 2 value))
4136 props)))
4137 ((equal key "DRAWERS")
4138 (setq drawers (org-split-string value splitre)))
4139 ((equal key "CONSTANTS")
4140 (setq const (append const (org-split-string value splitre))))
4141 ((equal key "STARTUP")
4142 (let ((opts (org-split-string value splitre))
4143 l var val)
4144 (while (setq l (pop opts))
4145 (when (setq l (assoc l org-startup-options))
4146 (setq var (nth 1 l) val (nth 2 l))
4147 (if (not (nth 3 l))
4148 (set (make-local-variable var) val)
4149 (if (not (listp (symbol-value var)))
4150 (set (make-local-variable var) nil))
4151 (set (make-local-variable var) (symbol-value var))
4152 (add-to-list var val))))))
4153 ((equal key "ARCHIVE")
4154 (string-match " *$" value)
4155 (setq arch (replace-match "" t t value))
4156 (remove-text-properties 0 (length arch)
4157 '(face t fontified t) arch)))
4158 )))
4159 (and cat (org-set-local 'org-category cat))
4160 (when prio
4161 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4162 (setq prio (mapcar 'string-to-char prio))
4163 (org-set-local 'org-highest-priority (nth 0 prio))
4164 (org-set-local 'org-lowest-priority (nth 1 prio))
4165 (org-set-local 'org-default-priority (nth 2 prio)))
4166 (and props (org-set-local 'org-local-properties (nreverse props)))
4167 (and drawers (org-set-local 'org-drawers drawers))
4168 (and arch (org-set-local 'org-archive-location arch))
4169 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4170 ;; Process the TODO keywords
4171 (unless kwds
4172 ;; Use the global values as if they had been given locally.
4173 (setq kwds (default-value 'org-todo-keywords))
4174 (if (stringp (car kwds))
4175 (setq kwds (list (cons org-todo-interpretation
4176 (default-value 'org-todo-keywords)))))
4177 (setq kwds (reverse kwds)))
4178 (setq kwds (nreverse kwds))
4179 (let (inter kws kw)
4180 (while (setq kws (pop kwds))
4181 (setq inter (pop kws) sep (member "|" kws)
4182 kws0 (delete "|" (copy-sequence kws))
4183 kwsa nil
4184 kws1 (mapcar
4185 (lambda (x)
4186 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4187 (progn
4188 (setq kw (match-string 1 x)
4189 ex (and (match-end 2) (match-string 2 x))
4190 log (and ex (string-match "@" ex))
4191 key (and ex (substring ex 0 1)))
4192 (if (equal key "@") (setq key nil))
4193 (push (cons kw (and key (string-to-char key))) kwsa)
4194 (and log (push kw org-todo-log-states))
4195 kw)
4196 (error "Invalid TODO keyword %s" x)))
4197 kws0)
4198 kwsa (if kwsa (append '((:startgroup))
4199 (nreverse kwsa)
4200 '((:endgroup))))
4201 hw (car kws1)
4202 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4203 tail (list inter hw (car dws) (org-last dws)))
4204 (add-to-list 'org-todo-heads hw 'append)
4205 (push kws1 org-todo-sets)
4206 (setq org-done-keywords (append org-done-keywords dws nil))
4207 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4208 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4209 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4210 (setq org-todo-sets (nreverse org-todo-sets)
4211 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4212 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4213 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4214 ;; Process the constants
4215 (when const
4216 (let (e cst)
4217 (while (setq e (pop const))
4218 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4219 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4220 (setq org-table-formula-constants-local cst)))
4221
4222 ;; Process the tags.
4223 (when tags
4224 (let (e tgs)
4225 (while (setq e (pop tags))
4226 (cond
4227 ((equal e "{") (push '(:startgroup) tgs))
4228 ((equal e "}") (push '(:endgroup) tgs))
4229 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4230 (push (cons (match-string 1 e)
4231 (string-to-char (match-string 2 e)))
4232 tgs))
4233 (t (push (list e) tgs))))
4234 (org-set-local 'org-tag-alist nil)
4235 (while (setq e (pop tgs))
4236 (or (and (stringp (car e))
4237 (assoc (car e) org-tag-alist))
4238 (push e org-tag-alist))))))
4239
4240 ;; Compute the regular expressions and other local variables
4241 (if (not org-done-keywords)
4242 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4243 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4244 (length org-scheduled-string)))
4245 org-drawer-regexp
4246 (concat "^[ \t]*:\\("
4247 (mapconcat 'regexp-quote org-drawers "\\|")
4248 "\\):[ \t]*$")
4249 org-not-done-keywords
4250 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4251 org-todo-regexp
4252 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4253 "\\|") "\\)\\>")
4254 org-not-done-regexp
4255 (concat "\\<\\("
4256 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4257 "\\)\\>")
4258 org-todo-line-regexp
4259 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4260 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4261 "\\)\\>\\)?[ \t]*\\(.*\\)")
4262 org-complex-heading-regexp
4263 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4264 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4265 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4266 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4267 org-nl-done-regexp
4268 (concat "\n\\*+[ \t]+"
4269 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4270 "\\)" "\\>")
4271 org-todo-line-tags-regexp
4272 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4273 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4274 (org-re
4275 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4276 org-looking-at-done-regexp
4277 (concat "^" "\\(?:"
4278 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4279 "\\>")
4280 org-deadline-regexp (concat "\\<" org-deadline-string)
4281 org-deadline-time-regexp
4282 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4283 org-deadline-line-regexp
4284 (concat "\\<\\(" org-deadline-string "\\).*")
4285 org-scheduled-regexp
4286 (concat "\\<" org-scheduled-string)
4287 org-scheduled-time-regexp
4288 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4289 org-closed-time-regexp
4290 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4291 org-keyword-time-regexp
4292 (concat "\\<\\(" org-scheduled-string
4293 "\\|" org-deadline-string
4294 "\\|" org-closed-string
4295 "\\|" org-clock-string "\\)"
4296 " *[[<]\\([^]>]+\\)[]>]")
4297 org-keyword-time-not-clock-regexp
4298 (concat "\\<\\(" org-scheduled-string
4299 "\\|" org-deadline-string
4300 "\\|" org-closed-string
4301 "\\)"
4302 " *[[<]\\([^]>]+\\)[]>]")
4303 org-maybe-keyword-time-regexp
4304 (concat "\\(\\<\\(" org-scheduled-string
4305 "\\|" org-deadline-string
4306 "\\|" org-closed-string
4307 "\\|" org-clock-string "\\)\\)?"
4308 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4309 org-planning-or-clock-line-re
4310 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4311 "\\|" org-deadline-string
4312 "\\|" org-closed-string "\\|" org-clock-string
4313 "\\)\\>\\)")
4314 )
4315
4316 (org-set-font-lock-defaults)))
4317
4318 (defun org-remove-keyword-keys (list)
4319 (mapcar (lambda (x)
4320 (if (string-match "(..?)$" x)
4321 (substring x 0 (match-beginning 0))
4322 x))
4323 list))
4324
4325 ;;; Some variables ujsed in various places
4326
4327 (defvar org-window-configuration nil
4328 "Used in various places to store a window configuration.")
4329 (defvar org-finish-function nil
4330 "Function to be called when `C-c C-c' is used.
4331 This is for getting out of special buffers like remember.")
4332
4333 ;;; Foreign variables, to inform the compiler
4334
4335 ;; XEmacs only
4336 (defvar outline-mode-menu-heading)
4337 (defvar outline-mode-menu-show)
4338 (defvar outline-mode-menu-hide)
4339 (defvar zmacs-regions) ; XEmacs regions
4340 ;; Emacs only
4341 (defvar mark-active)
4342
4343 ;; Packages that org-mode interacts with
4344 (defvar calc-embedded-close-formula)
4345 (defvar calc-embedded-open-formula)
4346 (defvar font-lock-unfontify-region-function)
4347 (defvar org-goto-start-pos)
4348 (defvar vm-message-pointer)
4349 (defvar vm-folder-directory)
4350 (defvar wl-summary-buffer-elmo-folder)
4351 (defvar wl-summary-buffer-folder-name)
4352 (defvar gnus-other-frame-object)
4353 (defvar gnus-group-name)
4354 (defvar gnus-article-current)
4355 (defvar w3m-current-url)
4356 (defvar w3m-current-title)
4357 (defvar mh-progs)
4358 (defvar mh-current-folder)
4359 (defvar mh-show-folder-buffer)
4360 (defvar mh-index-folder)
4361 (defvar mh-searcher)
4362 (defvar calendar-mode-map)
4363 (defvar Info-current-file)
4364 (defvar Info-current-node)
4365 (defvar texmathp-why)
4366 (defvar remember-save-after-remembering)
4367 (defvar remember-data-file)
4368 (defvar remember-register)
4369 (defvar remember-buffer)
4370 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
4371 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
4372 (defvar org-latex-regexps)
4373 (defvar constants-unit-system)
4374
4375 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4376
4377 ;; FIXME: Occasionally check by commenting these, to make sure
4378 ;; no other functions uses these, forgetting to let-bind them.
4379 (defvar entry)
4380 (defvar state)
4381 (defvar last-state)
4382 (defvar date)
4383 (defvar description)
4384
4385
4386 ;; Defined somewhere in this file, but used before definition.
4387 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4388 (defvar org-agenda-buffer-name)
4389 (defvar org-agenda-undo-list)
4390 (defvar org-agenda-pending-undo-list)
4391 (defvar org-agenda-overriding-header)
4392 (defvar orgtbl-mode)
4393 (defvar org-html-entities)
4394 (defvar org-struct-menu)
4395 (defvar org-org-menu)
4396 (defvar org-tbl-menu)
4397 (defvar org-agenda-keymap)
4398
4399 ;;;; Emacs/XEmacs compatibility
4400
4401 ;; Overlay compatibility functions
4402 (defun org-make-overlay (beg end &optional buffer)
4403 (if (featurep 'xemacs)
4404 (make-extent beg end buffer)
4405 (make-overlay beg end buffer)))
4406 (defun org-delete-overlay (ovl)
4407 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4408 (defun org-detach-overlay (ovl)
4409 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4410 (defun org-move-overlay (ovl beg end &optional buffer)
4411 (if (featurep 'xemacs)
4412 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4413 (move-overlay ovl beg end buffer)))
4414 (defun org-overlay-put (ovl prop value)
4415 (if (featurep 'xemacs)
4416 (set-extent-property ovl prop value)
4417 (overlay-put ovl prop value)))
4418 (defun org-overlay-display (ovl text &optional face evap)
4419 "Make overlay OVL display TEXT with face FACE."
4420 (if (featurep 'xemacs)
4421 (let ((gl (make-glyph text)))
4422 (and face (set-glyph-face gl face))
4423 (set-extent-property ovl 'invisible t)
4424 (set-extent-property ovl 'end-glyph gl))
4425 (overlay-put ovl 'display text)
4426 (if face (overlay-put ovl 'face face))
4427 (if evap (overlay-put ovl 'evaporate t))))
4428 (defun org-overlay-before-string (ovl text &optional face evap)
4429 "Make overlay OVL display TEXT with face FACE."
4430 (if (featurep 'xemacs)
4431 (let ((gl (make-glyph text)))
4432 (and face (set-glyph-face gl face))
4433 (set-extent-property ovl 'begin-glyph gl))
4434 (if face (org-add-props text nil 'face face))
4435 (overlay-put ovl 'before-string text)
4436 (if evap (overlay-put ovl 'evaporate t))))
4437 (defun org-overlay-get (ovl prop)
4438 (if (featurep 'xemacs)
4439 (extent-property ovl prop)
4440 (overlay-get ovl prop)))
4441 (defun org-overlays-at (pos)
4442 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4443 (defun org-overlays-in (&optional start end)
4444 (if (featurep 'xemacs)
4445 (extent-list nil start end)
4446 (overlays-in start end)))
4447 (defun org-overlay-start (o)
4448 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4449 (defun org-overlay-end (o)
4450 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4451 (defun org-find-overlays (prop &optional pos delete)
4452 "Find all overlays specifying PROP at POS or point.
4453 If DELETE is non-nil, delete all those overlays."
4454 (let ((overlays (org-overlays-at (or pos (point))))
4455 ov found)
4456 (while (setq ov (pop overlays))
4457 (if (org-overlay-get ov prop)
4458 (if delete (org-delete-overlay ov) (push ov found))))
4459 found))
4460
4461 ;; Region compatibility
4462
4463 (defun org-add-hook (hook function &optional append local)
4464 "Add-hook, compatible with both Emacsen."
4465 (if (and local (featurep 'xemacs))
4466 (add-local-hook hook function append)
4467 (add-hook hook function append local)))
4468
4469 (defvar org-ignore-region nil
4470 "To temporarily disable the active region.")
4471
4472 (defun org-region-active-p ()
4473 "Is `transient-mark-mode' on and the region active?
4474 Works on both Emacs and XEmacs."
4475 (if org-ignore-region
4476 nil
4477 (if (featurep 'xemacs)
4478 (and zmacs-regions (region-active-p))
4479 (and transient-mark-mode mark-active))))
4480
4481 ;; Invisibility compatibility
4482
4483 (defun org-add-to-invisibility-spec (arg)
4484 "Add elements to `buffer-invisibility-spec'.
4485 See documentation for `buffer-invisibility-spec' for the kind of elements
4486 that can be added."
4487 (cond
4488 ((fboundp 'add-to-invisibility-spec)
4489 (add-to-invisibility-spec arg))
4490 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4491 (setq buffer-invisibility-spec (list arg)))
4492 (t
4493 (setq buffer-invisibility-spec
4494 (cons arg buffer-invisibility-spec)))))
4495
4496 (defun org-remove-from-invisibility-spec (arg)
4497 "Remove elements from `buffer-invisibility-spec'."
4498 (if (fboundp 'remove-from-invisibility-spec)
4499 (remove-from-invisibility-spec arg)
4500 (if (consp buffer-invisibility-spec)
4501 (setq buffer-invisibility-spec
4502 (delete arg buffer-invisibility-spec)))))
4503
4504 (defun org-in-invisibility-spec-p (arg)
4505 "Is ARG a member of `buffer-invisibility-spec'?"
4506 (if (consp buffer-invisibility-spec)
4507 (member arg buffer-invisibility-spec)
4508 nil))
4509
4510 ;;;; Define the Org-mode
4511
4512 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4513 (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."))
4514
4515
4516 ;; We use a before-change function to check if a table might need
4517 ;; an update.
4518 (defvar org-table-may-need-update t
4519 "Indicates that a table might need an update.
4520 This variable is set by `org-before-change-function'.
4521 `org-table-align' sets it back to nil.")
4522 (defvar org-mode-map)
4523 (defvar org-mode-hook nil)
4524 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4525 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4526 (defvar org-table-buffer-is-an nil)
4527 (defconst org-outline-regexp "\\*+ ")
4528
4529 ;;;###autoload
4530 (define-derived-mode org-mode outline-mode "Org"
4531 "Outline-based notes management and organizer, alias
4532 \"Carsten's outline-mode for keeping track of everything.\"
4533
4534 Org-mode develops organizational tasks around a NOTES file which
4535 contains information about projects as plain text. Org-mode is
4536 implemented on top of outline-mode, which is ideal to keep the content
4537 of large files well structured. It supports ToDo items, deadlines and
4538 time stamps, which magically appear in the diary listing of the Emacs
4539 calendar. Tables are easily created with a built-in table editor.
4540 Plain text URL-like links connect to websites, emails (VM), Usenet
4541 messages (Gnus), BBDB entries, and any files related to the project.
4542 For printing and sharing of notes, an Org-mode file (or a part of it)
4543 can be exported as a structured ASCII or HTML file.
4544
4545 The following commands are available:
4546
4547 \\{org-mode-map}"
4548
4549 ;; Get rid of Outline menus, they are not needed
4550 ;; Need to do this here because define-derived-mode sets up
4551 ;; the keymap so late. Still, it is a waste to call this each time
4552 ;; we switch another buffer into org-mode.
4553 (if (featurep 'xemacs)
4554 (when (boundp 'outline-mode-menu-heading)
4555 ;; Assume this is Greg's port, it used easymenu
4556 (easy-menu-remove outline-mode-menu-heading)
4557 (easy-menu-remove outline-mode-menu-show)
4558 (easy-menu-remove outline-mode-menu-hide))
4559 (define-key org-mode-map [menu-bar headings] 'undefined)
4560 (define-key org-mode-map [menu-bar hide] 'undefined)
4561 (define-key org-mode-map [menu-bar show] 'undefined))
4562
4563 (easy-menu-add org-org-menu)
4564 (easy-menu-add org-tbl-menu)
4565 (org-install-agenda-files-menu)
4566 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4567 (org-add-to-invisibility-spec '(org-cwidth))
4568 (when (featurep 'xemacs)
4569 (org-set-local 'line-move-ignore-invisible t))
4570 (org-set-local 'outline-regexp org-outline-regexp)
4571 (org-set-local 'outline-level 'org-outline-level)
4572 (when (and org-ellipsis
4573 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4574 (fboundp 'make-glyph-code))
4575 (unless org-display-table
4576 (setq org-display-table (make-display-table)))
4577 (set-display-table-slot
4578 org-display-table 4
4579 (vconcat (mapcar
4580 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4581 org-ellipsis)))
4582 (if (stringp org-ellipsis) org-ellipsis "..."))))
4583 (setq buffer-display-table org-display-table))
4584 (org-set-regexps-and-options)
4585 ;; Calc embedded
4586 (org-set-local 'calc-embedded-open-mode "# ")
4587 (modify-syntax-entry ?# "<")
4588 (modify-syntax-entry ?@ "w")
4589 (if org-startup-truncated (setq truncate-lines t))
4590 (org-set-local 'font-lock-unfontify-region-function
4591 'org-unfontify-region)
4592 ;; Activate before-change-function
4593 (org-set-local 'org-table-may-need-update t)
4594 (org-add-hook 'before-change-functions 'org-before-change-function nil
4595 'local)
4596 ;; Check for running clock before killing a buffer
4597 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4598 ;; Paragraphs and auto-filling
4599 (org-set-autofill-regexps)
4600 (setq indent-line-function 'org-indent-line-function)
4601 (org-update-radio-target-regexp)
4602
4603 ;; Comment characters
4604 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4605 (org-set-local 'comment-padding " ")
4606
4607 ;; Make isearch reveal context
4608 (if (or (featurep 'xemacs)
4609 (not (boundp 'outline-isearch-open-invisible-function)))
4610 ;; Emacs 21 and XEmacs make use of the hook
4611 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4612 ;; Emacs 22 deals with this through a special variable
4613 (org-set-local 'outline-isearch-open-invisible-function
4614 (lambda (&rest ignore) (org-show-context 'isearch))))
4615
4616 ;; If empty file that did not turn on org-mode automatically, make it to.
4617 (if (and org-insert-mode-line-in-empty-file
4618 (interactive-p)
4619 (= (point-min) (point-max)))
4620 (insert "# -*- mode: org -*-\n\n"))
4621
4622 (unless org-inhibit-startup
4623 (when org-startup-align-all-tables
4624 (let ((bmp (buffer-modified-p)))
4625 (org-table-map-tables 'org-table-align)
4626 (set-buffer-modified-p bmp)))
4627 (org-cycle-hide-drawers 'all)
4628 (cond
4629 ((eq org-startup-folded t)
4630 (org-cycle '(4)))
4631 ((eq org-startup-folded 'content)
4632 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4633 (org-cycle '(4)) (org-cycle '(4)))))))
4634
4635 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4636
4637 (defsubst org-call-with-arg (command arg)
4638 "Call COMMAND interactively, but pretend prefix are was ARG."
4639 (let ((current-prefix-arg arg)) (call-interactively command)))
4640
4641 (defsubst org-current-line (&optional pos)
4642 (save-excursion
4643 (and pos (goto-char pos))
4644 ;; works also in narrowed buffer, because we start at 1, not point-min
4645 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4646
4647 (defun org-current-time ()
4648 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4649 (if (> org-time-stamp-rounding-minutes 0)
4650 (let ((r org-time-stamp-rounding-minutes)
4651 (time (decode-time)))
4652 (apply 'encode-time
4653 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4654 (nthcdr 2 time))))
4655 (current-time)))
4656
4657 (defun org-add-props (string plist &rest props)
4658 "Add text properties to entire string, from beginning to end.
4659 PLIST may be a list of properties, PROPS are individual properties and values
4660 that will be added to PLIST. Returns the string that was modified."
4661 (add-text-properties
4662 0 (length string) (if props (append plist props) plist) string)
4663 string)
4664 (put 'org-add-props 'lisp-indent-function 2)
4665
4666
4667 ;;;; Font-Lock stuff, including the activators
4668
4669 (defvar org-mouse-map (make-sparse-keymap))
4670 (org-defkey org-mouse-map
4671 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4672 (org-defkey org-mouse-map
4673 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4674 (when org-mouse-1-follows-link
4675 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4676 (when org-tab-follows-link
4677 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4678 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4679 (when org-return-follows-link
4680 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4681 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4682
4683 (require 'font-lock)
4684
4685 (defconst org-non-link-chars "]\t\n\r<>")
4686 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4687 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4688 (defvar org-link-re-with-space nil
4689 "Matches a link with spaces, optional angular brackets around it.")
4690 (defvar org-link-re-with-space2 nil
4691 "Matches a link with spaces, optional angular brackets around it.")
4692 (defvar org-angle-link-re nil
4693 "Matches link with angular brackets, spaces are allowed.")
4694 (defvar org-plain-link-re nil
4695 "Matches plain link, without spaces.")
4696 (defvar org-bracket-link-regexp nil
4697 "Matches a link in double brackets.")
4698 (defvar org-bracket-link-analytic-regexp nil
4699 "Regular expression used to analyze links.
4700 Here is what the match groups contain after a match:
4701 1: http:
4702 2: http
4703 3: path
4704 4: [desc]
4705 5: desc")
4706 (defvar org-any-link-re nil
4707 "Regular expression matching any link.")
4708
4709 (defun org-make-link-regexps ()
4710 "Update the link regular expressions.
4711 This should be called after the variable `org-link-types' has changed."
4712 (setq org-link-re-with-space
4713 (concat
4714 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4715 "\\([^" org-non-link-chars " ]"
4716 "[^" org-non-link-chars "]*"
4717 "[^" org-non-link-chars " ]\\)>?")
4718 org-link-re-with-space2
4719 (concat
4720 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4721 "\\([^" org-non-link-chars " ]"
4722 "[^]\t\n\r]*"
4723 "[^" org-non-link-chars " ]\\)>?")
4724 org-angle-link-re
4725 (concat
4726 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4727 "\\([^" org-non-link-chars " ]"
4728 "[^" org-non-link-chars "]*"
4729 "\\)>")
4730 org-plain-link-re
4731 (concat
4732 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4733 "\\([^]\t\n\r<>,;() ]+\\)")
4734 org-bracket-link-regexp
4735 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4736 org-bracket-link-analytic-regexp
4737 (concat
4738 "\\[\\["
4739 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4740 "\\([^]]+\\)"
4741 "\\]"
4742 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4743 "\\]")
4744 org-any-link-re
4745 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4746 org-angle-link-re "\\)\\|\\("
4747 org-plain-link-re "\\)")))
4748
4749 (org-make-link-regexps)
4750
4751 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4752 "Regular expression for fast time stamp matching.")
4753 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4754 "Regular expression for fast time stamp matching.")
4755 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4756 "Regular expression matching time strings for analysis.
4757 This one does not require the space after the date.")
4758 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4759 "Regular expression matching time strings for analysis.")
4760 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4761 "Regular expression matching time stamps, with groups.")
4762 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4763 "Regular expression matching time stamps (also [..]), with groups.")
4764 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4765 "Regular expression matching a time stamp range.")
4766 (defconst org-tr-regexp-both
4767 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4768 "Regular expression matching a time stamp range.")
4769 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4770 org-ts-regexp "\\)?")
4771 "Regular expression matching a time stamp or time stamp range.")
4772 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4773 org-ts-regexp-both "\\)?")
4774 "Regular expression matching a time stamp or time stamp range.
4775 The time stamps may be either active or inactive.")
4776
4777 (defvar org-emph-face nil)
4778
4779 (defun org-do-emphasis-faces (limit)
4780 "Run through the buffer and add overlays to links."
4781 (let (rtn)
4782 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4783 (if (not (= (char-after (match-beginning 3))
4784 (char-after (match-beginning 4))))
4785 (progn
4786 (setq rtn t)
4787 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4788 'face
4789 (nth 1 (assoc (match-string 3)
4790 org-emphasis-alist)))
4791 (add-text-properties (match-beginning 2) (match-end 2)
4792 '(font-lock-multiline t))
4793 (backward-char 1))))
4794 rtn))
4795
4796 (defun org-emphasize (&optional char)
4797 "Insert or change an emphasis, i.e. a font like bold or italic.
4798 If there is an active region, change that region to a new emphasis.
4799 If there is no region, just insert the marker characters and position
4800 the cursor between them.
4801 CHAR should be either the marker character, or the first character of the
4802 HTML tag associated with that emphasis. If CHAR is a space, the means
4803 to remove the emphasis of the selected region.
4804 If char is not given (for example in an interactive call) it
4805 will be prompted for."
4806 (interactive)
4807 (let ((eal org-emphasis-alist) e det
4808 (erc org-emphasis-regexp-components)
4809 (prompt "")
4810 (string "") beg end move tag c s)
4811 (if (org-region-active-p)
4812 (setq beg (region-beginning) end (region-end)
4813 string (buffer-substring beg end))
4814 (setq move t))
4815
4816 (while (setq e (pop eal))
4817 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4818 c (aref tag 0))
4819 (push (cons c (string-to-char (car e))) det)
4820 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4821 (substring tag 1)))))
4822 (unless char
4823 (message "%s" (concat "Emphasis marker or tag:" prompt))
4824 (setq char (read-char-exclusive)))
4825 (setq char (or (cdr (assoc char det)) char))
4826 (if (equal char ?\ )
4827 (setq s "" move nil)
4828 (unless (assoc (char-to-string char) org-emphasis-alist)
4829 (error "No such emphasis marker: \"%c\"" char))
4830 (setq s (char-to-string char)))
4831 (while (and (> (length string) 1)
4832 (equal (substring string 0 1) (substring string -1))
4833 (assoc (substring string 0 1) org-emphasis-alist))
4834 (setq string (substring string 1 -1)))
4835 (setq string (concat s string s))
4836 (if beg (delete-region beg end))
4837 (unless (or (bolp)
4838 (string-match (concat "[" (nth 0 erc) "\n]")
4839 (char-to-string (char-before (point)))))
4840 (insert " "))
4841 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4842 (char-to-string (char-after (point))))
4843 (insert " ") (backward-char 1))
4844 (insert string)
4845 (and move (backward-char 1))))
4846
4847 (defconst org-nonsticky-props
4848 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4849
4850
4851 (defun org-activate-plain-links (limit)
4852 "Run through the buffer and add overlays to links."
4853 (catch 'exit
4854 (let (f)
4855 (while (re-search-forward org-plain-link-re limit t)
4856 (setq f (get-text-property (match-beginning 0) 'face))
4857 (if (or (eq f 'org-tag)
4858 (and (listp f) (memq 'org-tag f)))
4859 nil
4860 (add-text-properties (match-beginning 0) (match-end 0)
4861 (list 'mouse-face 'highlight
4862 'rear-nonsticky org-nonsticky-props
4863 'keymap org-mouse-map
4864 ))
4865 (throw 'exit t))))))
4866
4867 (defun org-activate-code (limit)
4868 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
4869 (unless (get-text-property (match-beginning 1) 'face)
4870 (remove-text-properties (match-beginning 0) (match-end 0)
4871 '(display t invisible t intangible t))
4872 t)))
4873
4874 (defun org-activate-angle-links (limit)
4875 "Run through the buffer and add overlays to links."
4876 (if (re-search-forward org-angle-link-re limit t)
4877 (progn
4878 (add-text-properties (match-beginning 0) (match-end 0)
4879 (list 'mouse-face 'highlight
4880 'rear-nonsticky org-nonsticky-props
4881 'keymap org-mouse-map
4882 ))
4883 t)))
4884
4885 (defmacro org-maybe-intangible (props)
4886 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
4887 In emacs 21, invisible text is not avoided by the command loop, so the
4888 intangible property is needed to make sure point skips this text.
4889 In Emacs 22, this is not necessary. The intangible text property has
4890 led to problems with flyspell. These problems are fixed in flyspell.el,
4891 but we still avoid setting the property in Emacs 22 and later.
4892 We use a macro so that the test can happen at compilation time."
4893 (if (< emacs-major-version 22)
4894 `(append '(intangible t) ,props)
4895 props))
4896
4897 (defun org-activate-bracket-links (limit)
4898 "Run through the buffer and add overlays to bracketed links."
4899 (if (re-search-forward org-bracket-link-regexp limit t)
4900 (let* ((help (concat "LINK: "
4901 (org-match-string-no-properties 1)))
4902 ;; FIXME: above we should remove the escapes.
4903 ;; but that requires another match, protecting match data,
4904 ;; a lot of overhead for font-lock.
4905 (ip (org-maybe-intangible
4906 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4907 'keymap org-mouse-map 'mouse-face 'highlight
4908 'help-echo help)))
4909 (vp (list 'rear-nonsticky org-nonsticky-props
4910 'keymap org-mouse-map 'mouse-face 'highlight
4911 'help-echo help)))
4912 ;; We need to remove the invisible property here. Table narrowing
4913 ;; may have made some of this invisible.
4914 (remove-text-properties (match-beginning 0) (match-end 0)
4915 '(invisible nil))
4916 (if (match-end 3)
4917 (progn
4918 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4919 (add-text-properties (match-beginning 3) (match-end 3) vp)
4920 (add-text-properties (match-end 3) (match-end 0) ip))
4921 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4922 (add-text-properties (match-beginning 1) (match-end 1) vp)
4923 (add-text-properties (match-end 1) (match-end 0) ip))
4924 t)))
4925
4926 (defun org-activate-dates (limit)
4927 "Run through the buffer and add overlays to dates."
4928 (if (re-search-forward org-tsr-regexp-both limit t)
4929 (progn
4930 (add-text-properties (match-beginning 0) (match-end 0)
4931 (list 'mouse-face 'highlight
4932 'rear-nonsticky org-nonsticky-props
4933 'keymap org-mouse-map))
4934 (when org-display-custom-times
4935 (if (match-end 3)
4936 (org-display-custom-time (match-beginning 3) (match-end 3)))
4937 (org-display-custom-time (match-beginning 1) (match-end 1)))
4938 t)))
4939
4940 (defvar org-target-link-regexp nil
4941 "Regular expression matching radio targets in plain text.")
4942 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4943 "Regular expression matching a link target.")
4944 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4945 "Regular expression matching a radio target.")
4946 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4947 "Regular expression matching any target.")
4948
4949 (defun org-activate-target-links (limit)
4950 "Run through the buffer and add overlays to target matches."
4951 (when org-target-link-regexp
4952 (let ((case-fold-search t))
4953 (if (re-search-forward org-target-link-regexp limit t)
4954 (progn
4955 (add-text-properties (match-beginning 0) (match-end 0)
4956 (list 'mouse-face 'highlight
4957 'rear-nonsticky org-nonsticky-props
4958 'keymap org-mouse-map
4959 'help-echo "Radio target link"
4960 'org-linked-text t))
4961 t)))))
4962
4963 (defun org-update-radio-target-regexp ()
4964 "Find all radio targets in this file and update the regular expression."
4965 (interactive)
4966 (when (memq 'radio org-activate-links)
4967 (setq org-target-link-regexp
4968 (org-make-target-link-regexp (org-all-targets 'radio)))
4969 (org-restart-font-lock)))
4970
4971 (defun org-hide-wide-columns (limit)
4972 (let (s e)
4973 (setq s (text-property-any (point) (or limit (point-max))
4974 'org-cwidth t))
4975 (when s
4976 (setq e (next-single-property-change s 'org-cwidth))
4977 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4978 (goto-char e)
4979 t)))
4980
4981 (defun org-restart-font-lock ()
4982 "Restart font-lock-mode, to force refontification."
4983 (when (and (boundp 'font-lock-mode) font-lock-mode)
4984 (font-lock-mode -1)
4985 (font-lock-mode 1)))
4986
4987 (defun org-all-targets (&optional radio)
4988 "Return a list of all targets in this file.
4989 With optional argument RADIO, only find radio targets."
4990 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4991 rtn)
4992 (save-excursion
4993 (goto-char (point-min))
4994 (while (re-search-forward re nil t)
4995 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4996 rtn)))
4997
4998 (defun org-make-target-link-regexp (targets)
4999 "Make regular expression matching all strings in TARGETS.
5000 The regular expression finds the targets also if there is a line break
5001 between words."
5002 (and targets
5003 (concat
5004 "\\<\\("
5005 (mapconcat
5006 (lambda (x)
5007 (while (string-match " +" x)
5008 (setq x (replace-match "\\s-+" t t x)))
5009 x)
5010 targets
5011 "\\|")
5012 "\\)\\>")))
5013
5014 (defun org-activate-tags (limit)
5015 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5016 (progn
5017 (add-text-properties (match-beginning 1) (match-end 1)
5018 (list 'mouse-face 'highlight
5019 'rear-nonsticky org-nonsticky-props
5020 'keymap org-mouse-map))
5021 t)))
5022
5023 (defun org-outline-level ()
5024 (save-excursion
5025 (looking-at outline-regexp)
5026 (if (match-beginning 1)
5027 (+ (org-get-string-indentation (match-string 1)) 1000)
5028 (1- (- (match-end 0) (match-beginning 0))))))
5029
5030 (defvar org-font-lock-keywords nil)
5031
5032 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5033 "Regular expression matching a property line.")
5034
5035 (defun org-set-font-lock-defaults ()
5036 (let* ((em org-fontify-emphasized-text)
5037 (lk org-activate-links)
5038 (org-font-lock-extra-keywords
5039 (list
5040 ;; Headlines
5041 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5042 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5043 ;; Table lines
5044 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5045 (1 'org-table t))
5046 ;; Table internals
5047 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5048 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5049 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5050 ;; Drawers
5051 (list org-drawer-regexp '(0 'org-special-keyword t))
5052 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5053 ;; Properties
5054 (list org-property-re
5055 '(1 'org-special-keyword t)
5056 '(3 'org-property-value t))
5057 (if org-format-transports-properties-p
5058 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5059 ;; Links
5060 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5061 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5062 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5063 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5064 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5065 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5066 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5067 '(org-hide-wide-columns (0 nil append))
5068 ;; TODO lines
5069 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5070 '(1 (org-get-todo-face 1) t))
5071 ;; DONE
5072 (if org-fontify-done-headline
5073 (list (concat "^[*]+ +\\<\\("
5074 (mapconcat 'regexp-quote org-done-keywords "\\|")
5075 "\\)\\(.*\\)")
5076 '(2 'org-headline-done t))
5077 nil)
5078 ;; Priorities
5079 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5080 ;; Special keywords
5081 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5082 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5083 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5084 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5085 ;; Emphasis
5086 (if em
5087 (if (featurep 'xemacs)
5088 '(org-do-emphasis-faces (0 nil append))
5089 '(org-do-emphasis-faces)))
5090 ;; Checkboxes
5091 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5092 2 'bold prepend)
5093 (if org-provide-checkbox-statistics
5094 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5095 (0 (org-get-checkbox-statistics-face) t)))
5096 ;; COMMENT
5097 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5098 "\\|" org-quote-string "\\)\\>")
5099 '(1 'org-special-keyword t))
5100 '("^#.*" (0 'font-lock-comment-face t))
5101 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
5102 ;; Code
5103 '(org-activate-code (1 'org-code t))
5104 )))
5105 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5106 ;; Now set the full font-lock-keywords
5107 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5108 (org-set-local 'font-lock-defaults
5109 '(org-font-lock-keywords t nil nil backward-paragraph))
5110 (kill-local-variable 'font-lock-keywords) nil))
5111
5112 (defvar org-m nil)
5113 (defvar org-l nil)
5114 (defvar org-f nil)
5115 (defun org-get-level-face (n)
5116 "Get the right face for match N in font-lock matching of healdines."
5117 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5118 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5119 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5120 (cond
5121 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5122 ((eq n 2) org-f)
5123 (t (if org-level-color-stars-only nil org-f))))
5124
5125 (defun org-get-todo-face (kwd)
5126 "Get the right face for a TODO keyword KWD.
5127 If KWD is a number, get the corresponding match group."
5128 (if (numberp kwd) (setq kwd (match-string kwd)))
5129 (or (cdr (assoc kwd org-todo-keyword-faces))
5130 (and (member kwd org-done-keywords) 'org-done)
5131 'org-todo))
5132
5133 (defun org-unfontify-region (beg end &optional maybe_loudly)
5134 "Remove fontification and activation overlays from links."
5135 (font-lock-default-unfontify-region beg end)
5136 (let* ((buffer-undo-list t)
5137 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5138 (inhibit-modification-hooks t)
5139 deactivate-mark buffer-file-name buffer-file-truename)
5140 (remove-text-properties beg end
5141 '(mouse-face t keymap t org-linked-text t
5142 invisible t intangible t))))
5143
5144 ;;;; Visibility cycling, including org-goto and indirect buffer
5145
5146 ;;; Cycling
5147
5148 (defvar org-cycle-global-status nil)
5149 (make-variable-buffer-local 'org-cycle-global-status)
5150 (defvar org-cycle-subtree-status nil)
5151 (make-variable-buffer-local 'org-cycle-subtree-status)
5152
5153 ;;;###autoload
5154 (defun org-cycle (&optional arg)
5155 "Visibility cycling for Org-mode.
5156
5157 - When this function is called with a prefix argument, rotate the entire
5158 buffer through 3 states (global cycling)
5159 1. OVERVIEW: Show only top-level headlines.
5160 2. CONTENTS: Show all headlines of all levels, but no body text.
5161 3. SHOW ALL: Show everything.
5162
5163 - When point is at the beginning of a headline, rotate the subtree started
5164 by this line through 3 different states (local cycling)
5165 1. FOLDED: Only the main headline is shown.
5166 2. CHILDREN: The main headline and the direct children are shown.
5167 From this state, you can move to one of the children
5168 and zoom in further.
5169 3. SUBTREE: Show the entire subtree, including body text.
5170
5171 - When there is a numeric prefix, go up to a heading with level ARG, do
5172 a `show-subtree' and return to the previous cursor position. If ARG
5173 is negative, go up that many levels.
5174
5175 - When point is not at the beginning of a headline, execute
5176 `indent-relative', like TAB normally does. See the option
5177 `org-cycle-emulate-tab' for details.
5178
5179 - Special case: if point is at the beginning of the buffer and there is
5180 no headline in line 1, this function will act as if called with prefix arg.
5181 But only if also the variable `org-cycle-global-at-bob' is t."
5182 (interactive "P")
5183 (let* ((outline-regexp
5184 (if (and (org-mode-p) org-cycle-include-plain-lists)
5185 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5186 outline-regexp))
5187 (bob-special (and org-cycle-global-at-bob (bobp)
5188 (not (looking-at outline-regexp))))
5189 (org-cycle-hook
5190 (if bob-special
5191 (delq 'org-optimize-window-after-visibility-change
5192 (copy-sequence org-cycle-hook))
5193 org-cycle-hook))
5194 (pos (point)))
5195
5196 (if (or bob-special (equal arg '(4)))
5197 ;; special case: use global cycling
5198 (setq arg t))
5199
5200 (cond
5201
5202 ((org-at-table-p 'any)
5203 ;; Enter the table or move to the next field in the table
5204 (or (org-table-recognize-table.el)
5205 (progn
5206 (if arg (org-table-edit-field t)
5207 (org-table-justify-field-maybe)
5208 (call-interactively 'org-table-next-field)))))
5209
5210 ((eq arg t) ;; Global cycling
5211
5212 (cond
5213 ((and (eq last-command this-command)
5214 (eq org-cycle-global-status 'overview))
5215 ;; We just created the overview - now do table of contents
5216 ;; This can be slow in very large buffers, so indicate action
5217 (message "CONTENTS...")
5218 (org-content)
5219 (message "CONTENTS...done")
5220 (setq org-cycle-global-status 'contents)
5221 (run-hook-with-args 'org-cycle-hook 'contents))
5222
5223 ((and (eq last-command this-command)
5224 (eq org-cycle-global-status 'contents))
5225 ;; We just showed the table of contents - now show everything
5226 (show-all)
5227 (message "SHOW ALL")
5228 (setq org-cycle-global-status 'all)
5229 (run-hook-with-args 'org-cycle-hook 'all))
5230
5231 (t
5232 ;; Default action: go to overview
5233 (org-overview)
5234 (message "OVERVIEW")
5235 (setq org-cycle-global-status 'overview)
5236 (run-hook-with-args 'org-cycle-hook 'overview))))
5237
5238 ((and org-drawers org-drawer-regexp
5239 (save-excursion
5240 (beginning-of-line 1)
5241 (looking-at org-drawer-regexp)))
5242 ;; Toggle block visibility
5243 (org-flag-drawer
5244 (not (get-char-property (match-end 0) 'invisible))))
5245
5246 ((integerp arg)
5247 ;; Show-subtree, ARG levels up from here.
5248 (save-excursion
5249 (org-back-to-heading)
5250 (outline-up-heading (if (< arg 0) (- arg)
5251 (- (funcall outline-level) arg)))
5252 (org-show-subtree)))
5253
5254 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5255 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5256 ;; At a heading: rotate between three different views
5257 (org-back-to-heading)
5258 (let ((goal-column 0) eoh eol eos)
5259 ;; First, some boundaries
5260 (save-excursion
5261 (org-back-to-heading)
5262 (save-excursion
5263 (beginning-of-line 2)
5264 (while (and (not (eobp)) ;; this is like `next-line'
5265 (get-char-property (1- (point)) 'invisible))
5266 (beginning-of-line 2)) (setq eol (point)))
5267 (outline-end-of-heading) (setq eoh (point))
5268 (org-end-of-subtree t)
5269 (unless (eobp)
5270 (skip-chars-forward " \t\n")
5271 (beginning-of-line 1) ; in case this is an item
5272 )
5273 (setq eos (1- (point))))
5274 ;; Find out what to do next and set `this-command'
5275 (cond
5276 ((= eos eoh)
5277 ;; Nothing is hidden behind this heading
5278 (message "EMPTY ENTRY")
5279 (setq org-cycle-subtree-status nil)
5280 (save-excursion
5281 (goto-char eos)
5282 (outline-next-heading)
5283 (if (org-invisible-p) (org-flag-heading nil))))
5284 ((or (>= eol eos)
5285 (not (string-match "\\S-" (buffer-substring eol eos))))
5286 ;; Entire subtree is hidden in one line: open it
5287 (org-show-entry)
5288 (show-children)
5289 (message "CHILDREN")
5290 (save-excursion
5291 (goto-char eos)
5292 (outline-next-heading)
5293 (if (org-invisible-p) (org-flag-heading nil)))
5294 (setq org-cycle-subtree-status 'children)
5295 (run-hook-with-args 'org-cycle-hook 'children))
5296 ((and (eq last-command this-command)
5297 (eq org-cycle-subtree-status 'children))
5298 ;; We just showed the children, now show everything.
5299 (org-show-subtree)
5300 (message "SUBTREE")
5301 (setq org-cycle-subtree-status 'subtree)
5302 (run-hook-with-args 'org-cycle-hook 'subtree))
5303 (t
5304 ;; Default action: hide the subtree.
5305 (hide-subtree)
5306 (message "FOLDED")
5307 (setq org-cycle-subtree-status 'folded)
5308 (run-hook-with-args 'org-cycle-hook 'folded)))))
5309
5310 ;; TAB emulation
5311 (buffer-read-only (org-back-to-heading))
5312
5313 ((org-try-cdlatex-tab))
5314
5315 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5316 (or (not (bolp))
5317 (not (looking-at outline-regexp))))
5318 (call-interactively (global-key-binding "\t")))
5319
5320 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5321 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5322 (or (and (eq org-cycle-emulate-tab 'white)
5323 (= (match-end 0) (point-at-eol)))
5324 (and (eq org-cycle-emulate-tab 'whitestart)
5325 (>= (match-end 0) pos))))
5326 t
5327 (eq org-cycle-emulate-tab t))
5328 (if (and (looking-at "[ \n\r\t]")
5329 (string-match "^[ \t]*$" (buffer-substring
5330 (point-at-bol) (point))))
5331 (progn
5332 (beginning-of-line 1)
5333 (and (looking-at "[ \t]+") (replace-match ""))))
5334 (call-interactively (global-key-binding "\t")))
5335
5336 (t (save-excursion
5337 (org-back-to-heading)
5338 (org-cycle))))))
5339
5340 ;;;###autoload
5341 (defun org-global-cycle (&optional arg)
5342 "Cycle the global visibility. For details see `org-cycle'."
5343 (interactive "P")
5344 (let ((org-cycle-include-plain-lists
5345 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5346 (if (integerp arg)
5347 (progn
5348 (show-all)
5349 (hide-sublevels arg)
5350 (setq org-cycle-global-status 'contents))
5351 (org-cycle '(4)))))
5352
5353 (defun org-overview ()
5354 "Switch to overview mode, shoing only top-level headlines.
5355 Really, this shows all headlines with level equal or greater than the level
5356 of the first headline in the buffer. This is important, because if the
5357 first headline is not level one, then (hide-sublevels 1) gives confusing
5358 results."
5359 (interactive)
5360 (let ((level (save-excursion
5361 (goto-char (point-min))
5362 (if (re-search-forward (concat "^" outline-regexp) nil t)
5363 (progn
5364 (goto-char (match-beginning 0))
5365 (funcall outline-level))))))
5366 (and level (hide-sublevels level))))
5367
5368 (defun org-content (&optional arg)
5369 "Show all headlines in the buffer, like a table of contents.
5370 With numerical argument N, show content up to level N."
5371 (interactive "P")
5372 (save-excursion
5373 ;; Visit all headings and show their offspring
5374 (and (integerp arg) (org-overview))
5375 (goto-char (point-max))
5376 (catch 'exit
5377 (while (and (progn (condition-case nil
5378 (outline-previous-visible-heading 1)
5379 (error (goto-char (point-min))))
5380 t)
5381 (looking-at outline-regexp))
5382 (if (integerp arg)
5383 (show-children (1- arg))
5384 (show-branches))
5385 (if (bobp) (throw 'exit nil))))))
5386
5387
5388 (defun org-optimize-window-after-visibility-change (state)
5389 "Adjust the window after a change in outline visibility.
5390 This function is the default value of the hook `org-cycle-hook'."
5391 (when (get-buffer-window (current-buffer))
5392 (cond
5393 ; ((eq state 'overview) (org-first-headline-recenter 1))
5394 ; ((eq state 'overview) (org-beginning-of-line))
5395 ((eq state 'content) nil)
5396 ((eq state 'all) nil)
5397 ((eq state 'folded) nil)
5398 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5399 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5400
5401
5402 (defun org-cycle-show-empty-lines (state)
5403 "Show empty lines above all visible headlines.
5404 The region to be covered depends on STATE when called through
5405 `org-cycle-hook'. Lisp program can use t for STATE to get the
5406 entire buffer covered. Note that an empty line is only shown if there
5407 are at least `org-cycle-separator-lines' empty lines before the headeline."
5408 (when (> org-cycle-separator-lines 0)
5409 (save-excursion
5410 (let* ((n org-cycle-separator-lines)
5411 (re (cond
5412 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5413 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5414 (t (let ((ns (number-to-string (- n 2))))
5415 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5416 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5417 beg end)
5418 (cond
5419 ((memq state '(overview contents t))
5420 (setq beg (point-min) end (point-max)))
5421 ((memq state '(children folded))
5422 (setq beg (point) end (progn (org-end-of-subtree t t)
5423 (beginning-of-line 2)
5424 (point)))))
5425 (when beg
5426 (goto-char beg)
5427 (while (re-search-forward re end t)
5428 (if (not (get-char-property (match-end 1) 'invisible))
5429 (outline-flag-region
5430 (match-beginning 1) (match-end 1) nil)))))))
5431 ;; Never hide empty lines at the end of the file.
5432 (save-excursion
5433 (goto-char (point-max))
5434 (outline-previous-heading)
5435 (outline-end-of-heading)
5436 (if (and (looking-at "[ \t\n]+")
5437 (= (match-end 0) (point-max)))
5438 (outline-flag-region (point) (match-end 0) nil))))
5439
5440 (defun org-subtree-end-visible-p ()
5441 "Is the end of the current subtree visible?"
5442 (pos-visible-in-window-p
5443 (save-excursion (org-end-of-subtree t) (point))))
5444
5445 (defun org-first-headline-recenter (&optional N)
5446 "Move cursor to the first headline and recenter the headline.
5447 Optional argument N means, put the headline into the Nth line of the window."
5448 (goto-char (point-min))
5449 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5450 (beginning-of-line)
5451 (recenter (prefix-numeric-value N))))
5452
5453 ;;; Org-goto
5454
5455 (defvar org-goto-window-configuration nil)
5456 (defvar org-goto-marker nil)
5457 (defvar org-goto-map
5458 (let ((map (make-sparse-keymap)))
5459 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5460 (while (setq cmd (pop cmds))
5461 (substitute-key-definition cmd cmd map global-map)))
5462 (suppress-keymap map)
5463 (org-defkey map "\C-m" 'org-goto-ret)
5464 (org-defkey map [(left)] 'org-goto-left)
5465 (org-defkey map [(right)] 'org-goto-right)
5466 (org-defkey map [(?q)] 'org-goto-quit)
5467 (org-defkey map [(control ?g)] 'org-goto-quit)
5468 (org-defkey map "\C-i" 'org-cycle)
5469 (org-defkey map [(tab)] 'org-cycle)
5470 (org-defkey map [(down)] 'outline-next-visible-heading)
5471 (org-defkey map [(up)] 'outline-previous-visible-heading)
5472 (org-defkey map "n" 'outline-next-visible-heading)
5473 (org-defkey map "p" 'outline-previous-visible-heading)
5474 (org-defkey map "f" 'outline-forward-same-level)
5475 (org-defkey map "b" 'outline-backward-same-level)
5476 (org-defkey map "u" 'outline-up-heading)
5477 (org-defkey map "/" 'org-occur)
5478 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5479 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5480 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5481 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5482 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5483 map))
5484
5485 (defconst org-goto-help
5486 "Browse copy of buffer to find location or copy text.
5487 RET=jump to location [Q]uit and return to previous location
5488 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur"
5489 )
5490
5491 (defun org-goto ()
5492 "Look up a different location in the current file, keeping current visibility.
5493
5494 When you want look-up or go to a different location in a document, the
5495 fastest way is often to fold the entire buffer and then dive into the tree.
5496 This method has the disadvantage, that the previous location will be folded,
5497 which may not be what you want.
5498
5499 This command works around this by showing a copy of the current buffer
5500 in an indirect buffer, in overview mode. You can dive into the tree in
5501 that copy, use org-occur and incremental search to find a location.
5502 When pressing RET or `Q', the command returns to the original buffer in
5503 which the visibility is still unchanged. After RET is will also jump to
5504 the location selected in the indirect buffer and expose the
5505 the headline hierarchy above."
5506 (interactive)
5507 (let* ((org-goto-start-pos (point))
5508 (selected-point
5509 (car (org-get-location (current-buffer) org-goto-help))))
5510 (if selected-point
5511 (progn
5512 (org-mark-ring-push org-goto-start-pos)
5513 (goto-char selected-point)
5514 (if (or (org-invisible-p) (org-invisible-p2))
5515 (org-show-context 'org-goto)))
5516 (message "Quit"))))
5517
5518 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5519 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5520
5521 (defun org-get-location (buf help)
5522 "Let the user select a location in the Org-mode buffer BUF.
5523 This function uses a recursive edit. It returns the selected position
5524 or nil."
5525 (let (org-goto-selected-point org-goto-exit-command)
5526 (save-excursion
5527 (save-window-excursion
5528 (delete-other-windows)
5529 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5530 (switch-to-buffer
5531 (condition-case nil
5532 (make-indirect-buffer (current-buffer) "*org-goto*")
5533 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5534 (with-output-to-temp-buffer "*Help*"
5535 (princ help))
5536 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5537 (setq buffer-read-only nil)
5538 (let ((org-startup-truncated t)
5539 (org-startup-folded nil)
5540 (org-startup-align-all-tables nil))
5541 (org-mode)
5542 (org-overview))
5543 (setq buffer-read-only t)
5544 (if (and (boundp 'org-goto-start-pos)
5545 (integer-or-marker-p org-goto-start-pos))
5546 (let ((org-show-hierarchy-above t)
5547 (org-show-siblings t)
5548 (org-show-following-heading t))
5549 (goto-char org-goto-start-pos)
5550 (and (org-invisible-p) (org-show-context)))
5551 (goto-char (point-min)))
5552 (org-beginning-of-line)
5553 (message "Select location and press RET")
5554 ;; now we make sure that during selection, ony very few keys work
5555 ;; and that it is impossible to switch to another window.
5556 ; (let ((gm (current-global-map))
5557 ; (overriding-local-map org-goto-map))
5558 ; (unwind-protect
5559 ; (progn
5560 ; (use-global-map org-goto-map)
5561 ; (recursive-edit))
5562 ; (use-global-map gm)))
5563 (use-local-map org-goto-map)
5564 (recursive-edit)
5565 ))
5566 (kill-buffer "*org-goto*")
5567 (cons org-goto-selected-point org-goto-exit-command)))
5568
5569 (defun org-goto-ret (&optional arg)
5570 "Finish `org-goto' by going to the new location."
5571 (interactive "P")
5572 (setq org-goto-selected-point (point)
5573 org-goto-exit-command 'return)
5574 (throw 'exit nil))
5575
5576 (defun org-goto-left ()
5577 "Finish `org-goto' by going to the new location."
5578 (interactive)
5579 (if (org-on-heading-p)
5580 (progn
5581 (beginning-of-line 1)
5582 (setq org-goto-selected-point (point)
5583 org-goto-exit-command 'left)
5584 (throw 'exit nil))
5585 (error "Not on a heading")))
5586
5587 (defun org-goto-right ()
5588 "Finish `org-goto' by going to the new location."
5589 (interactive)
5590 (if (org-on-heading-p)
5591 (progn
5592 (setq org-goto-selected-point (point)
5593 org-goto-exit-command 'right)
5594 (throw 'exit nil))
5595 (error "Not on a heading")))
5596
5597 (defun org-goto-quit ()
5598 "Finish `org-goto' without cursor motion."
5599 (interactive)
5600 (setq org-goto-selected-point nil)
5601 (setq org-goto-exit-command 'quit)
5602 (throw 'exit nil))
5603
5604 ;;; Indirect buffer display of subtrees
5605
5606 (defvar org-indirect-dedicated-frame nil
5607 "This is the frame being used for indirect tree display.")
5608 (defvar org-last-indirect-buffer nil)
5609
5610 (defun org-tree-to-indirect-buffer (&optional arg)
5611 "Create indirect buffer and narrow it to current subtree.
5612 With numerical prefix ARG, go up to this level and then take that tree.
5613 If ARG is negative, go up that many levels.
5614 Normally this command removes the indirect buffer previously made
5615 with this command. However, when called with a C-u prefix, the last buffer
5616 is kept so that you can work with several indirect buffers at the same time.
5617 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5618 requests that a new frame be made for the new buffer, so that the dedicated
5619 frame is not changed."
5620 (interactive "P")
5621 (let ((cbuf (current-buffer))
5622 (cwin (selected-window))
5623 (pos (point))
5624 beg end level heading ibuf)
5625 (save-excursion
5626 (org-back-to-heading t)
5627 (when (numberp arg)
5628 (setq level (org-outline-level))
5629 (if (< arg 0) (setq arg (+ level arg)))
5630 (while (> (setq level (org-outline-level)) arg)
5631 (outline-up-heading 1 t)))
5632 (setq beg (point)
5633 heading (org-get-heading))
5634 (org-end-of-subtree t) (setq end (point)))
5635 (if (and (not arg)
5636 (buffer-live-p org-last-indirect-buffer))
5637 (kill-buffer org-last-indirect-buffer))
5638 (setq ibuf (org-get-indirect-buffer cbuf)
5639 org-last-indirect-buffer ibuf)
5640 (cond
5641 ((or (eq org-indirect-buffer-display 'new-frame)
5642 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5643 (select-frame (make-frame))
5644 (delete-other-windows)
5645 (switch-to-buffer ibuf)
5646 (org-set-frame-title heading))
5647 ((eq org-indirect-buffer-display 'dedicated-frame)
5648 (raise-frame
5649 (select-frame (or (and org-indirect-dedicated-frame
5650 (frame-live-p org-indirect-dedicated-frame)
5651 org-indirect-dedicated-frame)
5652 (setq org-indirect-dedicated-frame (make-frame)))))
5653 (delete-other-windows)
5654 (switch-to-buffer ibuf)
5655 (org-set-frame-title (concat "Indirect: " heading)))
5656 ((eq org-indirect-buffer-display 'current-window)
5657 (switch-to-buffer ibuf))
5658 ((eq org-indirect-buffer-display 'other-window)
5659 (pop-to-buffer ibuf))
5660 (t (error "Invalid value.")))
5661 (if (featurep 'xemacs)
5662 (save-excursion (org-mode) (turn-on-font-lock)))
5663 (narrow-to-region beg end)
5664 (show-all)
5665 (goto-char pos)
5666 (and (window-live-p cwin) (select-window cwin))))
5667
5668 (defun org-get-indirect-buffer (&optional buffer)
5669 (setq buffer (or buffer (current-buffer)))
5670 (let ((n 1) (base (buffer-name buffer)) bname)
5671 (while (buffer-live-p
5672 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5673 (setq n (1+ n)))
5674 (condition-case nil
5675 (make-indirect-buffer buffer bname 'clone)
5676 (error (make-indirect-buffer buffer bname)))))
5677
5678 (defun org-set-frame-title (title)
5679 "Set the title of the current frame to the string TITLE."
5680 ;; FIXME: how to name a single frame in XEmacs???
5681 (unless (featurep 'xemacs)
5682 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5683
5684 ;;;; Structure editing
5685
5686 ;;; Inserting headlines
5687
5688 (defun org-insert-heading (&optional force-heading)
5689 "Insert a new heading or item with same depth at point.
5690 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5691 If point is at the beginning of a headline, insert a sibling before the
5692 current headline. If point is in the middle of a headline, split the headline
5693 at that position and make the rest of the headline part of the sibling below
5694 the current headline."
5695 (interactive "P")
5696 (if (= (buffer-size) 0)
5697 (insert "\n* ")
5698 (when (or force-heading (not (org-insert-item)))
5699 (let* ((head (save-excursion
5700 (condition-case nil
5701 (progn
5702 (org-back-to-heading)
5703 (match-string 0))
5704 (error "*"))))
5705 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5706 pos)
5707 (cond
5708 ((and (org-on-heading-p) (bolp)
5709 (or (bobp)
5710 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5711 (open-line (if blank 2 1)))
5712 ((and (bolp)
5713 (or (bobp)
5714 (save-excursion
5715 (backward-char 1) (not (org-invisible-p)))))
5716 nil)
5717 (t (newline (if blank 2 1))))
5718 (insert head) (just-one-space)
5719 (setq pos (point))
5720 (end-of-line 1)
5721 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5722 (run-hooks 'org-insert-heading-hook)))))
5723
5724 (defun org-insert-heading-after-current ()
5725 "Insert a new heading with same level as current, after current subtree."
5726 (interactive)
5727 (org-back-to-heading)
5728 (org-insert-heading)
5729 (org-move-subtree-down)
5730 (end-of-line 1))
5731
5732 (defun org-insert-todo-heading (arg)
5733 "Insert a new heading with the same level and TODO state as current heading.
5734 If the heading has no TODO state, or if the state is DONE, use the first
5735 state (TODO by default). Also with prefix arg, force first state."
5736 (interactive "P")
5737 (when (not (org-insert-item 'checkbox))
5738 (org-insert-heading)
5739 (save-excursion
5740 (org-back-to-heading)
5741 (outline-previous-heading)
5742 (looking-at org-todo-line-regexp))
5743 (if (or arg
5744 (not (match-beginning 2))
5745 (member (match-string 2) org-done-keywords))
5746 (insert (car org-todo-keywords-1) " ")
5747 (insert (match-string 2) " "))))
5748
5749 (defun org-insert-subheading (arg)
5750 "Insert a new subheading and demote it.
5751 Works for outline headings and for plain lists alike."
5752 (interactive "P")
5753 (org-insert-heading arg)
5754 (cond
5755 ((org-on-heading-p) (org-do-demote))
5756 ((org-at-item-p) (org-indent-item 1))))
5757
5758 (defun org-insert-todo-subheading (arg)
5759 "Insert a new subheading with TODO keyword or checkbox and demote it.
5760 Works for outline headings and for plain lists alike."
5761 (interactive "P")
5762 (org-insert-todo-heading arg)
5763 (cond
5764 ((org-on-heading-p) (org-do-demote))
5765 ((org-at-item-p) (org-indent-item 1))))
5766
5767 ;;; Promotion and Demotion
5768
5769 (defun org-promote-subtree ()
5770 "Promote the entire subtree.
5771 See also `org-promote'."
5772 (interactive)
5773 (save-excursion
5774 (org-map-tree 'org-promote))
5775 (org-fix-position-after-promote))
5776
5777 (defun org-demote-subtree ()
5778 "Demote the entire subtree. See `org-demote'.
5779 See also `org-promote'."
5780 (interactive)
5781 (save-excursion
5782 (org-map-tree 'org-demote))
5783 (org-fix-position-after-promote))
5784
5785
5786 (defun org-do-promote ()
5787 "Promote the current heading higher up the tree.
5788 If the region is active in `transient-mark-mode', promote all headings
5789 in the region."
5790 (interactive)
5791 (save-excursion
5792 (if (org-region-active-p)
5793 (org-map-region 'org-promote (region-beginning) (region-end))
5794 (org-promote)))
5795 (org-fix-position-after-promote))
5796
5797 (defun org-do-demote ()
5798 "Demote the current heading lower down the tree.
5799 If the region is active in `transient-mark-mode', demote all headings
5800 in the region."
5801 (interactive)
5802 (save-excursion
5803 (if (org-region-active-p)
5804 (org-map-region 'org-demote (region-beginning) (region-end))
5805 (org-demote)))
5806 (org-fix-position-after-promote))
5807
5808 (defun org-fix-position-after-promote ()
5809 "Make sure that after pro/demotion cursor position is right."
5810 (let ((pos (point)))
5811 (when (save-excursion
5812 (beginning-of-line 1)
5813 (looking-at org-todo-line-regexp)
5814 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5815 (cond ((eobp) (insert " "))
5816 ((eolp) (insert " "))
5817 ((equal (char-after) ?\ ) (forward-char 1))))))
5818
5819 (defun org-reduced-level (l)
5820 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5821
5822 (defun org-get-legal-level (level &optional change)
5823 "Rectify a level change under the influence of `org-odd-levels-only'
5824 LEVEL is a current level, CHANGE is by how much the level should be
5825 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5826 even level numbers will become the next higher odd number."
5827 (if org-odd-levels-only
5828 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5829 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5830 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5831 (max 1 (+ level change))))
5832
5833 (defun org-promote ()
5834 "Promote the current heading higher up the tree.
5835 If the region is active in `transient-mark-mode', promote all headings
5836 in the region."
5837 (org-back-to-heading t)
5838 (let* ((level (save-match-data (funcall outline-level)))
5839 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
5840 (diff (abs (- level (length up-head) -1))))
5841 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5842 (replace-match up-head nil t)
5843 ;; Fixup tag positioning
5844 (and org-auto-align-tags (org-set-tags nil t))
5845 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5846
5847 (defun org-demote ()
5848 "Demote the current heading lower down the tree.
5849 If the region is active in `transient-mark-mode', demote all headings
5850 in the region."
5851 (org-back-to-heading t)
5852 (let* ((level (save-match-data (funcall outline-level)))
5853 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
5854 (diff (abs (- level (length down-head) -1))))
5855 (replace-match down-head nil t)
5856 ;; Fixup tag positioning
5857 (and org-auto-align-tags (org-set-tags nil t))
5858 (if org-adapt-indentation (org-fixup-indentation diff))))
5859
5860 (defun org-map-tree (fun)
5861 "Call FUN for every heading underneath the current one."
5862 (org-back-to-heading)
5863 (let ((level (funcall outline-level)))
5864 (save-excursion
5865 (funcall fun)
5866 (while (and (progn
5867 (outline-next-heading)
5868 (> (funcall outline-level) level))
5869 (not (eobp)))
5870 (funcall fun)))))
5871
5872 (defun org-map-region (fun beg end)
5873 "Call FUN for every heading between BEG and END."
5874 (let ((org-ignore-region t))
5875 (save-excursion
5876 (setq end (copy-marker end))
5877 (goto-char beg)
5878 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5879 (< (point) end))
5880 (funcall fun))
5881 (while (and (progn
5882 (outline-next-heading)
5883 (< (point) end))
5884 (not (eobp)))
5885 (funcall fun)))))
5886
5887 (defun org-fixup-indentation (diff)
5888 "Change the indentation in the current entry by DIFF
5889 However, if any line in the current entry has no indentation, or if it
5890 would end up with no indentation after the change, nothing at all is done."
5891 (save-excursion
5892 (let ((end (save-excursion (outline-next-heading)
5893 (point-marker)))
5894 (prohibit (if (> diff 0)
5895 "^\\S-"
5896 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5897 col)
5898 (unless (save-excursion (end-of-line 1)
5899 (re-search-forward prohibit end t))
5900 (while (re-search-forward "^[ \t]+" end t)
5901 (goto-char (match-end 0))
5902 (setq col (current-column))
5903 (if (< diff 0) (replace-match ""))
5904 (indent-to (+ diff col))))
5905 (move-marker end nil))))
5906
5907 (defun org-convert-to-odd-levels ()
5908 "Convert an org-mode file with all levels allowed to one with odd levels.
5909 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5910 level 5 etc."
5911 (interactive)
5912 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5913 (let ((org-odd-levels-only nil) n)
5914 (save-excursion
5915 (goto-char (point-min))
5916 (while (re-search-forward "^\\*\\*+ " nil t)
5917 (setq n (- (length (match-string 0)) 2))
5918 (while (>= (setq n (1- n)) 0)
5919 (org-demote))
5920 (end-of-line 1))))))
5921
5922
5923 (defun org-convert-to-oddeven-levels ()
5924 "Convert an org-mode file with only odd levels to one with odd and even levels.
5925 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5926 section with an even level, conversion would destroy the structure of the file. An error
5927 is signaled in this case."
5928 (interactive)
5929 (goto-char (point-min))
5930 ;; First check if there are no even levels
5931 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5932 (org-show-context t)
5933 (error "Not all levels are odd in this file. Conversion not possible."))
5934 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5935 (let ((org-odd-levels-only nil) n)
5936 (save-excursion
5937 (goto-char (point-min))
5938 (while (re-search-forward "^\\*\\*+ " nil t)
5939 (setq n (/ (1- (length (match-string 0))) 2))
5940 (while (>= (setq n (1- n)) 0)
5941 (org-promote))
5942 (end-of-line 1))))))
5943
5944 (defun org-tr-level (n)
5945 "Make N odd if required."
5946 (if org-odd-levels-only (1+ (/ n 2)) n))
5947
5948 ;;; Vertical tree motion, cutting and pasting of subtrees
5949
5950 (defun org-move-subtree-up (&optional arg)
5951 "Move the current subtree up past ARG headlines of the same level."
5952 (interactive "p")
5953 (org-move-subtree-down (- (prefix-numeric-value arg))))
5954
5955 (defun org-move-subtree-down (&optional arg)
5956 "Move the current subtree down past ARG headlines of the same level."
5957 (interactive "p")
5958 (setq arg (prefix-numeric-value arg))
5959 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5960 'outline-get-last-sibling))
5961 (ins-point (make-marker))
5962 (cnt (abs arg))
5963 beg end txt folded)
5964 ;; Select the tree
5965 (org-back-to-heading)
5966 (setq beg (point))
5967 (save-match-data
5968 (save-excursion (outline-end-of-heading)
5969 (setq folded (org-invisible-p)))
5970 (outline-end-of-subtree))
5971 (outline-next-heading)
5972 (setq end (point))
5973 ;; Find insertion point, with error handling
5974 (goto-char beg)
5975 (while (> cnt 0)
5976 (or (and (funcall movfunc) (looking-at outline-regexp))
5977 (progn (goto-char beg)
5978 (error "Cannot move past superior level or buffer limit")))
5979 (setq cnt (1- cnt)))
5980 (if (> arg 0)
5981 ;; Moving forward - still need to move over subtree
5982 (progn (outline-end-of-subtree)
5983 (outline-next-heading)
5984 (if (not (or (looking-at (concat "^" outline-regexp))
5985 (bolp)))
5986 (newline))))
5987 (move-marker ins-point (point))
5988 (setq txt (buffer-substring beg end))
5989 (delete-region beg end)
5990 (insert txt)
5991 (or (bolp) (insert "\n"))
5992 (goto-char ins-point)
5993 (if folded (hide-subtree))
5994 (move-marker ins-point nil)))
5995
5996 (defvar org-subtree-clip ""
5997 "Clipboard for cut and paste of subtrees.
5998 This is actually only a copy of the kill, because we use the normal kill
5999 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6000
6001 (defvar org-subtree-clip-folded nil
6002 "Was the last copied subtree folded?
6003 This is used to fold the tree back after pasting.")
6004
6005 (defun org-cut-subtree (&optional n)
6006 "Cut the current subtree into the clipboard.
6007 With prefix arg N, cut this many sequential subtrees.
6008 This is a short-hand for marking the subtree and then cutting it."
6009 (interactive "p")
6010 (org-copy-subtree n 'cut))
6011
6012 (defun org-copy-subtree (&optional n cut)
6013 "Cut the current subtree into the clipboard.
6014 With prefix arg N, cut this many sequential subtrees.
6015 This is a short-hand for marking the subtree and then copying it.
6016 If CUT is non-nil, actually cut the subtree."
6017 (interactive "p")
6018 (let (beg end folded)
6019 (if (interactive-p)
6020 (org-back-to-heading nil) ; take what looks like a subtree
6021 (org-back-to-heading t)) ; take what is really there
6022 (setq beg (point))
6023 (save-match-data
6024 (save-excursion (outline-end-of-heading)
6025 (setq folded (org-invisible-p)))
6026 (condition-case nil
6027 (outline-forward-same-level (1- n))
6028 (error nil))
6029 (org-end-of-subtree t t))
6030 (setq end (point))
6031 (goto-char beg)
6032 (when (> end beg)
6033 (setq org-subtree-clip-folded folded)
6034 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6035 (setq org-subtree-clip (current-kill 0))
6036 (message "%s: Subtree(s) with %d characters"
6037 (if cut "Cut" "Copied")
6038 (length org-subtree-clip)))))
6039
6040 (defun org-paste-subtree (&optional level tree)
6041 "Paste the clipboard as a subtree, with modification of headline level.
6042 The entire subtree is promoted or demoted in order to match a new headline
6043 level. By default, the new level is derived from the visible headings
6044 before and after the insertion point, and taken to be the inferior headline
6045 level of the two. So if the previous visible heading is level 3 and the
6046 next is level 4 (or vice versa), level 4 will be used for insertion.
6047 This makes sure that the subtree remains an independent subtree and does
6048 not swallow low level entries.
6049
6050 You can also force a different level, either by using a numeric prefix
6051 argument, or by inserting the heading marker by hand. For example, if the
6052 cursor is after \"*****\", then the tree will be shifted to level 5.
6053
6054 If you want to insert the tree as is, just use \\[yank].
6055
6056 If optional TREE is given, use this text instead of the kill ring."
6057 (interactive "P")
6058 (unless (org-kill-is-subtree-p tree)
6059 (error
6060 (substitute-command-keys
6061 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6062 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6063 (^re (concat "^\\(" outline-regexp "\\)"))
6064 (re (concat "\\(" outline-regexp "\\)"))
6065 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6066
6067 (old-level (if (string-match ^re txt)
6068 (- (match-end 0) (match-beginning 0) 1)
6069 -1))
6070 (force-level (cond (level (prefix-numeric-value level))
6071 ((string-match
6072 ^re_ (buffer-substring (point-at-bol) (point)))
6073 (- (match-end 1) (match-beginning 1)))
6074 (t nil)))
6075 (previous-level (save-excursion
6076 (condition-case nil
6077 (progn
6078 (outline-previous-visible-heading 1)
6079 (if (looking-at re)
6080 (- (match-end 0) (match-beginning 0) 1)
6081 1))
6082 (error 1))))
6083 (next-level (save-excursion
6084 (condition-case nil
6085 (progn
6086 (or (looking-at outline-regexp)
6087 (outline-next-visible-heading 1))
6088 (if (looking-at re)
6089 (- (match-end 0) (match-beginning 0) 1)
6090 1))
6091 (error 1))))
6092 (new-level (or force-level (max previous-level next-level)))
6093 (shift (if (or (= old-level -1)
6094 (= new-level -1)
6095 (= old-level new-level))
6096 0
6097 (- new-level old-level)))
6098 (delta (if (> shift 0) -1 1))
6099 (func (if (> shift 0) 'org-demote 'org-promote))
6100 (org-odd-levels-only nil)
6101 beg end)
6102 ;; Remove the forced level indicator
6103 (if force-level
6104 (delete-region (point-at-bol) (point)))
6105 ;; Paste
6106 (beginning-of-line 1)
6107 (setq beg (point))
6108 (insert txt)
6109 (unless (string-match "\n[ \t]*\\'" txt) (insert "\n"))
6110 (setq end (point))
6111 (goto-char beg)
6112 ;; Shift if necessary
6113 (unless (= shift 0)
6114 (save-restriction
6115 (narrow-to-region beg end)
6116 (while (not (= shift 0))
6117 (org-map-region func (point-min) (point-max))
6118 (setq shift (+ delta shift)))
6119 (goto-char (point-min))))
6120 (when (interactive-p)
6121 (message "Clipboard pasted as level %d subtree" new-level))
6122 (if (and kill-ring
6123 (eq org-subtree-clip (current-kill 0))
6124 org-subtree-clip-folded)
6125 ;; The tree was folded before it was killed/copied
6126 (hide-subtree))))
6127
6128 (defun org-kill-is-subtree-p (&optional txt)
6129 "Check if the current kill is an outline subtree, or a set of trees.
6130 Returns nil if kill does not start with a headline, or if the first
6131 headline level is not the largest headline level in the tree.
6132 So this will actually accept several entries of equal levels as well,
6133 which is OK for `org-paste-subtree'.
6134 If optional TXT is given, check this string instead of the current kill."
6135 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6136 (start-level (and kill
6137 (string-match (concat "\\`" org-outline-regexp) kill)
6138 (- (match-end 0) (match-beginning 0) 1)))
6139 (re (concat "^" org-outline-regexp))
6140 (start 1))
6141 (if (not start-level)
6142 (progn
6143 nil) ;; does not even start with a heading
6144 (catch 'exit
6145 (while (setq start (string-match re kill (1+ start)))
6146 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6147 (throw 'exit nil)))
6148 t))))
6149
6150 (defun org-narrow-to-subtree ()
6151 "Narrow buffer to the current subtree."
6152 (interactive)
6153 (save-excursion
6154 (narrow-to-region
6155 (progn (org-back-to-heading) (point))
6156 (progn (org-end-of-subtree t t) (point)))))
6157
6158
6159 ;;; Outline Sorting
6160
6161 (defun org-sort (with-case)
6162 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6163 Optional argument WITH-CASE means sort case-sensitively."
6164 (interactive "P")
6165 (if (org-at-table-p)
6166 (org-call-with-arg 'org-table-sort-lines with-case)
6167 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6168
6169 (defvar org-priority-regexp) ; defined later in the file
6170
6171 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6172 "Sort entries on a certain level of an outline tree.
6173 If there is an active region, the entries in the region are sorted.
6174 Else, if the cursor is before the first entry, sort the top-level items.
6175 Else, the children of the entry at point are sorted.
6176
6177 Sorting can be alphabetically, numerically, and by date/time as given by
6178 the first time stamp in the entry. The command prompts for the sorting
6179 type unless it has been given to the function through the SORTING-TYPE
6180 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6181 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6182 called with point at the beginning of the record. It must return either
6183 a string or a number that should serve as the sorting key for that record.
6184
6185 Comparing entries ignores case by default. However, with an optional argument
6186 WITH-CASE, the sorting considers case as well."
6187 (interactive "P")
6188 (let ((case-func (if with-case 'identity 'downcase))
6189 start beg end stars re re2
6190 txt what tmp plain-list-p)
6191 ;; Find beginning and end of region to sort
6192 (cond
6193 ((org-region-active-p)
6194 ;; we will sort the region
6195 (setq end (region-end)
6196 what "region")
6197 (goto-char (region-beginning))
6198 (if (not (org-on-heading-p)) (outline-next-heading))
6199 (setq start (point)))
6200 ((org-at-item-p)
6201 ;; we will sort this plain list
6202 (org-beginning-of-item-list) (setq start (point))
6203 (org-end-of-item-list) (setq end (point))
6204 (goto-char start)
6205 (setq plain-list-p t
6206 what "plain list"))
6207 ((or (org-on-heading-p)
6208 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6209 ;; we will sort the children of the current headline
6210 (org-back-to-heading)
6211 (setq start (point) end (org-end-of-subtree) what "children")
6212 (goto-char start)
6213 (show-subtree)
6214 (outline-next-heading))
6215 (t
6216 ;; we will sort the top-level entries in this file
6217 (goto-char (point-min))
6218 (or (org-on-heading-p) (outline-next-heading))
6219 (setq start (point) end (point-max) what "top-level")
6220 (goto-char start)
6221 (show-all)))
6222
6223 (setq beg (point))
6224 (if (>= beg end) (error "Nothing to sort"))
6225
6226 (unless plain-list-p
6227 (looking-at "\\(\\*+\\)")
6228 (setq stars (match-string 1)
6229 re (concat "^" (regexp-quote stars) " +")
6230 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6231 txt (buffer-substring beg end))
6232 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6233 (if (and (not (equal stars "*")) (string-match re2 txt))
6234 (error "Region to sort contains a level above the first entry")))
6235
6236 (unless sorting-type
6237 (message
6238 (if plain-list-p
6239 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6240 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6241 what)
6242 (setq sorting-type (read-char-exclusive))
6243
6244 (and (= (downcase sorting-type) ?f)
6245 (setq getkey-func
6246 (completing-read "Sort using function: "
6247 obarray 'fboundp t nil nil))
6248 (setq getkey-func (intern getkey-func)))
6249
6250 (and (= (downcase sorting-type) ?r)
6251 (setq property
6252 (completing-read "Property: "
6253 (mapcar 'list (org-buffer-property-keys t))
6254 nil t))))
6255
6256 (message "Sorting entries...")
6257
6258 (save-restriction
6259 (narrow-to-region start end)
6260
6261 (let ((dcst (downcase sorting-type))
6262 (now (current-time)))
6263 (sort-subr
6264 (/= dcst sorting-type)
6265 ;; This function moves to the beginning character of the "record" to
6266 ;; be sorted.
6267 (if plain-list-p
6268 (lambda nil
6269 (if (org-at-item-p) t (goto-char (point-max))))
6270 (lambda nil
6271 (if (re-search-forward re nil t)
6272 (goto-char (match-beginning 0))
6273 (goto-char (point-max)))))
6274 ;; This function moves to the last character of the "record" being
6275 ;; sorted.
6276 (if plain-list-p
6277 'org-end-of-item
6278 (lambda nil
6279 (save-match-data
6280 (condition-case nil
6281 (outline-forward-same-level 1)
6282 (error
6283 (goto-char (point-max)))))))
6284
6285 ;; This function returns the value that gets sorted against.
6286 (if plain-list-p
6287 (lambda nil
6288 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6289 (cond
6290 ((= dcst ?n)
6291 (string-to-number (buffer-substring (match-end 0)
6292 (line-end-position))))
6293 ((= dcst ?a)
6294 (buffer-substring (match-end 0) (line-end-position)))
6295 ((= dcst ?t)
6296 (if (re-search-forward org-ts-regexp
6297 (line-end-position) t)
6298 (org-time-string-to-time (match-string 0))
6299 now))
6300 ((= dcst ?f)
6301 (if getkey-func
6302 (progn
6303 (setq tmp (funcall getkey-func))
6304 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6305 tmp)
6306 (error "Invalid key function `%s'" getkey-func)))
6307 (t (error "Invalid sorting type `%c'" sorting-type)))))
6308 (lambda nil
6309 (cond
6310 ((= dcst ?n)
6311 (if (looking-at outline-regexp)
6312 (string-to-number (buffer-substring (match-end 0)
6313 (line-end-position)))
6314 nil))
6315 ((= dcst ?a)
6316 (funcall case-func (buffer-substring (line-beginning-position)
6317 (line-end-position))))
6318 ((= dcst ?t)
6319 (if (re-search-forward org-ts-regexp
6320 (save-excursion
6321 (forward-line 2)
6322 (point)) t)
6323 (org-time-string-to-time (match-string 0))
6324 now))
6325 ((= dcst ?p)
6326 (if (re-search-forward org-priority-regexp (line-end-position) t)
6327 (string-to-char (match-string 2))
6328 org-default-priority))
6329 ((= dcst ?r)
6330 (or (org-entry-get nil property) ""))
6331 ((= dcst ?f)
6332 (if getkey-func
6333 (progn
6334 (setq tmp (funcall getkey-func))
6335 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6336 tmp)
6337 (error "Invalid key function `%s'" getkey-func)))
6338 (t (error "Invalid sorting type `%c'" sorting-type)))))
6339 nil
6340 (cond
6341 ((= dcst ?a) 'string<)
6342 ((= dcst ?t) 'time-less-p)
6343 (t nil)))))
6344 (message "Sorting entries...done")))
6345
6346 (defun org-do-sort (table what &optional with-case sorting-type)
6347 "Sort TABLE of WHAT according to SORTING-TYPE.
6348 The user will be prompted for the SORTING-TYPE if the call to this
6349 function does not specify it. WHAT is only for the prompt, to indicate
6350 what is being sorted. The sorting key will be extracted from
6351 the car of the elements of the table.
6352 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6353 (unless sorting-type
6354 (message
6355 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6356 what)
6357 (setq sorting-type (read-char-exclusive)))
6358 (let ((dcst (downcase sorting-type))
6359 extractfun comparefun)
6360 ;; Define the appropriate functions
6361 (cond
6362 ((= dcst ?n)
6363 (setq extractfun 'string-to-number
6364 comparefun (if (= dcst sorting-type) '< '>)))
6365 ((= dcst ?a)
6366 (setq extractfun (if with-case 'identity 'downcase)
6367 comparefun (if (= dcst sorting-type)
6368 'string<
6369 (lambda (a b) (and (not (string< a b))
6370 (not (string= a b)))))))
6371 ((= dcst ?t)
6372 (setq extractfun
6373 (lambda (x)
6374 (if (string-match org-ts-regexp x)
6375 (time-to-seconds
6376 (org-time-string-to-time (match-string 0 x)))
6377 0))
6378 comparefun (if (= dcst sorting-type) '< '>)))
6379 (t (error "Invalid sorting type `%c'" sorting-type)))
6380
6381 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6382 table)
6383 (lambda (a b) (funcall comparefun (car a) (car b))))))
6384
6385 ;;;; Plain list items, including checkboxes
6386
6387 ;;; Plain list items
6388
6389 (defun org-at-item-p ()
6390 "Is point in a line starting a hand-formatted item?"
6391 (let ((llt org-plain-list-ordered-item-terminator))
6392 (save-excursion
6393 (goto-char (point-at-bol))
6394 (looking-at
6395 (cond
6396 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6397 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6398 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6399 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6400
6401 (defun org-in-item-p ()
6402 "It the cursor inside a plain list item.
6403 Does not have to be the first line."
6404 (save-excursion
6405 (condition-case nil
6406 (progn
6407 (org-beginning-of-item)
6408 (org-at-item-p)
6409 t)
6410 (error nil))))
6411
6412 (defun org-insert-item (&optional checkbox)
6413 "Insert a new item at the current level.
6414 Return t when things worked, nil when we are not in an item."
6415 (when (save-excursion
6416 (condition-case nil
6417 (progn
6418 (org-beginning-of-item)
6419 (org-at-item-p)
6420 (if (org-invisible-p) (error "Invisible item"))
6421 t)
6422 (error nil)))
6423 (let* ((bul (match-string 0))
6424 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6425 (match-end 0)))
6426 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6427 pos)
6428 (cond
6429 ((and (org-at-item-p) (<= (point) eow))
6430 ;; before the bullet
6431 (beginning-of-line 1)
6432 (open-line (if blank 2 1)))
6433 ((<= (point) eow)
6434 (beginning-of-line 1))
6435 (t (newline (if blank 2 1))))
6436 (insert bul (if checkbox "[ ]" ""))
6437 (just-one-space)
6438 (setq pos (point))
6439 (end-of-line 1)
6440 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6441 (org-maybe-renumber-ordered-list)
6442 (and checkbox (org-update-checkbox-count-maybe))
6443 t))
6444
6445 ;;; Checkboxes
6446
6447 (defun org-at-item-checkbox-p ()
6448 "Is point at a line starting a plain-list item with a checklet?"
6449 (and (org-at-item-p)
6450 (save-excursion
6451 (goto-char (match-end 0))
6452 (skip-chars-forward " \t")
6453 (looking-at "\\[[- X]\\]"))))
6454
6455 (defun org-toggle-checkbox (&optional arg)
6456 "Toggle the checkbox in the current line."
6457 (interactive "P")
6458 (catch 'exit
6459 (let (beg end status (firstnew 'unknown))
6460 (cond
6461 ((org-region-active-p)
6462 (setq beg (region-beginning) end (region-end)))
6463 ((org-on-heading-p)
6464 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6465 ((org-at-item-checkbox-p)
6466 (save-excursion
6467 (replace-match
6468 (cond (arg "[-]")
6469 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6470 (t "[ ]"))
6471 t t))
6472 (throw 'exit t))
6473 (t (error "Not at a checkbox or heading, and no active region")))
6474 (save-excursion
6475 (goto-char beg)
6476 (while (< (point) end)
6477 (when (org-at-item-checkbox-p)
6478 (setq status (equal (match-string 0) "[X]"))
6479 (when (eq firstnew 'unknown)
6480 (setq firstnew (not status)))
6481 (replace-match
6482 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6483 (beginning-of-line 2)))))
6484 (org-update-checkbox-count-maybe))
6485
6486 (defun org-update-checkbox-count-maybe ()
6487 "Update checkbox statistics unless turned off by user."
6488 (when org-provide-checkbox-statistics
6489 (org-update-checkbox-count)))
6490
6491 (defun org-update-checkbox-count (&optional all)
6492 "Update the checkbox statistics in the current section.
6493 This will find all statistic cookies like [57%] and [6/12] and update them
6494 with the current numbers. With optional prefix argument ALL, do this for
6495 the whole buffer."
6496 (interactive "P")
6497 (save-excursion
6498 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6499 (beg (condition-case nil
6500 (progn (outline-back-to-heading) (point))
6501 (error (point-min))))
6502 (end (move-marker (make-marker)
6503 (progn (outline-next-heading) (point))))
6504 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6505 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6506 b1 e1 f1 c-on c-off lim (cstat 0))
6507 (when all
6508 (goto-char (point-min))
6509 (outline-next-heading)
6510 (setq beg (point) end (point-max)))
6511 (goto-char beg)
6512 (while (re-search-forward re end t)
6513 (setq cstat (1+ cstat)
6514 b1 (match-beginning 0)
6515 e1 (match-end 0)
6516 f1 (match-beginning 1)
6517 lim (cond
6518 ((org-on-heading-p) (outline-next-heading) (point))
6519 ((org-at-item-p) (org-end-of-item) (point))
6520 (t nil))
6521 c-on 0 c-off 0)
6522 (goto-char e1)
6523 (when lim
6524 (while (re-search-forward re-box lim t)
6525 (if (member (match-string 2) '("[ ]" "[-]"))
6526 (setq c-off (1+ c-off))
6527 (setq c-on (1+ c-on))))
6528 ; (delete-region b1 e1)
6529 (goto-char b1)
6530 (insert (if f1
6531 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6532 (format "[%d/%d]" c-on (+ c-on c-off))))
6533 (and (looking-at "\\[.*?\\]")
6534 (replace-match ""))))
6535 (when (interactive-p)
6536 (message "Checkbox satistics updated %s (%d places)"
6537 (if all "in entire file" "in current outline entry") cstat)))))
6538
6539 (defun org-get-checkbox-statistics-face ()
6540 "Select the face for checkbox statistics.
6541 The face will be `org-done' when all relevant boxes are checked. Otherwise
6542 it will be `org-todo'."
6543 (if (match-end 1)
6544 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6545 (if (and (> (match-end 2) (match-beginning 2))
6546 (equal (match-string 2) (match-string 3)))
6547 'org-done
6548 'org-todo)))
6549
6550 (defun org-get-indentation (&optional line)
6551 "Get the indentation of the current line, interpreting tabs.
6552 When LINE is given, assume it represents a line and compute its indentation."
6553 (if line
6554 (if (string-match "^ *" (org-remove-tabs line))
6555 (match-end 0))
6556 (save-excursion
6557 (beginning-of-line 1)
6558 (skip-chars-forward " \t")
6559 (current-column))))
6560
6561 (defun org-remove-tabs (s &optional width)
6562 "Replace tabulators in S with spaces.
6563 Assumes that s is a single line, starting in column 0."
6564 (setq width (or width tab-width))
6565 (while (string-match "\t" s)
6566 (setq s (replace-match
6567 (make-string
6568 (- (* width (/ (+ (match-beginning 0) width) width))
6569 (match-beginning 0)) ?\ )
6570 t t s)))
6571 s)
6572
6573 (defun org-fix-indentation (line ind)
6574 "Fix indentation in LINE.
6575 IND is a cons cell with target and minimum indentation.
6576 If the current indenation in LINE is smaller than the minimum,
6577 leave it alone. If it is larger than ind, set it to the target."
6578 (let* ((l (org-remove-tabs line))
6579 (i (org-get-indentation l))
6580 (i1 (car ind)) (i2 (cdr ind)))
6581 (if (>= i i2) (setq l (substring line i2)))
6582 (if (> i1 0)
6583 (concat (make-string i1 ?\ ) l)
6584 l)))
6585
6586 (defcustom org-empty-line-terminates-plain-lists nil
6587 "Non-nil means, an empty line ends all plain list levels.
6588 When nil, empty lines are part of the preceeding item."
6589 :group 'org-plain-lists
6590 :type 'boolean)
6591
6592 (defun org-beginning-of-item ()
6593 "Go to the beginning of the current hand-formatted item.
6594 If the cursor is not in an item, throw an error."
6595 (interactive)
6596 (let ((pos (point))
6597 (limit (save-excursion
6598 (condition-case nil
6599 (progn
6600 (org-back-to-heading)
6601 (beginning-of-line 2) (point))
6602 (error (point-min)))))
6603 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6604 ind ind1)
6605 (if (org-at-item-p)
6606 (beginning-of-line 1)
6607 (beginning-of-line 1)
6608 (skip-chars-forward " \t")
6609 (setq ind (current-column))
6610 (if (catch 'exit
6611 (while t
6612 (beginning-of-line 0)
6613 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6614
6615 (if (looking-at "[ \t]*$")
6616 (setq ind1 ind-empty)
6617 (skip-chars-forward " \t")
6618 (setq ind1 (current-column)))
6619 (if (< ind1 ind)
6620 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6621 nil
6622 (goto-char pos)
6623 (error "Not in an item")))))
6624
6625 (defun org-end-of-item ()
6626 "Go to the end of the current hand-formatted item.
6627 If the cursor is not in an item, throw an error."
6628 (interactive)
6629 (let* ((pos (point))
6630 ind1
6631 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6632 (limit (save-excursion (outline-next-heading) (point)))
6633 (ind (save-excursion
6634 (org-beginning-of-item)
6635 (skip-chars-forward " \t")
6636 (current-column)))
6637 (end (catch 'exit
6638 (while t
6639 (beginning-of-line 2)
6640 (if (eobp) (throw 'exit (point)))
6641 (if (>= (point) limit) (throw 'exit (point-at-bol)))
6642 (if (looking-at "[ \t]*$")
6643 (setq ind1 ind-empty)
6644 (skip-chars-forward " \t")
6645 (setq ind1 (current-column)))
6646 (if (<= ind1 ind)
6647 (throw 'exit (point-at-bol)))))))
6648 (if end
6649 (goto-char end)
6650 (goto-char pos)
6651 (error "Not in an item"))))
6652
6653 (defun org-next-item ()
6654 "Move to the beginning of the next item in the current plain list.
6655 Error if not at a plain list, or if this is the last item in the list."
6656 (interactive)
6657 (let (ind ind1 (pos (point)))
6658 (org-beginning-of-item)
6659 (setq ind (org-get-indentation))
6660 (org-end-of-item)
6661 (setq ind1 (org-get-indentation))
6662 (unless (and (org-at-item-p) (= ind ind1))
6663 (goto-char pos)
6664 (error "On last item"))))
6665
6666 (defun org-previous-item ()
6667 "Move to the beginning of the previous item in the current plain list.
6668 Error if not at a plain list, or if this is the first item in the list."
6669 (interactive)
6670 (let (beg ind ind1 (pos (point)))
6671 (org-beginning-of-item)
6672 (setq beg (point))
6673 (setq ind (org-get-indentation))
6674 (goto-char beg)
6675 (catch 'exit
6676 (while t
6677 (beginning-of-line 0)
6678 (if (looking-at "[ \t]*$")
6679 nil
6680 (if (<= (setq ind1 (org-get-indentation)) ind)
6681 (throw 'exit t)))))
6682 (condition-case nil
6683 (if (or (not (org-at-item-p))
6684 (< ind1 (1- ind)))
6685 (error "")
6686 (org-beginning-of-item))
6687 (error (goto-char pos)
6688 (error "On first item")))))
6689
6690 (defun org-move-item-down ()
6691 "Move the plain list item at point down, i.e. swap with following item.
6692 Subitems (items with larger indentation) are considered part of the item,
6693 so this really moves item trees."
6694 (interactive)
6695 (let (beg end ind ind1 (pos (point)) txt)
6696 (org-beginning-of-item)
6697 (setq beg (point))
6698 (setq ind (org-get-indentation))
6699 (org-end-of-item)
6700 (setq end (point))
6701 (setq ind1 (org-get-indentation))
6702 (if (and (org-at-item-p) (= ind ind1))
6703 (progn
6704 (org-end-of-item)
6705 (setq txt (buffer-substring beg end))
6706 (save-excursion
6707 (delete-region beg end))
6708 (setq pos (point))
6709 (insert txt)
6710 (goto-char pos)
6711 (org-maybe-renumber-ordered-list))
6712 (goto-char pos)
6713 (error "Cannot move this item further down"))))
6714
6715 (defun org-move-item-up (arg)
6716 "Move the plain list item at point up, i.e. swap with previous item.
6717 Subitems (items with larger indentation) are considered part of the item,
6718 so this really moves item trees."
6719 (interactive "p")
6720 (let (beg end ind ind1 (pos (point)) txt)
6721 (org-beginning-of-item)
6722 (setq beg (point))
6723 (setq ind (org-get-indentation))
6724 (org-end-of-item)
6725 (setq end (point))
6726 (goto-char beg)
6727 (catch 'exit
6728 (while t
6729 (beginning-of-line 0)
6730 (if (looking-at "[ \t]*$")
6731 (if org-empty-line-terminates-plain-lists
6732 (progn
6733 (goto-char pos)
6734 (error "Cannot move this item further up"))
6735 nil)
6736 (if (<= (setq ind1 (org-get-indentation)) ind)
6737 (throw 'exit t)))))
6738 (condition-case nil
6739 (org-beginning-of-item)
6740 (error (goto-char beg)
6741 (error "Cannot move this item further up")))
6742 (setq ind1 (org-get-indentation))
6743 (if (and (org-at-item-p) (= ind ind1))
6744 (progn
6745 (setq txt (buffer-substring beg end))
6746 (save-excursion
6747 (delete-region beg end))
6748 (setq pos (point))
6749 (insert txt)
6750 (goto-char pos)
6751 (org-maybe-renumber-ordered-list))
6752 (goto-char pos)
6753 (error "Cannot move this item further up"))))
6754
6755 (defun org-maybe-renumber-ordered-list ()
6756 "Renumber the ordered list at point if setup allows it.
6757 This tests the user option `org-auto-renumber-ordered-lists' before
6758 doing the renumbering."
6759 (interactive)
6760 (when (and org-auto-renumber-ordered-lists
6761 (org-at-item-p))
6762 (if (match-beginning 3)
6763 (org-renumber-ordered-list 1)
6764 (org-fix-bullet-type))))
6765
6766 (defun org-maybe-renumber-ordered-list-safe ()
6767 (condition-case nil
6768 (save-excursion
6769 (org-maybe-renumber-ordered-list))
6770 (error nil)))
6771
6772 (defun org-cycle-list-bullet (&optional which)
6773 "Cycle through the different itemize/enumerate bullets.
6774 This cycle the entire list level through the sequence:
6775
6776 `-' -> `+' -> `*' -> `1.' -> `1)'
6777
6778 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6779 0 meand `-', 1 means `+' etc."
6780 (interactive "P")
6781 (org-preserve-lc
6782 (org-beginning-of-item-list)
6783 (org-at-item-p)
6784 (beginning-of-line 1)
6785 (let ((current (match-string 0))
6786 (prevp (eq which 'previous))
6787 new)
6788 (setq new (cond
6789 ((and (numberp which)
6790 (nth (1- which) '("-" "+" "*" "1." "1)"))))
6791 ((string-match "-" current) (if prevp "1)" "+"))
6792 ((string-match "\\+" current)
6793 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
6794 ((string-match "\\*" current) (if prevp "+" "1."))
6795 ((string-match "\\." current) (if prevp "*" "1)"))
6796 ((string-match ")" current) (if prevp "1." "-"))
6797 (t (error "This should not happen"))))
6798 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6799 (org-fix-bullet-type)
6800 (org-maybe-renumber-ordered-list))))
6801
6802 (defun org-get-string-indentation (s)
6803 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6804 (let ((n -1) (i 0) (w tab-width) c)
6805 (catch 'exit
6806 (while (< (setq n (1+ n)) (length s))
6807 (setq c (aref s n))
6808 (cond ((= c ?\ ) (setq i (1+ i)))
6809 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6810 (t (throw 'exit t)))))
6811 i))
6812
6813 (defun org-renumber-ordered-list (arg)
6814 "Renumber an ordered plain list.
6815 Cursor needs to be in the first line of an item, the line that starts
6816 with something like \"1.\" or \"2)\"."
6817 (interactive "p")
6818 (unless (and (org-at-item-p)
6819 (match-beginning 3))
6820 (error "This is not an ordered list"))
6821 (let ((line (org-current-line))
6822 (col (current-column))
6823 (ind (org-get-string-indentation
6824 (buffer-substring (point-at-bol) (match-beginning 3))))
6825 ;; (term (substring (match-string 3) -1))
6826 ind1 (n (1- arg))
6827 fmt)
6828 ;; find where this list begins
6829 (org-beginning-of-item-list)
6830 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6831 (setq fmt (concat "%d" (match-string 1)))
6832 (beginning-of-line 0)
6833 ;; walk forward and replace these numbers
6834 (catch 'exit
6835 (while t
6836 (catch 'next
6837 (beginning-of-line 2)
6838 (if (eobp) (throw 'exit nil))
6839 (if (looking-at "[ \t]*$") (throw 'next nil))
6840 (skip-chars-forward " \t") (setq ind1 (current-column))
6841 (if (> ind1 ind) (throw 'next t))
6842 (if (< ind1 ind) (throw 'exit t))
6843 (if (not (org-at-item-p)) (throw 'exit nil))
6844 (delete-region (match-beginning 2) (match-end 2))
6845 (goto-char (match-beginning 2))
6846 (insert (format fmt (setq n (1+ n)))))))
6847 (goto-line line)
6848 (move-to-column col)))
6849
6850 (defun org-fix-bullet-type ()
6851 "Make sure all items in this list have the same bullet as the firsst item."
6852 (interactive)
6853 (unless (org-at-item-p) (error "This is not a list"))
6854 (let ((line (org-current-line))
6855 (col (current-column))
6856 (ind (current-indentation))
6857 ind1 bullet)
6858 ;; find where this list begins
6859 (org-beginning-of-item-list)
6860 (beginning-of-line 1)
6861 ;; find out what the bullet type is
6862 (looking-at "[ \t]*\\(\\S-+\\)")
6863 (setq bullet (match-string 1))
6864 ;; walk forward and replace these numbers
6865 (beginning-of-line 0)
6866 (catch 'exit
6867 (while t
6868 (catch 'next
6869 (beginning-of-line 2)
6870 (if (eobp) (throw 'exit nil))
6871 (if (looking-at "[ \t]*$") (throw 'next nil))
6872 (skip-chars-forward " \t") (setq ind1 (current-column))
6873 (if (> ind1 ind) (throw 'next t))
6874 (if (< ind1 ind) (throw 'exit t))
6875 (if (not (org-at-item-p)) (throw 'exit nil))
6876 (skip-chars-forward " \t")
6877 (looking-at "\\S-+")
6878 (replace-match bullet))))
6879 (goto-line line)
6880 (move-to-column col)
6881 (if (string-match "[0-9]" bullet)
6882 (org-renumber-ordered-list 1))))
6883
6884 (defun org-beginning-of-item-list ()
6885 "Go to the beginning of the current item list.
6886 I.e. to the first item in this list."
6887 (interactive)
6888 (org-beginning-of-item)
6889 (let ((pos (point-at-bol))
6890 (ind (org-get-indentation))
6891 ind1)
6892 ;; find where this list begins
6893 (catch 'exit
6894 (while t
6895 (catch 'next
6896 (beginning-of-line 0)
6897 (if (looking-at "[ \t]*$")
6898 (throw (if (bobp) 'exit 'next) t))
6899 (skip-chars-forward " \t") (setq ind1 (current-column))
6900 (if (or (< ind1 ind)
6901 (and (= ind1 ind)
6902 (not (org-at-item-p)))
6903 (bobp))
6904 (throw 'exit t)
6905 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6906 (goto-char pos)))
6907
6908
6909 (defun org-end-of-item-list ()
6910 "Go to the end of the current item list.
6911 I.e. to the text after the last item."
6912 (interactive)
6913 (org-beginning-of-item)
6914 (let ((pos (point-at-bol))
6915 (ind (org-get-indentation))
6916 ind1)
6917 ;; find where this list begins
6918 (catch 'exit
6919 (while t
6920 (catch 'next
6921 (beginning-of-line 2)
6922 (if (looking-at "[ \t]*$")
6923 (throw (if (eobp) 'exit 'next) t))
6924 (skip-chars-forward " \t") (setq ind1 (current-column))
6925 (if (or (< ind1 ind)
6926 (and (= ind1 ind)
6927 (not (org-at-item-p)))
6928 (eobp))
6929 (progn
6930 (setq pos (point-at-bol))
6931 (throw 'exit t))))))
6932 (goto-char pos)))
6933
6934
6935 (defvar org-last-indent-begin-marker (make-marker))
6936 (defvar org-last-indent-end-marker (make-marker))
6937
6938 (defun org-outdent-item (arg)
6939 "Outdent a local list item."
6940 (interactive "p")
6941 (org-indent-item (- arg)))
6942
6943 (defun org-indent-item (arg)
6944 "Indent a local list item."
6945 (interactive "p")
6946 (unless (org-at-item-p)
6947 (error "Not on an item"))
6948 (save-excursion
6949 (let (beg end ind ind1 tmp delta ind-down ind-up)
6950 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6951 (setq beg org-last-indent-begin-marker
6952 end org-last-indent-end-marker)
6953 (org-beginning-of-item)
6954 (setq beg (move-marker org-last-indent-begin-marker (point)))
6955 (org-end-of-item)
6956 (setq end (move-marker org-last-indent-end-marker (point))))
6957 (goto-char beg)
6958 (setq tmp (org-item-indent-positions)
6959 ind (car tmp)
6960 ind-down (nth 2 tmp)
6961 ind-up (nth 1 tmp)
6962 delta (if (> arg 0)
6963 (if ind-down (- ind-down ind) 2)
6964 (if ind-up (- ind-up ind) -2)))
6965 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6966 (while (< (point) end)
6967 (beginning-of-line 1)
6968 (skip-chars-forward " \t") (setq ind1 (current-column))
6969 (delete-region (point-at-bol) (point))
6970 (or (eolp) (indent-to-column (+ ind1 delta)))
6971 (beginning-of-line 2))))
6972 (org-fix-bullet-type)
6973 (org-maybe-renumber-ordered-list-safe)
6974 (save-excursion
6975 (beginning-of-line 0)
6976 (condition-case nil (org-beginning-of-item) (error nil))
6977 (org-maybe-renumber-ordered-list-safe)))
6978
6979 (defun org-item-indent-positions ()
6980 "Return indentation for plain list items.
6981 This returns a list with three values: The current indentation, the
6982 parent indentation and the indentation a child should habe.
6983 Assumes cursor in item line."
6984 (let* ((bolpos (point-at-bol))
6985 (ind (org-get-indentation))
6986 ind-down ind-up pos)
6987 (save-excursion
6988 (org-beginning-of-item-list)
6989 (skip-chars-backward "\n\r \t")
6990 (when (org-in-item-p)
6991 (org-beginning-of-item)
6992 (setq ind-up (org-get-indentation))))
6993 (setq pos (point))
6994 (save-excursion
6995 (cond
6996 ((and (condition-case nil (progn (org-previous-item) t)
6997 (error nil))
6998 (or (forward-char 1) t)
6999 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7000 (setq ind-down (org-get-indentation)))
7001 ((and (goto-char pos)
7002 (org-at-item-p))
7003 (goto-char (match-end 0))
7004 (skip-chars-forward " \t")
7005 (setq ind-down (current-column)))))
7006 (list ind ind-up ind-down)))
7007
7008 ;;; The orgstruct minor mode
7009
7010 ;; Define a minor mode which can be used in other modes in order to
7011 ;; integrate the org-mode structure editing commands.
7012
7013 ;; This is really a hack, because the org-mode structure commands use
7014 ;; keys which normally belong to the major mode. Here is how it
7015 ;; works: The minor mode defines all the keys necessary to operate the
7016 ;; structure commands, but wraps the commands into a function which
7017 ;; tests if the cursor is currently at a headline or a plain list
7018 ;; item. If that is the case, the structure command is used,
7019 ;; temporarily setting many Org-mode variables like regular
7020 ;; expressions for filling etc. However, when any of those keys is
7021 ;; used at a different location, function uses `key-binding' to look
7022 ;; up if the key has an associated command in another currently active
7023 ;; keymap (minor modes, major mode, global), and executes that
7024 ;; command. There might be problems if any of the keys is otherwise
7025 ;; used as a prefix key.
7026
7027 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7028 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7029 ;; addresses this by checking explicitly for both bindings.
7030
7031 (defvar orgstruct-mode-map (make-sparse-keymap)
7032 "Keymap for the minor `orgstruct-mode'.")
7033
7034 (defvar org-local-vars nil
7035 "List of local variables, for use by `orgstruct-mode'")
7036
7037 ;;;###autoload
7038 (define-minor-mode orgstruct-mode
7039 "Toggle the minor more `orgstruct-mode'.
7040 This mode is for using Org-mode structure commands in other modes.
7041 The following key behave as if Org-mode was active, if the cursor
7042 is on a headline, or on a plain list item (both in the definition
7043 of Org-mode).
7044
7045 M-up Move entry/item up
7046 M-down Move entry/item down
7047 M-left Promote
7048 M-right Demote
7049 M-S-up Move entry/item up
7050 M-S-down Move entry/item down
7051 M-S-left Promote subtree
7052 M-S-right Demote subtree
7053 M-q Fill paragraph and items like in Org-mode
7054 C-c ^ Sort entries
7055 C-c - Cycle list bullet
7056 TAB Cycle item visibility
7057 M-RET Insert new heading/item
7058 S-M-RET Insert new TODO heading / Chekbox item
7059 C-c C-c Set tags / toggle checkbox"
7060 nil " OrgStruct" nil
7061 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7062
7063 ;;;###autoload
7064 (defun turn-on-orgstruct ()
7065 "Unconditionally turn on `orgstruct-mode'."
7066 (orgstruct-mode 1))
7067
7068 ;;;###autoload
7069 (defun turn-on-orgstruct++ ()
7070 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7071 In addition to setting orgstruct-mode, this also exports all indentation and
7072 autofilling variables from org-mode into the buffer. Note that turning
7073 off orgstruct-mode will *not* remove these additonal settings."
7074 (orgstruct-mode 1)
7075 (let (var val)
7076 (mapc
7077 (lambda (x)
7078 (when (string-match
7079 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7080 (symbol-name (car x)))
7081 (setq var (car x) val (nth 1 x))
7082 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7083 org-local-vars)))
7084
7085 (defun orgstruct-error ()
7086 "Error when there is no default binding for a structure key."
7087 (interactive)
7088 (error "This key is has no function outside structure elements"))
7089
7090 (defun orgstruct-setup ()
7091 "Setup orgstruct keymaps."
7092 (let ((nfunc 0)
7093 (bindings
7094 (list
7095 '([(meta up)] org-metaup)
7096 '([(meta down)] org-metadown)
7097 '([(meta left)] org-metaleft)
7098 '([(meta right)] org-metaright)
7099 '([(meta shift up)] org-shiftmetaup)
7100 '([(meta shift down)] org-shiftmetadown)
7101 '([(meta shift left)] org-shiftmetaleft)
7102 '([(meta shift right)] org-shiftmetaright)
7103 '([(shift up)] org-shiftup)
7104 '([(shift down)] org-shiftdown)
7105 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7106 '("\M-q" fill-paragraph)
7107 '("\C-c^" org-sort)
7108 '("\C-c-" org-cycle-list-bullet)))
7109 elt key fun cmd)
7110 (while (setq elt (pop bindings))
7111 (setq nfunc (1+ nfunc))
7112 (setq key (org-key (car elt))
7113 fun (nth 1 elt)
7114 cmd (orgstruct-make-binding fun nfunc key))
7115 (org-defkey orgstruct-mode-map key cmd))
7116
7117 ;; Special treatment needed for TAB and RET
7118 (org-defkey orgstruct-mode-map [(tab)]
7119 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7120 (org-defkey orgstruct-mode-map "\C-i"
7121 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7122
7123 (org-defkey orgstruct-mode-map "\M-\C-m"
7124 (orgstruct-make-binding 'org-insert-heading 105
7125 "\M-\C-m" [(meta return)]))
7126 (org-defkey orgstruct-mode-map [(meta return)]
7127 (orgstruct-make-binding 'org-insert-heading 106
7128 [(meta return)] "\M-\C-m"))
7129
7130 (org-defkey orgstruct-mode-map [(shift meta return)]
7131 (orgstruct-make-binding 'org-insert-todo-heading 107
7132 [(meta return)] "\M-\C-m"))
7133
7134 (unless org-local-vars
7135 (setq org-local-vars (org-get-local-variables)))
7136
7137 t))
7138
7139 (defun orgstruct-make-binding (fun n &rest keys)
7140 "Create a function for binding in the structure minor mode.
7141 FUN is the command to call inside a table. N is used to create a unique
7142 command name. KEYS are keys that should be checked in for a command
7143 to execute outside of tables."
7144 (eval
7145 (list 'defun
7146 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7147 '(arg)
7148 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7149 "Outside of structure, run the binding of `"
7150 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7151 "'.")
7152 '(interactive "p")
7153 (list 'if
7154 '(org-context-p 'headline 'item)
7155 (list 'org-run-like-in-org-mode (list 'quote fun))
7156 (list 'let '(orgstruct-mode)
7157 (list 'call-interactively
7158 (append '(or)
7159 (mapcar (lambda (k)
7160 (list 'key-binding k))
7161 keys)
7162 '('orgstruct-error))))))))
7163
7164 (defun org-context-p (&rest contexts)
7165 "Check if local context is and of CONTEXTS.
7166 Possible values in the list of contexts are `table', `headline', and `item'."
7167 (let ((pos (point)))
7168 (goto-char (point-at-bol))
7169 (prog1 (or (and (memq 'table contexts)
7170 (looking-at "[ \t]*|"))
7171 (and (memq 'headline contexts)
7172 (looking-at "\\*+"))
7173 (and (memq 'item contexts)
7174 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7175 (goto-char pos))))
7176
7177 (defun org-get-local-variables ()
7178 "Return a list of all local variables in an org-mode buffer."
7179 (let (varlist)
7180 (with-current-buffer (get-buffer-create "*Org tmp*")
7181 (erase-buffer)
7182 (org-mode)
7183 (setq varlist (buffer-local-variables)))
7184 (kill-buffer "*Org tmp*")
7185 (delq nil
7186 (mapcar
7187 (lambda (x)
7188 (setq x
7189 (if (symbolp x)
7190 (list x)
7191 (list (car x) (list 'quote (cdr x)))))
7192 (if (string-match
7193 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7194 (symbol-name (car x)))
7195 x nil))
7196 varlist))))
7197
7198 ;;;###autoload
7199 (defun org-run-like-in-org-mode (cmd)
7200 (unless org-local-vars
7201 (setq org-local-vars (org-get-local-variables)))
7202 (eval (list 'let org-local-vars
7203 (list 'call-interactively (list 'quote cmd)))))
7204
7205 ;;;; Archiving
7206
7207 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7208
7209 (defun org-archive-subtree (&optional find-done)
7210 "Move the current subtree to the archive.
7211 The archive can be a certain top-level heading in the current file, or in
7212 a different file. The tree will be moved to that location, the subtree
7213 heading be marked DONE, and the current time will be added.
7214
7215 When called with prefix argument FIND-DONE, find whole trees without any
7216 open TODO items and archive them (after getting confirmation from the user).
7217 If the cursor is not at a headline when this comand is called, try all level
7218 1 trees. If the cursor is on a headline, only try the direct children of
7219 this heading."
7220 (interactive "P")
7221 (if find-done
7222 (org-archive-all-done)
7223 ;; Save all relevant TODO keyword-relatex variables
7224
7225 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7226 (tr-org-todo-keywords-1 org-todo-keywords-1)
7227 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7228 (tr-org-done-keywords org-done-keywords)
7229 (tr-org-todo-regexp org-todo-regexp)
7230 (tr-org-todo-line-regexp org-todo-line-regexp)
7231 (tr-org-odd-levels-only org-odd-levels-only)
7232 (this-buffer (current-buffer))
7233 (org-archive-location org-archive-location)
7234 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7235 ;; start of variables that will be used for savind context
7236 (file (abbreviate-file-name (buffer-file-name)))
7237 (time (format-time-string
7238 (substring (cdr org-time-stamp-formats) 1 -1)
7239 (current-time)))
7240 afile heading buffer level newfile-p
7241 category todo priority
7242 ;; start of variables that will be used for savind context
7243 ltags itags prop)
7244
7245 ;; Try to find a local archive location
7246 (save-excursion
7247 (save-restriction
7248 (widen)
7249 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7250 (if (and prop (string-match "\\S-" prop))
7251 (setq org-archive-location prop)
7252 (if (or (re-search-backward re nil t)
7253 (re-search-forward re nil t))
7254 (setq org-archive-location (match-string 1))))))
7255
7256 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7257 (progn
7258 (setq afile (format (match-string 1 org-archive-location)
7259 (file-name-nondirectory buffer-file-name))
7260 heading (match-string 2 org-archive-location)))
7261 (error "Invalid `org-archive-location'"))
7262 (if (> (length afile) 0)
7263 (setq newfile-p (not (file-exists-p afile))
7264 buffer (find-file-noselect afile))
7265 (setq buffer (current-buffer)))
7266 (unless buffer
7267 (error "Cannot access file \"%s\"" afile))
7268 (if (and (> (length heading) 0)
7269 (string-match "^\\*+" heading))
7270 (setq level (match-end 0))
7271 (setq heading nil level 0))
7272 (save-excursion
7273 (org-back-to-heading t)
7274 ;; Get context information that will be lost by moving the tree
7275 (org-refresh-category-properties)
7276 (setq category (org-get-category)
7277 todo (and (looking-at org-todo-line-regexp)
7278 (match-string 2))
7279 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7280 ltags (org-get-tags)
7281 itags (org-delete-all ltags (org-get-tags-at)))
7282 (setq ltags (mapconcat 'identity ltags " ")
7283 itags (mapconcat 'identity itags " "))
7284 ;; We first only copy, in case something goes wrong
7285 ;; we need to protect this-command, to avoid kill-region sets it,
7286 ;; which would lead to duplication of subtrees
7287 (let (this-command) (org-copy-subtree))
7288 (set-buffer buffer)
7289 ;; Enforce org-mode for the archive buffer
7290 (if (not (org-mode-p))
7291 ;; Force the mode for future visits.
7292 (let ((org-insert-mode-line-in-empty-file t)
7293 (org-inhibit-startup t))
7294 (call-interactively 'org-mode)))
7295 (when newfile-p
7296 (goto-char (point-max))
7297 (insert (format "\nArchived entries from file %s\n\n"
7298 (buffer-file-name this-buffer))))
7299 ;; Force the TODO keywords of the original buffer
7300 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7301 (org-todo-keywords-1 tr-org-todo-keywords-1)
7302 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7303 (org-done-keywords tr-org-done-keywords)
7304 (org-todo-regexp tr-org-todo-regexp)
7305 (org-todo-line-regexp tr-org-todo-line-regexp)
7306 (org-odd-levels-only
7307 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7308 org-odd-levels-only
7309 tr-org-odd-levels-only)))
7310 (goto-char (point-min))
7311 (if heading
7312 (progn
7313 (if (re-search-forward
7314 (concat "^" (regexp-quote heading)
7315 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7316 nil t)
7317 (goto-char (match-end 0))
7318 ;; Heading not found, just insert it at the end
7319 (goto-char (point-max))
7320 (or (bolp) (insert "\n"))
7321 (insert "\n" heading "\n")
7322 (end-of-line 0))
7323 ;; Make the subtree visible
7324 (show-subtree)
7325 (org-end-of-subtree t)
7326 (skip-chars-backward " \t\r\n")
7327 (and (looking-at "[ \t\r\n]*")
7328 (replace-match "\n\n")))
7329 ;; No specific heading, just go to end of file.
7330 (goto-char (point-max)) (insert "\n"))
7331 ;; Paste
7332 (org-paste-subtree (org-get-legal-level level 1))
7333
7334 ;; Mark the entry as done
7335 (when (and org-archive-mark-done
7336 (looking-at org-todo-line-regexp)
7337 (or (not (match-end 2))
7338 (not (member (match-string 2) org-done-keywords))))
7339 (let (org-log-done)
7340 (org-todo
7341 (car (or (member org-archive-mark-done org-done-keywords)
7342 org-done-keywords)))))
7343
7344 ;; Add the context info
7345 (when org-archive-save-context-info
7346 (let ((l org-archive-save-context-info) e n v)
7347 (while (setq e (pop l))
7348 (when (and (setq v (symbol-value e))
7349 (stringp v) (string-match "\\S-" v))
7350 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7351 (org-entry-put (point) n v)))))
7352
7353 ;; Save the buffer, if it is not the same buffer.
7354 (if (not (eq this-buffer buffer)) (save-buffer))))
7355 ;; Here we are back in the original buffer. Everything seems to have
7356 ;; worked. So now cut the tree and finish up.
7357 (let (this-command) (org-cut-subtree))
7358 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7359 (message "Subtree archived %s"
7360 (if (eq this-buffer buffer)
7361 (concat "under heading: " heading)
7362 (concat "in file: " (abbreviate-file-name afile)))))))
7363
7364 (defun org-refresh-category-properties ()
7365 "Refresh category text properties in teh buffer."
7366 (let ((def-cat (cond
7367 ((null org-category)
7368 (if buffer-file-name
7369 (file-name-sans-extension
7370 (file-name-nondirectory buffer-file-name))
7371 "???"))
7372 ((symbolp org-category) (symbol-name org-category))
7373 (t org-category)))
7374 beg end cat pos optionp)
7375 (org-unmodified
7376 (save-excursion
7377 (save-restriction
7378 (widen)
7379 (goto-char (point-min))
7380 (put-text-property (point) (point-max) 'org-category def-cat)
7381 (while (re-search-forward
7382 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7383 (setq pos (match-end 0)
7384 optionp (equal (char-after (match-beginning 0)) ?#)
7385 cat (org-trim (match-string 2)))
7386 (if optionp
7387 (setq beg (point-at-bol) end (point-max))
7388 (org-back-to-heading t)
7389 (setq beg (point) end (org-end-of-subtree t t)))
7390 (put-text-property beg end 'org-category cat)
7391 (goto-char pos)))))))
7392
7393 (defun org-archive-all-done (&optional tag)
7394 "Archive sublevels of the current tree without open TODO items.
7395 If the cursor is not on a headline, try all level 1 trees. If
7396 it is on a headline, try all direct children.
7397 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7398 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7399 (rea (concat ".*:" org-archive-tag ":"))
7400 (begm (make-marker))
7401 (endm (make-marker))
7402 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7403 "Move subtree to archive (no open TODO items)? "))
7404 beg end (cntarch 0))
7405 (if (org-on-heading-p)
7406 (progn
7407 (setq re1 (concat "^" (regexp-quote
7408 (make-string
7409 (1+ (- (match-end 0) (match-beginning 0)))
7410 ?*))
7411 " "))
7412 (move-marker begm (point))
7413 (move-marker endm (org-end-of-subtree t)))
7414 (setq re1 "^* ")
7415 (move-marker begm (point-min))
7416 (move-marker endm (point-max)))
7417 (save-excursion
7418 (goto-char begm)
7419 (while (re-search-forward re1 endm t)
7420 (setq beg (match-beginning 0)
7421 end (save-excursion (org-end-of-subtree t) (point)))
7422 (goto-char beg)
7423 (if (re-search-forward re end t)
7424 (goto-char end)
7425 (goto-char beg)
7426 (if (and (or (not tag) (not (looking-at rea)))
7427 (y-or-n-p question))
7428 (progn
7429 (if tag
7430 (org-toggle-tag org-archive-tag 'on)
7431 (org-archive-subtree))
7432 (setq cntarch (1+ cntarch)))
7433 (goto-char end)))))
7434 (message "%d trees archived" cntarch)))
7435
7436 (defun org-cycle-hide-drawers (state)
7437 "Re-hide all drawers after a visibility state change."
7438 (when (and (org-mode-p)
7439 (not (memq state '(overview folded))))
7440 (save-excursion
7441 (let* ((globalp (memq state '(contents all)))
7442 (beg (if globalp (point-min) (point)))
7443 (end (if globalp (point-max) (org-end-of-subtree t))))
7444 (goto-char beg)
7445 (while (re-search-forward org-drawer-regexp end t)
7446 (org-flag-drawer t))))))
7447
7448 (defun org-flag-drawer (flag)
7449 (save-excursion
7450 (beginning-of-line 1)
7451 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7452 (let ((b (match-end 0)))
7453 (if (re-search-forward
7454 "^[ \t]*:END:"
7455 (save-excursion (outline-next-heading) (point)) t)
7456 (outline-flag-region b (point-at-eol) flag)
7457 (error ":END: line missing"))))))
7458
7459 (defun org-cycle-hide-archived-subtrees (state)
7460 "Re-hide all archived subtrees after a visibility state change."
7461 (when (and (not org-cycle-open-archived-trees)
7462 (not (memq state '(overview folded))))
7463 (save-excursion
7464 (let* ((globalp (memq state '(contents all)))
7465 (beg (if globalp (point-min) (point)))
7466 (end (if globalp (point-max) (org-end-of-subtree t))))
7467 (org-hide-archived-subtrees beg end)
7468 (goto-char beg)
7469 (if (looking-at (concat ".*:" org-archive-tag ":"))
7470 (message (substitute-command-keys
7471 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7472
7473 (defun org-force-cycle-archived ()
7474 "Cycle subtree even if it is archived."
7475 (interactive)
7476 (setq this-command 'org-cycle)
7477 (let ((org-cycle-open-archived-trees t))
7478 (call-interactively 'org-cycle)))
7479
7480 (defun org-hide-archived-subtrees (beg end)
7481 "Re-hide all archived subtrees after a visibility state change."
7482 (save-excursion
7483 (let* ((re (concat ":" org-archive-tag ":")))
7484 (goto-char beg)
7485 (while (re-search-forward re end t)
7486 (and (org-on-heading-p) (hide-subtree))
7487 (org-end-of-subtree t)))))
7488
7489 (defun org-toggle-tag (tag &optional onoff)
7490 "Toggle the tag TAG for the current line.
7491 If ONOFF is `on' or `off', don't toggle but set to this state."
7492 (unless (org-on-heading-p t) (error "Not on headling"))
7493 (let (res current)
7494 (save-excursion
7495 (beginning-of-line)
7496 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7497 (point-at-eol) t)
7498 (progn
7499 (setq current (match-string 1))
7500 (replace-match ""))
7501 (setq current ""))
7502 (setq current (nreverse (org-split-string current ":")))
7503 (cond
7504 ((eq onoff 'on)
7505 (setq res t)
7506 (or (member tag current) (push tag current)))
7507 ((eq onoff 'off)
7508 (or (not (member tag current)) (setq current (delete tag current))))
7509 (t (if (member tag current)
7510 (setq current (delete tag current))
7511 (setq res t)
7512 (push tag current))))
7513 (end-of-line 1)
7514 (if current
7515 (progn
7516 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
7517 (org-set-tags nil t))
7518 (delete-horizontal-space))
7519 (run-hooks 'org-after-tags-change-hook))
7520 res))
7521
7522 (defun org-toggle-archive-tag (&optional arg)
7523 "Toggle the archive tag for the current headline.
7524 With prefix ARG, check all children of current headline and offer tagging
7525 the children that do not contain any open TODO items."
7526 (interactive "P")
7527 (if arg
7528 (org-archive-all-done 'tag)
7529 (let (set)
7530 (save-excursion
7531 (org-back-to-heading t)
7532 (setq set (org-toggle-tag org-archive-tag))
7533 (when set (hide-subtree)))
7534 (and set (beginning-of-line 1))
7535 (message "Subtree %s" (if set "archived" "unarchived")))))
7536
7537
7538 ;;;; Tables
7539
7540 ;;; The table editor
7541
7542 ;; Watch out: Here we are talking about two different kind of tables.
7543 ;; Most of the code is for the tables created with the Org-mode table editor.
7544 ;; Sometimes, we talk about tables created and edited with the table.el
7545 ;; Emacs package. We call the former org-type tables, and the latter
7546 ;; table.el-type tables.
7547
7548 (defun org-before-change-function (beg end)
7549 "Every change indicates that a table might need an update."
7550 (setq org-table-may-need-update t))
7551
7552 (defconst org-table-line-regexp "^[ \t]*|"
7553 "Detects an org-type table line.")
7554 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7555 "Detects an org-type table line.")
7556 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7557 "Detects a table line marked for automatic recalculation.")
7558 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7559 "Detects a table line marked for automatic recalculation.")
7560 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7561 "Detects a table line marked for automatic recalculation.")
7562 (defconst org-table-hline-regexp "^[ \t]*|-"
7563 "Detects an org-type table hline.")
7564 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7565 "Detects a table-type table hline.")
7566 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7567 "Detects an org-type or table-type table.")
7568 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7569 "Searching from within a table (any type) this finds the first line
7570 outside the table.")
7571 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7572 "Searching from within a table (any type) this finds the first line
7573 outside the table.")
7574
7575 (defvar org-table-last-highlighted-reference nil)
7576 (defvar org-table-formula-history nil)
7577
7578 (defvar org-table-column-names nil
7579 "Alist with column names, derived from the `!' line.")
7580 (defvar org-table-column-name-regexp nil
7581 "Regular expression matching the current column names.")
7582 (defvar org-table-local-parameters nil
7583 "Alist with parameter names, derived from the `$' line.")
7584 (defvar org-table-named-field-locations nil
7585 "Alist with locations of named fields.")
7586
7587 (defvar org-table-current-line-types nil
7588 "Table row types, non-nil only for the duration of a comand.")
7589 (defvar org-table-current-begin-line nil
7590 "Table begin line, non-nil only for the duration of a comand.")
7591 (defvar org-table-current-begin-pos nil
7592 "Table begin position, non-nil only for the duration of a comand.")
7593 (defvar org-table-dlines nil
7594 "Vector of data line line numbers in the current table.")
7595 (defvar org-table-hlines nil
7596 "Vector of hline line numbers in the current table.")
7597
7598 (defconst org-table-range-regexp
7599 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
7600 ;; 1 2 3 4 5
7601 "Regular expression for matching ranges in formulas.")
7602
7603 (defconst org-table-range-regexp2
7604 (concat
7605 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
7606 "\\.\\."
7607 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
7608 "Match a range for reference display.")
7609
7610 (defconst org-table-translate-regexp
7611 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
7612 "Match a reference that needs translation, for reference display.")
7613
7614 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
7615
7616 (defun org-table-create-with-table.el ()
7617 "Use the table.el package to insert a new table.
7618 If there is already a table at point, convert between Org-mode tables
7619 and table.el tables."
7620 (interactive)
7621 (require 'table)
7622 (cond
7623 ((org-at-table.el-p)
7624 (if (y-or-n-p "Convert table to Org-mode table? ")
7625 (org-table-convert)))
7626 ((org-at-table-p)
7627 (if (y-or-n-p "Convert table to table.el table? ")
7628 (org-table-convert)))
7629 (t (call-interactively 'table-insert))))
7630
7631 (defun org-table-create-or-convert-from-region (arg)
7632 "Convert region to table, or create an empty table.
7633 If there is an active region, convert it to a table, using the function
7634 `org-table-convert-region'. See the documentation of that function
7635 to learn how the prefix argument is interpreted to determine the field
7636 separator.
7637 If there is no such region, create an empty table with `org-table-create'."
7638 (interactive "P")
7639 (if (org-region-active-p)
7640 (org-table-convert-region (region-beginning) (region-end) arg)
7641 (org-table-create arg)))
7642
7643 (defun org-table-create (&optional size)
7644 "Query for a size and insert a table skeleton.
7645 SIZE is a string Columns x Rows like for example \"3x2\"."
7646 (interactive "P")
7647 (unless size
7648 (setq size (read-string
7649 (concat "Table size Columns x Rows [e.g. "
7650 org-table-default-size "]: ")
7651 "" nil org-table-default-size)))
7652
7653 (let* ((pos (point))
7654 (indent (make-string (current-column) ?\ ))
7655 (split (org-split-string size " *x *"))
7656 (rows (string-to-number (nth 1 split)))
7657 (columns (string-to-number (car split)))
7658 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7659 "\n")))
7660 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7661 (point-at-bol) (point)))
7662 (beginning-of-line 1)
7663 (newline))
7664 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7665 (dotimes (i rows) (insert line))
7666 (goto-char pos)
7667 (if (> rows 1)
7668 ;; Insert a hline after the first row.
7669 (progn
7670 (end-of-line 1)
7671 (insert "\n|-")
7672 (goto-char pos)))
7673 (org-table-align)))
7674
7675 (defun org-table-convert-region (beg0 end0 &optional separator)
7676 "Convert region to a table.
7677 The region goes from BEG0 to END0, but these borders will be moved
7678 slightly, to make sure a beginning of line in the first line is included.
7679
7680 SEPARATOR specifies the field separator in the lines. It can have the
7681 following values:
7682
7683 '(4) Use the comma as a field separator
7684 '(16) Use a TAB as field separator
7685 integer When a number, use that many spaces as field separator
7686 nil When nil, the command tries to be smart and figure out the
7687 separator in the following way:
7688 - when each line contains a TAB, assume TAB-separated material
7689 - when each line contains a comme, assume CSV material
7690 - else, assume one or more SPACE charcters as separator."
7691 (interactive "rP")
7692 (let* ((beg (min beg0 end0))
7693 (end (max beg0 end0))
7694 re)
7695 (goto-char beg)
7696 (beginning-of-line 1)
7697 (setq beg (move-marker (make-marker) (point)))
7698 (goto-char end)
7699 (if (bolp) (backward-char 1) (end-of-line 1))
7700 (setq end (move-marker (make-marker) (point)))
7701 ;; Get the right field separator
7702 (unless separator
7703 (goto-char beg)
7704 (setq separator
7705 (cond
7706 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
7707 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
7708 (t 1))))
7709 (setq re (cond
7710 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
7711 ((equal separator '(16)) "^\\|\t")
7712 ((integerp separator)
7713 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
7714 (t (error "This should not happen"))))
7715 (goto-char beg)
7716 (while (re-search-forward re end t)
7717 (replace-match "| " t t))
7718 (goto-char beg)
7719 (insert " ")
7720 (org-table-align)))
7721
7722 (defun org-table-import (file arg)
7723 "Import FILE as a table.
7724 The file is assumed to be tab-separated. Such files can be produced by most
7725 spreadsheet and database applications. If no tabs (at least one per line)
7726 are found, lines will be split on whitespace into fields."
7727 (interactive "f\nP")
7728 (or (bolp) (newline))
7729 (let ((beg (point))
7730 (pm (point-max)))
7731 (insert-file-contents file)
7732 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7733
7734 (defun org-table-export ()
7735 "Export table as a tab-separated file.
7736 Such a file can be imported into a spreadsheet program like Excel."
7737 (interactive)
7738 (let* ((beg (org-table-begin))
7739 (end (org-table-end))
7740 (table (buffer-substring beg end))
7741 (file (read-file-name "Export table to: "))
7742 buf)
7743 (unless (or (not (file-exists-p file))
7744 (y-or-n-p (format "Overwrite file %s? " file)))
7745 (error "Abort"))
7746 (with-current-buffer (find-file-noselect file)
7747 (setq buf (current-buffer))
7748 (erase-buffer)
7749 (fundamental-mode)
7750 (insert table)
7751 (goto-char (point-min))
7752 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7753 (replace-match "" t t)
7754 (end-of-line 1))
7755 (goto-char (point-min))
7756 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7757 (replace-match "" t t)
7758 (goto-char (min (1+ (point)) (point-max))))
7759 (goto-char (point-min))
7760 (while (re-search-forward "^-[-+]*$" nil t)
7761 (replace-match "")
7762 (if (looking-at "\n")
7763 (delete-char 1)))
7764 (goto-char (point-min))
7765 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7766 (replace-match "\t" t t))
7767 (save-buffer))
7768 (kill-buffer buf)))
7769
7770 (defvar org-table-aligned-begin-marker (make-marker)
7771 "Marker at the beginning of the table last aligned.
7772 Used to check if cursor still is in that table, to minimize realignment.")
7773 (defvar org-table-aligned-end-marker (make-marker)
7774 "Marker at the end of the table last aligned.
7775 Used to check if cursor still is in that table, to minimize realignment.")
7776 (defvar org-table-last-alignment nil
7777 "List of flags for flushright alignment, from the last re-alignment.
7778 This is being used to correctly align a single field after TAB or RET.")
7779 (defvar org-table-last-column-widths nil
7780 "List of max width of fields in each column.
7781 This is being used to correctly align a single field after TAB or RET.")
7782 (defvar org-table-overlay-coordinates nil
7783 "Overlay coordinates after each align of a table.")
7784 (make-variable-buffer-local 'org-table-overlay-coordinates)
7785
7786 (defvar org-last-recalc-line nil)
7787 (defconst org-narrow-column-arrow "=>"
7788 "Used as display property in narrowed table columns.")
7789
7790 (defun org-table-align ()
7791 "Align the table at point by aligning all vertical bars."
7792 (interactive)
7793 (let* (
7794 ;; Limits of table
7795 (beg (org-table-begin))
7796 (end (org-table-end))
7797 ;; Current cursor position
7798 (linepos (org-current-line))
7799 (colpos (org-table-current-column))
7800 (winstart (window-start))
7801 (winstartline (org-current-line (min winstart (1- (point-max)))))
7802 lines (new "") lengths l typenums ty fields maxfields i
7803 column
7804 (indent "") cnt frac
7805 rfmt hfmt
7806 (spaces '(1 . 1))
7807 (sp1 (car spaces))
7808 (sp2 (cdr spaces))
7809 (rfmt1 (concat
7810 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7811 (hfmt1 (concat
7812 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7813 emptystrings links dates narrow fmax f1 len c e)
7814 (untabify beg end)
7815 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
7816 ;; Check if we have links or dates
7817 (goto-char beg)
7818 (setq links (re-search-forward org-bracket-link-regexp end t))
7819 (goto-char beg)
7820 (setq dates (and org-display-custom-times
7821 (re-search-forward org-ts-regexp-both end t)))
7822 ;; Make sure the link properties are right
7823 (when links (goto-char beg) (while (org-activate-bracket-links end)))
7824 ;; Make sure the date properties are right
7825 (when dates (goto-char beg) (while (org-activate-dates end)))
7826
7827 ;; Check if we are narrowing any columns
7828 (goto-char beg)
7829 (setq narrow (and org-format-transports-properties-p
7830 (re-search-forward "<[0-9]+>" end t)))
7831 ;; Get the rows
7832 (setq lines (org-split-string
7833 (buffer-substring beg end) "\n"))
7834 ;; Store the indentation of the first line
7835 (if (string-match "^ *" (car lines))
7836 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7837 ;; Mark the hlines by setting the corresponding element to nil
7838 ;; At the same time, we remove trailing space.
7839 (setq lines (mapcar (lambda (l)
7840 (if (string-match "^ *|-" l)
7841 nil
7842 (if (string-match "[ \t]+$" l)
7843 (substring l 0 (match-beginning 0))
7844 l)))
7845 lines))
7846 ;; Get the data fields by splitting the lines.
7847 (setq fields (mapcar
7848 (lambda (l)
7849 (org-split-string l " *| *"))
7850 (delq nil (copy-sequence lines))))
7851 ;; How many fields in the longest line?
7852 (condition-case nil
7853 (setq maxfields (apply 'max (mapcar 'length fields)))
7854 (error
7855 (kill-region beg end)
7856 (org-table-create org-table-default-size)
7857 (error "Empty table - created default table")))
7858 ;; A list of empty strings to fill any short rows on output
7859 (setq emptystrings (make-list maxfields ""))
7860 ;; Check for special formatting.
7861 (setq i -1)
7862 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7863 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7864 ;; Check if there is an explicit width specified
7865 (when narrow
7866 (setq c column fmax nil)
7867 (while c
7868 (setq e (pop c))
7869 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
7870 (setq fmax (string-to-number (match-string 1 e)) c nil)))
7871 ;; Find fields that are wider than fmax, and shorten them
7872 (when fmax
7873 (loop for xx in column do
7874 (when (and (stringp xx)
7875 (> (org-string-width xx) fmax))
7876 (org-add-props xx nil
7877 'help-echo
7878 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
7879 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
7880 (unless (> f1 1)
7881 (error "Cannot narrow field starting with wide link \"%s\""
7882 (match-string 0 xx)))
7883 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
7884 (add-text-properties (- f1 2) f1
7885 (list 'display org-narrow-column-arrow)
7886 xx)))))
7887 ;; Get the maximum width for each column
7888 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
7889 ;; Get the fraction of numbers, to decide about alignment of the column
7890 (setq cnt 0 frac 0.0)
7891 (loop for x in column do
7892 (if (equal x "")
7893 nil
7894 (setq frac ( / (+ (* frac cnt)
7895 (if (string-match org-table-number-regexp x) 1 0))
7896 (setq cnt (1+ cnt))))))
7897 (push (>= frac org-table-number-fraction) typenums))
7898 (setq lengths (nreverse lengths) typenums (nreverse typenums))
7899
7900 ;; Store the alignment of this table, for later editing of single fields
7901 (setq org-table-last-alignment typenums
7902 org-table-last-column-widths lengths)
7903
7904 ;; With invisible characters, `format' does not get the field width right
7905 ;; So we need to make these fields wide by hand.
7906 (when links
7907 (loop for i from 0 upto (1- maxfields) do
7908 (setq len (nth i lengths))
7909 (loop for j from 0 upto (1- (length fields)) do
7910 (setq c (nthcdr i (car (nthcdr j fields))))
7911 (if (and (stringp (car c))
7912 (string-match org-bracket-link-regexp (car c))
7913 (< (org-string-width (car c)) len))
7914 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
7915
7916 ;; Compute the formats needed for output of the table
7917 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7918 (while (setq l (pop lengths))
7919 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7920 (setq rfmt (concat rfmt (format rfmt1 ty l))
7921 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7922 (setq rfmt (concat rfmt "\n")
7923 hfmt (concat (substring hfmt 0 -1) "|\n"))
7924
7925 (setq new (mapconcat
7926 (lambda (l)
7927 (if l (apply 'format rfmt
7928 (append (pop fields) emptystrings))
7929 hfmt))
7930 lines ""))
7931 ;; Replace the old one
7932 (delete-region beg end)
7933 (move-marker end nil)
7934 (move-marker org-table-aligned-begin-marker (point))
7935 (insert new)
7936 (move-marker org-table-aligned-end-marker (point))
7937 (when (and orgtbl-mode (not (org-mode-p)))
7938 (goto-char org-table-aligned-begin-marker)
7939 (while (org-hide-wide-columns org-table-aligned-end-marker)))
7940 ;; Try to move to the old location
7941 (goto-line winstartline)
7942 (setq winstart (point-at-bol))
7943 (goto-line linepos)
7944 (set-window-start (selected-window) winstart 'noforce)
7945 (org-table-goto-column colpos)
7946 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
7947 (setq org-table-may-need-update nil)
7948 ))
7949
7950 (defun org-string-width (s)
7951 "Compute width of string, ignoring invisible characters.
7952 This ignores character with invisibility property `org-link', and also
7953 characters with property `org-cwidth', because these will become invisible
7954 upon the next fontification round."
7955 (let (b l)
7956 (when (or (eq t buffer-invisibility-spec)
7957 (assq 'org-link buffer-invisibility-spec))
7958 (while (setq b (text-property-any 0 (length s)
7959 'invisible 'org-link s))
7960 (setq s (concat (substring s 0 b)
7961 (substring s (or (next-single-property-change
7962 b 'invisible s) (length s)))))))
7963 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
7964 (setq s (concat (substring s 0 b)
7965 (substring s (or (next-single-property-change
7966 b 'org-cwidth s) (length s))))))
7967 (setq l (string-width s) b -1)
7968 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
7969 (setq l (- l (get-text-property b 'org-dwidth-n s))))
7970 l))
7971
7972 (defun org-table-begin (&optional table-type)
7973 "Find the beginning of the table and return its position.
7974 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7975 (save-excursion
7976 (if (not (re-search-backward
7977 (if table-type org-table-any-border-regexp
7978 org-table-border-regexp)
7979 nil t))
7980 (progn (goto-char (point-min)) (point))
7981 (goto-char (match-beginning 0))
7982 (beginning-of-line 2)
7983 (point))))
7984
7985 (defun org-table-end (&optional table-type)
7986 "Find the end of the table and return its position.
7987 With argument TABLE-TYPE, go to the end of a table.el-type table."
7988 (save-excursion
7989 (if (not (re-search-forward
7990 (if table-type org-table-any-border-regexp
7991 org-table-border-regexp)
7992 nil t))
7993 (goto-char (point-max))
7994 (goto-char (match-beginning 0)))
7995 (point-marker)))
7996
7997 (defun org-table-justify-field-maybe (&optional new)
7998 "Justify the current field, text to left, number to right.
7999 Optional argument NEW may specify text to replace the current field content."
8000 (cond
8001 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8002 ((org-at-table-hline-p))
8003 ((and (not new)
8004 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8005 (current-buffer)))
8006 (< (point) org-table-aligned-begin-marker)
8007 (>= (point) org-table-aligned-end-marker)))
8008 ;; This is not the same table, force a full re-align
8009 (setq org-table-may-need-update t))
8010 (t ;; realign the current field, based on previous full realign
8011 (let* ((pos (point)) s
8012 (col (org-table-current-column))
8013 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8014 l f n o e)
8015 (when (> col 0)
8016 (skip-chars-backward "^|\n")
8017 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8018 (progn
8019 (setq s (match-string 1)
8020 o (match-string 0)
8021 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8022 e (not (= (match-beginning 2) (match-end 2))))
8023 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8024 l (if e "|" (setq org-table-may-need-update t) ""))
8025 n (format f s))
8026 (if new
8027 (if (<= (length new) l) ;; FIXME: length -> str-width?
8028 (setq n (format f new))
8029 (setq n (concat new "|") org-table-may-need-update t)))
8030 (or (equal n o)
8031 (let (org-table-may-need-update)
8032 (replace-match n t t))))
8033 (setq org-table-may-need-update t))
8034 (goto-char pos))))))
8035
8036 (defun org-table-next-field ()
8037 "Go to the next field in the current table, creating new lines as needed.
8038 Before doing so, re-align the table if necessary."
8039 (interactive)
8040 (org-table-maybe-eval-formula)
8041 (org-table-maybe-recalculate-line)
8042 (if (and org-table-automatic-realign
8043 org-table-may-need-update)
8044 (org-table-align))
8045 (let ((end (org-table-end)))
8046 (if (org-at-table-hline-p)
8047 (end-of-line 1))
8048 (condition-case nil
8049 (progn
8050 (re-search-forward "|" end)
8051 (if (looking-at "[ \t]*$")
8052 (re-search-forward "|" end))
8053 (if (and (looking-at "-")
8054 org-table-tab-jumps-over-hlines
8055 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8056 (goto-char (match-beginning 1)))
8057 (if (looking-at "-")
8058 (progn
8059 (beginning-of-line 0)
8060 (org-table-insert-row 'below))
8061 (if (looking-at " ") (forward-char 1))))
8062 (error
8063 (org-table-insert-row 'below)))))
8064
8065 (defun org-table-previous-field ()
8066 "Go to the previous field in the table.
8067 Before doing so, re-align the table if necessary."
8068 (interactive)
8069 (org-table-justify-field-maybe)
8070 (org-table-maybe-recalculate-line)
8071 (if (and org-table-automatic-realign
8072 org-table-may-need-update)
8073 (org-table-align))
8074 (if (org-at-table-hline-p)
8075 (end-of-line 1))
8076 (re-search-backward "|" (org-table-begin))
8077 (re-search-backward "|" (org-table-begin))
8078 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8079 (re-search-backward "|" (org-table-begin)))
8080 (if (looking-at "| ?")
8081 (goto-char (match-end 0))))
8082
8083 (defun org-table-next-row ()
8084 "Go to the next row (same column) in the current table.
8085 Before doing so, re-align the table if necessary."
8086 (interactive)
8087 (org-table-maybe-eval-formula)
8088 (org-table-maybe-recalculate-line)
8089 (if (or (looking-at "[ \t]*$")
8090 (save-excursion (skip-chars-backward " \t") (bolp)))
8091 (newline)
8092 (if (and org-table-automatic-realign
8093 org-table-may-need-update)
8094 (org-table-align))
8095 (let ((col (org-table-current-column)))
8096 (beginning-of-line 2)
8097 (if (or (not (org-at-table-p))
8098 (org-at-table-hline-p))
8099 (progn
8100 (beginning-of-line 0)
8101 (org-table-insert-row 'below)))
8102 (org-table-goto-column col)
8103 (skip-chars-backward "^|\n\r")
8104 (if (looking-at " ") (forward-char 1)))))
8105
8106 (defun org-table-copy-down (n)
8107 "Copy a field down in the current column.
8108 If the field at the cursor is empty, copy into it the content of the nearest
8109 non-empty field above. With argument N, use the Nth non-empty field.
8110 If the current field is not empty, it is copied down to the next row, and
8111 the cursor is moved with it. Therefore, repeating this command causes the
8112 column to be filled row-by-row.
8113 If the variable `org-table-copy-increment' is non-nil and the field is an
8114 integer or a timestamp, it will be incremented while copying. In the case of
8115 a timestamp, if the cursor is on the year, change the year. If it is on the
8116 month or the day, change that. Point will stay on the current date field
8117 in order to easily repeat the interval."
8118 (interactive "p")
8119 (let* ((colpos (org-table-current-column))
8120 (col (current-column))
8121 (field (org-table-get-field))
8122 (non-empty (string-match "[^ \t]" field))
8123 (beg (org-table-begin))
8124 txt)
8125 (org-table-check-inside-data-field)
8126 (if non-empty
8127 (progn
8128 (setq txt (org-trim field))
8129 (org-table-next-row)
8130 (org-table-blank-field))
8131 (save-excursion
8132 (setq txt
8133 (catch 'exit
8134 (while (progn (beginning-of-line 1)
8135 (re-search-backward org-table-dataline-regexp
8136 beg t))
8137 (org-table-goto-column colpos t)
8138 (if (and (looking-at
8139 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8140 (= (setq n (1- n)) 0))
8141 (throw 'exit (match-string 1))))))))
8142 (if txt
8143 (progn
8144 (if (and org-table-copy-increment
8145 (string-match "^[0-9]+$" txt))
8146 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8147 (insert txt)
8148 (move-to-column col)
8149 (if (and org-table-copy-increment (org-at-timestamp-p t))
8150 (org-timestamp-up 1)
8151 (org-table-maybe-recalculate-line))
8152 (org-table-align)
8153 (move-to-column col))
8154 (error "No non-empty field found"))))
8155
8156 (defun org-table-check-inside-data-field ()
8157 "Is point inside a table data field?
8158 I.e. not on a hline or before the first or after the last column?
8159 This actually throws an error, so it aborts the current command."
8160 (if (or (not (org-at-table-p))
8161 (= (org-table-current-column) 0)
8162 (org-at-table-hline-p)
8163 (looking-at "[ \t]*$"))
8164 (error "Not in table data field")))
8165
8166 (defvar org-table-clip nil
8167 "Clipboard for table regions.")
8168
8169 (defun org-table-blank-field ()
8170 "Blank the current table field or active region."
8171 (interactive)
8172 (org-table-check-inside-data-field)
8173 (if (and (interactive-p) (org-region-active-p))
8174 (let (org-table-clip)
8175 (org-table-cut-region (region-beginning) (region-end)))
8176 (skip-chars-backward "^|")
8177 (backward-char 1)
8178 (if (looking-at "|[^|\n]+")
8179 (let* ((pos (match-beginning 0))
8180 (match (match-string 0))
8181 (len (org-string-width match)))
8182 (replace-match (concat "|" (make-string (1- len) ?\ )))
8183 (goto-char (+ 2 pos))
8184 (substring match 1)))))
8185
8186 (defun org-table-get-field (&optional n replace)
8187 "Return the value of the field in column N of current row.
8188 N defaults to current field.
8189 If REPLACE is a string, replace field with this value. The return value
8190 is always the old value."
8191 (and n (org-table-goto-column n))
8192 (skip-chars-backward "^|\n")
8193 (backward-char 1)
8194 (if (looking-at "|[^|\r\n]*")
8195 (let* ((pos (match-beginning 0))
8196 (val (buffer-substring (1+ pos) (match-end 0))))
8197 (if replace
8198 (replace-match (concat "|" replace) t t))
8199 (goto-char (min (point-at-eol) (+ 2 pos)))
8200 val)
8201 (forward-char 1) ""))
8202
8203 (defun org-table-field-info (arg)
8204 "Show info about the current field, and highlight any reference at point."
8205 (interactive "P")
8206 (org-table-get-specials)
8207 (save-excursion
8208 (let* ((pos (point))
8209 (col (org-table-current-column))
8210 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8211 (name (car (rassoc (list (org-current-line) col)
8212 org-table-named-field-locations)))
8213 (eql (org-table-get-stored-formulas))
8214 (dline (org-table-current-dline))
8215 (ref (format "@%d$%d" dline col))
8216 (ref1 (org-table-convert-refs-to-an ref))
8217 (fequation (or (assoc name eql) (assoc ref eql)))
8218 (cequation (assoc (int-to-string col) eql))
8219 (eqn (or fequation cequation)))
8220 (goto-char pos)
8221 (condition-case nil
8222 (org-table-show-reference 'local)
8223 (error nil))
8224 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8225 dline col
8226 (if cname (concat " or $" cname) "")
8227 dline col ref1
8228 (if name (concat " or $" name) "")
8229 ;; FIXME: formula info not correct if special table line
8230 (if eqn
8231 (concat ", formula: "
8232 (org-table-formula-to-user
8233 (concat
8234 (if (string-match "^[$@]"(car eqn)) "" "$")
8235 (car eqn) "=" (cdr eqn))))
8236 "")))))
8237
8238 (defun org-table-current-column ()
8239 "Find out which column we are in.
8240 When called interactively, column is also displayed in echo area."
8241 (interactive)
8242 (if (interactive-p) (org-table-check-inside-data-field))
8243 (save-excursion
8244 (let ((cnt 0) (pos (point)))
8245 (beginning-of-line 1)
8246 (while (search-forward "|" pos t)
8247 (setq cnt (1+ cnt)))
8248 (if (interactive-p) (message "This is table column %d" cnt))
8249 cnt)))
8250
8251 (defun org-table-current-dline ()
8252 "Find out what table data line we are in.
8253 Only datalins count for this."
8254 (interactive)
8255 (if (interactive-p) (org-table-check-inside-data-field))
8256 (save-excursion
8257 (let ((cnt 0) (pos (point)))
8258 (goto-char (org-table-begin))
8259 (while (<= (point) pos)
8260 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8261 (beginning-of-line 2))
8262 (if (interactive-p) (message "This is table line %d" cnt))
8263 cnt)))
8264
8265 (defun org-table-goto-column (n &optional on-delim force)
8266 "Move the cursor to the Nth column in the current table line.
8267 With optional argument ON-DELIM, stop with point before the left delimiter
8268 of the field.
8269 If there are less than N fields, just go to after the last delimiter.
8270 However, when FORCE is non-nil, create new columns if necessary."
8271 (interactive "p")
8272 (let ((pos (point-at-eol)))
8273 (beginning-of-line 1)
8274 (when (> n 0)
8275 (while (and (> (setq n (1- n)) -1)
8276 (or (search-forward "|" pos t)
8277 (and force
8278 (progn (end-of-line 1)
8279 (skip-chars-backward "^|")
8280 (insert " | "))))))
8281 ; (backward-char 2) t)))))
8282 (when (and force (not (looking-at ".*|")))
8283 (save-excursion (end-of-line 1) (insert " | ")))
8284 (if on-delim
8285 (backward-char 1)
8286 (if (looking-at " ") (forward-char 1))))))
8287
8288 (defun org-at-table-p (&optional table-type)
8289 "Return t if the cursor is inside an org-type table.
8290 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8291 (if org-enable-table-editor
8292 (save-excursion
8293 (beginning-of-line 1)
8294 (looking-at (if table-type org-table-any-line-regexp
8295 org-table-line-regexp)))
8296 nil))
8297
8298 (defun org-at-table.el-p ()
8299 "Return t if and only if we are at a table.el table."
8300 (and (org-at-table-p 'any)
8301 (save-excursion
8302 (goto-char (org-table-begin 'any))
8303 (looking-at org-table1-hline-regexp))))
8304
8305 (defun org-table-recognize-table.el ()
8306 "If there is a table.el table nearby, recognize it and move into it."
8307 (if org-table-tab-recognizes-table.el
8308 (if (org-at-table.el-p)
8309 (progn
8310 (beginning-of-line 1)
8311 (if (looking-at org-table-dataline-regexp)
8312 nil
8313 (if (looking-at org-table1-hline-regexp)
8314 (progn
8315 (beginning-of-line 2)
8316 (if (looking-at org-table-any-border-regexp)
8317 (beginning-of-line -1)))))
8318 (if (re-search-forward "|" (org-table-end t) t)
8319 (progn
8320 (require 'table)
8321 (if (table--at-cell-p (point))
8322 t
8323 (message "recognizing table.el table...")
8324 (table-recognize-table)
8325 (message "recognizing table.el table...done")))
8326 (error "This should not happen..."))
8327 t)
8328 nil)
8329 nil))
8330
8331 (defun org-at-table-hline-p ()
8332 "Return t if the cursor is inside a hline in a table."
8333 (if org-enable-table-editor
8334 (save-excursion
8335 (beginning-of-line 1)
8336 (looking-at org-table-hline-regexp))
8337 nil))
8338
8339 (defun org-table-insert-column ()
8340 "Insert a new column into the table."
8341 (interactive)
8342 (if (not (org-at-table-p))
8343 (error "Not at a table"))
8344 (org-table-find-dataline)
8345 (let* ((col (max 1 (org-table-current-column)))
8346 (beg (org-table-begin))
8347 (end (org-table-end))
8348 ;; Current cursor position
8349 (linepos (org-current-line))
8350 (colpos col))
8351 (goto-char beg)
8352 (while (< (point) end)
8353 (if (org-at-table-hline-p)
8354 nil
8355 (org-table-goto-column col t)
8356 (insert "| "))
8357 (beginning-of-line 2))
8358 (move-marker end nil)
8359 (goto-line linepos)
8360 (org-table-goto-column colpos)
8361 (org-table-align)
8362 (org-table-fix-formulas "$" nil (1- col) 1)))
8363
8364 (defun org-table-find-dataline ()
8365 "Find a dataline in the current table, which is needed for column commands."
8366 (if (and (org-at-table-p)
8367 (not (org-at-table-hline-p)))
8368 t
8369 (let ((col (current-column))
8370 (end (org-table-end)))
8371 (move-to-column col)
8372 (while (and (< (point) end)
8373 (or (not (= (current-column) col))
8374 (org-at-table-hline-p)))
8375 (beginning-of-line 2)
8376 (move-to-column col))
8377 (if (and (org-at-table-p)
8378 (not (org-at-table-hline-p)))
8379 t
8380 (error
8381 "Please position cursor in a data line for column operations")))))
8382
8383 (defun org-table-delete-column ()
8384 "Delete a column from the table."
8385 (interactive)
8386 (if (not (org-at-table-p))
8387 (error "Not at a table"))
8388 (org-table-find-dataline)
8389 (org-table-check-inside-data-field)
8390 (let* ((col (org-table-current-column))
8391 (beg (org-table-begin))
8392 (end (org-table-end))
8393 ;; Current cursor position
8394 (linepos (org-current-line))
8395 (colpos col))
8396 (goto-char beg)
8397 (while (< (point) end)
8398 (if (org-at-table-hline-p)
8399 nil
8400 (org-table-goto-column col t)
8401 (and (looking-at "|[^|\n]+|")
8402 (replace-match "|")))
8403 (beginning-of-line 2))
8404 (move-marker end nil)
8405 (goto-line linepos)
8406 (org-table-goto-column colpos)
8407 (org-table-align)
8408 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8409 col -1 col)))
8410
8411 (defun org-table-move-column-right ()
8412 "Move column to the right."
8413 (interactive)
8414 (org-table-move-column nil))
8415 (defun org-table-move-column-left ()
8416 "Move column to the left."
8417 (interactive)
8418 (org-table-move-column 'left))
8419
8420 (defun org-table-move-column (&optional left)
8421 "Move the current column to the right. With arg LEFT, move to the left."
8422 (interactive "P")
8423 (if (not (org-at-table-p))
8424 (error "Not at a table"))
8425 (org-table-find-dataline)
8426 (org-table-check-inside-data-field)
8427 (let* ((col (org-table-current-column))
8428 (col1 (if left (1- col) col))
8429 (beg (org-table-begin))
8430 (end (org-table-end))
8431 ;; Current cursor position
8432 (linepos (org-current-line))
8433 (colpos (if left (1- col) (1+ col))))
8434 (if (and left (= col 1))
8435 (error "Cannot move column further left"))
8436 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8437 (error "Cannot move column further right"))
8438 (goto-char beg)
8439 (while (< (point) end)
8440 (if (org-at-table-hline-p)
8441 nil
8442 (org-table-goto-column col1 t)
8443 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8444 (replace-match "|\\2|\\1|")))
8445 (beginning-of-line 2))
8446 (move-marker end nil)
8447 (goto-line linepos)
8448 (org-table-goto-column colpos)
8449 (org-table-align)
8450 (org-table-fix-formulas
8451 "$" (list (cons (number-to-string col) (number-to-string colpos))
8452 (cons (number-to-string colpos) (number-to-string col))))))
8453
8454 (defun org-table-move-row-down ()
8455 "Move table row down."
8456 (interactive)
8457 (org-table-move-row nil))
8458 (defun org-table-move-row-up ()
8459 "Move table row up."
8460 (interactive)
8461 (org-table-move-row 'up))
8462
8463 (defun org-table-move-row (&optional up)
8464 "Move the current table line down. With arg UP, move it up."
8465 (interactive "P")
8466 (let* ((col (current-column))
8467 (pos (point))
8468 (hline1p (save-excursion (beginning-of-line 1)
8469 (looking-at org-table-hline-regexp)))
8470 (dline1 (org-table-current-dline))
8471 (dline2 (+ dline1 (if up -1 1)))
8472 (tonew (if up 0 2))
8473 txt hline2p)
8474 (beginning-of-line tonew)
8475 (unless (org-at-table-p)
8476 (goto-char pos)
8477 (error "Cannot move row further"))
8478 (setq hline2p (looking-at org-table-hline-regexp))
8479 (goto-char pos)
8480 (beginning-of-line 1)
8481 (setq pos (point))
8482 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8483 (delete-region (point) (1+ (point-at-eol)))
8484 (beginning-of-line tonew)
8485 (insert txt)
8486 (beginning-of-line 0)
8487 (move-to-column col)
8488 (unless (or hline1p hline2p)
8489 (org-table-fix-formulas
8490 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8491 (cons (number-to-string dline2) (number-to-string dline1)))))))
8492
8493 (defun org-table-insert-row (&optional arg)
8494 "Insert a new row above the current line into the table.
8495 With prefix ARG, insert below the current line."
8496 (interactive "P")
8497 (if (not (org-at-table-p))
8498 (error "Not at a table"))
8499 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8500 (new (org-table-clean-line line)))
8501 ;; Fix the first field if necessary
8502 (if (string-match "^[ \t]*| *[#$] *|" line)
8503 (setq new (replace-match (match-string 0 line) t t new)))
8504 (beginning-of-line (if arg 2 1))
8505 (let (org-table-may-need-update) (insert-before-markers new "\n"))
8506 (beginning-of-line 0)
8507 (re-search-forward "| ?" (point-at-eol) t)
8508 (and (or org-table-may-need-update org-table-overlay-coordinates)
8509 (org-table-align))
8510 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8511
8512 (defun org-table-insert-hline (&optional above)
8513 "Insert a horizontal-line below the current line into the table.
8514 With prefix ABOVE, insert above the current line."
8515 (interactive "P")
8516 (if (not (org-at-table-p))
8517 (error "Not at a table"))
8518 (let ((line (org-table-clean-line
8519 (buffer-substring (point-at-bol) (point-at-eol))))
8520 (col (current-column)))
8521 (while (string-match "|\\( +\\)|" line)
8522 (setq line (replace-match
8523 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8524 ?-) "|") t t line)))
8525 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8526 (beginning-of-line (if above 1 2))
8527 (insert line "\n")
8528 (beginning-of-line (if above 1 -1))
8529 (move-to-column col)
8530 (and org-table-overlay-coordinates (org-table-align))))
8531
8532 (defun org-table-hline-and-move (&optional same-column)
8533 "Insert a hline and move to the row below that line."
8534 (interactive "P")
8535 (let ((col (org-table-current-column)))
8536 (org-table-maybe-eval-formula)
8537 (org-table-maybe-recalculate-line)
8538 (org-table-insert-hline)
8539 (end-of-line 2)
8540 (if (looking-at "\n[ \t]*|-")
8541 (progn (insert "\n|") (org-table-align))
8542 (org-table-next-field))
8543 (if same-column (org-table-goto-column col))))
8544
8545 (defun org-table-clean-line (s)
8546 "Convert a table line S into a string with only \"|\" and space.
8547 In particular, this does handle wide and invisible characters."
8548 (if (string-match "^[ \t]*|-" s)
8549 ;; It's a hline, just map the characters
8550 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
8551 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8552 (setq s (replace-match
8553 (concat "|" (make-string (org-string-width (match-string 1 s))
8554 ?\ ) "|")
8555 t t s)))
8556 s))
8557
8558 (defun org-table-kill-row ()
8559 "Delete the current row or horizontal line from the table."
8560 (interactive)
8561 (if (not (org-at-table-p))
8562 (error "Not at a table"))
8563 (let ((col (current-column))
8564 (dline (org-table-current-dline)))
8565 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8566 (if (not (org-at-table-p)) (beginning-of-line 0))
8567 (move-to-column col)
8568 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
8569 dline -1 dline)))
8570
8571 (defun org-table-sort-lines (with-case &optional sorting-type)
8572 "Sort table lines according to the column at point.
8573
8574 The position of point indicates the column to be used for
8575 sorting, and the range of lines is the range between the nearest
8576 horizontal separator lines, or the entire table of no such lines
8577 exist. If point is before the first column, you will be prompted
8578 for the sorting column. If there is an active region, the mark
8579 specifies the first line and the sorting column, while point
8580 should be in the last line to be included into the sorting.
8581
8582 The command then prompts for the sorting type which can be
8583 alphabetically, numerically, or by time (as given in a time stamp
8584 in the field). Sorting in reverse order is also possible.
8585
8586 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
8587
8588 If SORTING-TYPE is specified when this function is called from a Lisp
8589 program, no prompting will take place. SORTING-TYPE must be a character,
8590 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
8591 should be done in reverse order."
8592 (interactive "P")
8593 (let* ((thisline (org-current-line))
8594 (thiscol (org-table-current-column))
8595 beg end bcol ecol tend tbeg column lns pos)
8596 (when (equal thiscol 0)
8597 (if (interactive-p)
8598 (setq thiscol
8599 (string-to-number
8600 (read-string "Use column N for sorting: ")))
8601 (setq thiscol 1))
8602 (org-table-goto-column thiscol))
8603 (org-table-check-inside-data-field)
8604 (if (org-region-active-p)
8605 (progn
8606 (setq beg (region-beginning) end (region-end))
8607 (goto-char beg)
8608 (setq column (org-table-current-column)
8609 beg (point-at-bol))
8610 (goto-char end)
8611 (setq end (point-at-bol 2)))
8612 (setq column (org-table-current-column)
8613 pos (point)
8614 tbeg (org-table-begin)
8615 tend (org-table-end))
8616 (if (re-search-backward org-table-hline-regexp tbeg t)
8617 (setq beg (point-at-bol 2))
8618 (goto-char tbeg)
8619 (setq beg (point-at-bol 1)))
8620 (goto-char pos)
8621 (if (re-search-forward org-table-hline-regexp tend t)
8622 (setq end (point-at-bol 1))
8623 (goto-char tend)
8624 (setq end (point-at-bol))))
8625 (setq beg (move-marker (make-marker) beg)
8626 end (move-marker (make-marker) end))
8627 (untabify beg end)
8628 (goto-char beg)
8629 (org-table-goto-column column)
8630 (skip-chars-backward "^|")
8631 (setq bcol (current-column))
8632 (org-table-goto-column (1+ column))
8633 (skip-chars-backward "^|")
8634 (setq ecol (1- (current-column)))
8635 (org-table-goto-column column)
8636 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8637 (org-split-string (buffer-substring beg end) "\n")))
8638 (setq lns (org-do-sort lns "Table" with-case sorting-type))
8639 (delete-region beg end)
8640 (move-marker beg nil)
8641 (move-marker end nil)
8642 (insert (mapconcat 'cdr lns "\n") "\n")
8643 (goto-line thisline)
8644 (org-table-goto-column thiscol)
8645 (message "%d lines sorted, based on column %d" (length lns) column)))
8646
8647 (defun org-table-cut-region (beg end)
8648 "Copy region in table to the clipboard and blank all relevant fields."
8649 (interactive "r")
8650 (org-table-copy-region beg end 'cut))
8651
8652 (defun org-table-copy-region (beg end &optional cut)
8653 "Copy rectangular region in table to clipboard.
8654 A special clipboard is used which can only be accessed
8655 with `org-table-paste-rectangle'."
8656 (interactive "rP")
8657 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8658 region cols
8659 (rpl (if cut " " nil)))
8660 (goto-char beg)
8661 (org-table-check-inside-data-field)
8662 (setq l01 (org-current-line)
8663 c01 (org-table-current-column))
8664 (goto-char end)
8665 (org-table-check-inside-data-field)
8666 (setq l02 (org-current-line)
8667 c02 (org-table-current-column))
8668 (setq l1 (min l01 l02) l2 (max l01 l02)
8669 c1 (min c01 c02) c2 (max c01 c02))
8670 (catch 'exit
8671 (while t
8672 (catch 'nextline
8673 (if (> l1 l2) (throw 'exit t))
8674 (goto-line l1)
8675 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8676 (setq cols nil ic1 c1 ic2 c2)
8677 (while (< ic1 (1+ ic2))
8678 (push (org-table-get-field ic1 rpl) cols)
8679 (setq ic1 (1+ ic1)))
8680 (push (nreverse cols) region)
8681 (setq l1 (1+ l1)))))
8682 (setq org-table-clip (nreverse region))
8683 (if cut (org-table-align))
8684 org-table-clip))
8685
8686 (defun org-table-paste-rectangle ()
8687 "Paste a rectangular region into a table.
8688 The upper right corner ends up in the current field. All involved fields
8689 will be overwritten. If the rectangle does not fit into the present table,
8690 the table is enlarged as needed. The process ignores horizontal separator
8691 lines."
8692 (interactive)
8693 (unless (and org-table-clip (listp org-table-clip))
8694 (error "First cut/copy a region to paste!"))
8695 (org-table-check-inside-data-field)
8696 (let* ((clip org-table-clip)
8697 (line (org-current-line))
8698 (col (org-table-current-column))
8699 (org-enable-table-editor t)
8700 (org-table-automatic-realign nil)
8701 c cols field)
8702 (while (setq cols (pop clip))
8703 (while (org-at-table-hline-p) (beginning-of-line 2))
8704 (if (not (org-at-table-p))
8705 (progn (end-of-line 0) (org-table-next-field)))
8706 (setq c col)
8707 (while (setq field (pop cols))
8708 (org-table-goto-column c nil 'force)
8709 (org-table-get-field nil field)
8710 (setq c (1+ c)))
8711 (beginning-of-line 2))
8712 (goto-line line)
8713 (org-table-goto-column col)
8714 (org-table-align)))
8715
8716 (defun org-table-convert ()
8717 "Convert from `org-mode' table to table.el and back.
8718 Obviously, this only works within limits. When an Org-mode table is
8719 converted to table.el, all horizontal separator lines get lost, because
8720 table.el uses these as cell boundaries and has no notion of horizontal lines.
8721 A table.el table can be converted to an Org-mode table only if it does not
8722 do row or column spanning. Multiline cells will become multiple cells.
8723 Beware, Org-mode does not test if the table can be successfully converted - it
8724 blindly applies a recipe that works for simple tables."
8725 (interactive)
8726 (require 'table)
8727 (if (org-at-table.el-p)
8728 ;; convert to Org-mode table
8729 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8730 (end (move-marker (make-marker) (org-table-end t))))
8731 (table-unrecognize-region beg end)
8732 (goto-char beg)
8733 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8734 (replace-match ""))
8735 (goto-char beg))
8736 (if (org-at-table-p)
8737 ;; convert to table.el table
8738 (let ((beg (move-marker (make-marker) (org-table-begin)))
8739 (end (move-marker (make-marker) (org-table-end))))
8740 ;; first, get rid of all horizontal lines
8741 (goto-char beg)
8742 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8743 (replace-match ""))
8744 ;; insert a hline before first
8745 (goto-char beg)
8746 (org-table-insert-hline 'above)
8747 (beginning-of-line -1)
8748 ;; insert a hline after each line
8749 (while (progn (beginning-of-line 3) (< (point) end))
8750 (org-table-insert-hline))
8751 (goto-char beg)
8752 (setq end (move-marker end (org-table-end)))
8753 ;; replace "+" at beginning and ending of hlines
8754 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8755 (replace-match "\\1+-"))
8756 (goto-char beg)
8757 (while (re-search-forward "-|[ \t]*$" end t)
8758 (replace-match "-+"))
8759 (goto-char beg)))))
8760
8761 (defun org-table-wrap-region (arg)
8762 "Wrap several fields in a column like a paragraph.
8763 This is useful if you'd like to spread the contents of a field over several
8764 lines, in order to keep the table compact.
8765
8766 If there is an active region, and both point and mark are in the same column,
8767 the text in the column is wrapped to minimum width for the given number of
8768 lines. Generally, this makes the table more compact. A prefix ARG may be
8769 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8770 formats the selected text to two lines. If the region was longer than two
8771 lines, the remaining lines remain empty. A negative prefix argument reduces
8772 the current number of lines by that amount. The wrapped text is pasted back
8773 into the table. If you formatted it to more lines than it was before, fields
8774 further down in the table get overwritten - so you might need to make space in
8775 the table first.
8776
8777 If there is no region, the current field is split at the cursor position and
8778 the text fragment to the right of the cursor is prepended to the field one
8779 line down.
8780
8781 If there is no region, but you specify a prefix ARG, the current field gets
8782 blank, and the content is appended to the field above."
8783 (interactive "P")
8784 (org-table-check-inside-data-field)
8785 (if (org-region-active-p)
8786 ;; There is a region: fill as a paragraph
8787 (let* ((beg (region-beginning))
8788 (cline (save-excursion (goto-char beg) (org-current-line)))
8789 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
8790 nlines)
8791 (org-table-cut-region (region-beginning) (region-end))
8792 (if (> (length (car org-table-clip)) 1)
8793 (error "Region must be limited to single column"))
8794 (setq nlines (if arg
8795 (if (< arg 1)
8796 (+ (length org-table-clip) arg)
8797 arg)
8798 (length org-table-clip)))
8799 (setq org-table-clip
8800 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8801 nil nlines)))
8802 (goto-line cline)
8803 (org-table-goto-column ccol)
8804 (org-table-paste-rectangle))
8805 ;; No region, split the current field at point
8806 (if arg
8807 ;; combine with field above
8808 (let ((s (org-table-blank-field))
8809 (col (org-table-current-column)))
8810 (beginning-of-line 0)
8811 (while (org-at-table-hline-p) (beginning-of-line 0))
8812 (org-table-goto-column col)
8813 (skip-chars-forward "^|")
8814 (skip-chars-backward " ")
8815 (insert " " (org-trim s))
8816 (org-table-align))
8817 ;; split field
8818 (when (looking-at "\\([^|]+\\)+|")
8819 (let ((s (match-string 1)))
8820 (replace-match " |")
8821 (goto-char (match-beginning 0))
8822 (org-table-next-row)
8823 (insert (org-trim s) " ")
8824 (org-table-align))))))
8825
8826 (defvar org-field-marker nil)
8827
8828 (defun org-table-edit-field (arg)
8829 "Edit table field in a different window.
8830 This is mainly useful for fields that contain hidden parts.
8831 When called with a \\[universal-argument] prefix, just make the full field visible so that
8832 it can be edited in place."
8833 (interactive "P")
8834 (if arg
8835 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
8836 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
8837 (remove-text-properties b e '(org-cwidth t invisible t
8838 display t intangible t))
8839 (if (and (boundp 'font-lock-mode) font-lock-mode)
8840 (font-lock-fontify-block)))
8841 (let ((pos (move-marker (make-marker) (point)))
8842 (field (org-table-get-field))
8843 (cw (current-window-configuration))
8844 p)
8845 (org-switch-to-buffer-other-window "*Org tmp*")
8846 (erase-buffer)
8847 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
8848 (let ((org-inhibit-startup t)) (org-mode))
8849 (goto-char (setq p (point-max)))
8850 (insert (org-trim field))
8851 (remove-text-properties p (point-max)
8852 '(invisible t org-cwidth t display t
8853 intangible t))
8854 (goto-char p)
8855 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
8856 (org-set-local 'org-window-configuration cw)
8857 (org-set-local 'org-field-marker pos)
8858 (message "Edit and finish with C-c C-c"))))
8859
8860 (defun org-table-finish-edit-field ()
8861 "Finish editing a table data field.
8862 Remove all newline characters, insert the result into the table, realign
8863 the table and kill the editing buffer."
8864 (let ((pos org-field-marker)
8865 (cw org-window-configuration)
8866 (cb (current-buffer))
8867 text)
8868 (goto-char (point-min))
8869 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
8870 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
8871 (replace-match " "))
8872 (setq text (org-trim (buffer-string)))
8873 (set-window-configuration cw)
8874 (kill-buffer cb)
8875 (select-window (get-buffer-window (marker-buffer pos)))
8876 (goto-char pos)
8877 (move-marker pos nil)
8878 (org-table-check-inside-data-field)
8879 (org-table-get-field nil text)
8880 (org-table-align)
8881 (message "New field value inserted")))
8882
8883 (defun org-trim (s)
8884 "Remove whitespace at beginning and end of string."
8885 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
8886 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
8887 s)
8888
8889 (defun org-wrap (string &optional width lines)
8890 "Wrap string to either a number of lines, or a width in characters.
8891 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8892 that costs. If there is a word longer than WIDTH, the text is actually
8893 wrapped to the length of that word.
8894 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8895 many lines, whatever width that takes.
8896 The return value is a list of lines, without newlines at the end."
8897 (let* ((words (org-split-string string "[ \t\n]+"))
8898 (maxword (apply 'max (mapcar 'org-string-width words)))
8899 w ll)
8900 (cond (width
8901 (org-do-wrap words (max maxword width)))
8902 (lines
8903 (setq w maxword)
8904 (setq ll (org-do-wrap words maxword))
8905 (if (<= (length ll) lines)
8906 ll
8907 (setq ll words)
8908 (while (> (length ll) lines)
8909 (setq w (1+ w))
8910 (setq ll (org-do-wrap words w)))
8911 ll))
8912 (t (error "Cannot wrap this")))))
8913
8914
8915 (defun org-do-wrap (words width)
8916 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8917 (let (lines line)
8918 (while words
8919 (setq line (pop words))
8920 (while (and words (< (+ (length line) (length (car words))) width))
8921 (setq line (concat line " " (pop words))))
8922 (setq lines (push line lines)))
8923 (nreverse lines)))
8924
8925 (defun org-split-string (string &optional separators)
8926 "Splits STRING into substrings at SEPARATORS.
8927 No empty strings are returned if there are matches at the beginning
8928 and end of string."
8929 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8930 (start 0)
8931 notfirst
8932 (list nil))
8933 (while (and (string-match rexp string
8934 (if (and notfirst
8935 (= start (match-beginning 0))
8936 (< start (length string)))
8937 (1+ start) start))
8938 (< (match-beginning 0) (length string)))
8939 (setq notfirst t)
8940 (or (eq (match-beginning 0) 0)
8941 (and (eq (match-beginning 0) (match-end 0))
8942 (eq (match-beginning 0) start))
8943 (setq list
8944 (cons (substring string start (match-beginning 0))
8945 list)))
8946 (setq start (match-end 0)))
8947 (or (eq start (length string))
8948 (setq list
8949 (cons (substring string start)
8950 list)))
8951 (nreverse list)))
8952
8953 (defun org-table-map-tables (function)
8954 "Apply FUNCTION to the start of all tables in the buffer."
8955 (save-excursion
8956 (save-restriction
8957 (widen)
8958 (goto-char (point-min))
8959 (while (re-search-forward org-table-any-line-regexp nil t)
8960 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8961 (beginning-of-line 1)
8962 (if (looking-at org-table-line-regexp)
8963 (save-excursion (funcall function)))
8964 (re-search-forward org-table-any-border-regexp nil 1))))
8965 (message "Mapping tables: done"))
8966
8967 (defvar org-timecnt) ; dynamically scoped parameter
8968
8969 (defun org-table-sum (&optional beg end nlast)
8970 "Sum numbers in region of current table column.
8971 The result will be displayed in the echo area, and will be available
8972 as kill to be inserted with \\[yank].
8973
8974 If there is an active region, it is interpreted as a rectangle and all
8975 numbers in that rectangle will be summed. If there is no active
8976 region and point is located in a table column, sum all numbers in that
8977 column.
8978
8979 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8980 numbers are assumed to be times as well (in decimal hours) and the
8981 numbers are added as such.
8982
8983 If NLAST is a number, only the NLAST fields will actually be summed."
8984 (interactive)
8985 (save-excursion
8986 (let (col (org-timecnt 0) diff h m s org-table-clip)
8987 (cond
8988 ((and beg end)) ; beg and end given explicitly
8989 ((org-region-active-p)
8990 (setq beg (region-beginning) end (region-end)))
8991 (t
8992 (setq col (org-table-current-column))
8993 (goto-char (org-table-begin))
8994 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8995 (error "No table data"))
8996 (org-table-goto-column col)
8997 (setq beg (point))
8998 (goto-char (org-table-end))
8999 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9000 (error "No table data"))
9001 (org-table-goto-column col)
9002 (setq end (point))))
9003 (let* ((items (apply 'append (org-table-copy-region beg end)))
9004 (items1 (cond ((not nlast) items)
9005 ((>= nlast (length items)) items)
9006 (t (setq items (reverse items))
9007 (setcdr (nthcdr (1- nlast) items) nil)
9008 (nreverse items))))
9009 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9010 items1)))
9011 (res (apply '+ numbers))
9012 (sres (if (= org-timecnt 0)
9013 (format "%g" res)
9014 (setq diff (* 3600 res)
9015 h (floor (/ diff 3600)) diff (mod diff 3600)
9016 m (floor (/ diff 60)) diff (mod diff 60)
9017 s diff)
9018 (format "%d:%02d:%02d" h m s))))
9019 (kill-new sres)
9020 (if (interactive-p)
9021 (message "%s"
9022 (substitute-command-keys
9023 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9024 (length numbers) sres))))
9025 sres))))
9026
9027 (defun org-table-get-number-for-summing (s)
9028 (let (n)
9029 (if (string-match "^ *|? *" s)
9030 (setq s (replace-match "" nil nil s)))
9031 (if (string-match " *|? *$" s)
9032 (setq s (replace-match "" nil nil s)))
9033 (setq n (string-to-number s))
9034 (cond
9035 ((and (string-match "0" s)
9036 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9037 ((string-match "\\`[ \t]+\\'" s) nil)
9038 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9039 (let ((h (string-to-number (or (match-string 1 s) "0")))
9040 (m (string-to-number (or (match-string 2 s) "0")))
9041 (s (string-to-number (or (match-string 4 s) "0"))))
9042 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9043 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9044 ((equal n 0) nil)
9045 (t n))))
9046
9047 (defun org-table-current-field-formula (&optional key noerror)
9048 "Return the formula active for the current field.
9049 Assumes that specials are in place.
9050 If KEY is given, return the key to this formula.
9051 Otherwise return the formula preceeded with \"=\" or \":=\"."
9052 (let* ((name (car (rassoc (list (org-current-line)
9053 (org-table-current-column))
9054 org-table-named-field-locations)))
9055 (col (org-table-current-column))
9056 (scol (int-to-string col))
9057 (ref (format "@%d$%d" (org-table-current-dline) col))
9058 (stored-list (org-table-get-stored-formulas noerror))
9059 (ass (or (assoc name stored-list)
9060 (assoc ref stored-list)
9061 (assoc scol stored-list))))
9062 (if key
9063 (car ass)
9064 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9065 (cdr ass))))))
9066
9067 (defun org-table-get-formula (&optional equation named)
9068 "Read a formula from the minibuffer, offer stored formula as default.
9069 When NAMED is non-nil, look for a named equation."
9070 (let* ((stored-list (org-table-get-stored-formulas))
9071 (name (car (rassoc (list (org-current-line)
9072 (org-table-current-column))
9073 org-table-named-field-locations)))
9074 (ref (format "@%d$%d" (org-table-current-dline)
9075 (org-table-current-column)))
9076 (refass (assoc ref stored-list))
9077 (scol (if named
9078 (if name name ref)
9079 (int-to-string (org-table-current-column))))
9080 (dummy (and (or name refass) (not named)
9081 (not (y-or-n-p "Replace field formula with column formula? " ))
9082 (error "Abort")))
9083 (name (or name ref))
9084 (org-table-may-need-update nil)
9085 (stored (cdr (assoc scol stored-list)))
9086 (eq (cond
9087 ((and stored equation (string-match "^ *=? *$" equation))
9088 stored)
9089 ((stringp equation)
9090 equation)
9091 (t (org-table-formula-from-user
9092 (read-string
9093 (org-table-formula-to-user
9094 (format "%s formula %s%s="
9095 (if named "Field" "Column")
9096 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9097 scol))
9098 (if stored (org-table-formula-to-user stored) "")
9099 'org-table-formula-history
9100 )))))
9101 mustsave)
9102 (when (not (string-match "\\S-" eq))
9103 ;; remove formula
9104 (setq stored-list (delq (assoc scol stored-list) stored-list))
9105 (org-table-store-formulas stored-list)
9106 (error "Formula removed"))
9107 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9108 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9109 (if (and name (not named))
9110 ;; We set the column equation, delete the named one.
9111 (setq stored-list (delq (assoc name stored-list) stored-list)
9112 mustsave t))
9113 (if stored
9114 (setcdr (assoc scol stored-list) eq)
9115 (setq stored-list (cons (cons scol eq) stored-list)))
9116 (if (or mustsave (not (equal stored eq)))
9117 (org-table-store-formulas stored-list))
9118 eq))
9119
9120 (defun org-table-store-formulas (alist)
9121 "Store the list of formulas below the current table."
9122 (setq alist (sort alist 'org-table-formula-less-p))
9123 (save-excursion
9124 (goto-char (org-table-end))
9125 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9126 (progn
9127 ;; don't overwrite TBLFM, we might use text properties to store stuff
9128 (goto-char (match-beginning 2))
9129 (delete-region (match-beginning 2) (match-end 0)))
9130 (insert "#+TBLFM:"))
9131 (insert " "
9132 (mapconcat (lambda (x)
9133 (concat
9134 (if (equal (string-to-char (car x)) ?@) "" "$")
9135 (car x) "=" (cdr x)))
9136 alist "::")
9137 "\n")))
9138
9139 (defsubst org-table-formula-make-cmp-string (a)
9140 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9141 (concat
9142 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9143 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9144 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9145
9146 (defun org-table-formula-less-p (a b)
9147 "Compare two formulas for sorting."
9148 (let ((as (org-table-formula-make-cmp-string (car a)))
9149 (bs (org-table-formula-make-cmp-string (car b))))
9150 (and as bs (string< as bs))))
9151
9152 (defun org-table-get-stored-formulas (&optional noerror)
9153 "Return an alist with the stored formulas directly after current table."
9154 (interactive)
9155 (let (scol eq eq-alist strings string seen)
9156 (save-excursion
9157 (goto-char (org-table-end))
9158 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9159 (setq strings (org-split-string (match-string 2) " *:: *"))
9160 (while (setq string (pop strings))
9161 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9162 (setq scol (if (match-end 2)
9163 (match-string 2 string)
9164 (match-string 1 string))
9165 eq (match-string 3 string)
9166 eq-alist (cons (cons scol eq) eq-alist))
9167 (if (member scol seen)
9168 (if noerror
9169 (progn
9170 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9171 (ding)
9172 (sit-for 2))
9173 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9174 (push scol seen))))))
9175 (nreverse eq-alist)))
9176
9177 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9178 "Modify the equations after the table structure has been edited.
9179 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9180 For all numbers larger than LIMIT, shift them by DELTA."
9181 (save-excursion
9182 (goto-char (org-table-end))
9183 (when (looking-at "#\\+TBLFM:")
9184 (let ((re (concat key "\\([0-9]+\\)"))
9185 (re2
9186 (when remove
9187 (if (equal key "$")
9188 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9189 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9190 s n a)
9191 (when remove
9192 (while (re-search-forward re2 (point-at-eol) t)
9193 (replace-match "")))
9194 (while (re-search-forward re (point-at-eol) t)
9195 (setq s (match-string 1) n (string-to-number s))
9196 (cond
9197 ((setq a (assoc s replace))
9198 (replace-match (concat key (cdr a)) t t))
9199 ((and limit (> n limit))
9200 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9201
9202 (defun org-table-get-specials ()
9203 "Get the column names and local parameters for this table."
9204 (save-excursion
9205 (let ((beg (org-table-begin)) (end (org-table-end))
9206 names name fields fields1 field cnt
9207 c v l line col types dlines hlines)
9208 (setq org-table-column-names nil
9209 org-table-local-parameters nil
9210 org-table-named-field-locations nil
9211 org-table-current-begin-line nil
9212 org-table-current-begin-pos nil
9213 org-table-current-line-types nil)
9214 (goto-char beg)
9215 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9216 (setq names (org-split-string (match-string 1) " *| *")
9217 cnt 1)
9218 (while (setq name (pop names))
9219 (setq cnt (1+ cnt))
9220 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9221 (push (cons name (int-to-string cnt)) org-table-column-names))))
9222 (setq org-table-column-names (nreverse org-table-column-names))
9223 (setq org-table-column-name-regexp
9224 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9225 (goto-char beg)
9226 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9227 (setq fields (org-split-string (match-string 1) " *| *"))
9228 (while (setq field (pop fields))
9229 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9230 (push (cons (match-string 1 field) (match-string 2 field))
9231 org-table-local-parameters))))
9232 (goto-char beg)
9233 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9234 (setq c (match-string 1)
9235 fields (org-split-string (match-string 2) " *| *"))
9236 (save-excursion
9237 (beginning-of-line (if (equal c "_") 2 0))
9238 (setq line (org-current-line) col 1)
9239 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9240 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9241 (while (and fields1 (setq field (pop fields)))
9242 (setq v (pop fields1) col (1+ col))
9243 (when (and (stringp field) (stringp v)
9244 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9245 (push (cons field v) org-table-local-parameters)
9246 (push (list field line col) org-table-named-field-locations))))
9247 ;; Analyse the line types
9248 (goto-char beg)
9249 (setq org-table-current-begin-line (org-current-line)
9250 org-table-current-begin-pos (point)
9251 l org-table-current-begin-line)
9252 (while (looking-at "[ \t]*|\\(-\\)?")
9253 (push (if (match-end 1) 'hline 'dline) types)
9254 (if (match-end 1) (push l hlines) (push l dlines))
9255 (beginning-of-line 2)
9256 (setq l (1+ l)))
9257 (setq org-table-current-line-types (apply 'vector (nreverse types))
9258 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9259 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9260
9261 (defun org-table-maybe-eval-formula ()
9262 "Check if the current field starts with \"=\" or \":=\".
9263 If yes, store the formula and apply it."
9264 ;; We already know we are in a table. Get field will only return a formula
9265 ;; when appropriate. It might return a separator line, but no problem.
9266 (when org-table-formula-evaluate-inline
9267 (let* ((field (org-trim (or (org-table-get-field) "")))
9268 named eq)
9269 (when (string-match "^:?=\\(.*\\)" field)
9270 (setq named (equal (string-to-char field) ?:)
9271 eq (match-string 1 field))
9272 (if (or (fboundp 'calc-eval)
9273 (equal (substring eq 0 (min 2 (length eq))) "'("))
9274 (org-table-eval-formula (if named '(4) nil)
9275 (org-table-formula-from-user eq))
9276 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9277
9278 (defvar org-recalc-commands nil
9279 "List of commands triggering the recalculation of a line.
9280 Will be filled automatically during use.")
9281
9282 (defvar org-recalc-marks
9283 '((" " . "Unmarked: no special line, no automatic recalculation")
9284 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9285 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9286 ("!" . "Column name definition line. Reference in formula as $name.")
9287 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9288 ("_" . "Names for values in row below this one.")
9289 ("^" . "Names for values in row above this one.")))
9290
9291 (defun org-table-rotate-recalc-marks (&optional newchar)
9292 "Rotate the recalculation mark in the first column.
9293 If in any row, the first field is not consistent with a mark,
9294 insert a new column for the markers.
9295 When there is an active region, change all the lines in the region,
9296 after prompting for the marking character.
9297 After each change, a message will be displayed indicating the meaning
9298 of the new mark."
9299 (interactive)
9300 (unless (org-at-table-p) (error "Not at a table"))
9301 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9302 (beg (org-table-begin))
9303 (end (org-table-end))
9304 (l (org-current-line))
9305 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9306 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9307 (have-col
9308 (save-excursion
9309 (goto-char beg)
9310 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9311 (col (org-table-current-column))
9312 (forcenew (car (assoc newchar org-recalc-marks)))
9313 epos new)
9314 (when l1
9315 (message "Change region to what mark? Type # * ! $ or SPC: ")
9316 (setq newchar (char-to-string (read-char-exclusive))
9317 forcenew (car (assoc newchar org-recalc-marks))))
9318 (if (and newchar (not forcenew))
9319 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9320 newchar))
9321 (if l1 (goto-line l1))
9322 (save-excursion
9323 (beginning-of-line 1)
9324 (unless (looking-at org-table-dataline-regexp)
9325 (error "Not at a table data line")))
9326 (unless have-col
9327 (org-table-goto-column 1)
9328 (org-table-insert-column)
9329 (org-table-goto-column (1+ col)))
9330 (setq epos (point-at-eol))
9331 (save-excursion
9332 (beginning-of-line 1)
9333 (org-table-get-field
9334 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9335 (concat " "
9336 (setq new (or forcenew
9337 (cadr (member (match-string 1) marks))))
9338 " ")
9339 " # ")))
9340 (if (and l1 l2)
9341 (progn
9342 (goto-line l1)
9343 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9344 (and (looking-at org-table-dataline-regexp)
9345 (org-table-get-field 1 (concat " " new " "))))
9346 (goto-line l1)))
9347 (if (not (= epos (point-at-eol))) (org-table-align))
9348 (goto-line l)
9349 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9350
9351 (defun org-table-maybe-recalculate-line ()
9352 "Recompute the current line if marked for it, and if we haven't just done it."
9353 (interactive)
9354 (and org-table-allow-automatic-line-recalculation
9355 (not (and (memq last-command org-recalc-commands)
9356 (equal org-last-recalc-line (org-current-line))))
9357 (save-excursion (beginning-of-line 1)
9358 (looking-at org-table-auto-recalculate-regexp))
9359 (org-table-recalculate) t))
9360
9361 (defvar org-table-formula-debug nil
9362 "Non-nil means, debug table formulas.
9363 When nil, simply write \"#ERROR\" in corrupted fields.")
9364 (make-variable-buffer-local 'org-table-formula-debug)
9365
9366 (defvar modes)
9367 (defsubst org-set-calc-mode (var &optional value)
9368 (if (stringp var)
9369 (setq var (assoc var '(("D" calc-angle-mode deg)
9370 ("R" calc-angle-mode rad)
9371 ("F" calc-prefer-frac t)
9372 ("S" calc-symbolic-mode t)))
9373 value (nth 2 var) var (nth 1 var)))
9374 (if (memq var modes)
9375 (setcar (cdr (memq var modes)) value)
9376 (cons var (cons value modes)))
9377 modes)
9378
9379 (defun org-table-eval-formula (&optional arg equation
9380 suppress-align suppress-const
9381 suppress-store suppress-analysis)
9382 "Replace the table field value at the cursor by the result of a calculation.
9383
9384 This function makes use of Dave Gillespie's Calc package, in my view the
9385 most exciting program ever written for GNU Emacs. So you need to have Calc
9386 installed in order to use this function.
9387
9388 In a table, this command replaces the value in the current field with the
9389 result of a formula. It also installs the formula as the \"current\" column
9390 formula, by storing it in a special line below the table. When called
9391 with a `C-u' prefix, the current field must ba a named field, and the
9392 formula is installed as valid in only this specific field.
9393
9394 When called with two `C-u' prefixes, insert the active equation
9395 for the field back into the current field, so that it can be
9396 edited there. This is useful in order to use \\[org-table-show-reference]
9397 to check the referenced fields.
9398
9399 When called, the command first prompts for a formula, which is read in
9400 the minibuffer. Previously entered formulas are available through the
9401 history list, and the last used formula is offered as a default.
9402 These stored formulas are adapted correctly when moving, inserting, or
9403 deleting columns with the corresponding commands.
9404
9405 The formula can be any algebraic expression understood by the Calc package.
9406 For details, see the Org-mode manual.
9407
9408 This function can also be called from Lisp programs and offers
9409 additional arguments: EQUATION can be the formula to apply. If this
9410 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9411 used to speed-up recursive calls by by-passing unnecessary aligns.
9412 SUPPRESS-CONST suppresses the interpretation of constants in the
9413 formula, assuming that this has been done already outside the function.
9414 SUPPRESS-STORE means the formula should not be stored, either because
9415 it is already stored, or because it is a modified equation that should
9416 not overwrite the stored one."
9417 (interactive "P")
9418 (org-table-check-inside-data-field)
9419 (or suppress-analysis (org-table-get-specials))
9420 (if (equal arg '(16))
9421 (let ((eq (org-table-current-field-formula)))
9422 (or eq (error "No equation active for current field"))
9423 (org-table-get-field nil eq)
9424 (org-table-align)
9425 (setq org-table-may-need-update t))
9426 (let* (fields
9427 (ndown (if (integerp arg) arg 1))
9428 (org-table-automatic-realign nil)
9429 (case-fold-search nil)
9430 (down (> ndown 1))
9431 (formula (if (and equation suppress-store)
9432 equation
9433 (org-table-get-formula equation (equal arg '(4)))))
9434 (n0 (org-table-current-column))
9435 (modes (copy-sequence org-calc-default-modes))
9436 (numbers nil) ; was a variable, now fixed default
9437 (keep-empty nil)
9438 n form form0 bw fmt x ev orig c lispp literal)
9439 ;; Parse the format string. Since we have a lot of modes, this is
9440 ;; a lot of work. However, I think calc still uses most of the time.
9441 (if (string-match ";" formula)
9442 (let ((tmp (org-split-string formula ";")))
9443 (setq formula (car tmp)
9444 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9445 (nth 1 tmp)))
9446 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9447 (setq c (string-to-char (match-string 1 fmt))
9448 n (string-to-number (match-string 2 fmt)))
9449 (if (= c ?p)
9450 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9451 (setq modes (org-set-calc-mode
9452 'calc-float-format
9453 (list (cdr (assoc c '((?n . float) (?f . fix)
9454 (?s . sci) (?e . eng))))
9455 n))))
9456 (setq fmt (replace-match "" t t fmt)))
9457 (if (string-match "[NT]" fmt)
9458 (setq numbers (equal (match-string 0 fmt) "N")
9459 fmt (replace-match "" t t fmt)))
9460 (if (string-match "L" fmt)
9461 (setq literal t
9462 fmt (replace-match "" t t fmt)))
9463 (if (string-match "E" fmt)
9464 (setq keep-empty t
9465 fmt (replace-match "" t t fmt)))
9466 (while (string-match "[DRFS]" fmt)
9467 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9468 (setq fmt (replace-match "" t t fmt)))
9469 (unless (string-match "\\S-" fmt)
9470 (setq fmt nil))))
9471 (if (and (not suppress-const) org-table-formula-use-constants)
9472 (setq formula (org-table-formula-substitute-names formula)))
9473 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9474 (while (> ndown 0)
9475 (setq fields (org-split-string
9476 (org-no-properties
9477 (buffer-substring (point-at-bol) (point-at-eol)))
9478 " *| *"))
9479 (if (eq numbers t)
9480 (setq fields (mapcar
9481 (lambda (x) (number-to-string (string-to-number x)))
9482 fields)))
9483 (setq ndown (1- ndown))
9484 (setq form (copy-sequence formula)
9485 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9486 (if (and lispp literal) (setq lispp 'literal))
9487 ;; Check for old vertical references
9488 (setq form (org-rewrite-old-row-references form))
9489 ;; Insert complex ranges
9490 (while (string-match org-table-range-regexp form)
9491 (setq form
9492 (replace-match
9493 (save-match-data
9494 (org-table-make-reference
9495 (org-table-get-range (match-string 0 form) nil n0)
9496 keep-empty numbers lispp))
9497 t t form)))
9498 ;; Insert simple ranges
9499 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
9500 (setq form
9501 (replace-match
9502 (save-match-data
9503 (org-table-make-reference
9504 (org-sublist
9505 fields (string-to-number (match-string 1 form))
9506 (string-to-number (match-string 2 form)))
9507 keep-empty numbers lispp))
9508 t t form)))
9509 (setq form0 form)
9510 ;; Insert the references to fields in same row
9511 (while (string-match "\\$\\([0-9]+\\)" form)
9512 (setq n (string-to-number (match-string 1 form))
9513 x (nth (1- (if (= n 0) n0 n)) fields))
9514 (unless x (error "Invalid field specifier \"%s\""
9515 (match-string 0 form)))
9516 (setq form (replace-match
9517 (save-match-data
9518 (org-table-make-reference x nil numbers lispp))
9519 t t form)))
9520
9521 (if lispp
9522 (setq ev (condition-case nil
9523 (eval (eval (read form)))
9524 (error "#ERROR"))
9525 ev (if (numberp ev) (number-to-string ev) ev))
9526 (or (fboundp 'calc-eval)
9527 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
9528 (setq ev (calc-eval (cons form modes)
9529 (if numbers 'num))))
9530
9531 (when org-table-formula-debug
9532 (with-output-to-temp-buffer "*Substitution History*"
9533 (princ (format "Substitution history of formula
9534 Orig: %s
9535 $xyz-> %s
9536 @r$c-> %s
9537 $1-> %s\n" orig formula form0 form))
9538 (if (listp ev)
9539 (princ (format " %s^\nError: %s"
9540 (make-string (car ev) ?\-) (nth 1 ev)))
9541 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9542 ev (or fmt "NONE")
9543 (if fmt (format fmt (string-to-number ev)) ev)))))
9544 (setq bw (get-buffer-window "*Substitution History*"))
9545 (shrink-window-if-larger-than-buffer bw)
9546 (unless (and (interactive-p) (not ndown))
9547 (unless (let (inhibit-redisplay)
9548 (y-or-n-p "Debugging Formula. Continue to next? "))
9549 (org-table-align)
9550 (error "Abort"))
9551 (delete-window bw)
9552 (message "")))
9553 (if (listp ev) (setq fmt nil ev "#ERROR"))
9554 (org-table-justify-field-maybe
9555 (if fmt (format fmt (string-to-number ev)) ev))
9556 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9557 (call-interactively 'org-return)
9558 (setq ndown 0)))
9559 (and down (org-table-maybe-recalculate-line))
9560 (or suppress-align (and org-table-may-need-update
9561 (org-table-align))))))
9562
9563 (defun org-table-put-field-property (prop value)
9564 (save-excursion
9565 (put-text-property (progn (skip-chars-backward "^|") (point))
9566 (progn (skip-chars-forward "^|") (point))
9567 prop value)))
9568
9569 (defun org-table-get-range (desc &optional tbeg col highlight)
9570 "Get a calc vector from a column, accorting to descriptor DESC.
9571 Optional arguments TBEG and COL can give the beginning of the table and
9572 the current column, to avoid unnecessary parsing.
9573 HIGHLIGHT means, just highlight the range."
9574 (if (not (equal (string-to-char desc) ?@))
9575 (setq desc (concat "@" desc)))
9576 (save-excursion
9577 (or tbeg (setq tbeg (org-table-begin)))
9578 (or col (setq col (org-table-current-column)))
9579 (let ((thisline (org-current-line))
9580 beg end c1 c2 r1 r2 rangep tmp)
9581 (unless (string-match org-table-range-regexp desc)
9582 (error "Invalid table range specifier `%s'" desc))
9583 (setq rangep (match-end 3)
9584 r1 (and (match-end 1) (match-string 1 desc))
9585 r2 (and (match-end 4) (match-string 4 desc))
9586 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
9587 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
9588
9589 (and c1 (setq c1 (+ (string-to-number c1)
9590 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
9591 (and c2 (setq c2 (+ (string-to-number c2)
9592 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
9593 (if (equal r1 "") (setq r1 nil))
9594 (if (equal r2 "") (setq r2 nil))
9595 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
9596 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
9597 ; (setq r2 (or r2 r1) c2 (or c2 c1))
9598 (if (not r1) (setq r1 thisline))
9599 (if (not r2) (setq r2 thisline))
9600 (if (not c1) (setq c1 col))
9601 (if (not c2) (setq c2 col))
9602 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
9603 ;; just one field
9604 (progn
9605 (goto-line r1)
9606 (while (not (looking-at org-table-dataline-regexp))
9607 (beginning-of-line 2))
9608 (prog1 (org-trim (org-table-get-field c1))
9609 (if highlight (org-table-highlight-rectangle (point) (point)))))
9610 ;; A range, return a vector
9611 ;; First sort the numbers to get a regular ractangle
9612 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
9613 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
9614 (goto-line r1)
9615 (while (not (looking-at org-table-dataline-regexp))
9616 (beginning-of-line 2))
9617 (org-table-goto-column c1)
9618 (setq beg (point))
9619 (goto-line r2)
9620 (while (not (looking-at org-table-dataline-regexp))
9621 (beginning-of-line 0))
9622 (org-table-goto-column c2)
9623 (setq end (point))
9624 (if highlight
9625 (org-table-highlight-rectangle
9626 beg (progn (skip-chars-forward "^|\n") (point))))
9627 ;; return string representation of calc vector
9628 (mapcar 'org-trim
9629 (apply 'append (org-table-copy-region beg end)))))))
9630
9631 (defun org-table-get-descriptor-line (desc &optional cline bline table)
9632 "Analyze descriptor DESC and retrieve the corresponding line number.
9633 The cursor is currently in line CLINE, the table begins in line BLINE,
9634 and TABLE is a vector with line types."
9635 (if (string-match "^[0-9]+$" desc)
9636 (aref org-table-dlines (string-to-number desc))
9637 (setq cline (or cline (org-current-line))
9638 bline (or bline org-table-current-begin-line)
9639 table (or table org-table-current-line-types))
9640 (if (or
9641 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
9642 ;; 1 2 3 4 5 6
9643 (and (not (match-end 3)) (not (match-end 6)))
9644 (and (match-end 3) (match-end 6) (not (match-end 5))))
9645 (error "invalid row descriptor `%s'" desc))
9646 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
9647 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
9648 (odir (and (match-end 5) (match-string 5 desc)))
9649 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
9650 (i (- cline bline))
9651 (rel (and (match-end 6)
9652 (or (and (match-end 1) (not (match-end 3)))
9653 (match-end 5)))))
9654 (if (and hn (not hdir))
9655 (progn
9656 (setq i 0 hdir "+")
9657 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
9658 (if (and (not hn) on (not odir))
9659 (error "should never happen");;(aref org-table-dlines on)
9660 (if (and hn (> hn 0))
9661 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
9662 (if on
9663 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
9664 (+ bline i)))))
9665
9666 (defun org-find-row-type (table i type backwards relative n)
9667 (let ((l (length table)))
9668 (while (> n 0)
9669 (while (and (setq i (+ i (if backwards -1 1)))
9670 (>= i 0) (< i l)
9671 (not (eq (aref table i) type))
9672 (if (and relative (eq (aref table i) 'hline))
9673 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
9674 t)))
9675 (setq n (1- n)))
9676 (if (or (< i 0) (>= i l))
9677 (error "Row descriptior leads outside table")
9678 i)))
9679
9680 (defun org-rewrite-old-row-references (s)
9681 (if (string-match "&[-+0-9I]" s)
9682 (error "Formula contains old &row reference, please rewrite using @-syntax")
9683 s))
9684
9685 (defun org-table-make-reference (elements keep-empty numbers lispp)
9686 "Convert list ELEMENTS to something appropriate to insert into formula.
9687 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
9688 NUMBERS indicates that everything should be converted to numbers.
9689 LISPP means to return something appropriate for a Lisp list."
9690 (if (stringp elements) ; just a single val
9691 (if lispp
9692 (if (eq lispp 'literal)
9693 elements
9694 (prin1-to-string (if numbers (string-to-number elements) elements)))
9695 (if (equal elements "") (setq elements "0"))
9696 (if numbers (number-to-string (string-to-number elements)) elements))
9697 (unless keep-empty
9698 (setq elements
9699 (delq nil
9700 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
9701 elements))))
9702 (setq elements (or elements '("0")))
9703 (if lispp
9704 (mapconcat
9705 (lambda (x)
9706 (if (eq lispp 'literal)
9707 x
9708 (prin1-to-string (if numbers (string-to-number x) x))))
9709 elements " ")
9710 (concat "[" (mapconcat
9711 (lambda (x)
9712 (if numbers (number-to-string (string-to-number x)) x))
9713 elements
9714 ",") "]"))))
9715
9716 (defun org-table-recalculate (&optional all noalign)
9717 "Recalculate the current table line by applying all stored formulas.
9718 With prefix arg ALL, do this for all lines in the table."
9719 (interactive "P")
9720 (or (memq this-command org-recalc-commands)
9721 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9722 (unless (org-at-table-p) (error "Not at a table"))
9723 (if (equal all '(16))
9724 (org-table-iterate)
9725 (org-table-get-specials)
9726 (let* ((eqlist (sort (org-table-get-stored-formulas)
9727 (lambda (a b) (string< (car a) (car b)))))
9728 (inhibit-redisplay (not debug-on-error))
9729 (line-re org-table-dataline-regexp)
9730 (thisline (org-current-line))
9731 (thiscol (org-table-current-column))
9732 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
9733 ;; Insert constants in all formulas
9734 (setq eqlist
9735 (mapcar (lambda (x)
9736 (setcdr x (org-table-formula-substitute-names (cdr x)))
9737 x)
9738 eqlist))
9739 ;; Split the equation list
9740 (while (setq eq (pop eqlist))
9741 (if (<= (string-to-char (car eq)) ?9)
9742 (push eq eqlnum)
9743 (push eq eqlname)))
9744 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9745 (if all
9746 (progn
9747 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9748 (goto-char (setq beg (org-table-begin)))
9749 (if (re-search-forward org-table-calculate-mark-regexp end t)
9750 ;; This is a table with marked lines, compute selected lines
9751 (setq line-re org-table-recalculate-regexp)
9752 ;; Move forward to the first non-header line
9753 (if (and (re-search-forward org-table-dataline-regexp end t)
9754 (re-search-forward org-table-hline-regexp end t)
9755 (re-search-forward org-table-dataline-regexp end t))
9756 (setq beg (match-beginning 0))
9757 nil))) ;; just leave beg where it is
9758 (setq beg (point-at-bol)
9759 end (move-marker (make-marker) (1+ (point-at-eol)))))
9760 (goto-char beg)
9761 (and all (message "Re-applying formulas to full table..."))
9762
9763 ;; First find the named fields, and mark them untouchanble
9764 (remove-text-properties beg end '(org-untouchable t))
9765 (while (setq eq (pop eqlname))
9766 (setq name (car eq)
9767 a (assoc name org-table-named-field-locations))
9768 (and (not a)
9769 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
9770 (setq a (list name
9771 (aref org-table-dlines
9772 (string-to-number (match-string 1 name)))
9773 (string-to-number (match-string 2 name)))))
9774 (when (and a (or all (equal (nth 1 a) thisline)))
9775 (message "Re-applying formula to field: %s" name)
9776 (goto-line (nth 1 a))
9777 (org-table-goto-column (nth 2 a))
9778 (push (append a (list (cdr eq))) eqlname1)
9779 (org-table-put-field-property :org-untouchable t)))
9780
9781 ;; Now evauluate the column formulas, but skip fields covered by
9782 ;; field formulas
9783 (goto-char beg)
9784 (while (re-search-forward line-re end t)
9785 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
9786 ;; Unprotected line, recalculate
9787 (and all (message "Re-applying formulas to full table...(line %d)"
9788 (setq cnt (1+ cnt))))
9789 (setq org-last-recalc-line (org-current-line))
9790 (setq eql eqlnum)
9791 (while (setq entry (pop eql))
9792 (goto-line org-last-recalc-line)
9793 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9794 (unless (get-text-property (point) :org-untouchable)
9795 (org-table-eval-formula nil (cdr entry)
9796 'noalign 'nocst 'nostore 'noanalysis)))))
9797
9798 ;; Now evaluate the field formulas
9799 (while (setq eq (pop eqlname1))
9800 (message "Re-applying formula to field: %s" (car eq))
9801 (goto-line (nth 1 eq))
9802 (org-table-goto-column (nth 2 eq))
9803 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
9804 'nostore 'noanalysis))
9805
9806 (goto-line thisline)
9807 (org-table-goto-column thiscol)
9808 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
9809 (or noalign (and org-table-may-need-update (org-table-align))
9810 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9811
9812 ;; back to initial position
9813 (message "Re-applying formulas...done")
9814 (goto-line thisline)
9815 (org-table-goto-column thiscol)
9816 (or noalign (and org-table-may-need-update (org-table-align))
9817 (and all (message "Re-applying formulas...done"))))))
9818
9819 (defun org-table-iterate (&optional arg)
9820 "Recalculate the table until it does not change anymore."
9821 (interactive "P")
9822 (let ((imax (if arg (prefix-numeric-value arg) 10))
9823 (i 0)
9824 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
9825 thistbl)
9826 (catch 'exit
9827 (while (< i imax)
9828 (setq i (1+ i))
9829 (org-table-recalculate 'all)
9830 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
9831 (if (not (string= lasttbl thistbl))
9832 (setq lasttbl thistbl)
9833 (if (> i 1)
9834 (message "Convergence after %d iterations" i)
9835 (message "Table was already stable"))
9836 (throw 'exit t)))
9837 (error "No convergence after %d iterations" i))))
9838
9839 (defun org-table-formula-substitute-names (f)
9840 "Replace $const with values in string F."
9841 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
9842 ;; First, check for column names
9843 (while (setq start (string-match org-table-column-name-regexp f start))
9844 (setq start (1+ start))
9845 (setq a (assoc (match-string 1 f) org-table-column-names))
9846 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9847 ;; Parameters and constants
9848 (setq start 0)
9849 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
9850 (setq start (1+ start))
9851 (if (setq a (save-match-data
9852 (org-table-get-constant (match-string 1 f))))
9853 (setq f (replace-match
9854 (concat (if pp "(") a (if pp ")")) t t f))))
9855 (if org-table-formula-debug
9856 (put-text-property 0 (length f) :orig-formula f1 f))
9857 f))
9858
9859 (defun org-table-get-constant (const)
9860 "Find the value for a parameter or constant in a formula.
9861 Parameters get priority."
9862 (or (cdr (assoc const org-table-local-parameters))
9863 (cdr (assoc const org-table-formula-constants-local))
9864 (cdr (assoc const org-table-formula-constants))
9865 (and (fboundp 'constants-get) (constants-get const))
9866 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
9867 (org-entry-get nil (substring const 5) 'inherit))
9868 "#UNDEFINED_NAME"))
9869
9870 (defvar org-table-fedit-map
9871 (let ((map (make-sparse-keymap)))
9872 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
9873 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
9874 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
9875 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
9876 (org-defkey map "\C-c?" 'org-table-show-reference)
9877 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
9878 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
9879 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
9880 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
9881 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
9882 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
9883 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
9884 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
9885 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
9886 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
9887 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
9888 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
9889 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
9890 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
9891 map))
9892
9893 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
9894 '("Edit-Formulas"
9895 ["Finish and Install" org-table-fedit-finish t]
9896 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
9897 ["Abort" org-table-fedit-abort t]
9898 "--"
9899 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
9900 ["Complete Lisp Symbol" lisp-complete-symbol t]
9901 "--"
9902 "Shift Reference at Point"
9903 ["Up" org-table-fedit-ref-up t]
9904 ["Down" org-table-fedit-ref-down t]
9905 ["Left" org-table-fedit-ref-left t]
9906 ["Right" org-table-fedit-ref-right t]
9907 "-"
9908 "Change Test Row for Column Formulas"
9909 ["Up" org-table-fedit-line-up t]
9910 ["Down" org-table-fedit-line-down t]
9911 "--"
9912 ["Scroll Table Window" org-table-fedit-scroll t]
9913 ["Scroll Table Window down" org-table-fedit-scroll-down t]
9914 ["Show Table Grid" org-table-fedit-toggle-coordinates
9915 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
9916 org-table-overlay-coordinates)]
9917 "--"
9918 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
9919 :style toggle :selected org-table-buffer-is-an]))
9920
9921 (defvar org-pos)
9922
9923 (defun org-table-edit-formulas ()
9924 "Edit the formulas of the current table in a separate buffer."
9925 (interactive)
9926 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
9927 (beginning-of-line 0))
9928 (unless (org-at-table-p) (error "Not at a table"))
9929 (org-table-get-specials)
9930 (let ((key (org-table-current-field-formula 'key 'noerror))
9931 (eql (sort (org-table-get-stored-formulas 'noerror)
9932 'org-table-formula-less-p))
9933 (pos (move-marker (make-marker) (point)))
9934 (startline 1)
9935 (wc (current-window-configuration))
9936 (titles '((column . "# Column Formulas\n")
9937 (field . "# Field Formulas\n")
9938 (named . "# Named Field Formulas\n")))
9939 entry s type title)
9940 (org-switch-to-buffer-other-window "*Edit Formulas*")
9941 (erase-buffer)
9942 ;; Keep global-font-lock-mode from turning on font-lock-mode
9943 (let ((font-lock-global-modes '(not fundamental-mode)))
9944 (fundamental-mode))
9945 (org-set-local 'font-lock-global-modes (list 'not major-mode))
9946 (org-set-local 'org-pos pos)
9947 (org-set-local 'org-window-configuration wc)
9948 (use-local-map org-table-fedit-map)
9949 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
9950 (easy-menu-add org-table-fedit-menu)
9951 (setq startline (org-current-line))
9952 (while (setq entry (pop eql))
9953 (setq type (cond
9954 ((equal (string-to-char (car entry)) ?@) 'field)
9955 ((string-match "^[0-9]" (car entry)) 'column)
9956 (t 'named)))
9957 (when (setq title (assq type titles))
9958 (or (bobp) (insert "\n"))
9959 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
9960 (setq titles (delq title titles)))
9961 (if (equal key (car entry)) (setq startline (org-current-line)))
9962 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
9963 (car entry) " = " (cdr entry) "\n"))
9964 (remove-text-properties 0 (length s) '(face nil) s)
9965 (insert s))
9966 (if (eq org-table-use-standard-references t)
9967 (org-table-fedit-toggle-ref-type))
9968 (goto-line startline)
9969 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
9970
9971 (defun org-table-fedit-post-command ()
9972 (when (not (memq this-command '(lisp-complete-symbol)))
9973 (let ((win (selected-window)))
9974 (save-excursion
9975 (condition-case nil
9976 (org-table-show-reference)
9977 (error nil))
9978 (select-window win)))))
9979
9980 (defun org-table-formula-to-user (s)
9981 "Convert a formula from internal to user representation."
9982 (if (eq org-table-use-standard-references t)
9983 (org-table-convert-refs-to-an s)
9984 s))
9985
9986 (defun org-table-formula-from-user (s)
9987 "Convert a formula from user to internal representation."
9988 (if org-table-use-standard-references
9989 (org-table-convert-refs-to-rc s)
9990 s))
9991
9992 (defun org-table-convert-refs-to-rc (s)
9993 "Convert spreadsheet references from AB7 to @7$28.
9994 Works for single references, but also for entire formulas and even the
9995 full TBLFM line."
9996 (let ((start 0))
9997 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
9998 (cond
9999 ((match-end 3)
10000 ;; format match, just advance
10001 (setq start (match-end 0)))
10002 ((and (> (match-beginning 0) 0)
10003 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10004 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10005 ;; 3.e5 or something like this.
10006 (setq start (match-end 0)))
10007 (t
10008 (setq start (match-beginning 0)
10009 s (replace-match
10010 (if (equal (match-string 2 s) "&")
10011 (format "$%d" (org-letters-to-number (match-string 1 s)))
10012 (format "@%d$%d"
10013 (string-to-number (match-string 2 s))
10014 (org-letters-to-number (match-string 1 s))))
10015 t t s)))))
10016 s))
10017
10018 (defun org-table-convert-refs-to-an (s)
10019 "Convert spreadsheet references from to @7$28 to AB7.
10020 Works for single references, but also for entire formulas and even the
10021 full TBLFM line."
10022 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10023 (setq s (replace-match
10024 (format "%s%d"
10025 (org-number-to-letters
10026 (string-to-number (match-string 2 s)))
10027 (string-to-number (match-string 1 s)))
10028 t t s)))
10029 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10030 (setq s (replace-match (concat "\\1"
10031 (org-number-to-letters
10032 (string-to-number (match-string 2 s))) "&")
10033 t nil s)))
10034 s)
10035
10036 (defun org-letters-to-number (s)
10037 "Convert a base 26 number represented by letters into an integer.
10038 For example: AB -> 28."
10039 (let ((n 0))
10040 (setq s (upcase s))
10041 (while (> (length s) 0)
10042 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10043 s (substring s 1)))
10044 n))
10045
10046 (defun org-number-to-letters (n)
10047 "Convert an integer into a base 26 number represented by letters.
10048 For example: 28 -> AB."
10049 (let ((s ""))
10050 (while (> n 0)
10051 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10052 n (/ (1- n) 26)))
10053 s))
10054
10055 (defun org-table-fedit-convert-buffer (function)
10056 "Convert all references in this buffer, using FUNTION."
10057 (let ((line (org-current-line)))
10058 (goto-char (point-min))
10059 (while (not (eobp))
10060 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10061 (delete-region (point) (point-at-eol))
10062 (or (eobp) (forward-char 1)))
10063 (goto-line line)))
10064
10065 (defun org-table-fedit-toggle-ref-type ()
10066 "Convert all references in the buffer from B3 to @3$2 and back."
10067 (interactive)
10068 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10069 (org-table-fedit-convert-buffer
10070 (if org-table-buffer-is-an
10071 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10072 (message "Reference type switched to %s"
10073 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10074
10075 (defun org-table-fedit-ref-up ()
10076 "Shift the reference at point one row/hline up."
10077 (interactive)
10078 (org-table-fedit-shift-reference 'up))
10079 (defun org-table-fedit-ref-down ()
10080 "Shift the reference at point one row/hline down."
10081 (interactive)
10082 (org-table-fedit-shift-reference 'down))
10083 (defun org-table-fedit-ref-left ()
10084 "Shift the reference at point one field to the left."
10085 (interactive)
10086 (org-table-fedit-shift-reference 'left))
10087 (defun org-table-fedit-ref-right ()
10088 "Shift the reference at point one field to the right."
10089 (interactive)
10090 (org-table-fedit-shift-reference 'right))
10091
10092 (defun org-table-fedit-shift-reference (dir)
10093 (cond
10094 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10095 (if (memq dir '(left right))
10096 (org-rematch-and-replace 1 (eq dir 'left))
10097 (error "Cannot shift reference in this direction")))
10098 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10099 ;; A B3-like reference
10100 (if (memq dir '(up down))
10101 (org-rematch-and-replace 2 (eq dir 'up))
10102 (org-rematch-and-replace 1 (eq dir 'left))))
10103 ((org-at-regexp-p
10104 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10105 ;; An internal reference
10106 (if (memq dir '(up down))
10107 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10108 (org-rematch-and-replace 5 (eq dir 'left))))))
10109
10110 (defun org-rematch-and-replace (n &optional decr hline)
10111 "Re-match the group N, and replace it with the shifted refrence."
10112 (or (match-end n) (error "Cannot shift reference in this direction"))
10113 (goto-char (match-beginning n))
10114 (and (looking-at (regexp-quote (match-string n)))
10115 (replace-match (org-shift-refpart (match-string 0) decr hline)
10116 t t)))
10117
10118 (defun org-shift-refpart (ref &optional decr hline)
10119 "Shift a refrence part REF.
10120 If DECR is set, decrease the references row/column, else increase.
10121 If HLINE is set, this may be a hline reference, it certainly is not
10122 a translation reference."
10123 (save-match-data
10124 (let* ((sign (string-match "^[-+]" ref)) n)
10125
10126 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10127 (cond
10128 ((and hline (string-match "^I+" ref))
10129 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10130 (setq n (+ n (if decr -1 1)))
10131 (if (= n 0) (setq n (+ n (if decr -1 1))))
10132 (if sign
10133 (setq sign (if (< n 0) "-" "+") n (abs n))
10134 (setq n (max 1 n)))
10135 (concat sign (make-string n ?I)))
10136
10137 ((string-match "^[0-9]+" ref)
10138 (setq n (string-to-number (concat sign ref)))
10139 (setq n (+ n (if decr -1 1)))
10140 (if sign
10141 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10142 (number-to-string (max 1 n))))
10143
10144 ((string-match "^[a-zA-Z]+" ref)
10145 (org-number-to-letters
10146 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10147
10148 (t (error "Cannot shift reference"))))))
10149
10150 (defun org-table-fedit-toggle-coordinates ()
10151 "Toggle the display of coordinates in the refrenced table."
10152 (interactive)
10153 (let ((pos (marker-position org-pos)))
10154 (with-current-buffer (marker-buffer org-pos)
10155 (save-excursion
10156 (goto-char pos)
10157 (org-table-toggle-coordinate-overlays)))))
10158
10159 (defun org-table-fedit-finish (&optional arg)
10160 "Parse the buffer for formula definitions and install them.
10161 With prefix ARG, apply the new formulas to the table."
10162 (interactive "P")
10163 (org-table-remove-rectangle-highlight)
10164 (if org-table-use-standard-references
10165 (progn
10166 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10167 (setq org-table-buffer-is-an nil)))
10168 (let ((pos org-pos) eql var form)
10169 (goto-char (point-min))
10170 (while (re-search-forward
10171 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10172 nil t)
10173 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10174 form (match-string 3))
10175 (setq form (org-trim form))
10176 (when (not (equal form ""))
10177 (while (string-match "[ \t]*\n[ \t]*" form)
10178 (setq form (replace-match " " t t form)))
10179 (when (assoc var eql)
10180 (error "Double formulas for %s" var))
10181 (push (cons var form) eql)))
10182 (setq org-pos nil)
10183 (set-window-configuration org-window-configuration)
10184 (select-window (get-buffer-window (marker-buffer pos)))
10185 (goto-char pos)
10186 (unless (org-at-table-p)
10187 (error "Lost table position - cannot install formulae"))
10188 (org-table-store-formulas eql)
10189 (move-marker pos nil)
10190 (kill-buffer "*Edit Formulas*")
10191 (if arg
10192 (org-table-recalculate 'all)
10193 (message "New formulas installed - press C-u C-c C-c to apply."))))
10194
10195 (defun org-table-fedit-abort ()
10196 "Abort editing formulas, without installing the changes."
10197 (interactive)
10198 (org-table-remove-rectangle-highlight)
10199 (let ((pos org-pos))
10200 (set-window-configuration org-window-configuration)
10201 (select-window (get-buffer-window (marker-buffer pos)))
10202 (goto-char pos)
10203 (move-marker pos nil)
10204 (message "Formula editing aborted without installing changes")))
10205
10206 (defun org-table-fedit-lisp-indent ()
10207 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10208 (interactive)
10209 (let ((pos (point)) beg end ind)
10210 (beginning-of-line 1)
10211 (cond
10212 ((looking-at "[ \t]")
10213 (goto-char pos)
10214 (call-interactively 'lisp-indent-line))
10215 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10216 ((not (fboundp 'pp-buffer))
10217 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10218 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10219 (goto-char (- (match-end 0) 2))
10220 (setq beg (point))
10221 (setq ind (make-string (current-column) ?\ ))
10222 (condition-case nil (forward-sexp 1)
10223 (error
10224 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10225 (setq end (point))
10226 (save-restriction
10227 (narrow-to-region beg end)
10228 (if (eq last-command this-command)
10229 (progn
10230 (goto-char (point-min))
10231 (setq this-command nil)
10232 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10233 (replace-match " ")))
10234 (pp-buffer)
10235 (untabify (point-min) (point-max))
10236 (goto-char (1+ (point-min)))
10237 (while (re-search-forward "^." nil t)
10238 (beginning-of-line 1)
10239 (insert ind))
10240 (goto-char (point-max))
10241 (backward-delete-char 1)))
10242 (goto-char beg))
10243 (t nil))))
10244
10245 (defvar org-show-positions nil)
10246
10247 (defun org-table-show-reference (&optional local)
10248 "Show the location/value of the $ expression at point."
10249 (interactive)
10250 (org-table-remove-rectangle-highlight)
10251 (catch 'exit
10252 (let ((pos (if local (point) org-pos))
10253 (face2 'highlight)
10254 (org-inhibit-highlight-removal t)
10255 (win (selected-window))
10256 (org-show-positions nil)
10257 var name e what match dest)
10258 (if local (org-table-get-specials))
10259 (setq what (cond
10260 ((or (org-at-regexp-p org-table-range-regexp2)
10261 (org-at-regexp-p org-table-translate-regexp)
10262 (org-at-regexp-p org-table-range-regexp))
10263 (setq match
10264 (save-match-data
10265 (org-table-convert-refs-to-rc (match-string 0))))
10266 'range)
10267 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10268 ((org-at-regexp-p "\\$[0-9]+") 'column)
10269 ((not local) nil)
10270 (t (error "No reference at point")))
10271 match (and what (or match (match-string 0))))
10272 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10273 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10274 'secondary-selection))
10275 (org-add-hook 'before-change-functions
10276 'org-table-remove-rectangle-highlight)
10277 (if (eq what 'name) (setq var (substring match 1)))
10278 (when (eq what 'range)
10279 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10280 (setq match (org-table-formula-substitute-names match)))
10281 (unless local
10282 (save-excursion
10283 (end-of-line 1)
10284 (re-search-backward "^\\S-" nil t)
10285 (beginning-of-line 1)
10286 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10287 (setq dest
10288 (save-match-data
10289 (org-table-convert-refs-to-rc (match-string 1))))
10290 (org-table-add-rectangle-overlay
10291 (match-beginning 1) (match-end 1) face2))))
10292 (if (and (markerp pos) (marker-buffer pos))
10293 (if (get-buffer-window (marker-buffer pos))
10294 (select-window (get-buffer-window (marker-buffer pos)))
10295 (org-switch-to-buffer-other-window (get-buffer-window
10296 (marker-buffer pos)))))
10297 (goto-char pos)
10298 (org-table-force-dataline)
10299 (when dest
10300 (setq name (substring dest 1))
10301 (cond
10302 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10303 (setq e (assoc name org-table-named-field-locations))
10304 (goto-line (nth 1 e))
10305 (org-table-goto-column (nth 2 e)))
10306 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10307 (let ((l (string-to-number (match-string 1 dest)))
10308 (c (string-to-number (match-string 2 dest))))
10309 (goto-line (aref org-table-dlines l))
10310 (org-table-goto-column c)))
10311 (t (org-table-goto-column (string-to-number name))))
10312 (move-marker pos (point))
10313 (org-table-highlight-rectangle nil nil face2))
10314 (cond
10315 ((equal dest match))
10316 ((not match))
10317 ((eq what 'range)
10318 (condition-case nil
10319 (save-excursion
10320 (org-table-get-range match nil nil 'highlight))
10321 (error nil)))
10322 ((setq e (assoc var org-table-named-field-locations))
10323 (goto-line (nth 1 e))
10324 (org-table-goto-column (nth 2 e))
10325 (org-table-highlight-rectangle (point) (point))
10326 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10327 ((setq e (assoc var org-table-column-names))
10328 (org-table-goto-column (string-to-number (cdr e)))
10329 (org-table-highlight-rectangle (point) (point))
10330 (goto-char (org-table-begin))
10331 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10332 (org-table-end) t)
10333 (progn
10334 (goto-char (match-beginning 1))
10335 (org-table-highlight-rectangle)
10336 (message "Named column (column %s)" (cdr e)))
10337 (error "Column name not found")))
10338 ((eq what 'column)
10339 ;; column number
10340 (org-table-goto-column (string-to-number (substring match 1)))
10341 (org-table-highlight-rectangle (point) (point))
10342 (message "Column %s" (substring match 1)))
10343 ((setq e (assoc var org-table-local-parameters))
10344 (goto-char (org-table-begin))
10345 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10346 (progn
10347 (goto-char (match-beginning 1))
10348 (org-table-highlight-rectangle)
10349 (message "Local parameter."))
10350 (error "Parameter not found")))
10351 (t
10352 (cond
10353 ((not var) (error "No reference at point"))
10354 ((setq e (assoc var org-table-formula-constants-local))
10355 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10356 var (cdr e)))
10357 ((setq e (assoc var org-table-formula-constants))
10358 (message "Constant: $%s=%s in `org-table-formula-constants'."
10359 var (cdr e)))
10360 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10361 (message "Constant: $%s=%s, from `constants.el'%s."
10362 var e (format " (%s units)" constants-unit-system)))
10363 (t (error "Undefined name $%s" var)))))
10364 (goto-char pos)
10365 (when (and org-show-positions
10366 (not (memq this-command '(org-table-fedit-scroll
10367 org-table-fedit-scroll-down))))
10368 (push pos org-show-positions)
10369 (push org-table-current-begin-pos org-show-positions)
10370 (let ((min (apply 'min org-show-positions))
10371 (max (apply 'max org-show-positions)))
10372 (goto-char min) (recenter 0)
10373 (goto-char max)
10374 (or (pos-visible-in-window-p max) (recenter -1))))
10375 (select-window win))))
10376
10377 (defun org-table-force-dataline ()
10378 "Make sure the cursor is in a dataline in a table."
10379 (unless (save-excursion
10380 (beginning-of-line 1)
10381 (looking-at org-table-dataline-regexp))
10382 (let* ((re org-table-dataline-regexp)
10383 (p1 (save-excursion (re-search-forward re nil 'move)))
10384 (p2 (save-excursion (re-search-backward re nil 'move))))
10385 (cond ((and p1 p2)
10386 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10387 p1 p2)))
10388 ((or p1 p2) (goto-char (or p1 p2)))
10389 (t (error "No table dataline around here"))))))
10390
10391 (defun org-table-fedit-line-up ()
10392 "Move cursor one line up in the window showing the table."
10393 (interactive)
10394 (org-table-fedit-move 'previous-line))
10395
10396 (defun org-table-fedit-line-down ()
10397 "Move cursor one line down in the window showing the table."
10398 (interactive)
10399 (org-table-fedit-move 'next-line))
10400
10401 (defun org-table-fedit-move (command)
10402 "Move the cursor in the window shoinw the table.
10403 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10404 (let ((org-table-allow-automatic-line-recalculation nil)
10405 (pos org-pos) (win (selected-window)) p)
10406 (select-window (get-buffer-window (marker-buffer org-pos)))
10407 (setq p (point))
10408 (call-interactively command)
10409 (while (and (org-at-table-p)
10410 (org-at-table-hline-p))
10411 (call-interactively command))
10412 (or (org-at-table-p) (goto-char p))
10413 (move-marker pos (point))
10414 (select-window win)))
10415
10416 (defun org-table-fedit-scroll (N)
10417 (interactive "p")
10418 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10419 (scroll-other-window N)))
10420
10421 (defun org-table-fedit-scroll-down (N)
10422 (interactive "p")
10423 (org-table-fedit-scroll (- N)))
10424
10425 (defvar org-table-rectangle-overlays nil)
10426
10427 (defun org-table-add-rectangle-overlay (beg end &optional face)
10428 "Add a new overlay."
10429 (let ((ov (org-make-overlay beg end)))
10430 (org-overlay-put ov 'face (or face 'secondary-selection))
10431 (push ov org-table-rectangle-overlays)))
10432
10433 (defun org-table-highlight-rectangle (&optional beg end face)
10434 "Highlight rectangular region in a table."
10435 (setq beg (or beg (point)) end (or end (point)))
10436 (let ((b (min beg end))
10437 (e (max beg end))
10438 l1 c1 l2 c2 tmp)
10439 (and (boundp 'org-show-positions)
10440 (setq org-show-positions (cons b (cons e org-show-positions))))
10441 (goto-char (min beg end))
10442 (setq l1 (org-current-line)
10443 c1 (org-table-current-column))
10444 (goto-char (max beg end))
10445 (setq l2 (org-current-line)
10446 c2 (org-table-current-column))
10447 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10448 (goto-line l1)
10449 (beginning-of-line 1)
10450 (loop for line from l1 to l2 do
10451 (when (looking-at org-table-dataline-regexp)
10452 (org-table-goto-column c1)
10453 (skip-chars-backward "^|\n") (setq beg (point))
10454 (org-table-goto-column c2)
10455 (skip-chars-forward "^|\n") (setq end (point))
10456 (org-table-add-rectangle-overlay beg end face))
10457 (beginning-of-line 2))
10458 (goto-char b))
10459 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10460
10461 (defun org-table-remove-rectangle-highlight (&rest ignore)
10462 "Remove the rectangle overlays."
10463 (unless org-inhibit-highlight-removal
10464 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10465 (mapc 'org-delete-overlay org-table-rectangle-overlays)
10466 (setq org-table-rectangle-overlays nil)))
10467
10468 (defvar org-table-coordinate-overlays nil
10469 "Collects the cooordinate grid overlays, so that they can be removed.")
10470 (make-variable-buffer-local 'org-table-coordinate-overlays)
10471
10472 (defun org-table-overlay-coordinates ()
10473 "Add overlays to the table at point, to show row/column coordinates."
10474 (interactive)
10475 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10476 (setq org-table-coordinate-overlays nil)
10477 (save-excursion
10478 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10479 (goto-char (org-table-begin))
10480 (while (org-at-table-p)
10481 (setq eol (point-at-eol))
10482 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10483 (push ov org-table-coordinate-overlays)
10484 (setq hline (looking-at org-table-hline-regexp))
10485 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10486 (format "%4d" (setq id (1+ id)))))
10487 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10488 (when hline
10489 (setq ic 0)
10490 (while (re-search-forward "[+|]\\(-+\\)" eol t)
10491 (setq beg (1+ (match-beginning 0))
10492 ic (1+ ic)
10493 s1 (concat "$" (int-to-string ic))
10494 s2 (org-number-to-letters ic)
10495 str (if (eq org-table-use-standard-references t) s2 s1))
10496 (setq ov (org-make-overlay beg (+ beg (length str))))
10497 (push ov org-table-coordinate-overlays)
10498 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10499 (beginning-of-line 2)))))
10500
10501 (defun org-table-toggle-coordinate-overlays ()
10502 "Toggle the display of Row/Column numbers in tables."
10503 (interactive)
10504 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10505 (message "Row/Column number display turned %s"
10506 (if org-table-overlay-coordinates "on" "off"))
10507 (if (and (org-at-table-p) org-table-overlay-coordinates)
10508 (org-table-align))
10509 (unless org-table-overlay-coordinates
10510 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10511 (setq org-table-coordinate-overlays nil)))
10512
10513 (defun org-table-toggle-formula-debugger ()
10514 "Toggle the formula debugger in tables."
10515 (interactive)
10516 (setq org-table-formula-debug (not org-table-formula-debug))
10517 (message "Formula debugging has been turned %s"
10518 (if org-table-formula-debug "on" "off")))
10519
10520 ;;; The orgtbl minor mode
10521
10522 ;; Define a minor mode which can be used in other modes in order to
10523 ;; integrate the org-mode table editor.
10524
10525 ;; This is really a hack, because the org-mode table editor uses several
10526 ;; keys which normally belong to the major mode, for example the TAB and
10527 ;; RET keys. Here is how it works: The minor mode defines all the keys
10528 ;; necessary to operate the table editor, but wraps the commands into a
10529 ;; function which tests if the cursor is currently inside a table. If that
10530 ;; is the case, the table editor command is executed. However, when any of
10531 ;; those keys is used outside a table, the function uses `key-binding' to
10532 ;; look up if the key has an associated command in another currently active
10533 ;; keymap (minor modes, major mode, global), and executes that command.
10534 ;; There might be problems if any of the keys used by the table editor is
10535 ;; otherwise used as a prefix key.
10536
10537 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10538 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10539 ;; addresses this by checking explicitly for both bindings.
10540
10541 ;; The optimized version (see variable `orgtbl-optimized') takes over
10542 ;; all keys which are bound to `self-insert-command' in the *global map*.
10543 ;; Some modes bind other commands to simple characters, for example
10544 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10545 ;; active, this binding is ignored inside tables and replaced with a
10546 ;; modified self-insert.
10547
10548 (defvar orgtbl-mode nil
10549 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10550 table editor in arbitrary modes.")
10551 (make-variable-buffer-local 'orgtbl-mode)
10552
10553 (defvar orgtbl-mode-map (make-keymap)
10554 "Keymap for `orgtbl-mode'.")
10555
10556 ;;;###autoload
10557 (defun turn-on-orgtbl ()
10558 "Unconditionally turn on `orgtbl-mode'."
10559 (orgtbl-mode 1))
10560
10561 (defvar org-old-auto-fill-inhibit-regexp nil
10562 "Local variable used by `orgtbl-mode'")
10563
10564 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
10565 "Matches a line belonging to an orgtbl.")
10566
10567 (defconst orgtbl-extra-font-lock-keywords
10568 (list (list (concat "^" orgtbl-line-start-regexp ".*")
10569 0 (quote 'org-table) 'prepend))
10570 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
10571
10572 ;;;###autoload
10573 (defun orgtbl-mode (&optional arg)
10574 "The `org-mode' table editor as a minor mode for use in other modes."
10575 (interactive)
10576 (if (org-mode-p)
10577 ;; Exit without error, in case some hook functions calls this
10578 ;; by accident in org-mode.
10579 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10580 (setq orgtbl-mode
10581 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10582 (if orgtbl-mode
10583 (progn
10584 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10585 ;; Make sure we are first in minor-mode-map-alist
10586 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10587 (and c (setq minor-mode-map-alist
10588 (cons c (delq c minor-mode-map-alist)))))
10589 (org-set-local (quote org-table-may-need-update) t)
10590 (org-add-hook 'before-change-functions 'org-before-change-function
10591 nil 'local)
10592 (org-set-local 'org-old-auto-fill-inhibit-regexp
10593 auto-fill-inhibit-regexp)
10594 (org-set-local 'auto-fill-inhibit-regexp
10595 (if auto-fill-inhibit-regexp
10596 (concat orgtbl-line-start-regexp "\\|"
10597 auto-fill-inhibit-regexp)
10598 orgtbl-line-start-regexp))
10599 (org-add-to-invisibility-spec '(org-cwidth))
10600 (when (fboundp 'font-lock-add-keywords)
10601 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
10602 (org-restart-font-lock))
10603 (easy-menu-add orgtbl-mode-menu)
10604 (run-hooks 'orgtbl-mode-hook))
10605 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10606 (org-cleanup-narrow-column-properties)
10607 (org-remove-from-invisibility-spec '(org-cwidth))
10608 (remove-hook 'before-change-functions 'org-before-change-function t)
10609 (when (fboundp 'font-lock-remove-keywords)
10610 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
10611 (org-restart-font-lock))
10612 (easy-menu-remove orgtbl-mode-menu)
10613 (force-mode-line-update 'all))))
10614
10615 (defun org-cleanup-narrow-column-properties ()
10616 "Remove all properties related to narrow-column invisibility."
10617 (let ((s 1))
10618 (while (setq s (text-property-any s (point-max)
10619 'display org-narrow-column-arrow))
10620 (remove-text-properties s (1+ s) '(display t)))
10621 (setq s 1)
10622 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10623 (remove-text-properties s (1+ s) '(org-cwidth t)))
10624 (setq s 1)
10625 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10626 (remove-text-properties s (1+ s) '(invisible t)))))
10627
10628 ;; Install it as a minor mode.
10629 (put 'orgtbl-mode :included t)
10630 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10631 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10632
10633 (defun orgtbl-make-binding (fun n &rest keys)
10634 "Create a function for binding in the table minor mode.
10635 FUN is the command to call inside a table. N is used to create a unique
10636 command name. KEYS are keys that should be checked in for a command
10637 to execute outside of tables."
10638 (eval
10639 (list 'defun
10640 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10641 '(arg)
10642 (concat "In tables, run `" (symbol-name fun) "'.\n"
10643 "Outside of tables, run the binding of `"
10644 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10645 "'.")
10646 '(interactive "p")
10647 (list 'if
10648 '(org-at-table-p)
10649 (list 'call-interactively (list 'quote fun))
10650 (list 'let '(orgtbl-mode)
10651 (list 'call-interactively
10652 (append '(or)
10653 (mapcar (lambda (k)
10654 (list 'key-binding k))
10655 keys)
10656 '('orgtbl-error))))))))
10657
10658 (defun orgtbl-error ()
10659 "Error when there is no default binding for a table key."
10660 (interactive)
10661 (error "This key is has no function outside tables"))
10662
10663 (defun orgtbl-setup ()
10664 "Setup orgtbl keymaps."
10665 (let ((nfunc 0)
10666 (bindings
10667 (list
10668 '([(meta shift left)] org-table-delete-column)
10669 '([(meta left)] org-table-move-column-left)
10670 '([(meta right)] org-table-move-column-right)
10671 '([(meta shift right)] org-table-insert-column)
10672 '([(meta shift up)] org-table-kill-row)
10673 '([(meta shift down)] org-table-insert-row)
10674 '([(meta up)] org-table-move-row-up)
10675 '([(meta down)] org-table-move-row-down)
10676 '("\C-c\C-w" org-table-cut-region)
10677 '("\C-c\M-w" org-table-copy-region)
10678 '("\C-c\C-y" org-table-paste-rectangle)
10679 '("\C-c-" org-table-insert-hline)
10680 '("\C-c}" org-table-toggle-coordinate-overlays)
10681 '("\C-c{" org-table-toggle-formula-debugger)
10682 '("\C-m" org-table-next-row)
10683 '([(shift return)] org-table-copy-down)
10684 '("\C-c\C-q" org-table-wrap-region)
10685 '("\C-c?" org-table-field-info)
10686 '("\C-c " org-table-blank-field)
10687 '("\C-c+" org-table-sum)
10688 '("\C-c=" org-table-eval-formula)
10689 '("\C-c'" org-table-edit-formulas)
10690 '("\C-c`" org-table-edit-field)
10691 '("\C-c*" org-table-recalculate)
10692 '("\C-c|" org-table-create-or-convert-from-region)
10693 '("\C-c^" org-table-sort-lines)
10694 '([(control ?#)] org-table-rotate-recalc-marks)))
10695 elt key fun cmd)
10696 (while (setq elt (pop bindings))
10697 (setq nfunc (1+ nfunc))
10698 (setq key (org-key (car elt))
10699 fun (nth 1 elt)
10700 cmd (orgtbl-make-binding fun nfunc key))
10701 (org-defkey orgtbl-mode-map key cmd))
10702
10703 ;; Special treatment needed for TAB and RET
10704 (org-defkey orgtbl-mode-map [(return)]
10705 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10706 (org-defkey orgtbl-mode-map "\C-m"
10707 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10708
10709 (org-defkey orgtbl-mode-map [(tab)]
10710 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10711 (org-defkey orgtbl-mode-map "\C-i"
10712 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
10713
10714 (org-defkey orgtbl-mode-map [(shift tab)]
10715 (orgtbl-make-binding 'org-table-previous-field 104
10716 [(shift tab)] [(tab)] "\C-i"))
10717
10718 (org-defkey orgtbl-mode-map "\M-\C-m"
10719 (orgtbl-make-binding 'org-table-wrap-region 105
10720 "\M-\C-m" [(meta return)]))
10721 (org-defkey orgtbl-mode-map [(meta return)]
10722 (orgtbl-make-binding 'org-table-wrap-region 106
10723 [(meta return)] "\M-\C-m"))
10724
10725 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
10726 (when orgtbl-optimized
10727 ;; If the user wants maximum table support, we need to hijack
10728 ;; some standard editing functions
10729 (org-remap orgtbl-mode-map
10730 'self-insert-command 'orgtbl-self-insert-command
10731 'delete-char 'org-delete-char
10732 'delete-backward-char 'org-delete-backward-char)
10733 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
10734 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10735 '("OrgTbl"
10736 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10737 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10738 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10739 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10740 "--"
10741 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10742 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10743 ["Copy Field from Above"
10744 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10745 "--"
10746 ("Column"
10747 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10748 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10749 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10750 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10751 ("Row"
10752 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10753 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10754 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10755 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10756 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10757 "--"
10758 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10759 ("Rectangle"
10760 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10761 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10762 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10763 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10764 "--"
10765 ("Radio tables"
10766 ["Insert table template" orgtbl-insert-radio-table
10767 (assq major-mode orgtbl-radio-table-templates)]
10768 ["Comment/uncomment table" orgtbl-toggle-comment t])
10769 "--"
10770 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10771 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10772 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10773 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10774 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10775 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
10776 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10777 ["Sum Column/Rectangle" org-table-sum
10778 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10779 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10780 ["Debug Formulas"
10781 org-table-toggle-formula-debugger :active (org-at-table-p)
10782 :keys "C-c {"
10783 :style toggle :selected org-table-formula-debug]
10784 ["Show Col/Row Numbers"
10785 org-table-toggle-coordinate-overlays :active (org-at-table-p)
10786 :keys "C-c }"
10787 :style toggle :selected org-table-overlay-coordinates]
10788 ))
10789 t))
10790
10791 (defun orgtbl-ctrl-c-ctrl-c (arg)
10792 "If the cursor is inside a table, realign the table.
10793 It it is a table to be sent away to a receiver, do it.
10794 With prefix arg, also recompute table."
10795 (interactive "P")
10796 (let ((pos (point)) action)
10797 (save-excursion
10798 (beginning-of-line 1)
10799 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
10800 ((looking-at "[ \t]*|") pos)
10801 ((looking-at "#\\+TBLFM:") 'recalc))))
10802 (cond
10803 ((integerp action)
10804 (goto-char action)
10805 (org-table-maybe-eval-formula)
10806 (if arg
10807 (call-interactively 'org-table-recalculate)
10808 (org-table-maybe-recalculate-line))
10809 (call-interactively 'org-table-align)
10810 (orgtbl-send-table 'maybe))
10811 ((eq action 'recalc)
10812 (save-excursion
10813 (beginning-of-line 1)
10814 (skip-chars-backward " \r\n\t")
10815 (if (org-at-table-p)
10816 (org-call-with-arg 'org-table-recalculate t))))
10817 (t (let (orgtbl-mode)
10818 (call-interactively (key-binding "\C-c\C-c")))))))
10819
10820 (defun orgtbl-tab (arg)
10821 "Justification and field motion for `orgtbl-mode'."
10822 (interactive "P")
10823 (if arg (org-table-edit-field t)
10824 (org-table-justify-field-maybe)
10825 (org-table-next-field)))
10826
10827 (defun orgtbl-ret ()
10828 "Justification and field motion for `orgtbl-mode'."
10829 (interactive)
10830 (org-table-justify-field-maybe)
10831 (org-table-next-row))
10832
10833 (defun orgtbl-self-insert-command (N)
10834 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10835 If the cursor is in a table looking at whitespace, the whitespace is
10836 overwritten, and the table is not marked as requiring realignment."
10837 (interactive "p")
10838 (if (and (org-at-table-p)
10839 (or
10840 (and org-table-auto-blank-field
10841 (member last-command
10842 '(orgtbl-hijacker-command-100
10843 orgtbl-hijacker-command-101
10844 orgtbl-hijacker-command-102
10845 orgtbl-hijacker-command-103
10846 orgtbl-hijacker-command-104
10847 orgtbl-hijacker-command-105))
10848 (org-table-blank-field))
10849 t)
10850 (eq N 1)
10851 (looking-at "[^|\n]* +|"))
10852 (let (org-table-may-need-update)
10853 (goto-char (1- (match-end 0)))
10854 (delete-backward-char 1)
10855 (goto-char (match-beginning 0))
10856 (self-insert-command N))
10857 (setq org-table-may-need-update t)
10858 (let (orgtbl-mode)
10859 (call-interactively (key-binding (vector last-input-event))))))
10860
10861 (defun org-force-self-insert (N)
10862 "Needed to enforce self-insert under remapping."
10863 (interactive "p")
10864 (self-insert-command N))
10865
10866 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
10867 "Regula expression matching exponentials as produced by calc.")
10868
10869 (defvar org-table-clean-did-remove-column nil)
10870
10871 (defun orgtbl-export (table target)
10872 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
10873 (lines (org-split-string table "[ \t]*\n[ \t]*"))
10874 org-table-last-alignment org-table-last-column-widths
10875 maxcol column)
10876 (if (not (fboundp func))
10877 (error "Cannot export orgtbl table to %s" target))
10878 (setq lines (org-table-clean-before-export lines))
10879 (setq table
10880 (mapcar
10881 (lambda (x)
10882 (if (string-match org-table-hline-regexp x)
10883 'hline
10884 (org-split-string (org-trim x) "\\s-*|\\s-*")))
10885 lines))
10886 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
10887 table)))
10888 (loop for i from (1- maxcol) downto 0 do
10889 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
10890 (setq column (delq nil column))
10891 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
10892 (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))
10893 (funcall func table nil)))
10894
10895 (defun orgtbl-send-table (&optional maybe)
10896 "Send a tranformed version of this table to the receiver position.
10897 With argument MAYBE, fail quietly if no transformation is defined for
10898 this table."
10899 (interactive)
10900 (catch 'exit
10901 (unless (org-at-table-p) (error "Not at a table"))
10902 ;; when non-interactive, we assume align has just happened.
10903 (when (interactive-p) (org-table-align))
10904 (save-excursion
10905 (goto-char (org-table-begin))
10906 (beginning-of-line 0)
10907 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
10908 (if maybe
10909 (throw 'exit nil)
10910 (error "Don't know how to transform this table."))))
10911 (let* ((name (match-string 1))
10912 beg
10913 (transform (intern (match-string 2)))
10914 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
10915 (skip (plist-get params :skip))
10916 (skipcols (plist-get params :skipcols))
10917 (txt (buffer-substring-no-properties
10918 (org-table-begin) (org-table-end)))
10919 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
10920 (lines (org-table-clean-before-export lines))
10921 (i0 (if org-table-clean-did-remove-column 2 1))
10922 (table (mapcar
10923 (lambda (x)
10924 (if (string-match org-table-hline-regexp x)
10925 'hline
10926 (org-remove-by-index
10927 (org-split-string (org-trim x) "\\s-*|\\s-*")
10928 skipcols i0)))
10929 lines))
10930 (fun (if (= i0 2) 'cdr 'identity))
10931 (org-table-last-alignment
10932 (org-remove-by-index (funcall fun org-table-last-alignment)
10933 skipcols i0))
10934 (org-table-last-column-widths
10935 (org-remove-by-index (funcall fun org-table-last-column-widths)
10936 skipcols i0)))
10937
10938 (unless (fboundp transform)
10939 (error "No such transformation function %s" transform))
10940 (setq txt (funcall transform table params))
10941 ;; Find the insertion place
10942 (save-excursion
10943 (goto-char (point-min))
10944 (unless (re-search-forward
10945 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
10946 (error "Don't know where to insert translated table"))
10947 (goto-char (match-beginning 0))
10948 (beginning-of-line 2)
10949 (setq beg (point))
10950 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
10951 (error "Cannot find end of insertion region"))
10952 (beginning-of-line 1)
10953 (delete-region beg (point))
10954 (goto-char beg)
10955 (insert txt "\n"))
10956 (message "Table converted and installed at receiver location"))))
10957
10958 (defun org-remove-by-index (list indices &optional i0)
10959 "Remove the elements in LIST with indices in INDICES.
10960 First element has index 0, or I0 if given."
10961 (if (not indices)
10962 list
10963 (if (integerp indices) (setq indices (list indices)))
10964 (setq i0 (1- (or i0 0)))
10965 (delq :rm (mapcar (lambda (x)
10966 (setq i0 (1+ i0))
10967 (if (memq i0 indices) :rm x))
10968 list))))
10969
10970 (defun orgtbl-toggle-comment ()
10971 "Comment or uncomment the orgtbl at point."
10972 (interactive)
10973 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
10974 (re2 (concat "^" orgtbl-line-start-regexp))
10975 (commented (save-excursion (beginning-of-line 1)
10976 (cond ((looking-at re1) t)
10977 ((looking-at re2) nil)
10978 (t (error "Not at an org table")))))
10979 (re (if commented re1 re2))
10980 beg end)
10981 (save-excursion
10982 (beginning-of-line 1)
10983 (while (looking-at re) (beginning-of-line 0))
10984 (beginning-of-line 2)
10985 (setq beg (point))
10986 (while (looking-at re) (beginning-of-line 2))
10987 (setq end (point)))
10988 (comment-region beg end (if commented '(4) nil))))
10989
10990 (defun orgtbl-insert-radio-table ()
10991 "Insert a radio table template appropriate for this major mode."
10992 (interactive)
10993 (let* ((e (assq major-mode orgtbl-radio-table-templates))
10994 (txt (nth 1 e))
10995 name pos)
10996 (unless e (error "No radio table setup defined for %s" major-mode))
10997 (setq name (read-string "Table name: "))
10998 (while (string-match "%n" txt)
10999 (setq txt (replace-match name t t txt)))
11000 (or (bolp) (insert "\n"))
11001 (setq pos (point))
11002 (insert txt)
11003 (goto-char pos)))
11004
11005 (defun org-get-param (params header i sym &optional hsym)
11006 "Get parameter value for symbol SYM.
11007 If this is a header line, actually get the value for the symbol with an
11008 additional \"h\" inserted after the colon.
11009 If the value is a protperty list, get the element for the current column.
11010 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11011 (let ((val (plist-get params sym)))
11012 (and hsym header (setq val (or (plist-get params hsym) val)))
11013 (if (consp val) (plist-get val i) val)))
11014
11015 (defun orgtbl-to-generic (table params)
11016 "Convert the orgtbl-mode TABLE to some other format.
11017 This generic routine can be used for many standard cases.
11018 TABLE is a list, each entry either the symbol `hline' for a horizontal
11019 separator line, or a list of fields for that line.
11020 PARAMS is a property list of parameters that can influence the conversion.
11021 For the generic converter, some parameters are obligatory: You need to
11022 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11023 :splice, you must have :tstart and :tend.
11024
11025 Valid parameters are
11026
11027 :tstart String to start the table. Ignored when :splice is t.
11028 :tend String to end the table. Ignored when :splice is t.
11029
11030 :splice When set to t, return only table body lines, don't wrap
11031 them into :tstart and :tend. Default is nil.
11032
11033 :hline String to be inserted on horizontal separation lines.
11034 May be nil to ignore hlines.
11035
11036 :lstart String to start a new table line.
11037 :lend String to end a table line
11038 :sep Separator between two fields
11039 :lfmt Format for entire line, with enough %s to capture all fields.
11040 If this is present, :lstart, :lend, and :sep are ignored.
11041 :fmt A format to be used to wrap the field, should contain
11042 %s for the original field value. For example, to wrap
11043 everything in dollars, you could use :fmt \"$%s$\".
11044 This may also be a property list with column numbers and
11045 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11046
11047 :hlstart :hlend :hlsep :hlfmt :hfmt
11048 Same as above, specific for the header lines in the table.
11049 All lines before the first hline are treated as header.
11050 If any of these is not present, the data line value is used.
11051
11052 :efmt Use this format to print numbers with exponentials.
11053 The format should have %s twice for inserting mantissa
11054 and exponent, for example \"%s\\\\times10^{%s}\". This
11055 may also be a property list with column numbers and
11056 formats. :fmt will still be applied after :efmt.
11057
11058 In addition to this, the parameters :skip and :skipcols are always handled
11059 directly by `orgtbl-send-table'. See manual."
11060 (interactive)
11061 (let* ((p params)
11062 (splicep (plist-get p :splice))
11063 (hline (plist-get p :hline))
11064 rtn line i fm efm lfmt h)
11065
11066 ;; Do we have a header?
11067 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11068 (setq h t))
11069
11070 ;; Put header
11071 (unless splicep
11072 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11073
11074 ;; Now loop over all lines
11075 (while (setq line (pop table))
11076 (if (eq line 'hline)
11077 ;; A horizontal separator line
11078 (progn (if hline (push hline rtn))
11079 (setq h nil)) ; no longer in header
11080 ;; A normal line. Convert the fields, push line onto the result list
11081 (setq i 0)
11082 (setq line
11083 (mapcar
11084 (lambda (f)
11085 (setq i (1+ i)
11086 fm (org-get-param p h i :fmt :hfmt)
11087 efm (org-get-param p h i :efmt))
11088 (if (and efm (string-match orgtbl-exp-regexp f))
11089 (setq f (format
11090 efm (match-string 1 f) (match-string 2 f))))
11091 (if fm (setq f (format fm f)))
11092 f)
11093 line))
11094 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11095 (push (apply 'format lfmt line) rtn)
11096 (push (concat
11097 (org-get-param p h i :lstart :hlstart)
11098 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11099 (org-get-param p h i :lend :hlend))
11100 rtn))))
11101
11102 (unless splicep
11103 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11104
11105 (mapconcat 'identity (nreverse rtn) "\n")))
11106
11107 (defun orgtbl-to-latex (table params)
11108 "Convert the orgtbl-mode TABLE to LaTeX.
11109 TABLE is a list, each entry either the symbol `hline' for a horizontal
11110 separator line, or a list of fields for that line.
11111 PARAMS is a property list of parameters that can influence the conversion.
11112 Supports all parameters from `orgtbl-to-generic'. Most important for
11113 LaTeX are:
11114
11115 :splice When set to t, return only table body lines, don't wrap
11116 them into a tabular environment. Default is nil.
11117
11118 :fmt A format to be used to wrap the field, should contain %s for the
11119 original field value. For example, to wrap everything in dollars,
11120 use :fmt \"$%s$\". This may also be a property list with column
11121 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11122
11123 :efmt Format for transforming numbers with exponentials. The format
11124 should have %s twice for inserting mantissa and exponent, for
11125 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11126 This may also be a property list with column numbers and formats.
11127
11128 The general parameters :skip and :skipcols have already been applied when
11129 this function is called."
11130 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11131 org-table-last-alignment ""))
11132 (params2
11133 (list
11134 :tstart (concat "\\begin{tabular}{" alignment "}")
11135 :tend "\\end{tabular}"
11136 :lstart "" :lend " \\\\" :sep " & "
11137 :efmt "%s\\,(%s)" :hline "\\hline")))
11138 (orgtbl-to-generic table (org-combine-plists params2 params))))
11139
11140 (defun orgtbl-to-html (table params)
11141 "Convert the orgtbl-mode TABLE to LaTeX.
11142 TABLE is a list, each entry either the symbol `hline' for a horizontal
11143 separator line, or a list of fields for that line.
11144 PARAMS is a property list of parameters that can influence the conversion.
11145 Currently this function recognizes the following parameters:
11146
11147 :splice When set to t, return only table body lines, don't wrap
11148 them into a <table> environment. Default is nil.
11149
11150 The general parameters :skip and :skipcols have already been applied when
11151 this function is called. The function does *not* use `orgtbl-to-generic',
11152 so you cannot specify parameters for it."
11153 (let* ((splicep (plist-get params :splice))
11154 html)
11155 ;; Just call the formatter we already have
11156 ;; We need to make text lines for it, so put the fields back together.
11157 (setq html (org-format-org-table-html
11158 (mapcar
11159 (lambda (x)
11160 (if (eq x 'hline)
11161 "|----+----|"
11162 (concat "| " (mapconcat 'identity x " | ") " |")))
11163 table)
11164 splicep))
11165 (if (string-match "\n+\\'" html)
11166 (setq html (replace-match "" t t html)))
11167 html))
11168
11169 (defun orgtbl-to-texinfo (table params)
11170 "Convert the orgtbl-mode TABLE to TeXInfo.
11171 TABLE is a list, each entry either the symbol `hline' for a horizontal
11172 separator line, or a list of fields for that line.
11173 PARAMS is a property list of parameters that can influence the conversion.
11174 Supports all parameters from `orgtbl-to-generic'. Most important for
11175 TeXInfo are:
11176
11177 :splice nil/t When set to t, return only table body lines, don't wrap
11178 them into a multitable environment. Default is nil.
11179
11180 :fmt fmt A format to be used to wrap the field, should contain
11181 %s for the original field value. For example, to wrap
11182 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11183 This may also be a property list with column numbers and
11184 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11185
11186 :cf \"f1 f2..\" The column fractions for the table. Bye default these
11187 are computed automatically from the width of the columns
11188 under org-mode.
11189
11190 The general parameters :skip and :skipcols have already been applied when
11191 this function is called."
11192 (let* ((total (float (apply '+ org-table-last-column-widths)))
11193 (colfrac (or (plist-get params :cf)
11194 (mapconcat
11195 (lambda (x) (format "%.3f" (/ (float x) total)))
11196 org-table-last-column-widths " ")))
11197 (params2
11198 (list
11199 :tstart (concat "@multitable @columnfractions " colfrac)
11200 :tend "@end multitable"
11201 :lstart "@item " :lend "" :sep " @tab "
11202 :hlstart "@headitem ")))
11203 (orgtbl-to-generic table (org-combine-plists params2 params))))
11204
11205 ;;;; Link Stuff
11206
11207 ;;; Link abbreviations
11208
11209 (defun org-link-expand-abbrev (link)
11210 "Apply replacements as defined in `org-link-abbrev-alist."
11211 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11212 (let* ((key (match-string 1 link))
11213 (as (or (assoc key org-link-abbrev-alist-local)
11214 (assoc key org-link-abbrev-alist)))
11215 (tag (and (match-end 2) (match-string 3 link)))
11216 rpl)
11217 (if (not as)
11218 link
11219 (setq rpl (cdr as))
11220 (cond
11221 ((symbolp rpl) (funcall rpl tag))
11222 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11223 (t (concat rpl tag)))))
11224 link))
11225
11226 ;;; Storing and inserting links
11227
11228 (defvar org-insert-link-history nil
11229 "Minibuffer history for links inserted with `org-insert-link'.")
11230
11231 (defvar org-stored-links nil
11232 "Contains the links stored with `org-store-link'.")
11233
11234 (defvar org-store-link-plist nil
11235 "Plist with info about the most recently link created with `org-store-link'.")
11236
11237 (defvar org-link-protocols nil
11238 "Link protocols added to Org-mode using `org-add-link-type'.")
11239
11240 (defvar org-store-link-functions nil
11241 "List of functions that are called to create and store a link.
11242 Each function will be called in turn until one returns a non-nil
11243 value. Each function should check if it is responsible for creating
11244 this link (for example by looking at the major mode).
11245 If not, it must exit and return nil.
11246 If yes, it should return a non-nil value after a calling
11247 `org-store-link-properties' with a list of properties and values.
11248 Special properties are:
11249
11250 :type The link prefix. like \"http\". This must be given.
11251 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11252 This is obligatory as well.
11253 :description Optional default description for the second pair
11254 of brackets in an Org-mode link. The user can still change
11255 this when inserting this link into an Org-mode buffer.
11256
11257 In addition to these, any additional properties can be specified
11258 and then used in remember templates.")
11259
11260 (defun org-add-link-type (type &optional follow publish)
11261 "Add TYPE to the list of `org-link-types'.
11262 Re-compute all regular expressions depending on `org-link-types'
11263 FOLLOW and PUBLISH are two functions. Both take the link path as
11264 an argument.
11265 FOLLOW should do whatever is necessary to follow the link, for example
11266 to find a file or display a mail message.
11267 PUBLISH takes the path and retuns the string that should be used when
11268 this document is published."
11269 (add-to-list 'org-link-types type t)
11270 (org-make-link-regexps)
11271 (add-to-list 'org-link-protocols
11272 (list type follow publish)))
11273
11274 (defun org-add-agenda-custom-command (entry)
11275 "Replace or add a command in `org-agenda-custom-commands'.
11276 This is mostly for hacking and trying a new command - once the command
11277 works you probably want to add it to `org-agenda-custom-commands' for good."
11278 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11279 (if ass
11280 (setcdr ass (cdr entry))
11281 (push entry org-agenda-custom-commands))))
11282
11283 ;;;###autoload
11284 (defun org-store-link (arg)
11285 "\\<org-mode-map>Store an org-link to the current location.
11286 This link can later be inserted into an org-buffer with
11287 \\[org-insert-link].
11288 For some link types, a prefix arg is interpreted:
11289 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11290 For file links, arg negates `org-context-in-file-links'."
11291 (interactive "P")
11292 (setq org-store-link-plist nil) ; reset
11293 (let (link cpltxt desc description search txt)
11294 (cond
11295
11296 ((run-hook-with-args-until-success 'org-store-link-functions)
11297 (setq link (plist-get org-store-link-plist :link)
11298 desc (or (plist-get org-store-link-plist :description) link)))
11299
11300 ((eq major-mode 'bbdb-mode)
11301 (let ((name (bbdb-record-name (bbdb-current-record)))
11302 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11303 (setq cpltxt (concat "bbdb:" (or name company))
11304 link (org-make-link cpltxt))
11305 (org-store-link-props :type "bbdb" :name name :company company)))
11306
11307 ((eq major-mode 'Info-mode)
11308 (setq link (org-make-link "info:"
11309 (file-name-nondirectory Info-current-file)
11310 ":" Info-current-node))
11311 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11312 ":" Info-current-node))
11313 (org-store-link-props :type "info" :file Info-current-file
11314 :node Info-current-node))
11315
11316 ((eq major-mode 'calendar-mode)
11317 (let ((cd (calendar-cursor-to-date)))
11318 (setq link
11319 (format-time-string
11320 (car org-time-stamp-formats)
11321 (apply 'encode-time
11322 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11323 nil nil nil))))
11324 (org-store-link-props :type "calendar" :date cd)))
11325
11326 ((or (eq major-mode 'vm-summary-mode)
11327 (eq major-mode 'vm-presentation-mode))
11328 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11329 (vm-follow-summary-cursor)
11330 (save-excursion
11331 (vm-select-folder-buffer)
11332 (let* ((message (car vm-message-pointer))
11333 (folder buffer-file-name)
11334 (subject (vm-su-subject message))
11335 (to (vm-get-header-contents message "To"))
11336 (from (vm-get-header-contents message "From"))
11337 (message-id (vm-su-message-id message)))
11338 (org-store-link-props :type "vm" :from from :to to :subject subject
11339 :message-id message-id)
11340 (setq message-id (org-remove-angle-brackets message-id))
11341 (setq folder (abbreviate-file-name folder))
11342 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11343 folder)
11344 (setq folder (replace-match "" t t folder)))
11345 (setq cpltxt (org-email-link-description))
11346 (setq link (org-make-link "vm:" folder "#" message-id)))))
11347
11348 ((eq major-mode 'wl-summary-mode)
11349 (let* ((msgnum (wl-summary-message-number))
11350 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11351 msgnum 'message-id))
11352 (wl-message-entity
11353 (if (fboundp 'elmo-message-entity)
11354 (elmo-message-entity
11355 wl-summary-buffer-elmo-folder msgnum)
11356 (elmo-msgdb-overview-get-entity
11357 msgnum (wl-summary-buffer-msgdb))))
11358 (from (wl-summary-line-from))
11359 (to (elmo-message-entity-field wl-message-entity 'to))
11360 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11361 (wl-summary-line-subject))))
11362 (org-store-link-props :type "wl" :from from :to to
11363 :subject subject :message-id message-id)
11364 (setq message-id (org-remove-angle-brackets message-id))
11365 (setq cpltxt (org-email-link-description))
11366 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11367 "#" message-id))))
11368
11369 ((or (equal major-mode 'mh-folder-mode)
11370 (equal major-mode 'mh-show-mode))
11371 (let ((from (org-mhe-get-header "From:"))
11372 (to (org-mhe-get-header "To:"))
11373 (message-id (org-mhe-get-header "Message-Id:"))
11374 (subject (org-mhe-get-header "Subject:")))
11375 (org-store-link-props :type "mh" :from from :to to
11376 :subject subject :message-id message-id)
11377 (setq cpltxt (org-email-link-description))
11378 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11379 (org-remove-angle-brackets message-id)))))
11380
11381 ((eq major-mode 'rmail-mode)
11382 (save-excursion
11383 (save-restriction
11384 (rmail-narrow-to-non-pruned-header)
11385 (let ((folder buffer-file-name)
11386 (message-id (mail-fetch-field "message-id"))
11387 (from (mail-fetch-field "from"))
11388 (to (mail-fetch-field "to"))
11389 (subject (mail-fetch-field "subject")))
11390 (org-store-link-props
11391 :type "rmail" :from from :to to
11392 :subject subject :message-id message-id)
11393 (setq message-id (org-remove-angle-brackets message-id))
11394 (setq cpltxt (org-email-link-description))
11395 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11396
11397 ((eq major-mode 'gnus-group-mode)
11398 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11399 (gnus-group-group-name)) ; version
11400 ((fboundp 'gnus-group-name)
11401 (gnus-group-name))
11402 (t "???"))))
11403 (unless group (error "Not on a group"))
11404 (org-store-link-props :type "gnus" :group group)
11405 (setq cpltxt (concat
11406 (if (org-xor arg org-usenet-links-prefer-google)
11407 "http://groups.google.com/groups?group="
11408 "gnus:")
11409 group)
11410 link (org-make-link cpltxt))))
11411
11412 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11413 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11414 (let* ((group gnus-newsgroup-name)
11415 (article (gnus-summary-article-number))
11416 (header (gnus-summary-article-header article))
11417 (from (mail-header-from header))
11418 (message-id (mail-header-id header))
11419 (date (mail-header-date header))
11420 (subject (gnus-summary-subject-string)))
11421 (org-store-link-props :type "gnus" :from from :subject subject
11422 :message-id message-id :group group)
11423 (setq cpltxt (org-email-link-description))
11424 (if (org-xor arg org-usenet-links-prefer-google)
11425 (setq link
11426 (concat
11427 cpltxt "\n "
11428 (format "http://groups.google.com/groups?as_umsgid=%s"
11429 (org-fixup-message-id-for-http message-id))))
11430 (setq link (org-make-link "gnus:" group
11431 "#" (number-to-string article))))))
11432
11433 ((eq major-mode 'w3-mode)
11434 (setq cpltxt (url-view-url t)
11435 link (org-make-link cpltxt))
11436 (org-store-link-props :type "w3" :url (url-view-url t)))
11437
11438 ((eq major-mode 'w3m-mode)
11439 (setq cpltxt (or w3m-current-title w3m-current-url)
11440 link (org-make-link w3m-current-url))
11441 (org-store-link-props :type "w3m" :url (url-view-url t)))
11442
11443 ((setq search (run-hook-with-args-until-success
11444 'org-create-file-search-functions))
11445 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11446 "::" search))
11447 (setq cpltxt (or description link)))
11448
11449 ((eq major-mode 'image-mode)
11450 (setq cpltxt (concat "file:"
11451 (abbreviate-file-name buffer-file-name))
11452 link (org-make-link cpltxt))
11453 (org-store-link-props :type "image" :file buffer-file-name))
11454
11455 ((eq major-mode 'dired-mode)
11456 ;; link to the file in the current line
11457 (setq cpltxt (concat "file:"
11458 (abbreviate-file-name
11459 (expand-file-name
11460 (dired-get-filename nil t))))
11461 link (org-make-link cpltxt)))
11462
11463 ((and buffer-file-name (org-mode-p))
11464 ;; Just link to current headline
11465 (setq cpltxt (concat "file:"
11466 (abbreviate-file-name buffer-file-name)))
11467 ;; Add a context search string
11468 (when (org-xor org-context-in-file-links arg)
11469 ;; Check if we are on a target
11470 (if (org-in-regexp "<<\\(.*?\\)>>")
11471 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11472 (setq txt (cond
11473 ((org-on-heading-p) nil)
11474 ((org-region-active-p)
11475 (buffer-substring (region-beginning) (region-end)))
11476 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11477 (when (or (null txt) (string-match "\\S-" txt))
11478 (setq cpltxt
11479 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11480 desc "NONE"))))
11481 (if (string-match "::\\'" cpltxt)
11482 (setq cpltxt (substring cpltxt 0 -2)))
11483 (setq link (org-make-link cpltxt)))
11484
11485 ((buffer-file-name (buffer-base-buffer))
11486 ;; Just link to this file here.
11487 (setq cpltxt (concat "file:"
11488 (abbreviate-file-name
11489 (buffer-file-name (buffer-base-buffer)))))
11490 ;; Add a context string
11491 (when (org-xor org-context-in-file-links arg)
11492 (setq txt (if (org-region-active-p)
11493 (buffer-substring (region-beginning) (region-end))
11494 (buffer-substring (point-at-bol) (point-at-eol))))
11495 ;; Only use search option if there is some text.
11496 (when (string-match "\\S-" txt)
11497 (setq cpltxt
11498 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11499 desc "NONE")))
11500 (setq link (org-make-link cpltxt)))
11501
11502 ((interactive-p)
11503 (error "Cannot link to a buffer which is not visiting a file"))
11504
11505 (t (setq link nil)))
11506
11507 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11508 (setq link (or link cpltxt)
11509 desc (or desc cpltxt))
11510 (if (equal desc "NONE") (setq desc nil))
11511
11512 (if (and (interactive-p) link)
11513 (progn
11514 (setq org-stored-links
11515 (cons (list link desc) org-stored-links))
11516 (message "Stored: %s" (or desc link)))
11517 (and link (org-make-link-string link desc)))))
11518
11519 (defun org-store-link-props (&rest plist)
11520 "Store link properties, extract names and addresses."
11521 (let (x adr)
11522 (when (setq x (plist-get plist :from))
11523 (setq adr (mail-extract-address-components x))
11524 (plist-put plist :fromname (car adr))
11525 (plist-put plist :fromaddress (nth 1 adr)))
11526 (when (setq x (plist-get plist :to))
11527 (setq adr (mail-extract-address-components x))
11528 (plist-put plist :toname (car adr))
11529 (plist-put plist :toaddress (nth 1 adr))))
11530 (let ((from (plist-get plist :from))
11531 (to (plist-get plist :to)))
11532 (when (and from to org-from-is-user-regexp)
11533 (plist-put plist :fromto
11534 (if (string-match org-from-is-user-regexp from)
11535 (concat "to %t")
11536 (concat "from %f")))))
11537 (setq org-store-link-plist plist))
11538
11539 (defun org-email-link-description (&optional fmt)
11540 "Return the description part of an email link.
11541 This takes information from `org-store-link-plist' and formats it
11542 according to FMT (default from `org-email-link-description-format')."
11543 (setq fmt (or fmt org-email-link-description-format))
11544 (let* ((p org-store-link-plist)
11545 (to (plist-get p :toaddress))
11546 (from (plist-get p :fromaddress))
11547 (table
11548 (list
11549 (cons "%c" (plist-get p :fromto))
11550 (cons "%F" (plist-get p :from))
11551 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
11552 (cons "%T" (plist-get p :to))
11553 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
11554 (cons "%s" (plist-get p :subject))
11555 (cons "%m" (plist-get p :message-id)))))
11556 (when (string-match "%c" fmt)
11557 ;; Check if the user wrote this message
11558 (if (and org-from-is-user-regexp from to
11559 (save-match-data (string-match org-from-is-user-regexp from)))
11560 (setq fmt (replace-match "to %t" t t fmt))
11561 (setq fmt (replace-match "from %f" t t fmt))))
11562 (org-replace-escapes fmt table)))
11563
11564 (defun org-make-org-heading-search-string (&optional string heading)
11565 "Make search string for STRING or current headline."
11566 (interactive)
11567 (let ((s (or string (org-get-heading))))
11568 (unless (and string (not heading))
11569 ;; We are using a headline, clean up garbage in there.
11570 (if (string-match org-todo-regexp s)
11571 (setq s (replace-match "" t t s)))
11572 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
11573 (setq s (replace-match "" t t s)))
11574 (setq s (org-trim s))
11575 (if (string-match (concat "^\\(" org-quote-string "\\|"
11576 org-comment-string "\\)") s)
11577 (setq s (replace-match "" t t s)))
11578 (while (string-match org-ts-regexp s)
11579 (setq s (replace-match "" t t s))))
11580 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
11581 (setq s (replace-match " " t t s)))
11582 (or string (setq s (concat "*" s))) ; Add * for headlines
11583 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
11584
11585 (defun org-make-link (&rest strings)
11586 "Concatenate STRINGS."
11587 (apply 'concat strings))
11588
11589 (defun org-make-link-string (link &optional description)
11590 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11591 (unless (string-match "\\S-" link)
11592 (error "Empty link"))
11593 (when (stringp description)
11594 ;; Remove brackets from the description, they are fatal.
11595 (while (string-match "\\[\\|\\]" description)
11596 (setq description (replace-match "" t t description))))
11597 (when (equal (org-link-escape link) description)
11598 ;; No description needed, it is identical
11599 (setq description nil))
11600 (when (and (not description)
11601 (not (equal link (org-link-escape link))))
11602 (setq description link))
11603 (concat "[[" (org-link-escape link) "]"
11604 (if description (concat "[" description "]") "")
11605 "]"))
11606
11607 (defconst org-link-escape-chars
11608 '((" " . "%20")
11609 ("[" . "%5B")
11610 ("]" . "%5d")
11611 ("\340" . "%E0") ; `a
11612 ("\342" . "%E2") ; ^a
11613 ("\347" . "%E7") ; ,c
11614 ("\350" . "%E8") ; `e
11615 ("\351" . "%E9") ; 'e
11616 ("\352" . "%EA") ; ^e
11617 ("\356" . "%EE") ; ^i
11618 ("\364" . "%F4") ; ^o
11619 ("\371" . "%F9") ; `u
11620 ("\373" . "%FB") ; ^u
11621 (";" . "%3B")
11622 ("?" . "%3F")
11623 ("=" . "%3D")
11624 ("+" . "%2B")
11625 )
11626 "Association list of escapes for some characters problematic in links.
11627 This is the list that is used for internal purposes.")
11628
11629 (defconst org-link-escape-chars-browser
11630 '((" " . "%20"))
11631 "Association list of escapes for some characters problematic in links.
11632 This is the list that is used before handing over to the browser.")
11633
11634 (defun org-link-escape (text &optional table)
11635 "Escape charaters in TEXT that are problematic for links."
11636 (setq table (or table org-link-escape-chars))
11637 (when text
11638 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
11639 table "\\|")))
11640 (while (string-match re text)
11641 (setq text
11642 (replace-match
11643 (cdr (assoc (match-string 0 text) table))
11644 t t text)))
11645 text)))
11646
11647 (defun org-link-unescape (text &optional table)
11648 "Reverse the action of `org-link-escape'."
11649 (setq table (or table org-link-escape-chars))
11650 (when text
11651 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
11652 table "\\|")))
11653 (while (string-match re text)
11654 (setq text
11655 (replace-match
11656 (car (rassoc (match-string 0 text) table))
11657 t t text)))
11658 text)))
11659
11660 (defun org-xor (a b)
11661 "Exclusive or."
11662 (if a (not b) b))
11663
11664 (defun org-get-header (header)
11665 "Find a header field in the current buffer."
11666 (save-excursion
11667 (goto-char (point-min))
11668 (let ((case-fold-search t) s)
11669 (cond
11670 ((eq header 'from)
11671 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11672 (setq s (match-string 1)))
11673 (while (string-match "\"" s)
11674 (setq s (replace-match "" t t s)))
11675 (if (string-match "[<(].*" s)
11676 (setq s (replace-match "" t t s))))
11677 ((eq header 'message-id)
11678 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11679 (setq s (match-string 1))))
11680 ((eq header 'subject)
11681 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11682 (setq s (match-string 1)))))
11683 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11684 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11685 s)))
11686
11687
11688 (defun org-fixup-message-id-for-http (s)
11689 "Replace special characters in a message id, so it can be used in an http query."
11690 (while (string-match "<" s)
11691 (setq s (replace-match "%3C" t t s)))
11692 (while (string-match ">" s)
11693 (setq s (replace-match "%3E" t t s)))
11694 (while (string-match "@" s)
11695 (setq s (replace-match "%40" t t s)))
11696 s)
11697
11698 ;;;###autoload
11699 (defun org-insert-link-global ()
11700 "Insert a link like Org-mode does.
11701 This command can be called in any mode to insert a link in Org-mode syntax."
11702 (interactive)
11703 (org-run-like-in-org-mode 'org-insert-link))
11704
11705 (defun org-insert-link (&optional complete-file)
11706 "Insert a link. At the prompt, enter the link.
11707
11708 Completion can be used to select a link previously stored with
11709 `org-store-link'. When the empty string is entered (i.e. if you just
11710 press RET at the prompt), the link defaults to the most recently
11711 stored link. As SPC triggers completion in the minibuffer, you need to
11712 use M-SPC or C-q SPC to force the insertion of a space character.
11713
11714 You will also be prompted for a description, and if one is given, it will
11715 be displayed in the buffer instead of the link.
11716
11717 If there is already a link at point, this command will allow you to edit link
11718 and description parts.
11719
11720 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11721 selected using completion. The path to the file will be relative to
11722 the current directory if the file is in the current directory or a
11723 subdirectory. Otherwise, the link will be the absolute path as
11724 completed in the minibuffer (i.e. normally ~/path/to/file).
11725
11726 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11727 is in the current directory or below.
11728 With three \\[universal-argument] prefixes, negate the meaning of
11729 `org-keep-stored-link-after-insertion'."
11730 (interactive "P")
11731 (let* ((wcf (current-window-configuration))
11732 (region (if (org-region-active-p)
11733 (buffer-substring (region-beginning) (region-end))))
11734 (remove (and region (list (region-beginning) (region-end))))
11735 (desc region)
11736 tmphist ; byte-compile incorrectly complains about this
11737 link entry file)
11738 (cond
11739 ((org-in-regexp org-bracket-link-regexp 1)
11740 ;; We do have a link at point, and we are going to edit it.
11741 (setq remove (list (match-beginning 0) (match-end 0)))
11742 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11743 (setq link (read-string "Link: "
11744 (org-link-unescape
11745 (org-match-string-no-properties 1)))))
11746 ((or (org-in-regexp org-angle-link-re)
11747 (org-in-regexp org-plain-link-re))
11748 ;; Convert to bracket link
11749 (setq remove (list (match-beginning 0) (match-end 0))
11750 link (read-string "Link: "
11751 (org-remove-angle-brackets (match-string 0)))))
11752 ((equal complete-file '(4))
11753 ;; Completing read for file names.
11754 (setq file (read-file-name "File: "))
11755 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11756 (pwd1 (file-name-as-directory (abbreviate-file-name
11757 (expand-file-name ".")))))
11758 (cond
11759 ((equal complete-file '(16))
11760 (setq link (org-make-link
11761 "file:"
11762 (abbreviate-file-name (expand-file-name file)))))
11763 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11764 (setq link (org-make-link "file:" (match-string 1 file))))
11765 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11766 (expand-file-name file))
11767 (setq link (org-make-link
11768 "file:" (match-string 1 (expand-file-name file)))))
11769 (t (setq link (org-make-link "file:" file))))))
11770 (t
11771 ;; Read link, with completion for stored links.
11772 (with-output-to-temp-buffer "*Org Links*"
11773 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
11774 (when org-stored-links
11775 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
11776 (princ (mapconcat
11777 (lambda (x)
11778 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
11779 (reverse org-stored-links) "\n"))))
11780 (let ((cw (selected-window)))
11781 (select-window (get-buffer-window "*Org Links*"))
11782 (shrink-window-if-larger-than-buffer)
11783 (setq truncate-lines t)
11784 (select-window cw))
11785 ;; Fake a link history, containing the stored links.
11786 (setq tmphist (append (mapcar 'car org-stored-links)
11787 org-insert-link-history))
11788 (unwind-protect
11789 (setq link (org-completing-read
11790 "Link: "
11791 (append
11792 (mapcar (lambda (x) (list (concat (car x) ":")))
11793 (append org-link-abbrev-alist-local org-link-abbrev-alist))
11794 (mapcar (lambda (x) (list (concat x ":")))
11795 org-link-types))
11796 nil nil nil
11797 'tmphist
11798 (or (car (car org-stored-links)))))
11799 (set-window-configuration wcf)
11800 (kill-buffer "*Org Links*"))
11801 (setq entry (assoc link org-stored-links))
11802 (or entry (push link org-insert-link-history))
11803 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11804 (not org-keep-stored-link-after-insertion))
11805 (setq org-stored-links (delq (assoc link org-stored-links)
11806 org-stored-links)))
11807 (setq desc (or desc (nth 1 entry)))))
11808
11809 (if (string-match org-plain-link-re link)
11810 ;; URL-like link, normalize the use of angular brackets.
11811 (setq link (org-make-link (org-remove-angle-brackets link))))
11812
11813 ;; Check if we are linking to the current file with a search option
11814 ;; If yes, simplify the link by using only the search option.
11815 (when (and buffer-file-name
11816 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11817 (let* ((path (match-string 1 link))
11818 (case-fold-search nil)
11819 (search (match-string 2 link)))
11820 (save-match-data
11821 (if (equal (file-truename buffer-file-name) (file-truename path))
11822 ;; We are linking to this same file, with a search option
11823 (setq link search)))))
11824
11825 ;; Check if we can/should use a relative path. If yes, simplify the link
11826 (when (string-match "\\<file:\\(.*\\)" link)
11827 (let* ((path (match-string 1 link))
11828 (origpath path)
11829 (desc-is-link (equal link desc))
11830 (case-fold-search nil))
11831 (cond
11832 ((eq org-link-file-path-type 'absolute)
11833 (setq path (abbreviate-file-name (expand-file-name path))))
11834 ((eq org-link-file-path-type 'noabbrev)
11835 (setq path (expand-file-name path)))
11836 ((eq org-link-file-path-type 'relative)
11837 (setq path (file-relative-name path)))
11838 (t
11839 (save-match-data
11840 (if (string-match (concat "^" (regexp-quote
11841 (file-name-as-directory
11842 (expand-file-name "."))))
11843 (expand-file-name path))
11844 ;; We are linking a file with relative path name.
11845 (setq path (substring (expand-file-name path)
11846 (match-end 0)))))))
11847 (setq link (concat "file:" path))
11848 (if (equal desc origpath)
11849 (setq desc path))))
11850
11851 (setq desc (read-string "Description: " desc))
11852 (unless (string-match "\\S-" desc) (setq desc nil))
11853 (if remove (apply 'delete-region remove))
11854 (insert (org-make-link-string link desc))))
11855
11856 (defun org-completing-read (&rest args)
11857 (let ((minibuffer-local-completion-map
11858 (copy-keymap minibuffer-local-completion-map)))
11859 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
11860 (apply 'completing-read args)))
11861
11862 ;;; Opening/following a link
11863 (defvar org-link-search-failed nil)
11864
11865 (defun org-next-link ()
11866 "Move forward to the next link.
11867 If the link is in hidden text, expose it."
11868 (interactive)
11869 (when (and org-link-search-failed (eq this-command last-command))
11870 (goto-char (point-min))
11871 (message "Link search wrapped back to beginning of buffer"))
11872 (setq org-link-search-failed nil)
11873 (let* ((pos (point))
11874 (ct (org-context))
11875 (a (assoc :link ct)))
11876 (if a (goto-char (nth 2 a)))
11877 (if (re-search-forward org-any-link-re nil t)
11878 (progn
11879 (goto-char (match-beginning 0))
11880 (if (org-invisible-p) (org-show-context)))
11881 (goto-char pos)
11882 (setq org-link-search-failed t)
11883 (error "No further link found"))))
11884
11885 (defun org-previous-link ()
11886 "Move backward to the previous link.
11887 If the link is in hidden text, expose it."
11888 (interactive)
11889 (when (and org-link-search-failed (eq this-command last-command))
11890 (goto-char (point-max))
11891 (message "Link search wrapped back to end of buffer"))
11892 (setq org-link-search-failed nil)
11893 (let* ((pos (point))
11894 (ct (org-context))
11895 (a (assoc :link ct)))
11896 (if a (goto-char (nth 1 a)))
11897 (if (re-search-backward org-any-link-re nil t)
11898 (progn
11899 (goto-char (match-beginning 0))
11900 (if (org-invisible-p) (org-show-context)))
11901 (goto-char pos)
11902 (setq org-link-search-failed t)
11903 (error "No further link found"))))
11904
11905 (defun org-find-file-at-mouse (ev)
11906 "Open file link or URL at mouse."
11907 (interactive "e")
11908 (mouse-set-point ev)
11909 (org-open-at-point 'in-emacs))
11910
11911 (defun org-open-at-mouse (ev)
11912 "Open file link or URL at mouse."
11913 (interactive "e")
11914 (mouse-set-point ev)
11915 (org-open-at-point))
11916
11917 (defvar org-window-config-before-follow-link nil
11918 "The window configuration before following a link.
11919 This is saved in case the need arises to restore it.")
11920
11921 (defvar org-open-link-marker (make-marker)
11922 "Marker pointing to the location where `org-open-at-point; was called.")
11923
11924 ;;;###autoload
11925 (defun org-open-at-point-global ()
11926 "Follow a link like Org-mode does.
11927 This command can be called in any mode to follow a link that has
11928 Org-mode syntax."
11929 (interactive)
11930 (org-run-like-in-org-mode 'org-open-at-point))
11931
11932 (defun org-open-at-point (&optional in-emacs)
11933 "Open link at or after point.
11934 If there is no link at point, this function will search forward up to
11935 the end of the current subtree.
11936 Normally, files will be opened by an appropriate application. If the
11937 optional argument IN-EMACS is non-nil, Emacs will visit the file."
11938 (interactive "P")
11939 (move-marker org-open-link-marker (point))
11940 (setq org-window-config-before-follow-link (current-window-configuration))
11941 (org-remove-occur-highlights nil nil t)
11942 (if (org-at-timestamp-p t)
11943 (org-follow-timestamp-link)
11944 (let (type path link line search (pos (point)))
11945 (catch 'match
11946 (save-excursion
11947 (skip-chars-forward "^]\n\r")
11948 (when (org-in-regexp org-bracket-link-regexp)
11949 (setq link (org-link-unescape (org-match-string-no-properties 1)))
11950 (while (string-match " *\n *" link)
11951 (setq link (replace-match " " t t link)))
11952 (setq link (org-link-expand-abbrev link))
11953 (if (string-match org-link-re-with-space2 link)
11954 (setq type (match-string 1 link) path (match-string 2 link))
11955 (setq type "thisfile" path link))
11956 (throw 'match t)))
11957
11958 (when (get-text-property (point) 'org-linked-text)
11959 (setq type "thisfile"
11960 pos (if (get-text-property (1+ (point)) 'org-linked-text)
11961 (1+ (point)) (point))
11962 path (buffer-substring
11963 (previous-single-property-change pos 'org-linked-text)
11964 (next-single-property-change pos 'org-linked-text)))
11965 (throw 'match t))
11966
11967 (save-excursion
11968 (when (or (org-in-regexp org-angle-link-re)
11969 (org-in-regexp org-plain-link-re))
11970 (setq type (match-string 1) path (match-string 2))
11971 (throw 'match t)))
11972 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
11973 (setq type "tree-match"
11974 path (match-string 1))
11975 (throw 'match t))
11976 (save-excursion
11977 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
11978 (setq type "tags"
11979 path (match-string 1))
11980 (while (string-match ":" path)
11981 (setq path (replace-match "+" t t path)))
11982 (throw 'match t))))
11983 (unless path
11984 (error "No link found"))
11985 ;; Remove any trailing spaces in path
11986 (if (string-match " +\\'" path)
11987 (setq path (replace-match "" t t path)))
11988
11989 (cond
11990
11991 ((assoc type org-link-protocols)
11992 (funcall (nth 1 (assoc type org-link-protocols)) path))
11993
11994 ((equal type "mailto")
11995 (let ((cmd (car org-link-mailto-program))
11996 (args (cdr org-link-mailto-program)) args1
11997 (address path) (subject "") a)
11998 (if (string-match "\\(.*\\)::\\(.*\\)" path)
11999 (setq address (match-string 1 path)
12000 subject (org-link-escape (match-string 2 path))))
12001 (while args
12002 (cond
12003 ((not (stringp (car args))) (push (pop args) args1))
12004 (t (setq a (pop args))
12005 (if (string-match "%a" a)
12006 (setq a (replace-match address t t a)))
12007 (if (string-match "%s" a)
12008 (setq a (replace-match subject t t a)))
12009 (push a args1))))
12010 (apply cmd (nreverse args1))))
12011
12012 ((member type '("http" "https" "ftp" "news"))
12013 (browse-url (concat type ":" (org-link-escape
12014 path org-link-escape-chars-browser))))
12015
12016 ((string= type "tags")
12017 (org-tags-view in-emacs path))
12018 ((string= type "thisfile")
12019 (if in-emacs
12020 (switch-to-buffer-other-window
12021 (org-get-buffer-for-internal-link (current-buffer)))
12022 (org-mark-ring-push))
12023 (let ((cmd `(org-link-search
12024 ,path
12025 ,(cond ((equal in-emacs '(4)) 'occur)
12026 ((equal in-emacs '(16)) 'org-occur)
12027 (t nil))
12028 ,pos)))
12029 (condition-case nil (eval cmd)
12030 (error (progn (widen) (eval cmd))))))
12031
12032 ((string= type "tree-match")
12033 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12034
12035 ((string= type "file")
12036 (if (string-match "::\\([0-9]+\\)\\'" path)
12037 (setq line (string-to-number (match-string 1 path))
12038 path (substring path 0 (match-beginning 0)))
12039 (if (string-match "::\\(.+\\)\\'" path)
12040 (setq search (match-string 1 path)
12041 path (substring path 0 (match-beginning 0)))))
12042 (org-open-file path in-emacs line search))
12043
12044 ((string= type "news")
12045 (org-follow-gnus-link path))
12046
12047 ((string= type "bbdb")
12048 (org-follow-bbdb-link path))
12049
12050 ((string= type "info")
12051 (org-follow-info-link path))
12052
12053 ((string= type "gnus")
12054 (let (group article)
12055 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12056 (error "Error in Gnus link"))
12057 (setq group (match-string 1 path)
12058 article (match-string 3 path))
12059 (org-follow-gnus-link group article)))
12060
12061 ((string= type "vm")
12062 (let (folder article)
12063 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12064 (error "Error in VM link"))
12065 (setq folder (match-string 1 path)
12066 article (match-string 3 path))
12067 ;; in-emacs is the prefix arg, will be interpreted as read-only
12068 (org-follow-vm-link folder article in-emacs)))
12069
12070 ((string= type "wl")
12071 (let (folder article)
12072 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12073 (error "Error in Wanderlust link"))
12074 (setq folder (match-string 1 path)
12075 article (match-string 3 path))
12076 (org-follow-wl-link folder article)))
12077
12078 ((string= type "mhe")
12079 (let (folder article)
12080 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12081 (error "Error in MHE link"))
12082 (setq folder (match-string 1 path)
12083 article (match-string 3 path))
12084 (org-follow-mhe-link folder article)))
12085
12086 ((string= type "rmail")
12087 (let (folder article)
12088 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12089 (error "Error in RMAIL link"))
12090 (setq folder (match-string 1 path)
12091 article (match-string 3 path))
12092 (org-follow-rmail-link folder article)))
12093
12094 ((string= type "shell")
12095 (let ((cmd path))
12096 ;; The following is only for backward compatibility
12097 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
12098 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
12099 (if (or (not org-confirm-shell-link-function)
12100 (funcall org-confirm-shell-link-function
12101 (format "Execute \"%s\" in shell? "
12102 (org-add-props cmd nil
12103 'face 'org-warning))))
12104 (progn
12105 (message "Executing %s" cmd)
12106 (shell-command cmd))
12107 (error "Abort"))))
12108
12109 ((string= type "elisp")
12110 (let ((cmd path))
12111 (if (or (not org-confirm-elisp-link-function)
12112 (funcall org-confirm-elisp-link-function
12113 (format "Execute \"%s\" as elisp? "
12114 (org-add-props cmd nil
12115 'face 'org-warning))))
12116 (message "%s => %s" cmd (eval (read cmd)))
12117 (error "Abort"))))
12118
12119 (t
12120 (browse-url-at-point)))))
12121 (move-marker org-open-link-marker nil))
12122
12123 ;;; File search
12124
12125 (defvar org-create-file-search-functions nil
12126 "List of functions to construct the right search string for a file link.
12127 These functions are called in turn with point at the location to
12128 which the link should point.
12129
12130 A function in the hook should first test if it would like to
12131 handle this file type, for example by checking the major-mode or
12132 the file extension. If it decides not to handle this file, it
12133 should just return nil to give other functions a chance. If it
12134 does handle the file, it must return the search string to be used
12135 when following the link. The search string will be part of the
12136 file link, given after a double colon, and `org-open-at-point'
12137 will automatically search for it. If special measures must be
12138 taken to make the search successful, another function should be
12139 added to the companion hook `org-execute-file-search-functions',
12140 which see.
12141
12142 A function in this hook may also use `setq' to set the variable
12143 `description' to provide a suggestion for the descriptive text to
12144 be used for this link when it gets inserted into an Org-mode
12145 buffer with \\[org-insert-link].")
12146
12147 (defvar org-execute-file-search-functions nil
12148 "List of functions to execute a file search triggered by a link.
12149
12150 Functions added to this hook must accept a single argument, the
12151 search string that was part of the file link, the part after the
12152 double colon. The function must first check if it would like to
12153 handle this search, for example by checking the major-mode or the
12154 file extension. If it decides not to handle this search, it
12155 should just return nil to give other functions a chance. If it
12156 does handle the search, it must return a non-nil value to keep
12157 other functions from trying.
12158
12159 Each function can access the current prefix argument through the
12160 variable `current-prefix-argument'. Note that a single prefix is
12161 used to force opening a link in Emacs, so it may be good to only
12162 use a numeric or double prefix to guide the search function.
12163
12164 In case this is needed, a function in this hook can also restore
12165 the window configuration before `org-open-at-point' was called using:
12166
12167 (set-window-configuration org-window-config-before-follow-link)")
12168
12169 (defun org-link-search (s &optional type avoid-pos)
12170 "Search for a link search option.
12171 If S is surrounded by forward slashes, it is interpreted as a
12172 regular expression. In org-mode files, this will create an `org-occur'
12173 sparse tree. In ordinary files, `occur' will be used to list matches.
12174 If the current buffer is in `dired-mode', grep will be used to search
12175 in all files. If AVOID-POS is given, ignore matches near that position."
12176 (let ((case-fold-search t)
12177 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12178 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12179 (append '(("") (" ") ("\t") ("\n"))
12180 org-emphasis-alist)
12181 "\\|") "\\)"))
12182 (pos (point))
12183 (pre "") (post "")
12184 words re0 re1 re2 re3 re4 re5 re2a reall)
12185 (cond
12186 ;; First check if there are any special
12187 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12188 ;; Now try the builtin stuff
12189 ((save-excursion
12190 (goto-char (point-min))
12191 (and
12192 (re-search-forward
12193 (concat "<<" (regexp-quote s0) ">>") nil t)
12194 (setq pos (match-beginning 0))))
12195 ;; There is an exact target for this
12196 (goto-char pos))
12197 ((string-match "^/\\(.*\\)/$" s)
12198 ;; A regular expression
12199 (cond
12200 ((org-mode-p)
12201 (org-occur (match-string 1 s)))
12202 ;;((eq major-mode 'dired-mode)
12203 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12204 (t (org-do-occur (match-string 1 s)))))
12205 (t
12206 ;; A normal search strings
12207 (when (equal (string-to-char s) ?*)
12208 ;; Anchor on headlines, post may include tags.
12209 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12210 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12211 s (substring s 1)))
12212 (remove-text-properties
12213 0 (length s)
12214 '(face nil mouse-face nil keymap nil fontified nil) s)
12215 ;; Make a series of regular expressions to find a match
12216 (setq words (org-split-string s "[ \n\r\t]+")
12217 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12218 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12219 "\\)" markers)
12220 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12221 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12222 re1 (concat pre re2 post)
12223 re3 (concat pre re4 post)
12224 re5 (concat pre ".*" re4)
12225 re2 (concat pre re2)
12226 re2a (concat pre re2a)
12227 re4 (concat pre re4)
12228 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12229 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12230 re5 "\\)"
12231 ))
12232 (cond
12233 ((eq type 'org-occur) (org-occur reall))
12234 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12235 (t (goto-char (point-min))
12236 (if (or (org-search-not-self 1 re0 nil t)
12237 (org-search-not-self 1 re1 nil t)
12238 (org-search-not-self 1 re2 nil t)
12239 (org-search-not-self 1 re2a nil t)
12240 (org-search-not-self 1 re3 nil t)
12241 (org-search-not-self 1 re4 nil t)
12242 (org-search-not-self 1 re5 nil t)
12243 )
12244 (goto-char (match-beginning 1))
12245 (goto-char pos)
12246 (error "No match")))))
12247 (t
12248 ;; Normal string-search
12249 (goto-char (point-min))
12250 (if (search-forward s nil t)
12251 (goto-char (match-beginning 0))
12252 (error "No match"))))
12253 (and (org-mode-p) (org-show-context 'link-search))))
12254
12255 (defun org-search-not-self (group &rest args)
12256 "Execute `re-search-forward', but only accept matches that do not
12257 enclose the position of `org-open-link-marker'."
12258 (let ((m org-open-link-marker))
12259 (catch 'exit
12260 (while (apply 're-search-forward args)
12261 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12262 (goto-char (match-end group))
12263 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12264 (> (match-beginning 0) (marker-position m))
12265 (< (match-end 0) (marker-position m)))
12266 (save-match-data
12267 (or (not (org-in-regexp
12268 org-bracket-link-analytic-regexp 1))
12269 (not (match-end 4)) ; no description
12270 (and (<= (match-beginning 4) (point))
12271 (>= (match-end 4) (point))))))
12272 (throw 'exit (point))))))))
12273
12274 (defun org-get-buffer-for-internal-link (buffer)
12275 "Return a buffer to be used for displaying the link target of internal links."
12276 (cond
12277 ((not org-display-internal-link-with-indirect-buffer)
12278 buffer)
12279 ((string-match "(Clone)$" (buffer-name buffer))
12280 (message "Buffer is already a clone, not making another one")
12281 ;; we also do not modify visibility in this case
12282 buffer)
12283 (t ; make a new indirect buffer for displaying the link
12284 (let* ((bn (buffer-name buffer))
12285 (ibn (concat bn "(Clone)"))
12286 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12287 (with-current-buffer ib (org-overview))
12288 ib))))
12289
12290 (defun org-do-occur (regexp &optional cleanup)
12291 "Call the Emacs command `occur'.
12292 If CLEANUP is non-nil, remove the printout of the regular expression
12293 in the *Occur* buffer. This is useful if the regex is long and not useful
12294 to read."
12295 (occur regexp)
12296 (when cleanup
12297 (let ((cwin (selected-window)) win beg end)
12298 (when (setq win (get-buffer-window "*Occur*"))
12299 (select-window win))
12300 (goto-char (point-min))
12301 (when (re-search-forward "match[a-z]+" nil t)
12302 (setq beg (match-end 0))
12303 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12304 (setq end (1- (match-beginning 0)))))
12305 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12306 (goto-char (point-min))
12307 (select-window cwin))))
12308
12309 ;;; The mark ring for links jumps
12310
12311 (defvar org-mark-ring nil
12312 "Mark ring for positions before jumps in Org-mode.")
12313 (defvar org-mark-ring-last-goto nil
12314 "Last position in the mark ring used to go back.")
12315 ;; Fill and close the ring
12316 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12317 (loop for i from 1 to org-mark-ring-length do
12318 (push (make-marker) org-mark-ring))
12319 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12320 org-mark-ring)
12321
12322 (defun org-mark-ring-push (&optional pos buffer)
12323 "Put the current position or POS into the mark ring and rotate it."
12324 (interactive)
12325 (setq pos (or pos (point)))
12326 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12327 (move-marker (car org-mark-ring)
12328 (or pos (point))
12329 (or buffer (current-buffer)))
12330 (message
12331 (substitute-command-keys
12332 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12333
12334 (defun org-mark-ring-goto (&optional n)
12335 "Jump to the previous position in the mark ring.
12336 With prefix arg N, jump back that many stored positions. When
12337 called several times in succession, walk through the entire ring.
12338 Org-mode commands jumping to a different position in the current file,
12339 or to another Org-mode file, automatically push the old position
12340 onto the ring."
12341 (interactive "p")
12342 (let (p m)
12343 (if (eq last-command this-command)
12344 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12345 (setq p org-mark-ring))
12346 (setq org-mark-ring-last-goto p)
12347 (setq m (car p))
12348 (switch-to-buffer (marker-buffer m))
12349 (goto-char m)
12350 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12351
12352 (defun org-remove-angle-brackets (s)
12353 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12354 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12355 s)
12356 (defun org-add-angle-brackets (s)
12357 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12358 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12359 s)
12360
12361 ;;; Following specific links
12362
12363 (defun org-follow-timestamp-link ()
12364 (cond
12365 ((org-at-date-range-p t)
12366 (let ((org-agenda-start-on-weekday)
12367 (t1 (match-string 1))
12368 (t2 (match-string 2)))
12369 (setq t1 (time-to-days (org-time-string-to-time t1))
12370 t2 (time-to-days (org-time-string-to-time t2)))
12371 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12372 ((org-at-timestamp-p t)
12373 (org-agenda-list nil (time-to-days (org-time-string-to-time
12374 (substring (match-string 1) 0 10)))
12375 1))
12376 (t (error "This should not happen"))))
12377
12378
12379 (defun org-follow-bbdb-link (name)
12380 "Follow a BBDB link to NAME."
12381 (require 'bbdb)
12382 (let ((inhibit-redisplay (not debug-on-error))
12383 (bbdb-electric-p nil))
12384 (catch 'exit
12385 ;; Exact match on name
12386 (bbdb-name (concat "\\`" name "\\'") nil)
12387 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12388 ;; Exact match on name
12389 (bbdb-company (concat "\\`" name "\\'") nil)
12390 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12391 ;; Partial match on name
12392 (bbdb-name name nil)
12393 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12394 ;; Partial match on company
12395 (bbdb-company name nil)
12396 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12397 ;; General match including network address and notes
12398 (bbdb name nil)
12399 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12400 (delete-window (get-buffer-window "*BBDB*"))
12401 (error "No matching BBDB record")))))
12402
12403 (defun org-follow-info-link (name)
12404 "Follow an info file & node link to NAME."
12405 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12406 (string-match "\\(.*\\)" name))
12407 (progn
12408 (require 'info)
12409 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12410 (Info-find-node (match-string 1 name) (match-string 2 name))
12411 (Info-find-node (match-string 1 name) "Top")))
12412 (message (concat "Could not open: " name))))
12413
12414 (defun org-follow-gnus-link (&optional group article)
12415 "Follow a Gnus link to GROUP and ARTICLE."
12416 (require 'gnus)
12417 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12418 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12419 (cond ((and group article)
12420 (gnus-group-read-group 1 nil group)
12421 (gnus-summary-goto-article (string-to-number article) nil t))
12422 (group (gnus-group-jump-to-group group))))
12423
12424 (defun org-follow-vm-link (&optional folder article readonly)
12425 "Follow a VM link to FOLDER and ARTICLE."
12426 (require 'vm)
12427 (setq article (org-add-angle-brackets article))
12428 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12429 ;; ange-ftp or efs or tramp access
12430 (let ((user (or (match-string 1 folder) (user-login-name)))
12431 (host (match-string 2 folder))
12432 (file (match-string 3 folder)))
12433 (cond
12434 ((featurep 'tramp)
12435 ;; use tramp to access the file
12436 (if (featurep 'xemacs)
12437 (setq folder (format "[%s@%s]%s" user host file))
12438 (setq folder (format "/%s@%s:%s" user host file))))
12439 (t
12440 ;; use ange-ftp or efs
12441 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12442 (setq folder (format "/%s@%s:%s" user host file))))))
12443 (when folder
12444 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12445 (sit-for 0.1)
12446 (when article
12447 (vm-select-folder-buffer)
12448 (widen)
12449 (let ((case-fold-search t))
12450 (goto-char (point-min))
12451 (if (not (re-search-forward
12452 (concat "^" "message-id: *" (regexp-quote article))))
12453 (error "Could not find the specified message in this folder"))
12454 (vm-isearch-update)
12455 (vm-isearch-narrow)
12456 (vm-beginning-of-message)
12457 (vm-summarize)))))
12458
12459 (defun org-follow-wl-link (folder article)
12460 "Follow a Wanderlust link to FOLDER and ARTICLE."
12461 (if (and (string= folder "%")
12462 article
12463 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12464 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12465 ;; Thus, we recompose folder and article ids.
12466 (setq folder (format "%s#%s" folder (match-string 1 article))
12467 article (match-string 3 article)))
12468 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12469 (error "No such folder: %s" folder))
12470 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12471 (and article
12472 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12473 (wl-summary-redisplay)))
12474
12475 (defun org-follow-rmail-link (folder article)
12476 "Follow an RMAIL link to FOLDER and ARTICLE."
12477 (setq article (org-add-angle-brackets article))
12478 (let (message-number)
12479 (save-excursion
12480 (save-window-excursion
12481 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12482 (setq message-number
12483 (save-restriction
12484 (widen)
12485 (goto-char (point-max))
12486 (if (re-search-backward
12487 (concat "^Message-ID:\\s-+" (regexp-quote
12488 (or article "")))
12489 nil t)
12490 (rmail-what-message))))))
12491 (if message-number
12492 (progn
12493 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12494 (rmail-show-message message-number)
12495 message-number)
12496 (error "Message not found"))))
12497
12498 ;;; mh-e integration based on planner-mode
12499 (defun org-mhe-get-message-real-folder ()
12500 "Return the name of the current message real folder, so if you use
12501 sequences, it will now work."
12502 (save-excursion
12503 (let* ((folder
12504 (if (equal major-mode 'mh-folder-mode)
12505 mh-current-folder
12506 ;; Refer to the show buffer
12507 mh-show-folder-buffer))
12508 (end-index
12509 (if (boundp 'mh-index-folder)
12510 (min (length mh-index-folder) (length folder))))
12511 )
12512 ;; a simple test on mh-index-data does not work, because
12513 ;; mh-index-data is always nil in a show buffer.
12514 (if (and (boundp 'mh-index-folder)
12515 (string= mh-index-folder (substring folder 0 end-index)))
12516 (if (equal major-mode 'mh-show-mode)
12517 (save-window-excursion
12518 (let (pop-up-frames)
12519 (when (buffer-live-p (get-buffer folder))
12520 (progn
12521 (pop-to-buffer folder)
12522 (org-mhe-get-message-folder-from-index)
12523 )
12524 )))
12525 (org-mhe-get-message-folder-from-index)
12526 )
12527 folder
12528 )
12529 )))
12530
12531 (defun org-mhe-get-message-folder-from-index ()
12532 "Returns the name of the message folder in a index folder buffer."
12533 (save-excursion
12534 (mh-index-previous-folder)
12535 (re-search-forward "^\\(+.*\\)$" nil t)
12536 (message (match-string 1))))
12537
12538 (defun org-mhe-get-message-folder ()
12539 "Return the name of the current message folder. Be careful if you
12540 use sequences."
12541 (save-excursion
12542 (if (equal major-mode 'mh-folder-mode)
12543 mh-current-folder
12544 ;; Refer to the show buffer
12545 mh-show-folder-buffer)))
12546
12547 (defun org-mhe-get-message-num ()
12548 "Return the number of the current message. Be careful if you
12549 use sequences."
12550 (save-excursion
12551 (if (equal major-mode 'mh-folder-mode)
12552 (mh-get-msg-num nil)
12553 ;; Refer to the show buffer
12554 (mh-show-buffer-message-number))))
12555
12556 (defun org-mhe-get-header (header)
12557 "Return a header of the message in folder mode. This will create a
12558 show buffer for the corresponding message. If you have a more clever
12559 idea..."
12560 (let* ((folder (org-mhe-get-message-folder))
12561 (num (org-mhe-get-message-num))
12562 (buffer (get-buffer-create (concat "show-" folder)))
12563 (header-field))
12564 (with-current-buffer buffer
12565 (mh-display-msg num folder)
12566 (if (equal major-mode 'mh-folder-mode)
12567 (mh-header-display)
12568 (mh-show-header-display))
12569 (set-buffer buffer)
12570 (setq header-field (mh-get-header-field header))
12571 (if (equal major-mode 'mh-folder-mode)
12572 (mh-show)
12573 (mh-show-show))
12574 header-field)))
12575
12576 (defun org-follow-mhe-link (folder article)
12577 "Follow an MHE link to FOLDER and ARTICLE.
12578 If ARTICLE is nil FOLDER is shown. If the configuration variable
12579 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
12580 ARTICLE is searched in all folders. Indexed searches (swish++,
12581 namazu, and others supported by MH-E) will always search in all
12582 folders."
12583 (require 'mh-e)
12584 (require 'mh-search)
12585 (require 'mh-utils)
12586 (mh-find-path)
12587 (if (not article)
12588 (mh-visit-folder (mh-normalize-folder-name folder))
12589 (setq article (org-add-angle-brackets article))
12590 (mh-search-choose)
12591 (if (equal mh-searcher 'pick)
12592 (progn
12593 (mh-search folder (list "--message-id" article))
12594 (when (and org-mhe-search-all-folders
12595 (not (org-mhe-get-message-real-folder)))
12596 (kill-this-buffer)
12597 (mh-search "+" (list "--message-id" article))))
12598 (mh-search "+" article))
12599 (if (org-mhe-get-message-real-folder)
12600 (mh-show-msg 1)
12601 (kill-this-buffer)
12602 (error "Message not found"))))
12603
12604 ;;; BibTeX links
12605
12606 ;; Use the custom search meachnism to construct and use search strings for
12607 ;; file links to BibTeX database entries.
12608
12609 (defun org-create-file-search-in-bibtex ()
12610 "Create the search string and description for a BibTeX database entry."
12611 (when (eq major-mode 'bibtex-mode)
12612 ;; yes, we want to construct this search string.
12613 ;; Make a good description for this entry, using names, year and the title
12614 ;; Put it into the `description' variable which is dynamically scoped.
12615 (let ((bibtex-autokey-names 1)
12616 (bibtex-autokey-names-stretch 1)
12617 (bibtex-autokey-name-case-convert-function 'identity)
12618 (bibtex-autokey-name-separator " & ")
12619 (bibtex-autokey-additional-names " et al.")
12620 (bibtex-autokey-year-length 4)
12621 (bibtex-autokey-name-year-separator " ")
12622 (bibtex-autokey-titlewords 3)
12623 (bibtex-autokey-titleword-separator " ")
12624 (bibtex-autokey-titleword-case-convert-function 'identity)
12625 (bibtex-autokey-titleword-length 'infty)
12626 (bibtex-autokey-year-title-separator ": "))
12627 (setq description (bibtex-generate-autokey)))
12628 ;; Now parse the entry, get the key and return it.
12629 (save-excursion
12630 (bibtex-beginning-of-entry)
12631 (cdr (assoc "=key=" (bibtex-parse-entry))))))
12632
12633 (defun org-execute-file-search-in-bibtex (s)
12634 "Find the link search string S as a key for a database entry."
12635 (when (eq major-mode 'bibtex-mode)
12636 ;; Yes, we want to do the search in this file.
12637 ;; We construct a regexp that searches for "@entrytype{" followed by the key
12638 (goto-char (point-min))
12639 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
12640 (regexp-quote s) "[ \t\n]*,") nil t)
12641 (goto-char (match-beginning 0)))
12642 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
12643 ;; Use double prefix to indicate that any web link should be browsed
12644 (let ((b (current-buffer)) (p (point)))
12645 ;; Restore the window configuration because we just use the web link
12646 (set-window-configuration org-window-config-before-follow-link)
12647 (save-excursion (set-buffer b) (goto-char p)
12648 (bibtex-url)))
12649 (recenter 0)) ; Move entry start to beginning of window
12650 ;; return t to indicate that the search is done.
12651 t))
12652
12653 ;; Finally add the functions to the right hooks.
12654 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
12655 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
12656
12657 ;; end of Bibtex link setup
12658
12659 ;;; Following file links
12660
12661 (defun org-open-file (path &optional in-emacs line search)
12662 "Open the file at PATH.
12663 First, this expands any special file name abbreviations. Then the
12664 configuration variable `org-file-apps' is checked if it contains an
12665 entry for this file type, and if yes, the corresponding command is launched.
12666 If no application is found, Emacs simply visits the file.
12667 With optional argument IN-EMACS, Emacs will visit the file.
12668 Optional LINE specifies a line to go to, optional SEARCH a string to
12669 search for. If LINE or SEARCH is given, the file will always be
12670 opened in Emacs.
12671 If the file does not exist, an error is thrown."
12672 (setq in-emacs (or in-emacs line search))
12673 (let* ((file (if (equal path "")
12674 buffer-file-name
12675 (substitute-in-file-name (expand-file-name path))))
12676 (apps (append org-file-apps (org-default-apps)))
12677 (remp (and (assq 'remote apps) (org-file-remote-p file)))
12678 (dirp (if remp nil (file-directory-p file)))
12679 (dfile (downcase file))
12680 (old-buffer (current-buffer))
12681 (old-pos (point))
12682 (old-mode major-mode)
12683 ext cmd)
12684 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
12685 (setq ext (match-string 1 dfile))
12686 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
12687 (setq ext (match-string 1 dfile))))
12688 (if in-emacs
12689 (setq cmd 'emacs)
12690 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
12691 (and dirp (cdr (assoc 'directory apps)))
12692 (cdr (assoc ext apps))
12693 (cdr (assoc t apps)))))
12694 (when (eq cmd 'mailcap)
12695 (require 'mailcap)
12696 (mailcap-parse-mailcaps)
12697 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
12698 (command (mailcap-mime-info mime-type)))
12699 (if (stringp command)
12700 (setq cmd command)
12701 (setq cmd 'emacs))))
12702 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
12703 (not (file-exists-p file))
12704 (not org-open-non-existing-files))
12705 (error "No such file: %s" file))
12706 (cond
12707 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
12708 ;; Remove quotes around the file name - we'll use shell-quote-argument.
12709 (if (string-match "['\"]%s['\"]" cmd)
12710 (setq cmd (replace-match "%s" t t cmd)))
12711 (setq cmd (format cmd (shell-quote-argument file)))
12712 (save-window-excursion
12713 (start-process-shell-command cmd nil cmd)))
12714 ((or (stringp cmd)
12715 (eq cmd 'emacs))
12716 (funcall (cdr (assq 'file org-link-frame-setup)) file)
12717 (widen)
12718 (if line (goto-line line)
12719 (if search (org-link-search search))))
12720 ((consp cmd)
12721 (eval cmd))
12722 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
12723 (and (org-mode-p) (eq old-mode 'org-mode)
12724 (or (not (equal old-buffer (current-buffer)))
12725 (not (equal old-pos (point))))
12726 (org-mark-ring-push old-pos old-buffer))))
12727
12728 (defun org-default-apps ()
12729 "Return the default applications for this operating system."
12730 (cond
12731 ((eq system-type 'darwin)
12732 org-file-apps-defaults-macosx)
12733 ((eq system-type 'windows-nt)
12734 org-file-apps-defaults-windowsnt)
12735 (t org-file-apps-defaults-gnu)))
12736
12737 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
12738 (defun org-file-remote-p (file)
12739 "Test whether FILE specifies a location on a remote system.
12740 Return non-nil if the location is indeed remote.
12741
12742 For example, the filename \"/user@host:/foo\" specifies a location
12743 on the system \"/user@host:\"."
12744 (cond ((fboundp 'file-remote-p)
12745 (file-remote-p file))
12746 ((fboundp 'tramp-handle-file-remote-p)
12747 (tramp-handle-file-remote-p file))
12748 ((and (boundp 'ange-ftp-name-format)
12749 (string-match (car ange-ftp-name-format) file))
12750 t)
12751 (t nil)))
12752
12753
12754 ;;;; Hooks for remember.el
12755
12756 ;;;###autoload
12757 (defun org-remember-annotation ()
12758 "Return a link to the current location as an annotation for remember.el.
12759 If you are using Org-mode files as target for data storage with
12760 remember.el, then the annotations should include a link compatible with the
12761 conventions in Org-mode. This function returns such a link."
12762 (org-store-link nil))
12763
12764 (defconst org-remember-help
12765 "Select a destination location for the note.
12766 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
12767 RET on headline -> Store as sublevel entry to current headline
12768 RET at beg-of-buf -> Append to file as level 2 headline
12769 <left>/<right> -> before/after current headline, same headings level")
12770
12771 (defvar org-remember-previous-location nil)
12772 (defvar org-force-remember-template-char) ;; dynamically scoped
12773
12774 ;;;###autoload
12775 (defun org-remember-apply-template (&optional use-char skip-interactive)
12776 "Initialize *remember* buffer with template, invoke `org-mode'.
12777 This function should be placed into `remember-mode-hook' and in fact requires
12778 to be run from that hook to fucntion properly."
12779 (if org-remember-templates
12780 (let* ((templates (mapcar (lambda (x)
12781 (if (stringp (car x))
12782 (append (list (nth 1 x) (car x)) (cddr x))
12783 (append (list (car x) "") (cdr x))))
12784 org-remember-templates))
12785 (char (or use-char
12786 (cond
12787 ((= (length templates) 1)
12788 (caar templates))
12789 ((and (boundp 'org-force-remember-template-char)
12790 org-force-remember-template-char)
12791 (if (stringp org-force-remember-template-char)
12792 (string-to-char org-force-remember-template-char)
12793 org-force-remember-template-char))
12794 (t
12795 (message "Select template: %s"
12796 (mapconcat
12797 (lambda (x)
12798 (cond
12799 ((not (string-match "\\S-" (nth 1 x)))
12800 (format "[%c]" (car x)))
12801 ((equal (downcase (car x))
12802 (downcase (aref (nth 1 x) 0)))
12803 (format "[%c]%s" (car x) (substring (nth 1 x) 1)))
12804 (t (format "[%c]%s" (car x) (nth 1 x)))))
12805 templates " "))
12806 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
12807 (when (equal char0 ?\C-g)
12808 (jump-to-register remember-register)
12809 (kill-buffer remember-buffer))
12810 char0)))))
12811 (entry (cddr (assoc char templates)))
12812 (tpl (car entry))
12813 (plist-p (if org-store-link-plist t nil))
12814 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
12815 (string-match "\\S-" (nth 1 entry)))
12816 (nth 1 entry)
12817 org-default-notes-file))
12818 (headline (nth 2 entry))
12819 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
12820 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
12821 (v-u (concat "[" (substring v-t 1 -1) "]"))
12822 (v-U (concat "[" (substring v-T 1 -1) "]"))
12823 ;; `initial' and `annotation' are bound in `remember'
12824 (v-i (if (boundp 'initial) initial))
12825 (v-a (if (and (boundp 'annotation) annotation)
12826 (if (equal annotation "[[]]") "" annotation)
12827 ""))
12828 (v-A (if (and v-a
12829 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
12830 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
12831 v-a))
12832 (v-n user-full-name)
12833 (org-startup-folded nil)
12834 org-time-was-given org-end-time-was-given x prompt char time)
12835 (setq org-store-link-plist
12836 (append (list :annotation v-a :initial v-i)
12837 org-store-link-plist))
12838 (unless tpl (setq tpl "") (message "No template") (ding))
12839 (erase-buffer)
12840 (insert (substitute-command-keys
12841 (format
12842 "## Filing location: Select interactively, default, or last used:
12843 ## %s to select file and header location interactively.
12844 ## %s \"%s\" -> \"* %s\"
12845 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
12846 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
12847 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
12848 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
12849 (abbreviate-file-name (or file org-default-notes-file))
12850 (or headline "")
12851 (or (car org-remember-previous-location) "???")
12852 (or (cdr org-remember-previous-location) "???"))))
12853 (insert tpl) (goto-char (point-min))
12854 ;; Simple %-escapes
12855 (while (re-search-forward "%\\([tTuUaiA]\\)" nil t)
12856 (when (and initial (equal (match-string 0) "%i"))
12857 (save-match-data
12858 (let* ((lead (buffer-substring
12859 (point-at-bol) (match-beginning 0))))
12860 (setq v-i (mapconcat 'identity
12861 (org-split-string initial "\n")
12862 (concat "\n" lead))))))
12863 (replace-match
12864 (or (eval (intern (concat "v-" (match-string 1)))) "")
12865 t t))
12866 ;; From the property list
12867 (when plist-p
12868 (goto-char (point-min))
12869 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
12870 (and (setq x (plist-get org-store-link-plist
12871 (intern (match-string 1))))
12872 (replace-match x t t))))
12873 ;; Turn on org-mode in the remember buffer, set local variables
12874 (org-mode)
12875 (org-set-local 'org-finish-function 'remember-buffer)
12876 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
12877 (org-set-local 'org-default-notes-file file))
12878 (if (and headline (stringp headline) (string-match "\\S-" headline))
12879 (org-set-local 'org-remember-default-headline headline))
12880 ;; Interactive template entries
12881 (goto-char (point-min))
12882 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
12883 (setq char (if (match-end 3) (match-string 3))
12884 prompt (if (match-end 2) (match-string 2)))
12885 (goto-char (match-beginning 0))
12886 (replace-match "")
12887 (cond
12888 ((member char '("G" "g"))
12889 (let* ((org-last-tags-completion-table
12890 (org-global-tags-completion-table
12891 (if (equal char "G") (org-agenda-files) (and file (list file)))))
12892 (org-add-colon-after-tag-completion t)
12893 (ins (completing-read
12894 (if prompt (concat prompt ": ") "Tags: ")
12895 'org-tags-completion-function nil nil nil
12896 'org-tags-history)))
12897 (setq ins (mapconcat 'identity
12898 (org-split-string ins (org-re "[^[:alnum:]]+"))
12899 ":"))
12900 (when (string-match "\\S-" ins)
12901 (or (equal (char-before) ?:) (insert ":"))
12902 (insert ins)
12903 (or (equal (char-after) ?:) (insert ":")))))
12904 (char
12905 (setq org-time-was-given (equal (upcase char) char))
12906 (setq time (org-read-date (equal (upcase char) "U") t nil
12907 prompt))
12908 (org-insert-time-stamp time org-time-was-given
12909 (member char '("u" "U"))
12910 nil nil (list org-end-time-was-given)))
12911 (t
12912 (insert (read-string
12913 (if prompt (concat prompt ": ") "Enter string"))))))
12914 (goto-char (point-min))
12915 (if (re-search-forward "%\\?" nil t)
12916 (replace-match "")
12917 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
12918 (org-mode)
12919 (org-set-local 'org-finish-function 'remember-buffer)))
12920
12921 ;;;###autoload
12922 (defun org-remember (&optional org-force-remember-template-char)
12923 "Call `remember'. If this is already a remember buffer, re-apply template.
12924 If there is an active region, make sure remember uses it as initial content
12925 of the remember buffer."
12926 (interactive)
12927 (if (eq org-finish-function 'remember-buffer)
12928 (progn
12929 (when (< (length org-remember-templates) 2)
12930 (error "No other template available"))
12931 (erase-buffer)
12932 (let ((annotation (plist-get org-store-link-plist :annotation))
12933 (initial (plist-get org-store-link-plist :initial)))
12934 (org-remember-apply-template))
12935 (message "Press C-c C-c to remember data"))
12936 (if (org-region-active-p)
12937 (remember (buffer-substring (point) (mark)))
12938 (call-interactively 'remember))))
12939
12940 (defvar org-note-abort nil) ; dynamically scoped
12941
12942 ;;;###autoload
12943 (defun org-remember-handler ()
12944 "Store stuff from remember.el into an org file.
12945 First prompts for an org file. If the user just presses return, the value
12946 of `org-default-notes-file' is used.
12947 Then the command offers the headings tree of the selected file in order to
12948 file the text at a specific location.
12949 You can either immediately press RET to get the note appended to the
12950 file, or you can use vertical cursor motion and visibility cycling (TAB) to
12951 find a better place. Then press RET or <left> or <right> in insert the note.
12952
12953 Key Cursor position Note gets inserted
12954 -----------------------------------------------------------------------------
12955 RET buffer-start as level 1 heading at end of file
12956 RET on headline as sublevel of the heading at cursor
12957 RET no heading at cursor position, level taken from context.
12958 Or use prefix arg to specify level manually.
12959 <left> on headline as same level, before current heading
12960 <right> on headline as same level, after current heading
12961
12962 So the fastest way to store the note is to press RET RET to append it to
12963 the default file. This way your current train of thought is not
12964 interrupted, in accordance with the principles of remember.el.
12965 You can also get the fast execution without prompting by using
12966 C-u C-c C-c to exit the remember buffer. See also the variable
12967 `org-remember-store-without-prompt'.
12968
12969 Before being stored away, the function ensures that the text has a
12970 headline, i.e. a first line that starts with a \"*\". If not, a headline
12971 is constructed from the current date and some additional data.
12972
12973 If the variable `org-adapt-indentation' is non-nil, the entire text is
12974 also indented so that it starts in the same column as the headline
12975 \(i.e. after the stars).
12976
12977 See also the variable `org-reverse-note-order'."
12978 (goto-char (point-min))
12979 (while (looking-at "^[ \t]*\n\\|^##.*\n")
12980 (replace-match ""))
12981 (goto-char (point-max))
12982 (unless (equal (char-before) ?\n) (insert "\n"))
12983 (catch 'quit
12984 (if org-note-abort (throw 'quit nil))
12985 (let* ((txt (buffer-substring (point-min) (point-max)))
12986 (fastp (org-xor (equal current-prefix-arg '(4))
12987 org-remember-store-without-prompt))
12988 (file (if fastp org-default-notes-file (org-get-org-file)))
12989 (heading org-remember-default-headline)
12990 (visiting (org-find-base-buffer-visiting file))
12991 (org-startup-folded nil)
12992 (org-startup-align-all-tables nil)
12993 (org-goto-start-pos 1)
12994 spos exitcmd level indent reversed)
12995 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
12996 (setq file (car org-remember-previous-location)
12997 heading (cdr org-remember-previous-location)))
12998 (setq current-prefix-arg nil)
12999 ;; Modify text so that it becomes a nice subtree which can be inserted
13000 ;; into an org tree.
13001 (let* ((lines (split-string txt "\n"))
13002 first)
13003 (setq first (car lines) lines (cdr lines))
13004 (if (string-match "^\\*+ " first)
13005 ;; Is already a headline
13006 (setq indent nil)
13007 ;; We need to add a headline: Use time and first buffer line
13008 (setq lines (cons first lines)
13009 first (concat "* " (current-time-string)
13010 " (" (remember-buffer-desc) ")")
13011 indent " "))
13012 (if (and org-adapt-indentation indent)
13013 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
13014 (setq txt (concat first "\n"
13015 (mapconcat 'identity lines "\n"))))
13016 ;; Find the file
13017 (if (not visiting) (find-file-noselect file))
13018 (with-current-buffer (or visiting (get-file-buffer file))
13019 (unless (org-mode-p)
13020 (error "Target files for remember notes must be in Org-mode"))
13021 (save-excursion
13022 (save-restriction
13023 (widen)
13024 (and (goto-char (point-min))
13025 (not (re-search-forward "^\\* " nil t))
13026 (insert "\n* " (or heading "Notes") "\n"))
13027 (setq reversed (org-notes-order-reversed-p))
13028
13029 ;; Find the default location
13030 (when (and heading (stringp heading) (string-match "\\S-" heading))
13031 (goto-char (point-min))
13032 (if (re-search-forward
13033 (concat "^\\*+[ \t]+" (regexp-quote heading)
13034 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13035 nil t)
13036 (setq org-goto-start-pos (match-beginning 0))
13037 (when fastp
13038 (goto-char (point-max))
13039 (unless (bolp) (newline))
13040 (insert "* " heading "\n")
13041 (setq org-goto-start-pos (point-at-bol 0)))))
13042
13043 ;; Ask the User for a location
13044 (if fastp
13045 (setq spos org-goto-start-pos
13046 exitcmd 'return)
13047 (setq spos (org-get-location (current-buffer) org-remember-help)
13048 exitcmd (cdr spos)
13049 spos (car spos)))
13050 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13051 ; not handle this note
13052 (goto-char spos)
13053 (cond ((org-on-heading-p t)
13054 (org-back-to-heading t)
13055 (setq level (funcall outline-level))
13056 (cond
13057 ((eq exitcmd 'return)
13058 ;; sublevel of current
13059 (setq org-remember-previous-location
13060 (cons (abbreviate-file-name file)
13061 (org-get-heading 'notags)))
13062 (if reversed
13063 (outline-next-heading)
13064 (org-end-of-subtree)
13065 (if (not (bolp))
13066 (if (looking-at "[ \t]*\n")
13067 (beginning-of-line 2)
13068 (end-of-line 1)
13069 (insert "\n"))))
13070 (org-paste-subtree (org-get-legal-level level 1) txt))
13071 ((eq exitcmd 'left)
13072 ;; before current
13073 (org-paste-subtree level txt))
13074 ((eq exitcmd 'right)
13075 ;; after current
13076 (org-end-of-subtree t)
13077 (org-paste-subtree level txt))
13078 (t (error "This should not happen"))))
13079
13080 ((and (bobp) (not reversed))
13081 ;; Put it at the end, one level below level 1
13082 (save-restriction
13083 (widen)
13084 (goto-char (point-max))
13085 (if (not (bolp)) (newline))
13086 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13087
13088 ((and (bobp) reversed)
13089 ;; Put it at the start, as level 1
13090 (save-restriction
13091 (widen)
13092 (goto-char (point-min))
13093 (re-search-forward "^\\*+ " nil t)
13094 (beginning-of-line 1)
13095 (org-paste-subtree 1 txt)))
13096 (t
13097 ;; Put it right there, with automatic level determined by
13098 ;; org-paste-subtree or from prefix arg
13099 (org-paste-subtree
13100 (if (numberp current-prefix-arg) current-prefix-arg)
13101 txt)))
13102 (when remember-save-after-remembering
13103 (save-buffer)
13104 (if (not visiting) (kill-buffer (current-buffer)))))))))
13105 t) ;; return t to indicate that we took care of this note.
13106
13107 (defun org-get-org-file ()
13108 "Read a filename, with default directory `org-directory'."
13109 (let ((default (or org-default-notes-file remember-data-file)))
13110 (read-file-name (format "File name [%s]: " default)
13111 (file-name-as-directory org-directory)
13112 default)))
13113
13114 (defun org-notes-order-reversed-p ()
13115 "Check if the current file should receive notes in reversed order."
13116 (cond
13117 ((not org-reverse-note-order) nil)
13118 ((eq t org-reverse-note-order) t)
13119 ((not (listp org-reverse-note-order)) nil)
13120 (t (catch 'exit
13121 (let ((all org-reverse-note-order)
13122 entry)
13123 (while (setq entry (pop all))
13124 (if (string-match (car entry) buffer-file-name)
13125 (throw 'exit (cdr entry))))
13126 nil)))))
13127
13128 ;;;; Dynamic blocks
13129
13130 (defun org-find-dblock (name)
13131 "Find the first dynamic block with name NAME in the buffer.
13132 If not found, stay at current position and return nil."
13133 (let (pos)
13134 (save-excursion
13135 (goto-char (point-min))
13136 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
13137 nil t)
13138 (match-beginning 0))))
13139 (if pos (goto-char pos))
13140 pos))
13141
13142 (defconst org-dblock-start-re
13143 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
13144 "Matches the startline of a dynamic block, with parameters.")
13145
13146 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
13147 "Matches the end of a dyhamic block.")
13148
13149 (defun org-create-dblock (plist)
13150 "Create a dynamic block section, with parameters taken from PLIST.
13151 PLIST must containe a :name entry which is used as name of the block."
13152 (unless (bolp) (newline))
13153 (let ((name (plist-get plist :name)))
13154 (insert "#+BEGIN: " name)
13155 (while plist
13156 (if (eq (car plist) :name)
13157 (setq plist (cddr plist))
13158 (insert " " (prin1-to-string (pop plist)))))
13159 (insert "\n\n#+END:\n")
13160 (beginning-of-line -2)))
13161
13162 (defun org-prepare-dblock ()
13163 "Prepare dynamic block for refresh.
13164 This empties the block, puts the cursor at the insert position and returns
13165 the property list including an extra property :name with the block name."
13166 (unless (looking-at org-dblock-start-re)
13167 (error "Not at a dynamic block"))
13168 (let* ((begdel (1+ (match-end 0)))
13169 (name (org-no-properties (match-string 1)))
13170 (params (append (list :name name)
13171 (read (concat "(" (match-string 3) ")")))))
13172 (unless (re-search-forward org-dblock-end-re nil t)
13173 (error "Dynamic block not terminated"))
13174 (delete-region begdel (match-beginning 0))
13175 (goto-char begdel)
13176 (open-line 1)
13177 params))
13178
13179 (defun org-map-dblocks (&optional command)
13180 "Apply COMMAND to all dynamic blocks in the current buffer.
13181 If COMMAND is not given, use `org-update-dblock'."
13182 (let ((cmd (or command 'org-update-dblock))
13183 pos)
13184 (save-excursion
13185 (goto-char (point-min))
13186 (while (re-search-forward org-dblock-start-re nil t)
13187 (goto-char (setq pos (match-beginning 0)))
13188 (condition-case nil
13189 (funcall cmd)
13190 (error (message "Error during update of dynamic block")))
13191 (goto-char pos)
13192 (unless (re-search-forward org-dblock-end-re nil t)
13193 (error "Dynamic block not terminated"))))))
13194
13195 (defun org-dblock-update (&optional arg)
13196 "User command for updating dynamic blocks.
13197 Update the dynamic block at point. With prefix ARG, update all dynamic
13198 blocks in the buffer."
13199 (interactive "P")
13200 (if arg
13201 (org-update-all-dblocks)
13202 (or (looking-at org-dblock-start-re)
13203 (org-beginning-of-dblock))
13204 (org-update-dblock)))
13205
13206 (defun org-update-dblock ()
13207 "Update the dynamic block at point
13208 This means to empty the block, parse for parameters and then call
13209 the correct writing function."
13210 (save-window-excursion
13211 (let* ((pos (point))
13212 (line (org-current-line))
13213 (params (org-prepare-dblock))
13214 (name (plist-get params :name))
13215 (cmd (intern (concat "org-dblock-write:" name))))
13216 (message "Updating dynamic block `%s' at line %d..." name line)
13217 (funcall cmd params)
13218 (message "Updating dynamic block `%s' at line %d...done" name line)
13219 (goto-char pos))))
13220
13221 (defun org-beginning-of-dblock ()
13222 "Find the beginning of the dynamic block at point.
13223 Error if there is no scuh block at point."
13224 (let ((pos (point))
13225 beg)
13226 (end-of-line 1)
13227 (if (and (re-search-backward org-dblock-start-re nil t)
13228 (setq beg (match-beginning 0))
13229 (re-search-forward org-dblock-end-re nil t)
13230 (> (match-end 0) pos))
13231 (goto-char beg)
13232 (goto-char pos)
13233 (error "Not in a dynamic block"))))
13234
13235 (defun org-update-all-dblocks ()
13236 "Update all dynamic blocks in the buffer.
13237 This function can be used in a hook."
13238 (when (org-mode-p)
13239 (org-map-dblocks 'org-update-dblock)))
13240
13241
13242 ;;;; Completion
13243
13244 (defconst org-additional-option-like-keywords
13245 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
13246 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:"))
13247
13248 (defun org-complete (&optional arg)
13249 "Perform completion on word at point.
13250 At the beginning of a headline, this completes TODO keywords as given in
13251 `org-todo-keywords'.
13252 If the current word is preceded by a backslash, completes the TeX symbols
13253 that are supported for HTML support.
13254 If the current word is preceded by \"#+\", completes special words for
13255 setting file options.
13256 In the line after \"#+STARTUP:, complete valid keywords.\"
13257 At all other locations, this simply calls the value of
13258 `org-completion-fallback-command'."
13259 (interactive "P")
13260 (org-without-partial-completion
13261 (catch 'exit
13262 (let* ((end (point))
13263 (beg1 (save-excursion
13264 (skip-chars-backward (org-re "[:alnum:]_@"))
13265 (point)))
13266 (beg (save-excursion
13267 (skip-chars-backward "a-zA-Z0-9_:$")
13268 (point)))
13269 (confirm (lambda (x) (stringp (car x))))
13270 (searchhead (equal (char-before beg) ?*))
13271 (tag (and (equal (char-before beg1) ?:)
13272 (equal (char-after (point-at-bol)) ?*)))
13273 (prop (and (equal (char-before beg1) ?:)
13274 (not (equal (char-after (point-at-bol)) ?*))))
13275 (texp (equal (char-before beg) ?\\))
13276 (link (equal (char-before beg) ?\[))
13277 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
13278 beg)
13279 "#+"))
13280 (startup (string-match "^#\\+STARTUP:.*"
13281 (buffer-substring (point-at-bol) (point))))
13282 (completion-ignore-case opt)
13283 (type nil)
13284 (tbl nil)
13285 (table (cond
13286 (opt
13287 (setq type :opt)
13288 (append
13289 (mapcar
13290 (lambda (x)
13291 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
13292 (cons (match-string 2 x) (match-string 1 x)))
13293 (org-split-string (org-get-current-options) "\n"))
13294 (mapcar 'list org-additional-option-like-keywords)))
13295 (startup
13296 (setq type :startup)
13297 org-startup-options)
13298 (link (append org-link-abbrev-alist-local
13299 org-link-abbrev-alist))
13300 (texp
13301 (setq type :tex)
13302 org-html-entities)
13303 ((string-match "\\`\\*+[ \t]+\\'"
13304 (buffer-substring (point-at-bol) beg))
13305 (setq type :todo)
13306 (mapcar 'list org-todo-keywords-1))
13307 (searchhead
13308 (setq type :searchhead)
13309 (save-excursion
13310 (goto-char (point-min))
13311 (while (re-search-forward org-todo-line-regexp nil t)
13312 (push (list
13313 (org-make-org-heading-search-string
13314 (match-string 3) t))
13315 tbl)))
13316 tbl)
13317 (tag (setq type :tag beg beg1)
13318 (or org-tag-alist (org-get-buffer-tags)))
13319 (prop (setq type :prop beg beg1)
13320 (mapcar 'list (org-buffer-property-keys)))
13321 (t (progn
13322 (call-interactively org-completion-fallback-command)
13323 (throw 'exit nil)))))
13324 (pattern (buffer-substring-no-properties beg end))
13325 (completion (try-completion pattern table confirm)))
13326 (cond ((eq completion t)
13327 (if (not (assoc (upcase pattern) table))
13328 (message "Already complete")
13329 (if (equal type :opt)
13330 (insert (substring (cdr (assoc (upcase pattern) table))
13331 (length pattern)))
13332 (if (memq type '(:tag :prop)) (insert ":")))))
13333 ((null completion)
13334 (message "Can't find completion for \"%s\"" pattern)
13335 (ding))
13336 ((not (string= pattern completion))
13337 (delete-region beg end)
13338 (if (string-match " +$" completion)
13339 (setq completion (replace-match "" t t completion)))
13340 (insert completion)
13341 (if (get-buffer-window "*Completions*")
13342 (delete-window (get-buffer-window "*Completions*")))
13343 (if (assoc completion table)
13344 (if (eq type :todo) (insert " ")
13345 (if (memq type '(:tag :prop)) (insert ":"))))
13346 (if (and (equal type :opt) (assoc completion table))
13347 (message "%s" (substitute-command-keys
13348 "Press \\[org-complete] again to insert example settings"))))
13349 (t
13350 (message "Making completion list...")
13351 (let ((list (sort (all-completions pattern table confirm)
13352 'string<)))
13353 (with-output-to-temp-buffer "*Completions*"
13354 (condition-case nil
13355 ;; Protection needed for XEmacs and emacs 21
13356 (display-completion-list list pattern)
13357 (error (display-completion-list list)))))
13358 (message "Making completion list...%s" "done")))))))
13359
13360 ;;;; TODO, DEADLINE, Comments
13361
13362 (defun org-toggle-comment ()
13363 "Change the COMMENT state of an entry."
13364 (interactive)
13365 (save-excursion
13366 (org-back-to-heading)
13367 (if (looking-at (concat outline-regexp
13368 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
13369 (replace-match "" t t nil 1)
13370 (if (looking-at outline-regexp)
13371 (progn
13372 (goto-char (match-end 0))
13373 (insert org-comment-string " "))))))
13374
13375 (defvar org-last-todo-state-is-todo nil
13376 "This is non-nil when the last TODO state change led to a TODO state.
13377 If the last change removed the TODO tag or switched to DONE, then
13378 this is nil.")
13379
13380 (defvar org-setting-tags nil) ; dynamically skiped
13381
13382 ;; FIXME: better place
13383 (defun org-property-or-variable-value (var &optional inherit)
13384 "Check if there is a property fixing the value of VAR.
13385 If yes, return this value. If not, return the current value of the variable."
13386 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13387 (if (and prop (stringp prop) (string-match "\\S-" prop))
13388 (read prop)
13389 (symbol-value var))))
13390
13391 (defun org-parse-local-options (string var)
13392 "Parse STRING for startup setting relevant for variable VAR."
13393 (let ((rtn (symbol-value var))
13394 e opts)
13395 (save-match-data
13396 (if (or (not string) (not (string-match "\\S-" string)))
13397 rtn
13398 (setq opts (delq nil (mapcar (lambda (x)
13399 (setq e (assoc x org-startup-options))
13400 (if (eq (nth 1 e) var) e nil))
13401 (org-split-string string "[ \t]+"))))
13402 (if (not opts)
13403 rtn
13404 (setq rtn nil)
13405 (while (setq e (pop opts))
13406 (if (not (nth 3 e))
13407 (setq rtn (nth 2 e))
13408 (if (not (listp rtn)) (setq rtn nil))
13409 (push (nth 2 e) rtn)))
13410 rtn)))))
13411
13412 (defvar org-blocker-hook nil
13413 "Hook for functions that are allowed to block a state change.
13414
13415 Each function gets as its single argument a property list, see
13416 `org-trigger-hook' for more information about this list.
13417
13418 If any of the functions in this hook returns nil, the state change
13419 is blocked.")
13420
13421 (defvar org-trigger-hook nil
13422 "Hook for functions that are triggered by a state change.
13423
13424 Each function gets as its single argument a property list with at least
13425 the following elements:
13426
13427 (:type type-of-change :position pos-at-entry-start
13428 :from old-state :to new-state)
13429
13430 Depending on the type, more properties may be present.
13431
13432 This mechanism is currently implemented for:
13433
13434 TODO state changes
13435 ------------------
13436 :type todo-state-change
13437 :from previous state (keyword as a string), or nil
13438 :to new state (keyword as a string), or nil")
13439
13440
13441 (defun org-todo (&optional arg)
13442 "Change the TODO state of an item.
13443 The state of an item is given by a keyword at the start of the heading,
13444 like
13445 *** TODO Write paper
13446 *** DONE Call mom
13447
13448 The different keywords are specified in the variable `org-todo-keywords'.
13449 By default the available states are \"TODO\" and \"DONE\".
13450 So for this example: when the item starts with TODO, it is changed to DONE.
13451 When it starts with DONE, the DONE is removed. And when neither TODO nor
13452 DONE are present, add TODO at the beginning of the heading.
13453
13454 With C-u prefix arg, use completion to determine the new state.
13455 With numeric prefix arg, switch to that state.
13456
13457 For calling through lisp, arg is also interpreted in the following way:
13458 'none -> empty state
13459 \"\"(empty string) -> switch to empty state
13460 'done -> switch to DONE
13461 'nextset -> switch to the next set of keywords
13462 'previousset -> switch to the previous set of keywords
13463 \"WAITING\" -> switch to the specified keyword, but only if it
13464 really is a member of `org-todo-keywords'."
13465 (interactive "P")
13466 (save-excursion
13467 (catch 'exit
13468 (org-back-to-heading)
13469 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
13470 (or (looking-at (concat " +" org-todo-regexp " *"))
13471 (looking-at " *"))
13472 (let* ((match-data (match-data))
13473 (startpos (line-beginning-position))
13474 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
13475 (org-log-done (org-parse-local-options logging 'org-log-done))
13476 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
13477 (this (match-string 1))
13478 (hl-pos (match-beginning 0))
13479 (head (org-get-todo-sequence-head this))
13480 (ass (assoc head org-todo-kwd-alist))
13481 (interpret (nth 1 ass))
13482 (done-word (nth 3 ass))
13483 (final-done-word (nth 4 ass))
13484 (last-state (or this ""))
13485 (completion-ignore-case t)
13486 (member (member this org-todo-keywords-1))
13487 (tail (cdr member))
13488 (state (cond
13489 ((and org-todo-key-trigger
13490 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
13491 (and (not arg) org-use-fast-todo-selection
13492 (not (eq org-use-fast-todo-selection 'prefix)))))
13493 ;; Use fast selection
13494 (org-fast-todo-selection))
13495 ((and (equal arg '(4))
13496 (or (not org-use-fast-todo-selection)
13497 (not org-todo-key-trigger)))
13498 ;; Read a state with completion
13499 (completing-read "State: " (mapcar (lambda(x) (list x))
13500 org-todo-keywords-1)
13501 nil t))
13502 ((eq arg 'right)
13503 (if this
13504 (if tail (car tail) nil)
13505 (car org-todo-keywords-1)))
13506 ((eq arg 'left)
13507 (if (equal member org-todo-keywords-1)
13508 nil
13509 (if this
13510 (nth (- (length org-todo-keywords-1) (length tail) 2)
13511 org-todo-keywords-1)
13512 (org-last org-todo-keywords-1))))
13513 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
13514 (setq arg nil))) ; hack to fall back to cycling
13515 (arg
13516 ;; user or caller requests a specific state
13517 (cond
13518 ((equal arg "") nil)
13519 ((eq arg 'none) nil)
13520 ((eq arg 'done) (or done-word (car org-done-keywords)))
13521 ((eq arg 'nextset)
13522 (or (car (cdr (member head org-todo-heads)))
13523 (car org-todo-heads)))
13524 ((eq arg 'previousset)
13525 (let ((org-todo-heads (reverse org-todo-heads)))
13526 (or (car (cdr (member head org-todo-heads)))
13527 (car org-todo-heads))))
13528 ((car (member arg org-todo-keywords-1)))
13529 ((nth (1- (prefix-numeric-value arg))
13530 org-todo-keywords-1))))
13531 ((null member) (or head (car org-todo-keywords-1)))
13532 ((equal this final-done-word) nil) ;; -> make empty
13533 ((null tail) nil) ;; -> first entry
13534 ((eq interpret 'sequence)
13535 (car tail))
13536 ((memq interpret '(type priority))
13537 (if (eq this-command last-command)
13538 (car tail)
13539 (if (> (length tail) 0)
13540 (or done-word (car org-done-keywords))
13541 nil)))
13542 (t nil)))
13543 (next (if state (concat " " state " ") " "))
13544 (change-plist (list :type 'todo-state-change :from this :to state
13545 :position startpos))
13546 dostates)
13547 (when org-blocker-hook
13548 (unless (save-excursion
13549 (save-match-data
13550 (run-hook-with-args-until-failure
13551 'org-blocker-hook change-plist)))
13552 (if (interactive-p)
13553 (error "TODO state change from %s to %s blocked" this state)
13554 ;; fail silently
13555 (message "TODO state change from %s to %s blocked" this state)
13556 (throw 'exit nil))))
13557 (store-match-data match-data)
13558 (replace-match next t t)
13559 (unless (pos-visible-in-window-p hl-pos)
13560 (message "TODO state changed to %s" (org-trim next)))
13561 (unless head
13562 (setq head (org-get-todo-sequence-head state)
13563 ass (assoc head org-todo-kwd-alist)
13564 interpret (nth 1 ass)
13565 done-word (nth 3 ass)
13566 final-done-word (nth 4 ass)))
13567 (when (memq arg '(nextset previousset))
13568 (message "Keyword-Set %d/%d: %s"
13569 (- (length org-todo-sets) -1
13570 (length (memq (assoc state org-todo-sets) org-todo-sets)))
13571 (length org-todo-sets)
13572 (mapconcat 'identity (assoc state org-todo-sets) " ")))
13573 (setq org-last-todo-state-is-todo
13574 (not (member state org-done-keywords)))
13575 (when (and org-log-done (not (memq arg '(nextset previousset))))
13576 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
13577 (or (not org-todo-log-states)
13578 (member state org-todo-log-states))))
13579
13580 (cond
13581 ((and state (member state org-not-done-keywords)
13582 (not (member this org-not-done-keywords)))
13583 ;; This is now a todo state and was not one before
13584 ;; Remove any CLOSED timestamp, and possibly log the state change
13585 (org-add-planning-info nil nil 'closed)
13586 (and dostates (org-add-log-maybe 'state state 'findpos)))
13587 ((and state dostates)
13588 ;; This is a non-nil state, and we need to log it
13589 (org-add-log-maybe 'state state 'findpos))
13590 ((and (member state org-done-keywords)
13591 (not (member this org-done-keywords)))
13592 ;; It is now done, and it was not done before
13593 (org-add-planning-info 'closed (org-current-time))
13594 (org-add-log-maybe 'done state 'findpos))))
13595 ;; Fixup tag positioning
13596 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
13597 (run-hooks 'org-after-todo-state-change-hook)
13598 (and (member state org-done-keywords) (org-auto-repeat-maybe))
13599 (if (and arg (not (member state org-done-keywords)))
13600 (setq head (org-get-todo-sequence-head state)))
13601 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
13602 ;; Fixup cursor location if close to the keyword
13603 (if (and (outline-on-heading-p)
13604 (not (bolp))
13605 (save-excursion (beginning-of-line 1)
13606 (looking-at org-todo-line-regexp))
13607 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
13608 (progn
13609 (goto-char (or (match-end 2) (match-end 1)))
13610 (just-one-space)))
13611 (when org-trigger-hook
13612 (save-excursion
13613 (run-hook-with-args 'org-trigger-hook change-plist)))))))
13614
13615 (defun org-get-todo-sequence-head (kwd)
13616 "Return the head of the TODO sequence to which KWD belongs.
13617 If KWD is not set, check if there is a text property remembering the
13618 right sequence."
13619 (let (p)
13620 (cond
13621 ((not kwd)
13622 (or (get-text-property (point-at-bol) 'org-todo-head)
13623 (progn
13624 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13625 nil (point-at-eol)))
13626 (get-text-property p 'org-todo-head))))
13627 ((not (member kwd org-todo-keywords-1))
13628 (car org-todo-keywords-1))
13629 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13630
13631 (defun org-fast-todo-selection ()
13632 "Fast TODO keyword selection with single keys.
13633 Returns the new TODO keyword, or nil if no state change should occur."
13634 (let* ((fulltable org-todo-key-alist)
13635 (done-keywords org-done-keywords) ;; needed for the faces.
13636 (maxlen (apply 'max (mapcar
13637 (lambda (x)
13638 (if (stringp (car x)) (string-width (car x)) 0))
13639 fulltable)))
13640 (expert nil)
13641 (fwidth (+ maxlen 3 1 3))
13642 (ncol (/ (- (window-width) 4) fwidth))
13643 tg cnt e c tbl
13644 groups ingroup)
13645 (save-window-excursion
13646 (if expert
13647 (set-buffer (get-buffer-create " *Org todo*"))
13648 ; (delete-other-windows)
13649 ; (split-window-vertically)
13650 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13651 (erase-buffer)
13652 (org-set-local 'org-done-keywords done-keywords)
13653 (setq tbl fulltable cnt 0)
13654 (while (setq e (pop tbl))
13655 (cond
13656 ((equal e '(:startgroup))
13657 (push '() groups) (setq ingroup t)
13658 (when (not (= cnt 0))
13659 (setq cnt 0)
13660 (insert "\n"))
13661 (insert "{ "))
13662 ((equal e '(:endgroup))
13663 (setq ingroup nil cnt 0)
13664 (insert "}\n"))
13665 (t
13666 (setq tg (car e) c (cdr e))
13667 (if ingroup (push tg (car groups)))
13668 (setq tg (org-add-props tg nil 'face
13669 (org-get-todo-face tg)))
13670 (if (and (= cnt 0) (not ingroup)) (insert " "))
13671 (insert "[" c "] " tg (make-string
13672 (- fwidth 4 (length tg)) ?\ ))
13673 (when (= (setq cnt (1+ cnt)) ncol)
13674 (insert "\n")
13675 (if ingroup (insert " "))
13676 (setq cnt 0)))))
13677 (insert "\n")
13678 (goto-char (point-min))
13679 (if (and (not expert) (fboundp 'fit-window-to-buffer))
13680 (fit-window-to-buffer))
13681 (message "[a-z..]:Set [SPC]:clear")
13682 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13683 (cond
13684 ((or (= c ?\C-g)
13685 (and (= c ?q) (not (rassoc c fulltable))))
13686 (setq quit-flag t))
13687 ((= c ?\ ) nil)
13688 ((setq e (rassoc c fulltable) tg (car e))
13689 tg)
13690 (t (setq quit-flag t))))))
13691
13692 (defun org-get-repeat ()
13693 "Check if tere is a deadline/schedule with repeater in this entry."
13694 (save-match-data
13695 (save-excursion
13696 (org-back-to-heading t)
13697 (if (re-search-forward
13698 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
13699 (match-string 1)))))
13700
13701 (defvar org-last-changed-timestamp)
13702 (defvar org-log-post-message)
13703 (defun org-auto-repeat-maybe ()
13704 "Check if the current headline contains a repeated deadline/schedule.
13705 If yes, set TODO state back to what it was and change the base date
13706 of repeating deadline/scheduled time stamps to new date.
13707 This function should be run in the `org-after-todo-state-change-hook'."
13708 ;; last-state is dynamically scoped into this function
13709 (let* ((repeat (org-get-repeat))
13710 (aa (assoc last-state org-todo-kwd-alist))
13711 (interpret (nth 1 aa))
13712 (head (nth 2 aa))
13713 (done-word (nth 3 aa))
13714 (whata '(("d" . day) ("m" . month) ("y" . year)))
13715 (msg "Entry repeats: ")
13716 (org-log-done)
13717 re type n what ts)
13718 (when repeat
13719 (org-todo (if (eq interpret 'type) last-state head))
13720 (when (and org-log-repeat
13721 (not (memq 'org-add-log-note
13722 (default-value 'post-command-hook))))
13723 ;; Make sure a note is taken
13724 (let ((org-log-done '(done)))
13725 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
13726 'findpos)))
13727 (org-back-to-heading t)
13728 (org-add-planning-info nil nil 'closed)
13729 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13730 org-deadline-time-regexp "\\)"))
13731 (while (re-search-forward
13732 re (save-excursion (outline-next-heading) (point)) t)
13733 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
13734 ts (match-string (if (match-end 2) 2 4)))
13735 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
13736 (setq n (string-to-number (match-string 1 ts))
13737 what (match-string 2 ts))
13738 (if (equal what "w") (setq n (* n 7) what "d"))
13739 (org-timestamp-change n (cdr (assoc what whata))))
13740 (setq msg (concat msg type org-last-changed-timestamp " ")))
13741 (setq org-log-post-message msg)
13742 (message msg))))
13743
13744 (defun org-show-todo-tree (arg)
13745 "Make a compact tree which shows all headlines marked with TODO.
13746 The tree will show the lines where the regexp matches, and all higher
13747 headlines above the match.
13748 With \\[universal-argument] prefix, also show the DONE entries.
13749 With a numeric prefix N, construct a sparse tree for the Nth element
13750 of `org-todo-keywords-1'."
13751 (interactive "P")
13752 (let ((case-fold-search nil)
13753 (kwd-re
13754 (cond ((null arg) org-not-done-regexp)
13755 ((equal arg '(4))
13756 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
13757 (mapcar 'list org-todo-keywords-1))))
13758 (concat "\\("
13759 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13760 "\\)\\>")))
13761 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13762 (regexp-quote (nth (1- (prefix-numeric-value arg))
13763 org-todo-keywords-1)))
13764 (t (error "Invalid prefix argument: %s" arg)))))
13765 (message "%d TODO entries found"
13766 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
13767
13768 (defun org-deadline (&optional remove)
13769 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13770 With argument REMOVE, remove any deadline from the item."
13771 (interactive "P")
13772 (if remove
13773 (progn
13774 (org-add-planning-info nil nil 'deadline)
13775 (message "Item no longer has a deadline."))
13776 (org-add-planning-info 'deadline nil 'closed)))
13777
13778 (defun org-schedule (&optional remove)
13779 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13780 With argument REMOVE, remove any scheduling date from the item."
13781 (interactive "P")
13782 (if remove
13783 (progn
13784 (org-add-planning-info nil nil 'scheduled)
13785 (message "Item is no longer scheduled."))
13786 (org-add-planning-info 'scheduled nil 'closed)))
13787
13788 (defun org-add-planning-info (what &optional time &rest remove)
13789 "Insert new timestamp with keyword in the line directly after the headline.
13790 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
13791 If non is given, the user is prompted for a date.
13792 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13793 be removed."
13794 (interactive)
13795 (let (org-time-was-given org-end-time-was-given)
13796 (when what (setq time (or time (org-read-date nil 'to-time))))
13797 (when (and org-insert-labeled-timestamps-at-point
13798 (member what '(scheduled deadline)))
13799 (insert
13800 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13801 (org-insert-time-stamp time org-time-was-given
13802 nil nil nil (list org-end-time-was-given))
13803 (setq what nil))
13804 (save-excursion
13805 (save-restriction
13806 (let (col list elt ts buffer-invisibility-spec)
13807 (org-back-to-heading t)
13808 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
13809 (goto-char (match-end 1))
13810 (setq col (current-column))
13811 (goto-char (match-end 0))
13812 (if (eobp) (insert "\n") (forward-char 1))
13813 (if (and (not (looking-at outline-regexp))
13814 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13815 "[^\r\n]*"))
13816 (not (equal (match-string 1) org-clock-string)))
13817 (narrow-to-region (match-beginning 0) (match-end 0))
13818 (insert-before-markers "\n")
13819 (backward-char 1)
13820 (narrow-to-region (point) (point))
13821 (indent-to-column col))
13822 ;; Check if we have to remove something.
13823 (setq list (cons what remove))
13824 (while list
13825 (setq elt (pop list))
13826 (goto-char (point-min))
13827 (when (or (and (eq elt 'scheduled)
13828 (re-search-forward org-scheduled-time-regexp nil t))
13829 (and (eq elt 'deadline)
13830 (re-search-forward org-deadline-time-regexp nil t))
13831 (and (eq elt 'closed)
13832 (re-search-forward org-closed-time-regexp nil t)))
13833 (replace-match "")
13834 (if (looking-at "--+<[^>]+>") (replace-match ""))
13835 (if (looking-at " +") (replace-match ""))))
13836 (goto-char (point-max))
13837 (when what
13838 (insert
13839 (if (not (equal (char-before) ?\ )) " " "")
13840 (cond ((eq what 'scheduled) org-scheduled-string)
13841 ((eq what 'deadline) org-deadline-string)
13842 ((eq what 'closed) org-closed-string))
13843 " ")
13844 (setq ts (org-insert-time-stamp
13845 time
13846 (or org-time-was-given
13847 (and (eq what 'closed) org-log-done-with-time))
13848 (eq what 'closed)
13849 nil nil (list org-end-time-was-given)))
13850 (end-of-line 1))
13851 (goto-char (point-min))
13852 (widen)
13853 (if (looking-at "[ \t]+\r?\n")
13854 (replace-match ""))
13855 ts)))))
13856
13857 (defvar org-log-note-marker (make-marker))
13858 (defvar org-log-note-purpose nil)
13859 (defvar org-log-note-state nil)
13860 (defvar org-log-note-window-configuration nil)
13861 (defvar org-log-note-return-to (make-marker))
13862 (defvar org-log-post-message nil
13863 "Message to be displayed after a log note has been stored.
13864 The auto-repeater uses this.")
13865
13866 (defun org-add-log-maybe (&optional purpose state findpos)
13867 "Set up the post command hook to take a note."
13868 (save-excursion
13869 (when (and (listp org-log-done)
13870 (memq purpose org-log-done))
13871 (when findpos
13872 (org-back-to-heading t)
13873 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
13874 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13875 "[^\r\n]*\\)?"))
13876 (goto-char (match-end 0))
13877 (unless org-log-states-order-reversed
13878 (and (= (char-after) ?\n) (forward-char 1))
13879 (org-skip-over-state-notes)
13880 (skip-chars-backward " \t\n\r")))
13881 (move-marker org-log-note-marker (point))
13882 (setq org-log-note-purpose purpose)
13883 (setq org-log-note-state state)
13884 (add-hook 'post-command-hook 'org-add-log-note 'append))))
13885
13886 (defun org-skip-over-state-notes ()
13887 "Skip past the list of State notes in an entry."
13888 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13889 (while (looking-at "[ \t]*- State")
13890 (condition-case nil
13891 (org-next-item)
13892 (error (org-end-of-item)))))
13893
13894 (defun org-add-log-note (&optional purpose)
13895 "Pop up a window for taking a note, and add this note later at point."
13896 (remove-hook 'post-command-hook 'org-add-log-note)
13897 (setq org-log-note-window-configuration (current-window-configuration))
13898 (delete-other-windows)
13899 (move-marker org-log-note-return-to (point))
13900 (switch-to-buffer (marker-buffer org-log-note-marker))
13901 (goto-char org-log-note-marker)
13902 (org-switch-to-buffer-other-window "*Org Note*")
13903 (erase-buffer)
13904 (let ((org-inhibit-startup t)) (org-mode))
13905 (insert (format "# Insert note for %s.
13906 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13907 (cond
13908 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13909 ((eq org-log-note-purpose 'done) "closed todo item")
13910 ((eq org-log-note-purpose 'state)
13911 (format "state change to \"%s\"" org-log-note-state))
13912 (t (error "This should not happen")))))
13913 (org-set-local 'org-finish-function 'org-store-log-note))
13914
13915 (defun org-store-log-note ()
13916 "Finish taking a log note, and insert it to where it belongs."
13917 (let ((txt (buffer-string))
13918 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13919 lines ind)
13920 (kill-buffer (current-buffer))
13921 (while (string-match "\\`#.*\n[ \t\n]*" txt)
13922 (setq txt (replace-match "" t t txt)))
13923 (if (string-match "\\s-+\\'" txt)
13924 (setq txt (replace-match "" t t txt)))
13925 (setq lines (org-split-string txt "\n"))
13926 (when (and note (string-match "\\S-" note))
13927 (setq note
13928 (org-replace-escapes
13929 note
13930 (list (cons "%u" (user-login-name))
13931 (cons "%U" user-full-name)
13932 (cons "%t" (format-time-string
13933 (org-time-stamp-format 'long 'inactive)
13934 (current-time)))
13935 (cons "%s" (if org-log-note-state
13936 (concat "\"" org-log-note-state "\"")
13937 "")))))
13938 (if lines (setq note (concat note " \\\\")))
13939 (push note lines))
13940 (when (or current-prefix-arg org-note-abort) (setq lines nil))
13941 (when lines
13942 (save-excursion
13943 (set-buffer (marker-buffer org-log-note-marker))
13944 (save-excursion
13945 (goto-char org-log-note-marker)
13946 (move-marker org-log-note-marker nil)
13947 (end-of-line 1)
13948 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13949 (indent-relative nil)
13950 (insert " - " (pop lines))
13951 (org-indent-line-function)
13952 (beginning-of-line 1)
13953 (looking-at "[ \t]*")
13954 (setq ind (concat (match-string 0) " "))
13955 (end-of-line 1)
13956 (while lines (insert "\n" ind (pop lines)))))))
13957 (set-window-configuration org-log-note-window-configuration)
13958 (with-current-buffer (marker-buffer org-log-note-return-to)
13959 (goto-char org-log-note-return-to))
13960 (move-marker org-log-note-return-to nil)
13961 (and org-log-post-message (message org-log-post-message)))
13962
13963 ;; FIXME: what else would be useful?
13964 ;; - priority
13965 ;; - date
13966
13967 (defun org-sparse-tree (&optional arg)
13968 "Create a sparse tree, prompt for the details.
13969 This command can create sparse trees. You first need to select the type
13970 of match used to create the tree:
13971
13972 t Show entries with a specific TODO keyword.
13973 T Show entries selected by a tags match.
13974 p Enter a property name and its value (both with completion on existing
13975 names/values) and show entries with that property.
13976 r Show entries matching a regular expression"
13977 (interactive "P")
13978 (let (ans kwd value)
13979 (message "Sparse tree: [r]egexp [t]odo-kwd [T]ag [p]roperty")
13980 (setq ans (read-char-exclusive))
13981 (cond
13982 ((equal ans ?t)
13983 (org-show-todo-tree '(4)))
13984 ((equal ans ?T)
13985 (call-interactively 'org-tags-sparse-tree))
13986 ((member ans '(?p ?P))
13987 (setq kwd (completing-read "Property: "
13988 (mapcar 'list (org-buffer-property-keys))))
13989 (setq value (completing-read "Value: "
13990 (mapcar 'list (org-property-values kwd))))
13991 (unless (string-match "\\`{.*}\\'" value)
13992 (setq value (concat "\"" value "\"")))
13993 (org-tags-sparse-tree arg (concat kwd "=" value)))
13994 ((member ans '(?r ?R))
13995 (call-interactively 'org-occur))
13996 (t (error "No such sparse tree command \"%c\"" ans)))))
13997
13998 (defvar org-occur-highlights nil)
13999 (make-variable-buffer-local 'org-occur-highlights)
14000
14001 (defun org-occur (regexp &optional keep-previous callback)
14002 "Make a compact tree which shows all matches of REGEXP.
14003 The tree will show the lines where the regexp matches, and all higher
14004 headlines above the match. It will also show the heading after the match,
14005 to make sure editing the matching entry is easy.
14006 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
14007 call to `org-occur' will be kept, to allow stacking of calls to this
14008 command.
14009 If CALLBACK is non-nil, it is a function which is called to confirm
14010 that the match should indeed be shown."
14011 (interactive "sRegexp: \nP")
14012 (or keep-previous (org-remove-occur-highlights nil nil t))
14013 (let ((cnt 0))
14014 (save-excursion
14015 (goto-char (point-min))
14016 (if (or (not keep-previous) ; do not want to keep
14017 (not org-occur-highlights)) ; no previous matches
14018 ;; hide everything
14019 (org-overview))
14020 (while (re-search-forward regexp nil t)
14021 (when (or (not callback)
14022 (save-match-data (funcall callback)))
14023 (setq cnt (1+ cnt))
14024 (when org-highlight-sparse-tree-matches
14025 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14026 (org-show-context 'occur-tree))))
14027 (when org-remove-highlights-with-change
14028 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
14029 nil 'local))
14030 (unless org-sparse-tree-open-archived-trees
14031 (org-hide-archived-subtrees (point-min) (point-max)))
14032 (run-hooks 'org-occur-hook)
14033 (if (interactive-p)
14034 (message "%d match(es) for regexp %s" cnt regexp))
14035 cnt))
14036
14037 (defun org-show-context (&optional key)
14038 "Make sure point and context and visible.
14039 How much context is shown depends upon the variables
14040 `org-show-hierarchy-above', `org-show-following-heading'. and
14041 `org-show-siblings'."
14042 (let ((heading-p (org-on-heading-p t))
14043 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
14044 (following-p (org-get-alist-option org-show-following-heading key))
14045 (siblings-p (org-get-alist-option org-show-siblings key)))
14046 (catch 'exit
14047 ;; Show heading or entry text
14048 (if heading-p
14049 (org-flag-heading nil) ; only show the heading
14050 (and (or (org-invisible-p) (org-invisible-p2))
14051 (org-show-hidden-entry))) ; show entire entry
14052 (when following-p
14053 ;; Show next sibling, or heading below text
14054 (save-excursion
14055 (and (if heading-p (org-goto-sibling) (outline-next-heading))
14056 (org-flag-heading nil))))
14057 (when siblings-p (org-show-siblings))
14058 (when hierarchy-p
14059 ;; show all higher headings, possibly with siblings
14060 (save-excursion
14061 (while (and (condition-case nil
14062 (progn (org-up-heading-all 1) t)
14063 (error nil))
14064 (not (bobp)))
14065 (org-flag-heading nil)
14066 (when siblings-p (org-show-siblings))))))))
14067
14068 (defun org-reveal (&optional siblings)
14069 "Show current entry, hierarchy above it, and the following headline.
14070 This can be used to show a consistent set of context around locations
14071 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
14072 not t for the search context.
14073
14074 With optional argument SIBLINGS, on each level of the hierarchy all
14075 siblings are shown. This repairs the tree structure to what it would
14076 look like when opened with hierarchical calls to `org-cycle'."
14077 (interactive "P")
14078 (let ((org-show-hierarchy-above t)
14079 (org-show-following-heading t)
14080 (org-show-siblings (if siblings t org-show-siblings)))
14081 (org-show-context nil)))
14082
14083 (defun org-highlight-new-match (beg end)
14084 "Highlight from BEG to END and mark the highlight is an occur headline."
14085 (let ((ov (org-make-overlay beg end)))
14086 (org-overlay-put ov 'face 'secondary-selection)
14087 (push ov org-occur-highlights)))
14088
14089 (defun org-remove-occur-highlights (&optional beg end noremove)
14090 "Remove the occur highlights from the buffer.
14091 BEG and END are ignored. If NOREMOVE is nil, remove this function
14092 from the `before-change-functions' in the current buffer."
14093 (interactive)
14094 (unless org-inhibit-highlight-removal
14095 (mapc 'org-delete-overlay org-occur-highlights)
14096 (setq org-occur-highlights nil)
14097 (unless noremove
14098 (remove-hook 'before-change-functions
14099 'org-remove-occur-highlights 'local))))
14100
14101 ;;;; Priorities
14102
14103 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14104 "Regular expression matching the priority indicator.")
14105
14106 (defvar org-remove-priority-next-time nil)
14107
14108 (defun org-priority-up ()
14109 "Increase the priority of the current item."
14110 (interactive)
14111 (org-priority 'up))
14112
14113 (defun org-priority-down ()
14114 "Decrease the priority of the current item."
14115 (interactive)
14116 (org-priority 'down))
14117
14118 (defun org-priority (&optional action)
14119 "Change the priority of an item by ARG.
14120 ACTION can be `set', `up', `down', or a character."
14121 (interactive)
14122 (setq action (or action 'set))
14123 (let (current new news have remove)
14124 (save-excursion
14125 (org-back-to-heading)
14126 (if (looking-at org-priority-regexp)
14127 (setq current (string-to-char (match-string 2))
14128 have t)
14129 (setq current org-default-priority))
14130 (cond
14131 ((or (eq action 'set) (integerp action))
14132 (if (integerp action)
14133 (setq new action)
14134 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
14135 (setq new (read-char-exclusive)))
14136 (if (and (= (upcase org-highest-priority) org-highest-priority)
14137 (= (upcase org-lowest-priority) org-lowest-priority))
14138 (setq new (upcase new)))
14139 (cond ((equal new ?\ ) (setq remove t))
14140 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14141 (error "Priority must be between `%c' and `%c'"
14142 org-highest-priority org-lowest-priority))))
14143 ((eq action 'up)
14144 (if (and (not have) (eq last-command this-command))
14145 (setq new org-lowest-priority)
14146 (setq new (if (and org-priority-start-cycle-with-default (not have))
14147 org-default-priority (1- current)))))
14148 ((eq action 'down)
14149 (if (and (not have) (eq last-command this-command))
14150 (setq new org-highest-priority)
14151 (setq new (if (and org-priority-start-cycle-with-default (not have))
14152 org-default-priority (1+ current)))))
14153 (t (error "Invalid action")))
14154 (if (or (< (upcase new) org-highest-priority)
14155 (> (upcase new) org-lowest-priority))
14156 (setq remove t))
14157 (setq news (format "%c" new))
14158 (if have
14159 (if remove
14160 (replace-match "" t t nil 1)
14161 (replace-match news t t nil 2))
14162 (if remove
14163 (error "No priority cookie found in line")
14164 (looking-at org-todo-line-regexp)
14165 (if (match-end 2)
14166 (progn
14167 (goto-char (match-end 2))
14168 (insert " [#" news "]"))
14169 (goto-char (match-beginning 3))
14170 (insert "[#" news "] ")))))
14171 (org-preserve-lc (org-set-tags nil 'align))
14172 (if remove
14173 (message "Priority removed")
14174 (message "Priority of current item set to %s" news))))
14175
14176
14177 (defun org-get-priority (s)
14178 "Find priority cookie and return priority."
14179 (save-match-data
14180 (if (not (string-match org-priority-regexp s))
14181 (* 1000 (- org-lowest-priority org-default-priority))
14182 (* 1000 (- org-lowest-priority
14183 (string-to-char (match-string 2 s)))))))
14184
14185 ;;;; Tags
14186
14187 (defun org-scan-tags (action matcher &optional todo-only)
14188 "Scan headline tags with inheritance and produce output ACTION.
14189 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
14190 evaluated, testing if a given set of tags qualifies a headline for
14191 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
14192 are included in the output."
14193 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
14194 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14195 (org-re
14196 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
14197 (props (list 'face nil
14198 'done-face 'org-done
14199 'undone-face nil
14200 'mouse-face 'highlight
14201 'org-not-done-regexp org-not-done-regexp
14202 'org-todo-regexp org-todo-regexp
14203 'keymap org-agenda-keymap
14204 'help-echo
14205 (format "mouse-2 or RET jump to org file %s"
14206 (abbreviate-file-name
14207 (or (buffer-file-name (buffer-base-buffer))
14208 (buffer-name (buffer-base-buffer)))))))
14209 (case-fold-search nil)
14210 lspos
14211 tags tags-list tags-alist (llast 0) rtn level category i txt
14212 todo marker entry priority)
14213 (save-excursion
14214 (goto-char (point-min))
14215 (when (eq action 'sparse-tree)
14216 (org-overview)
14217 (org-remove-occur-highlights))
14218 (while (re-search-forward re nil t)
14219 (catch :skip
14220 (setq todo (if (match-end 1) (match-string 2))
14221 tags (if (match-end 4) (match-string 4)))
14222 (goto-char (setq lspos (1+ (match-beginning 0))))
14223 (setq level (org-reduced-level (funcall outline-level))
14224 category (org-get-category))
14225 (setq i llast llast level)
14226 ;; remove tag lists from same and sublevels
14227 (while (>= i level)
14228 (when (setq entry (assoc i tags-alist))
14229 (setq tags-alist (delete entry tags-alist)))
14230 (setq i (1- i)))
14231 ;; add the nex tags
14232 (when tags
14233 (setq tags (mapcar 'downcase (org-split-string tags ":"))
14234 tags-alist
14235 (cons (cons level tags) tags-alist)))
14236 ;; compile tags for current headline
14237 (setq tags-list
14238 (if org-use-tag-inheritance
14239 (apply 'append (mapcar 'cdr tags-alist))
14240 tags))
14241 (when (and (or (not todo-only) (member todo org-not-done-keywords))
14242 (eval matcher)
14243 (or (not org-agenda-skip-archived-trees)
14244 (not (member org-archive-tag tags-list))))
14245 (and (eq action 'agenda) (org-agenda-skip))
14246 ;; list this headline
14247
14248 (if (eq action 'sparse-tree)
14249 (progn
14250 (and org-highlight-sparse-tree-matches
14251 (org-get-heading) (match-end 0)
14252 (org-highlight-new-match
14253 (match-beginning 0) (match-beginning 1)))
14254 (org-show-context 'tags-tree))
14255 (setq txt (org-format-agenda-item
14256 ""
14257 (concat
14258 (if org-tags-match-list-sublevels
14259 (make-string (1- level) ?.) "")
14260 (org-get-heading))
14261 category tags-list)
14262 priority (org-get-priority txt))
14263 (goto-char lspos)
14264 (setq marker (org-agenda-new-marker))
14265 (org-add-props txt props
14266 'org-marker marker 'org-hd-marker marker 'org-category category
14267 'priority priority 'type "tagsmatch")
14268 (push txt rtn))
14269 ;; if we are to skip sublevels, jump to end of subtree
14270 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
14271 (when (and (eq action 'sparse-tree)
14272 (not org-sparse-tree-open-archived-trees))
14273 (org-hide-archived-subtrees (point-min) (point-max)))
14274 (nreverse rtn)))
14275
14276 (defvar todo-only) ;; dynamically scoped
14277
14278 (defun org-tags-sparse-tree (&optional todo-only match)
14279 "Create a sparse tree according to tags string MATCH.
14280 MATCH can contain positive and negative selection of tags, like
14281 \"+WORK+URGENT-WITHBOSS\".
14282 If optional argument TODO_ONLY is non-nil, only select lines that are
14283 also TODO lines."
14284 (interactive "P")
14285 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14286
14287 (defvar org-cached-props nil)
14288 (defun org-cached-entry-get (pom property)
14289 (if org-use-property-inheritance
14290 ;; Caching is not possible, check it directly
14291 (org-entry-get pom property 'inherit)
14292 ;; Get all properties, so that we can do complicated checks easily
14293 (cdr (assoc property (or org-cached-props
14294 (setq org-cached-props
14295 (org-entry-properties pom)))))))
14296
14297 (defun org-global-tags-completion-table (&optional files)
14298 "Return the list of all tags in all agenda buffer/files."
14299 (save-excursion
14300 (org-uniquify
14301 (apply 'append
14302 (mapcar
14303 (lambda (file)
14304 (set-buffer (find-file-noselect file))
14305 (org-get-buffer-tags))
14306 (if (and files (car files))
14307 files
14308 (org-agenda-files)))))))
14309
14310 (defun org-make-tags-matcher (match)
14311 "Create the TAGS//TODO matcher form for the selection string MATCH."
14312 ;; todo-only is scoped dynamically into this function, and the function
14313 ;; may change it it the matcher asksk for it.
14314 (unless match
14315 ;; Get a new match request, with completion
14316 (let ((org-last-tags-completion-table
14317 (org-global-tags-completion-table)))
14318 (setq match (completing-read
14319 "Match: " 'org-tags-completion-function nil nil nil
14320 'org-tags-history))))
14321
14322 ;; Parse the string and create a lisp form
14323 (let ((match0 match)
14324 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
14325 minus tag mm
14326 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14327 orterms term orlist re-p level-p prop-p pn pv)
14328 (if (string-match "/+" match)
14329 ;; match contains also a todo-matching request
14330 (progn
14331 (setq tagsmatch (substring match 0 (match-beginning 0))
14332 todomatch (substring match (match-end 0)))
14333 (if (string-match "^!" todomatch)
14334 (setq todo-only t todomatch (substring todomatch 1)))
14335 (if (string-match "^\\s-*$" todomatch)
14336 (setq todomatch nil)))
14337 ;; only matching tags
14338 (setq tagsmatch match todomatch nil))
14339
14340 ;; Make the tags matcher
14341 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14342 (setq tagsmatcher t)
14343 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14344 (while (setq term (pop orterms))
14345 (while (and (equal (substring term -1) "\\") orterms)
14346 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14347 (while (string-match re term)
14348 (setq minus (and (match-end 1)
14349 (equal (match-string 1 term) "-"))
14350 tag (match-string 2 term)
14351 re-p (equal (string-to-char tag) ?{)
14352 level-p (match-end 3)
14353 prop-p (match-end 4)
14354 mm (cond
14355 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14356 (level-p `(= level ,(string-to-number
14357 (match-string 3 term))))
14358 (prop-p
14359 (setq pn (match-string 4 term)
14360 pv (match-string 5 term)
14361 re-p (equal (string-to-char pv) ?{)
14362 pv (substring pv 1 -1))
14363 (if re-p
14364 `(string-match ,pv (or (org-cached-entry-get nil ,pn) ""))
14365 `(equal ,pv (org-cached-entry-get nil ,pn))))
14366 (t `(member ,(downcase tag) tags-list)))
14367 mm (if minus (list 'not mm) mm)
14368 term (substring term (match-end 0)))
14369 (push mm tagsmatcher))
14370 (push (if (> (length tagsmatcher) 1)
14371 (cons 'and tagsmatcher)
14372 (car tagsmatcher))
14373 orlist)
14374 (setq tagsmatcher nil))
14375 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14376 (setq tagsmatcher
14377 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14378
14379 ;; Make the todo matcher
14380 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14381 (setq todomatcher t)
14382 (setq orterms (org-split-string todomatch "|") orlist nil)
14383 (while (setq term (pop orterms))
14384 (while (string-match re term)
14385 (setq minus (and (match-end 1)
14386 (equal (match-string 1 term) "-"))
14387 kwd (match-string 2 term)
14388 re-p (equal (string-to-char kwd) ?{)
14389 term (substring term (match-end 0))
14390 mm (if re-p
14391 `(string-match ,(substring kwd 1 -1) todo)
14392 (list 'equal 'todo kwd))
14393 mm (if minus (list 'not mm) mm))
14394 (push mm todomatcher))
14395 (push (if (> (length todomatcher) 1)
14396 (cons 'and todomatcher)
14397 (car todomatcher))
14398 orlist)
14399 (setq todomatcher nil))
14400 (setq todomatcher (if (> (length orlist) 1)
14401 (cons 'or orlist) (car orlist))))
14402
14403 ;; Return the string and lisp forms of the matcher
14404 (setq matcher (if todomatcher
14405 (list 'and tagsmatcher todomatcher)
14406 tagsmatcher))
14407 (cons match0 matcher)))
14408
14409 (defun org-match-any-p (re list)
14410 "Does re match any element of list?"
14411 (setq list (mapcar (lambda (x) (string-match re x)) list))
14412 (delq nil list))
14413
14414 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
14415 (defvar org-tags-overlay (org-make-overlay 1 1))
14416 (org-detach-overlay org-tags-overlay)
14417
14418 (defun org-align-tags-here (to-col)
14419 ;; Assumes that this is a headline
14420 (let ((pos (point)) (col (current-column)) tags)
14421 (beginning-of-line 1)
14422 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14423 (< pos (match-beginning 2)))
14424 (progn
14425 (setq tags (match-string 2))
14426 (goto-char (match-beginning 1))
14427 (insert " ")
14428 (delete-region (point) (1+ (match-end 0)))
14429 (backward-char 1)
14430 (move-to-column
14431 (max (1+ (current-column))
14432 (1+ col)
14433 (if (> to-col 0)
14434 to-col
14435 (- (abs to-col) (length tags))))
14436 t)
14437 (insert tags)
14438 (move-to-column (min (current-column) col) t))
14439 (goto-char pos))))
14440
14441 (defun org-set-tags (&optional arg just-align)
14442 "Set the tags for the current headline.
14443 With prefix ARG, realign all tags in headings in the current buffer."
14444 (interactive "P")
14445 (let* ((re (concat "^" outline-regexp))
14446 (current (org-get-tags-string))
14447 (col (current-column))
14448 (org-setting-tags t)
14449 table current-tags inherited-tags ; computed below when needed
14450 tags p0 c0 c1 rpl)
14451 (if arg
14452 (save-excursion
14453 (goto-char (point-min))
14454 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14455 (while (re-search-forward re nil t)
14456 (org-set-tags nil t)
14457 (end-of-line 1)))
14458 (message "All tags realigned to column %d" org-tags-column))
14459 (if just-align
14460 (setq tags current)
14461 ;; Get a new set of tags from the user
14462 (save-excursion
14463 (setq table (or org-tag-alist (org-get-buffer-tags))
14464 org-last-tags-completion-table table
14465 current-tags (org-split-string current ":")
14466 inherited-tags (nreverse
14467 (nthcdr (length current-tags)
14468 (nreverse (org-get-tags-at))))
14469 tags
14470 (if (or (eq t org-use-fast-tag-selection)
14471 (and org-use-fast-tag-selection
14472 (delq nil (mapcar 'cdr table))))
14473 (org-fast-tag-selection
14474 current-tags inherited-tags table
14475 (if org-fast-tag-selection-include-todo org-todo-key-alist))
14476 (let ((org-add-colon-after-tag-completion t))
14477 (org-trim
14478 (org-without-partial-completion
14479 (completing-read "Tags: " 'org-tags-completion-function
14480 nil nil current 'org-tags-history)))))))
14481 (while (string-match "[-+&]+" tags)
14482 ;; No boolean logic, just a list
14483 (setq tags (replace-match ":" t t tags))))
14484
14485 (if (string-match "\\`[\t ]*\\'" tags)
14486 (setq tags "")
14487 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14488 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14489
14490 ;; Insert new tags at the correct column
14491 (beginning-of-line 1)
14492 (cond
14493 ((and (equal current "") (equal tags "")))
14494 ((re-search-forward
14495 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14496 (point-at-eol) t)
14497 (if (equal tags "")
14498 (setq rpl "")
14499 (goto-char (match-beginning 0))
14500 (setq c0 (current-column) p0 (point)
14501 c1 (max (1+ c0) (if (> org-tags-column 0)
14502 org-tags-column
14503 (- (- org-tags-column) (length tags))))
14504 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14505 (replace-match rpl t t)
14506 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
14507 tags)
14508 (t (error "Tags alignment failed")))
14509 (move-to-column col)
14510 (unless just-align
14511 (run-hooks 'org-after-tags-change-hook)))))
14512
14513 (defun org-change-tag-in-region (beg end tag off)
14514 "Add or remove TAG for each entry in the region.
14515 This works in the agenda, and also in an org-mode buffer."
14516 (interactive
14517 (list (region-beginning) (region-end)
14518 (let ((org-last-tags-completion-table
14519 (if (org-mode-p)
14520 (org-get-buffer-tags)
14521 (org-global-tags-completion-table))))
14522 (completing-read
14523 "Tag: " 'org-tags-completion-function nil nil nil
14524 'org-tags-history))
14525 (progn
14526 (message "[s]et or [r]emove? ")
14527 (equal (read-char-exclusive) ?r))))
14528 (if (fboundp 'deactivate-mark) (deactivate-mark))
14529 (let ((agendap (equal major-mode 'org-agenda-mode))
14530 l1 l2 m buf pos newhead (cnt 0))
14531 (goto-char end)
14532 (setq l2 (1- (org-current-line)))
14533 (goto-char beg)
14534 (setq l1 (org-current-line))
14535 (loop for l from l1 to l2 do
14536 (goto-line l)
14537 (setq m (get-text-property (point) 'org-hd-marker))
14538 (when (or (and (org-mode-p) (org-on-heading-p))
14539 (and agendap m))
14540 (setq buf (if agendap (marker-buffer m) (current-buffer))
14541 pos (if agendap m (point)))
14542 (with-current-buffer buf
14543 (save-excursion
14544 (save-restriction
14545 (goto-char pos)
14546 (setq cnt (1+ cnt))
14547 (org-toggle-tag tag (if off 'off 'on))
14548 (setq newhead (org-get-heading)))))
14549 (and agendap (org-agenda-change-all-lines newhead m))))
14550 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14551
14552 (defun org-tags-completion-function (string predicate &optional flag)
14553 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14554 (confirm (lambda (x) (stringp (car x)))))
14555 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
14556 (setq s1 (match-string 1 string)
14557 s2 (match-string 2 string))
14558 (setq s1 "" s2 string))
14559 (cond
14560 ((eq flag nil)
14561 ;; try completion
14562 (setq rtn (try-completion s2 ctable confirm))
14563 (if (stringp rtn)
14564 (setq rtn
14565 (concat s1 s2 (substring rtn (length s2))
14566 (if (and org-add-colon-after-tag-completion
14567 (assoc rtn ctable))
14568 ":" ""))))
14569 rtn)
14570 ((eq flag t)
14571 ;; all-completions
14572 (all-completions s2 ctable confirm)
14573 )
14574 ((eq flag 'lambda)
14575 ;; exact match?
14576 (assoc s2 ctable)))
14577 ))
14578
14579 (defun org-fast-tag-insert (kwd tags face &optional end)
14580 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
14581 (insert (format "%-12s" (concat kwd ":"))
14582 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14583 (or end "")))
14584
14585 (defun org-fast-tag-show-exit (flag)
14586 (save-excursion
14587 (goto-line 3)
14588 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14589 (replace-match ""))
14590 (when flag
14591 (end-of-line 1)
14592 (move-to-column (- (window-width) 19) t)
14593 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14594
14595 (defun org-set-current-tags-overlay (current prefix)
14596 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14597 (if (featurep 'xemacs)
14598 (org-overlay-display org-tags-overlay (concat prefix s)
14599 'secondary-selection)
14600 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14601 (org-overlay-display org-tags-overlay (concat prefix s)))))
14602
14603 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14604 "Fast tag selection with single keys.
14605 CURRENT is the current list of tags in the headline, INHERITED is the
14606 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14607 possibly with grouping information. TODO-TABLE is a similar table with
14608 TODO keywords, should these have keys assigned to them.
14609 If the keys are nil, a-z are automatically assigned.
14610 Returns the new tags string, or nil to not change the current settings."
14611 (let* ((fulltable (append table todo-table))
14612 (maxlen (apply 'max (mapcar
14613 (lambda (x)
14614 (if (stringp (car x)) (string-width (car x)) 0))
14615 fulltable)))
14616 (buf (current-buffer))
14617 (expert (eq org-fast-tag-selection-single-key 'expert))
14618 (buffer-tags nil)
14619 (fwidth (+ maxlen 3 1 3))
14620 (ncol (/ (- (window-width) 4) fwidth))
14621 (i-face 'org-done)
14622 (c-face 'org-todo)
14623 tg cnt e c char c1 c2 ntable tbl rtn
14624 ov-start ov-end ov-prefix
14625 (exit-after-next org-fast-tag-selection-single-key)
14626 (done-keywords org-done-keywords)
14627 groups ingroup)
14628 (save-excursion
14629 (beginning-of-line 1)
14630 (if (looking-at
14631 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14632 (setq ov-start (match-beginning 1)
14633 ov-end (match-end 1)
14634 ov-prefix "")
14635 (setq ov-start (1- (point-at-eol))
14636 ov-end (1+ ov-start))
14637 (skip-chars-forward "^\n\r")
14638 (setq ov-prefix
14639 (concat
14640 (buffer-substring (1- (point)) (point))
14641 (if (> (current-column) org-tags-column)
14642 " "
14643 (make-string (- org-tags-column (current-column)) ?\ ))))))
14644 (org-move-overlay org-tags-overlay ov-start ov-end)
14645 (save-window-excursion
14646 (if expert
14647 (set-buffer (get-buffer-create " *Org tags*"))
14648 (delete-other-windows)
14649 (split-window-vertically)
14650 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14651 (erase-buffer)
14652 (org-set-local 'org-done-keywords done-keywords)
14653 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14654 (org-fast-tag-insert "Current" current c-face "\n\n")
14655 (org-fast-tag-show-exit exit-after-next)
14656 (org-set-current-tags-overlay current ov-prefix)
14657 (setq tbl fulltable char ?a cnt 0)
14658 (while (setq e (pop tbl))
14659 (cond
14660 ((equal e '(:startgroup))
14661 (push '() groups) (setq ingroup t)
14662 (when (not (= cnt 0))
14663 (setq cnt 0)
14664 (insert "\n"))
14665 (insert "{ "))
14666 ((equal e '(:endgroup))
14667 (setq ingroup nil cnt 0)
14668 (insert "}\n"))
14669 (t
14670 (setq tg (car e) c2 nil)
14671 (if (cdr e)
14672 (setq c (cdr e))
14673 ;; automatically assign a character.
14674 (setq c1 (string-to-char
14675 (downcase (substring
14676 tg (if (= (string-to-char tg) ?@) 1 0)))))
14677 (if (or (rassoc c1 ntable) (rassoc c1 table))
14678 (while (or (rassoc char ntable) (rassoc char table))
14679 (setq char (1+ char)))
14680 (setq c2 c1))
14681 (setq c (or c2 char)))
14682 (if ingroup (push tg (car groups)))
14683 (setq tg (org-add-props tg nil 'face
14684 (cond
14685 ((not (assoc tg table))
14686 (org-get-todo-face tg))
14687 ((member tg current) c-face)
14688 ((member tg inherited) i-face)
14689 (t nil))))
14690 (if (and (= cnt 0) (not ingroup)) (insert " "))
14691 (insert "[" c "] " tg (make-string
14692 (- fwidth 4 (length tg)) ?\ ))
14693 (push (cons tg c) ntable)
14694 (when (= (setq cnt (1+ cnt)) ncol)
14695 (insert "\n")
14696 (if ingroup (insert " "))
14697 (setq cnt 0)))))
14698 (setq ntable (nreverse ntable))
14699 (insert "\n")
14700 (goto-char (point-min))
14701 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14702 (fit-window-to-buffer))
14703 (setq rtn
14704 (catch 'exit
14705 (while t
14706 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
14707 (if groups " [!] no groups" " [!]groups")
14708 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14709 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14710 (cond
14711 ((= c ?\r) (throw 'exit t))
14712 ((= c ?!)
14713 (setq groups (not groups))
14714 (goto-char (point-min))
14715 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14716 ((= c ?\C-c)
14717 (if (not expert)
14718 (org-fast-tag-show-exit
14719 (setq exit-after-next (not exit-after-next)))
14720 (setq expert nil)
14721 (delete-other-windows)
14722 (split-window-vertically)
14723 (org-switch-to-buffer-other-window " *Org tags*")
14724 (and (fboundp 'fit-window-to-buffer)
14725 (fit-window-to-buffer))))
14726 ((or (= c ?\C-g)
14727 (and (= c ?q) (not (rassoc c ntable))))
14728 (org-detach-overlay org-tags-overlay)
14729 (setq quit-flag t))
14730 ((= c ?\ )
14731 (setq current nil)
14732 (if exit-after-next (setq exit-after-next 'now)))
14733 ((= c ?\t)
14734 (condition-case nil
14735 (setq tg (completing-read
14736 "Tag: "
14737 (or buffer-tags
14738 (with-current-buffer buf
14739 (org-get-buffer-tags)))))
14740 (quit (setq tg "")))
14741 (when (string-match "\\S-" tg)
14742 (add-to-list 'buffer-tags (list tg))
14743 (if (member tg current)
14744 (setq current (delete tg current))
14745 (push tg current)))
14746 (if exit-after-next (setq exit-after-next 'now)))
14747 ((setq e (rassoc c todo-table) tg (car e))
14748 (with-current-buffer buf
14749 (save-excursion (org-todo tg)))
14750 (if exit-after-next (setq exit-after-next 'now)))
14751 ((setq e (rassoc c ntable) tg (car e))
14752 (if (member tg current)
14753 (setq current (delete tg current))
14754 (loop for g in groups do
14755 (if (member tg g)
14756 (mapc (lambda (x)
14757 (setq current (delete x current)))
14758 g)))
14759 (push tg current))
14760 (if exit-after-next (setq exit-after-next 'now))))
14761
14762 ;; Create a sorted list
14763 (setq current
14764 (sort current
14765 (lambda (a b)
14766 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14767 (if (eq exit-after-next 'now) (throw 'exit t))
14768 (goto-char (point-min))
14769 (beginning-of-line 2)
14770 (delete-region (point) (point-at-eol))
14771 (org-fast-tag-insert "Current" current c-face)
14772 (org-set-current-tags-overlay current ov-prefix)
14773 (while (re-search-forward
14774 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
14775 (setq tg (match-string 1))
14776 (add-text-properties
14777 (match-beginning 1) (match-end 1)
14778 (list 'face
14779 (cond
14780 ((member tg current) c-face)
14781 ((member tg inherited) i-face)
14782 (t (get-text-property (match-beginning 1) 'face))))))
14783 (goto-char (point-min)))))
14784 (org-detach-overlay org-tags-overlay)
14785 (if rtn
14786 (mapconcat 'identity current ":")
14787 nil))))
14788
14789 (defun org-get-tags-string ()
14790 "Get the TAGS string in the current headline."
14791 (unless (org-on-heading-p t)
14792 (error "Not on a heading"))
14793 (save-excursion
14794 (beginning-of-line 1)
14795 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14796 (org-match-string-no-properties 1)
14797 "")))
14798
14799 (defun org-get-tags ()
14800 "Get the list of tags specified in the current headline."
14801 (org-split-string (org-get-tags-string) ":"))
14802
14803 (defun org-get-buffer-tags ()
14804 "Get a table of all tags used in the buffer, for completion."
14805 (let (tags)
14806 (save-excursion
14807 (goto-char (point-min))
14808 (while (re-search-forward
14809 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
14810 (when (equal (char-after (point-at-bol 0)) ?*)
14811 (mapc (lambda (x) (add-to-list 'tags x))
14812 (org-split-string (org-match-string-no-properties 1) ":")))))
14813 (mapcar 'list tags)))
14814
14815
14816 ;;;; Properties
14817
14818 ;;; Setting and retrieving properties
14819
14820 (defconst org-special-properties
14821 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY")
14822 "The special properties valid in Org-mode.
14823
14824 These are properties that are not defined in the property drawer,
14825 but in some other way.")
14826
14827 (defconst org-default-properties
14828 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
14829 "LOCATION" "LOGGING" "COLUMNS")
14830 "Some properties that are used by Org-mode for various purposes.
14831 Being in this list makes sure that they are offered for completion.")
14832
14833 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14834 "Regular expression matching the first line of a property drawer.")
14835
14836 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14837 "Regular expression matching the first line of a property drawer.")
14838
14839 (defun org-property-action ()
14840 "Do an action on properties."
14841 (interactive)
14842 (let (c)
14843 (org-at-property-p)
14844 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14845 (setq c (read-char-exclusive))
14846 (cond
14847 ((equal c ?s)
14848 (call-interactively 'org-set-property))
14849 ((equal c ?d)
14850 (call-interactively 'org-delete-property))
14851 ((equal c ?D)
14852 (call-interactively 'org-delete-property-globally))
14853 ((equal c ?c)
14854 (call-interactively 'org-compute-property-at-point))
14855 (t (error "No such property action %c" c)))))
14856
14857 (defun org-at-property-p ()
14858 "Is the cursor in a property line?"
14859 ;; FIXME: Does not check if we are actually in the drawer.
14860 ;; FIXME: also returns true on any drawers.....
14861 ;; This is used by C-c C-c for property action.
14862 (save-excursion
14863 (beginning-of-line 1)
14864 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
14865
14866 (defmacro org-with-point-at (pom &rest body)
14867 "Move to buffer and point of point-or-marker POM for the duration of BODY."
14868 (declare (indent 1) (debug t))
14869 `(save-excursion
14870 (if (markerp pom) (set-buffer (marker-buffer pom)))
14871 (save-excursion
14872 (goto-char (or pom (point)))
14873 ,@body)))
14874
14875 (defun org-get-property-block (&optional beg end force)
14876 "Return the (beg . end) range of the body of the property drawer.
14877 BEG and END can be beginning and end of subtree, if not given
14878 they will be found.
14879 If the drawer does not exist and FORCE is non-nil, create the drawer."
14880 (catch 'exit
14881 (save-excursion
14882 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14883 (end (or end (progn (outline-next-heading) (point)))))
14884 (goto-char beg)
14885 (if (re-search-forward org-property-start-re end t)
14886 (setq beg (1+ (match-end 0)))
14887 (if force
14888 (save-excursion
14889 (org-insert-property-drawer)
14890 (setq end (progn (outline-next-heading) (point))))
14891 (throw 'exit nil))
14892 (goto-char beg)
14893 (if (re-search-forward org-property-start-re end t)
14894 (setq beg (1+ (match-end 0)))))
14895 (if (re-search-forward org-property-end-re end t)
14896 (setq end (match-beginning 0))
14897 (or force (throw 'exit nil))
14898 (goto-char beg)
14899 (setq end beg)
14900 (org-indent-line-function)
14901 (insert ":END:\n"))
14902 (cons beg end)))))
14903
14904 (defun org-entry-properties (&optional pom which)
14905 "Get all properties of the entry at point-or-marker POM.
14906 This includes the TODO keyword, the tags, time strings for deadline,
14907 scheduled, and clocking, and any additional properties defined in the
14908 entry. The return value is an alist, keys may occur multiple times
14909 if the property key was used several times.
14910 POM may also be nil, in which case the current entry is used.
14911 If WHICH is nil or `all', get all properties. If WHICH is
14912 `special' or `standard', only get that subclass."
14913 (setq which (or which 'all))
14914 (org-with-point-at pom
14915 (let ((clockstr (substring org-clock-string 0 -1))
14916 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
14917 beg end range props sum-props key value)
14918 (save-excursion
14919 (when (condition-case nil (org-back-to-heading t) (error nil))
14920 (setq beg (point))
14921 (setq sum-props (get-text-property (point) 'org-summaries))
14922 (outline-next-heading)
14923 (setq end (point))
14924 (when (memq which '(all special))
14925 ;; Get the special properties, like TODO and tags
14926 (goto-char beg)
14927 (when (and (looking-at org-todo-line-regexp) (match-end 2))
14928 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14929 (when (looking-at org-priority-regexp)
14930 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14931 (when (and (setq value (org-get-tags-string))
14932 (string-match "\\S-" value))
14933 (push (cons "TAGS" value) props))
14934 (when (setq value (org-get-tags-at))
14935 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
14936 props))
14937 (while (re-search-forward org-keyword-time-regexp end t)
14938 (setq key (substring (org-match-string-no-properties 1) 0 -1))
14939 (unless (member key excluded) (push key excluded))
14940 (push (cons key
14941 (if (equal key clockstr)
14942 (org-no-properties
14943 (org-trim
14944 (buffer-substring
14945 (match-beginning 2) (point-at-eol))))
14946 (org-match-string-no-properties 2)))
14947 props)))
14948 (when (memq which '(all standard))
14949 ;; Get the standard properties, like :PORP: ...
14950 (setq range (org-get-property-block beg end))
14951 (when range
14952 (goto-char (car range))
14953 (while (re-search-forward
14954 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14955 (cdr range) t)
14956 (setq key (org-match-string-no-properties 1)
14957 value (org-trim (or (org-match-string-no-properties 2) "")))
14958 (unless (member key excluded)
14959 (push (cons key (or value "")) props)))))
14960 (append sum-props (nreverse props)))))))
14961
14962 (defun org-entry-get (pom property &optional inherit)
14963 "Get value of PROPERTY for entry at point-or-marker POM.
14964 If INHERIT is non-nil and the entry does not have the property,
14965 then also check higher levels of the hierarchy.
14966 If the property is present but empty, the return value is the empty string.
14967 If the property is not present at all, nil is returned."
14968 (org-with-point-at pom
14969 (if inherit
14970 (org-entry-get-with-inheritance property)
14971 (if (member property org-special-properties)
14972 ;; We need a special property. Use brute force, get all properties.
14973 (cdr (assoc property (org-entry-properties nil 'special)))
14974 (let ((range (org-get-property-block)))
14975 (if (and range
14976 (goto-char (car range))
14977 (re-search-forward
14978 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
14979 (cdr range) t))
14980 ;; Found the property, return it.
14981 (if (match-end 1)
14982 (org-match-string-no-properties 1)
14983 "")))))))
14984
14985 (defun org-entry-delete (pom property)
14986 "Delete the property PROPERTY from entry at point-or-marker POM."
14987 (org-with-point-at pom
14988 (if (member property org-special-properties)
14989 nil ; cannot delete these properties.
14990 (let ((range (org-get-property-block)))
14991 (if (and range
14992 (goto-char (car range))
14993 (re-search-forward
14994 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
14995 (cdr range) t))
14996 (progn
14997 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14998 t)
14999 nil)))))
15000
15001 ;; Multi-values properties are properties that contain multiple values
15002 ;; These values are assumed to be single words, separated by whitespace.
15003 (defun org-entry-add-to-multivalued-property (pom property value)
15004 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15005 (let* ((old (org-entry-get pom property))
15006 (values (and old (org-split-string old "[ \t]"))))
15007 (unless (member value values)
15008 (setq values (cons value values))
15009 (org-entry-put pom property
15010 (mapconcat 'identity values " ")))))
15011
15012 (defun org-entry-remove-from-multivalued-property (pom property value)
15013 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15014 (let* ((old (org-entry-get pom property))
15015 (values (and old (org-split-string old "[ \t]"))))
15016 (when (member value values)
15017 (setq values (delete value values))
15018 (org-entry-put pom property
15019 (mapconcat 'identity values " ")))))
15020
15021 (defun org-entry-member-in-multivalued-property (pom property value)
15022 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15023 (let* ((old (org-entry-get pom property))
15024 (values (and old (org-split-string old "[ \t]"))))
15025 (member value values)))
15026
15027 (defvar org-entry-property-inherited-from (make-marker))
15028
15029 (defun org-entry-get-with-inheritance (property)
15030 "Get entry property, and search higher levels if not present."
15031 (let (tmp)
15032 (save-excursion
15033 (save-restriction
15034 (widen)
15035 (catch 'ex
15036 (while t
15037 (when (setq tmp (org-entry-get nil property))
15038 (org-back-to-heading t)
15039 (move-marker org-entry-property-inherited-from (point))
15040 (throw 'ex tmp))
15041 (or (org-up-heading-safe) (throw 'ex nil)))))
15042 (or tmp (cdr (assoc property org-local-properties))
15043 (cdr (assoc property org-global-properties))))))
15044
15045 (defun org-entry-put (pom property value)
15046 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15047 (org-with-point-at pom
15048 (org-back-to-heading t)
15049 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15050 range)
15051 (cond
15052 ((equal property "TODO")
15053 (when (and (stringp value) (string-match "\\S-" value)
15054 (not (member value org-todo-keywords-1)))
15055 (error "\"%s\" is not a valid TODO state" value))
15056 (if (or (not value)
15057 (not (string-match "\\S-" value)))
15058 (setq value 'none))
15059 (org-todo value)
15060 (org-set-tags nil 'align))
15061 ((equal property "PRIORITY")
15062 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15063 (string-to-char value) ?\ ))
15064 (org-set-tags nil 'align))
15065 ((equal property "SCHEDULED")
15066 (if (re-search-forward org-scheduled-time-regexp end t)
15067 (cond
15068 ((eq value 'earlier) (org-timestamp-change -1 'day))
15069 ((eq value 'later) (org-timestamp-change 1 'day))
15070 (t (call-interactively 'org-schedule)))
15071 (call-interactively 'org-schedule)))
15072 ((equal property "DEADLINE")
15073 (if (re-search-forward org-deadline-time-regexp end t)
15074 (cond
15075 ((eq value 'earlier) (org-timestamp-change -1 'day))
15076 ((eq value 'later) (org-timestamp-change 1 'day))
15077 (t (call-interactively 'org-deadline)))
15078 (call-interactively 'org-deadline)))
15079 ((member property org-special-properties)
15080 (error "The %s property can not yet be set with `org-entry-put'"
15081 property))
15082 (t ; a non-special property
15083 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15084 (setq range (org-get-property-block beg end 'force))
15085 (goto-char (car range))
15086 (if (re-search-forward
15087 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
15088 (progn
15089 (delete-region (match-beginning 1) (match-end 1))
15090 (goto-char (match-beginning 1)))
15091 (goto-char (cdr range))
15092 (insert "\n")
15093 (backward-char 1)
15094 (org-indent-line-function)
15095 (insert ":" property ":"))
15096 (and value (insert " " value))
15097 (org-indent-line-function)))))))
15098
15099 (defun org-buffer-property-keys (&optional include-specials include-defaults)
15100 "Get all property keys in the current buffer.
15101 With INCLUDE-SPECIALS, also list the special properties that relect things
15102 like tags and TODO state.
15103 With INCLUDE-DEFAULTS, also include properties that has special meaning
15104 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
15105 (let (rtn range)
15106 (save-excursion
15107 (save-restriction
15108 (widen)
15109 (goto-char (point-min))
15110 (while (re-search-forward org-property-start-re nil t)
15111 (setq range (org-get-property-block))
15112 (goto-char (car range))
15113 (while (re-search-forward
15114 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
15115 (cdr range) t)
15116 (add-to-list 'rtn (org-match-string-no-properties 1)))
15117 (outline-next-heading))))
15118
15119 (when include-specials
15120 (setq rtn (append org-special-properties rtn)))
15121
15122 (when include-defaults
15123 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
15124
15125 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15126
15127 (defun org-property-values (key)
15128 "Return a list of all values of property KEY."
15129 (save-excursion
15130 (save-restriction
15131 (widen)
15132 (goto-char (point-min))
15133 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
15134 values)
15135 (while (re-search-forward re nil t)
15136 (add-to-list 'values (org-trim (match-string 1))))
15137 (delete "" values)))))
15138
15139 (defun org-insert-property-drawer ()
15140 "Insert a property drawer into the current entry."
15141 (interactive)
15142 (org-back-to-heading t)
15143 (looking-at outline-regexp)
15144 (let ((indent (- (match-end 0)(match-beginning 0)))
15145 (beg (point))
15146 (re (concat "^[ \t]*" org-keyword-time-regexp))
15147 end hiddenp)
15148 (outline-next-heading)
15149 (setq end (point))
15150 (goto-char beg)
15151 (while (re-search-forward re end t))
15152 (setq hiddenp (org-invisible-p))
15153 (end-of-line 1)
15154 (and (equal (char-after) ?\n) (forward-char 1))
15155 (org-skip-over-state-notes)
15156 (skip-chars-backward " \t\n\r")
15157 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15158 (beginning-of-line 0)
15159 (indent-to-column indent)
15160 (beginning-of-line 2)
15161 (indent-to-column indent)
15162 (beginning-of-line 0)
15163 (if hiddenp
15164 (save-excursion
15165 (org-back-to-heading t)
15166 (hide-entry))
15167 (org-flag-drawer t))))
15168
15169 (defun org-set-property (property value)
15170 "In the current entry, set PROPERTY to VALUE.
15171 When called interactively, this will prompt for a property name, offering
15172 completion on existing and default properties. And then it will prompt
15173 for a value, offering competion either on allowed values (via an inherited
15174 xxx_ALL property) or on existing values in other instances of this property
15175 in the current file."
15176 (interactive
15177 (let* ((prop (completing-read
15178 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
15179 (cur (org-entry-get nil prop))
15180 (allowed (org-property-get-allowed-values nil prop 'table))
15181 (existing (mapcar 'list (org-property-values prop)))
15182 (val (if allowed
15183 (completing-read "Value: " allowed nil 'req-match)
15184 (completing-read
15185 (concat "Value" (if (and cur (string-match "\\S-" cur))
15186 (concat "[" cur "]") "")
15187 ": ")
15188 existing nil nil "" nil cur))))
15189 (list prop (if (equal val "") cur val))))
15190 (unless (equal (org-entry-get nil property) value)
15191 (org-entry-put nil property value)))
15192
15193 (defun org-delete-property (property)
15194 "In the current entry, delete PROPERTY."
15195 (interactive
15196 (let* ((prop (completing-read
15197 "Property: " (org-entry-properties nil 'standard))))
15198 (list prop)))
15199 (message (concat "Property " property
15200 (if (org-entry-delete nil property)
15201 " deleted"
15202 " was not present in the entry"))))
15203
15204 (defun org-delete-property-globally (property)
15205 "Remove PROPERTY globally, from all entries."
15206 (interactive
15207 (let* ((prop (completing-read
15208 "Globally remove property: "
15209 (mapcar 'list (org-buffer-property-keys)))))
15210 (list prop)))
15211 (save-excursion
15212 (save-restriction
15213 (widen)
15214 (goto-char (point-min))
15215 (let ((cnt 0))
15216 (while (re-search-forward
15217 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
15218 nil t)
15219 (setq cnt (1+ cnt))
15220 (replace-match ""))
15221 (message "Property \"%s\" removed from %d entries" property cnt)))))
15222
15223 (defvar org-columns-current-fmt-compiled) ; defined below
15224
15225 (defun org-compute-property-at-point ()
15226 "Compute the property at point.
15227 This looks for an enclosing column format, extracts the operator and
15228 then applies it to the proerty in the column format's scope."
15229 (interactive)
15230 (unless (org-at-property-p)
15231 (error "Not at a property"))
15232 (let ((prop (org-match-string-no-properties 2)))
15233 (org-columns-get-format-and-top-level)
15234 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15235 (error "No operator defined for property %s" prop))
15236 (org-columns-compute prop)))
15237
15238 (defun org-property-get-allowed-values (pom property &optional table)
15239 "Get allowed values for the property PROPERTY.
15240 When TABLE is non-nil, return an alist that can directly be used for
15241 completion."
15242 (let (vals)
15243 (cond
15244 ((equal property "TODO")
15245 (setq vals (org-with-point-at pom
15246 (append org-todo-keywords-1 '("")))))
15247 ((equal property "PRIORITY")
15248 (let ((n org-lowest-priority))
15249 (while (>= n org-highest-priority)
15250 (push (char-to-string n) vals)
15251 (setq n (1- n)))))
15252 ((member property org-special-properties))
15253 (t
15254 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15255
15256 (when (and vals (string-match "\\S-" vals))
15257 (setq vals (car (read-from-string (concat "(" vals ")"))))
15258 (setq vals (mapcar (lambda (x)
15259 (cond ((stringp x) x)
15260 ((numberp x) (number-to-string x))
15261 ((symbolp x) (symbol-name x))
15262 (t "???")))
15263 vals)))))
15264 (if table (mapcar 'list vals) vals)))
15265
15266 (defun org-property-previous-allowed-value (&optional previous)
15267 "Switch to the next allowed value for this property."
15268 (interactive)
15269 (org-property-next-allowed-value t))
15270
15271 (defun org-property-next-allowed-value (&optional previous)
15272 "Switch to the next allowed value for this property."
15273 (interactive)
15274 (unless (org-at-property-p)
15275 (error "Not at a property"))
15276 (let* ((key (match-string 2))
15277 (value (match-string 3))
15278 (allowed (or (org-property-get-allowed-values (point) key)
15279 (and (member value '("[ ]" "[-]" "[X]"))
15280 '("[ ]" "[X]"))))
15281 nval)
15282 (unless allowed
15283 (error "Allowed values for this property have not been defined"))
15284 (if previous (setq allowed (reverse allowed)))
15285 (if (member value allowed)
15286 (setq nval (car (cdr (member value allowed)))))
15287 (setq nval (or nval (car allowed)))
15288 (if (equal nval value)
15289 (error "Only one allowed value for this property"))
15290 (org-at-property-p)
15291 (replace-match (concat " :" key ": " nval) t t)
15292 (org-indent-line-function)
15293 (beginning-of-line 1)
15294 (skip-chars-forward " \t")))
15295
15296 (defun org-find-entry-with-id (ident)
15297 "Locate the entry that contains the ID property with exact value IDENT.
15298 IDENT can be a string, a symbol or a number, this function will search for
15299 the string representation of it.
15300 Return the position where this entry starts, or nil if there is no such entry."
15301 (let ((id (cond
15302 ((stringp ident) ident)
15303 ((symbol-name ident) (symbol-name ident))
15304 ((numberp ident) (number-to-string ident))
15305 (t (error "IDENT %s must be a string, symbol or number" ident))))
15306 (case-fold-search nil))
15307 (save-excursion
15308 (save-restriction
15309 (goto-char (point-min))
15310 (when (re-search-forward
15311 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15312 nil t)
15313 (org-back-to-heading)
15314 (point))))))
15315
15316 ;;; Column View
15317
15318 (defvar org-columns-overlays nil
15319 "Holds the list of current column overlays.")
15320
15321 (defvar org-columns-current-fmt nil
15322 "Local variable, holds the currently active column format.")
15323 (defvar org-columns-current-fmt-compiled nil
15324 "Local variable, holds the currently active column format.
15325 This is the compiled version of the format.")
15326 (defvar org-columns-current-widths nil
15327 "Loval variable, holds the currently widths of fields.")
15328 (defvar org-columns-current-maxwidths nil
15329 "Loval variable, holds the currently active maximum column widths.")
15330 (defvar org-columns-begin-marker (make-marker)
15331 "Points to the position where last a column creation command was called.")
15332 (defvar org-columns-top-level-marker (make-marker)
15333 "Points to the position where current columns region starts.")
15334
15335 (defvar org-columns-map (make-sparse-keymap)
15336 "The keymap valid in column display.")
15337
15338 (defun org-columns-content ()
15339 "Switch to contents view while in columns view."
15340 (interactive)
15341 (org-overview)
15342 (org-content))
15343
15344 (org-defkey org-columns-map "c" 'org-columns-content)
15345 (org-defkey org-columns-map "o" 'org-overview)
15346 (org-defkey org-columns-map "e" 'org-columns-edit-value)
15347 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
15348 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
15349 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
15350 (org-defkey org-columns-map "v" 'org-columns-show-value)
15351 (org-defkey org-columns-map "q" 'org-columns-quit)
15352 (org-defkey org-columns-map "r" 'org-columns-redo)
15353 (org-defkey org-columns-map [left] 'backward-char)
15354 (org-defkey org-columns-map "\M-b" 'backward-char)
15355 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
15356 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
15357 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
15358 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
15359 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
15360 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
15361 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
15362 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
15363 (org-defkey org-columns-map "<" 'org-columns-narrow)
15364 (org-defkey org-columns-map ">" 'org-columns-widen)
15365 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
15366 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
15367 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
15368 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
15369
15370 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
15371 '("Column"
15372 ["Edit property" org-columns-edit-value t]
15373 ["Next allowed value" org-columns-next-allowed-value t]
15374 ["Previous allowed value" org-columns-previous-allowed-value t]
15375 ["Show full value" org-columns-show-value t]
15376 ["Edit allowed values" org-columns-edit-allowed t]
15377 "--"
15378 ["Edit column attributes" org-columns-edit-attributes t]
15379 ["Increase column width" org-columns-widen t]
15380 ["Decrease column width" org-columns-narrow t]
15381 "--"
15382 ["Move column right" org-columns-move-right t]
15383 ["Move column left" org-columns-move-left t]
15384 ["Add column" org-columns-new t]
15385 ["Delete column" org-columns-delete t]
15386 "--"
15387 ["CONTENTS" org-columns-content t]
15388 ["OVERVIEW" org-overview t]
15389 ["Refresh columns display" org-columns-redo t]
15390 "--"
15391 ["Open link" org-columns-open-link t]
15392 "--"
15393 ["Quit" org-columns-quit t]))
15394
15395 (defun org-columns-new-overlay (beg end &optional string face)
15396 "Create a new column overlay and add it to the list."
15397 (let ((ov (org-make-overlay beg end)))
15398 (org-overlay-put ov 'face (or face 'secondary-selection))
15399 (org-overlay-display ov string face)
15400 (push ov org-columns-overlays)
15401 ov))
15402
15403 (defun org-columns-display-here (&optional props)
15404 "Overlay the current line with column display."
15405 (interactive)
15406 (let* ((fmt org-columns-current-fmt-compiled)
15407 (beg (point-at-bol))
15408 (level-face (save-excursion
15409 (beginning-of-line 1)
15410 (and (looking-at "\\(\\**\\)\\(\\* \\)")
15411 (org-get-level-face 2))))
15412 (color (list :foreground
15413 (face-attribute (or level-face 'default) :foreground)))
15414 props pom property ass width f string ov column val modval)
15415 ;; Check if the entry is in another buffer.
15416 (unless props
15417 (if (eq major-mode 'org-agenda-mode)
15418 (setq pom (or (get-text-property (point) 'org-hd-marker)
15419 (get-text-property (point) 'org-marker))
15420 props (if pom (org-entry-properties pom) nil))
15421 (setq props (org-entry-properties nil))))
15422 ;; Walk the format
15423 (while (setq column (pop fmt))
15424 (setq property (car column)
15425 ass (if (equal property "ITEM")
15426 (cons "ITEM"
15427 (save-match-data
15428 (org-no-properties
15429 (org-remove-tabs
15430 (buffer-substring-no-properties
15431 (point-at-bol) (point-at-eol))))))
15432 (assoc property props))
15433 width (or (cdr (assoc property org-columns-current-maxwidths))
15434 (nth 2 column)
15435 (length property))
15436 f (format "%%-%d.%ds | " width width)
15437 val (or (cdr ass) "")
15438 modval (if (equal property "ITEM")
15439 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
15440 string (format f (or modval val)))
15441 ;; Create the overlay
15442 (org-unmodified
15443 (setq ov (org-columns-new-overlay
15444 beg (setq beg (1+ beg)) string
15445 (list color 'org-column)))
15446 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
15447 (org-overlay-put ov 'keymap org-columns-map)
15448 (org-overlay-put ov 'org-columns-key property)
15449 (org-overlay-put ov 'org-columns-value (cdr ass))
15450 (org-overlay-put ov 'org-columns-value-modified modval)
15451 (org-overlay-put ov 'org-columns-pom pom)
15452 (org-overlay-put ov 'org-columns-format f))
15453 (if (or (not (char-after beg))
15454 (equal (char-after beg) ?\n))
15455 (let ((inhibit-read-only t))
15456 (save-excursion
15457 (goto-char beg)
15458 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
15459 ;; Make the rest of the line disappear.
15460 (org-unmodified
15461 (setq ov (org-columns-new-overlay beg (point-at-eol)))
15462 (org-overlay-put ov 'invisible t)
15463 (org-overlay-put ov 'keymap org-columns-map)
15464 (org-overlay-put ov 'intangible t)
15465 (push ov org-columns-overlays)
15466 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
15467 (org-overlay-put ov 'keymap org-columns-map)
15468 (push ov org-columns-overlays)
15469 (let ((inhibit-read-only t))
15470 (put-text-property (max (point-min) (1- (point-at-bol)))
15471 (min (point-max) (1+ (point-at-eol)))
15472 'read-only "Type `e' to edit property")))))
15473
15474 (defvar org-previous-header-line-format nil
15475 "The header line format before column view was turned on.")
15476 (defvar org-columns-inhibit-recalculation nil
15477 "Inhibit recomputing of columns on column view startup.")
15478
15479
15480 (defvar header-line-format)
15481 (defun org-columns-display-here-title ()
15482 "Overlay the newline before the current line with the table title."
15483 (interactive)
15484 (let ((fmt org-columns-current-fmt-compiled)
15485 string (title "")
15486 property width f column str widths)
15487 (while (setq column (pop fmt))
15488 (setq property (car column)
15489 str (or (nth 1 column) property)
15490 width (or (cdr (assoc property org-columns-current-maxwidths))
15491 (nth 2 column)
15492 (length str))
15493 widths (push width widths)
15494 f (format "%%-%d.%ds | " width width)
15495 string (format f str)
15496 title (concat title string)))
15497 (setq title (concat
15498 (org-add-props " " nil 'display '(space :align-to 0))
15499 (org-add-props title nil 'face '(:weight bold :underline t))))
15500 (org-set-local 'org-previous-header-line-format header-line-format)
15501 (org-set-local 'org-columns-current-widths (nreverse widths))
15502 (setq header-line-format title)))
15503
15504 (defun org-columns-remove-overlays ()
15505 "Remove all currently active column overlays."
15506 (interactive)
15507 (when (marker-buffer org-columns-begin-marker)
15508 (with-current-buffer (marker-buffer org-columns-begin-marker)
15509 (when (local-variable-p 'org-previous-header-line-format)
15510 (setq header-line-format org-previous-header-line-format)
15511 (kill-local-variable 'org-previous-header-line-format))
15512 (move-marker org-columns-begin-marker nil)
15513 (move-marker org-columns-top-level-marker nil)
15514 (org-unmodified
15515 (mapc 'org-delete-overlay org-columns-overlays)
15516 (setq org-columns-overlays nil)
15517 (let ((inhibit-read-only t))
15518 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
15519
15520 (defun org-columns-cleanup-item (item fmt)
15521 "Remove from ITEM what is a column in the format FMT."
15522 (if (not org-complex-heading-regexp)
15523 item
15524 (when (string-match org-complex-heading-regexp item)
15525 (concat
15526 (org-add-props (concat (match-string 1 item) " ") nil
15527 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
15528 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
15529 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
15530 " " (match-string 4 item)
15531 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
15532
15533 (defun org-columns-show-value ()
15534 "Show the full value of the property."
15535 (interactive)
15536 (let ((value (get-char-property (point) 'org-columns-value)))
15537 (message "Value is: %s" (or value ""))))
15538
15539 (defun org-columns-quit ()
15540 "Remove the column overlays and in this way exit column editing."
15541 (interactive)
15542 (org-unmodified
15543 (org-columns-remove-overlays)
15544 (let ((inhibit-read-only t))
15545 (remove-text-properties (point-min) (point-max) '(read-only t))))
15546 (when (eq major-mode 'org-agenda-mode)
15547 (message
15548 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
15549
15550 (defun org-columns-check-computed ()
15551 "Check if this column value is computed.
15552 If yes, throw an error indicating that changing it does not make sense."
15553 (let ((val (get-char-property (point) 'org-columns-value)))
15554 (when (and (stringp val)
15555 (get-char-property 0 'org-computed val))
15556 (error "This value is computed from the entry's children"))))
15557
15558 (defun org-columns-todo (&optional arg)
15559 "Change the TODO state during column view."
15560 (interactive "P")
15561 (org-columns-edit-value "TODO"))
15562
15563 (defun org-columns-set-tags-or-toggle (&optional arg)
15564 "Toggle checkbox at point, or set tags for current headline."
15565 (interactive "P")
15566 (if (string-match "\\`\\[[ xX-]\\]\\'"
15567 (get-char-property (point) 'org-columns-value))
15568 (org-columns-next-allowed-value)
15569 (org-columns-edit-value "TAGS")))
15570
15571 (defun org-columns-edit-value (&optional key)
15572 "Edit the value of the property at point in column view.
15573 Where possible, use the standard interface for changing this line."
15574 (interactive)
15575 (org-columns-check-computed)
15576 (let* ((external-key key)
15577 (col (current-column))
15578 (key (or key (get-char-property (point) 'org-columns-key)))
15579 (value (get-char-property (point) 'org-columns-value))
15580 (bol (point-at-bol)) (eol (point-at-eol))
15581 (pom (or (get-text-property bol 'org-hd-marker)
15582 (point))) ; keep despite of compiler waring
15583 (line-overlays
15584 (delq nil (mapcar (lambda (x)
15585 (and (eq (overlay-buffer x) (current-buffer))
15586 (>= (overlay-start x) bol)
15587 (<= (overlay-start x) eol)
15588 x))
15589 org-columns-overlays)))
15590 nval eval allowed)
15591 (cond
15592 ((equal key "ITEM")
15593 (setq eval '(org-with-point-at pom
15594 (org-edit-headline))))
15595 ((equal key "TODO")
15596 (setq eval '(org-with-point-at pom
15597 (let ((current-prefix-arg
15598 (if external-key current-prefix-arg '(4))))
15599 (call-interactively 'org-todo)))))
15600 ((equal key "PRIORITY")
15601 (setq eval '(org-with-point-at pom
15602 (call-interactively 'org-priority))))
15603 ((equal key "TAGS")
15604 (setq eval '(org-with-point-at pom
15605 (let ((org-fast-tag-selection-single-key
15606 (if (eq org-fast-tag-selection-single-key 'expert)
15607 t org-fast-tag-selection-single-key)))
15608 (call-interactively 'org-set-tags)))))
15609 ((equal key "DEADLINE")
15610 (setq eval '(org-with-point-at pom
15611 (call-interactively 'org-deadline))))
15612 ((equal key "SCHEDULED")
15613 (setq eval '(org-with-point-at pom
15614 (call-interactively 'org-schedule))))
15615 (t
15616 (setq allowed (org-property-get-allowed-values pom key 'table))
15617 (if allowed
15618 (setq nval (completing-read "Value: " allowed nil t))
15619 (setq nval (read-string "Edit: " value)))
15620 (setq nval (org-trim nval))
15621 (when (not (equal nval value))
15622 (setq eval '(org-entry-put pom key nval)))))
15623 (when eval
15624 (let ((inhibit-read-only t))
15625 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
15626 (unwind-protect
15627 (progn
15628 (setq org-columns-overlays
15629 (org-delete-all line-overlays org-columns-overlays))
15630 (mapc 'org-delete-overlay line-overlays)
15631 (org-columns-eval eval))
15632 (org-columns-display-here))))
15633 (move-to-column col)
15634 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15635 (org-columns-update key))))
15636
15637 (defun org-edit-headline () ; FIXME: this is not columns specific
15638 "Edit the current headline, the part without TODO keyword, TAGS."
15639 (org-back-to-heading)
15640 (when (looking-at org-todo-line-regexp)
15641 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
15642 (txt (match-string 3))
15643 (post "")
15644 txt2)
15645 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
15646 (setq post (match-string 0 txt)
15647 txt (substring txt 0 (match-beginning 0))))
15648 (setq txt2 (read-string "Edit: " txt))
15649 (when (not (equal txt txt2))
15650 (beginning-of-line 1)
15651 (insert pre txt2 post)
15652 (delete-region (point) (point-at-eol))
15653 (org-set-tags nil t)))))
15654
15655 (defun org-columns-edit-allowed ()
15656 "Edit the list of allowed values for the current property."
15657 (interactive)
15658 (let* ((key (get-char-property (point) 'org-columns-key))
15659 (key1 (concat key "_ALL"))
15660 (allowed (org-entry-get (point) key1 t))
15661 nval)
15662 ;; FIXME: Cover editing TODO, TAGS etc inbiffer settings.????
15663 (setq nval (read-string "Allowed: " allowed))
15664 (org-entry-put
15665 (cond ((marker-position org-entry-property-inherited-from)
15666 org-entry-property-inherited-from)
15667 ((marker-position org-columns-top-level-marker)
15668 org-columns-top-level-marker))
15669 key1 nval)))
15670
15671 (defmacro org-no-warnings (&rest body)
15672 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
15673
15674 (defun org-columns-eval (form)
15675 (let (hidep)
15676 (save-excursion
15677 (beginning-of-line 1)
15678 ;; `next-line' is needed here, because it skips invisible line.
15679 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
15680 (setq hidep (org-on-heading-p 1)))
15681 (eval form)
15682 (and hidep (hide-entry))))
15683
15684 (defun org-columns-previous-allowed-value ()
15685 "Switch to the previous allowed value for this column."
15686 (interactive)
15687 (org-columns-next-allowed-value t))
15688
15689 (defun org-columns-next-allowed-value (&optional previous)
15690 "Switch to the next allowed value for this column."
15691 (interactive)
15692 (org-columns-check-computed)
15693 (let* ((col (current-column))
15694 (key (get-char-property (point) 'org-columns-key))
15695 (value (get-char-property (point) 'org-columns-value))
15696 (bol (point-at-bol)) (eol (point-at-eol))
15697 (pom (or (get-text-property bol 'org-hd-marker)
15698 (point))) ; keep despite of compiler waring
15699 (line-overlays
15700 (delq nil (mapcar (lambda (x)
15701 (and (eq (overlay-buffer x) (current-buffer))
15702 (>= (overlay-start x) bol)
15703 (<= (overlay-start x) eol)
15704 x))
15705 org-columns-overlays)))
15706 (allowed (or (org-property-get-allowed-values pom key)
15707 (and (equal
15708 (nth 4 (assoc key org-columns-current-fmt-compiled))
15709 'checkbox) '("[ ]" "[X]"))))
15710 nval)
15711 (when (equal key "ITEM")
15712 (error "Cannot edit item headline from here"))
15713 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
15714 (error "Allowed values for this property have not been defined"))
15715 (if (member key '("SCHEDULED" "DEADLINE"))
15716 (setq nval (if previous 'earlier 'later))
15717 (if previous (setq allowed (reverse allowed)))
15718 (if (member value allowed)
15719 (setq nval (car (cdr (member value allowed)))))
15720 (setq nval (or nval (car allowed)))
15721 (if (equal nval value)
15722 (error "Only one allowed value for this property")))
15723 (let ((inhibit-read-only t))
15724 (remove-text-properties (1- bol) eol '(read-only t))
15725 (unwind-protect
15726 (progn
15727 (setq org-columns-overlays
15728 (org-delete-all line-overlays org-columns-overlays))
15729 (mapc 'org-delete-overlay line-overlays)
15730 (org-columns-eval '(org-entry-put pom key nval)))
15731 (org-columns-display-here)))
15732 (move-to-column col)
15733 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15734 (org-columns-update key))))
15735
15736 (defun org-verify-version (task)
15737 (cond
15738 ((eq task 'columns)
15739 (if (or (featurep 'xemacs)
15740 (< emacs-major-version 22))
15741 (error "Emacs 22 is required for the columns feature")))))
15742
15743 (defun org-columns-open-link (&optional arg)
15744 (interactive "P")
15745 (let ((key (get-char-property (point) 'org-columns-key))
15746 (value (get-char-property (point) 'org-columns-value)))
15747 (org-open-link-from-string arg)))
15748
15749 (defun org-open-link-from-string (s &optional arg)
15750 "Open a link in the string S, as if it was in Org-mode."
15751 (interactive)
15752 (with-temp-buffer
15753 (let ((org-inhibit-startup t))
15754 (org-mode)
15755 (insert s)
15756 (goto-char (point-min))
15757 (org-open-at-point arg))))
15758
15759 (defun org-columns-get-format-and-top-level ()
15760 (let (fmt)
15761 (when (condition-case nil (org-back-to-heading) (error nil))
15762 (move-marker org-entry-property-inherited-from nil)
15763 (setq fmt (org-entry-get nil "COLUMNS" t)))
15764 (setq fmt (or fmt org-columns-default-format))
15765 (org-set-local 'org-columns-current-fmt fmt)
15766 (org-columns-compile-format fmt)
15767 (if (marker-position org-entry-property-inherited-from)
15768 (move-marker org-columns-top-level-marker
15769 org-entry-property-inherited-from)
15770 (move-marker org-columns-top-level-marker (point)))
15771 fmt))
15772
15773 (defun org-columns ()
15774 "Turn on column view on an org-mode file."
15775 (interactive)
15776 (org-verify-version 'columns)
15777 (org-columns-remove-overlays)
15778 (move-marker org-columns-begin-marker (point))
15779 (let (beg end fmt cache maxwidths)
15780 (setq fmt (org-columns-get-format-and-top-level))
15781 (save-excursion
15782 (goto-char org-columns-top-level-marker)
15783 (setq beg (point))
15784 (unless org-columns-inhibit-recalculation
15785 (org-columns-compute-all))
15786 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
15787 (point-max)))
15788 (goto-char beg)
15789 ;; Get and cache the properties
15790 (while (re-search-forward (concat "^" outline-regexp) end t)
15791 (push (cons (org-current-line) (org-entry-properties)) cache))
15792 (when cache
15793 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
15794 (org-set-local 'org-columns-current-maxwidths maxwidths)
15795 (org-columns-display-here-title)
15796 (mapc (lambda (x)
15797 (goto-line (car x))
15798 (org-columns-display-here (cdr x)))
15799 cache)))))
15800
15801 (defun org-columns-new (&optional prop title width op fmt)
15802 "Insert a new column, to the leeft o the current column."
15803 (interactive)
15804 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
15805 cell)
15806 (setq prop (completing-read
15807 "Property: " (mapcar 'list (org-buffer-property-keys t))
15808 nil nil prop))
15809 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
15810 (setq width (read-string "Column width: " (if width (number-to-string width))))
15811 (if (string-match "\\S-" width)
15812 (setq width (string-to-number width))
15813 (setq width nil))
15814 (setq fmt (completing-read "Summary [none]: "
15815 '(("none") ("add_numbers") ("add_times") ("checkbox"))
15816 nil t))
15817 (if (string-match "\\S-" fmt)
15818 (setq fmt (intern fmt))
15819 (setq fmt nil))
15820 (if (eq fmt 'none) (setq fmt nil))
15821 (if editp
15822 (progn
15823 (setcar editp prop)
15824 (setcdr editp (list title width nil fmt)))
15825 (setq cell (nthcdr (1- (current-column))
15826 org-columns-current-fmt-compiled))
15827 (setcdr cell (cons (list prop title width nil fmt)
15828 (cdr cell))))
15829 (org-columns-store-format)
15830 (org-columns-redo)))
15831
15832 (defun org-columns-delete ()
15833 "Delete the column at point from columns view."
15834 (interactive)
15835 (let* ((n (current-column))
15836 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
15837 (when (y-or-n-p
15838 (format "Are you sure you want to remove column \"%s\"? " title))
15839 (setq org-columns-current-fmt-compiled
15840 (delq (nth n org-columns-current-fmt-compiled)
15841 org-columns-current-fmt-compiled))
15842 (org-columns-store-format)
15843 (org-columns-redo)
15844 (if (>= (current-column) (length org-columns-current-fmt-compiled))
15845 (backward-char 1)))))
15846
15847 (defun org-columns-edit-attributes ()
15848 "Edit the attributes of the current column."
15849 (interactive)
15850 (let* ((n (current-column))
15851 (info (nth n org-columns-current-fmt-compiled)))
15852 (apply 'org-columns-new info)))
15853
15854 (defun org-columns-widen (arg)
15855 "Make the column wider by ARG characters."
15856 (interactive "p")
15857 (let* ((n (current-column))
15858 (entry (nth n org-columns-current-fmt-compiled))
15859 (width (or (nth 2 entry)
15860 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
15861 (setq width (max 1 (+ width arg)))
15862 (setcar (nthcdr 2 entry) width)
15863 (org-columns-store-format)
15864 (org-columns-redo)))
15865
15866 (defun org-columns-narrow (arg)
15867 "Make the column nrrower by ARG characters."
15868 (interactive "p")
15869 (org-columns-widen (- arg)))
15870
15871 (defun org-columns-move-right ()
15872 "Swap this column with the one to the right."
15873 (interactive)
15874 (let* ((n (current-column))
15875 (cell (nthcdr n org-columns-current-fmt-compiled))
15876 e)
15877 (when (>= n (1- (length org-columns-current-fmt-compiled)))
15878 (error "Cannot shift this column further to the right"))
15879 (setq e (car cell))
15880 (setcar cell (car (cdr cell)))
15881 (setcdr cell (cons e (cdr (cdr cell))))
15882 (org-columns-store-format)
15883 (org-columns-redo)
15884 (forward-char 1)))
15885
15886 (defun org-columns-move-left ()
15887 "Swap this column with the one to the left."
15888 (interactive)
15889 (let* ((n (current-column)))
15890 (when (= n 0)
15891 (error "Cannot shift this column further to the left"))
15892 (backward-char 1)
15893 (org-columns-move-right)
15894 (backward-char 1)))
15895
15896 (defun org-columns-store-format ()
15897 "Store the text version of the current columns format in appropriate place.
15898 This is either in the COLUMNS property of the node starting the current column
15899 display, or in the #+COLUMNS line of the current buffer."
15900 (let (fmt (cnt 0))
15901 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
15902 (org-set-local 'org-columns-current-fmt fmt)
15903 (if (marker-position org-columns-top-level-marker)
15904 (save-excursion
15905 (goto-char org-columns-top-level-marker)
15906 (if (and (org-at-heading-p)
15907 (org-entry-get nil "COLUMNS"))
15908 (org-entry-put nil "COLUMNS" fmt)
15909 (goto-char (point-min))
15910 ;; Overwrite all #+COLUMNS lines....
15911 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
15912 (setq cnt (1+ cnt))
15913 (replace-match (concat "#+COLUMNS: " fmt) t t))
15914 (unless (> cnt 0)
15915 (goto-char (point-min))
15916 (or (org-on-heading-p t) (outline-next-heading))
15917 (let ((inhibit-read-only t))
15918 (insert-before-markers "#+COLUMNS: " fmt "\n")))
15919 (org-set-local 'org-columns-default-format fmt))))))
15920
15921 (defvar org-overriding-columns-format nil
15922 "When set, overrides any other definition.")
15923 (defvar org-agenda-view-columns-initially nil
15924 "When set, switch to columns view immediately after creating the agenda.")
15925
15926 (defun org-agenda-columns ()
15927 "Turn on column view in the agenda."
15928 (interactive)
15929 (org-verify-version 'columns)
15930 (org-columns-remove-overlays)
15931 (move-marker org-columns-begin-marker (point))
15932 (let (fmt cache maxwidths m)
15933 (cond
15934 ((and (local-variable-p 'org-overriding-columns-format)
15935 org-overriding-columns-format)
15936 (setq fmt org-overriding-columns-format))
15937 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
15938 (setq fmt (org-entry-get m "COLUMNS" t)))
15939 ((and (boundp 'org-columns-current-fmt)
15940 (local-variable-p 'org-columns-current-fmt)
15941 org-columns-current-fmt)
15942 (setq fmt org-columns-current-fmt))
15943 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
15944 (setq m (get-text-property m 'org-hd-marker))
15945 (setq fmt (org-entry-get m "COLUMNS" t))))
15946 (setq fmt (or fmt org-columns-default-format))
15947 (org-set-local 'org-columns-current-fmt fmt)
15948 (org-columns-compile-format fmt)
15949 (save-excursion
15950 ;; Get and cache the properties
15951 (goto-char (point-min))
15952 (while (not (eobp))
15953 (when (setq m (or (get-text-property (point) 'org-hd-marker)
15954 (get-text-property (point) 'org-marker)))
15955 (push (cons (org-current-line) (org-entry-properties m)) cache))
15956 (beginning-of-line 2))
15957 (when cache
15958 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
15959 (org-set-local 'org-columns-current-maxwidths maxwidths)
15960 (org-columns-display-here-title)
15961 (mapc (lambda (x)
15962 (goto-line (car x))
15963 (org-columns-display-here (cdr x)))
15964 cache)))))
15965
15966 (defun org-columns-get-autowidth-alist (s cache)
15967 "Derive the maximum column widths from the format and the cache."
15968 (let ((start 0) rtn)
15969 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
15970 (push (cons (match-string 1 s) 1) rtn)
15971 (setq start (match-end 0)))
15972 (mapc (lambda (x)
15973 (setcdr x (apply 'max
15974 (mapcar
15975 (lambda (y)
15976 (length (or (cdr (assoc (car x) (cdr y))) " ")))
15977 cache))))
15978 rtn)
15979 rtn))
15980
15981 (defun org-columns-compute-all ()
15982 "Compute all columns that have operators defined."
15983 (org-unmodified
15984 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
15985 (let ((columns org-columns-current-fmt-compiled) col)
15986 (while (setq col (pop columns))
15987 (when (nth 3 col)
15988 (save-excursion
15989 (org-columns-compute (car col)))))))
15990
15991 (defun org-columns-update (property)
15992 "Recompute PROPERTY, and update the columns display for it."
15993 (org-columns-compute property)
15994 (let (fmt val pos)
15995 (save-excursion
15996 (mapc (lambda (ov)
15997 (when (equal (org-overlay-get ov 'org-columns-key) property)
15998 (setq pos (org-overlay-start ov))
15999 (goto-char pos)
16000 (when (setq val (cdr (assoc property
16001 (get-text-property
16002 (point-at-bol) 'org-summaries))))
16003 (setq fmt (org-overlay-get ov 'org-columns-format))
16004 (org-overlay-put ov 'org-columns-value val)
16005 (org-overlay-put ov 'display (format fmt val)))))
16006 org-columns-overlays))))
16007
16008 (defun org-columns-compute (property)
16009 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
16010 (interactive)
16011 (let* ((re (concat "^" outline-regexp))
16012 (lmax 30) ; Does anyone use deeper levels???
16013 (lsum (make-vector lmax 0))
16014 (lflag (make-vector lmax nil))
16015 (level 0)
16016 (ass (assoc property org-columns-current-fmt-compiled))
16017 (format (nth 4 ass))
16018 (beg org-columns-top-level-marker)
16019 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
16020 (save-excursion
16021 ;; Find the region to compute
16022 (goto-char beg)
16023 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
16024 (goto-char end)
16025 ;; Walk the tree from the back and do the computations
16026 (while (re-search-backward re beg t)
16027 (setq sumpos (match-beginning 0)
16028 last-level level
16029 level (org-outline-level)
16030 val (org-entry-get nil property)
16031 valflag (and val (string-match "\\S-" val)))
16032 (cond
16033 ((< level last-level)
16034 ;; put the sum of lower levels here as a property
16035 (setq sum (aref lsum last-level) ; current sum
16036 flag (aref lflag last-level) ; any valid entries from children?
16037 str (org-column-number-to-string sum format)
16038 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
16039 useval (if flag str1 (if valflag val ""))
16040 sum-alist (get-text-property sumpos 'org-summaries))
16041 (if (assoc property sum-alist)
16042 (setcdr (assoc property sum-alist) useval)
16043 (push (cons property useval) sum-alist)
16044 (org-unmodified
16045 (add-text-properties sumpos (1+ sumpos)
16046 (list 'org-summaries sum-alist))))
16047 (when val
16048 (org-entry-put nil property (if flag str val)))
16049 ;; add current to current level accumulator
16050 (when (or flag valflag)
16051 ;; FIXME: is this ok?????????
16052 (aset lsum level (+ (aref lsum level)
16053 (if flag sum (org-column-string-to-number
16054 (if flag str val) format))))
16055 (aset lflag level t))
16056 ;; clear accumulators for deeper levels
16057 (loop for l from (1+ level) to (1- lmax) do
16058 (aset lsum l 0)
16059 (aset lflag l nil)))
16060 ((>= level last-level)
16061 ;; add what we have here to the accumulator for this level
16062 (aset lsum level (+ (aref lsum level)
16063 (org-column-string-to-number (or val "0") format)))
16064 (and valflag (aset lflag level t)))
16065 (t (error "This should not happen")))))))
16066
16067 (defun org-columns-redo ()
16068 "Construct the column display again."
16069 (interactive)
16070 (message "Recomputing columns...")
16071 (save-excursion
16072 (if (marker-position org-columns-begin-marker)
16073 (goto-char org-columns-begin-marker))
16074 (org-columns-remove-overlays)
16075 (if (org-mode-p)
16076 (call-interactively 'org-columns)
16077 (call-interactively 'org-agenda-columns)))
16078 (message "Recomputing columns...done"))
16079
16080 (defun org-columns-not-in-agenda ()
16081 (if (eq major-mode 'org-agenda-mode)
16082 (error "This command is only allowed in Org-mode buffers")))
16083
16084
16085 (defun org-string-to-number (s)
16086 "Convert string to number, and interpret hh:mm:ss."
16087 (if (not (string-match ":" s))
16088 (string-to-number s)
16089 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16090 (while l
16091 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16092 sum)))
16093
16094 (defun org-column-number-to-string (n fmt)
16095 "Convert a computed column number to a string value, according to FMT."
16096 (cond
16097 ((eq fmt 'add_times)
16098 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
16099 (format "%d:%02d" h m)))
16100 ((eq fmt 'checkbox)
16101 (cond ((= n (floor n)) "[X]")
16102 ((> n 1.) "[-]")
16103 (t "[ ]")))
16104 (t (number-to-string n))))
16105
16106 (defun org-column-string-to-number (s fmt)
16107 "Convert a column value to a number that can be used for column computing."
16108 (cond
16109 ((string-match ":" s)
16110 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16111 (while l
16112 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16113 sum))
16114 ((eq fmt 'checkbox)
16115 (if (equal s "[X]") 1. 0.000001))
16116 (t (string-to-number s))))
16117
16118 (defun org-columns-uncompile-format (cfmt)
16119 "Turn the compiled columns format back into a string representation."
16120 (let ((rtn "") e s prop title op width fmt)
16121 (while (setq e (pop cfmt))
16122 (setq prop (car e)
16123 title (nth 1 e)
16124 width (nth 2 e)
16125 op (nth 3 e)
16126 fmt (nth 4 e))
16127 (cond
16128 ((eq fmt 'add_times) (setq op ":"))
16129 ((eq fmt 'checkbox) (setq op "X"))
16130 ((eq fmt 'add_numbers) (setq op "+")))
16131 (if (equal title prop) (setq title nil))
16132 (setq s (concat "%" (if width (number-to-string width))
16133 prop
16134 (if title (concat "(" title ")"))
16135 (if op (concat "{" op "}"))))
16136 (setq rtn (concat rtn " " s)))
16137 (org-trim rtn)))
16138
16139 (defun org-columns-compile-format (fmt)
16140 "Turn a column format string into an alist of specifications.
16141 The alist has one entry for each column in the format. The elements of
16142 that list are:
16143 property the property
16144 title the title field for the columns
16145 width the column width in characters, can be nil for automatic
16146 operator the operator if any
16147 format the output format for computed results, derived from operator"
16148 (let ((start 0) width prop title op f)
16149 (setq org-columns-current-fmt-compiled nil)
16150 (while (string-match
16151 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
16152 fmt start)
16153 (setq start (match-end 0)
16154 width (match-string 1 fmt)
16155 prop (match-string 2 fmt)
16156 title (or (match-string 3 fmt) prop)
16157 op (match-string 4 fmt)
16158 f nil)
16159 (if width (setq width (string-to-number width)))
16160 (cond
16161 ((equal op "+") (setq f 'add_numbers))
16162 ((equal op ":") (setq f 'add_times))
16163 ((equal op "X") (setq f 'checkbox)))
16164 (push (list prop title width op f) org-columns-current-fmt-compiled))
16165 (setq org-columns-current-fmt-compiled
16166 (nreverse org-columns-current-fmt-compiled))))
16167
16168
16169 ;;; Dynamic block for Column view
16170
16171 (defun org-columns-capture-view ()
16172 "Get the column view of the current buffer and return it as a list.
16173 The list will contains the title row and all other rows. Each row is
16174 a list of fields."
16175 (save-excursion
16176 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
16177 (n (length title)) row tbl)
16178 (goto-char (point-min))
16179 (while (re-search-forward "^\\*+ " nil t)
16180 (when (get-char-property (match-beginning 0) 'org-columns-key)
16181 (setq row nil)
16182 (loop for i from 0 to (1- n) do
16183 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
16184 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
16185 "")
16186 row))
16187 (setq row (nreverse row))
16188 (push row tbl)))
16189 (append (list title 'hline) (nreverse tbl)))))
16190
16191 (defun org-dblock-write:columnview (params)
16192 "Write the column view table.
16193 PARAMS is a property list of parameters:
16194
16195 :width enforce same column widths with <N> specifiers.
16196 :id the :ID: property of the entry where the columns view
16197 should be built, as a string. When `local', call locally.
16198 When `global' call column view with the cursor at the beginning
16199 of the buffer (usually this means that the whole buffer switches
16200 to column view).
16201 :hlines When t, insert a hline before each item. When a number, insert
16202 a hline before each level <= that number.
16203 :vlines When t, make each column a colgroup to enforce vertical lines."
16204 (let ((pos (move-marker (make-marker) (point)))
16205 (hlines (plist-get params :hlines))
16206 (vlines (plist-get params :vlines))
16207 tbl id idpos nfields tmp)
16208 (save-excursion
16209 (save-restriction
16210 (when (setq id (plist-get params :id))
16211 (cond ((not id) nil)
16212 ((eq id 'global) (goto-char (point-min)))
16213 ((eq id 'local) nil)
16214 ((setq idpos (org-find-entry-with-id id))
16215 (goto-char idpos))
16216 (t (error "Cannot find entry with :ID: %s" id))))
16217 (org-columns)
16218 (setq tbl (org-columns-capture-view))
16219 (setq nfields (length (car tbl)))
16220 (org-columns-quit)))
16221 (goto-char pos)
16222 (move-marker pos nil)
16223 (when tbl
16224 (when (plist-get params :hlines)
16225 (setq tmp nil)
16226 (while tbl
16227 (if (eq (car tbl) 'hline)
16228 (push (pop tbl) tmp)
16229 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
16230 (if (and (not (eq (car tmp) 'hline))
16231 (or (eq hlines t)
16232 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
16233 (push 'hline tmp)))
16234 (push (pop tbl) tmp)))
16235 (setq tbl (nreverse tmp)))
16236 (when vlines
16237 (setq tbl (mapcar (lambda (x)
16238 (if (eq 'hline x) x (cons "" x)))
16239 tbl))
16240 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
16241 (setq pos (point))
16242 (insert (org-listtable-to-string tbl))
16243 (when (plist-get params :width)
16244 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
16245 org-columns-current-widths "|")))
16246 (goto-char pos)
16247 (org-table-align))))
16248
16249 (defun org-listtable-to-string (tbl)
16250 "Convert a listtable TBL to a string that contains the Org-mode table.
16251 The table still need to be alligned. The resulting string has no leading
16252 and tailing newline characters."
16253 (mapconcat
16254 (lambda (x)
16255 (cond
16256 ((listp x)
16257 (concat "|" (mapconcat 'identity x "|") "|"))
16258 ((eq x 'hline) "|-|")
16259 (t (error "Garbage in listtable: %s" x))))
16260 tbl "\n"))
16261
16262 (defun org-insert-columns-dblock ()
16263 "Create a dynamic block capturing a column view table."
16264 (interactive)
16265 (let ((defaults '(:name "columnview" :hlines 1))
16266 (id (completing-read
16267 "Capture columns (local, global, entry with :ID: property) [local]: "
16268 (append '(("global") ("local"))
16269 (mapcar 'list (org-property-values "ID"))))))
16270 (if (equal id "") (setq id 'local))
16271 (if (equal id "global") (setq id 'global))
16272 (setq defaults (append defaults (list :id id)))
16273 (org-create-dblock defaults)
16274 (org-update-dblock)))
16275
16276 ;;;; Timestamps
16277
16278 (defvar org-last-changed-timestamp nil)
16279 (defvar org-time-was-given) ; dynamically scoped parameter
16280 (defvar org-end-time-was-given) ; dynamically scoped parameter
16281 (defvar org-ts-what) ; dynamically scoped parameter
16282
16283 (defun org-time-stamp (arg)
16284 "Prompt for a date/time and insert a time stamp.
16285 If the user specifies a time like HH:MM, or if this command is called
16286 with a prefix argument, the time stamp will contain date and time.
16287 Otherwise, only the date will be included. All parts of a date not
16288 specified by the user will be filled in from the current date/time.
16289 So if you press just return without typing anything, the time stamp
16290 will represent the current date/time. If there is already a timestamp
16291 at the cursor, it will be modified."
16292 (interactive "P")
16293 (let ((default-time
16294 ;; Default time is either today, or, when entering a range,
16295 ;; the range start.
16296 (if (or (org-at-timestamp-p t)
16297 (save-excursion
16298 (re-search-backward
16299 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16300 (- (point) 20) t)))
16301 (apply 'encode-time (org-parse-time-string (match-string 1)))
16302 (current-time)))
16303 org-time-was-given org-end-time-was-given time)
16304 (cond
16305 ((and (org-at-timestamp-p)
16306 (eq last-command 'org-time-stamp)
16307 (eq this-command 'org-time-stamp))
16308 (insert "--")
16309 (setq time (let ((this-command this-command))
16310 (org-read-date arg 'totime nil nil default-time)))
16311 (org-insert-time-stamp time (or org-time-was-given arg)))
16312 ((org-at-timestamp-p)
16313 (setq time (let ((this-command this-command))
16314 (org-read-date arg 'totime nil nil default-time)))
16315 (when (org-at-timestamp-p) ; just to get the match data
16316 (replace-match "")
16317 (setq org-last-changed-timestamp
16318 (org-insert-time-stamp
16319 time (or org-time-was-given arg)
16320 nil nil nil (list org-end-time-was-given))))
16321 (message "Timestamp updated"))
16322 (t
16323 (setq time (let ((this-command this-command))
16324 (org-read-date arg 'totime nil nil default-time)))
16325 (org-insert-time-stamp time (or org-time-was-given arg)
16326 nil nil nil (list org-end-time-was-given))))))
16327
16328 (defun org-time-stamp-inactive (&optional arg)
16329 "Insert an inactive time stamp.
16330 An inactive time stamp is enclosed in square brackets instead of angle
16331 brackets. It is inactive in the sense that it does not trigger agenda entries,
16332 does not link to the calendar and cannot be changed with the S-cursor keys.
16333 So these are more for recording a certain time/date."
16334 (interactive "P")
16335 (let (org-time-was-given org-end-time-was-given time)
16336 (setq time (org-read-date arg 'totime))
16337 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
16338 nil nil (list org-end-time-was-given))))
16339
16340 (defvar org-date-ovl (org-make-overlay 1 1))
16341 (org-overlay-put org-date-ovl 'face 'org-warning)
16342 (org-detach-overlay org-date-ovl)
16343
16344 (defvar org-ans1) ; dynamically scoped parameter
16345 (defvar org-ans2) ; dynamically scoped parameter
16346
16347 (defvar org-plain-time-of-day-regexp) ; defined below
16348 (defun org-read-date (&optional with-time to-time from-string prompt
16349 default-time)
16350 "Read a date and make things smooth for the user.
16351 The prompt will suggest to enter an ISO date, but you can also enter anything
16352 which will at least partially be understood by `parse-time-string'.
16353 Unrecognized parts of the date will default to the current day, month, year,
16354 hour and minute. If this command is called to replace a timestamp at point,
16355 of to enter the second timestamp of a range, the default time is taken from the
16356 existing stamp. For example,
16357 3-2-5 --> 2003-02-05
16358 feb 15 --> currentyear-02-15
16359 sep 12 9 --> 2009-09-12
16360 12:45 --> today 12:45
16361 22 sept 0:34 --> currentyear-09-22 0:34
16362 12 --> currentyear-currentmonth-12
16363 Fri --> nearest Friday (today or later)
16364 etc.
16365
16366 Furthermore you can specify a relative date by giving, as the *first* thing
16367 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
16368 change in days weeks, months, years.
16369 With a single plus or minus, the date is relative to today. With a double
16370 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16371 +4d --> four days from today
16372 +4 --> same as above
16373 +2w --> two weeks from today
16374 ++5 --> five days from default date
16375
16376 The function understands only English month and weekday abbreviations,
16377 but this can be configured with the variables `parse-time-months' and
16378 `parse-time-weekdays'.
16379
16380 While prompting, a calendar is popped up - you can also select the
16381 date with the mouse (button 1). The calendar shows a period of three
16382 months. To scroll it to other months, use the keys `>' and `<'.
16383 If you don't like the calendar, turn it off with
16384 \(setq org-popup-calendar-for-date-prompt nil)
16385
16386 With optional argument TO-TIME, the date will immediately be converted
16387 to an internal time.
16388 With an optional argument WITH-TIME, the prompt will suggest to also
16389 insert a time. Note that when WITH-TIME is not set, you can still
16390 enter a time, and this function will inform the calling routine about
16391 this change. The calling routine may then choose to change the format
16392 used to insert the time stamp into the buffer to include the time.
16393 With optional argument FROM-STRING, read fomr this string instead from
16394 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16395 the time/date that is used for everything that is not specified by the
16396 user."
16397 (require 'parse-time)
16398 (let* ((org-time-stamp-rounding-minutes
16399 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
16400 (ct (org-current-time))
16401 (def (or default-time ct))
16402 ; (defdecode (decode-time def))
16403 (calendar-move-hook nil)
16404 (view-diary-entries-initially nil)
16405 (view-calendar-holidays-initially nil)
16406 (timestr (format-time-string
16407 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
16408 (prompt (concat (if prompt (concat prompt " ") "")
16409 (format "Date and/or time (default [%s]): " timestr)))
16410 ans (org-ans0 "") org-ans1 org-ans2 delta deltan deltaw deltadef
16411 second minute hour day month year tl wday wday1 pm h2 m2)
16412
16413 (cond
16414 (from-string (setq ans from-string))
16415 (org-popup-calendar-for-date-prompt
16416 (save-excursion
16417 (save-window-excursion
16418 (calendar)
16419 (calendar-forward-day (- (time-to-days def)
16420 (calendar-absolute-from-gregorian
16421 (calendar-current-date))))
16422 (org-eval-in-calendar nil t)
16423 (let* ((old-map (current-local-map))
16424 (map (copy-keymap calendar-mode-map))
16425 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
16426 (org-defkey map (kbd "RET") 'org-calendar-select)
16427 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
16428 'org-calendar-select-mouse)
16429 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
16430 'org-calendar-select-mouse)
16431 (org-defkey minibuffer-local-map [(meta shift left)]
16432 (lambda () (interactive)
16433 (org-eval-in-calendar '(calendar-backward-month 1))))
16434 (org-defkey minibuffer-local-map [(meta shift right)]
16435 (lambda () (interactive)
16436 (org-eval-in-calendar '(calendar-forward-month 1))))
16437 (org-defkey minibuffer-local-map [(shift up)]
16438 (lambda () (interactive)
16439 (org-eval-in-calendar '(calendar-backward-week 1))))
16440 (org-defkey minibuffer-local-map [(shift down)]
16441 (lambda () (interactive)
16442 (org-eval-in-calendar '(calendar-forward-week 1))))
16443 (org-defkey minibuffer-local-map [(shift left)]
16444 (lambda () (interactive)
16445 (org-eval-in-calendar '(calendar-backward-day 1))))
16446 (org-defkey minibuffer-local-map [(shift right)]
16447 (lambda () (interactive)
16448 (org-eval-in-calendar '(calendar-forward-day 1))))
16449 (org-defkey minibuffer-local-map ">"
16450 (lambda () (interactive)
16451 (org-eval-in-calendar '(scroll-calendar-left 1))))
16452 (org-defkey minibuffer-local-map "<"
16453 (lambda () (interactive)
16454 (org-eval-in-calendar '(scroll-calendar-right 1))))
16455 (unwind-protect
16456 (progn
16457 (use-local-map map)
16458 (setq org-ans0 (read-string prompt "" nil nil))
16459 ;; org-ans0: from prompt
16460 ;; org-ans1: from mouse click
16461 ;; org-ans2: from calendar motion
16462 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16463 (use-local-map old-map))))))
16464 (t ; Naked prompt only
16465 (setq ans (read-string prompt "" nil timestr))))
16466 (org-detach-overlay org-date-ovl)
16467
16468 (when (setq delta (org-read-date-get-relative ans (current-time) def))
16469 (setq ans (replace-match "" t t ans)
16470 deltan (car delta)
16471 deltaw (nth 1 delta)
16472 deltadef (nth 2 delta)))
16473
16474 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
16475 (when (string-match
16476 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16477 (setq year (if (match-end 2)
16478 (string-to-number (match-string 2 ans))
16479 (string-to-number (format-time-string "%Y")))
16480 month (string-to-number (match-string 3 ans))
16481 day (string-to-number (match-string 4 ans)))
16482 (if (< year 100) (setq year (+ 2000 year)))
16483 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16484 t nil ans)))
16485 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16486 ;; If there is a time with am/pm, and *no* time without it, we convert
16487 ;; so that matching will be successful.
16488 (loop for i from 1 to 2 do ; twice, for end time as well
16489 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16490 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16491 (setq hour (string-to-number (match-string 1 ans))
16492 minute (if (match-end 3)
16493 (string-to-number (match-string 3 ans))
16494 0)
16495 pm (equal ?p
16496 (string-to-char (downcase (match-string 4 ans)))))
16497 (if (and (= hour 12) (not pm))
16498 (setq hour 0)
16499 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16500 (setq ans (replace-match (format "%02d:%02d" hour minute)
16501 t t ans))))
16502
16503 ;; Check if a time range is given as a duration
16504 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16505 (setq hour (string-to-number (match-string 1 ans))
16506 h2 (+ hour (string-to-number (match-string 3 ans)))
16507 minute (string-to-number (match-string 2 ans))
16508 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
16509 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
16510
16511 ;; Check if there is a time range
16512 (when (and (boundp 'org-end-time-was-given)
16513 (string-match org-plain-time-of-day-regexp ans)
16514 (match-end 8))
16515 (setq org-end-time-was-given (match-string 8 ans))
16516 (setq ans (concat (substring ans 0 (match-beginning 7))
16517 (substring ans (match-end 7)))))
16518
16519 (setq tl (parse-time-string ans)
16520 day (or (nth 3 tl) (string-to-number (format-time-string "%d" def)))
16521 month (or (nth 4 tl) (string-to-number (format-time-string "%m" def)))
16522 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" def)))
16523 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" def)))
16524 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" def)))
16525 second (or (nth 0 tl) 0)
16526 wday (nth 6 tl))
16527 (when deltan
16528 (unless deltadef
16529 (let ((now (decode-time (current-time))))
16530 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16531 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16532 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16533 ((equal deltaw "m") (setq month (+ month deltan)))
16534 ((equal deltaw "y") (setq year (+ year deltan)))))
16535 (when (and wday (not (nth 3 tl)))
16536 ;; Weekday was given, but no day, so pick that day in the week
16537 ;; on or after the derived date.
16538 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16539 (unless (equal wday wday1)
16540 (setq day (+ day (% (- wday wday1 -7) 7)))))
16541 (if (and (boundp 'org-time-was-given)
16542 (nth 2 tl))
16543 (setq org-time-was-given t))
16544 (if (< year 100) (setq year (+ 2000 year)))
16545 (if to-time
16546 (encode-time second minute hour day month year)
16547 (if (or (nth 1 tl) (nth 2 tl))
16548 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
16549 (format "%04d-%02d-%02d" year month day)))))
16550
16551 ;(defun org-parse-for-shift (n1 n2 given-dec default-dec)
16552 ; (cond
16553 ; ((not (nth n1 given-dec))
16554 ; (nth n1 default-dec))
16555 ; ((or (> (nth n1 given-dec) (nth n1 (default-dec)))
16556 ; (not org-read-date-prefer-future))
16557 ; (nth n1 given-dec))
16558 ; (t (1+
16559 ; (if (nth 3 given-dec)
16560 ; (nth 3 given-dec)
16561 ; (if (> (nth
16562 ; (setq given
16563 ; (if (and
16564
16565 (defvar parse-time-weekdays)
16566
16567 (defun org-read-date-get-relative (s today default)
16568 "Check string S for special relative date string.
16569 TODAY and DEFAULT are internal times, for today and for a default.
16570 Return shift list (N what def-flag)
16571 WHAT is \"d\", \"w\", \"m\", or \"y\" for day. week, month, year.
16572 N is the number if WHATs to shift
16573 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16574 the DEFAULT date rather than TODAY."
16575 (when (string-match
16576 (concat
16577 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
16578 "\\([0-9]+\\)?"
16579 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16580 "\\([ \t]\\|$\\)") s)
16581 (let* ((dir (if (match-end 1)
16582 (string-to-char (substring (match-string 1 s) -1))
16583 ?+))
16584 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16585 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16586 (what (if (match-end 3) (match-string 3 s) "d"))
16587 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16588 (date (if rel default today))
16589 (wday (nth 6 (decode-time date)))
16590 delta)
16591 (if wday1
16592 (progn
16593 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16594 (if (= dir ?-) (setq delta (- delta 7)))
16595 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16596 (list delta "d" rel))
16597 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16598
16599 (defun org-eval-in-calendar (form &optional keepdate)
16600 "Eval FORM in the calendar window and return to current window.
16601 Also, store the cursor date in variable org-ans2."
16602 (let ((sw (selected-window)))
16603 (select-window (get-buffer-window "*Calendar*"))
16604 (eval form)
16605 (when (and (not keepdate) (calendar-cursor-to-date))
16606 (let* ((date (calendar-cursor-to-date))
16607 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16608 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16609 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16610 (select-window sw)
16611 ;; Update the prompt to show new default date
16612 (save-excursion
16613 (goto-char (point-min))
16614 (when (and org-ans2
16615 (re-search-forward "\\[[-0-9]+\\]" nil t)
16616 (get-text-property (match-end 0) 'field))
16617 (let ((inhibit-read-only t))
16618 (replace-match (concat "[" org-ans2 "]") t t)
16619 (add-text-properties (point-min) (1+ (match-end 0))
16620 (text-properties-at (1+ (point-min)))))))))
16621
16622 (defun org-calendar-select ()
16623 "Return to `org-read-date' with the date currently selected.
16624 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16625 (interactive)
16626 (when (calendar-cursor-to-date)
16627 (let* ((date (calendar-cursor-to-date))
16628 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16629 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16630 (if (active-minibuffer-window) (exit-minibuffer))))
16631
16632 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16633 "Insert a date stamp for the date given by the internal TIME.
16634 WITH-HM means, use the stamp format that includes the time of the day.
16635 INACTIVE means use square brackets instead of angular ones, so that the
16636 stamp will not contribute to the agenda.
16637 PRE and POST are optional strings to be inserted before and after the
16638 stamp.
16639 The command returns the inserted time stamp."
16640 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16641 stamp)
16642 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16643 (insert-before-markers (or pre ""))
16644 (insert-before-markers (setq stamp (format-time-string fmt time)))
16645 (when (listp extra)
16646 (setq extra (car extra))
16647 (if (and (stringp extra)
16648 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16649 (setq extra (format "-%02d:%02d"
16650 (string-to-number (match-string 1 extra))
16651 (string-to-number (match-string 2 extra))))
16652 (setq extra nil)))
16653 (when extra
16654 (backward-char 1)
16655 (insert-before-markers extra)
16656 (forward-char 1))
16657 (insert-before-markers (or post ""))
16658 stamp))
16659
16660 (defun org-toggle-time-stamp-overlays ()
16661 "Toggle the use of custom time stamp formats."
16662 (interactive)
16663 (setq org-display-custom-times (not org-display-custom-times))
16664 (unless org-display-custom-times
16665 (let ((p (point-min)) (bmp (buffer-modified-p)))
16666 (while (setq p (next-single-property-change p 'display))
16667 (if (and (get-text-property p 'display)
16668 (eq (get-text-property p 'face) 'org-date))
16669 (remove-text-properties
16670 p (setq p (next-single-property-change p 'display))
16671 '(display t))))
16672 (set-buffer-modified-p bmp)))
16673 (if (featurep 'xemacs)
16674 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16675 (org-restart-font-lock)
16676 (setq org-table-may-need-update t)
16677 (if org-display-custom-times
16678 (message "Time stamps are overlayed with custom format")
16679 (message "Time stamp overlays removed")))
16680
16681 (defun org-display-custom-time (beg end)
16682 "Overlay modified time stamp format over timestamp between BED and END."
16683 (let* ((ts (buffer-substring beg end))
16684 t1 w1 with-hm tf time str w2 (off 0))
16685 (save-match-data
16686 (setq t1 (org-parse-time-string ts t))
16687 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
16688 (setq off (- (match-end 0) (match-beginning 0)))))
16689 (setq end (- end off))
16690 (setq w1 (- end beg)
16691 with-hm (and (nth 1 t1) (nth 2 t1))
16692 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16693 time (org-fix-decoded-time t1)
16694 str (org-add-props
16695 (format-time-string
16696 (substring tf 1 -1) (apply 'encode-time time))
16697 nil 'mouse-face 'highlight)
16698 w2 (length str))
16699 (if (not (= w2 w1))
16700 (add-text-properties (1+ beg) (+ 2 beg)
16701 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16702 (if (featurep 'xemacs)
16703 (progn
16704 (put-text-property beg end 'invisible t)
16705 (put-text-property beg end 'end-glyph (make-glyph str)))
16706 (put-text-property beg end 'display str))))
16707
16708 (defun org-translate-time (string)
16709 "Translate all timestamps in STRING to custom format.
16710 But do this only if the variable `org-display-custom-times' is set."
16711 (when org-display-custom-times
16712 (save-match-data
16713 (let* ((start 0)
16714 (re org-ts-regexp-both)
16715 t1 with-hm inactive tf time str beg end)
16716 (while (setq start (string-match re string start))
16717 (setq beg (match-beginning 0)
16718 end (match-end 0)
16719 t1 (save-match-data
16720 (org-parse-time-string (substring string beg end) t))
16721 with-hm (and (nth 1 t1) (nth 2 t1))
16722 inactive (equal (substring string beg (1+ beg)) "[")
16723 tf (funcall (if with-hm 'cdr 'car)
16724 org-time-stamp-custom-formats)
16725 time (org-fix-decoded-time t1)
16726 str (format-time-string
16727 (concat
16728 (if inactive "[" "<") (substring tf 1 -1)
16729 (if inactive "]" ">"))
16730 (apply 'encode-time time))
16731 string (replace-match str t t string)
16732 start (+ start (length str)))))))
16733 string)
16734
16735 (defun org-fix-decoded-time (time)
16736 "Set 0 instead of nil for the first 6 elements of time.
16737 Don't touch the rest."
16738 (let ((n 0))
16739 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16740
16741 (defun org-days-to-time (timestamp-string)
16742 "Difference between TIMESTAMP-STRING and now in days."
16743 (- (time-to-days (org-time-string-to-time timestamp-string))
16744 (time-to-days (current-time))))
16745
16746 (defun org-deadline-close (timestamp-string &optional ndays)
16747 "Is the time in TIMESTAMP-STRING close to the current date?"
16748 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16749 (and (< (org-days-to-time timestamp-string) ndays)
16750 (not (org-entry-is-done-p))))
16751
16752 (defun org-get-wdays (ts)
16753 "Get the deadline lead time appropriate for timestring TS."
16754 (cond
16755 ((<= org-deadline-warning-days 0)
16756 ;; 0 or negative, enforce this value no matter what
16757 (- org-deadline-warning-days))
16758 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
16759 ;; lead time is specified.
16760 (floor (* (string-to-number (match-string 1 ts))
16761 (cdr (assoc (match-string 2 ts)
16762 '(("d" . 1) ("w" . 7)
16763 ("m" . 30.4) ("y" . 365.25)))))))
16764 ;; go for the default.
16765 (t org-deadline-warning-days)))
16766
16767 (defun org-calendar-select-mouse (ev)
16768 "Return to `org-read-date' with the date currently selected.
16769 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16770 (interactive "e")
16771 (mouse-set-point ev)
16772 (when (calendar-cursor-to-date)
16773 (let* ((date (calendar-cursor-to-date))
16774 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16775 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16776 (if (active-minibuffer-window) (exit-minibuffer))))
16777
16778 (defun org-check-deadlines (ndays)
16779 "Check if there are any deadlines due or past due.
16780 A deadline is considered due if it happens within `org-deadline-warning-days'
16781 days from today's date. If the deadline appears in an entry marked DONE,
16782 it is not shown. The prefix arg NDAYS can be used to test that many
16783 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16784 (interactive "P")
16785 (let* ((org-warn-days
16786 (cond
16787 ((equal ndays '(4)) 100000)
16788 (ndays (prefix-numeric-value ndays))
16789 (t (abs org-deadline-warning-days))))
16790 (case-fold-search nil)
16791 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16792 (callback
16793 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16794
16795 (message "%d deadlines past-due or due within %d days"
16796 (org-occur regexp nil callback)
16797 org-warn-days)))
16798
16799 (defun org-evaluate-time-range (&optional to-buffer)
16800 "Evaluate a time range by computing the difference between start and end.
16801 Normally the result is just printed in the echo area, but with prefix arg
16802 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16803 If the time range is actually in a table, the result is inserted into the
16804 next column.
16805 For time difference computation, a year is assumed to be exactly 365
16806 days in order to avoid rounding problems."
16807 (interactive "P")
16808 (or
16809 (org-clock-update-time-maybe)
16810 (save-excursion
16811 (unless (org-at-date-range-p t)
16812 (goto-char (point-at-bol))
16813 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16814 (if (not (org-at-date-range-p t))
16815 (error "Not at a time-stamp range, and none found in current line")))
16816 (let* ((ts1 (match-string 1))
16817 (ts2 (match-string 2))
16818 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16819 (match-end (match-end 0))
16820 (time1 (org-time-string-to-time ts1))
16821 (time2 (org-time-string-to-time ts2))
16822 (t1 (time-to-seconds time1))
16823 (t2 (time-to-seconds time2))
16824 (diff (abs (- t2 t1)))
16825 (negative (< (- t2 t1) 0))
16826 ;; (ys (floor (* 365 24 60 60)))
16827 (ds (* 24 60 60))
16828 (hs (* 60 60))
16829 (fy "%dy %dd %02d:%02d")
16830 (fy1 "%dy %dd")
16831 (fd "%dd %02d:%02d")
16832 (fd1 "%dd")
16833 (fh "%02d:%02d")
16834 y d h m align)
16835 (if havetime
16836 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16837 y 0
16838 d (floor (/ diff ds)) diff (mod diff ds)
16839 h (floor (/ diff hs)) diff (mod diff hs)
16840 m (floor (/ diff 60)))
16841 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16842 y 0
16843 d (floor (+ (/ diff ds) 0.5))
16844 h 0 m 0))
16845 (if (not to-buffer)
16846 (message (org-make-tdiff-string y d h m))
16847 (when (org-at-table-p)
16848 (goto-char match-end)
16849 (setq align t)
16850 (and (looking-at " *|") (goto-char (match-end 0))))
16851 (if (looking-at
16852 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16853 (replace-match ""))
16854 (if negative (insert " -"))
16855 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16856 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16857 (insert " " (format fh h m))))
16858 (if align (org-table-align))
16859 (message "Time difference inserted")))))
16860
16861 (defun org-make-tdiff-string (y d h m)
16862 (let ((fmt "")
16863 (l nil))
16864 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16865 l (push y l)))
16866 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16867 l (push d l)))
16868 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16869 l (push h l)))
16870 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16871 l (push m l)))
16872 (apply 'format fmt (nreverse l))))
16873
16874 (defun org-time-string-to-time (s)
16875 (apply 'encode-time (org-parse-time-string s)))
16876
16877 (defun org-time-string-to-absolute (s &optional daynr)
16878 "Convert a time stamp to an absolute day number.
16879 If there is a specifyer for a cyclic time stamp, get the closest date to
16880 DAYNR."
16881 (cond
16882 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16883 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16884 daynr
16885 (+ daynr 1000)))
16886 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
16887 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16888 (time-to-days (current-time))) (match-string 0 s)))
16889 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
16890
16891 (defun org-time-from-absolute (d)
16892 "Return the time corresponding to date D.
16893 D may be an absolute day number, or a calendar-type list (month day year)."
16894 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16895 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16896
16897 (defun org-calendar-holiday ()
16898 "List of holidays, for Diary display in Org-mode."
16899 (let ((hl (calendar-check-holidays date)))
16900 (if hl (mapconcat 'identity hl "; "))))
16901
16902 (defun org-diary-sexp-entry (sexp entry date)
16903 "Process a SEXP diary ENTRY for DATE."
16904 (require 'diary-lib)
16905 (let ((result (if calendar-debug-sexp
16906 (let ((stack-trace-on-error t))
16907 (eval (car (read-from-string sexp))))
16908 (condition-case nil
16909 (eval (car (read-from-string sexp)))
16910 (error
16911 (beep)
16912 (message "Bad sexp at line %d in %s: %s"
16913 (org-current-line)
16914 (buffer-file-name) sexp)
16915 (sleep-for 2))))))
16916 (cond ((stringp result) result)
16917 ((and (consp result)
16918 (stringp (cdr result))) (cdr result))
16919 (result entry)
16920 (t nil))))
16921
16922 (defun org-diary-to-ical-string (frombuf)
16923 "Get iCalendar entreis from diary entries in buffer FROMBUF.
16924 This uses the icalendar.el library."
16925 (let* ((tmpdir (if (featurep 'xemacs)
16926 (temp-directory)
16927 temporary-file-directory))
16928 (tmpfile (make-temp-name
16929 (expand-file-name "orgics" tmpdir)))
16930 buf rtn b e)
16931 (save-excursion
16932 (set-buffer frombuf)
16933 (icalendar-export-region (point-min) (point-max) tmpfile)
16934 (setq buf (find-buffer-visiting tmpfile))
16935 (set-buffer buf)
16936 (goto-char (point-min))
16937 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16938 (setq b (match-beginning 0)))
16939 (goto-char (point-max))
16940 (if (re-search-backward "^END:VEVENT" nil t)
16941 (setq e (match-end 0)))
16942 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16943 (kill-buffer buf)
16944 (kill-buffer frombuf)
16945 (delete-file tmpfile)
16946 rtn))
16947
16948 (defun org-closest-date (start current change)
16949 "Find the date closest to CURRENT that is consistent with START and CHANGE."
16950 ;; Make the proper lists from the dates
16951 (catch 'exit
16952 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16953 dn dw sday cday n1 n2
16954 d m y y1 y2 date1 date2 nmonths nm ny m2)
16955
16956 (setq start (org-date-to-gregorian start)
16957 current (org-date-to-gregorian
16958 (if org-agenda-repeating-timestamp-show-all
16959 current
16960 (time-to-days (current-time))))
16961 sday (calendar-absolute-from-gregorian start)
16962 cday (calendar-absolute-from-gregorian current))
16963
16964 (if (<= cday sday) (throw 'exit sday))
16965
16966 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
16967 (setq dn (string-to-number (match-string 1 change))
16968 dw (cdr (assoc (match-string 2 change) a1)))
16969 (error "Invalid change specifyer: %s" change))
16970 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16971 (cond
16972 ((eq dw 'day)
16973 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16974 n2 (+ n1 dn)))
16975 ((eq dw 'year)
16976 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16977 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16978 (setq date1 (list m d y1)
16979 n1 (calendar-absolute-from-gregorian date1)
16980 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16981 n2 (calendar-absolute-from-gregorian date2)))
16982 ((eq dw 'month)
16983 ;; approx number of month between the tow dates
16984 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16985 ;; How often does dn fit in there?
16986 (setq d (nth 1 start) m (car start) y (nth 2 start)
16987 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16988 m (+ m nm)
16989 ny (floor (/ m 12))
16990 y (+ y ny)
16991 m (- m (* ny 12)))
16992 (while (> m 12) (setq m (- m 12) y (1+ y)))
16993 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16994 (setq m2 (+ m dn) y2 y)
16995 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16996 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16997 (while (< n2 cday)
16998 (setq n1 n2 m m2 y y2)
16999 (setq m2 (+ m dn) y2 y)
17000 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17001 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17002
17003 (if org-agenda-repeating-timestamp-show-all
17004 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
17005 (if (= cday n1) n1 n2)))))
17006
17007 (defun org-date-to-gregorian (date)
17008 "Turn any specification of DATE into a gregorian date for the calendar."
17009 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17010 ((and (listp date) (= (length date) 3)) date)
17011 ((stringp date)
17012 (setq date (org-parse-time-string date))
17013 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17014 ((listp date)
17015 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17016
17017 (defun org-parse-time-string (s &optional nodefault)
17018 "Parse the standard Org-mode time string.
17019 This should be a lot faster than the normal `parse-time-string'.
17020 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17021 hour and minute fields will be nil if not given."
17022 (if (string-match org-ts-regexp0 s)
17023 (list 0
17024 (if (or (match-beginning 8) (not nodefault))
17025 (string-to-number (or (match-string 8 s) "0")))
17026 (if (or (match-beginning 7) (not nodefault))
17027 (string-to-number (or (match-string 7 s) "0")))
17028 (string-to-number (match-string 4 s))
17029 (string-to-number (match-string 3 s))
17030 (string-to-number (match-string 2 s))
17031 nil nil nil)
17032 (make-list 9 0)))
17033
17034 (defun org-timestamp-up (&optional arg)
17035 "Increase the date item at the cursor by one.
17036 If the cursor is on the year, change the year. If it is on the month or
17037 the day, change that.
17038 With prefix ARG, change by that many units."
17039 (interactive "p")
17040 (org-timestamp-change (prefix-numeric-value arg)))
17041
17042 (defun org-timestamp-down (&optional arg)
17043 "Decrease the date item at the cursor by one.
17044 If the cursor is on the year, change the year. If it is on the month or
17045 the day, change that.
17046 With prefix ARG, change by that many units."
17047 (interactive "p")
17048 (org-timestamp-change (- (prefix-numeric-value arg))))
17049
17050 (defun org-timestamp-up-day (&optional arg)
17051 "Increase the date in the time stamp by one day.
17052 With prefix ARG, change that many days."
17053 (interactive "p")
17054 (if (and (not (org-at-timestamp-p t))
17055 (org-on-heading-p))
17056 (org-todo 'up)
17057 (org-timestamp-change (prefix-numeric-value arg) 'day)))
17058
17059 (defun org-timestamp-down-day (&optional arg)
17060 "Decrease the date in the time stamp by one day.
17061 With prefix ARG, change that many days."
17062 (interactive "p")
17063 (if (and (not (org-at-timestamp-p t))
17064 (org-on-heading-p))
17065 (org-todo 'down)
17066 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
17067
17068 (defsubst org-pos-in-match-range (pos n)
17069 (and (match-beginning n)
17070 (<= (match-beginning n) pos)
17071 (>= (match-end n) pos)))
17072
17073 (defun org-at-timestamp-p (&optional inactive-ok)
17074 "Determine if the cursor is in or at a timestamp."
17075 (interactive)
17076 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17077 (pos (point))
17078 (ans (or (looking-at tsr)
17079 (save-excursion
17080 (skip-chars-backward "^[<\n\r\t")
17081 (if (> (point) (point-min)) (backward-char 1))
17082 (and (looking-at tsr)
17083 (> (- (match-end 0) pos) -1))))))
17084 (and ans
17085 (boundp 'org-ts-what)
17086 (setq org-ts-what
17087 (cond
17088 ((= pos (match-beginning 0)) 'bracket)
17089 ((= pos (1- (match-end 0))) 'bracket)
17090 ((org-pos-in-match-range pos 2) 'year)
17091 ((org-pos-in-match-range pos 3) 'month)
17092 ((org-pos-in-match-range pos 7) 'hour)
17093 ((org-pos-in-match-range pos 8) 'minute)
17094 ((or (org-pos-in-match-range pos 4)
17095 (org-pos-in-match-range pos 5)) 'day)
17096 ((and (> pos (or (match-end 8) (match-end 5)))
17097 (< pos (match-end 0)))
17098 (- pos (or (match-end 8) (match-end 5))))
17099 (t 'day))))
17100 ans))
17101
17102 (defun org-toggle-timestamp-type ()
17103 ""
17104 (interactive)
17105 (when (org-at-timestamp-p t)
17106 (save-excursion
17107 (goto-char (match-beginning 0))
17108 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
17109 (goto-char (1- (match-end 0)))
17110 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
17111 (message "Timestamp is now %sactive"
17112 (if (equal (char-before) ?>) "in" ""))))
17113
17114 (defun org-timestamp-change (n &optional what)
17115 "Change the date in the time stamp at point.
17116 The date will be changed by N times WHAT. WHAT can be `day', `month',
17117 `year', `minute', `second'. If WHAT is not given, the cursor position
17118 in the timestamp determines what will be changed."
17119 (let ((pos (point))
17120 with-hm inactive
17121 org-ts-what
17122 extra
17123 ts time time0)
17124 (if (not (org-at-timestamp-p t))
17125 (error "Not at a timestamp"))
17126 (if (and (not what) (eq org-ts-what 'bracket))
17127 (org-toggle-timestamp-type)
17128 (if (and (not what) (not (eq org-ts-what 'day))
17129 org-display-custom-times
17130 (get-text-property (point) 'display)
17131 (not (get-text-property (1- (point)) 'display)))
17132 (setq org-ts-what 'day))
17133 (setq org-ts-what (or what org-ts-what)
17134 inactive (= (char-after (match-beginning 0)) ?\[)
17135 ts (match-string 0))
17136 (replace-match "")
17137 (if (string-match
17138 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
17139 ts)
17140 (setq extra (match-string 1 ts)))
17141 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17142 (setq with-hm t))
17143 (setq time0 (org-parse-time-string ts))
17144 (setq time
17145 (encode-time (or (car time0) 0)
17146 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17147 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17148 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17149 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17150 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17151 (nthcdr 6 time0)))
17152 (when (integerp org-ts-what)
17153 (setq extra (org-modify-ts-extra extra org-ts-what n)))
17154 (if (eq what 'calendar)
17155 (let ((cal-date (org-get-date-from-calendar)))
17156 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17157 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17158 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17159 (setcar time0 (or (car time0) 0))
17160 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17161 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17162 (setq time (apply 'encode-time time0))))
17163 (setq org-last-changed-timestamp
17164 (org-insert-time-stamp time with-hm inactive nil nil extra))
17165 (org-clock-update-time-maybe)
17166 (goto-char pos)
17167 ;; Try to recenter the calendar window, if any
17168 (if (and org-calendar-follow-timestamp-change
17169 (get-buffer-window "*Calendar*" t)
17170 (memq org-ts-what '(day month year)))
17171 (org-recenter-calendar (time-to-days time))))))
17172
17173 ;; FIXME: does not yet work for lead times
17174 (defun org-modify-ts-extra (s pos n)
17175 "Change the different parts of the lead-time and repeat fields in timestamp."
17176 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17177 ng h m new)
17178 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17179 (cond
17180 ((or (org-pos-in-match-range pos 2)
17181 (org-pos-in-match-range pos 3))
17182 (setq m (string-to-number (match-string 3 s))
17183 h (string-to-number (match-string 2 s)))
17184 (if (org-pos-in-match-range pos 2)
17185 (setq h (+ h n))
17186 (setq m (+ m n)))
17187 (if (< m 0) (setq m (+ m 60) h (1- h)))
17188 (if (> m 59) (setq m (- m 60) h (1+ h)))
17189 (setq h (min 24 (max 0 h)))
17190 (setq ng 1 new (format "-%02d:%02d" h m)))
17191 ((org-pos-in-match-range pos 6)
17192 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17193 ((org-pos-in-match-range pos 5)
17194 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
17195
17196 (when ng
17197 (setq s (concat
17198 (substring s 0 (match-beginning ng))
17199 new
17200 (substring s (match-end ng))))))
17201 s))
17202
17203 (defun org-recenter-calendar (date)
17204 "If the calendar is visible, recenter it to DATE."
17205 (let* ((win (selected-window))
17206 (cwin (get-buffer-window "*Calendar*" t))
17207 (calendar-move-hook nil))
17208 (when cwin
17209 (select-window cwin)
17210 (calendar-goto-date (if (listp date) date
17211 (calendar-gregorian-from-absolute date)))
17212 (select-window win))))
17213
17214 (defun org-goto-calendar (&optional arg)
17215 "Go to the Emacs calendar at the current date.
17216 If there is a time stamp in the current line, go to that date.
17217 A prefix ARG can be used to force the current date."
17218 (interactive "P")
17219 (let ((tsr org-ts-regexp) diff
17220 (calendar-move-hook nil)
17221 (view-calendar-holidays-initially nil)
17222 (view-diary-entries-initially nil))
17223 (if (or (org-at-timestamp-p)
17224 (save-excursion
17225 (beginning-of-line 1)
17226 (looking-at (concat ".*" tsr))))
17227 (let ((d1 (time-to-days (current-time)))
17228 (d2 (time-to-days
17229 (org-time-string-to-time (match-string 1)))))
17230 (setq diff (- d2 d1))))
17231 (calendar)
17232 (calendar-goto-today)
17233 (if (and diff (not arg)) (calendar-forward-day diff))))
17234
17235 (defun org-get-date-from-calendar ()
17236 "Return a list (month day year) of date at point in calendar."
17237 (with-current-buffer "*Calendar*"
17238 (save-match-data
17239 (calendar-cursor-to-date))))
17240
17241 (defun org-date-from-calendar ()
17242 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17243 If there is already a time stamp at the cursor position, update it."
17244 (interactive)
17245 (if (org-at-timestamp-p t)
17246 (org-timestamp-change 0 'calendar)
17247 (let ((cal-date (org-get-date-from-calendar)))
17248 (org-insert-time-stamp
17249 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17250
17251 ;; Make appt aware of appointments from the agenda
17252 ;;;###autoload
17253 (defun org-agenda-to-appt (&optional filter)
17254 "Activate appointments found in `org-agenda-files'.
17255 When prefixed, prompt for a regular expression and use it as a
17256 filter: only add entries if they match this regular expression.
17257
17258 FILTER can be a string. In this case, use this string as a
17259 regular expression to filter results.
17260
17261 FILTER can also be an alist, with the car of each cell being
17262 either 'headline or 'category. For example:
17263
17264 '((headline \"IMPORTANT\")
17265 (category \"Work\"))
17266
17267 will only add headlines containing IMPORTANT or headlines
17268 belonging to the category \"Work\"."
17269 (interactive "P")
17270 (require 'calendar)
17271 (if (equal filter '(4))
17272 (setq filter (read-from-minibuffer "Regexp filter: ")))
17273 (let* ((cnt 0) ; count added events
17274 (today (org-date-to-gregorian
17275 (time-to-days (current-time))))
17276 (files (org-agenda-files)) entries file)
17277 ;; Get all entries which may contain an appt
17278 (while (setq file (pop files))
17279 (setq entries
17280 (append entries
17281 (org-agenda-get-day-entries
17282 file today
17283 :timestamp :scheduled :deadline))))
17284 (setq entries (delq nil entries))
17285 ;; Map thru entries and find if they pass thru the filter
17286 (mapc
17287 (lambda(x)
17288 (let* ((evt (org-trim (get-text-property 1 'txt x)))
17289 (cat (get-text-property 1 'org-category x))
17290 (tod (get-text-property 1 'time-of-day x))
17291 (ok (or (null filter)
17292 (and (stringp filter) (string-match filter evt))
17293 (and (listp filter)
17294 (or (string-match
17295 (cadr (assoc 'category filter)) cat)
17296 (string-match
17297 (cadr (assoc 'headline filter)) evt))))))
17298 ;; FIXME Shall we remove text-properties for the appt text?
17299 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
17300 (when (and ok tod)
17301 (setq tod (number-to-string tod)
17302 tod (when (string-match
17303 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
17304 (concat (match-string 1 tod) ":"
17305 (match-string 2 tod))))
17306 (appt-add tod evt)
17307 (setq cnt (1+ cnt))))) entries)
17308 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
17309
17310 ;;; The clock for measuring work time.
17311
17312 (defvar org-mode-line-string "")
17313 (put 'org-mode-line-string 'risky-local-variable t)
17314
17315 (defvar org-mode-line-timer nil)
17316 (defvar org-clock-heading "")
17317 (defvar org-clock-start-time "")
17318
17319 (defun org-update-mode-line ()
17320 (let* ((delta (- (time-to-seconds (current-time))
17321 (time-to-seconds org-clock-start-time)))
17322 (h (floor delta 3600))
17323 (m (floor (- delta (* 3600 h)) 60)))
17324 (setq org-mode-line-string
17325 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
17326 'help-echo "Org-mode clock is running"))
17327 (force-mode-line-update)))
17328
17329 (defvar org-clock-marker (make-marker)
17330 "Marker recording the last clock-in.")
17331 (defvar org-clock-mode-line-entry nil
17332 "Information for the modeline about the running clock.")
17333
17334 (defun org-clock-in ()
17335 "Start the clock on the current item.
17336 If necessary, clock-out of the currently active clock."
17337 (interactive)
17338 (org-clock-out t)
17339 (let (ts)
17340 (save-excursion
17341 (org-back-to-heading t)
17342 (if (looking-at org-todo-line-regexp)
17343 (setq org-clock-heading (match-string 3))
17344 (setq org-clock-heading "???"))
17345 (setq org-clock-heading (propertize org-clock-heading 'face nil))
17346 (org-clock-find-position)
17347
17348 (insert "\n") (backward-char 1)
17349 (indent-relative)
17350 (insert org-clock-string " ")
17351 (setq org-clock-start-time (current-time))
17352 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
17353 (move-marker org-clock-marker (point) (buffer-base-buffer))
17354 (or global-mode-string (setq global-mode-string '("")))
17355 (or (memq 'org-mode-line-string global-mode-string)
17356 (setq global-mode-string
17357 (append global-mode-string '(org-mode-line-string))))
17358 (org-update-mode-line)
17359 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
17360 (message "Clock started at %s" ts))))
17361
17362 (defun org-clock-find-position ()
17363 "Find the location where the next clock line should be inserted."
17364 (org-back-to-heading t)
17365 (catch 'exit
17366 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
17367 (re (concat "^[ \t]*" org-clock-string))
17368 (cnt 0)
17369 first last)
17370 (goto-char beg)
17371 (when (eobp) (newline) (setq end (max (point) end)))
17372 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
17373 ;; we seem to have a CLOCK drawer, so go there.
17374 (beginning-of-line 2)
17375 (throw 'exit t))
17376 ;; Lets count the CLOCK lines
17377 (goto-char beg)
17378 (while (re-search-forward re end t)
17379 (setq first (or first (match-beginning 0))
17380 last (match-beginning 0)
17381 cnt (1+ cnt)))
17382 (when (and (integerp org-clock-into-drawer)
17383 (>= (1+ cnt) org-clock-into-drawer))
17384 ;; Wrap current entries into a new drawer
17385 (goto-char last)
17386 (beginning-of-line 2)
17387 (if (org-at-item-p) (org-end-of-item))
17388 (insert ":END:\n")
17389 (beginning-of-line 0)
17390 (org-indent-line-function)
17391 (goto-char first)
17392 (insert ":CLOCK:\n")
17393 (beginning-of-line 0)
17394 (org-indent-line-function)
17395 (org-flag-drawer t)
17396 (beginning-of-line 2)
17397 (throw 'exit nil))
17398
17399 (goto-char beg)
17400 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
17401 (not (equal (match-string 1) org-clock-string)))
17402 ;; Planning info, skip to after it
17403 (beginning-of-line 2)
17404 (or (bolp) (newline)))
17405 (when (eq t org-clock-into-drawer)
17406 (insert ":CLOCK:\n:END:\n")
17407 (beginning-of-line -1)
17408 (org-indent-line-function)
17409 (org-flag-drawer t)
17410 (beginning-of-line 2)
17411 (org-indent-line-function)))))
17412
17413 (defun org-clock-out (&optional fail-quietly)
17414 "Stop the currently running clock.
17415 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
17416 (interactive)
17417 (catch 'exit
17418 (if (not (marker-buffer org-clock-marker))
17419 (if fail-quietly (throw 'exit t) (error "No active clock")))
17420 (let (ts te s h m)
17421 (save-excursion
17422 (set-buffer (marker-buffer org-clock-marker))
17423 (goto-char org-clock-marker)
17424 (beginning-of-line 1)
17425 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
17426 (equal (match-string 1) org-clock-string))
17427 (setq ts (match-string 2))
17428 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
17429 (goto-char (match-end 0))
17430 (delete-region (point) (point-at-eol))
17431 (insert "--")
17432 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
17433 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
17434 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
17435 h (floor (/ s 3600))
17436 s (- s (* 3600 h))
17437 m (floor (/ s 60))
17438 s (- s (* 60 s)))
17439 (insert " => " (format "%2d:%02d" h m))
17440 (move-marker org-clock-marker nil)
17441 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
17442 (org-log-done (org-parse-local-options logging 'org-log-done))
17443 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
17444 (org-add-log-maybe 'clock-out))
17445 (when org-mode-line-timer
17446 (cancel-timer org-mode-line-timer)
17447 (setq org-mode-line-timer nil))
17448 (setq global-mode-string
17449 (delq 'org-mode-line-string global-mode-string))
17450 (force-mode-line-update)
17451 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
17452
17453 (defun org-clock-cancel ()
17454 "Cancel the running clock be removing the start timestamp."
17455 (interactive)
17456 (if (not (marker-buffer org-clock-marker))
17457 (error "No active clock"))
17458 (save-excursion
17459 (set-buffer (marker-buffer org-clock-marker))
17460 (goto-char org-clock-marker)
17461 (delete-region (1- (point-at-bol)) (point-at-eol)))
17462 (message "Clock canceled"))
17463
17464 (defun org-clock-goto (&optional delete-windows)
17465 "Go to the currently clocked-in entry."
17466 (interactive "P")
17467 (if (not (marker-buffer org-clock-marker))
17468 (error "No active clock"))
17469 (switch-to-buffer-other-window
17470 (marker-buffer org-clock-marker))
17471 (if delete-windows (delete-other-windows))
17472 (goto-char org-clock-marker)
17473 (org-show-entry)
17474 (org-back-to-heading)
17475 (recenter))
17476
17477 (defvar org-clock-file-total-minutes nil
17478 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
17479 (make-variable-buffer-local 'org-clock-file-total-minutes)
17480
17481 (defun org-clock-sum (&optional tstart tend)
17482 "Sum the times for each subtree.
17483 Puts the resulting times in minutes as a text property on each headline."
17484 (interactive)
17485 (let* ((bmp (buffer-modified-p))
17486 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
17487 org-clock-string
17488 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
17489 (lmax 30)
17490 (ltimes (make-vector lmax 0))
17491 (t1 0)
17492 (level 0)
17493 ts te dt
17494 time)
17495 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
17496 (save-excursion
17497 (goto-char (point-max))
17498 (while (re-search-backward re nil t)
17499 (cond
17500 ((match-end 2)
17501 ;; Two time stamps
17502 (setq ts (match-string 2)
17503 te (match-string 3)
17504 ts (time-to-seconds
17505 (apply 'encode-time (org-parse-time-string ts)))
17506 te (time-to-seconds
17507 (apply 'encode-time (org-parse-time-string te)))
17508 ts (if tstart (max ts tstart) ts)
17509 te (if tend (min te tend) te)
17510 dt (- te ts)
17511 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
17512 ((match-end 4)
17513 ;; A naket time
17514 (setq t1 (+ t1 (string-to-number (match-string 5))
17515 (* 60 (string-to-number (match-string 4))))))
17516 (t ;; A headline
17517 (setq level (- (match-end 1) (match-beginning 1)))
17518 (when (or (> t1 0) (> (aref ltimes level) 0))
17519 (loop for l from 0 to level do
17520 (aset ltimes l (+ (aref ltimes l) t1)))
17521 (setq t1 0 time (aref ltimes level))
17522 (loop for l from level to (1- lmax) do
17523 (aset ltimes l 0))
17524 (goto-char (match-beginning 0))
17525 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
17526 (setq org-clock-file-total-minutes (aref ltimes 0)))
17527 (set-buffer-modified-p bmp)))
17528
17529 (defun org-clock-display (&optional total-only)
17530 "Show subtree times in the entire buffer.
17531 If TOTAL-ONLY is non-nil, only show the total time for the entire file
17532 in the echo area."
17533 (interactive)
17534 (org-remove-clock-overlays)
17535 (let (time h m p)
17536 (org-clock-sum)
17537 (unless total-only
17538 (save-excursion
17539 (goto-char (point-min))
17540 (while (or (and (equal (setq p (point)) (point-min))
17541 (get-text-property p :org-clock-minutes))
17542 (setq p (next-single-property-change
17543 (point) :org-clock-minutes)))
17544 (goto-char p)
17545 (when (setq time (get-text-property p :org-clock-minutes))
17546 (org-put-clock-overlay time (funcall outline-level))))
17547 (setq h (/ org-clock-file-total-minutes 60)
17548 m (- org-clock-file-total-minutes (* 60 h)))
17549 ;; Arrange to remove the overlays upon next change.
17550 (when org-remove-highlights-with-change
17551 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
17552 nil 'local))))
17553 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
17554
17555 (defvar org-clock-overlays nil)
17556 (make-variable-buffer-local 'org-clock-overlays)
17557
17558 (defun org-put-clock-overlay (time &optional level)
17559 "Put an overlays on the current line, displaying TIME.
17560 If LEVEL is given, prefix time with a corresponding number of stars.
17561 This creates a new overlay and stores it in `org-clock-overlays', so that it
17562 will be easy to remove."
17563 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
17564 (l (if level (org-get-legal-level level 0) 0))
17565 (off 0)
17566 ov tx)
17567 (move-to-column c)
17568 (unless (eolp) (skip-chars-backward "^ \t"))
17569 (skip-chars-backward " \t")
17570 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
17571 tx (concat (buffer-substring (1- (point)) (point))
17572 (make-string (+ off (max 0 (- c (current-column)))) ?.)
17573 (org-add-props (format "%s %2d:%02d%s"
17574 (make-string l ?*) h m
17575 (make-string (- 10 l) ?\ ))
17576 '(face secondary-selection))
17577 ""))
17578 (if (not (featurep 'xemacs))
17579 (org-overlay-put ov 'display tx)
17580 (org-overlay-put ov 'invisible t)
17581 (org-overlay-put ov 'end-glyph (make-glyph tx)))
17582 (push ov org-clock-overlays)))
17583
17584 (defun org-remove-clock-overlays (&optional beg end noremove)
17585 "Remove the occur highlights from the buffer.
17586 BEG and END are ignored. If NOREMOVE is nil, remove this function
17587 from the `before-change-functions' in the current buffer."
17588 (interactive)
17589 (unless org-inhibit-highlight-removal
17590 (mapc 'org-delete-overlay org-clock-overlays)
17591 (setq org-clock-overlays nil)
17592 (unless noremove
17593 (remove-hook 'before-change-functions
17594 'org-remove-clock-overlays 'local))))
17595
17596 (defun org-clock-out-if-current ()
17597 "Clock out if the current entry contains the running clock.
17598 This is used to stop the clock after a TODO entry is marked DONE,
17599 and is only done if the variable `org-clock-out-when-done' is not nil."
17600 (when (and org-clock-out-when-done
17601 (member state org-done-keywords)
17602 (equal (marker-buffer org-clock-marker) (current-buffer))
17603 (< (point) org-clock-marker)
17604 (> (save-excursion (outline-next-heading) (point))
17605 org-clock-marker))
17606 ;; Clock out, but don't accept a logging message for this.
17607 (let ((org-log-done (if (and (listp org-log-done)
17608 (member 'clock-out org-log-done))
17609 '(done)
17610 org-log-done)))
17611 (org-clock-out))))
17612
17613 (add-hook 'org-after-todo-state-change-hook
17614 'org-clock-out-if-current)
17615
17616 (defun org-check-running-clock ()
17617 "Check if the current buffer contains the running clock.
17618 If yes, offer to stop it and to save the buffer with the changes."
17619 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
17620 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
17621 (buffer-name))))
17622 (org-clock-out)
17623 (when (y-or-n-p "Save changed buffer?")
17624 (save-buffer))))
17625
17626 (defun org-clock-report (&optional arg)
17627 "Create a table containing a report about clocked time.
17628 If the cursor is inside an existing clocktable block, then the table
17629 will be updated. If not, a new clocktable will be inserted.
17630 When called with a prefix argument, move to the first clock table in the
17631 buffer and update it."
17632 (interactive "P")
17633 (org-remove-clock-overlays)
17634 (when arg (org-find-dblock "clocktable"))
17635 (if (org-in-clocktable-p)
17636 (goto-char (org-in-clocktable-p))
17637 (org-create-dblock (list :name "clocktable"
17638 :maxlevel 2 :scope 'file)))
17639 (org-update-dblock))
17640
17641 (defun org-in-clocktable-p ()
17642 "Check if the cursor is in a clocktable."
17643 (let ((pos (point)) start)
17644 (save-excursion
17645 (end-of-line 1)
17646 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
17647 (setq start (match-beginning 0))
17648 (re-search-forward "^#\\+END:.*" nil t)
17649 (>= (match-end 0) pos)
17650 start))))
17651
17652 (defun org-clock-update-time-maybe ()
17653 "If this is a CLOCK line, update it and return t.
17654 Otherwise, return nil."
17655 (interactive)
17656 (save-excursion
17657 (beginning-of-line 1)
17658 (skip-chars-forward " \t")
17659 (when (looking-at org-clock-string)
17660 (let ((re (concat "[ \t]*" org-clock-string
17661 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
17662 "\\([ \t]*=>.*\\)?"))
17663 ts te h m s)
17664 (if (not (looking-at re))
17665 nil
17666 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
17667 (end-of-line 1)
17668 (setq ts (match-string 1)
17669 te (match-string 2))
17670 (setq s (- (time-to-seconds
17671 (apply 'encode-time (org-parse-time-string te)))
17672 (time-to-seconds
17673 (apply 'encode-time (org-parse-time-string ts))))
17674 h (floor (/ s 3600))
17675 s (- s (* 3600 h))
17676 m (floor (/ s 60))
17677 s (- s (* 60 s)))
17678 (insert " => " (format "%2d:%02d" h m))
17679 t)))))
17680
17681 (defun org-clock-special-range (key &optional time as-strings)
17682 "Return two times bordering a special time range.
17683 Key is a symbol specifying the range and can be one of `today', `yesterday',
17684 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
17685 A week starts Monday 0:00 and ends Sunday 24:00.
17686 The range is determined relative to TIME. TIME defaults to the current time.
17687 The return value is a cons cell with two internal times like the ones
17688 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
17689 the returned times will be formatted strings."
17690 (let* ((tm (decode-time (or time (current-time))))
17691 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
17692 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
17693 (dow (nth 6 tm))
17694 s1 m1 h1 d1 month1 y1 diff ts te fm)
17695 (cond
17696 ((eq key 'today)
17697 (setq h 0 m 0 h1 24 m1 0))
17698 ((eq key 'yesterday)
17699 (setq d (1- d) h 0 m 0 h1 24 m1 0))
17700 ((eq key 'thisweek)
17701 (setq diff (if (= dow 0) 6 (1- dow))
17702 m 0 h 0 d (- d diff) d1 (+ 7 d)))
17703 ((eq key 'lastweek)
17704 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
17705 m 0 h 0 d (- d diff) d1 (+ 7 d)))
17706 ((eq key 'thismonth)
17707 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
17708 ((eq key 'lastmonth)
17709 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
17710 ((eq key 'thisyear)
17711 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
17712 ((eq key 'lastyear)
17713 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
17714 (t (error "No such time block %s" key)))
17715 (setq ts (encode-time s m h d month y)
17716 te (encode-time (or s1 s) (or m1 m) (or h1 h)
17717 (or d1 d) (or month1 month) (or y1 y)))
17718 (setq fm (cdr org-time-stamp-formats))
17719 (if as-strings
17720 (cons (format-time-string fm ts) (format-time-string fm te))
17721 (cons ts te))))
17722
17723 (defun org-dblock-write:clocktable (params)
17724 "Write the standard clocktable."
17725 (let ((hlchars '((1 . "*") (2 . "/")))
17726 (emph nil)
17727 (ins (make-marker))
17728 (total-time nil)
17729 ipos time h m p level hlc hdl maxlevel
17730 ts te cc block beg end pos scope tbl tostring multifile)
17731 (setq scope (plist-get params :scope)
17732 tostring (plist-get params :tostring)
17733 multifile (plist-get params :multifile)
17734 maxlevel (or (plist-get params :maxlevel) 3)
17735 emph (plist-get params :emphasize)
17736 ts (plist-get params :tstart)
17737 te (plist-get params :tend)
17738 block (plist-get params :block))
17739 (when block
17740 (setq cc (org-clock-special-range block nil t)
17741 ts (car cc) te (cdr cc)))
17742 (if ts (setq ts (time-to-seconds
17743 (apply 'encode-time (org-parse-time-string ts)))))
17744 (if te (setq te (time-to-seconds
17745 (apply 'encode-time (org-parse-time-string te)))))
17746 (move-marker ins (point))
17747 (setq ipos (point))
17748
17749 ;; Get the right scope
17750 (setq pos (point))
17751 (save-restriction
17752 (cond
17753 ((not scope))
17754 ((eq scope 'file) (widen))
17755 ((eq scope 'subtree) (org-narrow-to-subtree))
17756 ((eq scope 'tree)
17757 (while (org-up-heading-safe))
17758 (org-narrow-to-subtree))
17759 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
17760 (symbol-name scope)))
17761 (setq level (string-to-number (match-string 1 (symbol-name scope))))
17762 (catch 'exit
17763 (while (org-up-heading-safe)
17764 (looking-at outline-regexp)
17765 (if (<= (org-reduced-level (funcall outline-level)) level)
17766 (throw 'exit nil))))
17767 (org-narrow-to-subtree))
17768 ((or (listp scope) (eq scope 'agenda))
17769 (let* ((files (if (listp scope) scope (org-agenda-files)))
17770 (scope 'agenda)
17771 (p1 (copy-sequence params))
17772 file)
17773 (plist-put p1 :tostring t)
17774 (plist-put p1 :multifile t)
17775 (plist-put p1 :scope 'file)
17776 (org-prepare-agenda-buffers files)
17777 (while (setq file (pop files))
17778 (with-current-buffer (find-buffer-visiting file)
17779 (push (org-clocktable-add-file
17780 file (org-dblock-write:clocktable p1)) tbl)
17781 (setq total-time (+ (or total-time 0)
17782 org-clock-file-total-minutes)))))))
17783 (goto-char pos)
17784
17785 (unless (eq scope 'agenda)
17786 (org-clock-sum ts te)
17787 (goto-char (point-min))
17788 (while (setq p (next-single-property-change (point) :org-clock-minutes))
17789 (goto-char p)
17790 (when (setq time (get-text-property p :org-clock-minutes))
17791 (save-excursion
17792 (beginning-of-line 1)
17793 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
17794 (setq level (org-reduced-level
17795 (- (match-end 1) (match-beginning 1))))
17796 (<= level maxlevel))
17797 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
17798 hdl (match-string 2)
17799 h (/ time 60)
17800 m (- time (* 60 h)))
17801 (if (and (not multifile) (= level 1)) (push "|-" tbl))
17802 (push (concat
17803 "| " (int-to-string level) "|" hlc hdl hlc " |"
17804 (make-string (1- level) ?|)
17805 hlc (format "%d:%02d" h m) hlc
17806 " |") tbl))))))
17807 (setq tbl (nreverse tbl))
17808 (if tostring
17809 (if tbl (mapconcat 'identity tbl "\n") nil)
17810 (goto-char ins)
17811 (insert-before-markers
17812 "Clock summary at ["
17813 (substring
17814 (format-time-string (cdr org-time-stamp-formats))
17815 1 -1)
17816 "]."
17817 (if block
17818 (format " Considered range is /%s/." block)
17819 "")
17820 "\n\n"
17821 (if (eq scope 'agenda) "|File" "")
17822 "|L|Headline|Time|\n")
17823 (setq total-time (or total-time org-clock-file-total-minutes)
17824 h (/ total-time 60)
17825 m (- total-time (* 60 h)))
17826 (insert-before-markers
17827 "|-\n|"
17828 (if (eq scope 'agenda) "|" "")
17829 "|"
17830 "*Total time*| "
17831 (format "*%d:%02d*" h m)
17832 "|\n|-\n")
17833 (setq tbl (delq nil tbl))
17834 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
17835 (equal (substring (car tbl) 0 2) "|-"))
17836 (pop tbl))
17837 (insert-before-markers (mapconcat
17838 'identity (delq nil tbl)
17839 (if (eq scope 'agenda) "\n|-\n" "\n")))
17840 (backward-delete-char 1)
17841 (goto-char ipos)
17842 (skip-chars-forward "^|")
17843 (org-table-align)))))
17844
17845 (defun org-clocktable-add-file (file table)
17846 (if table
17847 (let ((lines (org-split-string table "\n"))
17848 (ff (file-name-nondirectory file)))
17849 (mapconcat 'identity
17850 (mapcar (lambda (x)
17851 (if (string-match org-table-dataline-regexp x)
17852 (concat "|" ff x)
17853 x))
17854 lines)
17855 "\n"))))
17856
17857 ;; FIXME: I don't think anybody uses this, ask David
17858 (defun org-collect-clock-time-entries ()
17859 "Return an internal list with clocking information.
17860 This list has one entry for each CLOCK interval.
17861 FIXME: describe the elements."
17862 (interactive)
17863 (let ((re (concat "^[ \t]*" org-clock-string
17864 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
17865 rtn beg end next cont level title total closedp leafp
17866 clockpos titlepos h m donep)
17867 (save-excursion
17868 (org-clock-sum)
17869 (goto-char (point-min))
17870 (while (re-search-forward re nil t)
17871 (setq clockpos (match-beginning 0)
17872 beg (match-string 1) end (match-string 2)
17873 cont (match-end 0))
17874 (setq beg (apply 'encode-time (org-parse-time-string beg))
17875 end (apply 'encode-time (org-parse-time-string end)))
17876 (org-back-to-heading t)
17877 (setq donep (org-entry-is-done-p))
17878 (setq titlepos (point)
17879 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
17880 h (/ total 60) m (- total (* 60 h))
17881 total (cons h m))
17882 (looking-at "\\(\\*+\\) +\\(.*\\)")
17883 (setq level (- (match-end 1) (match-beginning 1))
17884 title (org-match-string-no-properties 2))
17885 (save-excursion (outline-next-heading) (setq next (point)))
17886 (setq closedp (re-search-forward org-closed-time-regexp next t))
17887 (goto-char next)
17888 (setq leafp (and (looking-at "^\\*+ ")
17889 (<= (- (match-end 0) (point)) level)))
17890 (push (list beg end clockpos closedp donep
17891 total title titlepos level leafp)
17892 rtn)
17893 (goto-char cont)))
17894 (nreverse rtn)))
17895
17896 ;;;; Agenda, and Diary Integration
17897
17898 ;;; Define the Org-agenda-mode
17899
17900 (defvar org-agenda-mode-map (make-sparse-keymap)
17901 "Keymap for `org-agenda-mode'.")
17902
17903 (defvar org-agenda-menu) ; defined later in this file.
17904 (defvar org-agenda-follow-mode nil)
17905 (defvar org-agenda-show-log nil)
17906 (defvar org-agenda-redo-command nil)
17907 (defvar org-agenda-mode-hook nil)
17908 (defvar org-agenda-type nil)
17909 (defvar org-agenda-force-single-file nil)
17910
17911 (defun org-agenda-mode ()
17912 "Mode for time-sorted view on action items in Org-mode files.
17913
17914 The following commands are available:
17915
17916 \\{org-agenda-mode-map}"
17917 (interactive)
17918 (kill-all-local-variables)
17919 (setq org-agenda-undo-list nil
17920 org-agenda-pending-undo-list nil)
17921 (setq major-mode 'org-agenda-mode)
17922 ;; Keep global-font-lock-mode from turning on font-lock-mode
17923 (org-set-local 'font-lock-global-modes (list 'not major-mode))
17924 (setq mode-name "Org-Agenda")
17925 (use-local-map org-agenda-mode-map)
17926 (easy-menu-add org-agenda-menu)
17927 (if org-startup-truncated (setq truncate-lines t))
17928 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
17929 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
17930 ;; Make sure properties are removed when copying text
17931 (when (boundp 'buffer-substring-filters)
17932 (org-set-local 'buffer-substring-filters
17933 (cons (lambda (x)
17934 (set-text-properties 0 (length x) nil x) x)
17935 buffer-substring-filters)))
17936 (unless org-agenda-keep-modes
17937 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
17938 org-agenda-show-log nil))
17939 (easy-menu-change
17940 '("Agenda") "Agenda Files"
17941 (append
17942 (list
17943 (vector
17944 (if (get 'org-agenda-files 'org-restrict)
17945 "Restricted to single file"
17946 "Edit File List")
17947 '(org-edit-agenda-file-list)
17948 (not (get 'org-agenda-files 'org-restrict)))
17949 "--")
17950 (mapcar 'org-file-menu-entry (org-agenda-files))))
17951 (org-agenda-set-mode-name)
17952 (apply
17953 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
17954 (list 'org-agenda-mode-hook)))
17955
17956 (substitute-key-definition 'undo 'org-agenda-undo
17957 org-agenda-mode-map global-map)
17958 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
17959 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
17960 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
17961 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
17962 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
17963 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
17964 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
17965 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
17966 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
17967 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
17968 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
17969 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
17970 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
17971 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
17972 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
17973 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
17974 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
17975 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
17976 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
17977 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
17978 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
17979 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
17980 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
17981 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
17982 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
17983 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
17984 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
17985 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
17986 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
17987
17988 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
17989 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
17990 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
17991 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
17992 (while l (org-defkey org-agenda-mode-map
17993 (int-to-string (pop l)) 'digit-argument)))
17994
17995 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
17996 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
17997 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
17998 (org-defkey org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
17999 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
18000 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
18001 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
18002 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
18003 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
18004 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
18005 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
18006 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
18007 (org-defkey org-agenda-mode-map "n" 'next-line)
18008 (org-defkey org-agenda-mode-map "p" 'previous-line)
18009 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
18010 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
18011 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
18012 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
18013 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
18014 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
18015 (eval-after-load "calendar"
18016 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
18017 'org-calendar-goto-agenda))
18018 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
18019 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
18020 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
18021 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
18022 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
18023 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
18024 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
18025 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
18026 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
18027 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
18028 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
18029 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18030 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
18031 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
18032 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
18033 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
18034 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
18035 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
18036 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
18037 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
18038 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
18039 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
18040
18041 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
18042 "Local keymap for agenda entries from Org-mode.")
18043
18044 (org-defkey org-agenda-keymap
18045 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
18046 (org-defkey org-agenda-keymap
18047 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
18048 (when org-agenda-mouse-1-follows-link
18049 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
18050 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
18051 '("Agenda"
18052 ("Agenda Files")
18053 "--"
18054 ["Show" org-agenda-show t]
18055 ["Go To (other window)" org-agenda-goto t]
18056 ["Go To (this window)" org-agenda-switch-to t]
18057 ["Follow Mode" org-agenda-follow-mode
18058 :style toggle :selected org-agenda-follow-mode :active t]
18059 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
18060 "--"
18061 ["Cycle TODO" org-agenda-todo t]
18062 ["Archive subtree" org-agenda-archive t]
18063 ["Delete subtree" org-agenda-kill t]
18064 "--"
18065 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
18066 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
18067 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
18068 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
18069 "--"
18070 ("Tags and Properties"
18071 ["Show all Tags" org-agenda-show-tags t]
18072 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
18073 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
18074 "--"
18075 ["Column View" org-columns t])
18076 ("Date/Schedule"
18077 ["Schedule" org-agenda-schedule t]
18078 ["Set Deadline" org-agenda-deadline t]
18079 "--"
18080 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
18081 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
18082 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
18083 ("Clock"
18084 ["Clock in" org-agenda-clock-in t]
18085 ["Clock out" org-agenda-clock-out t]
18086 ["Clock cancel" org-agenda-clock-cancel t]
18087 ["Goto running clock" org-clock-goto t])
18088 ("Priority"
18089 ["Set Priority" org-agenda-priority t]
18090 ["Increase Priority" org-agenda-priority-up t]
18091 ["Decrease Priority" org-agenda-priority-down t]
18092 ["Show Priority" org-agenda-show-priority t])
18093 ("Calendar/Diary"
18094 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
18095 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
18096 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
18097 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
18098 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
18099 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
18100 "--"
18101 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
18102 "--"
18103 ("View"
18104 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
18105 :style radio :selected (equal org-agenda-ndays 1)]
18106 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
18107 :style radio :selected (equal org-agenda-ndays 7)]
18108 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
18109 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
18110 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
18111 :style radio :selected (member org-agenda-ndays '(365 366))]
18112 "--"
18113 ["Show Logbook entries" org-agenda-log-mode
18114 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
18115 ["Include Diary" org-agenda-toggle-diary
18116 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
18117 ["Use Time Grid" org-agenda-toggle-time-grid
18118 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
18119 ["Write view to file" org-write-agenda t]
18120 ["Rebuild buffer" org-agenda-redo t]
18121 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
18122 "--"
18123 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
18124 "--"
18125 ["Quit" org-agenda-quit t]
18126 ["Exit and Release Buffers" org-agenda-exit t]
18127 ))
18128
18129 ;;; Agenda undo
18130
18131 (defvar org-agenda-allow-remote-undo t
18132 "Non-nil means, allow remote undo from the agenda buffer.")
18133 (defvar org-agenda-undo-list nil
18134 "List of undoable operations in the agenda since last refresh.")
18135 (defvar org-agenda-undo-has-started-in nil
18136 "Buffers that have already seen `undo-start' in the current undo sequence.")
18137 (defvar org-agenda-pending-undo-list nil
18138 "In a series of undo commands, this is the list of remaning undo items.")
18139
18140 (defmacro org-if-unprotected (&rest body)
18141 "Execute BODY if there is no `org-protected' text property at point."
18142 (declare (debug t))
18143 `(unless (get-text-property (point) 'org-protected)
18144 ,@body))
18145
18146 (defmacro org-with-remote-undo (_buffer &rest _body)
18147 "Execute BODY while recording undo information in two buffers."
18148 (declare (indent 1) (debug t))
18149 `(let ((_cline (org-current-line))
18150 (_cmd this-command)
18151 (_buf1 (current-buffer))
18152 (_buf2 ,_buffer)
18153 (_undo1 buffer-undo-list)
18154 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
18155 _c1 _c2)
18156 ,@_body
18157 (when org-agenda-allow-remote-undo
18158 (setq _c1 (org-verify-change-for-undo
18159 _undo1 (with-current-buffer _buf1 buffer-undo-list))
18160 _c2 (org-verify-change-for-undo
18161 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
18162 (when (or _c1 _c2)
18163 ;; make sure there are undo boundaries
18164 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
18165 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
18166 ;; remember which buffer to undo
18167 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
18168 org-agenda-undo-list)))))
18169
18170 (defun org-agenda-undo ()
18171 "Undo a remote editing step in the agenda.
18172 This undoes changes both in the agenda buffer and in the remote buffer
18173 that have been changed along."
18174 (interactive)
18175 (or org-agenda-allow-remote-undo
18176 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
18177 (if (not (eq this-command last-command))
18178 (setq org-agenda-undo-has-started-in nil
18179 org-agenda-pending-undo-list org-agenda-undo-list))
18180 (if (not org-agenda-pending-undo-list)
18181 (error "No further undo information"))
18182 (let* ((entry (pop org-agenda-pending-undo-list))
18183 buf line cmd rembuf)
18184 (setq cmd (pop entry) line (pop entry))
18185 (setq rembuf (nth 2 entry))
18186 (org-with-remote-undo rembuf
18187 (while (bufferp (setq buf (pop entry)))
18188 (if (pop entry)
18189 (with-current-buffer buf
18190 (let ((last-undo-buffer buf)
18191 (inhibit-read-only t))
18192 (unless (memq buf org-agenda-undo-has-started-in)
18193 (push buf org-agenda-undo-has-started-in)
18194 (make-local-variable 'pending-undo-list)
18195 (undo-start))
18196 (while (and pending-undo-list
18197 (listp pending-undo-list)
18198 (not (car pending-undo-list)))
18199 (pop pending-undo-list))
18200 (undo-more 1))))))
18201 (goto-line line)
18202 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
18203
18204 (defun org-verify-change-for-undo (l1 l2)
18205 "Verify that a real change occurred between the undo lists L1 and L2."
18206 (while (and l1 (listp l1) (null (car l1))) (pop l1))
18207 (while (and l2 (listp l2) (null (car l2))) (pop l2))
18208 (not (eq l1 l2)))
18209
18210 ;;; Agenda dispatch
18211
18212 (defvar org-agenda-restrict nil)
18213 (defvar org-agenda-restrict-begin (make-marker))
18214 (defvar org-agenda-restrict-end (make-marker))
18215 (defvar org-agenda-last-dispatch-buffer nil)
18216
18217 ;;;###autoload
18218 (defun org-agenda (arg &optional keys restriction)
18219 "Dispatch agenda commands to collect entries to the agenda buffer.
18220 Prompts for a command to execute. Any prefix arg will be passed
18221 on to the selected command. The default selections are:
18222
18223 a Call `org-agenda-list' to display the agenda for current day or week.
18224 t Call `org-todo-list' to display the global todo list.
18225 T Call `org-todo-list' to display the global todo list, select only
18226 entries with a specific TODO keyword (the user gets a prompt).
18227 m Call `org-tags-view' to display headlines with tags matching
18228 a condition (the user is prompted for the condition).
18229 M Like `m', but select only TODO entries, no ordinary headlines.
18230 L Create a timeline for the current buffer.
18231 e Export views to associated files.
18232
18233 More commands can be added by configuring the variable
18234 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
18235 searches can be pre-defined in this way.
18236
18237 If the current buffer is in Org-mode and visiting a file, you can also
18238 first press `<' once to indicate that the agenda should be temporarily
18239 \(until the next use of \\[org-agenda]) restricted to the current file.
18240 Pressing `<' twice means to restrict to the current subtree or region
18241 \(if active)."
18242 (interactive "P")
18243 (catch 'exit
18244 (let* ((prefix-descriptions nil)
18245 (org-agenda-custom-commands
18246 ;; normalize different versions
18247 (delq nil
18248 (mapcar
18249 (lambda (x)
18250 (cond ((stringp (cdr x))
18251 (push x prefix-descriptions)
18252 nil)
18253 ((stringp (nth 1 x)) x)
18254 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
18255 (t (cons (car x) (cons "" (cdr x))))))
18256 org-agenda-custom-commands)))
18257 (buf (current-buffer))
18258 (bfn (buffer-file-name (buffer-base-buffer)))
18259 entry key type match lprops ans)
18260 ;; Turn off restriction
18261 (put 'org-agenda-files 'org-restrict nil)
18262 (setq org-agenda-restrict nil)
18263 (move-marker org-agenda-restrict-begin nil)
18264 (move-marker org-agenda-restrict-end nil)
18265 ;; Delete old local properties
18266 (put 'org-agenda-redo-command 'org-lprops nil)
18267 ;; Remember where this call originated
18268 (setq org-agenda-last-dispatch-buffer (current-buffer))
18269 (unless keys
18270 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
18271 keys (car ans)
18272 restriction (cdr ans)))
18273 ;; Estabish the restriction, if any
18274 (when restriction
18275 (put 'org-agenda-files 'org-restrict (list bfn))
18276 (cond
18277 ((eq restriction 'region)
18278 (setq org-agenda-restrict t)
18279 (move-marker org-agenda-restrict-begin (region-beginning))
18280 (move-marker org-agenda-restrict-end (region-end)))
18281 ((eq restriction 'subtree)
18282 (save-excursion
18283 (setq org-agenda-restrict t)
18284 (org-back-to-heading t)
18285 (move-marker org-agenda-restrict-begin (point))
18286 (move-marker org-agenda-restrict-end
18287 (progn (org-end-of-subtree t)))))))
18288
18289 (require 'calendar) ; FIXME: can we avoid this for some commands?
18290 ;; For example the todo list should not need it (but does...)
18291 (cond
18292 ((setq entry (assoc keys org-agenda-custom-commands))
18293 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
18294 (progn
18295 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
18296 (put 'org-agenda-redo-command 'org-lprops lprops)
18297 (cond
18298 ((eq type 'agenda)
18299 (org-let lprops '(org-agenda-list current-prefix-arg)))
18300 ((eq type 'alltodo)
18301 (org-let lprops '(org-todo-list current-prefix-arg)))
18302 ((eq type 'stuck)
18303 (org-let lprops '(org-agenda-list-stuck-projects
18304 current-prefix-arg)))
18305 ((eq type 'tags)
18306 (org-let lprops '(org-tags-view current-prefix-arg match)))
18307 ((eq type 'tags-todo)
18308 (org-let lprops '(org-tags-view '(4) match)))
18309 ((eq type 'todo)
18310 (org-let lprops '(org-todo-list match)))
18311 ((eq type 'tags-tree)
18312 (org-check-for-org-mode)
18313 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
18314 ((eq type 'todo-tree)
18315 (org-check-for-org-mode)
18316 (org-let lprops
18317 '(org-occur (concat "^" outline-regexp "[ \t]*"
18318 (regexp-quote match) "\\>"))))
18319 ((eq type 'occur-tree)
18320 (org-check-for-org-mode)
18321 (org-let lprops '(org-occur match)))
18322 ((functionp type)
18323 (org-let lprops '(funcall type match)))
18324 ((fboundp type)
18325 (org-let lprops '(funcall type match)))
18326 (t (error "Invalid custom agenda command type %s" type))))
18327 (org-run-agenda-series (nth 1 entry) (cddr entry))))
18328 ((equal keys "C") (customize-variable 'org-agenda-custom-commands))
18329 ((equal keys "a") (call-interactively 'org-agenda-list))
18330 ((equal keys "t") (call-interactively 'org-todo-list))
18331 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
18332 ((equal keys "m") (call-interactively 'org-tags-view))
18333 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
18334 ((equal keys "e") (call-interactively 'org-store-agenda-views))
18335 ((equal keys "L")
18336 (unless (org-mode-p)
18337 (error "This is not an Org-mode file"))
18338 (unless restriction
18339 (put 'org-agenda-files 'org-restrict (list bfn))
18340 (org-call-with-arg 'org-timeline arg)))
18341 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
18342 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
18343 ((equal keys "!") (customize-variable 'org-stuck-projects))
18344 (t (error "Invalid agenda key"))))))
18345
18346 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
18347 "The user interface for selecting an agenda command."
18348 (catch 'exit
18349 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
18350 (restrict-ok (and bfn (org-mode-p)))
18351 (region-p (org-region-active-p))
18352 (custom org-agenda-custom-commands)
18353 (selstring "")
18354 restriction second-time
18355 c entry key type match prefixes rmheader header-end custom1 desc)
18356 (save-window-excursion
18357 (delete-other-windows)
18358 (org-switch-to-buffer-other-window " *Agenda Commands*")
18359 (erase-buffer)
18360 (insert (eval-when-compile
18361 (let ((header
18362 "Press key for an agenda command: < Buffer,subtree/region restriction
18363 -------------------------------- C Configure custom agenda commands
18364 a Agenda for current week or day e Export agenda views
18365 t List of all TODO entries T Entries with special TODO kwd
18366 m Match a TAGS query M Like m, but only TODO entries
18367 L Timeline for current buffer # List stuck projects (!=configure)
18368 / Multi-occur
18369 ")
18370 (start 0))
18371 (while (string-match
18372 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
18373 header start)
18374 (setq start (match-end 0))
18375 (add-text-properties (match-beginning 2) (match-end 2)
18376 '(face bold) header))
18377 header)))
18378 (setq header-end (move-marker (make-marker) (point)))
18379 (while t
18380 (setq custom1 custom)
18381 (when (eq rmheader t)
18382 (goto-line 1)
18383 (re-search-forward ":" nil t)
18384 (delete-region (match-end 0) (line-end-position))
18385 (forward-char 1)
18386 (looking-at "-+")
18387 (delete-region (match-end 0) (line-end-position))
18388 (move-marker header-end (match-end 0)))
18389 (goto-char header-end)
18390 (delete-region (point) (point-max))
18391 (while (setq entry (pop custom1))
18392 (setq key (car entry) desc (nth 1 entry)
18393 type (nth 2 entry) match (nth 3 entry))
18394 (if (> (length key) 1)
18395 (add-to-list 'prefixes (string-to-char key))
18396 (insert
18397 (format
18398 "\n%-4s%-14s: %s"
18399 (org-add-props (copy-sequence key)
18400 '(face bold))
18401 (cond
18402 ((string-match "\\S-" desc) desc)
18403 ((eq type 'agenda) "Agenda for current week or day")
18404 ((eq type 'alltodo) "List of all TODO entries")
18405 ((eq type 'stuck) "List of stuck projects")
18406 ((eq type 'todo) "TODO keyword")
18407 ((eq type 'tags) "Tags query")
18408 ((eq type 'tags-todo) "Tags (TODO)")
18409 ((eq type 'tags-tree) "Tags tree")
18410 ((eq type 'todo-tree) "TODO kwd tree")
18411 ((eq type 'occur-tree) "Occur tree")
18412 ((functionp type) (if (symbolp type)
18413 (symbol-name type)
18414 "Lambda expression"))
18415 (t "???"))
18416 (cond
18417 ((stringp match)
18418 (org-add-props match nil 'face 'org-warning))
18419 (match
18420 (format "set of %d commands" (length match)))
18421 (t ""))))))
18422 (when prefixes
18423 (mapc (lambda (x)
18424 (insert
18425 (format "\n%s %s"
18426 (org-add-props (char-to-string x)
18427 nil 'face 'bold)
18428 (or (cdr (assoc (concat selstring (char-to-string x))
18429 prefix-descriptions))
18430 "Prefix key"))))
18431 prefixes))
18432 (goto-char (point-min))
18433 (when (fboundp 'fit-window-to-buffer)
18434 (if second-time
18435 (if (not (pos-visible-in-window-p (point-max)))
18436 (fit-window-to-buffer))
18437 (setq second-time t)
18438 (fit-window-to-buffer)))
18439 (message "Press key for agenda command%s:"
18440 (if restrict-ok
18441 (if restriction
18442 (format " (restricted to %s)" restriction)
18443 " (unrestricted)")
18444 ""))
18445 (setq c (read-char-exclusive))
18446 (message "")
18447 (cond
18448 ((assoc (char-to-string c) custom)
18449 (setq selstring (concat selstring (char-to-string c)))
18450 (throw 'exit (cons selstring restriction)))
18451 ((memq c prefixes)
18452 (setq selstring (concat selstring (char-to-string c))
18453 prefixes nil
18454 rmheader (or rmheader t)
18455 custom (delq nil (mapcar
18456 (lambda (x)
18457 (if (or (= (length (car x)) 1)
18458 (/= (string-to-char (car x)) c))
18459 nil
18460 (cons (substring (car x) 1) (cdr x))))
18461 custom))))
18462 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
18463 (message "Restriction is only possible in Org-mode buffers")
18464 (ding) (sit-for 1))
18465 ((eq c ?1)
18466 (setq restriction 'buffer))
18467 ((eq c ?0)
18468 (setq restriction (if region-p 'region 'subtree)))
18469 ((eq c ?<)
18470 (setq restriction
18471 (cond
18472 ((eq restriction 'buffer)
18473 (if region-p 'region 'subtree))
18474 ((memq restriction '(subtree region))
18475 nil)
18476 (t 'buffer))))
18477 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?/)))
18478 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
18479 ((equal c ?q) (error "Abort"))
18480 (t (error "Invalid key %c" c))))))))
18481
18482 (defun org-run-agenda-series (name series)
18483 (org-prepare-agenda name)
18484 (let* ((org-agenda-multi t)
18485 (redo (list 'org-run-agenda-series name (list 'quote series)))
18486 (cmds (car series))
18487 (gprops (nth 1 series))
18488 match ;; The byte compiler incorrectly complains about this. Keep it!
18489 cmd type lprops)
18490 (while (setq cmd (pop cmds))
18491 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
18492 (cond
18493 ((eq type 'agenda)
18494 (org-let2 gprops lprops
18495 '(call-interactively 'org-agenda-list)))
18496 ((eq type 'alltodo)
18497 (org-let2 gprops lprops
18498 '(call-interactively 'org-todo-list)))
18499 ((eq type 'stuck)
18500 (org-let2 gprops lprops
18501 '(call-interactively 'org-agenda-list-stuck-projects)))
18502 ((eq type 'tags)
18503 (org-let2 gprops lprops
18504 '(org-tags-view current-prefix-arg match)))
18505 ((eq type 'tags-todo)
18506 (org-let2 gprops lprops
18507 '(org-tags-view '(4) match)))
18508 ((eq type 'todo)
18509 (org-let2 gprops lprops
18510 '(org-todo-list match)))
18511 ((fboundp type)
18512 (org-let2 gprops lprops
18513 '(funcall type match)))
18514 (t (error "Invalid type in command series"))))
18515 (widen)
18516 (setq org-agenda-redo-command redo)
18517 (goto-char (point-min)))
18518 (org-finalize-agenda))
18519
18520 ;;;###autoload
18521 (defmacro org-batch-agenda (cmd-key &rest parameters)
18522 "Run an agenda command in batch mode and send the result to STDOUT.
18523 If CMD-KEY is a string of length 1, it is used as a key in
18524 `org-agenda-custom-commands' and triggers this command. If it is a
18525 longer string is is used as a tags/todo match string.
18526 Paramters are alternating variable names and values that will be bound
18527 before running the agenda command."
18528 (let (pars)
18529 (while parameters
18530 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18531 (if (> (length cmd-key) 2)
18532 (eval (list 'let (nreverse pars)
18533 (list 'org-tags-view nil cmd-key)))
18534 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
18535 (set-buffer org-agenda-buffer-name)
18536 (princ (org-encode-for-stdout (buffer-string)))))
18537
18538 (defun org-encode-for-stdout (string)
18539 (if (fboundp 'encode-coding-string)
18540 (encode-coding-string string buffer-file-coding-system)
18541 string))
18542
18543 (defvar org-agenda-info nil)
18544
18545 ;;;###autoload
18546 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
18547 "Run an agenda command in batch mode and send the result to STDOUT.
18548 If CMD-KEY is a string of length 1, it is used as a key in
18549 `org-agenda-custom-commands' and triggers this command. If it is a
18550 longer string is is used as a tags/todo match string.
18551 Paramters are alternating variable names and values that will be bound
18552 before running the agenda command.
18553
18554 The output gives a line for each selected agenda item. Each
18555 item is a list of comma-separated values, like this:
18556
18557 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
18558
18559 category The category of the item
18560 head The headline, without TODO kwd, TAGS and PRIORITY
18561 type The type of the agenda entry, can be
18562 todo selected in TODO match
18563 tagsmatch selected in tags match
18564 diary imported from diary
18565 deadline a deadline on given date
18566 scheduled scheduled on given date
18567 timestamp entry has timestamp on given date
18568 closed entry was closed on given date
18569 upcoming-deadline warning about deadline
18570 past-scheduled forwarded scheduled item
18571 block entry has date block including g. date
18572 todo The todo keyword, if any
18573 tags All tags including inherited ones, separated by colons
18574 date The relevant date, like 2007-2-14
18575 time The time, like 15:00-16:50
18576 extra Sting with extra planning info
18577 priority-l The priority letter if any was given
18578 priority-n The computed numerical priority
18579 agenda-day The day in the agenda where this is listed"
18580
18581 (let (pars)
18582 (while parameters
18583 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18584 (push (list 'org-agenda-remove-tags t) pars)
18585 (if (> (length cmd-key) 2)
18586 (eval (list 'let (nreverse pars)
18587 (list 'org-tags-view nil cmd-key)))
18588 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
18589 (set-buffer org-agenda-buffer-name)
18590 (let* ((lines (org-split-string (buffer-string) "\n"))
18591 line)
18592 (while (setq line (pop lines))
18593 (catch 'next
18594 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
18595 (setq org-agenda-info
18596 (org-fix-agenda-info (text-properties-at 0 line)))
18597 (princ
18598 (org-encode-for-stdout
18599 (mapconcat 'org-agenda-export-csv-mapper
18600 '(org-category txt type todo tags date time-of-day extra
18601 priority-letter priority agenda-day)
18602 ",")))
18603 (princ "\n"))))))
18604
18605 (defun org-fix-agenda-info (props)
18606 "Make sure all properties on an agenda item have a canonical form,
18607 so the the export commands caneasily use it."
18608 (let (tmp re)
18609 (when (setq tmp (plist-get props 'tags))
18610 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
18611 (when (setq tmp (plist-get props 'date))
18612 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
18613 (let ((calendar-date-display-form '(year "-" month "-" day)))
18614 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
18615
18616 (setq tmp (calendar-date-string tmp)))
18617 (setq props (plist-put props 'date tmp)))
18618 (when (setq tmp (plist-get props 'day))
18619 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
18620 (let ((calendar-date-display-form '(year "-" month "-" day)))
18621 (setq tmp (calendar-date-string tmp)))
18622 (setq props (plist-put props 'day tmp))
18623 (setq props (plist-put props 'agenda-day tmp)))
18624 (when (setq tmp (plist-get props 'txt))
18625 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
18626 (plist-put props 'priority-letter (match-string 1 tmp))
18627 (setq tmp (replace-match "" t t tmp)))
18628 (when (and (setq re (plist-get props 'org-todo-regexp))
18629 (setq re (concat "\\`\\.*" re " ?"))
18630 (string-match re tmp))
18631 (plist-put props 'todo (match-string 1 tmp))
18632 (setq tmp (replace-match "" t t tmp)))
18633 (plist-put props 'txt tmp)))
18634 props)
18635
18636 (defun org-agenda-export-csv-mapper (prop)
18637 (let ((res (plist-get org-agenda-info prop)))
18638 (setq res
18639 (cond
18640 ((not res) "")
18641 ((stringp res) res)
18642 (t (prin1-to-string res))))
18643 (while (string-match "," res)
18644 (setq res (replace-match ";" t t res)))
18645 (org-trim res)))
18646
18647
18648 ;;;###autoload
18649 (defun org-store-agenda-views (&rest parameters)
18650 (interactive)
18651 (eval (list 'org-batch-store-agenda-views)))
18652
18653 ;; FIXME, why is this a macro?????
18654 ;;;###autoload
18655 (defmacro org-batch-store-agenda-views (&rest parameters)
18656 "Run all custom agenda commands that have a file argument."
18657 (let ((cmds org-agenda-custom-commands)
18658 (pop-up-frames nil)
18659 (dir default-directory)
18660 pars cmd thiscmdkey files opts)
18661 (while parameters
18662 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18663 (setq pars (reverse pars))
18664 (save-window-excursion
18665 (while cmds
18666 (setq cmd (pop cmds)
18667 thiscmdkey (car cmd)
18668 opts (nth 3 cmd)
18669 files (nth 4 cmd))
18670 (if (stringp files) (setq files (list files)))
18671 (when files
18672 (eval (list 'let (append org-agenda-exporter-settings opts pars)
18673 (list 'org-agenda nil thiscmdkey)))
18674 (set-buffer org-agenda-buffer-name)
18675 (while files
18676 (eval (list 'let (append org-agenda-exporter-settings opts pars)
18677 (list 'org-write-agenda
18678 (expand-file-name (pop files) dir) t))))
18679 (and (get-buffer org-agenda-buffer-name)
18680 (kill-buffer org-agenda-buffer-name)))))))
18681
18682 (defun org-write-agenda (file &optional nosettings)
18683 "Write the current buffer (an agenda view) as a file.
18684 Depending on the extension of the file name, plain text (.txt),
18685 HTML (.html or .htm) or Postscript (.ps) is produced.
18686 If NOSETTINGS is given, do not scope the settings of
18687 `org-agenda-exporter-settings' into the export commands. This is used when
18688 the settings have already been scoped and we do not wish to overrule other,
18689 higher priority settings."
18690 (interactive "FWrite agenda to file: ")
18691 (if (not (file-writable-p file))
18692 (error "Cannot write agenda to file %s" file))
18693 (cond
18694 ((string-match "\\.html?\\'" file) (require 'htmlize))
18695 ((string-match "\\.ps\\'" file) (require 'ps-print)))
18696 (org-let (if nosettings nil org-agenda-exporter-settings)
18697 '(save-excursion
18698 (save-window-excursion
18699 (cond
18700 ((string-match "\\.html?\\'" file)
18701 (set-buffer (htmlize-buffer (current-buffer)))
18702
18703 (when (and org-agenda-export-html-style
18704 (string-match "<style>" org-agenda-export-html-style))
18705 ;; replace <style> section with org-agenda-export-html-style
18706 (goto-char (point-min))
18707 (kill-region (- (search-forward "<style") 6)
18708 (search-forward "</style>"))
18709 (insert org-agenda-export-html-style))
18710 (write-file file)
18711 (kill-buffer (current-buffer))
18712 (message "HTML written to %s" file))
18713 ((string-match "\\.ps\\'" file)
18714 (ps-print-buffer-with-faces file)
18715 (message "Postscript written to %s" file))
18716 (t
18717 (let ((bs (buffer-string)))
18718 (find-file file)
18719 (insert bs)
18720 (save-buffer 0)
18721 (kill-buffer (current-buffer))
18722 (message "Plain text written to %s" file))))))
18723 (set-buffer org-agenda-buffer-name)))
18724
18725 (defmacro org-no-read-only (&rest body)
18726 "Inhibit read-only for BODY."
18727 `(let ((inhibit-read-only t)) ,@body))
18728
18729 (defun org-check-for-org-mode ()
18730 "Make sure current buffer is in org-mode. Error if not."
18731 (or (org-mode-p)
18732 (error "Cannot execute org-mode agenda command on buffer in %s."
18733 major-mode)))
18734
18735 (defun org-fit-agenda-window ()
18736 "Fit the window to the buffer size."
18737 (and (memq org-agenda-window-setup '(reorganize-frame))
18738 (fboundp 'fit-window-to-buffer)
18739 (fit-window-to-buffer
18740 nil
18741 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
18742 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
18743
18744 ;;; Agenda file list
18745
18746 (defun org-agenda-files (&optional unrestricted)
18747 "Get the list of agenda files.
18748 Optional UNRESTRICTED means return the full list even if a restriction
18749 is currently in place."
18750 (let ((files
18751 (cond
18752 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18753 ((stringp org-agenda-files) (org-read-agenda-file-list))
18754 ((listp org-agenda-files) org-agenda-files)
18755 (t (error "Invalid value of `org-agenda-files'")))))
18756 (setq files (apply 'append
18757 (mapcar (lambda (f)
18758 (if (file-directory-p f)
18759 (directory-files f t "\\.org\\'")
18760 (list f)))
18761 files)))
18762 (if org-agenda-skip-unavailable-files
18763 (delq nil
18764 (mapcar (function
18765 (lambda (file)
18766 (and (file-readable-p file) file)))
18767 files))
18768 files))) ; `org-check-agenda-file' will remove them from the list
18769
18770 (defun org-edit-agenda-file-list ()
18771 "Edit the list of agenda files.
18772 Depending on setup, this either uses customize to edit the variable
18773 `org-agenda-files', or it visits the file that is holding the list. In the
18774 latter case, the buffer is set up in a way that saving it automatically kills
18775 the buffer and restores the previous window configuration."
18776 (interactive)
18777 (if (stringp org-agenda-files)
18778 (let ((cw (current-window-configuration)))
18779 (find-file org-agenda-files)
18780 (org-set-local 'org-window-configuration cw)
18781 (org-add-hook 'after-save-hook
18782 (lambda ()
18783 (set-window-configuration
18784 (prog1 org-window-configuration
18785 (kill-buffer (current-buffer))))
18786 (org-install-agenda-files-menu)
18787 (message "New agenda file list installed"))
18788 nil 'local)
18789 (message (substitute-command-keys
18790 "Edit list and finish with \\[save-buffer]")))
18791 (customize-variable 'org-agenda-files)))
18792
18793 (defun org-store-new-agenda-file-list (list)
18794 "Set new value for the agenda file list and save it correcly."
18795 (if (stringp org-agenda-files)
18796 (let ((f org-agenda-files) b)
18797 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
18798 (with-temp-file f
18799 (insert (mapconcat 'identity list "\n") "\n")))
18800 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
18801 (setq org-agenda-files list)
18802 (customize-save-variable 'org-agenda-files org-agenda-files))))
18803
18804 (defun org-read-agenda-file-list ()
18805 "Read the list of agenda files from a file."
18806 (when (stringp org-agenda-files)
18807 (with-temp-buffer
18808 (insert-file-contents org-agenda-files)
18809 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
18810
18811
18812 ;;;###autoload
18813 (defun org-cycle-agenda-files ()
18814 "Cycle through the files in `org-agenda-files'.
18815 If the current buffer visits an agenda file, find the next one in the list.
18816 If the current buffer does not, find the first agenda file."
18817 (interactive)
18818 (let* ((fs (org-agenda-files t))
18819 (files (append fs (list (car fs))))
18820 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18821 file)
18822 (unless files (error "No agenda files"))
18823 (catch 'exit
18824 (while (setq file (pop files))
18825 (if (equal (file-truename file) tcf)
18826 (when (car files)
18827 (find-file (car files))
18828 (throw 'exit t))))
18829 (find-file (car fs)))
18830 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
18831
18832 (defun org-agenda-file-to-front (&optional to-end)
18833 "Move/add the current file to the top of the agenda file list.
18834 If the file is not present in the list, it is added to the front. If it is
18835 present, it is moved there. With optional argument TO-END, add/move to the
18836 end of the list."
18837 (interactive "P")
18838 (let ((org-agenda-skip-unavailable-files nil)
18839 (file-alist (mapcar (lambda (x)
18840 (cons (file-truename x) x))
18841 (org-agenda-files t)))
18842 (ctf (file-truename buffer-file-name))
18843 x had)
18844 (setq x (assoc ctf file-alist) had x)
18845
18846 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18847 (if to-end
18848 (setq file-alist (append (delq x file-alist) (list x)))
18849 (setq file-alist (cons x (delq x file-alist))))
18850 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18851 (org-install-agenda-files-menu)
18852 (message "File %s to %s of agenda file list"
18853 (if had "moved" "added") (if to-end "end" "front"))))
18854
18855 (defun org-remove-file (&optional file)
18856 "Remove current file from the list of files in variable `org-agenda-files'.
18857 These are the files which are being checked for agenda entries.
18858 Optional argument FILE means, use this file instead of the current."
18859 (interactive)
18860 (let* ((org-agenda-skip-unavailable-files nil)
18861 (file (or file buffer-file-name))
18862 (true-file (file-truename file))
18863 (afile (abbreviate-file-name file))
18864 (files (delq nil (mapcar
18865 (lambda (x)
18866 (if (equal true-file
18867 (file-truename x))
18868 nil x))
18869 (org-agenda-files t)))))
18870 (if (not (= (length files) (length (org-agenda-files t))))
18871 (progn
18872 (org-store-new-agenda-file-list files)
18873 (org-install-agenda-files-menu)
18874 (message "Removed file: %s" afile))
18875 (message "File was not in list: %s" afile))))
18876
18877 (defun org-file-menu-entry (file)
18878 (vector file (list 'find-file file) t))
18879
18880 (defun org-check-agenda-file (file)
18881 "Make sure FILE exists. If not, ask user what to do."
18882 (when (not (file-exists-p file))
18883 (message "non-existent file %s. [R]emove from list or [A]bort?"
18884 (abbreviate-file-name file))
18885 (let ((r (downcase (read-char-exclusive))))
18886 (cond
18887 ((equal r ?r)
18888 (org-remove-file file)
18889 (throw 'nextfile t))
18890 (t (error "Abort"))))))
18891
18892 ;;; Agenda prepare and finalize
18893
18894 (defvar org-agenda-multi nil) ; dynammically scoped
18895 (defvar org-agenda-buffer-name "*Org Agenda*")
18896 (defvar org-pre-agenda-window-conf nil)
18897 (defvar org-agenda-name nil)
18898 (defun org-prepare-agenda (&optional name)
18899 (setq org-todo-keywords-for-agenda nil)
18900 (setq org-done-keywords-for-agenda nil)
18901 (if org-agenda-multi
18902 (progn
18903 (setq buffer-read-only nil)
18904 (goto-char (point-max))
18905 (unless (or (bobp) org-agenda-compact-blocks)
18906 (insert "\n" (make-string (window-width) ?=) "\n"))
18907 (narrow-to-region (point) (point-max)))
18908 (org-agenda-maybe-reset-markers 'force)
18909 (org-prepare-agenda-buffers (org-agenda-files))
18910 (setq org-todo-keywords-for-agenda
18911 (org-uniquify org-todo-keywords-for-agenda))
18912 (setq org-done-keywords-for-agenda
18913 (org-uniquify org-done-keywords-for-agenda))
18914 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
18915 (awin (get-buffer-window abuf)))
18916 (cond
18917 ((equal (current-buffer) abuf) nil)
18918 (awin (select-window awin))
18919 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
18920 ((equal org-agenda-window-setup 'current-window)
18921 (switch-to-buffer abuf))
18922 ((equal org-agenda-window-setup 'other-window)
18923 (org-switch-to-buffer-other-window abuf))
18924 ((equal org-agenda-window-setup 'other-frame)
18925 (switch-to-buffer-other-frame abuf))
18926 ((equal org-agenda-window-setup 'reorganize-frame)
18927 (delete-other-windows)
18928 (org-switch-to-buffer-other-window abuf))))
18929 (setq buffer-read-only nil)
18930 (erase-buffer)
18931 (org-agenda-mode)
18932 (and name (not org-agenda-name)
18933 (org-set-local 'org-agenda-name name)))
18934 (setq buffer-read-only nil))
18935
18936 (defun org-finalize-agenda ()
18937 "Finishing touch for the agenda buffer, called just before displaying it."
18938 (unless org-agenda-multi
18939 (save-excursion
18940 (let ((inhibit-read-only t))
18941 (goto-char (point-min))
18942 (while (org-activate-bracket-links (point-max))
18943 (add-text-properties (match-beginning 0) (match-end 0)
18944 '(face org-link)))
18945 (org-agenda-align-tags)
18946 (unless org-agenda-with-colors
18947 (remove-text-properties (point-min) (point-max) '(face nil))))
18948 (if (and (boundp 'org-overriding-columns-format)
18949 org-overriding-columns-format)
18950 (org-set-local 'org-overriding-columns-format
18951 org-overriding-columns-format))
18952 (if (and (boundp 'org-agenda-view-columns-initially)
18953 org-agenda-view-columns-initially)
18954 (org-agenda-columns))
18955 (when org-agenda-fontify-priorities
18956 (org-fontify-priorities))
18957 (run-hooks 'org-finalize-agenda-hook))))
18958
18959 (defun org-fontify-priorities ()
18960 "Make highest priority lines bold, and lowest italic."
18961 (interactive)
18962 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
18963 (org-delete-overlay o)))
18964 (overlays-in (point-min) (point-max)))
18965 (save-excursion
18966 (let ((ovs (org-overlays-in (point-min) (point-max)))
18967 (inhibit-read-only t)
18968 b e p ov h l)
18969 (goto-char (point-min))
18970 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
18971 (setq h (or (get-char-property (point) 'org-highest-priority)
18972 org-highest-priority)
18973 l (or (get-char-property (point) 'org-lowest-priority)
18974 org-lowest-priority)
18975 p (string-to-char (match-string 1))
18976 b (match-beginning 0) e (line-end-position)
18977 ov (org-make-overlay b e))
18978 (org-overlay-put
18979 ov 'face
18980 (cond ((listp org-agenda-fontify-priorities)
18981 (cdr (assoc p org-agenda-fontify-priorities)))
18982 ((equal p l) 'italic)
18983 ((equal p h) 'bold)))
18984 (org-overlay-put ov 'org-type 'org-priority)))))
18985
18986 (defun org-prepare-agenda-buffers (files)
18987 "Create buffers for all agenda files, protect archived trees and comments."
18988 (interactive)
18989 (let ((pa '(:org-archived t))
18990 (pc '(:org-comment t))
18991 (pall '(:org-archived t :org-comment t))
18992 (inhibit-read-only t)
18993 (rea (concat ":" org-archive-tag ":"))
18994 bmp file re)
18995 (save-excursion
18996 (save-restriction
18997 (while (setq file (pop files))
18998 (org-check-agenda-file file)
18999 (set-buffer (org-get-agenda-file-buffer file))
19000 (widen)
19001 (setq bmp (buffer-modified-p))
19002 (org-refresh-category-properties)
19003 (setq org-todo-keywords-for-agenda
19004 (append org-todo-keywords-for-agenda org-todo-keywords-1))
19005 (setq org-done-keywords-for-agenda
19006 (append org-done-keywords-for-agenda org-done-keywords))
19007 (save-excursion
19008 (remove-text-properties (point-min) (point-max) pall)
19009 (when org-agenda-skip-archived-trees
19010 (goto-char (point-min))
19011 (while (re-search-forward rea nil t)
19012 (if (org-on-heading-p t)
19013 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
19014 (goto-char (point-min))
19015 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
19016 (while (re-search-forward re nil t)
19017 (add-text-properties
19018 (match-beginning 0) (org-end-of-subtree t) pc)))
19019 (set-buffer-modified-p bmp))))))
19020
19021 (defvar org-agenda-skip-function nil
19022 "Function to be called at each match during agenda construction.
19023 If this function returns nil, the current match should not be skipped.
19024 Otherwise, the function must return a position from where the search
19025 should be continued.
19026 This may also be a Lisp form, it will be evaluated.
19027 Never set this variable using `setq' or so, because then it will apply
19028 to all future agenda commands. Instead, bind it with `let' to scope
19029 it dynamically into the agenda-constructing command. A good way to set
19030 it is through options in org-agenda-custom-commands.")
19031
19032 (defun org-agenda-skip ()
19033 "Throw to `:skip' in places that should be skipped.
19034 Also moves point to the end of the skipped region, so that search can
19035 continue from there."
19036 (let ((p (point-at-bol)) to fp)
19037 (and org-agenda-skip-archived-trees
19038 (get-text-property p :org-archived)
19039 (org-end-of-subtree t)
19040 (throw :skip t))
19041 (and (get-text-property p :org-comment)
19042 (org-end-of-subtree t)
19043 (throw :skip t))
19044 (if (equal (char-after p) ?#) (throw :skip t))
19045 (when (and (or (setq fp (functionp org-agenda-skip-function))
19046 (consp org-agenda-skip-function))
19047 (setq to (save-excursion
19048 (save-match-data
19049 (if fp
19050 (funcall org-agenda-skip-function)
19051 (eval org-agenda-skip-function))))))
19052 (goto-char to)
19053 (throw :skip t))))
19054
19055 (defvar org-agenda-markers nil
19056 "List of all currently active markers created by `org-agenda'.")
19057 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
19058 "Creation time of the last agenda marker.")
19059
19060 (defun org-agenda-new-marker (&optional pos)
19061 "Return a new agenda marker.
19062 Org-mode keeps a list of these markers and resets them when they are
19063 no longer in use."
19064 (let ((m (copy-marker (or pos (point)))))
19065 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
19066 (push m org-agenda-markers)
19067 m))
19068
19069 (defun org-agenda-maybe-reset-markers (&optional force)
19070 "Reset markers created by `org-agenda'. But only if they are old enough."
19071 (if (or (and force (not org-agenda-multi))
19072 (> (- (time-to-seconds (current-time))
19073 org-agenda-last-marker-time)
19074 5))
19075 (while org-agenda-markers
19076 (move-marker (pop org-agenda-markers) nil))))
19077
19078 (defvar org-agenda-new-buffers nil
19079 "Buffers created to visit agenda files.")
19080
19081 (defun org-get-agenda-file-buffer (file)
19082 "Get a buffer visiting FILE. If the buffer needs to be created, add
19083 it to the list of buffers which might be released later."
19084 (let ((buf (org-find-base-buffer-visiting file)))
19085 (if buf
19086 buf ; just return it
19087 ;; Make a new buffer and remember it
19088 (setq buf (find-file-noselect file))
19089 (if buf (push buf org-agenda-new-buffers))
19090 buf)))
19091
19092 (defun org-release-buffers (blist)
19093 "Release all buffers in list, asking the user for confirmation when needed.
19094 When a buffer is unmodified, it is just killed. When modified, it is saved
19095 \(if the user agrees) and then killed."
19096 (let (buf file)
19097 (while (setq buf (pop blist))
19098 (setq file (buffer-file-name buf))
19099 (when (and (buffer-modified-p buf)
19100 file
19101 (y-or-n-p (format "Save file %s? " file)))
19102 (with-current-buffer buf (save-buffer)))
19103 (kill-buffer buf))))
19104
19105 (defun org-get-category (&optional pos)
19106 "Get the category applying to position POS."
19107 (get-text-property (or pos (point)) 'org-category))
19108
19109 ;;; Agenda timeline
19110
19111 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
19112
19113 (defun org-timeline (&optional include-all)
19114 "Show a time-sorted view of the entries in the current org file.
19115 Only entries with a time stamp of today or later will be listed. With
19116 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
19117 under the current date.
19118 If the buffer contains an active region, only check the region for
19119 dates."
19120 (interactive "P")
19121 (require 'calendar)
19122 (org-compile-prefix-format 'timeline)
19123 (org-set-sorting-strategy 'timeline)
19124 (let* ((dopast t)
19125 (dotodo include-all)
19126 (doclosed org-agenda-show-log)
19127 (entry buffer-file-name)
19128 (date (calendar-current-date))
19129 (beg (if (org-region-active-p) (region-beginning) (point-min)))
19130 (end (if (org-region-active-p) (region-end) (point-max)))
19131 (day-numbers (org-get-all-dates beg end 'no-ranges
19132 t doclosed ; always include today
19133 org-timeline-show-empty-dates))
19134 (org-deadline-warning-days 0)
19135 (org-agenda-only-exact-dates t)
19136 (today (time-to-days (current-time)))
19137 (past t)
19138 args
19139 s e rtn d emptyp)
19140 (setq org-agenda-redo-command
19141 (list 'progn
19142 (list 'org-switch-to-buffer-other-window (current-buffer))
19143 (list 'org-timeline (list 'quote include-all))))
19144 (if (not dopast)
19145 ;; Remove past dates from the list of dates.
19146 (setq day-numbers (delq nil (mapcar (lambda(x)
19147 (if (>= x today) x nil))
19148 day-numbers))))
19149 (org-prepare-agenda (concat "Timeline "
19150 (file-name-nondirectory buffer-file-name)))
19151 (if doclosed (push :closed args))
19152 (push :timestamp args)
19153 (push :deadline args)
19154 (push :scheduled args)
19155 (push :sexp args)
19156 (if dotodo (push :todo args))
19157 (while (setq d (pop day-numbers))
19158 (if (and (listp d) (eq (car d) :omitted))
19159 (progn
19160 (setq s (point))
19161 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
19162 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
19163 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
19164 (if (and (>= d today)
19165 dopast
19166 past)
19167 (progn
19168 (setq past nil)
19169 (insert (make-string 79 ?-) "\n")))
19170 (setq date (calendar-gregorian-from-absolute d))
19171 (setq s (point))
19172 (setq rtn (and (not emptyp)
19173 (apply 'org-agenda-get-day-entries entry
19174 date args)))
19175 (if (or rtn (equal d today) org-timeline-show-empty-dates)
19176 (progn
19177 (insert
19178 (if (stringp org-agenda-format-date)
19179 (format-time-string org-agenda-format-date
19180 (org-time-from-absolute date))
19181 (funcall org-agenda-format-date date))
19182 "\n")
19183 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19184 (put-text-property s (1- (point)) 'org-date-line t)
19185 (if (equal d today)
19186 (put-text-property s (1- (point)) 'org-today t))
19187 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
19188 (put-text-property s (1- (point)) 'day d)))))
19189 (goto-char (point-min))
19190 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
19191 (point-min)))
19192 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
19193 (org-finalize-agenda)
19194 (setq buffer-read-only t)))
19195
19196 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
19197 "Return a list of all relevant day numbers from BEG to END buffer positions.
19198 If NO-RANGES is non-nil, include only the start and end dates of a range,
19199 not every single day in the range. If FORCE-TODAY is non-nil, make
19200 sure that TODAY is included in the list. If INACTIVE is non-nil, also
19201 inactive time stamps (those in square brackets) are included.
19202 When EMPTY is non-nil, also include days without any entries."
19203 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
19204 dates dates1 date day day1 day2 ts1 ts2)
19205 (if force-today
19206 (setq dates (list (time-to-days (current-time)))))
19207 (save-excursion
19208 (goto-char beg)
19209 (while (re-search-forward re end t)
19210 (setq day (time-to-days (org-time-string-to-time
19211 (substring (match-string 1) 0 10))))
19212 (or (memq day dates) (push day dates)))
19213 (unless no-ranges
19214 (goto-char beg)
19215 (while (re-search-forward org-tr-regexp end t)
19216 (setq ts1 (substring (match-string 1) 0 10)
19217 ts2 (substring (match-string 2) 0 10)
19218 day1 (time-to-days (org-time-string-to-time ts1))
19219 day2 (time-to-days (org-time-string-to-time ts2)))
19220 (while (< (setq day1 (1+ day1)) day2)
19221 (or (memq day1 dates) (push day1 dates)))))
19222 (setq dates (sort dates '<))
19223 (when empty
19224 (while (setq day (pop dates))
19225 (setq day2 (car dates))
19226 (push day dates1)
19227 (when (and day2 empty)
19228 (if (or (eq empty t)
19229 (and (numberp empty) (<= (- day2 day) empty)))
19230 (while (< (setq day (1+ day)) day2)
19231 (push (list day) dates1))
19232 (push (cons :omitted (- day2 day)) dates1))))
19233 (setq dates (nreverse dates1)))
19234 dates)))
19235
19236 ;;; Agenda Daily/Weekly
19237
19238 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
19239 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
19240 (defvar org-agenda-last-arguments nil
19241 "The arguments of the previous call to org-agenda")
19242 (defvar org-starting-day nil) ; local variable in the agenda buffer
19243 (defvar org-agenda-span nil) ; local variable in the agenda buffer
19244 (defvar org-include-all-loc nil) ; local variable
19245 (defvar org-agenda-remove-date nil) ; dynamically scoped
19246
19247 ;;;###autoload
19248 (defun org-agenda-list (&optional include-all start-day ndays)
19249 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
19250 The view will be for the current day or week, but from the overview buffer
19251 you will be able to go to other days/weeks.
19252
19253 With one \\[universal-argument] prefix argument INCLUDE-ALL,
19254 all unfinished TODO items will also be shown, before the agenda.
19255 This feature is considered obsolete, please use the TODO list or a block
19256 agenda instead.
19257
19258 With a numeric prefix argument in an interactive call, the agenda will
19259 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
19260 the number of days. NDAYS defaults to `org-agenda-ndays'.
19261
19262 START-DAY defaults to TODAY, or to the most recent match for the weekday
19263 given in `org-agenda-start-on-weekday'."
19264 (interactive "P")
19265 (if (and (integerp include-all) (> include-all 0))
19266 (setq ndays include-all include-all nil))
19267 (setq ndays (or ndays org-agenda-ndays)
19268 start-day (or start-day org-agenda-start-day))
19269 (if org-agenda-overriding-arguments
19270 (setq include-all (car org-agenda-overriding-arguments)
19271 start-day (nth 1 org-agenda-overriding-arguments)
19272 ndays (nth 2 org-agenda-overriding-arguments)))
19273 (if (stringp start-day)
19274 ;; Convert to an absolute day number
19275 (setq start-day (time-to-days (org-read-date nil t start-day))))
19276 (setq org-agenda-last-arguments (list include-all start-day ndays))
19277 (org-compile-prefix-format 'agenda)
19278 (org-set-sorting-strategy 'agenda)
19279 (require 'calendar)
19280 (let* ((org-agenda-start-on-weekday
19281 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
19282 org-agenda-start-on-weekday nil))
19283 (thefiles (org-agenda-files))
19284 (files thefiles)
19285 (today (time-to-days (current-time)))
19286 (sd (or start-day today))
19287 (start (if (or (null org-agenda-start-on-weekday)
19288 (< org-agenda-ndays 7))
19289 sd
19290 (let* ((nt (calendar-day-of-week
19291 (calendar-gregorian-from-absolute sd)))
19292 (n1 org-agenda-start-on-weekday)
19293 (d (- nt n1)))
19294 (- sd (+ (if (< d 0) 7 0) d)))))
19295 (day-numbers (list start))
19296 (day-cnt 0)
19297 (inhibit-redisplay (not debug-on-error))
19298 s e rtn rtnall file date d start-pos end-pos todayp nd)
19299 (setq org-agenda-redo-command
19300 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
19301 ;; Make the list of days
19302 (setq ndays (or ndays org-agenda-ndays)
19303 nd ndays)
19304 (while (> ndays 1)
19305 (push (1+ (car day-numbers)) day-numbers)
19306 (setq ndays (1- ndays)))
19307 (setq day-numbers (nreverse day-numbers))
19308 (org-prepare-agenda "Day/Week")
19309 (org-set-local 'org-starting-day (car day-numbers))
19310 (org-set-local 'org-include-all-loc include-all)
19311 (org-set-local 'org-agenda-span
19312 (org-agenda-ndays-to-span nd))
19313 (when (and (or include-all org-agenda-include-all-todo)
19314 (member today day-numbers))
19315 (setq files thefiles
19316 rtnall nil)
19317 (while (setq file (pop files))
19318 (catch 'nextfile
19319 (org-check-agenda-file file)
19320 (setq date (calendar-gregorian-from-absolute today)
19321 rtn (org-agenda-get-day-entries
19322 file date :todo))
19323 (setq rtnall (append rtnall rtn))))
19324 (when rtnall
19325 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
19326 (add-text-properties (point-min) (1- (point))
19327 (list 'face 'org-agenda-structure))
19328 (insert (org-finalize-agenda-entries rtnall) "\n")))
19329 (unless org-agenda-compact-blocks
19330 (setq s (point))
19331 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
19332 "-agenda:\n")
19333 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
19334 'org-date-line t)))
19335 (while (setq d (pop day-numbers))
19336 (setq date (calendar-gregorian-from-absolute d)
19337 s (point))
19338 (if (or (setq todayp (= d today))
19339 (and (not start-pos) (= d sd)))
19340 (setq start-pos (point))
19341 (if (and start-pos (not end-pos))
19342 (setq end-pos (point))))
19343 (setq files thefiles
19344 rtnall nil)
19345 (while (setq file (pop files))
19346 (catch 'nextfile
19347 (org-check-agenda-file file)
19348 (if org-agenda-show-log
19349 (setq rtn (org-agenda-get-day-entries
19350 file date
19351 :deadline :scheduled :timestamp :sexp :closed))
19352 (setq rtn (org-agenda-get-day-entries
19353 file date
19354 :deadline :scheduled :sexp :timestamp)))
19355 (setq rtnall (append rtnall rtn))))
19356 (if org-agenda-include-diary
19357 (progn
19358 (require 'diary-lib)
19359 (setq rtn (org-get-entries-from-diary date))
19360 (setq rtnall (append rtnall rtn))))
19361 (if (or rtnall org-agenda-show-all-dates)
19362 (progn
19363 (setq day-cnt (1+ day-cnt))
19364 (insert
19365 (if (stringp org-agenda-format-date)
19366 (format-time-string org-agenda-format-date
19367 (org-time-from-absolute date))
19368 (funcall org-agenda-format-date date))
19369 "\n")
19370 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19371 (put-text-property s (1- (point)) 'org-date-line t)
19372 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
19373 (if todayp (put-text-property s (1- (point)) 'org-today t))
19374 (if rtnall (insert
19375 (org-finalize-agenda-entries
19376 (org-agenda-add-time-grid-maybe
19377 rtnall nd todayp))
19378 "\n"))
19379 (put-text-property s (1- (point)) 'day d)
19380 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
19381 (goto-char (point-min))
19382 (org-fit-agenda-window)
19383 (unless (and (pos-visible-in-window-p (point-min))
19384 (pos-visible-in-window-p (point-max)))
19385 (goto-char (1- (point-max)))
19386 (recenter -1)
19387 (if (not (pos-visible-in-window-p (or start-pos 1)))
19388 (progn
19389 (goto-char (or start-pos 1))
19390 (recenter 1))))
19391 (goto-char (or start-pos 1))
19392 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
19393 (org-finalize-agenda)
19394 (setq buffer-read-only t)
19395 (message "")))
19396
19397 (defun org-agenda-ndays-to-span (n)
19398 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
19399
19400 ;;; Agenda TODO list
19401
19402 (defvar org-select-this-todo-keyword nil)
19403 (defvar org-last-arg nil)
19404
19405 ;;;###autoload
19406 (defun org-todo-list (arg)
19407 "Show all TODO entries from all agenda file in a single list.
19408 The prefix arg can be used to select a specific TODO keyword and limit
19409 the list to these. When using \\[universal-argument], you will be prompted
19410 for a keyword. A numeric prefix directly selects the Nth keyword in
19411 `org-todo-keywords-1'."
19412 (interactive "P")
19413 (require 'calendar)
19414 (org-compile-prefix-format 'todo)
19415 (org-set-sorting-strategy 'todo)
19416 (org-prepare-agenda "TODO")
19417 (let* ((today (time-to-days (current-time)))
19418 (date (calendar-gregorian-from-absolute today))
19419 (kwds org-todo-keywords-for-agenda)
19420 (completion-ignore-case t)
19421 (org-select-this-todo-keyword
19422 (if (stringp arg) arg
19423 (and arg (integerp arg) (> arg 0)
19424 (nth (1- arg) kwds))))
19425 rtn rtnall files file pos)
19426 (when (equal arg '(4))
19427 (setq org-select-this-todo-keyword
19428 (completing-read "Keyword (or KWD1|K2D2|...): "
19429 (mapcar 'list kwds) nil nil)))
19430 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
19431 (org-set-local 'org-last-arg arg)
19432 (setq org-agenda-redo-command
19433 '(org-todo-list (or current-prefix-arg org-last-arg)))
19434 (setq files (org-agenda-files)
19435 rtnall nil)
19436 (while (setq file (pop files))
19437 (catch 'nextfile
19438 (org-check-agenda-file file)
19439 (setq rtn (org-agenda-get-day-entries file date :todo))
19440 (setq rtnall (append rtnall rtn))))
19441 (if org-agenda-overriding-header
19442 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
19443 nil 'face 'org-agenda-structure) "\n")
19444 (insert "Global list of TODO items of type: ")
19445 (add-text-properties (point-min) (1- (point))
19446 (list 'face 'org-agenda-structure))
19447 (setq pos (point))
19448 (insert (or org-select-this-todo-keyword "ALL") "\n")
19449 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
19450 (setq pos (point))
19451 (unless org-agenda-multi
19452 (insert "Available with `N r': (0)ALL")
19453 (let ((n 0) s)
19454 (mapc (lambda (x)
19455 (setq s (format "(%d)%s" (setq n (1+ n)) x))
19456 (if (> (+ (current-column) (string-width s) 1) (frame-width))
19457 (insert "\n "))
19458 (insert " " s))
19459 kwds))
19460 (insert "\n"))
19461 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
19462 (when rtnall
19463 (insert (org-finalize-agenda-entries rtnall) "\n"))
19464 (goto-char (point-min))
19465 (org-fit-agenda-window)
19466 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
19467 (org-finalize-agenda)
19468 (setq buffer-read-only t)))
19469
19470 ;;; Agenda tags match
19471
19472 ;;;###autoload
19473 (defun org-tags-view (&optional todo-only match)
19474 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
19475 The prefix arg TODO-ONLY limits the search to TODO entries."
19476 (interactive "P")
19477 (org-compile-prefix-format 'tags)
19478 (org-set-sorting-strategy 'tags)
19479 (let* ((org-tags-match-list-sublevels
19480 (if todo-only t org-tags-match-list-sublevels))
19481 (completion-ignore-case t)
19482 rtn rtnall files file pos matcher
19483 buffer)
19484 (setq matcher (org-make-tags-matcher match)
19485 match (car matcher) matcher (cdr matcher))
19486 (org-prepare-agenda (concat "TAGS " match))
19487 (setq org-agenda-redo-command
19488 (list 'org-tags-view (list 'quote todo-only)
19489 (list 'if 'current-prefix-arg nil match)))
19490 (setq files (org-agenda-files)
19491 rtnall nil)
19492 (while (setq file (pop files))
19493 (catch 'nextfile
19494 (org-check-agenda-file file)
19495 (setq buffer (if (file-exists-p file)
19496 (org-get-agenda-file-buffer file)
19497 (error "No such file %s" file)))
19498 (if (not buffer)
19499 ;; If file does not exist, merror message to agenda
19500 (setq rtn (list
19501 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
19502 rtnall (append rtnall rtn))
19503 (with-current-buffer buffer
19504 (unless (org-mode-p)
19505 (error "Agenda file %s is not in `org-mode'" file))
19506 (save-excursion
19507 (save-restriction
19508 (if org-agenda-restrict
19509 (narrow-to-region org-agenda-restrict-begin
19510 org-agenda-restrict-end)
19511 (widen))
19512 (setq rtn (org-scan-tags 'agenda matcher todo-only))
19513 (setq rtnall (append rtnall rtn))))))))
19514 (if org-agenda-overriding-header
19515 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
19516 nil 'face 'org-agenda-structure) "\n")
19517 (insert "Headlines with TAGS match: ")
19518 (add-text-properties (point-min) (1- (point))
19519 (list 'face 'org-agenda-structure))
19520 (setq pos (point))
19521 (insert match "\n")
19522 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
19523 (setq pos (point))
19524 (unless org-agenda-multi
19525 (insert "Press `C-u r' to search again with new search string\n"))
19526 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
19527 (when rtnall
19528 (insert (org-finalize-agenda-entries rtnall) "\n"))
19529 (goto-char (point-min))
19530 (org-fit-agenda-window)
19531 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
19532 (org-finalize-agenda)
19533 (setq buffer-read-only t)))
19534
19535 ;;; Agenda Finding stuck projects
19536
19537 (defvar org-agenda-skip-regexp nil
19538 "Regular expression used in skipping subtrees for the agenda.
19539 This is basically a temporary global variable that can be set and then
19540 used by user-defined selections using `org-agenda-skip-function'.")
19541
19542 (defvar org-agenda-overriding-header nil
19543 "When this is set during todo and tags searches, will replace header.")
19544
19545 (defun org-agenda-skip-subtree-when-regexp-matches ()
19546 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
19547 If yes, it returns the end position of this tree, causing agenda commands
19548 to skip this subtree. This is a function that can be put into
19549 `org-agenda-skip-function' for the duration of a command."
19550 (let ((end (save-excursion (org-end-of-subtree t)))
19551 skip)
19552 (save-excursion
19553 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
19554 (and skip end)))
19555
19556 (defun org-agenda-skip-entry-if (&rest conditions)
19557 "Skip entry if any of CONDITIONS is true.
19558 See `org-agenda-skip-if for details."
19559 (org-agenda-skip-if nil conditions))
19560 (defun org-agenda-skip-subtree-if (&rest conditions)
19561 "Skip entry if any of CONDITIONS is true.
19562 See `org-agenda-skip-if for details."
19563 (org-agenda-skip-if t conditions))
19564
19565 (defun org-agenda-skip-if (subtree conditions)
19566 "Checks current entity for CONDITIONS.
19567 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
19568 the entry, i.e. the text before the next heading is checked.
19569
19570 CONDITIONS is a list of symbols, boolean OR is used to combine the results
19571 from different tests. Valid conditions are:
19572
19573 scheduled Check if there is a scheduled cookie
19574 notscheduled Check if there is no scheduled cookie
19575 deadline Check if there is a deadline
19576 notdeadline Check if there is no deadline
19577 regexp Check if regexp matches
19578 notregexp Check if regexp does not match.
19579
19580 The regexp is taken from the conditions list, it must com right after the
19581 `regexp' of `notregexp' element.
19582
19583 If any of these conditions is met, this function returns the end point of
19584 the entity, causing the search to continue from there. This is a function
19585 that can be put into `org-agenda-skip-function' for the duration of a command."
19586 (let (beg end m r)
19587 (org-back-to-heading t)
19588 (setq beg (point)
19589 end (if subtree
19590 (progn (org-end-of-subtree t) (point))
19591 (progn (outline-next-heading) (1- (point)))))
19592 (goto-char beg)
19593 (and
19594 (or
19595 (and (memq 'scheduled conditions)
19596 (re-search-forward org-scheduled-time-regexp end t))
19597 (and (memq 'notscheduled conditions)
19598 (not (re-search-forward org-scheduled-time-regexp end t)))
19599 (and (memq 'deadline conditions)
19600 (re-search-forward org-deadline-time-regexp end t))
19601 (and (memq 'notdeadline conditions)
19602 (not (re-search-forward org-deadline-time-regexp end t)))
19603 (and (setq m (memq 'regexp conditions))
19604 (stringp (setq r (nth 1 m)))
19605 (re-search-forward (nth 1 m) end t))
19606 (and (setq m (memq 'notregexp conditions))
19607 (stringp (setq r (nth 1 m)))
19608 (not (re-search-forward (nth 1 m) end t))))
19609 end)))
19610
19611 (defun org-agenda-list-stuck-projects (&rest ignore)
19612 "Create agenda view for projects that are stuck.
19613 Stuck projects are project that have no next actions. For the definitions
19614 of what a project is and how to check if it stuck, customize the variable
19615 `org-stuck-projects'.
19616 MATCH is being ignored."
19617 (interactive)
19618 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
19619 ;; FIXME: we could have used org-agenda-skip-if here.
19620 (org-agenda-overriding-header "List of stuck projects: ")
19621 (matcher (nth 0 org-stuck-projects))
19622 (todo (nth 1 org-stuck-projects))
19623 (todo-wds (if (member "*" todo)
19624 (progn
19625 (org-prepare-agenda-buffers (org-agenda-files))
19626 (org-delete-all
19627 org-done-keywords-for-agenda
19628 (copy-sequence org-todo-keywords-for-agenda)))
19629 todo))
19630 (todo-re (concat "^\\*+[ \t]+\\("
19631 (mapconcat 'identity todo-wds "\\|")
19632 "\\)\\>"))
19633 (tags (nth 2 org-stuck-projects))
19634 (tags-re (if (member "*" tags)
19635 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
19636 (concat "^\\*+ .*:\\("
19637 (mapconcat 'identity tags "\\|")
19638 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
19639 (gen-re (nth 3 org-stuck-projects))
19640 (re-list
19641 (delq nil
19642 (list
19643 (if todo todo-re)
19644 (if tags tags-re)
19645 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
19646 gen-re)))))
19647 (setq org-agenda-skip-regexp
19648 (if re-list
19649 (mapconcat 'identity re-list "\\|")
19650 (error "No information how to identify unstuck projects")))
19651 (org-tags-view nil matcher)
19652 (with-current-buffer org-agenda-buffer-name
19653 (setq org-agenda-redo-command
19654 '(org-agenda-list-stuck-projects
19655 (or current-prefix-arg org-last-arg))))))
19656
19657 ;;; Diary integration
19658
19659 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
19660
19661 (defun org-get-entries-from-diary (date)
19662 "Get the (Emacs Calendar) diary entries for DATE."
19663 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
19664 (diary-display-hook '(fancy-diary-display))
19665 (pop-up-frames nil)
19666 (list-diary-entries-hook
19667 (cons 'org-diary-default-entry list-diary-entries-hook))
19668 (diary-file-name-prefix-function nil) ; turn this feature off
19669 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
19670 entries
19671 (org-disable-agenda-to-diary t))
19672 (save-excursion
19673 (save-window-excursion
19674 (funcall (if (fboundp 'diary-list-entries)
19675 'diary-list-entries 'list-diary-entries)
19676 date 1)))
19677 (if (not (get-buffer fancy-diary-buffer))
19678 (setq entries nil)
19679 (with-current-buffer fancy-diary-buffer
19680 (setq buffer-read-only nil)
19681 (if (zerop (buffer-size))
19682 ;; No entries
19683 (setq entries nil)
19684 ;; Omit the date and other unnecessary stuff
19685 (org-agenda-cleanup-fancy-diary)
19686 ;; Add prefix to each line and extend the text properties
19687 (if (zerop (buffer-size))
19688 (setq entries nil)
19689 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
19690 (set-buffer-modified-p nil)
19691 (kill-buffer fancy-diary-buffer)))
19692 (when entries
19693 (setq entries (org-split-string entries "\n"))
19694 (setq entries
19695 (mapcar
19696 (lambda (x)
19697 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
19698 ;; Extend the text properties to the beginning of the line
19699 (org-add-props x (text-properties-at (1- (length x)) x)
19700 'type "diary" 'date date))
19701 entries)))))
19702
19703 (defun org-agenda-cleanup-fancy-diary ()
19704 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
19705 This gets rid of the date, the underline under the date, and
19706 the dummy entry installed by `org-mode' to ensure non-empty diary for each
19707 date. It also removes lines that contain only whitespace."
19708 (goto-char (point-min))
19709 (if (looking-at ".*?:[ \t]*")
19710 (progn
19711 (replace-match "")
19712 (re-search-forward "\n=+$" nil t)
19713 (replace-match "")
19714 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
19715 (re-search-forward "\n=+$" nil t)
19716 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
19717 (goto-char (point-min))
19718 (while (re-search-forward "^ +\n" nil t)
19719 (replace-match ""))
19720 (goto-char (point-min))
19721 (if (re-search-forward "^Org-mode dummy\n?" nil t)
19722 (replace-match "")))
19723
19724 ;; Make sure entries from the diary have the right text properties.
19725 (eval-after-load "diary-lib"
19726 '(if (boundp 'diary-modify-entry-list-string-function)
19727 ;; We can rely on the hook, nothing to do
19728 nil
19729 ;; Hook not avaiable, must use advice to make this work
19730 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
19731 "Make the position visible."
19732 (if (and org-disable-agenda-to-diary ;; called from org-agenda
19733 (stringp string)
19734 buffer-file-name)
19735 (setq string (org-modify-diary-entry-string string))))))
19736
19737 (defun org-modify-diary-entry-string (string)
19738 "Add text properties to string, allowing org-mode to act on it."
19739 (org-add-props string nil
19740 'mouse-face 'highlight
19741 'keymap org-agenda-keymap
19742 'help-echo (if buffer-file-name
19743 (format "mouse-2 or RET jump to diary file %s"
19744 (abbreviate-file-name buffer-file-name))
19745 "")
19746 'org-agenda-diary-link t
19747 'org-marker (org-agenda-new-marker (point-at-bol))))
19748
19749 (defun org-diary-default-entry ()
19750 "Add a dummy entry to the diary.
19751 Needed to avoid empty dates which mess up holiday display."
19752 ;; Catch the error if dealing with the new add-to-diary-alist
19753 (when org-disable-agenda-to-diary
19754 (condition-case nil
19755 (add-to-diary-list original-date "Org-mode dummy" "")
19756 (error
19757 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
19758
19759 ;;;###autoload
19760 (defun org-diary (&rest args)
19761 "Return diary information from org-files.
19762 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
19763 It accesses org files and extracts information from those files to be
19764 listed in the diary. The function accepts arguments specifying what
19765 items should be listed. The following arguments are allowed:
19766
19767 :timestamp List the headlines of items containing a date stamp or
19768 date range matching the selected date. Deadlines will
19769 also be listed, on the expiration day.
19770
19771 :sexp List entries resulting from diary-like sexps.
19772
19773 :deadline List any deadlines past due, or due within
19774 `org-deadline-warning-days'. The listing occurs only
19775 in the diary for *today*, not at any other date. If
19776 an entry is marked DONE, it is no longer listed.
19777
19778 :scheduled List all items which are scheduled for the given date.
19779 The diary for *today* also contains items which were
19780 scheduled earlier and are not yet marked DONE.
19781
19782 :todo List all TODO items from the org-file. This may be a
19783 long list - so this is not turned on by default.
19784 Like deadlines, these entries only show up in the
19785 diary for *today*, not at any other date.
19786
19787 The call in the diary file should look like this:
19788
19789 &%%(org-diary) ~/path/to/some/orgfile.org
19790
19791 Use a separate line for each org file to check. Or, if you omit the file name,
19792 all files listed in `org-agenda-files' will be checked automatically:
19793
19794 &%%(org-diary)
19795
19796 If you don't give any arguments (as in the example above), the default
19797 arguments (:deadline :scheduled :timestamp :sexp) are used.
19798 So the example above may also be written as
19799
19800 &%%(org-diary :deadline :timestamp :sexp :scheduled)
19801
19802 The function expects the lisp variables `entry' and `date' to be provided
19803 by the caller, because this is how the calendar works. Don't use this
19804 function from a program - use `org-agenda-get-day-entries' instead."
19805 (org-agenda-maybe-reset-markers)
19806 (org-compile-prefix-format 'agenda)
19807 (org-set-sorting-strategy 'agenda)
19808 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
19809 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
19810 (list entry)
19811 (org-agenda-files t)))
19812 file rtn results)
19813 (org-prepare-agenda-buffers files)
19814 ;; If this is called during org-agenda, don't return any entries to
19815 ;; the calendar. Org Agenda will list these entries itself.
19816 (if org-disable-agenda-to-diary (setq files nil))
19817 (while (setq file (pop files))
19818 (setq rtn (apply 'org-agenda-get-day-entries file date args))
19819 (setq results (append results rtn)))
19820 (if results
19821 (concat (org-finalize-agenda-entries results) "\n"))))
19822
19823 ;;; Agenda entry finders
19824
19825 (defun org-agenda-get-day-entries (file date &rest args)
19826 "Does the work for `org-diary' and `org-agenda'.
19827 FILE is the path to a file to be checked for entries. DATE is date like
19828 the one returned by `calendar-current-date'. ARGS are symbols indicating
19829 which kind of entries should be extracted. For details about these, see
19830 the documentation of `org-diary'."
19831 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
19832 (let* ((org-startup-folded nil)
19833 (org-startup-align-all-tables nil)
19834 (buffer (if (file-exists-p file)
19835 (org-get-agenda-file-buffer file)
19836 (error "No such file %s" file)))
19837 arg results rtn)
19838 (if (not buffer)
19839 ;; If file does not exist, make sure an error message ends up in diary
19840 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
19841 (with-current-buffer buffer
19842 (unless (org-mode-p)
19843 (error "Agenda file %s is not in `org-mode'" file))
19844 (let ((case-fold-search nil))
19845 (save-excursion
19846 (save-restriction
19847 (if org-agenda-restrict
19848 (narrow-to-region org-agenda-restrict-begin
19849 org-agenda-restrict-end)
19850 (widen))
19851 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
19852 (while (setq arg (pop args))
19853 (cond
19854 ((and (eq arg :todo)
19855 (equal date (calendar-current-date)))
19856 (setq rtn (org-agenda-get-todos))
19857 (setq results (append results rtn)))
19858 ((eq arg :timestamp)
19859 (setq rtn (org-agenda-get-blocks))
19860 (setq results (append results rtn))
19861 (setq rtn (org-agenda-get-timestamps))
19862 (setq results (append results rtn)))
19863 ((eq arg :sexp)
19864 (setq rtn (org-agenda-get-sexps))
19865 (setq results (append results rtn)))
19866 ((eq arg :scheduled)
19867 (setq rtn (org-agenda-get-scheduled))
19868 (setq results (append results rtn)))
19869 ((eq arg :closed)
19870 (setq rtn (org-agenda-get-closed))
19871 (setq results (append results rtn)))
19872 ((eq arg :deadline)
19873 (setq rtn (org-agenda-get-deadlines))
19874 (setq results (append results rtn))))))))
19875 results))))
19876
19877 ;; FIXME: this works only if the cursor is *not* at the
19878 ;; beginning of the entry
19879 ;(defun org-entry-is-done-p ()
19880 ; "Is the current entry marked DONE?"
19881 ; (save-excursion
19882 ; (and (re-search-backward "[\r\n]\\*+ " nil t)
19883 ; (looking-at org-nl-done-regexp))))
19884
19885 (defun org-entry-is-todo-p ()
19886 (member (org-get-todo-state) org-not-done-keywords))
19887
19888 (defun org-entry-is-done-p ()
19889 (member (org-get-todo-state) org-done-keywords))
19890
19891 (defun org-get-todo-state ()
19892 (save-excursion
19893 (org-back-to-heading t)
19894 (and (looking-at org-todo-line-regexp)
19895 (match-end 2)
19896 (match-string 2))))
19897
19898 (defun org-at-date-range-p (&optional inactive-ok)
19899 "Is the cursor inside a date range?"
19900 (interactive)
19901 (save-excursion
19902 (catch 'exit
19903 (let ((pos (point)))
19904 (skip-chars-backward "^[<\r\n")
19905 (skip-chars-backward "<[")
19906 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
19907 (>= (match-end 0) pos)
19908 (throw 'exit t))
19909 (skip-chars-backward "^<[\r\n")
19910 (skip-chars-backward "<[")
19911 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
19912 (>= (match-end 0) pos)
19913 (throw 'exit t)))
19914 nil)))
19915
19916 (defun org-agenda-get-todos ()
19917 "Return the TODO information for agenda display."
19918 (let* ((props (list 'face nil
19919 'done-face 'org-done
19920 'org-not-done-regexp org-not-done-regexp
19921 'org-todo-regexp org-todo-regexp
19922 'mouse-face 'highlight
19923 'keymap org-agenda-keymap
19924 'help-echo
19925 (format "mouse-2 or RET jump to org file %s"
19926 (abbreviate-file-name buffer-file-name))))
19927 ;; FIXME: get rid of the \n at some point but watch out
19928 (regexp (concat "^\\*+[ \t]+\\("
19929 (if org-select-this-todo-keyword
19930 (if (equal org-select-this-todo-keyword "*")
19931 org-todo-regexp
19932 (concat "\\<\\("
19933 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
19934 "\\)\\>"))
19935 org-not-done-regexp)
19936 "[^\n\r]*\\)"))
19937 marker priority category tags
19938 ee txt beg end)
19939 (goto-char (point-min))
19940 (while (re-search-forward regexp nil t)
19941 (catch :skip
19942 (save-match-data
19943 (beginning-of-line)
19944 (setq beg (point) end (progn (outline-next-heading) (point)))
19945 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
19946 (re-search-forward org-ts-regexp end t))
19947 (and org-agenda-todo-ignore-scheduled (goto-char beg)
19948 (re-search-forward org-scheduled-time-regexp end t))
19949 (and org-agenda-todo-ignore-deadlines (goto-char beg)
19950 (re-search-forward org-deadline-time-regexp end t)
19951 (org-deadline-close (match-string 1))))
19952 (goto-char (1+ beg))
19953 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
19954 (throw :skip nil)))
19955 (goto-char beg)
19956 (org-agenda-skip)
19957 (goto-char (match-beginning 1))
19958 (setq marker (org-agenda-new-marker (match-beginning 0))
19959 category (org-get-category)
19960 tags (org-get-tags-at (point))
19961 txt (org-format-agenda-item "" (match-string 1) category tags)
19962 priority (1+ (org-get-priority txt)))
19963 (org-add-props txt props
19964 'org-marker marker 'org-hd-marker marker
19965 'priority priority 'org-category category
19966 'type "todo")
19967 (push txt ee)
19968 (if org-agenda-todo-list-sublevels
19969 (goto-char (match-end 1))
19970 (org-end-of-subtree 'invisible))))
19971 (nreverse ee)))
19972
19973 (defconst org-agenda-no-heading-message
19974 "No heading for this item in buffer or region.")
19975
19976 (defun org-agenda-get-timestamps ()
19977 "Return the date stamp information for agenda display."
19978 (let* ((props (list 'face nil
19979 'org-not-done-regexp org-not-done-regexp
19980 'org-todo-regexp org-todo-regexp
19981 'mouse-face 'highlight
19982 'keymap org-agenda-keymap
19983 'help-echo
19984 (format "mouse-2 or RET jump to org file %s"
19985 (abbreviate-file-name buffer-file-name))))
19986 (d1 (calendar-absolute-from-gregorian date))
19987 (remove-re
19988 (concat
19989 (regexp-quote
19990 (format-time-string
19991 "<%Y-%m-%d"
19992 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19993 ".*?>"))
19994 (regexp
19995 (concat
19996 (regexp-quote
19997 (substring
19998 (format-time-string
19999 (car org-time-stamp-formats)
20000 (apply 'encode-time ; DATE bound by calendar
20001 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20002 0 11))
20003 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
20004 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
20005 marker hdmarker deadlinep scheduledp donep tmp priority category
20006 ee txt timestr tags b0 b3 e3)
20007 (goto-char (point-min))
20008 (while (re-search-forward regexp nil t)
20009 (setq b0 (match-beginning 0)
20010 b3 (match-beginning 3) e3 (match-end 3))
20011 (catch :skip
20012 (and (org-at-date-range-p) (throw :skip nil))
20013 (org-agenda-skip)
20014 (if (and (match-end 1)
20015 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
20016 (throw :skip nil))
20017 (if (and e3
20018 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
20019 (throw :skip nil))
20020 (setq marker (org-agenda-new-marker b0)
20021 category (org-get-category b0)
20022 tmp (buffer-substring (max (point-min)
20023 (- b0 org-ds-keyword-length))
20024 b0)
20025 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
20026 deadlinep (string-match org-deadline-regexp tmp)
20027 scheduledp (string-match org-scheduled-regexp tmp)
20028 donep (org-entry-is-done-p))
20029 (if (or scheduledp deadlinep) (throw :skip t))
20030 (if (string-match ">" timestr)
20031 ;; substring should only run to end of time stamp
20032 (setq timestr (substring timestr 0 (match-end 0))))
20033 (save-excursion
20034 (if (re-search-backward "^\\*+ " nil t)
20035 (progn
20036 (goto-char (match-beginning 0))
20037 (setq hdmarker (org-agenda-new-marker)
20038 tags (org-get-tags-at))
20039 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20040 (setq txt (org-format-agenda-item
20041 nil (match-string 1) category tags timestr nil
20042 remove-re)))
20043 (setq txt org-agenda-no-heading-message))
20044 (setq priority (org-get-priority txt))
20045 (org-add-props txt props
20046 'org-marker marker 'org-hd-marker hdmarker)
20047 (org-add-props txt nil 'priority priority
20048 'org-category category 'date date
20049 'type "timestamp")
20050 (push txt ee))
20051 (outline-next-heading)))
20052 (nreverse ee)))
20053
20054 (defun org-agenda-get-sexps ()
20055 "Return the sexp information for agenda display."
20056 (require 'diary-lib)
20057 (let* ((props (list 'face nil
20058 'mouse-face 'highlight
20059 'keymap org-agenda-keymap
20060 'help-echo
20061 (format "mouse-2 or RET jump to org file %s"
20062 (abbreviate-file-name buffer-file-name))))
20063 (regexp "^&?%%(")
20064 marker category ee txt tags entry result beg b sexp sexp-entry)
20065 (goto-char (point-min))
20066 (while (re-search-forward regexp nil t)
20067 (catch :skip
20068 (org-agenda-skip)
20069 (setq beg (match-beginning 0))
20070 (goto-char (1- (match-end 0)))
20071 (setq b (point))
20072 (forward-sexp 1)
20073 (setq sexp (buffer-substring b (point)))
20074 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
20075 (org-trim (match-string 1))
20076 ""))
20077 (setq result (org-diary-sexp-entry sexp sexp-entry date))
20078 (when result
20079 (setq marker (org-agenda-new-marker beg)
20080 category (org-get-category beg))
20081
20082 (if (string-match "\\S-" result)
20083 (setq txt result)
20084 (setq txt "SEXP entry returned empty string"))
20085
20086 (setq txt (org-format-agenda-item
20087 "" txt category tags 'time))
20088 (org-add-props txt props 'org-marker marker)
20089 (org-add-props txt nil
20090 'org-category category 'date date
20091 'type "sexp")
20092 (push txt ee))))
20093 (nreverse ee)))
20094
20095 (defun org-agenda-get-closed ()
20096 "Return the logged TODO entries for agenda display."
20097 (let* ((props (list 'mouse-face 'highlight
20098 'org-not-done-regexp org-not-done-regexp
20099 'org-todo-regexp org-todo-regexp
20100 'keymap org-agenda-keymap
20101 'help-echo
20102 (format "mouse-2 or RET jump to org file %s"
20103 (abbreviate-file-name buffer-file-name))))
20104 (regexp (concat
20105 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
20106 (regexp-quote
20107 (substring
20108 (format-time-string
20109 (car org-time-stamp-formats)
20110 (apply 'encode-time ; DATE bound by calendar
20111 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20112 1 11))))
20113 marker hdmarker priority category tags closedp
20114 ee txt timestr)
20115 (goto-char (point-min))
20116 (while (re-search-forward regexp nil t)
20117 (catch :skip
20118 (org-agenda-skip)
20119 (setq marker (org-agenda-new-marker (match-beginning 0))
20120 closedp (equal (match-string 1) org-closed-string)
20121 category (org-get-category (match-beginning 0))
20122 timestr (buffer-substring (match-beginning 0) (point-at-eol))
20123 ;; donep (org-entry-is-done-p)
20124 )
20125 (if (string-match "\\]" timestr)
20126 ;; substring should only run to end of time stamp
20127 (setq timestr (substring timestr 0 (match-end 0))))
20128 (save-excursion
20129 (if (re-search-backward "^\\*+ " nil t)
20130 (progn
20131 (goto-char (match-beginning 0))
20132 (setq hdmarker (org-agenda-new-marker)
20133 tags (org-get-tags-at))
20134 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20135 (setq txt (org-format-agenda-item
20136 (if closedp "Closed: " "Clocked: ")
20137 (match-string 1) category tags timestr)))
20138 (setq txt org-agenda-no-heading-message))
20139 (setq priority 100000)
20140 (org-add-props txt props
20141 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
20142 'priority priority 'org-category category
20143 'type "closed" 'date date
20144 'undone-face 'org-warning 'done-face 'org-done)
20145 (push txt ee))
20146 (outline-next-heading)))
20147 (nreverse ee)))
20148
20149 (defun org-agenda-get-deadlines ()
20150 "Return the deadline information for agenda display."
20151 (let* ((props (list 'mouse-face 'highlight
20152 'org-not-done-regexp org-not-done-regexp
20153 'org-todo-regexp org-todo-regexp
20154 'keymap org-agenda-keymap
20155 'help-echo
20156 (format "mouse-2 or RET jump to org file %s"
20157 (abbreviate-file-name buffer-file-name))))
20158 (regexp org-deadline-time-regexp)
20159 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20160 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20161 d2 diff dfrac wdays pos pos1 category tags
20162 ee txt head face s upcomingp donep timestr)
20163 (goto-char (point-min))
20164 (while (re-search-forward regexp nil t)
20165 (catch :skip
20166 (org-agenda-skip)
20167 (setq s (match-string 1)
20168 pos (1- (match-beginning 1))
20169 d2 (org-time-string-to-absolute (match-string 1) d1)
20170 diff (- d2 d1)
20171 wdays (org-get-wdays s)
20172 dfrac (/ (* 1.0 (- wdays diff)) wdays)
20173 upcomingp (and todayp (> diff 0)))
20174 ;; When to show a deadline in the calendar:
20175 ;; If the expiration is within wdays warning time.
20176 ;; Past-due deadlines are only shown on the current date
20177 (if (or (and (<= diff wdays)
20178 (and todayp (not org-agenda-only-exact-dates)))
20179 (= diff 0))
20180 (save-excursion
20181 (setq category (org-get-category))
20182 (if (re-search-backward "^\\*+[ \t]+" nil t)
20183 (progn
20184 (goto-char (match-end 0))
20185 (setq pos1 (match-beginning 0))
20186 (setq tags (org-get-tags-at pos1))
20187 (setq head (buffer-substring-no-properties
20188 (point)
20189 (progn (skip-chars-forward "^\r\n")
20190 (point))))
20191 (setq donep (string-match org-looking-at-done-regexp head))
20192 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20193 (setq timestr
20194 (concat (substring s (match-beginning 1)) " "))
20195 (setq timestr 'time))
20196 (if (and donep
20197 (or org-agenda-skip-deadline-if-done
20198 (not (= diff 0))))
20199 (setq txt nil)
20200 (setq txt (org-format-agenda-item
20201 (if (= diff 0)
20202 (car org-agenda-deadline-leaders)
20203 (format (nth 1 org-agenda-deadline-leaders)
20204 diff))
20205 head category tags timestr))))
20206 (setq txt org-agenda-no-heading-message))
20207 (when txt
20208 (setq face (org-agenda-deadline-face dfrac))
20209 (org-add-props txt props
20210 'org-marker (org-agenda-new-marker pos)
20211 'org-hd-marker (org-agenda-new-marker pos1)
20212 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
20213 (org-get-priority txt))
20214 'org-category category
20215 'type (if upcomingp "upcoming-deadline" "deadline")
20216 'date (if upcomingp date d2)
20217 'face (if donep 'org-done face)
20218 'undone-face face 'done-face 'org-done)
20219 (push txt ee))))))
20220 (nreverse ee)))
20221
20222 (defun org-agenda-deadline-face (fraction)
20223 "Return the face to displaying a deadline item.
20224 FRACTION is what fraction of the head-warning time has passed."
20225 (let ((faces org-agenda-deadline-faces) f)
20226 (catch 'exit
20227 (while (setq f (pop faces))
20228 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
20229
20230 (defun org-agenda-get-scheduled ()
20231 "Return the scheduled information for agenda display."
20232 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
20233 'org-todo-regexp org-todo-regexp
20234 'done-face 'org-done
20235 'mouse-face 'highlight
20236 'keymap org-agenda-keymap
20237 'help-echo
20238 (format "mouse-2 or RET jump to org file %s"
20239 (abbreviate-file-name buffer-file-name))))
20240 (regexp org-scheduled-time-regexp)
20241 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20242 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20243 d2 diff pos pos1 category tags
20244 ee txt head pastschedp donep face timestr s)
20245 (goto-char (point-min))
20246 (while (re-search-forward regexp nil t)
20247 (catch :skip
20248 (org-agenda-skip)
20249 (setq s (match-string 1)
20250 pos (1- (match-beginning 1))
20251 d2 (org-time-string-to-absolute (match-string 1) d1)
20252 diff (- d2 d1))
20253 (setq pastschedp (and todayp (< diff 0)))
20254 ;; When to show a scheduled item in the calendar:
20255 ;; If it is on or past the date.
20256 (if (or (and (< diff 0)
20257 (and todayp (not org-agenda-only-exact-dates)))
20258 (= diff 0))
20259 (save-excursion
20260 (setq category (org-get-category))
20261 (if (re-search-backward "^\\*+[ \t]+" nil t)
20262 (progn
20263 (goto-char (match-end 0))
20264 (setq pos1 (match-beginning 0))
20265 (setq tags (org-get-tags-at))
20266 (setq head (buffer-substring-no-properties
20267 (point)
20268 (progn (skip-chars-forward "^\r\n") (point))))
20269 (setq donep (string-match org-looking-at-done-regexp head))
20270 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20271 (setq timestr
20272 (concat (substring s (match-beginning 1)) " "))
20273 (setq timestr 'time))
20274 (if (and donep
20275 (or org-agenda-skip-scheduled-if-done
20276 (not (= diff 0))))
20277 (setq txt nil)
20278 (setq txt (org-format-agenda-item
20279 (if (= diff 0)
20280 (car org-agenda-scheduled-leaders)
20281 (format (nth 1 org-agenda-scheduled-leaders)
20282 (- 1 diff)))
20283 head category tags timestr))))
20284 (setq txt org-agenda-no-heading-message))
20285 (when txt
20286 (setq face (if pastschedp
20287 'org-scheduled-previously
20288 'org-scheduled-today))
20289 (org-add-props txt props
20290 'undone-face face
20291 'face (if donep 'org-done face)
20292 'org-marker (org-agenda-new-marker pos)
20293 'org-hd-marker (org-agenda-new-marker pos1)
20294 'type (if pastschedp "past-scheduled" "scheduled")
20295 'date (if pastschedp d2 date)
20296 'priority (+ 94 (- 5 diff) (org-get-priority txt))
20297 'org-category category)
20298 (push txt ee))))))
20299 (nreverse ee)))
20300
20301 (defun org-agenda-get-blocks ()
20302 "Return the date-range information for agenda display."
20303 (let* ((props (list 'face nil
20304 'org-not-done-regexp org-not-done-regexp
20305 'org-todo-regexp org-todo-regexp
20306 'mouse-face 'highlight
20307 'keymap org-agenda-keymap
20308 'help-echo
20309 (format "mouse-2 or RET jump to org file %s"
20310 (abbreviate-file-name buffer-file-name))))
20311 (regexp org-tr-regexp)
20312 (d0 (calendar-absolute-from-gregorian date))
20313 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
20314 (goto-char (point-min))
20315 (while (re-search-forward regexp nil t)
20316 (catch :skip
20317 (org-agenda-skip)
20318 (setq pos (point))
20319 (setq timestr (match-string 0)
20320 s1 (match-string 1)
20321 s2 (match-string 2)
20322 d1 (time-to-days (org-time-string-to-time s1))
20323 d2 (time-to-days (org-time-string-to-time s2)))
20324 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
20325 ;; Only allow days between the limits, because the normal
20326 ;; date stamps will catch the limits.
20327 (save-excursion
20328 (setq marker (org-agenda-new-marker (point)))
20329 (setq category (org-get-category))
20330 (if (re-search-backward "^\\*+ " nil t)
20331 (progn
20332 (goto-char (match-beginning 0))
20333 (setq hdmarker (org-agenda-new-marker (point)))
20334 (setq tags (org-get-tags-at))
20335 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20336 (setq txt (org-format-agenda-item
20337 (format (if (= d1 d2) "" "(%d/%d): ")
20338 (1+ (- d0 d1)) (1+ (- d2 d1)))
20339 (match-string 1) category tags
20340 (if (= d0 d1) timestr))))
20341 (setq txt org-agenda-no-heading-message))
20342 (org-add-props txt props
20343 'org-marker marker 'org-hd-marker hdmarker
20344 'type "block" 'date date
20345 'priority (org-get-priority txt) 'org-category category)
20346 (push txt ee)))
20347 (goto-char pos)))
20348 ;; Sort the entries by expiration date.
20349 (nreverse ee)))
20350
20351 ;;; Agenda presentation and sorting
20352
20353 (defconst org-plain-time-of-day-regexp
20354 (concat
20355 "\\(\\<[012]?[0-9]"
20356 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20357 "\\(--?"
20358 "\\(\\<[012]?[0-9]"
20359 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20360 "\\)?")
20361 "Regular expression to match a plain time or time range.
20362 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20363 groups carry important information:
20364 0 the full match
20365 1 the first time, range or not
20366 8 the second time, if it is a range.")
20367
20368 (defconst org-plain-time-extension-regexp
20369 (concat
20370 "\\(\\<[012]?[0-9]"
20371 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20372 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
20373 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
20374 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20375 groups carry important information:
20376 0 the full match
20377 7 hours of duration
20378 9 minutes of duration")
20379
20380 (defconst org-stamp-time-of-day-regexp
20381 (concat
20382 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
20383 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
20384 "\\(--?"
20385 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
20386 "Regular expression to match a timestamp time or time range.
20387 After a match, the following groups carry important information:
20388 0 the full match
20389 1 date plus weekday, for backreferencing to make sure both times on same day
20390 2 the first time, range or not
20391 4 the second time, if it is a range.")
20392
20393 (defvar org-prefix-has-time nil
20394 "A flag, set by `org-compile-prefix-format'.
20395 The flag is set if the currently compiled format contains a `%t'.")
20396 (defvar org-prefix-has-tag nil
20397 "A flag, set by `org-compile-prefix-format'.
20398 The flag is set if the currently compiled format contains a `%T'.")
20399
20400 (defun org-format-agenda-item (extra txt &optional category tags dotime
20401 noprefix remove-re)
20402 "Format TXT to be inserted into the agenda buffer.
20403 In particular, it adds the prefix and corresponding text properties. EXTRA
20404 must be a string and replaces the `%s' specifier in the prefix format.
20405 CATEGORY (string, symbol or nil) may be used to overrule the default
20406 category taken from local variable or file name. It will replace the `%c'
20407 specifier in the format. DOTIME, when non-nil, indicates that a
20408 time-of-day should be extracted from TXT for sorting of this entry, and for
20409 the `%t' specifier in the format. When DOTIME is a string, this string is
20410 searched for a time before TXT is. NOPREFIX is a flag and indicates that
20411 only the correctly processes TXT should be returned - this is used by
20412 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
20413 Any match of REMOVE-RE will be removed from TXT."
20414 (save-match-data
20415 ;; Diary entries sometimes have extra whitespace at the beginning
20416 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
20417 (let* ((category (or category
20418 org-category
20419 (if buffer-file-name
20420 (file-name-sans-extension
20421 (file-name-nondirectory buffer-file-name))
20422 "")))
20423 (tag (if tags (nth (1- (length tags)) tags) ""))
20424 time ; time and tag are needed for the eval of the prefix format
20425 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
20426 (time-of-day (and dotime (org-get-time-of-day ts)))
20427 stamp plain s0 s1 s2 rtn srp)
20428 (when (and dotime time-of-day org-prefix-has-time)
20429 ;; Extract starting and ending time and move them to prefix
20430 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
20431 (setq plain (string-match org-plain-time-of-day-regexp ts)))
20432 (setq s0 (match-string 0 ts)
20433 srp (and stamp (match-end 3))
20434 s1 (match-string (if plain 1 2) ts)
20435 s2 (match-string (if plain 8 (if srp 4 6)) ts))
20436
20437 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
20438 ;; them, we might want to remove them there to avoid duplication.
20439 ;; The user can turn this off with a variable.
20440 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
20441 (string-match (concat (regexp-quote s0) " *") txt)
20442 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
20443 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
20444 (= (match-beginning 0) 0)
20445 t))
20446 (setq txt (replace-match "" nil nil txt))))
20447 ;; Normalize the time(s) to 24 hour
20448 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
20449 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
20450
20451 (when (and s1 (not s2) org-agenda-default-appointment-duration
20452 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
20453 (let ((m (+ (string-to-number (match-string 2 s1))
20454 (* 60 (string-to-number (match-string 1 s1)))
20455 org-agenda-default-appointment-duration))
20456 h)
20457 (setq h (/ m 60) m (- m (* h 60)))
20458 (setq s2 (format "%02d:%02d" h m))))
20459
20460 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
20461 txt)
20462 ;; Tags are in the string
20463 (if (or (eq org-agenda-remove-tags t)
20464 (and org-agenda-remove-tags
20465 org-prefix-has-tag))
20466 (setq txt (replace-match "" t t txt))
20467 (setq txt (replace-match
20468 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
20469 (match-string 2 txt))
20470 t t txt))))
20471
20472 (when remove-re
20473 (while (string-match remove-re txt)
20474 (setq txt (replace-match "" t t txt))))
20475
20476 ;; Create the final string
20477 (if noprefix
20478 (setq rtn txt)
20479 ;; Prepare the variables needed in the eval of the compiled format
20480 (setq time (cond (s2 (concat s1 "-" s2))
20481 (s1 (concat s1 "......"))
20482 (t ""))
20483 extra (or extra "")
20484 category (if (symbolp category) (symbol-name category) category))
20485 ;; Evaluate the compiled format
20486 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
20487
20488 ;; And finally add the text properties
20489 (org-add-props rtn nil
20490 'org-category (downcase category) 'tags tags
20491 'org-highest-priority org-highest-priority
20492 'org-lowest-priority org-lowest-priority
20493 'prefix-length (- (length rtn) (length txt))
20494 'time-of-day time-of-day
20495 'txt txt
20496 'time time
20497 'extra extra
20498 'dotime dotime))))
20499
20500 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
20501 (defvar org-agenda-sorting-strategy-selected nil)
20502
20503 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
20504 (catch 'exit
20505 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
20506 ((and todayp (member 'today (car org-agenda-time-grid))))
20507 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
20508 ((member 'weekly (car org-agenda-time-grid)))
20509 (t (throw 'exit list)))
20510 (let* ((have (delq nil (mapcar
20511 (lambda (x) (get-text-property 1 'time-of-day x))
20512 list)))
20513 (string (nth 1 org-agenda-time-grid))
20514 (gridtimes (nth 2 org-agenda-time-grid))
20515 (req (car org-agenda-time-grid))
20516 (remove (member 'remove-match req))
20517 new time)
20518 (if (and (member 'require-timed req) (not have))
20519 ;; don't show empty grid
20520 (throw 'exit list))
20521 (while (setq time (pop gridtimes))
20522 (unless (and remove (member time have))
20523 (setq time (int-to-string time))
20524 (push (org-format-agenda-item
20525 nil string "" nil
20526 (concat (substring time 0 -2) ":" (substring time -2)))
20527 new)
20528 (put-text-property
20529 1 (length (car new)) 'face 'org-time-grid (car new))))
20530 (if (member 'time-up org-agenda-sorting-strategy-selected)
20531 (append new list)
20532 (append list new)))))
20533
20534 (defun org-compile-prefix-format (key)
20535 "Compile the prefix format into a Lisp form that can be evaluated.
20536 The resulting form is returned and stored in the variable
20537 `org-prefix-format-compiled'."
20538 (setq org-prefix-has-time nil org-prefix-has-tag nil)
20539 (let ((s (cond
20540 ((stringp org-agenda-prefix-format)
20541 org-agenda-prefix-format)
20542 ((assq key org-agenda-prefix-format)
20543 (cdr (assq key org-agenda-prefix-format)))
20544 (t " %-12:c%?-12t% s")))
20545 (start 0)
20546 varform vars var e c f opt)
20547 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
20548 s start)
20549 (setq var (cdr (assoc (match-string 4 s)
20550 '(("c" . category) ("t" . time) ("s" . extra)
20551 ("T" . tag))))
20552 c (or (match-string 3 s) "")
20553 opt (match-beginning 1)
20554 start (1+ (match-beginning 0)))
20555 (if (equal var 'time) (setq org-prefix-has-time t))
20556 (if (equal var 'tag) (setq org-prefix-has-tag t))
20557 (setq f (concat "%" (match-string 2 s) "s"))
20558 (if opt
20559 (setq varform
20560 `(if (equal "" ,var)
20561 ""
20562 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
20563 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
20564 (setq s (replace-match "%s" t nil s))
20565 (push varform vars))
20566 (setq vars (nreverse vars))
20567 (setq org-prefix-format-compiled `(format ,s ,@vars))))
20568
20569 (defun org-set-sorting-strategy (key)
20570 (if (symbolp (car org-agenda-sorting-strategy))
20571 ;; the old format
20572 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
20573 (setq org-agenda-sorting-strategy-selected
20574 (or (cdr (assq key org-agenda-sorting-strategy))
20575 (cdr (assq 'agenda org-agenda-sorting-strategy))
20576 '(time-up category-keep priority-down)))))
20577
20578 (defun org-get-time-of-day (s &optional string mod24)
20579 "Check string S for a time of day.
20580 If found, return it as a military time number between 0 and 2400.
20581 If not found, return nil.
20582 The optional STRING argument forces conversion into a 5 character wide string
20583 HH:MM."
20584 (save-match-data
20585 (when
20586 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
20587 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
20588 (let* ((h (string-to-number (match-string 1 s)))
20589 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
20590 (ampm (if (match-end 4) (downcase (match-string 4 s))))
20591 (am-p (equal ampm "am"))
20592 (h1 (cond ((not ampm) h)
20593 ((= h 12) (if am-p 0 12))
20594 (t (+ h (if am-p 0 12)))))
20595 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
20596 (mod h1 24) h1))
20597 (t0 (+ (* 100 h2) m))
20598 (t1 (concat (if (>= h1 24) "+" " ")
20599 (if (< t0 100) "0" "")
20600 (if (< t0 10) "0" "")
20601 (int-to-string t0))))
20602 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
20603
20604 (defun org-finalize-agenda-entries (list &optional nosort)
20605 "Sort and concatenate the agenda items."
20606 (setq list (mapcar 'org-agenda-highlight-todo list))
20607 (if nosort
20608 list
20609 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
20610
20611 (defun org-agenda-highlight-todo (x)
20612 (let (re pl)
20613 (if (eq x 'line)
20614 (save-excursion
20615 (beginning-of-line 1)
20616 (setq re (get-text-property (point) 'org-todo-regexp))
20617 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
20618 (and (looking-at (concat "[ \t]*\\.*" re))
20619 (add-text-properties (match-beginning 0) (match-end 0)
20620 (list 'face (org-get-todo-face 0)))))
20621 (setq re (concat (get-text-property 0 'org-todo-regexp x))
20622 pl (get-text-property 0 'prefix-length x))
20623 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
20624 (add-text-properties
20625 (or (match-end 1) (match-end 0)) (match-end 0)
20626 (list 'face (org-get-todo-face (match-string 2 x)))
20627 x))
20628 x)))
20629
20630 (defsubst org-cmp-priority (a b)
20631 "Compare the priorities of string A and B."
20632 (let ((pa (or (get-text-property 1 'priority a) 0))
20633 (pb (or (get-text-property 1 'priority b) 0)))
20634 (cond ((> pa pb) +1)
20635 ((< pa pb) -1)
20636 (t nil))))
20637
20638 (defsubst org-cmp-category (a b)
20639 "Compare the string values of categories of strings A and B."
20640 (let ((ca (or (get-text-property 1 'org-category a) ""))
20641 (cb (or (get-text-property 1 'org-category b) "")))
20642 (cond ((string-lessp ca cb) -1)
20643 ((string-lessp cb ca) +1)
20644 (t nil))))
20645
20646 (defsubst org-cmp-tag (a b)
20647 "Compare the string values of categories of strings A and B."
20648 (let ((ta (car (last (get-text-property 1 'tags a))))
20649 (tb (car (last (get-text-property 1 'tags b)))))
20650 (cond ((not ta) +1)
20651 ((not tb) -1)
20652 ((string-lessp ta tb) -1)
20653 ((string-lessp tb ta) +1)
20654 (t nil))))
20655
20656 (defsubst org-cmp-time (a b)
20657 "Compare the time-of-day values of strings A and B."
20658 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
20659 (ta (or (get-text-property 1 'time-of-day a) def))
20660 (tb (or (get-text-property 1 'time-of-day b) def)))
20661 (cond ((< ta tb) -1)
20662 ((< tb ta) +1)
20663 (t nil))))
20664
20665 (defun org-entries-lessp (a b)
20666 "Predicate for sorting agenda entries."
20667 ;; The following variables will be used when the form is evaluated.
20668 ;; So even though the compiler complains, keep them.
20669 (let* ((time-up (org-cmp-time a b))
20670 (time-down (if time-up (- time-up) nil))
20671 (priority-up (org-cmp-priority a b))
20672 (priority-down (if priority-up (- priority-up) nil))
20673 (category-up (org-cmp-category a b))
20674 (category-down (if category-up (- category-up) nil))
20675 (category-keep (if category-up +1 nil))
20676 (tag-up (org-cmp-tag a b))
20677 (tag-down (if tag-up (- tag-up) nil)))
20678 (cdr (assoc
20679 (eval (cons 'or org-agenda-sorting-strategy-selected))
20680 '((-1 . t) (1 . nil) (nil . nil))))))
20681
20682 ;;; Agenda commands
20683
20684 (defun org-agenda-check-type (error &rest types)
20685 "Check if agenda buffer is of allowed type.
20686 If ERROR is non-nil, throw an error, otherwise just return nil."
20687 (if (memq org-agenda-type types)
20688 t
20689 (if error
20690 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
20691 nil)))
20692
20693 (defun org-agenda-quit ()
20694 "Exit agenda by removing the window or the buffer."
20695 (interactive)
20696 (let ((buf (current-buffer)))
20697 (if (not (one-window-p)) (delete-window))
20698 (kill-buffer buf)
20699 (org-agenda-maybe-reset-markers 'force)
20700 (org-columns-remove-overlays))
20701 ;; Maybe restore the pre-agenda window configuration.
20702 (and org-agenda-restore-windows-after-quit
20703 (not (eq org-agenda-window-setup 'other-frame))
20704 org-pre-agenda-window-conf
20705 (set-window-configuration org-pre-agenda-window-conf)))
20706
20707 (defun org-agenda-exit ()
20708 "Exit agenda by removing the window or the buffer.
20709 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
20710 Org-mode buffers visited directly by the user will not be touched."
20711 (interactive)
20712 (org-release-buffers org-agenda-new-buffers)
20713 (setq org-agenda-new-buffers nil)
20714 (org-agenda-quit))
20715
20716 (defun org-save-all-org-buffers ()
20717 "Save all Org-mode buffers without user confirmation."
20718 (interactive)
20719 (message "Saving all Org-mode buffers...")
20720 (save-some-buffers t 'org-mode-p)
20721 (message "Saving all Org-mode buffers... done"))
20722
20723 (defun org-agenda-redo ()
20724 "Rebuild Agenda.
20725 When this is the global TODO list, a prefix argument will be interpreted."
20726 (interactive)
20727 (let* ((org-agenda-keep-modes t)
20728 (line (org-current-line))
20729 (window-line (- line (org-current-line (window-start))))
20730 (lprops (get 'org-agenda-redo-command 'org-lprops)))
20731 (message "Rebuilding agenda buffer...")
20732 (org-let lprops '(eval org-agenda-redo-command))
20733 (setq org-agenda-undo-list nil
20734 org-agenda-pending-undo-list nil)
20735 (message "Rebuilding agenda buffer...done")
20736 (goto-line line)
20737 (recenter window-line)))
20738
20739 (defun org-agenda-goto-date (date)
20740 "Jump to DATE in agenda."
20741 (interactive (list (org-read-date)))
20742 (org-agenda-list nil date))
20743
20744 (defun org-agenda-goto-today ()
20745 "Go to today."
20746 (interactive)
20747 (org-agenda-check-type t 'timeline 'agenda)
20748 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
20749 (cond
20750 (tdpos (goto-char tdpos))
20751 ((eq org-agenda-type 'agenda)
20752 (let* ((sd (time-to-days (current-time)))
20753 (comp (org-agenda-compute-time-span sd org-agenda-span))
20754 (org-agenda-overriding-arguments org-agenda-last-arguments))
20755 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
20756 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
20757 (org-agenda-redo)
20758 (org-agenda-find-same-or-today-or-agenda)))
20759 (t (error "Cannot find today")))))
20760
20761 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
20762 (goto-char
20763 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
20764 (text-property-any (point-min) (point-max) 'org-today t)
20765 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
20766 (point-min))))
20767
20768 (defun org-agenda-later (arg)
20769 "Go forward in time by thee current span.
20770 With prefix ARG, go forward that many times the current span."
20771 (interactive "p")
20772 (org-agenda-check-type t 'agenda)
20773 (let* ((span org-agenda-span)
20774 (sd org-starting-day)
20775 (greg (calendar-gregorian-from-absolute sd))
20776 (cnt (get-text-property (point) 'org-day-cnt))
20777 greg2 nd)
20778 (cond
20779 ((eq span 'day)
20780 (setq sd (+ arg sd) nd 1))
20781 ((eq span 'week)
20782 (setq sd (+ (* 7 arg) sd) nd 7))
20783 ((eq span 'month)
20784 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
20785 sd (calendar-absolute-from-gregorian greg2))
20786 (setcar greg2 (1+ (car greg2)))
20787 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
20788 ((eq span 'year)
20789 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
20790 sd (calendar-absolute-from-gregorian greg2))
20791 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
20792 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
20793 (let ((org-agenda-overriding-arguments
20794 (list (car org-agenda-last-arguments) sd nd t)))
20795 (org-agenda-redo)
20796 (org-agenda-find-same-or-today-or-agenda cnt))))
20797
20798 (defun org-agenda-earlier (arg)
20799 "Go backward in time by the current span.
20800 With prefix ARG, go backward that many times the current span."
20801 (interactive "p")
20802 (org-agenda-later (- arg)))
20803
20804 (defun org-agenda-day-view ()
20805 "Switch to daily view for agenda."
20806 (interactive)
20807 (setq org-agenda-ndays 1)
20808 (org-agenda-change-time-span 'day))
20809 (defun org-agenda-week-view ()
20810 "Switch to daily view for agenda."
20811 (interactive)
20812 (setq org-agenda-ndays 7)
20813 (org-agenda-change-time-span 'week))
20814 (defun org-agenda-month-view ()
20815 "Switch to daily view for agenda."
20816 (interactive)
20817 (org-agenda-change-time-span 'month))
20818 (defun org-agenda-year-view ()
20819 "Switch to daily view for agenda."
20820 (interactive)
20821 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
20822 (org-agenda-change-time-span 'year)
20823 (error "Abort")))
20824
20825 (defun org-agenda-change-time-span (span)
20826 "Change the agenda view to SPAN.
20827 SPAN may be `day', `week', `month', `year'."
20828 (org-agenda-check-type t 'agenda)
20829 (if (equal org-agenda-span span)
20830 (error "Viewing span is already \"%s\"" span))
20831 (let* ((sd (or (get-text-property (point) 'day)
20832 org-starting-day))
20833 (computed (org-agenda-compute-time-span sd span))
20834 (org-agenda-overriding-arguments
20835 (list (car org-agenda-last-arguments)
20836 (car computed) (cdr computed) t)))
20837 (org-agenda-redo)
20838 (org-agenda-find-same-or-today-or-agenda))
20839 (org-agenda-set-mode-name)
20840 (message "Switched to %s view" span))
20841
20842 (defun org-agenda-compute-time-span (sd span)
20843 "Compute starting date and number of days for agenda.
20844 SPAN may be `day', `week', `month', `year'. The return value
20845 is a cons cell with the starting date and the number of days,
20846 so that the date SD will be in that range."
20847 (let* ((greg (calendar-gregorian-from-absolute sd))
20848 nd)
20849 (cond
20850 ((eq span 'day)
20851 (setq nd 1))
20852 ((eq span 'week)
20853 (let* ((nt (calendar-day-of-week
20854 (calendar-gregorian-from-absolute sd)))
20855 (d (if org-agenda-start-on-weekday
20856 (- nt org-agenda-start-on-weekday)
20857 0)))
20858 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
20859 (setq nd 7)))
20860 ((eq span 'month)
20861 (setq sd (calendar-absolute-from-gregorian
20862 (list (car greg) 1 (nth 2 greg)))
20863 nd (- (calendar-absolute-from-gregorian
20864 (list (1+ (car greg)) 1 (nth 2 greg)))
20865 sd)))
20866 ((eq span 'year)
20867 (setq sd (calendar-absolute-from-gregorian
20868 (list 1 1 (nth 2 greg)))
20869 nd (- (calendar-absolute-from-gregorian
20870 (list 1 1 (1+ (nth 2 greg))))
20871 sd))))
20872 (cons sd nd)))
20873
20874 ;; FIXME: does not work if user makes date format that starts with a blank
20875 (defun org-agenda-next-date-line (&optional arg)
20876 "Jump to the next line indicating a date in agenda buffer."
20877 (interactive "p")
20878 (org-agenda-check-type t 'agenda 'timeline)
20879 (beginning-of-line 1)
20880 (if (looking-at "^\\S-") (forward-char 1))
20881 (if (not (re-search-forward "^\\S-" nil t arg))
20882 (progn
20883 (backward-char 1)
20884 (error "No next date after this line in this buffer")))
20885 (goto-char (match-beginning 0)))
20886
20887 (defun org-agenda-previous-date-line (&optional arg)
20888 "Jump to the previous line indicating a date in agenda buffer."
20889 (interactive "p")
20890 (org-agenda-check-type t 'agenda 'timeline)
20891 (beginning-of-line 1)
20892 (if (not (re-search-backward "^\\S-" nil t arg))
20893 (error "No previous date before this line in this buffer")))
20894
20895 ;; Initialize the highlight
20896 (defvar org-hl (org-make-overlay 1 1))
20897 (org-overlay-put org-hl 'face 'highlight)
20898
20899 (defun org-highlight (begin end &optional buffer)
20900 "Highlight a region with overlay."
20901 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
20902 org-hl begin end (or buffer (current-buffer))))
20903
20904 (defun org-unhighlight ()
20905 "Detach overlay INDEX."
20906 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
20907
20908 ;; FIXME this is currently not used.
20909 (defun org-highlight-until-next-command (beg end &optional buffer)
20910 (org-highlight beg end buffer)
20911 (add-hook 'pre-command-hook 'org-unhighlight-once))
20912 (defun org-unhighlight-once ()
20913 (remove-hook 'pre-command-hook 'org-unhighlight-once)
20914 (org-unhighlight))
20915
20916 (defun org-agenda-follow-mode ()
20917 "Toggle follow mode in an agenda buffer."
20918 (interactive)
20919 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
20920 (org-agenda-set-mode-name)
20921 (message "Follow mode is %s"
20922 (if org-agenda-follow-mode "on" "off")))
20923
20924 (defun org-agenda-log-mode ()
20925 "Toggle log mode in an agenda buffer."
20926 (interactive)
20927 (org-agenda-check-type t 'agenda 'timeline)
20928 (setq org-agenda-show-log (not org-agenda-show-log))
20929 (org-agenda-set-mode-name)
20930 (org-agenda-redo)
20931 (message "Log mode is %s"
20932 (if org-agenda-show-log "on" "off")))
20933
20934 (defun org-agenda-toggle-diary ()
20935 "Toggle diary inclusion in an agenda buffer."
20936 (interactive)
20937 (org-agenda-check-type t 'agenda)
20938 (setq org-agenda-include-diary (not org-agenda-include-diary))
20939 (org-agenda-redo)
20940 (org-agenda-set-mode-name)
20941 (message "Diary inclusion turned %s"
20942 (if org-agenda-include-diary "on" "off")))
20943
20944 (defun org-agenda-toggle-time-grid ()
20945 "Toggle time grid in an agenda buffer."
20946 (interactive)
20947 (org-agenda-check-type t 'agenda)
20948 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
20949 (org-agenda-redo)
20950 (org-agenda-set-mode-name)
20951 (message "Time-grid turned %s"
20952 (if org-agenda-use-time-grid "on" "off")))
20953
20954 (defun org-agenda-set-mode-name ()
20955 "Set the mode name to indicate all the small mode settings."
20956 (setq mode-name
20957 (concat "Org-Agenda"
20958 (if (equal org-agenda-ndays 1) " Day" "")
20959 (if (equal org-agenda-ndays 7) " Week" "")
20960 (if org-agenda-follow-mode " Follow" "")
20961 (if org-agenda-include-diary " Diary" "")
20962 (if org-agenda-use-time-grid " Grid" "")
20963 (if org-agenda-show-log " Log" "")))
20964 (force-mode-line-update))
20965
20966 (defun org-agenda-post-command-hook ()
20967 (and (eolp) (not (bolp)) (backward-char 1))
20968 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20969 (if (and org-agenda-follow-mode
20970 (get-text-property (point) 'org-marker))
20971 (org-agenda-show)))
20972
20973 (defun org-agenda-show-priority ()
20974 "Show the priority of the current item.
20975 This priority is composed of the main priority given with the [#A] cookies,
20976 and by additional input from the age of a schedules or deadline entry."
20977 (interactive)
20978 (let* ((pri (get-text-property (point-at-bol) 'priority)))
20979 (message "Priority is %d" (if pri pri -1000))))
20980
20981 (defun org-agenda-show-tags ()
20982 "Show the tags applicable to the current item."
20983 (interactive)
20984 (let* ((tags (get-text-property (point-at-bol) 'tags)))
20985 (if tags
20986 (message "Tags are :%s:"
20987 (org-no-properties (mapconcat 'identity tags ":")))
20988 (message "No tags associated with this line"))))
20989
20990 (defun org-agenda-goto (&optional highlight)
20991 "Go to the Org-mode file which contains the item at point."
20992 (interactive)
20993 (let* ((marker (or (get-text-property (point) 'org-marker)
20994 (org-agenda-error)))
20995 (buffer (marker-buffer marker))
20996 (pos (marker-position marker)))
20997 (switch-to-buffer-other-window buffer)
20998 (widen)
20999 (goto-char pos)
21000 (when (org-mode-p)
21001 (org-show-context 'agenda)
21002 (save-excursion
21003 (and (outline-next-heading)
21004 (org-flag-heading nil)))) ; show the next heading
21005 (run-hooks 'org-agenda-after-show-hook)
21006 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
21007
21008 (defvar org-agenda-after-show-hook nil
21009 "Normal hook run after an item has been shown from the agenda.
21010 Point is in the buffer where the item originated.")
21011
21012 (defun org-agenda-kill ()
21013 "Kill the entry or subtree belonging to the current agenda entry."
21014 (interactive)
21015 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
21016 (let* ((marker (or (get-text-property (point) 'org-marker)
21017 (org-agenda-error)))
21018 (buffer (marker-buffer marker))
21019 (pos (marker-position marker))
21020 (type (get-text-property (point) 'type))
21021 dbeg dend (n 0) conf)
21022 (org-with-remote-undo buffer
21023 (with-current-buffer buffer
21024 (save-excursion
21025 (goto-char pos)
21026 (if (and (org-mode-p) (not (member type '("sexp"))))
21027 (setq dbeg (progn (org-back-to-heading t) (point))
21028 dend (org-end-of-subtree t t))
21029 (setq dbeg (point-at-bol)
21030 dend (min (point-max) (1+ (point-at-eol)))))
21031 (goto-char dbeg)
21032 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
21033 (setq conf (or (eq t org-agenda-confirm-kill)
21034 (and (numberp org-agenda-confirm-kill)
21035 (> n org-agenda-confirm-kill))))
21036 (and conf
21037 (not (y-or-n-p
21038 (format "Delete entry with %d lines in buffer \"%s\"? "
21039 n (buffer-name buffer))))
21040 (error "Abort"))
21041 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
21042 (with-current-buffer buffer (delete-region dbeg dend))
21043 (message "Agenda item and source killed"))))
21044
21045 (defun org-agenda-archive ()
21046 "Kill the entry or subtree belonging to the current agenda entry."
21047 (interactive)
21048 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
21049 (let* ((marker (or (get-text-property (point) 'org-marker)
21050 (org-agenda-error)))
21051 (buffer (marker-buffer marker))
21052 (pos (marker-position marker)))
21053 (org-with-remote-undo buffer
21054 (with-current-buffer buffer
21055 (if (org-mode-p)
21056 (save-excursion
21057 (goto-char pos)
21058 (org-remove-subtree-entries-from-agenda)
21059 (org-back-to-heading t)
21060 (org-archive-subtree))
21061 (error "Archiving works only in Org-mode files"))))))
21062
21063 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
21064 "Remove all lines in the agenda that correspond to a given subtree.
21065 The subtree is the one in buffer BUF, starting at BEG and ending at END.
21066 If this information is not given, the function uses the tree at point."
21067 (let ((buf (or buf (current-buffer))) m p)
21068 (save-excursion
21069 (unless (and beg end)
21070 (org-back-to-heading t)
21071 (setq beg (point))
21072 (org-end-of-subtree t)
21073 (setq end (point)))
21074 (set-buffer (get-buffer org-agenda-buffer-name))
21075 (save-excursion
21076 (goto-char (point-max))
21077 (beginning-of-line 1)
21078 (while (not (bobp))
21079 (when (and (setq m (get-text-property (point) 'org-marker))
21080 (equal buf (marker-buffer m))
21081 (setq p (marker-position m))
21082 (>= p beg)
21083 (<= p end))
21084 (let ((inhibit-read-only t))
21085 (delete-region (point-at-bol) (1+ (point-at-eol)))))
21086 (beginning-of-line 0))))))
21087
21088 (defun org-agenda-open-link ()
21089 "Follow the link in the current line, if any."
21090 (interactive)
21091 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
21092 (save-excursion
21093 (save-restriction
21094 (narrow-to-region (point-at-bol) (point-at-eol))
21095 (org-open-at-point))))
21096
21097 (defun org-agenda-copy-local-variable (var)
21098 "Get a variable from a referenced buffer and install it here."
21099 (let ((m (get-text-property (point) 'org-marker)))
21100 (when (and m (buffer-live-p (marker-buffer m)))
21101 (org-set-local var (with-current-buffer (marker-buffer m)
21102 (symbol-value var))))))
21103
21104 (defun org-agenda-switch-to (&optional delete-other-windows)
21105 "Go to the Org-mode file which contains the item at point."
21106 (interactive)
21107 (let* ((marker (or (get-text-property (point) 'org-marker)
21108 (org-agenda-error)))
21109 (buffer (marker-buffer marker))
21110 (pos (marker-position marker)))
21111 (switch-to-buffer buffer)
21112 (and delete-other-windows (delete-other-windows))
21113 (widen)
21114 (goto-char pos)
21115 (when (org-mode-p)
21116 (org-show-context 'agenda)
21117 (save-excursion
21118 (and (outline-next-heading)
21119 (org-flag-heading nil)))))) ; show the next heading
21120
21121 (defun org-agenda-goto-mouse (ev)
21122 "Go to the Org-mode file which contains the item at the mouse click."
21123 (interactive "e")
21124 (mouse-set-point ev)
21125 (org-agenda-goto))
21126
21127 (defun org-agenda-show ()
21128 "Display the Org-mode file which contains the item at point."
21129 (interactive)
21130 (let ((win (selected-window)))
21131 (org-agenda-goto t)
21132 (select-window win)))
21133
21134 (defun org-agenda-recenter (arg)
21135 "Display the Org-mode file which contains the item at point and recenter."
21136 (interactive "P")
21137 (let ((win (selected-window)))
21138 (org-agenda-goto t)
21139 (recenter arg)
21140 (select-window win)))
21141
21142 (defun org-agenda-show-mouse (ev)
21143 "Display the Org-mode file which contains the item at the mouse click."
21144 (interactive "e")
21145 (mouse-set-point ev)
21146 (org-agenda-show))
21147
21148 (defun org-agenda-check-no-diary ()
21149 "Check if the entry is a diary link and abort if yes."
21150 (if (get-text-property (point) 'org-agenda-diary-link)
21151 (org-agenda-error)))
21152
21153 (defun org-agenda-error ()
21154 (error "Command not allowed in this line"))
21155
21156 (defun org-agenda-tree-to-indirect-buffer ()
21157 "Show the subtree corresponding to the current entry in an indirect buffer.
21158 This calls the command `org-tree-to-indirect-buffer' from the original
21159 Org-mode buffer.
21160 With numerical prefix arg ARG, go up to this level and then take that tree.
21161 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
21162 dedicated frame)."
21163 (interactive)
21164 (org-agenda-check-no-diary)
21165 (let* ((marker (or (get-text-property (point) 'org-marker)
21166 (org-agenda-error)))
21167 (buffer (marker-buffer marker))
21168 (pos (marker-position marker)))
21169 (with-current-buffer buffer
21170 (save-excursion
21171 (goto-char pos)
21172 (call-interactively 'org-tree-to-indirect-buffer)))))
21173
21174 (defvar org-last-heading-marker (make-marker)
21175 "Marker pointing to the headline that last changed its TODO state
21176 by a remote command from the agenda.")
21177
21178 (defun org-agenda-todo-nextset ()
21179 "Switch TODO entry to next sequence."
21180 (interactive)
21181 (org-agenda-todo 'nextset))
21182
21183 (defun org-agenda-todo-previousset ()
21184 "Switch TODO entry to previous sequence."
21185 (interactive)
21186 (org-agenda-todo 'previousset))
21187
21188 (defun org-agenda-todo (&optional arg)
21189 "Cycle TODO state of line at point, also in Org-mode file.
21190 This changes the line at point, all other lines in the agenda referring to
21191 the same tree node, and the headline of the tree node in the Org-mode file."
21192 (interactive "P")
21193 (org-agenda-check-no-diary)
21194 (let* ((col (current-column))
21195 (marker (or (get-text-property (point) 'org-marker)
21196 (org-agenda-error)))
21197 (buffer (marker-buffer marker))
21198 (pos (marker-position marker))
21199 (hdmarker (get-text-property (point) 'org-hd-marker))
21200 (inhibit-read-only t)
21201 newhead)
21202 (org-with-remote-undo buffer
21203 (with-current-buffer buffer
21204 (widen)
21205 (goto-char pos)
21206 (org-show-context 'agenda)
21207 (save-excursion
21208 (and (outline-next-heading)
21209 (org-flag-heading nil))) ; show the next heading
21210 (org-todo arg)
21211 (and (bolp) (forward-char 1))
21212 (setq newhead (org-get-heading))
21213 (save-excursion
21214 (org-back-to-heading)
21215 (move-marker org-last-heading-marker (point))))
21216 (beginning-of-line 1)
21217 (save-excursion
21218 (org-agenda-change-all-lines newhead hdmarker 'fixface))
21219 (move-to-column col))))
21220
21221 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
21222 "Change all lines in the agenda buffer which match HDMARKER.
21223 The new content of the line will be NEWHEAD (as modified by
21224 `org-format-agenda-item'). HDMARKER is checked with
21225 `equal' against all `org-hd-marker' text properties in the file.
21226 If FIXFACE is non-nil, the face of each item is modified acording to
21227 the new TODO state."
21228 (let* ((inhibit-read-only t)
21229 props m pl undone-face done-face finish new dotime cat tags)
21230 (save-excursion
21231 (goto-char (point-max))
21232 (beginning-of-line 1)
21233 (while (not finish)
21234 (setq finish (bobp))
21235 (when (and (setq m (get-text-property (point) 'org-hd-marker))
21236 (equal m hdmarker))
21237 (setq props (text-properties-at (point))
21238 dotime (get-text-property (point) 'dotime)
21239 cat (get-text-property (point) 'org-category)
21240 tags (get-text-property (point) 'tags)
21241 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
21242 pl (get-text-property (point) 'prefix-length)
21243 undone-face (get-text-property (point) 'undone-face)
21244 done-face (get-text-property (point) 'done-face))
21245 (move-to-column pl)
21246 (cond
21247 ((equal new "")
21248 (beginning-of-line 1)
21249 (and (looking-at ".*\n?") (replace-match "")))
21250 ((looking-at ".*")
21251 (replace-match new t t)
21252 (beginning-of-line 1)
21253 (add-text-properties (point-at-bol) (point-at-eol) props)
21254 (when fixface
21255 (add-text-properties
21256 (point-at-bol) (point-at-eol)
21257 (list 'face
21258 (if org-last-todo-state-is-todo
21259 undone-face done-face))))
21260 (org-agenda-highlight-todo 'line)
21261 (beginning-of-line 1))
21262 (t (error "Line update did not work"))))
21263 (beginning-of-line 0)))
21264 (org-finalize-agenda)))
21265
21266 (defun org-agenda-align-tags (&optional line)
21267 "Align all tags in agenda items to `org-agenda-tags-column'."
21268 (let ((inhibit-read-only t) l c)
21269 (save-excursion
21270 (goto-char (if line (point-at-bol) (point-min)))
21271 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21272 (if line (point-at-eol) nil) t)
21273 (add-text-properties
21274 (match-beginning 2) (match-end 2)
21275 (list 'face (list 'org-tag (get-text-property
21276 (match-beginning 2) 'face))))
21277 (setq l (- (match-end 2) (match-beginning 2))
21278 c (if (< org-agenda-tags-column 0)
21279 (- (abs org-agenda-tags-column) l)
21280 org-agenda-tags-column))
21281 (delete-region (match-beginning 1) (match-end 1))
21282 (goto-char (match-beginning 1))
21283 (insert (org-add-props
21284 (make-string (max 1 (- c (current-column))) ?\ )
21285 (text-properties-at (point))))))))
21286
21287 (defun org-agenda-priority-up ()
21288 "Increase the priority of line at point, also in Org-mode file."
21289 (interactive)
21290 (org-agenda-priority 'up))
21291
21292 (defun org-agenda-priority-down ()
21293 "Decrease the priority of line at point, also in Org-mode file."
21294 (interactive)
21295 (org-agenda-priority 'down))
21296
21297 (defun org-agenda-priority (&optional force-direction)
21298 "Set the priority of line at point, also in Org-mode file.
21299 This changes the line at point, all other lines in the agenda referring to
21300 the same tree node, and the headline of the tree node in the Org-mode file."
21301 (interactive)
21302 (org-agenda-check-no-diary)
21303 (let* ((marker (or (get-text-property (point) 'org-marker)
21304 (org-agenda-error)))
21305 (hdmarker (get-text-property (point) 'org-hd-marker))
21306 (buffer (marker-buffer hdmarker))
21307 (pos (marker-position hdmarker))
21308 (inhibit-read-only t)
21309 newhead)
21310 (org-with-remote-undo buffer
21311 (with-current-buffer buffer
21312 (widen)
21313 (goto-char pos)
21314 (org-show-context 'agenda)
21315 (save-excursion
21316 (and (outline-next-heading)
21317 (org-flag-heading nil))) ; show the next heading
21318 (funcall 'org-priority force-direction)
21319 (end-of-line 1)
21320 (setq newhead (org-get-heading)))
21321 (org-agenda-change-all-lines newhead hdmarker)
21322 (beginning-of-line 1))))
21323
21324 (defun org-get-tags-at (&optional pos)
21325 "Get a list of all headline tags applicable at POS.
21326 POS defaults to point. If tags are inherited, the list contains
21327 the targets in the same sequence as the headlines appear, i.e.
21328 the tags of the current headline come last."
21329 (interactive)
21330 (let (tags lastpos)
21331 (save-excursion
21332 (save-restriction
21333 (widen)
21334 (goto-char (or pos (point)))
21335 (save-match-data
21336 (org-back-to-heading t)
21337 (condition-case nil
21338 (while (not (equal lastpos (point)))
21339 (setq lastpos (point))
21340 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
21341 (setq tags (append (org-split-string
21342 (org-match-string-no-properties 1) ":")
21343 tags)))
21344 (or org-use-tag-inheritance (error ""))
21345 (org-up-heading-all 1))
21346 (error nil))))
21347 tags)))
21348
21349 ;; FIXME: should fix the tags property of the agenda line.
21350 (defun org-agenda-set-tags ()
21351 "Set tags for the current headline."
21352 (interactive)
21353 (org-agenda-check-no-diary)
21354 (if (and (org-region-active-p) (interactive-p))
21355 (call-interactively 'org-change-tag-in-region)
21356 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
21357 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
21358 (org-agenda-error)))
21359 (buffer (marker-buffer hdmarker))
21360 (pos (marker-position hdmarker))
21361 (inhibit-read-only t)
21362 newhead)
21363 (org-with-remote-undo buffer
21364 (with-current-buffer buffer
21365 (widen)
21366 (goto-char pos)
21367 (save-excursion
21368 (org-show-context 'agenda))
21369 (save-excursion
21370 (and (outline-next-heading)
21371 (org-flag-heading nil))) ; show the next heading
21372 (goto-char pos)
21373 (call-interactively 'org-set-tags)
21374 (end-of-line 1)
21375 (setq newhead (org-get-heading)))
21376 (org-agenda-change-all-lines newhead hdmarker)
21377 (beginning-of-line 1)))))
21378
21379 (defun org-agenda-toggle-archive-tag ()
21380 "Toggle the archive tag for the current entry."
21381 (interactive)
21382 (org-agenda-check-no-diary)
21383 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
21384 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
21385 (org-agenda-error)))
21386 (buffer (marker-buffer hdmarker))
21387 (pos (marker-position hdmarker))
21388 (inhibit-read-only t)
21389 newhead)
21390 (org-with-remote-undo buffer
21391 (with-current-buffer buffer
21392 (widen)
21393 (goto-char pos)
21394 (org-show-context 'agenda)
21395 (save-excursion
21396 (and (outline-next-heading)
21397 (org-flag-heading nil))) ; show the next heading
21398 (call-interactively 'org-toggle-archive-tag)
21399 (end-of-line 1)
21400 (setq newhead (org-get-heading)))
21401 (org-agenda-change-all-lines newhead hdmarker)
21402 (beginning-of-line 1))))
21403
21404 (defun org-agenda-date-later (arg &optional what)
21405 "Change the date of this item to one day later."
21406 (interactive "p")
21407 (org-agenda-check-type t 'agenda 'timeline)
21408 (org-agenda-check-no-diary)
21409 (let* ((marker (or (get-text-property (point) 'org-marker)
21410 (org-agenda-error)))
21411 (buffer (marker-buffer marker))
21412 (pos (marker-position marker)))
21413 (org-with-remote-undo buffer
21414 (with-current-buffer buffer
21415 (widen)
21416 (goto-char pos)
21417 (if (not (org-at-timestamp-p))
21418 (error "Cannot find time stamp"))
21419 (org-timestamp-change arg (or what 'day)))
21420 (org-agenda-show-new-time marker org-last-changed-timestamp))
21421 (message "Time stamp changed to %s" org-last-changed-timestamp)))
21422
21423 (defun org-agenda-date-earlier (arg &optional what)
21424 "Change the date of this item to one day earlier."
21425 (interactive "p")
21426 (org-agenda-date-later (- arg) what))
21427
21428 (defun org-agenda-show-new-time (marker stamp &optional prefix)
21429 "Show new date stamp via text properties."
21430 ;; We use text properties to make this undoable
21431 (let ((inhibit-read-only t))
21432 (setq stamp (concat " " prefix " => " stamp))
21433 (save-excursion
21434 (goto-char (point-max))
21435 (while (not (bobp))
21436 (when (equal marker (get-text-property (point) 'org-marker))
21437 (move-to-column (- (window-width) (length stamp)) t)
21438 (if (featurep 'xemacs)
21439 ;; Use `duplicable' property to trigger undo recording
21440 (let ((ex (make-extent nil nil))
21441 (gl (make-glyph stamp)))
21442 (set-glyph-face gl 'secondary-selection)
21443 (set-extent-properties
21444 ex (list 'invisible t 'end-glyph gl 'duplicable t))
21445 (insert-extent ex (1- (point)) (point-at-eol)))
21446 (add-text-properties
21447 (1- (point)) (point-at-eol)
21448 (list 'display (org-add-props stamp nil
21449 'face 'secondary-selection))))
21450 (beginning-of-line 1))
21451 (beginning-of-line 0)))))
21452
21453 (defun org-agenda-date-prompt (arg)
21454 "Change the date of this item. Date is prompted for, with default today.
21455 The prefix ARG is passed to the `org-time-stamp' command and can therefore
21456 be used to request time specification in the time stamp."
21457 (interactive "P")
21458 (org-agenda-check-type t 'agenda 'timeline)
21459 (org-agenda-check-no-diary)
21460 (let* ((marker (or (get-text-property (point) 'org-marker)
21461 (org-agenda-error)))
21462 (buffer (marker-buffer marker))
21463 (pos (marker-position marker)))
21464 (org-with-remote-undo buffer
21465 (with-current-buffer buffer
21466 (widen)
21467 (goto-char pos)
21468 (if (not (org-at-timestamp-p))
21469 (error "Cannot find time stamp"))
21470 (org-time-stamp arg)
21471 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
21472
21473 (defun org-agenda-schedule (arg)
21474 "Schedule the item at point."
21475 (interactive "P")
21476 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
21477 (org-agenda-check-no-diary)
21478 (let* ((marker (or (get-text-property (point) 'org-marker)
21479 (org-agenda-error)))
21480 (buffer (marker-buffer marker))
21481 (pos (marker-position marker))
21482 (org-insert-labeled-timestamps-at-point nil)
21483 ts)
21484 (org-with-remote-undo buffer
21485 (with-current-buffer buffer
21486 (widen)
21487 (goto-char pos)
21488 (setq ts (org-schedule arg)))
21489 (org-agenda-show-new-time marker ts "S"))
21490 (message "Item scheduled for %s" ts)))
21491
21492 (defun org-agenda-deadline (arg)
21493 "Schedule the item at point."
21494 (interactive "P")
21495 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
21496 (org-agenda-check-no-diary)
21497 (let* ((marker (or (get-text-property (point) 'org-marker)
21498 (org-agenda-error)))
21499 (buffer (marker-buffer marker))
21500 (pos (marker-position marker))
21501 (org-insert-labeled-timestamps-at-point nil)
21502 ts)
21503 (org-with-remote-undo buffer
21504 (with-current-buffer buffer
21505 (widen)
21506 (goto-char pos)
21507 (setq ts (org-deadline arg)))
21508 (org-agenda-show-new-time marker ts "S"))
21509 (message "Deadline for this item set to %s" ts)))
21510
21511 (defun org-get-heading (&optional no-tags)
21512 "Return the heading of the current entry, without the stars."
21513 (save-excursion
21514 (org-back-to-heading t)
21515 (if (looking-at
21516 (if no-tags
21517 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
21518 "\\*+[ \t]+\\([^\r\n]*\\)"))
21519 (match-string 1) "")))
21520
21521 (defun org-agenda-clock-in (&optional arg)
21522 "Start the clock on the currently selected item."
21523 (interactive "P")
21524 (org-agenda-check-no-diary)
21525 (let* ((marker (or (get-text-property (point) 'org-marker)
21526 (org-agenda-error)))
21527 (pos (marker-position marker)))
21528 (org-with-remote-undo (marker-buffer marker)
21529 (with-current-buffer (marker-buffer marker)
21530 (widen)
21531 (goto-char pos)
21532 (org-clock-in)))))
21533
21534 (defun org-agenda-clock-out (&optional arg)
21535 "Stop the currently running clock."
21536 (interactive "P")
21537 (unless (marker-buffer org-clock-marker)
21538 (error "No running clock"))
21539 (org-with-remote-undo (marker-buffer org-clock-marker)
21540 (org-clock-out)))
21541
21542 (defun org-agenda-clock-cancel (&optional arg)
21543 "Cancel the currently running clock."
21544 (interactive "P")
21545 (unless (marker-buffer org-clock-marker)
21546 (error "No running clock"))
21547 (org-with-remote-undo (marker-buffer org-clock-marker)
21548 (org-clock-cancel)))
21549
21550 (defun org-agenda-diary-entry ()
21551 "Make a diary entry, like the `i' command from the calendar.
21552 All the standard commands work: block, weekly etc."
21553 (interactive)
21554 (org-agenda-check-type t 'agenda 'timeline)
21555 (require 'diary-lib)
21556 (let* ((char (progn
21557 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
21558 (read-char-exclusive)))
21559 (cmd (cdr (assoc char
21560 '((?d . insert-diary-entry)
21561 (?w . insert-weekly-diary-entry)
21562 (?m . insert-monthly-diary-entry)
21563 (?y . insert-yearly-diary-entry)
21564 (?a . insert-anniversary-diary-entry)
21565 (?b . insert-block-diary-entry)
21566 (?c . insert-cyclic-diary-entry)))))
21567 (oldf (symbol-function 'calendar-cursor-to-date))
21568 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
21569 (point (point))
21570 (mark (or (mark t) (point))))
21571 (unless cmd
21572 (error "No command associated with <%c>" char))
21573 (unless (and (get-text-property point 'day)
21574 (or (not (equal ?b char))
21575 (get-text-property mark 'day)))
21576 (error "Don't know which date to use for diary entry"))
21577 ;; We implement this by hacking the `calendar-cursor-to-date' function
21578 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
21579 (let ((calendar-mark-ring
21580 (list (calendar-gregorian-from-absolute
21581 (or (get-text-property mark 'day)
21582 (get-text-property point 'day))))))
21583 (unwind-protect
21584 (progn
21585 (fset 'calendar-cursor-to-date
21586 (lambda (&optional error)
21587 (calendar-gregorian-from-absolute
21588 (get-text-property point 'day))))
21589 (call-interactively cmd))
21590 (fset 'calendar-cursor-to-date oldf)))))
21591
21592
21593 (defun org-agenda-execute-calendar-command (cmd)
21594 "Execute a calendar command from the agenda, with the date associated to
21595 the cursor position."
21596 (org-agenda-check-type t 'agenda 'timeline)
21597 (require 'diary-lib)
21598 (unless (get-text-property (point) 'day)
21599 (error "Don't know which date to use for calendar command"))
21600 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
21601 (point (point))
21602 (date (calendar-gregorian-from-absolute
21603 (get-text-property point 'day)))
21604 ;; the following 3 vars are needed in the calendar
21605 (displayed-day (extract-calendar-day date))
21606 (displayed-month (extract-calendar-month date))
21607 (displayed-year (extract-calendar-year date)))
21608 (unwind-protect
21609 (progn
21610 (fset 'calendar-cursor-to-date
21611 (lambda (&optional error)
21612 (calendar-gregorian-from-absolute
21613 (get-text-property point 'day))))
21614 (call-interactively cmd))
21615 (fset 'calendar-cursor-to-date oldf))))
21616
21617 (defun org-agenda-phases-of-moon ()
21618 "Display the phases of the moon for the 3 months around the cursor date."
21619 (interactive)
21620 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
21621
21622 (defun org-agenda-holidays ()
21623 "Display the holidays for the 3 months around the cursor date."
21624 (interactive)
21625 (org-agenda-execute-calendar-command 'list-calendar-holidays))
21626
21627 (defun org-agenda-sunrise-sunset (arg)
21628 "Display sunrise and sunset for the cursor date.
21629 Latitude and longitude can be specified with the variables
21630 `calendar-latitude' and `calendar-longitude'. When called with prefix
21631 argument, latitude and longitude will be prompted for."
21632 (interactive "P")
21633 (let ((calendar-longitude (if arg nil calendar-longitude))
21634 (calendar-latitude (if arg nil calendar-latitude))
21635 (calendar-location-name
21636 (if arg "the given coordinates" calendar-location-name)))
21637 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
21638
21639 (defun org-agenda-goto-calendar ()
21640 "Open the Emacs calendar with the date at the cursor."
21641 (interactive)
21642 (org-agenda-check-type t 'agenda 'timeline)
21643 (let* ((day (or (get-text-property (point) 'day)
21644 (error "Don't know which date to open in calendar")))
21645 (date (calendar-gregorian-from-absolute day))
21646 (calendar-move-hook nil)
21647 (view-calendar-holidays-initially nil)
21648 (view-diary-entries-initially nil))
21649 (calendar)
21650 (calendar-goto-date date)))
21651
21652 (defun org-calendar-goto-agenda ()
21653 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
21654 This is a command that has to be installed in `calendar-mode-map'."
21655 (interactive)
21656 (org-agenda-list nil (calendar-absolute-from-gregorian
21657 (calendar-cursor-to-date))
21658 nil))
21659
21660 (defun org-agenda-convert-date ()
21661 (interactive)
21662 (org-agenda-check-type t 'agenda 'timeline)
21663 (let ((day (get-text-property (point) 'day))
21664 date s)
21665 (unless day
21666 (error "Don't know which date to convert"))
21667 (setq date (calendar-gregorian-from-absolute day))
21668 (setq s (concat
21669 "Gregorian: " (calendar-date-string date) "\n"
21670 "ISO: " (calendar-iso-date-string date) "\n"
21671 "Day of Yr: " (calendar-day-of-year-string date) "\n"
21672 "Julian: " (calendar-julian-date-string date) "\n"
21673 "Astron. JD: " (calendar-astro-date-string date)
21674 " (Julian date number at noon UTC)\n"
21675 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
21676 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
21677 "French: " (calendar-french-date-string date) "\n"
21678 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
21679 "Mayan: " (calendar-mayan-date-string date) "\n"
21680 "Coptic: " (calendar-coptic-date-string date) "\n"
21681 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
21682 "Persian: " (calendar-persian-date-string date) "\n"
21683 "Chinese: " (calendar-chinese-date-string date) "\n"))
21684 (with-output-to-temp-buffer "*Dates*"
21685 (princ s))
21686 (if (fboundp 'fit-window-to-buffer)
21687 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
21688
21689
21690 ;;;; Embedded LaTeX
21691
21692 (defvar org-cdlatex-mode-map (make-sparse-keymap)
21693 "Keymap for the minor `org-cdlatex-mode'.")
21694
21695 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
21696 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
21697 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
21698 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
21699 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
21700
21701 (defvar org-cdlatex-texmathp-advice-is-done nil
21702 "Flag remembering if we have applied the advice to texmathp already.")
21703
21704 (define-minor-mode org-cdlatex-mode
21705 "Toggle the minor `org-cdlatex-mode'.
21706 This mode supports entering LaTeX environment and math in LaTeX fragments
21707 in Org-mode.
21708 \\{org-cdlatex-mode-map}"
21709 nil " OCDL" nil
21710 (when org-cdlatex-mode (require 'cdlatex))
21711 (unless org-cdlatex-texmathp-advice-is-done
21712 (setq org-cdlatex-texmathp-advice-is-done t)
21713 (defadvice texmathp (around org-math-always-on activate)
21714 "Always return t in org-mode buffers.
21715 This is because we want to insert math symbols without dollars even outside
21716 the LaTeX math segments. If Orgmode thinks that point is actually inside
21717 en embedded LaTeX fragement, let texmathp do its job.
21718 \\[org-cdlatex-mode-map]"
21719 (interactive)
21720 (let (p)
21721 (cond
21722 ((not (org-mode-p)) ad-do-it)
21723 ((eq this-command 'cdlatex-math-symbol)
21724 (setq ad-return-value t
21725 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
21726 (t
21727 (let ((p (org-inside-LaTeX-fragment-p)))
21728 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
21729 (setq ad-return-value t
21730 texmathp-why '("Org-mode embedded math" . 0))
21731 (if p ad-do-it)))))))))
21732
21733 (defun turn-on-org-cdlatex ()
21734 "Unconditionally turn on `org-cdlatex-mode'."
21735 (org-cdlatex-mode 1))
21736
21737 (defun org-inside-LaTeX-fragment-p ()
21738 "Test if point is inside a LaTeX fragment.
21739 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
21740 sequence appearing also before point.
21741 Even though the matchers for math are configurable, this function assumes
21742 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
21743 delimiters are skipped when they have been removed by customization.
21744 The return value is nil, or a cons cell with the delimiter and
21745 and the position of this delimiter.
21746
21747 This function does a reasonably good job, but can locally be fooled by
21748 for example currency specifications. For example it will assume being in
21749 inline math after \"$22.34\". The LaTeX fragment formatter will only format
21750 fragments that are properly closed, but during editing, we have to live
21751 with the uncertainty caused by missing closing delimiters. This function
21752 looks only before point, not after."
21753 (catch 'exit
21754 (let ((pos (point))
21755 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
21756 (lim (progn
21757 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
21758 (point)))
21759 dd-on str (start 0) m re)
21760 (goto-char pos)
21761 (when dodollar
21762 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
21763 re (nth 1 (assoc "$" org-latex-regexps)))
21764 (while (string-match re str start)
21765 (cond
21766 ((= (match-end 0) (length str))
21767 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
21768 ((= (match-end 0) (- (length str) 5))
21769 (throw 'exit nil))
21770 (t (setq start (match-end 0))))))
21771 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
21772 (goto-char pos)
21773 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
21774 (and (match-beginning 2) (throw 'exit nil))
21775 ;; count $$
21776 (while (re-search-backward "\\$\\$" lim t)
21777 (setq dd-on (not dd-on)))
21778 (goto-char pos)
21779 (if dd-on (cons "$$" m))))))
21780
21781
21782 (defun org-try-cdlatex-tab ()
21783 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
21784 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
21785 - inside a LaTeX fragment, or
21786 - after the first word in a line, where an abbreviation expansion could
21787 insert a LaTeX environment."
21788 (when org-cdlatex-mode
21789 (cond
21790 ((save-excursion
21791 (skip-chars-backward "a-zA-Z0-9*")
21792 (skip-chars-backward " \t")
21793 (bolp))
21794 (cdlatex-tab) t)
21795 ((org-inside-LaTeX-fragment-p)
21796 (cdlatex-tab) t)
21797 (t nil))))
21798
21799 (defun org-cdlatex-underscore-caret (&optional arg)
21800 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
21801 Revert to the normal definition outside of these fragments."
21802 (interactive "P")
21803 (if (org-inside-LaTeX-fragment-p)
21804 (call-interactively 'cdlatex-sub-superscript)
21805 (let (org-cdlatex-mode)
21806 (call-interactively (key-binding (vector last-input-event))))))
21807
21808 (defun org-cdlatex-math-modify (&optional arg)
21809 "Execute `cdlatex-math-modify' in LaTeX fragments.
21810 Revert to the normal definition outside of these fragments."
21811 (interactive "P")
21812 (if (org-inside-LaTeX-fragment-p)
21813 (call-interactively 'cdlatex-math-modify)
21814 (let (org-cdlatex-mode)
21815 (call-interactively (key-binding (vector last-input-event))))))
21816
21817 (defvar org-latex-fragment-image-overlays nil
21818 "List of overlays carrying the images of latex fragments.")
21819 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
21820
21821 (defun org-remove-latex-fragment-image-overlays ()
21822 "Remove all overlays with LaTeX fragment images in current buffer."
21823 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
21824 (setq org-latex-fragment-image-overlays nil))
21825
21826 (defun org-preview-latex-fragment (&optional subtree)
21827 "Preview the LaTeX fragment at point, or all locally or globally.
21828 If the cursor is in a LaTeX fragment, create the image and overlay
21829 it over the source code. If there is no fragment at point, display
21830 all fragments in the current text, from one headline to the next. With
21831 prefix SUBTREE, display all fragments in the current subtree. With a
21832 double prefix `C-u C-u', or when the cursor is before the first headline,
21833 display all fragments in the buffer.
21834 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
21835 (interactive "P")
21836 (org-remove-latex-fragment-image-overlays)
21837 (save-excursion
21838 (save-restriction
21839 (let (beg end at msg)
21840 (cond
21841 ((or (equal subtree '(16))
21842 (not (save-excursion
21843 (re-search-backward (concat "^" outline-regexp) nil t))))
21844 (setq beg (point-min) end (point-max)
21845 msg "Creating images for buffer...%s"))
21846 ((equal subtree '(4))
21847 (org-back-to-heading)
21848 (setq beg (point) end (org-end-of-subtree t)
21849 msg "Creating images for subtree...%s"))
21850 (t
21851 (if (setq at (org-inside-LaTeX-fragment-p))
21852 (goto-char (max (point-min) (- (cdr at) 2)))
21853 (org-back-to-heading))
21854 (setq beg (point) end (progn (outline-next-heading) (point))
21855 msg (if at "Creating image...%s"
21856 "Creating images for entry...%s"))))
21857 (message msg "")
21858 (narrow-to-region beg end)
21859 (goto-char beg)
21860 (org-format-latex
21861 (concat "ltxpng/" (file-name-sans-extension
21862 (file-name-nondirectory
21863 buffer-file-name)))
21864 default-directory 'overlays msg at 'forbuffer)
21865 (message msg "done. Use `C-c C-c' to remove images.")))))
21866
21867 (defvar org-latex-regexps
21868 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
21869 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
21870 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
21871 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
21872 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
21873 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
21874 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
21875 "Regular expressions for matching embedded LaTeX.")
21876
21877 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
21878 "Replace LaTeX fragments with links to an image, and produce images."
21879 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
21880 (let* ((prefixnodir (file-name-nondirectory prefix))
21881 (absprefix (expand-file-name prefix dir))
21882 (todir (file-name-directory absprefix))
21883 (opt org-format-latex-options)
21884 (matchers (plist-get opt :matchers))
21885 (re-list org-latex-regexps)
21886 (cnt 0) txt link beg end re e checkdir
21887 m n block linkfile movefile ov)
21888 ;; Check if there are old images files with this prefix, and remove them
21889 (when (file-directory-p todir)
21890 (mapc 'delete-file
21891 (directory-files
21892 todir 'full
21893 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
21894 ;; Check the different regular expressions
21895 (while (setq e (pop re-list))
21896 (setq m (car e) re (nth 1 e) n (nth 2 e)
21897 block (if (nth 3 e) "\n\n" ""))
21898 (when (member m matchers)
21899 (goto-char (point-min))
21900 (while (re-search-forward re nil t)
21901 (when (or (not at) (equal (cdr at) (match-beginning n)))
21902 (setq txt (match-string n)
21903 beg (match-beginning n) end (match-end n)
21904 cnt (1+ cnt)
21905 linkfile (format "%s_%04d.png" prefix cnt)
21906 movefile (format "%s_%04d.png" absprefix cnt)
21907 link (concat block "[[file:" linkfile "]]" block))
21908 (if msg (message msg cnt))
21909 (goto-char beg)
21910 (unless checkdir ; make sure the directory exists
21911 (setq checkdir t)
21912 (or (file-directory-p todir) (make-directory todir)))
21913 (org-create-formula-image
21914 txt movefile opt forbuffer)
21915 (if overlays
21916 (progn
21917 (setq ov (org-make-overlay beg end))
21918 (if (featurep 'xemacs)
21919 (progn
21920 (org-overlay-put ov 'invisible t)
21921 (org-overlay-put
21922 ov 'end-glyph
21923 (make-glyph (vector 'png :file movefile))))
21924 (org-overlay-put
21925 ov 'display
21926 (list 'image :type 'png :file movefile :ascent 'center)))
21927 (push ov org-latex-fragment-image-overlays)
21928 (goto-char end))
21929 (delete-region beg end)
21930 (insert link))))))))
21931
21932 ;; This function borrows from Ganesh Swami's latex2png.el
21933 (defun org-create-formula-image (string tofile options buffer)
21934 (let* ((tmpdir (if (featurep 'xemacs)
21935 (temp-directory)
21936 temporary-file-directory))
21937 (texfilebase (make-temp-name
21938 (expand-file-name "orgtex" tmpdir)))
21939 (texfile (concat texfilebase ".tex"))
21940 (dvifile (concat texfilebase ".dvi"))
21941 (pngfile (concat texfilebase ".png"))
21942 (fnh (face-attribute 'default :height nil))
21943 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
21944 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
21945 (fg (or (plist-get options (if buffer :foreground :html-foreground))
21946 "Black"))
21947 (bg (or (plist-get options (if buffer :background :html-background))
21948 "Transparent")))
21949 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
21950 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
21951 (with-temp-file texfile
21952 (insert org-format-latex-header
21953 "\n\\begin{document}\n" string "\n\\end{document}\n"))
21954 (let ((dir default-directory))
21955 (condition-case nil
21956 (progn
21957 (cd tmpdir)
21958 (call-process "latex" nil nil nil texfile))
21959 (error nil))
21960 (cd dir))
21961 (if (not (file-exists-p dvifile))
21962 (progn (message "Failed to create dvi file from %s" texfile) nil)
21963 (call-process "dvipng" nil nil nil
21964 "-E" "-fg" fg "-bg" bg
21965 "-D" dpi
21966 ;;"-x" scale "-y" scale
21967 "-T" "tight"
21968 "-o" pngfile
21969 dvifile)
21970 (if (not (file-exists-p pngfile))
21971 (progn (message "Failed to create png file from %s" texfile) nil)
21972 ;; Use the requested file name and clean up
21973 (copy-file pngfile tofile 'replace)
21974 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
21975 (delete-file (concat texfilebase e)))
21976 pngfile))))
21977
21978 (defun org-dvipng-color (attr)
21979 "Return an rgb color specification for dvipng."
21980 (apply 'format "rgb %s %s %s"
21981 (mapcar 'org-normalize-color
21982 (color-values (face-attribute 'default attr nil)))))
21983
21984 (defun org-normalize-color (value)
21985 "Return string to be used as color value for an RGB component."
21986 (format "%g" (/ value 65535.0)))
21987
21988 ;;;; Exporting
21989
21990 ;;; Variables, constants, and parameter plists
21991
21992 (defconst org-level-max 20)
21993
21994 (defvar org-export-html-preamble nil
21995 "Preamble, to be inserted just after <body>. Set by publishing functions.")
21996 (defvar org-export-html-postamble nil
21997 "Preamble, to be inserted just before </body>. Set by publishing functions.")
21998 (defvar org-export-html-auto-preamble t
21999 "Should default preamble be inserted? Set by publishing functions.")
22000 (defvar org-export-html-auto-postamble t
22001 "Should default postamble be inserted? Set by publishing functions.")
22002 (defvar org-current-export-file nil) ; dynamically scoped parameter
22003 (defvar org-current-export-dir nil) ; dynamically scoped parameter
22004
22005
22006 (defconst org-export-plist-vars
22007 '((:language . org-export-default-language)
22008 (:customtime . org-display-custom-times)
22009 (:headline-levels . org-export-headline-levels)
22010 (:section-numbers . org-export-with-section-numbers)
22011 (:table-of-contents . org-export-with-toc)
22012 (:preserve-breaks . org-export-preserve-breaks)
22013 (:archived-trees . org-export-with-archived-trees)
22014 (:emphasize . org-export-with-emphasize)
22015 (:sub-superscript . org-export-with-sub-superscripts)
22016 (:footnotes . org-export-with-footnotes)
22017 (:drawers . org-export-with-drawers)
22018 (:tags . org-export-with-tags)
22019 (:TeX-macros . org-export-with-TeX-macros)
22020 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
22021 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
22022 (:fixed-width . org-export-with-fixed-width)
22023 (:timestamps . org-export-with-timestamps)
22024 (:author-info . org-export-author-info)
22025 (:time-stamp-file . org-export-time-stamp-file)
22026 (:tables . org-export-with-tables)
22027 (:table-auto-headline . org-export-highlight-first-table-line)
22028 (:style . org-export-html-style)
22029 (:agenda-style . org-agenda-export-html-style) ;; FIXME: Does this work????
22030 (:convert-org-links . org-export-html-link-org-files-as-html)
22031 (:inline-images . org-export-html-inline-images)
22032 (:html-extension . org-export-html-extension)
22033 (:expand-quoted-html . org-export-html-expand)
22034 (:timestamp . org-export-html-with-timestamp)
22035 (:publishing-directory . org-export-publishing-directory)
22036 (:preamble . org-export-html-preamble)
22037 (:postamble . org-export-html-postamble)
22038 (:auto-preamble . org-export-html-auto-preamble)
22039 (:auto-postamble . org-export-html-auto-postamble)
22040 (:author . user-full-name)
22041 (:email . user-mail-address)))
22042
22043 (defun org-default-export-plist ()
22044 "Return the property list with default settings for the export variables."
22045 (let ((l org-export-plist-vars) rtn e)
22046 (while (setq e (pop l))
22047 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
22048 rtn))
22049
22050 (defun org-infile-export-plist ()
22051 "Return the property list with file-local settings for export."
22052 (save-excursion
22053 (goto-char 0)
22054 (let ((re (org-make-options-regexp
22055 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
22056 p key val text options)
22057 (while (re-search-forward re nil t)
22058 (setq key (org-match-string-no-properties 1)
22059 val (org-match-string-no-properties 2))
22060 (cond
22061 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
22062 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
22063 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
22064 ((string-equal key "DATE") (setq p (plist-put p :date val)))
22065 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
22066 ((string-equal key "TEXT")
22067 (setq text (if text (concat text "\n" val) val)))
22068 ((string-equal key "OPTIONS") (setq options val))))
22069 (setq p (plist-put p :text text))
22070 (when options
22071 (let ((op '(("H" . :headline-levels)
22072 ("num" . :section-numbers)
22073 ("toc" . :table-of-contents)
22074 ("\\n" . :preserve-breaks)
22075 ("@" . :expand-quoted-html)
22076 (":" . :fixed-width)
22077 ("|" . :tables)
22078 ("^" . :sub-superscript)
22079 ("f" . :footnotes)
22080 ("d" . :drawers)
22081 ("tags" . :tags)
22082 ("*" . :emphasize)
22083 ("TeX" . :TeX-macros)
22084 ("LaTeX" . :LaTeX-fragments)
22085 ("skip" . :skip-before-1st-heading)
22086 ("author" . :author-info)
22087 ("timestamp" . :time-stamp-file)))
22088 o)
22089 (while (setq o (pop op))
22090 (if (string-match (concat (regexp-quote (car o))
22091 ":\\([^ \t\n\r;,.]*\\)")
22092 options)
22093 (setq p (plist-put p (cdr o)
22094 (car (read-from-string
22095 (match-string 1 options)))))))))
22096 p)))
22097
22098 (defun org-export-directory (type plist)
22099 (let* ((val (plist-get plist :publishing-directory))
22100 (dir (if (listp val)
22101 (or (cdr (assoc type val)) ".")
22102 val)))
22103 dir))
22104
22105 (defun org-skip-comments (lines)
22106 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
22107 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
22108 (re2 "^\\(\\*+\\)[ \t\n\r]")
22109 (case-fold-search nil)
22110 rtn line level)
22111 (while (setq line (pop lines))
22112 (cond
22113 ((and (string-match re1 line)
22114 (setq level (- (match-end 1) (match-beginning 1))))
22115 ;; Beginning of a COMMENT subtree. Skip it.
22116 (while (and (setq line (pop lines))
22117 (or (not (string-match re2 line))
22118 (> (- (match-end 1) (match-beginning 1)) level))))
22119 (setq lines (cons line lines)))
22120 ((string-match "^#" line)
22121 ;; an ordinary comment line
22122 )
22123 ((and org-export-table-remove-special-lines
22124 (string-match "^[ \t]*|" line)
22125 (or (string-match "^[ \t]*| *[!_^] *|" line)
22126 (and (string-match "| *<[0-9]+> *|" line)
22127 (not (string-match "| *[^ <|]" line)))))
22128 ;; a special table line that should be removed
22129 )
22130 (t (setq rtn (cons line rtn)))))
22131 (nreverse rtn)))
22132
22133 (defun org-export (&optional arg)
22134 (interactive)
22135 (let ((help "[t] insert the export option template
22136 \[v] limit export to visible part of outline tree
22137
22138 \[a] export as ASCII
22139
22140 \[h] export as HTML
22141 \[H] export as HTML to temporary buffer
22142 \[R] export region as HTML
22143 \[b] export as HTML and browse immediately
22144 \[x] export as XOXO
22145
22146 \[l] export as LaTeX
22147 \[L] export as LaTeX to temporary buffer
22148
22149 \[i] export current file as iCalendar file
22150 \[I] export all agenda files as iCalendar files
22151 \[c] export agenda files into combined iCalendar file
22152
22153 \[F] publish current file
22154 \[P] publish current project
22155 \[X] publish... (project will be prompted for)
22156 \[A] publish all projects")
22157 (cmds
22158 '((?t . org-insert-export-options-template)
22159 (?v . org-export-visible)
22160 (?a . org-export-as-ascii)
22161 (?h . org-export-as-html)
22162 (?b . org-export-as-html-and-open)
22163 (?H . org-export-as-html-to-buffer)
22164 (?R . org-export-region-as-html)
22165 (?x . org-export-as-xoxo)
22166 (?l . org-export-as-latex)
22167 (?L . org-export-as-latex-to-buffer)
22168 (?i . org-export-icalendar-this-file)
22169 (?I . org-export-icalendar-all-agenda-files)
22170 (?c . org-export-icalendar-combine-agenda-files)
22171 (?F . org-publish-current-file)
22172 (?P . org-publish-current-project)
22173 (?X . org-publish)
22174 (?A . org-publish-all)))
22175 r1 r2 ass)
22176 (save-window-excursion
22177 (delete-other-windows)
22178 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
22179 (princ help))
22180 (message "Select command: ")
22181 (setq r1 (read-char-exclusive)))
22182 (setq r2 (if (< r1 27) (+ r1 96) r1))
22183 (if (setq ass (assq r2 cmds))
22184 (call-interactively (cdr ass))
22185 (error "No command associated with key %c" r1))))
22186
22187 (defconst org-html-entities
22188 '(("nbsp")
22189 ("iexcl")
22190 ("cent")
22191 ("pound")
22192 ("curren")
22193 ("yen")
22194 ("brvbar")
22195 ("vert" . "&#124;")
22196 ("sect")
22197 ("uml")
22198 ("copy")
22199 ("ordf")
22200 ("laquo")
22201 ("not")
22202 ("shy")
22203 ("reg")
22204 ("macr")
22205 ("deg")
22206 ("plusmn")
22207 ("sup2")
22208 ("sup3")
22209 ("acute")
22210 ("micro")
22211 ("para")
22212 ("middot")
22213 ("odot"."o")
22214 ("star"."*")
22215 ("cedil")
22216 ("sup1")
22217 ("ordm")
22218 ("raquo")
22219 ("frac14")
22220 ("frac12")
22221 ("frac34")
22222 ("iquest")
22223 ("Agrave")
22224 ("Aacute")
22225 ("Acirc")
22226 ("Atilde")
22227 ("Auml")
22228 ("Aring") ("AA"."&Aring;")
22229 ("AElig")
22230 ("Ccedil")
22231 ("Egrave")
22232 ("Eacute")
22233 ("Ecirc")
22234 ("Euml")
22235 ("Igrave")
22236 ("Iacute")
22237 ("Icirc")
22238 ("Iuml")
22239 ("ETH")
22240 ("Ntilde")
22241 ("Ograve")
22242 ("Oacute")
22243 ("Ocirc")
22244 ("Otilde")
22245 ("Ouml")
22246 ("times")
22247 ("Oslash")
22248 ("Ugrave")
22249 ("Uacute")
22250 ("Ucirc")
22251 ("Uuml")
22252 ("Yacute")
22253 ("THORN")
22254 ("szlig")
22255 ("agrave")
22256 ("aacute")
22257 ("acirc")
22258 ("atilde")
22259 ("auml")
22260 ("aring")
22261 ("aelig")
22262 ("ccedil")
22263 ("egrave")
22264 ("eacute")
22265 ("ecirc")
22266 ("euml")
22267 ("igrave")
22268 ("iacute")
22269 ("icirc")
22270 ("iuml")
22271 ("eth")
22272 ("ntilde")
22273 ("ograve")
22274 ("oacute")
22275 ("ocirc")
22276 ("otilde")
22277 ("ouml")
22278 ("divide")
22279 ("oslash")
22280 ("ugrave")
22281 ("uacute")
22282 ("ucirc")
22283 ("uuml")
22284 ("yacute")
22285 ("thorn")
22286 ("yuml")
22287 ("fnof")
22288 ("Alpha")
22289 ("Beta")
22290 ("Gamma")
22291 ("Delta")
22292 ("Epsilon")
22293 ("Zeta")
22294 ("Eta")
22295 ("Theta")
22296 ("Iota")
22297 ("Kappa")
22298 ("Lambda")
22299 ("Mu")
22300 ("Nu")
22301 ("Xi")
22302 ("Omicron")
22303 ("Pi")
22304 ("Rho")
22305 ("Sigma")
22306 ("Tau")
22307 ("Upsilon")
22308 ("Phi")
22309 ("Chi")
22310 ("Psi")
22311 ("Omega")
22312 ("alpha")
22313 ("beta")
22314 ("gamma")
22315 ("delta")
22316 ("epsilon")
22317 ("varepsilon"."&epsilon;")
22318 ("zeta")
22319 ("eta")
22320 ("theta")
22321 ("iota")
22322 ("kappa")
22323 ("lambda")
22324 ("mu")
22325 ("nu")
22326 ("xi")
22327 ("omicron")
22328 ("pi")
22329 ("rho")
22330 ("sigmaf") ("varsigma"."&sigmaf;")
22331 ("sigma")
22332 ("tau")
22333 ("upsilon")
22334 ("phi")
22335 ("chi")
22336 ("psi")
22337 ("omega")
22338 ("thetasym") ("vartheta"."&thetasym;")
22339 ("upsih")
22340 ("piv")
22341 ("bull") ("bullet"."&bull;")
22342 ("hellip") ("dots"."&hellip;")
22343 ("prime")
22344 ("Prime")
22345 ("oline")
22346 ("frasl")
22347 ("weierp")
22348 ("image")
22349 ("real")
22350 ("trade")
22351 ("alefsym")
22352 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
22353 ("uarr") ("uparrow"."&uarr;")
22354 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
22355 ("darr")("downarrow"."&darr;")
22356 ("harr") ("leftrightarrow"."&harr;")
22357 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
22358 ("lArr") ("Leftarrow"."&lArr;")
22359 ("uArr") ("Uparrow"."&uArr;")
22360 ("rArr") ("Rightarrow"."&rArr;")
22361 ("dArr") ("Downarrow"."&dArr;")
22362 ("hArr") ("Leftrightarrow"."&hArr;")
22363 ("forall")
22364 ("part") ("partial"."&part;")
22365 ("exist") ("exists"."&exist;")
22366 ("empty") ("emptyset"."&empty;")
22367 ("nabla")
22368 ("isin") ("in"."&isin;")
22369 ("notin")
22370 ("ni")
22371 ("prod")
22372 ("sum")
22373 ("minus")
22374 ("lowast") ("ast"."&lowast;")
22375 ("radic")
22376 ("prop") ("proptp"."&prop;")
22377 ("infin") ("infty"."&infin;")
22378 ("ang") ("angle"."&ang;")
22379 ("and") ("vee"."&and;")
22380 ("or") ("wedge"."&or;")
22381 ("cap")
22382 ("cup")
22383 ("int")
22384 ("there4")
22385 ("sim")
22386 ("cong") ("simeq"."&cong;")
22387 ("asymp")("approx"."&asymp;")
22388 ("ne") ("neq"."&ne;")
22389 ("equiv")
22390 ("le")
22391 ("ge")
22392 ("sub") ("subset"."&sub;")
22393 ("sup") ("supset"."&sup;")
22394 ("nsub")
22395 ("sube")
22396 ("supe")
22397 ("oplus")
22398 ("otimes")
22399 ("perp")
22400 ("sdot") ("cdot"."&sdot;")
22401 ("lceil")
22402 ("rceil")
22403 ("lfloor")
22404 ("rfloor")
22405 ("lang")
22406 ("rang")
22407 ("loz") ("Diamond"."&loz;")
22408 ("spades") ("spadesuit"."&spades;")
22409 ("clubs") ("clubsuit"."&clubs;")
22410 ("hearts") ("diamondsuit"."&hearts;")
22411 ("diams") ("diamondsuit"."&diams;")
22412 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
22413 ("quot")
22414 ("amp")
22415 ("lt")
22416 ("gt")
22417 ("OElig")
22418 ("oelig")
22419 ("Scaron")
22420 ("scaron")
22421 ("Yuml")
22422 ("circ")
22423 ("tilde")
22424 ("ensp")
22425 ("emsp")
22426 ("thinsp")
22427 ("zwnj")
22428 ("zwj")
22429 ("lrm")
22430 ("rlm")
22431 ("ndash")
22432 ("mdash")
22433 ("lsquo")
22434 ("rsquo")
22435 ("sbquo")
22436 ("ldquo")
22437 ("rdquo")
22438 ("bdquo")
22439 ("dagger")
22440 ("Dagger")
22441 ("permil")
22442 ("lsaquo")
22443 ("rsaquo")
22444 ("euro")
22445
22446 ("arccos"."arccos")
22447 ("arcsin"."arcsin")
22448 ("arctan"."arctan")
22449 ("arg"."arg")
22450 ("cos"."cos")
22451 ("cosh"."cosh")
22452 ("cot"."cot")
22453 ("coth"."coth")
22454 ("csc"."csc")
22455 ("deg"."deg")
22456 ("det"."det")
22457 ("dim"."dim")
22458 ("exp"."exp")
22459 ("gcd"."gcd")
22460 ("hom"."hom")
22461 ("inf"."inf")
22462 ("ker"."ker")
22463 ("lg"."lg")
22464 ("lim"."lim")
22465 ("liminf"."liminf")
22466 ("limsup"."limsup")
22467 ("ln"."ln")
22468 ("log"."log")
22469 ("max"."max")
22470 ("min"."min")
22471 ("Pr"."Pr")
22472 ("sec"."sec")
22473 ("sin"."sin")
22474 ("sinh"."sinh")
22475 ("sup"."sup")
22476 ("tan"."tan")
22477 ("tanh"."tanh")
22478 )
22479 "Entities for TeX->HTML translation.
22480 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
22481 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
22482 In that case, \"\\ent\" will be translated to \"&other;\".
22483 The list contains HTML entities for Latin-1, Greek and other symbols.
22484 It is supplemented by a number of commonly used TeX macros with appropriate
22485 translations. There is currently no way for users to extend this.")
22486
22487 ;;; General functions for all backends
22488
22489 (defun org-cleaned-string-for-export (string &rest parameters)
22490 "Cleanup a buffer STRING so that links can be created safely."
22491 (interactive)
22492 (let* ((re-radio (and org-target-link-regexp
22493 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
22494 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
22495 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
22496 (re-archive (concat ":" org-archive-tag ":"))
22497 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
22498 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
22499 (htmlp (plist-get parameters :for-html))
22500 (asciip (plist-get parameters :for-ascii))
22501 (latexp (plist-get parameters :for-LaTeX))
22502 (commentsp (plist-get parameters :comments))
22503 (archived-trees (plist-get parameters :archived-trees))
22504 (inhibit-read-only t)
22505 (outline-regexp "\\*+ ")
22506 a b xx
22507 rtn p)
22508 (with-current-buffer (get-buffer-create " org-mode-tmp")
22509 (erase-buffer)
22510 (insert string)
22511 ;; Remove license-to-kill stuff
22512 (while (setq p (text-property-any (point-min) (point-max)
22513 :org-license-to-kill t))
22514 (delete-region p (next-single-property-change p :org-license-to-kill)))
22515
22516 (let ((org-inhibit-startup t)) (org-mode))
22517 (untabify (point-min) (point-max))
22518
22519 ;; Get the correct stuff before the first headline
22520 (when (plist-get parameters :skip-before-1st-heading)
22521 (goto-char (point-min))
22522 (when (re-search-forward "^\\*+[ \t]" nil t)
22523 (delete-region (point-min) (match-beginning 0))
22524 (goto-char (point-min))
22525 (insert "\n")))
22526 (when (plist-get parameters :add-text)
22527 (goto-char (point-min))
22528 (insert (plist-get parameters :add-text) "\n"))
22529
22530 ;; Get rid of archived trees
22531 (when (not (eq archived-trees t))
22532 (goto-char (point-min))
22533 (while (re-search-forward re-archive nil t)
22534 (if (not (org-on-heading-p t))
22535 (org-end-of-subtree t)
22536 (beginning-of-line 1)
22537 (setq a (if archived-trees
22538 (1+ (point-at-eol)) (point))
22539 b (org-end-of-subtree t))
22540 (if (> b a) (delete-region a b)))))
22541
22542 ;; Get rid of drawers
22543 (unless (eq t org-export-with-drawers)
22544 (goto-char (point-min))
22545 (let ((re (concat "^[ \t]*:\\("
22546 (mapconcat 'identity
22547 (if (listp org-export-with-drawers)
22548 org-export-with-drawers
22549 org-drawers)
22550 "\\|")
22551 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
22552 (while (re-search-forward re nil t)
22553 (replace-match ""))))
22554
22555 ;; Find targets in comments and move them out of comments,
22556 ;; but mark them as targets that should be invisible
22557 (goto-char (point-min))
22558 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
22559 (replace-match "\\1(INVISIBLE)"))
22560
22561 ;; Protect backend specific stuff, throw away the others.
22562 (goto-char (point-min))
22563 (let ((formatters
22564 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
22565 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
22566 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
22567 fmt)
22568 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
22569 (add-text-properties (match-beginning 0) (match-end 0)
22570 '(org-protected t)))
22571 (while formatters
22572 (setq fmt (pop formatters))
22573 (when (car fmt)
22574 (goto-char (point-min))
22575 (while (re-search-forward (concat "^#\\+" (cadr fmt)
22576 ":[ \t]*\\(.*\\)") nil t)
22577 (replace-match "\\1" t)
22578 (add-text-properties
22579 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
22580 '(org-protected t))))
22581 (goto-char (point-min))
22582 (while (re-search-forward
22583 (concat "^#\\+"
22584 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
22585 (cadddr fmt) "\\>.*\n?") nil t)
22586 (if (car fmt)
22587 (add-text-properties (match-beginning 1) (1+ (match-end 1))
22588 '(org-protected t))
22589 (delete-region (match-beginning 0) (match-end 0))))))
22590
22591 ;; Protect quoted subtrees
22592 (goto-char (point-min))
22593 (while (re-search-forward re-quote nil t)
22594 (goto-char (match-beginning 0))
22595 (end-of-line 1)
22596 (add-text-properties (point) (org-end-of-subtree t)
22597 '(org-protected t)))
22598
22599 ;; Remove subtrees that are commented
22600 (goto-char (point-min))
22601 (while (re-search-forward re-commented nil t)
22602 (goto-char (match-beginning 0))
22603 (delete-region (point) (org-end-of-subtree t)))
22604
22605 ;; Remove special table lines
22606 (when org-export-table-remove-special-lines
22607 (goto-char (point-min))
22608 (while (re-search-forward "^[ \t]*|" nil t)
22609 (beginning-of-line 1)
22610 (if (or (looking-at "[ \t]*| *[!_^] *|")
22611 (and (looking-at ".*?| *<[0-9]+> *|")
22612 (not (looking-at ".*?| *[^ <|]"))))
22613 (delete-region (max (point-min) (1- (point-at-bol)))
22614 (point-at-eol))
22615 (end-of-line 1))))
22616
22617 ;; Specific LaTeX stuff
22618 (when latexp
22619 (require 'org-export-latex nil)
22620 (org-export-latex-cleaned-string))
22621
22622 ;; Specific HTML stuff
22623 (when htmlp
22624 ;; Convert LaTeX fragments to images
22625 (when (plist-get parameters :LaTeX-fragments)
22626 (org-format-latex
22627 (concat "ltxpng/" (file-name-sans-extension
22628 (file-name-nondirectory
22629 org-current-export-file)))
22630 org-current-export-dir nil "Creating LaTeX image %s"))
22631 (message "Exporting..."))
22632
22633 ;; Remove or replace comments
22634 (goto-char (point-min))
22635 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
22636 (if commentsp
22637 (progn (add-text-properties
22638 (match-beginning 0) (match-end 0) '(org-protected t))
22639 (replace-match (format commentsp (match-string 1)) t t))
22640 (replace-match "")))
22641
22642 ;; Find matches for radio targets and turn them into internal links
22643 (goto-char (point-min))
22644 (when re-radio
22645 (while (re-search-forward re-radio nil t)
22646 (org-if-unprotected
22647 (replace-match "\\1[[\\2]]"))))
22648
22649 ;; Find all links that contain a newline and put them into a single line
22650 (goto-char (point-min))
22651 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
22652 (org-if-unprotected
22653 (replace-match "\\1 \\3")
22654 (goto-char (match-beginning 0))))
22655
22656
22657 ;; Normalize links: Convert angle and plain links into bracket links
22658 ;; Expand link abbreviations
22659 (goto-char (point-min))
22660 (while (re-search-forward re-plain-link nil t)
22661 (goto-char (1- (match-end 0)))
22662 (org-if-unprotected
22663 (let* ((s (concat (match-string 1) "[[" (match-string 2)
22664 ":" (match-string 3) "]]")))
22665 ;; added 'org-link face to links
22666 (put-text-property 0 (length s) 'face 'org-link s)
22667 (replace-match s t t))))
22668 (goto-char (point-min))
22669 (while (re-search-forward re-angle-link nil t)
22670 (goto-char (1- (match-end 0)))
22671 (org-if-unprotected
22672 (let* ((s (concat (match-string 1) "[[" (match-string 2)
22673 ":" (match-string 3) "]]")))
22674 (put-text-property 0 (length s) 'face 'org-link s)
22675 (replace-match s t t))))
22676 (goto-char (point-min))
22677 (while (re-search-forward org-bracket-link-regexp nil t)
22678 (org-if-unprotected
22679 (let* ((s (concat "[[" (setq xx (save-match-data
22680 (org-link-expand-abbrev (match-string 1))))
22681 "]"
22682 (if (match-end 3)
22683 (match-string 2)
22684 (concat "[" xx "]"))
22685 "]")))
22686 (put-text-property 0 (length s) 'face 'org-link s)
22687 (replace-match s t t))))
22688
22689 ;; Find multiline emphasis and put them into single line
22690 (when (plist-get parameters :emph-multiline)
22691 (goto-char (point-min))
22692 (while (re-search-forward org-emph-re nil t)
22693 (if (not (= (char-after (match-beginning 3))
22694 (char-after (match-beginning 4))))
22695 (org-if-unprotected
22696 (subst-char-in-region (match-beginning 0) (match-end 0)
22697 ?\n ?\ t)
22698 (goto-char (1- (match-end 0))))
22699 (goto-char (1+ (match-beginning 0))))))
22700
22701 (setq rtn (buffer-string)))
22702 (kill-buffer " org-mode-tmp")
22703 rtn))
22704
22705 (defun org-export-grab-title-from-buffer ()
22706 "Get a title for the current document, from looking at the buffer."
22707 (let ((inhibit-read-only t))
22708 (save-excursion
22709 (goto-char (point-min))
22710 (let ((end (save-excursion (outline-next-heading) (point))))
22711 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
22712 ;; Mark the line so that it will not be exported as normal text.
22713 (org-unmodified
22714 (add-text-properties (match-beginning 0) (match-end 0)
22715 (list :org-license-to-kill t)))
22716 ;; Return the title string
22717 (org-trim (match-string 0)))))))
22718
22719 (defun org-export-get-title-from-subtree ()
22720 "Return subtree title and exclude it from export."
22721 (let (title (m (mark)))
22722 (save-excursion
22723 (goto-char (region-beginning))
22724 (when (and (org-at-heading-p)
22725 (>= (org-end-of-subtree t t) (region-end)))
22726 ;; This is a subtree, we take the title from the first heading
22727 (goto-char (region-beginning))
22728 (looking-at org-todo-line-regexp)
22729 (setq title (match-string 3))
22730 (org-unmodified
22731 (add-text-properties (point) (1+ (point-at-eol))
22732 (list :org-license-to-kill t)))))
22733 title))
22734
22735 (defun org-solidify-link-text (s &optional alist)
22736 "Take link text and make a safe target out of it."
22737 (save-match-data
22738 (let* ((rtn
22739 (mapconcat
22740 'identity
22741 (org-split-string s "[ \t\r\n]+") "--"))
22742 (a (assoc rtn alist)))
22743 (or (cdr a) rtn))))
22744
22745 (defun org-get-min-level (lines)
22746 "Get the minimum level in LINES."
22747 (let ((re "^\\(\\*+\\) ") l min)
22748 (catch 'exit
22749 (while (setq l (pop lines))
22750 (if (string-match re l)
22751 (throw 'exit (org-tr-level (length (match-string 1 l))))))
22752 1)))
22753
22754 ;; Variable holding the vector with section numbers
22755 (defvar org-section-numbers (make-vector org-level-max 0))
22756
22757 (defun org-init-section-numbers ()
22758 "Initialize the vector for the section numbers."
22759 (let* ((level -1)
22760 (numbers (nreverse (org-split-string "" "\\.")))
22761 (depth (1- (length org-section-numbers)))
22762 (i depth) number-string)
22763 (while (>= i 0)
22764 (if (> i level)
22765 (aset org-section-numbers i 0)
22766 (setq number-string (or (car numbers) "0"))
22767 (if (string-match "\\`[A-Z]\\'" number-string)
22768 (aset org-section-numbers i
22769 (- (string-to-char number-string) ?A -1))
22770 (aset org-section-numbers i (string-to-number number-string)))
22771 (pop numbers))
22772 (setq i (1- i)))))
22773
22774 (defun org-section-number (&optional level)
22775 "Return a string with the current section number.
22776 When LEVEL is non-nil, increase section numbers on that level."
22777 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
22778 (when level
22779 (when (> level -1)
22780 (aset org-section-numbers
22781 level (1+ (aref org-section-numbers level))))
22782 (setq idx (1+ level))
22783 (while (<= idx depth)
22784 (if (not (= idx 1))
22785 (aset org-section-numbers idx 0))
22786 (setq idx (1+ idx))))
22787 (setq idx 0)
22788 (while (<= idx depth)
22789 (setq n (aref org-section-numbers idx))
22790 (setq string (concat string (if (not (string= string "")) "." "")
22791 (int-to-string n)))
22792 (setq idx (1+ idx)))
22793 (save-match-data
22794 (if (string-match "\\`\\([@0]\\.\\)+" string)
22795 (setq string (replace-match "" t nil string)))
22796 (if (string-match "\\(\\.0\\)+\\'" string)
22797 (setq string (replace-match "" t nil string))))
22798 string))
22799
22800 ;;; ASCII export
22801
22802 (defvar org-last-level nil) ; dynamically scoped variable
22803 (defvar org-min-level nil) ; dynamically scoped variable
22804 (defvar org-levels-open nil) ; dynamically scoped parameter
22805 (defvar org-ascii-current-indentation nil) ; For communication
22806
22807 (defun org-export-as-ascii (arg)
22808 "Export the outline as a pretty ASCII file.
22809 If there is an active region, export only the region.
22810 The prefix ARG specifies how many levels of the outline should become
22811 underlined headlines. The default is 3."
22812 (interactive "P")
22813 (setq-default org-todo-line-regexp org-todo-line-regexp)
22814 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
22815 (org-infile-export-plist)))
22816 (region-p (org-region-active-p))
22817 (subtree-p
22818 (when region-p
22819 (save-excursion
22820 (goto-char (region-beginning))
22821 (and (org-at-heading-p)
22822 (>= (org-end-of-subtree t t) (region-end))))))
22823 (custom-times org-display-custom-times)
22824 (org-ascii-current-indentation '(0 . 0))
22825 (level 0) line txt
22826 (umax nil)
22827 (umax-toc nil)
22828 (case-fold-search nil)
22829 (filename (concat (file-name-as-directory
22830 (org-export-directory :ascii opt-plist))
22831 (file-name-sans-extension
22832 (or (and subtree-p
22833 (org-entry-get (region-beginning)
22834 "EXPORT_FILE_NAME" t))
22835 (file-name-nondirectory buffer-file-name)))
22836 ".txt"))
22837 (filename (if (equal (file-truename filename)
22838 (file-truename buffer-file-name))
22839 (concat filename ".txt")
22840 filename))
22841 (buffer (find-file-noselect filename))
22842 (org-levels-open (make-vector org-level-max nil))
22843 (odd org-odd-levels-only)
22844 (date (plist-get opt-plist :date))
22845 (author (plist-get opt-plist :author))
22846 (title (or (and subtree-p (org-export-get-title-from-subtree))
22847 (plist-get opt-plist :title)
22848 (and (not
22849 (plist-get opt-plist :skip-before-1st-heading))
22850 (org-export-grab-title-from-buffer))
22851 (file-name-sans-extension
22852 (file-name-nondirectory buffer-file-name))))
22853 (email (plist-get opt-plist :email))
22854 (language (plist-get opt-plist :language))
22855 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
22856 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
22857 (todo nil)
22858 (lang-words nil)
22859 (region
22860 (buffer-substring
22861 (if (org-region-active-p) (region-beginning) (point-min))
22862 (if (org-region-active-p) (region-end) (point-max))))
22863 (lines (org-split-string
22864 (org-cleaned-string-for-export
22865 region
22866 :for-ascii t
22867 :skip-before-1st-heading
22868 (plist-get opt-plist :skip-before-1st-heading)
22869 :archived-trees
22870 (plist-get opt-plist :archived-trees)
22871 :add-text (plist-get opt-plist :text))
22872 "\n"))
22873 thetoc have-headings first-heading-pos
22874 table-open table-buffer)
22875
22876 (let ((inhibit-read-only t))
22877 (org-unmodified
22878 (remove-text-properties (point-min) (point-max)
22879 '(:org-license-to-kill t))))
22880
22881 (setq org-min-level (org-get-min-level lines))
22882 (setq org-last-level org-min-level)
22883 (org-init-section-numbers)
22884
22885 (find-file-noselect filename)
22886
22887 (setq lang-words (or (assoc language org-export-language-setup)
22888 (assoc "en" org-export-language-setup)))
22889 (switch-to-buffer-other-window buffer)
22890 (erase-buffer)
22891 (fundamental-mode)
22892 ;; create local variables for all options, to make sure all called
22893 ;; functions get the correct information
22894 (mapc (lambda (x)
22895 (set (make-local-variable (cdr x))
22896 (plist-get opt-plist (car x))))
22897 org-export-plist-vars)
22898 (org-set-local 'org-odd-levels-only odd)
22899 (setq umax (if arg (prefix-numeric-value arg)
22900 org-export-headline-levels))
22901 (setq umax-toc (if (integerp org-export-with-toc)
22902 (min org-export-with-toc umax)
22903 umax))
22904
22905 ;; File header
22906 (if title (org-insert-centered title ?=))
22907 (insert "\n")
22908 (if (and (or author email)
22909 org-export-author-info)
22910 (insert (concat (nth 1 lang-words) ": " (or author "")
22911 (if email (concat " <" email ">") "")
22912 "\n")))
22913
22914 (cond
22915 ((and date (string-match "%" date))
22916 (setq date (format-time-string date (current-time))))
22917 (date)
22918 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
22919
22920 (if (and date org-export-time-stamp-file)
22921 (insert (concat (nth 2 lang-words) ": " date"\n")))
22922
22923 (insert "\n\n")
22924
22925 (if org-export-with-toc
22926 (progn
22927 (push (concat (nth 3 lang-words) "\n") thetoc)
22928 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
22929 (mapc '(lambda (line)
22930 (if (string-match org-todo-line-regexp
22931 line)
22932 ;; This is a headline
22933 (progn
22934 (setq have-headings t)
22935 (setq level (- (match-end 1) (match-beginning 1))
22936 level (org-tr-level level)
22937 txt (match-string 3 line)
22938 todo
22939 (or (and org-export-mark-todo-in-toc
22940 (match-beginning 2)
22941 (not (member (match-string 2 line)
22942 org-done-keywords)))
22943 ; TODO, not DONE
22944 (and org-export-mark-todo-in-toc
22945 (= level umax-toc)
22946 (org-search-todo-below
22947 line lines level))))
22948 (setq txt (org-html-expand-for-ascii txt))
22949
22950 (while (string-match org-bracket-link-regexp txt)
22951 (setq txt
22952 (replace-match
22953 (match-string (if (match-end 2) 3 1) txt)
22954 t t txt)))
22955
22956 (if (and (memq org-export-with-tags '(not-in-toc nil))
22957 (string-match
22958 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
22959 txt))
22960 (setq txt (replace-match "" t t txt)))
22961 (if (string-match quote-re0 txt)
22962 (setq txt (replace-match "" t t txt)))
22963
22964 (if org-export-with-section-numbers
22965 (setq txt (concat (org-section-number level)
22966 " " txt)))
22967 (if (<= level umax-toc)
22968 (progn
22969 (push
22970 (concat
22971 (make-string
22972 (* (max 0 (- level org-min-level)) 4) ?\ )
22973 (format (if todo "%s (*)\n" "%s\n") txt))
22974 thetoc)
22975 (setq org-last-level level))
22976 ))))
22977 lines)
22978 (setq thetoc (if have-headings (nreverse thetoc) nil))))
22979
22980 (org-init-section-numbers)
22981 (while (setq line (pop lines))
22982 ;; Remove the quoted HTML tags.
22983 (setq line (org-html-expand-for-ascii line))
22984 ;; Remove targets
22985 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
22986 (setq line (replace-match "" t t line)))
22987 ;; Replace internal links
22988 (while (string-match org-bracket-link-regexp line)
22989 (setq line (replace-match
22990 (if (match-end 3) "[\\3]" "[\\1]")
22991 t nil line)))
22992 (when custom-times
22993 (setq line (org-translate-time line)))
22994 (cond
22995 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
22996 ;; a Headline
22997 (setq first-heading-pos (or first-heading-pos (point)))
22998 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
22999 txt (match-string 2 line))
23000 (org-ascii-level-start level txt umax lines))
23001
23002 ((and org-export-with-tables
23003 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
23004 (if (not table-open)
23005 ;; New table starts
23006 (setq table-open t table-buffer nil))
23007 ;; Accumulate lines
23008 (setq table-buffer (cons line table-buffer))
23009 (when (or (not lines)
23010 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
23011 (car lines))))
23012 (setq table-open nil
23013 table-buffer (nreverse table-buffer))
23014 (insert (mapconcat
23015 (lambda (x)
23016 (org-fix-indentation x org-ascii-current-indentation))
23017 (org-format-table-ascii table-buffer)
23018 "\n") "\n")))
23019 (t
23020 (setq line (org-fix-indentation line org-ascii-current-indentation))
23021 (if (and org-export-with-fixed-width
23022 (string-match "^\\([ \t]*\\)\\(:\\)" line))
23023 (setq line (replace-match "\\1" nil nil line)))
23024 (insert line "\n"))))
23025
23026 (normal-mode)
23027
23028 ;; insert the table of contents
23029 (when thetoc
23030 (goto-char (point-min))
23031 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
23032 (progn
23033 (goto-char (match-beginning 0))
23034 (replace-match ""))
23035 (goto-char first-heading-pos))
23036 (mapc 'insert thetoc)
23037 (or (looking-at "[ \t]*\n[ \t]*\n")
23038 (insert "\n\n")))
23039
23040 ;; Convert whitespace place holders
23041 (goto-char (point-min))
23042 (let (beg end)
23043 (while (setq beg (next-single-property-change (point) 'org-whitespace))
23044 (setq end (next-single-property-change beg 'org-whitespace))
23045 (goto-char beg)
23046 (delete-region beg end)
23047 (insert (make-string (- end beg) ?\ ))))
23048
23049 (save-buffer)
23050 ;; remove display and invisible chars
23051 (let (beg end)
23052 (goto-char (point-min))
23053 (while (setq beg (next-single-property-change (point) 'display))
23054 (setq end (next-single-property-change beg 'display))
23055 (delete-region beg end)
23056 (goto-char beg)
23057 (insert "=>"))
23058 (goto-char (point-min))
23059 (while (setq beg (next-single-property-change (point) 'org-cwidth))
23060 (setq end (next-single-property-change beg 'org-cwidth))
23061 (delete-region beg end)
23062 (goto-char beg)))
23063 (goto-char (point-min))))
23064
23065 (defun org-search-todo-below (line lines level)
23066 "Search the subtree below LINE for any TODO entries."
23067 (let ((rest (cdr (memq line lines)))
23068 (re org-todo-line-regexp)
23069 line lv todo)
23070 (catch 'exit
23071 (while (setq line (pop rest))
23072 (if (string-match re line)
23073 (progn
23074 (setq lv (- (match-end 1) (match-beginning 1))
23075 todo (and (match-beginning 2)
23076 (not (member (match-string 2 line)
23077 org-done-keywords))))
23078 ; TODO, not DONE
23079 (if (<= lv level) (throw 'exit nil))
23080 (if todo (throw 'exit t))))))))
23081
23082 (defun org-html-expand-for-ascii (line)
23083 "Handle quoted HTML for ASCII export."
23084 (if org-export-html-expand
23085 (while (string-match "@<[^<>\n]*>" line)
23086 ;; We just remove the tags for now.
23087 (setq line (replace-match "" nil nil line))))
23088 line)
23089
23090 (defun org-insert-centered (s &optional underline)
23091 "Insert the string S centered and underline it with character UNDERLINE."
23092 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
23093 (insert (make-string ind ?\ ) s "\n")
23094 (if underline
23095 (insert (make-string ind ?\ )
23096 (make-string (string-width s) underline)
23097 "\n"))))
23098
23099 (defun org-ascii-level-start (level title umax &optional lines)
23100 "Insert a new level in ASCII export."
23101 (let (char (n (- level umax 1)) (ind 0))
23102 (if (> level umax)
23103 (progn
23104 (insert (make-string (* 2 n) ?\ )
23105 (char-to-string (nth (% n (length org-export-ascii-bullets))
23106 org-export-ascii-bullets))
23107 " " title "\n")
23108 ;; find the indentation of the next non-empty line
23109 (catch 'stop
23110 (while lines
23111 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
23112 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
23113 (throw 'stop (setq ind (org-get-indentation (car lines)))))
23114 (pop lines)))
23115 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
23116 (if (or (not (equal (char-before) ?\n))
23117 (not (equal (char-before (1- (point))) ?\n)))
23118 (insert "\n"))
23119 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
23120 (unless org-export-with-tags
23121 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
23122 (setq title (replace-match "" t t title))))
23123 (if org-export-with-section-numbers
23124 (setq title (concat (org-section-number level) " " title)))
23125 (insert title "\n" (make-string (string-width title) char) "\n")
23126 (setq org-ascii-current-indentation '(0 . 0)))))
23127
23128 (defun org-export-visible (type arg)
23129 "Create a copy of the visible part of the current buffer, and export it.
23130 The copy is created in a temporary buffer and removed after use.
23131 TYPE is the final key (as a string) that also select the export command in
23132 the `C-c C-e' export dispatcher.
23133 As a special case, if the you type SPC at the prompt, the temporary
23134 org-mode file will not be removed but presented to you so that you can
23135 continue to use it. The prefix arg ARG is passed through to the exporting
23136 command."
23137 (interactive
23138 (list (progn
23139 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
23140 (read-char-exclusive))
23141 current-prefix-arg))
23142 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
23143 (error "Invalid export key"))
23144 (let* ((binding (cdr (assoc type
23145 '((?a . org-export-as-ascii)
23146 (?\C-a . org-export-as-ascii)
23147 (?b . org-export-as-html-and-open)
23148 (?\C-b . org-export-as-html-and-open)
23149 (?h . org-export-as-html)
23150 (?H . org-export-as-html-to-buffer)
23151 (?R . org-export-region-as-html)
23152 (?x . org-export-as-xoxo)))))
23153 (keepp (equal type ?\ ))
23154 (file buffer-file-name)
23155 (buffer (get-buffer-create "*Org Export Visible*"))
23156 s e)
23157 ;; Need to hack the drawers here.
23158 (save-excursion
23159 (goto-char (point-min))
23160 (while (re-search-forward org-drawer-regexp nil t)
23161 (goto-char (match-beginning 1))
23162 (or (org-invisible-p) (org-flag-drawer nil))))
23163 (with-current-buffer buffer (erase-buffer))
23164 (save-excursion
23165 (setq s (goto-char (point-min)))
23166 (while (not (= (point) (point-max)))
23167 (goto-char (org-find-invisible))
23168 (append-to-buffer buffer s (point))
23169 (setq s (goto-char (org-find-visible))))
23170 (org-cycle-hide-drawers 'all)
23171 (goto-char (point-min))
23172 (unless keepp
23173 ;; Copy all comment lines to the end, to make sure #+ settings are
23174 ;; still available for the second export step. Kind of a hack, but
23175 ;; does do the trick.
23176 (if (looking-at "#[^\r\n]*")
23177 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
23178 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
23179 (append-to-buffer buffer (1+ (match-beginning 0))
23180 (min (point-max) (1+ (match-end 0))))))
23181 (set-buffer buffer)
23182 (let ((buffer-file-name file)
23183 (org-inhibit-startup t))
23184 (org-mode)
23185 (show-all)
23186 (unless keepp (funcall binding arg))))
23187 (if (not keepp)
23188 (kill-buffer buffer)
23189 (switch-to-buffer-other-window buffer)
23190 (goto-char (point-min)))))
23191
23192 (defun org-find-visible ()
23193 (let ((s (point)))
23194 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23195 (get-char-property s 'invisible)))
23196 s))
23197 (defun org-find-invisible ()
23198 (let ((s (point)))
23199 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23200 (not (get-char-property s 'invisible))))
23201 s))
23202
23203 ;;; HTML export
23204
23205 (defun org-get-current-options ()
23206 "Return a string with current options as keyword options.
23207 Does include HTML export options as well as TODO and CATEGORY stuff."
23208 (format
23209 "#+TITLE: %s
23210 #+AUTHOR: %s
23211 #+EMAIL: %s
23212 #+LANGUAGE: %s
23213 #+TEXT: Some descriptive text to be emitted. Several lines OK.
23214 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s d:%s tags:%s
23215 #+CATEGORY: %s
23216 #+SEQ_TODO: %s
23217 #+TYP_TODO: %s
23218 #+PRIORITIES: %c %c %c
23219 #+DRAWERS: %s
23220 #+STARTUP: %s %s %s %s %s
23221 #+TAGS: %s
23222 #+ARCHIVE: %s
23223 #+LINK: %s
23224 "
23225 (buffer-name) (user-full-name) user-mail-address org-export-default-language
23226 org-export-headline-levels
23227 org-export-with-section-numbers
23228 org-export-with-toc
23229 org-export-preserve-breaks
23230 org-export-html-expand
23231 org-export-with-fixed-width
23232 org-export-with-tables
23233 org-export-with-sub-superscripts
23234 org-export-with-footnotes
23235 org-export-with-emphasize
23236 org-export-with-TeX-macros
23237 org-export-with-LaTeX-fragments
23238 org-export-skip-text-before-1st-heading
23239 org-export-with-drawers
23240 org-export-with-tags
23241 (file-name-nondirectory buffer-file-name)
23242 "TODO FEEDBACK VERIFY DONE"
23243 "Me Jason Marie DONE"
23244 org-highest-priority org-lowest-priority org-default-priority
23245 (mapconcat 'identity org-drawers " ")
23246 (cdr (assoc org-startup-folded
23247 '((nil . "showall") (t . "overview") (content . "content"))))
23248 (if org-odd-levels-only "odd" "oddeven")
23249 (if org-hide-leading-stars "hidestars" "showstars")
23250 (if org-startup-align-all-tables "align" "noalign")
23251 (cond ((eq t org-log-done) "logdone")
23252 ((not org-log-done) "nologging")
23253 ((listp org-log-done)
23254 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
23255 org-log-done " ")))
23256 (or (mapconcat (lambda (x)
23257 (cond
23258 ((equal '(:startgroup) x) "{")
23259 ((equal '(:endgroup) x) "}")
23260 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
23261 (t (car x))))
23262 (or org-tag-alist (org-get-buffer-tags)) " ") "")
23263 org-archive-location
23264 "org file:~/org/%s.org"
23265 ))
23266
23267 (defun org-insert-export-options-template ()
23268 "Insert into the buffer a template with information for exporting."
23269 (interactive)
23270 (if (not (bolp)) (newline))
23271 (let ((s (org-get-current-options)))
23272 (and (string-match "#\\+CATEGORY" s)
23273 (setq s (substring s 0 (match-beginning 0))))
23274 (insert s)))
23275
23276 (defun org-toggle-fixed-width-section (arg)
23277 "Toggle the fixed-width export.
23278 If there is no active region, the QUOTE keyword at the current headline is
23279 inserted or removed. When present, it causes the text between this headline
23280 and the next to be exported as fixed-width text, and unmodified.
23281 If there is an active region, this command adds or removes a colon as the
23282 first character of this line. If the first character of a line is a colon,
23283 this line is also exported in fixed-width font."
23284 (interactive "P")
23285 (let* ((cc 0)
23286 (regionp (org-region-active-p))
23287 (beg (if regionp (region-beginning) (point)))
23288 (end (if regionp (region-end)))
23289 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
23290 (re "[ \t]*\\(:\\)")
23291 off)
23292 (if regionp
23293 (save-excursion
23294 (goto-char beg)
23295 (setq cc (current-column))
23296 (beginning-of-line 1)
23297 (setq off (looking-at re))
23298 (while (> nlines 0)
23299 (setq nlines (1- nlines))
23300 (beginning-of-line 1)
23301 (cond
23302 (arg
23303 (move-to-column cc t)
23304 (insert ":\n")
23305 (forward-line -1))
23306 ((and off (looking-at re))
23307 (replace-match "" t t nil 1))
23308 ((not off) (move-to-column cc t) (insert ":")))
23309 (forward-line 1)))
23310 (save-excursion
23311 (org-back-to-heading)
23312 (if (looking-at (concat outline-regexp
23313 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
23314 (replace-match "" t t nil 1)
23315 (if (looking-at outline-regexp)
23316 (progn
23317 (goto-char (match-end 0))
23318 (insert org-quote-string " "))))))))
23319
23320 (defun org-export-as-html-and-open (arg)
23321 "Export the outline as HTML and immediately open it with a browser.
23322 If there is an active region, export only the region.
23323 The prefix ARG specifies how many levels of the outline should become
23324 headlines. The default is 3. Lower levels will become bulleted lists."
23325 (interactive "P")
23326 (org-export-as-html arg 'hidden)
23327 (org-open-file buffer-file-name))
23328
23329 (defun org-export-as-html-batch ()
23330 "Call `org-export-as-html', may be used in batch processing as
23331 emacs --batch
23332 --load=$HOME/lib/emacs/org.el
23333 --eval \"(setq org-export-headline-levels 2)\"
23334 --visit=MyFile --funcall org-export-as-html-batch"
23335 (org-export-as-html org-export-headline-levels 'hidden))
23336
23337 (defun org-export-as-html-to-buffer (arg)
23338 "Call `org-exort-as-html` with output to a temporary buffer.
23339 No file is created. The prefix ARG is passed through to `org-export-as-html'."
23340 (interactive "P")
23341 (org-export-as-html arg nil nil "*Org HTML Export*")
23342 (switch-to-buffer-other-window "*Org HTML Export*"))
23343
23344 (defun org-replace-region-by-html (beg end)
23345 "Assume the current region has org-mode syntax, and convert it to HTML.
23346 This can be used in any buffer. For example, you could write an
23347 itemized list in org-mode syntax in an HTML buffer and then use this
23348 command to convert it."
23349 (interactive "r")
23350 (let (reg html buf pop-up-frames)
23351 (save-window-excursion
23352 (if (org-mode-p)
23353 (setq html (org-export-region-as-html
23354 beg end t 'string))
23355 (setq reg (buffer-substring beg end)
23356 buf (get-buffer-create "*Org tmp*"))
23357 (with-current-buffer buf
23358 (erase-buffer)
23359 (insert reg)
23360 (org-mode)
23361 (setq html (org-export-region-as-html
23362 (point-min) (point-max) t 'string)))
23363 (kill-buffer buf)))
23364 (delete-region beg end)
23365 (insert html)))
23366
23367 (defun org-export-region-as-html (beg end &optional body-only buffer)
23368 "Convert region from BEG to END in org-mode buffer to HTML.
23369 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
23370 contents, and only produce the region of converted text, useful for
23371 cut-and-paste operations.
23372 If BUFFER is a buffer or a string, use/create that buffer as a target
23373 of the converted HTML. If BUFFER is the symbol `string', return the
23374 produced HTML as a string and leave not buffer behind. For example,
23375 a Lisp program could call this function in the following way:
23376
23377 (setq html (org-export-region-as-html beg end t 'string))
23378
23379 When called interactively, the output buffer is selected, and shown
23380 in a window. A non-interactive call will only retunr the buffer."
23381 (interactive "r\nP")
23382 (when (interactive-p)
23383 (setq buffer "*Org HTML Export*"))
23384 (let ((transient-mark-mode t) (zmacs-regions t)
23385 rtn)
23386 (goto-char end)
23387 (set-mark (point)) ;; to activate the region
23388 (goto-char beg)
23389 (setq rtn (org-export-as-html
23390 nil nil nil
23391 buffer body-only))
23392 (if (fboundp 'deactivate-mark) (deactivate-mark))
23393 (if (and (interactive-p) (bufferp rtn))
23394 (switch-to-buffer-other-window rtn)
23395 rtn)))
23396
23397 (defun org-export-as-html (arg &optional hidden ext-plist
23398 to-buffer body-only)
23399 "Export the outline as a pretty HTML file.
23400 If there is an active region, export only the region. The prefix
23401 ARG specifies how many levels of the outline should become
23402 headlines. The default is 3. Lower levels will become bulleted
23403 lists. When HIDDEN is non-nil, don't display the HTML buffer.
23404 EXT-PLIST is a property list with external parameters overriding
23405 org-mode's default settings, but still inferior to file-local
23406 settings. When TO-BUFFER is non-nil, create a buffer with that
23407 name and export to that buffer. If TO-BUFFER is the symbol `string',
23408 don't leave any buffer behind but just return the resulting HTML as
23409 a string. When BODY-ONLY is set, don't produce the file header and footer,
23410 simply return the content of <body>...</body>, without even
23411 the body tags themselves."
23412 (interactive "P")
23413
23414 ;; Make sure we have a file name when we need it.
23415 (when (and (not (or to-buffer body-only))
23416 (not buffer-file-name))
23417 (if (buffer-base-buffer)
23418 (org-set-local 'buffer-file-name
23419 (with-current-buffer (buffer-base-buffer)
23420 buffer-file-name))
23421 (error "Need a file name to be able to export.")))
23422
23423 (message "Exporting...")
23424 (setq-default org-todo-line-regexp org-todo-line-regexp)
23425 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
23426 (setq-default org-done-keywords org-done-keywords)
23427 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
23428 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23429 ext-plist
23430 (org-infile-export-plist)))
23431
23432 (style (plist-get opt-plist :style))
23433 (link-validate (plist-get opt-plist :link-validation-function))
23434 valid thetoc have-headings first-heading-pos
23435 (odd org-odd-levels-only)
23436 (region-p (org-region-active-p))
23437 (subtree-p
23438 (when region-p
23439 (save-excursion
23440 (goto-char (region-beginning))
23441 (and (org-at-heading-p)
23442 (>= (org-end-of-subtree t t) (region-end))))))
23443 ;; The following two are dynamically scoped into other
23444 ;; routines below.
23445 (org-current-export-dir (org-export-directory :html opt-plist))
23446 (org-current-export-file buffer-file-name)
23447 (level 0) (line "") (origline "") txt todo
23448 (umax nil)
23449 (umax-toc nil)
23450 (filename (if to-buffer nil
23451 (concat (file-name-as-directory
23452 (org-export-directory :html opt-plist))
23453 (file-name-sans-extension
23454 (or (and subtree-p
23455 (org-entry-get (region-beginning)
23456 "EXPORT_FILE_NAME" t))
23457 (file-name-nondirectory buffer-file-name)))
23458 "." org-export-html-extension)))
23459 (current-dir (if buffer-file-name
23460 (file-name-directory buffer-file-name)
23461 default-directory))
23462 (buffer (if to-buffer
23463 (cond
23464 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
23465 (t (get-buffer-create to-buffer)))
23466 (find-file-noselect filename)))
23467 (org-levels-open (make-vector org-level-max nil))
23468 (date (plist-get opt-plist :date))
23469 (author (plist-get opt-plist :author))
23470 (title (or (and subtree-p (org-export-get-title-from-subtree))
23471 (plist-get opt-plist :title)
23472 (and (not
23473 (plist-get opt-plist :skip-before-1st-heading))
23474 (org-export-grab-title-from-buffer))
23475 (and buffer-file-name
23476 (file-name-sans-extension
23477 (file-name-nondirectory buffer-file-name)))
23478 "UNTITLED"))
23479 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
23480 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
23481 (inquote nil)
23482 (infixed nil)
23483 (in-local-list nil)
23484 (local-list-num nil)
23485 (local-list-indent nil)
23486 (llt org-plain-list-ordered-item-terminator)
23487 (email (plist-get opt-plist :email))
23488 (language (plist-get opt-plist :language))
23489 (lang-words nil)
23490 (target-alist nil) tg
23491 (head-count 0) cnt
23492 (start 0)
23493 (coding-system (and (boundp 'buffer-file-coding-system)
23494 buffer-file-coding-system))
23495 (coding-system-for-write (or org-export-html-coding-system
23496 coding-system))
23497 (save-buffer-coding-system (or org-export-html-coding-system
23498 coding-system))
23499 (charset (and coding-system-for-write
23500 (fboundp 'coding-system-get)
23501 (coding-system-get coding-system-for-write
23502 'mime-charset)))
23503 (region
23504 (buffer-substring
23505 (if region-p (region-beginning) (point-min))
23506 (if region-p (region-end) (point-max))))
23507 (lines
23508 (org-split-string
23509 (org-cleaned-string-for-export
23510 region
23511 :emph-multiline t
23512 :for-html t
23513 :skip-before-1st-heading
23514 (plist-get opt-plist :skip-before-1st-heading)
23515 :archived-trees
23516 (plist-get opt-plist :archived-trees)
23517 :add-text
23518 (plist-get opt-plist :text)
23519 :LaTeX-fragments
23520 (plist-get opt-plist :LaTeX-fragments))
23521 "[\r\n]"))
23522 table-open type
23523 table-buffer table-orig-buffer
23524 ind start-is-num starter didclose
23525 rpl path desc descp desc1 desc2 link
23526 )
23527
23528 (let ((inhibit-read-only t))
23529 (org-unmodified
23530 (remove-text-properties (point-min) (point-max)
23531 '(:org-license-to-kill t))))
23532
23533 (message "Exporting...")
23534
23535 (setq org-min-level (org-get-min-level lines))
23536 (setq org-last-level org-min-level)
23537 (org-init-section-numbers)
23538
23539 (cond
23540 ((and date (string-match "%" date))
23541 (setq date (format-time-string date (current-time))))
23542 (date)
23543 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
23544
23545 ;; Get the language-dependent settings
23546 (setq lang-words (or (assoc language org-export-language-setup)
23547 (assoc "en" org-export-language-setup)))
23548
23549 ;; Switch to the output buffer
23550 (set-buffer buffer)
23551 (erase-buffer)
23552 (fundamental-mode)
23553
23554 (and (fboundp 'set-buffer-file-coding-system)
23555 (set-buffer-file-coding-system coding-system-for-write))
23556
23557 (let ((case-fold-search nil)
23558 (org-odd-levels-only odd))
23559 ;; create local variables for all options, to make sure all called
23560 ;; functions get the correct information
23561 (mapc (lambda (x)
23562 (set (make-local-variable (cdr x))
23563 (plist-get opt-plist (car x))))
23564 org-export-plist-vars)
23565 (setq umax (if arg (prefix-numeric-value arg)
23566 org-export-headline-levels))
23567 (setq umax-toc (if (integerp org-export-with-toc)
23568 (min org-export-with-toc umax)
23569 umax))
23570 (unless body-only
23571 ;; File header
23572 (insert (format
23573 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
23574 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
23575 <html xmlns=\"http://www.w3.org/1999/xhtml\"
23576 lang=\"%s\" xml:lang=\"%s\">
23577 <head>
23578 <title>%s</title>
23579 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
23580 <meta name=\"generator\" content=\"Org-mode\"/>
23581 <meta name=\"generated\" content=\"%s\"/>
23582 <meta name=\"author\" content=\"%s\"/>
23583 %s
23584 </head><body>
23585 "
23586 language language (org-html-expand title)
23587 (or charset "iso-8859-1") date author style))
23588
23589 (insert (or (plist-get opt-plist :preamble) ""))
23590
23591 (when (plist-get opt-plist :auto-preamble)
23592 (if title (insert (format org-export-html-title-format
23593 (org-html-expand title))))))
23594
23595 (if (and org-export-with-toc (not body-only))
23596 (progn
23597 (push (format "<h%d>%s</h%d>\n"
23598 org-export-html-toplevel-hlevel
23599 (nth 3 lang-words)
23600 org-export-html-toplevel-hlevel)
23601 thetoc)
23602 (push "<ul>\n<li>" thetoc)
23603 (setq lines
23604 (mapcar '(lambda (line)
23605 (if (string-match org-todo-line-regexp line)
23606 ;; This is a headline
23607 (progn
23608 (setq have-headings t)
23609 (setq level (- (match-end 1) (match-beginning 1))
23610 level (org-tr-level level)
23611 txt (save-match-data
23612 (org-html-expand
23613 (org-export-cleanup-toc-line
23614 (match-string 3 line))))
23615 todo
23616 (or (and org-export-mark-todo-in-toc
23617 (match-beginning 2)
23618 (not (member (match-string 2 line)
23619 org-done-keywords)))
23620 ; TODO, not DONE
23621 (and org-export-mark-todo-in-toc
23622 (= level umax-toc)
23623 (org-search-todo-below
23624 line lines level))))
23625 (if (string-match
23626 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
23627 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
23628 (if (string-match quote-re0 txt)
23629 (setq txt (replace-match "" t t txt)))
23630 (if org-export-with-section-numbers
23631 (setq txt (concat (org-section-number level)
23632 " " txt)))
23633 (if (<= level (max umax umax-toc))
23634 (setq head-count (+ head-count 1)))
23635 (if (<= level umax-toc)
23636 (progn
23637 (if (> level org-last-level)
23638 (progn
23639 (setq cnt (- level org-last-level))
23640 (while (>= (setq cnt (1- cnt)) 0)
23641 (push "\n<ul>\n<li>" thetoc))
23642 (push "\n" thetoc)))
23643 (if (< level org-last-level)
23644 (progn
23645 (setq cnt (- org-last-level level))
23646 (while (>= (setq cnt (1- cnt)) 0)
23647 (push "</li>\n</ul>" thetoc))
23648 (push "\n" thetoc)))
23649 ;; Check for targets
23650 (while (string-match org-target-regexp line)
23651 (setq tg (match-string 1 line)
23652 line (replace-match
23653 (concat "@<span class=\"target\">" tg "@</span> ")
23654 t t line))
23655 (push (cons (org-solidify-link-text tg)
23656 (format "sec-%d" head-count))
23657 target-alist))
23658 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
23659 (setq txt (replace-match "" t t txt)))
23660 (push
23661 (format
23662 (if todo
23663 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
23664 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
23665 head-count txt) thetoc)
23666
23667 (setq org-last-level level))
23668 )))
23669 line)
23670 lines))
23671 (while (> org-last-level (1- org-min-level))
23672 (setq org-last-level (1- org-last-level))
23673 (push "</li>\n</ul>\n" thetoc))
23674 (setq thetoc (if have-headings (nreverse thetoc) nil))))
23675
23676 (setq head-count 0)
23677 (org-init-section-numbers)
23678
23679 (while (setq line (pop lines) origline line)
23680 (catch 'nextline
23681
23682 ;; end of quote section?
23683 (when (and inquote (string-match "^\\*+ " line))
23684 (insert "</pre>\n")
23685 (setq inquote nil))
23686 ;; inside a quote section?
23687 (when inquote
23688 (insert (org-html-protect line) "\n")
23689 (throw 'nextline nil))
23690
23691 ;; verbatim lines
23692 (when (and org-export-with-fixed-width
23693 (string-match "^[ \t]*:\\(.*\\)" line))
23694 (when (not infixed)
23695 (setq infixed t)
23696 (insert "<pre>\n"))
23697 (insert (org-html-protect (match-string 1 line)) "\n")
23698 (when (and lines
23699 (not (string-match "^[ \t]*\\(:.*\\)"
23700 (car lines))))
23701 (setq infixed nil)
23702 (insert "</pre>\n"))
23703 (throw 'nextline nil))
23704
23705 ;; Protected HTML
23706 (when (get-text-property 0 'org-protected line)
23707 (let (par)
23708 (when (re-search-backward
23709 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
23710 (setq par (match-string 1))
23711 (replace-match "\\2\n"))
23712 (insert line "\n")
23713 (while (and lines
23714 (get-text-property 0 'org-protected (car lines)))
23715 (insert (pop lines) "\n"))
23716 (and par (insert "<p>\n")))
23717 (throw 'nextline nil))
23718
23719 ;; Horizontal line
23720 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
23721 (insert "\n<hr/>\n")
23722 (throw 'nextline nil))
23723
23724 ;; make targets to anchors
23725 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
23726 (cond
23727 ((match-end 2)
23728 (setq line (replace-match
23729 (concat "@<a name=\""
23730 (org-solidify-link-text (match-string 1 line))
23731 "\">\\nbsp@</a>")
23732 t t line)))
23733 ((and org-export-with-toc (equal (string-to-char line) ?*))
23734 (setq line (replace-match
23735 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
23736 ; (concat "@<i>" (match-string 1 line) "@</i> ")
23737 t t line)))
23738 (t
23739 (setq line (replace-match
23740 (concat "@<a name=\""
23741 (org-solidify-link-text (match-string 1 line))
23742 "\" class=\"target\">" (match-string 1 line) "@</a> ")
23743 t t line)))))
23744
23745 (setq line (org-html-handle-time-stamps line))
23746
23747 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
23748 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
23749 ;; Also handle sub_superscripts and checkboxes
23750 (setq line (org-html-expand line))
23751
23752 ;; Format the links
23753 (setq start 0)
23754 (while (string-match org-bracket-link-analytic-regexp line start)
23755 (setq start (match-beginning 0))
23756 (setq type (if (match-end 2) (match-string 2 line) "internal"))
23757 (setq path (match-string 3 line))
23758 (setq desc1 (if (match-end 5) (match-string 5 line))
23759 desc2 (if (match-end 2) (concat type ":" path) path)
23760 descp (and desc1 (not (equal desc1 desc2)))
23761 desc (or desc1 desc2))
23762 ;; Make an image out of the description if that is so wanted
23763 (when (and descp (org-file-image-p desc))
23764 (save-match-data
23765 (if (string-match "^file:" desc)
23766 (setq desc (substring desc (match-end 0)))))
23767 (setq desc (concat "<img src=\"" desc "\"/>")))
23768 ;; FIXME: do we need to unescape here somewhere?
23769 (cond
23770 ((equal type "internal")
23771 (setq rpl
23772 (concat
23773 "<a href=\"#"
23774 (org-solidify-link-text
23775 (save-match-data (org-link-unescape path)) target-alist)
23776 "\">" desc "</a>")))
23777 ((member type '("http" "https"))
23778 ;; standard URL, just check if we need to inline an image
23779 (if (and (or (eq t org-export-html-inline-images)
23780 (and org-export-html-inline-images (not descp)))
23781 (org-file-image-p path))
23782 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
23783 (setq link (concat type ":" path))
23784 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
23785 ((member type '("ftp" "mailto" "news"))
23786 ;; standard URL
23787 (setq link (concat type ":" path))
23788 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
23789 ((string= type "file")
23790 ;; FILE link
23791 (let* ((filename path)
23792 (abs-p (file-name-absolute-p filename))
23793 thefile file-is-image-p search)
23794 (save-match-data
23795 (if (string-match "::\\(.*\\)" filename)
23796 (setq search (match-string 1 filename)
23797 filename (replace-match "" t nil filename)))
23798 (setq valid
23799 (if (functionp link-validate)
23800 (funcall link-validate filename current-dir)
23801 t))
23802 (setq file-is-image-p (org-file-image-p filename))
23803 (setq thefile (if abs-p (expand-file-name filename) filename))
23804 (when (and org-export-html-link-org-files-as-html
23805 (string-match "\\.org$" thefile))
23806 (setq thefile (concat (substring thefile 0
23807 (match-beginning 0))
23808 "." org-export-html-extension))
23809 (if (and search
23810 ;; make sure this is can be used as target search
23811 (not (string-match "^[0-9]*$" search))
23812 (not (string-match "^\\*" search))
23813 (not (string-match "^/.*/$" search)))
23814 (setq thefile (concat thefile "#"
23815 (org-solidify-link-text
23816 (org-link-unescape search)))))
23817 (when (string-match "^file:" desc)
23818 (setq desc (replace-match "" t t desc))
23819 (if (string-match "\\.org$" desc)
23820 (setq desc (replace-match "" t t desc))))))
23821 (setq rpl (if (and file-is-image-p
23822 (or (eq t org-export-html-inline-images)
23823 (and org-export-html-inline-images
23824 (not descp))))
23825 (concat "<img src=\"" thefile "\"/>")
23826 (concat "<a href=\"" thefile "\">" desc "</a>")))
23827 (if (not valid) (setq rpl desc))))
23828 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
23829 (setq rpl (concat "<i>&lt;" type ":"
23830 (save-match-data (org-link-unescape path))
23831 "&gt;</i>"))))
23832 (setq line (replace-match rpl t t line)
23833 start (+ start (length rpl))))
23834
23835 ;; TODO items
23836 (if (and (string-match org-todo-line-regexp line)
23837 (match-beginning 2))
23838
23839 (setq line
23840 (concat (substring line 0 (match-beginning 2))
23841 "<span class=\""
23842 (if (member (match-string 2 line)
23843 org-done-keywords)
23844 "done" "todo")
23845 "\">" (match-string 2 line)
23846 "</span>" (substring line (match-end 2)))))
23847
23848 ;; Does this contain a reference to a footnote?
23849 (when org-export-with-footnotes
23850 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line)
23851 (let ((n (match-string 2 line)))
23852 (setq line
23853 (replace-match
23854 (format
23855 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
23856 (match-string 1 line) n n n)
23857 t t line)))))
23858
23859 (cond
23860 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
23861 ;; This is a headline
23862 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
23863 txt (match-string 2 line))
23864 (if (string-match quote-re0 txt)
23865 (setq txt (replace-match "" t t txt)))
23866 (if (<= level (max umax umax-toc))
23867 (setq head-count (+ head-count 1)))
23868 (when in-local-list
23869 ;; Close any local lists before inserting a new header line
23870 (while local-list-num
23871 (org-close-li)
23872 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
23873 (pop local-list-num))
23874 (setq local-list-indent nil
23875 in-local-list nil))
23876 (setq first-heading-pos (or first-heading-pos (point)))
23877 (org-html-level-start level txt umax
23878 (and org-export-with-toc (<= level umax))
23879 head-count)
23880 ;; QUOTES
23881 (when (string-match quote-re line)
23882 (insert "<pre>")
23883 (setq inquote t)))
23884
23885 ((and org-export-with-tables
23886 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
23887 (if (not table-open)
23888 ;; New table starts
23889 (setq table-open t table-buffer nil table-orig-buffer nil))
23890 ;; Accumulate lines
23891 (setq table-buffer (cons line table-buffer)
23892 table-orig-buffer (cons origline table-orig-buffer))
23893 (when (or (not lines)
23894 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
23895 (car lines))))
23896 (setq table-open nil
23897 table-buffer (nreverse table-buffer)
23898 table-orig-buffer (nreverse table-orig-buffer))
23899 (org-close-par-maybe)
23900 (insert (org-format-table-html table-buffer table-orig-buffer))))
23901 (t
23902 ;; Normal lines
23903 (when (string-match
23904 (cond
23905 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23906 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23907 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23908 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
23909 line)
23910 (setq ind (org-get-string-indentation line)
23911 start-is-num (match-beginning 4)
23912 starter (if (match-beginning 2)
23913 (substring (match-string 2 line) 0 -1))
23914 line (substring line (match-beginning 5)))
23915 (unless (string-match "[^ \t]" line)
23916 ;; empty line. Pretend indentation is large.
23917 (setq ind (if org-empty-line-terminates-plain-lists
23918 0
23919 (1+ (or (car local-list-indent) 1)))))
23920 (setq didclose nil)
23921 (while (and in-local-list
23922 (or (and (= ind (car local-list-indent))
23923 (not starter))
23924 (< ind (car local-list-indent))))
23925 (setq didclose t)
23926 (org-close-li)
23927 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
23928 (pop local-list-num) (pop local-list-indent)
23929 (setq in-local-list local-list-indent))
23930 (cond
23931 ((and starter
23932 (or (not in-local-list)
23933 (> ind (car local-list-indent))))
23934 ;; Start new (level of) list
23935 (org-close-par-maybe)
23936 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
23937 (push start-is-num local-list-num)
23938 (push ind local-list-indent)
23939 (setq in-local-list t))
23940 (starter
23941 ;; continue current list
23942 (org-close-li)
23943 (insert "<li>\n"))
23944 (didclose
23945 ;; we did close a list, normal text follows: need <p>
23946 (org-open-par)))
23947 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
23948 (setq line
23949 (replace-match
23950 (if (equal (match-string 1 line) "X")
23951 "<b>[X]</b>"
23952 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
23953 t t line))))
23954
23955 ;; Empty lines start a new paragraph. If hand-formatted lists
23956 ;; are not fully interpreted, lines starting with "-", "+", "*"
23957 ;; also start a new paragraph.
23958 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
23959
23960 ;; Is this the start of a footnote?
23961 (when org-export-with-footnotes
23962 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
23963 (org-close-par-maybe)
23964 (let ((n (match-string 1 line)))
23965 (setq line (replace-match
23966 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
23967
23968 ;; Check if the line break needs to be conserved
23969 (cond
23970 ((string-match "\\\\\\\\[ \t]*$" line)
23971 (setq line (replace-match "<br/>" t t line)))
23972 (org-export-preserve-breaks
23973 (setq line (concat line "<br/>"))))
23974
23975 (insert line "\n")))))
23976
23977 ;; Properly close all local lists and other lists
23978 (when inquote (insert "</pre>\n"))
23979 (when in-local-list
23980 ;; Close any local lists before inserting a new header line
23981 (while local-list-num
23982 (org-close-li)
23983 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
23984 (pop local-list-num))
23985 (setq local-list-indent nil
23986 in-local-list nil))
23987 (org-html-level-start 0 nil umax
23988 (and org-export-with-toc (<= level umax))
23989 head-count)
23990
23991 (unless body-only
23992 (when (plist-get opt-plist :auto-postamble)
23993 (insert "<div id=\"postamble\">")
23994 (when (and org-export-author-info author)
23995 (insert "<p class=\"author\"> "
23996 (nth 1 lang-words) ": " author "\n")
23997 (when email
23998 (insert "<a href=\"mailto:" email "\">&lt;"
23999 email "&gt;</a>\n"))
24000 (insert "</p>\n"))
24001 (when (and date org-export-time-stamp-file)
24002 (insert "<p class=\"date\"> "
24003 (nth 2 lang-words) ": "
24004 date "</p>\n"))
24005 (insert "</div>"))
24006
24007 (if org-export-html-with-timestamp
24008 (insert org-export-html-html-helper-timestamp))
24009 (insert (or (plist-get opt-plist :postamble) ""))
24010 (insert "</body>\n</html>\n"))
24011
24012 (normal-mode)
24013 (if (eq major-mode default-major-mode) (html-mode))
24014
24015 ;; insert the table of contents
24016 (goto-char (point-min))
24017 (when thetoc
24018 (if (or (re-search-forward
24019 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
24020 (re-search-forward
24021 "\\[TABLE-OF-CONTENTS\\]" nil t))
24022 (progn
24023 (goto-char (match-beginning 0))
24024 (replace-match ""))
24025 (goto-char first-heading-pos)
24026 (when (looking-at "\\s-*</p>")
24027 (goto-char (match-end 0))
24028 (insert "\n")))
24029 (insert "<div id=\"table-of-contents\">\n")
24030 (mapc 'insert thetoc)
24031 (insert "</div>\n"))
24032 ;; remove empty paragraphs and lists
24033 (goto-char (point-min))
24034 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
24035 (replace-match ""))
24036 (goto-char (point-min))
24037 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
24038 (replace-match ""))
24039 ;; Convert whitespace place holders
24040 (goto-char (point-min))
24041 (let (beg end n)
24042 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24043 (setq n (get-text-property beg 'org-whitespace)
24044 end (next-single-property-change beg 'org-whitespace))
24045 (goto-char beg)
24046 (delete-region beg end)
24047 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
24048 (make-string n ?x)))))
24049
24050 (or to-buffer (save-buffer))
24051 (goto-char (point-min))
24052 (message "Exporting... done")
24053 (if (eq to-buffer 'string)
24054 (prog1 (buffer-substring (point-min) (point-max))
24055 (kill-buffer (current-buffer)))
24056 (current-buffer)))))
24057
24058 (defvar org-table-colgroup-info nil)
24059 (defun org-format-table-ascii (lines)
24060 "Format a table for ascii export."
24061 (if (stringp lines)
24062 (setq lines (org-split-string lines "\n")))
24063 (if (not (string-match "^[ \t]*|" (car lines)))
24064 ;; Table made by table.el - test for spanning
24065 lines
24066
24067 ;; A normal org table
24068 ;; Get rid of hlines at beginning and end
24069 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24070 (setq lines (nreverse lines))
24071 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24072 (setq lines (nreverse lines))
24073 (when org-export-table-remove-special-lines
24074 ;; Check if the table has a marking column. If yes remove the
24075 ;; column and the special lines
24076 (setq lines (org-table-clean-before-export lines)))
24077 ;; Get rid of the vertical lines except for grouping
24078 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
24079 rtn line vl1 start)
24080 (while (setq line (pop lines))
24081 (if (string-match org-table-hline-regexp line)
24082 (and (string-match "|\\(.*\\)|" line)
24083 (setq line (replace-match " \\1" t nil line)))
24084 (setq start 0 vl1 vl)
24085 (while (string-match "|" line start)
24086 (setq start (match-end 0))
24087 (or (pop vl1) (setq line (replace-match " " t t line)))))
24088 (push line rtn))
24089 (nreverse rtn))))
24090
24091 (defun org-colgroup-info-to-vline-list (info)
24092 (let (vl new last)
24093 (while info
24094 (setq last new new (pop info))
24095 (if (or (memq last '(:end :startend))
24096 (memq new '(:start :startend)))
24097 (push t vl)
24098 (push nil vl)))
24099 (setq vl (nreverse vl))
24100 (and vl (setcar vl nil))
24101 vl))
24102
24103 (defun org-format-table-html (lines olines)
24104 "Find out which HTML converter to use and return the HTML code."
24105 (if (stringp lines)
24106 (setq lines (org-split-string lines "\n")))
24107 (if (string-match "^[ \t]*|" (car lines))
24108 ;; A normal org table
24109 (org-format-org-table-html lines)
24110 ;; Table made by table.el - test for spanning
24111 (let* ((hlines (delq nil (mapcar
24112 (lambda (x)
24113 (if (string-match "^[ \t]*\\+-" x) x
24114 nil))
24115 lines)))
24116 (first (car hlines))
24117 (ll (and (string-match "\\S-+" first)
24118 (match-string 0 first)))
24119 (re (concat "^[ \t]*" (regexp-quote ll)))
24120 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
24121 hlines))))
24122 (if (and (not spanning)
24123 (not org-export-prefer-native-exporter-for-tables))
24124 ;; We can use my own converter with HTML conversions
24125 (org-format-table-table-html lines)
24126 ;; Need to use the code generator in table.el, with the original text.
24127 (org-format-table-table-html-using-table-generate-source olines)))))
24128
24129 (defun org-format-org-table-html (lines &optional splice)
24130 "Format a table into HTML."
24131 ;; Get rid of hlines at beginning and end
24132 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24133 (setq lines (nreverse lines))
24134 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24135 (setq lines (nreverse lines))
24136 (when org-export-table-remove-special-lines
24137 ;; Check if the table has a marking column. If yes remove the
24138 ;; column and the special lines
24139 (setq lines (org-table-clean-before-export lines)))
24140
24141 (let ((head (and org-export-highlight-first-table-line
24142 (delq nil (mapcar
24143 (lambda (x) (string-match "^[ \t]*|-" x))
24144 (cdr lines)))))
24145 (nlines 0) fnum i
24146 tbopen line fields html gr colgropen)
24147 (if splice (setq head nil))
24148 (unless splice (push (if head "<thead>" "<tbody>") html))
24149 (setq tbopen t)
24150 (while (setq line (pop lines))
24151 (catch 'next-line
24152 (if (string-match "^[ \t]*|-" line)
24153 (progn
24154 (unless splice
24155 (push (if head "</thead>" "</tbody>") html)
24156 (if lines (push "<tbody>" html) (setq tbopen nil)))
24157 (setq head nil) ;; head ends here, first time around
24158 ;; ignore this line
24159 (throw 'next-line t)))
24160 ;; Break the line into fields
24161 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
24162 (unless fnum (setq fnum (make-vector (length fields) 0)))
24163 (setq nlines (1+ nlines) i -1)
24164 (push (concat "<tr>"
24165 (mapconcat
24166 (lambda (x)
24167 (setq i (1+ i))
24168 (if (and (< i nlines)
24169 (string-match org-table-number-regexp x))
24170 (incf (aref fnum i)))
24171 (if head
24172 (concat (car org-export-table-header-tags) x
24173 (cdr org-export-table-header-tags))
24174 (concat (car org-export-table-data-tags) x
24175 (cdr org-export-table-data-tags))))
24176 fields "")
24177 "</tr>")
24178 html)))
24179 (unless splice (if tbopen (push "</tbody>" html)))
24180 (unless splice (push "</table>\n" html))
24181 (setq html (nreverse html))
24182 (unless splice
24183 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
24184 (push (mapconcat
24185 (lambda (x)
24186 (setq gr (pop org-table-colgroup-info))
24187 (format "%s<COL align=\"%s\"></COL>%s"
24188 (if (memq gr '(:start :startend))
24189 (prog1
24190 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
24191 (setq colgropen t))
24192 "")
24193 (if (> (/ (float x) nlines) org-table-number-fraction)
24194 "right" "left")
24195 (if (memq gr '(:end :startend))
24196 (progn (setq colgropen nil) "</colgroup>")
24197 "")))
24198 fnum "")
24199 html)
24200 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
24201 (push org-export-html-table-tag html))
24202 (concat (mapconcat 'identity html "\n") "\n")))
24203
24204 (defun org-table-clean-before-export (lines)
24205 "Check if the table has a marking column.
24206 If yes remove the column and the special lines."
24207 (setq org-table-colgroup-info nil)
24208 (if (memq nil
24209 (mapcar
24210 (lambda (x) (or (string-match "^[ \t]*|-" x)
24211 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
24212 lines))
24213 (progn
24214 (setq org-table-clean-did-remove-column nil)
24215 (delq nil
24216 (mapcar
24217 (lambda (x)
24218 (cond
24219 ((string-match "^[ \t]*| */ *|" x)
24220 (setq org-table-colgroup-info
24221 (mapcar (lambda (x)
24222 (cond ((member x '("<" "&lt;")) :start)
24223 ((member x '(">" "&gt;")) :end)
24224 ((member x '("<>" "&lt;&gt;")) :startend)
24225 (t nil)))
24226 (org-split-string x "[ \t]*|[ \t]*")))
24227 nil)
24228 (t x)))
24229 lines)))
24230 (setq org-table-clean-did-remove-column t)
24231 (delq nil
24232 (mapcar
24233 (lambda (x)
24234 (cond
24235 ((string-match "^[ \t]*| */ *|" x)
24236 (setq org-table-colgroup-info
24237 (mapcar (lambda (x)
24238 (cond ((member x '("<" "&lt;")) :start)
24239 ((member x '(">" "&gt;")) :end)
24240 ((member x '("<>" "&lt;&gt;")) :startend)
24241 (t nil)))
24242 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
24243 nil)
24244 ((string-match "^[ \t]*| *[!_^/] *|" x)
24245 nil) ; ignore this line
24246 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
24247 (string-match "^\\([ \t]*\\)|[^|]*|" x))
24248 ;; remove the first column
24249 (replace-match "\\1|" t nil x))
24250 (t (error "This should not happen"))))
24251 lines))))
24252
24253 (defun org-format-table-table-html (lines)
24254 "Format a table generated by table.el into HTML.
24255 This conversion does *not* use `table-generate-source' from table.el.
24256 This has the advantage that Org-mode's HTML conversions can be used.
24257 But it has the disadvantage, that no cell- or row-spanning is allowed."
24258 (let (line field-buffer
24259 (head org-export-highlight-first-table-line)
24260 fields html empty)
24261 (setq html (concat org-export-html-table-tag "\n"))
24262 (while (setq line (pop lines))
24263 (setq empty "&nbsp;")
24264 (catch 'next-line
24265 (if (string-match "^[ \t]*\\+-" line)
24266 (progn
24267 (if field-buffer
24268 (progn
24269 (setq
24270 html
24271 (concat
24272 html
24273 "<tr>"
24274 (mapconcat
24275 (lambda (x)
24276 (if (equal x "") (setq x empty))
24277 (if head
24278 (concat (car org-export-table-header-tags) x
24279 (cdr org-export-table-header-tags))
24280 (concat (car org-export-table-data-tags) x
24281 (cdr org-export-table-data-tags))))
24282 field-buffer "\n")
24283 "</tr>\n"))
24284 (setq head nil)
24285 (setq field-buffer nil)))
24286 ;; Ignore this line
24287 (throw 'next-line t)))
24288 ;; Break the line into fields and store the fields
24289 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
24290 (if field-buffer
24291 (setq field-buffer (mapcar
24292 (lambda (x)
24293 (concat x "<br/>" (pop fields)))
24294 field-buffer))
24295 (setq field-buffer fields))))
24296 (setq html (concat html "</table>\n"))
24297 html))
24298
24299 (defun org-format-table-table-html-using-table-generate-source (lines)
24300 "Format a table into html, using `table-generate-source' from table.el.
24301 This has the advantage that cell- or row-spanning is allowed.
24302 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
24303 (require 'table)
24304 (with-current-buffer (get-buffer-create " org-tmp1 ")
24305 (erase-buffer)
24306 (insert (mapconcat 'identity lines "\n"))
24307 (goto-char (point-min))
24308 (if (not (re-search-forward "|[^+]" nil t))
24309 (error "Error processing table"))
24310 (table-recognize-table)
24311 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
24312 (table-generate-source 'html " org-tmp2 ")
24313 (set-buffer " org-tmp2 ")
24314 (buffer-substring (point-min) (point-max))))
24315
24316 (defun org-html-handle-time-stamps (s)
24317 "Format time stamps in string S, or remove them."
24318 (catch 'exit
24319 (let (r b)
24320 (while (string-match org-maybe-keyword-time-regexp s)
24321 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
24322 ;; never export CLOCK
24323 (throw 'exit ""))
24324 (or b (setq b (substring s 0 (match-beginning 0))))
24325 (if (not org-export-with-timestamps)
24326 (setq r (concat r (substring s 0 (match-beginning 0)))
24327 s (substring s (match-end 0)))
24328 (setq r (concat
24329 r (substring s 0 (match-beginning 0))
24330 (if (match-end 1)
24331 (format "@<span class=\"timestamp-kwd\">%s @</span>"
24332 (match-string 1 s)))
24333 (format " @<span class=\"timestamp\">%s@</span>"
24334 (substring
24335 (org-translate-time (match-string 3 s)) 1 -1)))
24336 s (substring s (match-end 0)))))
24337 ;; Line break if line started and ended with time stamp stuff
24338 (if (not r)
24339 s
24340 (setq r (concat r s))
24341 (unless (string-match "\\S-" (concat b s))
24342 (setq r (concat r "@<br/>")))
24343 r))))
24344
24345 (defun org-html-protect (s)
24346 ;; convert & to &amp;, < to &lt; and > to &gt;
24347 (let ((start 0))
24348 (while (string-match "&" s start)
24349 (setq s (replace-match "&amp;" t t s)
24350 start (1+ (match-beginning 0))))
24351 (while (string-match "<" s)
24352 (setq s (replace-match "&lt;" t t s)))
24353 (while (string-match ">" s)
24354 (setq s (replace-match "&gt;" t t s))))
24355 s)
24356
24357 (defun org-export-cleanup-toc-line (s)
24358 "Remove tags and time staps from lines going into the toc."
24359 (when (memq org-export-with-tags '(not-in-toc nil))
24360 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
24361 (setq s (replace-match "" t t s))))
24362 (when org-export-remove-timestamps-from-toc
24363 (while (string-match org-maybe-keyword-time-regexp s)
24364 (setq s (replace-match "" t t s))))
24365 (while (string-match org-bracket-link-regexp s)
24366 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
24367 t t s)))
24368 s)
24369
24370 (defun org-html-expand (string)
24371 "Prepare STRING for HTML export. Applies all active conversions.
24372 If there are links in the string, don't modify these."
24373 (let* ((re (concat org-bracket-link-regexp "\\|"
24374 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
24375 m s l res)
24376 (while (setq m (string-match re string))
24377 (setq s (substring string 0 m)
24378 l (match-string 0 string)
24379 string (substring string (match-end 0)))
24380 (push (org-html-do-expand s) res)
24381 (push l res))
24382 (push (org-html-do-expand string) res)
24383 (apply 'concat (nreverse res))))
24384
24385 (defun org-html-do-expand (s)
24386 "Apply all active conversions to translate special ASCII to HTML."
24387 (setq s (org-html-protect s))
24388 (if org-export-html-expand
24389 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
24390 (setq s (replace-match "<\\1>" t nil s))))
24391 (if org-export-with-emphasize
24392 (setq s (org-export-html-convert-emphasize s)))
24393 (if org-export-with-sub-superscripts
24394 (setq s (org-export-html-convert-sub-super s)))
24395 (if org-export-with-TeX-macros
24396 (let ((start 0) wd ass)
24397 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
24398 (setq wd (match-string 1 s))
24399 (if (setq ass (assoc wd org-html-entities))
24400 (setq s (replace-match (or (cdr ass)
24401 (concat "&" (car ass) ";"))
24402 t t s))
24403 (setq start (+ start (length wd)))))))
24404 s)
24405
24406 (defun org-create-multibrace-regexp (left right n)
24407 "Create a regular expression which will match a balanced sexp.
24408 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
24409 as single character strings.
24410 The regexp returned will match the entire expression including the
24411 delimiters. It will also define a single group which contains the
24412 match except for the outermost delimiters. The maximum depth of
24413 stacked delimiters is N. Escaping delimiters is not possible."
24414 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
24415 (or "\\|")
24416 (re nothing)
24417 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
24418 (while (> n 1)
24419 (setq n (1- n)
24420 re (concat re or next)
24421 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
24422 (concat left "\\(" re "\\)" right)))
24423
24424 (defvar org-match-substring-regexp
24425 (concat
24426 "\\([^\\]\\)\\([_^]\\)\\("
24427 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
24428 "\\|"
24429 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
24430 "\\|"
24431 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
24432 "The regular expression matching a sub- or superscript.")
24433
24434 ;(let ((s "a\\_b"))
24435 ; (and (string-match org-match-substring-regexp s)
24436 ; (conca t (match-string 1 s) ":::" (match-string 2 s))))
24437
24438 (defun org-export-html-convert-sub-super (string)
24439 "Convert sub- and superscripts in STRING to HTML."
24440 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
24441 (while (string-match org-match-substring-regexp string s)
24442 (if (and requireb (match-end 8))
24443 (setq s (match-end 2))
24444 (setq s (match-end 1)
24445 key (if (string= (match-string 2 string) "_") "sub" "sup")
24446 c (or (match-string 8 string)
24447 (match-string 6 string)
24448 (match-string 5 string))
24449 string (replace-match
24450 (concat (match-string 1 string)
24451 "<" key ">" c "</" key ">")
24452 t t string))))
24453 (while (string-match "\\\\\\([_^]\\)" string)
24454 (setq string (replace-match (match-string 1 string) t t string)))
24455 string))
24456
24457 (defun org-export-html-convert-emphasize (string)
24458 "Apply emphasis."
24459 (let ((s 0))
24460 (while (string-match org-emph-re string s)
24461 (if (not (equal
24462 (substring string (match-beginning 3) (1+ (match-beginning 3)))
24463 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
24464 (setq string (replace-match
24465 (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
24466 "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist))
24467 "\\5") t nil string))
24468 (setq s (1+ s))))
24469 string))
24470
24471 (defvar org-par-open nil)
24472 (defun org-open-par ()
24473 "Insert <p>, but first close previous paragraph if any."
24474 (org-close-par-maybe)
24475 (insert "\n<p>")
24476 (setq org-par-open t))
24477 (defun org-close-par-maybe ()
24478 "Close paragraph if there is one open."
24479 (when org-par-open
24480 (insert "</p>")
24481 (setq org-par-open nil)))
24482 (defun org-close-li ()
24483 "Close <li> if necessary."
24484 (org-close-par-maybe)
24485 (insert "</li>\n"))
24486
24487 (defvar body-only) ; dynamically scoped into this.
24488 (defun org-html-level-start (level title umax with-toc head-count)
24489 "Insert a new level in HTML export.
24490 When TITLE is nil, just close all open levels."
24491 (org-close-par-maybe)
24492 (let ((l org-level-max))
24493 (while (>= l (1+ level))
24494 (if (aref org-levels-open (1- l))
24495 (progn
24496 (org-html-level-close l umax)
24497 (aset org-levels-open (1- l) nil)))
24498 (setq l (1- l)))
24499 (when title
24500 ;; If title is nil, this means this function is called to close
24501 ;; all levels, so the rest is done only if title is given
24502 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24503 (setq title (replace-match
24504 (if org-export-with-tags
24505 (save-match-data
24506 (concat
24507 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
24508 (mapconcat 'identity (org-split-string
24509 (match-string 1 title) ":")
24510 "&nbsp;")
24511 "</span>"))
24512 "")
24513 t t title)))
24514 (if (> level umax)
24515 (progn
24516 (if (aref org-levels-open (1- level))
24517 (progn
24518 (org-close-li)
24519 (insert "<li>" title "<br/>\n"))
24520 (aset org-levels-open (1- level) t)
24521 (org-close-par-maybe)
24522 (insert "<ul>\n<li>" title "<br/>\n")))
24523 (aset org-levels-open (1- level) t)
24524 (if (and org-export-with-section-numbers (not body-only))
24525 (setq title (concat (org-section-number level) " " title)))
24526 (setq level (+ level org-export-html-toplevel-hlevel -1))
24527 (if with-toc
24528 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
24529 level level head-count title level))
24530 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
24531 (org-open-par)))))
24532
24533 (defun org-html-level-close (level max-outline-level)
24534 "Terminate one level in HTML export."
24535 (if (<= level max-outline-level)
24536 (insert "</div>\n")
24537 (org-close-li)
24538 (insert "</ul>\n")))
24539
24540 ;;; iCalendar export
24541
24542 ;;;###autoload
24543 (defun org-export-icalendar-this-file ()
24544 "Export current file as an iCalendar file.
24545 The iCalendar file will be located in the same directory as the Org-mode
24546 file, but with extension `.ics'."
24547 (interactive)
24548 (org-export-icalendar nil buffer-file-name))
24549
24550 ;;;###autoload
24551 (defun org-export-icalendar-all-agenda-files ()
24552 "Export all files in `org-agenda-files' to iCalendar .ics files.
24553 Each iCalendar file will be located in the same directory as the Org-mode
24554 file, but with extension `.ics'."
24555 (interactive)
24556 (apply 'org-export-icalendar nil (org-agenda-files t)))
24557
24558 ;;;###autoload
24559 (defun org-export-icalendar-combine-agenda-files ()
24560 "Export all files in `org-agenda-files' to a single combined iCalendar file.
24561 The file is stored under the name `org-combined-agenda-icalendar-file'."
24562 (interactive)
24563 (apply 'org-export-icalendar t (org-agenda-files t)))
24564
24565 (defun org-export-icalendar (combine &rest files)
24566 "Create iCalendar files for all elements of FILES.
24567 If COMBINE is non-nil, combine all calendar entries into a single large
24568 file and store it under the name `org-combined-agenda-icalendar-file'."
24569 (save-excursion
24570 (org-prepare-agenda-buffers files)
24571 (let* ((dir (org-export-directory
24572 :ical (list :publishing-directory
24573 org-export-publishing-directory)))
24574 file ical-file ical-buffer category started org-agenda-new-buffers)
24575
24576 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
24577 (when combine
24578 (setq ical-file
24579 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
24580 org-combined-agenda-icalendar-file
24581 (expand-file-name org-combined-agenda-icalendar-file dir))
24582 ical-buffer (org-get-agenda-file-buffer ical-file))
24583 (set-buffer ical-buffer) (erase-buffer))
24584 (while (setq file (pop files))
24585 (catch 'nextfile
24586 (org-check-agenda-file file)
24587 (set-buffer (org-get-agenda-file-buffer file))
24588 (unless combine
24589 (setq ical-file (concat (file-name-as-directory dir)
24590 (file-name-sans-extension
24591 (file-name-nondirectory buffer-file-name))
24592 ".ics"))
24593 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
24594 (with-current-buffer ical-buffer (erase-buffer)))
24595 (setq category (or org-category
24596 (file-name-sans-extension
24597 (file-name-nondirectory buffer-file-name))))
24598 (if (symbolp category) (setq category (symbol-name category)))
24599 (let ((standard-output ical-buffer))
24600 (if combine
24601 (and (not started) (setq started t)
24602 (org-start-icalendar-file org-icalendar-combined-name))
24603 (org-start-icalendar-file category))
24604 (org-print-icalendar-entries combine)
24605 (when (or (and combine (not files)) (not combine))
24606 (org-finish-icalendar-file)
24607 (set-buffer ical-buffer)
24608 (save-buffer)
24609 (run-hooks 'org-after-save-iCalendar-file-hook)))))
24610 (org-release-buffers org-agenda-new-buffers))))
24611
24612 (defvar org-after-save-iCalendar-file-hook nil
24613 "Hook run after an iCalendar file has been saved.
24614 The iCalendar buffer is still current when this hook is run.
24615 A good way to use this is to tell a desktop calenndar application to re-read
24616 the iCalendar file.")
24617
24618 (defun org-print-icalendar-entries (&optional combine)
24619 "Print iCalendar entries for the current Org-mode file to `standard-output'.
24620 When COMBINE is non nil, add the category to each line."
24621 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
24622 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
24623 (dts (org-ical-ts-to-string
24624 (format-time-string (cdr org-time-stamp-formats) (current-time))
24625 "DTSTART"))
24626 hd ts ts2 state status (inc t) pos b sexp rrule
24627 scheduledp deadlinep tmp pri category entry location summary desc
24628 (sexp-buffer (get-buffer-create "*ical-tmp*")))
24629 (org-refresh-category-properties)
24630 (save-excursion
24631 (goto-char (point-min))
24632 (while (re-search-forward re1 nil t)
24633 (catch :skip
24634 (org-agenda-skip)
24635 (setq pos (match-beginning 0)
24636 ts (match-string 0)
24637 inc t
24638 hd (org-get-heading)
24639 summary (org-entry-get nil "SUMMARY")
24640 desc (or (org-entry-get nil "DESCRIPTION")
24641 (org-get-cleaned-entry org-icalendar-include-body))
24642 location (org-entry-get nil "LOCATION")
24643 category (org-get-category))
24644 (if (looking-at re2)
24645 (progn
24646 (goto-char (match-end 0))
24647 (setq ts2 (match-string 1) inc nil))
24648 (setq tmp (buffer-substring (max (point-min)
24649 (- pos org-ds-keyword-length))
24650 pos)
24651 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
24652 (progn
24653 (setq inc nil)
24654 (replace-match "\\1" t nil ts))
24655 ts)
24656 deadlinep (string-match org-deadline-regexp tmp)
24657 scheduledp (string-match org-scheduled-regexp tmp)
24658 ;; donep (org-entry-is-done-p)
24659 ))
24660 (if (or (string-match org-tr-regexp hd)
24661 (string-match org-ts-regexp hd))
24662 (setq hd (replace-match "" t t hd)))
24663 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
24664 (setq rrule
24665 (concat "\nRRULE:FREQ="
24666 (cdr (assoc
24667 (match-string 2 ts)
24668 '(("d" . "DAILY")("w" . "WEEKLY")
24669 ("m" . "MONTHLY")("y" . "YEARLY"))))
24670 ";INTERVAL=" (match-string 1 ts)))
24671 (setq rrule ""))
24672 (setq summary (or summary hd))
24673 (if (string-match org-bracket-link-regexp summary)
24674 (setq summary
24675 (replace-match (if (match-end 3)
24676 (match-string 3 summary)
24677 (match-string 1 summary))
24678 t t summary)))
24679 (if deadlinep (setq summary (concat "DL: " summary)))
24680 (if scheduledp (setq summary (concat "S: " summary)))
24681 (if (string-match "\\`<%%" ts)
24682 (with-current-buffer sexp-buffer
24683 (insert (substring ts 1 -1) " " summary "\n"))
24684 (princ (format "BEGIN:VEVENT
24685 %s
24686 %s%s
24687 SUMMARY:%s%s%s
24688 CATEGORIES:%s
24689 END:VEVENT\n"
24690 (org-ical-ts-to-string ts "DTSTART")
24691 (org-ical-ts-to-string ts2 "DTEND" inc)
24692 rrule summary
24693 (if (and desc (string-match "\\S-" desc))
24694 (concat "\nDESCRIPTION: " desc) "")
24695 (if (and location (string-match "\\S-" location))
24696 (concat "\nLOCATION: " location) "")
24697 category)))))
24698
24699 (when (and org-icalendar-include-sexps
24700 (condition-case nil (require 'icalendar) (error nil))
24701 (fboundp 'icalendar-export-region))
24702 ;; Get all the literal sexps
24703 (goto-char (point-min))
24704 (while (re-search-forward "^&?%%(" nil t)
24705 (catch :skip
24706 (org-agenda-skip)
24707 (setq b (match-beginning 0))
24708 (goto-char (1- (match-end 0)))
24709 (forward-sexp 1)
24710 (end-of-line 1)
24711 (setq sexp (buffer-substring b (point)))
24712 (with-current-buffer sexp-buffer
24713 (insert sexp "\n"))
24714 (princ (org-diary-to-ical-string sexp-buffer)))))
24715
24716 (when org-icalendar-include-todo
24717 (goto-char (point-min))
24718 (while (re-search-forward org-todo-line-regexp nil t)
24719 (catch :skip
24720 (org-agenda-skip)
24721 (setq state (match-string 2))
24722 (setq status (if (member state org-done-keywords)
24723 "COMPLETED" "NEEDS-ACTION"))
24724 (when (and state
24725 (or (not (member state org-done-keywords))
24726 (eq org-icalendar-include-todo 'all))
24727 (not (member org-archive-tag (org-get-tags-at)))
24728 )
24729 (setq hd (match-string 3)
24730 summary (org-entry-get nil "SUMMARY")
24731 desc (or (org-entry-get nil "DESCRIPTION")
24732 (org-get-cleaned-entry org-icalendar-include-body))
24733 location (org-entry-get nil "LOCATION"))
24734 (if (string-match org-bracket-link-regexp hd)
24735 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
24736 (match-string 1 hd))
24737 t t hd)))
24738 (if (string-match org-priority-regexp hd)
24739 (setq pri (string-to-char (match-string 2 hd))
24740 hd (concat (substring hd 0 (match-beginning 1))
24741 (substring hd (match-end 1))))
24742 (setq pri org-default-priority))
24743 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
24744 (- org-lowest-priority org-highest-priority))))))
24745
24746 (princ (format "BEGIN:VTODO
24747 %s
24748 SUMMARY:%s%s%s
24749 CATEGORIES:%s
24750 SEQUENCE:1
24751 PRIORITY:%d
24752 STATUS:%s
24753 END:VTODO\n"
24754 dts
24755 (or summary hd)
24756 (if (and location (string-match "\\S-" location))
24757 (concat "\nLOCATION: " location) "")
24758 (if (and desc (string-match "\\S-" desc))
24759 (concat "\nDESCRIPTION: " desc) "")
24760 category pri status)))))))))
24761
24762 (defun org-get-cleaned-entry (what)
24763 "Clean-up description string."
24764 (when what
24765 (save-excursion
24766 (org-back-to-heading t)
24767 (let ((s (buffer-substring (point-at-bol 2) (org-end-of-subtree t)))
24768 (re (concat org-drawer-regexp "[^\000]*?:END:.*\n?"))
24769 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
24770 (while (string-match re s) (setq s (replace-match "" t t s)))
24771 (while (string-match re2 s) (setq s (replace-match "" t t s)))
24772 (if (string-match "[ \t\r\n]+\\'" s) (setq s (replace-match "" t t s)))
24773 (while (string-match "[ \t]*\n[ \t]*" s)
24774 (setq s (replace-match "\\n" t t s)))
24775 (setq s (org-trim s))
24776 (if (and (numberp what)
24777 (> (length s) what))
24778 (substring s 0 what)
24779 s)))))
24780
24781 (defun org-start-icalendar-file (name)
24782 "Start an iCalendar file by inserting the header."
24783 (let ((user user-full-name)
24784 (name (or name "unknown"))
24785 (timezone (cadr (current-time-zone))))
24786 (princ
24787 (format "BEGIN:VCALENDAR
24788 VERSION:2.0
24789 X-WR-CALNAME:%s
24790 PRODID:-//%s//Emacs with Org-mode//EN
24791 X-WR-TIMEZONE:%s
24792 CALSCALE:GREGORIAN\n" name user timezone))))
24793
24794 (defun org-finish-icalendar-file ()
24795 "Finish an iCalendar file by inserting the END statement."
24796 (princ "END:VCALENDAR\n"))
24797
24798 (defun org-ical-ts-to-string (s keyword &optional inc)
24799 "Take a time string S and convert it to iCalendar format.
24800 KEYWORD is added in front, to make a complete line like DTSTART....
24801 When INC is non-nil, increase the hour by two (if time string contains
24802 a time), or the day by one (if it does not contain a time)."
24803 (let ((t1 (org-parse-time-string s 'nodefault))
24804 t2 fmt have-time time)
24805 (if (and (car t1) (nth 1 t1) (nth 2 t1))
24806 (setq t2 t1 have-time t)
24807 (setq t2 (org-parse-time-string s)))
24808 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
24809 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
24810 (when inc
24811 (if have-time
24812 (if org-agenda-default-appointment-duration
24813 (setq mi (+ org-agenda-default-appointment-duration mi))
24814 (setq h (+ 2 h)))
24815 (setq d (1+ d))))
24816 (setq time (encode-time s mi h d m y)))
24817 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
24818 (concat keyword (format-time-string fmt time))))
24819
24820 ;;; XOXO export
24821
24822 (defun org-export-as-xoxo-insert-into (buffer &rest output)
24823 (with-current-buffer buffer
24824 (apply 'insert output)))
24825 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
24826
24827 (defun org-export-as-xoxo (&optional buffer)
24828 "Export the org buffer as XOXO.
24829 The XOXO buffer is named *xoxo-<source buffer name>*"
24830 (interactive (list (current-buffer)))
24831 ;; A quickie abstraction
24832
24833 ;; Output everything as XOXO
24834 (with-current-buffer (get-buffer buffer)
24835 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
24836 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24837 (org-infile-export-plist)))
24838 (filename (concat (file-name-as-directory
24839 (org-export-directory :xoxo opt-plist))
24840 (file-name-sans-extension
24841 (file-name-nondirectory buffer-file-name))
24842 ".html"))
24843 (out (find-file-noselect filename))
24844 (last-level 1)
24845 (hanging-li nil))
24846 ;; Check the output buffer is empty.
24847 (with-current-buffer out (erase-buffer))
24848 ;; Kick off the output
24849 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
24850 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
24851 (let* ((hd (match-string-no-properties 1))
24852 (level (length hd))
24853 (text (concat
24854 (match-string-no-properties 2)
24855 (save-excursion
24856 (goto-char (match-end 0))
24857 (let ((str ""))
24858 (catch 'loop
24859 (while 't
24860 (forward-line)
24861 (if (looking-at "^[ \t]\\(.*\\)")
24862 (setq str (concat str (match-string-no-properties 1)))
24863 (throw 'loop str)))))))))
24864
24865 ;; Handle level rendering
24866 (cond
24867 ((> level last-level)
24868 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
24869
24870 ((< level last-level)
24871 (dotimes (- (- last-level level) 1)
24872 (if hanging-li
24873 (org-export-as-xoxo-insert-into out "</li>\n"))
24874 (org-export-as-xoxo-insert-into out "</ol>\n"))
24875 (when hanging-li
24876 (org-export-as-xoxo-insert-into out "</li>\n")
24877 (setq hanging-li nil)))
24878
24879 ((equal level last-level)
24880 (if hanging-li
24881 (org-export-as-xoxo-insert-into out "</li>\n")))
24882 )
24883
24884 (setq last-level level)
24885
24886 ;; And output the new li
24887 (setq hanging-li 't)
24888 (if (equal ?+ (elt text 0))
24889 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
24890 (org-export-as-xoxo-insert-into out "<li>" text))))
24891
24892 ;; Finally finish off the ol
24893 (dotimes (- last-level 1)
24894 (if hanging-li
24895 (org-export-as-xoxo-insert-into out "</li>\n"))
24896 (org-export-as-xoxo-insert-into out "</ol>\n"))
24897
24898 ;; Finish the buffer off and clean it up.
24899 (switch-to-buffer-other-window out)
24900 (indent-region (point-min) (point-max) nil)
24901 (save-buffer)
24902 (goto-char (point-min))
24903 )))
24904
24905
24906 ;;;; Key bindings
24907
24908 ;; Make `C-c C-x' a prefix key
24909 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
24910
24911 ;; TAB key with modifiers
24912 (org-defkey org-mode-map "\C-i" 'org-cycle)
24913 (org-defkey org-mode-map [(tab)] 'org-cycle)
24914 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
24915 (org-defkey org-mode-map [(meta tab)] 'org-complete)
24916 (org-defkey org-mode-map "\M-\t" 'org-complete)
24917 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
24918 ;; The following line is necessary under Suse GNU/Linux
24919 (unless (featurep 'xemacs)
24920 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
24921 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
24922 (define-key org-mode-map [backtab] 'org-shifttab)
24923
24924 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
24925 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
24926 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
24927
24928 ;; Cursor keys with modifiers
24929 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
24930 (org-defkey org-mode-map [(meta right)] 'org-metaright)
24931 (org-defkey org-mode-map [(meta up)] 'org-metaup)
24932 (org-defkey org-mode-map [(meta down)] 'org-metadown)
24933
24934 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
24935 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
24936 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
24937 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
24938
24939 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
24940 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
24941 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
24942 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
24943
24944 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
24945 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
24946
24947 ;;; Extra keys for tty access.
24948 ;; We only set them when really needed because otherwise the
24949 ;; menus don't show the simple keys
24950
24951 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
24952 (not window-system))
24953 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
24954 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
24955 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
24956 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
24957 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
24958 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
24959 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
24960 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
24961 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
24962 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
24963 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
24964 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
24965 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
24966 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
24967 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
24968 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
24969 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
24970 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
24971 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
24972 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
24973 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
24974 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
24975
24976 ;; All the other keys
24977
24978 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
24979 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
24980 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
24981 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
24982 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
24983 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
24984 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
24985 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
24986 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
24987 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
24988 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
24989 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
24990 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
24991 (org-defkey org-mode-map "\C-c\C-w" 'org-check-deadlines)
24992 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
24993 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
24994 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
24995 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
24996 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
24997 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
24998 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
24999 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
25000 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
25001 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
25002 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
25003 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
25004 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
25005 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
25006 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
25007 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
25008 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
25009 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
25010 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
25011 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
25012 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
25013 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
25014 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
25015 (org-defkey org-mode-map "\C-c^" 'org-sort)
25016 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
25017 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
25018 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
25019 (org-defkey org-mode-map "\C-m" 'org-return)
25020 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
25021 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
25022 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
25023 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
25024 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
25025 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
25026 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
25027 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
25028 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
25029 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
25030 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
25031 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
25032 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
25033 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
25034 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
25035 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
25036
25037 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
25038 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
25039 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
25040 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
25041
25042 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
25043 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
25044 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
25045 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
25046 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
25047 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
25048 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
25049 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
25050 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
25051 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
25052 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
25053 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
25054
25055 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
25056
25057 (when (featurep 'xemacs)
25058 (org-defkey org-mode-map 'button3 'popup-mode-menu))
25059
25060 (defsubst org-table-p () (org-at-table-p))
25061
25062 (defun org-self-insert-command (N)
25063 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
25064 If the cursor is in a table looking at whitespace, the whitespace is
25065 overwritten, and the table is not marked as requiring realignment."
25066 (interactive "p")
25067 (if (and (org-table-p)
25068 (progn
25069 ;; check if we blank the field, and if that triggers align
25070 (and org-table-auto-blank-field
25071 (member last-command
25072 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
25073 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
25074 ;; got extra space, this field does not determine column width
25075 (let (org-table-may-need-update) (org-table-blank-field))
25076 ;; no extra space, this field may determine column width
25077 (org-table-blank-field)))
25078 t)
25079 (eq N 1)
25080 (looking-at "[^|\n]* |"))
25081 (let (org-table-may-need-update)
25082 (goto-char (1- (match-end 0)))
25083 (delete-backward-char 1)
25084 (goto-char (match-beginning 0))
25085 (self-insert-command N))
25086 (setq org-table-may-need-update t)
25087 (self-insert-command N)
25088 (org-fix-tags-on-the-fly)))
25089
25090 (defun org-fix-tags-on-the-fly ()
25091 (when (and (equal (char-after (point-at-bol)) ?*)
25092 (org-on-heading-p))
25093 (org-align-tags-here org-tags-column)))
25094
25095 (defun org-delete-backward-char (N)
25096 "Like `delete-backward-char', insert whitespace at field end in tables.
25097 When deleting backwards, in tables this function will insert whitespace in
25098 front of the next \"|\" separator, to keep the table aligned. The table will
25099 still be marked for re-alignment if the field did fill the entire column,
25100 because, in this case the deletion might narrow the column."
25101 (interactive "p")
25102 (if (and (org-table-p)
25103 (eq N 1)
25104 (string-match "|" (buffer-substring (point-at-bol) (point)))
25105 (looking-at ".*?|"))
25106 (let ((pos (point))
25107 (noalign (looking-at "[^|\n\r]* |"))
25108 (c org-table-may-need-update))
25109 (backward-delete-char N)
25110 (skip-chars-forward "^|")
25111 (insert " ")
25112 (goto-char (1- pos))
25113 ;; noalign: if there were two spaces at the end, this field
25114 ;; does not determine the width of the column.
25115 (if noalign (setq org-table-may-need-update c)))
25116 (backward-delete-char N)
25117 (org-fix-tags-on-the-fly)))
25118
25119 (defun org-delete-char (N)
25120 "Like `delete-char', but insert whitespace at field end in tables.
25121 When deleting characters, in tables this function will insert whitespace in
25122 front of the next \"|\" separator, to keep the table aligned. The table will
25123 still be marked for re-alignment if the field did fill the entire column,
25124 because, in this case the deletion might narrow the column."
25125 (interactive "p")
25126 (if (and (org-table-p)
25127 (not (bolp))
25128 (not (= (char-after) ?|))
25129 (eq N 1))
25130 (if (looking-at ".*?|")
25131 (let ((pos (point))
25132 (noalign (looking-at "[^|\n\r]* |"))
25133 (c org-table-may-need-update))
25134 (replace-match (concat
25135 (substring (match-string 0) 1 -1)
25136 " |"))
25137 (goto-char pos)
25138 ;; noalign: if there were two spaces at the end, this field
25139 ;; does not determine the width of the column.
25140 (if noalign (setq org-table-may-need-update c)))
25141 (delete-char N))
25142 (delete-char N)
25143 (org-fix-tags-on-the-fly)))
25144
25145 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
25146 (put 'org-self-insert-command 'delete-selection t)
25147 (put 'orgtbl-self-insert-command 'delete-selection t)
25148 (put 'org-delete-char 'delete-selection 'supersede)
25149 (put 'org-delete-backward-char 'delete-selection 'supersede)
25150
25151 ;; Make `flyspell-mode' delay after some commands
25152 (put 'org-self-insert-command 'flyspell-delayed t)
25153 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
25154 (put 'org-delete-char 'flyspell-delayed t)
25155 (put 'org-delete-backward-char 'flyspell-delayed t)
25156
25157 (eval-after-load "pabbrev"
25158 '(progn
25159 (add-to-list 'pabbrev-expand-after-command-list
25160 'orgtbl-self-insert-command t)
25161 (add-to-list 'pabbrev-expand-after-command-list
25162 'org-self-insert-command t)))
25163
25164 ;; How to do this: Measure non-white length of current string
25165 ;; If equal to column width, we should realign.
25166
25167 (defun org-remap (map &rest commands)
25168 "In MAP, remap the functions given in COMMANDS.
25169 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
25170 (let (new old)
25171 (while commands
25172 (setq old (pop commands) new (pop commands))
25173 (if (fboundp 'command-remapping)
25174 (org-defkey map (vector 'remap old) new)
25175 (substitute-key-definition old new map global-map)))))
25176
25177 (when (eq org-enable-table-editor 'optimized)
25178 ;; If the user wants maximum table support, we need to hijack
25179 ;; some standard editing functions
25180 (org-remap org-mode-map
25181 'self-insert-command 'org-self-insert-command
25182 'delete-char 'org-delete-char
25183 'delete-backward-char 'org-delete-backward-char)
25184 (org-defkey org-mode-map "|" 'org-force-self-insert))
25185
25186 (defun org-shiftcursor-error ()
25187 "Throw an error because Shift-Cursor command was applied in wrong context."
25188 (error "This command is active in special context like tables, headlines or timestamps"))
25189
25190 (defun org-shifttab (&optional arg)
25191 "Global visibility cycling or move to previous table field.
25192 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
25193 on context.
25194 See the individual commands for more information."
25195 (interactive "P")
25196 (cond
25197 ((org-at-table-p) (call-interactively 'org-table-previous-field))
25198 (arg (message "Content view to level: ")
25199 (org-content (prefix-numeric-value arg))
25200 (setq org-cycle-global-status 'overview))
25201 (t (call-interactively 'org-global-cycle))))
25202
25203 (defun org-shiftmetaleft ()
25204 "Promote subtree or delete table column.
25205 Calls `org-promote-subtree', `org-outdent-item',
25206 or `org-table-delete-column', depending on context.
25207 See the individual commands for more information."
25208 (interactive)
25209 (cond
25210 ((org-at-table-p) (call-interactively 'org-table-delete-column))
25211 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
25212 ((org-at-item-p) (call-interactively 'org-outdent-item))
25213 (t (org-shiftcursor-error))))
25214
25215 (defun org-shiftmetaright ()
25216 "Demote subtree or insert table column.
25217 Calls `org-demote-subtree', `org-indent-item',
25218 or `org-table-insert-column', depending on context.
25219 See the individual commands for more information."
25220 (interactive)
25221 (cond
25222 ((org-at-table-p) (call-interactively 'org-table-insert-column))
25223 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
25224 ((org-at-item-p) (call-interactively 'org-indent-item))
25225 (t (org-shiftcursor-error))))
25226
25227 (defun org-shiftmetaup (&optional arg)
25228 "Move subtree up or kill table row.
25229 Calls `org-move-subtree-up' or `org-table-kill-row' or
25230 `org-move-item-up' depending on context. See the individual commands
25231 for more information."
25232 (interactive "P")
25233 (cond
25234 ((org-at-table-p) (call-interactively 'org-table-kill-row))
25235 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
25236 ((org-at-item-p) (call-interactively 'org-move-item-up))
25237 (t (org-shiftcursor-error))))
25238 (defun org-shiftmetadown (&optional arg)
25239 "Move subtree down or insert table row.
25240 Calls `org-move-subtree-down' or `org-table-insert-row' or
25241 `org-move-item-down', depending on context. See the individual
25242 commands for more information."
25243 (interactive "P")
25244 (cond
25245 ((org-at-table-p) (call-interactively 'org-table-insert-row))
25246 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
25247 ((org-at-item-p) (call-interactively 'org-move-item-down))
25248 (t (org-shiftcursor-error))))
25249
25250 (defun org-metaleft (&optional arg)
25251 "Promote heading or move table column to left.
25252 Calls `org-do-promote' or `org-table-move-column', depending on context.
25253 With no specific context, calls the Emacs default `backward-word'.
25254 See the individual commands for more information."
25255 (interactive "P")
25256 (cond
25257 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
25258 ((or (org-on-heading-p) (org-region-active-p))
25259 (call-interactively 'org-do-promote))
25260 ((org-at-item-p) (call-interactively 'org-outdent-item))
25261 (t (call-interactively 'backward-word))))
25262
25263 (defun org-metaright (&optional arg)
25264 "Demote subtree or move table column to right.
25265 Calls `org-do-demote' or `org-table-move-column', depending on context.
25266 With no specific context, calls the Emacs default `forward-word'.
25267 See the individual commands for more information."
25268 (interactive "P")
25269 (cond
25270 ((org-at-table-p) (call-interactively 'org-table-move-column))
25271 ((or (org-on-heading-p) (org-region-active-p))
25272 (call-interactively 'org-do-demote))
25273 ((org-at-item-p) (call-interactively 'org-indent-item))
25274 (t (call-interactively 'forward-word))))
25275
25276 (defun org-metaup (&optional arg)
25277 "Move subtree up or move table row up.
25278 Calls `org-move-subtree-up' or `org-table-move-row' or
25279 `org-move-item-up', depending on context. See the individual commands
25280 for more information."
25281 (interactive "P")
25282 (cond
25283 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
25284 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
25285 ((org-at-item-p) (call-interactively 'org-move-item-up))
25286 (t (transpose-lines 1) (beginning-of-line -1))))
25287
25288 (defun org-metadown (&optional arg)
25289 "Move subtree down or move table row down.
25290 Calls `org-move-subtree-down' or `org-table-move-row' or
25291 `org-move-item-down', depending on context. See the individual
25292 commands for more information."
25293 (interactive "P")
25294 (cond
25295 ((org-at-table-p) (call-interactively 'org-table-move-row))
25296 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
25297 ((org-at-item-p) (call-interactively 'org-move-item-down))
25298 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
25299
25300 (defun org-shiftup (&optional arg)
25301 "Increase item in timestamp or increase priority of current headline.
25302 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
25303 depending on context. See the individual commands for more information."
25304 (interactive "P")
25305 (cond
25306 ((org-at-timestamp-p t)
25307 (call-interactively (if org-edit-timestamp-down-means-later
25308 'org-timestamp-down 'org-timestamp-up)))
25309 ((org-on-heading-p) (call-interactively 'org-priority-up))
25310 ((org-at-item-p) (call-interactively 'org-previous-item))
25311 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
25312
25313 (defun org-shiftdown (&optional arg)
25314 "Decrease item in timestamp or decrease priority of current headline.
25315 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
25316 depending on context. See the individual commands for more information."
25317 (interactive "P")
25318 (cond
25319 ((org-at-timestamp-p t)
25320 (call-interactively (if org-edit-timestamp-down-means-later
25321 'org-timestamp-up 'org-timestamp-down)))
25322 ((org-on-heading-p) (call-interactively 'org-priority-down))
25323 (t (call-interactively 'org-next-item))))
25324
25325 (defun org-shiftright ()
25326 "Next TODO keyword or timestamp one day later, depending on context."
25327 (interactive)
25328 (cond
25329 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
25330 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
25331 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
25332 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
25333 (t (org-shiftcursor-error))))
25334
25335 (defun org-shiftleft ()
25336 "Previous TODO keyword or timestamp one day earlier, depending on context."
25337 (interactive)
25338 (cond
25339 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
25340 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
25341 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
25342 ((org-at-property-p)
25343 (call-interactively 'org-property-previous-allowed-value))
25344 (t (org-shiftcursor-error))))
25345
25346 (defun org-shiftcontrolright ()
25347 "Switch to next TODO set."
25348 (interactive)
25349 (cond
25350 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
25351 (t (org-shiftcursor-error))))
25352
25353 (defun org-shiftcontrolleft ()
25354 "Switch to previous TODO set."
25355 (interactive)
25356 (cond
25357 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
25358 (t (org-shiftcursor-error))))
25359
25360 (defun org-ctrl-c-ret ()
25361 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
25362 (interactive)
25363 (cond
25364 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
25365 (t (call-interactively 'org-insert-heading))))
25366
25367 (defun org-copy-special ()
25368 "Copy region in table or copy current subtree.
25369 Calls `org-table-copy' or `org-copy-subtree', depending on context.
25370 See the individual commands for more information."
25371 (interactive)
25372 (call-interactively
25373 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
25374
25375 (defun org-cut-special ()
25376 "Cut region in table or cut current subtree.
25377 Calls `org-table-copy' or `org-cut-subtree', depending on context.
25378 See the individual commands for more information."
25379 (interactive)
25380 (call-interactively
25381 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
25382
25383 (defun org-paste-special (arg)
25384 "Paste rectangular region into table, or past subtree relative to level.
25385 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
25386 See the individual commands for more information."
25387 (interactive "P")
25388 (if (org-at-table-p)
25389 (org-table-paste-rectangle)
25390 (org-paste-subtree arg)))
25391
25392 (defun org-ctrl-c-ctrl-c (&optional arg)
25393 "Set tags in headline, or update according to changed information at point.
25394
25395 This command does many different things, depending on context:
25396
25397 - If the cursor is in a headline, prompt for tags and insert them
25398 into the current line, aligned to `org-tags-column'. When called
25399 with prefix arg, realign all tags in the current buffer.
25400
25401 - If the cursor is in one of the special #+KEYWORD lines, this
25402 triggers scanning the buffer for these lines and updating the
25403 information.
25404
25405 - If the cursor is inside a table, realign the table. This command
25406 works even if the automatic table editor has been turned off.
25407
25408 - If the cursor is on a #+TBLFM line, re-apply the formulas to
25409 the entire table.
25410
25411 - If the cursor is a the beginning of a dynamic block, update it.
25412
25413 - If the cursor is inside a table created by the table.el package,
25414 activate that table.
25415
25416 - If the current buffer is a remember buffer, close note and file it.
25417 with a prefix argument, file it without further interaction to the default
25418 location.
25419
25420 - If the cursor is on a <<<target>>>, update radio targets and corresponding
25421 links in this buffer.
25422
25423 - If the cursor is on a numbered item in a plain list, renumber the
25424 ordered list."
25425 (interactive "P")
25426 (let ((org-enable-table-editor t))
25427 (cond
25428 ((or org-clock-overlays
25429 org-occur-highlights
25430 org-latex-fragment-image-overlays)
25431 (org-remove-clock-overlays)
25432 (org-remove-occur-highlights)
25433 (org-remove-latex-fragment-image-overlays)
25434 (message "Temporary highlights/overlays removed from current buffer"))
25435 ((and (local-variable-p 'org-finish-function (current-buffer))
25436 (fboundp org-finish-function))
25437 (funcall org-finish-function))
25438 ((org-at-property-p)
25439 (call-interactively 'org-property-action))
25440 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
25441 ((org-on-heading-p) (call-interactively 'org-set-tags))
25442 ((org-at-table.el-p)
25443 (require 'table)
25444 (beginning-of-line 1)
25445 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
25446 (call-interactively 'table-recognize-table))
25447 ((org-at-table-p)
25448 (org-table-maybe-eval-formula)
25449 (if arg
25450 (call-interactively 'org-table-recalculate)
25451 (org-table-maybe-recalculate-line))
25452 (call-interactively 'org-table-align))
25453 ((org-at-item-checkbox-p)
25454 (call-interactively 'org-toggle-checkbox))
25455 ((org-at-item-p)
25456 (call-interactively 'org-maybe-renumber-ordered-list))
25457 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
25458 ;; Dynamic block
25459 (beginning-of-line 1)
25460 (org-update-dblock))
25461 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
25462 (cond
25463 ((equal (match-string 1) "TBLFM")
25464 ;; Recalculate the table before this line
25465 (save-excursion
25466 (beginning-of-line 1)
25467 (skip-chars-backward " \r\n\t")
25468 (if (org-at-table-p)
25469 (org-call-with-arg 'org-table-recalculate t))))
25470 (t
25471 (call-interactively 'org-mode-restart))))
25472 (t (error "C-c C-c can do nothing useful at this location.")))))
25473
25474 (defun org-mode-restart ()
25475 "Restart Org-mode, to scan again for special lines.
25476 Also updates the keyword regular expressions."
25477 (interactive)
25478 (let ((org-inhibit-startup t)) (org-mode))
25479 (message "Org-mode restarted to refresh keyword and special line setup"))
25480
25481 (defun org-kill-note-or-show-branches ()
25482 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
25483 (interactive)
25484 (if (not org-finish-function)
25485 (call-interactively 'show-branches)
25486 (let ((org-note-abort t))
25487 (funcall org-finish-function))))
25488
25489 (defun org-return ()
25490 "Goto next table row or insert a newline.
25491 Calls `org-table-next-row' or `newline', depending on context.
25492 See the individual commands for more information."
25493 (interactive)
25494 (cond
25495 ((bobp) (newline))
25496 ((org-at-table-p)
25497 (org-table-justify-field-maybe)
25498 (call-interactively 'org-table-next-row))
25499 (t (newline))))
25500
25501
25502 (defun org-ctrl-c-minus ()
25503 "Insert separator line in table or modify bullet type in list.
25504 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
25505 depending on context."
25506 (interactive)
25507 (cond
25508 ((org-at-table-p)
25509 (call-interactively 'org-table-insert-hline))
25510 ((org-on-heading-p)
25511 ;; Convert to item
25512 (save-excursion
25513 (beginning-of-line 1)
25514 (if (looking-at "\\*+ ")
25515 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
25516 ((org-in-item-p)
25517 (call-interactively 'org-cycle-list-bullet))
25518 (t (error "`C-c -' does have no function here."))))
25519
25520 (defun org-meta-return (&optional arg)
25521 "Insert a new heading or wrap a region in a table.
25522 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
25523 See the individual commands for more information."
25524 (interactive "P")
25525 (cond
25526 ((org-at-table-p)
25527 (call-interactively 'org-table-wrap-region))
25528 (t (call-interactively 'org-insert-heading))))
25529
25530 ;;; Menu entries
25531
25532 ;; Define the Org-mode menus
25533 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
25534 '("Tbl"
25535 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
25536 ["Next Field" org-cycle (org-at-table-p)]
25537 ["Previous Field" org-shifttab (org-at-table-p)]
25538 ["Next Row" org-return (org-at-table-p)]
25539 "--"
25540 ["Blank Field" org-table-blank-field (org-at-table-p)]
25541 ["Edit Field" org-table-edit-field (org-at-table-p)]
25542 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
25543 "--"
25544 ("Column"
25545 ["Move Column Left" org-metaleft (org-at-table-p)]
25546 ["Move Column Right" org-metaright (org-at-table-p)]
25547 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
25548 ["Insert Column" org-shiftmetaright (org-at-table-p)])
25549 ("Row"
25550 ["Move Row Up" org-metaup (org-at-table-p)]
25551 ["Move Row Down" org-metadown (org-at-table-p)]
25552 ["Delete Row" org-shiftmetaup (org-at-table-p)]
25553 ["Insert Row" org-shiftmetadown (org-at-table-p)]
25554 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
25555 "--"
25556 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
25557 ("Rectangle"
25558 ["Copy Rectangle" org-copy-special (org-at-table-p)]
25559 ["Cut Rectangle" org-cut-special (org-at-table-p)]
25560 ["Paste Rectangle" org-paste-special (org-at-table-p)]
25561 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
25562 "--"
25563 ("Calculate"
25564 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
25565 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
25566 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
25567 "--"
25568 ["Recalculate line" org-table-recalculate (org-at-table-p)]
25569 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
25570 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
25571 "--"
25572 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
25573 "--"
25574 ["Sum Column/Rectangle" org-table-sum
25575 (or (org-at-table-p) (org-region-active-p))]
25576 ["Which Column?" org-table-current-column (org-at-table-p)])
25577 ["Debug Formulas"
25578 org-table-toggle-formula-debugger
25579 :style toggle :selected org-table-formula-debug]
25580 ["Show Col/Row Numbers"
25581 org-table-toggle-coordinate-overlays
25582 :style toggle :selected org-table-overlay-coordinates]
25583 "--"
25584 ["Create" org-table-create (and (not (org-at-table-p))
25585 org-enable-table-editor)]
25586 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
25587 ["Import from File" org-table-import (not (org-at-table-p))]
25588 ["Export to File" org-table-export (org-at-table-p)]
25589 "--"
25590 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
25591
25592 (easy-menu-define org-org-menu org-mode-map "Org menu"
25593 '("Org"
25594 ("Show/Hide"
25595 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
25596 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
25597 ["Sparse Tree" org-occur t]
25598 ["Reveal Context" org-reveal t]
25599 ["Show All" show-all t]
25600 "--"
25601 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
25602 "--"
25603 ["New Heading" org-insert-heading t]
25604 ("Navigate Headings"
25605 ["Up" outline-up-heading t]
25606 ["Next" outline-next-visible-heading t]
25607 ["Previous" outline-previous-visible-heading t]
25608 ["Next Same Level" outline-forward-same-level t]
25609 ["Previous Same Level" outline-backward-same-level t]
25610 "--"
25611 ["Jump" org-goto t])
25612 ("Edit Structure"
25613 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
25614 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
25615 "--"
25616 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
25617 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
25618 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
25619 "--"
25620 ["Promote Heading" org-metaleft (not (org-at-table-p))]
25621 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
25622 ["Demote Heading" org-metaright (not (org-at-table-p))]
25623 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
25624 "--"
25625 ["Sort Region/Children" org-sort (not (org-at-table-p))]
25626 "--"
25627 ["Convert to odd levels" org-convert-to-odd-levels t]
25628 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
25629 ("Editing"
25630 ["Emphasis..." org-emphasize t])
25631 ("Archive"
25632 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
25633 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
25634 ; :active t :keys "C-u C-c C-x C-a"]
25635 ["Sparse trees open ARCHIVE trees"
25636 (setq org-sparse-tree-open-archived-trees
25637 (not org-sparse-tree-open-archived-trees))
25638 :style toggle :selected org-sparse-tree-open-archived-trees]
25639 ["Cycling opens ARCHIVE trees"
25640 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
25641 :style toggle :selected org-cycle-open-archived-trees]
25642 ["Agenda includes ARCHIVE trees"
25643 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
25644 :style toggle :selected (not org-agenda-skip-archived-trees)]
25645 "--"
25646 ["Move Subtree to Archive" org-advertized-archive-subtree t]
25647 ; ["Check and Move Children" (org-archive-subtree '(4))
25648 ; :active t :keys "C-u C-c C-x C-s"]
25649 )
25650 "--"
25651 ("TODO Lists"
25652 ["TODO/DONE/-" org-todo t]
25653 ("Select keyword"
25654 ["Next keyword" org-shiftright (org-on-heading-p)]
25655 ["Previous keyword" org-shiftleft (org-on-heading-p)]
25656 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
25657 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
25658 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
25659 ["Show TODO Tree" org-show-todo-tree t]
25660 ["Global TODO list" org-todo-list t]
25661 "--"
25662 ["Set Priority" org-priority t]
25663 ["Priority Up" org-shiftup t]
25664 ["Priority Down" org-shiftdown t])
25665 ("TAGS and Properties"
25666 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
25667 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
25668 "--"
25669 ["Set property" 'org-set-property t]
25670 ["Column view of properties" org-columns t]
25671 ["Insert Column View DBlock" org-insert-columns-dblock t])
25672 ("Dates and Scheduling"
25673 ["Timestamp" org-time-stamp t]
25674 ["Timestamp (inactive)" org-time-stamp-inactive t]
25675 ("Change Date"
25676 ["1 Day Later" org-shiftright t]
25677 ["1 Day Earlier" org-shiftleft t]
25678 ["1 ... Later" org-shiftup t]
25679 ["1 ... Earlier" org-shiftdown t])
25680 ["Compute Time Range" org-evaluate-time-range t]
25681 ["Schedule Item" org-schedule t]
25682 ["Deadline" org-deadline t]
25683 "--"
25684 ["Custom time format" org-toggle-time-stamp-overlays
25685 :style radio :selected org-display-custom-times]
25686 "--"
25687 ["Goto Calendar" org-goto-calendar t]
25688 ["Date from Calendar" org-date-from-calendar t])
25689 ("Logging work"
25690 ["Clock in" org-clock-in t]
25691 ["Clock out" org-clock-out t]
25692 ["Clock cancel" org-clock-cancel t]
25693 ["Goto running clock" org-clock-goto t]
25694 ["Display times" org-clock-display t]
25695 ["Create clock table" org-clock-report t]
25696 "--"
25697 ["Record DONE time"
25698 (progn (setq org-log-done (not org-log-done))
25699 (message "Switching to %s will %s record a timestamp"
25700 (car org-done-keywords)
25701 (if org-log-done "automatically" "not")))
25702 :style toggle :selected org-log-done])
25703 "--"
25704 ["Agenda Command..." org-agenda t]
25705 ("File List for Agenda")
25706 ("Special views current file"
25707 ["TODO Tree" org-show-todo-tree t]
25708 ["Check Deadlines" org-check-deadlines t]
25709 ["Timeline" org-timeline t]
25710 ["Tags Tree" org-tags-sparse-tree t])
25711 "--"
25712 ("Hyperlinks"
25713 ["Store Link (Global)" org-store-link t]
25714 ["Insert Link" org-insert-link t]
25715 ["Follow Link" org-open-at-point t]
25716 "--"
25717 ["Next link" org-next-link t]
25718 ["Previous link" org-previous-link t]
25719 "--"
25720 ["Descriptive Links"
25721 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
25722 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
25723 ["Literal Links"
25724 (progn
25725 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
25726 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
25727 "--"
25728 ["Export/Publish..." org-export t]
25729 ("LaTeX"
25730 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
25731 :selected org-cdlatex-mode]
25732 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
25733 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
25734 ["Modify math symbol" org-cdlatex-math-modify
25735 (org-inside-LaTeX-fragment-p)]
25736 ["Export LaTeX fragments as images"
25737 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
25738 :style toggle :selected org-export-with-LaTeX-fragments])
25739 "--"
25740 ("Documentation"
25741 ["Show Version" org-version t]
25742 ["Info Documentation" org-info t])
25743 ("Customize"
25744 ["Browse Org Group" org-customize t]
25745 "--"
25746 ["Expand This Menu" org-create-customize-menu
25747 (fboundp 'customize-menu-create)])
25748 "--"
25749 ["Refresh setup" org-mode-restart t]
25750 ))
25751
25752 (defun org-info (&optional node)
25753 "Read documentation for Org-mode in the info system.
25754 With optional NODE, go directly to that node."
25755 (interactive)
25756 (require 'info)
25757 (Info-goto-node (format "(org)%s" (or node ""))))
25758
25759 (defun org-install-agenda-files-menu ()
25760 (let ((bl (buffer-list)))
25761 (save-excursion
25762 (while bl
25763 (set-buffer (pop bl))
25764 (if (org-mode-p) (setq bl nil)))
25765 (when (org-mode-p)
25766 (easy-menu-change
25767 '("Org") "File List for Agenda"
25768 (append
25769 (list
25770 ["Edit File List" (org-edit-agenda-file-list) t]
25771 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
25772 ["Remove Current File from List" org-remove-file t]
25773 ["Cycle through agenda files" org-cycle-agenda-files t]
25774 ["Occur in all agenda files" org-occur-in-agenda-files t]
25775 "--")
25776 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
25777
25778 ;;;; Documentation
25779
25780 (defun org-customize ()
25781 "Call the customize function with org as argument."
25782 (interactive)
25783 (customize-browse 'org))
25784
25785 (defun org-create-customize-menu ()
25786 "Create a full customization menu for Org-mode, insert it into the menu."
25787 (interactive)
25788 (if (fboundp 'customize-menu-create)
25789 (progn
25790 (easy-menu-change
25791 '("Org") "Customize"
25792 `(["Browse Org group" org-customize t]
25793 "--"
25794 ,(customize-menu-create 'org)
25795 ["Set" Custom-set t]
25796 ["Save" Custom-save t]
25797 ["Reset to Current" Custom-reset-current t]
25798 ["Reset to Saved" Custom-reset-saved t]
25799 ["Reset to Standard Settings" Custom-reset-standard t]))
25800 (message "\"Org\"-menu now contains full customization menu"))
25801 (error "Cannot expand menu (outdated version of cus-edit.el)")))
25802
25803 ;;;; Miscellaneous stuff
25804
25805
25806 ;;; Generally useful functions
25807
25808 (defun org-context ()
25809 "Return a list of contexts of the current cursor position.
25810 If several contexts apply, all are returned.
25811 Each context entry is a list with a symbol naming the context, and
25812 two positions indicating start and end of the context. Possible
25813 contexts are:
25814
25815 :headline anywhere in a headline
25816 :headline-stars on the leading stars in a headline
25817 :todo-keyword on a TODO keyword (including DONE) in a headline
25818 :tags on the TAGS in a headline
25819 :priority on the priority cookie in a headline
25820 :item on the first line of a plain list item
25821 :item-bullet on the bullet/number of a plain list item
25822 :checkbox on the checkbox in a plain list item
25823 :table in an org-mode table
25824 :table-special on a special filed in a table
25825 :table-table in a table.el table
25826 :link on a hyperlink
25827 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
25828 :target on a <<target>>
25829 :radio-target on a <<<radio-target>>>
25830 :latex-fragment on a LaTeX fragment
25831 :latex-preview on a LaTeX fragment with overlayed preview image
25832
25833 This function expects the position to be visible because it uses font-lock
25834 faces as a help to recognize the following contexts: :table-special, :link,
25835 and :keyword."
25836 (let* ((f (get-text-property (point) 'face))
25837 (faces (if (listp f) f (list f)))
25838 (p (point)) clist o)
25839 ;; First the large context
25840 (cond
25841 ((org-on-heading-p t)
25842 (push (list :headline (point-at-bol) (point-at-eol)) clist)
25843 (when (progn
25844 (beginning-of-line 1)
25845 (looking-at org-todo-line-tags-regexp))
25846 (push (org-point-in-group p 1 :headline-stars) clist)
25847 (push (org-point-in-group p 2 :todo-keyword) clist)
25848 (push (org-point-in-group p 4 :tags) clist))
25849 (goto-char p)
25850 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
25851 (if (looking-at "\\[#[A-Z0-9]\\]")
25852 (push (org-point-in-group p 0 :priority) clist)))
25853
25854 ((org-at-item-p)
25855 (push (org-point-in-group p 2 :item-bullet) clist)
25856 (push (list :item (point-at-bol)
25857 (save-excursion (org-end-of-item) (point)))
25858 clist)
25859 (and (org-at-item-checkbox-p)
25860 (push (org-point-in-group p 0 :checkbox) clist)))
25861
25862 ((org-at-table-p)
25863 (push (list :table (org-table-begin) (org-table-end)) clist)
25864 (if (memq 'org-formula faces)
25865 (push (list :table-special
25866 (previous-single-property-change p 'face)
25867 (next-single-property-change p 'face)) clist)))
25868 ((org-at-table-p 'any)
25869 (push (list :table-table) clist)))
25870 (goto-char p)
25871
25872 ;; Now the small context
25873 (cond
25874 ((org-at-timestamp-p)
25875 (push (org-point-in-group p 0 :timestamp) clist))
25876 ((memq 'org-link faces)
25877 (push (list :link
25878 (previous-single-property-change p 'face)
25879 (next-single-property-change p 'face)) clist))
25880 ((memq 'org-special-keyword faces)
25881 (push (list :keyword
25882 (previous-single-property-change p 'face)
25883 (next-single-property-change p 'face)) clist))
25884 ((org-on-target-p)
25885 (push (org-point-in-group p 0 :target) clist)
25886 (goto-char (1- (match-beginning 0)))
25887 (if (looking-at org-radio-target-regexp)
25888 (push (org-point-in-group p 0 :radio-target) clist))
25889 (goto-char p))
25890 ((setq o (car (delq nil
25891 (mapcar
25892 (lambda (x)
25893 (if (memq x org-latex-fragment-image-overlays) x))
25894 (org-overlays-at (point))))))
25895 (push (list :latex-fragment
25896 (org-overlay-start o) (org-overlay-end o)) clist)
25897 (push (list :latex-preview
25898 (org-overlay-start o) (org-overlay-end o)) clist))
25899 ((org-inside-LaTeX-fragment-p)
25900 ;; FIXME: positions wrong.
25901 (push (list :latex-fragment (point) (point)) clist)))
25902
25903 (setq clist (nreverse (delq nil clist)))
25904 clist))
25905
25906 ;; FIXME: Compare with at-regexp-p Do we need both?
25907 (defun org-in-regexp (re &optional nlines visually)
25908 "Check if point is inside a match of regexp.
25909 Normally only the current line is checked, but you can include NLINES extra
25910 lines both before and after point into the search.
25911 If VISUALLY is set, require that the cursor is not after the match but
25912 really on, so that the block visually is on the match."
25913 (catch 'exit
25914 (let ((pos (point))
25915 (eol (point-at-eol (+ 1 (or nlines 0))))
25916 (inc (if visually 1 0)))
25917 (save-excursion
25918 (beginning-of-line (- 1 (or nlines 0)))
25919 (while (re-search-forward re eol t)
25920 (if (and (<= (match-beginning 0) pos)
25921 (>= (+ inc (match-end 0)) pos))
25922 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
25923
25924 (defun org-at-regexp-p (regexp)
25925 "Is point inside a match of REGEXP in the current line?"
25926 (catch 'exit
25927 (save-excursion
25928 (let ((pos (point)) (end (point-at-eol)))
25929 (beginning-of-line 1)
25930 (while (re-search-forward regexp end t)
25931 (if (and (<= (match-beginning 0) pos)
25932 (>= (match-end 0) pos))
25933 (throw 'exit t)))
25934 nil))))
25935
25936 (defun org-occur-in-agenda-files (regexp &optional nlines)
25937 "Call `multi-occur' with buffers for all agenda files."
25938 (interactive "sOrg-files matching: \np")
25939 (let* ((files (org-agenda-files))
25940 (tnames (mapcar 'file-truename files))
25941 (extra org-agenda-multi-occur-extra-files)
25942 f)
25943 (while (setq f (pop extra))
25944 (unless (member (file-truename f) tnames)
25945 (add-to-list 'files f 'append)
25946 (add-to-list 'tnames (file-truename f) 'append)))
25947 (multi-occur
25948 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
25949 regexp)))
25950
25951 (defun org-uniquify (list)
25952 "Remove duplicate elements from LIST."
25953 (let (res)
25954 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
25955 res))
25956
25957 (defun org-delete-all (elts list)
25958 "Remove all elements in ELTS from LIST."
25959 (while elts
25960 (setq list (delete (pop elts) list)))
25961 list)
25962
25963 (defun org-point-in-group (point group &optional context)
25964 "Check if POINT is in match-group GROUP.
25965 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
25966 match. If the match group does ot exist or point is not inside it,
25967 return nil."
25968 (and (match-beginning group)
25969 (>= point (match-beginning group))
25970 (<= point (match-end group))
25971 (if context
25972 (list context (match-beginning group) (match-end group))
25973 t)))
25974
25975 (defun org-switch-to-buffer-other-window (&rest args)
25976 "Switch to buffer in a second window on the current frame.
25977 In particular, do not allow pop-up frames."
25978 (let (pop-up-frames special-display-buffer-names special-display-regexps
25979 special-display-function)
25980 (apply 'switch-to-buffer-other-window args)))
25981
25982 (defun org-combine-plists (&rest plists)
25983 "Create a single property list from all plists in PLISTS.
25984 The process starts by copying the first list, and then setting properties
25985 from the other lists. Settings in the last list are the most significant
25986 ones and overrule settings in the other lists."
25987 (let ((rtn (copy-sequence (pop plists)))
25988 p v ls)
25989 (while plists
25990 (setq ls (pop plists))
25991 (while ls
25992 (setq p (pop ls) v (pop ls))
25993 (setq rtn (plist-put rtn p v))))
25994 rtn))
25995
25996 (defun org-move-line-down (arg)
25997 "Move the current line down. With prefix argument, move it past ARG lines."
25998 (interactive "p")
25999 (let ((col (current-column))
26000 beg end pos)
26001 (beginning-of-line 1) (setq beg (point))
26002 (beginning-of-line 2) (setq end (point))
26003 (beginning-of-line (+ 1 arg))
26004 (setq pos (move-marker (make-marker) (point)))
26005 (insert (delete-and-extract-region beg end))
26006 (goto-char pos)
26007 (move-to-column col)))
26008
26009 (defun org-move-line-up (arg)
26010 "Move the current line up. With prefix argument, move it past ARG lines."
26011 (interactive "p")
26012 (let ((col (current-column))
26013 beg end pos)
26014 (beginning-of-line 1) (setq beg (point))
26015 (beginning-of-line 2) (setq end (point))
26016 (beginning-of-line (- arg))
26017 (setq pos (move-marker (make-marker) (point)))
26018 (insert (delete-and-extract-region beg end))
26019 (goto-char pos)
26020 (move-to-column col)))
26021
26022 (defun org-replace-escapes (string table)
26023 "Replace %-escapes in STRING with values in TABLE.
26024 TABLE is an association list with keys like \"%a\" and string values.
26025 The sequences in STRING may contain normal field width and padding information,
26026 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
26027 so values can contain further %-escapes if they are define later in TABLE."
26028 (let ((case-fold-search nil)
26029 e re rpl)
26030 (while (setq e (pop table))
26031 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
26032 (while (string-match re string)
26033 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
26034 (cdr e)))
26035 (setq string (replace-match rpl t t string))))
26036 string))
26037
26038
26039 (defun org-sublist (list start end)
26040 "Return a section of LIST, from START to END.
26041 Counting starts at 1."
26042 (let (rtn (c start))
26043 (setq list (nthcdr (1- start) list))
26044 (while (and list (<= c end))
26045 (push (pop list) rtn)
26046 (setq c (1+ c)))
26047 (nreverse rtn)))
26048
26049 (defun org-find-base-buffer-visiting (file)
26050 "Like `find-buffer-visiting' but alway return the base buffer and
26051 not an indirect buffer"
26052 (let ((buf (find-buffer-visiting file)))
26053 (if buf
26054 (or (buffer-base-buffer buf) buf)
26055 nil)))
26056
26057 (defun org-image-file-name-regexp ()
26058 "Return regexp matching the file names of images."
26059 (if (fboundp 'image-file-name-regexp)
26060 (image-file-name-regexp)
26061 (let ((image-file-name-extensions
26062 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
26063 "xbm" "xpm" "pbm" "pgm" "ppm")))
26064 (concat "\\."
26065 (regexp-opt (nconc (mapcar 'upcase
26066 image-file-name-extensions)
26067 image-file-name-extensions)
26068 t)
26069 "\\'"))))
26070
26071 (defun org-file-image-p (file)
26072 "Return non-nil if FILE is an image."
26073 (save-match-data
26074 (string-match (org-image-file-name-regexp) file)))
26075
26076 ;;; Paragraph filling stuff.
26077 ;; We want this to be just right, so use the full arsenal.
26078
26079 (defun org-indent-line-function ()
26080 "Indent line like previous, but further if previous was headline or item."
26081 (interactive)
26082 (let* ((pos (point))
26083 (itemp (org-at-item-p))
26084 column bpos bcol tpos tcol bullet btype bullet-type)
26085 ;; Find the previous relevant line
26086 (beginning-of-line 1)
26087 (cond
26088 ((looking-at "#") (setq column 0))
26089 ((looking-at "\\*+ ") (setq column 0))
26090 (t
26091 (beginning-of-line 0)
26092 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
26093 (beginning-of-line 0))
26094 (cond
26095 ((looking-at "\\*+[ \t]+")
26096 (goto-char (match-end 0))
26097 (setq column (current-column)))
26098 ((org-in-item-p)
26099 (org-beginning-of-item)
26100 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
26101 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
26102 (setq bpos (match-beginning 1) tpos (match-end 0)
26103 bcol (progn (goto-char bpos) (current-column))
26104 tcol (progn (goto-char tpos) (current-column))
26105 bullet (match-string 1)
26106 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
26107 (if (not itemp)
26108 (setq column tcol)
26109 (goto-char pos)
26110 (beginning-of-line 1)
26111 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
26112 (setq bullet (match-string 1)
26113 btype (if (string-match "[0-9]" bullet) "n" bullet))
26114 (setq column (if (equal btype bullet-type) bcol tcol))))
26115 (t (setq column (org-get-indentation))))))
26116 (goto-char pos)
26117 (if (<= (current-column) (current-indentation))
26118 (indent-line-to column)
26119 (save-excursion (indent-line-to column)))
26120 (setq column (current-column))
26121 (beginning-of-line 1)
26122 (if (looking-at
26123 "\\([ \t]+\\)\\(:[0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
26124 (replace-match (concat "\\1" (format org-property-format
26125 (match-string 2) (match-string 3)))
26126 t nil))
26127 (move-to-column column)))
26128
26129 (defun org-set-autofill-regexps ()
26130 (interactive)
26131 ;; In the paragraph separator we include headlines, because filling
26132 ;; text in a line directly attached to a headline would otherwise
26133 ;; fill the headline as well.
26134 (org-set-local 'comment-start-skip "^#+[ \t]*")
26135 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
26136 ;; The paragraph starter includes hand-formatted lists.
26137 (org-set-local 'paragraph-start
26138 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
26139 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
26140 ;; But only if the user has not turned off tables or fixed-width regions
26141 (org-set-local
26142 'auto-fill-inhibit-regexp
26143 (concat "\\*+ \\|#\\+"
26144 "\\|[ \t]*" org-keyword-time-regexp
26145 (if (or org-enable-table-editor org-enable-fixed-width-editor)
26146 (concat
26147 "\\|[ \t]*["
26148 (if org-enable-table-editor "|" "")
26149 (if org-enable-fixed-width-editor ":" "")
26150 "]"))))
26151 ;; We use our own fill-paragraph function, to make sure that tables
26152 ;; and fixed-width regions are not wrapped. That function will pass
26153 ;; through to `fill-paragraph' when appropriate.
26154 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
26155 ; Adaptive filling: To get full control, first make sure that
26156 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
26157 (org-set-local 'adaptive-fill-regexp "\000")
26158 (org-set-local 'adaptive-fill-function
26159 'org-adaptive-fill-function))
26160
26161 (defun org-fill-paragraph (&optional justify)
26162 "Re-align a table, pass through to fill-paragraph if no table."
26163 (let ((table-p (org-at-table-p))
26164 (table.el-p (org-at-table.el-p)))
26165 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
26166 (table.el-p t) ; skip table.el tables
26167 (table-p (org-table-align) t) ; align org-mode tables
26168 (t nil)))) ; call paragraph-fill
26169
26170 ;; For reference, this is the default value of adaptive-fill-regexp
26171 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
26172
26173 (defun org-adaptive-fill-function ()
26174 "Return a fill prefix for org-mode files.
26175 In particular, this makes sure hanging paragraphs for hand-formatted lists
26176 work correctly."
26177 (cond ((looking-at "#[ \t]+")
26178 (match-string 0))
26179 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
26180 (save-excursion
26181 (goto-char (match-end 0))
26182 (make-string (current-column) ?\ )))
26183 (t nil)))
26184
26185 ;;;; Functions extending outline functionality
26186
26187 (defun org-beginning-of-line (&optional arg)
26188 "Go to the beginning of the current line. If that is invisible, continue
26189 to a visible line beginning. This makes the function of C-a more intuitive.
26190 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
26191 first attempt, and only move to after the tags when the cursor is already
26192 beyond the end of the headline."
26193 (interactive "P")
26194 (let ((pos (point)))
26195 (beginning-of-line 1)
26196 (if (bobp)
26197 nil
26198 (backward-char 1)
26199 (if (org-invisible-p)
26200 (while (and (not (bobp)) (org-invisible-p))
26201 (backward-char 1)
26202 (beginning-of-line 1))
26203 (forward-char 1)))
26204 (when org-special-ctrl-a/e
26205 (cond
26206 ((and (looking-at org-todo-line-regexp)
26207 (= (char-after (match-end 1)) ?\ ))
26208 (goto-char
26209 (if (eq org-special-ctrl-a/e t)
26210 (cond ((> pos (match-beginning 3)) (match-beginning 3))
26211 ((= pos (point)) (match-beginning 3))
26212 (t (point)))
26213 (cond ((> pos (point)) (point))
26214 ((not (eq last-command this-command)) (point))
26215 (t (match-beginning 3))))))
26216 ((org-at-item-p)
26217 (goto-char
26218 (if (eq org-special-ctrl-a/e t)
26219 (cond ((> pos (match-end 4)) (match-end 4))
26220 ((= pos (point)) (match-end 4))
26221 (t (point)))
26222 (cond ((> pos (point)) (point))
26223 ((not (eq last-command this-command)) (point))
26224 (t (match-end 4))))))))))
26225
26226 (defun org-end-of-line (&optional arg)
26227 "Go to the end of the line.
26228 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
26229 first attempt, and only move to after the tags when the cursor is already
26230 beyond the end of the headline."
26231 (interactive "P")
26232 (if (or (not org-special-ctrl-a/e)
26233 (not (org-on-heading-p)))
26234 (end-of-line arg)
26235 (let ((pos (point)))
26236 (beginning-of-line 1)
26237 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
26238 (if (eq org-special-ctrl-a/e t)
26239 (if (or (< pos (match-beginning 1))
26240 (= pos (match-end 0)))
26241 (goto-char (match-beginning 1))
26242 (goto-char (match-end 0)))
26243 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
26244 (goto-char (match-end 0))
26245 (goto-char (match-beginning 1))))
26246 (end-of-line arg)))))
26247
26248 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
26249 (define-key org-mode-map "\C-e" 'org-end-of-line)
26250
26251 (defun org-invisible-p ()
26252 "Check if point is at a character currently not visible."
26253 ;; Early versions of noutline don't have `outline-invisible-p'.
26254 (if (fboundp 'outline-invisible-p)
26255 (outline-invisible-p)
26256 (get-char-property (point) 'invisible)))
26257
26258 (defun org-invisible-p2 ()
26259 "Check if point is at a character currently not visible."
26260 (save-excursion
26261 (if (and (eolp) (not (bobp))) (backward-char 1))
26262 ;; Early versions of noutline don't have `outline-invisible-p'.
26263 (if (fboundp 'outline-invisible-p)
26264 (outline-invisible-p)
26265 (get-char-property (point) 'invisible))))
26266
26267 (defalias 'org-back-to-heading 'outline-back-to-heading)
26268 (defalias 'org-on-heading-p 'outline-on-heading-p)
26269 (defalias 'org-at-heading-p 'outline-on-heading-p)
26270 (defun org-at-heading-or-item-p ()
26271 (or (org-on-heading-p) (org-at-item-p)))
26272
26273 (defun org-on-target-p ()
26274 (or (org-in-regexp org-radio-target-regexp)
26275 (org-in-regexp org-target-regexp)))
26276
26277 (defun org-up-heading-all (arg)
26278 "Move to the heading line of which the present line is a subheading.
26279 This function considers both visible and invisible heading lines.
26280 With argument, move up ARG levels."
26281 (if (fboundp 'outline-up-heading-all)
26282 (outline-up-heading-all arg) ; emacs 21 version of outline.el
26283 (outline-up-heading arg t))) ; emacs 22 version of outline.el
26284
26285 (defun org-up-heading-safe ()
26286 "Move to the heading line of which the present line is a subheading.
26287 This version will not throw an error. It will return the level of the
26288 headline found, or nil if no higher level is found."
26289 (let ((pos (point)) start-level level
26290 (re (concat "^" outline-regexp)))
26291 (catch 'exit
26292 (outline-back-to-heading t)
26293 (setq start-level (funcall outline-level))
26294 (if (equal start-level 1) (throw 'exit nil))
26295 (while (re-search-backward re nil t)
26296 (setq level (funcall outline-level))
26297 (if (< level start-level) (throw 'exit level)))
26298 nil)))
26299
26300 (defun org-goto-sibling (&optional previous)
26301 "Goto the next sibling, even if it is invisible.
26302 When PREVIOUS is set, go to the previous sibling instead. Returns t
26303 when a sibling was found. When none is found, return nil and don't
26304 move point."
26305 (let ((fun (if previous 're-search-backward 're-search-forward))
26306 (pos (point))
26307 (re (concat "^" outline-regexp))
26308 level l)
26309 (when (condition-case nil (org-back-to-heading t) (error nil))
26310 (setq level (funcall outline-level))
26311 (catch 'exit
26312 (or previous (forward-char 1))
26313 (while (funcall fun re nil t)
26314 (setq l (funcall outline-level))
26315 (when (< l level) (goto-char pos) (throw 'exit nil))
26316 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
26317 (goto-char pos)
26318 nil))))
26319
26320 (defun org-show-siblings ()
26321 "Show all siblings of the current headline."
26322 (save-excursion
26323 (while (org-goto-sibling) (org-flag-heading nil)))
26324 (save-excursion
26325 (while (org-goto-sibling 'previous)
26326 (org-flag-heading nil))))
26327
26328 (defun org-show-hidden-entry ()
26329 "Show an entry where even the heading is hidden."
26330 (save-excursion
26331 (org-show-entry)))
26332
26333 (defun org-flag-heading (flag &optional entry)
26334 "Flag the current heading. FLAG non-nil means make invisible.
26335 When ENTRY is non-nil, show the entire entry."
26336 (save-excursion
26337 (org-back-to-heading t)
26338 ;; Check if we should show the entire entry
26339 (if entry
26340 (progn
26341 (org-show-entry)
26342 (save-excursion
26343 (and (outline-next-heading)
26344 (org-flag-heading nil))))
26345 (outline-flag-region (max (point-min) (1- (point)))
26346 (save-excursion (outline-end-of-heading) (point))
26347 flag))))
26348
26349 (defun org-end-of-subtree (&optional invisible-OK to-heading)
26350 ;; This is an exact copy of the original function, but it uses
26351 ;; `org-back-to-heading', to make it work also in invisible
26352 ;; trees. And is uses an invisible-OK argument.
26353 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
26354 (org-back-to-heading invisible-OK)
26355 (let ((first t)
26356 (level (funcall outline-level)))
26357 (while (and (not (eobp))
26358 (or first (> (funcall outline-level) level)))
26359 (setq first nil)
26360 (outline-next-heading))
26361 (unless to-heading
26362 (if (memq (preceding-char) '(?\n ?\^M))
26363 (progn
26364 ;; Go to end of line before heading
26365 (forward-char -1)
26366 (if (memq (preceding-char) '(?\n ?\^M))
26367 ;; leave blank line before heading
26368 (forward-char -1))))))
26369 (point))
26370
26371 (defun org-show-subtree ()
26372 "Show everything after this heading at deeper levels."
26373 (outline-flag-region
26374 (point)
26375 (save-excursion
26376 (outline-end-of-subtree) (outline-next-heading) (point))
26377 nil))
26378
26379 (defun org-show-entry ()
26380 "Show the body directly following this heading.
26381 Show the heading too, if it is currently invisible."
26382 (interactive)
26383 (save-excursion
26384 (condition-case nil
26385 (progn
26386 (org-back-to-heading t)
26387 (outline-flag-region
26388 (max (point-min) (1- (point)))
26389 (save-excursion
26390 (re-search-forward
26391 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
26392 (or (match-beginning 1) (point-max)))
26393 nil))
26394 (error nil))))
26395
26396 (defun org-make-options-regexp (kwds)
26397 "Make a regular expression for keyword lines."
26398 (concat
26399 "^"
26400 "#?[ \t]*\\+\\("
26401 (mapconcat 'regexp-quote kwds "\\|")
26402 "\\):[ \t]*"
26403 "\\(.+\\)"))
26404
26405 ;; Make isearch reveal the necessary context
26406 (defun org-isearch-end ()
26407 "Reveal context after isearch exits."
26408 (when isearch-success ; only if search was successful
26409 (if (featurep 'xemacs)
26410 ;; Under XEmacs, the hook is run in the correct place,
26411 ;; we directly show the context.
26412 (org-show-context 'isearch)
26413 ;; In Emacs the hook runs *before* restoring the overlays.
26414 ;; So we have to use a one-time post-command-hook to do this.
26415 ;; (Emacs 22 has a special variable, see function `org-mode')
26416 (unless (and (boundp 'isearch-mode-end-hook-quit)
26417 isearch-mode-end-hook-quit)
26418 ;; Only when the isearch was not quitted.
26419 (org-add-hook 'post-command-hook 'org-isearch-post-command
26420 'append 'local)))))
26421
26422 (defun org-isearch-post-command ()
26423 "Remove self from hook, and show context."
26424 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
26425 (org-show-context 'isearch))
26426
26427
26428 ;;;; Address problems with some other packages
26429
26430 ;; Make flyspell not check words in links, to not mess up our keymap
26431 (defun org-mode-flyspell-verify ()
26432 "Don't let flyspell put overlays at active buttons."
26433 (not (get-text-property (point) 'keymap)))
26434
26435 ;; Make `bookmark-jump' show the jump location if it was hidden.
26436 (eval-after-load "bookmark"
26437 '(if (boundp 'bookmark-after-jump-hook)
26438 ;; We can use the hook
26439 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
26440 ;; Hook not available, use advice
26441 (defadvice bookmark-jump (after org-make-visible activate)
26442 "Make the position visible."
26443 (org-bookmark-jump-unhide))))
26444
26445 (defun org-bookmark-jump-unhide ()
26446 "Unhide the current position, to show the bookmark location."
26447 (and (org-mode-p)
26448 (or (org-invisible-p)
26449 (save-excursion (goto-char (max (point-min) (1- (point))))
26450 (org-invisible-p)))
26451 (org-show-context 'bookmark-jump)))
26452
26453 ;; Make session.el ignore our circular variable
26454 (eval-after-load "session"
26455 '(add-to-list 'session-globals-exclude 'org-mark-ring))
26456
26457 ;;;; Experimental code
26458
26459 (defun org-closed-in-range ()
26460 "Sparse tree of items closed in a certain time range.
26461 Still experimental, may disappear in the furture."
26462 (interactive)
26463 ;; Get the time interval from the user.
26464 (let* ((time1 (time-to-seconds
26465 (org-read-date nil 'to-time nil "Starting date: ")))
26466 (time2 (time-to-seconds
26467 (org-read-date nil 'to-time nil "End date:")))
26468 ;; callback function
26469 (callback (lambda ()
26470 (let ((time
26471 (time-to-seconds
26472 (apply 'encode-time
26473 (org-parse-time-string
26474 (match-string 1))))))
26475 ;; check if time in interval
26476 (and (>= time time1) (<= time time2))))))
26477 ;; make tree, check each match with the callback
26478 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
26479
26480 (defun org-fill-paragraph-experimental (&optional justify)
26481 "Re-align a table, pass through to fill-paragraph if no table."
26482 (let ((table-p (org-at-table-p))
26483 (table.el-p (org-at-table.el-p)))
26484 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
26485 (table.el-p t) ; skip table.el tables
26486 (table-p (org-table-align) t) ; align org-mode tables
26487 ((save-excursion
26488 (let ((pos (1+ (point-at-eol))))
26489 (backward-paragraph 1)
26490 (re-search-forward "\\\\\\\\[ \t]*$" pos t)))
26491 (save-excursion
26492 (save-restriction
26493 (narrow-to-region (1+ (match-end 0)) (point-max))
26494 (fill-paragraph nil)
26495 t)))
26496 (t nil)))) ; call paragraph-fill
26497
26498 ;; FIXME: this needs a much better algorithm
26499 (defun org-assign-fast-keys (alist)
26500 "Assign fast keys to a keyword-key alist.
26501 Respect keys that are already there."
26502 (let (new e k c c1 c2 (char ?a))
26503 (while (setq e (pop alist))
26504 (cond
26505 ((equal e '(:startgroup)) (push e new))
26506 ((equal e '(:endgroup)) (push e new))
26507 (t
26508 (setq k (car e) c2 nil)
26509 (if (cdr e)
26510 (setq c (cdr e))
26511 ;; automatically assign a character.
26512 (setq c1 (string-to-char
26513 (downcase (substring
26514 k (if (= (string-to-char k) ?@) 1 0)))))
26515 (if (or (rassoc c1 new) (rassoc c1 alist))
26516 (while (or (rassoc char new) (rassoc char alist))
26517 (setq char (1+ char)))
26518 (setq c2 c1))
26519 (setq c (or c2 char)))
26520 (push (cons k c) new))))
26521 (nreverse new)))
26522
26523 ;(defcustom org-read-date-prefer-future nil
26524 ; "Non-nil means, when reading an incomplete date from the user, assume future.
26525 ;This affects the following situations:
26526 ;1. The user give a day, but no month.
26527 ; In this case, if the day number if after today, the current month will
26528 ; be used, otherwise the next month.
26529 ;2. The user gives a month but not a year.
26530 ; In this case, the the given month is after the current month, the current
26531 ; year will be used. Otherwise the next year will be used.;
26532 ;
26533 ;When nil, always the current month and year will be used."
26534 ; :group 'org-time ;????
26535 ; :type 'boolean)
26536
26537
26538 ;;;; Finish up
26539
26540 (provide 'org)
26541
26542 (run-hooks 'org-load-hook)
26543
26544 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
26545 ;;; org.el ends here
26546
26547