Release 5.06e
[org-mode/org-tableheadings.git] / org.el
blob160a3f6147078a33c1b54e9fa044d300250b626c
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 <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
8 ;; Version: 5.06e
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://staff.science.uva.nl/~dominik/Tools/org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://www.astro.uva.nl/~dominik/Tools/org/Changes
65 ;;; Code:
67 ;;;; Require other packages
69 (eval-when-compile
70 (require 'cl)
71 (require 'gnus-sum)
72 (require 'calendar))
73 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
74 ;; the file noutline.el being loaded.
75 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
76 ;; We require noutline, which might be provided in outline.el
77 (require 'outline) (require 'noutline)
78 ;; Other stuff we need.
79 (require 'time-date)
80 (require 'easymenu)
82 ;;;; Customization variables
84 ;;; Version
86 (defconst org-version "5.06e"
87 "The version number of the file org.el.")
88 (defun org-version ()
89 (interactive)
90 (message "Org-mode version %s" org-version))
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?")
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)))
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 ss))
115 (defmacro org-preserve-lc (&rest body)
116 `(let ((_line (org-current-line))
117 (_col (current-column)))
118 (unwind-protect
119 (progn ,@body)
120 (goto-line _line)
121 (move-to-column _col))))
123 ;;; The custom variables
125 (defgroup org nil
126 "Outline-based notes management and organizer."
127 :tag "Org"
128 :group 'outlines
129 :group 'hypermedia
130 :group 'calendar)
132 (defgroup org-startup nil
133 "Options concerning startup of Org-mode."
134 :tag "Org Startup"
135 :group 'org)
137 (defcustom org-startup-folded t
138 "Non-nil means, entering Org-mode will switch to OVERVIEW.
139 This can also be configured on a per-file basis by adding one of
140 the following lines anywhere in the buffer:
142 #+STARTUP: fold
143 #+STARTUP: nofold
144 #+STARTUP: content"
145 :group 'org-startup
146 :type '(choice
147 (const :tag "nofold: show all" nil)
148 (const :tag "fold: overview" t)
149 (const :tag "content: all headlines" content)))
151 (defcustom org-startup-truncated t
152 "Non-nil means, entering Org-mode will set `truncate-lines'.
153 This is useful since some lines containing links can be very long and
154 uninteresting. Also tables look terrible when wrapped."
155 :group 'org-startup
156 :type 'boolean)
158 (defcustom org-startup-align-all-tables nil
159 "Non-nil means, align all tables when visiting a file.
160 This is useful when the column width in tables is forced with <N> cookies
161 in table fields. Such tables will look correct only after the first re-align.
162 This can also be configured on a per-file basis by adding one of
163 the following lines anywhere in the buffer:
164 #+STARTUP: align
165 #+STARTUP: noalign"
166 :group 'org-startup
167 :type 'boolean)
169 (defcustom org-insert-mode-line-in-empty-file nil
170 "Non-nil means insert the first line setting Org-mode in empty files.
171 When the function `org-mode' is called interactively in an empty file, this
172 normally means that the file name does not automatically trigger Org-mode.
173 To ensure that the file will always be in Org-mode in the future, a
174 line enforcing Org-mode will be inserted into the buffer, if this option
175 has been set."
176 :group 'org-startup
177 :type 'boolean)
179 (defcustom org-replace-disputed-keys nil
180 "Non-nil means use alternative key bindings for some keys.
181 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
182 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
183 If you want to use Org-mode together with one of these other modes,
184 or more generally if you would like to move some Org-mode commands to
185 other keys, set this variable and configure the keys with the variable
186 `org-disputed-keys'.
188 This option is only relevant at load-time of Org-mode, and must be set
189 *before* org.el is loaded. Changing it requires a restart of Emacs to
190 become effective."
191 :group 'org-startup
192 :type 'boolean)
194 (if (fboundp 'defvaralias)
195 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
197 (defcustom org-disputed-keys
198 '(([(shift up)] . [(meta p)])
199 ([(shift down)] . [(meta n)])
200 ([(shift left)] . [(meta -)])
201 ([(shift right)] . [(meta +)])
202 ([(control shift right)] . [(meta shift +)])
203 ([(control shift left)] . [(meta shift -)]))
204 "Keys for which Org-mode and other modes compete.
205 This is an alist, cars are the default keys, second element specifies
206 the alternative to use when `org-replace-disputed-keys' is t.
208 Keys can be specified in any syntax supported by `define-key'.
209 The value of this option takes effect only at Org-mode's startup,
210 therefore you'll have to restart Emacs to apply it after changing."
211 :group 'org-startup
212 :type 'alist)
214 (defun org-key (key)
215 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
216 Or return the original if not disputed."
217 (if org-replace-disputed-keys
218 (let* ((nkey (key-description key))
219 (x (org-find-if (lambda (x)
220 (equal (key-description (car x)) nkey))
221 org-disputed-keys)))
222 (if x (cdr x) key))
223 key))
225 (defun org-find-if (predicate seq)
226 (catch 'exit
227 (while seq
228 (if (funcall predicate (car seq))
229 (throw 'exit (car seq))
230 (pop seq)))))
232 (defun org-defkey (keymap key def)
233 "Define a key, possibly translated, as returned by `org-key'."
234 (define-key keymap (org-key key) def))
236 (defcustom org-ellipsis nil
237 "The ellipsis to use in the Org-mode outline.
238 When nil, just use the standard three dots. When a string, use that instead,
239 and just in Org-mode (which will then use its own display table).
240 Changing this requires executing `M-x org-mode' in a buffer to become
241 effective."
242 :group 'org-startup
243 :type '(choice (const :tag "Default" nil)
244 (string :tag "String" :value "...#")))
246 (defvar org-display-table nil
247 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
249 (defgroup org-keywords nil
250 "Keywords in Org-mode."
251 :tag "Org Keywords"
252 :group 'org)
254 (defcustom org-deadline-string "DEADLINE:"
255 "String to mark deadline entries.
256 A deadline is this string, followed by a time stamp. Should be a word,
257 terminated by a colon. You can insert a schedule keyword and
258 a timestamp with \\[org-deadline].
259 Changes become only effective after restarting Emacs."
260 :group 'org-keywords
261 :type 'string)
263 (defcustom org-scheduled-string "SCHEDULED:"
264 "String to mark scheduled TODO entries.
265 A schedule is this string, followed by a time stamp. Should be a word,
266 terminated by a colon. You can insert a schedule keyword and
267 a timestamp with \\[org-schedule].
268 Changes become only effective after restarting Emacs."
269 :group 'org-keywords
270 :type 'string)
272 (defcustom org-closed-string "CLOSED:"
273 "String used as the prefix for timestamps logging closing a TODO entry."
274 :group 'org-keywords
275 :type 'string)
277 (defcustom org-archived-string "ARCHIVED:"
278 "String used as the prefix for timestamps logging archiving a TODO entry."
279 :group 'org-keywords
280 :type 'string)
282 (defcustom org-clock-string "CLOCK:"
283 "String used as prefix for timestamps clocking work hours on an item."
284 :group 'org-keywords
285 :type 'string)
287 (defcustom org-comment-string "COMMENT"
288 "Entries starting with this keyword will never be exported.
289 An entry can be toggled between COMMENT and normal with
290 \\[org-toggle-comment].
291 Changes become only effective after restarting Emacs."
292 :group 'org-keywords
293 :type 'string)
295 (defcustom org-quote-string "QUOTE"
296 "Entries starting with this keyword will be exported in fixed-width font.
297 Quoting applies only to the text in the entry following the headline, and does
298 not extend beyond the next headline, even if that is lower level.
299 An entry can be toggled between QUOTE and normal with
300 \\[org-toggle-fixed-width-section]."
301 :group 'org-keywords
302 :type 'string)
304 (defconst org-repeat-re
305 (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
306 " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
307 "Regular expression for specifying repeated events.
308 After a match, group 1 contains the repeat expression.")
310 (defgroup org-structure nil
311 "Options concerning the general structure of Org-mode files."
312 :tag "Org Structure"
313 :group 'org)
315 (defgroup org-reveal-location nil
316 "Options about how to make context of a location visible."
317 :tag "Org Reveal Location"
318 :group 'org-structure)
320 (defcustom org-show-hierarchy-above '((default . t))
321 "Non-nil means, show full hierarchy when revealing a location.
322 Org-mode often shows locations in an org-mode file which might have
323 been invisible before. When this is set, the hierarchy of headings
324 above the exposed location is shown.
325 Turning this off for example for sparse trees makes them very compact.
326 Instead of t, this can also be an alist specifying this option for different
327 contexts. Valid contexts are
328 agenda when exposing an entry from the agenda
329 org-goto when using the command `org-goto' on key C-c C-j
330 occur-tree when using the command `org-occur' on key C-c /
331 tags-tree when constructing a sparse tree based on tags matches
332 link-search when exposing search matches associated with a link
333 mark-goto when exposing the jump goal of a mark
334 bookmark-jump when exposing a bookmark location
335 isearch when exiting from an incremental search
336 default default for all contexts not set explicitly"
337 :group 'org-reveal-location
338 :type '(choice
339 (const :tag "Always" t)
340 (const :tag "Never" nil)
341 (repeat :greedy t :tag "Individual contexts"
342 (cons
343 (choice :tag "Context"
344 (const agenda)
345 (const org-goto)
346 (const occur-tree)
347 (const tags-tree)
348 (const link-search)
349 (const mark-goto)
350 (const bookmark-jump)
351 (const isearch)
352 (const default))
353 (boolean)))))
355 (defcustom org-show-following-heading '((default . nil))
356 "Non-nil means, show following heading when revealing a location.
357 Org-mode often shows locations in an org-mode file which might have
358 been invisible before. When this is set, the heading following the
359 match is shown.
360 Turning this off for example for sparse trees makes them very compact,
361 but makes it harder to edit the location of the match. In such a case,
362 use the command \\[org-reveal] to show more context.
363 Instead of t, this can also be an alist specifying this option for different
364 contexts. See `org-show-hierarchy-above' for valid contexts."
365 :group 'org-reveal-location
366 :type '(choice
367 (const :tag "Always" t)
368 (const :tag "Never" nil)
369 (repeat :greedy t :tag "Individual contexts"
370 (cons
371 (choice :tag "Context"
372 (const agenda)
373 (const org-goto)
374 (const occur-tree)
375 (const tags-tree)
376 (const link-search)
377 (const mark-goto)
378 (const bookmark-jump)
379 (const isearch)
380 (const default))
381 (boolean)))))
383 (defcustom org-show-siblings '((default . nil) (isearch t))
384 "Non-nil means, show all sibling heading when revealing a location.
385 Org-mode often shows locations in an org-mode file which might have
386 been invisible before. When this is set, the sibling of the current entry
387 heading are all made visible. If `org-show-hierarchy-above' is t,
388 the same happens on each level of the hierarchy above the current entry.
390 By default this is on for the isearch context, off for all other contexts.
391 Turning this off for example for sparse trees makes them very compact,
392 but makes it harder to edit the location of the match. In such a case,
393 use the command \\[org-reveal] to show more context.
394 Instead of t, this can also be an alist specifying this option for different
395 contexts. See `org-show-hierarchy-above' for valid contexts."
396 :group 'org-reveal-location
397 :type '(choice
398 (const :tag "Always" t)
399 (const :tag "Never" nil)
400 (repeat :greedy t :tag "Individual contexts"
401 (cons
402 (choice :tag "Context"
403 (const agenda)
404 (const org-goto)
405 (const occur-tree)
406 (const tags-tree)
407 (const link-search)
408 (const mark-goto)
409 (const bookmark-jump)
410 (const isearch)
411 (const default))
412 (boolean)))))
414 (defgroup org-cycle nil
415 "Options concerning visibility cycling in Org-mode."
416 :tag "Org Cycle"
417 :group 'org-structure)
419 (defcustom org-drawers '("PROPERTIES")
420 "Names of drawers. Drawers are not opened by cycling on the headline above.
421 Drawers only open with a TAB on the drawer line itself. A drawer looks like
422 this:
423 :DRAWERNAME:
424 .....
425 :END:
426 The drawer \"PROPERTIES\" is special for capturing properties through
427 the property API."
428 :group 'org-structure
429 :type '(repeat (string :tag "Drawer Name")))
431 (defcustom org-cycle-global-at-bob nil
432 "Cycle globally if cursor is at beginning of buffer and not at a headline.
433 This makes it possible to do global cycling without having to use S-TAB or
434 C-u TAB. For this special case to work, the first line of the buffer
435 must not be a headline - it may be empty ot some other text. When used in
436 this way, `org-cycle-hook' is disables temporarily, to make sure the
437 cursor stays at the beginning of the buffer.
438 When this option is nil, don't do anything special at the beginning
439 of the buffer."
440 :group 'org-cycle
441 :type 'boolean)
443 (defcustom org-cycle-emulate-tab t
444 "Where should `org-cycle' emulate TAB.
445 nil Never
446 white Only in completely white lines
447 whitestart Only at the beginning of lines, before the first non-white char.
448 t Everywhere except in headlines
449 exc-hl-bol Everywhere except at the start of a headline
450 If TAB is used in a place where it does not emulate TAB, the current subtree
451 visibility is cycled."
452 :group 'org-cycle
453 :type '(choice (const :tag "Never" nil)
454 (const :tag "Only in completely white lines" white)
455 (const :tag "Before first char in a line" whitestart)
456 (const :tag "Everywhere except in headlines" t)
457 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
460 (defcustom org-cycle-separator-lines 2
461 "Number of empty lines needed to keep an empty line between collapsed trees.
462 If you leave an empty line between the end of a subtree and the following
463 headline, this empty line is hidden when the subtree is folded.
464 Org-mode will leave (exactly) one empty line visible if the number of
465 empty lines is equal or larger to the number given in this variable.
466 So the default 2 means, at least 2 empty lines after the end of a subtree
467 are needed to produce free space between a collapsed subtree and the
468 following headline.
470 Special case: when 0, never leave empty lines in collapsed view."
471 :group 'org-cycle
472 :type 'integer)
474 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
475 org-cycle-hide-drawers
476 org-cycle-show-empty-lines
477 org-optimize-window-after-visibility-change)
478 "Hook that is run after `org-cycle' has changed the buffer visibility.
479 The function(s) in this hook must accept a single argument which indicates
480 the new state that was set by the most recent `org-cycle' command. The
481 argument is a symbol. After a global state change, it can have the values
482 `overview', `content', or `all'. After a local state change, it can have
483 the values `folded', `children', or `subtree'."
484 :group 'org-cycle
485 :type 'hook)
487 (defgroup org-edit-structure nil
488 "Options concerning structure editing in Org-mode."
489 :tag "Org Edit Structure"
490 :group 'org-structure)
492 (defcustom org-special-ctrl-a/e nil
493 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
494 When t, `C-a' will bring back the cursor to the beginning of the
495 headline text, i.e. after the stars and after a possible TODO keyword.
496 In an item, this will be the position after the bullet.
497 When the cursor is already at that position, another `C-a' will bring
498 it to the beginning of the line.
499 `C-e' will jump to the end of the headline, ignoring the presence of tags
500 in the headline. A second `C-e' will then jump to the true end of the
501 line, after any tags.
502 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
503 and only a directly following, identical keypress will bring the cursor
504 to the special positions."
505 :group 'org-edit-structure
506 :type '(choice
507 (const :tag "off" nil)
508 (const :tag "after bullet first" t)
509 (const :tag "border first" reversed)))
511 (if (fboundp 'defvaralias)
512 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
514 (defcustom org-odd-levels-only nil
515 "Non-nil means, skip even levels and only use odd levels for the outline.
516 This has the effect that two stars are being added/taken away in
517 promotion/demotion commands. It also influences how levels are
518 handled by the exporters.
519 Changing it requires restart of `font-lock-mode' to become effective
520 for fontification also in regions already fontified.
521 You may also set this on a per-file basis by adding one of the following
522 lines to the buffer:
524 #+STARTUP: odd
525 #+STARTUP: oddeven"
526 :group 'org-edit-structure
527 :group 'org-font-lock
528 :type 'boolean)
530 (defcustom org-adapt-indentation t
531 "Non-nil means, adapt indentation when promoting and demoting.
532 When this is set and the *entire* text in an entry is indented, the
533 indentation is increased by one space in a demotion command, and
534 decreased by one in a promotion command. If any line in the entry
535 body starts at column 0, indentation is not changed at all."
536 :group 'org-edit-structure
537 :type 'boolean)
539 (defcustom org-blank-before-new-entry '((heading . nil)
540 (plain-list-item . nil))
541 "Should `org-insert-heading' leave a blank line before new heading/item?
542 The value is an alist, with `heading' and `plain-list-item' as car,
543 and a boolean flag as cdr."
544 :group 'org-edit-structure
545 :type '(list
546 (cons (const heading) (boolean))
547 (cons (const plain-list-item) (boolean))))
549 (defcustom org-insert-heading-hook nil
550 "Hook being run after inserting a new heading."
551 :group 'org-edit-structure
552 :type 'boolean)
554 (defcustom org-enable-fixed-width-editor t
555 "Non-nil means, lines starting with \":\" are treated as fixed-width.
556 This currently only means, they are never auto-wrapped.
557 When nil, such lines will be treated like ordinary lines.
558 See also the QUOTE keyword."
559 :group 'org-edit-structure
560 :type 'boolean)
562 (defgroup org-sparse-trees nil
563 "Options concerning sparse trees in Org-mode."
564 :tag "Org Sparse Trees"
565 :group 'org-structure)
567 (defcustom org-highlight-sparse-tree-matches t
568 "Non-nil means, highlight all matches that define a sparse tree.
569 The highlights will automatically disappear the next time the buffer is
570 changed by an edit command."
571 :group 'org-sparse-trees
572 :type 'boolean)
574 (defcustom org-remove-highlights-with-change t
575 "Non-nil means, any change to the buffer will remove temporary highlights.
576 Such highlights are created by `org-occur' and `org-clock-display'.
577 When nil, `C-c C-c needs to be used to get rid of the highlights.
578 The highlights created by `org-preview-latex-fragment' always need
579 `C-c C-c' to be removed."
580 :group 'org-sparse-trees
581 :group 'org-time
582 :type 'boolean)
585 (defcustom org-occur-hook '(org-first-headline-recenter)
586 "Hook that is run after `org-occur' has constructed a sparse tree.
587 This can be used to recenter the window to show as much of the structure
588 as possible."
589 :group 'org-sparse-trees
590 :type 'hook)
592 (defgroup org-plain-lists nil
593 "Options concerning plain lists in Org-mode."
594 :tag "Org Plain lists"
595 :group 'org-structure)
597 (defcustom org-cycle-include-plain-lists nil
598 "Non-nil means, include plain lists into visibility cycling.
599 This means that during cycling, plain list items will *temporarily* be
600 interpreted as outline headlines with a level given by 1000+i where i is the
601 indentation of the bullet. In all other operations, plain list items are
602 not seen as headlines. For example, you cannot assign a TODO keyword to
603 such an item."
604 :group 'org-plain-lists
605 :type 'boolean)
607 (defcustom org-plain-list-ordered-item-terminator t
608 "The character that makes a line with leading number an ordered list item.
609 Valid values are ?. and ?\). To get both terminators, use t. While
610 ?. may look nicer, it creates the danger that a line with leading
611 number may be incorrectly interpreted as an item. ?\) therefore is
612 the safe choice."
613 :group 'org-plain-lists
614 :type '(choice (const :tag "dot like in \"2.\"" ?.)
615 (const :tag "paren like in \"2)\"" ?\))
616 (const :tab "both" t)))
618 (defcustom org-auto-renumber-ordered-lists t
619 "Non-nil means, automatically renumber ordered plain lists.
620 Renumbering happens when the sequence have been changed with
621 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
622 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
623 :group 'org-plain-lists
624 :type 'boolean)
626 (defcustom org-provide-checkbox-statistics t
627 "Non-nil means, update checkbox statistics after insert and toggle.
628 When this is set, checkbox statistics is updated each time you either insert
629 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
630 with \\[org-ctrl-c-ctrl-c\\]."
631 :group 'org-plain-lists
632 :type 'boolean)
634 (defgroup org-archive nil
635 "Options concerning archiving in Org-mode."
636 :tag "Org Archive"
637 :group 'org-structure)
639 (defcustom org-archive-tag "ARCHIVE"
640 "The tag that marks a subtree as archived.
641 An archived subtree does not open during visibility cycling, and does
642 not contribute to the agenda listings."
643 :group 'org-archive
644 :group 'org-keywords
645 :type 'string)
647 (defcustom org-agenda-skip-archived-trees t
648 "Non-nil means, the agenda will skip any items located in archived trees.
649 An archived tree is a tree marked with the tag ARCHIVE."
650 :group 'org-archive
651 :group 'org-agenda-skip
652 :type 'boolean)
654 (defcustom org-cycle-open-archived-trees nil
655 "Non-nil means, `org-cycle' will open archived trees.
656 An archived tree is a tree marked with the tag ARCHIVE.
657 When nil, archived trees will stay folded. You can still open them with
658 normal outline commands like `show-all', but not with the cycling commands."
659 :group 'org-archive
660 :group 'org-cycle
661 :type 'boolean)
663 (defcustom org-sparse-tree-open-archived-trees nil
664 "Non-nil means sparse tree construction shows matches in archived trees.
665 When nil, matches in these trees are highlighted, but the trees are kept in
666 collapsed state."
667 :group 'org-archive
668 :group 'org-sparse-trees
669 :type 'boolean)
671 (defcustom org-archive-location "%s_archive::"
672 "The location where subtrees should be archived.
673 This string consists of two parts, separated by a double-colon.
675 The first part is a file name - when omitted, archiving happens in the same
676 file. %s will be replaced by the current file name (without directory part).
677 Archiving to a different file is useful to keep archived entries from
678 contributing to the Org-mode Agenda.
680 The part after the double colon is a headline. The archived entries will be
681 filed under that headline. When omitted, the subtrees are simply filed away
682 at the end of the file, as top-level entries.
684 Here are a few examples:
685 \"%s_archive::\"
686 If the current file is Projects.org, archive in file
687 Projects.org_archive, as top-level trees. This is the default.
689 \"::* Archived Tasks\"
690 Archive in the current file, under the top-level headline
691 \"* Archived Tasks\".
693 \"~/org/archive.org::\"
694 Archive in file ~/org/archive.org (absolute path), as top-level trees.
696 \"basement::** Finished Tasks\"
697 Archive in file ./basement (relative path), as level 3 trees
698 below the level 2 heading \"** Finished Tasks\".
700 You may set this option on a per-file basis by adding to the buffer a
701 line like
703 #+ARCHIVE: basement::** Finished Tasks"
704 :group 'org-archive
705 :type 'string)
707 (defcustom org-archive-mark-done t
708 "Non-nil means, mark entries as DONE when they are moved to the archive file.
709 This can be a string to set the keyword to use. When t, Org-mode will
710 use the first keyword in its list that means done."
711 :group 'org-archive
712 :type '(choice
713 (const :tag "No" nil)
714 (const :tag "Yes" t)
715 (string :tag "Use this keyword")))
717 (defcustom org-archive-stamp-time t
718 "Non-nil means, add a time stamp to entries moved to an archive file."
719 :group 'org-archive
720 :type 'boolean)
722 (defgroup org-table nil
723 "Options concerning tables in Org-mode."
724 :tag "Org Table"
725 :group 'org)
727 (defcustom org-enable-table-editor 'optimized
728 "Non-nil means, lines starting with \"|\" are handled by the table editor.
729 When nil, such lines will be treated like ordinary lines.
731 When equal to the symbol `optimized', the table editor will be optimized to
732 do the following:
733 - Automatic overwrite mode in front of whitespace in table fields.
734 This makes the structure of the table stay in tact as long as the edited
735 field does not exceed the column width.
736 - Minimize the number of realigns. Normally, the table is aligned each time
737 TAB or RET are pressed to move to another field. With optimization this
738 happens only if changes to a field might have changed the column width.
739 Optimization requires replacing the functions `self-insert-command',
740 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
741 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
742 very good at guessing when a re-align will be necessary, but you can always
743 force one with \\[org-ctrl-c-ctrl-c].
745 If you would like to use the optimized version in Org-mode, but the
746 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
748 This variable can be used to turn on and off the table editor during a session,
749 but in order to toggle optimization, a restart is required.
751 See also the variable `org-table-auto-blank-field'."
752 :group 'org-table
753 :type '(choice
754 (const :tag "off" nil)
755 (const :tag "on" t)
756 (const :tag "on, optimized" optimized)))
758 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
759 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
760 In the optimized version, the table editor takes over all simple keys that
761 normally just insert a character. In tables, the characters are inserted
762 in a way to minimize disturbing the table structure (i.e. in overwrite mode
763 for empty fields). Outside tables, the correct binding of the keys is
764 restored.
766 The default for this option is t if the optimized version is also used in
767 Org-mode. See the variable `org-enable-table-editor' for details. Changing
768 this variable requires a restart of Emacs to become effective."
769 :group 'org-table
770 :type 'boolean)
772 (defcustom orgtbl-radio-table-templates
773 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
774 % END RECEIVE ORGTBL %n
775 \\begin{comment}
776 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
777 | | |
778 \\end{comment}\n")
779 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
780 @c END RECEIVE ORGTBL %n
781 @ignore
782 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
783 | | |
784 @end ignore\n")
785 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
786 <!-- END RECEIVE ORGTBL %n -->
787 <!--
788 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
789 | | |
790 -->\n"))
791 "Templates for radio tables in different major modes.
792 All occurrences of %n in a template will be replaced with the name of the
793 table, obtained by prompting the user."
794 :group 'org-table
795 :type '(repeat
796 (list (symbol :tag "Major mode")
797 (string :tag "Format"))))
799 (defgroup org-table-settings nil
800 "Settings for tables in Org-mode."
801 :tag "Org Table Settings"
802 :group 'org-table)
804 (defcustom org-table-default-size "5x2"
805 "The default size for newly created tables, Columns x Rows."
806 :group 'org-table-settings
807 :type 'string)
809 (defcustom org-table-number-regexp
810 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
811 "Regular expression for recognizing numbers in table columns.
812 If a table column contains mostly numbers, it will be aligned to the
813 right. If not, it will be aligned to the left.
815 The default value of this option is a regular expression which allows
816 anything which looks remotely like a number as used in scientific
817 context. For example, all of the following will be considered a
818 number:
819 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
821 Other options offered by the customize interface are more restrictive."
822 :group 'org-table-settings
823 :type '(choice
824 (const :tag "Positive Integers"
825 "^[0-9]+$")
826 (const :tag "Integers"
827 "^[-+]?[0-9]+$")
828 (const :tag "Floating Point Numbers"
829 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
830 (const :tag "Floating Point Number or Integer"
831 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
832 (const :tag "Exponential, Floating point, Integer"
833 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
834 (const :tag "Very General Number-Like, including hex"
835 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
836 (string :tag "Regexp:")))
838 (defcustom org-table-number-fraction 0.5
839 "Fraction of numbers in a column required to make the column align right.
840 In a column all non-white fields are considered. If at least this
841 fraction of fields is matched by `org-table-number-fraction',
842 alignment to the right border applies."
843 :group 'org-table-settings
844 :type 'number)
846 (defgroup org-table-editing nil
847 "Bahavior of tables during editing in Org-mode."
848 :tag "Org Table Editing"
849 :group 'org-table)
851 (defcustom org-table-automatic-realign t
852 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
853 When nil, aligning is only done with \\[org-table-align], or after column
854 removal/insertion."
855 :group 'org-table-editing
856 :type 'boolean)
858 (defcustom org-table-auto-blank-field t
859 "Non-nil means, automatically blank table field when starting to type into it.
860 This only happens when typing immediately after a field motion
861 command (TAB, S-TAB or RET).
862 Only relevant when `org-enable-table-editor' is equal to `optimized'."
863 :group 'org-table-editing
864 :type 'boolean)
866 (defcustom org-table-tab-jumps-over-hlines t
867 "Non-nil means, tab in the last column of a table with jump over a hline.
868 If a horizontal separator line is following the current line,
869 `org-table-next-field' can either create a new row before that line, or jump
870 over the line. When this option is nil, a new line will be created before
871 this line."
872 :group 'org-table-editing
873 :type 'boolean)
875 (defcustom org-table-tab-recognizes-table.el t
876 "Non-nil means, TAB will automatically notice a table.el table.
877 When it sees such a table, it moves point into it and - if necessary -
878 calls `table-recognize-table'."
879 :group 'org-table-editing
880 :type 'boolean)
882 (defgroup org-table-calculation nil
883 "Options concerning tables in Org-mode."
884 :tag "Org Table Calculation"
885 :group 'org-table)
887 (defcustom org-table-use-standard-references t
888 "Should org-mode work with table refrences like B3 instead of @3$2?
889 Possible values are:
890 nil never use them
891 from accept as input, do not present for editing
892 t: accept as input and present for editing"
893 :group 'org-table-calculation
894 :type '(choice
895 (const :tag "Never, don't even check unser input for them" nil)
896 (const :tag "Always, both as user input, and when editing" t)
897 (const :tag "Convert user input, don't offer during editing" 'from)))
899 (defcustom org-table-copy-increment t
900 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
901 :group 'org-table-calculation
902 :type 'boolean)
904 (defcustom org-calc-default-modes
905 '(calc-internal-prec 12
906 calc-float-format (float 5)
907 calc-angle-mode deg
908 calc-prefer-frac nil
909 calc-symbolic-mode nil
910 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
911 calc-display-working-message t
913 "List with Calc mode settings for use in calc-eval for table formulas.
914 The list must contain alternating symbols (Calc modes variables and values).
915 Don't remove any of the default settings, just change the values. Org-mode
916 relies on the variables to be present in the list."
917 :group 'org-table-calculation
918 :type 'plist)
920 (defcustom org-table-formula-evaluate-inline t
921 "Non-nil means, TAB and RET evaluate a formula in current table field.
922 If the current field starts with an equal sign, it is assumed to be a formula
923 which should be evaluated as described in the manual and in the documentation
924 string of the command `org-table-eval-formula'. This feature requires the
925 Emacs calc package.
926 When this variable is nil, formula calculation is only available through
927 the command \\[org-table-eval-formula]."
928 :group 'org-table-calculation
929 :type 'boolean)
931 (defcustom org-table-formula-use-constants t
932 "Non-nil means, interpret constants in formulas in tables.
933 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
934 by the value given in `org-table-formula-constants', or by a value obtained
935 from the `constants.el' package."
936 :group 'org-table-calculation
937 :type 'boolean)
939 (defcustom org-table-formula-constants nil
940 "Alist with constant names and values, for use in table formulas.
941 The car of each element is a name of a constant, without the `$' before it.
942 The cdr is the value as a string. For example, if you'd like to use the
943 speed of light in a formula, you would configure
945 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
947 and then use it in an equation like `$1*$c'.
949 Constants can also be defined on a per-file basis using a line like
951 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
952 :group 'org-table-calculation
953 :type '(repeat
954 (cons (string :tag "name")
955 (string :tag "value"))))
957 (defvar org-table-formula-constants-local nil
958 "Local version of `org-table-formula-constants'.")
959 (make-variable-buffer-local 'org-table-formula-constants-local)
961 (defcustom org-table-allow-automatic-line-recalculation t
962 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
963 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
964 :group 'org-table-calculation
965 :type 'boolean)
967 (defgroup org-link nil
968 "Options concerning links in Org-mode."
969 :tag "Org Link"
970 :group 'org)
972 (defvar org-link-abbrev-alist-local nil
973 "Buffer-local version of `org-link-abbrev-alist', which see.
974 The value of this is taken from the #+LINK lines.")
975 (make-variable-buffer-local 'org-link-abbrev-alist-local)
977 (defcustom org-link-abbrev-alist nil
978 "Alist of link abbreviations.
979 The car of each element is a string, to be replaced at the start of a link.
980 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
981 links in Org-mode buffers can have an optional tag after a double colon, e.g.
983 [[linkkey:tag][description]]
985 If REPLACE is a string, the tag will simply be appended to create the link.
986 If the string contains \"%s\", the tag will be inserted there. REPLACE may
987 also be a function that will be called with the tag as the only argument to
988 create the link. See the manual for examples."
989 :group 'org-link
990 :type 'alist)
992 (defcustom org-descriptive-links t
993 "Non-nil means, hide link part and only show description of bracket links.
994 Bracket links are like [[link][descritpion]]. This variable sets the initial
995 state in new org-mode buffers. The setting can then be toggled on a
996 per-buffer basis from the Org->Hyperlinks menu."
997 :group 'org-link
998 :type 'boolean)
1000 (defcustom org-link-file-path-type 'adaptive
1001 "How the path name in file links should be stored.
1002 Valid values are:
1004 relative relative to the current directory, i.e. the directory of the file
1005 into which the link is being inserted.
1006 absolute absolute path, if possible with ~ for home directory.
1007 noabbrev absolute path, no abbreviation of home directory.
1008 adaptive Use relative path for files in the current directory and sub-
1009 directories of it. For other files, use an absolute path."
1010 :group 'org-link
1011 :type '(choice
1012 (const relative)
1013 (const absolute)
1014 (const noabbrev)
1015 (const adaptive)))
1017 (defcustom org-activate-links '(bracket angle plain radio tag date)
1018 "Types of links that should be activated in Org-mode files.
1019 This is a list of symbols, each leading to the activation of a certain link
1020 type. In principle, it does not hurt to turn on most link types - there may
1021 be a small gain when turning off unused link types. The types are:
1023 bracket The recommended [[link][description]] or [[link]] links with hiding.
1024 angular Links in angular brackes that may contain whitespace like
1025 <bbdb:Carsten Dominik>.
1026 plain Plain links in normal text, no whitespace, like http://google.com.
1027 radio Text that is matched by a radio target, see manual for details.
1028 tag Tag settings in a headline (link to tag search).
1029 date Time stamps (link to calendar).
1031 Changing this variable requires a restart of Emacs to become effective."
1032 :group 'org-link
1033 :type '(set (const :tag "Double bracket links (new style)" bracket)
1034 (const :tag "Angular bracket links (old style)" angular)
1035 (const :tag "plain text links" plain)
1036 (const :tag "Radio target matches" radio)
1037 (const :tag "Tags" tag)
1038 (const :tag "Tags" target)
1039 (const :tag "Timestamps" date)))
1041 (defgroup org-link-store nil
1042 "Options concerning storing links in Org-mode"
1043 :tag "Org Store Link"
1044 :group 'org-link)
1046 (defcustom org-email-link-description-format "Email %c: %.30s"
1047 "Format of the description part of a link to an email or usenet message.
1048 The following %-excapes will be replaced by corresponding information:
1050 %F full \"From\" field
1051 %f name, taken from \"From\" field, address if no name
1052 %T full \"To\" field
1053 %t first name in \"To\" field, address if no name
1054 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1055 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1056 %s subject
1057 %m message-id.
1059 You may use normal field width specification between the % and the letter.
1060 This is for example useful to limit the length of the subject.
1062 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1063 :group 'org-link-store
1064 :type 'string)
1066 (defcustom org-from-is-user-regexp
1067 (let (r1 r2)
1068 (when (and user-mail-address (not (string= user-mail-address "")))
1069 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1070 (when (and user-full-name (not (string= user-full-name "")))
1071 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1072 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1073 "Regexp mached against the \"From:\" header of an email or usenet message.
1074 It should match if the message is from the user him/herself."
1075 :group 'org-link-store
1076 :type 'regexp)
1078 (defcustom org-context-in-file-links t
1079 "Non-nil means, file links from `org-store-link' contain context.
1080 A search string will be added to the file name with :: as separator and
1081 used to find the context when the link is activated by the command
1082 `org-open-at-point'.
1083 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1084 negates this setting for the duration of the command."
1085 :group 'org-link-store
1086 :type 'boolean)
1088 (defcustom org-keep-stored-link-after-insertion nil
1089 "Non-nil means, keep link in list for entire session.
1091 The command `org-store-link' adds a link pointing to the current
1092 location to an internal list. These links accumulate during a session.
1093 The command `org-insert-link' can be used to insert links into any
1094 Org-mode file (offering completion for all stored links). When this
1095 option is nil, every link which has been inserted once using \\[org-insert-link]
1096 will be removed from the list, to make completing the unused links
1097 more efficient."
1098 :group 'org-link-store
1099 :type 'boolean)
1101 (defcustom org-usenet-links-prefer-google nil
1102 "Non-nil means, `org-store-link' will create web links to Google groups.
1103 When nil, Gnus will be used for such links.
1104 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1105 negates this setting for the duration of the command."
1106 :group 'org-link-store
1107 :type 'boolean)
1109 (defgroup org-link-follow nil
1110 "Options concerning following links in Org-mode"
1111 :tag "Org Follow Link"
1112 :group 'org-link)
1114 (defcustom org-tab-follows-link nil
1115 "Non-nil means, on links TAB will follow the link.
1116 Needs to be set before org.el is loaded."
1117 :group 'org-link-follow
1118 :type 'boolean)
1120 (defcustom org-return-follows-link nil
1121 "Non-nil means, on links RET will follow the link.
1122 Needs to be set before org.el is loaded."
1123 :group 'org-link-follow
1124 :type 'boolean)
1126 (defcustom org-mouse-1-follows-link t
1127 "Non-nil means, mouse-1 on a link will follow the link.
1128 A longer mouse click will still set point. Does not wortk on XEmacs.
1129 Needs to be set before org.el is loaded."
1130 :group 'org-link-follow
1131 :type 'boolean)
1133 (defcustom org-mark-ring-length 4
1134 "Number of different positions to be recorded in the ring
1135 Changing this requires a restart of Emacs to work correctly."
1136 :group 'org-link-follow
1137 :type 'interger)
1139 (defcustom org-link-frame-setup
1140 '((vm . vm-visit-folder-other-frame)
1141 (gnus . gnus-other-frame)
1142 (file . find-file-other-window))
1143 "Setup the frame configuration for following links.
1144 When following a link with Emacs, it may often be useful to display
1145 this link in another window or frame. This variable can be used to
1146 set this up for the different types of links.
1147 For VM, use any of
1148 `vm-visit-folder'
1149 `vm-visit-folder-other-frame'
1150 For Gnus, use any of
1151 `gnus'
1152 `gnus-other-frame'
1153 For FILE, use any of
1154 `find-file'
1155 `find-file-other-window'
1156 `find-file-other-frame'
1157 For the calendar, use the variable `calendar-setup'.
1158 For BBDB, it is currently only possible to display the matches in
1159 another window."
1160 :group 'org-link-follow
1161 :type '(list
1162 (cons (const vm)
1163 (choice
1164 (const vm-visit-folder)
1165 (const vm-visit-folder-other-window)
1166 (const vm-visit-folder-other-frame)))
1167 (cons (const gnus)
1168 (choice
1169 (const gnus)
1170 (const gnus-other-frame)))
1171 (cons (const file)
1172 (choice
1173 (const find-file)
1174 (const find-file-other-window)
1175 (const find-file-other-frame)))))
1177 (defcustom org-display-internal-link-with-indirect-buffer nil
1178 "Non-nil means, use indirect buffer to display infile links.
1179 Activating internal links (from one location in a file to another location
1180 in the same file) normally just jumps to the location. When the link is
1181 activated with a C-u prefix (or with mouse-3), the link is displayed in
1182 another window. When this option is set, the other window actually displays
1183 an indirect buffer clone of the current buffer, to avoid any visibility
1184 changes to the current buffer."
1185 :group 'org-link-follow
1186 :type 'boolean)
1188 (defcustom org-open-non-existing-files nil
1189 "Non-nil means, `org-open-file' will open non-existing files.
1190 When nil, an error will be generated."
1191 :group 'org-link-follow
1192 :type 'boolean)
1194 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1195 "Function and arguments to call for following mailto links.
1196 This is a list with the first element being a lisp function, and the
1197 remaining elements being arguments to the function. In string arguments,
1198 %a will be replaced by the address, and %s will be replaced by the subject
1199 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1200 :group 'org-link-follow
1201 :type '(choice
1202 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1203 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1204 (const :tag "message-mail" (message-mail "%a" "%s"))
1205 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1207 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1208 "Non-nil means, ask for confirmation before executing shell links.
1209 Shell links can be dangerous, just thing about a link
1211 [[shell:rm -rf ~/*][Google Search]]
1213 This link would show up in your Org-mode document as \"Google Search\"
1214 but really it would remove your entire home directory.
1215 Therefore I *definitely* advise against setting this variable to nil.
1216 Just change it to `y-or-n-p' of you want to confirm with a single key press
1217 rather than having to type \"yes\"."
1218 :group 'org-link-follow
1219 :type '(choice
1220 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1221 (const :tag "with y-or-n (faster)" y-or-n-p)
1222 (const :tag "no confirmation (dangerous)" nil)))
1224 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1225 "Non-nil means, ask for confirmation before executing elisp links.
1226 Elisp links can be dangerous, just think about a link
1228 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1230 This link would show up in your Org-mode document as \"Google Search\"
1231 but really it would remove your entire home directory.
1232 Therefore I *definitely* advise against setting this variable to nil.
1233 Just change it to `y-or-n-p' of you want to confirm with a single key press
1234 rather than having to type \"yes\"."
1235 :group 'org-link-follow
1236 :type '(choice
1237 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1238 (const :tag "with y-or-n (faster)" y-or-n-p)
1239 (const :tag "no confirmation (dangerous)" nil)))
1241 (defconst org-file-apps-defaults-gnu
1242 '((remote . emacs)
1243 (t . mailcap))
1244 "Default file applications on a UNIX or GNU/Linux system.
1245 See `org-file-apps'.")
1247 (defconst org-file-apps-defaults-macosx
1248 '((remote . emacs)
1249 (t . "open %s")
1250 ("ps" . "gv %s")
1251 ("ps.gz" . "gv %s")
1252 ("eps" . "gv %s")
1253 ("eps.gz" . "gv %s")
1254 ("dvi" . "xdvi %s")
1255 ("fig" . "xfig %s"))
1256 "Default file applications on a MacOS X system.
1257 The system \"open\" is known as a default, but we use X11 applications
1258 for some files for which the OS does not have a good default.
1259 See `org-file-apps'.")
1261 (defconst org-file-apps-defaults-windowsnt
1262 (list
1263 '(remote . emacs)
1264 (cons t
1265 (list (if (featurep 'xemacs)
1266 'mswindows-shell-execute
1267 'w32-shell-execute)
1268 "open" 'file)))
1269 "Default file applications on a Windows NT system.
1270 The system \"open\" is used for most files.
1271 See `org-file-apps'.")
1273 (defcustom org-file-apps
1275 ("txt" . emacs)
1276 ("tex" . emacs)
1277 ("ltx" . emacs)
1278 ("org" . emacs)
1279 ("el" . emacs)
1280 ("bib" . emacs)
1282 "External applications for opening `file:path' items in a document.
1283 Org-mode uses system defaults for different file types, but
1284 you can use this variable to set the application for a given file
1285 extension. The entries in this list are cons cells where the car identifies
1286 files and the cdr the corresponding command. Possible values for the
1287 file identifier are
1288 \"ext\" A string identifying an extension
1289 `directory' Matches a directory
1290 `remote' Matches a remote file, accessible through tramp or efs.
1291 Remote files most likely should be visited through Emacs
1292 because external applications cannot handle such paths.
1293 t Default for all remaining files
1295 Possible values for the command are:
1296 `emacs' The file will be visited by the current Emacs process.
1297 `default' Use the default application for this file type.
1298 string A command to be executed by a shell; %s will be replaced
1299 by the path to the file.
1300 sexp A Lisp form which will be evaluated. The file path will
1301 be available in the Lisp variable `file'.
1302 For more examples, see the system specific constants
1303 `org-file-apps-defaults-macosx'
1304 `org-file-apps-defaults-windowsnt'
1305 `org-file-apps-defaults-gnu'."
1306 :group 'org-link-follow
1307 :type '(repeat
1308 (cons (choice :value ""
1309 (string :tag "Extension")
1310 (const :tag "Default for unrecognized files" t)
1311 (const :tag "Remote file" remote)
1312 (const :tag "Links to a directory" directory))
1313 (choice :value ""
1314 (const :tag "Visit with Emacs" emacs)
1315 (const :tag "Use system default" default)
1316 (string :tag "Command")
1317 (sexp :tag "Lisp form")))))
1319 (defcustom org-mhe-search-all-folders nil
1320 "Non-nil means, that the search for the mh-message will be extended to
1321 all folders if the message cannot be found in the folder given in the link.
1322 Searching all folders is very efficient with one of the search engines
1323 supported by MH-E, but will be slow with pick."
1324 :group 'org-link-follow
1325 :type 'boolean)
1327 (defgroup org-remember nil
1328 "Options concerning interaction with remember.el."
1329 :tag "Org Remember"
1330 :group 'org)
1332 (defcustom org-directory "~/org"
1333 "Directory with org files.
1334 This directory will be used as default to prompt for org files.
1335 Used by the hooks for remember.el."
1336 :group 'org-remember
1337 :type 'directory)
1339 (defcustom org-default-notes-file "~/.notes"
1340 "Default target for storing notes.
1341 Used by the hooks for remember.el. This can be a string, or nil to mean
1342 the value of `remember-data-file'.
1343 You can set this on a per-template basis with the variable
1344 `org-remember-templates'."
1345 :group 'org-remember
1346 :type '(choice
1347 (const :tag "Default from remember-data-file" nil)
1348 file))
1350 (defcustom org-remember-store-without-prompt nil
1351 "Non-nil means, `C-c C-c' stores remember note without further promts.
1352 In this case, you need `C-u C-c C-c' to get the prompts for
1353 note file and headline.
1354 When this variable is nil, `C-c C-c' give you the prompts, and
1355 `C-u C-c C-c' trigger the fasttrack."
1356 :group 'org-remember
1357 :type 'boolean)
1359 (defcustom org-remember-default-headline ""
1360 "The headline that should be the default location in the notes file.
1361 When filing remember notes, the cursor will start at that position.
1362 You can set this on a per-template basis with the variable
1363 `org-remember-templates'."
1364 :group 'org-remember
1365 :type 'string)
1367 (defcustom org-remember-templates nil
1368 "Templates for the creation of remember buffers.
1369 When nil, just let remember make the buffer.
1370 When not nil, this is a list of 4-element lists. In each entry, the first
1371 element is a character, a unique key to select this template.
1372 The second element is the template. The third element is optional and can
1373 specify a destination file for remember items created with this template.
1374 The default file is given by `org-default-notes-file'. An optional forth
1375 element can specify the headline in that file that should be offered
1376 first when the user is asked to file the entry. The default headline is
1377 given in the variable `org-remember-default-headline'.
1379 The template specifies the structure of the remember buffer. It should have
1380 a first line starting with a star, to act as the org-mode headline.
1381 Furthermore, the following %-escapes will be replaced with content:
1383 %^{prompt} prompt the user for a string and replace this sequence with it.
1384 %t time stamp, date only
1385 %T time stamp with date and time
1386 %u, %U like the above, but inactive time stamps
1387 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1388 You may define a prompt like %^{Please specify birthday}t
1389 %n user name (taken from `user-full-name')
1390 %a annotation, normally the link created with org-store-link
1391 %i initial content, the region when remember is called with C-u.
1392 If %i is indented, the entire inserted text will be indented
1393 as well.
1395 %? After completing the template, position cursor here.
1397 Apart from these general escapes, you can access information specific to the
1398 link type that is created. For example, calling `remember' in emails or gnus
1399 will record the author and the subject of the message, which you can access
1400 with %:author and %:subject, respectively. Here is a complete list of what
1401 is recorded for each link type.
1403 Link type | Available information
1404 -------------------+------------------------------------------------------
1405 bbdb | %:type %:name %:company
1406 vm, wl, mh, rmail | %:type %:subject %:message-id
1407 | %:from %:fromname %:fromaddress
1408 | %:to %:toname %:toaddress
1409 | %:fromto (either \"to NAME\" or \"from NAME\")
1410 gnus | %:group, for messages also all email fields
1411 w3, w3m | %:type %:url
1412 info | %:type %:file %:node
1413 calendar | %:type %:date"
1414 :group 'org-remember
1415 :get (lambda (var) ; Make sure all entries have 4 elements
1416 (mapcar (lambda (x)
1417 (cond ((= (length x) 3) (append x '("")))
1418 ((= (length x) 2) (append x '("" "")))
1419 (t x)))
1420 (default-value var)))
1421 :type '(repeat
1422 :tag "enabled"
1423 (list :value (?a "\n" nil nil)
1424 (character :tag "Selection Key")
1425 (string :tag "Template")
1426 (file :tag "Destination file (optional)")
1427 (string :tag "Destination headline (optional)"))))
1429 (defcustom org-reverse-note-order nil
1430 "Non-nil means, store new notes at the beginning of a file or entry.
1431 When nil, new notes will be filed to the end of a file or entry."
1432 :group 'org-remember
1433 :type '(choice
1434 (const :tag "Reverse always" t)
1435 (const :tag "Reverse never" nil)
1436 (repeat :tag "By file name regexp"
1437 (cons regexp boolean))))
1439 (defgroup org-todo nil
1440 "Options concerning TODO items in Org-mode."
1441 :tag "Org TODO"
1442 :group 'org)
1444 (defgroup org-progress nil
1445 "Options concerning Progress logging in Org-mode."
1446 :tag "Org Progress"
1447 :group 'org-time)
1449 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1450 "List of TODO entry keyword sequences and their interpretation.
1451 \\<org-mode-map>This is a list of sequences.
1453 Each sequence starts with a symbol, either `sequence' or `type',
1454 indicating if the keywords should be interpreted as a sequence of
1455 action steps, or as different types of TODO items. The first
1456 keywords are states requiring action - these states will select a headline
1457 for inclusion into the global TODO list Org-mode produces. If one of
1458 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1459 signify that no further action is necessary. If \"|\" is not found,
1460 the last keyword is treated as the only DONE state of the sequence.
1462 The command \\[org-todo] cycles an entry through these states, and one
1463 additional state where no keyword is present. For details about this
1464 cycling, see the manual.
1466 TODO keywords and interpretation can also be set on a per-file basis with
1467 the special #+SEQ_TODO and #+TYP_TODO lines.
1469 For backward compatibility, this variable may also be just a list
1470 of keywords - in this case the interptetation (sequence or type) will be
1471 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1472 :group 'org-todo
1473 :group 'org-keywords
1474 :type '(choice
1475 (repeat :tag "Old syntax, just keywords"
1476 (string :tag "Keyword"))
1477 (repeat :tag "New syntax"
1478 (cons
1479 (choice
1480 :tag "Interpretation"
1481 (const :tag "Sequence (cycling hits every state)" sequence)
1482 (const :tag "Type (cycling directly to DONE)" type))
1483 (repeat
1484 (string :tag "Keyword"))))))
1486 (defvar org-todo-keywords-1 nil)
1487 (make-variable-buffer-local 'org-todo-keywords-1)
1488 (defvar org-todo-keywords-for-agenda nil)
1489 (defvar org-done-keywords-for-agenda nil)
1490 (defvar org-not-done-keywords nil)
1491 (make-variable-buffer-local 'org-not-done-keywords)
1492 (defvar org-done-keywords nil)
1493 (make-variable-buffer-local 'org-done-keywords)
1494 (defvar org-todo-heads nil)
1495 (make-variable-buffer-local 'org-todo-heads)
1496 (defvar org-todo-sets nil)
1497 (make-variable-buffer-local 'org-todo-sets)
1498 (defvar org-todo-kwd-alist nil)
1499 (make-variable-buffer-local 'org-todo-kwd-alist)
1501 (defcustom org-todo-interpretation 'sequence
1502 "Controls how TODO keywords are interpreted.
1503 This variable is in principle obsolete and is only used for
1504 backward compatibility, if the interpretation of todo keywords is
1505 not given already in `org-todo-keywords'. See that variable for
1506 more information."
1507 :group 'org-todo
1508 :group 'org-keywords
1509 :type '(choice (const sequence)
1510 (const type)))
1512 (defcustom org-after-todo-state-change-hook nil
1513 "Hook which is run after the state of a TODO item was changed.
1514 The new state (a string with a TODO keyword, or nil) is available in the
1515 Lisp variable `state'."
1516 :group 'org-todo
1517 :type 'hook)
1519 (defcustom org-log-done nil
1520 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1521 When the state of an entry is changed from nothing to TODO, remove a previous
1522 closing date.
1524 This can also be a list of symbols indicating under which conditions
1525 the time stamp recording the action should be annotated with a short note.
1526 Valid members of this list are
1528 done Offer to record a note when marking entries done
1529 state Offer to record a note whenever changing the TODO state
1530 of an item. This is only relevant if TODO keywords are
1531 interpreted as sequence, see variable `org-todo-interpretation'.
1532 When `state' is set, this includes tracking `done'.
1533 clock-out Offer to record a note when clocking out of an item.
1535 A separate window will then pop up and allow you to type a note.
1536 After finishing with C-c C-c, the note will be added directly after the
1537 timestamp, as a plain list item. See also the variable
1538 `org-log-note-headings'.
1540 Logging can also be configured on a per-file basis by adding one of
1541 the following lines anywhere in the buffer:
1543 #+STARTUP: logdone
1544 #+STARTUP: nologging
1545 #+STARTUP: lognotedone
1546 #+STARTUP: lognotestate
1547 #+STARTUP: lognoteclock-out"
1548 :group 'org-todo
1549 :group 'org-progress
1550 :type '(choice
1551 (const :tag "off" nil)
1552 (const :tag "on" t)
1553 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1554 (const :tag "when item is marked DONE" done)
1555 (const :tag "when TODO state changes" state)
1556 (const :tag "when clocking out" clock-out))))
1558 (defcustom org-log-done-with-time t
1559 "Non-nil means, the CLOSED time stamp will contain date and time.
1560 When nil, only the date will be recorded."
1561 :group 'org-progress
1562 :type 'boolean)
1564 (defcustom org-log-note-headings
1565 '((done . "CLOSING NOTE %t")
1566 (state . "State %-12s %t")
1567 (clock-out . ""))
1568 "Headings for notes added when clocking out or closing TODO items.
1569 The value is an alist, with the car being a symbol indicating the note
1570 context, and the cdr is the heading to be used. The heading may also be the
1571 empty string.
1572 %t in the heading will be replaced by a time stamp.
1573 %s will be replaced by the new TODO state, in double quotes.
1574 %u will be replaced by the user name.
1575 %U will be replaced by the full user name."
1576 :group 'org-todo
1577 :group 'org-progress
1578 :type '(list :greedy t
1579 (cons (const :tag "Heading when closing an item" done) string)
1580 (cons (const :tag
1581 "Heading when changing todo state (todo sequence only)"
1582 state) string)
1583 (cons (const :tag "Heading when clocking out" clock-out) string)))
1585 (defcustom org-log-states-order-reversed t
1586 "Non-nil means, the latest state change note will be directly after heading.
1587 When nil, the notes will be orderer according to time."
1588 :group 'org-todo
1589 :group 'org-progress
1590 :type 'boolean)
1592 (defcustom org-log-repeat t
1593 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1594 When nil, no note will be taken."
1595 :group 'org-todo
1596 :group 'org-progress
1597 :type 'boolean)
1599 (defcustom org-clock-out-when-done t
1600 "When t, the clock will be stopped when the relevant entry is marked DONE.
1601 Nil means, clock will keep running until stopped explicitly with
1602 `C-c C-x C-o', or until the clock is started in a different item."
1603 :group 'org-progress
1604 :type 'boolean)
1606 (defgroup org-priorities nil
1607 "Priorities in Org-mode."
1608 :tag "Org Priorities"
1609 :group 'org-todo)
1611 (defcustom org-highest-priority ?A
1612 "The highest priority of TODO items. A character like ?A, ?B etc.
1613 Must have a smaller ASCII number than `org-lowest-priority'."
1614 :group 'org-priorities
1615 :type 'character)
1617 (defcustom org-lowest-priority ?C
1618 "The lowest priority of TODO items. A character like ?A, ?B etc.
1619 Must have a larger ASCII number than `org-highest-priority'."
1620 :group 'org-priorities
1621 :type 'character)
1623 (defcustom org-default-priority ?B
1624 "The default priority of TODO items.
1625 This is the priority an item get if no explicit priority is given."
1626 :group 'org-priorities
1627 :type 'character)
1629 (defgroup org-time nil
1630 "Options concerning time stamps and deadlines in Org-mode."
1631 :tag "Org Time"
1632 :group 'org)
1634 (defcustom org-insert-labeled-timestamps-at-point nil
1635 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1636 When nil, these labeled time stamps are forces into the second line of an
1637 entry, just after the headline. When scheduling from the global TODO list,
1638 the time stamp will always be forced into the second line."
1639 :group 'org-time
1640 :type 'boolean)
1642 (defcustom org-insert-labeled-timestamps-before-properties-drawer t
1643 "Non-nil means, always insert planning info before property drawer.
1644 When this is nil and there is a property drawer *directly* after
1645 the headline, move the planning info into the drawer. If the property
1646 drawer separated from the headline by at least one line, this variable
1647 has no effect."
1648 :group 'org-time
1649 :type 'boolean)
1651 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1652 "Formats for `format-time-string' which are used for time stamps.
1653 It is not recommended to change this constant.")
1655 (defcustom org-time-stamp-rounding-minutes 0
1656 "Number of minutes to round time stamps to upon insertion.
1657 When zero, insert the time unmodified. Useful rounding numbers
1658 should be factors of 60, so for example 5, 10, 15.
1659 When this is not zero, you can still force an exact time-stamp by using
1660 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1661 :group 'org-time
1662 :type 'integer)
1664 (defcustom org-display-custom-times nil
1665 "Non-nil means, overlay custom formats over all time stamps.
1666 The formats are defined through the variable `org-time-stamp-custom-formats'.
1667 To turn this on on a per-file basis, insert anywhere in the file:
1668 #+STARTUP: customtime"
1669 :group 'org-time
1670 :set 'set-default
1671 :type 'sexp)
1672 (make-variable-buffer-local 'org-display-custom-times)
1674 (defcustom org-time-stamp-custom-formats
1675 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1676 "Custom formats for time stamps. See `format-time-string' for the syntax.
1677 These are overlayed over the default ISO format if the variable
1678 `org-display-custom-times' is set. Time like %H:%M should be at the
1679 end of the second format."
1680 :group 'org-time
1681 :type 'sexp)
1683 (defun org-time-stamp-format (&optional long inactive)
1684 "Get the right format for a time string."
1685 (let ((f (if long (cdr org-time-stamp-formats)
1686 (car org-time-stamp-formats))))
1687 (if inactive
1688 (concat "[" (substring f 1 -1) "]")
1689 f)))
1691 (defcustom org-deadline-warning-days 30
1692 "No. of days before expiration during which a deadline becomes active.
1693 This variable governs the display in sparse trees and in the agenda."
1694 :group 'org-time
1695 :type 'number)
1697 (defcustom org-popup-calendar-for-date-prompt t
1698 "Non-nil means, pop up a calendar when prompting for a date.
1699 In the calendar, the date can be selected with mouse-1. However, the
1700 minibuffer will also be active, and you can simply enter the date as well.
1701 When nil, only the minibuffer will be available."
1702 :group 'org-time
1703 :type 'boolean)
1705 (defcustom org-calendar-follow-timestamp-change t
1706 "Non-nil means, make the calendar window follow timestamp changes.
1707 When a timestamp is modified and the calendar window is visible, it will be
1708 moved to the new date."
1709 :group 'org-time
1710 :type 'boolean)
1712 (defgroup org-tags nil
1713 "Options concerning tags in Org-mode."
1714 :tag "Org Tags"
1715 :group 'org)
1717 (defcustom org-tag-alist nil
1718 "List of tags allowed in Org-mode files.
1719 When this list is nil, Org-mode will base TAG input on what is already in the
1720 buffer.
1721 The value of this variable is an alist, the car may be (and should) be a
1722 character that is used to select that tag through the fast-tag-selection
1723 interface. See the manual for details."
1724 :group 'org-tags
1725 :type '(repeat
1726 (choice
1727 (cons (string :tag "Tag name")
1728 (character :tag "Access char"))
1729 (const :tag "Start radio group" (:startgroup))
1730 (const :tag "End radio group" (:endgroup)))))
1732 (defcustom org-use-fast-tag-selection 'auto
1733 "Non-nil means, use fast tag selection scheme.
1734 This is a special interface to select and deselect tags with single keys.
1735 When nil, fast selection is never used.
1736 When the symbol `auto', fast selection is used if and only if selection
1737 characters for tags have been configured, either through the variable
1738 `org-tag-alist' or through a #+TAGS line in the buffer.
1739 When t, fast selection is always used and selection keys are assigned
1740 automatically if necessary."
1741 :group 'org-tags
1742 :type '(choice
1743 (const :tag "Always" t)
1744 (const :tag "Never" nil)
1745 (const :tag "When selection characters are configured" 'auto)))
1747 (defcustom org-fast-tag-selection-single-key nil
1748 "Non-nil means, fast tag selection exits after first change.
1749 When nil, you have to press RET to exit it.
1750 During fast tag selection, you can toggle this flag with `C-c'.
1751 This variable can also have the value `expert'. In this case, the window
1752 displaying the tags menu is not even shown, until you press C-c again."
1753 :group 'org-tags
1754 :type '(choice
1755 (const :tag "No" nil)
1756 (const :tag "Yes" t)
1757 (const :tag "Expert" expert)))
1759 (defcustom org-tags-column 48
1760 "The column to which tags should be indented in a headline.
1761 If this number is positive, it specifies the column. If it is negative,
1762 it means that the tags should be flushright to that column. For example,
1763 -79 works well for a normal 80 character screen."
1764 :group 'org-tags
1765 :type 'integer)
1767 (defcustom org-auto-align-tags t
1768 "Non-nil means, realign tags after pro/demotion of TODO state change.
1769 These operations change the length of a headline and therefore shift
1770 the tags around. With this options turned on, after each such operation
1771 the tags are again aligned to `org-tags-column'."
1772 :group 'org-tags
1773 :type 'boolean)
1775 (defcustom org-use-tag-inheritance t
1776 "Non-nil means, tags in levels apply also for sublevels.
1777 When nil, only the tags directly given in a specific line apply there.
1778 If you turn off this option, you very likely want to turn on the
1779 companion option `org-tags-match-list-sublevels'."
1780 :group 'org-tags
1781 :type 'boolean)
1783 (defcustom org-tags-match-list-sublevels nil
1784 "Non-nil means list also sublevels of headlines matching tag search.
1785 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1786 the sublevels of a headline matching a tag search often also match
1787 the same search. Listing all of them can create very long lists.
1788 Setting this variable to nil causes subtrees of a match to be skipped.
1789 This option is off by default, because inheritance in on. If you turn
1790 inheritance off, you very likely want to turn this option on.
1792 As a special case, if the tag search is restricted to TODO items, the
1793 value of this variable is ignored and sublevels are always checked, to
1794 make sure all corresponding TODO items find their way into the list."
1795 :group 'org-tags
1796 :type 'boolean)
1798 (defvar org-tags-history nil
1799 "History of minibuffer reads for tags.")
1800 (defvar org-last-tags-completion-table nil
1801 "The last used completion table for tags.")
1803 (defgroup org-properties nil
1804 "Options concerning properties in Org-mode."
1805 :tag "Org Properties"
1806 :group 'org)
1808 (defcustom org-property-format "%-10s %s"
1809 "How property key/value pairs should be formatted by `indent-line'.
1810 When `indent-line' hits a property definition, it will format the line
1811 according to this format, mainly to make sure that the values are
1812 lined-up with respect to each other."
1813 :group 'org-properties
1814 :type 'string)
1816 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1817 "The default column format, if no other format has been defined.
1818 This variable can be set on the per-file basis by inserting a line
1820 #+COLUMNS: %25ITEM ....."
1821 :group 'org-properties
1822 :type 'string)
1824 (defcustom org-global-properties nil
1825 "List of property/value pairs that can be inherited by any entry.
1826 You can set buffer-local values for this by adding lines like
1828 #+PROPERTY: NAME VALUE"
1829 :group 'org-properties
1830 :type '(repeat
1831 (cons (string :tag "Property")
1832 (string :tag "Value"))))
1834 (defvar org-local-properties nil
1835 "List of property/value pairs that can be inherited by any entry.
1836 Valid for the current buffer.
1837 This variable is populated from #+PROPERTY lines.")
1839 (defgroup org-agenda nil
1840 "Options concerning agenda views in Org-mode."
1841 :tag "Org Agenda"
1842 :group 'org)
1844 (defvar org-category nil
1845 "Variable used by org files to set a category for agenda display.
1846 Such files should use a file variable to set it, for example
1848 # -*- mode: org; org-category: \"ELisp\"
1850 or contain a special line
1852 #+CATEGORY: ELisp
1854 If the file does not specify a category, then file's base name
1855 is used instead.")
1856 (make-variable-buffer-local 'org-category)
1858 (defcustom org-agenda-files nil
1859 "The files to be used for agenda display.
1860 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1861 \\[org-remove-file]. You can also use customize to edit the list.
1863 If the value of the variable is not a list but a single file name, then
1864 the list of agenda files is actually stored and maintained in that file, one
1865 agenda file per line."
1866 :group 'org-agenda
1867 :type '(choice
1868 (repeat :tag "List of files" file)
1869 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1872 (defcustom org-agenda-confirm-kill 1
1873 "When set, remote killing from the agenda buffer needs confirmation.
1874 When t, a confirmation is always needed. When a number N, confirmation is
1875 only needed when the text to be killed contains more than N non-white lines."
1876 :group 'org-agenda
1877 :type '(choice
1878 (const :tag "Never" nil)
1879 (const :tag "Always" t)
1880 (number :tag "When more than N lines")))
1882 (defcustom org-calendar-to-agenda-key [?c]
1883 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1884 The command `org-calendar-goto-agenda' will be bound to this key. The
1885 default is the character `c' because then `c' can be used to switch back and
1886 forth between agenda and calendar."
1887 :group 'org-agenda
1888 :type 'sexp)
1890 (defgroup org-agenda-export nil
1891 "Options concerning exporting agenda views in Org-mode."
1892 :tag "Org Agenda Export"
1893 :group 'org-agenda)
1895 (defcustom org-agenda-with-colors t
1896 "Non-nil means, use colors in agenda views."
1897 :group 'org-agenda-export
1898 :type 'boolean)
1900 (defcustom org-agenda-exporter-settings nil
1901 "Alist of variable/value pairs that should be active during agenda export.
1902 This is a good place to set uptions for ps-print and for htmlize."
1903 :group 'org-agenda-export
1904 :type '(repeat
1905 (list
1906 (variable)
1907 (sexp :tag "Value"))))
1909 (defcustom org-agenda-export-html-style ""
1910 "The style specification for exported HTML Agenda files.
1911 If this variable contains a string, it will replace the default <style>
1912 section as produced by `htmlize'.
1913 Since there are different ways of setting style information, this variable
1914 needs to contain the full HTML structure to provide a style, including the
1915 surrounding HTML tags. The style specifications should include definitions
1916 the fonts used by the agenda, here is an example:
1918 <style type=\"text/css\">
1919 p { font-weight: normal; color: gray; }
1920 .org-agenda-structure {
1921 font-size: 110%;
1922 color: #003399;
1923 font-weight: 600;
1925 .org-todo {
1926 color: #cc6666;Week-agenda:
1927 font-weight: bold;
1929 .org-done {
1930 color: #339933;
1932 .title { text-align: center; }
1933 .todo, .deadline { color: red; }
1934 .done { color: green; }
1935 </style>
1937 or, if you want to keep the style in a file,
1939 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1941 As the value of this option simply gets inserted into the HTML <head> header,
1942 you can \"misuse\" it to also add other text to the header. However,
1943 <style>...</style> is required, if not present the variable will be ignored."
1944 :group 'org-agenda-export
1945 :group 'org-export-html
1946 :type 'string)
1948 (defgroup org-agenda-custom-commands nil
1949 "Options concerning agenda views in Org-mode."
1950 :tag "Org Agenda Custom Commands"
1951 :group 'org-agenda)
1953 (defcustom org-agenda-custom-commands nil
1954 "Custom commands for the agenda.
1955 These commands will be offered on the splash screen displayed by the
1956 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1958 (key type match options files)
1960 key The key (a single char as a string) to be associated with the command.
1961 type The command type, any of the following symbols:
1962 todo Entries with a specific TODO keyword, in all agenda files.
1963 tags Tags match in all agenda files.
1964 tags-todo Tags match in all agenda files, TODO entries only.
1965 todo-tree Sparse tree of specific TODO keyword in *current* file.
1966 tags-tree Sparse tree with all tags matches in *current* file.
1967 occur-tree Occur sparse tree for *current* file.
1968 match What to search for:
1969 - a single keyword for TODO keyword searches
1970 - a tags match expression for tags searches
1971 - a regular expression for occur searches
1972 options A list of option settings, similar to that in a let form, so like
1973 this: ((opt1 val1) (opt2 val2) ...)
1974 files A list of files file to write the produced agenda buffer to
1975 with the command `org-store-agenda-views'.
1976 If a file name ends in \".html\", an HTML version of the buffer
1977 is written out. If it ends in \".ps\", a postscript version is
1978 produced. Otherwide, only the plain text is written to the file.
1980 You can also define a set of commands, to create a composite agenda buffer.
1981 In this case, an entry looks like this:
1983 (key desc (cmd1 cmd2 ...) general-options file)
1985 where
1987 desc A description string to be displayed in the dispatcher menu.
1988 cmd An agenda command, similar to the above. However, tree commands
1989 are no allowed, but instead you can get agenda and global todo list.
1990 So valid commands for a set are:
1991 (agenda)
1992 (alltodo)
1993 (stuck)
1994 (todo \"match\" options files)
1995 (tags \"match\" options files)
1996 (tags-todo \"match\" options files)
1998 Each command can carry a list of options, and another set of options can be
1999 given for the whole set of commands. Individual command options take
2000 precedence over the general options."
2001 :group 'org-agenda-custom-commands
2002 :type '(repeat
2003 (choice :value ("a" tags "" nil)
2004 (list :tag "Single command"
2005 (string :tag "Key")
2006 (choice
2007 (const :tag "Agenda" agenda)
2008 (const :tag "TODO list" alltodo)
2009 (const :tag "Stuck projects" stuck)
2010 (const :tag "Tags search (all agenda files)" tags)
2011 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2012 (const :tag "TODO keyword search (all agenda files)" todo)
2013 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2014 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2015 (const :tag "Occur tree (current buffer)" occur-tree)
2016 (symbol :tag "Other, user-defined function"))
2017 (string :tag "Match")
2018 (repeat :tag "Local options"
2019 (list (variable :tag "Option") (sexp :tag "Value")))
2020 (option (repeat :tag "Export" (file :tag "Export to"))))
2021 (list :tag "Command series, all agenda files"
2022 (string :tag "Key")
2023 (string :tag "Description")
2024 (repeat
2025 (choice
2026 (const :tag "Agenda" (agenda))
2027 (const :tag "TODO list" (alltodo))
2028 (const :tag "Stuck projects" (stuck))
2029 (list :tag "Tags search"
2030 (const :format "" tags)
2031 (string :tag "Match")
2032 (repeat :tag "Local options"
2033 (list (variable :tag "Option")
2034 (sexp :tag "Value"))))
2036 (list :tag "Tags search, TODO entries only"
2037 (const :format "" tags-todo)
2038 (string :tag "Match")
2039 (repeat :tag "Local options"
2040 (list (variable :tag "Option")
2041 (sexp :tag "Value"))))
2043 (list :tag "TODO keyword search"
2044 (const :format "" todo)
2045 (string :tag "Match")
2046 (repeat :tag "Local options"
2047 (list (variable :tag "Option")
2048 (sexp :tag "Value"))))
2050 (list :tag "Other, user-defined function"
2051 (symbol :tag "function")
2052 (string :tag "Match")
2053 (repeat :tag "Local options"
2054 (list (variable :tag "Option")
2055 (sexp :tag "Value"))))))
2057 (repeat :tag "General options"
2058 (list (variable :tag "Option")
2059 (sexp :tag "Value")))
2060 (option (repeat :tag "Export" (file :tag "Export to")))))))
2062 (defcustom org-stuck-projects
2063 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2064 "How to identify stuck projects.
2065 This is a list of four items:
2066 1. A tags/todo matcher string that is used to identify a project.
2067 The entire tree below a headline matched by this is considered one project.
2068 2. A list of TODO keywords identifying non-stuck projects.
2069 If the project subtree contains any headline with one of these todo
2070 keywords, the project is considered to be not stuck. If you specify
2071 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2072 3. A list of tags identifying non-stuck projects.
2073 If the project subtree contains any headline with one of these tags,
2074 the project is considered to be not stuck. If you specify \"*\" as
2075 a tag, any tag will mark the project unstuck.
2076 4. An arbitrary regular expression matching non-stuck projects.
2078 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2079 or `C-c a #' to produce the list."
2080 :group 'org-agenda-custom-commands
2081 :type '(list
2082 (string :tag "Tags/TODO match to identify a project")
2083 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2084 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2085 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2088 (defgroup org-agenda-skip nil
2089 "Options concerning skipping parts of agenda files."
2090 :tag "Org Agenda Skip"
2091 :group 'org-agenda)
2093 (defcustom org-agenda-todo-list-sublevels t
2094 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2095 When nil, the sublevels of a TODO entry are not checked, resulting in
2096 potentially much shorter TODO lists."
2097 :group 'org-agenda-skip
2098 :group 'org-todo
2099 :type 'boolean)
2101 (defcustom org-agenda-todo-ignore-scheduled nil
2102 "Non-nil means, don't show scheduled entries in the global todo list.
2103 The idea behind this is that by scheduling it, you have already taken care
2104 of this item."
2105 :group 'org-agenda-skip
2106 :group 'org-todo
2107 :type 'boolean)
2109 (defcustom org-agenda-todo-ignore-deadlines nil
2110 "Non-nil means, don't show near deadline entries in the global todo list.
2111 Near means closer than `org-deadline-warning-days' days.
2112 The idea behind this is that such items will appear in the agenda anyway."
2113 :group 'org-agenda-skip
2114 :group 'org-todo
2115 :type 'boolean)
2117 (defcustom org-agenda-skip-scheduled-if-done nil
2118 "Non-nil means don't show scheduled items in agenda when they are done.
2119 This is relevant for the daily/weekly agenda, not for the TODO list. And
2120 it applied only to the actualy date of the scheduling. Warnings about
2121 an item with a past scheduling dates are always turned off when the item
2122 is DONE."
2123 :group 'org-agenda-skip
2124 :type 'boolean)
2126 (defcustom org-agenda-skip-deadline-if-done nil
2127 "Non-nil means don't show deadines when the corresponding item is done.
2128 When nil, the deadline is still shown and should give you a happy feeling.
2129 This is relevant for the daily/weekly agenda. And it applied only to the
2130 actualy date of the deadline. Warnings about approching and past-due
2131 deadlines are always turned off when the item is DONE."
2132 :group 'org-agenda-skip
2133 :type 'boolean)
2135 (defcustom org-timeline-show-empty-dates 3
2136 "Non-nil means, `org-timeline' also shows dates without an entry.
2137 When nil, only the days which actually have entries are shown.
2138 When t, all days between the first and the last date are shown.
2139 When an integer, show also empty dates, but if there is a gap of more than
2140 N days, just insert a special line indicating the size of the gap."
2141 :group 'org-agenda-skip
2142 :type '(choice
2143 (const :tag "None" nil)
2144 (const :tag "All" t)
2145 (number :tag "at most")))
2148 (defgroup org-agenda-startup nil
2149 "Options concerning initial settings in the Agenda in Org Mode."
2150 :tag "Org Agenda Startup"
2151 :group 'org-agenda)
2153 (defcustom org-finalize-agenda-hook nil
2154 "Hook run just before displaying an agenda buffer."
2155 :group 'org-agenda-startup
2156 :type 'hook)
2158 (defcustom org-agenda-mouse-1-follows-link nil
2159 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2160 A longer mouse click will still set point. Does not wortk on XEmacs.
2161 Needs to be set before org.el is loaded."
2162 :group 'org-agenda-startup
2163 :type 'boolean)
2165 (defcustom org-agenda-start-with-follow-mode nil
2166 "The initial value of follow-mode in a newly created agenda window."
2167 :group 'org-agenda-startup
2168 :type 'boolean)
2170 (defgroup org-agenda-windows nil
2171 "Options concerning the windows used by the Agenda in Org Mode."
2172 :tag "Org Agenda Windows"
2173 :group 'org-agenda)
2175 (defcustom org-agenda-window-setup 'reorganize-frame
2176 "How the agenda buffer should be displayed.
2177 Possible values for this option are:
2179 current-window Show agenda in the current window, keeping all other windows.
2180 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2181 other-window Use `switch-to-buffer-other-window' to display agenda.
2182 reorganize-frame Show only two windows on the current frame, the current
2183 window and the agenda.
2184 See also the variable `org-agenda-restore-windows-after-quit'."
2185 :group 'org-agenda-windows
2186 :type '(choice
2187 (const current-window)
2188 (const other-frame)
2189 (const other-window)
2190 (const reorganize-frame)))
2192 (defcustom org-agenda-restore-windows-after-quit nil
2193 "Non-nil means, restore window configuration open exiting agenda.
2194 Before the window configuration is changed for displaying the agenda,
2195 the current status is recorded. When the agenda is exited with
2196 `q' or `x' and this option is set, the old state is restored. If
2197 `org-agenda-window-setup' is `other-frame', the value of this
2198 option will be ignored.."
2199 :group 'org-agenda-windows
2200 :type 'boolean)
2202 (defcustom org-indirect-buffer-display 'other-window
2203 "How should indirect tree buffers be displayed?
2204 This applies to indirect buffers created with the commands
2205 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2206 Valid values are:
2207 current-window Display in the current window
2208 other-window Just display in another window.
2209 dedicated-frame Create one new frame, and re-use it each time.
2210 new-frame Make a new frame each time."
2211 :group 'org-structure
2212 :group 'org-agenda-windows
2213 :type '(choice
2214 (const :tag "In current window" current-window)
2215 (const :tag "In current frame, other window" other-window)
2216 (const :tag "Each time a new frame" new-frame)
2217 (const :tag "One dedicated frame" dedicated-frame)))
2219 (defgroup org-agenda-daily/weekly nil
2220 "Options concerning the daily/weekly agenda."
2221 :tag "Org Agenda Daily/Weekly"
2222 :group 'org-agenda)
2224 (defcustom org-agenda-ndays 7
2225 "Number of days to include in overview display.
2226 Should be 1 or 7."
2227 :group 'org-agenda-daily/weekly
2228 :type 'number)
2230 (defcustom org-agenda-start-on-weekday 1
2231 "Non-nil means, start the overview always on the specified weekday.
2232 0 denotes Sunday, 1 denotes Monday etc.
2233 When nil, always start on the current day."
2234 :group 'org-agenda-daily/weekly
2235 :type '(choice (const :tag "Today" nil)
2236 (number :tag "Weekday No.")))
2238 (defcustom org-agenda-show-all-dates t
2239 "Non-nil means, `org-agenda' shows every day in the selected range.
2240 When nil, only the days which actually have entries are shown."
2241 :group 'org-agenda-daily/weekly
2242 :type 'boolean)
2244 (defcustom org-agenda-date-format "%A %d %B %Y"
2245 "Format string for displaying dates in the agenda.
2246 Used by the daily/weekly agenda and by the timeline. This should be
2247 a format string understood by `format-time-string'.
2248 FIXME: Not used currently, because of timezone problem."
2249 :group 'org-agenda-daily/weekly
2250 :type 'string)
2252 (defcustom org-agenda-include-diary nil
2253 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2254 :group 'org-agenda-daily/weekly
2255 :type 'boolean)
2257 (defcustom org-agenda-include-all-todo nil
2258 "Set means weekly/daily agenda will always contain all TODO entries.
2259 The TODO entries will be listed at the top of the agenda, before
2260 the entries for specific days."
2261 :group 'org-agenda-daily/weekly
2262 :type 'boolean)
2264 (defcustom org-agenda-repeating-timestamp-show-all t
2265 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2266 When nil, only one occurence is shown, either today or the
2267 nearest into the future."
2268 :group 'org-agenda-daily/weekly
2269 :type 'boolean)
2271 (defgroup org-agenda-time-grid nil
2272 "Options concerning the time grid in the Org-mode Agenda."
2273 :tag "Org Agenda Time Grid"
2274 :group 'org-agenda)
2276 (defcustom org-agenda-use-time-grid t
2277 "Non-nil means, show a time grid in the agenda schedule.
2278 A time grid is a set of lines for specific times (like every two hours between
2279 8:00 and 20:00). The items scheduled for a day at specific times are
2280 sorted in between these lines.
2281 For details about when the grid will be shown, and what it will look like, see
2282 the variable `org-agenda-time-grid'."
2283 :group 'org-agenda-time-grid
2284 :type 'boolean)
2286 (defcustom org-agenda-time-grid
2287 '((daily today require-timed)
2288 "----------------"
2289 (800 1000 1200 1400 1600 1800 2000))
2291 "The settings for time grid for agenda display.
2292 This is a list of three items. The first item is again a list. It contains
2293 symbols specifying conditions when the grid should be displayed:
2295 daily if the agenda shows a single day
2296 weekly if the agenda shows an entire week
2297 today show grid on current date, independent of daily/weekly display
2298 require-timed show grid only if at least one item has a time specification
2300 The second item is a string which will be places behing the grid time.
2302 The third item is a list of integers, indicating the times that should have
2303 a grid line."
2304 :group 'org-agenda-time-grid
2305 :type
2306 '(list
2307 (set :greedy t :tag "Grid Display Options"
2308 (const :tag "Show grid in single day agenda display" daily)
2309 (const :tag "Show grid in weekly agenda display" weekly)
2310 (const :tag "Always show grid for today" today)
2311 (const :tag "Show grid only if any timed entries are present"
2312 require-timed)
2313 (const :tag "Skip grid times already present in an entry"
2314 remove-match))
2315 (string :tag "Grid String")
2316 (repeat :tag "Grid Times" (integer :tag "Time"))))
2318 (defgroup org-agenda-sorting nil
2319 "Options concerning sorting in the Org-mode Agenda."
2320 :tag "Org Agenda Sorting"
2321 :group 'org-agenda)
2323 (let ((sorting-choice
2324 '(choice
2325 (const time-up) (const time-down)
2326 (const category-keep) (const category-up) (const category-down)
2327 (const tag-down) (const tag-up)
2328 (const priority-up) (const priority-down))))
2330 (defcustom org-agenda-sorting-strategy
2331 '((agenda time-up category-keep priority-down)
2332 (todo category-keep priority-down)
2333 (tags category-keep priority-down))
2334 "Sorting structure for the agenda items of a single day.
2335 This is a list of symbols which will be used in sequence to determine
2336 if an entry should be listed before another entry. The following
2337 symbols are recognized:
2339 time-up Put entries with time-of-day indications first, early first
2340 time-down Put entries with time-of-day indications first, late first
2341 category-keep Keep the default order of categories, corresponding to the
2342 sequence in `org-agenda-files'.
2343 category-up Sort alphabetically by category, A-Z.
2344 category-down Sort alphabetically by category, Z-A.
2345 tag-up Sort alphabetically by last tag, A-Z.
2346 tag-down Sort alphabetically by last tag, Z-A.
2347 priority-up Sort numerically by priority, high priority last.
2348 priority-down Sort numerically by priority, high priority first.
2350 The different possibilities will be tried in sequence, and testing stops
2351 if one comparison returns a \"not-equal\". For example, the default
2352 '(time-up category-keep priority-down)
2353 means: Pull out all entries having a specified time of day and sort them,
2354 in order to make a time schedule for the current day the first thing in the
2355 agenda listing for the day. Of the entries without a time indication, keep
2356 the grouped in categories, don't sort the categories, but keep them in
2357 the sequence given in `org-agenda-files'. Within each category sort by
2358 priority.
2360 Leaving out `category-keep' would mean that items will be sorted across
2361 categories by priority."
2362 :group 'org-agenda-sorting
2363 :type `(choice
2364 (repeat :tag "General" ,sorting-choice)
2365 (list :tag "Individually"
2366 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2367 (repeat ,sorting-choice))
2368 (cons (const :tag "Strategy for TODO lists" todo)
2369 (repeat ,sorting-choice))
2370 (cons (const :tag "Strategy for Tags matches" tags)
2371 (repeat ,sorting-choice))))))
2373 (defcustom org-sort-agenda-notime-is-late t
2374 "Non-nil means, items without time are considered late.
2375 This is only relevant for sorting. When t, items which have no explicit
2376 time like 15:30 will be considered as 99:01, i.e. later than any items which
2377 do have a time. When nil, the default time is before 0:00. You can use this
2378 option to decide if the schedule for today should come before or after timeless
2379 agenda entries."
2380 :group 'org-agenda-sorting
2381 :type 'boolean)
2383 (defgroup org-agenda-prefix nil
2384 "Options concerning the entry prefix in the Org-mode agenda display."
2385 :tag "Org Agenda Prefix"
2386 :group 'org-agenda)
2388 (defcustom org-agenda-prefix-format
2389 '((agenda . " %-12:c%?-12t% s")
2390 (timeline . " % s")
2391 (todo . " %-12:c")
2392 (tags . " %-12:c"))
2393 "Format specifications for the prefix of items in the agenda views.
2394 An alist with four entries, for the different agenda types. The keys to the
2395 sublists are `agenda', `timeline', `todo', and `tags'. The values
2396 are format strings.
2397 This format works similar to a printf format, with the following meaning:
2399 %c the category of the item, \"Diary\" for entries from the diary, or
2400 as given by the CATEGORY keyword or derived from the file name.
2401 %T the *last* tag of the item. Last because inherited tags come
2402 first in the list.
2403 %t the time-of-day specification if one applies to the entry, in the
2404 format HH:MM
2405 %s Scheduling/Deadline information, a short string
2407 All specifiers work basically like the standard `%s' of printf, but may
2408 contain two additional characters: A question mark just after the `%' and
2409 a whitespace/punctuation character just before the final letter.
2411 If the first character after `%' is a question mark, the entire field
2412 will only be included if the corresponding value applies to the
2413 current entry. This is useful for fields which should have fixed
2414 width when present, but zero width when absent. For example,
2415 \"%?-12t\" will result in a 12 character time field if a time of the
2416 day is specified, but will completely disappear in entries which do
2417 not contain a time.
2419 If there is punctuation or whitespace character just before the final
2420 format letter, this character will be appended to the field value if
2421 the value is not empty. For example, the format \"%-12:c\" leads to
2422 \"Diary: \" if the category is \"Diary\". If the category were be
2423 empty, no additional colon would be interted.
2425 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2426 - Indent the line with two space characters
2427 - Give the category in a 12 chars wide field, padded with whitespace on
2428 the right (because of `-'). Append a colon if there is a category
2429 (because of `:').
2430 - If there is a time-of-day, put it into a 12 chars wide field. If no
2431 time, don't put in an empty field, just skip it (because of '?').
2432 - Finally, put the scheduling information and append a whitespace.
2434 As another example, if you don't want the time-of-day of entries in
2435 the prefix, you could use:
2437 (setq org-agenda-prefix-format \" %-11:c% s\")
2439 See also the variables `org-agenda-remove-times-when-in-prefix' and
2440 `org-agenda-remove-tags'."
2441 :type '(choice
2442 (string :tag "General format")
2443 (list :greedy t :tag "View dependent"
2444 (cons (const agenda) (string :tag "Format"))
2445 (cons (const timeline) (string :tag "Format"))
2446 (cons (const todo) (string :tag "Format"))
2447 (cons (const tags) (string :tag "Format"))))
2448 :group 'org-agenda-prefix)
2450 (defvar org-prefix-format-compiled nil
2451 "The compiled version of the most recently used prefix format.
2452 See the variable `org-agenda-prefix-format'.")
2454 (defcustom org-agenda-remove-times-when-in-prefix t
2455 "Non-nil means, remove duplicate time specifications in agenda items.
2456 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2457 time-of-day specification in a headline or diary entry is extracted and
2458 placed into the prefix. If this option is non-nil, the original specification
2459 \(a timestamp or -range, or just a plain time(range) specification like
2460 11:30-4pm) will be removed for agenda display. This makes the agenda less
2461 cluttered.
2462 The option can be t or nil. It may also be the symbol `beg', indicating
2463 that the time should only be removed what it is located at the beginning of
2464 the headline/diary entry."
2465 :group 'org-agenda-prefix
2466 :type '(choice
2467 (const :tag "Always" t)
2468 (const :tag "Never" nil)
2469 (const :tag "When at beginning of entry" beg)))
2472 (defcustom org-agenda-default-appointment-duration nil
2473 "Default duration for appointments that only have a starting time.
2474 When nil, no duration is specified in such cases.
2475 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2476 :group 'org-agenda-prefix
2477 :type '(choice
2478 (integer :tag "Minutes")
2479 (const :tag "No default duration")))
2482 (defcustom org-agenda-remove-tags nil
2483 "Non-nil means, remove the tags from the headline copy in the agenda.
2484 When this is the symbol `prefix', only remove tags when
2485 `org-agenda-prefix-format' contains a `%T' specifier."
2486 :group 'org-agenda-prefix
2487 :type '(choice
2488 (const :tag "Always" t)
2489 (const :tag "Never" nil)
2490 (const :tag "When prefix format contains %T" prefix)))
2492 (if (fboundp 'defvaralias)
2493 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2494 'org-agenda-remove-tags))
2496 (defcustom org-agenda-align-tags-to-column 65
2497 "Shift tags in agenda items to this column."
2498 :group 'org-agenda-prefix
2499 :type 'integer)
2501 (defgroup org-latex nil
2502 "Options for embedding LaTeX code into Org-mode"
2503 :tag "Org LaTeX"
2504 :group 'org)
2506 (defcustom org-format-latex-options
2507 '(:foreground default :background default :scale 1.0
2508 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2509 :matchers ("begin" "$" "$$" "\\(" "\\["))
2510 "Options for creating images from LaTeX fragments.
2511 This is a property list with the following properties:
2512 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2513 `default' means use the forground of the default face.
2514 :background the background color, or \"Transparent\".
2515 `default' means use the background of the default face.
2516 :scale a scaling factor for the size of the images
2517 :html-foreground, :html-background, :html-scale
2518 The same numbers for HTML export.
2519 :matchers a list indicating which matchers should be used to
2520 find LaTeX fragments. Valid members of this list are:
2521 \"begin\" find environments
2522 \"$\" find math expressions surrounded by $...$
2523 \"$$\" find math expressions surrounded by $$....$$
2524 \"\\(\" find math expressions surrounded by \\(...\\)
2525 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2526 :group 'org-export-latex
2527 :type 'plist)
2529 (defcustom org-format-latex-header "\\documentclass{article}
2530 \\usepackage{fullpage} % do not remove
2531 \\usepackage{amssymb}
2532 \\usepackage[usenames]{color}
2533 \\usepackage{amsmath}
2534 \\usepackage{latexsym}
2535 \\usepackage[mathscr]{eucal}
2536 \\pagestyle{empty} % do not remove"
2537 "The document header used for processing LaTeX fragments."
2538 :group 'org-export-latex
2539 :type 'string)
2541 (defgroup org-export nil
2542 "Options for exporting org-listings."
2543 :tag "Org Export"
2544 :group 'org)
2546 (defgroup org-export-general nil
2547 "General options for exporting Org-mode files."
2548 :tag "Org Export General"
2549 :group 'org-export)
2551 (defcustom org-export-publishing-directory "."
2552 "Path to the location where exported files should be located.
2553 This path may be relative to the directory where the Org-mode file lives.
2554 The default is to put them into the same directory as the Org-mode file.
2555 The variable may also be an alist with export types `:html', `:ascii',
2556 `:ical', or `:xoxo' and the corresponding directories. If a directory path
2557 is relative, it is interpreted relative to the directory where the exported
2558 Org-mode files lives."
2559 :group 'org-export-general
2560 :type '(choice
2561 (directory)
2562 (repeat
2563 (cons
2564 (choice :tag "Type"
2565 (const :html) (const :ascii) (const :ical) (const :xoxo))
2566 (directory)))))
2568 (defcustom org-export-language-setup
2569 '(("en" "Author" "Date" "Table of Contents")
2570 ("cs" "Autor" "Datum" "Obsah")
2571 ("da" "Ophavsmand" "Dato" "Indhold")
2572 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2573 ("es" "Autor" "Fecha" "\xccndice")
2574 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2575 ("it" "Autore" "Data" "Indice")
2576 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2577 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2578 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2579 "Terms used in export text, translated to different languages.
2580 Use the variable `org-export-default-language' to set the language,
2581 or use the +OPTION lines for a per-file setting."
2582 :group 'org-export-general
2583 :type '(repeat
2584 (list
2585 (string :tag "HTML language tag")
2586 (string :tag "Author")
2587 (string :tag "Date")
2588 (string :tag "Table of Contents"))))
2590 (defcustom org-export-default-language "en"
2591 "The default language of HTML export, as a string.
2592 This should have an association in `org-export-language-setup'."
2593 :group 'org-export-general
2594 :type 'string)
2596 (defcustom org-export-skip-text-before-1st-heading t
2597 "Non-nil means, skip all text before the first headline when exporting.
2598 When nil, that text is exported as well."
2599 :group 'org-export-general
2600 :type 'boolean)
2602 (defcustom org-export-headline-levels 3
2603 "The last level which is still exported as a headline.
2604 Inferior levels will produce itemize lists when exported.
2605 Note that a numeric prefix argument to an exporter function overrides
2606 this setting.
2608 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2609 :group 'org-export-general
2610 :type 'number)
2612 (defcustom org-export-with-section-numbers t
2613 "Non-nil means, add section numbers to headlines when exporting.
2615 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2616 :group 'org-export-general
2617 :type 'boolean)
2619 (defcustom org-export-with-toc t
2620 "Non-nil means, create a table of contents in exported files.
2621 The TOC contains headlines with levels up to`org-export-headline-levels'.
2622 When an integer, include levels up to N in the toc, this may then be
2623 different from `org-export-headline-levels', but it will not be allowed
2624 to be larger than the number of headline levels.
2625 When nil, no table of contents is made.
2627 Headlines which contain any TODO items will be marked with \"(*)\" in
2628 ASCII export, and with red color in HTML output, if the option
2629 `org-export-mark-todo-in-toc' is set.
2631 In HTML output, the TOC will be clickable.
2633 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2634 or \"toc:3\"."
2635 :group 'org-export-general
2636 :type '(choice
2637 (const :tag "No Table of Contents" nil)
2638 (const :tag "Full Table of Contents" t)
2639 (integer :tag "TOC to level")))
2641 (defcustom org-export-mark-todo-in-toc nil
2642 "Non-nil means, mark TOC lines that contain any open TODO items."
2643 :group 'org-export-general
2644 :type 'boolean)
2646 (defcustom org-export-preserve-breaks nil
2647 "Non-nil means, preserve all line breaks when exporting.
2648 Normally, in HTML output paragraphs will be reformatted. In ASCII
2649 export, line breaks will always be preserved, regardless of this variable.
2651 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2652 :group 'org-export-general
2653 :type 'boolean)
2655 (defcustom org-export-with-archived-trees 'headline
2656 "Whether subtrees with the ARCHIVE tag should be exported.
2657 This can have three different values
2658 nil Do not export, pretend this tree is not present
2659 t Do export the entire tree
2660 headline Only export the headline, but skip the tree below it."
2661 :group 'org-export-general
2662 :group 'org-archive
2663 :type '(choice
2664 (const :tag "not at all" nil)
2665 (const :tag "headline only" 'headline)
2666 (const :tag "entirely" t)))
2668 (defcustom org-export-author-info t
2669 "Non-nil means, insert author name and email into the exported file.
2671 This option can also be set with the +OPTIONS line,
2672 e.g. \"author-info:nil\"."
2673 :group 'org-export-general
2674 :type 'boolean)
2676 (defcustom org-export-time-stamp-file t
2677 "Non-nil means, insert a time stamp into the exported file.
2678 The time stamp shows when the file was created.
2680 This option can also be set with the +OPTIONS line,
2681 e.g. \"timestamp:nil\"."
2682 :group 'org-export-general
2683 :type 'boolean)
2685 (defcustom org-export-with-timestamps t
2686 "If nil, do not export time stamps and associated keywords."
2687 :group 'org-export-general
2688 :type 'boolean)
2690 (defcustom org-export-remove-timestamps-from-toc t
2691 "If nil, remove timestamps from the table of contents entries."
2692 :group 'org-export-general
2693 :type 'boolean)
2695 (defcustom org-export-with-tags 'not-in-toc
2696 "If nil, do not export tags, just remove them from headlines.
2697 If this is the symbol `not-in-toc', tags will be removed from table of
2698 contents entries, but still be shown in the headlines of the document."
2699 :group 'org-export-general
2700 :type '(choice
2701 (const :tag "Off" nil)
2702 (const :tag "Not in TOC" not-in-toc)
2703 (const :tag "On" t)))
2705 (defcustom org-export-with-property-drawer nil
2706 "Non-nil means, export property drawers.
2707 When nil, these drawers are removed before export.
2709 This option can also be set with the +OPTIONS line, e.g. \"p:t\"."
2710 :group 'org-export-general
2711 :type 'boolean)
2713 (defgroup org-export-translation nil
2714 "Options for translating special ascii sequences for the export backends."
2715 :tag "Org Export Translation"
2716 :group 'org-export)
2718 (defcustom org-export-with-emphasize t
2719 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2720 If the export target supports emphasizing text, the word will be
2721 typeset in bold, italic, or underlined, respectively. Works only for
2722 single words, but you can say: I *really* *mean* *this*.
2723 Not all export backends support this.
2725 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2726 :group 'org-export-translation
2727 :type 'boolean)
2729 (defcustom org-export-with-footnotes t
2730 "If nil, export [1] as a footnote marker.
2731 Lines starting with [1] will be formatted as footnotes.
2733 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
2734 :group 'org-export-translation
2735 :type 'boolean)
2737 (defcustom org-export-with-sub-superscripts t
2738 "Non-nil means, interpret \"_\" and \"^\" for export.
2739 When this option is turned on, you can use TeX-like syntax for sub- and
2740 superscripts. Several characters after \"_\" or \"^\" will be
2741 considered as a single item - so grouping with {} is normally not
2742 needed. For example, the following things will be parsed as single
2743 sub- or superscripts.
2745 10^24 or 10^tau several digits will be considered 1 item.
2746 10^-12 or 10^-tau a leading sign with digits or a word
2747 x^2-y^3 will be read as x^2 - y^3, because items are
2748 terminated by almost any nonword/nondigit char.
2749 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2751 Still, ambiguity is possible - so when in doubt use {} to enclose the
2752 sub/superscript. If you set this variable to the symbol `{}',
2753 the braces are *required* in order to trigger interpretations as
2754 sub/superscript. This can be helpful in documents that need \"_\"
2755 frequently in plain text.
2757 Not all export backends support this, but HTML does.
2759 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2760 :group 'org-export-translation
2761 :type '(choice
2762 (const :tag "Always interpret" t)
2763 (const :tag "Only with braces" {})
2764 (const :tag "Never interpret" nil)))
2766 (defcustom org-export-with-TeX-macros t
2767 "Non-nil means, interpret simple TeX-like macros when exporting.
2768 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2769 No only real TeX macros will work here, but the standard HTML entities
2770 for math can be used as macro names as well. For a list of supported
2771 names in HTML export, see the constant `org-html-entities'.
2772 Not all export backends support this.
2774 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2775 :group 'org-export-translation
2776 :group 'org-export-latex
2777 :type 'boolean)
2779 (defcustom org-export-with-LaTeX-fragments nil
2780 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2781 When set, the exporter will find LaTeX environments if the \\begin line is
2782 the first non-white thing on a line. It will also find the math delimiters
2783 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2784 display math.
2786 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2787 :group 'org-export-translation
2788 :group 'org-export-latex
2789 :type 'boolean)
2791 (defcustom org-export-with-fixed-width t
2792 "Non-nil means, lines starting with \":\" will be in fixed width font.
2793 This can be used to have pre-formatted text, fragments of code etc. For
2794 example:
2795 : ;; Some Lisp examples
2796 : (while (defc cnt)
2797 : (ding))
2798 will be looking just like this in also HTML. See also the QUOTE keyword.
2799 Not all export backends support this.
2801 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2802 :group 'org-export-translation
2803 :type 'boolean)
2805 (defcustom org-match-sexp-depth 3
2806 "Number of stacked braces for sub/superscript matching.
2807 This has to be set before loading org.el to be effective."
2808 :group 'org-export-translation
2809 :type 'integer)
2811 (defgroup org-export-tables nil
2812 "Options for exporting tables in Org-mode."
2813 :tag "Org Export Tables"
2814 :group 'org-export)
2816 (defcustom org-export-with-tables t
2817 "If non-nil, lines starting with \"|\" define a table.
2818 For example:
2820 | Name | Address | Birthday |
2821 |-------------+----------+-----------|
2822 | Arthur Dent | England | 29.2.2100 |
2824 Not all export backends support this.
2826 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2827 :group 'org-export-tables
2828 :type 'boolean)
2830 (defcustom org-export-highlight-first-table-line t
2831 "Non-nil means, highlight the first table line.
2832 In HTML export, this means use <th> instead of <td>.
2833 In tables created with table.el, this applies to the first table line.
2834 In Org-mode tables, all lines before the first horizontal separator
2835 line will be formatted with <th> tags."
2836 :group 'org-export-tables
2837 :type 'boolean)
2839 (defcustom org-export-table-remove-special-lines t
2840 "Remove special lines and marking characters in calculating tables.
2841 This removes the special marking character column from tables that are set
2842 up for spreadsheet calculations. It also removes the entire lines
2843 marked with `!', `_', or `^'. The lines with `$' are kept, because
2844 the values of constants may be useful to have."
2845 :group 'org-export-tables
2846 :type 'boolean)
2848 (defcustom org-export-prefer-native-exporter-for-tables nil
2849 "Non-nil means, always export tables created with table.el natively.
2850 Natively means, use the HTML code generator in table.el.
2851 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2852 the table does not use row- or column-spanning). This has the
2853 advantage, that the automatic HTML conversions for math symbols and
2854 sub/superscripts can be applied. Org-mode's HTML generator is also
2855 much faster."
2856 :group 'org-export-tables
2857 :type 'boolean)
2859 (defgroup org-export-ascii nil
2860 "Options specific for ASCII export of Org-mode files."
2861 :tag "Org Export ASCII"
2862 :group 'org-export)
2864 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2865 "Characters for underlining headings in ASCII export.
2866 In the given sequence, these characters will be used for level 1, 2, ..."
2867 :group 'org-export-ascii
2868 :type '(repeat character))
2870 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2871 "Bullet characters for headlines converted to lists in ASCII export.
2872 The first character is is used for the first lest level generated in this
2873 way, and so on. If there are more levels than characters given here,
2874 the list will be repeated.
2875 Note that plain lists will keep the same bullets as the have in the
2876 Org-mode file."
2877 :group 'org-export-ascii
2878 :type '(repeat character))
2880 (defgroup org-export-xml nil
2881 "Options specific for XML export of Org-mode files."
2882 :tag "Org Export XML"
2883 :group 'org-export)
2885 (defgroup org-export-html nil
2886 "Options specific for HTML export of Org-mode files."
2887 :tag "Org Export HTML"
2888 :group 'org-export)
2890 (defcustom org-export-html-coding-system nil
2892 :group 'org-export-html
2893 :type 'coding-system)
2895 (defcustom org-export-html-style
2896 "<style type=\"text/css\">
2897 html {
2898 font-family: Times, serif;
2899 font-size: 12pt;
2901 .title { text-align: center; }
2902 .todo { color: red; }
2903 .done { color: green; }
2904 .timestamp { color: grey }
2905 .timestamp-kwd { color: CadetBlue }
2906 .tag { background-color:lightblue; font-weight:normal }
2907 .target { background-color: lavender; }
2908 pre {
2909 border: 1pt solid #AEBDCC;
2910 background-color: #F3F5F7;
2911 padding: 5pt;
2912 font-family: courier, monospace;
2914 table { border-collapse: collapse; }
2915 td, th {
2916 vertical-align: top;
2917 <!--border: 1pt solid #ADB9CC;-->
2919 </style>"
2920 "The default style specification for exported HTML files.
2921 Since there are different ways of setting style information, this variable
2922 needs to contain the full HTML structure to provide a style, including the
2923 surrounding HTML tags. The style specifications should include definitions
2924 for new classes todo, done, title, and deadline. For example, legal values
2925 would be:
2927 <style type=\"text/css\">
2928 p { font-weight: normal; color: gray; }
2929 h1 { color: black; }
2930 .title { text-align: center; }
2931 .todo, .deadline { color: red; }
2932 .done { color: green; }
2933 </style>
2935 or, if you want to keep the style in a file,
2937 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2939 As the value of this option simply gets inserted into the HTML <head> header,
2940 you can \"misuse\" it to add arbitrary text to the header."
2941 :group 'org-export-html
2942 :type 'string)
2945 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2946 "Format for typesetting the document title in HTML export."
2947 :group 'org-export-html
2948 :type 'string)
2950 (defcustom org-export-html-toplevel-hlevel 2
2951 "The <H> level for level 1 headings in HTML export."
2952 :group 'org-export-html
2953 :type 'string)
2955 (defcustom org-export-html-link-org-files-as-html t
2956 "Non-nil means, make file links to `file.org' point to `file.html'.
2957 When org-mode is exporting an org-mode file to HTML, links to
2958 non-html files are directly put into a href tag in HTML.
2959 However, links to other Org-mode files (recognized by the
2960 extension `.org.) should become links to the corresponding html
2961 file, assuming that the linked org-mode file will also be
2962 converted to HTML.
2963 When nil, the links still point to the plain `.org' file."
2964 :group 'org-export-html
2965 :type 'boolean)
2967 (defcustom org-export-html-inline-images 'maybe
2968 "Non-nil means, inline images into exported HTML pages.
2969 This is done using an <img> tag. When nil, an anchor with href is used to
2970 link to the image. If this option is `maybe', then images in links with
2971 an empty description will be inlined, while images with a description will
2972 be linked only."
2973 :group 'org-export-html
2974 :type '(choice (const :tag "Never" nil)
2975 (const :tag "Always" t)
2976 (const :tag "When there is no description" maybe)))
2978 ;; FIXME: rename
2979 (defcustom org-export-html-expand t
2980 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2981 When nil, these tags will be exported as plain text and therefore
2982 not be interpreted by a browser.
2984 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2985 :group 'org-export-html
2986 :type 'boolean)
2988 (defcustom org-export-html-table-tag
2989 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
2990 "The HTML tag that is used to start a table.
2991 This must be a <table> tag, but you may change the options like
2992 borders and spacing."
2993 :group 'org-export-html
2994 :type 'string)
2996 (defcustom org-export-table-header-tags '("<th>" . "</th>")
2997 "The opening tag for table header fields.
2998 This is customizable so that alignment options can be specified."
2999 :group 'org-export-tables
3000 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3002 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3003 "The opening tag for table data fields.
3004 This is customizable so that alignment options can be specified."
3005 :group 'org-export-tables
3006 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3008 (defcustom org-export-html-with-timestamp nil
3009 "If non-nil, write `org-export-html-html-helper-timestamp'
3010 into the exported HTML text. Otherwise, the buffer will just be saved
3011 to a file."
3012 :group 'org-export-html
3013 :type 'boolean)
3015 (defcustom org-export-html-html-helper-timestamp
3016 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3017 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3018 :group 'org-export-html
3019 :type 'string)
3021 (defgroup org-export-icalendar nil
3022 "Options specific for iCalendar export of Org-mode files."
3023 :tag "Org Export iCalendar"
3024 :group 'org-export)
3026 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3027 "The file name for the iCalendar file covering all agenda files.
3028 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3029 The file name should be absolute."
3030 :group 'org-export-icalendar
3031 :type 'file)
3033 (defcustom org-icalendar-include-todo nil
3034 "Non-nil means, export to iCalendar files should also cover TODO items."
3035 :group 'org-export-icalendar
3036 :type '(choice
3037 (const :tag "None" nil)
3038 (const :tag "Unfinished" t)
3039 (const :tag "All" all)))
3041 (defcustom org-icalendar-include-sexps t
3042 "Non-nil means, export to iCalendar files should also cover sexp entries.
3043 These are entries like in the diary, but directly in an Org-mode file."
3044 :group 'org-export-icalendar
3045 :type 'boolean)
3047 (defcustom org-icalendar-combined-name "OrgMode"
3048 "Calendar name for the combined iCalendar representing all agenda files."
3049 :group 'org-export-icalendar
3050 :type 'string)
3052 (defgroup org-font-lock nil
3053 "Font-lock settings for highlighting in Org-mode."
3054 :tag "Org Font Lock"
3055 :group 'org)
3057 (defcustom org-level-color-stars-only nil
3058 "Non-nil means fontify only the stars in each headline.
3059 When nil, the entire headline is fontified.
3060 Changing it requires restart of `font-lock-mode' to become effective
3061 also in regions already fontified."
3062 :group 'org-font-lock
3063 :type 'boolean)
3065 (defcustom org-hide-leading-stars nil
3066 "Non-nil means, hide the first N-1 stars in a headline.
3067 This works by using the face `org-hide' for these stars. This
3068 face is white for a light background, and black for a dark
3069 background. You may have to customize the face `org-hide' to
3070 make this work.
3071 Changing it requires restart of `font-lock-mode' to become effective
3072 also in regions already fontified.
3073 You may also set this on a per-file basis by adding one of the following
3074 lines to the buffer:
3076 #+STARTUP: hidestars
3077 #+STARTUP: showstars"
3078 :group 'org-font-lock
3079 :type 'boolean)
3081 (defcustom org-fontify-done-headline nil
3082 "Non-nil means, change the face of a headline if it is marked DONE.
3083 Normally, only the TODO/DONE keyword indicates the state of a headline.
3084 When this is non-nil, the headline after the keyword is set to the
3085 `org-headline-done' as an additional indication."
3086 :group 'org-font-lock
3087 :type 'boolean)
3089 (defcustom org-fontify-emphasized-text t
3090 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3091 Changing this variable requires a restart of Emacs to take effect."
3092 :group 'org-font-lock
3093 :type 'boolean)
3095 (defvar org-emph-re nil
3096 "Regular expression for matching emphasis.")
3097 (defvar org-emphasis-regexp-components) ; defined just below
3098 (defvar org-emphasis-alist) ; defined just below
3099 (defun org-set-emph-re (var val)
3100 "Set variable and compute the emphasis regular expression."
3101 (set var val)
3102 (when (and (boundp 'org-emphasis-alist)
3103 (boundp 'org-emphasis-regexp-components)
3104 org-emphasis-alist org-emphasis-regexp-components)
3105 (let* ((e org-emphasis-regexp-components)
3106 (pre (car e))
3107 (post (nth 1 e))
3108 (border (nth 2 e))
3109 (body (nth 3 e))
3110 (nl (nth 4 e))
3111 (stacked (nth 5 e))
3112 (body1 (concat body "*?"))
3113 (markers (mapconcat 'car org-emphasis-alist "")))
3114 ;; make sure special characters appear at the right position in the class
3115 (if (string-match "\\^" markers)
3116 (setq markers (concat (replace-match "" t t markers) "^")))
3117 (if (string-match "-" markers)
3118 (setq markers (concat (replace-match "" t t markers) "-")))
3119 (if (> nl 0)
3120 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3121 (int-to-string nl) "\\}")))
3122 ;; Make the regexp
3123 (setq org-emph-re
3124 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
3125 "\\("
3126 "\\([" markers "]\\)"
3127 "\\("
3128 "[^" border (if (and nil stacked) markers) "]"
3129 body1
3130 "[^" border (if (and nil stacked) markers) "]"
3131 "\\)"
3132 "\\3\\)"
3133 "\\([" post (if stacked markers) "]\\|$\\)")))))
3135 (defcustom org-emphasis-regexp-components
3136 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1 nil)
3137 "Components used to build the reqular expression for emphasis.
3138 This is a list with 6 entries. Terminology: In an emphasis string
3139 like \" *strong word* \", we call the initial space PREMATCH, the final
3140 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3141 and \"trong wor\" is the body. The different components in this variable
3142 specify what is allowed/forbidden in each part:
3144 pre Chars allowed as prematch. Beginning of line will be allowed too.
3145 post Chars allowed as postmatch. End of line will be allowed too.
3146 border The chars *forbidden* as border characters.
3147 body-regexp A regexp like \".\" to match a body character. Don't use
3148 non-shy groups here, and don't allow newline here.
3149 newline The maximum number of newlines allowed in an emphasis exp.
3150 stacked Non-nil means, allow stacked styles. This works only in HTML
3151 export. When this is set, all marker characters (as given in
3152 `org-emphasis-alist') will be allowed as pre/post, aiding
3153 inside-out matching.
3154 Use customize to modify this, or restart Emacs after changing it."
3155 :group 'org-font-lock
3156 :set 'org-set-emph-re
3157 :type '(list
3158 (sexp :tag "Allowed chars in pre ")
3159 (sexp :tag "Allowed chars in post ")
3160 (sexp :tag "Forbidden chars in border ")
3161 (sexp :tag "Regexp for body ")
3162 (integer :tag "number of newlines allowed")
3163 (boolean :tag "Stacking allowed ")))
3165 (defcustom org-emphasis-alist
3166 '(("*" bold "<b>" "</b>")
3167 ("/" italic "<i>" "</i>")
3168 ("_" underline "<u>" "</u>")
3169 ("=" org-code "<code>" "</code>")
3170 ("+" (:strike-through t) "<del>" "</del>")
3172 "Special syntax for emphasized text.
3173 Text starting and ending with a special character will be emphasized, for
3174 example *bold*, _underlined_ and /italic/. This variable sets the marker
3175 characters, the face to be used by font-lock for highlighting in Org-mode
3176 Emacs buffers, and the HTML tags to be used for this.
3177 Use customize to modify this, or restart Emacs after changing it."
3178 :group 'org-font-lock
3179 :set 'org-set-emph-re
3180 :type '(repeat
3181 (list
3182 (string :tag "Marker character")
3183 (choice
3184 (face :tag "Font-lock-face")
3185 (plist :tag "Face property list"))
3186 (string :tag "HTML start tag")
3187 (string :tag "HTML end tag"))))
3189 ;;; The faces
3191 (defgroup org-faces nil
3192 "Faces in Org-mode."
3193 :tag "Org Faces"
3194 :group 'org-font-lock)
3196 ;; FIXME: convert that into a macro? Not critical, because this
3197 ;; is only executed a few times at load time.
3198 (defun org-compatible-face (specs)
3199 "Make a compatible face specification.
3200 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3201 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3202 to the top of the list. The `min-colors' attribute will be removed from
3203 any other entries, and any resulting duplicates will be removed entirely."
3204 (if (or (featurep 'xemacs) (< emacs-major-version 22))
3205 (let (r e a)
3206 (while (setq e (pop specs))
3207 (cond
3208 ((memq (car e) '(t default)) (push e r))
3209 ((setq a (member '(min-colors 8) (car e)))
3210 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3211 (cdr e)))))
3212 ((setq a (assq 'min-colors (car e)))
3213 (setq e (cons (delq a (car e)) (cdr e)))
3214 (or (assoc (car e) r) (push e r)))
3215 (t (or (assoc (car e) r) (push e r)))))
3216 (nreverse r))
3217 specs))
3219 (defface org-hide
3220 '((((background light)) (:foreground "white"))
3221 (((background dark)) (:foreground "black")))
3222 "Face used to hide leading stars in headlines.
3223 The forground color of this face should be equal to the background
3224 color of the frame."
3225 :group 'org-faces)
3227 (defface org-level-1 ;; font-lock-function-name-face
3228 (org-compatible-face
3229 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3230 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3231 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3232 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3233 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3234 (t (:bold t))))
3235 "Face used for level 1 headlines."
3236 :group 'org-faces)
3238 (defface org-level-2 ;; font-lock-variable-name-face
3239 (org-compatible-face
3240 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3241 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3242 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3243 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3244 (t (:bold t))))
3245 "Face used for level 2 headlines."
3246 :group 'org-faces)
3248 (defface org-level-3 ;; font-lock-keyword-face
3249 (org-compatible-face
3250 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3251 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3252 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3253 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3254 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3255 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3256 (t (:bold t))))
3257 "Face used for level 3 headlines."
3258 :group 'org-faces)
3260 (defface org-level-4 ;; font-lock-comment-face
3261 (org-compatible-face
3262 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3263 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3264 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3265 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3266 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3267 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3268 (t (:bold t))))
3269 "Face used for level 4 headlines."
3270 :group 'org-faces)
3272 (defface org-level-5 ;; font-lock-type-face
3273 (org-compatible-face
3274 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3275 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3276 (((class color) (min-colors 8)) (:foreground "green"))))
3277 "Face used for level 5 headlines."
3278 :group 'org-faces)
3280 (defface org-level-6 ;; font-lock-constant-face
3281 (org-compatible-face
3282 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3283 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3284 (((class color) (min-colors 8)) (:foreground "magenta"))))
3285 "Face used for level 6 headlines."
3286 :group 'org-faces)
3288 (defface org-level-7 ;; font-lock-builtin-face
3289 (org-compatible-face
3290 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3291 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3292 (((class color) (min-colors 8)) (:foreground "blue"))))
3293 "Face used for level 7 headlines."
3294 :group 'org-faces)
3296 (defface org-level-8 ;; font-lock-string-face
3297 (org-compatible-face
3298 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3299 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3300 (((class color) (min-colors 8)) (:foreground "green"))))
3301 "Face used for level 8 headlines."
3302 :group 'org-faces)
3304 (defface org-special-keyword ;; font-lock-string-face
3305 (org-compatible-face
3306 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3307 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3308 (t (:italic t))))
3309 "Face used for special keywords."
3310 :group 'org-faces)
3312 (defface org-drawer ;; font-lock-function-name-face
3313 (org-compatible-face
3314 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3315 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3316 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3317 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3318 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3319 (t (:bold t))))
3320 "Face used for drawers."
3321 :group 'org-faces)
3323 (defface org-property-value nil
3324 "Face used for the value of a property."
3325 :group 'org-faces)
3327 (defface org-column
3328 (org-compatible-face
3329 '((((class color) (min-colors 16) (background light))
3330 (:background "grey90"))
3331 (((class color) (min-colors 16) (background dark))
3332 (:background "grey30"))
3333 (((class color) (min-colors 8))
3334 (:background "cyan" :foreground "black"))
3335 (t (:inverse-video t))))
3336 "Face for column display of entry properties."
3337 :group 'org-faces)
3339 (when (fboundp 'set-face-attribute)
3340 ;; Make sure that a fixed-width face is used when we have a column table.
3341 (set-face-attribute 'org-column nil
3342 :height (face-attribute 'default :height)
3343 :family (face-attribute 'default :family)))
3345 (defface org-warning ;; font-lock-warning-face
3346 (org-compatible-face
3347 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3348 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3349 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3350 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3351 (t (:bold t))))
3352 "Face for deadlines and TODO keywords."
3353 :group 'org-faces)
3355 (defface org-archived ; similar to shadow
3356 (org-compatible-face
3357 '((((class color grayscale) (min-colors 88) (background light))
3358 (:foreground "grey50"))
3359 (((class color grayscale) (min-colors 88) (background dark))
3360 (:foreground "grey70"))
3361 (((class color) (min-colors 8) (background light))
3362 (:foreground "green"))
3363 (((class color) (min-colors 8) (background dark))
3364 (:foreground "yellow"))))
3365 "Face for headline with the ARCHIVE tag."
3366 :group 'org-faces)
3368 (defface org-link
3369 '((((class color) (background light)) (:foreground "Purple" :underline t))
3370 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3371 (t (:underline t)))
3372 "Face for links."
3373 :group 'org-faces)
3375 (defface org-target
3376 '((((class color) (background light)) (:underline t))
3377 (((class color) (background dark)) (:underline t))
3378 (t (:underline t)))
3379 "Face for links."
3380 :group 'org-faces)
3382 (defface org-date
3383 '((((class color) (background light)) (:foreground "Purple" :underline t))
3384 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3385 (t (:underline t)))
3386 "Face for links."
3387 :group 'org-faces)
3389 (defface org-sexp-date
3390 '((((class color) (background light)) (:foreground "Purple"))
3391 (((class color) (background dark)) (:foreground "Cyan"))
3392 (t (:underline t)))
3393 "Face for links."
3394 :group 'org-faces)
3396 (defface org-tag
3397 '((t (:bold t)))
3398 "Face for tags."
3399 :group 'org-faces)
3401 (defface org-todo ;; font-lock-warning-face
3402 (org-compatible-face
3403 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3404 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3405 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3406 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3407 (t (:inverse-video t :bold t))))
3408 "Face for TODO keywords."
3409 :group 'org-faces)
3411 (defface org-done ;; font-lock-type-face
3412 (org-compatible-face
3413 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3414 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3415 (((class color) (min-colors 8)) (:foreground "green"))
3416 (t (:bold t))))
3417 "Face used for todo keywords that indicate DONE items."
3418 :group 'org-faces)
3420 (defface org-headline-done ;; font-lock-string-face
3421 (org-compatible-face
3422 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3423 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3424 (((class color) (min-colors 8) (background light)) (:bold nil))))
3425 "Face used to indicate that a headline is DONE.
3426 This face is only used if `org-fontify-done-headline' is set. If applies
3427 to the part of the headline after the DONE keyword."
3428 :group 'org-faces)
3430 (defface org-table ;; font-lock-function-name-face
3431 (org-compatible-face
3432 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3433 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3434 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3435 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3436 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3437 (((class color) (min-colors 8) (background dark)))))
3438 "Face used for tables."
3439 :group 'org-faces)
3441 (defface org-formula
3442 (org-compatible-face
3443 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3444 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3445 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3446 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3447 (t (:bold t :italic t))))
3448 "Face for formulas."
3449 :group 'org-faces)
3451 (defface org-code
3452 (org-compatible-face
3453 '((((class color grayscale) (min-colors 88) (background light))
3454 :foreground "grey50")
3455 (((class color grayscale) (min-colors 88) (background dark))
3456 :foreground "grey70")
3457 (((class color) (min-colors 8) (background light))
3458 :foreground "green")
3459 (((class color) (min-colors 8) (background dark))
3460 :foreground "yellow")))
3461 "Face for fixed-with text like code snippets."
3462 :group 'org-faces
3463 :version "22.1")
3465 (defface org-agenda-structure ;; font-lock-function-name-face
3466 (org-compatible-face
3467 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3468 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3469 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3470 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3471 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3472 (t (:bold t))))
3473 "Face used in agenda for captions and dates."
3474 :group 'org-faces)
3476 (defface org-scheduled-today
3477 (org-compatible-face
3478 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3479 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3480 (((class color) (min-colors 8)) (:foreground "green"))
3481 (t (:bold t :italic t))))
3482 "Face for items scheduled for a certain day."
3483 :group 'org-faces)
3485 (defface org-scheduled-previously
3486 (org-compatible-face
3487 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3488 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3489 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3490 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3491 (t (:bold t))))
3492 "Face for items scheduled previously, and not yet done."
3493 :group 'org-faces)
3495 (defface org-upcoming-deadline
3496 (org-compatible-face
3497 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3498 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3499 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3500 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3501 (t (:bold t))))
3502 "Face for items scheduled previously, and not yet done."
3503 :group 'org-faces)
3505 (defcustom org-agenda-deadline-faces
3506 '((1.0 . org-warning)
3507 (0.5 . org-upcoming-deadline)
3508 (0.0 . default))
3509 "Faces for showing deadlines in the agenda.
3510 This is a list of cons cells. The cdr of each cess is a face to be used,
3511 and it can also just be a like like '(:foreground \"yellow\").
3512 Each car is a fraction of the head-warning time that must have passed for
3513 this the face in the cdr to be used for display. The numbers must be
3514 given in descending order. The head-warning time is normally taken
3515 from `org-deadline-warning-days', but can also be specified in the deadline
3516 timestamp itself, like this:
3518 DEADLINE: <2007-08-13 Mon -8d>
3520 You may use d for days, w for weeks, m for months and y for years. Months
3521 and years will only be treated in an approximate fashion (30.4 days for a
3522 month and 365.24 days for a year)."
3523 :group 'org-faces
3524 :group 'org-agenda-daily/weekly
3525 :type '(repeat
3526 (cons
3527 (number :tag "Fraction of head-warning time passed")
3528 (sexp :tag "Face"))))
3530 (defface org-time-grid ;; font-lock-variable-name-face
3531 (org-compatible-face
3532 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3533 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3534 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3535 "Face used for time grids."
3536 :group 'org-faces)
3538 (defconst org-level-faces
3539 '(org-level-1 org-level-2 org-level-3 org-level-4
3540 org-level-5 org-level-6 org-level-7 org-level-8
3543 (defcustom org-n-level-faces (length org-level-faces)
3544 "The number different faces to be used for headlines.
3545 Org-mode defines 8 different headline faces, so this can be at most 8.
3546 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
3547 :type 'number
3548 :group 'org-faces)
3550 ;;; Variables for pre-computed regular expressions, all buffer local
3552 (defvar org-drawer-regexp nil
3553 "Matches first line of a hidden block.")
3554 (make-variable-buffer-local 'org-drawer-regexp)
3555 (defvar org-todo-regexp nil
3556 "Matches any of the TODO state keywords.")
3557 (make-variable-buffer-local 'org-todo-regexp)
3558 (defvar org-not-done-regexp nil
3559 "Matches any of the TODO state keywords except the last one.")
3560 (make-variable-buffer-local 'org-not-done-regexp)
3561 (defvar org-todo-line-regexp nil
3562 "Matches a headline and puts TODO state into group 2 if present.")
3563 (make-variable-buffer-local 'org-todo-line-regexp)
3564 (defvar org-todo-line-tags-regexp nil
3565 "Matches a headline and puts TODO state into group 2 if present.
3566 Also put tags into group 4 if tags are present.")
3567 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3568 (defvar org-nl-done-regexp nil
3569 "Matches newline followed by a headline with the DONE keyword.")
3570 (make-variable-buffer-local 'org-nl-done-regexp)
3571 (defvar org-looking-at-done-regexp nil
3572 "Matches the DONE keyword a point.")
3573 (make-variable-buffer-local 'org-looking-at-done-regexp)
3574 (defvar org-ds-keyword-length 12
3575 "Maximum length of the Deadline and SCHEDULED keywords.")
3576 (make-variable-buffer-local 'org-ds-keyword-length)
3577 (defvar org-deadline-regexp nil
3578 "Matches the DEADLINE keyword.")
3579 (make-variable-buffer-local 'org-deadline-regexp)
3580 (defvar org-deadline-time-regexp nil
3581 "Matches the DEADLINE keyword together with a time stamp.")
3582 (make-variable-buffer-local 'org-deadline-time-regexp)
3583 (defvar org-deadline-line-regexp nil
3584 "Matches the DEADLINE keyword and the rest of the line.")
3585 (make-variable-buffer-local 'org-deadline-line-regexp)
3586 (defvar org-scheduled-regexp nil
3587 "Matches the SCHEDULED keyword.")
3588 (make-variable-buffer-local 'org-scheduled-regexp)
3589 (defvar org-scheduled-time-regexp nil
3590 "Matches the SCHEDULED keyword together with a time stamp.")
3591 (make-variable-buffer-local 'org-scheduled-time-regexp)
3592 (defvar org-closed-time-regexp nil
3593 "Matches the CLOSED keyword together with a time stamp.")
3594 (make-variable-buffer-local 'org-closed-time-regexp)
3596 (defvar org-keyword-time-regexp nil
3597 "Matches any of the 4 keywords, together with the time stamp.")
3598 (make-variable-buffer-local 'org-keyword-time-regexp)
3599 (defvar org-keyword-time-not-clock-regexp nil
3600 "Matches any of the 3 keywords, together with the time stamp.")
3601 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3602 (defvar org-maybe-keyword-time-regexp nil
3603 "Matches a timestamp, possibly preceeded by a keyword.")
3604 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3605 (defvar org-planning-or-clock-line-re nil
3606 "Matches a line with planning or clock info.")
3607 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3609 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3610 rear-nonsticky t mouse-map t fontified t)
3611 "Properties to remove when a string without properties is wanted.")
3613 (defsubst org-match-string-no-properties (num &optional string)
3614 (if (featurep 'xemacs)
3615 (let ((s (match-string num string)))
3616 (remove-text-properties 0 (length s) org-rm-props s)
3618 (match-string-no-properties num string)))
3620 (defsubst org-no-properties (s)
3621 (if (fboundp 'set-text-properties)
3622 (set-text-properties 0 (length s) nil s)
3623 (remove-text-properties 0 (length s) org-rm-props s))
3626 (defsubst org-get-alist-option (option key)
3627 (cond ((eq key t) t)
3628 ((eq option t) t)
3629 ((assoc key option) (cdr (assoc key option)))
3630 (t (cdr (assq 'default option)))))
3632 (defsubst org-inhibit-invisibility ()
3633 "Modified `buffer-invisibility-spec' for Emacs 21.
3634 Some ops with invisible text do not work correctly on Emacs 21. For these
3635 we turn off invisibility temporarily. Use this in a `let' form."
3636 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
3638 (defsubst org-set-local (var value)
3639 "Make VAR local in current buffer and set it to VALUE."
3640 (set (make-variable-buffer-local var) value))
3642 (defsubst org-mode-p ()
3643 "Check if the current buffer is in Org-mode."
3644 (eq major-mode 'org-mode))
3646 (defsubst org-last (list)
3647 "Return the last element of LIST."
3648 (car (last list)))
3650 (defun org-let (list &rest body)
3651 (eval (cons 'let (cons list body))))
3652 (put 'org-let 'lisp-indent-function 1)
3654 (defun org-let2 (list1 list2 &rest body)
3655 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3656 (put 'org-let2 'lisp-indent-function 2)
3657 (defconst org-startup-options
3658 '(("fold" org-startup-folded t)
3659 ("overview" org-startup-folded t)
3660 ("nofold" org-startup-folded nil)
3661 ("showall" org-startup-folded nil)
3662 ("content" org-startup-folded content)
3663 ("hidestars" org-hide-leading-stars t)
3664 ("showstars" org-hide-leading-stars nil)
3665 ("odd" org-odd-levels-only t)
3666 ("oddeven" org-odd-levels-only nil)
3667 ("align" org-startup-align-all-tables t)
3668 ("noalign" org-startup-align-all-tables nil)
3669 ("customtime" org-display-custom-times t)
3670 ("logging" org-log-done t)
3671 ("logdone" org-log-done t)
3672 ("nologging" org-log-done nil)
3673 ("lognotedone" org-log-done done push)
3674 ("lognotestate" org-log-done state push)
3675 ("lognoteclock-out" org-log-done clock-out push)
3676 ("logrepeat" org-log-repeat t)
3677 ("nologrepeat" org-log-repeat nil)
3678 ("constcgs" constants-unit-system cgs)
3679 ("constSI" constants-unit-system SI))
3680 "Variable associated with STARTUP options for org-mode.
3681 Each element is a list of three items: The startup options as written
3682 in the #+STARTUP line, the corresponding variable, and the value to
3683 set this variable to if the option is found. An optional forth element PUSH
3684 means to push this value onto the list in the variable.")
3686 (defun org-set-regexps-and-options ()
3687 "Precompute regular expressions for current buffer."
3688 (when (org-mode-p)
3689 (org-set-local 'org-todo-kwd-alist nil)
3690 (org-set-local 'org-todo-keywords-1 nil)
3691 (org-set-local 'org-done-keywords nil)
3692 (org-set-local 'org-todo-heads nil)
3693 (org-set-local 'org-todo-sets nil)
3694 (let ((re (org-make-options-regexp
3695 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO" "COLUMNS"
3696 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
3697 "CONSTANTS" "PROPERTY")))
3698 (splitre "[ \t]+")
3699 kwds key value cat arch tags const links hw dws tail sep kws1 prio
3700 props)
3701 (save-excursion
3702 (save-restriction
3703 (widen)
3704 (goto-char (point-min))
3705 (while (re-search-forward re nil t)
3706 (setq key (match-string 1) value (org-match-string-no-properties 2))
3707 (cond
3708 ((equal key "CATEGORY")
3709 (if (string-match "[ \t]+$" value)
3710 (setq value (replace-match "" t t value)))
3711 (setq cat (intern value)))
3712 ((equal key "SEQ_TODO")
3713 (push (cons 'sequence (org-split-string value splitre)) kwds))
3714 ((equal key "TYP_TODO")
3715 (push (cons 'type (org-split-string value splitre)) kwds))
3716 ((equal key "TAGS")
3717 (setq tags (append tags (org-split-string value splitre))))
3718 ((equal key "COLUMNS")
3719 (org-set-local 'org-columns-default-format value))
3720 ((equal key "LINK")
3721 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3722 (push (cons (match-string 1 value)
3723 (org-trim (match-string 2 value)))
3724 links)))
3725 ((equal key "PRIORITIES")
3726 (setq prio (org-split-string value " +")))
3727 ((equal key "PROPERTY")
3728 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3729 (push (cons (match-string 1 value) (match-string 2 value))
3730 props)))
3731 ((equal key "CONSTANTS")
3732 (setq const (append const (org-split-string value splitre))))
3733 ((equal key "STARTUP")
3734 (let ((opts (org-split-string value splitre))
3735 l var val)
3736 (while (setq l (pop opts))
3737 (when (setq l (assoc l org-startup-options))
3738 (setq var (nth 1 l) val (nth 2 l))
3739 (if (not (nth 3 l))
3740 (set (make-local-variable var) val)
3741 (if (not (listp (symbol-value var)))
3742 (set (make-local-variable var) nil))
3743 (set (make-local-variable var) (symbol-value var))
3744 (add-to-list var val))))))
3745 ((equal key "ARCHIVE")
3746 (string-match " *$" value)
3747 (setq arch (replace-match "" t t value))
3748 (remove-text-properties 0 (length arch)
3749 '(face t fontified t) arch)))
3751 (and cat (org-set-local 'org-category cat))
3752 (when prio
3753 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3754 (setq prio (mapcar 'string-to-char prio))
3755 (org-set-local 'org-highest-priority (nth 0 prio))
3756 (org-set-local 'org-lowest-priority (nth 1 prio))
3757 (org-set-local 'org-default-priority (nth 2 prio)))
3758 (and props (org-set-local 'org-local-properties (nreverse props)))
3759 (and arch (org-set-local 'org-archive-location arch))
3760 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3761 ;; Process the TODO keywords
3762 (unless kwds
3763 ;; Use the global values as if they had been given locally.
3764 (setq kwds (default-value 'org-todo-keywords))
3765 (if (stringp (car kwds))
3766 (setq kwds (list (cons org-todo-interpretation
3767 (default-value 'org-todo-keywords)))))
3768 (setq kwds (reverse kwds)))
3769 (setq kwds (nreverse kwds))
3770 (let (inter kws)
3771 (while (setq kws (pop kwds))
3772 (setq inter (pop kws) sep (member "|" kws)
3773 kws1 (delete "|" (copy-sequence kws))
3774 hw (car kws1)
3775 dws (if sep (cdr sep) (last kws1))
3776 tail (list inter hw (car dws) (org-last dws)))
3777 (add-to-list 'org-todo-heads hw 'append)
3778 (push kws1 org-todo-sets)
3779 (setq org-done-keywords (append org-done-keywords dws nil))
3780 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3781 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3782 (setq org-todo-sets (nreverse org-todo-sets)
3783 org-todo-kwd-alist (nreverse org-todo-kwd-alist)))
3784 ;; Process the constants
3785 (when const
3786 (let (e cst)
3787 (while (setq e (pop const))
3788 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3789 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3790 (setq org-table-formula-constants-local cst)))
3792 ;; Process the tags.
3793 (when tags
3794 (let (e tgs)
3795 (while (setq e (pop tags))
3796 (cond
3797 ((equal e "{") (push '(:startgroup) tgs))
3798 ((equal e "}") (push '(:endgroup) tgs))
3799 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3800 (push (cons (match-string 1 e)
3801 (string-to-char (match-string 2 e)))
3802 tgs))
3803 (t (push (list e) tgs))))
3804 (org-set-local 'org-tag-alist nil)
3805 (while (setq e (pop tgs))
3806 (or (and (stringp (car e))
3807 (assoc (car e) org-tag-alist))
3808 (push e org-tag-alist))))))
3810 ;; Compute the regular expressions and other local variables
3811 (if (not org-done-keywords)
3812 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3813 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3814 (length org-scheduled-string)))
3815 org-drawer-regexp
3816 (concat "^[ \t]*:\\("
3817 (mapconcat 'regexp-quote org-drawers "\\|")
3818 "\\):[ \t]*$")
3819 org-not-done-keywords
3820 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3821 org-todo-regexp
3822 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3823 "\\|") "\\)\\>")
3824 org-not-done-regexp
3825 (concat "\\<\\("
3826 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3827 "\\)\\>")
3828 org-todo-line-regexp
3829 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3830 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3831 "\\)\\>\\)?[ \t]*\\(.*\\)")
3832 org-nl-done-regexp
3833 (concat "\n\\*+[ \t]+"
3834 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3835 "\\)" "\\>")
3836 org-todo-line-tags-regexp
3837 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3838 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3839 (org-re
3840 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3841 org-looking-at-done-regexp
3842 (concat "^" "\\(?:"
3843 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3844 "\\>")
3845 org-deadline-regexp (concat "\\<" org-deadline-string)
3846 org-deadline-time-regexp
3847 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3848 org-deadline-line-regexp
3849 (concat "\\<\\(" org-deadline-string "\\).*")
3850 org-scheduled-regexp
3851 (concat "\\<" org-scheduled-string)
3852 org-scheduled-time-regexp
3853 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3854 org-closed-time-regexp
3855 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3856 org-keyword-time-regexp
3857 (concat "\\<\\(" org-scheduled-string
3858 "\\|" org-deadline-string
3859 "\\|" org-closed-string
3860 "\\|" org-archived-string
3861 "\\|" org-clock-string "\\)"
3862 " *[[<]\\([^]>]+\\)[]>]")
3863 org-keyword-time-not-clock-regexp
3864 (concat "\\<\\(" org-scheduled-string
3865 "\\|" org-deadline-string
3866 "\\|" org-closed-string
3867 "\\|" org-archived-string
3868 "\\)"
3869 " *[[<]\\([^]>]+\\)[]>]")
3870 org-maybe-keyword-time-regexp
3871 (concat "\\(\\<\\(" org-scheduled-string
3872 "\\|" org-deadline-string
3873 "\\|" org-closed-string
3874 "\\|" org-archived-string
3875 "\\|" org-clock-string "\\)\\)?"
3876 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3877 org-planning-or-clock-line-re
3878 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3879 "\\|" org-deadline-string
3880 "\\|" org-closed-string "\\|" org-clock-string
3881 "\\|" org-archived-string "\\)\\>\\)")
3884 (org-set-font-lock-defaults)))
3887 ;;; Some variables ujsed in various places
3889 (defvar org-window-configuration nil
3890 "Used in various places to store a window configuration.")
3891 (defvar org-finish-function nil
3892 "Function to be called when `C-c C-c' is used.
3893 This is for getting out of special buffers like remember.")
3895 ;;; Foreign variables, to inform the compiler
3897 ;; XEmacs only
3898 (defvar outline-mode-menu-heading)
3899 (defvar outline-mode-menu-show)
3900 (defvar outline-mode-menu-hide)
3901 (defvar zmacs-regions) ; XEmacs regions
3902 ;; Emacs only
3903 (defvar mark-active)
3905 ;; Packages that org-mode interacts with
3906 (defvar calc-embedded-close-formula)
3907 (defvar calc-embedded-open-formula)
3908 (defvar font-lock-unfontify-region-function)
3909 (defvar org-goto-start-pos)
3910 (defvar vm-message-pointer)
3911 (defvar vm-folder-directory)
3912 (defvar wl-summary-buffer-elmo-folder)
3913 (defvar wl-summary-buffer-folder-name)
3914 (defvar gnus-other-frame-object)
3915 (defvar gnus-group-name)
3916 (defvar gnus-article-current)
3917 (defvar w3m-current-url)
3918 (defvar w3m-current-title)
3919 (defvar mh-progs)
3920 (defvar mh-current-folder)
3921 (defvar mh-show-folder-buffer)
3922 (defvar mh-index-folder)
3923 (defvar mh-searcher)
3924 (defvar calendar-mode-map)
3925 (defvar Info-current-file)
3926 (defvar Info-current-node)
3927 (defvar texmathp-why)
3928 (defvar remember-save-after-remembering)
3929 (defvar remember-data-file)
3930 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3931 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3932 (defvar org-latex-regexps)
3933 (defvar constants-unit-system)
3935 (defvar original-date) ; dynamically scoped in calendar.el does scope this
3937 ;; FIXME: Occasionally check by commenting these, to make sure
3938 ;; no other functions uses these, forgetting to let-bind them.
3939 (defvar entry)
3940 (defvar state)
3941 (defvar last-state)
3942 (defvar date)
3943 (defvar description)
3946 ;; Defined somewhere in this file, but used before definition.
3947 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3948 (defvar org-agenda-buffer-name)
3949 (defvar org-agenda-undo-list)
3950 (defvar org-agenda-pending-undo-list)
3951 (defvar org-agenda-overriding-header)
3952 (defvar orgtbl-mode)
3953 (defvar org-html-entities)
3954 (defvar org-struct-menu)
3955 (defvar org-org-menu)
3956 (defvar org-tbl-menu)
3957 (defvar org-agenda-keymap)
3958 (defvar org-category-table)
3960 ;;;; Emacs/XEmacs compatibility
3962 ;; Overlay compatibility functions
3963 (defun org-make-overlay (beg end &optional buffer)
3964 (if (featurep 'xemacs)
3965 (make-extent beg end buffer)
3966 (make-overlay beg end buffer)))
3967 (defun org-delete-overlay (ovl)
3968 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
3969 (defun org-detach-overlay (ovl)
3970 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
3971 (defun org-move-overlay (ovl beg end &optional buffer)
3972 (if (featurep 'xemacs)
3973 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
3974 (move-overlay ovl beg end buffer)))
3975 (defun org-overlay-put (ovl prop value)
3976 (if (featurep 'xemacs)
3977 (set-extent-property ovl prop value)
3978 (overlay-put ovl prop value)))
3979 (defun org-overlay-display (ovl text &optional face evap)
3980 "Make overlay OVL display TEXT with face FACE."
3981 (if (featurep 'xemacs)
3982 (let ((gl (make-glyph text)))
3983 (and face (set-glyph-face gl face))
3984 (set-extent-property ovl 'invisible t)
3985 (set-extent-property ovl 'end-glyph gl))
3986 (overlay-put ovl 'display text)
3987 (if face (overlay-put ovl 'face face))
3988 (if evap (overlay-put ovl 'evaporate t))))
3989 (defun org-overlay-before-string (ovl text &optional face evap)
3990 "Make overlay OVL display TEXT with face FACE."
3991 (if (featurep 'xemacs)
3992 (let ((gl (make-glyph text)))
3993 (and face (set-glyph-face gl face))
3994 (set-extent-property ovl 'begin-glyph gl))
3995 (if face (org-add-props text nil 'face face))
3996 (overlay-put ovl 'before-string text)
3997 (if evap (overlay-put ovl 'evaporate t))))
3998 (defun org-overlay-get (ovl prop)
3999 (if (featurep 'xemacs)
4000 (extent-property ovl prop)
4001 (overlay-get ovl prop)))
4002 (defun org-overlays-at (pos)
4003 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4004 ;; FIXME: this is currently not used
4005 (defun org-overlays-in (&optional start end)
4006 (if (featurep 'xemacs)
4007 (extent-list nil start end)
4008 (overlays-in start end)))
4009 (defun org-overlay-start (o)
4010 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4011 (defun org-overlay-end (o)
4012 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4013 ;; FIXME: this is currently not used
4014 (defun org-find-overlays (prop &optional pos delete)
4015 "Find all overlays specifying PROP at POS or point.
4016 If DELETE is non-nil, delete all those overlays."
4017 (let ((overlays (org-overlays-at (or pos (point))))
4018 ov found)
4019 (while (setq ov (pop overlays))
4020 (if (org-overlay-get ov prop)
4021 (if delete (org-delete-overlay ov) (push ov found))))
4022 found))
4024 ;; Region compatibility
4026 (defun org-add-hook (hook function &optional append local)
4027 "Add-hook, compatible with both Emacsen."
4028 (if (and local (featurep 'xemacs))
4029 (add-local-hook hook function append)
4030 (add-hook hook function append local)))
4032 (defvar org-ignore-region nil
4033 "To temporarily disable the active region.")
4035 (defun org-region-active-p ()
4036 "Is `transient-mark-mode' on and the region active?
4037 Works on both Emacs and XEmacs."
4038 (if org-ignore-region
4040 (if (featurep 'xemacs)
4041 (and zmacs-regions (region-active-p))
4042 (and transient-mark-mode mark-active))))
4044 ;; Invisibility compatibility
4046 (defun org-add-to-invisibility-spec (arg)
4047 "Add elements to `buffer-invisibility-spec'.
4048 See documentation for `buffer-invisibility-spec' for the kind of elements
4049 that can be added."
4050 (cond
4051 ((fboundp 'add-to-invisibility-spec)
4052 (add-to-invisibility-spec arg))
4053 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4054 (setq buffer-invisibility-spec (list arg)))
4056 (setq buffer-invisibility-spec
4057 (cons arg buffer-invisibility-spec)))))
4059 (defun org-remove-from-invisibility-spec (arg)
4060 "Remove elements from `buffer-invisibility-spec'."
4061 (if (fboundp 'remove-from-invisibility-spec)
4062 (remove-from-invisibility-spec arg)
4063 (if (consp buffer-invisibility-spec)
4064 (setq buffer-invisibility-spec
4065 (delete arg buffer-invisibility-spec)))))
4067 ;; FIXME: this is currently not used
4068 (defun org-in-invisibility-spec-p (arg)
4069 "Is ARG a member of `buffer-invisibility-spec'?"
4070 (if (consp buffer-invisibility-spec)
4071 (member arg buffer-invisibility-spec)
4072 nil))
4074 ;;;; Define the Org-mode
4076 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4077 (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."))
4080 ;; We use a before-change function to check if a table might need
4081 ;; an update.
4082 (defvar org-table-may-need-update t
4083 "Indicates that a table might need an update.
4084 This variable is set by `org-before-change-function'.
4085 `org-table-align' sets it back to nil.")
4086 (defvar org-mode-map)
4087 (defvar org-mode-hook nil)
4088 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4089 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4090 (defvar org-table-buffer-is-an nil)
4093 ;;;###autoload
4094 (define-derived-mode org-mode outline-mode "Org"
4095 "Outline-based notes management and organizer, alias
4096 \"Carsten's outline-mode for keeping track of everything.\"
4098 Org-mode develops organizational tasks around a NOTES file which
4099 contains information about projects as plain text. Org-mode is
4100 implemented on top of outline-mode, which is ideal to keep the content
4101 of large files well structured. It supports ToDo items, deadlines and
4102 time stamps, which magically appear in the diary listing of the Emacs
4103 calendar. Tables are easily created with a built-in table editor.
4104 Plain text URL-like links connect to websites, emails (VM), Usenet
4105 messages (Gnus), BBDB entries, and any files related to the project.
4106 For printing and sharing of notes, an Org-mode file (or a part of it)
4107 can be exported as a structured ASCII or HTML file.
4109 The following commands are available:
4111 \\{org-mode-map}"
4113 ;; Get rid of Outline menus, they are not needed
4114 ;; Need to do this here because define-derived-mode sets up
4115 ;; the keymap so late. Still, it is a waste to call this each time
4116 ;; we switch another buffer into org-mode.
4117 (if (featurep 'xemacs)
4118 (when (boundp 'outline-mode-menu-heading)
4119 ;; Assume this is Greg's port, it used easymenu
4120 (easy-menu-remove outline-mode-menu-heading)
4121 (easy-menu-remove outline-mode-menu-show)
4122 (easy-menu-remove outline-mode-menu-hide))
4123 (define-key org-mode-map [menu-bar headings] 'undefined)
4124 (define-key org-mode-map [menu-bar hide] 'undefined)
4125 (define-key org-mode-map [menu-bar show] 'undefined))
4127 (easy-menu-add org-org-menu)
4128 (easy-menu-add org-tbl-menu)
4129 (org-install-agenda-files-menu)
4130 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4131 (org-add-to-invisibility-spec '(org-cwidth))
4132 (when (featurep 'xemacs)
4133 (org-set-local 'line-move-ignore-invisible t))
4134 (org-set-local 'outline-regexp "\\*+ ")
4135 (setq outline-level 'org-outline-level)
4136 (when (and org-ellipsis (stringp org-ellipsis)
4137 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table))
4138 (unless org-display-table
4139 (setq org-display-table (make-display-table)))
4140 (set-display-table-slot org-display-table
4141 4 (string-to-vector org-ellipsis))
4142 (setq buffer-display-table org-display-table))
4143 (org-set-regexps-and-options)
4144 ;; Calc embedded
4145 (org-set-local 'calc-embedded-open-mode "# ")
4146 (modify-syntax-entry ?# "<")
4147 (modify-syntax-entry ?@ "w")
4148 (if org-startup-truncated (setq truncate-lines t))
4149 (org-set-local 'font-lock-unfontify-region-function
4150 'org-unfontify-region)
4151 ;; Activate before-change-function
4152 (org-set-local 'org-table-may-need-update t)
4153 (org-add-hook 'before-change-functions 'org-before-change-function nil
4154 'local)
4155 ;; Check for running clock before killing a buffer
4156 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4157 ;; Paragraphs and auto-filling
4158 (org-set-autofill-regexps)
4159 (setq indent-line-function 'org-indent-line-function)
4160 (org-update-radio-target-regexp)
4162 ;; Comment characters
4163 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4164 (org-set-local 'comment-padding " ")
4166 ;; Make isearch reveal context
4167 (if (or (featurep 'xemacs)
4168 (not (boundp 'outline-isearch-open-invisible-function)))
4169 ;; Emacs 21 and XEmacs make use of the hook
4170 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4171 ;; Emacs 22 deals with this through a special variable
4172 (org-set-local 'outline-isearch-open-invisible-function
4173 (lambda (&rest ignore) (org-show-context 'isearch))))
4175 ;; If empty file that did not turn on org-mode automatically, make it to.
4176 (if (and org-insert-mode-line-in-empty-file
4177 (interactive-p)
4178 (= (point-min) (point-max)))
4179 (insert "# -*- mode: org -*-\n\n"))
4181 (unless org-inhibit-startup
4182 (when org-startup-align-all-tables
4183 (let ((bmp (buffer-modified-p)))
4184 (org-table-map-tables 'org-table-align)
4185 (set-buffer-modified-p bmp)))
4186 (org-cycle-hide-drawers 'all)
4187 (cond
4188 ((eq org-startup-folded t)
4189 (org-cycle '(4)))
4190 ((eq org-startup-folded 'content)
4191 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4192 (org-cycle '(4)) (org-cycle '(4)))))))
4194 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4196 (defsubst org-call-with-arg (command arg)
4197 "Call COMMAND interactively, but pretend prefix are was ARG."
4198 (let ((current-prefix-arg arg)) (call-interactively command)))
4200 (defsubst org-current-line (&optional pos)
4201 (save-excursion
4202 (and pos (goto-char pos))
4203 ;; works also in narrowed buffer, because we start at 1, not point-min
4204 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4206 (defun org-current-time ()
4207 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4208 (if (> org-time-stamp-rounding-minutes 0)
4209 (let ((r org-time-stamp-rounding-minutes)
4210 (time (decode-time)))
4211 (apply 'encode-time
4212 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4213 (nthcdr 2 time))))
4214 (current-time)))
4216 (defun org-add-props (string plist &rest props)
4217 "Add text properties to entire string, from beginning to end.
4218 PLIST may be a list of properties, PROPS are individual properties and values
4219 that will be added to PLIST. Returns the string that was modified."
4220 (add-text-properties
4221 0 (length string) (if props (append plist props) plist) string)
4222 string)
4223 (put 'org-add-props 'lisp-indent-function 2)
4226 ;;;; Font-Lock stuff, including the activators
4228 (defvar org-mouse-map (make-sparse-keymap))
4229 (org-defkey org-mouse-map
4230 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4231 (org-defkey org-mouse-map
4232 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4233 (when org-mouse-1-follows-link
4234 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4235 (when org-tab-follows-link
4236 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4237 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4238 (when org-return-follows-link
4239 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4240 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4242 (require 'font-lock)
4244 (defconst org-non-link-chars "]\t\n\r<>")
4245 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4246 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4247 (defvar org-link-re-with-space nil
4248 "Matches a link with spaces, optional angular brackets around it.")
4249 (defvar org-link-re-with-space2 nil
4250 "Matches a link with spaces, optional angular brackets around it.")
4251 (defvar org-angle-link-re nil
4252 "Matches link with angular brackets, spaces are allowed.")
4253 (defvar org-plain-link-re nil
4254 "Matches plain link, without spaces.")
4255 (defvar org-bracket-link-regexp nil
4256 "Matches a link in double brackets.")
4257 (defvar org-bracket-link-analytic-regexp nil
4258 "Regular expression used to analyze links.
4259 Here is what the match groups contain after a match:
4260 1: http:
4261 2: http
4262 3: path
4263 4: [desc]
4264 5: desc")
4265 (defvar org-any-link-re nil
4266 "Regular expression matching any link.")
4268 (defun org-make-link-regexps ()
4269 "Update the link regular expressions.
4270 This should be called after the variable `org-link-types' has changed."
4271 (setq org-link-re-with-space
4272 (concat
4273 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4274 "\\([^" org-non-link-chars " ]"
4275 "[^" org-non-link-chars "]*"
4276 "[^" org-non-link-chars " ]\\)>?")
4277 org-link-re-with-space2
4278 (concat
4279 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4280 "\\([^" org-non-link-chars " ]"
4281 "[^]\t\n\r]*"
4282 "[^" org-non-link-chars " ]\\)>?")
4283 org-angle-link-re
4284 (concat
4285 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4286 "\\([^" org-non-link-chars " ]"
4287 "[^" org-non-link-chars "]*"
4288 "\\)>")
4289 org-plain-link-re
4290 (concat
4291 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4292 "\\([^]\t\n\r<>,;() ]+\\)")
4293 org-bracket-link-regexp
4294 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4295 org-bracket-link-analytic-regexp
4296 (concat
4297 "\\[\\["
4298 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4299 "\\([^]]+\\)"
4300 "\\]"
4301 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4302 "\\]")
4303 org-any-link-re
4304 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4305 org-angle-link-re "\\)\\|\\("
4306 org-plain-link-re "\\)")))
4308 (org-make-link-regexps)
4310 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4311 "Regular expression for fast time stamp matching.")
4312 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4313 "Regular expression for fast time stamp matching.")
4314 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4315 "Regular expression matching time strings for analysis.
4316 This one does not require the space after the date.")
4317 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4318 "Regular expression matching time strings for analysis.")
4319 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,11\\}>")
4320 "Regular expression matching time stamps, with groups.")
4321 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,11\\}[]>]")
4322 "Regular expression matching time stamps (also [..]), with groups.")
4323 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4324 "Regular expression matching a time stamp range.")
4325 (defconst org-tr-regexp-both
4326 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4327 "Regular expression matching a time stamp range.")
4328 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4329 org-ts-regexp "\\)?")
4330 "Regular expression matching a time stamp or time stamp range.")
4331 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4332 org-ts-regexp-both "\\)?")
4333 "Regular expression matching a time stamp or time stamp range.
4334 The time stamps may be either active or inactive.")
4336 (defvar org-emph-face nil)
4338 (defun org-do-emphasis-faces (limit)
4339 "Run through the buffer and add overlays to links."
4340 (let (rtn)
4341 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4342 (if (not (= (char-after (match-beginning 3))
4343 (char-after (match-beginning 4))))
4344 (progn
4345 (setq rtn t)
4346 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4347 'face
4348 (nth 1 (assoc (match-string 3)
4349 org-emphasis-alist)))
4350 (add-text-properties (match-beginning 2) (match-end 2)
4351 '(font-lock-multiline t))
4352 (backward-char 1))))
4353 rtn))
4355 (defun org-emphasize (&optional char)
4356 "Insert or change an emphasis, i.e. a font like bold or italic.
4357 If there is an active region, change that region to a new emphasis.
4358 If there is no region, just insert the marker characters and position
4359 the cursor between them.
4360 CHAR should be either the marker character, or the first character of the
4361 HTML tag associated with that emphasis. If CHAR is a space, the means
4362 to remove the emphasis of the selected region.
4363 If char is not given (for example in an interactive call) it
4364 will be prompted for."
4365 (interactive)
4366 (let ((eal org-emphasis-alist) e det
4367 (erc org-emphasis-regexp-components)
4368 (prompt "")
4369 (string "") beg end move tag c s)
4370 (if (org-region-active-p)
4371 (setq beg (region-beginning) end (region-end)
4372 string (buffer-substring beg end))
4373 (setq move t))
4375 (while (setq e (pop eal))
4376 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4377 c (aref tag 0))
4378 (push (cons c (string-to-char (car e))) det)
4379 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4380 (substring tag 1)))))
4381 (unless char
4382 (message "%s" (concat "Emphasis marker or tag:" prompt))
4383 (setq char (read-char-exclusive)))
4384 (setq char (or (cdr (assoc char det)) char))
4385 (if (equal char ?\ )
4386 (setq s "" move nil)
4387 (unless (assoc (char-to-string char) org-emphasis-alist)
4388 (error "No such emphasis marker: \"%c\"" char))
4389 (setq s (char-to-string char)))
4390 (while (and (> (length string) 1)
4391 (equal (substring string 0 1) (substring string -1))
4392 (assoc (substring string 0 1) org-emphasis-alist))
4393 (setq string (substring string 1 -1)))
4394 (setq string (concat s string s))
4395 (if beg (delete-region beg end))
4396 (unless (or (bolp)
4397 (string-match (concat "[" (nth 0 erc) "\n]")
4398 (char-to-string (char-before (point)))))
4399 (insert " "))
4400 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4401 (char-to-string (char-after (point))))
4402 (insert " ") (backward-char 1))
4403 (insert string)
4404 (and move (backward-char 1))))
4406 (defun org-activate-plain-links (limit)
4407 "Run through the buffer and add overlays to links."
4408 (catch 'exit
4409 (let (f)
4410 (while (re-search-forward org-plain-link-re limit t)
4411 (setq f (get-text-property (match-beginning 0) 'face))
4412 (if (or (eq f 'org-tag)
4413 (and (listp f) (memq 'org-tag f)))
4415 (add-text-properties (match-beginning 0) (match-end 0)
4416 (list 'mouse-face 'highlight
4417 'rear-nonsticky t
4418 'keymap org-mouse-map
4420 (throw 'exit t))))))
4422 (defun org-activate-angle-links (limit)
4423 "Run through the buffer and add overlays to links."
4424 (if (re-search-forward org-angle-link-re limit t)
4425 (progn
4426 (add-text-properties (match-beginning 0) (match-end 0)
4427 (list 'mouse-face 'highlight
4428 'rear-nonsticky t
4429 'keymap org-mouse-map
4431 t)))
4433 (defmacro org-maybe-intangible (props)
4434 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
4435 In emacs 21, invisible text is not avoided by the command loop, so the
4436 intangible property is needed to make sure point skips this text.
4437 In Emacs 22, this is not necessary. The intangible text property has
4438 led to problems with flyspell. These problems are fixed in flyspell.el,
4439 but we still avoid setting the property in Emacs 22 and later.
4440 We use a macro so that the test can happen at compilation time."
4441 (if (< emacs-major-version 22)
4442 `(append '(intangible t) ,props)
4443 props))
4445 (defun org-activate-bracket-links (limit)
4446 "Run through the buffer and add overlays to bracketed links."
4447 (if (re-search-forward org-bracket-link-regexp limit t)
4448 (let* ((help (concat "LINK: "
4449 (org-match-string-no-properties 1)))
4450 ;; FIXME: above we should remove the escapes.
4451 ;; but that requires another match, protecting match data,
4452 ;; a lot of overhead for font-lock.
4453 (ip (org-maybe-intangible
4454 (list 'invisible 'org-link 'rear-nonsticky t
4455 'keymap org-mouse-map 'mouse-face 'highlight
4456 'help-echo help)))
4457 (vp (list 'rear-nonsticky t
4458 'keymap org-mouse-map 'mouse-face 'highlight
4459 'help-echo help)))
4460 ;; We need to remove the invisible property here. Table narrowing
4461 ;; may have made some of this invisible.
4462 (remove-text-properties (match-beginning 0) (match-end 0)
4463 '(invisible nil))
4464 (if (match-end 3)
4465 (progn
4466 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4467 (add-text-properties (match-beginning 3) (match-end 3) vp)
4468 (add-text-properties (match-end 3) (match-end 0) ip))
4469 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4470 (add-text-properties (match-beginning 1) (match-end 1) vp)
4471 (add-text-properties (match-end 1) (match-end 0) ip))
4472 t)))
4474 (defun org-activate-dates (limit)
4475 "Run through the buffer and add overlays to dates."
4476 (if (re-search-forward org-tsr-regexp-both limit t)
4477 (progn
4478 (add-text-properties (match-beginning 0) (match-end 0)
4479 (list 'mouse-face 'highlight
4480 'rear-nonsticky t
4481 'keymap org-mouse-map))
4482 (when org-display-custom-times
4483 (if (match-end 3)
4484 (org-display-custom-time (match-beginning 3) (match-end 3)))
4485 (org-display-custom-time (match-beginning 1) (match-end 1)))
4486 t)))
4488 (defvar org-target-link-regexp nil
4489 "Regular expression matching radio targets in plain text.")
4490 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4491 "Regular expression matching a link target.")
4492 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4493 "Regular expression matching a radio target.")
4494 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4495 "Regular expression matching any target.")
4497 (defun org-activate-target-links (limit)
4498 "Run through the buffer and add overlays to target matches."
4499 (when org-target-link-regexp
4500 (let ((case-fold-search t))
4501 (if (re-search-forward org-target-link-regexp limit t)
4502 (progn
4503 (add-text-properties (match-beginning 0) (match-end 0)
4504 (list 'mouse-face 'highlight
4505 'rear-nonsticky t
4506 'keymap org-mouse-map
4507 'help-echo "Radio target link"
4508 'org-linked-text t))
4509 t)))))
4511 (defun org-update-radio-target-regexp ()
4512 "Find all radio targets in this file and update the regular expression."
4513 (interactive)
4514 (when (memq 'radio org-activate-links)
4515 (setq org-target-link-regexp
4516 (org-make-target-link-regexp (org-all-targets 'radio)))
4517 (org-restart-font-lock)))
4519 (defun org-hide-wide-columns (limit)
4520 (let (s e)
4521 (setq s (text-property-any (point) (or limit (point-max))
4522 'org-cwidth t))
4523 (when s
4524 (setq e (next-single-property-change s 'org-cwidth))
4525 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4526 (goto-char e)
4527 t)))
4529 (defun org-restart-font-lock ()
4530 "Restart font-lock-mode, to force refontification."
4531 (when (and (boundp 'font-lock-mode) font-lock-mode)
4532 ;; FIXME: Could font-lock-fontify-buffer be enough???
4533 (font-lock-mode -1)
4534 (font-lock-mode 1)))
4536 (defun org-all-targets (&optional radio)
4537 "Return a list of all targets in this file.
4538 With optional argument RADIO, only find radio targets."
4539 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4540 rtn)
4541 (save-excursion
4542 (goto-char (point-min))
4543 (while (re-search-forward re nil t)
4544 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4545 rtn)))
4547 (defun org-make-target-link-regexp (targets)
4548 "Make regular expression matching all strings in TARGETS.
4549 The regular expression finds the targets also if there is a line break
4550 between words."
4551 (and targets
4552 (concat
4553 "\\<\\("
4554 (mapconcat
4555 (lambda (x)
4556 (while (string-match " +" x)
4557 (setq x (replace-match "\\s-+" t t x)))
4559 targets
4560 "\\|")
4561 "\\)\\>")))
4563 (defun org-activate-tags (limit)
4564 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4565 (progn
4566 (add-text-properties (match-beginning 1) (match-end 1)
4567 (list 'mouse-face 'highlight
4568 'rear-nonsticky t
4569 'keymap org-mouse-map))
4570 t)))
4572 (defun org-outline-level ()
4573 (save-excursion
4574 (looking-at outline-regexp)
4575 (if (match-beginning 1)
4576 (+ (org-get-string-indentation (match-string 1)) 1000)
4577 (1- (- (match-end 0) (match-beginning 0))))))
4579 (defvar org-font-lock-keywords nil)
4581 (defconst org-property-re "^[ \t]*\\(:\\([a-zA-Z_0-9]+\\):\\)[ \t]*\\(\\S-.*\\)"
4582 "Regular expression matching a property line.")
4584 (defun org-set-font-lock-defaults ()
4585 (let* ((em org-fontify-emphasized-text)
4586 (lk org-activate-links)
4587 (org-font-lock-extra-keywords
4588 ;; Headlines
4589 (list
4590 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4591 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4592 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4593 (1 'org-table))
4594 ;; Links
4595 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4596 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4597 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4598 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4599 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4600 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4601 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4602 '(org-hide-wide-columns (0 nil append))
4603 ;; TODO lines
4604 (list (concat "^\\*+[ \t]+" org-not-done-regexp)
4605 '(1 'org-todo t))
4606 ;; Priorities
4607 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4608 ;; Special keywords
4609 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4610 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4611 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4612 (list (concat "\\<" org-archived-string) '(0 'org-special-keyword t))
4613 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4614 ;; Emphasis
4615 (if em
4616 (if (featurep 'xemacs)
4617 '(org-do-emphasis-faces (0 nil append))
4618 '(org-do-emphasis-faces)))
4619 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
4620 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4621 2 'bold prepend)
4622 (if org-provide-checkbox-statistics
4623 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4624 (0 (org-get-checkbox-statistics-face) t)))
4625 ;; COMMENT
4626 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4627 "\\|" org-quote-string "\\)\\>")
4628 '(1 'org-special-keyword t))
4629 '("^#.*" (0 'font-lock-comment-face t))
4630 ;; DONE
4631 (if org-fontify-done-headline
4632 (list (concat "^[*]+ +\\<\\("
4633 (mapconcat 'regexp-quote org-done-keywords "\\|")
4634 "\\)\\(.*\\)")
4635 '(1 'org-done t) '(2 'org-headline-done t))
4636 (list (concat "^[*]+ +\\<\\("
4637 (mapconcat 'regexp-quote org-done-keywords "\\|")
4638 "\\)\\>")
4639 '(1 'org-done t)))
4640 ;; Code
4641 '("^[ \t]*\\(:.*\\)" (1 'org-code t))
4642 ;; Table
4643 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4644 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4645 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4646 ;; Drawers
4647 (list org-drawer-regexp '(0 'org-special-keyword t))
4648 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4649 ;; Properties
4650 (list org-property-re
4651 '(1 'org-special-keyword t)
4652 '(3 'org-property-value t))
4653 (if org-format-transports-properties-p
4654 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4655 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
4657 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4658 ;; Now set the full font-lock-keywords
4659 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4660 (org-set-local 'font-lock-defaults
4661 '(org-font-lock-keywords t nil nil backward-paragraph))
4662 (kill-local-variable 'font-lock-keywords) nil))
4664 (defvar org-m nil)
4665 (defvar org-l nil)
4666 (defvar org-f nil)
4667 (defun org-get-level-face (n)
4668 "Get the right face for match N in font-lock matching of healdines."
4669 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4670 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4671 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4672 (cond
4673 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4674 ((eq n 2) org-f)
4675 (t (if org-level-color-stars-only nil org-f))))
4677 (defun org-unfontify-region (beg end &optional maybe_loudly)
4678 "Remove fontification and activation overlays from links."
4679 (font-lock-default-unfontify-region beg end)
4680 (let* ((buffer-undo-list t)
4681 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4682 (inhibit-modification-hooks t)
4683 deactivate-mark buffer-file-name buffer-file-truename)
4684 (remove-text-properties beg end
4685 '(mouse-face t keymap t org-linked-text t
4686 rear-nonsticky t
4687 invisible t intangible t))))
4689 ;;;; Visibility cycling, including org-goto and indirect buffer
4691 ;;; Cycling
4693 (defvar org-cycle-global-status nil)
4694 (make-variable-buffer-local 'org-cycle-global-status)
4695 (defvar org-cycle-subtree-status nil)
4696 (make-variable-buffer-local 'org-cycle-subtree-status)
4698 ;;;###autoload
4699 (defun org-cycle (&optional arg)
4700 "Visibility cycling for Org-mode.
4702 - When this function is called with a prefix argument, rotate the entire
4703 buffer through 3 states (global cycling)
4704 1. OVERVIEW: Show only top-level headlines.
4705 2. CONTENTS: Show all headlines of all levels, but no body text.
4706 3. SHOW ALL: Show everything.
4708 - When point is at the beginning of a headline, rotate the subtree started
4709 by this line through 3 different states (local cycling)
4710 1. FOLDED: Only the main headline is shown.
4711 2. CHILDREN: The main headline and the direct children are shown.
4712 From this state, you can move to one of the children
4713 and zoom in further.
4714 3. SUBTREE: Show the entire subtree, including body text.
4716 - When there is a numeric prefix, go up to a heading with level ARG, do
4717 a `show-subtree' and return to the previous cursor position. If ARG
4718 is negative, go up that many levels.
4720 - When point is not at the beginning of a headline, execute
4721 `indent-relative', like TAB normally does. See the option
4722 `org-cycle-emulate-tab' for details.
4724 - Special case: if point is at the beginning of the buffer and there is
4725 no headline in line 1, this function will act as if called with prefix arg."
4726 (interactive "P")
4727 (let* ((outline-regexp
4728 (if (and (org-mode-p) org-cycle-include-plain-lists)
4729 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4730 outline-regexp))
4731 (bob-special (and org-cycle-global-at-bob (bobp)
4732 (not (looking-at outline-regexp))))
4733 (org-cycle-hook
4734 (if bob-special
4735 (delq 'org-optimize-window-after-visibility-change
4736 (copy-sequence org-cycle-hook))
4737 org-cycle-hook))
4738 (pos (point)))
4740 (if (or bob-special (equal arg '(4)))
4741 ;; special case: use global cycling
4742 (setq arg t))
4744 (cond
4746 ((org-at-table-p 'any)
4747 ;; Enter the table or move to the next field in the table
4748 (or (org-table-recognize-table.el)
4749 (progn
4750 (if arg (org-table-edit-field t)
4751 (org-table-justify-field-maybe)
4752 (call-interactively 'org-table-next-field)))))
4754 ((eq arg t) ;; Global cycling
4756 (cond
4757 ((and (eq last-command this-command)
4758 (eq org-cycle-global-status 'overview))
4759 ;; We just created the overview - now do table of contents
4760 ;; This can be slow in very large buffers, so indicate action
4761 (message "CONTENTS...")
4762 (org-content)
4763 (message "CONTENTS...done")
4764 (setq org-cycle-global-status 'contents)
4765 (run-hook-with-args 'org-cycle-hook 'contents))
4767 ((and (eq last-command this-command)
4768 (eq org-cycle-global-status 'contents))
4769 ;; We just showed the table of contents - now show everything
4770 (show-all)
4771 (message "SHOW ALL")
4772 (setq org-cycle-global-status 'all)
4773 (run-hook-with-args 'org-cycle-hook 'all))
4776 ;; Default action: go to overview
4777 (org-overview)
4778 (message "OVERVIEW")
4779 (setq org-cycle-global-status 'overview)
4780 (run-hook-with-args 'org-cycle-hook 'overview))))
4782 ((and org-drawers org-drawer-regexp
4783 (save-excursion
4784 (beginning-of-line 1)
4785 (looking-at org-drawer-regexp)))
4786 ;; Toggle block visibility
4787 (org-flag-drawer
4788 (not (get-char-property (match-end 0) 'invisible))))
4790 ((integerp arg)
4791 ;; Show-subtree, ARG levels up from here.
4792 (save-excursion
4793 (org-back-to-heading)
4794 (outline-up-heading (if (< arg 0) (- arg)
4795 (- (funcall outline-level) arg)))
4796 (org-show-subtree)))
4798 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4799 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4800 ;; At a heading: rotate between three different views
4801 (org-back-to-heading)
4802 (let ((goal-column 0) eoh eol eos)
4803 ;; First, some boundaries
4804 (save-excursion
4805 (org-back-to-heading)
4806 (save-excursion
4807 (beginning-of-line 2)
4808 (while (and (not (eobp)) ;; this is like `next-line'
4809 (get-char-property (1- (point)) 'invisible))
4810 (beginning-of-line 2)) (setq eol (point)))
4811 (outline-end-of-heading) (setq eoh (point))
4812 (org-end-of-subtree t)
4813 (unless (eobp)
4814 (skip-chars-forward " \t\n")
4815 (beginning-of-line 1) ; in case this is an item
4817 (setq eos (1- (point))))
4818 ;; Find out what to do next and set `this-command'
4819 (cond
4820 ((= eos eoh)
4821 ;; Nothing is hidden behind this heading
4822 (message "EMPTY ENTRY")
4823 (setq org-cycle-subtree-status nil)
4824 (save-excursion
4825 (goto-char eos)
4826 (outline-next-heading)
4827 (if (org-invisible-p) (org-flag-heading nil))))
4828 ((or (>= eol eos)
4829 (not (string-match "\\S-" (buffer-substring eol eos))))
4830 ;; Entire subtree is hidden in one line: open it
4831 (org-show-entry)
4832 (show-children)
4833 (message "CHILDREN")
4834 (save-excursion
4835 (goto-char eos)
4836 (outline-next-heading)
4837 (if (org-invisible-p) (org-flag-heading nil)))
4838 (setq org-cycle-subtree-status 'children)
4839 (run-hook-with-args 'org-cycle-hook 'children))
4840 ((and (eq last-command this-command)
4841 (eq org-cycle-subtree-status 'children))
4842 ;; We just showed the children, now show everything.
4843 (org-show-subtree)
4844 (message "SUBTREE")
4845 (setq org-cycle-subtree-status 'subtree)
4846 (run-hook-with-args 'org-cycle-hook 'subtree))
4848 ;; Default action: hide the subtree.
4849 (hide-subtree)
4850 (message "FOLDED")
4851 (setq org-cycle-subtree-status 'folded)
4852 (run-hook-with-args 'org-cycle-hook 'folded)))))
4854 ;; TAB emulation
4855 (buffer-read-only (org-back-to-heading))
4857 ((org-try-cdlatex-tab))
4859 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4860 (or (not (bolp))
4861 (not (looking-at outline-regexp))))
4862 (call-interactively (global-key-binding "\t")))
4864 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4865 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4866 (or (and (eq org-cycle-emulate-tab 'white)
4867 (= (match-end 0) (point-at-eol)))
4868 (and (eq org-cycle-emulate-tab 'whitestart)
4869 (>= (match-end 0) pos))))
4871 (eq org-cycle-emulate-tab t))
4872 (if (and (looking-at "[ \n\r\t]")
4873 (string-match "^[ \t]*$" (buffer-substring
4874 (point-at-bol) (point))))
4875 (progn
4876 (beginning-of-line 1)
4877 (and (looking-at "[ \t]+") (replace-match ""))))
4878 (call-interactively (global-key-binding "\t")))
4880 (t (save-excursion
4881 (org-back-to-heading)
4882 (org-cycle))))))
4884 ;;;###autoload
4885 (defun org-global-cycle (&optional arg)
4886 "Cycle the global visibility. For details see `org-cycle'."
4887 (interactive "P")
4888 (let ((org-cycle-include-plain-lists
4889 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4890 (if (integerp arg)
4891 (progn
4892 (show-all)
4893 (hide-sublevels arg)
4894 (setq org-cycle-global-status 'contents))
4895 (org-cycle '(4)))))
4897 (defun org-overview ()
4898 "Switch to overview mode, shoing only top-level headlines.
4899 Really, this shows all headlines with level equal or greater than the level
4900 of the first headline in the buffer. This is important, because if the
4901 first headline is not level one, then (hide-sublevels 1) gives confusing
4902 results."
4903 (interactive)
4904 (let ((level (save-excursion
4905 (goto-char (point-min))
4906 (if (re-search-forward (concat "^" outline-regexp) nil t)
4907 (progn
4908 (goto-char (match-beginning 0))
4909 (funcall outline-level))))))
4910 (and level (hide-sublevels level))))
4912 (defun org-content (&optional arg)
4913 "Show all headlines in the buffer, like a table of contents.
4914 With numerical argument N, show content up to level N."
4915 (interactive "P")
4916 (save-excursion
4917 ;; Visit all headings and show their offspring
4918 (and (integerp arg) (org-overview))
4919 (goto-char (point-max))
4920 (catch 'exit
4921 (while (and (progn (condition-case nil
4922 (outline-previous-visible-heading 1)
4923 (error (goto-char (point-min))))
4925 (looking-at outline-regexp))
4926 (if (integerp arg)
4927 (show-children (1- arg))
4928 (show-branches))
4929 (if (bobp) (throw 'exit nil))))))
4932 (defun org-optimize-window-after-visibility-change (state)
4933 "Adjust the window after a change in outline visibility.
4934 This function is the default value of the hook `org-cycle-hook'."
4935 (when (get-buffer-window (current-buffer))
4936 (cond
4937 ; ((eq state 'overview) (org-first-headline-recenter 1))
4938 ; ((eq state 'overview) (org-beginning-of-line))
4939 ((eq state 'content) nil)
4940 ((eq state 'all) nil)
4941 ((eq state 'folded) nil)
4942 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4943 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4946 (defun org-cycle-show-empty-lines (state)
4947 "Show empty lines above all visible headlines.
4948 The region to be covered depends on STATE when called through
4949 `org-cycle-hook'. Lisp program can use t for STATE to get the
4950 entire buffer covered. Note that an empty line is only shown if there
4951 are at least `org-cycle-separator-lines' empty lines before the headeline."
4952 (when (> org-cycle-separator-lines 0)
4953 (save-excursion
4954 (let* ((n org-cycle-separator-lines)
4955 (re (cond
4956 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4957 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4958 (t (let ((ns (number-to-string (- n 2))))
4959 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4960 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4961 beg end)
4962 (cond
4963 ((memq state '(overview contents t))
4964 (setq beg (point-min) end (point-max)))
4965 ((memq state '(children folded))
4966 (setq beg (point) end (progn (org-end-of-subtree t t)
4967 (beginning-of-line 2)
4968 (point)))))
4969 (when beg
4970 (goto-char beg)
4971 (while (re-search-forward re end t)
4972 (if (not (get-char-property (match-end 1) 'invisible))
4973 (outline-flag-region
4974 (match-beginning 1) (match-end 1) nil)))))))
4975 ;; Never hide empty lines at the end of the file.
4976 (save-excursion
4977 (goto-char (point-max))
4978 (outline-previous-heading)
4979 (outline-end-of-heading)
4980 (if (and (looking-at "[ \t\n]+")
4981 (= (match-end 0) (point-max)))
4982 (outline-flag-region (point) (match-end 0) nil))))
4984 (defun org-subtree-end-visible-p ()
4985 "Is the end of the current subtree visible?"
4986 (pos-visible-in-window-p
4987 (save-excursion (org-end-of-subtree t) (point))))
4989 (defun org-first-headline-recenter (&optional N)
4990 "Move cursor to the first headline and recenter the headline.
4991 Optional argument N means, put the headline into the Nth line of the window."
4992 (goto-char (point-min))
4993 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4994 (beginning-of-line)
4995 (recenter (prefix-numeric-value N))))
4997 ;;; Org-goto
4999 (defvar org-goto-window-configuration nil)
5000 (defvar org-goto-marker nil)
5001 (defvar org-goto-map
5002 (let ((map (make-sparse-keymap)))
5003 (let ((cmds '(isearch-forward isearch-backward)) cmd)
5004 (while (setq cmd (pop cmds))
5005 (substitute-key-definition cmd cmd map global-map)))
5006 (org-defkey map "\C-m" 'org-goto-ret)
5007 (org-defkey map [(left)] 'org-goto-left)
5008 (org-defkey map [(right)] 'org-goto-right)
5009 (org-defkey map [(?q)] 'org-goto-quit)
5010 (org-defkey map [(control ?g)] 'org-goto-quit)
5011 (org-defkey map "\C-i" 'org-cycle)
5012 (org-defkey map [(tab)] 'org-cycle)
5013 (org-defkey map [(down)] 'outline-next-visible-heading)
5014 (org-defkey map [(up)] 'outline-previous-visible-heading)
5015 (org-defkey map "n" 'outline-next-visible-heading)
5016 (org-defkey map "p" 'outline-previous-visible-heading)
5017 (org-defkey map "f" 'outline-forward-same-level)
5018 (org-defkey map "b" 'outline-backward-same-level)
5019 (org-defkey map "u" 'outline-up-heading)
5020 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5021 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5022 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5023 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5024 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5025 ;; FIXME: Could we use suppress-keymap?
5026 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
5027 (while l (org-defkey map (int-to-string (pop l)) 'digit-argument)))
5028 map))
5030 (defconst org-goto-help
5031 "Select a location to jump to, press RET
5032 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
5034 (defun org-goto ()
5035 "Go to a different location of the document, keeping current visibility.
5037 When you want to go to a different location in a document, the fastest way
5038 is often to fold the entire buffer and then dive into the tree. This
5039 method has the disadvantage, that the previous location will be folded,
5040 which may not be what you want.
5042 This command works around this by showing a copy of the current buffer in
5043 overview mode. You can dive into the tree in that copy, to find the
5044 location you want to reach. When pressing RET, the command returns to the
5045 original buffer in which the visibility is still unchanged. It then jumps
5046 to the new location, making it and the headline hierarchy above it visible."
5047 (interactive)
5048 (let* ((org-goto-start-pos (point))
5049 (selected-point
5050 (org-get-location (current-buffer) org-goto-help)))
5051 (if selected-point
5052 (progn
5053 (org-mark-ring-push org-goto-start-pos)
5054 (goto-char selected-point)
5055 (if (or (org-invisible-p) (org-invisible-p2))
5056 (org-show-context 'org-goto)))
5057 (error "Quit"))))
5059 (defvar org-selected-point nil) ; dynamically scoped parameter
5061 (defun org-get-location (buf help)
5062 "Let the user select a location in the Org-mode buffer BUF.
5063 This function uses a recursive edit. It returns the selected position
5064 or nil."
5065 (let (org-selected-point)
5066 (save-excursion
5067 (save-window-excursion
5068 (delete-other-windows)
5069 (switch-to-buffer (get-buffer-create "*org-goto*"))
5070 (with-output-to-temp-buffer "*Help*"
5071 (princ help))
5072 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5073 (setq buffer-read-only nil)
5074 (erase-buffer)
5075 (insert-buffer-substring buf)
5076 (let ((org-startup-truncated t)
5077 (org-startup-folded t)
5078 (org-startup-align-all-tables nil))
5079 (org-mode))
5080 (setq buffer-read-only t)
5081 (if (and (boundp 'org-goto-start-pos)
5082 (integer-or-marker-p org-goto-start-pos))
5083 (let ((org-show-hierarchy-above t)
5084 (org-show-siblings t)
5085 (org-show-following-heading t))
5086 (goto-char org-goto-start-pos)
5087 (and (org-invisible-p) (org-show-context)))
5088 (goto-char (point-min)))
5089 (org-beginning-of-line)
5090 (message "Select location and press RET")
5091 ;; now we make sure that during selection, ony very few keys work
5092 ;; and that it is impossible to switch to another window.
5093 (let ((gm (current-global-map))
5094 (overriding-local-map org-goto-map))
5095 (unwind-protect
5096 (progn
5097 (use-global-map org-goto-map)
5098 (recursive-edit))
5099 (use-global-map gm)))))
5100 (kill-buffer "*org-goto*")
5101 org-selected-point))
5103 (defun org-goto-ret (&optional arg)
5104 "Finish `org-goto' by going to the new location."
5105 (interactive "P")
5106 (setq org-selected-point (point)
5107 current-prefix-arg arg)
5108 (throw 'exit nil))
5110 (defun org-goto-left ()
5111 "Finish `org-goto' by going to the new location."
5112 (interactive)
5113 (if (org-on-heading-p)
5114 (progn
5115 (beginning-of-line 1)
5116 (setq org-selected-point (point)
5117 current-prefix-arg (- (match-end 0) (match-beginning 0)))
5118 (throw 'exit nil))
5119 (error "Not on a heading")))
5121 (defun org-goto-right ()
5122 "Finish `org-goto' by going to the new location."
5123 (interactive)
5124 (if (org-on-heading-p)
5125 (progn
5126 (outline-end-of-subtree)
5127 (or (eobp) (forward-char 1))
5128 (setq org-selected-point (point)
5129 current-prefix-arg (- (match-end 0) (match-beginning 0)))
5130 (throw 'exit nil))
5131 (error "Not on a heading")))
5133 (defun org-goto-quit ()
5134 "Finish `org-goto' without cursor motion."
5135 (interactive)
5136 (setq org-selected-point nil)
5137 (throw 'exit nil))
5139 ;;; Indirect buffer display of subtrees
5141 (defvar org-indirect-dedicated-frame nil
5142 "This is the frame being used for indirect tree display.")
5143 (defvar org-last-indirect-buffer nil)
5145 (defun org-tree-to-indirect-buffer (&optional arg)
5146 "Create indirect buffer and narrow it to current subtree.
5147 With numerical prefix ARG, go up to this level and then take that tree.
5148 If ARG is negative, go up that many levels.
5149 Normally this command removes the indirect buffer previously made
5150 with this command. However, when called with a C-u prefix, the last buffer
5151 is kept so that you can work with several indirect buffers at the same time.
5152 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5153 requests that a new frame be made for the new buffer, so that the dedicated
5154 frame is not changed."
5155 (interactive "P")
5156 (let ((cbuf (current-buffer))
5157 (cwin (selected-window))
5158 (pos (point))
5159 beg end level heading ibuf)
5160 (save-excursion
5161 (org-back-to-heading t)
5162 (when (numberp arg)
5163 (setq level (org-outline-level))
5164 (if (< arg 0) (setq arg (+ level arg)))
5165 (while (> (setq level (org-outline-level)) arg)
5166 (outline-up-heading 1 t)))
5167 (setq beg (point)
5168 heading (org-get-heading))
5169 (org-end-of-subtree t) (setq end (point)))
5170 (if (and (not arg)
5171 (buffer-live-p org-last-indirect-buffer))
5172 (kill-buffer org-last-indirect-buffer))
5173 (setq ibuf (org-get-indirect-buffer cbuf)
5174 org-last-indirect-buffer ibuf)
5175 (cond
5176 ((or (eq org-indirect-buffer-display 'new-frame)
5177 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5178 (select-frame (make-frame))
5179 (delete-other-windows)
5180 (switch-to-buffer ibuf)
5181 (org-set-frame-title heading))
5182 ((eq org-indirect-buffer-display 'dedicated-frame)
5183 (raise-frame
5184 (select-frame (or (and org-indirect-dedicated-frame
5185 (frame-live-p org-indirect-dedicated-frame)
5186 org-indirect-dedicated-frame)
5187 (setq org-indirect-dedicated-frame (make-frame)))))
5188 (delete-other-windows)
5189 (switch-to-buffer ibuf)
5190 (org-set-frame-title (concat "Indirect: " heading)))
5191 ((eq org-indirect-buffer-display 'current-window)
5192 (switch-to-buffer ibuf))
5193 ((eq org-indirect-buffer-display 'other-window)
5194 (pop-to-buffer ibuf))
5195 (t (error "Invalid value.")))
5196 (if (featurep 'xemacs)
5197 (save-excursion (org-mode) (turn-on-font-lock)))
5198 (narrow-to-region beg end)
5199 (show-all)
5200 (goto-char pos)
5201 (and (window-live-p cwin) (select-window cwin))))
5203 (defun org-get-indirect-buffer (&optional buffer)
5204 (setq buffer (or buffer (current-buffer)))
5205 (let ((n 1) (base (buffer-name buffer)) bname)
5206 (while (buffer-live-p
5207 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5208 (setq n (1+ n)))
5209 (condition-case nil
5210 (make-indirect-buffer buffer bname 'clone)
5211 (error (make-indirect-buffer buffer bname)))))
5213 (defun org-set-frame-title (title)
5214 "Set the title of the current frame to the string TITLE."
5215 ;; FIXME: how to name a single frame in XEmacs???
5216 (unless (featurep 'xemacs)
5217 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5219 ;;;; Structure editing
5221 ;;; Inserting headlines
5223 (defun org-insert-heading (&optional force-heading)
5224 "Insert a new heading or item with same depth at point.
5225 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5226 If point is at the beginning of a headline, insert a sibling before the
5227 current headline. If point is in the middle of a headline, split the headline
5228 at that position and make the rest of the headline part of the sibling below
5229 the current headline."
5230 (interactive "P")
5231 (if (= (buffer-size) 0)
5232 (insert "\n* ")
5233 (when (or force-heading (not (org-insert-item)))
5234 (let* ((head (save-excursion
5235 (condition-case nil
5236 (progn
5237 (org-back-to-heading)
5238 (match-string 0))
5239 (error "*"))))
5240 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5241 pos)
5242 (cond
5243 ((and (org-on-heading-p) (bolp)
5244 (or (bobp)
5245 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5246 (open-line (if blank 2 1)))
5247 ((and (bolp)
5248 (or (bobp)
5249 (save-excursion
5250 (backward-char 1) (not (org-invisible-p)))))
5251 nil)
5252 (t (newline (if blank 2 1))))
5253 (insert head) (just-one-space)
5254 (setq pos (point))
5255 (end-of-line 1)
5256 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5257 (run-hooks 'org-insert-heading-hook)))))
5259 (defun org-insert-todo-heading (arg)
5260 "Insert a new heading with the same level and TODO state as current heading.
5261 If the heading has no TODO state, or if the state is DONE, use the first
5262 state (TODO by default). Also with prefix arg, force first state."
5263 (interactive "P")
5264 (when (not (org-insert-item 'checkbox))
5265 (org-insert-heading)
5266 (save-excursion
5267 (org-back-to-heading)
5268 (outline-previous-heading)
5269 (looking-at org-todo-line-regexp))
5270 (if (or arg
5271 (not (match-beginning 2))
5272 (member (match-string 2) org-done-keywords))
5273 (insert (car org-todo-keywords-1) " ")
5274 (insert (match-string 2) " "))))
5276 (defun org-insert-subheading (arg)
5277 "Insert a new subheading and demote it.
5278 Works for outline headings and for plain lists alike."
5279 (interactive "P")
5280 (org-insert-heading arg)
5281 (cond
5282 ((org-on-heading-p) (org-do-demote))
5283 ((org-at-item-p) (org-indent-item 1))))
5285 (defun org-insert-todo-subheading (arg)
5286 "Insert a new subheading with TODO keyword or checkbox and demote it.
5287 Works for outline headings and for plain lists alike."
5288 (interactive "P")
5289 (org-insert-todo-heading arg)
5290 (cond
5291 ((org-on-heading-p) (org-do-demote))
5292 ((org-at-item-p) (org-indent-item 1))))
5294 ;;; Promotion and Demotion
5296 (defun org-promote-subtree ()
5297 "Promote the entire subtree.
5298 See also `org-promote'."
5299 (interactive)
5300 (save-excursion
5301 (org-map-tree 'org-promote))
5302 (org-fix-position-after-promote))
5304 (defun org-demote-subtree ()
5305 "Demote the entire subtree. See `org-demote'.
5306 See also `org-promote'."
5307 (interactive)
5308 (save-excursion
5309 (org-map-tree 'org-demote))
5310 (org-fix-position-after-promote))
5313 (defun org-do-promote ()
5314 "Promote the current heading higher up the tree.
5315 If the region is active in `transient-mark-mode', promote all headings
5316 in the region."
5317 (interactive)
5318 (save-excursion
5319 (if (org-region-active-p)
5320 (org-map-region 'org-promote (region-beginning) (region-end))
5321 (org-promote)))
5322 (org-fix-position-after-promote))
5324 (defun org-do-demote ()
5325 "Demote the current heading lower down the tree.
5326 If the region is active in `transient-mark-mode', demote all headings
5327 in the region."
5328 (interactive)
5329 (save-excursion
5330 (if (org-region-active-p)
5331 (org-map-region 'org-demote (region-beginning) (region-end))
5332 (org-demote)))
5333 (org-fix-position-after-promote))
5335 (defun org-fix-position-after-promote ()
5336 "Make sure that after pro/demotion cursor position is right."
5337 (let ((pos (point)))
5338 (when (save-excursion
5339 (beginning-of-line 1)
5340 (looking-at org-todo-line-regexp)
5341 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5342 (cond ((eobp) (insert " "))
5343 ((eolp) (insert " "))
5344 ((equal (char-after) ?\ ) (forward-char 1))))))
5346 (defun org-reduced-level (l)
5347 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5349 (defun org-get-legal-level (level &optional change)
5350 "Rectify a level change under the influence of `org-odd-levels-only'
5351 LEVEL is a current level, CHANGE is by how much the level should be
5352 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5353 even level numbers will become the next higher odd number."
5354 (if org-odd-levels-only
5355 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5356 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5357 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5358 (max 1 (+ level change))))
5360 (defun org-promote ()
5361 "Promote the current heading higher up the tree.
5362 If the region is active in `transient-mark-mode', promote all headings
5363 in the region."
5364 (org-back-to-heading t)
5365 (let* ((level (save-match-data (funcall outline-level)))
5366 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
5367 (diff (abs (- level (length up-head) -1))))
5368 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5369 (replace-match up-head nil t)
5370 ;; Fixup tag positioning
5371 (and org-auto-align-tags (org-set-tags nil t))
5372 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5374 (defun org-demote ()
5375 "Demote the current heading lower down the tree.
5376 If the region is active in `transient-mark-mode', demote all headings
5377 in the region."
5378 (org-back-to-heading t)
5379 (let* ((level (save-match-data (funcall outline-level)))
5380 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
5381 (diff (abs (- level (length down-head) -1))))
5382 (replace-match down-head nil t)
5383 ;; Fixup tag positioning
5384 (and org-auto-align-tags (org-set-tags nil t))
5385 (if org-adapt-indentation (org-fixup-indentation diff))))
5387 (defun org-map-tree (fun)
5388 "Call FUN for every heading underneath the current one."
5389 (org-back-to-heading)
5390 (let ((level (funcall outline-level)))
5391 (save-excursion
5392 (funcall fun)
5393 (while (and (progn
5394 (outline-next-heading)
5395 (> (funcall outline-level) level))
5396 (not (eobp)))
5397 (funcall fun)))))
5399 (defun org-map-region (fun beg end)
5400 "Call FUN for every heading between BEG and END."
5401 (let ((org-ignore-region t))
5402 (save-excursion
5403 (setq end (copy-marker end))
5404 (goto-char beg)
5405 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5406 (< (point) end))
5407 (funcall fun))
5408 (while (and (progn
5409 (outline-next-heading)
5410 (< (point) end))
5411 (not (eobp)))
5412 (funcall fun)))))
5414 (defun org-fixup-indentation (diff)
5415 "Change the indentation in the current entry by DIFF
5416 However, if any line in the current entry has no indentation, or if it
5417 would end up with no indentation after the change, nothing at all is done."
5418 (save-excursion
5419 (let ((end (save-excursion (outline-next-heading)
5420 (point-marker)))
5421 (prohibit (if (> diff 0)
5422 "^\\S-"
5423 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5424 col)
5425 (unless (save-excursion (end-of-line 1)
5426 (re-search-forward prohibit end t))
5427 (while (re-search-forward "^[ \t]+" end t)
5428 (goto-char (match-end 0))
5429 (setq col (current-column))
5430 (if (< diff 0) (replace-match ""))
5431 (indent-to (+ diff col))))
5432 (move-marker end nil))))
5434 (defun org-convert-to-odd-levels ()
5435 "Convert an org-mode file with all levels allowed to one with odd levels.
5436 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5437 level 5 etc."
5438 (interactive)
5439 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5440 (let ((org-odd-levels-only nil) n)
5441 (save-excursion
5442 (goto-char (point-min))
5443 (while (re-search-forward "^\\*\\*+ " nil t)
5444 (setq n (- (length (match-string 0)) 2))
5445 (while (>= (setq n (1- n)) 0)
5446 (org-demote))
5447 (end-of-line 1))))))
5450 (defun org-convert-to-oddeven-levels ()
5451 "Convert an org-mode file with only odd levels to one with odd and even levels.
5452 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5453 section with an even level, conversion would destroy the structure of the file. An error
5454 is signaled in this case."
5455 (interactive)
5456 (goto-char (point-min))
5457 ;; First check if there are no even levels
5458 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5459 (org-show-context t)
5460 (error "Not all levels are odd in this file. Conversion not possible."))
5461 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5462 (let ((org-odd-levels-only nil) n)
5463 (save-excursion
5464 (goto-char (point-min))
5465 (while (re-search-forward "^\\*\\*+ " nil t)
5466 (setq n (/ (length (1- (match-string 0))) 2))
5467 (while (>= (setq n (1- n)) 0)
5468 (org-promote))
5469 (end-of-line 1))))))
5471 (defun org-tr-level (n)
5472 "Make N odd if required."
5473 (if org-odd-levels-only (1+ (/ n 2)) n))
5475 ;;; Vertical tree motion, cutting and pasting of subtrees
5477 (defun org-move-subtree-up (&optional arg)
5478 "Move the current subtree up past ARG headlines of the same level."
5479 (interactive "p")
5480 (org-move-subtree-down (- (prefix-numeric-value arg))))
5482 (defun org-move-subtree-down (&optional arg)
5483 "Move the current subtree down past ARG headlines of the same level."
5484 (interactive "p")
5485 (setq arg (prefix-numeric-value arg))
5486 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5487 'outline-get-last-sibling))
5488 (ins-point (make-marker))
5489 (cnt (abs arg))
5490 beg end txt folded)
5491 ;; Select the tree
5492 (org-back-to-heading)
5493 (setq beg (point))
5494 (save-match-data
5495 (save-excursion (outline-end-of-heading)
5496 (setq folded (org-invisible-p)))
5497 (outline-end-of-subtree))
5498 (outline-next-heading)
5499 (setq end (point))
5500 ;; Find insertion point, with error handling
5501 (goto-char beg)
5502 (while (> cnt 0)
5503 (or (and (funcall movfunc) (looking-at outline-regexp))
5504 (progn (goto-char beg)
5505 (error "Cannot move past superior level or buffer limit")))
5506 (setq cnt (1- cnt)))
5507 (if (> arg 0)
5508 ;; Moving forward - still need to move over subtree
5509 (progn (outline-end-of-subtree)
5510 (outline-next-heading)
5511 (if (not (or (looking-at (concat "^" outline-regexp))
5512 (bolp)))
5513 (newline))))
5514 (move-marker ins-point (point))
5515 (setq txt (buffer-substring beg end))
5516 (delete-region beg end)
5517 (insert txt)
5518 (or (bolp) (insert "\n"))
5519 (goto-char ins-point)
5520 (if folded (hide-subtree))
5521 (move-marker ins-point nil)))
5523 (defvar org-subtree-clip ""
5524 "Clipboard for cut and paste of subtrees.
5525 This is actually only a copy of the kill, because we use the normal kill
5526 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5528 (defvar org-subtree-clip-folded nil
5529 "Was the last copied subtree folded?
5530 This is used to fold the tree back after pasting.")
5532 (defun org-cut-subtree ()
5533 "Cut the current subtree into the clipboard.
5534 This is a short-hand for marking the subtree and then cutting it."
5535 (interactive)
5536 (org-copy-subtree 'cut))
5538 (defun org-copy-subtree (&optional cut)
5539 "Cut the current subtree into the clipboard.
5540 This is a short-hand for marking the subtree and then copying it.
5541 If CUT is non-nil, actually cut the subtree."
5542 (interactive)
5543 (let (beg end folded)
5544 (if (interactive-p)
5545 (org-back-to-heading nil) ; take what looks like a subtree
5546 (org-back-to-heading t)) ; take what is really there
5547 (setq beg (point))
5548 (save-match-data
5549 (save-excursion (outline-end-of-heading)
5550 (setq folded (org-invisible-p)))
5551 (outline-end-of-subtree))
5552 (if (equal (char-after) ?\n) (forward-char 1))
5553 (setq end (point))
5554 (goto-char beg)
5555 (when (> end beg)
5556 (setq org-subtree-clip-folded folded)
5557 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5558 (setq org-subtree-clip (current-kill 0))
5559 (message "%s: Subtree with %d characters"
5560 (if cut "Cut" "Copied")
5561 (length org-subtree-clip)))))
5563 (defun org-paste-subtree (&optional level tree)
5564 "Paste the clipboard as a subtree, with modification of headline level.
5565 The entire subtree is promoted or demoted in order to match a new headline
5566 level. By default, the new level is derived from the visible headings
5567 before and after the insertion point, and taken to be the inferior headline
5568 level of the two. So if the previous visible heading is level 3 and the
5569 next is level 4 (or vice versa), level 4 will be used for insertion.
5570 This makes sure that the subtree remains an independent subtree and does
5571 not swallow low level entries.
5573 You can also force a different level, either by using a numeric prefix
5574 argument, or by inserting the heading marker by hand. For example, if the
5575 cursor is after \"*****\", then the tree will be shifted to level 5.
5577 If you want to insert the tree as is, just use \\[yank].
5579 If optional TREE is given, use this text instead of the kill ring."
5580 (interactive "P")
5581 (unless (org-kill-is-subtree-p tree)
5582 (error
5583 (substitute-command-keys
5584 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5585 (let* ((txt (or tree (and kill-ring (current-kill 0))))
5586 (^re (concat "^\\(" outline-regexp "\\)"))
5587 (re (concat "\\(" outline-regexp "\\)"))
5588 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
5590 (old-level (if (string-match ^re txt)
5591 (- (match-end 0) (match-beginning 0) 1)
5592 -1))
5593 (force-level (cond (level (prefix-numeric-value level))
5594 ((string-match
5595 ^re_ (buffer-substring (point-at-bol) (point)))
5596 (- (match-end 0) (match-beginning 0)))
5597 (t nil)))
5598 (previous-level (save-excursion
5599 (condition-case nil
5600 (progn
5601 (outline-previous-visible-heading 1)
5602 (if (looking-at re)
5603 (- (match-end 0) (match-beginning 0))
5605 (error 1))))
5606 (next-level (save-excursion
5607 (condition-case nil
5608 (progn
5609 (outline-next-visible-heading 1)
5610 (if (looking-at re)
5611 (- (match-end 0) (match-beginning 0))
5613 (error 1))))
5614 (new-level (or force-level (max previous-level next-level)))
5615 (shift (if (or (= old-level -1)
5616 (= new-level -1)
5617 (= old-level new-level))
5619 (- new-level old-level)))
5620 (shift1 shift)
5621 (delta (if (> shift 0) -1 1))
5622 (func (if (> shift 0) 'org-demote 'org-promote))
5623 (org-odd-levels-only nil)
5624 beg end)
5625 ;; Remove the forces level indicator
5626 (if force-level
5627 (delete-region (point-at-bol) (point)))
5628 ;; Make sure we start at the beginning of an empty line
5629 (if (not (bolp)) (insert "\n"))
5630 (if (not (looking-at "[ \t]*$"))
5631 (progn (insert "\n") (backward-char 1)))
5632 ;; Paste
5633 (setq beg (point))
5634 (if (string-match "[ \t\r\n]+\\'" txt)
5635 (setq txt (replace-match "\n" t t txt)))
5636 (insert txt)
5637 (setq end (point))
5638 (if (looking-at "[ \t\r\n]+")
5639 (replace-match "\n"))
5640 (goto-char beg)
5641 ;; Shift if necessary
5642 (if (= shift 0)
5643 (message "Pasted at level %d, without shift" new-level)
5644 (save-restriction
5645 (narrow-to-region beg end)
5646 (while (not (= shift 0))
5647 (org-map-region func (point-min) (point-max))
5648 (setq shift (+ delta shift)))
5649 (goto-char (point-min))
5650 (message "Pasted at level %d, with shift by %d levels"
5651 new-level shift1)))
5652 (if (and kill-ring
5653 (eq org-subtree-clip (current-kill 0))
5654 org-subtree-clip-folded)
5655 ;; The tree was folded before it was killed/copied
5656 (hide-subtree))))
5658 (defun org-kill-is-subtree-p (&optional txt)
5659 "Check if the current kill is an outline subtree, or a set of trees.
5660 Returns nil if kill does not start with a headline, or if the first
5661 headline level is not the largest headline level in the tree.
5662 So this will actually accept several entries of equal levels as well,
5663 which is OK for `org-paste-subtree'.
5664 If optional TXT is given, check this string instead of the current kill."
5665 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5666 (start-level (and kill
5667 (string-match (concat "\\`" outline-regexp) kill)
5668 (- (match-end 0) (match-beginning 0))))
5669 (re (concat "^" outline-regexp))
5670 (start 1))
5671 (if (not start-level)
5672 nil ;; does not even start with a heading
5673 (catch 'exit
5674 (while (setq start (string-match re kill (1+ start)))
5675 (if (< (- (match-end 0) (match-beginning 0)) start-level)
5676 (throw 'exit nil)))
5677 t))))
5679 (defun org-narrow-to-subtree ()
5680 "Narrow buffer to the current subtree."
5681 (interactive)
5682 (save-excursion
5683 (narrow-to-region
5684 (progn (org-back-to-heading) (point))
5685 (progn (org-end-of-subtree t t) (point)))))
5688 ;;; Outline Sorting
5690 (defun org-sort (with-case)
5691 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
5692 (interactive "P")
5693 (if (org-at-table-p)
5694 (org-call-with-arg 'org-table-sort-lines with-case)
5695 (org-call-with-arg 'org-sort-entries with-case)))
5697 (defun org-sort-entries (&optional with-case sorting-type)
5698 "Sort entries on a certain level of an outline tree.
5699 If there is an active region, the entries in the region are sorted.
5700 Else, if the cursor is before the first entry, sort the top-level items.
5701 Else, the children of the entry at point are sorted.
5703 Sorting can be alphabetically, numerically, and by date/time as given by
5704 the first time stamp in the entry. The command prompts for the sorting
5705 type unless it has been given to the function through the SORTING-TYPE
5706 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
5708 Comparing entries ignores case by default. However, with an optional argument
5709 WITH-CASE, the sorting considers case as well. With two prefix arguments
5710 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
5711 (interactive "P")
5712 (let ((unique (equal with-case '(16)))
5713 start beg end entries stars re re2 p nentries (nremoved 0)
5714 last txt what)
5715 ;; Find beginning and end of region to sort
5716 (cond
5717 ((org-region-active-p)
5718 ;; we will sort the region
5719 (setq end (region-end)
5720 what "region")
5721 (goto-char (region-beginning))
5722 (if (not (org-on-heading-p)) (outline-next-heading))
5723 (setq start (point)))
5724 ((or (org-on-heading-p)
5725 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5726 ;; we will sort the children of the current headline
5727 (org-back-to-heading)
5728 (setq start (point) end (org-end-of-subtree) what "children")
5729 (goto-char start)
5730 (show-subtree)
5731 (outline-next-heading))
5733 ;; we will sort the top-level entries in this file
5734 (goto-char (point-min))
5735 (or (org-on-heading-p) (outline-next-heading))
5736 (setq start (point) end (point-max) what "top-level")
5737 (goto-char start)
5738 (show-all)))
5739 (setq beg (point))
5740 (if (>= (point) end) (error "Nothing to sort"))
5741 (looking-at "\\(\\*+\\)")
5742 (setq stars (match-string 1)
5743 re (concat "^" (regexp-quote stars) " +")
5744 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5745 txt (buffer-substring beg end))
5746 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5747 (if (and (not (equal stars "*")) (string-match re2 txt))
5748 (error "Region to sort contains a level above the first entry"))
5749 ;; Make a list that can be sorted.
5750 ;; The car is the string for comparison, the cdr is the subtree
5751 (message "Sorting entries...")
5752 (setq entries
5753 (mapcar
5754 (lambda (x)
5755 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
5756 (cons (match-string 0 x) x))
5757 (org-split-string txt re)))
5759 ;; Sort the list
5760 (save-excursion
5761 (goto-char start)
5762 (setq entries (org-do-sort entries what with-case sorting-type)))
5764 ;; Delete the old stuff
5765 (goto-char beg)
5766 (kill-region beg end)
5767 (setq nentries (length entries))
5768 ;; Insert the sorted entries, and remove duplicates if this is required
5769 (while (setq p (pop entries))
5770 (if (and unique (equal last (setq last (org-trim (cdr p)))))
5771 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
5772 (insert stars " " (cdr p))))
5773 (goto-char start)
5774 (message "Sorting entries...done (%d entries%s)"
5775 nentries
5776 (if unique (format ", %d duplicates removed" nremoved) ""))))
5778 (defun org-do-sort (table what &optional with-case sorting-type)
5779 "Sort TABLE of WHAT according to SORTING-TYPE.
5780 The user will be prompted for the SORTING-TYPE if the call to this
5781 function does not specify it. WHAT is only for the prompt, to indicate
5782 what is being sorted. The sorting key will be extracted from
5783 the car of the elements of the table.
5784 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5785 (unless sorting-type
5786 (message
5787 "Sort %s: [a]lphabetically [n]umerically [t]ime. A/N/T means reversed:"
5788 what)
5789 (setq sorting-type (read-char-exclusive)))
5790 (let ((dcst (downcase sorting-type))
5791 extractfun comparefun)
5792 ;; Define the appropriate functions
5793 (cond
5794 ((= dcst ?n)
5795 (setq extractfun 'string-to-number
5796 comparefun (if (= dcst sorting-type) '< '>)))
5797 ((= dcst ?a)
5798 (setq extractfun (if with-case 'identity 'downcase)
5799 comparefun (if (= dcst sorting-type)
5800 'string<
5801 (lambda (a b) (and (not (string< a b))
5802 (not (string= a b)))))))
5803 ((= dcst ?t)
5804 (setq extractfun
5805 (lambda (x)
5806 (if (string-match org-ts-regexp x)
5807 (time-to-seconds
5808 (org-time-string-to-time (match-string 0 x)))
5810 comparefun (if (= dcst sorting-type) '< '>)))
5811 (t (error "Invalid sorting type `%c'" sorting-type)))
5813 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5814 table)
5815 (lambda (a b) (funcall comparefun (car a) (car b))))))
5817 ;;;; Plain list items, including checkboxes
5819 ;;; Plain list items
5821 (defun org-at-item-p ()
5822 "Is point in a line starting a hand-formatted item?"
5823 (let ((llt org-plain-list-ordered-item-terminator))
5824 (save-excursion
5825 (goto-char (point-at-bol))
5826 (looking-at
5827 (cond
5828 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5829 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5830 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5831 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5833 (defun org-in-item-p ()
5834 "It the cursor inside a plain list item.
5835 Does not have to be the first line."
5836 (save-excursion
5837 (condition-case nil
5838 (progn
5839 (org-beginning-of-item)
5840 (org-at-item-p)
5842 (error nil))))
5844 (defun org-insert-item (&optional checkbox)
5845 "Insert a new item at the current level.
5846 Return t when things worked, nil when we are not in an item."
5847 (when (save-excursion
5848 (condition-case nil
5849 (progn
5850 (org-beginning-of-item)
5851 (org-at-item-p)
5852 (if (org-invisible-p) (error "Invisible item"))
5854 (error nil)))
5855 (let* ((bul (match-string 0))
5856 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5857 (match-end 0)))
5858 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5859 pos)
5860 (cond
5861 ((and (org-at-item-p) (<= (point) eow))
5862 ;; before the bullet
5863 (beginning-of-line 1)
5864 (open-line (if blank 2 1)))
5865 ((<= (point) eow)
5866 (beginning-of-line 1))
5867 (t (newline (if blank 2 1))))
5868 (insert bul (if checkbox "[ ]" ""))
5869 (just-one-space)
5870 (setq pos (point))
5871 (end-of-line 1)
5872 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5873 (org-maybe-renumber-ordered-list)
5874 (and checkbox (org-update-checkbox-count-maybe))
5877 ;;; Checkboxes
5879 (defun org-at-item-checkbox-p ()
5880 "Is point at a line starting a plain-list item with a checklet?"
5881 (and (org-at-item-p)
5882 (save-excursion
5883 (goto-char (match-end 0))
5884 (skip-chars-forward " \t")
5885 (looking-at "\\[[- X]\\]"))))
5887 (defun org-toggle-checkbox (&optional arg)
5888 "Toggle the checkbox in the current line."
5889 (interactive "P")
5890 (catch 'exit
5891 (let (beg end status (firstnew 'unknown))
5892 (cond
5893 ((org-region-active-p)
5894 (setq beg (region-beginning) end (region-end)))
5895 ((org-on-heading-p)
5896 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5897 ((org-at-item-checkbox-p)
5898 (save-excursion
5899 (replace-match
5900 (cond (arg "[-]")
5901 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5902 (t "[ ]"))
5903 t t))
5904 (throw 'exit t))
5905 (t (error "Not at a checkbox or heading, and no active region")))
5906 (save-excursion
5907 (goto-char beg)
5908 (while (< (point) end)
5909 (when (org-at-item-checkbox-p)
5910 (setq status (equal (match-string 0) "[X]"))
5911 (when (eq firstnew 'unknown)
5912 (setq firstnew (not status)))
5913 (replace-match
5914 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5915 (beginning-of-line 2)))))
5916 (org-update-checkbox-count-maybe))
5918 (defun org-update-checkbox-count-maybe ()
5919 "Update checkbox statistics unless turned off by user."
5920 (when org-provide-checkbox-statistics
5921 (org-update-checkbox-count)))
5923 (defun org-update-checkbox-count (&optional all)
5924 "Update the checkbox statistics in the current section.
5925 This will find all statistic cookies like [57%] and [6/12] and update them
5926 with the current numbers. With optional prefix argument ALL, do this for
5927 the whole buffer."
5928 (interactive "P")
5929 (save-excursion
5930 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5931 (beg (condition-case nil
5932 (progn (outline-back-to-heading) (point))
5933 (error (point-min))))
5934 (end (move-marker (make-marker)
5935 (progn (outline-next-heading) (point))))
5936 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
5937 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5938 b1 e1 f1 c-on c-off lim (cstat 0))
5939 (when all
5940 (goto-char (point-min))
5941 (outline-next-heading)
5942 (setq beg (point) end (point-max)))
5943 (goto-char beg)
5944 (while (re-search-forward re end t)
5945 (setq cstat (1+ cstat)
5946 b1 (match-beginning 0)
5947 e1 (match-end 0)
5948 f1 (match-beginning 1)
5949 lim (cond
5950 ((org-on-heading-p) (outline-next-heading) (point))
5951 ((org-at-item-p) (org-end-of-item) (point))
5952 (t nil))
5953 c-on 0 c-off 0)
5954 (goto-char e1)
5955 (when lim
5956 (while (re-search-forward re-box lim t)
5957 (if (member (match-string 2) '("[ ]" "[-]"))
5958 (setq c-off (1+ c-off))
5959 (setq c-on (1+ c-on))))
5960 ; (delete-region b1 e1)
5961 (goto-char b1)
5962 (insert (if f1
5963 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5964 (format "[%d/%d]" c-on (+ c-on c-off))))
5965 (and (looking-at "\\[.*?\\]")
5966 (replace-match ""))))
5967 (when (interactive-p)
5968 (message "Checkbox satistics updated %s (%d places)"
5969 (if all "in entire file" "in current outline entry") cstat)))))
5971 (defun org-get-checkbox-statistics-face ()
5972 "Select the face for checkbox statistics.
5973 The face will be `org-done' when all relevant boxes are checked. Otherwise
5974 it will be `org-todo'."
5975 (if (match-end 1)
5976 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5977 (if (and (> (match-end 2) (match-beginning 2))
5978 (equal (match-string 2) (match-string 3)))
5979 'org-done
5980 'org-todo)))
5982 (defun org-get-indentation (&optional line)
5983 "Get the indentation of the current line, interpreting tabs.
5984 When LINE is given, assume it represents a line and compute its indentation."
5985 (if line
5986 (if (string-match "^ *" (org-remove-tabs line))
5987 (match-end 0))
5988 (save-excursion
5989 (beginning-of-line 1)
5990 (skip-chars-forward " \t")
5991 (current-column))))
5993 (defun org-remove-tabs (s &optional width)
5994 "Replace tabulators in S with spaces.
5995 Assumes that s is a single line, starting in column 0."
5996 (setq width (or width tab-width))
5997 (while (string-match "\t" s)
5998 (setq s (replace-match
5999 (make-string
6000 (- (* width (/ (+ (match-beginning 0) width) width))
6001 (match-beginning 0)) ?\ )
6002 t t s)))
6005 (defun org-fix-indentation (line ind)
6006 "Fix indentation in LINE.
6007 IND is a cons cell with target and minimum indentation.
6008 If the current indenation in LINE is smaller than the minimum,
6009 leave it alone. If it is larger than ind, set it to the target."
6010 (let* ((l (org-remove-tabs line))
6011 (i (org-get-indentation l))
6012 (i1 (car ind)) (i2 (cdr ind)))
6013 (if (>= i i2) (setq l (substring line i2)))
6014 (if (> i1 0)
6015 (concat (make-string i1 ?\ ) l)
6016 l)))
6018 (defcustom org-empty-line-terminates-plain-lists nil
6019 "Non-nil means, an empty line ends all plain list levels.
6020 When nil, empty lines are part of the preceeding item."
6021 :group 'org-plain-lists
6022 :type 'boolean)
6024 (defun org-beginning-of-item ()
6025 "Go to the beginning of the current hand-formatted item.
6026 If the cursor is not in an item, throw an error."
6027 (interactive)
6028 (let ((pos (point))
6029 (limit (save-excursion
6030 (condition-case nil
6031 (progn
6032 (org-back-to-heading)
6033 (beginning-of-line 2) (point))
6034 (error (point-min)))))
6035 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6036 ind ind1)
6037 (if (org-at-item-p)
6038 (beginning-of-line 1)
6039 (beginning-of-line 1)
6040 (skip-chars-forward " \t")
6041 (setq ind (current-column))
6042 (if (catch 'exit
6043 (while t
6044 (beginning-of-line 0)
6045 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6047 (if (looking-at "[ \t]*$")
6048 (setq ind1 ind-empty)
6049 (skip-chars-forward " \t")
6050 (setq ind1 (current-column)))
6051 (if (< ind1 ind)
6052 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6054 (goto-char pos)
6055 (error "Not in an item")))))
6057 (defun org-end-of-item ()
6058 "Go to the end of the current hand-formatted item.
6059 If the cursor is not in an item, throw an error."
6060 (interactive)
6061 (let* ((pos (point))
6062 ind1
6063 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6064 (limit (save-excursion (outline-next-heading) (point)))
6065 (ind (save-excursion
6066 (org-beginning-of-item)
6067 (skip-chars-forward " \t")
6068 (current-column)))
6069 (end (catch 'exit
6070 (while t
6071 (beginning-of-line 2)
6072 (if (eobp) (throw 'exit (point)))
6073 (if (>= (point) limit) (throw 'exit (point-at-bol)))
6074 (if (looking-at "[ \t]*$")
6075 (setq ind1 ind-empty)
6076 (skip-chars-forward " \t")
6077 (setq ind1 (current-column)))
6078 (if (<= ind1 ind)
6079 (throw 'exit (point-at-bol)))))))
6080 (if end
6081 (goto-char end)
6082 (goto-char pos)
6083 (error "Not in an item"))))
6085 (defun org-next-item ()
6086 "Move to the beginning of the next item in the current plain list.
6087 Error if not at a plain list, or if this is the last item in the list."
6088 (interactive)
6089 (let (ind ind1 (pos (point)))
6090 (org-beginning-of-item)
6091 (setq ind (org-get-indentation))
6092 (org-end-of-item)
6093 (setq ind1 (org-get-indentation))
6094 (unless (and (org-at-item-p) (= ind ind1))
6095 (goto-char pos)
6096 (error "On last item"))))
6098 (defun org-previous-item ()
6099 "Move to the beginning of the previous item in the current plain list.
6100 Error if not at a plain list, or if this is the first item in the list."
6101 (interactive)
6102 (let (beg ind ind1 (pos (point)))
6103 (org-beginning-of-item)
6104 (setq beg (point))
6105 (setq ind (org-get-indentation))
6106 (goto-char beg)
6107 (catch 'exit
6108 (while t
6109 (beginning-of-line 0)
6110 (if (looking-at "[ \t]*$")
6112 (if (<= (setq ind1 (org-get-indentation)) ind)
6113 (throw 'exit t)))))
6114 (condition-case nil
6115 (if (or (not (org-at-item-p))
6116 (< ind1 (1- ind)))
6117 (error "")
6118 (org-beginning-of-item))
6119 (error (goto-char pos)
6120 (error "On first item")))))
6122 (defun org-move-item-down ()
6123 "Move the plain list item at point down, i.e. swap with following item.
6124 Subitems (items with larger indentation) are considered part of the item,
6125 so this really moves item trees."
6126 (interactive)
6127 (let (beg end ind ind1 (pos (point)) txt)
6128 (org-beginning-of-item)
6129 (setq beg (point))
6130 (setq ind (org-get-indentation))
6131 (org-end-of-item)
6132 (setq end (point))
6133 (setq ind1 (org-get-indentation))
6134 (if (and (org-at-item-p) (= ind ind1))
6135 (progn
6136 (org-end-of-item)
6137 (setq txt (buffer-substring beg end))
6138 (save-excursion
6139 (delete-region beg end))
6140 (setq pos (point))
6141 (insert txt)
6142 (goto-char pos)
6143 (org-maybe-renumber-ordered-list))
6144 (goto-char pos)
6145 (error "Cannot move this item further down"))))
6147 (defun org-move-item-up (arg)
6148 "Move the plain list item at point up, i.e. swap with previous item.
6149 Subitems (items with larger indentation) are considered part of the item,
6150 so this really moves item trees."
6151 (interactive "p")
6152 (let (beg end ind ind1 (pos (point)) txt)
6153 (org-beginning-of-item)
6154 (setq beg (point))
6155 (setq ind (org-get-indentation))
6156 (org-end-of-item)
6157 (setq end (point))
6158 (goto-char beg)
6159 (catch 'exit
6160 (while t
6161 (beginning-of-line 0)
6162 (if (looking-at "[ \t]*$")
6163 (if org-empty-line-terminates-plain-lists
6164 (progn
6165 (goto-char pos)
6166 (error "Cannot move this item further up"))
6167 nil)
6168 (if (<= (setq ind1 (org-get-indentation)) ind)
6169 (throw 'exit t)))))
6170 (condition-case nil
6171 (org-beginning-of-item)
6172 (error (goto-char beg)
6173 (error "Cannot move this item further up")))
6174 (setq ind1 (org-get-indentation))
6175 (if (and (org-at-item-p) (= ind ind1))
6176 (progn
6177 (setq txt (buffer-substring beg end))
6178 (save-excursion
6179 (delete-region beg end))
6180 (setq pos (point))
6181 (insert txt)
6182 (goto-char pos)
6183 (org-maybe-renumber-ordered-list))
6184 (goto-char pos)
6185 (error "Cannot move this item further up"))))
6187 (defun org-maybe-renumber-ordered-list ()
6188 "Renumber the ordered list at point if setup allows it.
6189 This tests the user option `org-auto-renumber-ordered-lists' before
6190 doing the renumbering."
6191 (interactive)
6192 (when (and org-auto-renumber-ordered-lists
6193 (org-at-item-p))
6194 (if (match-beginning 3)
6195 (org-renumber-ordered-list 1)
6196 (org-fix-bullet-type 1))))
6198 (defun org-maybe-renumber-ordered-list-safe ()
6199 (condition-case nil
6200 (save-excursion
6201 (org-maybe-renumber-ordered-list))
6202 (error nil)))
6204 (defun org-cycle-list-bullet (&optional which)
6205 "Cycle through the different itemize/enumerate bullets.
6206 This cycle the entire list level through the sequence:
6208 `-' -> `+' -> `*' -> `1.' -> `1)'
6210 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6211 0 meand `-', 1 means `+' etc."
6212 (interactive "P")
6213 (org-preserve-lc
6214 (org-beginning-of-item-list)
6215 (org-at-item-p)
6216 (beginning-of-line 1)
6217 (let ((current (match-string 0)) new)
6218 (setq new (cond
6219 ((and which (nth (1- which) '("-" "+" "*" "1." "1)"))))
6220 ((string-match "-" current) "+")
6221 ((string-match "\\+" current)
6222 (if (looking-at "\\S-") "1." "*"))
6223 ((string-match "\\*" current) "1.")
6224 ((string-match "\\." current) "1)")
6225 ((string-match ")" current) "-")
6226 (t (error "This should not happen"))))
6227 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6228 (org-fix-bullet-type 1)
6229 (org-maybe-renumber-ordered-list))))
6231 (defun org-get-string-indentation (s)
6232 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6233 (let ((n -1) (i 0) (w tab-width) c)
6234 (catch 'exit
6235 (while (< (setq n (1+ n)) (length s))
6236 (setq c (aref s n))
6237 (cond ((= c ?\ ) (setq i (1+ i)))
6238 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6239 (t (throw 'exit t)))))
6242 (defun org-renumber-ordered-list (arg)
6243 "Renumber an ordered plain list.
6244 Cursor needs to be in the first line of an item, the line that starts
6245 with something like \"1.\" or \"2)\"."
6246 (interactive "p")
6247 (unless (and (org-at-item-p)
6248 (match-beginning 3))
6249 (error "This is not an ordered list"))
6250 (let ((line (org-current-line))
6251 (col (current-column))
6252 (ind (org-get-string-indentation
6253 (buffer-substring (point-at-bol) (match-beginning 3))))
6254 ;; (term (substring (match-string 3) -1))
6255 ind1 (n (1- arg))
6256 fmt)
6257 ;; find where this list begins
6258 (org-beginning-of-item-list)
6259 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6260 (setq fmt (concat "%d" (match-string 1)))
6261 (beginning-of-line 0)
6262 ;; walk forward and replace these numbers
6263 (catch 'exit
6264 (while t
6265 (catch 'next
6266 (beginning-of-line 2)
6267 (if (eobp) (throw 'exit nil))
6268 (if (looking-at "[ \t]*$") (throw 'next nil))
6269 (skip-chars-forward " \t") (setq ind1 (current-column))
6270 (if (> ind1 ind) (throw 'next t))
6271 (if (< ind1 ind) (throw 'exit t))
6272 (if (not (org-at-item-p)) (throw 'exit nil))
6273 (delete-region (match-beginning 2) (match-end 2))
6274 (goto-char (match-beginning 2))
6275 (insert (format fmt (setq n (1+ n)))))))
6276 (goto-line line)
6277 (move-to-column col)))
6279 (defun org-fix-bullet-type (arg)
6280 "Make sure all items in this list have the same bullet."
6281 (interactive "p")
6282 (unless (org-at-item-p) (error "This is not a list"))
6283 (let ((line (org-current-line))
6284 (col (current-column))
6285 (ind (current-indentation))
6286 ind1 bullet)
6287 ;; find where this list begins
6288 (org-beginning-of-item-list)
6289 (beginning-of-line 1)
6290 ;; find out what the bullet type is
6291 (looking-at "[ \t]*\\(\\S-+\\)")
6292 (setq bullet (match-string 1))
6293 ;; walk forward and replace these numbers
6294 (beginning-of-line 0)
6295 (catch 'exit
6296 (while t
6297 (catch 'next
6298 (beginning-of-line 2)
6299 (if (eobp) (throw 'exit nil))
6300 (if (looking-at "[ \t]*$") (throw 'next nil))
6301 (skip-chars-forward " \t") (setq ind1 (current-column))
6302 (if (> ind1 ind) (throw 'next t))
6303 (if (< ind1 ind) (throw 'exit t))
6304 (if (not (org-at-item-p)) (throw 'exit nil))
6305 (skip-chars-forward " \t")
6306 (looking-at "\\S-+")
6307 (replace-match bullet))))
6308 (goto-line line)
6309 (move-to-column col)
6310 (if (string-match "[0-9]" bullet)
6311 (org-renumber-ordered-list 1))))
6313 (defun org-beginning-of-item-list ()
6314 "Go to the beginning of the current item list.
6315 I.e. to the first item in this list."
6316 (interactive)
6317 (org-beginning-of-item)
6318 (let ((pos (point-at-bol))
6319 (ind (org-get-indentation))
6320 ind1)
6321 ;; find where this list begins
6322 (catch 'exit
6323 (while t
6324 (catch 'next
6325 (beginning-of-line 0)
6326 (if (looking-at "[ \t]*$")
6327 (throw (if (bobp) 'exit 'next) t))
6328 (skip-chars-forward " \t") (setq ind1 (current-column))
6329 (if (or (< ind1 ind)
6330 (and (= ind1 ind)
6331 (not (org-at-item-p)))
6332 (bobp))
6333 (throw 'exit t)
6334 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6335 (goto-char pos)))
6337 (defvar org-last-indent-begin-marker (make-marker))
6338 (defvar org-last-indent-end-marker (make-marker))
6340 (defun org-outdent-item (arg)
6341 "Outdent a local list item."
6342 (interactive "p")
6343 (org-indent-item (- arg)))
6345 (defun org-indent-item (arg)
6346 "Indent a local list item."
6347 (interactive "p")
6348 (unless (org-at-item-p)
6349 (error "Not on an item"))
6350 (save-excursion
6351 (let (beg end ind ind1 tmp delta ind-down ind-up)
6352 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6353 (setq beg org-last-indent-begin-marker
6354 end org-last-indent-end-marker)
6355 (org-beginning-of-item)
6356 (setq beg (move-marker org-last-indent-begin-marker (point)))
6357 (org-end-of-item)
6358 (setq end (move-marker org-last-indent-end-marker (point))))
6359 (goto-char beg)
6360 (setq tmp (org-item-indent-positions)
6361 ind (car tmp)
6362 ind-down (nth 2 tmp)
6363 ind-up (nth 1 tmp)
6364 delta (if (> arg 0)
6365 (if ind-down (- ind-down ind) 2)
6366 (if ind-up (- ind-up ind) -2)))
6367 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6368 (while (< (point) end)
6369 (beginning-of-line 1)
6370 (skip-chars-forward " \t") (setq ind1 (current-column))
6371 (delete-region (point-at-bol) (point))
6372 (or (eolp) (indent-to-column (+ ind1 delta)))
6373 (beginning-of-line 2))))
6374 (org-maybe-renumber-ordered-list-safe)
6375 (save-excursion
6376 (beginning-of-line 0)
6377 (condition-case nil (org-beginning-of-item) (error nil))
6378 (org-maybe-renumber-ordered-list-safe)))
6381 (defun org-item-indent-positions ()
6382 "Assumes cursor in item line. FIXME"
6383 (let* ((bolpos (point-at-bol))
6384 (ind (org-get-indentation))
6385 ind-down ind-up pos)
6386 (save-excursion
6387 (org-beginning-of-item-list)
6388 (skip-chars-backward "\n\r \t")
6389 (when (org-in-item-p)
6390 (org-beginning-of-item)
6391 (setq ind-up (org-get-indentation))))
6392 (setq pos (point))
6393 (save-excursion
6394 (cond
6395 ((and (condition-case nil (progn (org-previous-item) t)
6396 (error nil))
6397 (or (forward-char 1) t)
6398 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6399 (setq ind-down (org-get-indentation)))
6400 ((and (goto-char pos)
6401 (org-at-item-p))
6402 (goto-char (match-end 0))
6403 (skip-chars-forward " \t")
6404 (setq ind-down (current-column)))))
6405 (list ind ind-up ind-down)))
6407 ;;; The orgstruct minor mode
6409 ;; Define a minor mode which can be used in other modes in order to
6410 ;; integrate the org-mode structure editing commands.
6412 ;; This is really a hack, because the org-mode structure commands use
6413 ;; keys which normally belong to the major mode. Here is how it
6414 ;; works: The minor mode defines all the keys necessary to operate the
6415 ;; structure commands, but wraps the commands into a function which
6416 ;; tests if the cursor is currently at a headline or a plain list
6417 ;; item. If that is the case, the structure command is used,
6418 ;; temporarily setting many Org-mode variables like regular
6419 ;; expressions for filling etc. However, when any of those keys is
6420 ;; used at a different location, function uses `key-binding' to look
6421 ;; up if the key has an associated command in another currently active
6422 ;; keymap (minor modes, major mode, global), and executes that
6423 ;; command. There might be problems if any of the keys is otherwise
6424 ;; used as a prefix key.
6426 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6427 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6428 ;; addresses this by checking explicitly for both bindings.
6430 (defvar orgstruct-mode-map (make-sparse-keymap)
6431 "Keymap for the minor `orgstruct-mode'.")
6433 ;;;###autoload
6434 (define-minor-mode orgstruct-mode
6435 "Toggle the minor more `orgstruct-mode'.
6436 This mode is for using Org-mode structure commands in other modes.
6437 The following key behave as if Org-mode was active, if the cursor
6438 is on a headline, or on a plain list item (both in the definition
6439 of Org-mode).
6441 M-up Move entry/item up
6442 M-down Move entry/item down
6443 M-left Promote
6444 M-right Demote
6445 M-S-up Move entry/item up
6446 M-S-down Move entry/item down
6447 M-S-left Promote subtree
6448 M-S-right Demote subtree
6449 M-q Fill paragraph and items like in Org-mode
6450 C-c ^ Sort entries
6451 C-c - Cycle list bullet
6452 TAB Cycle item visibility
6453 M-RET Insert new heading/item
6454 S-M-RET Insert new TODO heading / Chekbox item
6455 C-c C-c Set tags / toggle checkbox"
6456 nil " OrgStruct" nil
6457 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6459 ;;;###autoload
6460 (defun turn-on-orgstruct ()
6461 "Unconditionally turn on `orgstruct-mode'."
6462 (orgstruct-mode 1))
6464 (defun orgstruct-error ()
6465 "Error when there is no default binding for a structure key."
6466 (interactive)
6467 (error "This key is has no function outside structure elements"))
6469 (defvar org-local-vars nil
6470 "List of local variables, for use by `orgstruct-mode'")
6472 (defun orgstruct-setup ()
6473 "Setup orgstruct keymaps."
6474 (let ((nfunc 0)
6475 (bindings
6476 (list
6477 '([(meta up)] org-metaup)
6478 '([(meta down)] org-metadown)
6479 '([(meta left)] org-metaleft)
6480 '([(meta right)] org-metaright)
6481 '([(meta shift up)] org-shiftmetaup)
6482 '([(meta shift down)] org-shiftmetadown)
6483 '([(meta shift left)] org-shiftmetaleft)
6484 '([(meta shift right)] org-shiftmetaright)
6485 '([(shift up)] org-shiftup)
6486 '([(shift down)] org-shiftdown)
6487 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6488 '("\M-q" fill-paragraph)
6489 '("\C-c^" org-sort)
6490 '("\C-c-" org-cycle-list-bullet)))
6491 elt key fun cmd)
6492 (while (setq elt (pop bindings))
6493 (setq nfunc (1+ nfunc))
6494 (setq key (org-key (car elt))
6495 fun (nth 1 elt)
6496 cmd (orgstruct-make-binding fun nfunc key))
6497 (org-defkey orgstruct-mode-map key cmd))
6499 ;; Special treatment needed for TAB and RET
6500 (org-defkey orgstruct-mode-map [(tab)]
6501 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6502 (org-defkey orgstruct-mode-map "\C-i"
6503 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6505 (org-defkey orgstruct-mode-map "\M-\C-m"
6506 (orgstruct-make-binding 'org-insert-heading 105
6507 "\M-\C-m" [(meta return)]))
6508 (org-defkey orgstruct-mode-map [(meta return)]
6509 (orgstruct-make-binding 'org-insert-heading 106
6510 [(meta return)] "\M-\C-m"))
6512 (org-defkey orgstruct-mode-map [(shift meta return)]
6513 (orgstruct-make-binding 'org-insert-todo-heading 107
6514 [(meta return)] "\M-\C-m"))
6516 (unless org-local-vars
6517 (setq org-local-vars (org-get-local-variables)))
6521 (defun orgstruct-make-binding (fun n &rest keys)
6522 "Create a function for binding in the structure minor mode.
6523 FUN is the command to call inside a table. N is used to create a unique
6524 command name. KEYS are keys that should be checked in for a command
6525 to execute outside of tables."
6526 (eval
6527 (list 'defun
6528 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6529 '(arg)
6530 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6531 "Outside of structure, run the binding of `"
6532 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6533 "'.")
6534 '(interactive "p")
6535 (list 'if
6536 '(org-context-p 'headline 'item)
6537 (list 'org-run-like-in-org-mode (list 'quote fun))
6538 (list 'let '(orgstruct-mode)
6539 (list 'call-interactively
6540 (append '(or)
6541 (mapcar (lambda (k)
6542 (list 'key-binding k))
6543 keys)
6544 '('orgstruct-error))))))))
6546 (defun org-context-p (&rest contexts)
6547 "FIXME:"
6548 (let ((pos (point)))
6549 (goto-char (point-at-bol))
6550 (prog1 (or (and (memq 'table contexts)
6551 (looking-at "[ \t]*|"))
6552 (and (memq 'headline contexts)
6553 (looking-at "\\*+"))
6554 (and (memq 'item contexts)
6555 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6556 (goto-char pos))))
6558 (defun org-get-local-variables ()
6559 "Return a list of all local variables in an org-mode buffer."
6560 (let (varlist)
6561 (with-current-buffer (get-buffer-create "*Org tmp*")
6562 (erase-buffer)
6563 (org-mode)
6564 (setq varlist (buffer-local-variables)))
6565 (kill-buffer "*Org tmp*")
6566 (delq nil
6567 (mapcar
6568 (lambda (x)
6569 (setq x
6570 (if (symbolp x)
6571 (list x)
6572 (list (car x) (list 'quote (cdr x)))))
6573 (if (string-match
6574 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6575 (symbol-name (car x)))
6576 x nil))
6577 varlist))))
6579 ;;;###autoload
6580 (defun org-run-like-in-org-mode (cmd)
6581 (unless org-local-vars
6582 (setq org-local-vars (org-get-local-variables)))
6583 (eval (list 'let org-local-vars
6584 (list 'call-interactively (list 'quote cmd)))))
6586 ;;;; Archiving
6588 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
6590 (defun org-archive-subtree (&optional find-done)
6591 "Move the current subtree to the archive.
6592 The archive can be a certain top-level heading in the current file, or in
6593 a different file. The tree will be moved to that location, the subtree
6594 heading be marked DONE, and the current time will be added.
6596 When called with prefix argument FIND-DONE, find whole trees without any
6597 open TODO items and archive them (after getting confirmation from the user).
6598 If the cursor is not at a headline when this comand is called, try all level
6599 1 trees. If the cursor is on a headline, only try the direct children of
6600 this heading."
6601 (interactive "P")
6602 (if find-done
6603 (org-archive-all-done)
6604 ;; Save all relevant TODO keyword-relatex variables
6606 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
6607 (tr-org-todo-keywords-1 org-todo-keywords-1)
6608 (tr-org-todo-kwd-alist org-todo-kwd-alist)
6609 (tr-org-done-keywords org-done-keywords)
6610 (tr-org-todo-regexp org-todo-regexp)
6611 (tr-org-todo-line-regexp org-todo-line-regexp)
6612 (tr-org-odd-levels-only org-odd-levels-only)
6613 (this-buffer (current-buffer))
6614 (org-archive-location org-archive-location)
6615 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
6616 file heading buffer level newfile-p)
6618 ;; Try to find a local archive location
6619 (save-excursion
6620 (save-restriction
6621 (widen)
6622 (if (or (re-search-backward re nil t) (re-search-forward re nil t))
6623 (setq org-archive-location (match-string 1)))))
6625 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
6626 (progn
6627 (setq file (format (match-string 1 org-archive-location)
6628 (file-name-nondirectory buffer-file-name))
6629 heading (match-string 2 org-archive-location)))
6630 (error "Invalid `org-archive-location'"))
6631 (if (> (length file) 0)
6632 (setq newfile-p (not (file-exists-p file))
6633 buffer (find-file-noselect file))
6634 (setq buffer (current-buffer)))
6635 (unless buffer
6636 (error "Cannot access file \"%s\"" file))
6637 (if (and (> (length heading) 0)
6638 (string-match "^\\*+" heading))
6639 (setq level (match-end 0))
6640 (setq heading nil level 0))
6641 (save-excursion
6642 ;; We first only copy, in case something goes wrong
6643 ;; we need to protect this-command, to avoid kill-region sets it,
6644 ;; which would lead to duplication of subtrees
6645 (let (this-command) (org-copy-subtree))
6646 (set-buffer buffer)
6647 ;; Enforce org-mode for the archive buffer
6648 (if (not (org-mode-p))
6649 ;; Force the mode for future visits.
6650 (let ((org-insert-mode-line-in-empty-file t)
6651 (org-inhibit-startup t))
6652 (call-interactively 'org-mode)))
6653 (when newfile-p
6654 (goto-char (point-max))
6655 (insert (format "\nArchived entries from file %s\n\n"
6656 (buffer-file-name this-buffer))))
6657 ;; Force the TODO keywords of the original buffer
6658 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
6659 (org-todo-keywords-1 tr-org-todo-keywords-1)
6660 (org-todo-kwd-alist tr-org-todo-kwd-alist)
6661 (org-done-keywords tr-org-done-keywords)
6662 (org-todo-regexp tr-org-todo-regexp)
6663 (org-todo-line-regexp tr-org-todo-line-regexp)
6664 (org-odd-levels-only
6665 (if (local-variable-p 'org-odd-levels-only (current-buffer))
6666 org-odd-levels-only
6667 tr-org-odd-levels-only)))
6668 (goto-char (point-min))
6669 (if heading
6670 (progn
6671 (if (re-search-forward
6672 (concat "^" (regexp-quote heading)
6673 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
6674 nil t)
6675 (goto-char (match-end 0))
6676 ;; Heading not found, just insert it at the end
6677 (goto-char (point-max))
6678 (or (bolp) (insert "\n"))
6679 (insert "\n" heading "\n")
6680 (end-of-line 0))
6681 ;; Make the subtree visible
6682 (show-subtree)
6683 (org-end-of-subtree t)
6684 (skip-chars-backward " \t\r\n")
6685 (and (looking-at "[ \t\r\n]*")
6686 (replace-match "\n\n")))
6687 ;; No specific heading, just go to end of file.
6688 (goto-char (point-max)) (insert "\n"))
6689 ;; Paste
6690 (org-paste-subtree (org-get-legal-level level 1))
6692 ;; Mark the entry as done
6693 (when (and org-archive-mark-done
6694 (looking-at org-todo-line-regexp)
6695 (or (not (match-end 2))
6696 (not (member (match-string 2) org-done-keywords))))
6697 (let (org-log-done)
6698 (org-todo
6699 (car (or (member org-archive-mark-done org-done-keywords)
6700 org-done-keywords)))))
6702 ;; Move cursor to right after the TODO keyword
6703 (when org-archive-stamp-time
6704 (org-add-planning-info 'archived (org-current-time)))
6705 ;; Save the buffer, if it is not the same buffer.
6706 (if (not (eq this-buffer buffer)) (save-buffer))))
6707 ;; Here we are back in the original buffer. Everything seems to have
6708 ;; worked. So now cut the tree and finish up.
6709 (let (this-command) (org-cut-subtree))
6710 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
6711 (message "Subtree archived %s"
6712 (if (eq this-buffer buffer)
6713 (concat "under heading: " heading)
6714 (concat "in file: " (abbreviate-file-name file)))))))
6716 (defun org-archive-all-done (&optional tag)
6717 "Archive sublevels of the current tree without open TODO items.
6718 If the cursor is not on a headline, try all level 1 trees. If
6719 it is on a headline, try all direct children.
6720 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
6721 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
6722 (rea (concat ".*:" org-archive-tag ":"))
6723 (begm (make-marker))
6724 (endm (make-marker))
6725 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
6726 "Move subtree to archive (no open TODO items)? "))
6727 beg end (cntarch 0))
6728 (if (org-on-heading-p)
6729 (progn
6730 (setq re1 (concat "^" (regexp-quote
6731 (make-string
6732 (1+ (- (match-end 0) (match-beginning 0)))
6733 ?*))
6734 " "))
6735 (move-marker begm (point))
6736 (move-marker endm (org-end-of-subtree t)))
6737 (setq re1 "^* ")
6738 (move-marker begm (point-min))
6739 (move-marker endm (point-max)))
6740 (save-excursion
6741 (goto-char begm)
6742 (while (re-search-forward re1 endm t)
6743 (setq beg (match-beginning 0)
6744 end (save-excursion (org-end-of-subtree t) (point)))
6745 (goto-char beg)
6746 (if (re-search-forward re end t)
6747 (goto-char end)
6748 (goto-char beg)
6749 (if (and (or (not tag) (not (looking-at rea)))
6750 (y-or-n-p question))
6751 (progn
6752 (if tag
6753 (org-toggle-tag org-archive-tag 'on)
6754 (org-archive-subtree))
6755 (setq cntarch (1+ cntarch)))
6756 (goto-char end)))))
6757 (message "%d trees archived" cntarch)))
6759 (defun org-cycle-hide-drawers (state)
6760 "Re-hide all drawers after a visibility state change."
6761 (when (and (org-mode-p)
6762 (not (memq state '(overview folded))))
6763 (save-excursion
6764 (let* ((globalp (memq state '(contents all)))
6765 (beg (if globalp (point-min) (point)))
6766 (end (if globalp (point-max) (org-end-of-subtree t))))
6767 (goto-char beg)
6768 (while (re-search-forward org-drawer-regexp end t)
6769 (org-flag-drawer t))))))
6771 (defun org-flag-drawer (flag)
6772 (save-excursion
6773 (beginning-of-line 1)
6774 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6775 (let ((b (match-end 0)))
6776 (if (re-search-forward
6777 "^[ \t]*:END:"
6778 (save-excursion (outline-next-heading) (point)) t)
6779 (outline-flag-region b (point-at-eol) flag)
6780 (error ":END: line missing"))))))
6782 (defun org-cycle-hide-archived-subtrees (state)
6783 "Re-hide all archived subtrees after a visibility state change."
6784 (when (and (not org-cycle-open-archived-trees)
6785 (not (memq state '(overview folded))))
6786 (save-excursion
6787 (let* ((globalp (memq state '(contents all)))
6788 (beg (if globalp (point-min) (point)))
6789 (end (if globalp (point-max) (org-end-of-subtree t))))
6790 (org-hide-archived-subtrees beg end)
6791 (goto-char beg)
6792 (if (looking-at (concat ".*:" org-archive-tag ":"))
6793 (message (substitute-command-keys
6794 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
6796 (defun org-force-cycle-archived ()
6797 "Cycle subtree even if it is archived."
6798 (interactive)
6799 (setq this-command 'org-cycle)
6800 (let ((org-cycle-open-archived-trees t))
6801 (call-interactively 'org-cycle)))
6803 (defun org-hide-archived-subtrees (beg end)
6804 "Re-hide all archived subtrees after a visibility state change."
6805 (save-excursion
6806 (let* ((re (concat ":" org-archive-tag ":")))
6807 (goto-char beg)
6808 (while (re-search-forward re end t)
6809 (and (org-on-heading-p) (hide-subtree))
6810 (org-end-of-subtree t)))))
6812 (defun org-toggle-tag (tag &optional onoff)
6813 "Toggle the tag TAG for the current line.
6814 If ONOFF is `on' or `off', don't toggle but set to this state."
6815 (unless (org-on-heading-p t) (error "Not on headling"))
6816 (let (res current)
6817 (save-excursion
6818 (beginning-of-line)
6819 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
6820 (point-at-eol) t)
6821 (progn
6822 (setq current (match-string 1))
6823 (replace-match ""))
6824 (setq current ""))
6825 (setq current (nreverse (org-split-string current ":")))
6826 (cond
6827 ((eq onoff 'on)
6828 (setq res t)
6829 (or (member tag current) (push tag current)))
6830 ((eq onoff 'off)
6831 (or (not (member tag current)) (setq current (delete tag current))))
6832 (t (if (member tag current)
6833 (setq current (delete tag current))
6834 (setq res t)
6835 (push tag current))))
6836 (end-of-line 1)
6837 (when current
6838 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
6839 (org-set-tags nil t))
6840 res))
6842 (defun org-toggle-archive-tag (&optional arg)
6843 "Toggle the archive tag for the current headline.
6844 With prefix ARG, check all children of current headline and offer tagging
6845 the children that do not contain any open TODO items."
6846 (interactive "P")
6847 (if arg
6848 (org-archive-all-done 'tag)
6849 (let (set)
6850 (save-excursion
6851 (org-back-to-heading t)
6852 (setq set (org-toggle-tag org-archive-tag))
6853 (when set (hide-subtree)))
6854 (and set (beginning-of-line 1))
6855 (message "Subtree %s" (if set "archived" "unarchived")))))
6858 ;;;; Tables
6860 ;;; The table editor
6862 ;; Watch out: Here we are talking about two different kind of tables.
6863 ;; Most of the code is for the tables created with the Org-mode table editor.
6864 ;; Sometimes, we talk about tables created and edited with the table.el
6865 ;; Emacs package. We call the former org-type tables, and the latter
6866 ;; table.el-type tables.
6868 (defun org-before-change-function (beg end)
6869 "Every change indicates that a table might need an update."
6870 (setq org-table-may-need-update t))
6872 (defconst org-table-line-regexp "^[ \t]*|"
6873 "Detects an org-type table line.")
6874 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
6875 "Detects an org-type table line.")
6876 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
6877 "Detects a table line marked for automatic recalculation.")
6878 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
6879 "Detects a table line marked for automatic recalculation.")
6880 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
6881 "Detects a table line marked for automatic recalculation.")
6882 (defconst org-table-hline-regexp "^[ \t]*|-"
6883 "Detects an org-type table hline.")
6884 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
6885 "Detects a table-type table hline.")
6886 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
6887 "Detects an org-type or table-type table.")
6888 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
6889 "Searching from within a table (any type) this finds the first line
6890 outside the table.")
6891 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
6892 "Searching from within a table (any type) this finds the first line
6893 outside the table.")
6895 (defvar org-table-last-highlighted-reference nil)
6896 (defvar org-table-formula-history nil)
6898 (defvar org-table-column-names nil
6899 "Alist with column names, derived from the `!' line.")
6900 (defvar org-table-column-name-regexp nil
6901 "Regular expression matching the current column names.")
6902 (defvar org-table-local-parameters nil
6903 "Alist with parameter names, derived from the `$' line.")
6904 (defvar org-table-named-field-locations nil
6905 "Alist with locations of named fields.")
6907 (defvar org-table-current-line-types nil
6908 "Table row types, non-nil only for the duration of a comand.")
6909 (defvar org-table-current-begin-line nil
6910 "Table begin line, non-nil only for the duration of a comand.")
6911 (defvar org-table-current-begin-pos nil
6912 "Table begin position, non-nil only for the duration of a comand.")
6913 (defvar org-table-dlines nil
6914 "Vector of data line line numbers in the current table.")
6915 (defvar org-table-hlines nil
6916 "Vector of hline line numbers in the current table.")
6918 (defconst org-table-range-regexp
6919 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
6920 ;; 1 2 3 4 5
6921 "Regular expression for matching ranges in formulas.")
6923 (defconst org-table-range-regexp2
6924 (concat
6925 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
6926 "\\.\\."
6927 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
6928 "Match a range for reference display.")
6930 (defconst org-table-translate-regexp
6931 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
6932 "Match a reference that needs translation, for reference display.")
6934 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
6936 (defun org-table-create-with-table.el ()
6937 "Use the table.el package to insert a new table.
6938 If there is already a table at point, convert between Org-mode tables
6939 and table.el tables."
6940 (interactive)
6941 (require 'table)
6942 (cond
6943 ((org-at-table.el-p)
6944 (if (y-or-n-p "Convert table to Org-mode table? ")
6945 (org-table-convert)))
6946 ((org-at-table-p)
6947 (if (y-or-n-p "Convert table to table.el table? ")
6948 (org-table-convert)))
6949 (t (call-interactively 'table-insert))))
6951 (defun org-table-create-or-convert-from-region (arg)
6952 "Convert region to table, or create an empty table.
6953 If there is an active region, convert it to a table, using the function
6954 `org-table-convert-region'.
6955 If there is no such region, create an empty table with `org-table-create'."
6956 (interactive "P")
6957 (if (org-region-active-p)
6958 (org-table-convert-region (region-beginning) (region-end) arg)
6959 (org-table-create arg)))
6961 (defun org-table-create (&optional size)
6962 "Query for a size and insert a table skeleton.
6963 SIZE is a string Columns x Rows like for example \"3x2\"."
6964 (interactive "P")
6965 (unless size
6966 (setq size (read-string
6967 (concat "Table size Columns x Rows [e.g. "
6968 org-table-default-size "]: ")
6969 "" nil org-table-default-size)))
6971 (let* ((pos (point))
6972 (indent (make-string (current-column) ?\ ))
6973 (split (org-split-string size " *x *"))
6974 (rows (string-to-number (nth 1 split)))
6975 (columns (string-to-number (car split)))
6976 (line (concat (apply 'concat indent "|" (make-list columns " |"))
6977 "\n")))
6978 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
6979 (point-at-bol) (point)))
6980 (beginning-of-line 1)
6981 (newline))
6982 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
6983 (dotimes (i rows) (insert line))
6984 (goto-char pos)
6985 (if (> rows 1)
6986 ;; Insert a hline after the first row.
6987 (progn
6988 (end-of-line 1)
6989 (insert "\n|-")
6990 (goto-char pos)))
6991 (org-table-align)))
6993 (defun org-table-convert-region (beg0 end0 &optional nspace)
6994 "Convert region to a table.
6995 The region goes from BEG0 to END0, but these borders will be moved
6996 slightly, to make sure a beginning of line in the first line is included.
6997 When NSPACE is non-nil, it indicates the minimum number of spaces that
6998 separate columns. By default, the function first checks if every line
6999 contains at lease one TAB. If yes, it assumes that the material is TAB
7000 separated. If not, it assumes a single space as separator."
7001 (interactive "rP")
7002 (let* ((beg (min beg0 end0))
7003 (end (max beg0 end0))
7004 (tabsep t)
7006 (goto-char beg)
7007 (beginning-of-line 1)
7008 (setq beg (move-marker (make-marker) (point)))
7009 (goto-char end)
7010 (if (bolp) (backward-char 1) (end-of-line 1))
7011 (setq end (move-marker (make-marker) (point)))
7012 ;; Lets see if this is tab-separated material. If every nonempty line
7013 ;; contains a tab, we will assume that it is tab-separated material
7014 (if nspace
7015 (setq tabsep nil)
7016 (goto-char beg)
7017 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
7018 (if nspace (setq tabsep nil))
7019 (if tabsep
7020 (setq re "^\\|\t")
7021 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
7022 (max 1 (prefix-numeric-value nspace)))))
7023 (goto-char beg)
7024 (while (re-search-forward re end t)
7025 (replace-match "| " t t))
7026 (goto-char beg)
7027 (insert " ")
7028 (org-table-align)))
7030 (defun org-table-import (file arg)
7031 "Import FILE as a table.
7032 The file is assumed to be tab-separated. Such files can be produced by most
7033 spreadsheet and database applications. If no tabs (at least one per line)
7034 are found, lines will be split on whitespace into fields."
7035 (interactive "f\nP")
7036 (or (bolp) (newline))
7037 (let ((beg (point))
7038 (pm (point-max)))
7039 (insert-file-contents file)
7040 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7042 (defun org-table-export ()
7043 "Export table as a tab-separated file.
7044 Such a file can be imported into a spreadsheet program like Excel."
7045 (interactive)
7046 (let* ((beg (org-table-begin))
7047 (end (org-table-end))
7048 (table (buffer-substring beg end))
7049 (file (read-file-name "Export table to: "))
7050 buf)
7051 (unless (or (not (file-exists-p file))
7052 (y-or-n-p (format "Overwrite file %s? " file)))
7053 (error "Abort"))
7054 (with-current-buffer (find-file-noselect file)
7055 (setq buf (current-buffer))
7056 (erase-buffer)
7057 (fundamental-mode)
7058 (insert table)
7059 (goto-char (point-min))
7060 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7061 (replace-match "" t t)
7062 (end-of-line 1))
7063 (goto-char (point-min))
7064 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7065 (replace-match "" t t)
7066 (goto-char (min (1+ (point)) (point-max))))
7067 (goto-char (point-min))
7068 (while (re-search-forward "^-[-+]*$" nil t)
7069 (replace-match "")
7070 (if (looking-at "\n")
7071 (delete-char 1)))
7072 (goto-char (point-min))
7073 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7074 (replace-match "\t" t t))
7075 (save-buffer))
7076 (kill-buffer buf)))
7078 (defvar org-table-aligned-begin-marker (make-marker)
7079 "Marker at the beginning of the table last aligned.
7080 Used to check if cursor still is in that table, to minimize realignment.")
7081 (defvar org-table-aligned-end-marker (make-marker)
7082 "Marker at the end of the table last aligned.
7083 Used to check if cursor still is in that table, to minimize realignment.")
7084 (defvar org-table-last-alignment nil
7085 "List of flags for flushright alignment, from the last re-alignment.
7086 This is being used to correctly align a single field after TAB or RET.")
7087 (defvar org-table-last-column-widths nil
7088 "List of max width of fields in each column.
7089 This is being used to correctly align a single field after TAB or RET.")
7090 (defvar org-table-overlay-coordinates nil
7091 "Overlay coordinates after each align of a table.")
7092 (make-variable-buffer-local 'org-table-overlay-coordinates)
7094 (defvar org-last-recalc-line nil)
7095 (defconst org-narrow-column-arrow "=>"
7096 "Used as display property in narrowed table columns.")
7098 (defun org-table-align ()
7099 "Align the table at point by aligning all vertical bars."
7100 (interactive)
7101 (let* (
7102 ;; Limits of table
7103 (beg (org-table-begin))
7104 (end (org-table-end))
7105 ;; Current cursor position
7106 (linepos (org-current-line))
7107 (colpos (org-table-current-column))
7108 (winstart (window-start))
7109 (winstartline (org-current-line (min winstart (1- (point-max)))))
7110 lines (new "") lengths l typenums ty fields maxfields i
7111 column
7112 (indent "") cnt frac
7113 rfmt hfmt
7114 (spaces '(1 . 1))
7115 (sp1 (car spaces))
7116 (sp2 (cdr spaces))
7117 (rfmt1 (concat
7118 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7119 (hfmt1 (concat
7120 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7121 emptystrings links dates narrow fmax f1 len c e)
7122 (untabify beg end)
7123 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
7124 ;; Check if we have links or dates
7125 (goto-char beg)
7126 (setq links (re-search-forward org-bracket-link-regexp end t))
7127 (goto-char beg)
7128 (setq dates (and org-display-custom-times
7129 (re-search-forward org-ts-regexp-both end t)))
7130 ;; Make sure the link properties are right
7131 (when links (goto-char beg) (while (org-activate-bracket-links end)))
7132 ;; Make sure the date properties are right
7133 (when dates (goto-char beg) (while (org-activate-dates end)))
7135 ;; Check if we are narrowing any columns
7136 (goto-char beg)
7137 (setq narrow (and org-format-transports-properties-p
7138 (re-search-forward "<[0-9]+>" end t)))
7139 ;; Get the rows
7140 (setq lines (org-split-string
7141 (buffer-substring beg end) "\n"))
7142 ;; Store the indentation of the first line
7143 (if (string-match "^ *" (car lines))
7144 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7145 ;; Mark the hlines by setting the corresponding element to nil
7146 ;; At the same time, we remove trailing space.
7147 (setq lines (mapcar (lambda (l)
7148 (if (string-match "^ *|-" l)
7150 (if (string-match "[ \t]+$" l)
7151 (substring l 0 (match-beginning 0))
7152 l)))
7153 lines))
7154 ;; Get the data fields by splitting the lines.
7155 (setq fields (mapcar
7156 (lambda (l)
7157 (org-split-string l " *| *"))
7158 (delq nil (copy-sequence lines))))
7159 ;; How many fields in the longest line?
7160 (condition-case nil
7161 (setq maxfields (apply 'max (mapcar 'length fields)))
7162 (error
7163 (kill-region beg end)
7164 (org-table-create org-table-default-size)
7165 (error "Empty table - created default table")))
7166 ;; A list of empty strings to fill any short rows on output
7167 (setq emptystrings (make-list maxfields ""))
7168 ;; Check for special formatting.
7169 (setq i -1)
7170 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7171 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7172 ;; Check if there is an explicit width specified
7173 (when narrow
7174 (setq c column fmax nil)
7175 (while c
7176 (setq e (pop c))
7177 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
7178 (setq fmax (string-to-number (match-string 1 e)) c nil)))
7179 ;; Find fields that are wider than fmax, and shorten them
7180 (when fmax
7181 (loop for xx in column do
7182 (when (and (stringp xx)
7183 (> (org-string-width xx) fmax))
7184 (org-add-props xx nil
7185 'help-echo
7186 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
7187 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
7188 (unless (> f1 1)
7189 (error "Cannot narrow field starting with wide link \"%s\""
7190 (match-string 0 xx)))
7191 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
7192 (add-text-properties (- f1 2) f1
7193 (list 'display org-narrow-column-arrow)
7194 xx)))))
7195 ;; Get the maximum width for each column
7196 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
7197 ;; Get the fraction of numbers, to decide about alignment of the column
7198 (setq cnt 0 frac 0.0)
7199 (loop for x in column do
7200 (if (equal x "")
7202 (setq frac ( / (+ (* frac cnt)
7203 (if (string-match org-table-number-regexp x) 1 0))
7204 (setq cnt (1+ cnt))))))
7205 (push (>= frac org-table-number-fraction) typenums))
7206 (setq lengths (nreverse lengths) typenums (nreverse typenums))
7208 ;; Store the alignment of this table, for later editing of single fields
7209 (setq org-table-last-alignment typenums
7210 org-table-last-column-widths lengths)
7212 ;; With invisible characters, `format' does not get the field width right
7213 ;; So we need to make these fields wide by hand.
7214 (when links
7215 (loop for i from 0 upto (1- maxfields) do
7216 (setq len (nth i lengths))
7217 (loop for j from 0 upto (1- (length fields)) do
7218 (setq c (nthcdr i (car (nthcdr j fields))))
7219 (if (and (stringp (car c))
7220 (string-match org-bracket-link-regexp (car c))
7221 (< (org-string-width (car c)) len))
7222 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
7224 ;; Compute the formats needed for output of the table
7225 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7226 (while (setq l (pop lengths))
7227 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7228 (setq rfmt (concat rfmt (format rfmt1 ty l))
7229 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7230 (setq rfmt (concat rfmt "\n")
7231 hfmt (concat (substring hfmt 0 -1) "|\n"))
7233 (setq new (mapconcat
7234 (lambda (l)
7235 (if l (apply 'format rfmt
7236 (append (pop fields) emptystrings))
7237 hfmt))
7238 lines ""))
7239 ;; Replace the old one
7240 (delete-region beg end)
7241 (move-marker end nil)
7242 (move-marker org-table-aligned-begin-marker (point))
7243 (insert new)
7244 (move-marker org-table-aligned-end-marker (point))
7245 (when (and orgtbl-mode (not (org-mode-p)))
7246 (goto-char org-table-aligned-begin-marker)
7247 (while (org-hide-wide-columns org-table-aligned-end-marker)))
7248 ;; Try to move to the old location
7249 (goto-line winstartline)
7250 (setq winstart (point-at-bol))
7251 (goto-line linepos)
7252 (set-window-start (selected-window) winstart 'noforce)
7253 (org-table-goto-column colpos)
7254 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
7255 (setq org-table-may-need-update nil)
7258 (defun org-string-width (s)
7259 "Compute width of string, ignoring invisible characters.
7260 This ignores character with invisibility property `org-link', and also
7261 characters with property `org-cwidth', because these will become invisible
7262 upon the next fontification round."
7263 (let (b l)
7264 (when (or (eq t buffer-invisibility-spec)
7265 (assq 'org-link buffer-invisibility-spec))
7266 (while (setq b (text-property-any 0 (length s)
7267 'invisible 'org-link s))
7268 (setq s (concat (substring s 0 b)
7269 (substring s (or (next-single-property-change
7270 b 'invisible s) (length s)))))))
7271 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
7272 (setq s (concat (substring s 0 b)
7273 (substring s (or (next-single-property-change
7274 b 'org-cwidth s) (length s))))))
7275 (setq l (string-width s) b -1)
7276 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
7277 (setq l (- l (get-text-property b 'org-dwidth-n s))))
7280 (defun org-table-begin (&optional table-type)
7281 "Find the beginning of the table and return its position.
7282 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7283 (save-excursion
7284 (if (not (re-search-backward
7285 (if table-type org-table-any-border-regexp
7286 org-table-border-regexp)
7287 nil t))
7288 (progn (goto-char (point-min)) (point))
7289 (goto-char (match-beginning 0))
7290 (beginning-of-line 2)
7291 (point))))
7293 (defun org-table-end (&optional table-type)
7294 "Find the end of the table and return its position.
7295 With argument TABLE-TYPE, go to the end of a table.el-type table."
7296 (save-excursion
7297 (if (not (re-search-forward
7298 (if table-type org-table-any-border-regexp
7299 org-table-border-regexp)
7300 nil t))
7301 (goto-char (point-max))
7302 (goto-char (match-beginning 0)))
7303 (point-marker)))
7305 (defun org-table-justify-field-maybe (&optional new)
7306 "Justify the current field, text to left, number to right.
7307 Optional argument NEW may specify text to replace the current field content."
7308 (cond
7309 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7310 ((org-at-table-hline-p))
7311 ((and (not new)
7312 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7313 (current-buffer)))
7314 (< (point) org-table-aligned-begin-marker)
7315 (>= (point) org-table-aligned-end-marker)))
7316 ;; This is not the same table, force a full re-align
7317 (setq org-table-may-need-update t))
7318 (t ;; realign the current field, based on previous full realign
7319 (let* ((pos (point)) s
7320 (col (org-table-current-column))
7321 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
7322 l f n o e)
7323 (when (> col 0)
7324 (skip-chars-backward "^|\n")
7325 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7326 (progn
7327 (setq s (match-string 1)
7328 o (match-string 0)
7329 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7330 e (not (= (match-beginning 2) (match-end 2))))
7331 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7332 l (if e "|" (setq org-table-may-need-update t) ""))
7333 n (format f s))
7334 (if new
7335 (if (<= (length new) l) ;; FIXME: length -> str-width?
7336 (setq n (format f new))
7337 (setq n (concat new "|") org-table-may-need-update t)))
7338 (or (equal n o)
7339 (let (org-table-may-need-update)
7340 (replace-match n t t))))
7341 (setq org-table-may-need-update t))
7342 (goto-char pos))))))
7344 (defun org-table-next-field ()
7345 "Go to the next field in the current table, creating new lines as needed.
7346 Before doing so, re-align the table if necessary."
7347 (interactive)
7348 (org-table-maybe-eval-formula)
7349 (org-table-maybe-recalculate-line)
7350 (if (and org-table-automatic-realign
7351 org-table-may-need-update)
7352 (org-table-align))
7353 (let ((end (org-table-end)))
7354 (if (org-at-table-hline-p)
7355 (end-of-line 1))
7356 (condition-case nil
7357 (progn
7358 (re-search-forward "|" end)
7359 (if (looking-at "[ \t]*$")
7360 (re-search-forward "|" end))
7361 (if (and (looking-at "-")
7362 org-table-tab-jumps-over-hlines
7363 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7364 (goto-char (match-beginning 1)))
7365 (if (looking-at "-")
7366 (progn
7367 (beginning-of-line 0)
7368 (org-table-insert-row 'below))
7369 (if (looking-at " ") (forward-char 1))))
7370 (error
7371 (org-table-insert-row 'below)))))
7373 (defun org-table-previous-field ()
7374 "Go to the previous field in the table.
7375 Before doing so, re-align the table if necessary."
7376 (interactive)
7377 (org-table-justify-field-maybe)
7378 (org-table-maybe-recalculate-line)
7379 (if (and org-table-automatic-realign
7380 org-table-may-need-update)
7381 (org-table-align))
7382 (if (org-at-table-hline-p)
7383 (end-of-line 1))
7384 (re-search-backward "|" (org-table-begin))
7385 (re-search-backward "|" (org-table-begin))
7386 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7387 (re-search-backward "|" (org-table-begin)))
7388 (if (looking-at "| ?")
7389 (goto-char (match-end 0))))
7391 (defun org-table-next-row ()
7392 "Go to the next row (same column) in the current table.
7393 Before doing so, re-align the table if necessary."
7394 (interactive)
7395 (org-table-maybe-eval-formula)
7396 (org-table-maybe-recalculate-line)
7397 (if (or (looking-at "[ \t]*$")
7398 (save-excursion (skip-chars-backward " \t") (bolp)))
7399 (newline)
7400 (if (and org-table-automatic-realign
7401 org-table-may-need-update)
7402 (org-table-align))
7403 (let ((col (org-table-current-column)))
7404 (beginning-of-line 2)
7405 (if (or (not (org-at-table-p))
7406 (org-at-table-hline-p))
7407 (progn
7408 (beginning-of-line 0)
7409 (org-table-insert-row 'below)))
7410 (org-table-goto-column col)
7411 (skip-chars-backward "^|\n\r")
7412 (if (looking-at " ") (forward-char 1)))))
7414 (defun org-table-copy-down (n)
7415 "Copy a field down in the current column.
7416 If the field at the cursor is empty, copy into it the content of the nearest
7417 non-empty field above. With argument N, use the Nth non-empty field.
7418 If the current field is not empty, it is copied down to the next row, and
7419 the cursor is moved with it. Therefore, repeating this command causes the
7420 column to be filled row-by-row.
7421 If the variable `org-table-copy-increment' is non-nil and the field is an
7422 integer or a timestamp, it will be incremented while copying. In the case of
7423 a timestamp, if the cursor is on the year, change the year. If it is on the
7424 month or the day, change that. Point will stay on the current date field
7425 in order to easily repeat the interval."
7426 (interactive "p")
7427 (let* ((colpos (org-table-current-column))
7428 (col (current-column))
7429 (field (org-table-get-field))
7430 (non-empty (string-match "[^ \t]" field))
7431 (beg (org-table-begin))
7432 txt)
7433 (org-table-check-inside-data-field)
7434 (if non-empty
7435 (progn
7436 (setq txt (org-trim field))
7437 (org-table-next-row)
7438 (org-table-blank-field))
7439 (save-excursion
7440 (setq txt
7441 (catch 'exit
7442 (while (progn (beginning-of-line 1)
7443 (re-search-backward org-table-dataline-regexp
7444 beg t))
7445 (org-table-goto-column colpos t)
7446 (if (and (looking-at
7447 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7448 (= (setq n (1- n)) 0))
7449 (throw 'exit (match-string 1))))))))
7450 (if txt
7451 (progn
7452 (if (and org-table-copy-increment
7453 (string-match "^[0-9]+$" txt))
7454 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7455 (insert txt)
7456 (move-to-column col)
7457 (if (and org-table-copy-increment (org-at-timestamp-p t))
7458 (org-timestamp-up 1)
7459 (org-table-maybe-recalculate-line))
7460 (org-table-align)
7461 (move-to-column col))
7462 (error "No non-empty field found"))))
7464 (defun org-table-check-inside-data-field ()
7465 "Is point inside a table data field?
7466 I.e. not on a hline or before the first or after the last column?
7467 This actually throws an error, so it aborts the current command."
7468 (if (or (not (org-at-table-p))
7469 (= (org-table-current-column) 0)
7470 (org-at-table-hline-p)
7471 (looking-at "[ \t]*$"))
7472 (error "Not in table data field")))
7474 (defvar org-table-clip nil
7475 "Clipboard for table regions.")
7477 (defun org-table-blank-field ()
7478 "Blank the current table field or active region."
7479 (interactive)
7480 (org-table-check-inside-data-field)
7481 (if (and (interactive-p) (org-region-active-p))
7482 (let (org-table-clip)
7483 (org-table-cut-region (region-beginning) (region-end)))
7484 (skip-chars-backward "^|")
7485 (backward-char 1)
7486 (if (looking-at "|[^|\n]+")
7487 (let* ((pos (match-beginning 0))
7488 (match (match-string 0))
7489 (len (org-string-width match)))
7490 (replace-match (concat "|" (make-string (1- len) ?\ )))
7491 (goto-char (+ 2 pos))
7492 (substring match 1)))))
7494 (defun org-table-get-field (&optional n replace)
7495 "Return the value of the field in column N of current row.
7496 N defaults to current field.
7497 If REPLACE is a string, replace field with this value. The return value
7498 is always the old value."
7499 (and n (org-table-goto-column n))
7500 (skip-chars-backward "^|\n")
7501 (backward-char 1)
7502 (if (looking-at "|[^|\r\n]*")
7503 (let* ((pos (match-beginning 0))
7504 (val (buffer-substring (1+ pos) (match-end 0))))
7505 (if replace
7506 (replace-match (concat "|" replace) t t))
7507 (goto-char (min (point-at-eol) (+ 2 pos)))
7508 val)
7509 (forward-char 1) ""))
7511 (defun org-table-field-info (arg)
7512 "Show info about the current field, and highlight any reference at point."
7513 (interactive "P")
7514 (org-table-get-specials)
7515 (save-excursion
7516 (let* ((pos (point))
7517 (col (org-table-current-column))
7518 (cname (car (rassoc (int-to-string col) org-table-column-names)))
7519 (name (car (rassoc (list (org-current-line) col)
7520 org-table-named-field-locations)))
7521 (eql (org-table-get-stored-formulas))
7522 (dline (org-table-current-dline))
7523 (ref (format "@%d$%d" dline col))
7524 (ref1 (org-table-convert-refs-to-an ref))
7525 (fequation (or (assoc name eql) (assoc ref eql)))
7526 (cequation (assoc (int-to-string col) eql))
7527 (eqn (or fequation cequation)))
7528 (goto-char pos)
7529 (condition-case nil
7530 (org-table-show-reference 'local)
7531 (error nil))
7532 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
7533 dline col
7534 (if cname (concat " or $" cname) "")
7535 dline col ref1
7536 (if name (concat " or $" name) "")
7537 ;; FIXME: formula info not correct if special table line
7538 (if eqn
7539 (concat ", formula: "
7540 (org-table-formula-to-user
7541 (concat
7542 (if (string-match "^[$@]"(car eqn)) "" "$")
7543 (car eqn) "=" (cdr eqn))))
7544 "")))))
7546 (defun org-table-current-column ()
7547 "Find out which column we are in.
7548 When called interactively, column is also displayed in echo area."
7549 (interactive)
7550 (if (interactive-p) (org-table-check-inside-data-field))
7551 (save-excursion
7552 (let ((cnt 0) (pos (point)))
7553 (beginning-of-line 1)
7554 (while (search-forward "|" pos t)
7555 (setq cnt (1+ cnt)))
7556 (if (interactive-p) (message "This is table column %d" cnt))
7557 cnt)))
7559 (defun org-table-current-dline ()
7560 "Find out what table data line we are in.
7561 Only datalins count for this."
7562 (interactive)
7563 (if (interactive-p) (org-table-check-inside-data-field))
7564 (save-excursion
7565 (let ((cnt 0) (pos (point)))
7566 (goto-char (org-table-begin))
7567 (while (<= (point) pos)
7568 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
7569 (beginning-of-line 2))
7570 (if (interactive-p) (message "This is table line %d" cnt))
7571 cnt)))
7573 (defun org-table-goto-column (n &optional on-delim force)
7574 "Move the cursor to the Nth column in the current table line.
7575 With optional argument ON-DELIM, stop with point before the left delimiter
7576 of the field.
7577 If there are less than N fields, just go to after the last delimiter.
7578 However, when FORCE is non-nil, create new columns if necessary."
7579 (interactive "p")
7580 (let ((pos (point-at-eol)))
7581 (beginning-of-line 1)
7582 (when (> n 0)
7583 (while (and (> (setq n (1- n)) -1)
7584 (or (search-forward "|" pos t)
7585 (and force
7586 (progn (end-of-line 1)
7587 (skip-chars-backward "^|")
7588 (insert " | "))))))
7589 ; (backward-char 2) t)))))
7590 (when (and force (not (looking-at ".*|")))
7591 (save-excursion (end-of-line 1) (insert " | ")))
7592 (if on-delim
7593 (backward-char 1)
7594 (if (looking-at " ") (forward-char 1))))))
7596 (defun org-at-table-p (&optional table-type)
7597 "Return t if the cursor is inside an org-type table.
7598 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7599 (if org-enable-table-editor
7600 (save-excursion
7601 (beginning-of-line 1)
7602 (looking-at (if table-type org-table-any-line-regexp
7603 org-table-line-regexp)))
7604 nil))
7606 (defun org-at-table.el-p ()
7607 "Return t if and only if we are at a table.el table."
7608 (and (org-at-table-p 'any)
7609 (save-excursion
7610 (goto-char (org-table-begin 'any))
7611 (looking-at org-table1-hline-regexp))))
7613 (defun org-table-recognize-table.el ()
7614 "If there is a table.el table nearby, recognize it and move into it."
7615 (if org-table-tab-recognizes-table.el
7616 (if (org-at-table.el-p)
7617 (progn
7618 (beginning-of-line 1)
7619 (if (looking-at org-table-dataline-regexp)
7621 (if (looking-at org-table1-hline-regexp)
7622 (progn
7623 (beginning-of-line 2)
7624 (if (looking-at org-table-any-border-regexp)
7625 (beginning-of-line -1)))))
7626 (if (re-search-forward "|" (org-table-end t) t)
7627 (progn
7628 (require 'table)
7629 (if (table--at-cell-p (point))
7631 (message "recognizing table.el table...")
7632 (table-recognize-table)
7633 (message "recognizing table.el table...done")))
7634 (error "This should not happen..."))
7636 nil)
7637 nil))
7639 (defun org-at-table-hline-p ()
7640 "Return t if the cursor is inside a hline in a table."
7641 (if org-enable-table-editor
7642 (save-excursion
7643 (beginning-of-line 1)
7644 (looking-at org-table-hline-regexp))
7645 nil))
7647 (defun org-table-insert-column ()
7648 "Insert a new column into the table."
7649 (interactive)
7650 (if (not (org-at-table-p))
7651 (error "Not at a table"))
7652 (org-table-find-dataline)
7653 (let* ((col (max 1 (org-table-current-column)))
7654 (beg (org-table-begin))
7655 (end (org-table-end))
7656 ;; Current cursor position
7657 (linepos (org-current-line))
7658 (colpos col))
7659 (goto-char beg)
7660 (while (< (point) end)
7661 (if (org-at-table-hline-p)
7663 (org-table-goto-column col t)
7664 (insert "| "))
7665 (beginning-of-line 2))
7666 (move-marker end nil)
7667 (goto-line linepos)
7668 (org-table-goto-column colpos)
7669 (org-table-align)
7670 (org-table-fix-formulas "$" nil (1- col) 1)))
7672 (defun org-table-find-dataline ()
7673 "Find a dataline in the current table, which is needed for column commands."
7674 (if (and (org-at-table-p)
7675 (not (org-at-table-hline-p)))
7677 (let ((col (current-column))
7678 (end (org-table-end)))
7679 (move-to-column col)
7680 (while (and (< (point) end)
7681 (or (not (= (current-column) col))
7682 (org-at-table-hline-p)))
7683 (beginning-of-line 2)
7684 (move-to-column col))
7685 (if (and (org-at-table-p)
7686 (not (org-at-table-hline-p)))
7688 (error
7689 "Please position cursor in a data line for column operations")))))
7691 (defun org-table-delete-column ()
7692 "Delete a column from the table."
7693 (interactive)
7694 (if (not (org-at-table-p))
7695 (error "Not at a table"))
7696 (org-table-find-dataline)
7697 (org-table-check-inside-data-field)
7698 (let* ((col (org-table-current-column))
7699 (beg (org-table-begin))
7700 (end (org-table-end))
7701 ;; Current cursor position
7702 (linepos (org-current-line))
7703 (colpos col))
7704 (goto-char beg)
7705 (while (< (point) end)
7706 (if (org-at-table-hline-p)
7708 (org-table-goto-column col t)
7709 (and (looking-at "|[^|\n]+|")
7710 (replace-match "|")))
7711 (beginning-of-line 2))
7712 (move-marker end nil)
7713 (goto-line linepos)
7714 (org-table-goto-column colpos)
7715 (org-table-align)
7716 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
7717 col -1 col)))
7719 (defun org-table-move-column-right ()
7720 "Move column to the right."
7721 (interactive)
7722 (org-table-move-column nil))
7723 (defun org-table-move-column-left ()
7724 "Move column to the left."
7725 (interactive)
7726 (org-table-move-column 'left))
7728 (defun org-table-move-column (&optional left)
7729 "Move the current column to the right. With arg LEFT, move to the left."
7730 (interactive "P")
7731 (if (not (org-at-table-p))
7732 (error "Not at a table"))
7733 (org-table-find-dataline)
7734 (org-table-check-inside-data-field)
7735 (let* ((col (org-table-current-column))
7736 (col1 (if left (1- col) col))
7737 (beg (org-table-begin))
7738 (end (org-table-end))
7739 ;; Current cursor position
7740 (linepos (org-current-line))
7741 (colpos (if left (1- col) (1+ col))))
7742 (if (and left (= col 1))
7743 (error "Cannot move column further left"))
7744 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
7745 (error "Cannot move column further right"))
7746 (goto-char beg)
7747 (while (< (point) end)
7748 (if (org-at-table-hline-p)
7750 (org-table-goto-column col1 t)
7751 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
7752 (replace-match "|\\2|\\1|")))
7753 (beginning-of-line 2))
7754 (move-marker end nil)
7755 (goto-line linepos)
7756 (org-table-goto-column colpos)
7757 (org-table-align)
7758 (org-table-fix-formulas
7759 "$" (list (cons (number-to-string col) (number-to-string colpos))
7760 (cons (number-to-string colpos) (number-to-string col))))))
7762 (defun org-table-move-row-down ()
7763 "Move table row down."
7764 (interactive)
7765 (org-table-move-row nil))
7766 (defun org-table-move-row-up ()
7767 "Move table row up."
7768 (interactive)
7769 (org-table-move-row 'up))
7771 (defun org-table-move-row (&optional up)
7772 "Move the current table line down. With arg UP, move it up."
7773 (interactive "P")
7774 (let* ((col (current-column))
7775 (pos (point))
7776 (hline1p (save-excursion (beginning-of-line 1)
7777 (looking-at org-table-hline-regexp)))
7778 (dline1 (org-table-current-dline))
7779 (dline2 (+ dline1 (if up -1 1)))
7780 (tonew (if up 0 2))
7781 txt hline2p)
7782 (beginning-of-line tonew)
7783 (unless (org-at-table-p)
7784 (goto-char pos)
7785 (error "Cannot move row further"))
7786 (setq hline2p (looking-at org-table-hline-regexp))
7787 (goto-char pos)
7788 (beginning-of-line 1)
7789 (setq pos (point))
7790 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
7791 (delete-region (point) (1+ (point-at-eol)))
7792 (beginning-of-line tonew)
7793 (insert txt)
7794 (beginning-of-line 0)
7795 (move-to-column col)
7796 (unless (or hline1p hline2p)
7797 (org-table-fix-formulas
7798 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
7799 (cons (number-to-string dline2) (number-to-string dline1)))))))
7801 (defun org-table-insert-row (&optional arg)
7802 "Insert a new row above the current line into the table.
7803 With prefix ARG, insert below the current line."
7804 (interactive "P")
7805 (if (not (org-at-table-p))
7806 (error "Not at a table"))
7807 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
7808 (new (org-table-clean-line line)))
7809 ;; Fix the first field if necessary
7810 (if (string-match "^[ \t]*| *[#$] *|" line)
7811 (setq new (replace-match (match-string 0 line) t t new)))
7812 (beginning-of-line (if arg 2 1))
7813 (let (org-table-may-need-update) (insert-before-markers new "\n"))
7814 (beginning-of-line 0)
7815 (re-search-forward "| ?" (point-at-eol) t)
7816 (and (or org-table-may-need-update org-table-overlay-coordinates)
7817 (org-table-align))
7818 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
7820 (defun org-table-insert-hline (&optional above)
7821 "Insert a horizontal-line below the current line into the table.
7822 With prefix ABOVE, insert above the current line."
7823 (interactive "P")
7824 (if (not (org-at-table-p))
7825 (error "Not at a table"))
7826 (let ((line (org-table-clean-line
7827 (buffer-substring (point-at-bol) (point-at-eol))))
7828 (col (current-column)))
7829 (while (string-match "|\\( +\\)|" line)
7830 (setq line (replace-match
7831 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
7832 ?-) "|") t t line)))
7833 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
7834 (beginning-of-line (if above 1 2))
7835 (insert line "\n")
7836 (beginning-of-line (if above 1 -1))
7837 (move-to-column col)
7838 (and org-table-overlay-coordinates (org-table-align))))
7840 (defun org-table-hline-and-move (&optional same-column)
7841 "Insert a hline and move to the row below that line."
7842 (interactive "P")
7843 (let ((col (org-table-current-column)))
7844 (org-table-maybe-eval-formula)
7845 (org-table-maybe-recalculate-line)
7846 (org-table-insert-hline)
7847 (end-of-line 2)
7848 (if (looking-at "\n[ \t]*|-")
7849 (progn (insert "\n|") (org-table-align))
7850 (org-table-next-field))
7851 (if same-column (org-table-goto-column col))))
7853 (defun org-table-clean-line (s)
7854 "Convert a table line S into a string with only \"|\" and space.
7855 In particular, this does handle wide and invisible characters."
7856 (if (string-match "^[ \t]*|-" s)
7857 ;; It's a hline, just map the characters
7858 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
7859 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
7860 (setq s (replace-match
7861 (concat "|" (make-string (org-string-width (match-string 1 s))
7862 ?\ ) "|")
7863 t t s)))
7866 (defun org-table-kill-row ()
7867 "Delete the current row or horizontal line from the table."
7868 (interactive)
7869 (if (not (org-at-table-p))
7870 (error "Not at a table"))
7871 (let ((col (current-column))
7872 (dline (org-table-current-dline)))
7873 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
7874 (if (not (org-at-table-p)) (beginning-of-line 0))
7875 (move-to-column col)
7876 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
7877 dline -1 dline)))
7880 (defun org-table-sort-lines (with-case &optional sorting-type)
7881 "Sort table lines according to the column at point.
7883 The position of point indicates the column to be used for
7884 sorting, and the range of lines is the range between the nearest
7885 horizontal separator lines, or the entire table of no such lines
7886 exist. If point is before the first column, you will be prompted
7887 for the sorting column. If there is an active region, the mark
7888 specifies the first line and the sorting column, while point
7889 should be in the last line to be included into the sorting.
7891 The command then prompts for the sorting type which can be
7892 alphabetically, numerically, or by time (as given in a time stamp
7893 in the field). Sorting in reverse order is also possible.
7895 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
7897 If SORTING-TYPE is specified when this function is called from a Lisp
7898 program, no prompting will take place. SORTING-TYPE must be a character,
7899 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
7900 should be done in reverse order."
7901 (interactive "P")
7902 (let* ((thisline (org-current-line))
7903 (thiscol (org-table-current-column))
7904 beg end bcol ecol tend tbeg column lns pos)
7905 (when (equal thiscol 0)
7906 (if (interactive-p)
7907 (setq thiscol
7908 (string-to-number
7909 (read-string "Use column N for sorting: ")))
7910 (setq thiscol 1))
7911 (org-table-goto-column thiscol))
7912 (org-table-check-inside-data-field)
7913 (if (org-region-active-p)
7914 (progn
7915 (setq beg (region-beginning) end (region-end))
7916 (goto-char beg)
7917 (setq column (org-table-current-column)
7918 beg (point-at-bol))
7919 (goto-char end)
7920 (setq end (point-at-bol 2)))
7921 (setq column (org-table-current-column)
7922 pos (point)
7923 tbeg (org-table-begin)
7924 tend (org-table-end))
7925 (if (re-search-backward org-table-hline-regexp tbeg t)
7926 (setq beg (point-at-bol 2))
7927 (goto-char tbeg)
7928 (setq beg (point-at-bol 1)))
7929 (goto-char pos)
7930 (if (re-search-forward org-table-hline-regexp tend t)
7931 (setq end (point-at-bol 1))
7932 (goto-char tend)
7933 (setq end (point-at-bol))))
7934 (setq beg (move-marker (make-marker) beg)
7935 end (move-marker (make-marker) end))
7936 (untabify beg end)
7937 (goto-char beg)
7938 (org-table-goto-column column)
7939 (skip-chars-backward "^|")
7940 (setq bcol (current-column))
7941 (org-table-goto-column (1+ column))
7942 (skip-chars-backward "^|")
7943 (setq ecol (1- (current-column)))
7944 (org-table-goto-column column)
7945 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
7946 (org-split-string (buffer-substring beg end) "\n")))
7947 (setq lns (org-do-sort lns "Table" with-case sorting-type))
7948 (delete-region beg end)
7949 (move-marker beg nil)
7950 (move-marker end nil)
7951 (insert (mapconcat 'cdr lns "\n") "\n")
7952 (goto-line thisline)
7953 (org-table-goto-column thiscol)
7954 (message "%d lines sorted, based on column %d" (length lns) column)))
7956 (defun org-table-cut-region (beg end)
7957 "Copy region in table to the clipboard and blank all relevant fields."
7958 (interactive "r")
7959 (org-table-copy-region beg end 'cut))
7961 (defun org-table-copy-region (beg end &optional cut)
7962 "Copy rectangular region in table to clipboard.
7963 A special clipboard is used which can only be accessed
7964 with `org-table-paste-rectangle'."
7965 (interactive "rP")
7966 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
7967 region cols
7968 (rpl (if cut " " nil)))
7969 (goto-char beg)
7970 (org-table-check-inside-data-field)
7971 (setq l01 (org-current-line)
7972 c01 (org-table-current-column))
7973 (goto-char end)
7974 (org-table-check-inside-data-field)
7975 (setq l02 (org-current-line)
7976 c02 (org-table-current-column))
7977 (setq l1 (min l01 l02) l2 (max l01 l02)
7978 c1 (min c01 c02) c2 (max c01 c02))
7979 (catch 'exit
7980 (while t
7981 (catch 'nextline
7982 (if (> l1 l2) (throw 'exit t))
7983 (goto-line l1)
7984 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
7985 (setq cols nil ic1 c1 ic2 c2)
7986 (while (< ic1 (1+ ic2))
7987 (push (org-table-get-field ic1 rpl) cols)
7988 (setq ic1 (1+ ic1)))
7989 (push (nreverse cols) region)
7990 (setq l1 (1+ l1)))))
7991 (setq org-table-clip (nreverse region))
7992 (if cut (org-table-align))
7993 org-table-clip))
7995 (defun org-table-paste-rectangle ()
7996 "Paste a rectangular region into a table.
7997 The upper right corner ends up in the current field. All involved fields
7998 will be overwritten. If the rectangle does not fit into the present table,
7999 the table is enlarged as needed. The process ignores horizontal separator
8000 lines."
8001 (interactive)
8002 (unless (and org-table-clip (listp org-table-clip))
8003 (error "First cut/copy a region to paste!"))
8004 (org-table-check-inside-data-field)
8005 (let* ((clip org-table-clip)
8006 (line (org-current-line))
8007 (col (org-table-current-column))
8008 (org-enable-table-editor t)
8009 (org-table-automatic-realign nil)
8010 c cols field)
8011 (while (setq cols (pop clip))
8012 (while (org-at-table-hline-p) (beginning-of-line 2))
8013 (if (not (org-at-table-p))
8014 (progn (end-of-line 0) (org-table-next-field)))
8015 (setq c col)
8016 (while (setq field (pop cols))
8017 (org-table-goto-column c nil 'force)
8018 (org-table-get-field nil field)
8019 (setq c (1+ c)))
8020 (beginning-of-line 2))
8021 (goto-line line)
8022 (org-table-goto-column col)
8023 (org-table-align)))
8025 (defun org-table-convert ()
8026 "Convert from `org-mode' table to table.el and back.
8027 Obviously, this only works within limits. When an Org-mode table is
8028 converted to table.el, all horizontal separator lines get lost, because
8029 table.el uses these as cell boundaries and has no notion of horizontal lines.
8030 A table.el table can be converted to an Org-mode table only if it does not
8031 do row or column spanning. Multiline cells will become multiple cells.
8032 Beware, Org-mode does not test if the table can be successfully converted - it
8033 blindly applies a recipe that works for simple tables."
8034 (interactive)
8035 (require 'table)
8036 (if (org-at-table.el-p)
8037 ;; convert to Org-mode table
8038 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8039 (end (move-marker (make-marker) (org-table-end t))))
8040 (table-unrecognize-region beg end)
8041 (goto-char beg)
8042 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8043 (replace-match ""))
8044 (goto-char beg))
8045 (if (org-at-table-p)
8046 ;; convert to table.el table
8047 (let ((beg (move-marker (make-marker) (org-table-begin)))
8048 (end (move-marker (make-marker) (org-table-end))))
8049 ;; first, get rid of all horizontal lines
8050 (goto-char beg)
8051 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8052 (replace-match ""))
8053 ;; insert a hline before first
8054 (goto-char beg)
8055 (org-table-insert-hline 'above)
8056 (beginning-of-line -1)
8057 ;; insert a hline after each line
8058 (while (progn (beginning-of-line 3) (< (point) end))
8059 (org-table-insert-hline))
8060 (goto-char beg)
8061 (setq end (move-marker end (org-table-end)))
8062 ;; replace "+" at beginning and ending of hlines
8063 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8064 (replace-match "\\1+-"))
8065 (goto-char beg)
8066 (while (re-search-forward "-|[ \t]*$" end t)
8067 (replace-match "-+"))
8068 (goto-char beg)))))
8070 (defun org-table-wrap-region (arg)
8071 "Wrap several fields in a column like a paragraph.
8072 This is useful if you'd like to spread the contents of a field over several
8073 lines, in order to keep the table compact.
8075 If there is an active region, and both point and mark are in the same column,
8076 the text in the column is wrapped to minimum width for the given number of
8077 lines. Generally, this makes the table more compact. A prefix ARG may be
8078 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8079 formats the selected text to two lines. If the region was longer than two
8080 lines, the remaining lines remain empty. A negative prefix argument reduces
8081 the current number of lines by that amount. The wrapped text is pasted back
8082 into the table. If you formatted it to more lines than it was before, fields
8083 further down in the table get overwritten - so you might need to make space in
8084 the table first.
8086 If there is no region, the current field is split at the cursor position and
8087 the text fragment to the right of the cursor is prepended to the field one
8088 line down.
8090 If there is no region, but you specify a prefix ARG, the current field gets
8091 blank, and the content is appended to the field above."
8092 (interactive "P")
8093 (org-table-check-inside-data-field)
8094 (if (org-region-active-p)
8095 ;; There is a region: fill as a paragraph
8096 (let* ((beg (region-beginning))
8097 (cline (save-excursion (goto-char beg) (org-current-line)))
8098 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
8099 nlines)
8100 (org-table-cut-region (region-beginning) (region-end))
8101 (if (> (length (car org-table-clip)) 1)
8102 (error "Region must be limited to single column"))
8103 (setq nlines (if arg
8104 (if (< arg 1)
8105 (+ (length org-table-clip) arg)
8106 arg)
8107 (length org-table-clip)))
8108 (setq org-table-clip
8109 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8110 nil nlines)))
8111 (goto-line cline)
8112 (org-table-goto-column ccol)
8113 (org-table-paste-rectangle))
8114 ;; No region, split the current field at point
8115 (if arg
8116 ;; combine with field above
8117 (let ((s (org-table-blank-field))
8118 (col (org-table-current-column)))
8119 (beginning-of-line 0)
8120 (while (org-at-table-hline-p) (beginning-of-line 0))
8121 (org-table-goto-column col)
8122 (skip-chars-forward "^|")
8123 (skip-chars-backward " ")
8124 (insert " " (org-trim s))
8125 (org-table-align))
8126 ;; split field
8127 (when (looking-at "\\([^|]+\\)+|")
8128 (let ((s (match-string 1)))
8129 (replace-match " |")
8130 (goto-char (match-beginning 0))
8131 (org-table-next-row)
8132 (insert (org-trim s) " ")
8133 (org-table-align))))))
8135 (defvar org-field-marker nil)
8137 (defun org-table-edit-field (arg)
8138 "Edit table field in a different window.
8139 This is mainly useful for fields that contain hidden parts.
8140 When called with a \\[universal-argument] prefix, just make the full field visible so that
8141 it can be edited in place."
8142 (interactive "P")
8143 (if arg
8144 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
8145 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
8146 (remove-text-properties b e '(org-cwidth t invisible t
8147 display t intangible t))
8148 (if (and (boundp 'font-lock-mode) font-lock-mode)
8149 (font-lock-fontify-block)))
8150 (let ((pos (move-marker (make-marker) (point)))
8151 (field (org-table-get-field))
8152 (cw (current-window-configuration))
8154 (switch-to-buffer-other-window "*Org tmp*")
8155 (erase-buffer)
8156 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
8157 (let ((org-inhibit-startup t)) (org-mode))
8158 (goto-char (setq p (point-max)))
8159 (insert (org-trim field))
8160 (remove-text-properties p (point-max)
8161 '(invisible t org-cwidth t display t
8162 intangible t))
8163 (goto-char p)
8164 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
8165 (org-set-local 'org-window-configuration cw)
8166 (org-set-local 'org-field-marker pos)
8167 (message "Edit and finish with C-c C-c"))))
8169 (defun org-table-finish-edit-field ()
8170 "Finish editing a table data field.
8171 Remove all newline characters, insert the result into the table, realign
8172 the table and kill the editing buffer."
8173 (let ((pos org-field-marker)
8174 (cw org-window-configuration)
8175 (cb (current-buffer))
8176 text)
8177 (goto-char (point-min))
8178 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
8179 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
8180 (replace-match " "))
8181 (setq text (org-trim (buffer-string)))
8182 (set-window-configuration cw)
8183 (kill-buffer cb)
8184 (select-window (get-buffer-window (marker-buffer pos)))
8185 (goto-char pos)
8186 (move-marker pos nil)
8187 (org-table-check-inside-data-field)
8188 (org-table-get-field nil text)
8189 (org-table-align)
8190 (message "New field value inserted")))
8192 (defun org-trim (s)
8193 "Remove whitespace at beginning and end of string."
8194 (if (string-match "^[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
8195 (if (string-match "[ \t\n\r]+$" s) (setq s (replace-match "" t t s)))
8198 (defun org-wrap (string &optional width lines)
8199 "Wrap string to either a number of lines, or a width in characters.
8200 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8201 that costs. If there is a word longer than WIDTH, the text is actually
8202 wrapped to the length of that word.
8203 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8204 many lines, whatever width that takes.
8205 The return value is a list of lines, without newlines at the end."
8206 (let* ((words (org-split-string string "[ \t\n]+"))
8207 (maxword (apply 'max (mapcar 'org-string-width words)))
8208 w ll)
8209 (cond (width
8210 (org-do-wrap words (max maxword width)))
8211 (lines
8212 (setq w maxword)
8213 (setq ll (org-do-wrap words maxword))
8214 (if (<= (length ll) lines)
8216 (setq ll words)
8217 (while (> (length ll) lines)
8218 (setq w (1+ w))
8219 (setq ll (org-do-wrap words w)))
8220 ll))
8221 (t (error "Cannot wrap this")))))
8224 (defun org-do-wrap (words width)
8225 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8226 (let (lines line)
8227 (while words
8228 (setq line (pop words))
8229 (while (and words (< (+ (length line) (length (car words))) width))
8230 (setq line (concat line " " (pop words))))
8231 (setq lines (push line lines)))
8232 (nreverse lines)))
8234 (defun org-split-string (string &optional separators)
8235 "Splits STRING into substrings at SEPARATORS.
8236 No empty strings are returned if there are matches at the beginning
8237 and end of string."
8238 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8239 (start 0)
8240 notfirst
8241 (list nil))
8242 (while (and (string-match rexp string
8243 (if (and notfirst
8244 (= start (match-beginning 0))
8245 (< start (length string)))
8246 (1+ start) start))
8247 (< (match-beginning 0) (length string)))
8248 (setq notfirst t)
8249 (or (eq (match-beginning 0) 0)
8250 (and (eq (match-beginning 0) (match-end 0))
8251 (eq (match-beginning 0) start))
8252 (setq list
8253 (cons (substring string start (match-beginning 0))
8254 list)))
8255 (setq start (match-end 0)))
8256 (or (eq start (length string))
8257 (setq list
8258 (cons (substring string start)
8259 list)))
8260 (nreverse list)))
8262 (defun org-table-map-tables (function)
8263 "Apply FUNCTION to the start of all tables in the buffer."
8264 (save-excursion
8265 (save-restriction
8266 (widen)
8267 (goto-char (point-min))
8268 (while (re-search-forward org-table-any-line-regexp nil t)
8269 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8270 (beginning-of-line 1)
8271 (if (looking-at org-table-line-regexp)
8272 (save-excursion (funcall function)))
8273 (re-search-forward org-table-any-border-regexp nil 1))))
8274 (message "Mapping tables: done"))
8276 (defvar org-timecnt) ; dynamically scoped parameter
8278 (defun org-table-sum (&optional beg end nlast)
8279 "Sum numbers in region of current table column.
8280 The result will be displayed in the echo area, and will be available
8281 as kill to be inserted with \\[yank].
8283 If there is an active region, it is interpreted as a rectangle and all
8284 numbers in that rectangle will be summed. If there is no active
8285 region and point is located in a table column, sum all numbers in that
8286 column.
8288 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8289 numbers are assumed to be times as well (in decimal hours) and the
8290 numbers are added as such.
8292 If NLAST is a number, only the NLAST fields will actually be summed."
8293 (interactive)
8294 (save-excursion
8295 (let (col (org-timecnt 0) diff h m s org-table-clip)
8296 (cond
8297 ((and beg end)) ; beg and end given explicitly
8298 ((org-region-active-p)
8299 (setq beg (region-beginning) end (region-end)))
8301 (setq col (org-table-current-column))
8302 (goto-char (org-table-begin))
8303 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8304 (error "No table data"))
8305 (org-table-goto-column col)
8306 (setq beg (point))
8307 (goto-char (org-table-end))
8308 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8309 (error "No table data"))
8310 (org-table-goto-column col)
8311 (setq end (point))))
8312 (let* ((items (apply 'append (org-table-copy-region beg end)))
8313 (items1 (cond ((not nlast) items)
8314 ((>= nlast (length items)) items)
8315 (t (setq items (reverse items))
8316 (setcdr (nthcdr (1- nlast) items) nil)
8317 (nreverse items))))
8318 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8319 items1)))
8320 (res (apply '+ numbers))
8321 (sres (if (= org-timecnt 0)
8322 (format "%g" res)
8323 (setq diff (* 3600 res)
8324 h (floor (/ diff 3600)) diff (mod diff 3600)
8325 m (floor (/ diff 60)) diff (mod diff 60)
8326 s diff)
8327 (format "%d:%02d:%02d" h m s))))
8328 (kill-new sres)
8329 (if (interactive-p)
8330 (message "%s"
8331 (substitute-command-keys
8332 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8333 (length numbers) sres))))
8334 sres))))
8336 (defun org-table-get-number-for-summing (s)
8337 (let (n)
8338 (if (string-match "^ *|? *" s)
8339 (setq s (replace-match "" nil nil s)))
8340 (if (string-match " *|? *$" s)
8341 (setq s (replace-match "" nil nil s)))
8342 (setq n (string-to-number s))
8343 (cond
8344 ((and (string-match "0" s)
8345 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8346 ((string-match "\\`[ \t]+\\'" s) nil)
8347 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8348 (let ((h (string-to-number (or (match-string 1 s) "0")))
8349 (m (string-to-number (or (match-string 2 s) "0")))
8350 (s (string-to-number (or (match-string 4 s) "0"))))
8351 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
8352 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8353 ((equal n 0) nil)
8354 (t n))))
8356 (defun org-table-current-field-formula (&optional key noerror)
8357 "Return the formula active for the current field.
8358 Assumes that specials are in place.
8359 If KEY is given, return the key to this formula.
8360 Otherwise return the formula preceeded with \"=\" or \":=\"."
8361 (let* ((name (car (rassoc (list (org-current-line)
8362 (org-table-current-column))
8363 org-table-named-field-locations)))
8364 (col (org-table-current-column))
8365 (scol (int-to-string col))
8366 (ref (format "@%d$%d" (org-table-current-dline) col))
8367 (stored-list (org-table-get-stored-formulas noerror))
8368 (ass (or (assoc name stored-list)
8369 (assoc ref stored-list)
8370 (assoc scol stored-list))))
8371 (if key
8372 (car ass)
8373 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
8374 (cdr ass))))))
8376 (defun org-table-get-formula (&optional equation named)
8377 "Read a formula from the minibuffer, offer stored formula as default.
8378 When NAMED is non-nil, look for a named equation."
8379 (let* ((stored-list (org-table-get-stored-formulas))
8380 (name (car (rassoc (list (org-current-line)
8381 (org-table-current-column))
8382 org-table-named-field-locations)))
8383 (ref (format "@%d$%d" (org-table-current-dline)
8384 (org-table-current-column)))
8385 (refass (assoc ref stored-list))
8386 (scol (if named
8387 (if name name ref)
8388 (int-to-string (org-table-current-column))))
8389 (dummy (and (or name refass) (not named)
8390 (not (y-or-n-p "Replace field formula with column formula? " ))
8391 (error "Abort")))
8392 (name (or name ref))
8393 (org-table-may-need-update nil)
8394 (stored (cdr (assoc scol stored-list)))
8395 (eq (cond
8396 ((and stored equation (string-match "^ *=? *$" equation))
8397 stored)
8398 ((stringp equation)
8399 equation)
8400 (t (org-table-formula-from-user
8401 (read-string
8402 (org-table-formula-to-user
8403 (format "%s formula %s%s="
8404 (if named "Field" "Column")
8405 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
8406 scol))
8407 (if stored (org-table-formula-to-user stored) "")
8408 'org-table-formula-history
8409 )))))
8410 mustsave)
8411 (when (not (string-match "\\S-" eq))
8412 ;; remove formula
8413 (setq stored-list (delq (assoc scol stored-list) stored-list))
8414 (org-table-store-formulas stored-list)
8415 (error "Formula removed"))
8416 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8417 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8418 (if (and name (not named))
8419 ;; We set the column equation, delete the named one.
8420 (setq stored-list (delq (assoc name stored-list) stored-list)
8421 mustsave t))
8422 (if stored
8423 (setcdr (assoc scol stored-list) eq)
8424 (setq stored-list (cons (cons scol eq) stored-list)))
8425 (if (or mustsave (not (equal stored eq)))
8426 (org-table-store-formulas stored-list))
8427 eq))
8429 (defun org-table-store-formulas (alist)
8430 "Store the list of formulas below the current table."
8431 (setq alist (sort alist 'org-table-formula-less-p))
8432 (save-excursion
8433 (goto-char (org-table-end))
8434 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
8435 (progn
8436 ;; don't overwrite TBLFM, we might use text properties to store stuff
8437 (goto-char (match-beginning 2))
8438 (delete-region (match-beginning 2) (match-end 0)))
8439 (insert "#+TBLFM:"))
8440 (insert " "
8441 (mapconcat (lambda (x)
8442 (concat
8443 (if (equal (string-to-char (car x)) ?@) "" "$")
8444 (car x) "=" (cdr x)))
8445 alist "::")
8446 "\n")))
8448 (defsubst org-table-formula-make-cmp-string (a)
8449 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
8450 (concat
8451 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
8452 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
8453 (if (match-end 5) (concat "@@" (match-string 5 a))))))
8455 (defun org-table-formula-less-p (a b)
8456 "Compare two formulas for sorting."
8457 (let ((as (org-table-formula-make-cmp-string (car a)))
8458 (bs (org-table-formula-make-cmp-string (car b))))
8459 (and as bs (string< as bs))))
8461 (defun org-table-get-stored-formulas (&optional noerror)
8462 "Return an alist with the stored formulas directly after current table."
8463 (interactive)
8464 (let (scol eq eq-alist strings string seen)
8465 (save-excursion
8466 (goto-char (org-table-end))
8467 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8468 (setq strings (org-split-string (match-string 2) " *:: *"))
8469 (while (setq string (pop strings))
8470 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
8471 (setq scol (if (match-end 2)
8472 (match-string 2 string)
8473 (match-string 1 string))
8474 eq (match-string 3 string)
8475 eq-alist (cons (cons scol eq) eq-alist))
8476 (if (member scol seen)
8477 (if noerror
8478 (progn
8479 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8480 (ding)
8481 (sit-for 2))
8482 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
8483 (push scol seen))))))
8484 (nreverse eq-alist)))
8486 (defun org-table-fix-formulas (key replace &optional limit delta remove)
8487 "Modify the equations after the table structure has been edited.
8488 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
8489 For all numbers larger than LIMIT, shift them by DELTA."
8490 (save-excursion
8491 (goto-char (org-table-end))
8492 (when (looking-at "#\\+TBLFM:")
8493 (let ((re (concat key "\\([0-9]+\\)"))
8494 (re2
8495 (when remove
8496 (if (equal key "$")
8497 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
8498 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
8499 s n a)
8500 (when remove
8501 (while (re-search-forward re2 (point-at-eol) t)
8502 (replace-match "")))
8503 (while (re-search-forward re (point-at-eol) t)
8504 (setq s (match-string 1) n (string-to-number s))
8505 (cond
8506 ((setq a (assoc s replace))
8507 (replace-match (concat key (cdr a)) t t))
8508 ((and limit (> n limit))
8509 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
8511 (defun org-table-get-specials ()
8512 "Get the column names and local parameters for this table."
8513 (save-excursion
8514 (let ((beg (org-table-begin)) (end (org-table-end))
8515 names name fields fields1 field cnt
8516 c v l line col types dlines hlines)
8517 (setq org-table-column-names nil
8518 org-table-local-parameters nil
8519 org-table-named-field-locations nil
8520 org-table-current-begin-line nil
8521 org-table-current-begin-pos nil
8522 org-table-current-line-types nil)
8523 (goto-char beg)
8524 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8525 (setq names (org-split-string (match-string 1) " *| *")
8526 cnt 1)
8527 (while (setq name (pop names))
8528 (setq cnt (1+ cnt))
8529 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8530 (push (cons name (int-to-string cnt)) org-table-column-names))))
8531 (setq org-table-column-names (nreverse org-table-column-names))
8532 (setq org-table-column-name-regexp
8533 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8534 (goto-char beg)
8535 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8536 (setq fields (org-split-string (match-string 1) " *| *"))
8537 (while (setq field (pop fields))
8538 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8539 (push (cons (match-string 1 field) (match-string 2 field))
8540 org-table-local-parameters))))
8541 (goto-char beg)
8542 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8543 (setq c (match-string 1)
8544 fields (org-split-string (match-string 2) " *| *"))
8545 (save-excursion
8546 (beginning-of-line (if (equal c "_") 2 0))
8547 (setq line (org-current-line) col 1)
8548 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8549 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8550 (while (and fields1 (setq field (pop fields)))
8551 (setq v (pop fields1) col (1+ col))
8552 (when (and (stringp field) (stringp v)
8553 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8554 (push (cons field v) org-table-local-parameters)
8555 (push (list field line col) org-table-named-field-locations))))
8556 ;; Analyse the line types
8557 (goto-char beg)
8558 (setq org-table-current-begin-line (org-current-line)
8559 org-table-current-begin-pos (point)
8560 l org-table-current-begin-line)
8561 (while (looking-at "[ \t]*|\\(-\\)?")
8562 (push (if (match-end 1) 'hline 'dline) types)
8563 (if (match-end 1) (push l hlines) (push l dlines))
8564 (beginning-of-line 2)
8565 (setq l (1+ l)))
8566 (setq org-table-current-line-types (apply 'vector (nreverse types))
8567 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
8568 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
8570 (defun org-table-maybe-eval-formula ()
8571 "Check if the current field starts with \"=\" or \":=\".
8572 If yes, store the formula and apply it."
8573 ;; We already know we are in a table. Get field will only return a formula
8574 ;; when appropriate. It might return a separator line, but no problem.
8575 (when org-table-formula-evaluate-inline
8576 (let* ((field (org-trim (or (org-table-get-field) "")))
8577 named eq)
8578 (when (string-match "^:?=\\(.*\\)" field)
8579 (setq named (equal (string-to-char field) ?:)
8580 eq (match-string 1 field))
8581 (if (or (fboundp 'calc-eval)
8582 (equal (substring eq 0 (min 2 (length eq))) "'("))
8583 (org-table-eval-formula (if named '(4) nil)
8584 (org-table-formula-from-user eq))
8585 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
8587 (defvar org-recalc-commands nil
8588 "List of commands triggering the recalculation of a line.
8589 Will be filled automatically during use.")
8591 (defvar org-recalc-marks
8592 '((" " . "Unmarked: no special line, no automatic recalculation")
8593 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
8594 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
8595 ("!" . "Column name definition line. Reference in formula as $name.")
8596 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8597 ("_" . "Names for values in row below this one.")
8598 ("^" . "Names for values in row above this one.")))
8600 (defun org-table-rotate-recalc-marks (&optional newchar)
8601 "Rotate the recalculation mark in the first column.
8602 If in any row, the first field is not consistent with a mark,
8603 insert a new column for the markers.
8604 When there is an active region, change all the lines in the region,
8605 after prompting for the marking character.
8606 After each change, a message will be displayed indicating the meaning
8607 of the new mark."
8608 (interactive)
8609 (unless (org-at-table-p) (error "Not at a table"))
8610 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8611 (beg (org-table-begin))
8612 (end (org-table-end))
8613 (l (org-current-line))
8614 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8615 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8616 (have-col
8617 (save-excursion
8618 (goto-char beg)
8619 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8620 (col (org-table-current-column))
8621 (forcenew (car (assoc newchar org-recalc-marks)))
8622 epos new)
8623 (when l1
8624 (message "Change region to what mark? Type # * ! $ or SPC: ")
8625 (setq newchar (char-to-string (read-char-exclusive))
8626 forcenew (car (assoc newchar org-recalc-marks))))
8627 (if (and newchar (not forcenew))
8628 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8629 newchar))
8630 (if l1 (goto-line l1))
8631 (save-excursion
8632 (beginning-of-line 1)
8633 (unless (looking-at org-table-dataline-regexp)
8634 (error "Not at a table data line")))
8635 (unless have-col
8636 (org-table-goto-column 1)
8637 (org-table-insert-column)
8638 (org-table-goto-column (1+ col)))
8639 (setq epos (point-at-eol))
8640 (save-excursion
8641 (beginning-of-line 1)
8642 (org-table-get-field
8643 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8644 (concat " "
8645 (setq new (or forcenew
8646 (cadr (member (match-string 1) marks))))
8647 " ")
8648 " # ")))
8649 (if (and l1 l2)
8650 (progn
8651 (goto-line l1)
8652 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8653 (and (looking-at org-table-dataline-regexp)
8654 (org-table-get-field 1 (concat " " new " "))))
8655 (goto-line l1)))
8656 (if (not (= epos (point-at-eol))) (org-table-align))
8657 (goto-line l)
8658 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
8660 (defun org-table-maybe-recalculate-line ()
8661 "Recompute the current line if marked for it, and if we haven't just done it."
8662 (interactive)
8663 (and org-table-allow-automatic-line-recalculation
8664 (not (and (memq last-command org-recalc-commands)
8665 (equal org-last-recalc-line (org-current-line))))
8666 (save-excursion (beginning-of-line 1)
8667 (looking-at org-table-auto-recalculate-regexp))
8668 (org-table-recalculate) t))
8670 (defvar org-table-formula-debug nil
8671 "Non-nil means, debug table formulas.
8672 When nil, simply write \"#ERROR\" in corrupted fields.")
8673 (make-variable-buffer-local 'org-table-formula-debug)
8675 (defvar modes)
8676 (defsubst org-set-calc-mode (var &optional value)
8677 (if (stringp var)
8678 (setq var (assoc var '(("D" calc-angle-mode deg)
8679 ("R" calc-angle-mode rad)
8680 ("F" calc-prefer-frac t)
8681 ("S" calc-symbolic-mode t)))
8682 value (nth 2 var) var (nth 1 var)))
8683 (if (memq var modes)
8684 (setcar (cdr (memq var modes)) value)
8685 (cons var (cons value modes)))
8686 modes)
8688 (defun org-table-eval-formula (&optional arg equation
8689 suppress-align suppress-const
8690 suppress-store suppress-analysis)
8691 "Replace the table field value at the cursor by the result of a calculation.
8693 This function makes use of Dave Gillespie's Calc package, in my view the
8694 most exciting program ever written for GNU Emacs. So you need to have Calc
8695 installed in order to use this function.
8697 In a table, this command replaces the value in the current field with the
8698 result of a formula. It also installs the formula as the \"current\" column
8699 formula, by storing it in a special line below the table. When called
8700 with a `C-u' prefix, the current field must ba a named field, and the
8701 formula is installed as valid in only this specific field.
8703 When called with two `C-u' prefixes, insert the active equation
8704 for the field back into the current field, so that it can be
8705 edited there. This is useful in order to use \\[org-table-show-reference]
8706 to check the referenced fields.
8708 When called, the command first prompts for a formula, which is read in
8709 the minibuffer. Previously entered formulas are available through the
8710 history list, and the last used formula is offered as a default.
8711 These stored formulas are adapted correctly when moving, inserting, or
8712 deleting columns with the corresponding commands.
8714 The formula can be any algebraic expression understood by the Calc package.
8715 For details, see the Org-mode manual.
8717 This function can also be called from Lisp programs and offers
8718 additional arguments: EQUATION can be the formula to apply. If this
8719 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
8720 used to speed-up recursive calls by by-passing unnecessary aligns.
8721 SUPPRESS-CONST suppresses the interpretation of constants in the
8722 formula, assuming that this has been done already outside the function.
8723 SUPPRESS-STORE means the formula should not be stored, either because
8724 it is already stored, or because it is a modified equation that should
8725 not overwrite the stored one."
8726 (interactive "P")
8727 (org-table-check-inside-data-field)
8728 (or suppress-analysis (org-table-get-specials))
8729 (if (equal arg '(16))
8730 (let ((eq (org-table-current-field-formula)))
8731 (or eq (error "No equation active for current field"))
8732 (org-table-get-field nil eq)
8733 (org-table-align)
8734 (setq org-table-may-need-update t))
8735 (let* (fields
8736 (ndown (if (integerp arg) arg 1))
8737 (org-table-automatic-realign nil)
8738 (case-fold-search nil)
8739 (down (> ndown 1))
8740 (formula (if (and equation suppress-store)
8741 equation
8742 (org-table-get-formula equation (equal arg '(4)))))
8743 (n0 (org-table-current-column))
8744 (modes (copy-sequence org-calc-default-modes))
8745 (numbers nil) ; was a variable, now fixed default
8746 (keep-empty nil)
8747 n form form0 bw fmt x ev orig c lispp literal)
8748 ;; Parse the format string. Since we have a lot of modes, this is
8749 ;; a lot of work. However, I think calc still uses most of the time.
8750 (if (string-match ";" formula)
8751 (let ((tmp (org-split-string formula ";")))
8752 (setq formula (car tmp)
8753 fmt (concat (cdr (assoc "%" org-table-local-parameters))
8754 (nth 1 tmp)))
8755 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
8756 (setq c (string-to-char (match-string 1 fmt))
8757 n (string-to-number (match-string 2 fmt)))
8758 (if (= c ?p)
8759 (setq modes (org-set-calc-mode 'calc-internal-prec n))
8760 (setq modes (org-set-calc-mode
8761 'calc-float-format
8762 (list (cdr (assoc c '((?n . float) (?f . fix)
8763 (?s . sci) (?e . eng))))
8764 n))))
8765 (setq fmt (replace-match "" t t fmt)))
8766 (if (string-match "[NT]" fmt)
8767 (setq numbers (equal (match-string 0 fmt) "N")
8768 fmt (replace-match "" t t fmt)))
8769 (if (string-match "L" fmt)
8770 (setq literal t
8771 fmt (replace-match "" t t fmt)))
8772 (if (string-match "E" fmt)
8773 (setq keep-empty t
8774 fmt (replace-match "" t t fmt)))
8775 (while (string-match "[DRFS]" fmt)
8776 (setq modes (org-set-calc-mode (match-string 0 fmt)))
8777 (setq fmt (replace-match "" t t fmt)))
8778 (unless (string-match "\\S-" fmt)
8779 (setq fmt nil))))
8780 (if (and (not suppress-const) org-table-formula-use-constants)
8781 (setq formula (org-table-formula-substitute-names formula)))
8782 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
8783 (while (> ndown 0)
8784 (setq fields (org-split-string
8785 (org-no-properties
8786 (buffer-substring (point-at-bol) (point-at-eol)))
8787 " *| *"))
8788 (if (eq numbers t)
8789 (setq fields (mapcar
8790 (lambda (x) (number-to-string (string-to-number x)))
8791 fields)))
8792 (setq ndown (1- ndown))
8793 (setq form (copy-sequence formula)
8794 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
8795 (if (and lispp literal) (setq lispp 'literal))
8796 ;; Check for old vertical references
8797 (setq form (org-rewrite-old-row-references form))
8798 ;; Insert complex ranges
8799 (while (string-match org-table-range-regexp form)
8800 (setq form
8801 (replace-match
8802 (save-match-data
8803 (org-table-make-reference
8804 (org-table-get-range (match-string 0 form) nil n0)
8805 keep-empty numbers lispp))
8806 t t form)))
8807 ;; Insert simple ranges
8808 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
8809 (setq form
8810 (replace-match
8811 (save-match-data
8812 (org-table-make-reference
8813 (org-sublist
8814 fields (string-to-number (match-string 1 form))
8815 (string-to-number (match-string 2 form)))
8816 keep-empty numbers lispp))
8817 t t form)))
8818 (setq form0 form)
8819 ;; Insert the references to fields in same row
8820 (while (string-match "\\$\\([0-9]+\\)" form)
8821 (setq n (string-to-number (match-string 1 form))
8822 x (nth (1- (if (= n 0) n0 n)) fields))
8823 (unless x (error "Invalid field specifier \"%s\""
8824 (match-string 0 form)))
8825 (setq form (replace-match
8826 (save-match-data
8827 (org-table-make-reference x nil numbers lispp))
8828 t t form)))
8830 (if lispp
8831 (setq ev (condition-case nil
8832 (eval (eval (read form)))
8833 (error "#ERROR"))
8834 ev (if (numberp ev) (number-to-string ev) ev))
8835 (or (fboundp 'calc-eval)
8836 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
8837 (setq ev (calc-eval (cons form modes)
8838 (if numbers 'num))))
8840 (when org-table-formula-debug
8841 (with-output-to-temp-buffer "*Substitution History*"
8842 (princ (format "Substitution history of formula
8843 Orig: %s
8844 $xyz-> %s
8845 @r$c-> %s
8846 $1-> %s\n" orig formula form0 form))
8847 (if (listp ev)
8848 (princ (format " %s^\nError: %s"
8849 (make-string (car ev) ?\-) (nth 1 ev)))
8850 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
8851 ev (or fmt "NONE")
8852 (if fmt (format fmt (string-to-number ev)) ev)))))
8853 (setq bw (get-buffer-window "*Substitution History*"))
8854 (shrink-window-if-larger-than-buffer bw)
8855 (unless (and (interactive-p) (not ndown))
8856 (unless (let (inhibit-redisplay)
8857 (y-or-n-p "Debugging Formula. Continue to next? "))
8858 (org-table-align)
8859 (error "Abort"))
8860 (delete-window bw)
8861 (message "")))
8862 (if (listp ev) (setq fmt nil ev "#ERROR"))
8863 (org-table-justify-field-maybe
8864 (if fmt (format fmt (string-to-number ev)) ev))
8865 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
8866 (call-interactively 'org-return)
8867 (setq ndown 0)))
8868 (and down (org-table-maybe-recalculate-line))
8869 (or suppress-align (and org-table-may-need-update
8870 (org-table-align))))))
8872 (defun org-table-put-field-property (prop value)
8873 (save-excursion
8874 (put-text-property (progn (skip-chars-backward "^|") (point))
8875 (progn (skip-chars-forward "^|") (point))
8876 prop value)))
8878 (defun org-table-get-range (desc &optional tbeg col highlight)
8879 "Get a calc vector from a column, accorting to descriptor DESC.
8880 Optional arguments TBEG and COL can give the beginning of the table and
8881 the current column, to avoid unnecessary parsing.
8882 HIGHLIGHT means, just highlight the range."
8883 (if (not (equal (string-to-char desc) ?@))
8884 (setq desc (concat "@" desc)))
8885 (save-excursion
8886 (or tbeg (setq tbeg (org-table-begin)))
8887 (or col (setq col (org-table-current-column)))
8888 (let ((thisline (org-current-line))
8889 beg end c1 c2 r1 r2 rangep tmp)
8890 (unless (string-match org-table-range-regexp desc)
8891 (error "Invalid table range specifier `%s'" desc))
8892 (setq rangep (match-end 3)
8893 r1 (and (match-end 1) (match-string 1 desc))
8894 r2 (and (match-end 4) (match-string 4 desc))
8895 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
8896 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
8898 (and c1 (setq c1 (+ (string-to-number c1)
8899 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
8900 (and c2 (setq c2 (+ (string-to-number c2)
8901 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
8902 (if (equal r1 "") (setq r1 nil))
8903 (if (equal r2 "") (setq r2 nil))
8904 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
8905 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
8906 ; (setq r2 (or r2 r1) c2 (or c2 c1))
8907 (if (not r1) (setq r1 thisline))
8908 (if (not r2) (setq r2 thisline))
8909 (if (not c1) (setq c1 col))
8910 (if (not c2) (setq c2 col))
8911 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
8912 ;; just one field
8913 (progn
8914 (goto-line r1)
8915 (while (not (looking-at org-table-dataline-regexp))
8916 (beginning-of-line 2))
8917 (prog1 (org-trim (org-table-get-field c1))
8918 (if highlight (org-table-highlight-rectangle (point) (point)))))
8919 ;; A range, return a vector
8920 ;; First sort the numbers to get a regular ractangle
8921 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
8922 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
8923 (goto-line r1)
8924 (while (not (looking-at org-table-dataline-regexp))
8925 (beginning-of-line 2))
8926 (org-table-goto-column c1)
8927 (setq beg (point))
8928 (goto-line r2)
8929 (while (not (looking-at org-table-dataline-regexp))
8930 (beginning-of-line 0))
8931 (org-table-goto-column c2)
8932 (setq end (point))
8933 (if highlight
8934 (org-table-highlight-rectangle
8935 beg (progn (skip-chars-forward "^|\n") (point))))
8936 ;; return string representation of calc vector
8937 (mapcar 'org-trim
8938 (apply 'append (org-table-copy-region beg end)))))))
8940 (defun org-table-get-descriptor-line (desc &optional cline bline table)
8941 "Analyze descriptor DESC and retrieve the corresponding line number.
8942 The cursor is currently in line CLINE, the table begins in line BLINE,
8943 and TABLE is a vector with line types."
8944 (if (string-match "^[0-9]+$" desc)
8945 (aref org-table-dlines (string-to-number desc))
8946 (setq cline (or cline (org-current-line))
8947 bline (or bline org-table-current-begin-line)
8948 table (or table org-table-current-line-types))
8949 (if (or
8950 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
8951 ;; 1 2 3 4 5 6
8952 (and (not (match-end 3)) (not (match-end 6)))
8953 (and (match-end 3) (match-end 6) (not (match-end 5))))
8954 (error "invalid row descriptor `%s'" desc))
8955 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
8956 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
8957 (odir (and (match-end 5) (match-string 5 desc)))
8958 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
8959 (i (- cline bline))
8960 (rel (and (match-end 6)
8961 (or (and (match-end 1) (not (match-end 3)))
8962 (match-end 5)))))
8963 (if (and hn (not hdir))
8964 (progn
8965 (setq i 0 hdir "+")
8966 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
8967 (if (and (not hn) on (not odir))
8968 (error "should never happen");;(aref org-table-dlines on)
8969 (if (and hn (> hn 0))
8970 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
8971 (if on
8972 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
8973 (+ bline i)))))
8975 (defun org-find-row-type (table i type backwards relative n)
8976 (let ((l (length table)))
8977 (while (> n 0)
8978 (while (and (setq i (+ i (if backwards -1 1)))
8979 (>= i 0) (< i l)
8980 (not (eq (aref table i) type))
8981 (if (and relative (eq (aref table i) 'hline))
8982 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
8983 t)))
8984 (setq n (1- n)))
8985 (if (or (< i 0) (>= i l))
8986 (error "Row descriptior leads outside table")
8987 i)))
8989 (defun org-rewrite-old-row-references (s)
8990 (if (string-match "&[-+0-9I]" s)
8991 (error "Formula contains old &row reference, please rewrite using @-syntax")
8994 (defun org-table-make-reference (elements keep-empty numbers lispp)
8995 "Convert list ELEMENTS to something appropriate to insert into formula.
8996 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
8997 NUMBERS indicates that everything should be converted to numbers.
8998 LISPP means to return something appropriate for a Lisp list."
8999 (if (stringp elements) ; just a single val
9000 (if lispp
9001 (if (eq lispp 'literal)
9002 elements
9003 (prin1-to-string (if numbers (string-to-number elements) elements)))
9004 (if (equal elements "") (setq elements "0"))
9005 (if numbers (number-to-string (string-to-number elements)) elements))
9006 (unless keep-empty
9007 (setq elements
9008 (delq nil
9009 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
9010 elements))))
9011 (setq elements (or elements '("0")))
9012 (if lispp
9013 (mapconcat
9014 (lambda (x)
9015 (if (eq lispp 'literal)
9017 (prin1-to-string (if numbers (string-to-number x) x))))
9018 elements " ")
9019 (concat "[" (mapconcat
9020 (lambda (x)
9021 (if numbers (number-to-string (string-to-number x)) x))
9022 elements
9023 ",") "]"))))
9025 (defun org-table-recalculate (&optional all noalign)
9026 "Recalculate the current table line by applying all stored formulas.
9027 With prefix arg ALL, do this for all lines in the table."
9028 (interactive "P")
9029 (or (memq this-command org-recalc-commands)
9030 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9031 (unless (org-at-table-p) (error "Not at a table"))
9032 (if (equal all '(16))
9033 (org-table-iterate)
9034 (org-table-get-specials)
9035 (let* ((eqlist (sort (org-table-get-stored-formulas)
9036 (lambda (a b) (string< (car a) (car b)))))
9037 (inhibit-redisplay (not debug-on-error))
9038 (line-re org-table-dataline-regexp)
9039 (thisline (org-current-line))
9040 (thiscol (org-table-current-column))
9041 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
9042 ;; Insert constants in all formulas
9043 (setq eqlist
9044 (mapcar (lambda (x)
9045 (setcdr x (org-table-formula-substitute-names (cdr x)))
9047 eqlist))
9048 ;; Split the equation list
9049 (while (setq eq (pop eqlist))
9050 (if (<= (string-to-char (car eq)) ?9)
9051 (push eq eqlnum)
9052 (push eq eqlname)))
9053 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9054 (if all
9055 (progn
9056 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9057 (goto-char (setq beg (org-table-begin)))
9058 (if (re-search-forward org-table-calculate-mark-regexp end t)
9059 ;; This is a table with marked lines, compute selected lines
9060 (setq line-re org-table-recalculate-regexp)
9061 ;; Move forward to the first non-header line
9062 (if (and (re-search-forward org-table-dataline-regexp end t)
9063 (re-search-forward org-table-hline-regexp end t)
9064 (re-search-forward org-table-dataline-regexp end t))
9065 (setq beg (match-beginning 0))
9066 nil))) ;; just leave beg where it is
9067 (setq beg (point-at-bol)
9068 end (move-marker (make-marker) (1+ (point-at-eol)))))
9069 (goto-char beg)
9070 (and all (message "Re-applying formulas to full table..."))
9072 ;; First find the named fields, and mark them untouchanble
9073 (remove-text-properties beg end '(org-untouchable t))
9074 (while (setq eq (pop eqlname))
9075 (setq name (car eq)
9076 a (assoc name org-table-named-field-locations))
9077 (and (not a)
9078 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
9079 (setq a (list name
9080 (aref org-table-dlines
9081 (string-to-number (match-string 1 name)))
9082 (string-to-number (match-string 2 name)))))
9083 (when (and a (or all (equal (nth 1 a) thisline)))
9084 (message "Re-applying formula to field: %s" name)
9085 (goto-line (nth 1 a))
9086 (org-table-goto-column (nth 2 a))
9087 (push (append a (list (cdr eq))) eqlname1)
9088 ;; FIXME (org-table-eval-formula nil (cdr eq) 'noalign 'nocst
9089 ;; FIXME 'nostore 'noanalysis)
9090 (org-table-put-field-property :org-untouchable t)))
9092 ;; Now evauluate the column formulas, but skip fields covered by
9093 ;; field formulas
9094 (goto-char beg)
9095 (while (re-search-forward line-re end t)
9096 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
9097 ;; Unprotected line, recalculate
9098 (and all (message "Re-applying formulas to full table...(line %d)"
9099 (setq cnt (1+ cnt))))
9100 (setq org-last-recalc-line (org-current-line))
9101 (setq eql eqlnum)
9102 (while (setq entry (pop eql))
9103 (goto-line org-last-recalc-line)
9104 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9105 (unless (get-text-property (point) :org-untouchable)
9106 (org-table-eval-formula nil (cdr entry)
9107 'noalign 'nocst 'nostore 'noanalysis)))))
9109 ;; Now evaluate the field formulas
9110 (while (setq eq (pop eqlname1))
9111 (message "Re-applying formula to field: %s" (car eq))
9112 (goto-line (nth 1 eq))
9113 (org-table-goto-column (nth 2 eq))
9114 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
9115 'nostore 'noanalysis))
9117 (goto-line thisline)
9118 (org-table-goto-column thiscol)
9119 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
9120 (or noalign (and org-table-may-need-update (org-table-align))
9121 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9123 ;; back to initial position
9124 (message "Re-applying formulas...done")
9125 (goto-line thisline)
9126 (org-table-goto-column thiscol)
9127 (or noalign (and org-table-may-need-update (org-table-align))
9128 (and all (message "Re-applying formulas...done"))))))
9130 (defun org-table-iterate (&optional arg)
9131 "Recalculate the table until it does not change anymore."
9132 (interactive "P")
9133 (let ((imax (if arg (prefix-numeric-value arg) 10))
9134 (i 0)
9135 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
9136 thistbl)
9137 (catch 'exit
9138 (while (< i imax)
9139 (setq i (1+ i))
9140 (org-table-recalculate 'all)
9141 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
9142 (if (not (string= lasttbl thistbl))
9143 (setq lasttbl thistbl)
9144 (if (> i 1)
9145 (message "Convergence after %d iterations" i)
9146 (message "Table was already stable"))
9147 (throw 'exit t)))
9148 (error "No convergence after %d iterations" i))))
9150 (defun org-table-formula-substitute-names (f)
9151 "Replace $const with values in string F."
9152 (let ((start 0) a (f1 f))
9153 ;; First, check for column names
9154 (while (setq start (string-match org-table-column-name-regexp f start))
9155 (setq start (1+ start))
9156 (setq a (assoc (match-string 1 f) org-table-column-names))
9157 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9158 ;; Parameters and constants
9159 (setq start 0)
9160 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
9161 (setq start (1+ start))
9162 (if (setq a (save-match-data
9163 (org-table-get-constant (match-string 1 f))))
9164 (setq f (replace-match (concat "(" a ")") t t f))))
9165 (if org-table-formula-debug
9166 (put-text-property 0 (length f) :orig-formula f1 f))
9169 (defun org-table-get-constant (const)
9170 "Find the value for a parameter or constant in a formula.
9171 Parameters get priority."
9172 (or (cdr (assoc const org-table-local-parameters))
9173 (cdr (assoc const org-table-formula-constants-local))
9174 (cdr (assoc const org-table-formula-constants))
9175 (and (fboundp 'constants-get) (constants-get const))
9176 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
9177 (org-entry-get nil (substring const 5) 'inherit))
9178 "#UNDEFINED_NAME"))
9180 (defvar org-table-fedit-map
9181 (let ((map (make-sparse-keymap)))
9182 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
9183 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
9184 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
9185 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
9186 (org-defkey map "\C-c?" 'org-table-show-reference)
9187 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
9188 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
9189 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
9190 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
9191 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
9192 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
9193 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
9194 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
9195 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
9196 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
9197 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
9198 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
9199 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
9200 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
9201 map))
9203 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
9204 '("Edit-Formulas"
9205 ["Finish and Install" org-table-fedit-finish t]
9206 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
9207 ["Abort" org-table-fedit-abort t]
9208 "--"
9209 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
9210 ["Complete Lisp Symbol" lisp-complete-symbol t]
9211 "--"
9212 "Shift Reference at Point"
9213 ["Up" org-table-fedit-ref-up t]
9214 ["Down" org-table-fedit-ref-down t]
9215 ["Left" org-table-fedit-ref-left t]
9216 ["Right" org-table-fedit-ref-right t]
9218 "Change Test Row for Column Formulas"
9219 ["Up" org-table-fedit-line-up t]
9220 ["Down" org-table-fedit-line-down t]
9221 "--"
9222 ["Scroll Table Window" org-table-fedit-scroll t]
9223 ["Scroll Table Window down" org-table-fedit-scroll-down t]
9224 ["Show Table Grid" org-table-fedit-toggle-coordinates
9225 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
9226 org-table-overlay-coordinates)]
9227 "--"
9228 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
9229 :style toggle :selected org-table-buffer-is-an]))
9231 (defvar org-pos)
9233 (defun org-table-edit-formulas ()
9234 "Edit the formulas of the current table in a separate buffer."
9235 (interactive)
9236 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
9237 (beginning-of-line 0))
9238 (unless (org-at-table-p) (error "Not at a table"))
9239 (org-table-get-specials)
9240 (let ((key (org-table-current-field-formula 'key 'noerror))
9241 (eql (sort (org-table-get-stored-formulas 'noerror)
9242 'org-table-formula-less-p))
9243 (pos (move-marker (make-marker) (point)))
9244 (startline 1)
9245 (wc (current-window-configuration))
9246 (titles '((column . "# Column Formulas\n")
9247 (field . "# Field Formulas\n")
9248 (named . "# Named Field Formulas\n")))
9249 entry s type title)
9250 (switch-to-buffer-other-window "*Edit Formulas*")
9251 (erase-buffer)
9252 ;; Keep global-font-lock-mode from turning on font-lock-mode
9253 (let ((font-lock-global-modes '(not fundamental-mode)))
9254 (fundamental-mode))
9255 (org-set-local 'font-lock-global-modes (list 'not major-mode))
9256 (org-set-local 'org-pos pos)
9257 (org-set-local 'org-window-configuration wc)
9258 (use-local-map org-table-fedit-map)
9259 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
9260 (easy-menu-add org-table-fedit-menu)
9261 (setq startline (org-current-line))
9262 (while (setq entry (pop eql))
9263 (setq type (cond
9264 ((equal (string-to-char (car entry)) ?@) 'field)
9265 ((string-match "^[0-9]" (car entry)) 'column)
9266 (t 'named)))
9267 (when (setq title (assq type titles))
9268 (or (bobp) (insert "\n"))
9269 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
9270 (setq titles (delq title titles)))
9271 (if (equal key (car entry)) (setq startline (org-current-line)))
9272 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
9273 (car entry) " = " (cdr entry) "\n"))
9274 (remove-text-properties 0 (length s) '(face nil) s)
9275 (insert s))
9276 (if (eq org-table-use-standard-references t)
9277 (org-table-fedit-toggle-ref-type))
9278 (goto-line startline)
9279 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
9281 (defun org-table-fedit-post-command ()
9282 (when (not (memq this-command '(lisp-complete-symbol)))
9283 (let ((win (selected-window)))
9284 (save-excursion
9285 (condition-case nil
9286 (org-table-show-reference)
9287 (error nil))
9288 (select-window win)))))
9290 (defun org-table-formula-to-user (s)
9291 "Convert a formula from internal to user representation."
9292 (if (eq org-table-use-standard-references t)
9293 (org-table-convert-refs-to-an s)
9296 (defun org-table-formula-from-user (s)
9297 "Convert a formula from user to internal representation."
9298 (if org-table-use-standard-references
9299 (org-table-convert-refs-to-rc s)
9302 (defun org-table-convert-refs-to-rc (s)
9303 "Convert spreadsheet references from AB7 to @7$28.
9304 Works for single references, but also for entire formulas and even the
9305 full TBLFM line."
9306 (let ((start 0))
9307 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
9308 (cond
9309 ((match-end 3)
9310 ;; format match, just advance
9311 (setq start (match-end 0)))
9312 ((and (> (match-beginning 0) 0)
9313 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
9314 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
9315 ;; 3.e5 or something like this. FIXME: is this ok????
9316 (setq start (match-end 0)))
9318 (setq start (match-beginning 0)
9319 s (replace-match
9320 (if (equal (match-string 2 s) "&")
9321 (format "$%d" (org-letters-to-number (match-string 1 s)))
9322 (format "@%d$%d"
9323 (string-to-number (match-string 2 s))
9324 (org-letters-to-number (match-string 1 s))))
9325 t t s)))))
9328 (defun org-table-convert-refs-to-an (s)
9329 "Convert spreadsheet references from to @7$28 to AB7.
9330 Works for single references, but also for entire formulas and even the
9331 full TBLFM line."
9332 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
9333 (setq s (replace-match
9334 (format "%s%d"
9335 (org-number-to-letters
9336 (string-to-number (match-string 2 s)))
9337 (string-to-number (match-string 1 s)))
9338 t t s)))
9339 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
9340 (setq s (replace-match (concat "\\1"
9341 (org-number-to-letters
9342 (string-to-number (match-string 2 s))) "&")
9343 t nil s)))
9346 (defun org-letters-to-number (s)
9347 "Convert a base 26 number represented by letters into an integer.
9348 For example: AB -> 28."
9349 (let ((n 0))
9350 (setq s (upcase s))
9351 (while (> (length s) 0)
9352 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
9353 s (substring s 1)))
9356 (defun org-number-to-letters (n)
9357 "Convert an integer into a base 26 number represented by letters.
9358 For example: 28 -> AB."
9359 (let ((s ""))
9360 (while (> n 0)
9361 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
9362 n (/ (1- n) 26)))
9365 (defun org-table-fedit-convert-buffer (function)
9366 "Convert all references in this buffer, using FUNTION."
9367 (let ((line (org-current-line)))
9368 (goto-char (point-min))
9369 (while (not (eobp))
9370 (insert (funcall function (buffer-substring (point) (point-at-eol))))
9371 (delete-region (point) (point-at-eol))
9372 (or (eobp) (forward-char 1)))
9373 (goto-line line)))
9375 (defun org-table-fedit-toggle-ref-type ()
9376 "Convert all references in the buffer from B3 to @3$2 and back."
9377 (interactive)
9378 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
9379 (org-table-fedit-convert-buffer
9380 (if org-table-buffer-is-an
9381 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
9382 (message "Reference type switched to %s"
9383 (if org-table-buffer-is-an "A1 etc" "@row$column")))
9385 (defun org-table-fedit-ref-up ()
9386 "Shift the reference at point one row/hline up."
9387 (interactive)
9388 (org-table-fedit-shift-reference 'up))
9389 (defun org-table-fedit-ref-down ()
9390 "Shift the reference at point one row/hline down."
9391 (interactive)
9392 (org-table-fedit-shift-reference 'down))
9393 (defun org-table-fedit-ref-left ()
9394 "Shift the reference at point one field to the left."
9395 (interactive)
9396 (org-table-fedit-shift-reference 'left))
9397 (defun org-table-fedit-ref-right ()
9398 "Shift the reference at point one field to the right."
9399 (interactive)
9400 (org-table-fedit-shift-reference 'right))
9402 (defun org-table-fedit-shift-reference (dir)
9403 (cond
9404 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
9405 (if (memq dir '(left right))
9406 (org-rematch-and-replace 1 (eq dir 'left))
9407 (error "Cannot shift reference in this direction")))
9408 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
9409 ;; A B3-like reference
9410 (if (memq dir '(up down))
9411 (org-rematch-and-replace 2 (eq dir 'up))
9412 (org-rematch-and-replace 1 (eq dir 'left))))
9413 ((org-at-regexp-p
9414 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
9415 ;; An internal reference
9416 (if (memq dir '(up down))
9417 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
9418 (org-rematch-and-replace 5 (eq dir 'left))))))
9420 (defun org-rematch-and-replace (n &optional decr hline)
9421 "Re-match the group N, and replace it with the shifted refrence."
9422 (or (match-end n) (error "Cannot shift reference in this direction"))
9423 (goto-char (match-beginning n))
9424 (and (looking-at (regexp-quote (match-string n)))
9425 (replace-match (org-shift-refpart (match-string 0) decr hline)
9426 t t)))
9428 (defun org-shift-refpart (ref &optional decr hline)
9429 "Shift a refrence part REF.
9430 If DECR is set, decrease the references row/column, else increase.
9431 If HLINE is set, this may be a hline reference, it certainly is not
9432 a translation reference."
9433 (save-match-data
9434 (let* ((sign (string-match "^[-+]" ref)) n)
9436 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
9437 (cond
9438 ((and hline (string-match "^I+" ref))
9439 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
9440 (setq n (+ n (if decr -1 1)))
9441 (if (= n 0) (setq n (+ n (if decr -1 1))))
9442 (if sign
9443 (setq sign (if (< n 0) "-" "+") n (abs n))
9444 (setq n (max 1 n)))
9445 (concat sign (make-string n ?I)))
9447 ((string-match "^[0-9]+" ref)
9448 (setq n (string-to-number (concat sign ref)))
9449 (setq n (+ n (if decr -1 1)))
9450 (if sign
9451 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
9452 (number-to-string (max 1 n))))
9454 ((string-match "^[a-zA-Z]+" ref)
9455 (org-number-to-letters
9456 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
9458 (t (error "Cannot shift reference"))))))
9460 (defun org-table-fedit-toggle-coordinates ()
9461 "Toggle the display of coordinates in the refrenced table."
9462 (interactive)
9463 (let ((pos (marker-position org-pos)))
9464 (with-current-buffer (marker-buffer org-pos)
9465 (save-excursion
9466 (goto-char pos)
9467 (org-table-toggle-coordinate-overlays)))))
9469 (defun org-table-fedit-finish (&optional arg)
9470 "Parse the buffer for formula definitions and install them.
9471 With prefix ARG, apply the new formulas to the table."
9472 (interactive "P")
9473 (org-table-remove-rectangle-highlight)
9474 (if org-table-use-standard-references
9475 (progn
9476 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
9477 (setq org-table-buffer-is-an nil)))
9478 (let ((pos org-pos) eql var form)
9479 (goto-char (point-min))
9480 (while (re-search-forward
9481 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
9482 nil t)
9483 (setq var (if (match-end 2) (match-string 2) (match-string 1))
9484 form (match-string 3))
9485 (setq form (org-trim form))
9486 (when (not (equal form ""))
9487 (while (string-match "[ \t]*\n[ \t]*" form)
9488 (setq form (replace-match " " t t form)))
9489 (when (assoc var eql)
9490 (error "Double formulas for %s" var))
9491 (push (cons var form) eql)))
9492 (setq org-pos nil)
9493 (set-window-configuration org-window-configuration)
9494 (select-window (get-buffer-window (marker-buffer pos)))
9495 (goto-char pos)
9496 (unless (org-at-table-p)
9497 (error "Lost table position - cannot install formulae"))
9498 (org-table-store-formulas eql)
9499 (move-marker pos nil)
9500 (kill-buffer "*Edit Formulas*")
9501 (if arg
9502 (org-table-recalculate 'all)
9503 (message "New formulas installed - press C-u C-c C-c to apply."))))
9505 (defun org-table-fedit-abort ()
9506 "Abort editing formulas, without installing the changes."
9507 (interactive)
9508 (org-table-remove-rectangle-highlight)
9509 (let ((pos org-pos))
9510 (set-window-configuration org-window-configuration)
9511 (select-window (get-buffer-window (marker-buffer pos)))
9512 (goto-char pos)
9513 (move-marker pos nil)
9514 (message "Formula editing aborted without installing changes")))
9516 (defun org-table-fedit-lisp-indent ()
9517 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
9518 (interactive)
9519 (let ((pos (point)) beg end ind)
9520 (beginning-of-line 1)
9521 (cond
9522 ((looking-at "[ \t]")
9523 (goto-char pos)
9524 (call-interactively 'lisp-indent-line))
9525 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
9526 ((not (fboundp 'pp-buffer))
9527 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
9528 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
9529 (goto-char (- (match-end 0) 2))
9530 (setq beg (point))
9531 (setq ind (make-string (current-column) ?\ ))
9532 (condition-case nil (forward-sexp 1)
9533 (error
9534 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
9535 (setq end (point))
9536 (save-restriction
9537 (narrow-to-region beg end)
9538 (if (eq last-command this-command)
9539 (progn
9540 (goto-char (point-min))
9541 (setq this-command nil)
9542 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
9543 (replace-match " ")))
9544 (pp-buffer)
9545 (untabify (point-min) (point-max))
9546 (goto-char (1+ (point-min)))
9547 (while (re-search-forward "^." nil t)
9548 (beginning-of-line 1)
9549 (insert ind))
9550 (goto-char (point-max))
9551 (backward-delete-char 1)))
9552 (goto-char beg))
9553 (t nil))))
9555 (defvar org-show-positions nil)
9557 (defun org-table-show-reference (&optional local)
9558 "Show the location/value of the $ expression at point."
9559 (interactive)
9560 (org-table-remove-rectangle-highlight)
9561 (catch 'exit
9562 (let ((pos (if local (point) org-pos))
9563 (face2 'highlight)
9564 (org-inhibit-highlight-removal t)
9565 (win (selected-window))
9566 (org-show-positions nil)
9567 var name e what match dest)
9568 (if local (org-table-get-specials))
9569 (setq what (cond
9570 ((or (org-at-regexp-p org-table-range-regexp2)
9571 (org-at-regexp-p org-table-translate-regexp)
9572 (org-at-regexp-p org-table-range-regexp))
9573 (setq match
9574 (save-match-data
9575 (org-table-convert-refs-to-rc (match-string 0))))
9576 'range)
9577 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
9578 ((org-at-regexp-p "\\$[0-9]+") 'column)
9579 ((not local) nil)
9580 (t (error "No reference at point")))
9581 match (and what (or match (match-string 0))))
9582 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
9583 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
9584 'secondary-selection))
9585 (org-add-hook 'before-change-functions
9586 'org-table-remove-rectangle-highlight)
9587 (if (eq what 'name) (setq var (substring match 1)))
9588 (when (eq what 'range)
9589 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
9590 (setq match (org-table-formula-substitute-names match)))
9591 (unless local
9592 (save-excursion
9593 (end-of-line 1)
9594 (re-search-backward "^\\S-" nil t)
9595 (beginning-of-line 1)
9596 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
9597 (setq dest
9598 (save-match-data
9599 (org-table-convert-refs-to-rc (match-string 1))))
9600 (org-table-add-rectangle-overlay
9601 (match-beginning 1) (match-end 1) face2))))
9602 (if (and (markerp pos) (marker-buffer pos))
9603 (if (get-buffer-window (marker-buffer pos))
9604 (select-window (get-buffer-window (marker-buffer pos)))
9605 (switch-to-buffer-other-window (get-buffer-window
9606 (marker-buffer pos)))))
9607 (goto-char pos)
9608 (org-table-force-dataline)
9609 (when dest
9610 (setq name (substring dest 1))
9611 (cond
9612 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
9613 (setq e (assoc name org-table-named-field-locations))
9614 (goto-line (nth 1 e))
9615 (org-table-goto-column (nth 2 e)))
9616 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
9617 (let ((l (string-to-number (match-string 1 dest)))
9618 (c (string-to-number (match-string 2 dest))))
9619 (goto-line (aref org-table-dlines l))
9620 (org-table-goto-column c)))
9621 (t (org-table-goto-column (string-to-number name))))
9622 (move-marker pos (point))
9623 (org-table-highlight-rectangle nil nil face2))
9624 (cond
9625 ((equal dest match))
9626 ((not match))
9627 ((eq what 'range)
9628 (condition-case nil
9629 (save-excursion
9630 (org-table-get-range match nil nil 'highlight))
9631 (error nil)))
9632 ((setq e (assoc var org-table-named-field-locations))
9633 (goto-line (nth 1 e))
9634 (org-table-goto-column (nth 2 e))
9635 (org-table-highlight-rectangle (point) (point))
9636 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9637 ((setq e (assoc var org-table-column-names))
9638 (org-table-goto-column (string-to-number (cdr e)))
9639 (org-table-highlight-rectangle (point) (point))
9640 (goto-char (org-table-begin))
9641 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9642 (org-table-end) t)
9643 (progn
9644 (goto-char (match-beginning 1))
9645 (org-table-highlight-rectangle)
9646 (message "Named column (column %s)" (cdr e)))
9647 (error "Column name not found")))
9648 ((eq what 'column)
9649 ;; column number
9650 (org-table-goto-column (string-to-number (substring match 1)))
9651 (org-table-highlight-rectangle (point) (point))
9652 (message "Column %s" (substring match 1)))
9653 ((setq e (assoc var org-table-local-parameters))
9654 (goto-char (org-table-begin))
9655 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9656 (progn
9657 (goto-char (match-beginning 1))
9658 (org-table-highlight-rectangle)
9659 (message "Local parameter."))
9660 (error "Parameter not found")))
9662 (cond
9663 ((not var) (error "No reference at point"))
9664 ((setq e (assoc var org-table-formula-constants-local))
9665 (message "Local Constant: $%s=%s in #+CONSTANTS line."
9666 var (cdr e)))
9667 ((setq e (assoc var org-table-formula-constants))
9668 (message "Constant: $%s=%s in `org-table-formula-constants'."
9669 var (cdr e)))
9670 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9671 (message "Constant: $%s=%s, from `constants.el'%s."
9672 var e (format " (%s units)" constants-unit-system)))
9673 (t (error "Undefined name $%s" var)))))
9674 (goto-char pos)
9675 (when (and org-show-positions
9676 (not (memq this-command '(org-table-fedit-scroll
9677 org-table-fedit-scroll-down))))
9678 (push pos org-show-positions)
9679 (push org-table-current-begin-pos org-show-positions)
9680 (let ((min (apply 'min org-show-positions))
9681 (max (apply 'max org-show-positions)))
9682 (goto-char min) (recenter 0)
9683 (goto-char max)
9684 (or (pos-visible-in-window-p max) (recenter -1))))
9685 (select-window win))))
9687 (defun org-table-force-dataline ()
9688 "Make sure the cursor is in a dataline in a table."
9689 (unless (save-excursion
9690 (beginning-of-line 1)
9691 (looking-at org-table-dataline-regexp))
9692 (let* ((re org-table-dataline-regexp)
9693 (p1 (save-excursion (re-search-forward re nil 'move)))
9694 (p2 (save-excursion (re-search-backward re nil 'move))))
9695 (cond ((and p1 p2)
9696 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
9697 p1 p2)))
9698 ((or p1 p2) (goto-char (or p1 p2)))
9699 (t (error "No table dataline around here"))))))
9701 (defun org-table-fedit-line-up ()
9702 "Move cursor one line up in the window showing the table."
9703 (interactive)
9704 (org-table-fedit-move 'previous-line))
9706 (defun org-table-fedit-line-down ()
9707 "Move cursor one line down in the window showing the table."
9708 (interactive)
9709 (org-table-fedit-move 'next-line))
9711 (defun org-table-fedit-move (command)
9712 "Move the cursor in the window shoinw the table.
9713 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
9714 (let ((org-table-allow-automatic-line-recalculation nil)
9715 (pos org-pos) (win (selected-window)) p)
9716 (select-window (get-buffer-window (marker-buffer org-pos)))
9717 (setq p (point))
9718 (call-interactively command)
9719 (while (and (org-at-table-p)
9720 (org-at-table-hline-p))
9721 (call-interactively command))
9722 (or (org-at-table-p) (goto-char p))
9723 (move-marker pos (point))
9724 (select-window win)))
9726 (defun org-table-fedit-scroll (N)
9727 (interactive "p")
9728 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
9729 (scroll-other-window N)))
9731 (defun org-table-fedit-scroll-down (N)
9732 (interactive "p")
9733 (org-table-fedit-scroll (- N)))
9735 (defvar org-table-rectangle-overlays nil)
9737 (defun org-table-add-rectangle-overlay (beg end &optional face)
9738 "Add a new overlay."
9739 (let ((ov (org-make-overlay beg end)))
9740 (org-overlay-put ov 'face (or face 'secondary-selection))
9741 (push ov org-table-rectangle-overlays)))
9743 (defun org-table-highlight-rectangle (&optional beg end face)
9744 "Highlight rectangular region in a table."
9745 (setq beg (or beg (point)) end (or end (point)))
9746 (let ((b (min beg end))
9747 (e (max beg end))
9748 l1 c1 l2 c2 tmp)
9749 (and (boundp 'org-show-positions)
9750 (setq org-show-positions (cons b (cons e org-show-positions))))
9751 (goto-char (min beg end))
9752 (setq l1 (org-current-line)
9753 c1 (org-table-current-column))
9754 (goto-char (max beg end))
9755 (setq l2 (org-current-line)
9756 c2 (org-table-current-column))
9757 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
9758 (goto-line l1)
9759 (beginning-of-line 1)
9760 (loop for line from l1 to l2 do
9761 (when (looking-at org-table-dataline-regexp)
9762 (org-table-goto-column c1)
9763 (skip-chars-backward "^|\n") (setq beg (point))
9764 (org-table-goto-column c2)
9765 (skip-chars-forward "^|\n") (setq end (point))
9766 (org-table-add-rectangle-overlay beg end face))
9767 (beginning-of-line 2))
9768 (goto-char b))
9769 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
9771 (defun org-table-remove-rectangle-highlight (&rest ignore)
9772 "Remove the rectangle overlays."
9773 (unless org-inhibit-highlight-removal
9774 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
9775 (mapc 'org-delete-overlay org-table-rectangle-overlays)
9776 (setq org-table-rectangle-overlays nil)))
9778 (defvar org-table-coordinate-overlays nil
9779 "Collects the cooordinate grid overlays, so that they can be removed.")
9780 (make-variable-buffer-local 'org-table-coordinate-overlays)
9782 (defun org-table-overlay-coordinates ()
9783 "Add overlays to the table at point, to show row/column coordinates."
9784 (interactive)
9785 (mapc 'org-delete-overlay org-table-coordinate-overlays)
9786 (setq org-table-coordinate-overlays nil)
9787 (save-excursion
9788 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
9789 (goto-char (org-table-begin))
9790 (while (org-at-table-p)
9791 (setq eol (point-at-eol))
9792 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
9793 (push ov org-table-coordinate-overlays)
9794 (setq hline (looking-at org-table-hline-regexp))
9795 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
9796 (format "%4d" (setq id (1+ id)))))
9797 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
9798 (when hline
9799 (setq ic 0)
9800 (while (re-search-forward "[+|]\\(-+\\)" eol t)
9801 (setq beg (1+ (match-beginning 0))
9802 ic (1+ ic)
9803 s1 (concat "$" (int-to-string ic))
9804 s2 (org-number-to-letters ic)
9805 str (if (eq org-table-use-standard-references t) s2 s1))
9806 (setq ov (org-make-overlay beg (+ beg (length str))))
9807 (push ov org-table-coordinate-overlays)
9808 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
9809 (beginning-of-line 2)))))
9811 (defun org-table-toggle-coordinate-overlays ()
9812 "Toggle the display of Row/Column numbers in tables."
9813 (interactive)
9814 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
9815 (message "Row/Column number display turned %s"
9816 (if org-table-overlay-coordinates "on" "off"))
9817 (if (and (org-at-table-p) org-table-overlay-coordinates)
9818 (org-table-align))
9819 (unless org-table-overlay-coordinates
9820 (mapc 'org-delete-overlay org-table-coordinate-overlays)
9821 (setq org-table-coordinate-overlays nil)))
9823 (defun org-table-toggle-formula-debugger ()
9824 "Toggle the formula debugger in tables."
9825 (interactive)
9826 (setq org-table-formula-debug (not org-table-formula-debug))
9827 (message "Formula debugging has been turned %s"
9828 (if org-table-formula-debug "on" "off")))
9830 ;;; The orgtbl minor mode
9832 ;; Define a minor mode which can be used in other modes in order to
9833 ;; integrate the org-mode table editor.
9835 ;; This is really a hack, because the org-mode table editor uses several
9836 ;; keys which normally belong to the major mode, for example the TAB and
9837 ;; RET keys. Here is how it works: The minor mode defines all the keys
9838 ;; necessary to operate the table editor, but wraps the commands into a
9839 ;; function which tests if the cursor is currently inside a table. If that
9840 ;; is the case, the table editor command is executed. However, when any of
9841 ;; those keys is used outside a table, the function uses `key-binding' to
9842 ;; look up if the key has an associated command in another currently active
9843 ;; keymap (minor modes, major mode, global), and executes that command.
9844 ;; There might be problems if any of the keys used by the table editor is
9845 ;; otherwise used as a prefix key.
9847 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9848 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9849 ;; addresses this by checking explicitly for both bindings.
9851 ;; The optimized version (see variable `orgtbl-optimized') takes over
9852 ;; all keys which are bound to `self-insert-command' in the *global map*.
9853 ;; Some modes bind other commands to simple characters, for example
9854 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9855 ;; active, this binding is ignored inside tables and replaced with a
9856 ;; modified self-insert.
9858 (defvar orgtbl-mode nil
9859 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9860 table editor in arbitrary modes.")
9861 (make-variable-buffer-local 'orgtbl-mode)
9863 (defvar orgtbl-mode-map (make-keymap)
9864 "Keymap for `orgtbl-mode'.")
9866 ;;;###autoload
9867 (defun turn-on-orgtbl ()
9868 "Unconditionally turn on `orgtbl-mode'."
9869 (orgtbl-mode 1))
9871 (defvar org-old-auto-fill-inhibit-regexp nil
9872 "Local variable used by `orgtbl-mode'")
9874 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
9875 "Matches a line belonging to an orgtbl.")
9877 (defconst orgtbl-extra-font-lock-keywords
9878 (list (list (concat "^" orgtbl-line-start-regexp ".*")
9879 0 (quote 'org-table) 'prepend))
9880 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
9882 ;;;###autoload
9883 (defun orgtbl-mode (&optional arg)
9884 "The `org-mode' table editor as a minor mode for use in other modes."
9885 (interactive)
9886 (if (org-mode-p)
9887 ;; Exit without error, in case some hook functions calls this
9888 ;; by accident in org-mode.
9889 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9890 (setq orgtbl-mode
9891 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9892 (if orgtbl-mode
9893 (progn
9894 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9895 ;; Make sure we are first in minor-mode-map-alist
9896 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9897 (and c (setq minor-mode-map-alist
9898 (cons c (delq c minor-mode-map-alist)))))
9899 (org-set-local (quote org-table-may-need-update) t)
9900 (org-add-hook 'before-change-functions 'org-before-change-function
9901 nil 'local)
9902 (org-set-local 'org-old-auto-fill-inhibit-regexp
9903 auto-fill-inhibit-regexp)
9904 (org-set-local 'auto-fill-inhibit-regexp
9905 (if auto-fill-inhibit-regexp
9906 (concat orgtbl-line-start-regexp "\\|"
9907 auto-fill-inhibit-regexp)
9908 orgtbl-line-start-regexp))
9909 (org-add-to-invisibility-spec '(org-cwidth))
9910 (when (fboundp 'font-lock-add-keywords)
9911 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
9912 (org-restart-font-lock))
9913 (easy-menu-add orgtbl-mode-menu)
9914 (run-hooks 'orgtbl-mode-hook))
9915 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9916 (org-cleanup-narrow-column-properties)
9917 (org-remove-from-invisibility-spec '(org-cwidth))
9918 (remove-hook 'before-change-functions 'org-before-change-function t)
9919 (when (fboundp 'font-lock-remove-keywords)
9920 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
9921 (org-restart-font-lock))
9922 (easy-menu-remove orgtbl-mode-menu)
9923 (force-mode-line-update 'all))))
9925 (defun org-cleanup-narrow-column-properties ()
9926 "Remove all properties related to narrow-column invisibility."
9927 (let ((s 1))
9928 (while (setq s (text-property-any s (point-max)
9929 'display org-narrow-column-arrow))
9930 (remove-text-properties s (1+ s) '(display t)))
9931 (setq s 1)
9932 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
9933 (remove-text-properties s (1+ s) '(org-cwidth t)))
9934 (setq s 1)
9935 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
9936 (remove-text-properties s (1+ s) '(invisible t)))))
9938 ;; Install it as a minor mode.
9939 (put 'orgtbl-mode :included t)
9940 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9941 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9943 (defun orgtbl-make-binding (fun n &rest keys)
9944 "Create a function for binding in the table minor mode.
9945 FUN is the command to call inside a table. N is used to create a unique
9946 command name. KEYS are keys that should be checked in for a command
9947 to execute outside of tables."
9948 (eval
9949 (list 'defun
9950 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9951 '(arg)
9952 (concat "In tables, run `" (symbol-name fun) "'.\n"
9953 "Outside of tables, run the binding of `"
9954 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9955 "'.")
9956 '(interactive "p")
9957 (list 'if
9958 '(org-at-table-p)
9959 (list 'call-interactively (list 'quote fun))
9960 (list 'let '(orgtbl-mode)
9961 (list 'call-interactively
9962 (append '(or)
9963 (mapcar (lambda (k)
9964 (list 'key-binding k))
9965 keys)
9966 '('orgtbl-error))))))))
9968 (defun orgtbl-error ()
9969 "Error when there is no default binding for a table key."
9970 (interactive)
9971 (error "This key is has no function outside tables"))
9973 (defun orgtbl-setup ()
9974 "Setup orgtbl keymaps."
9975 (let ((nfunc 0)
9976 (bindings
9977 (list
9978 '([(meta shift left)] org-table-delete-column)
9979 '([(meta left)] org-table-move-column-left)
9980 '([(meta right)] org-table-move-column-right)
9981 '([(meta shift right)] org-table-insert-column)
9982 '([(meta shift up)] org-table-kill-row)
9983 '([(meta shift down)] org-table-insert-row)
9984 '([(meta up)] org-table-move-row-up)
9985 '([(meta down)] org-table-move-row-down)
9986 '("\C-c\C-w" org-table-cut-region)
9987 '("\C-c\M-w" org-table-copy-region)
9988 '("\C-c\C-y" org-table-paste-rectangle)
9989 '("\C-c-" org-table-insert-hline)
9990 '("\C-c}" org-table-toggle-coordinate-overlays)
9991 '("\C-c{" org-table-toggle-formula-debugger)
9992 '("\C-m" org-table-next-row)
9993 '([(shift return)] org-table-copy-down)
9994 '("\C-c\C-q" org-table-wrap-region)
9995 '("\C-c?" org-table-field-info)
9996 '("\C-c " org-table-blank-field)
9997 '("\C-c+" org-table-sum)
9998 '("\C-c=" org-table-eval-formula)
9999 '("\C-c'" org-table-edit-formulas)
10000 '("\C-c`" org-table-edit-field)
10001 '("\C-c*" org-table-recalculate)
10002 '("\C-c|" org-table-create-or-convert-from-region)
10003 '("\C-c^" org-table-sort-lines)
10004 '([(control ?#)] org-table-rotate-recalc-marks)))
10005 elt key fun cmd)
10006 (while (setq elt (pop bindings))
10007 (setq nfunc (1+ nfunc))
10008 (setq key (org-key (car elt))
10009 fun (nth 1 elt)
10010 cmd (orgtbl-make-binding fun nfunc key))
10011 (org-defkey orgtbl-mode-map key cmd))
10013 ;; Special treatment needed for TAB and RET
10014 (org-defkey orgtbl-mode-map [(return)]
10015 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10016 (org-defkey orgtbl-mode-map "\C-m"
10017 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10019 (org-defkey orgtbl-mode-map [(tab)]
10020 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10021 (org-defkey orgtbl-mode-map "\C-i"
10022 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
10024 (org-defkey orgtbl-mode-map [(shift tab)]
10025 (orgtbl-make-binding 'org-table-previous-field 104
10026 [(shift tab)] [(tab)] "\C-i"))
10028 (org-defkey orgtbl-mode-map "\M-\C-m"
10029 (orgtbl-make-binding 'org-table-wrap-region 105
10030 "\M-\C-m" [(meta return)]))
10031 (org-defkey orgtbl-mode-map [(meta return)]
10032 (orgtbl-make-binding 'org-table-wrap-region 106
10033 [(meta return)] "\M-\C-m"))
10035 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
10036 (when orgtbl-optimized
10037 ;; If the user wants maximum table support, we need to hijack
10038 ;; some standard editing functions
10039 (org-remap orgtbl-mode-map
10040 'self-insert-command 'orgtbl-self-insert-command
10041 'delete-char 'org-delete-char
10042 'delete-backward-char 'org-delete-backward-char)
10043 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
10044 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10045 '("OrgTbl"
10046 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10047 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10048 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10049 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10050 "--"
10051 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10052 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10053 ["Copy Field from Above"
10054 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10055 "--"
10056 ("Column"
10057 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10058 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10059 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10060 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10061 ("Row"
10062 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10063 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10064 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10065 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10066 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10067 "--"
10068 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10069 ("Rectangle"
10070 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10071 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10072 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10073 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10074 "--"
10075 ("Radio tables"
10076 ["Insert table template" orgtbl-insert-radio-table
10077 (assq major-mode orgtbl-radio-table-templates)]
10078 ["Comment/uncomment table" orgtbl-toggle-comment t])
10079 "--"
10080 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10081 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10082 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10083 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10084 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10085 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
10086 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10087 ["Sum Column/Rectangle" org-table-sum
10088 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10089 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10090 ["Debug Formulas"
10091 org-table-toggle-formula-debugger :active (org-at-table-p)
10092 :keys "C-c {"
10093 :style toggle :selected org-table-formula-debug]
10094 ["Show Col/Row Numbers"
10095 org-table-toggle-coordinate-overlays :active (org-at-table-p)
10096 :keys "C-c }"
10097 :style toggle :selected org-table-overlay-coordinates]
10101 (defun orgtbl-ctrl-c-ctrl-c (arg)
10102 "If the cursor is inside a table, realign the table.
10103 It it is a table to be sent away to a receiver, do it.
10104 With prefix arg, also recompute table."
10105 (interactive "P")
10106 (let ((pos (point)) action)
10107 (save-excursion
10108 (beginning-of-line 1)
10109 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
10110 ((looking-at "[ \t]*|") pos)
10111 ((looking-at "#\\+TBLFM:") 'recalc))))
10112 (cond
10113 ((integerp action)
10114 (goto-char action)
10115 (org-table-maybe-eval-formula)
10116 (if arg
10117 (call-interactively 'org-table-recalculate)
10118 (org-table-maybe-recalculate-line))
10119 (call-interactively 'org-table-align)
10120 (orgtbl-send-table 'maybe))
10121 ((eq action 'recalc)
10122 (save-excursion
10123 (beginning-of-line 1)
10124 (skip-chars-backward " \r\n\t")
10125 (if (org-at-table-p)
10126 (org-call-with-arg 'org-table-recalculate t))))
10127 (t (let (orgtbl-mode)
10128 (call-interactively (key-binding "\C-c\C-c")))))))
10130 (defun orgtbl-tab (arg)
10131 "Justification and field motion for `orgtbl-mode'."
10132 (interactive "P")
10133 (if arg (org-table-edit-field t)
10134 (org-table-justify-field-maybe)
10135 (org-table-next-field)))
10137 (defun orgtbl-ret ()
10138 "Justification and field motion for `orgtbl-mode'."
10139 (interactive)
10140 (org-table-justify-field-maybe)
10141 (org-table-next-row))
10143 (defun orgtbl-self-insert-command (N)
10144 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10145 If the cursor is in a table looking at whitespace, the whitespace is
10146 overwritten, and the table is not marked as requiring realignment."
10147 (interactive "p")
10148 (if (and (org-at-table-p)
10150 (and org-table-auto-blank-field
10151 (member last-command
10152 '(orgtbl-hijacker-command-100
10153 orgtbl-hijacker-command-101
10154 orgtbl-hijacker-command-102
10155 orgtbl-hijacker-command-103
10156 orgtbl-hijacker-command-104
10157 orgtbl-hijacker-command-105))
10158 (org-table-blank-field))
10160 (eq N 1)
10161 (looking-at "[^|\n]* +|"))
10162 (let (org-table-may-need-update)
10163 (goto-char (1- (match-end 0)))
10164 (delete-backward-char 1)
10165 (goto-char (match-beginning 0))
10166 (self-insert-command N))
10167 (setq org-table-may-need-update t)
10168 (let (orgtbl-mode)
10169 (call-interactively (key-binding (vector last-input-event))))))
10171 (defun org-force-self-insert (N)
10172 "Needed to enforce self-insert under remapping."
10173 (interactive "p")
10174 (self-insert-command N))
10176 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
10177 "Regula expression matching exponentials as produced by calc.")
10179 (defvar org-table-clean-did-remove-column nil)
10181 (defun orgtbl-export (table target)
10182 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
10183 (lines (org-split-string table "[ \t]*\n[ \t]*"))
10184 org-table-last-alignment org-table-last-column-widths
10185 maxcol column)
10186 (if (not (fboundp func))
10187 (error "Cannot export orgtbl table to %s" target))
10188 (setq lines (org-table-clean-before-export lines))
10189 (setq table
10190 (mapcar
10191 (lambda (x)
10192 (if (string-match org-table-hline-regexp x)
10193 'hline
10194 (org-split-string (org-trim x) "\\s-*|\\s-*")))
10195 lines))
10196 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
10197 table)))
10198 (loop for i from (1- maxcol) downto 0 do
10199 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
10200 (setq column (delq nil column))
10201 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
10202 (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))
10203 (funcall func table nil)))
10205 (defun orgtbl-send-table (&optional maybe)
10206 "Send a tranformed version of this table to the receiver position.
10207 With argument MAYBE, fail quietly if no transformation is defined for
10208 this table."
10209 (interactive)
10210 (catch 'exit
10211 (unless (org-at-table-p) (error "Not at a table"))
10212 ;; when non-interactive, we assume align has just happened.
10213 (when (interactive-p) (org-table-align))
10214 (save-excursion
10215 (goto-char (org-table-begin))
10216 (beginning-of-line 0)
10217 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
10218 (if maybe
10219 (throw 'exit nil)
10220 (error "Don't know how to transform this table."))))
10221 (let* ((name (match-string 1))
10223 (transform (intern (match-string 2)))
10224 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
10225 (skip (plist-get params :skip))
10226 (skipcols (plist-get params :skipcols))
10227 (txt (buffer-substring-no-properties
10228 (org-table-begin) (org-table-end)))
10229 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
10230 (lines (org-table-clean-before-export lines))
10231 (i0 (if org-table-clean-did-remove-column 2 1))
10232 (table (mapcar
10233 (lambda (x)
10234 (if (string-match org-table-hline-regexp x)
10235 'hline
10236 (org-remove-by-index
10237 (org-split-string (org-trim x) "\\s-*|\\s-*")
10238 skipcols i0)))
10239 lines))
10240 (fun (if (= i0 2) 'cdr 'identity))
10241 (org-table-last-alignment
10242 (org-remove-by-index (funcall fun org-table-last-alignment)
10243 skipcols i0))
10244 (org-table-last-column-widths
10245 (org-remove-by-index (funcall fun org-table-last-column-widths)
10246 skipcols i0)))
10248 (unless (fboundp transform)
10249 (error "No such transformation function %s" transform))
10250 (setq txt (funcall transform table params))
10251 ;; Find the insertion place
10252 (save-excursion
10253 (goto-char (point-min))
10254 (unless (re-search-forward
10255 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
10256 (error "Don't know where to insert translated table"))
10257 (goto-char (match-beginning 0))
10258 (beginning-of-line 2)
10259 (setq beg (point))
10260 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
10261 (error "Cannot find end of insertion region"))
10262 (beginning-of-line 1)
10263 (delete-region beg (point))
10264 (goto-char beg)
10265 (insert txt "\n"))
10266 (message "Table converted and installed at receiver location"))))
10268 (defun org-remove-by-index (list indices &optional i0)
10269 "Remove the elements in LIST with indices in INDICES.
10270 First element has index 0, or I0 if given."
10271 (if (not indices)
10272 list
10273 (if (integerp indices) (setq indices (list indices)))
10274 (setq i0 (1- (or i0 0)))
10275 (delq :rm (mapcar (lambda (x)
10276 (setq i0 (1+ i0))
10277 (if (memq i0 indices) :rm x))
10278 list))))
10280 (defun orgtbl-toggle-comment ()
10281 "Comment or uncomment the orgtbl at point."
10282 (interactive)
10283 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
10284 (re2 (concat "^" orgtbl-line-start-regexp))
10285 (commented (save-excursion (beginning-of-line 1)
10286 (cond ((looking-at re1) t)
10287 ((looking-at re2) nil)
10288 (t (error "Not at an org table")))))
10289 (re (if commented re1 re2))
10290 beg end)
10291 (save-excursion
10292 (beginning-of-line 1)
10293 (while (looking-at re) (beginning-of-line 0))
10294 (beginning-of-line 2)
10295 (setq beg (point))
10296 (while (looking-at re) (beginning-of-line 2))
10297 (setq end (point)))
10298 (comment-region beg end (if commented '(4) nil))))
10300 (defun orgtbl-insert-radio-table ()
10301 "Insert a radio table template appropriate for this major mode."
10302 (interactive)
10303 (let* ((e (assq major-mode orgtbl-radio-table-templates))
10304 (txt (nth 1 e))
10305 name pos)
10306 (unless e (error "No radio table setup defined for %s" major-mode))
10307 (setq name (read-string "Table name: "))
10308 (while (string-match "%n" txt)
10309 (setq txt (replace-match name t t txt)))
10310 (or (bolp) (insert "\n"))
10311 (setq pos (point))
10312 (insert txt)
10313 (goto-char pos)))
10315 (defun org-get-param (params header i sym &optional hsym)
10316 "Get parameter value for symbol SYM.
10317 If this is a header line, actually get the value for the symbol with an
10318 additional \"h\" inserted after the colon.
10319 If the value is a protperty list, get the element for the current column.
10320 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
10321 (let ((val (plist-get params sym)))
10322 (and hsym header (setq val (or (plist-get params hsym) val)))
10323 (if (consp val) (plist-get val i) val)))
10325 (defun orgtbl-to-generic (table params)
10326 "Convert the orgtbl-mode TABLE to some other format.
10327 This generic routine can be used for many standard cases.
10328 TABLE is a list, each entry either the symbol `hline' for a horizontal
10329 separator line, or a list of fields for that line.
10330 PARAMS is a property list of parameters that can influence the conversion.
10331 For the generic converter, some parameters are obligatory: You need to
10332 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
10333 :splice, you must have :tstart and :tend.
10335 Valid parameters are
10337 :tstart String to start the table. Ignored when :splice is t.
10338 :tend String to end the table. Ignored when :splice is t.
10340 :splice When set to t, return only table body lines, don't wrap
10341 them into :tstart and :tend. Default is nil.
10343 :hline String to be inserted on horizontal separation lines.
10344 May be nil to ignore hlines.
10346 :lstart String to start a new table line.
10347 :lend String to end a table line
10348 :sep Separator between two fields
10349 :lfmt Format for entire line, with enough %s to capture all fields.
10350 If this is present, :lstart, :lend, and :sep are ignored.
10351 :fmt A format to be used to wrap the field, should contain
10352 %s for the original field value. For example, to wrap
10353 everything in dollars, you could use :fmt \"$%s$\".
10354 This may also be a property list with column numbers and
10355 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10357 :hlstart :hlend :hlsep :hlfmt :hfmt
10358 Same as above, specific for the header lines in the table.
10359 All lines before the first hline are treated as header.
10360 If any of these is not present, the data line value is used.
10362 :efmt Use this format to print numbers with exponentials.
10363 The format should have %s twice for inserting mantissa
10364 and exponent, for example \"%s\\\\times10^{%s}\". This
10365 may also be a property list with column numbers and
10366 formats. :fmt will still be applied after :efmt.
10368 In addition to this, the parameters :skip and :skipcols are always handled
10369 directly by `orgtbl-send-table'. See manual."
10370 (interactive)
10371 (let* ((p params)
10372 (splicep (plist-get p :splice))
10373 (hline (plist-get p :hline))
10374 rtn line i fm efm lfmt h)
10376 ;; Do we have a header?
10377 (if (and (not splicep) (listp (car table)) (memq 'hline table))
10378 (setq h t))
10380 ;; Put header
10381 (unless splicep
10382 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
10384 ;; Now loop over all lines
10385 (while (setq line (pop table))
10386 (if (eq line 'hline)
10387 ;; A horizontal separator line
10388 (progn (if hline (push hline rtn))
10389 (setq h nil)) ; no longer in header
10390 ;; A normal line. Convert the fields, push line onto the result list
10391 (setq i 0)
10392 (setq line
10393 (mapcar
10394 (lambda (f)
10395 (setq i (1+ i)
10396 fm (org-get-param p h i :fmt :hfmt)
10397 efm (org-get-param p h i :efmt))
10398 (if (and efm (string-match orgtbl-exp-regexp f))
10399 (setq f (format
10400 efm (match-string 1 f) (match-string 2 f))))
10401 (if fm (setq f (format fm f)))
10403 line))
10404 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
10405 (push (apply 'format lfmt line) rtn)
10406 (push (concat
10407 (org-get-param p h i :lstart :hlstart)
10408 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
10409 (org-get-param p h i :lend :hlend))
10410 rtn))))
10412 (unless splicep
10413 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
10415 (mapconcat 'identity (nreverse rtn) "\n")))
10417 (defun orgtbl-to-latex (table params)
10418 "Convert the orgtbl-mode TABLE to LaTeX.
10419 TABLE is a list, each entry either the symbol `hline' for a horizontal
10420 separator line, or a list of fields for that line.
10421 PARAMS is a property list of parameters that can influence the conversion.
10422 Supports all parameters from `orgtbl-to-generic'. Most important for
10423 LaTeX are:
10425 :splice When set to t, return only table body lines, don't wrap
10426 them into a tabular environment. Default is nil.
10428 :fmt A format to be used to wrap the field, should contain %s for the
10429 original field value. For example, to wrap everything in dollars,
10430 use :fmt \"$%s$\". This may also be a property list with column
10431 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10433 :efmt Format for transforming numbers with exponentials. The format
10434 should have %s twice for inserting mantissa and exponent, for
10435 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
10436 This may also be a property list with column numbers and formats.
10438 The general parameters :skip and :skipcols have already been applied when
10439 this function is called."
10440 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
10441 org-table-last-alignment ""))
10442 (params2
10443 (list
10444 :tstart (concat "\\begin{tabular}{" alignment "}")
10445 :tend "\\end{tabular}"
10446 :lstart "" :lend " \\\\" :sep " & "
10447 :efmt "%s\\,(%s)" :hline "\\hline")))
10448 (orgtbl-to-generic table (org-combine-plists params2 params))))
10450 (defun orgtbl-to-html (table params)
10451 "Convert the orgtbl-mode TABLE to LaTeX.
10452 TABLE is a list, each entry either the symbol `hline' for a horizontal
10453 separator line, or a list of fields for that line.
10454 PARAMS is a property list of parameters that can influence the conversion.
10455 Currently this function recognizes the following parameters:
10457 :splice When set to t, return only table body lines, don't wrap
10458 them into a <table> environment. Default is nil.
10460 The general parameters :skip and :skipcols have already been applied when
10461 this function is called. The function does *not* use `orgtbl-to-generic',
10462 so you cannot specify parameters for it."
10463 (let* ((splicep (plist-get params :splice))
10464 html)
10465 ;; Just call the formatter we already have
10466 ;; We need to make text lines for it, so put the fields back together.
10467 (setq html (org-format-org-table-html
10468 (mapcar
10469 (lambda (x)
10470 (if (eq x 'hline)
10471 "|----+----|"
10472 (concat "| " (mapconcat 'identity x " | ") " |")))
10473 table)
10474 splicep))
10475 (if (string-match "\n+\\'" html)
10476 (setq html (replace-match "" t t html)))
10477 html))
10479 (defun orgtbl-to-texinfo (table params)
10480 "Convert the orgtbl-mode TABLE to TeXInfo.
10481 TABLE is a list, each entry either the symbol `hline' for a horizontal
10482 separator line, or a list of fields for that line.
10483 PARAMS is a property list of parameters that can influence the conversion.
10484 Supports all parameters from `orgtbl-to-generic'. Most important for
10485 TeXInfo are:
10487 :splice nil/t When set to t, return only table body lines, don't wrap
10488 them into a multitable environment. Default is nil.
10490 :fmt fmt A format to be used to wrap the field, should contain
10491 %s for the original field value. For example, to wrap
10492 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
10493 This may also be a property list with column numbers and
10494 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
10496 :cf \"f1 f2..\" The column fractions for the table. Bye default these
10497 are computed automatically from the width of the columns
10498 under org-mode.
10500 The general parameters :skip and :skipcols have already been applied when
10501 this function is called."
10502 (let* ((total (float (apply '+ org-table-last-column-widths)))
10503 (colfrac (or (plist-get params :cf)
10504 (mapconcat
10505 (lambda (x) (format "%.3f" (/ (float x) total)))
10506 org-table-last-column-widths " ")))
10507 (params2
10508 (list
10509 :tstart (concat "@multitable @columnfractions " colfrac)
10510 :tend "@end multitable"
10511 :lstart "@item " :lend "" :sep " @tab "
10512 :hlstart "@headitem ")))
10513 (orgtbl-to-generic table (org-combine-plists params2 params))))
10515 ;;;; Link Stuff
10517 ;;; Link abbreviations
10519 (defun org-link-expand-abbrev (link)
10520 "Apply replacements as defined in `org-link-abbrev-alist."
10521 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
10522 (let* ((key (match-string 1 link))
10523 (as (or (assoc key org-link-abbrev-alist-local)
10524 (assoc key org-link-abbrev-alist)))
10525 (tag (and (match-end 2) (match-string 3 link)))
10526 rpl)
10527 (if (not as)
10528 link
10529 (setq rpl (cdr as))
10530 (cond
10531 ((symbolp rpl) (funcall rpl tag))
10532 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
10533 (t (concat rpl tag)))))
10534 link))
10536 ;;; Storing and inserting links
10538 (defvar org-insert-link-history nil
10539 "Minibuffer history for links inserted with `org-insert-link'.")
10541 (defvar org-stored-links nil
10542 "Contains the links stored with `org-store-link'.")
10544 (defvar org-store-link-plist nil
10545 "Plist with info about the most recently link created with `org-store-link'.")
10547 (defvar org-link-protocols nil
10548 "Link protocols added to Org-mode using `org-add-link-type'.")
10550 (defvar org-store-link-functions nil
10551 "List of functions that are called to create and store a link.
10552 Each function will be called in turn until one returns a non-nil
10553 value. Each function should check if it is responsible for creating
10554 this link (for example by looking at the major mode).
10555 If not, it must exit and return nil.
10556 If yes, it should return a non-nil value after a calling
10557 `org-store-link-properties' with a list of properties and values.
10558 Special properties are:
10560 :type The link prefix. like \"http\". This must be given.
10561 :link The link, like \"http://www.astro.uva.nl/~dominik\".
10562 This is obligatory as well.
10563 :description Optional default description for the second pair
10564 of brackets in an Org-mode link. The user can still change
10565 this when inserting this link into an Org-mode buffer.
10567 In addition to these, any additional properties can be specified
10568 and then used in remember templates.")
10570 (defun org-add-link-type (type &optional follow publish)
10571 "Add TYPE to the list of `org-link-types'.
10572 Re-compute all regular expressions depending on `org-link-types'
10573 FOLLOW and PUBLISH are two functions. Both take the link path as
10574 an argument.
10575 FOLLOW should do whatever is necessary to follow the link, for example
10576 to find a file or display a mail message.
10577 PUBLISH takes the path and retuns the string that should be used when
10578 this document is published."
10579 (add-to-list 'org-link-types type t)
10580 (org-make-link-regexps)
10581 (add-to-list 'org-link-protocols
10582 (list type follow publish)))
10584 (defun org-add-agenda-custom-command (entry)
10585 "Replace or add a command in `org-agenda-custom-commands'.
10586 This is mostly for hacking and trying a new command - once the command
10587 works you probably want to add it to `org-agenda-custom-commands' for good."
10588 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
10589 (if ass
10590 (setcdr ass (cdr entry))
10591 (push entry org-agenda-custom-commands))))
10593 ;;;###autoload
10594 (defun org-store-link (arg)
10595 "\\<org-mode-map>Store an org-link to the current location.
10596 This link can later be inserted into an org-buffer with
10597 \\[org-insert-link].
10598 For some link types, a prefix arg is interpreted:
10599 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
10600 For file links, arg negates `org-context-in-file-links'."
10601 (interactive "P")
10602 (setq org-store-link-plist nil) ; reset
10603 (let (link cpltxt desc description search txt)
10604 (cond
10606 ((run-hook-with-args-until-success 'org-store-link-functions)
10607 (setq link (plist-get org-store-link-plist :link)
10608 desc (or (plist-get org-store-link-plist :description) link)))
10610 ((eq major-mode 'bbdb-mode)
10611 (let ((name (bbdb-record-name (bbdb-current-record)))
10612 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
10613 (setq cpltxt (concat "bbdb:" (or name company))
10614 link (org-make-link cpltxt))
10615 (org-store-link-props :type "bbdb" :name name :company company)))
10617 ((eq major-mode 'Info-mode)
10618 (setq link (org-make-link "info:"
10619 (file-name-nondirectory Info-current-file)
10620 ":" Info-current-node))
10621 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
10622 ":" Info-current-node))
10623 (org-store-link-props :type "info" :file Info-current-file
10624 :node Info-current-node))
10626 ((eq major-mode 'calendar-mode)
10627 (let ((cd (calendar-cursor-to-date)))
10628 (setq link
10629 (format-time-string
10630 (car org-time-stamp-formats)
10631 (apply 'encode-time
10632 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
10633 nil nil nil))))
10634 (org-store-link-props :type "calendar" :date cd)))
10636 ((or (eq major-mode 'vm-summary-mode)
10637 (eq major-mode 'vm-presentation-mode))
10638 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
10639 (vm-follow-summary-cursor)
10640 (save-excursion
10641 (vm-select-folder-buffer)
10642 (let* ((message (car vm-message-pointer))
10643 (folder buffer-file-name)
10644 (subject (vm-su-subject message))
10645 (to (vm-get-header-contents message "To"))
10646 (from (vm-get-header-contents message "From"))
10647 (message-id (vm-su-message-id message)))
10648 (org-store-link-props :type "vm" :from from :to to :subject subject
10649 :message-id message-id)
10650 (setq message-id (org-remove-angle-brackets message-id))
10651 (setq folder (abbreviate-file-name folder))
10652 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
10653 folder)
10654 (setq folder (replace-match "" t t folder)))
10655 (setq cpltxt (org-email-link-description))
10656 (setq link (org-make-link "vm:" folder "#" message-id)))))
10658 ((eq major-mode 'wl-summary-mode)
10659 (let* ((msgnum (wl-summary-message-number))
10660 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
10661 msgnum 'message-id))
10662 (wl-message-entity
10663 (if (fboundp 'elmo-message-entity)
10664 (elmo-message-entity
10665 wl-summary-buffer-elmo-folder msgnum)
10666 (elmo-msgdb-overview-get-entity
10667 msgnum (wl-summary-buffer-msgdb))))
10668 (from (wl-summary-line-from))
10669 (to (car (elmo-message-entity-field wl-message-entity 'to)))
10670 (subject (let (wl-thr-indent-string wl-parent-message-entity)
10671 (wl-summary-line-subject))))
10672 (org-store-link-props :type "wl" :from from :to to
10673 :subject subject :message-id message-id)
10674 (setq message-id (org-remove-angle-brackets message-id))
10675 (setq cpltxt (org-email-link-description))
10676 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
10677 "#" message-id))))
10679 ((or (equal major-mode 'mh-folder-mode)
10680 (equal major-mode 'mh-show-mode))
10681 (let ((from (org-mhe-get-header "From:"))
10682 (to (org-mhe-get-header "To:"))
10683 (message-id (org-mhe-get-header "Message-Id:"))
10684 (subject (org-mhe-get-header "Subject:")))
10685 (org-store-link-props :type "mh" :from from :to to
10686 :subject subject :message-id message-id)
10687 (setq cpltxt (org-email-link-description))
10688 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
10689 (org-remove-angle-brackets message-id)))))
10691 ((eq major-mode 'rmail-mode)
10692 (save-excursion
10693 (save-restriction
10694 (rmail-narrow-to-non-pruned-header)
10695 (let ((folder buffer-file-name)
10696 (message-id (mail-fetch-field "message-id"))
10697 (from (mail-fetch-field "from"))
10698 (to (mail-fetch-field "to"))
10699 (subject (mail-fetch-field "subject")))
10700 (org-store-link-props
10701 :type "rmail" :from from :to to
10702 :subject subject :message-id message-id)
10703 (setq message-id (org-remove-angle-brackets message-id))
10704 (setq cpltxt (org-email-link-description))
10705 (setq link (org-make-link "rmail:" folder "#" message-id))))))
10707 ((eq major-mode 'gnus-group-mode)
10708 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
10709 (gnus-group-group-name)) ; version
10710 ((fboundp 'gnus-group-name)
10711 (gnus-group-name))
10712 (t "???"))))
10713 (unless group (error "Not on a group"))
10714 (org-store-link-props :type "gnus" :group group)
10715 (setq cpltxt (concat
10716 (if (org-xor arg org-usenet-links-prefer-google)
10717 "http://groups.google.com/groups?group="
10718 "gnus:")
10719 group)
10720 link (org-make-link cpltxt))))
10722 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
10723 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
10724 (let* ((group gnus-newsgroup-name)
10725 (article (gnus-summary-article-number))
10726 (header (gnus-summary-article-header article))
10727 (from (mail-header-from header))
10728 (message-id (mail-header-id header))
10729 (date (mail-header-date header))
10730 (subject (gnus-summary-subject-string)))
10731 (org-store-link-props :type "gnus" :from from :subject subject
10732 :message-id message-id :group group)
10733 (setq cpltxt (org-email-link-description))
10734 (if (org-xor arg org-usenet-links-prefer-google)
10735 (setq link
10736 (concat
10737 cpltxt "\n "
10738 (format "http://groups.google.com/groups?as_umsgid=%s"
10739 (org-fixup-message-id-for-http message-id))))
10740 (setq link (org-make-link "gnus:" group
10741 "#" (number-to-string article))))))
10743 ((eq major-mode 'w3-mode)
10744 (setq cpltxt (url-view-url t)
10745 link (org-make-link cpltxt))
10746 (org-store-link-props :type "w3" :url (url-view-url t)))
10748 ((eq major-mode 'w3m-mode)
10749 (setq cpltxt (or w3m-current-title w3m-current-url)
10750 link (org-make-link w3m-current-url))
10751 (org-store-link-props :type "w3m" :url (url-view-url t)))
10753 ((setq search (run-hook-with-args-until-success
10754 'org-create-file-search-functions))
10755 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10756 "::" search))
10757 (setq cpltxt (or description link)))
10759 ((eq major-mode 'image-mode)
10760 (setq cpltxt (concat "file:"
10761 (abbreviate-file-name buffer-file-name))
10762 link (org-make-link cpltxt))
10763 (org-store-link-props :type "image" :file buffer-file-name))
10765 ((eq major-mode 'dired-mode)
10766 ;; link to the file in the current line
10767 (setq cpltxt (concat "file:"
10768 (abbreviate-file-name
10769 (expand-file-name
10770 (dired-get-filename nil t))))
10771 link (org-make-link cpltxt)))
10773 ((and buffer-file-name (org-mode-p))
10774 ;; Just link to current headline
10775 (setq cpltxt (concat "file:"
10776 (abbreviate-file-name buffer-file-name)))
10777 ;; Add a context search string
10778 (when (org-xor org-context-in-file-links arg)
10779 ;; Check if we are on a target
10780 (if (org-in-regexp "<<\\(.*?\\)>>")
10781 (setq cpltxt (concat cpltxt "::" (match-string 1)))
10782 (setq txt (cond
10783 ((org-on-heading-p) nil)
10784 ((org-region-active-p)
10785 (buffer-substring (region-beginning) (region-end)))
10786 (t (buffer-substring (point-at-bol) (point-at-eol)))))
10787 (when (or (null txt) (string-match "\\S-" txt))
10788 (setq cpltxt
10789 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10790 desc "NONE"))))
10791 (if (string-match "::\\'" cpltxt)
10792 (setq cpltxt (substring cpltxt 0 -2)))
10793 (setq link (org-make-link cpltxt)))
10795 (buffer-file-name
10796 ;; Just link to this file here.
10797 (setq cpltxt (concat "file:"
10798 (abbreviate-file-name buffer-file-name)))
10799 ;; Add a context string
10800 (when (org-xor org-context-in-file-links arg)
10801 (setq txt (if (org-region-active-p)
10802 (buffer-substring (region-beginning) (region-end))
10803 (buffer-substring (point-at-bol) (point-at-eol))))
10804 ;; Only use search option if there is some text.
10805 (when (string-match "\\S-" txt)
10806 (setq cpltxt
10807 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10808 desc "NONE")))
10809 (setq link (org-make-link cpltxt)))
10811 ((interactive-p)
10812 (error "Cannot link to a buffer which is not visiting a file"))
10814 (t (setq link nil)))
10816 (if (consp link) (setq cpltxt (car link) link (cdr link)))
10817 (setq link (or link cpltxt)
10818 desc (or desc cpltxt))
10819 (if (equal desc "NONE") (setq desc nil))
10821 (if (and (interactive-p) link)
10822 (progn
10823 (setq org-stored-links
10824 (cons (list cpltxt link desc) org-stored-links))
10825 (message "Stored: %s" (or cpltxt link)))
10826 (org-make-link-string link desc))))
10828 (defun org-store-link-props (&rest plist)
10829 "Store link properties, extract names and addresses."
10830 (let (x adr)
10831 (when (setq x (plist-get plist :from))
10832 (setq adr (mail-extract-address-components x))
10833 (plist-put plist :fromname (car adr))
10834 (plist-put plist :fromaddress (nth 1 adr)))
10835 (when (setq x (plist-get plist :to))
10836 (setq adr (mail-extract-address-components x))
10837 (plist-put plist :toname (car adr))
10838 (plist-put plist :toaddress (nth 1 adr))))
10839 (let ((from (plist-get plist :from))
10840 (to (plist-get plist :to)))
10841 (when (and from to org-from-is-user-regexp)
10842 (plist-put plist :fromto
10843 (if (string-match org-from-is-user-regexp from)
10844 (concat "to %t")
10845 (concat "from %f")))))
10846 (setq org-store-link-plist plist))
10848 (defun org-email-link-description (&optional fmt)
10849 "Return the description part of an email link.
10850 This takes information from `org-store-link-plist' and formats it
10851 according to FMT (default from `org-email-link-description-format')."
10852 (setq fmt (or fmt org-email-link-description-format))
10853 (let* ((p org-store-link-plist)
10854 (to (plist-get p :toaddress))
10855 (from (plist-get p :fromaddress))
10856 (table
10857 (list
10858 (cons "%c" (plist-get p :fromto))
10859 (cons "%F" (plist-get p :from))
10860 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10861 (cons "%T" (plist-get p :to))
10862 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10863 (cons "%s" (plist-get p :subject))
10864 (cons "%m" (plist-get p :message-id)))))
10865 (when (string-match "%c" fmt)
10866 ;; Check if the user wrote this message
10867 (if (and org-from-is-user-regexp from to
10868 (save-match-data (string-match org-from-is-user-regexp from)))
10869 (setq fmt (replace-match "to %t" t t fmt))
10870 (setq fmt (replace-match "from %f" t t fmt))))
10871 (org-replace-escapes fmt table)))
10873 (defun org-make-org-heading-search-string (&optional string heading)
10874 "Make search string for STRING or current headline."
10875 (interactive)
10876 (let ((s (or string (org-get-heading))))
10877 (unless (and string (not heading))
10878 ;; We are using a headline, clean up garbage in there.
10879 (if (string-match org-todo-regexp s)
10880 (setq s (replace-match "" t t s)))
10881 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
10882 (setq s (replace-match "" t t s)))
10883 (setq s (org-trim s))
10884 (if (string-match (concat "^\\(" org-quote-string "\\|"
10885 org-comment-string "\\)") s)
10886 (setq s (replace-match "" t t s)))
10887 (while (string-match org-ts-regexp s)
10888 (setq s (replace-match "" t t s))))
10889 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
10890 (setq s (replace-match " " t t s)))
10891 (or string (setq s (concat "*" s))) ; Add * for headlines
10892 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10894 (defun org-make-link (&rest strings)
10895 "Concatenate STRINGS."
10896 (apply 'concat strings))
10898 (defun org-make-link-string (link &optional description)
10899 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10900 (unless (string-match "\\S-" link)
10901 (error "Empty link"))
10902 (when (stringp description)
10903 ;; Remove brackets from the description, they are fatal.
10904 (while (string-match "\\[\\|\\]" description)
10905 (setq description (replace-match "" t t description))))
10906 (when (equal (org-link-escape link) description)
10907 ;; No description needed, it is identical
10908 (setq description nil))
10909 (when (and (not description)
10910 (not (equal link (org-link-escape link))))
10911 (setq description link))
10912 (concat "[[" (org-link-escape link) "]"
10913 (if description (concat "[" description "]") "")
10914 "]"))
10916 (defconst org-link-escape-chars
10917 '((" " . "%20") ("\340" . "%E0")
10918 ("\342" . "%E2") ("\347" . "%E7")
10919 ("\350" . "%E8") ("\351" . "%E9")
10920 ("\352" . "%EA") ("\356" . "%EE")
10921 ("\364" . "%F4") ("\371" . "%F9")
10922 ("\373" . "%FB") (";" . "%3B")
10923 ("?" . "%3F") ("=" . "%3D")
10924 ("+" . "%2B"))
10925 "Association list of escapes for some characters problematic in links.")
10927 (defun org-link-escape (text)
10928 "Escape charaters in TEXT that are problematic for links."
10929 (when text
10930 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
10931 org-link-escape-chars "\\|")))
10932 (while (string-match re text)
10933 (setq text
10934 (replace-match
10935 (cdr (assoc (match-string 0 text) org-link-escape-chars))
10936 t t text)))
10937 text)))
10939 (defun org-link-unescape (text)
10940 "Reverse the action of `org-link-escape'."
10941 (when text
10942 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
10943 org-link-escape-chars "\\|")))
10944 (while (string-match re text)
10945 (setq text
10946 (replace-match
10947 (car (rassoc (match-string 0 text) org-link-escape-chars))
10948 t t text)))
10949 text)))
10951 (defun org-xor (a b)
10952 "Exclusive or."
10953 (if a (not b) b))
10955 (defun org-get-header (header)
10956 "Find a header field in the current buffer."
10957 (save-excursion
10958 (goto-char (point-min))
10959 (let ((case-fold-search t) s)
10960 (cond
10961 ((eq header 'from)
10962 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
10963 (setq s (match-string 1)))
10964 (while (string-match "\"" s)
10965 (setq s (replace-match "" t t s)))
10966 (if (string-match "[<(].*" s)
10967 (setq s (replace-match "" t t s))))
10968 ((eq header 'message-id)
10969 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
10970 (setq s (match-string 1))))
10971 ((eq header 'subject)
10972 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
10973 (setq s (match-string 1)))))
10974 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
10975 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
10976 s)))
10979 (defun org-fixup-message-id-for-http (s)
10980 "Replace special characters in a message id, so it can be used in an http query."
10981 (while (string-match "<" s)
10982 (setq s (replace-match "%3C" t t s)))
10983 (while (string-match ">" s)
10984 (setq s (replace-match "%3E" t t s)))
10985 (while (string-match "@" s)
10986 (setq s (replace-match "%40" t t s)))
10989 ;;;###autoload
10990 (defun org-insert-link-global ()
10991 "Insert a link like Org-mode does.
10992 This command can be called in any mode to insert a link in Org-mode syntax."
10993 (interactive)
10994 (org-run-like-in-org-mode 'org-insert-link))
10996 (defun org-insert-link (&optional complete-file)
10997 "Insert a link. At the prompt, enter the link.
10999 Completion can be used to select a link previously stored with
11000 `org-store-link'. When the empty string is entered (i.e. if you just
11001 press RET at the prompt), the link defaults to the most recently
11002 stored link. As SPC triggers completion in the minibuffer, you need to
11003 use M-SPC or C-q SPC to force the insertion of a space character.
11005 You will also be prompted for a description, and if one is given, it will
11006 be displayed in the buffer instead of the link.
11008 If there is already a link at point, this command will allow you to edit link
11009 and description parts.
11011 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11012 selected using completion. The path to the file will be relative to
11013 the current directory if the file is in the current directory or a
11014 subdirectory. Otherwise, the link will be the absolute path as
11015 completed in the minibuffer (i.e. normally ~/path/to/file).
11017 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11018 is in the current directory or below.
11019 With three \\[universal-argument] prefixes, negate the meaning of
11020 `org-keep-stored-link-after-insertion'."
11021 (interactive "P")
11022 (let ((wcf (current-window-configuration))
11023 (region (if (org-region-active-p)
11024 (prog1 (buffer-substring (region-beginning) (region-end))
11025 (delete-region (region-beginning) (region-end)))))
11026 tmphist ; byte-compile incorrectly complains about this
11027 link desc entry remove file)
11028 (cond
11029 ((org-in-regexp org-bracket-link-regexp 1)
11030 ;; We do have a link at point, and we are going to edit it.
11031 (setq remove (list (match-beginning 0) (match-end 0)))
11032 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11033 (setq link (read-string "Link: "
11034 (org-link-unescape
11035 (org-match-string-no-properties 1)))))
11036 ((or (org-in-regexp org-angle-link-re)
11037 (org-in-regexp org-plain-link-re))
11038 ;; Convert to bracket link
11039 (setq remove (list (match-beginning 0) (match-end 0))
11040 link (read-string "Link: "
11041 (org-remove-angle-brackets (match-string 0)))))
11042 ((equal complete-file '(4))
11043 ;; Completing read for file names.
11044 (setq file (read-file-name "File: "))
11045 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11046 (pwd1 (file-name-as-directory (abbreviate-file-name
11047 (expand-file-name ".")))))
11048 (cond
11049 ((equal complete-file '(16))
11050 (setq link (org-make-link
11051 "file:"
11052 (abbreviate-file-name (expand-file-name file)))))
11053 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11054 (setq link (org-make-link "file:" (match-string 1 file))))
11055 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11056 (expand-file-name file))
11057 (setq link (org-make-link
11058 "file:" (match-string 1 (expand-file-name file)))))
11059 (t (setq link (org-make-link "file:" file))))))
11061 ;; Read link, with completion for stored links.
11062 (with-output-to-temp-buffer "*Org Links*"
11063 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
11064 (when org-stored-links
11065 (princ "\nStored links are available with <up>/<down> (most recent with RET):\n\n")
11066 (princ (mapconcat 'car (reverse org-stored-links) "\n"))))
11067 (let ((cw (selected-window)))
11068 (select-window (get-buffer-window "*Org Links*"))
11069 (shrink-window-if-larger-than-buffer)
11070 (setq truncate-lines t)
11071 (select-window cw))
11072 ;; Fake a link history, containing the stored links.
11073 (setq tmphist (append (mapcar 'car org-stored-links)
11074 org-insert-link-history))
11075 (unwind-protect
11076 (setq link (org-completing-read
11077 "Link: "
11078 (append
11079 (mapcar (lambda (x) (list (concat (car x) ":")))
11080 (append org-link-abbrev-alist-local org-link-abbrev-alist))
11081 (mapcar (lambda (x) (list (concat x ":")))
11082 org-link-types))
11083 nil nil nil
11084 'tmphist
11085 (or (car (car org-stored-links)))))
11086 (set-window-configuration wcf)
11087 (kill-buffer "*Org Links*"))
11088 (setq entry (assoc link org-stored-links))
11089 (or entry (push link org-insert-link-history))
11090 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11091 (not org-keep-stored-link-after-insertion))
11092 (setq org-stored-links (delq (assoc link org-stored-links)
11093 org-stored-links)))
11094 (setq link (if entry (nth 1 entry) link)
11095 desc (or region desc (nth 2 entry)))))
11097 (if (string-match org-plain-link-re link)
11098 ;; URL-like link, normalize the use of angular brackets.
11099 (setq link (org-make-link (org-remove-angle-brackets link))))
11101 ;; Check if we are linking to the current file with a search option
11102 ;; If yes, simplify the link by using only the search option.
11103 (when (and buffer-file-name
11104 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11105 (let* ((path (match-string 1 link))
11106 (case-fold-search nil)
11107 (search (match-string 2 link)))
11108 (save-match-data
11109 (if (equal (file-truename buffer-file-name) (file-truename path))
11110 ;; We are linking to this same file, with a search option
11111 (setq link search)))))
11113 ;; Check if we can/should use a relative path. If yes, simplify the link
11114 (when (string-match "\\<file:\\(.*\\)" link)
11115 (let* ((path (match-string 1 link))
11116 (case-fold-search nil))
11117 (cond
11118 ((eq org-link-file-path-type 'absolute)
11119 (setq path (abbreviate-file-name (expand-file-name path))))
11120 ((eq org-link-file-path-type 'noabbrev)
11121 (setq path (expand-file-name path)))
11122 ((eq org-link-file-path-type 'relative)
11123 (setq path (file-relative-name path)))
11125 (save-match-data
11126 (if (string-match (concat "^" (regexp-quote
11127 (file-name-as-directory
11128 (expand-file-name "."))))
11129 (expand-file-name path))
11130 ;; We are linking a file with relative path name.
11131 (setq path (substring (expand-file-name path)
11132 (match-end 0)))))))
11133 (setq link (concat "file:" path))))
11135 (setq desc (read-string "Description: " desc))
11136 (unless (string-match "\\S-" desc) (setq desc nil))
11137 (if remove (apply 'delete-region remove))
11138 (insert (org-make-link-string link desc))))
11140 (defun org-completing-read (&rest args)
11141 (let ((minibuffer-local-completion-map
11142 (copy-keymap minibuffer-local-completion-map)))
11143 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
11144 (apply 'completing-read args)))
11146 ;;; Opening/following a link
11147 (defvar org-link-search-failed nil)
11149 (defun org-next-link ()
11150 "Move forward to the next link.
11151 If the link is in hidden text, expose it."
11152 (interactive)
11153 (when (and org-link-search-failed (eq this-command last-command))
11154 (goto-char (point-min))
11155 (message "Link search wrapped back to beginning of buffer"))
11156 (setq org-link-search-failed nil)
11157 (let* ((pos (point))
11158 (ct (org-context))
11159 (a (assoc :link ct)))
11160 (if a (goto-char (nth 2 a)))
11161 (if (re-search-forward org-any-link-re nil t)
11162 (progn
11163 (goto-char (match-beginning 0))
11164 (if (org-invisible-p) (org-show-context)))
11165 (goto-char pos)
11166 (setq org-link-search-failed t)
11167 (error "No further link found"))))
11169 (defun org-previous-link ()
11170 "Move backward to the previous link.
11171 If the link is in hidden text, expose it."
11172 (interactive)
11173 (when (and org-link-search-failed (eq this-command last-command))
11174 (goto-char (point-max))
11175 (message "Link search wrapped back to end of buffer"))
11176 (setq org-link-search-failed nil)
11177 (let* ((pos (point))
11178 (ct (org-context))
11179 (a (assoc :link ct)))
11180 (if a (goto-char (nth 1 a)))
11181 (if (re-search-backward org-any-link-re nil t)
11182 (progn
11183 (goto-char (match-beginning 0))
11184 (if (org-invisible-p) (org-show-context)))
11185 (goto-char pos)
11186 (setq org-link-search-failed t)
11187 (error "No further link found"))))
11189 (defun org-find-file-at-mouse (ev)
11190 "Open file link or URL at mouse."
11191 (interactive "e")
11192 (mouse-set-point ev)
11193 (org-open-at-point 'in-emacs))
11195 (defun org-open-at-mouse (ev)
11196 "Open file link or URL at mouse."
11197 (interactive "e")
11198 (mouse-set-point ev)
11199 (org-open-at-point))
11201 (defvar org-window-config-before-follow-link nil
11202 "The window configuration before following a link.
11203 This is saved in case the need arises to restore it.")
11205 (defvar org-open-link-marker (make-marker)
11206 "Marker pointing to the location where `org-open-at-point; was called.")
11208 ;;;###autoload
11209 (defun org-open-at-point-global ()
11210 "Follow a link like Org-mode does.
11211 This command can be called in any mode to follow a link that has
11212 Org-mode syntax."
11213 (interactive)
11214 (org-run-like-in-org-mode 'org-open-at-point))
11216 (defun org-open-at-point (&optional in-emacs)
11217 "Open link at or after point.
11218 If there is no link at point, this function will search forward up to
11219 the end of the current subtree.
11220 Normally, files will be opened by an appropriate application. If the
11221 optional argument IN-EMACS is non-nil, Emacs will visit the file."
11222 (interactive "P")
11223 (move-marker org-open-link-marker (point))
11224 (setq org-window-config-before-follow-link (current-window-configuration))
11225 (org-remove-occur-highlights nil nil t)
11226 (if (org-at-timestamp-p t)
11227 (org-follow-timestamp-link)
11228 (let (type path link line search (pos (point)))
11229 (catch 'match
11230 (save-excursion
11231 (skip-chars-forward "^]\n\r")
11232 (when (org-in-regexp org-bracket-link-regexp)
11233 (setq link (org-link-unescape (org-match-string-no-properties 1)))
11234 (while (string-match " *\n *" link)
11235 (setq link (replace-match " " t t link)))
11236 (setq link (org-link-expand-abbrev link))
11237 (if (string-match org-link-re-with-space2 link)
11238 (setq type (match-string 1 link) path (match-string 2 link))
11239 (setq type "thisfile" path link))
11240 (throw 'match t)))
11242 (when (get-text-property (point) 'org-linked-text)
11243 (setq type "thisfile"
11244 pos (if (get-text-property (1+ (point)) 'org-linked-text)
11245 (1+ (point)) (point))
11246 path (buffer-substring
11247 (previous-single-property-change pos 'org-linked-text)
11248 (next-single-property-change pos 'org-linked-text)))
11249 (throw 'match t))
11251 (save-excursion
11252 (when (or (org-in-regexp org-angle-link-re)
11253 (org-in-regexp org-plain-link-re))
11254 (setq type (match-string 1) path (match-string 2))
11255 (throw 'match t)))
11256 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
11257 (setq type "tree-match"
11258 path (match-string 1))
11259 (throw 'match t))
11260 (save-excursion
11261 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
11262 (setq type "tags"
11263 path (match-string 1))
11264 (while (string-match ":" path)
11265 (setq path (replace-match "+" t t path)))
11266 (throw 'match t))))
11267 (unless path
11268 (error "No link found"))
11269 ;; Remove any trailing spaces in path
11270 (if (string-match " +\\'" path)
11271 (setq path (replace-match "" t t path)))
11273 (cond
11275 ((assoc type org-link-protocols)
11276 (funcall (nth 1 (assoc type org-link-protocols)) path))
11278 ((equal type "mailto")
11279 (let ((cmd (car org-link-mailto-program))
11280 (args (cdr org-link-mailto-program)) args1
11281 (address path) (subject "") a)
11282 (if (string-match "\\(.*\\)::\\(.*\\)" path)
11283 (setq address (match-string 1 path)
11284 subject (org-link-escape (match-string 2 path))))
11285 (while args
11286 (cond
11287 ((not (stringp (car args))) (push (pop args) args1))
11288 (t (setq a (pop args))
11289 (if (string-match "%a" a)
11290 (setq a (replace-match address t t a)))
11291 (if (string-match "%s" a)
11292 (setq a (replace-match subject t t a)))
11293 (push a args1))))
11294 (apply cmd (nreverse args1))))
11296 ((member type '("http" "https" "ftp" "news"))
11297 (browse-url (concat type ":" path)))
11299 ((string= type "tags")
11300 (org-tags-view in-emacs path))
11301 ((string= type "thisfile")
11302 (if in-emacs
11303 (switch-to-buffer-other-window
11304 (org-get-buffer-for-internal-link (current-buffer)))
11305 (org-mark-ring-push))
11306 (let ((cmd `(org-link-search
11307 ,path
11308 ,(cond ((equal in-emacs '(4)) 'occur)
11309 ((equal in-emacs '(16)) 'org-occur)
11310 (t nil))
11311 ,pos)))
11312 (condition-case nil (eval cmd)
11313 (error (progn (widen) (eval cmd))))))
11315 ((string= type "tree-match")
11316 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
11318 ((string= type "file")
11319 (if (string-match "::\\([0-9]+\\)\\'" path)
11320 (setq line (string-to-number (match-string 1 path))
11321 path (substring path 0 (match-beginning 0)))
11322 (if (string-match "::\\(.+\\)\\'" path)
11323 (setq search (match-string 1 path)
11324 path (substring path 0 (match-beginning 0)))))
11325 (org-open-file path in-emacs line search))
11327 ((string= type "news")
11328 (org-follow-gnus-link path))
11330 ((string= type "bbdb")
11331 (org-follow-bbdb-link path))
11333 ((string= type "info")
11334 (org-follow-info-link path))
11336 ((string= type "gnus")
11337 (let (group article)
11338 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11339 (error "Error in Gnus link"))
11340 (setq group (match-string 1 path)
11341 article (match-string 3 path))
11342 (org-follow-gnus-link group article)))
11344 ((string= type "vm")
11345 (let (folder article)
11346 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11347 (error "Error in VM link"))
11348 (setq folder (match-string 1 path)
11349 article (match-string 3 path))
11350 ;; in-emacs is the prefix arg, will be interpreted as read-only
11351 (org-follow-vm-link folder article in-emacs)))
11353 ((string= type "wl")
11354 (let (folder article)
11355 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11356 (error "Error in Wanderlust link"))
11357 (setq folder (match-string 1 path)
11358 article (match-string 3 path))
11359 (org-follow-wl-link folder article)))
11361 ((string= type "mhe")
11362 (let (folder article)
11363 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11364 (error "Error in MHE link"))
11365 (setq folder (match-string 1 path)
11366 article (match-string 3 path))
11367 (org-follow-mhe-link folder article)))
11369 ((string= type "rmail")
11370 (let (folder article)
11371 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11372 (error "Error in RMAIL link"))
11373 (setq folder (match-string 1 path)
11374 article (match-string 3 path))
11375 (org-follow-rmail-link folder article)))
11377 ((string= type "shell")
11378 (let ((cmd path))
11379 ;; FIXME: the following is only for backward compatibility
11380 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
11381 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
11382 (if (or (not org-confirm-shell-link-function)
11383 (funcall org-confirm-shell-link-function
11384 (format "Execute \"%s\" in shell? "
11385 (org-add-props cmd nil
11386 'face 'org-warning))))
11387 (progn
11388 (message "Executing %s" cmd)
11389 (shell-command cmd))
11390 (error "Abort"))))
11392 ((string= type "elisp")
11393 (let ((cmd path))
11394 (if (or (not org-confirm-elisp-link-function)
11395 (funcall org-confirm-elisp-link-function
11396 (format "Execute \"%s\" as elisp? "
11397 (org-add-props cmd nil
11398 'face 'org-warning))))
11399 (message "%s => %s" cmd (eval (read cmd)))
11400 (error "Abort"))))
11403 (browse-url-at-point)))))
11404 (move-marker org-open-link-marker nil))
11407 ;;; File search
11409 (defvar org-create-file-search-functions nil
11410 "List of functions to construct the right search string for a file link.
11411 These functions are called in turn with point at the location to
11412 which the link should point.
11414 A function in the hook should first test if it would like to
11415 handle this file type, for example by checking the major-mode or
11416 the file extension. If it decides not to handle this file, it
11417 should just return nil to give other functions a chance. If it
11418 does handle the file, it must return the search string to be used
11419 when following the link. The search string will be part of the
11420 file link, given after a double colon, and `org-open-at-point'
11421 will automatically search for it. If special measures must be
11422 taken to make the search successful, another function should be
11423 added to the companion hook `org-execute-file-search-functions',
11424 which see.
11426 A function in this hook may also use `setq' to set the variable
11427 `description' to provide a suggestion for the descriptive text to
11428 be used for this link when it gets inserted into an Org-mode
11429 buffer with \\[org-insert-link].")
11431 (defvar org-execute-file-search-functions nil
11432 "List of functions to execute a file search triggered by a link.
11434 Functions added to this hook must accept a single argument, the
11435 search string that was part of the file link, the part after the
11436 double colon. The function must first check if it would like to
11437 handle this search, for example by checking the major-mode or the
11438 file extension. If it decides not to handle this search, it
11439 should just return nil to give other functions a chance. If it
11440 does handle the search, it must return a non-nil value to keep
11441 other functions from trying.
11443 Each function can access the current prefix argument through the
11444 variable `current-prefix-argument'. Note that a single prefix is
11445 used to force opening a link in Emacs, so it may be good to only
11446 use a numeric or double prefix to guide the search function.
11448 In case this is needed, a function in this hook can also restore
11449 the window configuration before `org-open-at-point' was called using:
11451 (set-window-configuration org-window-config-before-follow-link)")
11453 (defun org-link-search (s &optional type avoid-pos)
11454 "Search for a link search option.
11455 If S is surrounded by forward slashes, it is interpreted as a
11456 regular expression. In org-mode files, this will create an `org-occur'
11457 sparse tree. In ordinary files, `occur' will be used to list matches.
11458 If the current buffer is in `dired-mode', grep will be used to search
11459 in all files. If AVOID-POS is given, ignore matches near that position."
11460 (let ((case-fold-search t)
11461 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
11462 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
11463 (append '(("") (" ") ("\t") ("\n"))
11464 org-emphasis-alist)
11465 "\\|") "\\)"))
11466 (pos (point))
11467 (pre "") (post "")
11468 words re0 re1 re2 re3 re4 re5 re2a reall)
11469 (cond
11470 ;; First check if there are any special
11471 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11472 ;; Now try the builtin stuff
11473 ((save-excursion
11474 (goto-char (point-min))
11475 (and
11476 (re-search-forward
11477 (concat "<<" (regexp-quote s0) ">>") nil t)
11478 (setq pos (match-beginning 0))))
11479 ;; There is an exact target for this
11480 (goto-char pos))
11481 ((string-match "^/\\(.*\\)/$" s)
11482 ;; A regular expression
11483 (cond
11484 ((org-mode-p)
11485 (org-occur (match-string 1 s)))
11486 ;;((eq major-mode 'dired-mode)
11487 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
11488 (t (org-do-occur (match-string 1 s)))))
11490 ;; A normal search strings
11491 (when (equal (string-to-char s) ?*)
11492 ;; Anchor on headlines, post may include tags.
11493 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11494 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
11495 s (substring s 1)))
11496 (remove-text-properties
11497 0 (length s)
11498 '(face nil mouse-face nil keymap nil fontified nil) s)
11499 ;; Make a series of regular expressions to find a match
11500 (setq words (org-split-string s "[ \n\r\t]+")
11501 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11502 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11503 "\\)" markers)
11504 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
11505 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11506 re1 (concat pre re2 post)
11507 re3 (concat pre re4 post)
11508 re5 (concat pre ".*" re4)
11509 re2 (concat pre re2)
11510 re2a (concat pre re2a)
11511 re4 (concat pre re4)
11512 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11513 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11514 re5 "\\)"
11516 (cond
11517 ((eq type 'org-occur) (org-occur reall))
11518 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11519 (t (goto-char (point-min))
11520 (if (or (org-search-not-self 1 re0 nil t)
11521 (org-search-not-self 1 re1 nil t)
11522 (org-search-not-self 1 re2 nil t)
11523 (org-search-not-self 1 re2a nil t)
11524 (org-search-not-self 1 re3 nil t)
11525 (org-search-not-self 1 re4 nil t)
11526 (org-search-not-self 1 re5 nil t)
11528 (goto-char (match-beginning 1))
11529 (goto-char pos)
11530 (error "No match")))))
11532 ;; Normal string-search
11533 (goto-char (point-min))
11534 (if (search-forward s nil t)
11535 (goto-char (match-beginning 0))
11536 (error "No match"))))
11537 (and (org-mode-p) (org-show-context 'link-search))))
11539 (defun org-search-not-self (group &rest args)
11540 "Execute `re-search-forward', but only accept matches that do not
11541 enclose the position of `org-open-link-marker'."
11542 (let ((m org-open-link-marker))
11543 (catch 'exit
11544 (while (apply 're-search-forward args)
11545 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11546 (goto-char (match-end group))
11547 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11548 (> (match-beginning 0) (marker-position m))
11549 (< (match-end 0) (marker-position m)))
11550 (save-match-data
11551 (or (not (org-in-regexp
11552 org-bracket-link-analytic-regexp 1))
11553 (not (match-end 4)) ; no description
11554 (and (<= (match-beginning 4) (point))
11555 (>= (match-end 4) (point))))))
11556 (throw 'exit (point))))))))
11558 (defun org-get-buffer-for-internal-link (buffer)
11559 "Return a buffer to be used for displaying the link target of internal links."
11560 (cond
11561 ((not org-display-internal-link-with-indirect-buffer)
11562 buffer)
11563 ((string-match "(Clone)$" (buffer-name buffer))
11564 (message "Buffer is already a clone, not making another one")
11565 ;; we also do not modify visibility in this case
11566 buffer)
11567 (t ; make a new indirect buffer for displaying the link
11568 (let* ((bn (buffer-name buffer))
11569 (ibn (concat bn "(Clone)"))
11570 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11571 (with-current-buffer ib (org-overview))
11572 ib))))
11574 (defun org-do-occur (regexp &optional cleanup)
11575 "Call the Emacs command `occur'.
11576 If CLEANUP is non-nil, remove the printout of the regular expression
11577 in the *Occur* buffer. This is useful if the regex is long and not useful
11578 to read."
11579 (occur regexp)
11580 (when cleanup
11581 (let ((cwin (selected-window)) win beg end)
11582 (when (setq win (get-buffer-window "*Occur*"))
11583 (select-window win))
11584 (goto-char (point-min))
11585 (when (re-search-forward "match[a-z]+" nil t)
11586 (setq beg (match-end 0))
11587 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11588 (setq end (1- (match-beginning 0)))))
11589 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11590 (goto-char (point-min))
11591 (select-window cwin))))
11593 ;;; The mark ring for links jumps
11595 (defvar org-mark-ring nil
11596 "Mark ring for positions before jumps in Org-mode.")
11597 (defvar org-mark-ring-last-goto nil
11598 "Last position in the mark ring used to go back.")
11599 ;; Fill and close the ring
11600 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11601 (loop for i from 1 to org-mark-ring-length do
11602 (push (make-marker) org-mark-ring))
11603 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11604 org-mark-ring)
11606 (defun org-mark-ring-push (&optional pos buffer)
11607 "Put the current position or POS into the mark ring and rotate it."
11608 (interactive)
11609 (setq pos (or pos (point)))
11610 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11611 (move-marker (car org-mark-ring)
11612 (or pos (point))
11613 (or buffer (current-buffer)))
11614 (message
11615 (substitute-command-keys
11616 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11618 (defun org-mark-ring-goto (&optional n)
11619 "Jump to the previous position in the mark ring.
11620 With prefix arg N, jump back that many stored positions. When
11621 called several times in succession, walk through the entire ring.
11622 Org-mode commands jumping to a different position in the current file,
11623 or to another Org-mode file, automatically push the old position
11624 onto the ring."
11625 (interactive "p")
11626 (let (p m)
11627 (if (eq last-command this-command)
11628 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11629 (setq p org-mark-ring))
11630 (setq org-mark-ring-last-goto p)
11631 (setq m (car p))
11632 (switch-to-buffer (marker-buffer m))
11633 (goto-char m)
11634 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11636 (defun org-remove-angle-brackets (s)
11637 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11638 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11640 (defun org-add-angle-brackets (s)
11641 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11642 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11645 ;;; Following specific links
11647 (defun org-follow-timestamp-link ()
11648 (cond
11649 ((org-at-date-range-p t)
11650 (let ((org-agenda-start-on-weekday)
11651 (t1 (match-string 1))
11652 (t2 (match-string 2)))
11653 (setq t1 (time-to-days (org-time-string-to-time t1))
11654 t2 (time-to-days (org-time-string-to-time t2)))
11655 (org-agenda-list nil t1 (1+ (- t2 t1)))))
11656 ((org-at-timestamp-p t)
11657 (org-agenda-list nil (time-to-days (org-time-string-to-time
11658 (substring (match-string 1) 0 10)))
11660 (t (error "This should not happen"))))
11663 (defun org-follow-bbdb-link (name)
11664 "Follow a BBDB link to NAME."
11665 (require 'bbdb)
11666 (let ((inhibit-redisplay (not debug-on-error))
11667 (bbdb-electric-p nil))
11668 (catch 'exit
11669 ;; Exact match on name
11670 (bbdb-name (concat "\\`" name "\\'") nil)
11671 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11672 ;; Exact match on name
11673 (bbdb-company (concat "\\`" name "\\'") nil)
11674 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11675 ;; Partial match on name
11676 (bbdb-name name nil)
11677 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11678 ;; Partial match on company
11679 (bbdb-company name nil)
11680 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11681 ;; General match including network address and notes
11682 (bbdb name nil)
11683 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
11684 (delete-window (get-buffer-window "*BBDB*"))
11685 (error "No matching BBDB record")))))
11687 (defun org-follow-info-link (name)
11688 "Follow an info file & node link to NAME."
11689 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
11690 (string-match "\\(.*\\)" name))
11691 (progn
11692 (require 'info)
11693 (if (match-string 2 name) ; If there isn't a node, choose "Top"
11694 (Info-find-node (match-string 1 name) (match-string 2 name))
11695 (Info-find-node (match-string 1 name) "Top")))
11696 (message (concat "Could not open: " name))))
11698 (defun org-follow-gnus-link (&optional group article)
11699 "Follow a Gnus link to GROUP and ARTICLE."
11700 (require 'gnus)
11701 (funcall (cdr (assq 'gnus org-link-frame-setup)))
11702 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
11703 (cond ((and group article)
11704 (gnus-group-read-group 1 nil group)
11705 (gnus-summary-goto-article (string-to-number article) nil t))
11706 (group (gnus-group-jump-to-group group))))
11708 (defun org-follow-vm-link (&optional folder article readonly)
11709 "Follow a VM link to FOLDER and ARTICLE."
11710 (require 'vm)
11711 (setq article (org-add-angle-brackets article))
11712 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
11713 ;; ange-ftp or efs or tramp access
11714 (let ((user (or (match-string 1 folder) (user-login-name)))
11715 (host (match-string 2 folder))
11716 (file (match-string 3 folder)))
11717 (cond
11718 ((featurep 'tramp)
11719 ;; use tramp to access the file
11720 (if (featurep 'xemacs)
11721 (setq folder (format "[%s@%s]%s" user host file))
11722 (setq folder (format "/%s@%s:%s" user host file))))
11724 ;; use ange-ftp or efs
11725 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
11726 (setq folder (format "/%s@%s:%s" user host file))))))
11727 (when folder
11728 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
11729 (sit-for 0.1)
11730 (when article
11731 (vm-select-folder-buffer)
11732 (widen)
11733 (let ((case-fold-search t))
11734 (goto-char (point-min))
11735 (if (not (re-search-forward
11736 (concat "^" "message-id: *" (regexp-quote article))))
11737 (error "Could not find the specified message in this folder"))
11738 (vm-isearch-update)
11739 (vm-isearch-narrow)
11740 (vm-beginning-of-message)
11741 (vm-summarize)))))
11743 (defun org-follow-wl-link (folder article)
11744 "Follow a Wanderlust link to FOLDER and ARTICLE."
11745 (if (and (string= folder "%")
11746 article
11747 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
11748 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
11749 ;; Thus, we recompose folder and article ids.
11750 (setq folder (format "%s#%s" folder (match-string 1 article))
11751 article (match-string 3 article)))
11752 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
11753 (error "No such folder: %s" folder))
11754 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
11755 (and article
11756 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
11757 (wl-summary-redisplay)))
11759 (defun org-follow-rmail-link (folder article)
11760 "Follow an RMAIL link to FOLDER and ARTICLE."
11761 (setq article (org-add-angle-brackets article))
11762 (let (message-number)
11763 (save-excursion
11764 (save-window-excursion
11765 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
11766 (setq message-number
11767 (save-restriction
11768 (widen)
11769 (goto-char (point-max))
11770 (if (re-search-backward
11771 (concat "^Message-ID:\\s-+" (regexp-quote
11772 (or article "")))
11773 nil t)
11774 (rmail-what-message))))))
11775 (if message-number
11776 (progn
11777 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
11778 (rmail-show-message message-number)
11779 message-number)
11780 (error "Message not found"))))
11782 ;;; mh-e integration based on planner-mode
11783 (defun org-mhe-get-message-real-folder ()
11784 "Return the name of the current message real folder, so if you use
11785 sequences, it will now work."
11786 (save-excursion
11787 (let* ((folder
11788 (if (equal major-mode 'mh-folder-mode)
11789 mh-current-folder
11790 ;; Refer to the show buffer
11791 mh-show-folder-buffer))
11792 (end-index
11793 (if (boundp 'mh-index-folder)
11794 (min (length mh-index-folder) (length folder))))
11796 ;; a simple test on mh-index-data does not work, because
11797 ;; mh-index-data is always nil in a show buffer.
11798 (if (and (boundp 'mh-index-folder)
11799 (string= mh-index-folder (substring folder 0 end-index)))
11800 (if (equal major-mode 'mh-show-mode)
11801 (save-window-excursion
11802 (when (buffer-live-p (get-buffer folder))
11803 (progn
11804 (pop-to-buffer folder)
11805 (org-mhe-get-message-folder-from-index)
11808 (org-mhe-get-message-folder-from-index)
11810 folder
11814 (defun org-mhe-get-message-folder-from-index ()
11815 "Returns the name of the message folder in a index folder buffer."
11816 (save-excursion
11817 (mh-index-previous-folder)
11818 (re-search-forward "^\\(+.*\\)$" nil t)
11819 (message (match-string 1))))
11821 (defun org-mhe-get-message-folder ()
11822 "Return the name of the current message folder. Be careful if you
11823 use sequences."
11824 (save-excursion
11825 (if (equal major-mode 'mh-folder-mode)
11826 mh-current-folder
11827 ;; Refer to the show buffer
11828 mh-show-folder-buffer)))
11830 (defun org-mhe-get-message-num ()
11831 "Return the number of the current message. Be careful if you
11832 use sequences."
11833 (save-excursion
11834 (if (equal major-mode 'mh-folder-mode)
11835 (mh-get-msg-num nil)
11836 ;; Refer to the show buffer
11837 (mh-show-buffer-message-number))))
11839 (defun org-mhe-get-header (header)
11840 "Return a header of the message in folder mode. This will create a
11841 show buffer for the corresponding message. If you have a more clever
11842 idea..."
11843 (let* ((folder (org-mhe-get-message-folder))
11844 (num (org-mhe-get-message-num))
11845 (buffer (get-buffer-create (concat "show-" folder)))
11846 (header-field))
11847 (with-current-buffer buffer
11848 (mh-display-msg num folder)
11849 (if (equal major-mode 'mh-folder-mode)
11850 (mh-header-display)
11851 (mh-show-header-display))
11852 (set-buffer buffer)
11853 (setq header-field (mh-get-header-field header))
11854 (if (equal major-mode 'mh-folder-mode)
11855 (mh-show)
11856 (mh-show-show))
11857 header-field)))
11859 (defun org-follow-mhe-link (folder article)
11860 "Follow an MHE link to FOLDER and ARTICLE.
11861 If ARTICLE is nil FOLDER is shown. If the configuration variable
11862 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
11863 ARTICLE is searched in all folders. Indexed searches (swish++,
11864 namazu, and others supported by MH-E) will always search in all
11865 folders."
11866 (require 'mh-e)
11867 (require 'mh-search)
11868 (require 'mh-utils)
11869 (mh-find-path)
11870 (if (not article)
11871 (mh-visit-folder (mh-normalize-folder-name folder))
11872 (setq article (org-add-angle-brackets article))
11873 (mh-search-choose)
11874 (if (equal mh-searcher 'pick)
11875 (progn
11876 (mh-search folder (list "--message-id" article))
11877 (when (and org-mhe-search-all-folders
11878 (not (org-mhe-get-message-real-folder)))
11879 (kill-this-buffer)
11880 (mh-search "+" (list "--message-id" article))))
11881 (mh-search "+" article))
11882 (if (org-mhe-get-message-real-folder)
11883 (mh-show-msg 1)
11884 (kill-this-buffer)
11885 (error "Message not found"))))
11887 ;;; BibTeX links
11889 ;; Use the custom search meachnism to construct and use search strings for
11890 ;; file links to BibTeX database entries.
11892 (defun org-create-file-search-in-bibtex ()
11893 "Create the search string and description for a BibTeX database entry."
11894 (when (eq major-mode 'bibtex-mode)
11895 ;; yes, we want to construct this search string.
11896 ;; Make a good description for this entry, using names, year and the title
11897 ;; Put it into the `description' variable which is dynamically scoped.
11898 (let ((bibtex-autokey-names 1)
11899 (bibtex-autokey-names-stretch 1)
11900 (bibtex-autokey-name-case-convert-function 'identity)
11901 (bibtex-autokey-name-separator " & ")
11902 (bibtex-autokey-additional-names " et al.")
11903 (bibtex-autokey-year-length 4)
11904 (bibtex-autokey-name-year-separator " ")
11905 (bibtex-autokey-titlewords 3)
11906 (bibtex-autokey-titleword-separator " ")
11907 (bibtex-autokey-titleword-case-convert-function 'identity)
11908 (bibtex-autokey-titleword-length 'infty)
11909 (bibtex-autokey-year-title-separator ": "))
11910 (setq description (bibtex-generate-autokey)))
11911 ;; Now parse the entry, get the key and return it.
11912 (save-excursion
11913 (bibtex-beginning-of-entry)
11914 (cdr (assoc "=key=" (bibtex-parse-entry))))))
11916 (defun org-execute-file-search-in-bibtex (s)
11917 "Find the link search string S as a key for a database entry."
11918 (when (eq major-mode 'bibtex-mode)
11919 ;; Yes, we want to do the search in this file.
11920 ;; We construct a regexp that searches for "@entrytype{" followed by the key
11921 (goto-char (point-min))
11922 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
11923 (regexp-quote s) "[ \t\n]*,") nil t)
11924 (goto-char (match-beginning 0)))
11925 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
11926 ;; Use double prefix to indicate that any web link should be browsed
11927 (let ((b (current-buffer)) (p (point)))
11928 ;; Restore the window configuration because we just use the web link
11929 (set-window-configuration org-window-config-before-follow-link)
11930 (save-excursion (set-buffer b) (goto-char p)
11931 (bibtex-url)))
11932 (recenter 0)) ; Move entry start to beginning of window
11933 ;; return t to indicate that the search is done.
11936 ;; Finally add the functions to the right hooks.
11937 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
11938 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
11940 ;; end of Bibtex link setup
11942 ;;; Following file links
11944 (defun org-open-file (path &optional in-emacs line search)
11945 "Open the file at PATH.
11946 First, this expands any special file name abbreviations. Then the
11947 configuration variable `org-file-apps' is checked if it contains an
11948 entry for this file type, and if yes, the corresponding command is launched.
11949 If no application is found, Emacs simply visits the file.
11950 With optional argument IN-EMACS, Emacs will visit the file.
11951 Optional LINE specifies a line to go to, optional SEARCH a string to
11952 search for. If LINE or SEARCH is given, the file will always be
11953 opened in Emacs.
11954 If the file does not exist, an error is thrown."
11955 (setq in-emacs (or in-emacs line search))
11956 (let* ((file (if (equal path "")
11957 buffer-file-name
11958 (substitute-in-file-name (expand-file-name path))))
11959 (apps (append org-file-apps (org-default-apps)))
11960 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11961 (dirp (if remp nil (file-directory-p file)))
11962 (dfile (downcase file))
11963 (old-buffer (current-buffer))
11964 (old-pos (point))
11965 (old-mode major-mode)
11966 ext cmd)
11967 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11968 (setq ext (match-string 1 dfile))
11969 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11970 (setq ext (match-string 1 dfile))))
11971 (if in-emacs
11972 (setq cmd 'emacs)
11973 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11974 (and dirp (cdr (assoc 'directory apps)))
11975 (cdr (assoc ext apps))
11976 (cdr (assoc t apps)))))
11977 (when (eq cmd 'mailcap)
11978 (require 'mailcap)
11979 (mailcap-parse-mailcaps)
11980 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11981 (command (mailcap-mime-info mime-type)))
11982 (if (stringp command)
11983 (setq cmd command)
11984 (setq cmd 'emacs))))
11985 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11986 (not (file-exists-p file))
11987 (not org-open-non-existing-files))
11988 (error "No such file: %s" file))
11989 (cond
11990 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11991 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11992 (if (string-match "['\"]%s['\"]" cmd)
11993 (setq cmd (replace-match "%s" t t cmd)))
11994 (setq cmd (format cmd (shell-quote-argument file)))
11995 (save-window-excursion
11996 (shell-command (concat cmd " &"))))
11997 ((or (stringp cmd)
11998 (eq cmd 'emacs))
11999 (funcall (cdr (assq 'file org-link-frame-setup)) file)
12000 (widen)
12001 (if line (goto-line line)
12002 (if search (org-link-search search))))
12003 ((consp cmd)
12004 (eval cmd))
12005 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
12006 (and (org-mode-p) (eq old-mode 'org-mode)
12007 (or (not (equal old-buffer (current-buffer)))
12008 (not (equal old-pos (point))))
12009 (org-mark-ring-push old-pos old-buffer))))
12011 (defun org-default-apps ()
12012 "Return the default applications for this operating system."
12013 (cond
12014 ((eq system-type 'darwin)
12015 org-file-apps-defaults-macosx)
12016 ((eq system-type 'windows-nt)
12017 org-file-apps-defaults-windowsnt)
12018 (t org-file-apps-defaults-gnu)))
12020 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
12021 (defun org-file-remote-p (file)
12022 "Test whether FILE specifies a location on a remote system.
12023 Return non-nil if the location is indeed remote.
12025 For example, the filename \"/user@host:/foo\" specifies a location
12026 on the system \"/user@host:\"."
12027 (cond ((fboundp 'file-remote-p)
12028 (file-remote-p file))
12029 ((fboundp 'tramp-handle-file-remote-p)
12030 (tramp-handle-file-remote-p file))
12031 ((and (boundp 'ange-ftp-name-format)
12032 (string-match (car ange-ftp-name-format) file))
12034 (t nil)))
12037 ;;;; Hooks for remember.el
12039 ;;;###autoload
12040 (defun org-remember-annotation ()
12041 "Return a link to the current location as an annotation for remember.el.
12042 If you are using Org-mode files as target for data storage with
12043 remember.el, then the annotations should include a link compatible with the
12044 conventions in Org-mode. This function returns such a link."
12045 (org-store-link nil))
12047 (defconst org-remember-help
12048 "Select a destination location for the note.
12049 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
12050 RET at beg-of-buf -> Append to file as level 2 headline
12051 RET on headline -> Store as sublevel entry to current headline
12052 <left>/<right> -> before/after current headline, same headings level")
12054 ;;;###autoload
12055 (defun org-remember-apply-template (&optional use-char skip-interactive)
12056 "Initialize *remember* buffer with template, invoke `org-mode'.
12057 This function should be placed into `remember-mode-hook' and in fact requires
12058 to be run from that hook to fucntion properly."
12059 (if org-remember-templates
12061 (let* ((char (or use-char
12062 (if (= (length org-remember-templates) 1)
12063 (caar org-remember-templates)
12064 (message "Select template: %s"
12065 (mapconcat
12066 (lambda (x) (char-to-string (car x)))
12067 org-remember-templates " "))
12068 (read-char-exclusive))))
12069 (entry (cdr (assoc char org-remember-templates)))
12070 (tpl (car entry))
12071 (plist-p (if org-store-link-plist t nil))
12072 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
12073 (string-match "\\S-" (nth 1 entry)))
12074 (nth 1 entry)
12075 org-default-notes-file))
12076 (headline (nth 2 entry))
12077 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
12078 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
12079 (v-u (concat "[" (substring v-t 1 -1) "]"))
12080 (v-U (concat "[" (substring v-T 1 -1) "]"))
12081 (v-i initial) ; defined in `remember-mode'
12082 (v-a (if (equal annotation "[[]]") "" annotation)) ; likewise
12083 (v-n user-full-name)
12084 (org-startup-folded nil)
12085 org-time-was-given org-end-time-was-given x prompt char time)
12086 (setq org-store-link-plist
12087 (append (list :annotation v-a :initial v-i)
12088 org-store-link-plist))
12089 (unless tpl (setq tpl "") (message "No template") (ding))
12090 (erase-buffer)
12091 (insert (substitute-command-keys
12092 (format
12093 "## `C-c C-c' to file interactively, `C-u C-c C-c' to file directly.
12094 ## Target file \"%s\", headline \"%s\"
12095 ## To switch templates, use `\\[org-remember]'.\n\n"
12096 (abbreviate-file-name (or file org-default-notes-file))
12097 (or headline ""))))
12098 (insert tpl) (goto-char (point-min))
12099 ;; Simple %-escapes
12100 (while (re-search-forward "%\\([tTuUai]\\)" nil t)
12101 (when (and initial (equal (match-string 0) "%i"))
12102 (save-match-data
12103 (let* ((lead (buffer-substring
12104 (point-at-bol) (match-beginning 0))))
12105 (setq v-i (mapconcat 'identity
12106 (org-split-string initial "\n")
12107 (concat "\n" lead))))))
12108 (replace-match
12109 (or (eval (intern (concat "v-" (match-string 1)))) "")
12110 t t))
12111 ;; From the property list
12112 (when plist-p
12113 (goto-char (point-min))
12114 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
12115 (and (setq x (plist-get org-store-link-plist
12116 (intern (match-string 1))))
12117 (replace-match x t t))))
12118 ;; Turn on org-mode in the remember buffer, set local variables
12119 (org-mode)
12120 (org-set-local 'org-finish-function 'remember-buffer)
12121 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
12122 (org-set-local 'org-default-notes-file file))
12123 (if (and headline (stringp headline) (string-match "\\S-" headline))
12124 (org-set-local 'org-remember-default-headline headline))
12125 ;; Interactive template entries
12126 (goto-char (point-min))
12127 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
12128 (setq char (if (match-end 3) (match-string 3))
12129 prompt (if (match-end 2) (match-string 2)))
12130 (goto-char (match-beginning 0))
12131 (replace-match "")
12132 (cond
12133 ((member char '("G" "g"))
12134 (let* ((org-last-tags-completion-table
12135 (org-global-tags-completion-table
12136 (if (equal char "G") (org-agenda-files) (and file (list file)))))
12137 (org-add-colon-after-tag-completion t)
12138 (ins (completing-read
12139 (if prompt (concat prompt ": ") "Tags: ")
12140 'org-tags-completion-function nil nil nil
12141 'org-tags-history)))
12142 (setq ins (mapconcat 'identity
12143 (org-split-string ins (org-re "[^[:alnum:]]+"))
12144 ":"))
12145 (when (string-match "\\S-" ins)
12146 (or (equal (char-before) ?:) (insert ":"))
12147 (insert ins)
12148 (or (equal (char-after) ?:) (insert ":")))))
12149 (char
12150 (setq org-time-was-given (equal (upcase char) char))
12151 (setq time (org-read-date (equal (upcase char) "U") t nil
12152 prompt))
12153 (org-insert-time-stamp time org-time-was-given
12154 (member char '("u" "U"))
12155 nil nil (list org-end-time-was-given)))
12157 (insert (read-string
12158 (if prompt (concat prompt ": ") "Enter string"))))))
12159 (goto-char (point-min))
12160 (if (re-search-forward "%\\?" nil t)
12161 (replace-match "")
12162 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
12163 (org-mode)
12164 (org-set-local 'org-finish-function 'remember-buffer)))
12166 ;;;###autoload
12167 (defun org-remember ()
12168 "Call `remember'. If this is already a remember buffer, re-apply template.
12169 If there is an active region, make sure remember uses it as initial content
12170 of the remember buffer."
12171 (interactive)
12172 (if (eq org-finish-function 'remember-buffer)
12173 (progn
12174 (when (< (length org-remember-templates) 2)
12175 (error "No other template available"))
12176 (erase-buffer)
12177 (let ((annotation (plist-get org-store-link-plist :annotation))
12178 (initial (plist-get org-store-link-plist :initial)))
12179 (org-remember-apply-template))
12180 (message "Press C-c C-c to remember data"))
12181 (if (org-region-active-p)
12182 (remember (buffer-substring (point) (mark)))
12183 (call-interactively 'remember))))
12185 ;;;###autoload
12186 (defun org-remember-handler ()
12187 "Store stuff from remember.el into an org file.
12188 First prompts for an org file. If the user just presses return, the value
12189 of `org-default-notes-file' is used.
12190 Then the command offers the headings tree of the selected file in order to
12191 file the text at a specific location.
12192 You can either immediately press RET to get the note appended to the
12193 file, or you can use vertical cursor motion and visibility cycling (TAB) to
12194 find a better place. Then press RET or <left> or <right> in insert the note.
12196 Key Cursor position Note gets inserted
12197 -----------------------------------------------------------------------------
12198 RET buffer-start as level 2 heading at end of file
12199 RET on headline as sublevel of the heading at cursor
12200 RET no heading at cursor position, level taken from context.
12201 Or use prefix arg to specify level manually.
12202 <left> on headline as same level, before current heading
12203 <right> on headline as same level, after current heading
12205 So the fastest way to store the note is to press RET RET to append it to
12206 the default file. This way your current train of thought is not
12207 interrupted, in accordance with the principles of remember.el.
12208 You can also get the fast execution without prompting by using
12209 C-u C-c C-c to exit the remember buffer. See also the variable
12210 `org-remember-store-without-prompt'.
12212 Before being stored away, the function ensures that the text has a
12213 headline, i.e. a first line that starts with a \"*\". If not, a headline
12214 is constructed from the current date and some additional data.
12216 If the variable `org-adapt-indentation' is non-nil, the entire text is
12217 also indented so that it starts in the same column as the headline
12218 \(i.e. after the stars).
12220 See also the variable `org-reverse-note-order'."
12221 (goto-char (point-min))
12222 (while (looking-at "^[ \t]*\n\\|^##.*\n")
12223 (replace-match ""))
12224 (catch 'quit
12225 (let* ((txt (buffer-substring (point-min) (point-max)))
12226 (fastp (org-xor (equal current-prefix-arg '(4))
12227 org-remember-store-without-prompt))
12228 (file (if fastp org-default-notes-file (org-get-org-file)))
12229 (heading org-remember-default-headline)
12230 (visiting (org-find-base-buffer-visiting file))
12231 (org-startup-folded nil)
12232 (org-startup-align-all-tables nil)
12233 (org-goto-start-pos 1)
12234 spos level indent reversed)
12235 (setq current-prefix-arg nil)
12236 ;; Modify text so that it becomes a nice subtree which can be inserted
12237 ;; into an org tree.
12238 (let* ((lines (split-string txt "\n"))
12239 first)
12240 (setq first (car lines) lines (cdr lines))
12241 (if (string-match "^\\*+ " first)
12242 ;; Is already a headline
12243 (setq indent nil)
12244 ;; We need to add a headline: Use time and first buffer line
12245 (setq lines (cons first lines)
12246 first (concat "* " (current-time-string)
12247 " (" (remember-buffer-desc) ")")
12248 indent " "))
12249 (if (and org-adapt-indentation indent)
12250 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
12251 (setq txt (concat first "\n"
12252 (mapconcat 'identity lines "\n"))))
12253 ;; Find the file
12254 (if (not visiting) (find-file-noselect file))
12255 (with-current-buffer (or visiting (get-file-buffer file))
12256 (save-excursion
12257 (save-restriction
12258 (widen)
12259 (and (goto-char (point-min))
12260 (not (re-search-forward "^\\* " nil t))
12261 (insert "\n* Notes\n"))
12262 (setq reversed (org-notes-order-reversed-p))
12264 ;; Find the default location
12265 (when (and heading (stringp heading) (string-match "\\S-" heading))
12266 (goto-char (point-min))
12267 (if (re-search-forward
12268 (concat "^\\*+[ \t]+" (regexp-quote heading)
12269 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
12270 nil t)
12271 (setq org-goto-start-pos (match-beginning 0))))
12273 ;; Ask the User for a location
12274 (setq spos (if fastp
12275 org-goto-start-pos
12276 (org-get-location (current-buffer) org-remember-help)))
12277 (if (not spos) (throw 'quit nil)) ; return nil to show we did
12278 ; not handle this note
12279 (goto-char spos)
12280 (cond ((and (bobp) (not reversed))
12281 ;; Put it at the end, one level below level 1
12282 (save-restriction
12283 (widen)
12284 (goto-char (point-max))
12285 (if (not (bolp)) (newline))
12286 (org-paste-subtree (org-get-legal-level 1 1) txt)))
12287 ((and (bobp) reversed)
12288 ;; Put it at the start, as level 1
12289 (save-restriction
12290 (widen)
12291 (goto-char (point-min))
12292 (re-search-forward "^\\*+ " nil t)
12293 (beginning-of-line 1)
12294 (org-paste-subtree 1 txt)))
12295 ((and (org-on-heading-p t) (not current-prefix-arg))
12296 ;; Put it below this entry, at the beg/end of the subtree
12297 (org-back-to-heading t)
12298 (setq level (funcall outline-level))
12299 (if reversed
12300 (outline-next-heading)
12301 (org-end-of-subtree t))
12302 (if (not (bolp)) (newline))
12303 (beginning-of-line 1)
12304 (org-paste-subtree (org-get-legal-level level 1) txt))
12306 ;; Put it right there, with automatic level determined by
12307 ;; org-paste-subtree or from prefix arg
12308 (org-paste-subtree
12309 (if (numberp current-prefix-arg) current-prefix-arg)
12310 txt)))
12311 (when remember-save-after-remembering
12312 (save-buffer)
12313 (if (not visiting) (kill-buffer (current-buffer)))))))))
12314 t) ;; return t to indicate that we took care of this note.
12316 (defun org-get-org-file ()
12317 "Read a filename, with default directory `org-directory'."
12318 (let ((default (or org-default-notes-file remember-data-file)))
12319 (read-file-name (format "File name [%s]: " default)
12320 (file-name-as-directory org-directory)
12321 default)))
12323 (defun org-notes-order-reversed-p ()
12324 "Check if the current file should receive notes in reversed order."
12325 (cond
12326 ((not org-reverse-note-order) nil)
12327 ((eq t org-reverse-note-order) t)
12328 ((not (listp org-reverse-note-order)) nil)
12329 (t (catch 'exit
12330 (let ((all org-reverse-note-order)
12331 entry)
12332 (while (setq entry (pop all))
12333 (if (string-match (car entry) buffer-file-name)
12334 (throw 'exit (cdr entry))))
12335 nil)))))
12337 ;;;; Dynamic blocks
12339 (defun org-find-dblock (name)
12340 "Find the first dynamic block with name NAME in the buffer.
12341 If not found, stay at current position and return nil."
12342 (let (pos)
12343 (save-excursion
12344 (goto-char (point-min))
12345 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
12346 nil t)
12347 (match-beginning 0))))
12348 (if pos (goto-char pos))
12349 pos))
12351 (defconst org-dblock-start-re
12352 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
12353 "Matches the startline of a dynamic block, with parameters.")
12355 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
12356 "Matches the end of a dyhamic block.")
12358 (defun org-create-dblock (plist)
12359 "Create a dynamic block section, with parameters taken from PLIST.
12360 PLIST must containe a :name entry which is used as name of the block."
12361 (unless (bolp) (newline))
12362 (let ((name (plist-get plist :name)))
12363 (insert "#+BEGIN: " name)
12364 (while plist
12365 (if (eq (car plist) :name)
12366 (setq plist (cddr plist))
12367 (insert " " (prin1-to-string (pop plist)))))
12368 (insert "\n\n#+END:\n")
12369 (beginning-of-line -2)))
12371 (defun org-prepare-dblock ()
12372 "Prepare dynamic block for refresh.
12373 This empties the block, puts the cursor at the insert position and returns
12374 the property list including an extra property :name with the block name."
12375 (unless (looking-at org-dblock-start-re)
12376 (error "Not at a dynamic block"))
12377 (let* ((begdel (1+ (match-end 0)))
12378 (name (match-string 1))
12379 (params (append (list :name name)
12380 (read (concat "(" (match-string 3) ")")))))
12381 (unless (re-search-forward org-dblock-end-re nil t)
12382 (error "Dynamic block not terminated"))
12383 (delete-region begdel (match-beginning 0))
12384 (goto-char begdel)
12385 (open-line 1)
12386 params))
12388 (defun org-map-dblocks (&optional command)
12389 "Apply COMMAND to all dynamic blocks in the current buffer.
12390 If COMMAND is not given, use `org-update-dblock'."
12391 (let ((cmd (or command 'org-update-dblock))
12392 pos)
12393 (save-excursion
12394 (goto-char (point-min))
12395 (while (re-search-forward org-dblock-start-re nil t)
12396 (goto-char (setq pos (match-beginning 0)))
12397 (condition-case nil
12398 (funcall cmd)
12399 (error (message "Error during update of dynamic block")))
12400 (goto-char pos)
12401 (unless (re-search-forward org-dblock-end-re nil t)
12402 (error "Dynamic block not terminated"))))))
12404 (defun org-dblock-update (&optional arg)
12405 "User command for updating dynamic blocks.
12406 Update the dynamic block at point. With prefix ARG, update all dynamic
12407 blocks in the buffer."
12408 (interactive "P")
12409 (if arg
12410 (org-update-all-dblocks)
12411 (or (looking-at org-dblock-start-re)
12412 (org-beginning-of-dblock))
12413 (org-update-dblock)))
12415 (defun org-update-dblock ()
12416 "Update the dynamic block at point
12417 This means to empty the block, parse for parameters and then call
12418 the correct writing function."
12419 (let* ((pos (point))
12420 (params (org-prepare-dblock))
12421 (name (plist-get params :name))
12422 (cmd (intern (concat "org-dblock-write:" name))))
12423 (funcall cmd params)
12424 (goto-char pos)))
12426 (defun org-beginning-of-dblock ()
12427 "Find the beginning of the dynamic block at point.
12428 Error if there is no scuh block at point."
12429 (let ((pos (point))
12430 beg)
12431 (end-of-line 1)
12432 (if (and (re-search-backward org-dblock-start-re nil t)
12433 (setq beg (match-beginning 0))
12434 (re-search-forward org-dblock-end-re nil t)
12435 (> (match-end 0) pos))
12436 (goto-char beg)
12437 (goto-char pos)
12438 (error "Not in a dynamic block"))))
12440 (defun org-update-all-dblocks ()
12441 "Update all dynamic blocks in the buffer.
12442 This function can be used in a hook."
12443 (when (org-mode-p)
12444 (org-map-dblocks 'org-update-dblock)))
12447 ;;;; Completion
12449 (defun org-complete (&optional arg)
12450 "Perform completion on word at point.
12451 At the beginning of a headline, this completes TODO keywords as given in
12452 `org-todo-keywords'.
12453 If the current word is preceded by a backslash, completes the TeX symbols
12454 that are supported for HTML support.
12455 If the current word is preceded by \"#+\", completes special words for
12456 setting file options.
12457 In the line after \"#+STARTUP:, complete valid keywords.\"
12458 At all other locations, this simply calls `ispell-complete-word'."
12459 (interactive "P")
12460 (catch 'exit
12461 (let* ((end (point))
12462 (beg1 (save-excursion
12463 (skip-chars-backward (org-re "[:alnum:]_@"))
12464 (point)))
12465 (beg (save-excursion
12466 (skip-chars-backward "a-zA-Z0-9_:$")
12467 (point)))
12468 (confirm (lambda (x) (stringp (car x))))
12469 (searchhead (equal (char-before beg) ?*))
12470 (tag (and (equal (char-before beg1) ?:)
12471 (equal (char-after (point-at-bol)) ?*)))
12472 (prop (and (equal (char-before beg1) ?:)
12473 (not (equal (char-after (point-at-bol)) ?*))))
12474 (texp (equal (char-before beg) ?\\))
12475 (link (equal (char-before beg) ?\[))
12476 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
12477 beg)
12478 "#+"))
12479 (startup (string-match "^#\\+STARTUP:.*"
12480 (buffer-substring (point-at-bol) (point))))
12481 (completion-ignore-case opt)
12482 (type nil)
12483 (tbl nil)
12484 (table (cond
12485 (opt
12486 (setq type :opt)
12487 (mapcar (lambda (x)
12488 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
12489 (cons (match-string 2 x) (match-string 1 x)))
12490 (org-split-string (org-get-current-options) "\n")))
12491 (startup
12492 (setq type :startup)
12493 org-startup-options)
12494 (link (append org-link-abbrev-alist-local
12495 org-link-abbrev-alist))
12496 (texp
12497 (setq type :tex)
12498 org-html-entities)
12499 ((string-match "\\`\\*+[ \t]+\\'"
12500 (buffer-substring (point-at-bol) beg))
12501 (setq type :todo)
12502 (mapcar 'list org-todo-keywords-1))
12503 (searchhead
12504 (setq type :searchhead)
12505 (save-excursion
12506 (goto-char (point-min))
12507 (while (re-search-forward org-todo-line-regexp nil t)
12508 (push (list
12509 (org-make-org-heading-search-string
12510 (match-string 3) t))
12511 tbl)))
12512 tbl)
12513 (tag (setq type :tag beg beg1)
12514 (or org-tag-alist (org-get-buffer-tags)))
12515 (prop (setq type :prop beg beg1)
12516 (mapcar 'list (org-buffer-property-keys)))
12517 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
12518 (pattern (buffer-substring-no-properties beg end))
12519 (completion (try-completion pattern table confirm)))
12520 (cond ((eq completion t)
12521 (if (equal type :opt)
12522 (insert (substring (cdr (assoc (upcase pattern) table))
12523 (length pattern)))
12524 (if (memq type '(:tag :prop)) (insert ":"))))
12525 ((null completion)
12526 (message "Can't find completion for \"%s\"" pattern)
12527 (ding))
12528 ((not (string= pattern completion))
12529 (delete-region beg end)
12530 (if (string-match " +$" completion)
12531 (setq completion (replace-match "" t t completion)))
12532 (insert completion)
12533 (if (get-buffer-window "*Completions*")
12534 (delete-window (get-buffer-window "*Completions*")))
12535 (if (assoc completion table)
12536 (if (eq type :todo) (insert " ")
12537 (if (memq type '(:tag :prop)) (insert ":"))))
12538 (if (and (equal type :opt) (assoc completion table))
12539 (message "%s" (substitute-command-keys
12540 "Press \\[org-complete] again to insert example settings"))))
12542 (message "Making completion list...")
12543 (let ((list (sort (all-completions pattern table confirm)
12544 'string<)))
12545 (with-output-to-temp-buffer "*Completions*"
12546 (condition-case nil
12547 ;; Protection needed for XEmacs and emacs 21
12548 (display-completion-list list pattern)
12549 (error (display-completion-list list)))))
12550 (message "Making completion list...%s" "done"))))))
12552 ;;;; TODO, DEADLINE, Comments
12554 (defun org-toggle-comment ()
12555 "Change the COMMENT state of an entry."
12556 (interactive)
12557 (save-excursion
12558 (org-back-to-heading)
12559 (if (looking-at (concat outline-regexp
12560 "\\( *\\<" org-comment-string "\\>\\)"))
12561 (replace-match "" t t nil 1)
12562 (if (looking-at outline-regexp)
12563 (progn
12564 (goto-char (match-end 0))
12565 (insert org-comment-string " "))))))
12567 (defvar org-last-todo-state-is-todo nil
12568 "This is non-nil when the last TODO state change led to a TODO state.
12569 If the last change removed the TODO tag or switched to DONE, then
12570 this is nil.")
12572 (defun org-todo (&optional arg)
12573 "Change the TODO state of an item.
12574 The state of an item is given by a keyword at the start of the heading,
12575 like
12576 *** TODO Write paper
12577 *** DONE Call mom
12579 The different keywords are specified in the variable `org-todo-keywords'.
12580 By default the available states are \"TODO\" and \"DONE\".
12581 So for this example: when the item starts with TODO, it is changed to DONE.
12582 When it starts with DONE, the DONE is removed. And when neither TODO nor
12583 DONE are present, add TODO at the beginning of the heading.
12585 With C-u prefix arg, use completion to determine the new state.
12586 With numeric prefix arg, switch to that state.
12588 For calling through lisp, arg is also interpreted in the following way:
12589 'none -> empty state
12590 \"\"(empty string) -> switch to empty state
12591 'done -> switch to DONE
12592 'nextset -> switch to the next set of keywords
12593 'previousset -> switch to the previous set of keywords
12594 \"WAITING\" -> switch to the specified keyword, but only if it
12595 really is a member of `org-todo-keywords'."
12596 (interactive "P")
12597 (save-excursion
12598 (org-back-to-heading)
12599 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
12600 (or (looking-at (concat " +" org-todo-regexp " *"))
12601 (looking-at " *"))
12602 (let* ((this (match-string 1))
12603 (head (org-get-todo-sequence-head this))
12604 (ass (assoc head org-todo-kwd-alist))
12605 (interpret (nth 1 ass))
12606 (done-word (nth 3 ass))
12607 (final-done-word (nth 4 ass))
12608 (last-state (or this ""))
12609 (completion-ignore-case t)
12610 (member (member this org-todo-keywords-1))
12611 (tail (cdr member))
12612 (state (cond
12613 ((equal arg '(4))
12614 ;; Read a state with completion
12615 (completing-read "State: " (mapcar (lambda(x) (list x))
12616 org-todo-keywords-1)
12617 nil t))
12618 ((eq arg 'right)
12619 (if this
12620 (if tail (car tail) nil)
12621 (car org-todo-keywords-1)))
12622 ((eq arg 'left)
12623 (if (equal member org-todo-keywords-1)
12625 (if this
12626 (nth (- (length org-todo-keywords-1) (length tail) 2)
12627 org-todo-keywords-1)
12628 (org-last org-todo-keywords-1))))
12629 (arg
12630 ;; user or caller requests a specific state
12631 (cond
12632 ((equal arg "") nil)
12633 ((eq arg 'none) nil)
12634 ((eq arg 'done) (or done-word (car org-done-keywords)))
12635 ((eq arg 'nextset)
12636 (or (car (cdr (member head org-todo-heads)))
12637 (car org-todo-heads)))
12638 ((eq arg 'previousset)
12639 (let ((org-todo-heads (reverse org-todo-heads)))
12640 (or (car (cdr (member head org-todo-heads)))
12641 (car org-todo-heads))))
12642 ((car (member arg org-todo-keywords-1)))
12643 ((nth (1- (prefix-numeric-value arg))
12644 org-todo-keywords-1))))
12645 ((null member) (or head (car org-todo-keywords-1)))
12646 ((equal this final-done-word) nil) ;; -> make empty
12647 ((null tail) nil) ;; -> first entry
12648 ((eq interpret 'sequence)
12649 (car tail))
12650 ((memq interpret '(type priority))
12651 (if (eq this-command last-command)
12652 (car tail)
12653 (if (> (length tail) 0)
12654 (or done-word (car org-done-keywords))
12655 nil)))
12656 (t nil)))
12657 (next (if state (concat " " state " ") " "))
12658 dostates)
12659 (replace-match next t t)
12660 (unless head
12661 (setq head (org-get-todo-sequence-head state)
12662 ass (assoc head org-todo-kwd-alist)
12663 interpret (nth 1 ass)
12664 done-word (nth 3 ass)
12665 final-done-word (nth 4 ass)))
12666 (when (memq arg '(nextset previousset))
12667 (message "Keyword-Set %d/%d: %s"
12668 (- (length org-todo-sets) -1
12669 (length (memq (assoc state org-todo-sets) org-todo-sets)))
12670 (length org-todo-sets)
12671 (mapconcat 'identity (assoc state org-todo-sets) " ")))
12672 (setq org-last-todo-state-is-todo
12673 (not (member state org-done-keywords)))
12674 (when (and org-log-done (not (memq arg '(nextset previousset))))
12675 (setq dostates (and (eq interpret 'sequence)
12676 (listp org-log-done) (memq 'state org-log-done)))
12677 (cond
12678 ((and state (not this))
12679 ;; FIXME: should we remove CLOSED already then state is nil?
12680 (org-add-planning-info nil nil 'closed)
12681 (and dostates (org-add-log-maybe 'state state 'findpos)))
12682 ((and state dostates)
12683 (org-add-log-maybe 'state state 'findpos))
12684 ((member state org-done-keywords)
12685 ;; Planning info calls the note-setting command.
12686 (org-add-planning-info 'closed (org-current-time)
12687 (if (org-get-repeat) nil 'scheduled))
12688 (org-add-log-maybe 'done state 'findpos))))
12689 ;; Fixup tag positioning
12690 (and org-auto-align-tags (org-set-tags nil t))
12691 (run-hooks 'org-after-todo-state-change-hook)
12692 (and (member state org-done-keywords) (org-auto-repeat-maybe))
12693 (if (and arg (not (member state org-done-keywords)))
12694 (setq head (org-get-todo-sequence-head state)))
12695 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)))
12696 ;; Fixup cursor location if close to the keyword
12697 (if (and (outline-on-heading-p)
12698 (not (bolp))
12699 (save-excursion (beginning-of-line 1)
12700 (looking-at org-todo-line-regexp))
12701 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12702 (progn
12703 (goto-char (or (match-end 2) (match-end 1)))
12704 (just-one-space))))
12706 (defun org-get-todo-sequence-head (kwd)
12707 "Return the head of the TODO sequence to which KWD belongs.
12708 If KWD is not set, check if there is a text property remembering the
12709 right sequence."
12710 (let (p)
12711 (cond
12712 ((not kwd)
12713 (or (get-text-property (point-at-bol) 'org-todo-head)
12714 (progn
12715 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12716 nil (point-at-eol)))
12717 (get-text-property p 'org-todo-head))))
12718 ((not (member kwd org-todo-keywords-1))
12719 (car org-todo-keywords-1))
12720 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12722 (defun org-get-repeat ()
12723 "Check if tere is a deadline/schedule with repeater in this entry."
12724 (save-match-data
12725 (save-excursion
12726 (org-back-to-heading t)
12727 (if (re-search-forward
12728 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
12729 (match-string 1)))))
12731 (defvar org-last-changed-timestamp)
12732 (defvar org-log-post-message)
12733 (defun org-auto-repeat-maybe ()
12734 "Check if the current headline contains a repeated deadline/schedule.
12735 If yes, set TODO state back to what it was and change the base date
12736 of repeating deadline/scheduled time stamps to new date.
12737 This function should be run in the `org-after-todo-state-change-hook'."
12738 ;; last-state is dynamically scoped into this function
12739 (let* ((repeat (org-get-repeat))
12740 (aa (assoc last-state org-todo-kwd-alist))
12741 (interpret (nth 1 aa))
12742 (head (nth 2 aa))
12743 (done-word (nth 3 aa))
12744 (whata '(("d" . day) ("m" . month) ("y" . year)))
12745 (msg "Entry repeats: ")
12746 (org-log-done)
12747 re type n what ts)
12748 (when repeat
12749 (org-todo (if (eq interpret 'type) last-state head))
12750 (when (and org-log-repeat
12751 (not (memq 'org-add-log-note
12752 (default-value 'post-command-hook))))
12753 ;; Make sure a note is taken
12754 (let ((org-log-done '(done)))
12755 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
12756 'findpos)))
12757 (org-back-to-heading t)
12758 (org-add-planning-info nil nil 'closed)
12759 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12760 org-deadline-time-regexp "\\)"))
12761 (while (re-search-forward
12762 re (save-excursion (outline-next-heading) (point)) t)
12763 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
12764 ts (match-string (if (match-end 2) 2 4)))
12765 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
12766 (setq n (string-to-number (match-string 1 ts))
12767 what (match-string 2 ts))
12768 (if (equal what "w") (setq n (* n 7) what "d"))
12769 (org-timestamp-change n (cdr (assoc what whata))))
12770 (setq msg (concat msg type org-last-changed-timestamp " ")))
12771 (setq org-log-post-message msg)
12772 (message msg))))
12774 (defun org-show-todo-tree (arg)
12775 "Make a compact tree which shows all headlines marked with TODO.
12776 The tree will show the lines where the regexp matches, and all higher
12777 headlines above the match.
12778 With \\[universal-argument] prefix, also show the DONE entries.
12779 With a numeric prefix N, construct a sparse tree for the Nth element
12780 of `org-todo-keywords-1'."
12781 (interactive "P")
12782 (let ((case-fold-search nil)
12783 (kwd-re
12784 (cond ((null arg) org-not-done-regexp)
12785 ((equal arg '(4))
12786 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
12787 (mapcar 'list org-todo-keywords-1))))
12788 (concat "\\("
12789 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12790 "\\)\\>")))
12791 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12792 (regexp-quote (nth (1- (prefix-numeric-value arg))
12793 org-todo-keywords-1)))
12794 (t (error "Invalid prefix argument: %s" arg)))))
12795 (message "%d TODO entries found"
12796 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
12798 (defun org-deadline ()
12799 "Insert the DEADLINE: string to make a deadline.
12800 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
12801 to modify it to the correct date."
12802 (interactive)
12803 (org-add-planning-info 'deadline nil 'closed))
12805 (defun org-schedule ()
12806 "Insert the SCHEDULED: string to schedule a TODO item.
12807 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
12808 to modify it to the correct date."
12809 (interactive)
12810 (org-add-planning-info 'scheduled nil 'closed))
12812 (defun org-add-planning-info (what &optional time &rest remove)
12813 "Insert new timestamp with keyword in the line directly after the headline.
12814 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
12815 If non is given, the user is prompted for a date.
12816 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12817 be removed."
12818 (interactive)
12819 (let (org-time-was-given org-end-time-was-given)
12820 (when what (setq time (or time (org-read-date nil 'to-time))))
12821 (when (and org-insert-labeled-timestamps-at-point
12822 (member what '(scheduled deadline)))
12823 (insert
12824 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12825 (org-insert-time-stamp time org-time-was-given
12826 nil nil nil (list org-end-time-was-given))
12827 (setq what nil))
12828 (save-excursion
12829 (save-restriction
12830 (let (col list elt ts buffer-invisibility-spec)
12831 (org-back-to-heading t)
12832 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
12833 (goto-char (match-end 1))
12834 (setq col (current-column))
12835 (goto-char (match-end 0))
12836 (if (eobp) (insert "\n"))
12837 (forward-char 1)
12838 (when (and (not org-insert-labeled-timestamps-before-properties-drawer)
12839 (looking-at "[ \t]*:PROPERTIES:[ \t]*$"))
12840 (goto-char (match-end 0))
12841 (if (eobp) (insert "\n"))
12842 (forward-char 1))
12843 (if (and (not (looking-at outline-regexp))
12844 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12845 "[^\r\n]*"))
12846 (not (equal (match-string 1) org-clock-string)))
12847 (narrow-to-region (match-beginning 0) (match-end 0))
12848 (insert-before-markers "\n")
12849 (backward-char 1)
12850 (narrow-to-region (point) (point))
12851 (indent-to-column col))
12852 ;; Check if we have to remove something.
12853 (setq list (cons what remove))
12854 (while list
12855 (setq elt (pop list))
12856 (goto-char (point-min))
12857 (when (or (and (eq elt 'scheduled)
12858 (re-search-forward org-scheduled-time-regexp nil t))
12859 (and (eq elt 'deadline)
12860 (re-search-forward org-deadline-time-regexp nil t))
12861 (and (eq elt 'closed)
12862 (re-search-forward org-closed-time-regexp nil t)))
12863 (replace-match "")
12864 (if (looking-at "--+<[^>]+>") (replace-match ""))
12865 (if (looking-at " +") (replace-match ""))))
12866 (goto-char (point-max))
12867 (when what
12868 (insert
12869 (if (not (equal (char-before) ?\ )) " " "")
12870 (cond ((eq what 'scheduled) org-scheduled-string)
12871 ((eq what 'deadline) org-deadline-string)
12872 ((eq what 'closed) org-closed-string)
12873 ((eq what 'archived) org-archived-string))
12874 " ")
12875 (org-insert-time-stamp
12876 time
12877 (or org-time-was-given
12878 (and (eq what 'closed) org-log-done-with-time))
12879 (eq what 'closed)
12880 nil nil (list org-end-time-was-given))
12881 (end-of-line 1))
12882 (goto-char (point-min))
12883 (widen)
12884 (if (looking-at "[ \t]+\r?\n")
12885 (replace-match ""))
12886 ts)))))
12888 (defvar org-log-note-marker (make-marker))
12889 (defvar org-log-note-purpose nil)
12890 (defvar org-log-note-state nil)
12891 (defvar org-log-note-window-configuration nil)
12892 (defvar org-log-note-return-to (make-marker))
12893 (defvar org-log-post-message nil
12894 "Message to be displayed after a log note has been stored.
12895 The auto-repeater uses this.")
12897 (defun org-add-log-maybe (&optional purpose state findpos)
12898 "Set up the post command hook to take a note."
12899 (save-excursion
12900 (when (and (listp org-log-done)
12901 (memq purpose org-log-done))
12902 (when findpos
12903 (org-back-to-heading t)
12904 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
12905 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12906 "[^\r\n]*\\)?"))
12907 (goto-char (match-end 0))
12908 (unless org-log-states-order-reversed
12909 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12910 (while (looking-at "[ \t]*- State")
12911 (condition-case nil
12912 (org-next-item)
12913 (error (org-end-of-item))))
12914 (skip-chars-backward " \t\n\r")))
12915 (move-marker org-log-note-marker (point))
12916 (setq org-log-note-purpose purpose)
12917 (setq org-log-note-state state)
12918 (add-hook 'post-command-hook 'org-add-log-note 'append))))
12920 (defun org-add-log-note (&optional purpose)
12921 "Pop up a window for taking a note, and add this note later at point."
12922 (remove-hook 'post-command-hook 'org-add-log-note)
12923 (setq org-log-note-window-configuration (current-window-configuration))
12924 (delete-other-windows)
12925 (move-marker org-log-note-return-to (point))
12926 (switch-to-buffer (marker-buffer org-log-note-marker))
12927 (goto-char org-log-note-marker)
12928 (switch-to-buffer-other-window "*Org Note*")
12929 (erase-buffer)
12930 (let ((org-inhibit-startup t)) (org-mode))
12931 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
12932 (cond
12933 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12934 ((eq org-log-note-purpose 'done) "closed todo item")
12935 ((eq org-log-note-purpose 'state) "state change")
12936 (t (error "This should not happen")))))
12937 (org-set-local 'org-finish-function 'org-store-log-note))
12939 (defun org-store-log-note ()
12940 "Finish taking a log note, and insert it to where it belongs."
12941 (let ((txt (buffer-string))
12942 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12943 lines ind)
12944 (kill-buffer (current-buffer))
12945 (if (string-match "^#.*\n[ \t\n]*" txt)
12946 (setq txt (replace-match "" t t txt)))
12947 (if (string-match "\\s-+\\'" txt)
12948 (setq txt (replace-match "" t t txt)))
12949 (setq lines (org-split-string txt "\n"))
12950 (when (and note (string-match "\\S-" note))
12951 (setq note
12952 (org-replace-escapes
12953 note
12954 (list (cons "%u" (user-login-name))
12955 (cons "%U" user-full-name)
12956 (cons "%t" (format-time-string
12957 (org-time-stamp-format 'long 'inactive)
12958 (current-time)))
12959 (cons "%s" (if org-log-note-state
12960 (concat "\"" org-log-note-state "\"")
12961 "")))))
12962 (if lines (setq note (concat note " \\\\")))
12963 (push note lines))
12964 (when lines
12965 (save-excursion
12966 (set-buffer (marker-buffer org-log-note-marker))
12967 (save-excursion
12968 (goto-char org-log-note-marker)
12969 (move-marker org-log-note-marker nil)
12970 (end-of-line 1)
12971 (if (not (bolp)) (insert "\n")) (indent-relative nil)
12972 (insert " - " (pop lines))
12973 (org-indent-line-function)
12974 (beginning-of-line 1)
12975 (looking-at "[ \t]*")
12976 (setq ind (concat (match-string 0) " "))
12977 (end-of-line 1)
12978 (while lines (insert "\n" ind (pop lines)))))))
12979 (set-window-configuration org-log-note-window-configuration)
12980 (with-current-buffer (marker-buffer org-log-note-return-to)
12981 (goto-char org-log-note-return-to))
12982 (move-marker org-log-note-return-to nil)
12983 (and org-log-post-message (message org-log-post-message)))
12985 (defvar org-occur-highlights nil)
12986 (make-variable-buffer-local 'org-occur-highlights)
12988 (defun org-occur (regexp &optional keep-previous callback)
12989 "Make a compact tree which shows all matches of REGEXP.
12990 The tree will show the lines where the regexp matches, and all higher
12991 headlines above the match. It will also show the heading after the match,
12992 to make sure editing the matching entry is easy.
12993 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12994 call to `org-occur' will be kept, to allow stacking of calls to this
12995 command.
12996 If CALLBACK is non-nil, it is a function which is called to confirm
12997 that the match should indeed be shown."
12998 (interactive "sRegexp: \nP")
12999 (or keep-previous (org-remove-occur-highlights nil nil t))
13000 (let ((cnt 0))
13001 (save-excursion
13002 (goto-char (point-min))
13003 (if (or (not keep-previous) ; do not want to keep
13004 (not org-occur-highlights)) ; no previous matches
13005 ;; hide everything
13006 (org-overview))
13007 (while (re-search-forward regexp nil t)
13008 (when (or (not callback)
13009 (save-match-data (funcall callback)))
13010 (setq cnt (1+ cnt))
13011 (when org-highlight-sparse-tree-matches
13012 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13013 (org-show-context 'occur-tree))))
13014 (when org-remove-highlights-with-change
13015 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13016 nil 'local))
13017 (unless org-sparse-tree-open-archived-trees
13018 (org-hide-archived-subtrees (point-min) (point-max)))
13019 (run-hooks 'org-occur-hook)
13020 (if (interactive-p)
13021 (message "%d match(es) for regexp %s" cnt regexp))
13022 cnt))
13024 (defun org-show-context (&optional key)
13025 "Make sure point and context and visible.
13026 How much context is shown depends upon the variables
13027 `org-show-hierarchy-above', `org-show-following-heading'. and
13028 `org-show-siblings'."
13029 (let ((heading-p (org-on-heading-p t))
13030 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13031 (following-p (org-get-alist-option org-show-following-heading key))
13032 (siblings-p (org-get-alist-option org-show-siblings key)))
13033 (catch 'exit
13034 ;; Show heading or entry text
13035 (if heading-p
13036 (org-flag-heading nil) ; only show the heading
13037 (and (or (org-invisible-p) (org-invisible-p2))
13038 (org-show-hidden-entry))) ; show entire entry
13039 (when following-p
13040 ;; Show next sibling, or heading below text
13041 (save-excursion
13042 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13043 (org-flag-heading nil))))
13044 (when siblings-p (org-show-siblings))
13045 (when hierarchy-p
13046 ;; show all higher headings, possibly with siblings
13047 (save-excursion
13048 (while (and (condition-case nil
13049 (progn (org-up-heading-all 1) t)
13050 (error nil))
13051 (not (bobp)))
13052 (org-flag-heading nil)
13053 (when siblings-p (org-show-siblings))))))))
13055 (defun org-reveal (&optional siblings)
13056 "Show current entry, hierarchy above it, and the following headline.
13057 This can be used to show a consistent set of context around locations
13058 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13059 not t for the search context.
13061 With optional argument SIBLINGS, on each level of the hierarchy all
13062 siblings are shown. This repairs the tree structure to what it would
13063 look like when opened with hierarchical calls to `org-cycle'."
13064 (interactive "P")
13065 (let ((org-show-hierarchy-above t)
13066 (org-show-following-heading t)
13067 (org-show-siblings (if siblings t org-show-siblings)))
13068 (org-show-context nil)))
13070 (defun org-highlight-new-match (beg end)
13071 "Highlight from BEG to END and mark the highlight is an occur headline."
13072 (let ((ov (org-make-overlay beg end)))
13073 (org-overlay-put ov 'face 'secondary-selection)
13074 (push ov org-occur-highlights)))
13076 (defun org-remove-occur-highlights (&optional beg end noremove)
13077 "Remove the occur highlights from the buffer.
13078 BEG and END are ignored. If NOREMOVE is nil, remove this function
13079 from the `before-change-functions' in the current buffer."
13080 (interactive)
13081 (unless org-inhibit-highlight-removal
13082 (mapc 'org-delete-overlay org-occur-highlights)
13083 (setq org-occur-highlights nil)
13084 (unless noremove
13085 (remove-hook 'before-change-functions
13086 'org-remove-occur-highlights 'local))))
13088 ;;;; Priorities
13090 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13091 "Regular expression matching the priority indicator.")
13093 (defvar org-remove-priority-next-time nil)
13095 (defun org-priority-up ()
13096 "Increase the priority of the current item."
13097 (interactive)
13098 (org-priority 'up))
13100 (defun org-priority-down ()
13101 "Decrease the priority of the current item."
13102 (interactive)
13103 (org-priority 'down))
13105 (defun org-priority (&optional action)
13106 "Change the priority of an item by ARG.
13107 ACTION can be `set', `up', `down', or a character."
13108 (interactive)
13109 (setq action (or action 'set))
13110 (let (current new news have remove)
13111 (save-excursion
13112 (org-back-to-heading)
13113 (if (looking-at org-priority-regexp)
13114 (setq current (string-to-char (match-string 2))
13115 have t)
13116 (setq current org-default-priority))
13117 (cond
13118 ((or (eq action 'set) (integerp action))
13119 (if (integerp action)
13120 (setq new action)
13121 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
13122 (setq new (read-char-exclusive)))
13123 (cond ((equal new ?\ ) (setq remove t))
13124 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13125 (error "Priority must be between `%c' and `%c'"
13126 org-highest-priority org-lowest-priority))))
13127 ((eq action 'up)
13128 (setq new (1- current)))
13129 ((eq action 'down)
13130 (setq new (1+ current)))
13131 (t (error "Invalid action")))
13132 (setq new (min (max org-highest-priority (upcase new)) org-lowest-priority))
13133 (setq news (format "%c" new))
13134 (if have
13135 (if remove
13136 (replace-match "" t t nil 1)
13137 (replace-match news t t nil 2))
13138 (if remove
13139 (error "No priority cookie found in line")
13140 (looking-at org-todo-line-regexp)
13141 (if (match-end 2)
13142 (progn
13143 (goto-char (match-end 2))
13144 (insert " [#" news "]"))
13145 (goto-char (match-beginning 3))
13146 (insert "[#" news "] ")))))
13147 (org-preserve-lc (org-set-tags nil 'align))
13148 (if remove
13149 (message "Priority removed")
13150 (message "Priority of current item set to %s" news))))
13153 (defun org-get-priority (s)
13154 "Find priority cookie and return priority."
13155 (save-match-data
13156 (if (not (string-match org-priority-regexp s))
13157 (* 1000 (- org-lowest-priority org-default-priority))
13158 (* 1000 (- org-lowest-priority
13159 (string-to-char (match-string 2 s)))))))
13161 ;;;; Tags
13163 (defun org-scan-tags (action matcher &optional todo-only)
13164 "Scan headline tags with inheritance and produce output ACTION.
13165 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
13166 evaluated, testing if a given set of tags qualifies a headline for
13167 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
13168 are included in the output."
13169 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
13170 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13171 (org-re
13172 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
13173 (props (list 'face nil
13174 'done-face 'org-done
13175 'undone-face nil
13176 'mouse-face 'highlight
13177 'org-not-done-regexp org-not-done-regexp
13178 'org-todo-regexp org-todo-regexp
13179 'keymap org-agenda-keymap
13180 'help-echo
13181 (format "mouse-2 or RET jump to org file %s"
13182 (abbreviate-file-name buffer-file-name))))
13183 (case-fold-search nil)
13184 lspos
13185 tags tags-list tags-alist (llast 0) rtn level category i txt
13186 todo marker entry priority)
13187 (save-excursion
13188 (goto-char (point-min))
13189 (when (eq action 'sparse-tree) (org-overview))
13190 (while (re-search-forward re nil t)
13191 (catch :skip
13192 (setq todo (if (match-end 1) (match-string 2))
13193 tags (if (match-end 4) (match-string 4)))
13194 (goto-char (setq lspos (1+ (match-beginning 0))))
13195 (setq level (org-reduced-level (funcall outline-level))
13196 category (org-get-category))
13197 (setq i llast llast level)
13198 ;; remove tag lists from same and sublevels
13199 (while (>= i level)
13200 (when (setq entry (assoc i tags-alist))
13201 (setq tags-alist (delete entry tags-alist)))
13202 (setq i (1- i)))
13203 ;; add the nex tags
13204 (when tags
13205 (setq tags (mapcar 'downcase (org-split-string tags ":"))
13206 tags-alist
13207 (cons (cons level tags) tags-alist)))
13208 ;; compile tags for current headline
13209 (setq tags-list
13210 (if org-use-tag-inheritance
13211 (apply 'append (mapcar 'cdr tags-alist))
13212 tags))
13213 (when (and (or (not todo-only) (member todo org-not-done-keywords))
13214 (eval matcher)
13215 (or (not org-agenda-skip-archived-trees)
13216 (not (member org-archive-tag tags-list))))
13217 (and (eq action 'agenda) (org-agenda-skip))
13218 ;; list this headline
13219 (if (eq action 'sparse-tree)
13220 (progn
13221 (org-show-context 'tags-tree))
13222 (setq txt (org-format-agenda-item
13224 (concat
13225 (if org-tags-match-list-sublevels
13226 (make-string (1- level) ?.) "")
13227 (org-get-heading))
13228 category tags-list)
13229 priority (org-get-priority txt))
13230 (goto-char lspos)
13231 (setq marker (org-agenda-new-marker))
13232 (org-add-props txt props
13233 'org-marker marker 'org-hd-marker marker 'org-category category
13234 'priority priority 'type "tagsmatch")
13235 (push txt rtn))
13236 ;; if we are to skip sublevels, jump to end of subtree
13237 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
13238 (when (and (eq action 'sparse-tree)
13239 (not org-sparse-tree-open-archived-trees))
13240 (org-hide-archived-subtrees (point-min) (point-max)))
13241 (nreverse rtn)))
13243 (defvar todo-only) ;; dynamically scoped
13245 (defun org-tags-sparse-tree (&optional todo-only match)
13246 "Create a sparse tree according to tags string MATCH.
13247 MATCH can contain positive and negative selection of tags, like
13248 \"+WORK+URGENT-WITHBOSS\".
13249 If optional argument TODO_ONLY is non-nil, only select lines that are
13250 also TODO lines."
13251 (interactive "P")
13252 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13254 (defvar org-cached-props nil)
13255 (defun org-cached-entry-get (pom property)
13256 (cdr (assoc property (or org-cached-props
13257 (setq org-cached-props
13258 (org-entry-properties pom))))))
13260 (defun org-global-tags-completion-table (&optional files)
13261 "Return the list of all tags in all agenda buffer/files."
13262 (save-excursion
13263 (org-uniquify
13264 (apply 'append
13265 (mapcar
13266 (lambda (file)
13267 (set-buffer (find-file-noselect file))
13268 (org-get-buffer-tags))
13269 (if (and files (car files))
13270 files
13271 (org-agenda-files)))))))
13273 (defun org-make-tags-matcher (match)
13274 "Create the TAGS//TODO matcher form for the selection string MATCH."
13275 ;; todo-only is scoped dynamically into this function, and the function
13276 ;; may change it it the matcher asksk for it.
13277 (unless match
13278 ;; Get a new match request, with completion
13279 (let ((org-last-tags-completion-table
13280 (org-global-tags-completion-table)))
13281 (setq match (completing-read
13282 "Match: " 'org-tags-completion-function nil nil nil
13283 'org-tags-history))))
13285 ;; Parse the string and create a lisp form
13286 (let ((match0 match)
13287 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
13288 minus tag mm
13289 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13290 orterms term orlist re-p level-p prop-p pn pv)
13291 (if (string-match "/+" match)
13292 ;; match contains also a todo-matching request
13293 (progn
13294 (setq tagsmatch (substring match 0 (match-beginning 0))
13295 todomatch (substring match (match-end 0)))
13296 (if (string-match "^!" todomatch)
13297 (setq todo-only t todomatch (substring todomatch 1)))
13298 (if (string-match "^\\s-*$" todomatch)
13299 (setq todomatch nil)))
13300 ;; only matching tags
13301 (setq tagsmatch match todomatch nil))
13303 ;; Make the tags matcher
13304 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13305 (setq tagsmatcher t)
13306 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13307 (while (setq term (pop orterms))
13308 (while (and (equal (substring term -1) "\\") orterms)
13309 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13310 (while (string-match re term)
13311 (setq minus (and (match-end 1)
13312 (equal (match-string 1 term) "-"))
13313 tag (match-string 2 term)
13314 re-p (equal (string-to-char tag) ?{)
13315 level-p (match-end 3)
13316 prop-p (match-end 4)
13317 mm (cond
13318 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13319 (level-p `(= level ,(string-to-number
13320 (match-string 3 term))))
13321 (prop-p
13322 (setq pn (match-string 4 term)
13323 pv (match-string 5 term)
13324 re-p (equal (string-to-char pv) ?{)
13325 pv (substring pv 1 -1))
13326 (if re-p
13327 `(string-match ,pv (org-cached-entry-get nil ,pn))
13328 `(equal ,pv (org-cached-entry-get nil ,pn))))
13329 (t `(member ,(downcase tag) tags-list)))
13330 mm (if minus (list 'not mm) mm)
13331 term (substring term (match-end 0)))
13332 (push mm tagsmatcher))
13333 (push (if (> (length tagsmatcher) 1)
13334 (cons 'and tagsmatcher)
13335 (car tagsmatcher))
13336 orlist)
13337 (setq tagsmatcher nil))
13338 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13339 (setq tagsmatcher
13340 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13342 ;; Make the todo matcher
13343 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13344 (setq todomatcher t)
13345 (setq orterms (org-split-string todomatch "|") orlist nil)
13346 (while (setq term (pop orterms))
13347 (while (string-match re term)
13348 (setq minus (and (match-end 1)
13349 (equal (match-string 1 term) "-"))
13350 kwd (match-string 2 term)
13351 re-p (equal (string-to-char kwd) ?{)
13352 term (substring term (match-end 0))
13353 mm (if re-p
13354 `(string-match ,(substring kwd 1 -1) todo)
13355 (list 'equal 'todo kwd))
13356 mm (if minus (list 'not mm) mm))
13357 (push mm todomatcher))
13358 (push (if (> (length todomatcher) 1)
13359 (cons 'and todomatcher)
13360 (car todomatcher))
13361 orlist)
13362 (setq todomatcher nil))
13363 (setq todomatcher (if (> (length orlist) 1)
13364 (cons 'or orlist) (car orlist))))
13366 ;; Return the string and lisp forms of the matcher
13367 (setq matcher (if todomatcher
13368 (list 'and tagsmatcher todomatcher)
13369 tagsmatcher))
13370 (cons match0 matcher)))
13372 (defun org-match-any-p (re list)
13373 "Does re match any element of list?"
13374 (setq list (mapcar (lambda (x) (string-match re x)) list))
13375 (delq nil list))
13377 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
13378 (defvar org-tags-overlay (org-make-overlay 1 1))
13379 (org-detach-overlay org-tags-overlay)
13381 (defun org-align-tags-here (to-col)
13382 ;; Assumes that this is a headline
13383 (let ((pos (point)) (col (current-column)) tags)
13384 (beginning-of-line 1)
13385 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13386 (< pos (match-beginning 2)))
13387 (progn
13388 (setq tags (match-string 2))
13389 (goto-char (match-beginning 1))
13390 (insert " ")
13391 (delete-region (point) (1+ (match-end 0)))
13392 (backward-char 1)
13393 (move-to-column
13394 (max (1+ (current-column))
13395 (1+ col)
13396 (if (> to-col 0)
13397 to-col
13398 (- (abs to-col) (length tags))))
13400 (insert tags)
13401 (move-to-column (min (current-column) col) t))
13402 (goto-char pos))))
13404 (defun org-set-tags (&optional arg just-align)
13405 "Set the tags for the current headline.
13406 With prefix ARG, realign all tags in headings in the current buffer."
13407 (interactive "P")
13408 (let* ((re (concat "^" outline-regexp))
13409 (current (org-get-tags))
13410 table current-tags inherited-tags ; computed below when needed
13411 tags p0 c0 c1 rpl)
13412 (if arg
13413 (save-excursion
13414 (goto-char (point-min))
13415 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13416 (while (re-search-forward re nil t)
13417 (org-set-tags nil t)
13418 (end-of-line 1)))
13419 (message "All tags realigned to column %d" org-tags-column))
13420 (if just-align
13421 (setq tags current)
13422 ;; Get a new set of tags from the user
13423 (save-excursion
13424 (setq table (or org-tag-alist (org-get-buffer-tags))
13425 org-last-tags-completion-table table
13426 current-tags (org-split-string current ":")
13427 inherited-tags (nreverse
13428 (nthcdr (length current-tags)
13429 (nreverse (org-get-tags-at))))
13430 tags
13431 (if (or (eq t org-use-fast-tag-selection)
13432 (and org-use-fast-tag-selection
13433 (delq nil (mapcar 'cdr table))))
13434 (org-fast-tag-selection current-tags inherited-tags table)
13435 (let ((org-add-colon-after-tag-completion t))
13436 (org-trim
13437 (completing-read "Tags: " 'org-tags-completion-function
13438 nil nil current 'org-tags-history))))))
13439 (while (string-match "[-+&]+" tags)
13440 ;; No boolean logic, just a list
13441 (setq tags (replace-match ":" t t tags))))
13443 (if (string-match "\\`[\t ]*\\'" tags)
13444 (setq tags "")
13445 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13446 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13448 ;; Insert new tags at the correct column
13449 (beginning-of-line 1)
13450 (cond
13451 ((and (equal current "") (equal tags "")))
13452 ((re-search-forward
13453 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13454 (point-at-eol) t)
13455 (if (equal tags "")
13456 (setq rpl "")
13457 (goto-char (match-beginning 0))
13458 (setq c0 (current-column) p0 (point)
13459 c1 (max (1+ c0) (if (> org-tags-column 0)
13460 org-tags-column
13461 (- (- org-tags-column) (length tags))))
13462 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13463 (replace-match rpl t t)
13464 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
13465 tags)
13466 (t (error "Tags alignment failed"))))))
13468 (defun org-change-tag-in-region (beg end tag off)
13469 "Add or remove TAG for each entry in the region.
13470 This works in the agenda, and also in an org-mode buffer."
13471 (interactive
13472 (list (region-beginning) (region-end)
13473 (let ((org-last-tags-completion-table
13474 (if (org-mode-p)
13475 (org-get-buffer-tags)
13476 (org-global-tags-completion-table))))
13477 (completing-read
13478 "Tag: " 'org-tags-completion-function nil nil nil
13479 'org-tags-history))
13480 (progn
13481 (message "[s]et or [r]emove? ")
13482 (equal (read-char-exclusive) ?r))))
13483 (if (fboundp 'deactivate-mark) (deactivate-mark))
13484 (let ((agendap (equal major-mode 'org-agenda-mode))
13485 l1 l2 m buf pos newhead (cnt 0))
13486 (goto-char end)
13487 (setq l2 (1- (org-current-line)))
13488 (goto-char beg)
13489 (setq l1 (org-current-line))
13490 (loop for l from l1 to l2 do
13491 (goto-line l)
13492 (setq m (get-text-property (point) 'org-hd-marker))
13493 (when (or (and (org-mode-p) (org-on-heading-p))
13494 (and agendap m))
13495 (setq buf (if agendap (marker-buffer m) (current-buffer))
13496 pos (if agendap m (point)))
13497 (with-current-buffer buf
13498 (save-excursion
13499 (save-restriction
13500 (goto-char pos)
13501 (setq cnt (1+ cnt))
13502 (org-toggle-tag tag (if off 'off 'on))
13503 (setq newhead (org-get-heading)))))
13504 (and agendap (org-agenda-change-all-lines newhead m))))
13505 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13507 (defun org-tags-completion-function (string predicate &optional flag)
13508 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13509 (confirm (lambda (x) (stringp (car x)))))
13510 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
13511 (setq s1 (match-string 1 string)
13512 s2 (match-string 2 string))
13513 (setq s1 "" s2 string))
13514 (cond
13515 ((eq flag nil)
13516 ;; try completion
13517 (setq rtn (try-completion s2 ctable confirm))
13518 (if (stringp rtn)
13519 (setq rtn
13520 (concat s1 s2 (substring rtn (length s2))
13521 (if (and org-add-colon-after-tag-completion
13522 (assoc rtn ctable))
13523 ":" ""))))
13524 rtn)
13525 ((eq flag t)
13526 ;; all-completions
13527 (all-completions s2 ctable confirm)
13529 ((eq flag 'lambda)
13530 ;; exact match?
13531 (assoc s2 ctable)))
13534 (defun org-fast-tag-insert (kwd tags face &optional end)
13535 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
13536 (insert (format "%-12s" (concat kwd ":"))
13537 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13538 (or end "")))
13540 (defun org-fast-tag-show-exit (flag)
13541 (save-excursion
13542 (goto-line 3)
13543 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13544 (replace-match ""))
13545 (when flag
13546 (end-of-line 1)
13547 (move-to-column (- (window-width) 19) t)
13548 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13550 (defun org-set-current-tags-overlay (current prefix)
13551 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13552 (if (featurep 'xemacs)
13553 (org-overlay-display org-tags-overlay (concat prefix s)
13554 'secondary-selection)
13555 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13556 (org-overlay-display org-tags-overlay (concat prefix s)))))
13558 (defun org-fast-tag-selection (current inherited table)
13559 "Fast tag selection with single keys.
13560 CURRENT is the current list of tags in the headline, INHERITED is the
13561 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13562 possibly with grouping information.
13563 If the keys are nil, a-z are automatically assigned.
13564 Returns the new tags string, or nil to not change the current settings."
13565 (let* ((maxlen (apply 'max (mapcar
13566 (lambda (x)
13567 (if (stringp (car x)) (string-width (car x)) 0))
13568 table)))
13569 (buf (current-buffer))
13570 (expert (eq org-fast-tag-selection-single-key 'expert))
13571 (buffer-tags nil)
13572 (fwidth (+ maxlen 3 1 3))
13573 (ncol (/ (- (window-width) 4) fwidth))
13574 (i-face 'org-done)
13575 (c-face 'org-todo)
13576 tg cnt e c char c1 c2 ntable tbl rtn
13577 ov-start ov-end ov-prefix
13578 (exit-after-next org-fast-tag-selection-single-key)
13579 groups ingroup)
13580 (save-excursion
13581 (beginning-of-line 1)
13582 (if (looking-at
13583 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13584 (setq ov-start (match-beginning 1)
13585 ov-end (match-end 1)
13586 ov-prefix "")
13587 (setq ov-start (1- (point-at-eol))
13588 ov-end (1+ ov-start))
13589 (skip-chars-forward "^\n\r")
13590 (setq ov-prefix
13591 (concat
13592 (buffer-substring (1- (point)) (point))
13593 (if (> (current-column) org-tags-column)
13595 (make-string (- org-tags-column (current-column)) ?\ ))))))
13596 (org-move-overlay org-tags-overlay ov-start ov-end)
13597 (save-window-excursion
13598 (if expert
13599 (set-buffer (get-buffer-create " *Org tags*"))
13600 (delete-other-windows)
13601 (split-window-vertically)
13602 (switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13603 (erase-buffer)
13604 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13605 (org-fast-tag-insert "Current" current c-face "\n\n")
13606 (org-fast-tag-show-exit exit-after-next)
13607 (org-set-current-tags-overlay current ov-prefix)
13608 (setq tbl table char ?a cnt 0)
13609 (while (setq e (pop tbl))
13610 (cond
13611 ((equal e '(:startgroup))
13612 (push '() groups) (setq ingroup t)
13613 (when (not (= cnt 0))
13614 (setq cnt 0)
13615 (insert "\n"))
13616 (insert "{ "))
13617 ((equal e '(:endgroup))
13618 (setq ingroup nil cnt 0)
13619 (insert "}\n"))
13621 (setq tg (car e) c2 nil)
13622 (if (cdr e)
13623 (setq c (cdr e))
13624 ;; automatically assign a character.
13625 (setq c1 (string-to-char
13626 (downcase (substring
13627 tg (if (= (string-to-char tg) ?@) 1 0)))))
13628 (if (or (rassoc c1 ntable) (rassoc c1 table))
13629 (while (or (rassoc char ntable) (rassoc char table))
13630 (setq char (1+ char)))
13631 (setq c2 c1))
13632 (setq c (or c2 char)))
13633 (if ingroup (push tg (car groups)))
13634 (setq tg (org-add-props tg nil 'face
13635 (cond
13636 ((member tg current) c-face)
13637 ((member tg inherited) i-face)
13638 (t nil))))
13639 (if (and (= cnt 0) (not ingroup)) (insert " "))
13640 (insert "[" c "] " tg (make-string
13641 (- fwidth 4 (length tg)) ?\ ))
13642 (push (cons tg c) ntable)
13643 (when (= (setq cnt (1+ cnt)) ncol)
13644 (insert "\n")
13645 (if ingroup (insert " "))
13646 (setq cnt 0)))))
13647 (setq ntable (nreverse ntable))
13648 (insert "\n")
13649 (goto-char (point-min))
13650 (if (and (not expert) (fboundp 'fit-window-to-buffer))
13651 (fit-window-to-buffer))
13652 (setq rtn
13653 (catch 'exit
13654 (while t
13655 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
13656 (if groups " [!] no groups" " [!]groups")
13657 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13658 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13659 (cond
13660 ((= c ?\r) (throw 'exit t))
13661 ((= c ?!)
13662 (setq groups (not groups))
13663 (goto-char (point-min))
13664 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13665 ((= c ?\C-c)
13666 (if (not expert)
13667 (org-fast-tag-show-exit
13668 (setq exit-after-next (not exit-after-next)))
13669 (setq expert nil)
13670 (delete-other-windows)
13671 (split-window-vertically)
13672 (switch-to-buffer-other-window " *Org tags*")
13673 (and (fboundp 'fit-window-to-buffer)
13674 (fit-window-to-buffer))))
13675 ((or (= c ?\C-g)
13676 (and (= c ?q) (not (rassoc c ntable))))
13677 (org-detach-overlay org-tags-overlay)
13678 (setq quit-flag t))
13679 ((= c ?\ )
13680 (setq current nil)
13681 (if exit-after-next (setq exit-after-next 'now)))
13682 ((= c ?\t)
13683 (condition-case nil
13684 (setq tg (completing-read
13685 "Tag: "
13686 (or buffer-tags
13687 (with-current-buffer buf
13688 (org-get-buffer-tags)))))
13689 (quit (setq tg "")))
13690 (when (string-match "\\S-" tg)
13691 (add-to-list 'buffer-tags (list tg))
13692 (if (member tg current)
13693 (setq current (delete tg current))
13694 (push tg current)))
13695 (if exit-after-next (setq exit-after-next 'now)))
13696 ((setq e (rassoc c ntable) tg (car e))
13697 (if (member tg current)
13698 (setq current (delete tg current))
13699 (loop for g in groups do
13700 (if (member tg g)
13701 (mapcar (lambda (x)
13702 (setq current (delete x current)))
13703 g)))
13704 (push tg current))
13705 (if exit-after-next (setq exit-after-next 'now))))
13707 ;; Create a sorted list
13708 (setq current
13709 (sort current
13710 (lambda (a b)
13711 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13712 (if (eq exit-after-next 'now) (throw 'exit t))
13713 (goto-char (point-min))
13714 (beginning-of-line 2)
13715 (delete-region (point) (point-at-eol))
13716 (org-fast-tag-insert "Current" current c-face)
13717 (org-set-current-tags-overlay current ov-prefix)
13718 (while (re-search-forward
13719 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
13720 (setq tg (match-string 1))
13721 (add-text-properties (match-beginning 1) (match-end 1)
13722 (list 'face
13723 (cond
13724 ((member tg current) c-face)
13725 ((member tg inherited) i-face)
13726 (t nil)))))
13727 (goto-char (point-min)))))
13728 (org-detach-overlay org-tags-overlay)
13729 (if rtn
13730 (mapconcat 'identity current ":")
13731 nil))))
13733 (defun org-get-tags ()
13734 "Get the TAGS string in the current headline."
13735 (unless (org-on-heading-p t)
13736 (error "Not on a heading"))
13737 (save-excursion
13738 (beginning-of-line 1)
13739 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13740 (org-match-string-no-properties 1)
13741 "")))
13743 (defun org-get-buffer-tags ()
13744 "Get a table of all tags used in the buffer, for completion."
13745 (let (tags)
13746 (save-excursion
13747 (goto-char (point-min))
13748 (while (re-search-forward
13749 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
13750 (when (equal (char-after (point-at-bol 0)) ?*)
13751 (mapc (lambda (x) (add-to-list 'tags x))
13752 (org-split-string (org-match-string-no-properties 1) ":")))))
13753 (mapcar 'list tags)))
13756 ;;;; Properties
13758 ;;; Setting and retrieving properties
13760 (defconst org-special-properties
13761 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED"
13762 "CLOCK" "PRIORITY")
13763 "The special properties valid in Org-mode.
13765 These are properties that are not defined in the property drawer,
13766 but in some other way.")
13768 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13769 "Regular expression matching the first line of a property drawer.")
13771 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13772 "Regular expression matching the first line of a property drawer.")
13774 (defun org-property-action ()
13775 "Do an action on properties."
13776 (interactive)
13777 (let (c prop)
13778 (org-at-property-p)
13779 (setq prop (match-string 2))
13780 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13781 (setq c (read-char-exclusive))
13782 (cond
13783 ((equal c ?s)
13784 (call-interactively 'org-set-property))
13785 ((equal c ?d)
13786 (call-interactively 'org-delete-property))
13787 ((equal c ?D)
13788 (call-interactively 'org-delete-property-globally))
13789 ((equal c ?c)
13790 (call-interactively 'org-compute-property-at-point))
13791 (t (error "No such property action %c" c)))))
13793 (defun org-at-property-p ()
13794 "Is the cursor in a property line?"
13795 ;; FIXME: Does not check if we are actually in the drawer.
13796 ;; FIXME: also returns true on any drawers.....
13797 ;; This is used by C-c C-c for property action.
13798 (save-excursion
13799 (beginning-of-line 1)
13800 (looking-at "^[ \t]*\\(:\\([a-zA-Z_0-9]+\\):\\)[ \t]*\\(.*\\)")))
13802 (defmacro org-with-point-at (pom &rest body)
13803 "Move to buffer and point of point-or-marker POM for the duration of BODY."
13804 (declare (indent 1) (debug t))
13805 `(save-excursion
13806 (if (markerp pom) (set-buffer (marker-buffer pom)))
13807 (save-excursion
13808 (goto-char (or pom (point)))
13809 ,@body)))
13811 (defun org-get-property-block (&optional beg end force)
13812 "Return the (beg . end) range of the body of the property drawer.
13813 BEG and END can be beginning and end of subtree, if not given
13814 they will be found.
13815 If the drawer does not exist and FORCE is non-nil, create the drawer."
13816 (catch 'exit
13817 (save-excursion
13818 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13819 (end (or end (progn (outline-next-heading) (point)))))
13820 (goto-char beg)
13821 (if (re-search-forward org-property-start-re end t)
13822 (setq beg (1+ (match-end 0)))
13823 (if force
13824 (save-excursion
13825 (org-insert-property-drawer)
13826 (setq end (progn (outline-next-heading) (point))))
13827 (throw 'exit nil))
13828 (goto-char beg)
13829 (if (re-search-forward org-property-start-re end t)
13830 (setq beg (1+ (match-end 0)))))
13831 (if (re-search-forward org-property-end-re end t)
13832 (setq end (match-beginning 0))
13833 (or force (throw 'exit nil))
13834 (goto-char beg)
13835 (setq end beg)
13836 (org-indent-line-function)
13837 (insert ":END:\n"))
13838 (cons beg end)))))
13840 (defun org-entry-properties (&optional pom which)
13841 "Get all properties of the entry at point-or-marker POM.
13842 This includes the TODO keyword, the tags, time strings for deadline,
13843 scheduled, and clocking, and any additional properties defined in the
13844 entry. The return value is an alist, keys may occur multiple times
13845 if the property key was used several times.
13846 POM may also be nil, in which case the current entry is used.
13847 If WHICH is nil or `all', get all properties. If WHICH is
13848 `special' or `standard', only get that subclass."
13849 (setq which (or which 'all))
13850 (org-with-point-at pom
13851 (let ((clockstr (substring org-clock-string 0 -1))
13852 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
13853 beg end range props sum-props key value)
13854 (save-excursion
13855 (when (condition-case nil (org-back-to-heading t) (error nil))
13856 (setq beg (point))
13857 (setq sum-props (get-text-property (point) 'org-summaries))
13858 (outline-next-heading)
13859 (setq end (point))
13860 (when (memq which '(all special))
13861 ;; Get the special properties, like TODO and tags
13862 (goto-char beg)
13863 (when (and (looking-at org-todo-line-regexp) (match-end 2))
13864 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13865 (when (looking-at org-priority-regexp)
13866 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13867 (when (and (setq value (org-get-tags)) (string-match "\\S-" value))
13868 (push (cons "TAGS" value) props))
13869 (when (setq value (org-get-tags-at))
13870 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
13871 props))
13872 (while (re-search-forward org-keyword-time-regexp end t)
13873 (setq key (substring (org-match-string-no-properties 1) 0 -1))
13874 (unless (member key excluded) (push key excluded))
13875 (push (cons key
13876 (if (equal key clockstr)
13877 (org-no-properties
13878 (org-trim
13879 (buffer-substring
13880 (match-beginning 2) (point-at-eol))))
13881 (org-match-string-no-properties 2)))
13882 props)))
13883 (when (memq which '(all standard))
13884 ;; Get the standard properties, like :PORP: ...
13885 (setq range (org-get-property-block beg end))
13886 (when range
13887 (goto-char (car range))
13888 (while (re-search-forward
13889 "^[ \t]*:\\([a-zA-Z][a-zA-Z_0-9]*\\):[ \t]*\\(\\S-.*\\)?"
13890 (cdr range) t)
13891 (setq key (org-match-string-no-properties 1)
13892 value (org-trim (or (org-match-string-no-properties 2) "")))
13893 (unless (member key excluded)
13894 (push (cons key (or value "")) props)))))
13895 (append sum-props (nreverse props)))))))
13897 (defun org-entry-get (pom property &optional inherit)
13898 "Get value of PROPERTY for entry at point-or-marker POM.
13899 If INHERIT is non-nil and the entry does not have the property,
13900 then also check higher levels of the hierarchy.
13901 If the property is present but empty, the return value is the empty string.
13902 If the property is not present at all, nil is returned."
13903 (org-with-point-at pom
13904 (if inherit
13905 (org-entry-get-with-inheritance property)
13906 (if (member property org-special-properties)
13907 ;; We need a special property. Use brute force, get all properties.
13908 (cdr (assoc property (org-entry-properties nil 'special)))
13909 (let ((range (org-get-property-block)))
13910 (if (and range
13911 (goto-char (car range))
13912 (re-search-forward
13913 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
13914 (cdr range) t))
13915 ;; Found the property, return it.
13916 (if (match-end 1)
13917 (org-match-string-no-properties 1)
13918 "")))))))
13920 (defun org-entry-delete (pom property)
13921 "Delete the property PROPERTY from entry at point-or-marker POM."
13922 (org-with-point-at pom
13923 (if (member property org-special-properties)
13924 nil ; cannot delete these properties.
13925 (let ((range (org-get-property-block)))
13926 (if (and range
13927 (goto-char (car range))
13928 (re-search-forward
13929 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
13930 (cdr range) t))
13931 (progn
13932 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13934 nil)))))
13936 (defvar org-entry-property-inherited-from (make-marker))
13938 (defun org-entry-get-with-inheritance (property)
13939 "Get entry property, and search higher levels if not present."
13940 (let (tmp)
13941 (save-excursion
13942 (catch 'ex
13943 (while t
13944 (when (setq tmp (org-entry-get nil property))
13945 (org-back-to-heading t)
13946 (move-marker org-entry-property-inherited-from (point))
13947 (throw 'ex tmp))
13948 (condition-case nil
13949 (org-up-heading-all 1)
13950 (error (throw 'ex nil))))))
13951 (or tmp (cdr (assoc property org-local-properties))
13952 (cdr (assoc property org-global-properties)))))
13954 (defun org-entry-put (pom property value)
13955 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13956 (org-with-point-at pom
13957 (org-back-to-heading t)
13958 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13959 range)
13960 (cond
13961 ((equal property "TODO")
13962 (when (and (stringp value) (string-match "\\S-" value)
13963 (not (member value org-todo-keywords-1)))
13964 (error "\"%s\" is not a valid TODO state" value))
13965 (if (or (not value)
13966 (not (string-match "\\S-" value)))
13967 (setq value 'none))
13968 (org-todo value)
13969 (org-set-tags nil 'align))
13970 ((equal property "PRIORITY")
13971 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13972 (string-to-char value) ?\ ))
13973 (org-set-tags nil 'align))
13974 ((equal property "SCHEDULED")
13975 (if (re-search-forward org-scheduled-time-regexp end t)
13976 (cond
13977 ((eq value 'earlier) (org-timestamp-change -1 'day))
13978 ((eq value 'later) (org-timestamp-change 1 'day))
13979 (t (call-interactively 'org-schedule)))
13980 (call-interactively 'org-schedule)))
13981 ((equal property "DEADLINE")
13982 (if (re-search-forward org-deadline-time-regexp end t)
13983 (cond
13984 ((eq value 'earlier) (org-timestamp-change -1 'day))
13985 ((eq value 'later) (org-timestamp-change 1 'day))
13986 (t (call-interactively 'org-deadline)))
13987 (call-interactively 'org-deadline)))
13988 ((member property org-special-properties)
13989 (error "The %s property can not yet be set with `org-entry-put'"
13990 property))
13991 (t ; a non-special property
13992 (setq range (org-get-property-block beg end 'force))
13993 (goto-char (car range))
13994 (if (re-search-forward
13995 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13996 (progn
13997 (delete-region (match-beginning 1) (match-end 1))
13998 (goto-char (match-beginning 1)))
13999 (goto-char (cdr range))
14000 (insert "\n")
14001 (backward-char 1)
14002 (org-indent-line-function)
14003 (insert ":" property ":"))
14004 (and value (insert " " value))
14005 (org-indent-line-function))))))
14007 (defun org-buffer-property-keys (&optional include-specials)
14008 "Get all property keys in the current buffer."
14009 (let (rtn range)
14010 (save-excursion
14011 (save-restriction
14012 (widen)
14013 (goto-char (point-min))
14014 (while (re-search-forward org-property-start-re nil t)
14015 (setq range (org-get-property-block))
14016 (goto-char (car range))
14017 (while (re-search-forward "^[ \t]*:\\([a-zA-Z0-9]+\\):" (cdr range) t)
14018 (add-to-list 'rtn (org-match-string-no-properties 1)))
14019 (outline-next-heading))))
14020 (when include-specials
14021 (setq rtn (append org-special-properties rtn)))
14022 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14024 (defun org-insert-property-drawer ()
14025 "Insert a property drawer into the current entry."
14026 (interactive)
14027 (org-back-to-heading t)
14028 (let ((beg (point))
14029 (re (concat "^[ \t]*" org-keyword-time-regexp))
14030 end hiddenp)
14031 (outline-next-heading)
14032 (setq end (point))
14033 (goto-char beg)
14034 (while (re-search-forward re end t))
14035 (setq hiddenp (org-invisible-p))
14036 (end-of-line 1)
14037 (insert "\n:PROPERTIES:\n:END:")
14038 (beginning-of-line 0)
14039 (org-indent-line-function)
14040 (beginning-of-line 2)
14041 (org-indent-line-function)
14042 (beginning-of-line 0)
14043 (if hiddenp
14044 (save-excursion
14045 (org-back-to-heading t)
14046 (hide-entry))
14047 (org-flag-drawer t))))
14049 (defun org-set-property (property value)
14050 "In the current entry, set PROPERTY to VALUE."
14051 (interactive
14052 (let* ((prop (completing-read "Property: "
14053 (mapcar 'list (org-buffer-property-keys))))
14054 (cur (org-entry-get nil prop))
14055 (allowed (org-property-get-allowed-values nil prop 'table))
14056 (val (if allowed
14057 (completing-read "Value: " allowed nil 'req-match)
14058 (read-string
14059 (concat "Value" (if (and cur (string-match "\\S-" cur))
14060 (concat "[" cur "]") "")
14061 ": ")
14062 "" cur))))
14063 (list prop (if (equal val "") cur val))))
14064 (unless (equal (org-entry-get nil property) value)
14065 (org-entry-put nil property value)))
14067 (defun org-delete-property (property)
14068 "In the current entry, delete PROPERTY."
14069 (interactive
14070 (let* ((prop (completing-read
14071 "Property: " (org-entry-properties nil 'standard))))
14072 (list prop)))
14073 (message (concat "Property " property
14074 (if (org-entry-delete nil property)
14075 " deleted"
14076 " was not present in the entry"))))
14078 (defun org-delete-property-globally (property)
14079 "Remove PROPERTY globally, from all entries."
14080 (interactive
14081 (let* ((prop (completing-read
14082 "Globally remove property: "
14083 (mapcar 'list (org-buffer-property-keys)))))
14084 (list prop)))
14085 (save-excursion
14086 (save-restriction
14087 (widen)
14088 (goto-char (point-min))
14089 (let ((cnt 0))
14090 (while (re-search-forward
14091 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
14092 nil t)
14093 (setq cnt (1+ cnt))
14094 (replace-match ""))
14095 (message "Property \"%s\" removed from %d entries" property cnt)))))
14097 (defvar org-columns-current-fmt-compiled) ; defined below
14099 (defun org-compute-property-at-point ()
14100 "FIXME:"
14101 (interactive)
14102 (unless (org-at-property-p)
14103 (error "Not at a property"))
14104 (let ((prop (org-match-string-no-properties 2)))
14105 (org-columns-get-format-and-top-level)
14106 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14107 (error "No operator defined for property %s" prop))
14108 (org-columns-compute prop)))
14110 (defun org-property-get-allowed-values (pom property &optional table)
14111 "Get allowed values for the property PROPERTY.
14112 When TABLE is non-nil, return an alist that can directly be used for
14113 completion."
14114 (let (vals)
14115 (cond
14116 ((equal property "TODO")
14117 (setq vals (org-with-point-at pom
14118 (append org-todo-keywords-1 '("")))))
14119 ((equal property "PRIORITY")
14120 (let ((n org-lowest-priority))
14121 (while (>= n org-highest-priority)
14122 (push (char-to-string n) vals)
14123 (setq n (1- n)))))
14124 ((member property org-special-properties))
14126 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14128 (when (and vals (string-match "\\S-" vals))
14129 (setq vals (car (read-from-string (concat "(" vals ")"))))
14130 (setq vals (mapcar (lambda (x)
14131 (cond ((stringp x) x)
14132 ((numberp x) (number-to-string x))
14133 ((symbolp x) (symbol-name x))
14134 (t "???")))
14135 vals)))))
14136 (if table (mapcar 'list vals) vals)))
14138 (defun org-property-previous-allowed-value (&optional previous)
14139 "Switch to the next allowed value for this property."
14140 (interactive)
14141 (org-property-next-allowed-value t))
14143 (defun org-property-next-allowed-value (&optional previous)
14144 "Switch to the next allowed value for this property."
14145 (interactive)
14146 (unless (org-at-property-p)
14147 (error "Not at a property"))
14148 (let* ((key (match-string 2))
14149 (value (match-string 3))
14150 (allowed (or (org-property-get-allowed-values (point) key)
14151 (and (member value '("[ ]" "[-]" "[X]"))
14152 '("[ ]" "[X]"))))
14153 nval)
14154 (unless allowed
14155 (error "Allowed values for this property have not been defined"))
14156 (if previous (setq allowed (reverse allowed)))
14157 (if (member value allowed)
14158 (setq nval (car (cdr (member value allowed)))))
14159 (setq nval (or nval (car allowed)))
14160 (if (equal nval value)
14161 (error "Only one allowed value for this property"))
14162 (org-at-property-p)
14163 (replace-match (concat " :" key ": " nval) t t)
14164 (org-indent-line-function)
14165 (beginning-of-line 1)
14166 (skip-chars-forward " \t")))
14168 ;;; Column View
14170 (defvar org-columns-overlays nil
14171 "Holds the list of current column overlays.")
14173 (defvar org-columns-current-fmt nil
14174 "Local variable, holds the currently active column format.")
14175 (defvar org-columns-current-fmt-compiled nil
14176 "Local variable, holds the currently active column format.
14177 This is the compiled version of the format.")
14178 (defvar org-columns-current-maxwidths nil
14179 "Loval variable, holds the currently active maximum column widths.")
14180 (defvar org-columns-begin-marker (make-marker)
14181 "Points to the position where last a column creation command was called.")
14182 (defvar org-columns-top-level-marker (make-marker)
14183 "Points to the position where current columns region starts.")
14185 (defvar org-columns-map (make-sparse-keymap)
14186 "The keymap valid in column display.")
14188 (defun org-columns-content ()
14189 "Switch to contents view while in columns view."
14190 (interactive)
14191 (org-overview)
14192 (org-content))
14194 (org-defkey org-columns-map "c" 'org-columns-content)
14195 (org-defkey org-columns-map "o" 'org-overview)
14196 (org-defkey org-columns-map "e" 'org-columns-edit-value)
14197 (org-defkey org-columns-map "v" 'org-columns-show-value)
14198 (org-defkey org-columns-map "q" 'org-columns-quit)
14199 (org-defkey org-columns-map "r" 'org-columns-redo)
14200 (org-defkey org-columns-map [left] 'backward-char)
14201 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
14202 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
14203 (org-defkey org-columns-map [right] 'forward-char)
14204 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
14205 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
14206 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-next-allowed-value)
14207 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
14208 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
14209 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
14210 (org-defkey org-columns-map "<" 'org-columns-narrow)
14211 (org-defkey org-columns-map ">" 'org-columns-widen)
14212 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
14213 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
14214 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
14215 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
14217 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
14218 '("Column"
14219 ["Edit property" org-columns-edit-value t]
14220 ["Next allowed value" org-columns-next-allowed-value t]
14221 ["Previous allowed value" org-columns-previous-allowed-value t]
14222 ["Show full value" org-columns-show-value t]
14223 ["Edit allowed" org-columns-edit-allowed t]
14224 "--"
14225 ["Edit column attributes" org-columns-edit-attributes t]
14226 ["Increase column width" org-columns-widen t]
14227 ["Decrease column width" org-columns-narrow t]
14228 "--"
14229 ["Move column right" org-columns-move-right t]
14230 ["Move column left" org-columns-move-left t]
14231 ["Add column" org-columns-new t]
14232 ["Delete column" org-columns-delete t]
14233 "--"
14234 ["CONTENTS" org-columns-content t]
14235 ["OVERVIEW" org-overview t]
14236 ["Refresh columns display" org-columns-redo t]
14237 "--"
14238 ["Quit" org-columns-quit t]))
14240 (defun org-columns-new-overlay (beg end &optional string face)
14241 "Create a new column overlay and add it to the list."
14242 (let ((ov (org-make-overlay beg end)))
14243 (org-overlay-put ov 'face (or face 'secondary-selection))
14244 (org-overlay-display ov string face)
14245 (push ov org-columns-overlays)
14246 ov))
14248 (defun org-columns-display-here (&optional props)
14249 "Overlay the current line with column display."
14250 (interactive)
14251 (let* ((fmt org-columns-current-fmt-compiled)
14252 (beg (point-at-bol))
14253 (level-face (save-excursion
14254 (beginning-of-line 1)
14255 (looking-at "\\(\\**\\)\\(\\* \\)")
14256 (org-get-level-face 2)))
14257 (color (list :foreground
14258 (face-attribute (or level-face 'default) :foreground)))
14259 props pom property ass width f string ov column)
14260 ;; Check if the entry is in another buffer.
14261 (unless props
14262 (if (eq major-mode 'org-agenda-mode)
14263 (setq pom (or (get-text-property (point) 'org-hd-marker)
14264 (get-text-property (point) 'org-marker))
14265 props (if pom (org-entry-properties pom) nil))
14266 (setq props (org-entry-properties nil))))
14267 ;; Walk the format
14268 (while (setq column (pop fmt))
14269 (setq property (car column)
14270 ass (if (equal property "ITEM")
14271 (cons "ITEM"
14272 (save-match-data
14273 (org-no-properties
14274 (org-remove-tabs
14275 (buffer-substring-no-properties
14276 (point-at-bol) (point-at-eol))))))
14277 (assoc property props))
14278 width (or (cdr (assoc property org-columns-current-maxwidths))
14279 (nth 2 column))
14280 f (format "%%-%d.%ds | " width width)
14281 string (format f (or (cdr ass) "")))
14282 ;; Create the overlay
14283 (org-unmodified
14284 (setq ov (org-columns-new-overlay
14285 beg (setq beg (1+ beg)) string
14286 (list color 'org-column)))
14287 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
14288 (org-overlay-put ov 'keymap org-columns-map)
14289 (org-overlay-put ov 'org-columns-key property)
14290 (org-overlay-put ov 'org-columns-value (cdr ass))
14291 (org-overlay-put ov 'org-columns-pom pom)
14292 (org-overlay-put ov 'org-columns-format f))
14293 (if (or (not (char-after beg))
14294 (equal (char-after beg) ?\n))
14295 (let ((inhibit-read-only t))
14296 (save-excursion
14297 (goto-char beg)
14298 (insert " ")))))
14299 ;; Make the rest of the line disappear.
14300 (org-unmodified
14301 (setq ov (org-columns-new-overlay beg (point-at-eol)))
14302 (org-overlay-put ov 'invisible t)
14303 (org-overlay-put ov 'keymap org-columns-map)
14304 (org-overlay-put ov 'intangible t)
14305 (push ov org-columns-overlays)
14306 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
14307 (org-overlay-put ov 'keymap org-columns-map)
14308 (push ov org-columns-overlays)
14309 (let ((inhibit-read-only t))
14310 (put-text-property (max (point-min) (1- (point-at-bol)))
14311 (min (point-max) (1+ (point-at-eol)))
14312 'read-only "Type `e' to edit property")))))
14314 (defvar org-previous-header-line-format nil
14315 "The header line format before column view was turned on.")
14316 (defvar org-columns-inhibit-recalculation nil
14317 "Inhibit recomputing of columns on column view startup.")
14319 (defvar header-line-format)
14320 (defun org-columns-display-here-title ()
14321 "Overlay the newline before the current line with the table title."
14322 (interactive)
14323 (let ((fmt org-columns-current-fmt-compiled)
14324 string (title "")
14325 property width f column str)
14326 (while (setq column (pop fmt))
14327 (setq property (car column)
14328 str (or (nth 1 column) property)
14329 width (or (cdr (assoc property org-columns-current-maxwidths))
14330 (nth 2 column))
14331 f (format "%%-%d.%ds | " width width)
14332 string (format f str)
14333 title (concat title string)))
14334 (setq title (concat
14335 (org-add-props " " nil 'display '(space :align-to 0))
14336 (org-add-props title nil 'face '(:weight bold :underline t))))
14337 (org-set-local 'org-previous-header-line-format header-line-format)
14338 (setq header-line-format title)))
14340 (defun org-columns-remove-overlays ()
14341 "Remove all currently active column overlays."
14342 (interactive)
14343 (when (marker-buffer org-columns-begin-marker)
14344 (with-current-buffer (marker-buffer org-columns-begin-marker)
14345 (when (local-variable-p 'org-previous-header-line-format)
14346 (setq header-line-format org-previous-header-line-format)
14347 (kill-local-variable 'org-previous-header-line-format))
14348 (move-marker org-columns-begin-marker nil)
14349 (move-marker org-columns-top-level-marker nil)
14350 (org-unmodified
14351 (mapc 'org-delete-overlay org-columns-overlays)
14352 (setq org-columns-overlays nil)
14353 (let ((inhibit-read-only t))
14354 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
14356 (defun org-columns-show-value ()
14357 "Show the full value of the property."
14358 (interactive)
14359 (let ((value (get-char-property (point) 'org-columns-value)))
14360 (message "Value is: %s" (or value ""))))
14362 (defun org-columns-quit ()
14363 "Remove the column overlays and in this way exit column editing."
14364 (interactive)
14365 (org-unmodified
14366 (org-columns-remove-overlays)
14367 (let ((inhibit-read-only t))
14368 ;; FIXME: is this safe???
14369 ;; or are there other reasons why there may be a read-only property????
14370 (remove-text-properties (point-min) (point-max) '(read-only t))))
14371 (when (eq major-mode 'org-agenda-mode)
14372 (message "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
14374 (defun org-columns-edit-value ()
14375 "Edit the value of the property at point in column view.
14376 Where possible, use the standard interface for changing this line."
14377 (interactive)
14378 (let* ((col (current-column))
14379 (key (get-char-property (point) 'org-columns-key))
14380 (value (get-char-property (point) 'org-columns-value))
14381 (bol (point-at-bol)) (eol (point-at-eol))
14382 (pom (or (get-text-property bol 'org-hd-marker)
14383 (point))) ; keep despite of compiler waring
14384 (line-overlays
14385 (delq nil (mapcar (lambda (x)
14386 (and (eq (overlay-buffer x) (current-buffer))
14387 (>= (overlay-start x) bol)
14388 (<= (overlay-start x) eol)
14390 org-columns-overlays)))
14391 nval eval allowed)
14392 (when (equal key "ITEM")
14393 (error "Cannot edit item headline from here"))
14395 (cond
14396 ((equal key "TODO")
14397 (setq eval '(org-with-point-at pom
14398 (let ((current-prefix-arg '(4))) (org-todo '(4))))))
14399 ((equal key "PRIORITY")
14400 (setq eval '(org-with-point-at pom
14401 (call-interactively 'org-priority))))
14402 ((equal key "TAGS")
14403 (setq eval '(org-with-point-at pom
14404 (let ((org-fast-tag-selection-single-key
14405 (if (eq org-fast-tag-selection-single-key 'expert)
14406 t org-fast-tag-selection-single-key)))
14407 (call-interactively 'org-set-tags)))))
14408 ((equal key "DEADLINE")
14409 (setq eval '(org-with-point-at pom
14410 (call-interactively 'org-deadline))))
14411 ((equal key "SCHEDULED")
14412 (setq eval '(org-with-point-at pom
14413 (call-interactively 'org-schedule))))
14415 (setq allowed (org-property-get-allowed-values pom key 'table))
14416 (if allowed
14417 (setq nval (completing-read "Value: " allowed nil t))
14418 (setq nval (read-string "Edit: " value)))
14419 (setq nval (org-trim nval))
14420 (when (not (equal nval value))
14421 (setq eval '(org-entry-put pom key nval)))))
14422 (when eval
14423 (let ((inhibit-read-only t))
14424 (remove-text-properties (1- bol) eol '(read-only t))
14425 (unwind-protect
14426 (progn
14427 (setq org-columns-overlays
14428 (org-delete-all line-overlays org-columns-overlays))
14429 (mapc 'org-delete-overlay line-overlays)
14430 (org-columns-eval eval))
14431 (org-columns-display-here))))
14432 (move-to-column col)
14433 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
14434 (org-columns-update key))))
14436 (defun org-columns-edit-allowed ()
14437 "Edit the list of allowed values for the current property."
14438 (interactive)
14439 (let* ((col (current-column))
14440 (key (get-char-property (point) 'org-columns-key))
14441 (key1 (concat key "_ALL"))
14442 (value (get-char-property (point) 'org-columns-value))
14443 (allowed (org-entry-get (point) key1 t))
14444 nval)
14445 (setq nval (read-string "Allowed: " allowed))
14446 (org-entry-put
14447 (cond ((marker-position org-entry-property-inherited-from)
14448 org-entry-property-inherited-from)
14449 ((marker-position org-columns-top-level-marker)
14450 org-columns-top-level-marker))
14451 key1 nval)))
14453 (defun org-columns-eval (form)
14454 (let (hidep)
14455 (save-excursion
14456 (beginning-of-line 1)
14457 (next-line 1)
14458 (setq hidep (org-on-heading-p 1)))
14459 (eval form)
14460 (and hidep (hide-entry))))
14462 (defun org-columns-previous-allowed-value ()
14463 "Switch to the previous allowed value for this column."
14464 (interactive)
14465 (org-columns-next-allowed-value t))
14467 (defun org-columns-next-allowed-value (&optional previous)
14468 "Switch to the next allowed value for this column."
14469 (interactive)
14470 (let* ((col (current-column))
14471 (key (get-char-property (point) 'org-columns-key))
14472 (value (get-char-property (point) 'org-columns-value))
14473 (bol (point-at-bol)) (eol (point-at-eol))
14474 (pom (or (get-text-property bol 'org-hd-marker)
14475 (point))) ; keep despite of compiler waring
14476 (line-overlays
14477 (delq nil (mapcar (lambda (x)
14478 (and (eq (overlay-buffer x) (current-buffer))
14479 (>= (overlay-start x) bol)
14480 (<= (overlay-start x) eol)
14482 org-columns-overlays)))
14483 (allowed (or (org-property-get-allowed-values pom key)
14484 (and (equal
14485 (nth 4 (assoc key org-columns-current-fmt-compiled))
14486 'checkbox) '("[ ]" "[X]"))))
14487 nval)
14488 (when (equal key "ITEM")
14489 (error "Cannot edit item headline from here"))
14490 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
14491 (error "Allowed values for this property have not been defined"))
14492 (if (member key '("SCHEDULED" "DEADLINE"))
14493 (setq nval (if previous 'earlier 'later))
14494 (if previous (setq allowed (reverse allowed)))
14495 (if (member value allowed)
14496 (setq nval (car (cdr (member value allowed)))))
14497 (setq nval (or nval (car allowed)))
14498 (if (equal nval value)
14499 (error "Only one allowed value for this property")))
14500 (let ((inhibit-read-only t))
14501 (remove-text-properties (1- bol) eol '(read-only t))
14502 (unwind-protect
14503 (progn
14504 (setq org-columns-overlays
14505 (org-delete-all line-overlays org-columns-overlays))
14506 (mapc 'org-delete-overlay line-overlays)
14507 (org-columns-eval '(org-entry-put pom key nval)))
14508 (org-columns-display-here)))
14509 (move-to-column col)
14510 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
14511 (org-columns-update key))))
14513 (defun org-verify-version (task)
14514 (cond
14515 ((eq task 'columns)
14516 (if (or (featurep 'xemacs)
14517 (< emacs-major-version 22))
14518 (error "Emacs 22 is required for the columns feature")))))
14520 (defun org-columns-get-format-and-top-level ()
14521 (let (fmt)
14522 (when (condition-case nil (org-back-to-heading) (error nil))
14523 (move-marker org-entry-property-inherited-from nil)
14524 (setq fmt (org-entry-get nil "COLUMNS" t)))
14525 (setq fmt (or fmt org-columns-default-format))
14526 (org-set-local 'org-columns-current-fmt fmt)
14527 (org-columns-compile-format fmt)
14528 (if (marker-position org-entry-property-inherited-from)
14529 (move-marker org-columns-top-level-marker
14530 org-entry-property-inherited-from)
14531 (move-marker org-columns-top-level-marker (point)))
14532 fmt))
14534 (defun org-columns ()
14535 "Turn on column view on an org-mode file."
14536 (interactive)
14537 (org-verify-version 'columns)
14538 (org-columns-remove-overlays)
14539 (move-marker org-columns-begin-marker (point))
14540 (let (beg end fmt cache maxwidths)
14541 (setq fmt (org-columns-get-format-and-top-level))
14542 (save-excursion
14543 (goto-char org-columns-top-level-marker)
14544 (setq beg (point))
14545 (unless org-columns-inhibit-recalculation
14546 (org-columns-compute-all))
14547 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
14548 (point-max)))
14549 (goto-char beg)
14550 ;; Get and cache the properties
14551 (while (re-search-forward (concat "^" outline-regexp) end t)
14552 (push (cons (org-current-line) (org-entry-properties)) cache))
14553 (when cache
14554 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
14555 (org-set-local 'org-columns-current-maxwidths maxwidths)
14556 (org-columns-display-here-title)
14557 (mapc (lambda (x)
14558 (goto-line (car x))
14559 (org-columns-display-here (cdr x)))
14560 cache)))))
14562 (defun org-columns-new (&optional prop title width op fmt)
14563 "Insert a new column, to the leeft o the current column."
14564 (interactive)
14565 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
14566 cell)
14567 (setq prop (completing-read
14568 "Property: " (mapcar 'list (org-buffer-property-keys t))
14569 nil nil prop))
14570 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
14571 (setq width (read-string "Column width: " (if width (number-to-string width))))
14572 (if (string-match "\\S-" width)
14573 (setq width (string-to-number width))
14574 (setq width nil))
14575 (setq fmt (completing-read "Summary [none]: "
14576 '(("none") ("add_numbers") ("add_times") ("checkbox"))
14577 nil t))
14578 (if (string-match "\\S-" fmt)
14579 (setq fmt (intern fmt))
14580 (setq fmt nil))
14581 (if (eq fmt 'none) (setq fmt nil))
14582 (if editp
14583 (progn
14584 (setcar editp prop)
14585 (setcdr editp (list title width nil fmt)))
14586 (setq cell (nthcdr (1- (current-column))
14587 org-columns-current-fmt-compiled))
14588 (setcdr cell (cons (list prop title width nil fmt)
14589 (cdr cell))))
14590 (org-columns-store-format)
14591 (org-columns-redo)))
14593 (defun org-columns-delete ()
14594 "Delete the column at point from columns view."
14595 (interactive)
14596 (let* ((n (current-column))
14597 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
14598 (when (y-or-n-p
14599 (format "Are you sure you want to remove column \"%s\"? " title))
14600 (setq org-columns-current-fmt-compiled
14601 (delq (nth n org-columns-current-fmt-compiled)
14602 org-columns-current-fmt-compiled))
14603 (org-columns-store-format)
14604 (org-columns-redo)
14605 (if (>= (current-column) (length org-columns-current-fmt-compiled))
14606 (backward-char 1)))))
14608 (defun org-columns-edit-attributes ()
14609 "Edit the attributes of the current column."
14610 (interactive)
14611 (let* ((n (current-column))
14612 (info (nth n org-columns-current-fmt-compiled)))
14613 (apply 'org-columns-new info)))
14615 (defun org-columns-widen (arg)
14616 "Make the column wider by ARG characters."
14617 (interactive "p")
14618 (let* ((n (current-column))
14619 (entry (nth n org-columns-current-fmt-compiled))
14620 (width (or (nth 2 entry)
14621 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
14622 (setq width (max 1 (+ width arg)))
14623 (setcar (nthcdr 2 entry) width)
14624 (org-columns-store-format)
14625 (org-columns-redo)))
14627 (defun org-columns-narrow (arg)
14628 "Make the column nrrower by ARG characters."
14629 (interactive "p")
14630 (org-columns-widen (- arg)))
14632 (defun org-columns-move-right ()
14633 "Swap this column with the one to the right."
14634 (interactive)
14635 (let* ((n (current-column))
14636 (cell (nthcdr n org-columns-current-fmt-compiled))
14638 (when (>= n (1- (length org-columns-current-fmt-compiled)))
14639 (error "Cannot shift this column further to the right"))
14640 (setq e (car cell))
14641 (setcar cell (car (cdr cell)))
14642 (setcdr cell (cons e (cdr (cdr cell))))
14643 (org-columns-store-format)
14644 (org-columns-redo)
14645 (forward-char 1)))
14647 (defun org-columns-move-left ()
14648 "Swap this column with the one to the left."
14649 (interactive)
14650 (let* ((n (current-column)))
14651 (when (= n 0)
14652 (error "Cannot shift this column further to the left"))
14653 (backward-char 1)
14654 (org-columns-move-right)
14655 (backward-char 1)))
14657 (defun org-columns-store-format ()
14658 "Store the text version of the current columns format in appropriate place.
14659 This is either in the COLUMNS property of the node starting the current column
14660 display, or in the #+COLUMNS line of the current buffer."
14661 (let (fmt)
14662 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
14663 (if (marker-position org-columns-top-level-marker)
14664 (save-excursion
14665 (goto-char org-columns-top-level-marker)
14666 (if (org-entry-get nil "COLUMNS")
14667 (org-entry-put nil "COLUMNS" fmt)
14668 (goto-char (point-min))
14669 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
14670 (replace-match (concat "#+COLUMNS: " fmt t t)))))
14671 (setq org-columns-current-fmt fmt))))
14673 (defvar org-overriding-columns-format nil
14674 "When set, overrides any other definition.")
14675 (defvar org-agenda-view-columns-initially nil
14676 "When set, switch to columns view immediately after creating the agenda.")
14678 (defun org-agenda-columns ()
14679 "Turn on column view in the agenda."
14680 (interactive)
14681 (org-verify-version 'columns)
14682 (org-columns-remove-overlays)
14683 (move-marker org-columns-begin-marker (point))
14684 (let (fmt cache maxwidths m)
14685 (cond
14686 ((and (local-variable-p 'org-overriding-columns-format)
14687 org-overriding-columns-format)
14688 (setq fmt org-overriding-columns-format))
14689 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
14690 (setq fmt (org-entry-get m "COLUMNS" t)))
14691 ((and (boundp 'org-columns-current-fmt)
14692 (local-variable-p 'org-columns-current-fmt)
14693 org-columns-current-fmt)
14694 (setq fmt org-columns-current-fmt))
14695 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
14696 (setq m (get-text-property m 'org-hd-marker))
14697 (setq fmt (org-entry-get m "COLUMNS" t))))
14698 (setq fmt (or fmt org-columns-default-format))
14699 (org-set-local 'org-columns-current-fmt fmt)
14700 (org-columns-compile-format fmt)
14701 (save-excursion
14702 ;; Get and cache the properties
14703 (goto-char (point-min))
14704 (while (not (eobp))
14705 (when (setq m (or (get-text-property (point) 'org-hd-marker)
14706 (get-text-property (point) 'org-marker)))
14707 (push (cons (org-current-line) (org-entry-properties m)) cache))
14708 (beginning-of-line 2))
14709 (when cache
14710 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
14711 (org-set-local 'org-columns-current-maxwidths maxwidths)
14712 (org-columns-display-here-title)
14713 (mapc (lambda (x)
14714 (goto-line (car x))
14715 (org-columns-display-here (cdr x)))
14716 cache)))))
14718 (defun org-columns-get-autowidth-alist (s cache)
14719 "Derive the maximum column widths from the format and the cache."
14720 (let ((start 0) rtn)
14721 (while (string-match "%\\([a-zA-Z]\\S-*\\)" s start)
14722 (push (cons (match-string 1 s) 1) rtn)
14723 (setq start (match-end 0)))
14724 (mapc (lambda (x)
14725 (setcdr x (apply 'max
14726 (mapcar
14727 (lambda (y)
14728 (length (or (cdr (assoc (car x) (cdr y))) " ")))
14729 cache))))
14730 rtn)
14731 rtn))
14733 (defun org-columns-compute-all ()
14734 "Compute all columns that have operators defined."
14735 (org-unmodified
14736 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
14737 (let ((columns org-columns-current-fmt-compiled) col)
14738 (while (setq col (pop columns))
14739 (when (nth 3 col)
14740 (save-excursion
14741 (org-columns-compute (car col)))))))
14743 (defun org-columns-update (property)
14744 "Recompute PROPERTY, and update the columns display for it."
14745 (org-columns-compute property)
14746 (let (fmt val pos)
14747 (save-excursion
14748 (mapc (lambda (ov)
14749 (when (equal (org-overlay-get ov 'org-columns-key) property)
14750 (setq pos (org-overlay-start ov))
14751 (goto-char pos)
14752 (when (setq val (cdr (assoc property
14753 (get-text-property (point-at-bol) 'org-summaries))))
14754 (setq fmt (org-overlay-get ov 'org-columns-format))
14755 (org-overlay-put ov 'display (format fmt val)))))
14756 org-columns-overlays))))
14758 (defun org-columns-compute (property)
14759 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
14760 (interactive)
14761 (let* ((re (concat "^" outline-regexp))
14762 (lmax 30) ; Does anyone use deeper levels???
14763 (lsum (make-vector lmax 0))
14764 (level 0)
14765 (ass (assoc property org-columns-current-fmt-compiled))
14766 (format (nth 4 ass))
14767 (beg org-columns-top-level-marker)
14768 last-level val end sumpos sum-alist sum str)
14769 (save-excursion
14770 ;; Find the region to compute
14771 (goto-char beg)
14772 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
14773 (goto-char end)
14774 ;; Walk the tree from the back and do the computations
14775 (while (re-search-backward re beg t)
14776 (setq sumpos (match-beginning 0)
14777 last-level level
14778 level (org-outline-level)
14779 val (org-entry-get nil property))
14780 (cond
14781 ((< level last-level)
14782 ;; put the sum of lower levels here as a property
14783 (setq sum (aref lsum last-level)
14784 str (org-column-number-to-string sum format)
14785 sum-alist (get-text-property sumpos 'org-summaries))
14786 (if (assoc property sum-alist)
14787 (setcdr (assoc property sum-alist) str)
14788 (push (cons property str) sum-alist)
14789 (org-unmodified
14790 (add-text-properties sumpos (1+ sumpos)
14791 (list 'org-summaries sum-alist))))
14792 (when val ;?????????????????????????????????? and force?????
14793 (org-entry-put nil property str))
14794 ;; add current to current level accumulator
14795 (aset lsum level (+ (aref lsum level) sum))
14796 ;; clear accumulators for deeper levels
14797 (loop for l from (1+ level) to (1- lmax) do (aset lsum l 0)))
14798 ((>= level last-level)
14799 ;; add what we have here to the accumulator for this level
14800 (aset lsum level (+ (aref lsum level)
14801 (org-column-string-to-number (or val "0") format))))
14802 (t (error "This should not happen")))))))
14804 (defun org-columns-redo ()
14805 "Construct the column display again."
14806 (interactive)
14807 (message "Recomputing columns...")
14808 (save-excursion
14809 (if (marker-position org-columns-begin-marker)
14810 (goto-char org-columns-begin-marker))
14811 (org-columns-remove-overlays)
14812 (if (org-mode-p)
14813 (call-interactively 'org-columns)
14814 (call-interactively 'org-agenda-columns)))
14815 (message "Recomputing columns...done"))
14817 (defun org-columns-not-in-agenda ()
14818 (if (eq major-mode 'org-agenda-mode)
14819 (error "This command is only allowed in Org-mode buffers")))
14822 (defun org-string-to-number (s)
14823 "Convert string to number, and interpret hh:mm:ss."
14824 (if (not (string-match ":" s))
14825 (string-to-number s)
14826 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
14827 (while l
14828 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
14829 sum)))
14831 (defun org-column-number-to-string (n fmt)
14832 "Convert a computed column number to a string value, according to FMT."
14833 (cond
14834 ((eq fmt 'add_times)
14835 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
14836 (format "%d:%02d" h m)))
14837 ((eq fmt 'checkbox)
14838 (cond ((= n (floor n)) "[X]")
14839 ((> n 1.) "[-]")
14840 (t "[ ]")))
14841 (t (number-to-string n))))
14843 (defun org-column-string-to-number (s fmt)
14844 "Convert a column value to a number that can be used for column computing."
14845 (cond
14846 ((string-match ":" s)
14847 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
14848 (while l
14849 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
14850 sum))
14851 ((eq fmt 'checkbox)
14852 (if (equal s "[X]") 1. 0.000001))
14853 (t (string-to-number s))))
14855 (defun org-columns-uncompile-format (cfmt)
14856 "Turn the compiled columns format back into a string representation."
14857 (let ((rtn "") e s prop title op width fmt)
14858 (while (setq e (pop cfmt))
14859 (setq prop (car e)
14860 title (nth 1 e)
14861 width (nth 2 e)
14862 op (nth 3 e)
14863 fmt (nth 4 e))
14864 (cond
14865 ((eq fmt 'add_times) (setq op ":"))
14866 ((eq fmt 'checkbox) (setq op "X"))
14867 ((eq fmt 'add_numbers) (setq op "+")))
14868 (if (equal title prop) (setq title nil))
14869 (setq s (concat "%" (if width (number-to-string width))
14870 prop
14871 (if title (concat "(" title ")"))
14872 (if op (concat "{" op "}"))))
14873 (setq rtn (concat rtn " " s)))
14874 (org-trim rtn)))
14876 (defun org-columns-compile-format (fmt)
14877 "FIXME"
14878 (let ((start 0) width prop title op f)
14879 (setq org-columns-current-fmt-compiled nil)
14880 (while (string-match "%\\([0-9]+\\)?\\([a-zA-Z_0-9]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*"
14881 fmt start)
14882 (setq start (match-end 0)
14883 width (match-string 1 fmt)
14884 prop (match-string 2 fmt)
14885 title (or (match-string 3 fmt) prop)
14886 op (match-string 4 fmt)
14887 f nil)
14888 (if width (setq width (string-to-number width)))
14889 (cond
14890 ((equal op "+") (setq f 'add_numbers))
14891 ((equal op ":") (setq f 'add_times))
14892 ((equal op "X") (setq f 'checkbox)))
14893 (push (list prop title width op f) org-columns-current-fmt-compiled))
14894 (setq org-columns-current-fmt-compiled
14895 (nreverse org-columns-current-fmt-compiled))))
14897 ;;;; Timestamps
14899 (defvar org-last-changed-timestamp nil)
14900 (defvar org-time-was-given) ; dynamically scoped parameter
14901 (defvar org-end-time-was-given) ; dynamically scoped parameter
14902 (defvar org-ts-what) ; dynamically scoped parameter
14904 (defun org-time-stamp (arg)
14905 "Prompt for a date/time and insert a time stamp.
14906 If the user specifies a time like HH:MM, or if this command is called
14907 with a prefix argument, the time stamp will contain date and time.
14908 Otherwise, only the date will be included. All parts of a date not
14909 specified by the user will be filled in from the current date/time.
14910 So if you press just return without typing anything, the time stamp
14911 will represent the current date/time. If there is already a timestamp
14912 at the cursor, it will be modified."
14913 (interactive "P")
14914 (let (org-time-was-given org-end-time-was-given time)
14915 (cond
14916 ((and (org-at-timestamp-p)
14917 (eq last-command 'org-time-stamp)
14918 (eq this-command 'org-time-stamp))
14919 (insert "--")
14920 (setq time (let ((this-command this-command))
14921 (org-read-date arg 'totime)))
14922 (org-insert-time-stamp time (or org-time-was-given arg)))
14923 ((org-at-timestamp-p)
14924 (setq time (let ((this-command this-command))
14925 (org-read-date arg 'totime)))
14926 (when (org-at-timestamp-p) ; just to get the match data
14927 (replace-match "")
14928 (setq org-last-changed-timestamp
14929 (org-insert-time-stamp
14930 time (or org-time-was-given arg)
14931 nil nil nil (list org-end-time-was-given))))
14932 (message "Timestamp updated"))
14934 (setq time (let ((this-command this-command))
14935 (org-read-date arg 'totime)))
14936 (org-insert-time-stamp time (or org-time-was-given arg)
14937 nil nil nil (list org-end-time-was-given))))))
14939 (defun org-time-stamp-inactive (&optional arg)
14940 "Insert an inactive time stamp.
14941 An inactive time stamp is enclosed in square brackets instead of angle
14942 brackets. It is inactive in the sense that it does not trigger agenda entries,
14943 does not link to the calendar and cannot be changed with the S-cursor keys.
14944 So these are more for recording a certain time/date."
14945 (interactive "P")
14946 (let (org-time-was-given org-end-time-was-given time)
14947 (setq time (org-read-date arg 'totime))
14948 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
14949 nil nil (list org-end-time-was-given))))
14951 (defvar org-date-ovl (org-make-overlay 1 1))
14952 (org-overlay-put org-date-ovl 'face 'org-warning)
14953 (org-detach-overlay org-date-ovl)
14955 (defvar org-ans1) ; dynamically scoped parameter
14956 (defvar org-ans2) ; dynamically scoped parameter
14958 (defvar org-plain-time-of-day-regexp) ; defined below
14959 (defun org-read-date (&optional with-time to-time from-string prompt)
14960 "Read a date and make things smooth for the user.
14961 The prompt will suggest to enter an ISO date, but you can also enter anything
14962 which will at least partially be understood by `parse-time-string'.
14963 Unrecognized parts of the date will default to the current day, month, year,
14964 hour and minute. For example,
14965 3-2-5 --> 2003-02-05
14966 feb 15 --> currentyear-02-15
14967 sep 12 9 --> 2009-09-12
14968 12:45 --> today 12:45
14969 22 sept 0:34 --> currentyear-09-22 0:34
14970 12 --> currentyear-currentmonth-12
14971 Fri --> nearest Friday (today or later)
14972 +4 --> four days from today (only if +N is the only thing given)
14973 etc.
14974 The function understands only English month and weekday abbreviations,
14975 but this can be configured with the variables `parse-time-months' and
14976 `parse-time-weekdays'.
14978 While prompting, a calendar is popped up - you can also select the
14979 date with the mouse (button 1). The calendar shows a period of three
14980 months. To scroll it to other months, use the keys `>' and `<'.
14981 If you don't like the calendar, turn it off with
14982 \(setq org-popup-calendar-for-date-prompt nil)
14984 With optional argument TO-TIME, the date will immediately be converted
14985 to an internal time.
14986 With an optional argument WITH-TIME, the prompt will suggest to also
14987 insert a time. Note that when WITH-TIME is not set, you can still
14988 enter a time, and this function will inform the calling routine about
14989 this change. The calling routine may then choose to change the format
14990 used to insert the time stamp into the buffer to include the time."
14991 (require 'parse-time)
14992 (let* ((org-time-stamp-rounding-minutes
14993 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
14994 (ct (org-current-time))
14995 (default-time
14996 ;; Default time is either today, or, when entering a range,
14997 ;; the range start.
14998 (if (save-excursion
14999 (re-search-backward
15000 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15001 (- (point) 20) t))
15002 (apply
15003 'encode-time
15004 (mapcar (lambda(x) (or x 0))
15005 (parse-time-string (match-string 1))))
15006 ct))
15007 (calendar-move-hook nil)
15008 (view-diary-entries-initially nil)
15009 (view-calendar-holidays-initially nil)
15010 (timestr (format-time-string
15011 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
15012 (prompt (concat (if prompt (concat prompt " ") "")
15013 (format "Date and/or time (default [%s]): " timestr)))
15014 ans (org-ans0 "") org-ans1 org-ans2 (deltadays 0)
15015 second minute hour day month year tl wday wday1 pm)
15017 (cond
15018 (from-string (setq ans from-string))
15019 (org-popup-calendar-for-date-prompt
15020 (save-excursion
15021 (save-window-excursion
15022 (calendar)
15023 (calendar-forward-day (- (time-to-days default-time)
15024 (calendar-absolute-from-gregorian
15025 (calendar-current-date))))
15026 (org-eval-in-calendar nil t)
15027 (let* ((old-map (current-local-map))
15028 (map (copy-keymap calendar-mode-map))
15029 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15030 (org-defkey map (kbd "RET") 'org-calendar-select)
15031 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
15032 'org-calendar-select-mouse)
15033 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
15034 'org-calendar-select-mouse)
15035 (org-defkey minibuffer-local-map [(meta shift left)]
15036 (lambda () (interactive)
15037 (org-eval-in-calendar '(calendar-backward-month 1))))
15038 (org-defkey minibuffer-local-map [(meta shift right)]
15039 (lambda () (interactive)
15040 (org-eval-in-calendar '(calendar-forward-month 1))))
15041 (org-defkey minibuffer-local-map [(shift up)]
15042 (lambda () (interactive)
15043 (org-eval-in-calendar '(calendar-backward-week 1))))
15044 (org-defkey minibuffer-local-map [(shift down)]
15045 (lambda () (interactive)
15046 (org-eval-in-calendar '(calendar-forward-week 1))))
15047 (org-defkey minibuffer-local-map [(shift left)]
15048 (lambda () (interactive)
15049 (org-eval-in-calendar '(calendar-backward-day 1))))
15050 (org-defkey minibuffer-local-map [(shift right)]
15051 (lambda () (interactive)
15052 (org-eval-in-calendar '(calendar-forward-day 1))))
15053 (org-defkey minibuffer-local-map ">"
15054 (lambda () (interactive)
15055 (org-eval-in-calendar '(scroll-calendar-left 1))))
15056 (org-defkey minibuffer-local-map "<"
15057 (lambda () (interactive)
15058 (org-eval-in-calendar '(scroll-calendar-right 1))))
15059 (unwind-protect
15060 (progn
15061 (use-local-map map)
15062 (setq org-ans0 (read-string prompt "" nil nil))
15063 ;; org-ans0: from prompt
15064 ;; org-ans1: from mouse click
15065 ;; org-ans2: from calendar motion
15066 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15067 (use-local-map old-map))))))
15068 (t ; Naked prompt only
15069 (setq ans (read-string prompt "" nil timestr))))
15070 (org-detach-overlay org-date-ovl)
15072 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" org-ans0)
15073 (setq deltadays (string-to-number ans) ans ""))
15075 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
15076 (when (string-match
15077 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15078 (setq year (if (match-end 2)
15079 (string-to-number (match-string 2 ans))
15080 (string-to-number (format-time-string "%Y")))
15081 month (string-to-number (match-string 3 ans))
15082 day (string-to-number (match-string 4 ans)))
15083 (if (< year 100) (setq year (+ 2000 year)))
15084 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15085 t nil ans)))
15086 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15087 ;; If there is a time with am/pm, and *no* time without it, we convert
15088 ;; so that matching will be successful.
15089 ;; FIXME: make this replace twice, so that we catch the end time.
15090 (when (and (not (string-match "[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15091 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15092 (setq hour (string-to-number (match-string 1 ans))
15093 minute (if (match-end 3) (string-to-number (match-string 3 ans)) 0)
15094 pm (equal ?p (string-to-char (downcase (match-string 4 ans)))))
15095 (if (and (= hour 12) (not pm))
15096 (setq hour 0)
15097 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15098 (setq ans (replace-match (format "%02d:%02d" hour minute) t t ans)))
15100 ;; Check if there is a time range
15101 (when (and (boundp 'org-end-time-was-given)
15102 (string-match org-plain-time-of-day-regexp ans)
15103 (match-end 8))
15104 (setq org-end-time-was-given (match-string 8 ans))
15105 (setq ans (concat (substring ans 0 (match-beginning 7))
15106 (substring ans (match-end 7)))))
15108 (setq tl (parse-time-string ans)
15109 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
15110 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
15111 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
15112 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
15113 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
15114 second (or (nth 0 tl) 0)
15115 wday (nth 6 tl))
15116 (setq day (+ day deltadays))
15117 (when (and wday (not (nth 3 tl)))
15118 ;; Weekday was given, but no day, so pick that day in the week
15119 ;; on or after the derived date.
15120 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15121 (unless (equal wday wday1)
15122 (setq day (+ day (% (- wday wday1 -7) 7)))))
15123 (if (and (boundp 'org-time-was-given)
15124 (nth 2 tl))
15125 (setq org-time-was-given t))
15126 (if (< year 100) (setq year (+ 2000 year)))
15127 (if to-time
15128 (encode-time second minute hour day month year)
15129 (if (or (nth 1 tl) (nth 2 tl))
15130 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
15131 (format "%04d-%02d-%02d" year month day)))))
15133 (defun org-eval-in-calendar (form &optional keepdate)
15134 "Eval FORM in the calendar window and return to current window.
15135 Also, store the cursor date in variable org-ans2."
15136 (let ((sw (selected-window)))
15137 (select-window (get-buffer-window "*Calendar*"))
15138 (eval form)
15139 (when (and (not keepdate) (calendar-cursor-to-date))
15140 (let* ((date (calendar-cursor-to-date))
15141 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15142 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15143 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15144 (select-window sw)
15145 ;; Update the prompt to show new default date
15146 (save-excursion
15147 (goto-char (point-min))
15148 (when (and org-ans2
15149 (re-search-forward "\\[[-0-9]+\\]" nil t)
15150 (get-text-property (match-end 0) 'field))
15151 (let ((inhibit-read-only t))
15152 (replace-match (concat "[" org-ans2 "]") t t)
15153 (add-text-properties (point-min) (1+ (match-end 0))
15154 (text-properties-at (1+ (point-min)))))))))
15156 (defun org-calendar-select ()
15157 "Return to `org-read-date' with the date currently selected.
15158 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15159 (interactive)
15160 (when (calendar-cursor-to-date)
15161 (let* ((date (calendar-cursor-to-date))
15162 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15163 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15164 (if (active-minibuffer-window) (exit-minibuffer))))
15166 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15167 "Insert a date stamp for the date given by the internal TIME.
15168 WITH-HM means, use the stamp format that includes the time of the day.
15169 INACTIVE means use square brackets instead of angular ones, so that the
15170 stamp will not contribute to the agenda.
15171 PRE and POST are optional strings to be inserted before and after the
15172 stamp.
15173 The command returns the inserted time stamp."
15174 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15175 stamp)
15176 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15177 (insert (or pre ""))
15178 (insert (setq stamp (format-time-string fmt time)))
15179 (when (listp extra)
15180 (setq extra (car extra))
15181 (if (and (stringp extra)
15182 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15183 (setq extra (format "-%02d:%02d"
15184 (string-to-number (match-string 1 extra))
15185 (string-to-number (match-string 2 extra))))
15186 (setq extra nil)))
15187 (when extra
15188 (backward-char 1)
15189 (insert extra)
15190 (forward-char 1))
15191 (insert (or post ""))
15192 stamp))
15194 (defun org-toggle-time-stamp-overlays ()
15195 "Toggle the use of custom time stamp formats."
15196 (interactive)
15197 (setq org-display-custom-times (not org-display-custom-times))
15198 (unless org-display-custom-times
15199 (let ((p (point-min)) (bmp (buffer-modified-p)))
15200 (while (setq p (next-single-property-change p 'display))
15201 (if (and (get-text-property p 'display)
15202 (eq (get-text-property p 'face) 'org-date))
15203 (remove-text-properties
15204 p (setq p (next-single-property-change p 'display))
15205 '(display t))))
15206 (set-buffer-modified-p bmp)))
15207 (if (featurep 'xemacs)
15208 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15209 (org-restart-font-lock)
15210 (setq org-table-may-need-update t)
15211 (if org-display-custom-times
15212 (message "Time stamps are overlayed with custom format")
15213 (message "Time stamp overlays removed")))
15215 (defun org-display-custom-time (beg end)
15216 "Overlay modified time stamp format over timestamp between BED and END."
15217 (let* ((ts (buffer-substring beg end))
15218 t1 w1 with-hm tf time str w2 (off 0))
15219 (save-match-data
15220 (setq t1 (org-parse-time-string ts t))
15221 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
15222 (setq off (- (match-end 0) (match-beginning 0)))))
15223 (setq end (- end off))
15224 (setq w1 (- end beg)
15225 with-hm (and (nth 1 t1) (nth 2 t1))
15226 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15227 time (org-fix-decoded-time t1)
15228 str (org-add-props
15229 (format-time-string
15230 (substring tf 1 -1) (apply 'encode-time time))
15231 nil 'mouse-face 'highlight)
15232 w2 (length str))
15233 (if (not (= w2 w1))
15234 (add-text-properties (1+ beg) (+ 2 beg)
15235 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15236 (if (featurep 'xemacs)
15237 (progn
15238 (put-text-property beg end 'invisible t)
15239 (put-text-property beg end 'end-glyph (make-glyph str)))
15240 (put-text-property beg end 'display str))))
15242 (defun org-translate-time (string)
15243 "Translate all timestamps in STRING to custom format.
15244 But do this only if the variable `org-display-custom-times' is set."
15245 (when org-display-custom-times
15246 (save-match-data
15247 (let* ((start 0)
15248 (re org-ts-regexp-both)
15249 t1 with-hm inactive tf time str beg end)
15250 (while (setq start (string-match re string start))
15251 (setq beg (match-beginning 0)
15252 end (match-end 0)
15253 t1 (save-match-data
15254 (org-parse-time-string (substring string beg end) t))
15255 with-hm (and (nth 1 t1) (nth 2 t1))
15256 inactive (equal (substring string beg (1+ beg)) "[")
15257 tf (funcall (if with-hm 'cdr 'car)
15258 org-time-stamp-custom-formats)
15259 time (org-fix-decoded-time t1)
15260 str (format-time-string
15261 (concat
15262 (if inactive "[" "<") (substring tf 1 -1)
15263 (if inactive "]" ">"))
15264 (apply 'encode-time time))
15265 string (replace-match str t t string)
15266 start (+ start (length str)))))))
15267 string)
15269 (defun org-fix-decoded-time (time)
15270 "Set 0 instead of nil for the first 6 elements of time.
15271 Don't touch the rest."
15272 (let ((n 0))
15273 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15275 (defun org-days-to-time (timestamp-string)
15276 "Difference between TIMESTAMP-STRING and now in days."
15277 (- (time-to-days (org-time-string-to-time timestamp-string))
15278 (time-to-days (current-time))))
15280 (defun org-deadline-close (timestamp-string &optional ndays)
15281 "Is the time in TIMESTAMP-STRING close to the current date?"
15282 (and (< (org-days-to-time timestamp-string)
15283 (or ndays org-deadline-warning-days))
15284 (not (org-entry-is-done-p))))
15286 (defun org-calendar-select-mouse (ev)
15287 "Return to `org-read-date' with the date currently selected.
15288 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15289 (interactive "e")
15290 (mouse-set-point ev)
15291 (when (calendar-cursor-to-date)
15292 (let* ((date (calendar-cursor-to-date))
15293 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15294 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15295 (if (active-minibuffer-window) (exit-minibuffer))))
15297 (defun org-check-deadlines (ndays)
15298 "Check if there are any deadlines due or past due.
15299 A deadline is considered due if it happens within `org-deadline-warning-days'
15300 days from today's date. If the deadline appears in an entry marked DONE,
15301 it is not shown. The prefix arg NDAYS can be used to test that many
15302 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15303 (interactive "P")
15304 (let* ((org-warn-days
15305 (cond
15306 ((equal ndays '(4)) 100000)
15307 (ndays (prefix-numeric-value ndays))
15308 (t org-deadline-warning-days)))
15309 (case-fold-search nil)
15310 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15311 (callback
15312 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15314 (message "%d deadlines past-due or due within %d days"
15315 (org-occur regexp nil callback)
15316 org-warn-days)))
15318 (defun org-evaluate-time-range (&optional to-buffer)
15319 "Evaluate a time range by computing the difference between start and end.
15320 Normally the result is just printed in the echo area, but with prefix arg
15321 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15322 If the time range is actually in a table, the result is inserted into the
15323 next column.
15324 For time difference computation, a year is assumed to be exactly 365
15325 days in order to avoid rounding problems."
15326 (interactive "P")
15328 (org-clock-update-time-maybe)
15329 (save-excursion
15330 (unless (org-at-date-range-p)
15331 (goto-char (point-at-bol))
15332 (re-search-forward org-tr-regexp (point-at-eol) t))
15333 (if (not (org-at-date-range-p))
15334 (error "Not at a time-stamp range, and none found in current line")))
15335 (let* ((ts1 (match-string 1))
15336 (ts2 (match-string 2))
15337 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15338 (match-end (match-end 0))
15339 (time1 (org-time-string-to-time ts1))
15340 (time2 (org-time-string-to-time ts2))
15341 (t1 (time-to-seconds time1))
15342 (t2 (time-to-seconds time2))
15343 (diff (abs (- t2 t1)))
15344 (negative (< (- t2 t1) 0))
15345 ;; (ys (floor (* 365 24 60 60)))
15346 (ds (* 24 60 60))
15347 (hs (* 60 60))
15348 (fy "%dy %dd %02d:%02d")
15349 (fy1 "%dy %dd")
15350 (fd "%dd %02d:%02d")
15351 (fd1 "%dd")
15352 (fh "%02d:%02d")
15353 y d h m align)
15354 (if havetime
15355 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15357 d (floor (/ diff ds)) diff (mod diff ds)
15358 h (floor (/ diff hs)) diff (mod diff hs)
15359 m (floor (/ diff 60)))
15360 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15362 d (floor (+ (/ diff ds) 0.5))
15363 h 0 m 0))
15364 (if (not to-buffer)
15365 (message (org-make-tdiff-string y d h m))
15366 (when (org-at-table-p)
15367 (goto-char match-end)
15368 (setq align t)
15369 (and (looking-at " *|") (goto-char (match-end 0))))
15370 (if (looking-at
15371 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15372 (replace-match ""))
15373 (if negative (insert " -"))
15374 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15375 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15376 (insert " " (format fh h m))))
15377 (if align (org-table-align))
15378 (message "Time difference inserted")))))
15380 (defun org-make-tdiff-string (y d h m)
15381 (let ((fmt "")
15382 (l nil))
15383 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15384 l (push y l)))
15385 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15386 l (push d l)))
15387 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15388 l (push h l)))
15389 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15390 l (push m l)))
15391 (apply 'format fmt (nreverse l))))
15393 (defun org-time-string-to-time (s)
15394 (apply 'encode-time (org-parse-time-string s)))
15396 (defun org-time-string-to-absolute (s &optional daynr)
15397 "Convert a time stamp to an absolute day number.
15398 If there is a specifyer for a cyclic time stamp, get the closest date to
15399 DAYNR."
15400 (cond
15401 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15402 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15403 daynr
15404 (+ daynr 1000)))
15405 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15406 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15407 (time-to-days (current-time))) (match-string 0 s)))
15408 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15410 (defun org-calendar-holiday ()
15411 "List of holidays, for Diary display in Org-mode."
15412 (let ((hl (check-calendar-holidays date)))
15413 (if hl (mapconcat 'identity hl "; "))))
15415 (defun org-diary-sexp-entry (sexp entry date)
15416 "Process a SEXP diary ENTRY for DATE."
15417 (require 'diary-lib)
15418 (let ((result (if calendar-debug-sexp
15419 (let ((stack-trace-on-error t))
15420 (eval (car (read-from-string sexp))))
15421 (condition-case nil
15422 (eval (car (read-from-string sexp)))
15423 (error
15424 (beep)
15425 (message "Bad sexp at line %d in %s: %s"
15426 (org-current-line)
15427 (buffer-file-name) sexp)
15428 (sleep-for 2))))))
15429 (cond ((stringp result) result)
15430 ((and (consp result)
15431 (stringp (cdr result))) (cdr result))
15432 (result entry)
15433 (t nil))))
15435 (defun org-diary-to-ical-string (frombuf)
15436 "FIXME"
15437 (let* ((tmpdir (if (featurep 'xemacs)
15438 (temp-directory)
15439 temporary-file-directory))
15440 (tmpfile (make-temp-name
15441 (expand-file-name "orgics" tmpdir)))
15442 buf rtn b e)
15443 (save-excursion
15444 (set-buffer frombuf)
15445 (icalendar-export-region (point-min) (point-max) tmpfile)
15446 (setq buf (find-buffer-visiting tmpfile))
15447 (set-buffer buf)
15448 (goto-char (point-min))
15449 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15450 (setq b (match-beginning 0)))
15451 (goto-char (point-max))
15452 (if (re-search-backward "^END:VEVENT" nil t)
15453 (setq e (match-end 0)))
15454 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15455 (kill-buffer buf)
15456 (kill-buffer frombuf)
15457 (delete-file tmpfile)
15458 rtn))
15460 (defun org-closest-date (start current change)
15461 "Find the date closest to CURRENT that is consistent with START and CHANGE."
15462 ;; Make the proper lists from the dates
15463 (catch 'exit
15464 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15465 dn dw sday cday n1 n2
15466 d m y y1 y2 date1 date2 nmonths nm ny m2)
15468 (setq start (org-date-to-gregorian start)
15469 current (org-date-to-gregorian
15470 (if org-agenda-repeating-timestamp-show-all
15471 current
15472 (time-to-days (current-time))))
15473 sday (calendar-absolute-from-gregorian start)
15474 cday (calendar-absolute-from-gregorian current))
15476 (if (<= cday sday) (throw 'exit sday))
15478 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15479 (setq dn (string-to-number (match-string 1 change))
15480 dw (cdr (assoc (match-string 2 change) a1)))
15481 (error "Invalid change specifyer: %s" change))
15482 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15483 (cond
15484 ((eq dw 'day)
15485 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15486 n2 (+ n1 dn)))
15487 ((eq dw 'year)
15488 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15489 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15490 (setq date1 (list m d y1)
15491 n1 (calendar-absolute-from-gregorian date1)
15492 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15493 n2 (calendar-absolute-from-gregorian date2)))
15494 ((eq dw 'month)
15495 ;; approx number of month between the tow dates
15496 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15497 ;; How often does dn fit in there?
15498 (setq d (nth 1 start) m (car start) y (nth 2 start)
15499 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15500 m (+ m nm)
15501 ny (floor (/ m 12))
15502 y (+ y ny)
15503 m (- m (* ny 12)))
15504 (while (> m 12) (setq m (- m 12) y (1+ y)))
15505 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15506 (setq m2 (+ m dn) y2 y)
15507 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15508 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15509 (while (< n2 cday)
15510 (setq n1 n2 m m2 y y2)
15511 (setq m2 (+ m dn) y2 y)
15512 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15513 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15515 (if org-agenda-repeating-timestamp-show-all
15516 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
15517 (if (= cday n1) n1 n2)))))
15519 (defun org-date-to-gregorian (date)
15520 "Turn any specification of DATE into a gregorian date for the calendar."
15521 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15522 ((and (listp date) (= (length date) 3)) date)
15523 ((stringp date)
15524 (setq date (org-parse-time-string date))
15525 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15526 ((listp date)
15527 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15529 (defun org-parse-time-string (s &optional nodefault)
15530 "Parse the standard Org-mode time string.
15531 This should be a lot faster than the normal `parse-time-string'.
15532 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15533 hour and minute fields will be nil if not given."
15534 (if (string-match org-ts-regexp0 s)
15535 (list 0
15536 (if (or (match-beginning 8) (not nodefault))
15537 (string-to-number (or (match-string 8 s) "0")))
15538 (if (or (match-beginning 7) (not nodefault))
15539 (string-to-number (or (match-string 7 s) "0")))
15540 (string-to-number (match-string 4 s))
15541 (string-to-number (match-string 3 s))
15542 (string-to-number (match-string 2 s))
15543 nil nil nil)
15544 (make-list 9 0)))
15546 (defun org-timestamp-up (&optional arg)
15547 "Increase the date item at the cursor by one.
15548 If the cursor is on the year, change the year. If it is on the month or
15549 the day, change that.
15550 With prefix ARG, change by that many units."
15551 (interactive "p")
15552 (org-timestamp-change (prefix-numeric-value arg)))
15554 (defun org-timestamp-down (&optional arg)
15555 "Decrease the date item at the cursor by one.
15556 If the cursor is on the year, change the year. If it is on the month or
15557 the day, change that.
15558 With prefix ARG, change by that many units."
15559 (interactive "p")
15560 (org-timestamp-change (- (prefix-numeric-value arg))))
15562 (defun org-timestamp-up-day (&optional arg)
15563 "Increase the date in the time stamp by one day.
15564 With prefix ARG, change that many days."
15565 (interactive "p")
15566 (if (and (not (org-at-timestamp-p t))
15567 (org-on-heading-p))
15568 (org-todo 'up)
15569 (org-timestamp-change (prefix-numeric-value arg) 'day)))
15571 (defun org-timestamp-down-day (&optional arg)
15572 "Decrease the date in the time stamp by one day.
15573 With prefix ARG, change that many days."
15574 (interactive "p")
15575 (if (and (not (org-at-timestamp-p t))
15576 (org-on-heading-p))
15577 (org-todo 'down)
15578 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
15580 (defsubst org-pos-in-match-range (pos n)
15581 (and (match-beginning n)
15582 (<= (match-beginning n) pos)
15583 (>= (match-end n) pos)))
15585 (defun org-at-timestamp-p (&optional inactive-ok)
15586 "Determine if the cursor is in or at a timestamp."
15587 (interactive)
15588 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15589 (pos (point))
15590 (ans (or (looking-at tsr)
15591 (save-excursion
15592 (skip-chars-backward "^[<\n\r\t")
15593 (if (> (point) 1) (backward-char 1))
15594 (and (looking-at tsr)
15595 (> (- (match-end 0) pos) -1))))))
15596 (and (boundp 'org-ts-what)
15597 (setq org-ts-what
15598 (cond
15599 ((org-pos-in-match-range pos 2) 'year)
15600 ((org-pos-in-match-range pos 3) 'month)
15601 ((org-pos-in-match-range pos 7) 'hour)
15602 ((org-pos-in-match-range pos 8) 'minute)
15603 ((or (org-pos-in-match-range pos 4)
15604 (org-pos-in-match-range pos 5)) 'day)
15605 ((and (> pos (or (match-end 8) (match-end 5)))
15606 (< pos (match-end 0)))
15607 (- pos (or (match-end 8) (match-end 5))))
15608 (t 'day))))
15609 ans))
15611 (defun org-timestamp-change (n &optional what)
15612 "Change the date in the time stamp at point.
15613 The date will be changed by N times WHAT. WHAT can be `day', `month',
15614 `year', `minute', `second'. If WHAT is not given, the cursor position
15615 in the timestamp determines what will be changed."
15616 (let ((pos (point))
15617 with-hm inactive
15618 org-ts-what
15619 extra
15620 ts time time0)
15621 (if (not (org-at-timestamp-p t))
15622 (error "Not at a timestamp"))
15623 (if (and (not what) (not (eq org-ts-what 'day))
15624 org-display-custom-times
15625 (get-text-property (point) 'display)
15626 (not (get-text-property (1- (point)) 'display)))
15627 (setq org-ts-what 'day))
15628 (setq org-ts-what (or what org-ts-what)
15629 inactive (= (char-after (match-beginning 0)) ?\[)
15630 ts (match-string 0))
15631 (replace-match "")
15632 (if (string-match
15633 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
15635 (setq extra (match-string 1 ts)))
15636 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15637 (setq with-hm t))
15638 (setq time0 (org-parse-time-string ts))
15639 (setq time
15640 (apply 'encode-time
15641 (append
15642 (list (or (car time0) 0))
15643 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
15644 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
15645 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
15646 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
15647 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
15648 (nthcdr 6 time0))))
15649 (when (integerp org-ts-what)
15650 (setq extra (org-modify-ts-extra extra org-ts-what n)))
15651 (if (eq what 'calendar)
15652 (let ((cal-date
15653 (save-excursion
15654 (save-match-data
15655 (set-buffer "*Calendar*")
15656 (calendar-cursor-to-date)))))
15657 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15658 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15659 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15660 (setcar time0 (or (car time0) 0))
15661 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15662 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
15663 (setq time (apply 'encode-time time0))))
15664 (setq org-last-changed-timestamp
15665 (org-insert-time-stamp time with-hm inactive nil nil extra))
15666 (org-clock-update-time-maybe)
15667 (goto-char pos)
15668 ;; Try to recenter the calendar window, if any
15669 (if (and org-calendar-follow-timestamp-change
15670 (get-buffer-window "*Calendar*" t)
15671 (memq org-ts-what '(day month year)))
15672 (org-recenter-calendar (time-to-days time)))))
15674 (defun org-modify-ts-extra (s pos n)
15675 "FIXME"
15676 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15677 ng h m new)
15678 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15679 (cond
15680 ((or (org-pos-in-match-range pos 2)
15681 (org-pos-in-match-range pos 3))
15682 (setq m (string-to-number (match-string 3 s))
15683 h (string-to-number (match-string 2 s)))
15684 (if (org-pos-in-match-range pos 2)
15685 (setq h (+ h n))
15686 (setq m (+ m n)))
15687 (if (< m 0) (setq m (+ m 60) h (1- h)))
15688 (if (> m 59) (setq m (- m 60) h (1+ h)))
15689 (setq h (min 24 (max 0 h)))
15690 (setq ng 1 new (format "-%02d:%02d" h m)))
15691 ((org-pos-in-match-range pos 6)
15692 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15693 ((org-pos-in-match-range pos 5)
15694 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
15696 (when ng
15697 (setq s (concat
15698 (substring s 0 (match-beginning ng))
15700 (substring s (match-end ng))))))
15703 (defun org-recenter-calendar (date)
15704 "If the calendar is visible, recenter it to DATE."
15705 (let* ((win (selected-window))
15706 (cwin (get-buffer-window "*Calendar*" t))
15707 (calendar-move-hook nil))
15708 (when cwin
15709 (select-window cwin)
15710 (calendar-goto-date (if (listp date) date
15711 (calendar-gregorian-from-absolute date)))
15712 (select-window win))))
15714 (defun org-goto-calendar (&optional arg)
15715 "Go to the Emacs calendar at the current date.
15716 If there is a time stamp in the current line, go to that date.
15717 A prefix ARG can be used to force the current date."
15718 (interactive "P")
15719 (let ((tsr org-ts-regexp) diff
15720 (calendar-move-hook nil)
15721 (view-calendar-holidays-initially nil)
15722 (view-diary-entries-initially nil))
15723 (if (or (org-at-timestamp-p)
15724 (save-excursion
15725 (beginning-of-line 1)
15726 (looking-at (concat ".*" tsr))))
15727 (let ((d1 (time-to-days (current-time)))
15728 (d2 (time-to-days
15729 (org-time-string-to-time (match-string 1)))))
15730 (setq diff (- d2 d1))))
15731 (calendar)
15732 (calendar-goto-today)
15733 (if (and diff (not arg)) (calendar-forward-day diff))))
15735 (defun org-date-from-calendar ()
15736 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15737 If there is already a time stamp at the cursor position, update it."
15738 (interactive)
15739 (org-timestamp-change 0 'calendar))
15741 ;;; The clock for measuring work time.
15743 (defvar org-mode-line-string "")
15744 (put 'org-mode-line-string 'risky-local-variable t)
15746 (defvar org-mode-line-timer nil)
15747 (defvar org-clock-heading "")
15748 (defvar org-clock-start-time "")
15750 (defun org-update-mode-line ()
15751 (let* ((delta (- (time-to-seconds (current-time))
15752 (time-to-seconds org-clock-start-time)))
15753 (h (floor delta 3600))
15754 (m (floor (- delta (* 3600 h)) 60)))
15755 (setq org-mode-line-string
15756 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
15757 'help-echo "Org-mode clock is running"))
15758 (force-mode-line-update)))
15760 (defvar org-clock-marker (make-marker)
15761 "Marker recording the last clock-in.")
15762 (defvar org-clock-mode-line-entry nil
15763 "Information for the modeline about the running clock.")
15765 (defun org-clock-in ()
15766 "Start the clock on the current item.
15767 If necessary, clock-out of the currently active clock."
15768 (interactive)
15769 (org-clock-out t)
15770 (let (ts)
15771 (save-excursion
15772 (org-back-to-heading t)
15773 (if (looking-at org-todo-line-regexp)
15774 (setq org-clock-heading (match-string 3))
15775 (setq org-clock-heading "???"))
15776 (setq org-clock-heading (propertize org-clock-heading 'face nil))
15777 (beginning-of-line 2)
15778 (while
15779 (or (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
15780 (not (equal (match-string 1) org-clock-string)))
15781 (and (looking-at "[ \t]*:PROPERTIES:")
15782 (not org-insert-labeled-timestamps-before-properties-drawer)))
15783 ;; Scheduling info, or properties drawer, move one line further
15784 (beginning-of-line 2)
15785 (or (bolp) (newline)))
15786 (insert "\n") (backward-char 1)
15787 (indent-relative)
15788 (insert org-clock-string " ")
15789 (setq org-clock-start-time (current-time))
15790 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
15791 (move-marker org-clock-marker (point) (buffer-base-buffer))
15792 (or global-mode-string (setq global-mode-string '("")))
15793 (or (memq 'org-mode-line-string global-mode-string)
15794 (setq global-mode-string
15795 (append global-mode-string '(org-mode-line-string))))
15796 (org-update-mode-line)
15797 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
15798 (message "Clock started at %s" ts))))
15800 (defun org-clock-out (&optional fail-quietly)
15801 "Stop the currently running clock.
15802 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
15803 (interactive)
15804 (catch 'exit
15805 (if (not (marker-buffer org-clock-marker))
15806 (if fail-quietly (throw 'exit t) (error "No active clock")))
15807 (let (ts te s h m)
15808 (save-excursion
15809 (set-buffer (marker-buffer org-clock-marker))
15810 (goto-char org-clock-marker)
15811 (beginning-of-line 1)
15812 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
15813 (equal (match-string 1) org-clock-string))
15814 (setq ts (match-string 2))
15815 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
15816 (goto-char (match-end 0))
15817 (delete-region (point) (point-at-eol))
15818 (insert "--")
15819 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
15820 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
15821 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
15822 h (floor (/ s 3600))
15823 s (- s (* 3600 h))
15824 m (floor (/ s 60))
15825 s (- s (* 60 s)))
15826 (insert " => " (format "%2d:%02d" h m))
15827 (move-marker org-clock-marker nil)
15828 (org-add-log-maybe 'clock-out)
15829 (when org-mode-line-timer
15830 (cancel-timer org-mode-line-timer)
15831 (setq org-mode-line-timer nil))
15832 (setq global-mode-string
15833 (delq 'org-mode-line-string global-mode-string))
15834 (force-mode-line-update)
15835 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
15837 (defun org-clock-cancel ()
15838 "Cancel the running clock be removing the start timestamp."
15839 (interactive)
15840 (if (not (marker-buffer org-clock-marker))
15841 (error "No active clock"))
15842 (save-excursion
15843 (set-buffer (marker-buffer org-clock-marker))
15844 (goto-char org-clock-marker)
15845 (delete-region (1- (point-at-bol)) (point-at-eol)))
15846 (message "Clock canceled"))
15848 (defvar org-clock-file-total-minutes nil
15849 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
15850 (make-variable-buffer-local 'org-clock-file-total-minutes)
15852 (defun org-clock-sum (&optional tstart tend)
15853 "Sum the times for each subtree.
15854 Puts the resulting times in minutes as a text property on each headline."
15855 (interactive)
15856 (let* ((bmp (buffer-modified-p))
15857 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
15858 org-clock-string
15859 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
15860 (lmax 30)
15861 (ltimes (make-vector lmax 0))
15862 (t1 0)
15863 (level 0)
15864 ts te dt
15865 time)
15866 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
15867 (save-excursion
15868 (goto-char (point-max))
15869 (while (re-search-backward re nil t)
15870 (cond
15871 ((match-end 2)
15872 ;; Two time stamps
15873 (setq ts (match-string 2)
15874 te (match-string 3)
15875 ts (time-to-seconds
15876 (apply 'encode-time (org-parse-time-string ts)))
15877 te (time-to-seconds
15878 (apply 'encode-time (org-parse-time-string te)))
15879 ts (if tstart (max ts tstart) ts)
15880 te (if tend (min te tend) te)
15881 dt (- te ts)
15882 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
15883 ((match-end 4)
15884 ;; A naket time
15885 (setq t1 (+ t1 (string-to-number (match-string 5))
15886 (* 60 (string-to-number (match-string 4))))))
15887 (t ;; A headline
15888 (setq level (- (match-end 1) (match-beginning 1)))
15889 (when (or (> t1 0) (> (aref ltimes level) 0))
15890 (loop for l from 0 to level do
15891 (aset ltimes l (+ (aref ltimes l) t1)))
15892 (setq t1 0 time (aref ltimes level))
15893 (loop for l from level to (1- lmax) do
15894 (aset ltimes l 0))
15895 (goto-char (match-beginning 0))
15896 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
15897 (setq org-clock-file-total-minutes (aref ltimes 0)))
15898 (set-buffer-modified-p bmp)))
15900 (defun org-clock-display (&optional total-only)
15901 "Show subtree times in the entire buffer.
15902 If TOTAL-ONLY is non-nil, only show the total time for the entire file
15903 in the echo area."
15904 (interactive)
15905 (org-remove-clock-overlays)
15906 (let (time h m p)
15907 (org-clock-sum)
15908 (unless total-only
15909 (save-excursion
15910 (goto-char (point-min))
15911 (while (setq p (next-single-property-change (point) :org-clock-minutes))
15912 (goto-char p)
15913 (when (setq time (get-text-property p :org-clock-minutes))
15914 (org-put-clock-overlay time (funcall outline-level))))
15915 (setq h (/ org-clock-file-total-minutes 60)
15916 m (- org-clock-file-total-minutes (* 60 h)))
15917 ;; Arrange to remove the overlays upon next change.
15918 (when org-remove-highlights-with-change
15919 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
15920 nil 'local))))
15921 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
15923 (defvar org-clock-overlays nil)
15924 (make-variable-buffer-local 'org-clock-overlays)
15926 (defun org-put-clock-overlay (time &optional level)
15927 "Put an overlays on the current line, displaying TIME.
15928 If LEVEL is given, prefix time with a corresponding number of stars.
15929 This creates a new overlay and stores it in `org-clock-overlays', so that it
15930 will be easy to remove."
15931 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
15932 (l (if level (org-get-legal-level level 0) 0))
15933 (off 0)
15934 ov tx)
15935 (move-to-column c)
15936 (unless (eolp) (skip-chars-backward "^ \t"))
15937 (skip-chars-backward " \t")
15938 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
15939 tx (concat (buffer-substring (1- (point)) (point))
15940 (make-string (+ off (max 0 (- c (current-column)))) ?.)
15941 (org-add-props (format "%s %2d:%02d%s"
15942 (make-string l ?*) h m
15943 (make-string (- 10 l) ?\ ))
15944 '(face secondary-selection))
15945 ""))
15946 (if (not (featurep 'xemacs))
15947 (org-overlay-put ov 'display tx)
15948 (org-overlay-put ov 'invisible t)
15949 (org-overlay-put ov 'end-glyph (make-glyph tx)))
15950 (push ov org-clock-overlays)))
15952 (defun org-remove-clock-overlays (&optional beg end noremove)
15953 "Remove the occur highlights from the buffer.
15954 BEG and END are ignored. If NOREMOVE is nil, remove this function
15955 from the `before-change-functions' in the current buffer."
15956 (interactive)
15957 (unless org-inhibit-highlight-removal
15958 (mapc 'org-delete-overlay org-clock-overlays)
15959 (setq org-clock-overlays nil)
15960 (unless noremove
15961 (remove-hook 'before-change-functions
15962 'org-remove-clock-overlays 'local))))
15964 (defun org-clock-out-if-current ()
15965 "Clock out if the current entry contains the running clock.
15966 This is used to stop the clock after a TODO entry is marked DONE,
15967 and is only done if the variable `org-clock-out-when-done' is not nil."
15968 (when (and org-clock-out-when-done
15969 (member state org-done-keywords)
15970 (equal (marker-buffer org-clock-marker) (current-buffer))
15971 (< (point) org-clock-marker)
15972 (> (save-excursion (outline-next-heading) (point))
15973 org-clock-marker))
15974 ;; Clock out, but don't accept a logging message for this.
15975 (let ((org-log-done (if (and (listp org-log-done)
15976 (member 'clock-out org-log-done))
15977 '(done)
15978 org-log-done)))
15979 (org-clock-out))))
15981 (add-hook 'org-after-todo-state-change-hook
15982 'org-clock-out-if-current)
15984 (defun org-check-running-clock ()
15985 "Check if the current buffer contains the running clock.
15986 If yes, offer to stop it and to save the buffer with the changes."
15987 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
15988 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
15989 (buffer-name))))
15990 (org-clock-out)
15991 (when (y-or-n-p "Save changed buffer?")
15992 (save-buffer))))
15994 (defun org-clock-report ()
15995 "Create a table containing a report about clocked time.
15996 If the buffer contains lines
15997 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
15999 #+END: clocktable
16000 then the table will be inserted between these lines, replacing whatever
16001 is was there before. If these lines are not in the buffer, the table
16002 is inserted at point, surrounded by the special lines.
16003 The BEGIN line can contain parameters. Allowed are:
16004 :maxlevel The maximum level to be included in the table. Default is 3.
16005 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
16006 (interactive)
16007 (org-remove-clock-overlays)
16008 (unless (org-find-dblock "clocktable")
16009 (org-create-dblock (list :name "clocktable"
16010 :maxlevel 2 :emphasize nil)))
16011 (org-update-dblock))
16013 (defun org-clock-update-time-maybe ()
16014 "If this is a CLOCK line, update it and return t.
16015 Otherwise, return nil."
16016 (interactive)
16017 (save-excursion
16018 (beginning-of-line 1)
16019 (skip-chars-forward " \t")
16020 (when (looking-at org-clock-string)
16021 (let ((re (concat "[ \t]*" org-clock-string
16022 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
16023 "\\([ \t]*=>.*\\)?"))
16024 ts te h m s)
16025 (if (not (looking-at re))
16027 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
16028 (end-of-line 1)
16029 (setq ts (match-string 1)
16030 te (match-string 2))
16031 (setq s (- (time-to-seconds
16032 (apply 'encode-time (org-parse-time-string te)))
16033 (time-to-seconds
16034 (apply 'encode-time (org-parse-time-string ts))))
16035 h (floor (/ s 3600))
16036 s (- s (* 3600 h))
16037 m (floor (/ s 60))
16038 s (- s (* 60 s)))
16039 (insert " => " (format "%2d:%02d" h m))
16040 t)))))
16042 (defun org-clock-special-range (key &optional time as-strings)
16043 "Return two times bordering a special time range.
16044 Key is a symbol specifying the range and can be one of `today', `yesterday',
16045 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
16046 A week starts Monday 0:00 and ends Sunday 24:00.
16047 The range is determined relative to TIME. TIME defaults to the current time.
16048 The return value is a cons cell with two internal times like the ones
16049 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
16050 the returned times will be formatted strings."
16051 (let* ((tm (decode-time (or time (current-time))))
16052 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
16053 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
16054 (dow (nth 6 tm))
16055 s1 m1 h1 d1 month1 y1 diff ts te fm)
16056 (cond
16057 ((eq key 'today)
16058 (setq h 0 m 0 h1 24 m1 0))
16059 ((eq key 'yesterday)
16060 (setq d (1- d) h 0 m 0 h1 24 m1 0))
16061 ((eq key 'thisweek)
16062 (setq diff (if (= dow 0) 6 (1- dow))
16063 m 0 h 0 d (- d diff) d1 (+ 7 d)))
16064 ((eq key 'lastweek)
16065 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
16066 m 0 h 0 d (- d diff) d1 (+ 7 d)))
16067 ((eq key 'thismonth)
16068 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
16069 ((eq key 'lastmonth)
16070 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
16071 ((eq key 'thisyear)
16072 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
16073 ((eq key 'lastyear)
16074 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
16075 (t (error "No such time block %s" key)))
16076 (setq ts (encode-time s m h d month y)
16077 te (encode-time (or s1 s) (or m1 m) (or h1 h)
16078 (or d1 d) (or month1 month) (or y1 y)))
16079 (setq fm (cdr org-time-stamp-formats))
16080 (if as-strings
16081 (cons (format-time-string fm ts) (format-time-string fm te))
16082 (cons ts te))))
16084 (defun org-dblock-write:clocktable (params)
16085 "Write the standard clocktable."
16086 (let ((hlchars '((1 . "*") (2 . ?/)))
16087 (emph nil)
16088 (ins (make-marker))
16089 ipos time h m p level hlc hdl maxlevel
16090 ts te cc block)
16091 (setq maxlevel (or (plist-get params :maxlevel) 3)
16092 emph (plist-get params :emphasize)
16093 ts (plist-get params :tstart)
16094 te (plist-get params :tend)
16095 block (plist-get params :block))
16096 (when block
16097 (setq cc (org-clock-special-range block nil t)
16098 ts (car cc) te (cdr cc)))
16099 (if ts (setq ts (time-to-seconds
16100 (apply 'encode-time (org-parse-time-string ts)))))
16101 (if te (setq te (time-to-seconds
16102 (apply 'encode-time (org-parse-time-string te)))))
16103 (move-marker ins (point))
16104 (setq ipos (point))
16105 (insert-before-markers "Clock summary at ["
16106 (substring
16107 (format-time-string (cdr org-time-stamp-formats))
16108 1 -1)
16109 "]."
16110 (if block
16111 (format " Considered range is /%s/." block)
16113 "\n\n|L|Headline|Time|\n")
16114 (org-clock-sum ts te)
16115 (setq h (/ org-clock-file-total-minutes 60)
16116 m (- org-clock-file-total-minutes (* 60 h)))
16117 (insert-before-markers "|-\n|0|" "*Total file time*| "
16118 (format "*%d:%02d*" h m)
16119 "|\n")
16120 (goto-char (point-min))
16121 (while (setq p (next-single-property-change (point) :org-clock-minutes))
16122 (goto-char p)
16123 (when (setq time (get-text-property p :org-clock-minutes))
16124 (save-excursion
16125 (beginning-of-line 1)
16126 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
16127 (setq level (- (match-end 1) (match-beginning 1)))
16128 (<= level maxlevel))
16129 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
16130 hdl (match-string 2)
16131 h (/ time 60)
16132 m (- time (* 60 h)))
16133 (goto-char ins)
16134 (if (= level 1) (insert-before-markers "|-\n"))
16135 (insert-before-markers
16136 "| " (int-to-string level) "|" hlc hdl hlc " |"
16137 (make-string (1- level) ?|)
16139 (format "%d:%02d" h m)
16141 " |\n")))))
16142 (goto-char ins)
16143 (backward-delete-char 1)
16144 (goto-char ipos)
16145 (skip-chars-forward "^|")
16146 (org-table-align)))
16148 ;; FIXME: I don't think anybody uses this, ask David
16149 (defun org-collect-clock-time-entries ()
16150 "Return an internal list with clocking information.
16151 This list has one entry for each CLOCK interval.
16152 FIXME: describe the elements."
16153 (interactive)
16154 (let ((re (concat "^[ \t]*" org-clock-string
16155 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
16156 rtn beg end next cont level title total closedp leafp
16157 clockpos titlepos h m donep)
16158 (save-excursion
16159 (org-clock-sum)
16160 (goto-char (point-min))
16161 (while (re-search-forward re nil t)
16162 (setq clockpos (match-beginning 0)
16163 beg (match-string 1) end (match-string 2)
16164 cont (match-end 0))
16165 (setq beg (apply 'encode-time (org-parse-time-string beg))
16166 end (apply 'encode-time (org-parse-time-string end)))
16167 (org-back-to-heading t)
16168 (setq donep (org-entry-is-done-p))
16169 (setq titlepos (point)
16170 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
16171 h (/ total 60) m (- total (* 60 h))
16172 total (cons h m))
16173 (looking-at "\\(\\*+\\) +\\(.*\\)")
16174 (setq level (- (match-end 1) (match-beginning 1))
16175 title (org-match-string-no-properties 2))
16176 (save-excursion (outline-next-heading) (setq next (point)))
16177 (setq closedp (re-search-forward org-closed-time-regexp next t))
16178 (goto-char next)
16179 (setq leafp (and (looking-at "^\\*+ ")
16180 (<= (- (match-end 0) (point)) level)))
16181 (push (list beg end clockpos closedp donep
16182 total title titlepos level leafp)
16183 rtn)
16184 (goto-char cont)))
16185 (nreverse rtn)))
16187 ;;;; Agenda, and Diary Integration
16189 ;;; Define the Org-agenda-mode
16191 (defvar org-agenda-mode-map (make-sparse-keymap)
16192 "Keymap for `org-agenda-mode'.")
16194 (defvar org-agenda-menu) ; defined later in this file.
16195 (defvar org-agenda-follow-mode nil)
16196 (defvar org-agenda-show-log nil)
16197 (defvar org-agenda-redo-command nil)
16198 (defvar org-agenda-mode-hook nil)
16199 (defvar org-agenda-type nil)
16200 (defvar org-agenda-force-single-file nil)
16202 (defun org-agenda-mode ()
16203 "Mode for time-sorted view on action items in Org-mode files.
16205 The following commands are available:
16207 \\{org-agenda-mode-map}"
16208 (interactive)
16209 (kill-all-local-variables)
16210 (setq org-agenda-undo-list nil
16211 org-agenda-pending-undo-list nil)
16212 (setq major-mode 'org-agenda-mode)
16213 ;; Keep global-font-lock-mode from turning on font-lock-mode
16214 (org-set-local 'font-lock-global-modes (list 'not major-mode))
16215 (setq mode-name "Org-Agenda")
16216 (use-local-map org-agenda-mode-map)
16217 (easy-menu-add org-agenda-menu)
16218 (if org-startup-truncated (setq truncate-lines t))
16219 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
16220 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
16221 ;; Make sure properties are removed when copying text
16222 (when (boundp 'buffer-substring-filters)
16223 (org-set-local 'buffer-substring-filters
16224 (cons (lambda (x)
16225 (set-text-properties 0 (length x) nil x) x)
16226 buffer-substring-filters)))
16227 (unless org-agenda-keep-modes
16228 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
16229 org-agenda-show-log nil))
16230 (easy-menu-change
16231 '("Agenda") "Agenda Files"
16232 (append
16233 (list
16234 (vector
16235 (if (get 'org-agenda-files 'org-restrict)
16236 "Restricted to single file"
16237 "Edit File List")
16238 '(org-edit-agenda-file-list)
16239 (not (get 'org-agenda-files 'org-restrict)))
16240 "--")
16241 (mapcar 'org-file-menu-entry (org-agenda-files))))
16242 (org-agenda-set-mode-name)
16243 (apply
16244 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
16245 (list 'org-agenda-mode-hook)))
16247 (substitute-key-definition 'undo 'org-agenda-undo
16248 org-agenda-mode-map global-map)
16249 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
16250 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
16251 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
16252 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
16253 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
16254 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
16255 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
16256 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
16257 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
16258 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
16259 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
16260 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
16261 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
16262 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
16263 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
16264 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
16265 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
16266 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
16267 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
16268 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
16269 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
16270 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
16271 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
16272 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
16273 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
16274 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
16275 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
16276 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
16277 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
16279 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
16280 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
16281 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
16282 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
16283 (while l (org-defkey org-agenda-mode-map
16284 (int-to-string (pop l)) 'digit-argument)))
16286 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
16287 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
16288 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
16289 (org-defkey org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
16290 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
16291 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
16292 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
16293 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
16294 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
16295 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
16296 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
16297 (org-defkey org-agenda-mode-map "n" 'next-line)
16298 (org-defkey org-agenda-mode-map "p" 'previous-line)
16299 (org-defkey org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
16300 (org-defkey org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
16301 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
16302 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
16303 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
16304 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
16305 (eval-after-load "calendar"
16306 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
16307 'org-calendar-goto-agenda))
16308 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
16309 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
16310 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
16311 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
16312 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
16313 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
16314 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
16315 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
16316 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
16317 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
16318 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
16319 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
16320 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
16321 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
16322 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
16323 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
16324 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
16326 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
16327 "Local keymap for agenda entries from Org-mode.")
16329 (org-defkey org-agenda-keymap
16330 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
16331 (org-defkey org-agenda-keymap
16332 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
16333 (when org-agenda-mouse-1-follows-link
16334 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
16335 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
16336 '("Agenda"
16337 ("Agenda Files")
16338 "--"
16339 ["Show" org-agenda-show t]
16340 ["Go To (other window)" org-agenda-goto t]
16341 ["Go To (this window)" org-agenda-switch-to t]
16342 ["Follow Mode" org-agenda-follow-mode
16343 :style toggle :selected org-agenda-follow-mode :active t]
16344 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
16345 "--"
16346 ["Cycle TODO" org-agenda-todo t]
16347 ["Archive subtree" org-agenda-archive t]
16348 ["Delete subtree" org-agenda-kill t]
16349 "--"
16350 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
16351 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
16352 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
16353 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
16354 "--"
16355 ("Tags and Properties"
16356 ["Show all Tags" org-agenda-show-tags t]
16357 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
16358 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
16359 "--"
16360 ["Column View" org-columns t])
16361 ("Date/Schedule"
16362 ["Schedule" org-agenda-schedule t]
16363 ["Set Deadline" org-agenda-deadline t]
16364 "--"
16365 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
16366 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
16367 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
16368 ("Priority"
16369 ["Set Priority" org-agenda-priority t]
16370 ["Increase Priority" org-agenda-priority-up t]
16371 ["Decrease Priority" org-agenda-priority-down t]
16372 ["Show Priority" org-agenda-show-priority t])
16373 ("Calendar/Diary"
16374 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
16375 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
16376 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
16377 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
16378 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
16379 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
16380 "--"
16381 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
16382 "--"
16383 ("View"
16384 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
16385 :style radio :selected (equal org-agenda-ndays 1)]
16386 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
16387 :style radio :selected (equal org-agenda-ndays 7)]
16388 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
16389 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
16390 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
16391 :style radio :selected (member org-agenda-ndays '(365 366))]
16392 "--"
16393 ["Show Logbook entries" org-agenda-log-mode
16394 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
16395 ["Include Diary" org-agenda-toggle-diary
16396 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
16397 ["Use Time Grid" org-agenda-toggle-time-grid
16398 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
16399 ["Write view to file" org-write-agenda t]
16400 ["Rebuild buffer" org-agenda-redo t]
16401 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
16402 "--"
16403 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
16404 "--"
16405 ["Quit" org-agenda-quit t]
16406 ["Exit and Release Buffers" org-agenda-exit t]
16409 ;;; Agenda undo
16411 (defvar org-agenda-allow-remote-undo t
16412 "Non-nil means, allow remote undo from the agenda buffer.")
16413 (defvar org-agenda-undo-list nil
16414 "List of undoable operations in the agenda since last refresh.")
16415 (defvar org-agenda-undo-has-started-in nil
16416 "Buffers that have already seen `undo-start' in the current undo sequence.")
16417 (defvar org-agenda-pending-undo-list nil
16418 "In a series of undo commands, this is the list of remaning undo items.")
16420 (defmacro org-if-unprotected (&rest body)
16421 "Execute BODY if there is no `org-protected' text property at point."
16422 (declare (debug t))
16423 `(unless (get-text-property (point) 'org-protected)
16424 ,@body))
16426 (defmacro org-with-remote-undo (_buffer &rest _body)
16427 "Execute BODY while recording undo information in two buffers."
16428 (declare (indent 1) (debug t))
16429 `(let ((_cline (org-current-line))
16430 (_cmd this-command)
16431 (_buf1 (current-buffer))
16432 (_buf2 ,_buffer)
16433 (_undo1 buffer-undo-list)
16434 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
16435 _c1 _c2)
16436 ,@_body
16437 (when org-agenda-allow-remote-undo
16438 (setq _c1 (org-verify-change-for-undo
16439 _undo1 (with-current-buffer _buf1 buffer-undo-list))
16440 _c2 (org-verify-change-for-undo
16441 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
16442 (when (or _c1 _c2)
16443 ;; make sure there are undo boundaries
16444 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
16445 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
16446 ;; remember which buffer to undo
16447 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
16448 org-agenda-undo-list)))))
16450 (defun org-agenda-undo ()
16451 "Undo a remote editing step in the agenda.
16452 This undoes changes both in the agenda buffer and in the remote buffer
16453 that have been changed along."
16454 (interactive)
16455 (or org-agenda-allow-remote-undo
16456 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
16457 (if (not (eq this-command last-command))
16458 (setq org-agenda-undo-has-started-in nil
16459 org-agenda-pending-undo-list org-agenda-undo-list))
16460 (if (not org-agenda-pending-undo-list)
16461 (error "No further undo information"))
16462 (let* ((entry (pop org-agenda-pending-undo-list))
16463 buf line cmd rembuf)
16464 (setq cmd (pop entry) line (pop entry))
16465 (setq rembuf (nth 2 entry))
16466 (org-with-remote-undo rembuf
16467 (while (bufferp (setq buf (pop entry)))
16468 (if (pop entry)
16469 (with-current-buffer buf
16470 (let ((last-undo-buffer buf)
16471 (inhibit-read-only t))
16472 (unless (memq buf org-agenda-undo-has-started-in)
16473 (push buf org-agenda-undo-has-started-in)
16474 (make-local-variable 'pending-undo-list)
16475 (undo-start))
16476 (while (and pending-undo-list
16477 (listp pending-undo-list)
16478 (not (car pending-undo-list)))
16479 (pop pending-undo-list))
16480 (undo-more 1))))))
16481 (goto-line line)
16482 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
16484 (defun org-verify-change-for-undo (l1 l2)
16485 "Verify that a real change occurred between the undo lists L1 and L2."
16486 (while (and l1 (listp l1) (null (car l1))) (pop l1))
16487 (while (and l2 (listp l2) (null (car l2))) (pop l2))
16488 (not (eq l1 l2)))
16490 ;;; Agenda dispatch
16492 (defvar org-agenda-restrict nil)
16493 (defvar org-agenda-restrict-begin (make-marker))
16494 (defvar org-agenda-restrict-end (make-marker))
16495 (defvar org-agenda-last-dispatch-buffer nil)
16497 ;;;###autoload
16498 (defun org-agenda (arg)
16499 "Dispatch agenda commands to collect entries to the agenda buffer.
16500 Prompts for a character to select a command. Any prefix arg will be passed
16501 on to the selected command. The default selections are:
16503 a Call `org-agenda-list' to display the agenda for current day or week.
16504 t Call `org-todo-list' to display the global todo list.
16505 T Call `org-todo-list' to display the global todo list, select only
16506 entries with a specific TODO keyword (the user gets a prompt).
16507 m Call `org-tags-view' to display headlines with tags matching
16508 a condition (the user is prompted for the condition).
16509 M Like `m', but select only TODO entries, no ordinary headlines.
16510 L Create a timeline for the current buffer.
16511 e Export views to associated files.
16513 More commands can be added by configuring the variable
16514 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
16515 searches can be pre-defined in this way.
16517 If the current buffer is in Org-mode and visiting a file, you can also
16518 first press `1' to indicate that the agenda should be temporarily (until the
16519 next use of \\[org-agenda]) restricted to the current file."
16520 (interactive "P")
16521 (catch 'exit
16522 (let* ((buf (current-buffer))
16523 (bfn (buffer-file-name (buffer-base-buffer)))
16524 (restrict-ok (and bfn (org-mode-p)))
16525 (custom org-agenda-custom-commands)
16526 c entry key type match lprops)
16527 ;; Turn off restriction
16528 (put 'org-agenda-files 'org-restrict nil)
16529 (setq org-agenda-restrict nil)
16530 (move-marker org-agenda-restrict-begin nil)
16531 (move-marker org-agenda-restrict-end nil)
16532 ;; Delete old local properties
16533 (put 'org-agenda-redo-command 'org-lprops nil)
16534 ;; Remember where this call originated
16535 (setq org-agenda-last-dispatch-buffer (current-buffer))
16536 (save-window-excursion
16537 (delete-other-windows)
16538 (switch-to-buffer-other-window " *Agenda Commands*")
16539 (erase-buffer)
16540 (insert (eval-when-compile
16541 (let ((header
16542 "Press key for an agenda command:
16543 -------------------------------- C Configure custom agenda commands
16544 a Agenda for current week or day e Export agenda views
16545 t List of all TODO entries T Entries with special TODO kwd
16546 m Match a TAGS query M Like m, but only TODO entries
16547 L Timeline for current buffer # List stuck projects (!=configure)
16549 (start 0))
16550 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
16551 (setq start (match-end 0))
16552 (add-text-properties (match-beginning 2) (match-end 2)
16553 '(face bold) header))
16554 header)))
16555 (while (setq entry (pop custom))
16556 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
16557 (insert (format "\n%-4s%-14s: %s"
16558 (org-add-props (copy-sequence key)
16559 '(face bold))
16560 (cond
16561 ((stringp type) type)
16562 ((eq type 'agenda) "Agenda for current week or day")
16563 ((eq type 'alltodo) "List of all TODO entries")
16564 ((eq type 'stuck) "List of stuck projects")
16565 ((eq type 'todo) "TODO keyword")
16566 ((eq type 'tags) "Tags query")
16567 ((eq type 'tags-todo) "Tags (TODO)")
16568 ((eq type 'tags-tree) "Tags tree")
16569 ((eq type 'todo-tree) "TODO kwd tree")
16570 ((eq type 'occur-tree) "Occur tree")
16571 ((functionp type) (symbol-name type))
16572 (t "???"))
16573 (if (stringp match)
16574 (org-add-props match nil 'face 'org-warning)
16575 (format "set of %d commands" (length match))))))
16576 (if restrict-ok
16577 (insert "\n"
16578 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
16579 (goto-char (point-min))
16580 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
16581 (message "Press key for agenda command%s"
16582 (if restrict-ok ", or [1] or [0] to restrict" ""))
16583 (setq c (read-char-exclusive))
16584 (message "")
16585 (when (memq c '(?L ?1 ?0))
16586 (if restrict-ok
16587 (put 'org-agenda-files 'org-restrict (list bfn))
16588 (error "Cannot restrict agenda to current buffer"))
16589 (with-current-buffer " *Agenda Commands*"
16590 (goto-char (point-max))
16591 (delete-region (point-at-bol) (point))
16592 (goto-char (point-min)))
16593 (when (eq c ?0)
16594 (setq org-agenda-restrict t)
16595 (with-current-buffer buf
16596 (if (org-region-active-p)
16597 (progn
16598 (move-marker org-agenda-restrict-begin (region-beginning))
16599 (move-marker org-agenda-restrict-end (region-end)))
16600 (save-excursion
16601 (org-back-to-heading t)
16602 (move-marker org-agenda-restrict-begin (point))
16603 (move-marker org-agenda-restrict-end
16604 (progn (org-end-of-subtree t)))))))
16605 (unless (eq c ?L)
16606 (message "Press key for agenda command%s"
16607 (if restrict-ok " (restricted to current file)" ""))
16608 (setq c (read-char-exclusive)))
16609 (message "")))
16610 (require 'calendar) ; FIXME: can we avoid this for some commands?
16611 ;; For example the todo list should not need it (but does...)
16612 (cond
16613 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
16614 (if (symbolp (nth 1 entry))
16615 (progn
16616 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
16617 lprops (nth 3 entry))
16618 (put 'org-agenda-redo-command 'org-lprops lprops)
16619 (cond
16620 ((eq type 'agenda)
16621 (org-let lprops '(org-agenda-list current-prefix-arg)))
16622 ((eq type 'alltodo)
16623 (org-let lprops '(org-todo-list current-prefix-arg)))
16624 ((eq type 'stuck)
16625 (org-let lprops '(org-agenda-list-stuck-projects
16626 current-prefix-arg)))
16627 ((eq type 'tags)
16628 (org-let lprops '(org-tags-view current-prefix-arg match)))
16629 ((eq type 'tags-todo)
16630 (org-let lprops '(org-tags-view '(4) match)))
16631 ((eq type 'todo)
16632 (org-let lprops '(org-todo-list match)))
16633 ((eq type 'tags-tree)
16634 (org-check-for-org-mode)
16635 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
16636 ((eq type 'todo-tree)
16637 (org-check-for-org-mode)
16638 (org-let lprops
16639 '(org-occur (concat "^" outline-regexp "[ \t]*"
16640 (regexp-quote match) "\\>"))))
16641 ((eq type 'occur-tree)
16642 (org-check-for-org-mode)
16643 (org-let lprops '(org-occur match)))
16644 ((fboundp type)
16645 (org-let lprops '(funcall type match)))
16646 (t (error "Invalid custom agenda command type %s" type))))
16647 (org-run-agenda-series (nth 1 entry) (cddr entry))))
16648 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
16649 ((equal c ?a) (call-interactively 'org-agenda-list))
16650 ((equal c ?t) (call-interactively 'org-todo-list))
16651 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
16652 ((equal c ?m) (call-interactively 'org-tags-view))
16653 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
16654 ((equal c ?e) (call-interactively 'org-store-agenda-views))
16655 ((equal c ?L)
16656 (unless restrict-ok
16657 (error "This is not an Org-mode file"))
16658 (org-call-with-arg 'org-timeline arg))
16659 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
16660 ((equal c ?!) (customize-variable 'org-stuck-projects))
16661 (t (error "Invalid key"))))))
16663 (defun org-run-agenda-series (name series)
16664 (org-prepare-agenda name)
16665 (let* ((org-agenda-multi t)
16666 (redo (list 'org-run-agenda-series name (list 'quote series)))
16667 (cmds (car series))
16668 (gprops (nth 1 series))
16669 match ;; The byte compiler incorrectly complains about this. Keep it!
16670 cmd type lprops)
16671 (while (setq cmd (pop cmds))
16672 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
16673 (cond
16674 ((eq type 'agenda)
16675 (org-let2 gprops lprops
16676 '(call-interactively 'org-agenda-list)))
16677 ((eq type 'alltodo)
16678 (org-let2 gprops lprops
16679 '(call-interactively 'org-todo-list)))
16680 ((eq type 'stuck)
16681 (org-let2 gprops lprops
16682 '(call-interactively 'org-agenda-list-stuck-projects)))
16683 ((eq type 'tags)
16684 (org-let2 gprops lprops
16685 '(org-tags-view current-prefix-arg match)))
16686 ((eq type 'tags-todo)
16687 (org-let2 gprops lprops
16688 '(org-tags-view '(4) match)))
16689 ((eq type 'todo)
16690 (org-let2 gprops lprops
16691 '(org-todo-list match)))
16692 ((fboundp type)
16693 (org-let2 gprops lprops
16694 '(funcall type match)))
16695 (t (error "Invalid type in command series"))))
16696 (widen)
16697 (setq org-agenda-redo-command redo)
16698 (goto-char (point-min)))
16699 (org-finalize-agenda))
16701 ;;;###autoload
16702 (defmacro org-batch-agenda (cmd-key &rest parameters)
16703 "Run an agenda command in batch mode and send the result to STDOUT.
16704 If CMD-KEY is a string of length 1, it is used as a key in
16705 `org-agenda-custom-commands' and triggers this command. If it is a
16706 longer string is is used as a tags/todo match string.
16707 Paramters are alternating variable names and values that will be bound
16708 before running the agenda command."
16709 (let (pars)
16710 (while parameters
16711 (push (list (pop parameters) (if parameters (pop parameters))) pars))
16712 (if (> (length cmd-key) 1)
16713 (eval (list 'let (nreverse pars)
16714 (list 'org-tags-view nil cmd-key)))
16715 (flet ((read-char-exclusive () (string-to-char cmd-key)))
16716 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
16717 (set-buffer org-agenda-buffer-name)
16718 (princ (org-encode-for-stdout (buffer-string)))))
16720 (defun org-encode-for-stdout (string)
16721 (if (fboundp 'encode-coding-string)
16722 (encode-coding-string string buffer-file-coding-system)
16723 string))
16725 (defvar org-agenda-info nil)
16727 ;;;###autoload
16728 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
16729 "Run an agenda command in batch mode and send the result to STDOUT.
16730 If CMD-KEY is a string of length 1, it is used as a key in
16731 `org-agenda-custom-commands' and triggers this command. If it is a
16732 longer string is is used as a tags/todo match string.
16733 Paramters are alternating variable names and values that will be bound
16734 before running the agenda command.
16736 The output gives a line for each selected agenda item. Each
16737 item is a list of comma-separated values, like this:
16739 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
16741 category The category of the item
16742 head The headline, without TODO kwd, TAGS and PRIORITY
16743 type The type of the agenda entry, can be
16744 todo selected in TODO match
16745 tagsmatch selected in tags match
16746 diary imported from diary
16747 deadline a deadline on given date
16748 scheduled scheduled on given date
16749 timestamp entry has timestamp on given date
16750 closed entry was closed on given date
16751 upcoming-deadline warning about deadline
16752 past-scheduled forwarded scheduled item
16753 block entry has date block including g. date
16754 todo The todo keyword, if any
16755 tags All tags including inherited ones, separated by colons
16756 date The relevant date, like 2007-2-14
16757 time The time, like 15:00-16:50
16758 extra Sting with extra planning info
16759 priority-l The priority letter if any was given
16760 priority-n The computed numerical priority
16761 agenda-day The day in the agenda where this is listed"
16763 (let (pars)
16764 (while parameters
16765 (push (list (pop parameters) (if parameters (pop parameters))) pars))
16766 (push (list 'org-agenda-remove-tags t) pars)
16767 (if (> (length cmd-key) 1)
16768 (eval (list 'let (nreverse pars)
16769 (list 'org-tags-view nil cmd-key)))
16770 (flet ((read-char-exclusive () (string-to-char cmd-key)))
16771 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
16772 (set-buffer org-agenda-buffer-name)
16773 (let* ((lines (org-split-string (buffer-string) "\n"))
16774 line)
16775 (while (setq line (pop lines))
16776 (catch 'next
16777 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
16778 (setq org-agenda-info
16779 (org-fix-agenda-info (text-properties-at 0 line)))
16780 (princ
16781 (org-encode-for-stdout
16782 (mapconcat 'org-agenda-export-csv-mapper
16783 '(org-category txt type todo tags date time-of-day extra
16784 priority-letter priority agenda-day)
16785 ",")))
16786 (princ "\n"))))))
16788 (defun org-fix-agenda-info (props)
16789 "FIXME"
16790 (let (tmp re)
16791 (when (setq tmp (plist-get props 'tags))
16792 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
16793 (when (setq tmp (plist-get props 'date))
16794 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
16795 (let ((calendar-date-display-form '(year "-" month "-" day)))
16796 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
16798 (setq tmp (calendar-date-string tmp)))
16799 (setq props (plist-put props 'date tmp)))
16800 (when (setq tmp (plist-get props 'day))
16801 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
16802 (let ((calendar-date-display-form '(year "-" month "-" day)))
16803 (setq tmp (calendar-date-string tmp)))
16804 (setq props (plist-put props 'day tmp))
16805 (setq props (plist-put props 'agenda-day tmp)))
16806 (when (setq tmp (plist-get props 'txt))
16807 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
16808 (plist-put props 'priority-letter (match-string 1 tmp))
16809 (setq tmp (replace-match "" t t tmp)))
16810 (when (and (setq re (plist-get props 'org-todo-regexp))
16811 (setq re (concat "\\`\\.*" re " ?"))
16812 (string-match re tmp))
16813 (plist-put props 'todo (match-string 1 tmp))
16814 (setq tmp (replace-match "" t t tmp)))
16815 (plist-put props 'txt tmp)))
16816 props)
16818 (defun org-agenda-export-csv-mapper (prop)
16819 (let ((res (plist-get org-agenda-info prop)))
16820 (setq res
16821 (cond
16822 ((not res) "")
16823 ((stringp res) res)
16824 (t (prin1-to-string res))))
16825 (while (string-match "," res)
16826 (setq res (replace-match ";" t t res)))
16827 (org-trim res)))
16830 ;;;###autoload
16831 (defun org-store-agenda-views (&rest parameters)
16832 (interactive)
16833 (eval (list 'org-batch-store-agenda-views)))
16835 ;; FIXME, why is this a macro?????
16836 ;;;###autoload
16837 (defmacro org-batch-store-agenda-views (&rest parameters)
16838 "Run all custom agenda commands that have a file argument."
16839 (let ((cmds org-agenda-custom-commands)
16840 (dir default-directory)
16841 pars cmd thiscmdkey files opts)
16842 (while parameters
16843 (push (list (pop parameters) (if parameters (pop parameters))) pars))
16844 (setq pars (reverse pars))
16845 (save-window-excursion
16846 (while cmds
16847 (setq cmd (pop cmds)
16848 thiscmdkey (car cmd)
16849 opts (nth 3 cmd)
16850 files (nth 4 cmd))
16851 (if (stringp files) (setq files (list files)))
16852 (when files
16853 (flet ((read-char-exclusive () (string-to-char thiscmdkey)))
16854 (eval (list 'let (append org-agenda-exporter-settings opts pars)
16855 '(org-agenda nil))))
16856 (set-buffer org-agenda-buffer-name)
16857 (while files
16858 (eval (list 'let (append org-agenda-exporter-settings opts pars)
16859 (list 'org-write-agenda
16860 (expand-file-name (pop files) dir) t))))
16861 (and (get-buffer org-agenda-buffer-name)
16862 (kill-buffer org-agenda-buffer-name)))))))
16864 (defun org-write-agenda (file &optional nosettings)
16865 "Write the current buffer (an agenda view) as a file.
16866 Depending on the extension of the file name, plain text (.txt),
16867 HTML (.html or .htm) or Postscript (.ps) is produced.
16868 If NOSETTINGS is given, do not scope the settings of
16869 `org-agenda-exporter-settings' into the export commands. This is used when
16870 the settings have already been scoped and we do not wish to overrule other,
16871 higher priority settings."
16872 (interactive "FWrite agenda to file: ")
16873 (if (not (file-writable-p file))
16874 (error "Cannot write agenda to file %s" file))
16875 (cond
16876 ((string-match "\\.html?\\'" file) (require 'htmlize))
16877 ((string-match "\\.ps\\'" file) (require 'ps-print)))
16878 (org-let (if nosettings nil org-agenda-exporter-settings)
16879 '(save-excursion
16880 (save-window-excursion
16881 (cond
16882 ((string-match "\\.html?\\'" file)
16883 (set-buffer (htmlize-buffer (current-buffer)))
16885 (when (and org-agenda-export-html-style
16886 (string-match "<style>" org-agenda-export-html-style))
16887 ;; replace <style> section with org-agenda-export-html-style
16888 (goto-char (point-min))
16889 (kill-region (- (search-forward "<style") 6)
16890 (search-forward "</style>"))
16891 (insert org-agenda-export-html-style))
16892 (write-file file)
16893 (kill-buffer (current-buffer))
16894 (message "HTML written to %s" file))
16895 ((string-match "\\.ps\\'" file)
16896 (ps-print-buffer-with-faces file)
16897 (message "Postscript written to %s" file))
16899 (let ((bs (buffer-string)))
16900 (find-file file)
16901 (insert bs)
16902 (save-buffer 0)
16903 (kill-buffer (current-buffer))
16904 (message "Plain text written to %s" file))))))
16905 (set-buffer org-agenda-buffer-name)))
16907 (defmacro org-no-read-only (&rest body)
16908 "Inhibit read-only for BODY."
16909 `(let ((inhibit-read-only t)) ,@body))
16911 (defun org-check-for-org-mode ()
16912 "Make sure current buffer is in org-mode. Error if not."
16913 (or (org-mode-p)
16914 (error "Cannot execute org-mode agenda command on buffer in %s."
16915 major-mode)))
16917 (defun org-fit-agenda-window ()
16918 "Fit the window to the buffer size."
16919 (and (memq org-agenda-window-setup '(reorganize-frame))
16920 (fboundp 'fit-window-to-buffer)
16921 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
16922 (/ (frame-height) 2))))
16924 ;;; Agenda file list
16926 (defun org-agenda-files (&optional unrestricted)
16927 "Get the list of agenda files.
16928 Optional UNRESTRICTED means return the full list even if a restriction
16929 is currently in place."
16930 (cond
16931 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16932 ((stringp org-agenda-files) (org-read-agenda-file-list))
16933 ((listp org-agenda-files) org-agenda-files)
16934 (t (error "Invalid value of `org-agenda-files'"))))
16936 (defun org-edit-agenda-file-list ()
16937 "Edit the list of agenda files.
16938 Depending on setup, this either uses customize to edit the variable
16939 `org-agenda-files', or it visits the file that is holding the list. In the
16940 latter case, the buffer is set up in a way that saving it automatically kills
16941 the buffer and restores the previous window configuration."
16942 (interactive)
16943 (if (stringp org-agenda-files)
16944 (let ((cw (current-window-configuration)))
16945 (find-file org-agenda-files)
16946 (org-set-local 'org-window-configuration cw)
16947 (org-add-hook 'after-save-hook
16948 (lambda ()
16949 (set-window-configuration
16950 (prog1 org-window-configuration
16951 (kill-buffer (current-buffer))))
16952 (org-install-agenda-files-menu)
16953 (message "New agenda file list installed"))
16954 nil 'local)
16955 (message (substitute-command-keys
16956 "Edit list and finish with \\[save-buffer]")))
16957 (customize-variable 'org-agenda-files)))
16959 (defun org-store-new-agenda-file-list (list)
16960 "Set new value for the agenda file list and save it correcly."
16961 (if (stringp org-agenda-files)
16962 (let ((f org-agenda-files) b)
16963 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
16964 (with-temp-file f
16965 (insert (mapconcat 'identity list "\n") "\n")))
16966 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
16967 (setq org-agenda-files list)
16968 (customize-save-variable 'org-agenda-files org-agenda-files))))
16970 (defun org-read-agenda-file-list ()
16971 "Read the list of agenda files from a file."
16972 (when (stringp org-agenda-files)
16973 (with-temp-buffer
16974 (insert-file-contents org-agenda-files)
16975 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
16978 ;;;###autoload
16979 (defun org-cycle-agenda-files ()
16980 "Cycle through the files in `org-agenda-files'.
16981 If the current buffer visits an agenda file, find the next one in the list.
16982 If the current buffer does not, find the first agenda file."
16983 (interactive)
16984 (let* ((fs (org-agenda-files t))
16985 (files (append fs (list (car fs))))
16986 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16987 file)
16988 (unless files (error "No agenda files"))
16989 (catch 'exit
16990 (while (setq file (pop files))
16991 (if (equal (file-truename file) tcf)
16992 (when (car files)
16993 (find-file (car files))
16994 (throw 'exit t))))
16995 (find-file (car fs)))
16996 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
16998 (defun org-agenda-file-to-front (&optional to-end)
16999 "Move/add the current file to the top of the agenda file list.
17000 If the file is not present in the list, it is added to the front. If it is
17001 present, it is moved there. With optional argument TO-END, add/move to the
17002 end of the list."
17003 (interactive "P")
17004 (let ((file-alist (mapcar (lambda (x)
17005 (cons (file-truename x) x))
17006 (org-agenda-files t)))
17007 (ctf (file-truename buffer-file-name))
17008 x had)
17009 (setq x (assoc ctf file-alist) had x)
17011 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17012 (if to-end
17013 (setq file-alist (append (delq x file-alist) (list x)))
17014 (setq file-alist (cons x (delq x file-alist))))
17015 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17016 (org-install-agenda-files-menu)
17017 (message "File %s to %s of agenda file list"
17018 (if had "moved" "added") (if to-end "end" "front"))))
17020 (defun org-remove-file (&optional file)
17021 "Remove current file from the list of files in variable `org-agenda-files'.
17022 These are the files which are being checked for agenda entries.
17023 Optional argument FILE means, use this file instead of the current."
17024 (interactive)
17025 (let* ((file (or file buffer-file-name))
17026 (true-file (file-truename file))
17027 (afile (abbreviate-file-name file))
17028 (files (delq nil (mapcar
17029 (lambda (x)
17030 (if (equal true-file
17031 (file-truename x))
17032 nil x))
17033 (org-agenda-files t)))))
17034 (if (not (= (length files) (length (org-agenda-files t))))
17035 (progn
17036 (org-store-new-agenda-file-list files)
17037 (org-install-agenda-files-menu)
17038 (message "Removed file: %s" afile))
17039 (message "File was not in list: %s" afile))))
17041 (defun org-file-menu-entry (file)
17042 (vector file (list 'find-file file) t))
17044 (defun org-check-agenda-file (file)
17045 "Make sure FILE exists. If not, ask user what to do."
17046 (when (not (file-exists-p file))
17047 (message "non-existent file %s. [R]emove from list or [A]bort?"
17048 (abbreviate-file-name file))
17049 (let ((r (downcase (read-char-exclusive))))
17050 (cond
17051 ((equal r ?r)
17052 (org-remove-file file)
17053 (throw 'nextfile t))
17054 (t (error "Abort"))))))
17056 ;;; Agenda prepare and finalize
17058 (defvar org-agenda-multi nil) ; dynammically scoped
17059 (defvar org-agenda-buffer-name "*Org Agenda*")
17060 (defvar org-pre-agenda-window-conf nil)
17061 (defvar org-agenda-name nil)
17062 (defun org-prepare-agenda (&optional name)
17063 (setq org-todo-keywords-for-agenda nil)
17064 (setq org-done-keywords-for-agenda nil)
17065 (if org-agenda-multi
17066 (progn
17067 (setq buffer-read-only nil)
17068 (goto-char (point-max))
17069 (unless (bobp)
17070 (insert "\n" (make-string (window-width) ?=) "\n"))
17071 (narrow-to-region (point) (point-max)))
17072 (org-agenda-maybe-reset-markers 'force)
17073 (org-prepare-agenda-buffers (org-agenda-files))
17074 (setq org-todo-keywords-for-agenda
17075 (org-uniquify org-todo-keywords-for-agenda))
17076 (setq org-done-keywords-for-agenda
17077 (org-uniquify org-done-keywords-for-agenda))
17078 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
17079 (awin (get-buffer-window abuf)))
17080 (cond
17081 ((equal (current-buffer) abuf) nil)
17082 (awin (select-window awin))
17083 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
17084 ((equal org-agenda-window-setup 'current-window)
17085 (switch-to-buffer abuf))
17086 ((equal org-agenda-window-setup 'other-window)
17087 (switch-to-buffer-other-window abuf))
17088 ((equal org-agenda-window-setup 'other-frame)
17089 (switch-to-buffer-other-frame abuf))
17090 ((equal org-agenda-window-setup 'reorganize-frame)
17091 (delete-other-windows)
17092 (switch-to-buffer-other-window abuf))))
17093 (setq buffer-read-only nil)
17094 (erase-buffer)
17095 (org-agenda-mode)
17096 (and name (not org-agenda-name)
17097 (org-set-local 'org-agenda-name name)))
17098 (setq buffer-read-only nil))
17100 (defun org-finalize-agenda ()
17101 "Finishing touch for the agenda buffer, called just before displaying it."
17102 (unless org-agenda-multi
17103 (save-excursion
17104 (let ((inhibit-read-only t))
17105 (goto-char (point-min))
17106 (while (org-activate-bracket-links (point-max))
17107 (add-text-properties (match-beginning 0) (match-end 0)
17108 '(face org-link)))
17109 (org-agenda-align-tags)
17110 (unless org-agenda-with-colors
17111 (remove-text-properties (point-min) (point-max) '(face nil))))
17112 (if (and (boundp 'org-overriding-columns-format)
17113 org-overriding-columns-format)
17114 (org-set-local 'org-overriding-columns-format
17115 org-overriding-columns-format))
17116 (if (and (boundp 'org-agenda-view-columns-initially)
17117 org-agenda-view-columns-initially)
17118 (org-agenda-columns))
17119 (run-hooks 'org-finalize-agenda-hook))))
17121 (defun org-prepare-agenda-buffers (files)
17122 "Create buffers for all agenda files, protect archived trees and comments."
17123 (interactive)
17124 (let ((pa '(:org-archived t))
17125 (pc '(:org-comment t))
17126 (pall '(:org-archived t :org-comment t))
17127 (inhibit-read-only t)
17128 (rea (concat ":" org-archive-tag ":"))
17129 bmp file re)
17130 (save-excursion
17131 (save-restriction
17132 (while (setq file (pop files))
17133 (org-check-agenda-file file)
17134 (set-buffer (org-get-agenda-file-buffer file))
17135 (widen)
17136 (setq bmp (buffer-modified-p))
17137 (setq org-todo-keywords-for-agenda
17138 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17139 (setq org-done-keywords-for-agenda
17140 (append org-done-keywords-for-agenda org-done-keywords))
17141 (save-excursion
17142 (remove-text-properties (point-min) (point-max) pall)
17143 (when org-agenda-skip-archived-trees
17144 (goto-char (point-min))
17145 (while (re-search-forward rea nil t)
17146 (if (org-on-heading-p t)
17147 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17148 (goto-char (point-min))
17149 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
17150 (while (re-search-forward re nil t)
17151 (add-text-properties
17152 (match-beginning 0) (org-end-of-subtree t) pc)))
17153 (set-buffer-modified-p bmp))))))
17155 (defvar org-agenda-skip-function nil
17156 "Function to be called at each match during agenda construction.
17157 If this function returns nil, the current match should not be skipped.
17158 Otherwise, the function must return a position from where the search
17159 should be continued.
17160 This may also be a Lisp form, it will be evaluated.
17161 Never set this variable using `setq' or so, because then it will apply
17162 to all future agenda commands. Instead, bind it with `let' to scope
17163 it dynamically into the agenda-constructing command. A good way to set
17164 it is through options in org-agenda-custom-commands.")
17166 (defun org-agenda-skip ()
17167 "Throw to `:skip' in places that should be skipped.
17168 Also moves point to the end of the skipped region, so that search can
17169 continue from there."
17170 (let ((p (point-at-bol)) to fp)
17171 (and org-agenda-skip-archived-trees
17172 (get-text-property p :org-archived)
17173 (org-end-of-subtree t)
17174 (throw :skip t))
17175 (and (get-text-property p :org-comment)
17176 (org-end-of-subtree t)
17177 (throw :skip t))
17178 (if (equal (char-after p) ?#) (throw :skip t))
17179 (when (and (or (setq fp (functionp org-agenda-skip-function))
17180 (consp org-agenda-skip-function))
17181 (setq to (save-excursion
17182 (save-match-data
17183 (if fp
17184 (funcall org-agenda-skip-function)
17185 (eval org-agenda-skip-function))))))
17186 (goto-char to)
17187 (throw :skip t))))
17189 (defvar org-agenda-markers nil
17190 "List of all currently active markers created by `org-agenda'.")
17191 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
17192 "Creation time of the last agenda marker.")
17194 (defun org-agenda-new-marker (&optional pos)
17195 "Return a new agenda marker.
17196 Org-mode keeps a list of these markers and resets them when they are
17197 no longer in use."
17198 (let ((m (copy-marker (or pos (point)))))
17199 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
17200 (push m org-agenda-markers)
17203 (defun org-agenda-maybe-reset-markers (&optional force)
17204 "Reset markers created by `org-agenda'. But only if they are old enough."
17205 (if (or (and force (not org-agenda-multi))
17206 (> (- (time-to-seconds (current-time))
17207 org-agenda-last-marker-time)
17209 (while org-agenda-markers
17210 (move-marker (pop org-agenda-markers) nil))))
17212 (defvar org-agenda-new-buffers nil
17213 "Buffers created to visit agenda files.")
17215 (defun org-get-agenda-file-buffer (file)
17216 "Get a buffer visiting FILE. If the buffer needs to be created, add
17217 it to the list of buffers which might be released later."
17218 (let ((buf (org-find-base-buffer-visiting file)))
17219 (if buf
17220 buf ; just return it
17221 ;; Make a new buffer and remember it
17222 (setq buf (find-file-noselect file))
17223 (if buf (push buf org-agenda-new-buffers))
17224 buf)))
17226 (defun org-release-buffers (blist)
17227 "Release all buffers in list, asking the user for confirmation when needed.
17228 When a buffer is unmodified, it is just killed. When modified, it is saved
17229 \(if the user agrees) and then killed."
17230 (let (buf file)
17231 (while (setq buf (pop blist))
17232 (setq file (buffer-file-name buf))
17233 (when (and (buffer-modified-p buf)
17234 file
17235 (y-or-n-p (format "Save file %s? " file)))
17236 (with-current-buffer buf (save-buffer)))
17237 (kill-buffer buf))))
17239 (defvar org-category-table nil)
17240 (defun org-get-category-table ()
17241 "Get the table of categories and positions in current buffer."
17242 (let (tbl)
17243 (save-excursion
17244 (save-restriction
17245 (widen)
17246 (goto-char (point-min))
17247 (while (re-search-forward "^#\\+CATEGORY:[ \t]*\\(.*\\)"
17248 nil t)
17249 (push (cons (match-beginning 1)
17250 (org-trim (match-string 1))) tbl))))
17251 tbl))
17253 (defun org-get-category (&optional pos)
17254 "Get the category applying to position POS."
17255 (if (not org-category-table)
17256 (cond
17257 ((null org-category)
17258 (setq org-category
17259 (if buffer-file-name
17260 (file-name-sans-extension
17261 (file-name-nondirectory buffer-file-name))
17262 "???")))
17263 ((symbolp org-category) (symbol-name org-category))
17264 (t org-category))
17265 (let ((tbl org-category-table)
17266 (pos (or pos (point))))
17267 (while (and tbl (> (caar tbl) pos))
17268 (pop tbl))
17269 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
17270 org-category-table))))))
17271 ;;; Agenda timeline
17273 (defun org-timeline (&optional include-all)
17274 "Show a time-sorted view of the entries in the current org file.
17275 Only entries with a time stamp of today or later will be listed. With
17276 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
17277 under the current date.
17278 If the buffer contains an active region, only check the region for
17279 dates."
17280 (interactive "P")
17281 (require 'calendar)
17282 (org-compile-prefix-format 'timeline)
17283 (org-set-sorting-strategy 'timeline)
17284 (let* ((dopast t)
17285 (dotodo include-all)
17286 (doclosed org-agenda-show-log)
17287 (entry buffer-file-name)
17288 (date (calendar-current-date))
17289 (beg (if (org-region-active-p) (region-beginning) (point-min)))
17290 (end (if (org-region-active-p) (region-end) (point-max)))
17291 (day-numbers (org-get-all-dates beg end 'no-ranges
17292 t doclosed ; always include today
17293 org-timeline-show-empty-dates))
17294 (today (time-to-days (current-time)))
17295 (past t)
17296 args
17297 s e rtn d emptyp)
17298 (setq org-agenda-redo-command
17299 (list 'progn
17300 (list 'switch-to-buffer-other-window (current-buffer))
17301 (list 'org-timeline (list 'quote include-all))))
17302 (if (not dopast)
17303 ;; Remove past dates from the list of dates.
17304 (setq day-numbers (delq nil (mapcar (lambda(x)
17305 (if (>= x today) x nil))
17306 day-numbers))))
17307 (org-prepare-agenda (concat "Timeline "
17308 (file-name-nondirectory buffer-file-name)))
17309 (if doclosed (push :closed args))
17310 (push :timestamp args)
17311 (push :sexp args)
17312 (if dotodo (push :todo args))
17313 (while (setq d (pop day-numbers))
17314 (if (and (listp d) (eq (car d) :omitted))
17315 (progn
17316 (setq s (point))
17317 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
17318 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
17319 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
17320 (if (and (>= d today)
17321 dopast
17322 past)
17323 (progn
17324 (setq past nil)
17325 (insert (make-string 79 ?-) "\n")))
17326 (setq date (calendar-gregorian-from-absolute d))
17327 (setq s (point))
17328 (setq rtn (and (not emptyp)
17329 (apply 'org-agenda-get-day-entries
17330 entry date args)))
17331 (if (or rtn (equal d today) org-timeline-show-empty-dates)
17332 (progn
17333 (insert (calendar-day-name date) " "
17334 (number-to-string (extract-calendar-day date)) " "
17335 (calendar-month-name (extract-calendar-month date)) " "
17336 (number-to-string (extract-calendar-year date)) "\n")
17337 ; FIXME: this gives a timezone problem
17338 ; (insert (format-time-string org-agenda-date-format
17339 ; (calendar-time-from-absolute d 0))
17340 ; "\n")
17341 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
17342 (put-text-property s (1- (point)) 'org-date-line t)
17343 (if (equal d today)
17344 (put-text-property s (1- (point)) 'org-today t))
17345 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
17346 (put-text-property s (1- (point)) 'day d)))))
17347 (goto-char (point-min))
17348 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
17349 (point-min)))
17350 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
17351 (org-finalize-agenda)
17352 (setq buffer-read-only t)))
17354 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
17355 "Return a list of all relevant day numbers from BEG to END buffer positions.
17356 If NO-RANGES is non-nil, include only the start and end dates of a range,
17357 not every single day in the range. If FORCE-TODAY is non-nil, make
17358 sure that TODAY is included in the list. If INACTIVE is non-nil, also
17359 inactive time stamps (those in square brackets) are included.
17360 When EMPTY is non-nil, also include days without any entries."
17361 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
17362 dates dates1 date day day1 day2 ts1 ts2)
17363 (if force-today
17364 (setq dates (list (time-to-days (current-time)))))
17365 (save-excursion
17366 (goto-char beg)
17367 (while (re-search-forward re end t)
17368 (setq day (time-to-days (org-time-string-to-time
17369 (substring (match-string 1) 0 10))))
17370 (or (memq day dates) (push day dates)))
17371 (unless no-ranges
17372 (goto-char beg)
17373 (while (re-search-forward org-tr-regexp end t)
17374 (setq ts1 (substring (match-string 1) 0 10)
17375 ts2 (substring (match-string 2) 0 10)
17376 day1 (time-to-days (org-time-string-to-time ts1))
17377 day2 (time-to-days (org-time-string-to-time ts2)))
17378 (while (< (setq day1 (1+ day1)) day2)
17379 (or (memq day1 dates) (push day1 dates)))))
17380 (setq dates (sort dates '<))
17381 (when empty
17382 (while (setq day (pop dates))
17383 (setq day2 (car dates))
17384 (push day dates1)
17385 (when (and day2 empty)
17386 (if (or (eq empty t)
17387 (and (numberp empty) (<= (- day2 day) empty)))
17388 (while (< (setq day (1+ day)) day2)
17389 (push (list day) dates1))
17390 (push (cons :omitted (- day2 day)) dates1))))
17391 (setq dates (nreverse dates1)))
17392 dates)))
17394 ;;; Agenda Daily/Weekly
17396 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
17397 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
17398 (defvar org-agenda-last-arguments nil
17399 "The arguments of the previous call to org-agenda")
17400 (defvar org-starting-day nil) ; local variable in the agenda buffer
17401 (defvar org-agenda-span nil) ; local variable in the agenda buffer
17402 (defvar org-include-all-loc nil) ; local variable
17405 ;;;###autoload
17406 (defun org-agenda-list (&optional include-all start-day ndays)
17407 "Produce a weekly view from all files in variable `org-agenda-files'.
17408 The view will be for the current week, but from the overview buffer you
17409 will be able to go to other weeks.
17410 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
17411 also be shown, under the current date.
17412 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
17413 on the days are also shown. See the variable `org-log-done' for how
17414 to turn on logging.
17415 START-DAY defaults to TODAY, or to the most recent match for the weekday
17416 given in `org-agenda-start-on-weekday'.
17417 NDAYS defaults to `org-agenda-ndays'."
17418 (interactive "P")
17419 (setq ndays (or ndays org-agenda-ndays)
17420 start-day (or start-day org-agenda-start-day))
17421 (if org-agenda-overriding-arguments
17422 (setq include-all (car org-agenda-overriding-arguments)
17423 start-day (nth 1 org-agenda-overriding-arguments)
17424 ndays (nth 2 org-agenda-overriding-arguments)))
17425 (if (stringp start-day)
17426 ;; Convert to an absolute day number
17427 (setq start-day (time-to-days (org-read-date nil t start-day))))
17428 (setq org-agenda-last-arguments (list include-all start-day ndays))
17429 (org-compile-prefix-format 'agenda)
17430 (org-set-sorting-strategy 'agenda)
17431 (require 'calendar)
17432 (let* ((org-agenda-start-on-weekday
17433 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
17434 org-agenda-start-on-weekday nil))
17435 (thefiles (org-agenda-files))
17436 (files thefiles)
17437 (today (time-to-days (current-time)))
17438 (sd (or start-day today))
17439 (start (if (or (null org-agenda-start-on-weekday)
17440 (< org-agenda-ndays 7))
17442 (let* ((nt (calendar-day-of-week
17443 (calendar-gregorian-from-absolute sd)))
17444 (n1 org-agenda-start-on-weekday)
17445 (d (- nt n1)))
17446 (- sd (+ (if (< d 0) 7 0) d)))))
17447 (day-numbers (list start))
17448 (inhibit-redisplay (not debug-on-error))
17449 s e rtn rtnall file date d start-pos end-pos todayp nd)
17450 (setq org-agenda-redo-command
17451 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
17452 ;; Make the list of days
17453 (setq ndays (or ndays org-agenda-ndays)
17454 nd ndays)
17455 (while (> ndays 1)
17456 (push (1+ (car day-numbers)) day-numbers)
17457 (setq ndays (1- ndays)))
17458 (setq day-numbers (nreverse day-numbers))
17459 (org-prepare-agenda "Day/Week")
17460 (org-set-local 'org-starting-day (car day-numbers))
17461 (org-set-local 'org-include-all-loc include-all)
17462 (org-set-local 'org-agenda-span
17463 (org-agenda-ndays-to-span nd))
17464 (when (and (or include-all org-agenda-include-all-todo)
17465 (member today day-numbers))
17466 (setq files thefiles
17467 rtnall nil)
17468 (while (setq file (pop files))
17469 (catch 'nextfile
17470 (org-check-agenda-file file)
17471 (setq date (calendar-gregorian-from-absolute today)
17472 rtn (org-agenda-get-day-entries
17473 file date :todo))
17474 (setq rtnall (append rtnall rtn))))
17475 (when rtnall
17476 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
17477 (add-text-properties (point-min) (1- (point))
17478 (list 'face 'org-agenda-structure))
17479 (insert (org-finalize-agenda-entries rtnall) "\n")))
17480 (setq s (point))
17481 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
17482 "-agenda:\n")
17483 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
17484 'org-date-line t))
17485 (while (setq d (pop day-numbers))
17486 (setq date (calendar-gregorian-from-absolute d)
17487 s (point))
17488 (if (or (setq todayp (= d today))
17489 (and (not start-pos) (= d sd)))
17490 (setq start-pos (point))
17491 (if (and start-pos (not end-pos))
17492 (setq end-pos (point))))
17493 (setq files thefiles
17494 rtnall nil)
17495 (while (setq file (pop files))
17496 (catch 'nextfile
17497 (org-check-agenda-file file)
17498 (if org-agenda-show-log
17499 (setq rtn (org-agenda-get-day-entries
17500 file date
17501 :deadline :scheduled :timestamp :sexp :closed))
17502 (setq rtn (org-agenda-get-day-entries
17503 file date
17504 :deadline :scheduled :sexp :timestamp)))
17505 (setq rtnall (append rtnall rtn))))
17506 (if org-agenda-include-diary
17507 (progn
17508 (require 'diary-lib)
17509 (setq rtn (org-get-entries-from-diary date))
17510 (setq rtnall (append rtnall rtn))))
17511 (if (or rtnall org-agenda-show-all-dates)
17512 (progn
17513 (insert (format "%-9s %2d %s %4d\n"
17514 (calendar-day-name date)
17515 (extract-calendar-day date)
17516 (calendar-month-name (extract-calendar-month date))
17517 (extract-calendar-year date)))
17518 ; FIXME: this gives a timezone problem
17519 ; (insert (format-time-string org-agenda-date-format
17520 ; (calendar-time-from-absolute d 0)) "\n")
17521 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
17522 (put-text-property s (1- (point)) 'org-date-line t)
17523 (if todayp (put-text-property s (1- (point)) 'org-today t))
17524 (if rtnall (insert
17525 (org-finalize-agenda-entries
17526 (org-agenda-add-time-grid-maybe
17527 rtnall nd todayp))
17528 "\n"))
17529 (put-text-property s (1- (point)) 'day d))))
17530 (goto-char (point-min))
17531 (org-fit-agenda-window)
17532 (unless (and (pos-visible-in-window-p (point-min))
17533 (pos-visible-in-window-p (point-max)))
17534 (goto-char (1- (point-max)))
17535 (recenter -1)
17536 (if (not (pos-visible-in-window-p (or start-pos 1)))
17537 (progn
17538 (goto-char (or start-pos 1))
17539 (recenter 1))))
17540 (goto-char (or start-pos 1))
17541 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
17542 (org-finalize-agenda)
17543 (setq buffer-read-only t)
17544 (message "")))
17546 (defun org-agenda-ndays-to-span (n)
17547 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
17549 ;;; Agenda TODO list
17551 (defvar org-select-this-todo-keyword nil)
17552 (defvar org-last-arg nil)
17554 ;;;###autoload
17555 (defun org-todo-list (arg)
17556 "Show all TODO entries from all agenda file in a single list.
17557 The prefix arg can be used to select a specific TODO keyword and limit
17558 the list to these. When using \\[universal-argument], you will be prompted
17559 for a keyword. A numeric prefix directly selects the Nth keyword in
17560 `org-todo-keywords-1'."
17561 (interactive "P")
17562 (require 'calendar)
17563 (org-compile-prefix-format 'todo)
17564 (org-set-sorting-strategy 'todo)
17565 (org-prepare-agenda "TODO")
17566 (let* ((today (time-to-days (current-time)))
17567 (date (calendar-gregorian-from-absolute today))
17568 (kwds org-todo-keywords-for-agenda)
17569 (completion-ignore-case t)
17570 (org-select-this-todo-keyword
17571 (if (stringp arg) arg
17572 (and arg (integerp arg) (> arg 0)
17573 (nth (1- arg) kwds))))
17574 rtn rtnall files file pos)
17575 (when (equal arg '(4))
17576 (setq org-select-this-todo-keyword
17577 (completing-read "Keyword (or KWD1|K2D2|...): "
17578 (mapcar 'list kwds) nil nil)))
17579 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
17580 (org-set-local 'org-last-arg arg)
17581 (setq org-agenda-redo-command
17582 '(org-todo-list (or current-prefix-arg org-last-arg)))
17583 (setq files (org-agenda-files)
17584 rtnall nil)
17585 (while (setq file (pop files))
17586 (catch 'nextfile
17587 (org-check-agenda-file file)
17588 (setq rtn (org-agenda-get-day-entries file date :todo))
17589 (setq rtnall (append rtnall rtn))))
17590 (if org-agenda-overriding-header
17591 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
17592 nil 'face 'org-agenda-structure) "\n")
17593 (insert "Global list of TODO items of type: ")
17594 (add-text-properties (point-min) (1- (point))
17595 (list 'face 'org-agenda-structure))
17596 (setq pos (point))
17597 (insert (or org-select-this-todo-keyword "ALL") "\n")
17598 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
17599 (setq pos (point))
17600 (unless org-agenda-multi
17601 (insert "Available with `N r': (0)ALL")
17602 (let ((n 0) s)
17603 (mapc (lambda (x)
17604 (setq s (format "(%d)%s" (setq n (1+ n)) x))
17605 (if (> (+ (current-column) (string-width s) 1) (frame-width))
17606 (insert "\n "))
17607 (insert " " s))
17608 kwds))
17609 (insert "\n"))
17610 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
17611 (when rtnall
17612 (insert (org-finalize-agenda-entries rtnall) "\n"))
17613 (goto-char (point-min))
17614 (org-fit-agenda-window)
17615 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
17616 (org-finalize-agenda)
17617 (setq buffer-read-only t)))
17619 ;;; Agenda tags match
17621 ;;;###autoload
17622 (defun org-tags-view (&optional todo-only match)
17623 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
17624 The prefix arg TODO-ONLY limits the search to TODO entries."
17625 (interactive "P")
17626 (org-compile-prefix-format 'tags)
17627 (org-set-sorting-strategy 'tags)
17628 (let* ((org-tags-match-list-sublevels
17629 (if todo-only t org-tags-match-list-sublevels))
17630 (completion-ignore-case t)
17631 rtn rtnall files file pos matcher
17632 buffer)
17633 (setq matcher (org-make-tags-matcher match)
17634 match (car matcher) matcher (cdr matcher))
17635 (org-prepare-agenda (concat "TAGS " match))
17636 (setq org-agenda-redo-command
17637 (list 'org-tags-view (list 'quote todo-only)
17638 (list 'if 'current-prefix-arg nil match)))
17639 (setq files (org-agenda-files)
17640 rtnall nil)
17641 (while (setq file (pop files))
17642 (catch 'nextfile
17643 (org-check-agenda-file file)
17644 (setq buffer (if (file-exists-p file)
17645 (org-get-agenda-file-buffer file)
17646 (error "No such file %s" file)))
17647 (if (not buffer)
17648 ;; If file does not exist, merror message to agenda
17649 (setq rtn (list
17650 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
17651 rtnall (append rtnall rtn))
17652 (with-current-buffer buffer
17653 (unless (org-mode-p)
17654 (error "Agenda file %s is not in `org-mode'" file))
17655 (setq org-category-table (org-get-category-table))
17656 (save-excursion
17657 (save-restriction
17658 (if org-agenda-restrict
17659 (narrow-to-region org-agenda-restrict-begin
17660 org-agenda-restrict-end)
17661 (widen))
17662 (setq rtn (org-scan-tags 'agenda matcher todo-only))
17663 (setq rtnall (append rtnall rtn))))))))
17664 (if org-agenda-overriding-header
17665 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
17666 nil 'face 'org-agenda-structure) "\n")
17667 (insert "Headlines with TAGS match: ")
17668 (add-text-properties (point-min) (1- (point))
17669 (list 'face 'org-agenda-structure))
17670 (setq pos (point))
17671 (insert match "\n")
17672 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
17673 (setq pos (point))
17674 (unless org-agenda-multi
17675 (insert "Press `C-u r' to search again with new search string\n"))
17676 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
17677 (when rtnall
17678 (insert (org-finalize-agenda-entries rtnall) "\n"))
17679 (goto-char (point-min))
17680 (org-fit-agenda-window)
17681 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
17682 (org-finalize-agenda)
17683 (setq buffer-read-only t)))
17685 ;;; Agenda Finding stuck projects
17687 (defvar org-agenda-skip-regexp nil
17688 "Regular expression used in skipping subtrees for the agenda.
17689 This is basically a temporary global variable that can be set and then
17690 used by user-defined selections using `org-agenda-skip-function'.")
17692 (defvar org-agenda-overriding-header nil
17693 "When this is set during todo and tags searches, will replace header.")
17695 (defun org-agenda-skip-subtree-when-regexp-matches ()
17696 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
17697 If yes, it returns the end position of this tree, causing agenda commands
17698 to skip this subtree. This is a function that can be put into
17699 `org-agenda-skip-function' for the duration of a command."
17700 (let ((end (save-excursion (org-end-of-subtree t)))
17701 skip)
17702 (save-excursion
17703 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
17704 (and skip end)))
17706 (defun org-agenda-skip-entry-if (&rest conditions)
17707 "Skip entry is any of CONDITIONS is true.
17708 See `org-agenda-skip-if for details."
17709 (org-agenda-skip-if nil conditions))
17710 (defun org-agenda-skip-subtree-if (&rest conditions)
17711 "Skip entry is any of CONDITIONS is true.
17712 See `org-agenda-skip-if for details."
17713 (org-agenda-skip-if t conditions))
17715 (defun org-agenda-skip-if (subtree conditions)
17716 "Checks current entity for CONDITIONS.
17717 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
17718 the entry, i.e. the text before the next heading is checked.
17720 CONDITIONS is a list of symbols, boolean OR is used to combine the results
17721 from different tests. Valid conditions are:
17723 scheduled Check if there is a scheduled cookie
17724 notscheduled Check if there is no scheduled cookie
17725 deadline Check if there is a deadline
17726 notdeadline Check if there is no deadline
17727 regexp Check if regexp matches
17728 notregexp Check if regexp does not match.
17730 The regexp is taken from the conditions list, it must com right after the
17731 `regexp' of `notregexp' element.
17733 If any of these conditions is met, this function returns the end point of
17734 the entity, causing the search to continue from there. This is a function
17735 that can be put into `org-agenda-skip-function' for the duration of a command."
17736 (let (beg end m r)
17737 (org-back-to-heading t)
17738 (setq beg (point)
17739 end (if subtree
17740 (progn (org-end-of-subtree t) (point))
17741 (progn (outline-next-heading) (1- (point)))))
17742 (goto-char beg)
17743 (and
17745 (and (memq 'scheduled conditions)
17746 (re-search-forward org-scheduled-time-regexp end t))
17747 (and (memq 'notscheduled conditions)
17748 (not (re-search-forward org-scheduled-time-regexp end t)))
17749 (and (memq 'deadline conditions)
17750 (re-search-forward org-deadline-time-regexp end t))
17751 (and (memq 'notdeadline conditions)
17752 (not (re-search-forward org-deadline-time-regexp end t)))
17753 (and (setq m (memq 'regexp conditions))
17754 (stringp (setq r (nth 1 m)))
17755 (re-search-forward (nth 1 m) end t))
17756 (and (setq m (memq 'notregexp conditions))
17757 (stringp (setq r (nth 1 m)))
17758 (not (re-search-forward (nth 1 m) end t))))
17759 end)))
17761 (defun org-agenda-list-stuck-projects (&rest ignore)
17762 "Create agenda view for projects that are stuck.
17763 Stuck projects are project that have no next actions. For the definitions
17764 of what a project is and how to check if it stuck, customize the variable
17765 `org-stuck-projects'.
17766 MATCH is being ignored."
17767 (interactive)
17768 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
17769 ;; FIXME: we could have used org-agenda-skip-if here.
17770 (org-agenda-overriding-header "List of stuck projects: ")
17771 (matcher (nth 0 org-stuck-projects))
17772 (todo (nth 1 org-stuck-projects))
17773 (todo-wds (if (member "*" todo)
17774 (progn
17775 (org-prepare-agenda-buffers (org-agenda-files))
17776 (org-delete-all
17777 org-done-keywords-for-agenda
17778 (copy-sequence org-todo-keywords-for-agenda)))
17779 todo))
17780 (todo-re (concat "^\\*+[ \t]+\\("
17781 (mapconcat 'identity todo-wds "\\|")
17782 "\\)\\>"))
17783 (tags (nth 2 org-stuck-projects))
17784 (tags-re (if (member "*" tags)
17785 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
17786 (concat "^\\*+ .*:\\("
17787 (mapconcat 'identity tags "\\|")
17788 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
17789 (gen-re (nth 3 org-stuck-projects))
17790 (re-list
17791 (delq nil
17792 (list
17793 (if todo todo-re)
17794 (if tags tags-re)
17795 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
17796 gen-re)))))
17797 (setq org-agenda-skip-regexp
17798 (if re-list
17799 (mapconcat 'identity re-list "\\|")
17800 (error "No information how to identify unstuck projects")))
17801 (org-tags-view nil matcher)
17802 (with-current-buffer org-agenda-buffer-name
17803 (setq org-agenda-redo-command
17804 '(org-agenda-list-stuck-projects
17805 (or current-prefix-arg org-last-arg))))))
17807 ;;; Diary integration
17809 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
17811 (defun org-get-entries-from-diary (date)
17812 "Get the (Emacs Calendar) diary entries for DATE."
17813 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
17814 (diary-display-hook '(fancy-diary-display))
17815 (list-diary-entries-hook
17816 (cons 'org-diary-default-entry list-diary-entries-hook))
17817 (diary-file-name-prefix-function nil) ; turn this feature off
17818 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
17819 entries
17820 (org-disable-agenda-to-diary t))
17821 (save-excursion
17822 (save-window-excursion
17823 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
17824 (if (not (get-buffer fancy-diary-buffer))
17825 (setq entries nil)
17826 (with-current-buffer fancy-diary-buffer
17827 (setq buffer-read-only nil)
17828 (if (zerop (buffer-size))
17829 ;; No entries
17830 (setq entries nil)
17831 ;; Omit the date and other unnecessary stuff
17832 (org-agenda-cleanup-fancy-diary)
17833 ;; Add prefix to each line and extend the text properties
17834 (if (zerop (buffer-size))
17835 (setq entries nil)
17836 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
17837 (set-buffer-modified-p nil)
17838 (kill-buffer fancy-diary-buffer)))
17839 (when entries
17840 (setq entries (org-split-string entries "\n"))
17841 (setq entries
17842 (mapcar
17843 (lambda (x)
17844 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
17845 ;; Extend the text properties to the beginning of the line
17846 (org-add-props x (text-properties-at (1- (length x)) x)
17847 'type "diary" 'date date))
17848 entries)))))
17850 (defun org-agenda-cleanup-fancy-diary ()
17851 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
17852 This gets rid of the date, the underline under the date, and
17853 the dummy entry installed by `org-mode' to ensure non-empty diary for each
17854 date. It also removes lines that contain only whitespace."
17855 (goto-char (point-min))
17856 (if (looking-at ".*?:[ \t]*")
17857 (progn
17858 (replace-match "")
17859 (re-search-forward "\n=+$" nil t)
17860 (replace-match "")
17861 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
17862 (re-search-forward "\n=+$" nil t)
17863 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
17864 (goto-char (point-min))
17865 (while (re-search-forward "^ +\n" nil t)
17866 (replace-match ""))
17867 (goto-char (point-min))
17868 (if (re-search-forward "^Org-mode dummy\n?" nil t)
17869 (replace-match "")))
17871 ;; Make sure entries from the diary have the right text properties.
17872 (eval-after-load "diary-lib"
17873 '(if (boundp 'diary-modify-entry-list-string-function)
17874 ;; We can rely on the hook, nothing to do
17876 ;; Hook not avaiable, must use advice to make this work
17877 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
17878 "Make the position visible."
17879 (if (and org-disable-agenda-to-diary ;; called from org-agenda
17880 (stringp string)
17881 buffer-file-name)
17882 (setq string (org-modify-diary-entry-string string))))))
17884 (defun org-modify-diary-entry-string (string)
17885 "Add text properties to string, allowing org-mode to act on it."
17886 (org-add-props string nil
17887 'mouse-face 'highlight
17888 'keymap org-agenda-keymap
17889 'help-echo (if buffer-file-name
17890 (format "mouse-2 or RET jump to diary file %s"
17891 (abbreviate-file-name buffer-file-name))
17893 'org-agenda-diary-link t
17894 'org-marker (org-agenda-new-marker (point-at-bol))))
17896 (defun org-diary-default-entry ()
17897 "Add a dummy entry to the diary.
17898 Needed to avoid empty dates which mess up holiday display."
17899 ;; Catch the error if dealing with the new add-to-diary-alist
17900 (when org-disable-agenda-to-diary
17901 (condition-case nil
17902 (add-to-diary-list original-date "Org-mode dummy" "")
17903 (error
17904 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
17906 ;;;###autoload
17907 (defun org-diary (&rest args)
17908 "Return diary information from org-files.
17909 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
17910 It accesses org files and extracts information from those files to be
17911 listed in the diary. The function accepts arguments specifying what
17912 items should be listed. The following arguments are allowed:
17914 :timestamp List the headlines of items containing a date stamp or
17915 date range matching the selected date. Deadlines will
17916 also be listed, on the expiration day.
17918 :sexp FIXME
17920 :deadline List any deadlines past due, or due within
17921 `org-deadline-warning-days'. The listing occurs only
17922 in the diary for *today*, not at any other date. If
17923 an entry is marked DONE, it is no longer listed.
17925 :scheduled List all items which are scheduled for the given date.
17926 The diary for *today* also contains items which were
17927 scheduled earlier and are not yet marked DONE.
17929 :todo List all TODO items from the org-file. This may be a
17930 long list - so this is not turned on by default.
17931 Like deadlines, these entries only show up in the
17932 diary for *today*, not at any other date.
17934 The call in the diary file should look like this:
17936 &%%(org-diary) ~/path/to/some/orgfile.org
17938 Use a separate line for each org file to check. Or, if you omit the file name,
17939 all files listed in `org-agenda-files' will be checked automatically:
17941 &%%(org-diary)
17943 If you don't give any arguments (as in the example above), the default
17944 arguments (:deadline :scheduled :timestamp :sexp) are used.
17945 So the example above may also be written as
17947 &%%(org-diary :deadline :timestamp :sexp :scheduled)
17949 The function expects the lisp variables `entry' and `date' to be provided
17950 by the caller, because this is how the calendar works. Don't use this
17951 function from a program - use `org-agenda-get-day-entries' instead."
17952 (org-agenda-maybe-reset-markers)
17953 (org-compile-prefix-format 'agenda)
17954 (org-set-sorting-strategy 'agenda)
17955 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
17956 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
17957 (list entry)
17958 (org-agenda-files t)))
17959 file rtn results)
17960 (org-prepare-agenda-buffers files)
17961 ;; If this is called during org-agenda, don't return any entries to
17962 ;; the calendar. Org Agenda will list these entries itself.
17963 (if org-disable-agenda-to-diary (setq files nil))
17964 (while (setq file (pop files))
17965 (setq rtn (apply 'org-agenda-get-day-entries file date args))
17966 (setq results (append results rtn)))
17967 (if results
17968 (concat (org-finalize-agenda-entries results) "\n"))))
17970 ;;; Agenda entry finders
17972 (defun org-agenda-get-day-entries (file date &rest args)
17973 "Does the work for `org-diary' and `org-agenda'.
17974 FILE is the path to a file to be checked for entries. DATE is date like
17975 the one returned by `calendar-current-date'. ARGS are symbols indicating
17976 which kind of entries should be extracted. For details about these, see
17977 the documentation of `org-diary'."
17978 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
17979 (let* ((org-startup-folded nil)
17980 (org-startup-align-all-tables nil)
17981 (buffer (if (file-exists-p file)
17982 (org-get-agenda-file-buffer file)
17983 (error "No such file %s" file)))
17984 arg results rtn)
17985 (if (not buffer)
17986 ;; If file does not exist, make sure an error message ends up in diary
17987 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
17988 (with-current-buffer buffer
17989 (unless (org-mode-p)
17990 (error "Agenda file %s is not in `org-mode'" file))
17991 (setq org-category-table (org-get-category-table))
17992 (let ((case-fold-search nil))
17993 (save-excursion
17994 (save-restriction
17995 (if org-agenda-restrict
17996 (narrow-to-region org-agenda-restrict-begin
17997 org-agenda-restrict-end)
17998 (widen))
17999 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
18000 (while (setq arg (pop args))
18001 (cond
18002 ((and (eq arg :todo)
18003 (equal date (calendar-current-date)))
18004 (setq rtn (org-agenda-get-todos))
18005 (setq results (append results rtn)))
18006 ((eq arg :timestamp)
18007 (setq rtn (org-agenda-get-blocks))
18008 (setq results (append results rtn))
18009 (setq rtn (org-agenda-get-timestamps))
18010 (setq results (append results rtn)))
18011 ((eq arg :sexp)
18012 (setq rtn (org-agenda-get-sexps))
18013 (setq results (append results rtn)))
18014 ((eq arg :scheduled)
18015 (setq rtn (org-agenda-get-scheduled))
18016 (setq results (append results rtn)))
18017 ((eq arg :closed)
18018 (setq rtn (org-agenda-get-closed))
18019 (setq results (append results rtn)))
18020 ((eq arg :deadline)
18021 (setq rtn (org-agenda-get-deadlines))
18022 (setq results (append results rtn))))))))
18023 results))))
18025 ;; FIXME: this works only if the cursor is not at the
18026 ;; beginning of the entry
18027 (defun org-entry-is-done-p ()
18028 "Is the current entry marked DONE?"
18029 (save-excursion
18030 (and (re-search-backward "[\r\n]\\*+ " nil t)
18031 (looking-at org-nl-done-regexp))))
18033 (defun org-at-date-range-p (&optional inactive-ok)
18034 "Is the cursor inside a date range?"
18035 (interactive)
18036 (save-excursion
18037 (catch 'exit
18038 (let ((pos (point)))
18039 (skip-chars-backward "^[<\r\n")
18040 (skip-chars-backward "<[")
18041 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
18042 (>= (match-end 0) pos)
18043 (throw 'exit t))
18044 (skip-chars-backward "^<[\r\n")
18045 (skip-chars-backward "<[")
18046 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
18047 (>= (match-end 0) pos)
18048 (throw 'exit t)))
18049 nil)))
18051 (defun org-agenda-get-todos ()
18052 "Return the TODO information for agenda display."
18053 (let* ((props (list 'face nil
18054 'done-face 'org-done
18055 'org-not-done-regexp org-not-done-regexp
18056 'org-todo-regexp org-todo-regexp
18057 'mouse-face 'highlight
18058 'keymap org-agenda-keymap
18059 'help-echo
18060 (format "mouse-2 or RET jump to org file %s"
18061 (abbreviate-file-name buffer-file-name))))
18062 ;; FIXME: get rid of the \n at some point but watch out
18063 (regexp (concat "^\\*+[ \t]+\\("
18064 (if org-select-this-todo-keyword
18065 (if (equal org-select-this-todo-keyword "*")
18066 org-todo-regexp
18067 (concat "\\<\\("
18068 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
18069 "\\)\\>"))
18070 org-not-done-regexp)
18071 "[^\n\r]*\\)"))
18072 marker priority category tags
18073 ee txt beg end)
18074 (goto-char (point-min))
18075 (while (re-search-forward regexp nil t)
18076 (catch :skip
18077 (save-match-data
18078 (beginning-of-line)
18079 (setq beg (point) end (progn (outline-next-heading) (point)))
18080 (when (or (and org-agenda-todo-ignore-scheduled (goto-char beg)
18081 (re-search-forward org-scheduled-time-regexp end t))
18082 (and org-agenda-todo-ignore-deadlines (goto-char beg)
18083 (re-search-forward org-deadline-time-regexp end t)
18084 (org-deadline-close (match-string 1))))
18085 (goto-char beg)
18086 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
18087 (throw :skip nil)))
18088 (goto-char beg)
18089 (org-agenda-skip)
18090 (goto-char (match-beginning 1))
18091 (setq marker (org-agenda-new-marker (match-beginning 0))
18092 category (org-get-category)
18093 tags (org-get-tags-at (point))
18094 txt (org-format-agenda-item "" (match-string 1) category tags)
18095 priority (1+ (org-get-priority txt)))
18096 (org-add-props txt props
18097 'org-marker marker 'org-hd-marker marker
18098 'priority priority 'org-category category
18099 'type "todo")
18100 (push txt ee)
18101 (if org-agenda-todo-list-sublevels
18102 (goto-char (match-end 1))
18103 (org-end-of-subtree 'invisible))))
18104 (nreverse ee)))
18106 (defconst org-agenda-no-heading-message
18107 "No heading for this item in buffer or region.")
18109 (defun org-agenda-get-timestamps ()
18110 "Return the date stamp information for agenda display."
18111 (let* ((props (list 'face nil
18112 'org-not-done-regexp org-not-done-regexp
18113 'org-todo-regexp org-todo-regexp
18114 'mouse-face 'highlight
18115 'keymap org-agenda-keymap
18116 'help-echo
18117 (format "mouse-2 or RET jump to org file %s"
18118 (abbreviate-file-name buffer-file-name))))
18119 (d1 (calendar-absolute-from-gregorian date))
18120 (regexp
18121 (concat
18122 (regexp-quote
18123 (substring
18124 (format-time-string
18125 (car org-time-stamp-formats)
18126 (apply 'encode-time ; DATE bound by calendar
18127 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
18128 0 11))
18129 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
18130 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
18131 marker hdmarker deadlinep scheduledp donep tmp priority category
18132 ee txt timestr tags b0 b3 e3)
18133 (goto-char (point-min))
18134 (while (re-search-forward regexp nil t)
18135 (setq b0 (match-beginning 0)
18136 b3 (match-beginning 3) e3 (match-end 3))
18137 (catch :skip
18138 (and (org-at-date-range-p) (throw :skip nil))
18139 (org-agenda-skip)
18140 (if (and (match-end 1)
18141 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
18142 (throw :skip nil))
18143 (if (and e3
18144 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
18145 (throw :skip nil))
18146 (setq marker (org-agenda-new-marker b0)
18147 category (org-get-category b0)
18148 tmp (buffer-substring (max (point-min)
18149 (- b0 org-ds-keyword-length))
18151 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
18152 deadlinep (string-match org-deadline-regexp tmp)
18153 scheduledp (string-match org-scheduled-regexp tmp)
18154 donep (org-entry-is-done-p))
18155 (if (or scheduledp deadlinep) (throw :skip t))
18156 (if (string-match ">" timestr)
18157 ;; substring should only run to end of time stamp
18158 (setq timestr (substring timestr 0 (match-end 0))))
18159 (save-excursion
18160 (if (re-search-backward "^\\*+ " nil t)
18161 (progn
18162 (goto-char (match-beginning 0))
18163 (setq hdmarker (org-agenda-new-marker)
18164 tags (org-get-tags-at))
18165 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
18166 (setq txt (org-format-agenda-item
18167 nil (match-string 1) category tags timestr)))
18168 (setq txt org-agenda-no-heading-message))
18169 (setq priority (org-get-priority txt))
18170 (org-add-props txt props
18171 'org-marker marker 'org-hd-marker hdmarker)
18172 (org-add-props txt nil 'priority priority
18173 'org-category category 'date date
18174 'type "timestamp")
18175 (push txt ee))
18176 (outline-next-heading)))
18177 (nreverse ee)))
18179 (defun org-agenda-get-sexps ()
18180 "Return the sexp information for agenda display."
18181 (require 'diary-lib)
18182 (let* ((props (list 'face nil
18183 'mouse-face 'highlight
18184 'keymap org-agenda-keymap
18185 'help-echo
18186 (format "mouse-2 or RET jump to org file %s"
18187 (abbreviate-file-name buffer-file-name))))
18188 (regexp "^&?%%(")
18189 marker category ee txt tags entry result beg b sexp sexp-entry)
18190 (goto-char (point-min))
18191 (while (re-search-forward regexp nil t)
18192 (catch :skip
18193 (org-agenda-skip)
18194 (setq beg (match-beginning 0))
18195 (goto-char (1- (match-end 0)))
18196 (setq b (point))
18197 (forward-sexp 1)
18198 (setq sexp (buffer-substring b (point)))
18199 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
18200 (org-trim (match-string 1))
18201 ""))
18202 (setq result (org-diary-sexp-entry sexp sexp-entry date))
18203 (when result
18204 (setq marker (org-agenda-new-marker beg)
18205 category (org-get-category beg))
18207 (if (string-match "\\S-" result)
18208 (setq txt result)
18209 (setq txt "SEXP entry returned empty string"))
18211 (setq txt (org-format-agenda-item
18212 "" txt category tags 'time))
18213 (org-add-props txt props 'org-marker marker)
18214 (org-add-props txt nil
18215 'org-category category 'date date
18216 'type "sexp")
18217 (push txt ee))))
18218 (nreverse ee)))
18220 (defun org-agenda-get-closed ()
18221 "Return the logged TODO entries for agenda display."
18222 (let* ((props (list 'mouse-face 'highlight
18223 'org-not-done-regexp org-not-done-regexp
18224 'org-todo-regexp org-todo-regexp
18225 'keymap org-agenda-keymap
18226 'help-echo
18227 (format "mouse-2 or RET jump to org file %s"
18228 (abbreviate-file-name buffer-file-name))))
18229 (regexp (concat
18230 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
18231 (regexp-quote
18232 (substring
18233 (format-time-string
18234 (car org-time-stamp-formats)
18235 (apply 'encode-time ; DATE bound by calendar
18236 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
18237 1 11))))
18238 marker hdmarker priority category tags closedp
18239 ee txt timestr)
18240 (goto-char (point-min))
18241 (while (re-search-forward regexp nil t)
18242 (catch :skip
18243 (org-agenda-skip)
18244 (setq marker (org-agenda-new-marker (match-beginning 0))
18245 closedp (equal (match-string 1) org-closed-string)
18246 category (org-get-category (match-beginning 0))
18247 timestr (buffer-substring (match-beginning 0) (point-at-eol))
18248 ;; donep (org-entry-is-done-p)
18250 (if (string-match "\\]" timestr)
18251 ;; substring should only run to end of time stamp
18252 (setq timestr (substring timestr 0 (match-end 0))))
18253 (save-excursion
18254 (if (re-search-backward "^\\*+ " nil t)
18255 (progn
18256 (goto-char (match-beginning 0))
18257 (setq hdmarker (org-agenda-new-marker)
18258 tags (org-get-tags-at))
18259 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
18260 (setq txt (org-format-agenda-item
18261 (if closedp "Closed: " "Clocked: ")
18262 (match-string 1) category tags timestr)))
18263 (setq txt org-agenda-no-heading-message))
18264 (setq priority 100000)
18265 (org-add-props txt props
18266 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
18267 'priority priority 'org-category category
18268 'type "closed" 'date date
18269 'undone-face 'org-warning 'done-face 'org-done)
18270 (push txt ee))
18271 (outline-next-heading)))
18272 (nreverse ee)))
18274 (defun org-agenda-get-deadlines ()
18275 "Return the deadline information for agenda display."
18276 (let* ((props (list 'mouse-face 'highlight
18277 'org-not-done-regexp org-not-done-regexp
18278 'org-todo-regexp org-todo-regexp
18279 'keymap org-agenda-keymap
18280 'help-echo
18281 (format "mouse-2 or RET jump to org file %s"
18282 (abbreviate-file-name buffer-file-name))))
18283 (regexp org-deadline-time-regexp)
18284 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
18285 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
18286 d2 diff dfrac wdays pos pos1 category tags
18287 ee txt head face s upcomingp donep timestr)
18288 (goto-char (point-min))
18289 (while (re-search-forward regexp nil t)
18290 (catch :skip
18291 (org-agenda-skip)
18292 (setq s (match-string 1)
18293 pos (1- (match-beginning 1))
18294 d2 (org-time-string-to-absolute (match-string 1) d1)
18295 diff (- d2 d1))
18296 (if (string-match "-\\([0-9]+\\)\\([dwmy]\\)\\'" s)
18297 (setq wdays
18298 (floor
18299 (* (string-to-number (match-string 1 s))
18300 (cdr (assoc (match-string 2 s)
18301 '(("d" . 1) ("w" . 7)
18302 ("m" . 30.4) ("y" . 365.25)))))))
18303 (setq wdays org-deadline-warning-days))
18304 (setq dfrac (/ (* 1.0 (- wdays diff)) wdays))
18305 (setq upcomingp (and todayp (> diff 0)))
18306 ;; When to show a deadline in the calendar:
18307 ;; If the expiration is within wdays warning time.
18308 ;; Past-due deadlines are only shown on the current date
18309 (if (or (and (<= diff wdays) todayp)
18310 (= diff 0))
18311 (save-excursion
18312 (setq category (org-get-category))
18313 (if (re-search-backward "^\\*+[ \t]+" nil t)
18314 (progn
18315 (goto-char (match-end 0))
18316 (setq pos1 (match-beginning 0))
18317 (setq tags (org-get-tags-at pos1))
18318 (setq head (buffer-substring-no-properties
18319 (point)
18320 (progn (skip-chars-forward "^\r\n")
18321 (point))))
18322 (setq donep (string-match org-looking-at-done-regexp head))
18323 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
18324 (setq timestr
18325 (concat (substring s (match-beginning 1)) " "))
18326 (setq timestr nil))
18327 (if (and donep
18328 (or org-agenda-skip-deadline-if-done
18329 (not (= diff 0))))
18330 (setq txt nil)
18331 (setq txt (org-format-agenda-item
18332 (if (= diff 0)
18333 "Deadline: "
18334 (format "In %3d d.: " diff))
18335 head category tags timestr))))
18336 (setq txt org-agenda-no-heading-message))
18337 (when txt
18338 (setq face (org-agenda-deadline-face dfrac))
18339 (org-add-props txt props
18340 'org-marker (org-agenda-new-marker pos)
18341 'org-hd-marker (org-agenda-new-marker pos1)
18342 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
18343 (org-get-priority txt))
18344 'org-category category
18345 'type (if upcomingp "upcoming-deadline" "deadline")
18346 'date (if upcomingp date d2)
18347 'face (if donep 'org-done face)
18348 'undone-face face 'done-face 'org-done)
18349 (push txt ee))))))
18350 ee))
18352 (defun org-agenda-deadline-face (fraction)
18353 "Return the face to displaying a deadline item.
18354 FRACTION is what fraction of the head-warning time has passed."
18355 (let ((faces org-agenda-deadline-faces) f)
18356 (catch 'exit
18357 (while (setq f (pop faces))
18358 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
18360 (defun org-agenda-get-scheduled ()
18361 "Return the scheduled information for agenda display."
18362 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
18363 'org-todo-regexp org-todo-regexp
18364 'done-face 'org-done
18365 'mouse-face 'highlight
18366 'keymap org-agenda-keymap
18367 'help-echo
18368 (format "mouse-2 or RET jump to org file %s"
18369 (abbreviate-file-name buffer-file-name))))
18370 (regexp org-scheduled-time-regexp)
18371 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
18372 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
18373 d2 diff pos pos1 category tags
18374 ee txt head pastschedp donep face timestr s)
18375 (goto-char (point-min))
18376 (while (re-search-forward regexp nil t)
18377 (catch :skip
18378 (org-agenda-skip)
18379 (setq s (match-string 1)
18380 pos (1- (match-beginning 1))
18381 d2 (org-time-string-to-absolute (match-string 1) d1)
18382 diff (- d2 d1))
18383 (setq pastschedp (and todayp (< diff 0)))
18384 ;; When to show a scheduled item in the calendar:
18385 ;; If it is on or past the date.
18386 (if (or (and (< diff 0) todayp)
18387 (= diff 0))
18388 (save-excursion
18389 (setq category (org-get-category))
18390 (if (re-search-backward "^\\*+[ \t]+" nil t)
18391 (progn
18392 (goto-char (match-end 0))
18393 (setq pos1 (match-beginning 0))
18394 (setq tags (org-get-tags-at))
18395 (setq head (buffer-substring-no-properties
18396 (point)
18397 (progn (skip-chars-forward "^\r\n") (point))))
18398 (setq donep (string-match org-looking-at-done-regexp head))
18399 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
18400 (setq timestr
18401 (concat (substring s (match-beginning 1)) " "))
18402 (setq timestr nil))
18403 (if (and donep
18404 (or org-agenda-skip-scheduled-if-done
18405 (not (= diff 0))))
18406 (setq txt nil)
18407 (setq txt (org-format-agenda-item
18408 (if (= diff 0)
18409 "Scheduled: "
18410 (format "Sched.%2dx: " (- 1 diff)))
18411 head category tags timestr))))
18412 (setq txt org-agenda-no-heading-message))
18413 (when txt
18414 (setq face (if pastschedp
18415 'org-scheduled-previously
18416 'org-scheduled-today))
18417 (org-add-props txt props
18418 'undone-face face
18419 'face (if donep 'org-done face)
18420 'org-marker (org-agenda-new-marker pos)
18421 'org-hd-marker (org-agenda-new-marker pos1)
18422 'type (if pastschedp "past-scheduled" "scheduled")
18423 'date (if pastschedp d2 date)
18424 'priority (+ (- 5 diff) (org-get-priority txt))
18425 'org-category category)
18426 (push txt ee))))))
18427 ee))
18429 (defun org-agenda-get-blocks ()
18430 "Return the date-range information for agenda display."
18431 (let* ((props (list 'face nil
18432 'org-not-done-regexp org-not-done-regexp
18433 'org-todo-regexp org-todo-regexp
18434 'mouse-face 'highlight
18435 'keymap org-agenda-keymap
18436 'help-echo
18437 (format "mouse-2 or RET jump to org file %s"
18438 (abbreviate-file-name buffer-file-name))))
18439 (regexp org-tr-regexp)
18440 (d0 (calendar-absolute-from-gregorian date))
18441 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
18442 (goto-char (point-min))
18443 (while (re-search-forward regexp nil t)
18444 (catch :skip
18445 (org-agenda-skip)
18446 (setq pos (point))
18447 (setq timestr (match-string 0)
18448 s1 (match-string 1)
18449 s2 (match-string 2)
18450 d1 (time-to-days (org-time-string-to-time s1))
18451 d2 (time-to-days (org-time-string-to-time s2)))
18452 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
18453 ;; Only allow days between the limits, because the normal
18454 ;; date stamps will catch the limits.
18455 (save-excursion
18456 (setq marker (org-agenda-new-marker (point)))
18457 (setq category (org-get-category))
18458 (if (re-search-backward "^\\*+ " nil t)
18459 (progn
18460 (goto-char (match-beginning 0))
18461 (setq hdmarker (org-agenda-new-marker (point)))
18462 (setq tags (org-get-tags-at))
18463 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
18464 (setq txt (org-format-agenda-item
18465 (format (if (= d1 d2) "" "(%d/%d): ")
18466 (1+ (- d0 d1)) (1+ (- d2 d1)))
18467 (match-string 1) category tags
18468 (if (= d0 d1) timestr))))
18469 (setq txt org-agenda-no-heading-message))
18470 (org-add-props txt props
18471 'org-marker marker 'org-hd-marker hdmarker
18472 'type "block" 'date date
18473 'priority (org-get-priority txt) 'org-category category)
18474 (push txt ee)))
18475 (goto-char pos)))
18476 ;; Sort the entries by expiration date.
18477 (nreverse ee)))
18479 ;;; Agenda presentation and sorting
18481 (defconst org-plain-time-of-day-regexp
18482 (concat
18483 "\\(\\<[012]?[0-9]"
18484 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
18485 "\\(--?"
18486 "\\(\\<[012]?[0-9]"
18487 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
18488 "\\)?")
18489 "Regular expression to match a plain time or time range.
18490 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
18491 groups carry important information:
18492 0 the full match
18493 1 the first time, range or not
18494 8 the second time, if it is a range.")
18496 (defconst org-stamp-time-of-day-regexp
18497 (concat
18498 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
18499 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
18500 "\\(--?"
18501 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
18502 "Regular expression to match a timestamp time or time range.
18503 After a match, the following groups carry important information:
18504 0 the full match
18505 1 date plus weekday, for backreferencing to make sure both times on same day
18506 2 the first time, range or not
18507 4 the second time, if it is a range.")
18509 (defvar org-prefix-has-time nil
18510 "A flag, set by `org-compile-prefix-format'.
18511 The flag is set if the currently compiled format contains a `%t'.")
18512 (defvar org-prefix-has-tag nil
18513 "A flag, set by `org-compile-prefix-format'.
18514 The flag is set if the currently compiled format contains a `%T'.")
18516 (defun org-format-agenda-item (extra txt &optional category tags dotime
18517 noprefix)
18518 "Format TXT to be inserted into the agenda buffer.
18519 In particular, it adds the prefix and corresponding text properties. EXTRA
18520 must be a string and replaces the `%s' specifier in the prefix format.
18521 CATEGORY (string, symbol or nil) may be used to overrule the default
18522 category taken from local variable or file name. It will replace the `%c'
18523 specifier in the format. DOTIME, when non-nil, indicates that a
18524 time-of-day should be extracted from TXT for sorting of this entry, and for
18525 the `%t' specifier in the format. When DOTIME is a string, this string is
18526 searched for a time before TXT is. NOPREFIX is a flag and indicates that
18527 only the correctly processes TXT should be returned - this is used by
18528 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
18529 (save-match-data
18530 ;; Diary entries sometimes have extra whitespace at the beginning
18531 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
18532 (let* ((category (or category
18533 org-category
18534 (if buffer-file-name
18535 (file-name-sans-extension
18536 (file-name-nondirectory buffer-file-name))
18537 "")))
18538 (tag (if tags (nth (1- (length tags)) tags) ""))
18539 time ; time and tag are needed for the eval of the prefix format
18540 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
18541 (time-of-day (and dotime (org-get-time-of-day ts)))
18542 stamp plain s0 s1 s2 rtn srp)
18543 (when (and dotime time-of-day org-prefix-has-time)
18544 ;; Extract starting and ending time and move them to prefix
18545 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
18546 (setq plain (string-match org-plain-time-of-day-regexp ts)))
18547 (setq s0 (match-string 0 ts)
18548 srp (and stamp (match-end 3))
18549 s1 (match-string (if plain 1 2) ts)
18550 s2 (match-string (if plain 8 (if srp 4 6)) ts))
18552 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
18553 ;; them, we might want to remove them there to avoid duplication.
18554 ;; The user can turn this off with a variable.
18555 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
18556 (string-match (concat (regexp-quote s0) " *") txt)
18557 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
18558 (= (match-beginning 0) 0)
18560 (setq txt (replace-match "" nil nil txt))))
18561 ;; Normalize the time(s) to 24 hour
18562 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
18563 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
18565 (when (and s1 (not s2) org-agenda-default-appointment-duration
18566 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
18567 (let ((m (+ (string-to-number (match-string 2 s1))
18568 (* 60 (string-to-number (match-string 1 s1)))
18569 org-agenda-default-appointment-duration))
18571 (setq h (/ m 60) m (- m (* h 60)))
18572 (setq s2 (format "%02d:%02d" h m))))
18574 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
18575 txt)
18576 ;; Tags are in the string
18577 (if (or (eq org-agenda-remove-tags t)
18578 (and org-agenda-remove-tags
18579 org-prefix-has-tag))
18580 (setq txt (replace-match "" t t txt))
18581 (setq txt (replace-match
18582 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
18583 (match-string 2 txt))
18584 t t txt))))
18586 ;; Create the final string
18587 (if noprefix
18588 (setq rtn txt)
18589 ;; Prepare the variables needed in the eval of the compiled format
18590 (setq time (cond (s2 (concat s1 "-" s2))
18591 (s1 (concat s1 "......"))
18592 (t ""))
18593 extra (or extra "")
18594 category (if (symbolp category) (symbol-name category) category))
18595 ;; Evaluate the compiled format
18596 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
18598 ;; And finally add the text properties
18599 (org-add-props rtn nil
18600 'org-category (downcase category) 'tags tags
18601 'prefix-length (- (length rtn) (length txt))
18602 'time-of-day time-of-day
18603 'txt txt
18604 'time time
18605 'extra extra
18606 'dotime dotime))))
18608 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
18609 (defvar org-agenda-sorting-strategy-selected nil)
18611 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
18612 (catch 'exit
18613 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
18614 ((and todayp (member 'today (car org-agenda-time-grid))))
18615 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
18616 ((member 'weekly (car org-agenda-time-grid)))
18617 (t (throw 'exit list)))
18618 (let* ((have (delq nil (mapcar
18619 (lambda (x) (get-text-property 1 'time-of-day x))
18620 list)))
18621 (string (nth 1 org-agenda-time-grid))
18622 (gridtimes (nth 2 org-agenda-time-grid))
18623 (req (car org-agenda-time-grid))
18624 (remove (member 'remove-match req))
18625 new time)
18626 (if (and (member 'require-timed req) (not have))
18627 ;; don't show empty grid
18628 (throw 'exit list))
18629 (while (setq time (pop gridtimes))
18630 (unless (and remove (member time have))
18631 (setq time (int-to-string time))
18632 (push (org-format-agenda-item
18633 nil string "" nil
18634 (concat (substring time 0 -2) ":" (substring time -2)))
18635 new)
18636 (put-text-property
18637 1 (length (car new)) 'face 'org-time-grid (car new))))
18638 (if (member 'time-up org-agenda-sorting-strategy-selected)
18639 (append new list)
18640 (append list new)))))
18642 (defun org-compile-prefix-format (key)
18643 "Compile the prefix format into a Lisp form that can be evaluated.
18644 The resulting form is returned and stored in the variable
18645 `org-prefix-format-compiled'."
18646 (setq org-prefix-has-time nil org-prefix-has-tag nil)
18647 (let ((s (cond
18648 ((stringp org-agenda-prefix-format)
18649 org-agenda-prefix-format)
18650 ((assq key org-agenda-prefix-format)
18651 (cdr (assq key org-agenda-prefix-format)))
18652 (t " %-12:c%?-12t% s")))
18653 (start 0)
18654 varform vars var e c f opt)
18655 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
18656 s start)
18657 (setq var (cdr (assoc (match-string 4 s)
18658 '(("c" . category) ("t" . time) ("s" . extra)
18659 ("T" . tag))))
18660 c (or (match-string 3 s) "")
18661 opt (match-beginning 1)
18662 start (1+ (match-beginning 0)))
18663 (if (equal var 'time) (setq org-prefix-has-time t))
18664 (if (equal var 'tag) (setq org-prefix-has-tag t))
18665 (setq f (concat "%" (match-string 2 s) "s"))
18666 (if opt
18667 (setq varform
18668 `(if (equal "" ,var)
18670 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
18671 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
18672 (setq s (replace-match "%s" t nil s))
18673 (push varform vars))
18674 (setq vars (nreverse vars))
18675 (setq org-prefix-format-compiled `(format ,s ,@vars))))
18677 (defun org-set-sorting-strategy (key)
18678 (if (symbolp (car org-agenda-sorting-strategy))
18679 ;; the old format
18680 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
18681 (setq org-agenda-sorting-strategy-selected
18682 (or (cdr (assq key org-agenda-sorting-strategy))
18683 (cdr (assq 'agenda org-agenda-sorting-strategy))
18684 '(time-up category-keep priority-down)))))
18686 (defun org-get-time-of-day (s &optional string mod24)
18687 "Check string S for a time of day.
18688 If found, return it as a military time number between 0 and 2400.
18689 If not found, return nil.
18690 The optional STRING argument forces conversion into a 5 character wide string
18691 HH:MM."
18692 (save-match-data
18693 (when
18695 (string-match
18696 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
18697 (string-match
18698 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
18699 (let* ((h (string-to-number (match-string 1 s)))
18700 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
18701 (ampm (if (match-end 4) (downcase (match-string 4 s))))
18702 (am-p (equal ampm "am"))
18703 (h1 (cond ((not ampm) h)
18704 ((= h 12) (if am-p 0 12))
18705 (t (+ h (if am-p 0 12)))))
18706 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
18707 (mod h1 24) h1))
18708 (t0 (+ (* 100 h2) m))
18709 (t1 (concat (if (>= h1 24) "+" " ")
18710 (if (< t0 100) "0" "")
18711 (if (< t0 10) "0" "")
18712 (int-to-string t0))))
18713 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
18715 (defun org-finalize-agenda-entries (list &optional nosort)
18716 "Sort and concatenate the agenda items."
18717 (setq list (mapcar 'org-agenda-highlight-todo list))
18718 (if nosort
18719 list
18720 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
18722 (defun org-agenda-highlight-todo (x)
18723 (let (re pl)
18724 (if (eq x 'line)
18725 (save-excursion
18726 (beginning-of-line 1)
18727 (setq re (get-text-property (point) 'org-not-done-regexp))
18728 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
18729 (and (looking-at (concat "[ \t]*\\.*" re))
18730 (add-text-properties (match-beginning 0) (match-end 0)
18731 '(face org-todo))))
18732 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
18733 pl (get-text-property 0 'prefix-length x))
18734 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
18735 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
18736 '(face org-todo) x))
18737 x)))
18739 (defsubst org-cmp-priority (a b)
18740 "Compare the priorities of string A and B."
18741 (let ((pa (or (get-text-property 1 'priority a) 0))
18742 (pb (or (get-text-property 1 'priority b) 0)))
18743 (cond ((> pa pb) +1)
18744 ((< pa pb) -1)
18745 (t nil))))
18747 (defsubst org-cmp-category (a b)
18748 "Compare the string values of categories of strings A and B."
18749 (let ((ca (or (get-text-property 1 'org-category a) ""))
18750 (cb (or (get-text-property 1 'org-category b) "")))
18751 (cond ((string-lessp ca cb) -1)
18752 ((string-lessp cb ca) +1)
18753 (t nil))))
18755 (defsubst org-cmp-tag (a b)
18756 "Compare the string values of categories of strings A and B."
18757 (let ((ta (car (last (get-text-property 1 'tags a))))
18758 (tb (car (last (get-text-property 1 'tags b)))))
18759 (cond ((not ta) +1)
18760 ((not tb) -1)
18761 ((string-lessp ta tb) -1)
18762 ((string-lessp tb ta) +1)
18763 (t nil))))
18765 (defsubst org-cmp-time (a b)
18766 "Compare the time-of-day values of strings A and B."
18767 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
18768 (ta (or (get-text-property 1 'time-of-day a) def))
18769 (tb (or (get-text-property 1 'time-of-day b) def)))
18770 (cond ((< ta tb) -1)
18771 ((< tb ta) +1)
18772 (t nil))))
18774 (defun org-entries-lessp (a b)
18775 "Predicate for sorting agenda entries."
18776 ;; The following variables will be used when the form is evaluated.
18777 ;; So even though the compiler complains, keep them.
18778 (let* ((time-up (org-cmp-time a b))
18779 (time-down (if time-up (- time-up) nil))
18780 (priority-up (org-cmp-priority a b))
18781 (priority-down (if priority-up (- priority-up) nil))
18782 (category-up (org-cmp-category a b))
18783 (category-down (if category-up (- category-up) nil))
18784 (category-keep (if category-up +1 nil))
18785 (tag-up (org-cmp-tag a b))
18786 (tag-down (if tag-up (- tag-up) nil)))
18787 (cdr (assoc
18788 (eval (cons 'or org-agenda-sorting-strategy-selected))
18789 '((-1 . t) (1 . nil) (nil . nil))))))
18791 ;;; Agenda commands
18793 (defun org-agenda-check-type (error &rest types)
18794 "Check if agenda buffer is of allowed type.
18795 If ERROR is non-nil, throw an error, otherwise just return nil."
18796 (if (memq org-agenda-type types)
18798 (if error
18799 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
18800 nil)))
18802 (defun org-agenda-quit ()
18803 "Exit agenda by removing the window or the buffer."
18804 (interactive)
18805 (let ((buf (current-buffer)))
18806 (if (not (one-window-p)) (delete-window))
18807 (kill-buffer buf)
18808 (org-agenda-maybe-reset-markers 'force)
18809 (org-columns-remove-overlays))
18810 ;; Maybe restore the pre-agenda window configuration.
18811 (and org-agenda-restore-windows-after-quit
18812 (not (eq org-agenda-window-setup 'other-frame))
18813 org-pre-agenda-window-conf
18814 (set-window-configuration org-pre-agenda-window-conf)))
18816 (defun org-agenda-exit ()
18817 "Exit agenda by removing the window or the buffer.
18818 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
18819 Org-mode buffers visited directly by the user will not be touched."
18820 (interactive)
18821 (org-release-buffers org-agenda-new-buffers)
18822 (setq org-agenda-new-buffers nil)
18823 (org-agenda-quit))
18825 (defun org-save-all-org-buffers ()
18826 "Save all Org-mode buffers without user confirmation."
18827 (interactive)
18828 (message "Saving all Org-mode buffers...")
18829 (save-some-buffers t 'org-mode-p)
18830 (message "Saving all Org-mode buffers... done"))
18832 (defun org-agenda-redo ()
18833 "Rebuild Agenda.
18834 When this is the global TODO list, a prefix argument will be interpreted."
18835 (interactive)
18836 (let* ((org-agenda-keep-modes t)
18837 (line (org-current-line))
18838 (window-line (- line (org-current-line (window-start))))
18839 (lprops (get 'org-agenda-redo-command 'org-lprops)))
18840 (message "Rebuilding agenda buffer...")
18841 (org-let lprops '(eval org-agenda-redo-command))
18842 (setq org-agenda-undo-list nil
18843 org-agenda-pending-undo-list nil)
18844 (message "Rebuilding agenda buffer...done")
18845 (goto-line line)
18846 (recenter window-line)))
18848 (defun org-agenda-goto-date (date)
18849 "Jump to DATE in agenda."
18850 (interactive (list (org-read-date)))
18851 (org-agenda-list nil date))
18853 (defun org-agenda-goto-today ()
18854 "Go to today."
18855 (interactive)
18856 (org-agenda-check-type t 'timeline 'agenda)
18857 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
18858 (cond
18859 (tdpos (goto-char tdpos))
18860 ((eq org-agenda-type 'agenda)
18861 (let* ((sd (time-to-days (current-time)))
18862 (comp (org-agenda-compute-time-span sd org-agenda-span))
18863 (org-agenda-overriding-arguments org-agenda-last-arguments))
18864 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
18865 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
18866 (org-agenda-redo)
18867 (org-agenda-find-today-or-agenda)))
18868 (t (error "Cannot find today")))))
18870 (defun org-agenda-find-today-or-agenda ()
18871 (goto-char
18872 (or (text-property-any (point-min) (point-max) 'org-today t)
18873 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
18874 (point-min))))
18876 (defun org-agenda-later (arg)
18877 "Go forward in time by thee current span.
18878 With prefix ARG, go forward that many times the current span."
18879 (interactive "p")
18880 (org-agenda-check-type t 'agenda)
18881 (let* ((span org-agenda-span)
18882 (sd org-starting-day)
18883 (greg (calendar-gregorian-from-absolute sd))
18884 greg2 nd)
18885 (cond
18886 ((eq span 'day)
18887 (setq sd (+ arg sd) nd 1))
18888 ((eq span 'week)
18889 (setq sd (+ (* 7 arg) sd) nd 7))
18890 ((eq span 'month)
18891 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
18892 sd (calendar-absolute-from-gregorian greg2))
18893 (setcar greg2 (1+ (car greg2)))
18894 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
18895 ((eq span 'year)
18896 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
18897 sd (calendar-absolute-from-gregorian greg2))
18898 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
18899 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
18900 (let ((org-agenda-overriding-arguments
18901 (list (car org-agenda-last-arguments) sd nd t)))
18902 (org-agenda-redo)
18903 (org-agenda-find-today-or-agenda))))
18905 (defun org-agenda-earlier (arg)
18906 "Go backward in time by the current span.
18907 With prefix ARG, go backward that many times the current span."
18908 (interactive "p")
18909 (org-agenda-later (- arg)))
18911 (defun org-agenda-day-view ()
18912 "Switch to daily view for agenda."
18913 (interactive)
18914 (setq org-agenda-ndays 1)
18915 (org-agenda-change-time-span 'day))
18916 (defun org-agenda-week-view ()
18917 "Switch to daily view for agenda."
18918 (interactive)
18919 (setq org-agenda-ndays 7)
18920 (org-agenda-change-time-span 'week))
18921 (defun org-agenda-month-view ()
18922 "Switch to daily view for agenda."
18923 (interactive)
18924 (org-agenda-change-time-span 'month))
18925 (defun org-agenda-year-view ()
18926 "Switch to daily view for agenda."
18927 (interactive)
18928 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
18929 (org-agenda-change-time-span 'year)
18930 (error "Abort")))
18932 (defun org-agenda-change-time-span (span)
18933 "Change the agenda view to SPAN.
18934 SPAN may be `day', `week', `month', `year'."
18935 (org-agenda-check-type t 'agenda)
18936 (if (equal org-agenda-span span)
18937 (error "Viewing span is already \"%s\"" span))
18938 (let* ((sd (or (get-text-property (point) 'day)
18939 org-starting-day))
18940 (computed (org-agenda-compute-time-span sd span))
18941 (org-agenda-overriding-arguments
18942 (list (car org-agenda-last-arguments)
18943 (car computed) (cdr computed) t)))
18944 (org-agenda-redo)
18945 (org-agenda-find-today-or-agenda))
18946 (org-agenda-set-mode-name)
18947 (message "Switched to %s view" span))
18949 (defun org-agenda-compute-time-span (sd span)
18950 "Compute starting date and number of days for agenda.
18951 SPAN may be `day', `week', `month', `year'. The return value
18952 is a cons cell with the starting date and the number of days,
18953 so that the date SD will be in that range."
18954 (let* ((greg (calendar-gregorian-from-absolute sd))
18956 (cond
18957 ((eq span 'day)
18958 (setq nd 1))
18959 ((eq span 'week)
18960 (let* ((nt (calendar-day-of-week
18961 (calendar-gregorian-from-absolute sd)))
18962 (d (if org-agenda-start-on-weekday
18963 (- nt org-agenda-start-on-weekday)
18964 0)))
18965 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
18966 (setq nd 7)))
18967 ((eq span 'month)
18968 (setq sd (calendar-absolute-from-gregorian
18969 (list (car greg) 1 (nth 2 greg)))
18970 nd (- (calendar-absolute-from-gregorian
18971 (list (1+ (car greg)) 1 (nth 2 greg)))
18972 sd)))
18973 ((eq span 'year)
18974 (setq sd (calendar-absolute-from-gregorian
18975 (list 1 1 (nth 2 greg)))
18976 nd (- (calendar-absolute-from-gregorian
18977 (list 1 1 (1+ (nth 2 greg))))
18978 sd))))
18979 (cons sd nd)))
18981 ;; FIXME: this no longer works if user make date format that starts with a blank
18982 (defun org-agenda-next-date-line (&optional arg)
18983 "Jump to the next line indicating a date in agenda buffer."
18984 (interactive "p")
18985 (org-agenda-check-type t 'agenda 'timeline)
18986 (beginning-of-line 1)
18987 (if (looking-at "^\\S-") (forward-char 1))
18988 (if (not (re-search-forward "^\\S-" nil t arg))
18989 (progn
18990 (backward-char 1)
18991 (error "No next date after this line in this buffer")))
18992 (goto-char (match-beginning 0)))
18994 (defun org-agenda-previous-date-line (&optional arg)
18995 "Jump to the previous line indicating a date in agenda buffer."
18996 (interactive "p")
18997 (org-agenda-check-type t 'agenda 'timeline)
18998 (beginning-of-line 1)
18999 (if (not (re-search-backward "^\\S-" nil t arg))
19000 (error "No previous date before this line in this buffer")))
19002 ;; Initialize the highlight
19003 (defvar org-hl (org-make-overlay 1 1))
19004 (org-overlay-put org-hl 'face 'highlight)
19006 (defun org-highlight (begin end &optional buffer)
19007 "Highlight a region with overlay."
19008 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
19009 org-hl begin end (or buffer (current-buffer))))
19011 (defun org-unhighlight ()
19012 "Detach overlay INDEX."
19013 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
19015 ;; FIXME this is currently not used.
19016 (defun org-highlight-until-next-command (beg end &optional buffer)
19017 (org-highlight beg end buffer)
19018 (add-hook 'pre-command-hook 'org-unhighlight-once))
19020 (defun org-unhighlight-once ()
19021 (remove-hook 'pre-command-hook 'org-unhighlight-once)
19022 (org-unhighlight))
19024 (defun org-agenda-follow-mode ()
19025 "Toggle follow mode in an agenda buffer."
19026 (interactive)
19027 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
19028 (org-agenda-set-mode-name)
19029 (message "Follow mode is %s"
19030 (if org-agenda-follow-mode "on" "off")))
19032 (defun org-agenda-log-mode ()
19033 "Toggle log mode in an agenda buffer."
19034 (interactive)
19035 (org-agenda-check-type t 'agenda 'timeline)
19036 (setq org-agenda-show-log (not org-agenda-show-log))
19037 (org-agenda-set-mode-name)
19038 (org-agenda-redo)
19039 (message "Log mode is %s"
19040 (if org-agenda-show-log "on" "off")))
19042 (defun org-agenda-toggle-diary ()
19043 "Toggle diary inclusion in an agenda buffer."
19044 (interactive)
19045 (org-agenda-check-type t 'agenda)
19046 (setq org-agenda-include-diary (not org-agenda-include-diary))
19047 (org-agenda-redo)
19048 (org-agenda-set-mode-name)
19049 (message "Diary inclusion turned %s"
19050 (if org-agenda-include-diary "on" "off")))
19052 (defun org-agenda-toggle-time-grid ()
19053 "Toggle time grid in an agenda buffer."
19054 (interactive)
19055 (org-agenda-check-type t 'agenda)
19056 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
19057 (org-agenda-redo)
19058 (org-agenda-set-mode-name)
19059 (message "Time-grid turned %s"
19060 (if org-agenda-use-time-grid "on" "off")))
19062 (defun org-agenda-set-mode-name ()
19063 "Set the mode name to indicate all the small mode settings."
19064 (setq mode-name
19065 (concat "Org-Agenda"
19066 (if (equal org-agenda-ndays 1) " Day" "")
19067 (if (equal org-agenda-ndays 7) " Week" "")
19068 (if org-agenda-follow-mode " Follow" "")
19069 (if org-agenda-include-diary " Diary" "")
19070 (if org-agenda-use-time-grid " Grid" "")
19071 (if org-agenda-show-log " Log" "")))
19072 (force-mode-line-update))
19074 (defun org-agenda-post-command-hook ()
19075 (and (eolp) (not (bolp)) (backward-char 1))
19076 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
19077 (if (and org-agenda-follow-mode
19078 (get-text-property (point) 'org-marker))
19079 (org-agenda-show)))
19081 (defun org-agenda-show-priority ()
19082 "Show the priority of the current item.
19083 This priority is composed of the main priority given with the [#A] cookies,
19084 and by additional input from the age of a schedules or deadline entry."
19085 (interactive)
19086 (let* ((pri (get-text-property (point-at-bol) 'priority)))
19087 (message "Priority is %d" (if pri pri -1000))))
19089 (defun org-agenda-show-tags ()
19090 "Show the tags applicable to the current item."
19091 (interactive)
19092 (let* ((tags (get-text-property (point-at-bol) 'tags)))
19093 (if tags
19094 (message "Tags are :%s:"
19095 (org-no-properties (mapconcat 'identity tags ":")))
19096 (message "No tags associated with this line"))))
19098 (defun org-agenda-goto (&optional highlight)
19099 "Go to the Org-mode file which contains the item at point."
19100 (interactive)
19101 (let* ((marker (or (get-text-property (point) 'org-marker)
19102 (org-agenda-error)))
19103 (buffer (marker-buffer marker))
19104 (pos (marker-position marker)))
19105 (switch-to-buffer-other-window buffer)
19106 (widen)
19107 (goto-char pos)
19108 (when (org-mode-p)
19109 (org-show-context 'agenda)
19110 (save-excursion
19111 (and (outline-next-heading)
19112 (org-flag-heading nil)))) ; show the next heading
19113 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
19115 (defun org-agenda-kill ()
19116 "Kill the entry or subtree belonging to the current agenda entry."
19117 (interactive)
19118 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
19119 (let* ((marker (or (get-text-property (point) 'org-marker)
19120 (org-agenda-error)))
19121 (buffer (marker-buffer marker))
19122 (pos (marker-position marker))
19123 (type (get-text-property (point) 'type))
19124 dbeg dend (n 0) conf)
19125 (org-with-remote-undo buffer
19126 (with-current-buffer buffer
19127 (save-excursion
19128 (goto-char pos)
19129 (if (and (org-mode-p) (not (member type '("sexp"))))
19130 (setq dbeg (progn (org-back-to-heading t) (point))
19131 dend (org-end-of-subtree t t))
19132 (setq dbeg (point-at-bol)
19133 dend (min (point-max) (1+ (point-at-eol)))))
19134 (goto-char dbeg)
19135 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
19136 (setq conf (or (eq t org-agenda-confirm-kill)
19137 (and (numberp org-agenda-confirm-kill)
19138 (> n org-agenda-confirm-kill))))
19139 (and conf
19140 (not (y-or-n-p
19141 (format "Delete entry with %d lines in buffer \"%s\"? "
19142 n (buffer-name buffer))))
19143 (error "Abort"))
19144 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
19145 (with-current-buffer buffer (delete-region dbeg dend))
19146 (message "Agenda item and source killed"))))
19148 (defun org-agenda-archive ()
19149 "Kill the entry or subtree belonging to the current agenda entry."
19150 (interactive)
19151 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
19152 (let* ((marker (or (get-text-property (point) 'org-marker)
19153 (org-agenda-error)))
19154 (buffer (marker-buffer marker))
19155 (pos (marker-position marker)))
19156 (org-with-remote-undo buffer
19157 (with-current-buffer buffer
19158 (if (org-mode-p)
19159 (save-excursion
19160 (goto-char pos)
19161 (org-remove-subtree-entries-from-agenda)
19162 (org-back-to-heading t)
19163 (org-archive-subtree))
19164 (error "Archiving works only in Org-mode files"))))))
19166 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
19167 "Remove all lines in the agenda that correspond to a given subtree.
19168 The subtree is the one in buffer BUF, starting at BEG and ending at END.
19169 If this information is not given, the function uses the tree at point."
19170 (let ((buf (or buf (current-buffer))) m p)
19171 (save-excursion
19172 (unless (and beg end)
19173 (org-back-to-heading t)
19174 (setq beg (point))
19175 (org-end-of-subtree t)
19176 (setq end (point)))
19177 (set-buffer (get-buffer org-agenda-buffer-name))
19178 (save-excursion
19179 (goto-char (point-max))
19180 (beginning-of-line 1)
19181 (while (not (bobp))
19182 (when (and (setq m (get-text-property (point) 'org-marker))
19183 (equal buf (marker-buffer m))
19184 (setq p (marker-position m))
19185 (>= p beg)
19186 (<= p end))
19187 (let ((inhibit-read-only t))
19188 (delete-region (point-at-bol) (1+ (point-at-eol)))))
19189 (beginning-of-line 0))))))
19191 (defun org-agenda-open-link ()
19192 "Follow the link in the current line, if any."
19193 (interactive)
19194 (let ((eol (point-at-eol)))
19195 (save-excursion
19196 (if (or (re-search-forward org-bracket-link-regexp eol t)
19197 (re-search-forward org-angle-link-re eol t)
19198 (re-search-forward org-plain-link-re eol t))
19199 (call-interactively 'org-open-at-point)
19200 (error "No link in current line")))))
19202 (defun org-agenda-switch-to (&optional delete-other-windows)
19203 "Go to the Org-mode file which contains the item at point."
19204 (interactive)
19205 (let* ((marker (or (get-text-property (point) 'org-marker)
19206 (org-agenda-error)))
19207 (buffer (marker-buffer marker))
19208 (pos (marker-position marker)))
19209 (switch-to-buffer buffer)
19210 (and delete-other-windows (delete-other-windows))
19211 (widen)
19212 (goto-char pos)
19213 (when (org-mode-p)
19214 (org-show-context 'agenda)
19215 (save-excursion
19216 (and (outline-next-heading)
19217 (org-flag-heading nil)))))) ; show the next heading
19219 (defun org-agenda-goto-mouse (ev)
19220 "Go to the Org-mode file which contains the item at the mouse click."
19221 (interactive "e")
19222 (mouse-set-point ev)
19223 (org-agenda-goto))
19225 (defun org-agenda-show ()
19226 "Display the Org-mode file which contains the item at point."
19227 (interactive)
19228 (let ((win (selected-window)))
19229 (org-agenda-goto t)
19230 (select-window win)))
19232 (defun org-agenda-recenter (arg)
19233 "Display the Org-mode file which contains the item at point and recenter."
19234 (interactive "P")
19235 (let ((win (selected-window)))
19236 (org-agenda-goto t)
19237 (recenter arg)
19238 (select-window win)))
19240 (defun org-agenda-show-mouse (ev)
19241 "Display the Org-mode file which contains the item at the mouse click."
19242 (interactive "e")
19243 (mouse-set-point ev)
19244 (org-agenda-show))
19246 (defun org-agenda-check-no-diary ()
19247 "Check if the entry is a diary link and abort if yes."
19248 (if (get-text-property (point) 'org-agenda-diary-link)
19249 (org-agenda-error)))
19251 (defun org-agenda-error ()
19252 (error "Command not allowed in this line"))
19254 (defun org-agenda-tree-to-indirect-buffer ()
19255 "Show the subtree corresponding to the current entry in an indirect buffer.
19256 This calls the command `org-tree-to-indirect-buffer' from the original
19257 Org-mode buffer.
19258 With numerical prefix arg ARG, go up to this level and then take that tree.
19259 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
19260 dedicated frame)."
19261 (interactive)
19262 (org-agenda-check-no-diary)
19263 (let* ((marker (or (get-text-property (point) 'org-marker)
19264 (org-agenda-error)))
19265 (buffer (marker-buffer marker))
19266 (pos (marker-position marker)))
19267 (with-current-buffer buffer
19268 (save-excursion
19269 (goto-char pos)
19270 (call-interactively 'org-tree-to-indirect-buffer)))))
19272 (defvar org-last-heading-marker (make-marker)
19273 "Marker pointing to the headline that last changed its TODO state
19274 by a remote command from the agenda.")
19276 (defun org-agenda-todo-nextset ()
19277 "Switch TODO entry to next sequence."
19278 (interactive)
19279 (org-agenda-todo 'nextset))
19281 (defun org-agenda-todo-previousset ()
19282 "Switch TODO entry to previous sequence."
19283 (interactive)
19284 (org-agenda-todo 'previousset))
19286 (defun org-agenda-todo (&optional arg)
19287 "Cycle TODO state of line at point, also in Org-mode file.
19288 This changes the line at point, all other lines in the agenda referring to
19289 the same tree node, and the headline of the tree node in the Org-mode file."
19290 (interactive "P")
19291 (org-agenda-check-no-diary)
19292 (let* ((col (current-column))
19293 (marker (or (get-text-property (point) 'org-marker)
19294 (org-agenda-error)))
19295 (buffer (marker-buffer marker))
19296 (pos (marker-position marker))
19297 (hdmarker (get-text-property (point) 'org-hd-marker))
19298 (inhibit-read-only t)
19299 newhead)
19300 (org-with-remote-undo buffer
19301 (with-current-buffer buffer
19302 (widen)
19303 (goto-char pos)
19304 (org-show-context 'agenda)
19305 (save-excursion
19306 (and (outline-next-heading)
19307 (org-flag-heading nil))) ; show the next heading
19308 (org-todo arg)
19309 (and (bolp) (forward-char 1))
19310 (setq newhead (org-get-heading))
19311 (save-excursion
19312 (org-back-to-heading)
19313 (move-marker org-last-heading-marker (point))))
19314 (beginning-of-line 1)
19315 (save-excursion
19316 (org-agenda-change-all-lines newhead hdmarker 'fixface))
19317 (move-to-column col))))
19319 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
19320 "Change all lines in the agenda buffer which match HDMARKER.
19321 The new content of the line will be NEWHEAD (as modified by
19322 `org-format-agenda-item'). HDMARKER is checked with
19323 `equal' against all `org-hd-marker' text properties in the file.
19324 If FIXFACE is non-nil, the face of each item is modified acording to
19325 the new TODO state."
19326 (let* ((inhibit-read-only t)
19327 props m pl undone-face done-face finish new dotime cat tags)
19328 (save-excursion
19329 (goto-char (point-max))
19330 (beginning-of-line 1)
19331 (while (not finish)
19332 (setq finish (bobp))
19333 (when (and (setq m (get-text-property (point) 'org-hd-marker))
19334 (equal m hdmarker))
19335 (setq props (text-properties-at (point))
19336 dotime (get-text-property (point) 'dotime)
19337 cat (get-text-property (point) 'org-category)
19338 tags (get-text-property (point) 'tags)
19339 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
19340 pl (get-text-property (point) 'prefix-length)
19341 undone-face (get-text-property (point) 'undone-face)
19342 done-face (get-text-property (point) 'done-face))
19343 (move-to-column pl)
19344 (cond
19345 ((equal new "")
19346 (beginning-of-line 1)
19347 (and (looking-at ".*\n?") (replace-match "")))
19348 ((looking-at ".*")
19349 (replace-match new t t)
19350 (beginning-of-line 1)
19351 (add-text-properties (point-at-bol) (point-at-eol) props)
19352 (when fixface
19353 (add-text-properties
19354 (point-at-bol) (point-at-eol)
19355 (list 'face
19356 (if org-last-todo-state-is-todo
19357 undone-face done-face))))
19358 (org-agenda-highlight-todo 'line)
19359 (beginning-of-line 1))
19360 (t (error "Line update did not work"))))
19361 (beginning-of-line 0)))
19362 (org-finalize-agenda)))
19364 ;; FIXME: allow negative value for org-agenda-align-tags-to-column
19365 ;; See the code in set-tags for the way to do this.
19366 (defun org-agenda-align-tags (&optional line)
19367 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
19368 (let ((inhibit-read-only t))
19369 (save-excursion
19370 (goto-char (if line (point-at-bol) (point-min)))
19371 (while (re-search-forward (org-re "\\([ \t]+\\):[[:alnum:]_@:]+:[ \t]*$")
19372 (if line (point-at-eol) nil) t)
19373 (delete-region (match-beginning 1) (match-end 1))
19374 (goto-char (match-beginning 1))
19375 (insert (org-add-props
19376 (make-string (max 1 (- org-agenda-align-tags-to-column
19377 (current-column))) ?\ )
19378 (text-properties-at (point))))))))
19380 (defun org-agenda-priority-up ()
19381 "Increase the priority of line at point, also in Org-mode file."
19382 (interactive)
19383 (org-agenda-priority 'up))
19385 (defun org-agenda-priority-down ()
19386 "Decrease the priority of line at point, also in Org-mode file."
19387 (interactive)
19388 (org-agenda-priority 'down))
19390 (defun org-agenda-priority (&optional force-direction)
19391 "Set the priority of line at point, also in Org-mode file.
19392 This changes the line at point, all other lines in the agenda referring to
19393 the same tree node, and the headline of the tree node in the Org-mode file."
19394 (interactive)
19395 (org-agenda-check-no-diary)
19396 (let* ((marker (or (get-text-property (point) 'org-marker)
19397 (org-agenda-error)))
19398 (hdmarker (get-text-property (point) 'org-hd-marker))
19399 (buffer (marker-buffer hdmarker))
19400 (pos (marker-position hdmarker))
19401 (inhibit-read-only t)
19402 newhead)
19403 (org-with-remote-undo buffer
19404 (with-current-buffer buffer
19405 (widen)
19406 (goto-char pos)
19407 (org-show-context 'agenda)
19408 (save-excursion
19409 (and (outline-next-heading)
19410 (org-flag-heading nil))) ; show the next heading
19411 (funcall 'org-priority force-direction)
19412 (end-of-line 1)
19413 (setq newhead (org-get-heading)))
19414 (org-agenda-change-all-lines newhead hdmarker)
19415 (beginning-of-line 1))))
19417 (defun org-get-tags-at (&optional pos)
19418 "Get a list of all headline tags applicable at POS.
19419 POS defaults to point. If tags are inherited, the list contains
19420 the targets in the same sequence as the headlines appear, i.e.
19421 the tags of the current headline come last."
19422 (interactive)
19423 (let (tags)
19424 (save-excursion
19425 (save-restriction
19426 (widen)
19427 (goto-char (or pos (point)))
19428 (save-match-data
19429 (org-back-to-heading t)
19430 (condition-case nil
19431 (while t
19432 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
19433 (setq tags (append (org-split-string
19434 (org-match-string-no-properties 1) ":")
19435 tags)))
19436 (or org-use-tag-inheritance (error ""))
19437 (org-up-heading-all 1))
19438 (error nil))))
19439 tags)))
19441 ;; FIXME: should fix the tags property of the agenda line.
19442 (defun org-agenda-set-tags ()
19443 "Set tags for the current headline."
19444 (interactive)
19445 (org-agenda-check-no-diary)
19446 (if (and (org-region-active-p) (interactive-p))
19447 (call-interactively 'org-change-tag-in-region)
19448 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
19449 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
19450 (org-agenda-error)))
19451 (buffer (marker-buffer hdmarker))
19452 (pos (marker-position hdmarker))
19453 (inhibit-read-only t)
19454 newhead)
19455 (org-with-remote-undo buffer
19456 (with-current-buffer buffer
19457 (widen)
19458 (goto-char pos)
19459 (save-excursion
19460 (org-show-context 'agenda))
19461 (save-excursion
19462 (and (outline-next-heading)
19463 (org-flag-heading nil))) ; show the next heading
19464 (goto-char pos)
19465 (call-interactively 'org-set-tags)
19466 (end-of-line 1)
19467 (setq newhead (org-get-heading)))
19468 (org-agenda-change-all-lines newhead hdmarker)
19469 (beginning-of-line 1)))))
19471 (defun org-agenda-toggle-archive-tag ()
19472 "Toggle the archive tag for the current entry."
19473 (interactive)
19474 (org-agenda-check-no-diary)
19475 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
19476 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
19477 (org-agenda-error)))
19478 (buffer (marker-buffer hdmarker))
19479 (pos (marker-position hdmarker))
19480 (inhibit-read-only t)
19481 newhead)
19482 (org-with-remote-undo buffer
19483 (with-current-buffer buffer
19484 (widen)
19485 (goto-char pos)
19486 (org-show-context 'agenda)
19487 (save-excursion
19488 (and (outline-next-heading)
19489 (org-flag-heading nil))) ; show the next heading
19490 (call-interactively 'org-toggle-archive-tag)
19491 (end-of-line 1)
19492 (setq newhead (org-get-heading)))
19493 (org-agenda-change-all-lines newhead hdmarker)
19494 (beginning-of-line 1))))
19496 (defun org-agenda-date-later (arg &optional what)
19497 "Change the date of this item to one day later."
19498 (interactive "p")
19499 (org-agenda-check-type t 'agenda 'timeline)
19500 (org-agenda-check-no-diary)
19501 (let* ((marker (or (get-text-property (point) 'org-marker)
19502 (org-agenda-error)))
19503 (buffer (marker-buffer marker))
19504 (pos (marker-position marker)))
19505 (org-with-remote-undo buffer
19506 (with-current-buffer buffer
19507 (widen)
19508 (goto-char pos)
19509 (if (not (org-at-timestamp-p))
19510 (error "Cannot find time stamp"))
19511 (org-timestamp-change arg (or what 'day)))
19512 (org-agenda-show-new-time marker org-last-changed-timestamp))
19513 (message "Time stamp changed to %s" org-last-changed-timestamp)))
19515 (defun org-agenda-date-earlier (arg &optional what)
19516 "Change the date of this item to one day earlier."
19517 (interactive "p")
19518 (org-agenda-date-later (- arg) what))
19520 (defun org-agenda-show-new-time (marker stamp)
19521 "Show new date stamp via text properties."
19522 ;; We use text properties to make this undoable
19523 (let ((inhibit-read-only t))
19524 (setq stamp (concat " => " stamp))
19525 (save-excursion
19526 (goto-char (point-max))
19527 (while (not (bobp))
19528 (when (equal marker (get-text-property (point) 'org-marker))
19529 (move-to-column (- (window-width) (length stamp)) t)
19530 (if (featurep 'xemacs)
19531 ;; Use `duplicable' property to trigger undo recording
19532 (let ((ex (make-extent nil nil))
19533 (gl (make-glyph stamp)))
19534 (set-glyph-face gl 'secondary-selection)
19535 (set-extent-properties
19536 ex (list 'invisible t 'end-glyph gl 'duplicable t))
19537 (insert-extent ex (1- (point)) (point-at-eol)))
19538 (add-text-properties
19539 (1- (point)) (point-at-eol)
19540 (list 'display (org-add-props stamp nil
19541 'face 'secondary-selection))))
19542 (beginning-of-line 1))
19543 (beginning-of-line 0)))))
19545 (defun org-agenda-date-prompt (arg)
19546 "Change the date of this item. Date is prompted for, with default today.
19547 The prefix ARG is passed to the `org-time-stamp' command and can therefore
19548 be used to request time specification in the time stamp."
19549 (interactive "P")
19550 (org-agenda-check-type t 'agenda 'timeline)
19551 (org-agenda-check-no-diary)
19552 (let* ((marker (or (get-text-property (point) 'org-marker)
19553 (org-agenda-error)))
19554 (buffer (marker-buffer marker))
19555 (pos (marker-position marker)))
19556 (org-with-remote-undo buffer
19557 (with-current-buffer buffer
19558 (widen)
19559 (goto-char pos)
19560 (if (not (org-at-timestamp-p))
19561 (error "Cannot find time stamp"))
19562 (org-time-stamp arg)
19563 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
19565 (defun org-agenda-schedule (arg)
19566 "Schedule the item at point."
19567 (interactive "P")
19568 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
19569 (org-agenda-check-no-diary)
19570 (let* ((marker (or (get-text-property (point) 'org-marker)
19571 (org-agenda-error)))
19572 (buffer (marker-buffer marker))
19573 (pos (marker-position marker))
19574 (org-insert-labeled-timestamps-at-point nil)
19576 (org-with-remote-undo buffer
19577 (with-current-buffer buffer
19578 (widen)
19579 (goto-char pos)
19580 (setq ts (org-schedule))
19581 (message "Item scheduled for %s" ts)))))
19583 (defun org-agenda-deadline (arg)
19584 "Schedule the item at point."
19585 (interactive "P")
19586 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
19587 (org-agenda-check-no-diary)
19588 (let* ((marker (or (get-text-property (point) 'org-marker)
19589 (org-agenda-error)))
19590 (buffer (marker-buffer marker))
19591 (pos (marker-position marker))
19592 (org-insert-labeled-timestamps-at-point nil)
19594 (org-with-remote-undo buffer
19595 (with-current-buffer buffer
19596 (widen)
19597 (goto-char pos)
19598 (setq ts (org-deadline))
19599 (message "Deadline for this item set to %s" ts)))))
19601 (defun org-get-heading ()
19602 "Return the heading of the current entry, without the stars."
19603 (save-excursion
19604 (org-back-to-heading t)
19605 (if (looking-at "\\*+[ \t]+\\([^\r\n]*\\)") (match-string 1) "")))
19607 (defun org-agenda-clock-in (&optional arg)
19608 "Start the clock on the currently selected item."
19609 (interactive "P")
19610 (org-agenda-check-no-diary)
19611 (let* ((marker (or (get-text-property (point) 'org-marker)
19612 (org-agenda-error)))
19613 (pos (marker-position marker)))
19614 (org-with-remote-undo (marker-buffer marker)
19615 (with-current-buffer (marker-buffer marker)
19616 (widen)
19617 (goto-char pos)
19618 (org-clock-in)))))
19620 (defun org-agenda-clock-out (&optional arg)
19621 "Stop the currently running clock."
19622 (interactive "P")
19623 (unless (marker-buffer org-clock-marker)
19624 (error "No running clock"))
19625 (org-with-remote-undo (marker-buffer org-clock-marker)
19626 (org-clock-out)))
19628 (defun org-agenda-clock-cancel (&optional arg)
19629 "Cancel the currently running clock."
19630 (interactive "P")
19631 (unless (marker-buffer org-clock-marker)
19632 (error "No running clock"))
19633 (org-with-remote-undo (marker-buffer org-clock-marker)
19634 (org-clock-cancel)))
19636 (defun org-agenda-diary-entry ()
19637 "Make a diary entry, like the `i' command from the calendar.
19638 All the standard commands work: block, weekly etc."
19639 (interactive)
19640 (org-agenda-check-type t 'agenda 'timeline)
19641 (require 'diary-lib)
19642 (let* ((char (progn
19643 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
19644 (read-char-exclusive)))
19645 (cmd (cdr (assoc char
19646 '((?d . insert-diary-entry)
19647 (?w . insert-weekly-diary-entry)
19648 (?m . insert-monthly-diary-entry)
19649 (?y . insert-yearly-diary-entry)
19650 (?a . insert-anniversary-diary-entry)
19651 (?b . insert-block-diary-entry)
19652 (?c . insert-cyclic-diary-entry)))))
19653 (oldf (symbol-function 'calendar-cursor-to-date))
19654 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
19655 (point (point))
19656 (mark (or (mark t) (point))))
19657 (unless cmd
19658 (error "No command associated with <%c>" char))
19659 (unless (and (get-text-property point 'day)
19660 (or (not (equal ?b char))
19661 (get-text-property mark 'day)))
19662 (error "Don't know which date to use for diary entry"))
19663 ;; We implement this by hacking the `calendar-cursor-to-date' function
19664 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
19665 (let ((calendar-mark-ring
19666 (list (calendar-gregorian-from-absolute
19667 (or (get-text-property mark 'day)
19668 (get-text-property point 'day))))))
19669 (unwind-protect
19670 (progn
19671 (fset 'calendar-cursor-to-date
19672 (lambda (&optional error)
19673 (calendar-gregorian-from-absolute
19674 (get-text-property point 'day))))
19675 (call-interactively cmd))
19676 (fset 'calendar-cursor-to-date oldf)))))
19679 (defun org-agenda-execute-calendar-command (cmd)
19680 "Execute a calendar command from the agenda, with the date associated to
19681 the cursor position."
19682 (org-agenda-check-type t 'agenda 'timeline)
19683 (require 'diary-lib)
19684 (unless (get-text-property (point) 'day)
19685 (error "Don't know which date to use for calendar command"))
19686 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
19687 (point (point))
19688 (date (calendar-gregorian-from-absolute
19689 (get-text-property point 'day)))
19690 ;; the following 3 vars are needed in the calendar
19691 (displayed-day (extract-calendar-day date))
19692 (displayed-month (extract-calendar-month date))
19693 (displayed-year (extract-calendar-year date)))
19694 (unwind-protect
19695 (progn
19696 (fset 'calendar-cursor-to-date
19697 (lambda (&optional error)
19698 (calendar-gregorian-from-absolute
19699 (get-text-property point 'day))))
19700 (call-interactively cmd))
19701 (fset 'calendar-cursor-to-date oldf))))
19703 (defun org-agenda-phases-of-moon ()
19704 "Display the phases of the moon for the 3 months around the cursor date."
19705 (interactive)
19706 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
19708 (defun org-agenda-holidays ()
19709 "Display the holidays for the 3 months around the cursor date."
19710 (interactive)
19711 (org-agenda-execute-calendar-command 'list-calendar-holidays))
19713 (defun org-agenda-sunrise-sunset (arg)
19714 "Display sunrise and sunset for the cursor date.
19715 Latitude and longitude can be specified with the variables
19716 `calendar-latitude' and `calendar-longitude'. When called with prefix
19717 argument, latitude and longitude will be prompted for."
19718 (interactive "P")
19719 (let ((calendar-longitude (if arg nil calendar-longitude))
19720 (calendar-latitude (if arg nil calendar-latitude))
19721 (calendar-location-name
19722 (if arg "the given coordinates" calendar-location-name)))
19723 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
19725 (defun org-agenda-goto-calendar ()
19726 "Open the Emacs calendar with the date at the cursor."
19727 (interactive)
19728 (org-agenda-check-type t 'agenda 'timeline)
19729 (let* ((day (or (get-text-property (point) 'day)
19730 (error "Don't know which date to open in calendar")))
19731 (date (calendar-gregorian-from-absolute day))
19732 (calendar-move-hook nil)
19733 (view-calendar-holidays-initially nil)
19734 (view-diary-entries-initially nil))
19735 (calendar)
19736 (calendar-goto-date date)))
19738 (defun org-calendar-goto-agenda ()
19739 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
19740 This is a command that has to be installed in `calendar-mode-map'."
19741 (interactive)
19742 (org-agenda-list nil (calendar-absolute-from-gregorian
19743 (calendar-cursor-to-date))
19744 nil))
19746 (defun org-agenda-convert-date ()
19747 (interactive)
19748 (org-agenda-check-type t 'agenda 'timeline)
19749 (let ((day (get-text-property (point) 'day))
19750 date s)
19751 (unless day
19752 (error "Don't know which date to convert"))
19753 (setq date (calendar-gregorian-from-absolute day))
19754 (setq s (concat
19755 "Gregorian: " (calendar-date-string date) "\n"
19756 "ISO: " (calendar-iso-date-string date) "\n"
19757 "Day of Yr: " (calendar-day-of-year-string date) "\n"
19758 "Julian: " (calendar-julian-date-string date) "\n"
19759 "Astron. JD: " (calendar-astro-date-string date)
19760 " (Julian date number at noon UTC)\n"
19761 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
19762 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
19763 "French: " (calendar-french-date-string date) "\n"
19764 "Mayan: " (calendar-mayan-date-string date) "\n"
19765 "Coptic: " (calendar-coptic-date-string date) "\n"
19766 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
19767 "Persian: " (calendar-persian-date-string date) "\n"
19768 "Chinese: " (calendar-chinese-date-string date) "\n"))
19769 (with-output-to-temp-buffer "*Dates*"
19770 (princ s))
19771 (if (fboundp 'fit-window-to-buffer)
19772 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
19775 ;;;; Embedded LaTeX
19777 (defvar org-cdlatex-mode-map (make-sparse-keymap)
19778 "Keymap for the minor `org-cdlatex-mode'.")
19780 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
19781 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
19782 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
19783 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
19784 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
19786 (defvar org-cdlatex-texmathp-advice-is-done nil
19787 "Flag remembering if we have applied the advice to texmathp already.")
19789 (define-minor-mode org-cdlatex-mode
19790 "Toggle the minor `org-cdlatex-mode'.
19791 This mode supports entering LaTeX environment and math in LaTeX fragments
19792 in Org-mode.
19793 \\{org-cdlatex-mode-map}"
19794 nil " OCDL" nil
19795 (when org-cdlatex-mode (require 'cdlatex))
19796 (unless org-cdlatex-texmathp-advice-is-done
19797 (setq org-cdlatex-texmathp-advice-is-done t)
19798 (defadvice texmathp (around org-math-always-on activate)
19799 "Always return t in org-mode buffers.
19800 This is because we want to insert math symbols without dollars even outside
19801 the LaTeX math segments. If Orgmode thinks that point is actually inside
19802 en embedded LaTeX fragement, let texmathp do its job.
19803 \\[org-cdlatex-mode-map]"
19804 (interactive)
19805 (let (p)
19806 (cond
19807 ((not (org-mode-p)) ad-do-it)
19808 ((eq this-command 'cdlatex-math-symbol)
19809 (setq ad-return-value t
19810 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
19812 (let ((p (org-inside-LaTeX-fragment-p)))
19813 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
19814 (setq ad-return-value t
19815 texmathp-why '("Org-mode embedded math" . 0))
19816 (if p ad-do-it)))))))))
19818 (defun turn-on-org-cdlatex ()
19819 "Unconditionally turn on `org-cdlatex-mode'."
19820 (org-cdlatex-mode 1))
19822 (defun org-inside-LaTeX-fragment-p ()
19823 "Test if point is inside a LaTeX fragment.
19824 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19825 sequence appearing also before point.
19826 Even though the matchers for math are configurable, this function assumes
19827 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19828 delimiters are skipped when they have been removed by customization.
19829 The return value is nil, or a cons cell with the delimiter and
19830 and the position of this delimiter.
19832 This function does a reasonably good job, but can locally be fooled by
19833 for example currency specifications. For example it will assume being in
19834 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19835 fragments that are properly closed, but during editing, we have to live
19836 with the uncertainty caused by missing closing delimiters. This function
19837 looks only before point, not after."
19838 (catch 'exit
19839 (let ((pos (point))
19840 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19841 (lim (progn
19842 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19843 (point)))
19844 dd-on str (start 0) m re)
19845 (goto-char pos)
19846 (when dodollar
19847 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19848 re (nth 1 (assoc "$" org-latex-regexps)))
19849 (while (string-match re str start)
19850 (cond
19851 ((= (match-end 0) (length str))
19852 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19853 ((= (match-end 0) (- (length str) 5))
19854 (throw 'exit nil))
19855 (t (setq start (match-end 0))))))
19856 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19857 (goto-char pos)
19858 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19859 (and (match-beginning 2) (throw 'exit nil))
19860 ;; count $$
19861 (while (re-search-backward "\\$\\$" lim t)
19862 (setq dd-on (not dd-on)))
19863 (goto-char pos)
19864 (if dd-on (cons "$$" m))))))
19867 (defun org-try-cdlatex-tab ()
19868 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
19869 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
19870 - inside a LaTeX fragment, or
19871 - after the first word in a line, where an abbreviation expansion could
19872 insert a LaTeX environment."
19873 (when org-cdlatex-mode
19874 (cond
19875 ((save-excursion
19876 (skip-chars-backward "a-zA-Z0-9*")
19877 (skip-chars-backward " \t")
19878 (bolp))
19879 (cdlatex-tab) t)
19880 ((org-inside-LaTeX-fragment-p)
19881 (cdlatex-tab) t)
19882 (t nil))))
19884 (defun org-cdlatex-underscore-caret (&optional arg)
19885 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
19886 Revert to the normal definition outside of these fragments."
19887 (interactive "P")
19888 (if (org-inside-LaTeX-fragment-p)
19889 (call-interactively 'cdlatex-sub-superscript)
19890 (let (org-cdlatex-mode)
19891 (call-interactively (key-binding (vector last-input-event))))))
19893 (defun org-cdlatex-math-modify (&optional arg)
19894 "Execute `cdlatex-math-modify' in LaTeX fragments.
19895 Revert to the normal definition outside of these fragments."
19896 (interactive "P")
19897 (if (org-inside-LaTeX-fragment-p)
19898 (call-interactively 'cdlatex-math-modify)
19899 (let (org-cdlatex-mode)
19900 (call-interactively (key-binding (vector last-input-event))))))
19902 (defvar org-latex-fragment-image-overlays nil
19903 "List of overlays carrying the images of latex fragments.")
19904 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
19906 (defun org-remove-latex-fragment-image-overlays ()
19907 "Remove all overlays with LaTeX fragment images in current buffer."
19908 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
19909 (setq org-latex-fragment-image-overlays nil))
19911 (defun org-preview-latex-fragment (&optional subtree)
19912 "Preview the LaTeX fragment at point, or all locally or globally.
19913 If the cursor is in a LaTeX fragment, create the image and overlay
19914 it over the source code. If there is no fragment at point, display
19915 all fragments in the current text, from one headline to the next. With
19916 prefix SUBTREE, display all fragments in the current subtree. With a
19917 double prefix `C-u C-u', or when the cursor is before the first headline,
19918 display all fragments in the buffer.
19919 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
19920 (interactive "P")
19921 (org-remove-latex-fragment-image-overlays)
19922 (save-excursion
19923 (save-restriction
19924 (let (beg end at msg)
19925 (cond
19926 ((or (equal subtree '(16))
19927 (not (save-excursion
19928 (re-search-backward (concat "^" outline-regexp) nil t))))
19929 (setq beg (point-min) end (point-max)
19930 msg "Creating images for buffer...%s"))
19931 ((equal subtree '(4))
19932 (org-back-to-heading)
19933 (setq beg (point) end (org-end-of-subtree t)
19934 msg "Creating images for subtree...%s"))
19936 (if (setq at (org-inside-LaTeX-fragment-p))
19937 (goto-char (max (point-min) (- (cdr at) 2)))
19938 (org-back-to-heading))
19939 (setq beg (point) end (progn (outline-next-heading) (point))
19940 msg (if at "Creating image...%s"
19941 "Creating images for entry...%s"))))
19942 (message msg "")
19943 (narrow-to-region beg end)
19944 (goto-char beg)
19945 (org-format-latex
19946 (concat "ltxpng/" (file-name-sans-extension
19947 (file-name-nondirectory
19948 buffer-file-name)))
19949 default-directory 'overlays msg at 'forbuffer)
19950 (message msg "done. Use `C-c C-c' to remove images.")))))
19952 (defvar org-latex-regexps
19953 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
19954 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
19955 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
19956 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
19957 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
19958 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
19959 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
19960 "Regular expressions for matching embedded LaTeX.")
19962 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
19963 "Replace LaTeX fragments with links to an image, and produce images."
19964 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19965 (let* ((prefixnodir (file-name-nondirectory prefix))
19966 (absprefix (expand-file-name prefix dir))
19967 (todir (file-name-directory absprefix))
19968 (opt org-format-latex-options)
19969 (matchers (plist-get opt :matchers))
19970 (re-list org-latex-regexps)
19971 (cnt 0) txt link beg end re e checkdir
19972 m n block linkfile movefile ov)
19973 ;; Check if there are old images files with this prefix, and remove them
19974 (when (file-directory-p todir)
19975 (mapc 'delete-file
19976 (directory-files
19977 todir 'full
19978 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
19979 ;; Check the different regular expressions
19980 (while (setq e (pop re-list))
19981 (setq m (car e) re (nth 1 e) n (nth 2 e)
19982 block (if (nth 3 e) "\n\n" ""))
19983 (when (member m matchers)
19984 (goto-char (point-min))
19985 (while (re-search-forward re nil t)
19986 (when (or (not at) (equal (cdr at) (match-beginning n)))
19987 (setq txt (match-string n)
19988 beg (match-beginning n) end (match-end n)
19989 cnt (1+ cnt)
19990 linkfile (format "%s_%04d.png" prefix cnt)
19991 movefile (format "%s_%04d.png" absprefix cnt)
19992 link (concat block "[[file:" linkfile "]]" block))
19993 (if msg (message msg cnt))
19994 (goto-char beg)
19995 (unless checkdir ; make sure the directory exists
19996 (setq checkdir t)
19997 (or (file-directory-p todir) (make-directory todir)))
19998 (org-create-formula-image
19999 txt movefile opt forbuffer)
20000 (if overlays
20001 (progn
20002 (setq ov (org-make-overlay beg end))
20003 (if (featurep 'xemacs)
20004 (progn
20005 (org-overlay-put ov 'invisible t)
20006 (org-overlay-put
20007 ov 'end-glyph
20008 (make-glyph (vector 'png :file movefile))))
20009 (org-overlay-put
20010 ov 'display
20011 (list 'image :type 'png :file movefile :ascent 'center)))
20012 (push ov org-latex-fragment-image-overlays)
20013 (goto-char end))
20014 (delete-region beg end)
20015 (insert link))))))))
20017 ;; This function borrows from Ganesh Swami's latex2png.el
20018 (defun org-create-formula-image (string tofile options buffer)
20019 (let* ((tmpdir (if (featurep 'xemacs)
20020 (temp-directory)
20021 temporary-file-directory))
20022 (texfilebase (make-temp-name
20023 (expand-file-name "orgtex" tmpdir)))
20024 (texfile (concat texfilebase ".tex"))
20025 (dvifile (concat texfilebase ".dvi"))
20026 (pngfile (concat texfilebase ".png"))
20027 (fnh (face-attribute 'default :height nil))
20028 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
20029 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
20030 (fg (or (plist-get options (if buffer :foreground :html-foreground))
20031 "Black"))
20032 (bg (or (plist-get options (if buffer :background :html-background))
20033 "Transparent")))
20034 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
20035 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
20036 (with-temp-file texfile
20037 (insert org-format-latex-header
20038 "\n\\begin{document}\n" string "\n\\end{document}\n"))
20039 (let ((dir default-directory))
20040 (condition-case nil
20041 (progn
20042 (cd tmpdir)
20043 (call-process "latex" nil nil nil texfile))
20044 (error nil))
20045 (cd dir))
20046 (if (not (file-exists-p dvifile))
20047 (progn (message "Failed to create dvi file from %s" texfile) nil)
20048 (call-process "dvipng" nil nil nil
20049 "-E" "-fg" fg "-bg" bg
20050 "-D" dpi
20051 ;;"-x" scale "-y" scale
20052 "-T" "tight"
20053 "-o" pngfile
20054 dvifile)
20055 (if (not (file-exists-p pngfile))
20056 (progn (message "Failed to create png file from %s" texfile) nil)
20057 ;; Use the requested file name and clean up
20058 (copy-file pngfile tofile 'replace)
20059 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
20060 (delete-file (concat texfilebase e)))
20061 pngfile))))
20063 (defun org-dvipng-color (attr)
20064 "Return an rgb color specification for dvipng."
20065 (apply 'format "rgb %s %s %s"
20066 (mapcar 'org-normalize-color
20067 (color-values (face-attribute 'default attr nil)))))
20069 (defun org-normalize-color (value)
20070 "Return string to be used as color value for an RGB component."
20071 (format "%g" (/ value 65535.0)))
20073 ;;;; Exporting
20075 ;;; Variables, constants, and parameter plists
20077 (defconst org-level-max 20)
20079 (defvar org-export-html-preamble nil
20080 "Preamble, to be inserted just after <body>. Set by publishing functions.")
20081 (defvar org-export-html-postamble nil
20082 "Preamble, to be inserted just before </body>. Set by publishing functions.")
20083 (defvar org-export-html-auto-preamble t
20084 "Should default preamble be inserted? Set by publishing functions.")
20085 (defvar org-export-html-auto-postamble t
20086 "Should default postamble be inserted? Set by publishing functions.")
20087 (defvar org-current-export-file nil) ; dynamically scoped parameter
20088 (defvar org-current-export-dir nil) ; dynamically scoped parameter
20091 (defconst org-export-plist-vars
20092 '((:language . org-export-default-language)
20093 (:customtime . org-display-custom-times)
20094 (:headline-levels . org-export-headline-levels)
20095 (:section-numbers . org-export-with-section-numbers)
20096 (:table-of-contents . org-export-with-toc)
20097 (:preserve-breaks . org-export-preserve-breaks)
20098 (:archived-trees . org-export-with-archived-trees)
20099 (:emphasize . org-export-with-emphasize)
20100 (:sub-superscript . org-export-with-sub-superscripts)
20101 (:footnotes . org-export-with-footnotes)
20102 (:property-drawer . org-export-with-property-drawer)
20103 (:TeX-macros . org-export-with-TeX-macros)
20104 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
20105 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
20106 (:fixed-width . org-export-with-fixed-width)
20107 (:timestamps . org-export-with-timestamps)
20108 (:author-info . org-export-author-info)
20109 (:time-stamp-file . org-export-time-stamp-file)
20110 (:tables . org-export-with-tables)
20111 (:table-auto-headline . org-export-highlight-first-table-line)
20112 (:style . org-export-html-style)
20113 (:agenda-style . org-agenda-export-html-style) ;; FIXME: Does this work????
20114 (:convert-org-links . org-export-html-link-org-files-as-html)
20115 (:inline-images . org-export-html-inline-images)
20116 (:expand-quoted-html . org-export-html-expand)
20117 (:timestamp . org-export-html-with-timestamp)
20118 (:publishing-directory . org-export-publishing-directory)
20119 (:preamble . org-export-html-preamble)
20120 (:postamble . org-export-html-postamble)
20121 (:auto-preamble . org-export-html-auto-preamble)
20122 (:auto-postamble . org-export-html-auto-postamble)
20123 (:author . user-full-name)
20124 (:email . user-mail-address)))
20126 (defun org-default-export-plist ()
20127 "Return the property list with default settings for the export variables."
20128 (let ((l org-export-plist-vars) rtn e)
20129 (while (setq e (pop l))
20130 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
20131 rtn))
20133 (defun org-infile-export-plist ()
20134 "Return the property list with file-local settings for export."
20135 (save-excursion
20136 (goto-char 0)
20137 (let ((re (org-make-options-regexp
20138 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
20139 p key val text options)
20140 (while (re-search-forward re nil t)
20141 (setq key (org-match-string-no-properties 1)
20142 val (org-match-string-no-properties 2))
20143 (cond
20144 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
20145 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
20146 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
20147 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
20148 ((string-equal key "TEXT")
20149 (setq text (if text (concat text "\n" val) val)))
20150 ((string-equal key "OPTIONS") (setq options val))))
20151 (setq p (plist-put p :text text))
20152 (when options
20153 (let ((op '(("H" . :headline-levels)
20154 ("num" . :section-numbers)
20155 ("toc" . :table-of-contents)
20156 ("\\n" . :preserve-breaks)
20157 ("@" . :expand-quoted-html)
20158 (":" . :fixed-width)
20159 ("|" . :tables)
20160 ("^" . :sub-superscript)
20161 ("f" . :footnotes)
20162 ("p" . :property-drawer)
20163 ("*" . :emphasize)
20164 ("TeX" . :TeX-macros)
20165 ("LaTeX" . :LaTeX-fragments)
20166 ("skip" . :skip-before-1st-heading)
20167 ("author" . :author-info)
20168 ("timestamp" . :time-stamp-file)))
20170 (while (setq o (pop op))
20171 (if (string-match (concat (regexp-quote (car o))
20172 ":\\([^ \t\n\r;,.]*\\)")
20173 options)
20174 (setq p (plist-put p (cdr o)
20175 (car (read-from-string
20176 (match-string 1 options)))))))))
20177 p)))
20179 (defun org-export-directory (type plist)
20180 (let* ((val (plist-get plist :publishing-directory))
20181 (dir (if (listp val)
20182 (or (cdr (assoc type val)) ".")
20183 val)))
20184 dir))
20186 (defun org-skip-comments (lines)
20187 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
20188 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
20189 (re2 "^\\(\\*+\\)[ \t\n\r]")
20190 (case-fold-search nil)
20191 rtn line level)
20192 (while (setq line (pop lines))
20193 (cond
20194 ((and (string-match re1 line)
20195 (setq level (- (match-end 1) (match-beginning 1))))
20196 ;; Beginning of a COMMENT subtree. Skip it.
20197 (while (and (setq line (pop lines))
20198 (or (not (string-match re2 line))
20199 (> (- (match-end 1) (match-beginning 1)) level))))
20200 (setq lines (cons line lines)))
20201 ((string-match "^#" line)
20202 ;; an ordinary comment line
20204 ((and org-export-table-remove-special-lines
20205 (string-match "^[ \t]*|" line)
20206 (or (string-match "^[ \t]*| *[!_^] *|" line)
20207 (and (string-match "| *<[0-9]+> *|" line)
20208 (not (string-match "| *[^ <|]" line)))))
20209 ;; a special table line that should be removed
20211 (t (setq rtn (cons line rtn)))))
20212 (nreverse rtn)))
20214 (defun org-export (&optional arg)
20215 (interactive)
20216 (let ((help "[t] insert the export option template
20217 \[v] limit export to visible part of outline tree
20219 \[a] export as ASCII
20221 \[h] export as HTML
20222 \[H] export as HTML to temporary buffer
20223 \[R] export region as HTML
20224 \[b] export as HTML and browse immediately
20225 \[x] export as XOXO
20227 \[l] export as LaTeX
20228 \[L] export as LaTeX to temporary buffer
20230 \[i] export current file as iCalendar file
20231 \[I] export all agenda files as iCalendar files
20232 \[c] export agenda files into combined iCalendar file
20234 \[F] publish current file
20235 \[P] publish current project
20236 \[X] publish... (project will be prompted for)
20237 \[A] publish all projects")
20238 (cmds
20239 '((?t . org-insert-export-options-template)
20240 (?v . org-export-visible)
20241 (?a . org-export-as-ascii)
20242 (?h . org-export-as-html)
20243 (?b . org-export-as-html-and-open)
20244 (?H . org-export-as-html-to-buffer)
20245 (?R . org-export-region-as-html)
20246 (?x . org-export-as-xoxo)
20247 (?l . org-export-as-latex)
20248 (?L . org-export-as-latex-to-buffer)
20249 (?i . org-export-icalendar-this-file)
20250 (?I . org-export-icalendar-all-agenda-files)
20251 (?c . org-export-icalendar-combine-agenda-files)
20252 (?F . org-publish-current-file)
20253 (?P . org-publish-current-project)
20254 (?X . org-publish)
20255 (?A . org-publish-all)))
20256 r1 r2 ass)
20257 (save-window-excursion
20258 (delete-other-windows)
20259 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
20260 (princ help))
20261 (message "Select command: ")
20262 (setq r1 (read-char-exclusive)))
20263 (setq r2 (if (< r1 27) (+ r1 96) r1))
20264 (if (setq ass (assq r2 cmds))
20265 (call-interactively (cdr ass))
20266 (error "No command associated with key %c" r1))))
20268 (defconst org-html-entities
20269 '(("nbsp")
20270 ("iexcl")
20271 ("cent")
20272 ("pound")
20273 ("curren")
20274 ("yen")
20275 ("brvbar")
20276 ("vert" . "&#124;")
20277 ("sect")
20278 ("uml")
20279 ("copy")
20280 ("ordf")
20281 ("laquo")
20282 ("not")
20283 ("shy")
20284 ("reg")
20285 ("macr")
20286 ("deg")
20287 ("plusmn")
20288 ("sup2")
20289 ("sup3")
20290 ("acute")
20291 ("micro")
20292 ("para")
20293 ("middot")
20294 ("odot"."o")
20295 ("star"."*")
20296 ("cedil")
20297 ("sup1")
20298 ("ordm")
20299 ("raquo")
20300 ("frac14")
20301 ("frac12")
20302 ("frac34")
20303 ("iquest")
20304 ("Agrave")
20305 ("Aacute")
20306 ("Acirc")
20307 ("Atilde")
20308 ("Auml")
20309 ("Aring") ("AA"."&Aring;")
20310 ("AElig")
20311 ("Ccedil")
20312 ("Egrave")
20313 ("Eacute")
20314 ("Ecirc")
20315 ("Euml")
20316 ("Igrave")
20317 ("Iacute")
20318 ("Icirc")
20319 ("Iuml")
20320 ("ETH")
20321 ("Ntilde")
20322 ("Ograve")
20323 ("Oacute")
20324 ("Ocirc")
20325 ("Otilde")
20326 ("Ouml")
20327 ("times")
20328 ("Oslash")
20329 ("Ugrave")
20330 ("Uacute")
20331 ("Ucirc")
20332 ("Uuml")
20333 ("Yacute")
20334 ("THORN")
20335 ("szlig")
20336 ("agrave")
20337 ("aacute")
20338 ("acirc")
20339 ("atilde")
20340 ("auml")
20341 ("aring")
20342 ("aelig")
20343 ("ccedil")
20344 ("egrave")
20345 ("eacute")
20346 ("ecirc")
20347 ("euml")
20348 ("igrave")
20349 ("iacute")
20350 ("icirc")
20351 ("iuml")
20352 ("eth")
20353 ("ntilde")
20354 ("ograve")
20355 ("oacute")
20356 ("ocirc")
20357 ("otilde")
20358 ("ouml")
20359 ("divide")
20360 ("oslash")
20361 ("ugrave")
20362 ("uacute")
20363 ("ucirc")
20364 ("uuml")
20365 ("yacute")
20366 ("thorn")
20367 ("yuml")
20368 ("fnof")
20369 ("Alpha")
20370 ("Beta")
20371 ("Gamma")
20372 ("Delta")
20373 ("Epsilon")
20374 ("Zeta")
20375 ("Eta")
20376 ("Theta")
20377 ("Iota")
20378 ("Kappa")
20379 ("Lambda")
20380 ("Mu")
20381 ("Nu")
20382 ("Xi")
20383 ("Omicron")
20384 ("Pi")
20385 ("Rho")
20386 ("Sigma")
20387 ("Tau")
20388 ("Upsilon")
20389 ("Phi")
20390 ("Chi")
20391 ("Psi")
20392 ("Omega")
20393 ("alpha")
20394 ("beta")
20395 ("gamma")
20396 ("delta")
20397 ("epsilon")
20398 ("varepsilon"."&epsilon;")
20399 ("zeta")
20400 ("eta")
20401 ("theta")
20402 ("iota")
20403 ("kappa")
20404 ("lambda")
20405 ("mu")
20406 ("nu")
20407 ("xi")
20408 ("omicron")
20409 ("pi")
20410 ("rho")
20411 ("sigmaf") ("varsigma"."&sigmaf;")
20412 ("sigma")
20413 ("tau")
20414 ("upsilon")
20415 ("phi")
20416 ("chi")
20417 ("psi")
20418 ("omega")
20419 ("thetasym") ("vartheta"."&thetasym;")
20420 ("upsih")
20421 ("piv")
20422 ("bull") ("bullet"."&bull;")
20423 ("hellip") ("dots"."&hellip;")
20424 ("prime")
20425 ("Prime")
20426 ("oline")
20427 ("frasl")
20428 ("weierp")
20429 ("image")
20430 ("real")
20431 ("trade")
20432 ("alefsym")
20433 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
20434 ("uarr") ("uparrow"."&uarr;")
20435 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
20436 ("darr")("downarrow"."&darr;")
20437 ("harr") ("leftrightarrow"."&harr;")
20438 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
20439 ("lArr") ("Leftarrow"."&lArr;")
20440 ("uArr") ("Uparrow"."&uArr;")
20441 ("rArr") ("Rightarrow"."&rArr;")
20442 ("dArr") ("Downarrow"."&dArr;")
20443 ("hArr") ("Leftrightarrow"."&hArr;")
20444 ("forall")
20445 ("part") ("partial"."&part;")
20446 ("exist") ("exists"."&exist;")
20447 ("empty") ("emptyset"."&empty;")
20448 ("nabla")
20449 ("isin") ("in"."&isin;")
20450 ("notin")
20451 ("ni")
20452 ("prod")
20453 ("sum")
20454 ("minus")
20455 ("lowast") ("ast"."&lowast;")
20456 ("radic")
20457 ("prop") ("proptp"."&prop;")
20458 ("infin") ("infty"."&infin;")
20459 ("ang") ("angle"."&ang;")
20460 ("and") ("vee"."&and;")
20461 ("or") ("wedge"."&or;")
20462 ("cap")
20463 ("cup")
20464 ("int")
20465 ("there4")
20466 ("sim")
20467 ("cong") ("simeq"."&cong;")
20468 ("asymp")("approx"."&asymp;")
20469 ("ne") ("neq"."&ne;")
20470 ("equiv")
20471 ("le")
20472 ("ge")
20473 ("sub") ("subset"."&sub;")
20474 ("sup") ("supset"."&sup;")
20475 ("nsub")
20476 ("sube")
20477 ("supe")
20478 ("oplus")
20479 ("otimes")
20480 ("perp")
20481 ("sdot") ("cdot"."&sdot;")
20482 ("lceil")
20483 ("rceil")
20484 ("lfloor")
20485 ("rfloor")
20486 ("lang")
20487 ("rang")
20488 ("loz") ("Diamond"."&loz;")
20489 ("spades") ("spadesuit"."&spades;")
20490 ("clubs") ("clubsuit"."&clubs;")
20491 ("hearts") ("diamondsuit"."&hearts;")
20492 ("diams") ("diamondsuit"."&diams;")
20493 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
20494 ("quot")
20495 ("amp")
20496 ("lt")
20497 ("gt")
20498 ("OElig")
20499 ("oelig")
20500 ("Scaron")
20501 ("scaron")
20502 ("Yuml")
20503 ("circ")
20504 ("tilde")
20505 ("ensp")
20506 ("emsp")
20507 ("thinsp")
20508 ("zwnj")
20509 ("zwj")
20510 ("lrm")
20511 ("rlm")
20512 ("ndash")
20513 ("mdash")
20514 ("lsquo")
20515 ("rsquo")
20516 ("sbquo")
20517 ("ldquo")
20518 ("rdquo")
20519 ("bdquo")
20520 ("dagger")
20521 ("Dagger")
20522 ("permil")
20523 ("lsaquo")
20524 ("rsaquo")
20525 ("euro")
20527 ("arccos"."arccos")
20528 ("arcsin"."arcsin")
20529 ("arctan"."arctan")
20530 ("arg"."arg")
20531 ("cos"."cos")
20532 ("cosh"."cosh")
20533 ("cot"."cot")
20534 ("coth"."coth")
20535 ("csc"."csc")
20536 ("deg"."deg")
20537 ("det"."det")
20538 ("dim"."dim")
20539 ("exp"."exp")
20540 ("gcd"."gcd")
20541 ("hom"."hom")
20542 ("inf"."inf")
20543 ("ker"."ker")
20544 ("lg"."lg")
20545 ("lim"."lim")
20546 ("liminf"."liminf")
20547 ("limsup"."limsup")
20548 ("ln"."ln")
20549 ("log"."log")
20550 ("max"."max")
20551 ("min"."min")
20552 ("Pr"."Pr")
20553 ("sec"."sec")
20554 ("sin"."sin")
20555 ("sinh"."sinh")
20556 ("sup"."sup")
20557 ("tan"."tan")
20558 ("tanh"."tanh")
20560 "Entities for TeX->HTML translation.
20561 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
20562 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
20563 In that case, \"\\ent\" will be translated to \"&other;\".
20564 The list contains HTML entities for Latin-1, Greek and other symbols.
20565 It is supplemented by a number of commonly used TeX macros with appropriate
20566 translations. There is currently no way for users to extend this.")
20568 ;;; General functions for all backends
20570 (defun org-cleaned-string-for-export (string &rest parameters)
20571 "Cleanup a buffer STRING so that links can be created safely."
20572 (interactive)
20573 (let* ((re-radio (and org-target-link-regexp
20574 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
20575 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
20576 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
20577 (re-archive (concat ":" org-archive-tag ":"))
20578 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
20579 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
20580 (htmlp (plist-get parameters :for-html))
20581 (asciip (plist-get parameters :for-ascii))
20582 (latexp (plist-get parameters :for-LaTeX))
20583 (commentsp (plist-get parameters :comments))
20584 (archived-trees (plist-get parameters :archived-trees))
20585 (inhibit-read-only t)
20586 (outline-regexp "\\*+ ")
20587 a b xx
20588 rtn p)
20589 (with-current-buffer (get-buffer-create " org-mode-tmp")
20590 (erase-buffer)
20591 (insert string)
20592 ;; Remove license-to-kill stuff
20593 (while (setq p (text-property-any (point-min) (point-max)
20594 :org-license-to-kill t))
20595 (delete-region p (next-single-property-change p :org-license-to-kill)))
20597 (let ((org-inhibit-startup t)) (org-mode))
20598 (untabify (point-min) (point-max))
20600 ;; Get the correct stuff before the first headline
20601 (when (plist-get parameters :skip-before-1st-heading)
20602 (goto-char (point-min))
20603 (when (re-search-forward "^\\*+[ \t]" nil t)
20604 (delete-region (point-min) (match-beginning 0))
20605 (goto-char (point-min))
20606 (insert "\n")))
20607 (when (plist-get parameters :add-text)
20608 (goto-char (point-min))
20609 (insert (plist-get parameters :add-text) "\n"))
20611 ;; Get rid of archived trees
20612 (when (not (eq archived-trees t))
20613 (goto-char (point-min))
20614 (while (re-search-forward re-archive nil t)
20615 (if (not (org-on-heading-p t))
20616 (org-end-of-subtree t)
20617 (beginning-of-line 1)
20618 (setq a (if archived-trees
20619 (1+ (point-at-eol)) (point))
20620 b (org-end-of-subtree t))
20621 (if (> b a) (delete-region a b)))))
20623 ;; Get rid of property drawers
20624 (unless org-export-with-property-drawer
20625 (goto-char (point-min))
20626 (while (re-search-forward "^[ \t]*:PROPERTIES:[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n" nil t)
20627 (replace-match "")))
20629 ;; Find targets in comments and move them out of comments,
20630 ;; but mark them as targets that should be invisible
20631 (goto-char (point-min))
20632 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
20633 (replace-match "\\1(INVISIBLE)"))
20635 ;; Protect backend specific stuff, throw away the others.
20636 (goto-char (point-min))
20637 (let ((formatters
20638 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
20639 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
20640 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
20641 fmt)
20642 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
20643 (add-text-properties (match-beginning 0) (match-end 0)
20644 '(org-protected t)))
20645 (while formatters
20646 (setq fmt (pop formatters))
20647 (when (car fmt)
20648 (goto-char (point-min))
20649 (while (re-search-forward (concat "^#\\+" (cadr fmt)
20650 ":[ \t]*\\(.*\\)") nil t)
20651 (replace-match "\\1" t)
20652 (add-text-properties
20653 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
20654 '(org-protected t))))
20655 (goto-char (point-min))
20656 (while (re-search-forward
20657 (concat "^#\\+"
20658 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
20659 (cadddr fmt) "\\>.*\n?") nil t)
20660 (if (car fmt)
20661 (add-text-properties (match-beginning 1) (1+ (match-end 1))
20662 '(org-protected t))
20663 (delete-region (match-beginning 0) (match-end 0))))))
20665 ;; Protect quoted subtrees
20666 (goto-char (point-min))
20667 (while (re-search-forward re-quote nil t)
20668 (goto-char (match-beginning 0))
20669 (end-of-line 1)
20670 (add-text-properties (point) (org-end-of-subtree t)
20671 '(org-protected t)))
20673 ;; Remove subtrees that are commented
20674 (goto-char (point-min))
20675 (while (re-search-forward re-commented nil t)
20676 (goto-char (match-beginning 0))
20677 (delete-region (point) (org-end-of-subtree t)))
20679 ;; Remove special table lines
20680 (when org-export-table-remove-special-lines
20681 (goto-char (point-min))
20682 (while (re-search-forward "^[ \t]*|" nil t)
20683 (beginning-of-line 1)
20684 (if (or (looking-at "[ \t]*| *[!_^] *|")
20685 (and (looking-at ".*?| *<[0-9]+> *|")
20686 (not (looking-at ".*?| *[^ <|]"))))
20687 (delete-region (max (point-min) (1- (point-at-bol)))
20688 (point-at-eol))
20689 (end-of-line 1))))
20691 ;; Specific LaTeX stuff
20692 (when latexp
20693 (require 'org-export-latex nil t)
20694 (org-export-latex-cleaned-string))
20696 ;; Specific HTML stuff
20697 (when htmlp
20698 ;; Convert LaTeX fragments to images
20699 (when (plist-get parameters :LaTeX-fragments)
20700 (org-format-latex
20701 (concat "ltxpng/" (file-name-sans-extension
20702 (file-name-nondirectory
20703 org-current-export-file)))
20704 org-current-export-dir nil "Creating LaTeX image %s"))
20705 (message "Exporting..."))
20707 ;; Remove or replace comments
20708 ;; FIXME: Does LaTeX export take care of its own comments?
20709 ;; If :comments is set, use this char for commenting out comments and
20710 ;; protect them. otherwise delete them
20711 (goto-char (point-min))
20712 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
20713 (if commentsp
20714 (progn (add-text-properties
20715 (match-beginning 0) (match-end 0) '(org-protected t))
20716 (replace-match (format commentsp (match-string 1)) t t))
20717 (replace-match "")))
20719 ;; Find matches for radio targets and turn them into internal links
20720 (goto-char (point-min))
20721 (when re-radio
20722 (while (re-search-forward re-radio nil t)
20723 (org-if-unprotected
20724 (replace-match "\\1[[\\2]]"))))
20726 ;; Find all links that contain a newline and put them into a single line
20727 (goto-char (point-min))
20728 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
20729 (org-if-unprotected
20730 (replace-match "\\1 \\3")
20731 (goto-char (match-beginning 0))))
20734 ;; Normalize links: Convert angle and plain links into bracket links
20735 ;; Expand link abbreviations
20736 (goto-char (point-min))
20737 (while (re-search-forward re-plain-link nil t)
20738 (goto-char (1- (match-end 0)))
20739 (org-if-unprotected
20740 (let* ((s (concat (match-string 1) "[[" (match-string 2)
20741 ":" (match-string 3) "]]")))
20742 ;; added 'org-link face to links
20743 (put-text-property 0 (length s) 'face 'org-link s)
20744 (replace-match s t t))))
20745 (goto-char (point-min))
20746 (while (re-search-forward re-angle-link nil t)
20747 (goto-char (1- (match-end 0)))
20748 (org-if-unprotected
20749 (let* ((s (concat (match-string 1) "[[" (match-string 2)
20750 ":" (match-string 3) "]]")))
20751 (put-text-property 0 (length s) 'face 'org-link s)
20752 (replace-match s t t))))
20753 (goto-char (point-min))
20754 (while (re-search-forward org-bracket-link-regexp nil t)
20755 (org-if-unprotected
20756 (let* ((s (concat "[[" (setq xx (save-match-data
20757 (org-link-expand-abbrev (match-string 1))))
20759 (if (match-end 3)
20760 (match-string 2)
20761 (concat "[" xx "]"))
20762 "]")))
20763 (put-text-property 0 (length s) 'face 'org-link s)
20764 (replace-match s t t))))
20766 ;; Find multiline emphasis and put them into single line
20767 (when (plist-get parameters :emph-multiline)
20768 (goto-char (point-min))
20769 (while (re-search-forward org-emph-re nil t)
20770 (if (not (= (char-after (match-beginning 3))
20771 (char-after (match-beginning 4))))
20772 (org-if-unprotected
20773 (subst-char-in-region (match-beginning 0) (match-end 0)
20774 ?\n ?\ t)
20775 (goto-char (1- (match-end 0))))
20776 (goto-char (1+ (match-beginning 0))))))
20778 (setq rtn (buffer-string)))
20779 (kill-buffer " org-mode-tmp")
20780 rtn))
20782 (defun org-export-grab-title-from-buffer ()
20783 "Get a title for the current document, from looking at the buffer."
20784 (let ((inhibit-read-only t))
20785 (save-excursion
20786 (goto-char (point-min))
20787 (let ((end (save-excursion (outline-next-heading) (point))))
20788 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
20789 ;; Mark the line so that it will not be exported as normal text.
20790 (org-unmodified
20791 (add-text-properties (match-beginning 0) (match-end 0)
20792 (list :org-license-to-kill t)))
20793 ;; Return the title string
20794 (org-trim (match-string 0)))))))
20796 (defun org-export-get-title-from-subtree ()
20797 "Return subtree title and exclude it from export."
20798 (let (title (m (mark)))
20799 (save-excursion
20800 (goto-char (region-beginning))
20801 (when (and (org-at-heading-p)
20802 (>= (org-end-of-subtree t t) (region-end)))
20803 ;; This is a subtree, we take the title from the first heading
20804 (goto-char (region-beginning))
20805 (looking-at org-todo-line-regexp)
20806 (setq title (match-string 3))
20807 (org-unmodified
20808 (add-text-properties (point) (1+ (point-at-eol))
20809 (list :org-license-to-kill t)))))
20810 title))
20812 (defun org-solidify-link-text (s &optional alist)
20813 "Take link text and make a safe target out of it."
20814 (save-match-data
20815 (let* ((rtn
20816 (mapconcat
20817 'identity
20818 (org-split-string s "[ \t\r\n]+") "--"))
20819 (a (assoc rtn alist)))
20820 (or (cdr a) rtn))))
20822 ;; Variable holding the vector with section numbers
20823 (defvar org-section-numbers (make-vector org-level-max 0))
20825 (defun org-init-section-numbers ()
20826 "Initialize the vector for the section numbers."
20827 (let* ((level -1)
20828 (numbers (nreverse (org-split-string "" "\\.")))
20829 (depth (1- (length org-section-numbers)))
20830 (i depth) number-string)
20831 (while (>= i 0)
20832 (if (> i level)
20833 (aset org-section-numbers i 0)
20834 (setq number-string (or (car numbers) "0"))
20835 (if (string-match "\\`[A-Z]\\'" number-string)
20836 (aset org-section-numbers i
20837 (- (string-to-char number-string) ?A -1))
20838 (aset org-section-numbers i (string-to-number number-string)))
20839 (pop numbers))
20840 (setq i (1- i)))))
20842 (defun org-section-number (&optional level)
20843 "Return a string with the current section number.
20844 When LEVEL is non-nil, increase section numbers on that level."
20845 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
20846 (when level
20847 (when (> level -1)
20848 (aset org-section-numbers
20849 level (1+ (aref org-section-numbers level))))
20850 (setq idx (1+ level))
20851 (while (<= idx depth)
20852 (if (not (= idx 1))
20853 (aset org-section-numbers idx 0))
20854 (setq idx (1+ idx))))
20855 (setq idx 0)
20856 (while (<= idx depth)
20857 (setq n (aref org-section-numbers idx))
20858 (setq string (concat string (if (not (string= string "")) "." "")
20859 (int-to-string n)))
20860 (setq idx (1+ idx)))
20861 (save-match-data
20862 (if (string-match "\\`\\([@0]\\.\\)+" string)
20863 (setq string (replace-match "" t nil string)))
20864 (if (string-match "\\(\\.0\\)+\\'" string)
20865 (setq string (replace-match "" t nil string))))
20866 string))
20868 ;;; ASCII export
20870 (defvar org-last-level nil) ; dynamically scoped variable
20871 (defvar org-min-level nil) ; dynamically scoped variable
20872 (defvar org-levels-open nil) ; dynamically scoped parameter
20873 (defvar org-ascii-current-indentation nil) ; For communication
20875 (defun org-export-as-ascii (arg)
20876 "Export the outline as a pretty ASCII file.
20877 If there is an active region, export only the region.
20878 The prefix ARG specifies how many levels of the outline should become
20879 underlined headlines. The default is 3."
20880 (interactive "P")
20881 (setq-default org-todo-line-regexp org-todo-line-regexp)
20882 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
20883 (org-infile-export-plist)))
20884 (region-p (org-region-active-p))
20885 (subtree-p
20886 (when region-p
20887 (save-excursion
20888 (goto-char (region-beginning))
20889 (and (org-at-heading-p)
20890 (>= (org-end-of-subtree t t) (region-end))))))
20891 (custom-times org-display-custom-times)
20892 (org-ascii-current-indentation '(0 . 0))
20893 (level 0) line txt
20894 (umax nil)
20895 (umax-toc nil)
20896 (case-fold-search nil)
20897 (filename (concat (file-name-as-directory
20898 (org-export-directory :ascii opt-plist))
20899 (file-name-sans-extension
20900 (or (and subtree-p
20901 (org-entry-get (region-beginning)
20902 "EXPORT_FILE_NAME" t))
20903 (file-name-nondirectory buffer-file-name)))
20904 ".txt"))
20905 (filename (if (equal (file-truename filename)
20906 (file-truename buffer-file-name))
20907 (concat filename ".txt")
20908 filename))
20909 (buffer (find-file-noselect filename))
20910 (org-levels-open (make-vector org-level-max nil))
20911 (odd org-odd-levels-only)
20912 (date (format-time-string "%Y/%m/%d" (current-time)))
20913 (time (format-time-string "%X" (org-current-time)))
20914 (author (plist-get opt-plist :author))
20915 (title (or (and subtree-p (org-export-get-title-from-subtree))
20916 (plist-get opt-plist :title)
20917 (and (not
20918 (plist-get opt-plist :skip-before-1st-heading))
20919 (org-export-grab-title-from-buffer))
20920 (file-name-sans-extension
20921 (file-name-nondirectory buffer-file-name))))
20922 (email (plist-get opt-plist :email))
20923 (language (plist-get opt-plist :language))
20924 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
20925 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
20926 (todo nil)
20927 (lang-words nil)
20928 (region
20929 (buffer-substring
20930 (if (org-region-active-p) (region-beginning) (point-min))
20931 (if (org-region-active-p) (region-end) (point-max))))
20932 (lines (org-split-string
20933 (org-cleaned-string-for-export
20934 region
20935 :for-ascii t
20936 :skip-before-1st-heading
20937 (plist-get opt-plist :skip-before-1st-heading)
20938 :archived-trees
20939 (plist-get opt-plist :archived-trees)
20940 :add-text (plist-get opt-plist :text))
20941 "[\r\n]")) ;; FIXME: why \r here???/
20942 thetoc have-headings first-heading-pos
20943 table-open table-buffer)
20945 (let ((inhibit-read-only t))
20946 (org-unmodified
20947 (remove-text-properties (point-min) (point-max)
20948 '(:org-license-to-kill t))))
20950 (setq org-min-level (org-get-min-level lines))
20951 (setq org-last-level org-min-level)
20952 (org-init-section-numbers)
20954 (find-file-noselect filename)
20956 (setq lang-words (or (assoc language org-export-language-setup)
20957 (assoc "en" org-export-language-setup)))
20958 (switch-to-buffer-other-window buffer)
20959 (erase-buffer)
20960 (fundamental-mode)
20961 ;; create local variables for all options, to make sure all called
20962 ;; functions get the correct information
20963 (mapcar (lambda (x)
20964 (set (make-local-variable (cdr x))
20965 (plist-get opt-plist (car x))))
20966 org-export-plist-vars)
20967 (org-set-local 'org-odd-levels-only odd)
20968 (setq umax (if arg (prefix-numeric-value arg)
20969 org-export-headline-levels))
20970 (setq umax-toc (if (integerp org-export-with-toc)
20971 (min org-export-with-toc umax)
20972 umax))
20974 ;; File header
20975 (if title (org-insert-centered title ?=))
20976 (insert "\n")
20977 (if (and (or author email)
20978 org-export-author-info)
20979 (insert (concat (nth 1 lang-words) ": " (or author "")
20980 (if email (concat " <" email ">") "")
20981 "\n")))
20982 (if (and date time org-export-time-stamp-file)
20983 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
20985 (insert "\n\n")
20987 (if org-export-with-toc
20988 (progn
20989 (push (concat (nth 3 lang-words) "\n") thetoc)
20990 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
20991 (mapcar '(lambda (line)
20992 (if (string-match org-todo-line-regexp
20993 line)
20994 ;; This is a headline
20995 (progn
20996 (setq have-headings t)
20997 (setq level (- (match-end 1) (match-beginning 1))
20998 level (org-tr-level level)
20999 txt (match-string 3 line)
21000 todo
21001 (or (and org-export-mark-todo-in-toc
21002 (match-beginning 2)
21003 (not (member (match-string 2 line)
21004 org-done-keywords)))
21005 ; TODO, not DONE
21006 (and org-export-mark-todo-in-toc
21007 (= level umax-toc)
21008 (org-search-todo-below
21009 line lines level))))
21010 (setq txt (org-html-expand-for-ascii txt))
21012 (if (and (memq org-export-with-tags '(not-in-toc nil))
21013 (string-match
21014 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
21015 txt))
21016 (setq txt (replace-match "" t t txt)))
21017 (if (string-match quote-re0 txt)
21018 (setq txt (replace-match "" t t txt)))
21020 (if org-export-with-section-numbers
21021 (setq txt (concat (org-section-number level)
21022 " " txt)))
21023 (if (<= level umax-toc)
21024 (progn
21025 (push
21026 (concat
21027 (make-string
21028 (* (max 0 (- level org-min-level)) 4) ?\ )
21029 (format (if todo "%s (*)\n" "%s\n") txt))
21030 thetoc)
21031 (setq org-last-level level))
21032 ))))
21033 lines)
21034 (setq thetoc (if have-headings (nreverse thetoc) nil))))
21036 (org-init-section-numbers)
21037 (while (setq line (pop lines))
21038 ;; Remove the quoted HTML tags.
21039 (setq line (org-html-expand-for-ascii line))
21040 ;; Remove targets
21041 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
21042 (setq line (replace-match "" t t line)))
21043 ;; Replace internal links
21044 (while (string-match org-bracket-link-regexp line)
21045 (setq line (replace-match
21046 (if (match-end 3) "[\\3]" "[\\1]")
21047 t nil line)))
21048 (when custom-times
21049 (setq line (org-translate-time line)))
21050 (cond
21051 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
21052 ;; a Headline
21053 (setq first-heading-pos (or first-heading-pos (point)))
21054 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
21055 txt (match-string 2 line))
21056 (org-ascii-level-start level txt umax lines))
21058 ((and org-export-with-tables
21059 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
21060 (if (not table-open)
21061 ;; New table starts
21062 (setq table-open t table-buffer nil))
21063 ;; Accumulate lines
21064 (setq table-buffer (cons line table-buffer))
21065 (when (or (not lines)
21066 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
21067 (car lines))))
21068 (setq table-open nil
21069 table-buffer (nreverse table-buffer))
21070 (insert (mapconcat
21071 (lambda (x)
21072 (org-fix-indentation x org-ascii-current-indentation))
21073 (org-format-table-ascii table-buffer)
21074 "\n") "\n")))
21076 (setq line (org-fix-indentation line org-ascii-current-indentation))
21077 (if (and org-export-with-fixed-width
21078 (string-match "^\\([ \t]*\\)\\(:\\)" line))
21079 (setq line (replace-match "\\1" nil nil line)))
21080 (insert line "\n"))))
21082 (normal-mode)
21084 ;; insert the table of contents
21085 (when thetoc
21086 (goto-char (point-min))
21087 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
21088 (progn
21089 (goto-char (match-beginning 0))
21090 (replace-match ""))
21091 (goto-char first-heading-pos))
21092 (mapc 'insert thetoc)
21093 (or (looking-at "[ \t]*\n[ \t]*\n")
21094 (insert "\n\n")))
21096 (save-buffer)
21097 ;; remove display and invisible chars
21098 (let (beg end)
21099 (goto-char (point-min))
21100 (while (setq beg (next-single-property-change (point) 'display))
21101 (setq end (next-single-property-change beg 'display))
21102 (delete-region beg end)
21103 (goto-char beg)
21104 (insert "=>"))
21105 (goto-char (point-min))
21106 (while (setq beg (next-single-property-change (point) 'org-cwidth))
21107 (setq end (next-single-property-change beg 'org-cwidth))
21108 (delete-region beg end)
21109 (goto-char beg)))
21110 (goto-char (point-min))))
21112 (defun org-search-todo-below (line lines level)
21113 "Search the subtree below LINE for any TODO entries."
21114 (let ((rest (cdr (memq line lines)))
21115 (re org-todo-line-regexp)
21116 line lv todo)
21117 (catch 'exit
21118 (while (setq line (pop rest))
21119 (if (string-match re line)
21120 (progn
21121 (setq lv (- (match-end 1) (match-beginning 1))
21122 todo (and (match-beginning 2)
21123 (not (member (match-string 2 line)
21124 org-done-keywords))))
21125 ; TODO, not DONE
21126 (if (<= lv level) (throw 'exit nil))
21127 (if todo (throw 'exit t))))))))
21129 (defun org-html-expand-for-ascii (line)
21130 "Handle quoted HTML for ASCII export."
21131 (if org-export-html-expand
21132 (while (string-match "@<[^<>\n]*>" line)
21133 ;; We just remove the tags for now.
21134 (setq line (replace-match "" nil nil line))))
21135 line)
21137 (defun org-insert-centered (s &optional underline)
21138 "Insert the string S centered and underline it with character UNDERLINE."
21139 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
21140 (insert (make-string ind ?\ ) s "\n")
21141 (if underline
21142 (insert (make-string ind ?\ )
21143 (make-string (string-width s) underline)
21144 "\n"))))
21146 (defun org-ascii-level-start (level title umax &optional lines)
21147 "Insert a new level in ASCII export."
21148 (let (char (n (- level umax 1)) (ind 0))
21149 (if (> level umax)
21150 (progn
21151 (insert (make-string (* 2 n) ?\ )
21152 (char-to-string (nth (% n (length org-export-ascii-bullets))
21153 org-export-ascii-bullets))
21154 " " title "\n")
21155 ;; find the indentation of the next non-empty line
21156 (catch 'stop
21157 (while lines
21158 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
21159 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
21160 (throw 'stop (setq ind (org-get-indentation (car lines)))))
21161 (pop lines)))
21162 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
21163 (if (or (not (equal (char-before) ?\n))
21164 (not (equal (char-before (1- (point))) ?\n)))
21165 (insert "\n"))
21166 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
21167 (unless org-export-with-tags
21168 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
21169 (setq title (replace-match "" t t title))))
21170 (if org-export-with-section-numbers
21171 (setq title (concat (org-section-number level) " " title)))
21172 (insert title "\n" (make-string (string-width title) char) "\n")
21173 (setq org-ascii-current-indentation '(0 . 0)))))
21175 (defun org-export-visible (type arg)
21176 "Create a copy of the visible part of the current buffer, and export it.
21177 The copy is created in a temporary buffer and removed after use.
21178 TYPE is the final key (as a string) that also select the export command in
21179 the `C-c C-e' export dispatcher.
21180 As a special case, if the you type SPC at the prompt, the temporary
21181 org-mode file will not be removed but presented to you so that you can
21182 continue to use it. The prefix arg ARG is passed through to the exporting
21183 command."
21184 (interactive
21185 (list (progn
21186 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
21187 (read-char-exclusive))
21188 current-prefix-arg))
21189 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
21190 (error "Invalid export key"))
21191 (let* ((binding (cdr (assoc type
21192 '((?a . org-export-as-ascii)
21193 (?\C-a . org-export-as-ascii)
21194 (?b . org-export-as-html-and-open)
21195 (?\C-b . org-export-as-html-and-open)
21196 (?h . org-export-as-html)
21197 (?H . org-export-as-html-to-buffer)
21198 (?R . org-export-region-as-html)
21199 (?x . org-export-as-xoxo)))))
21200 (keepp (equal type ?\ ))
21201 (file buffer-file-name)
21202 (buffer (get-buffer-create "*Org Export Visible*"))
21203 s e)
21204 (with-current-buffer buffer (erase-buffer))
21205 (save-excursion
21206 (setq s (goto-char (point-min)))
21207 (while (not (= (point) (point-max)))
21208 (goto-char (org-find-invisible))
21209 (append-to-buffer buffer s (point))
21210 (setq s (goto-char (org-find-visible))))
21211 (goto-char (point-min))
21212 (unless keepp
21213 ;; Copy all comment lines to the end, to make sure #+ settings are
21214 ;; still available for the second export step. Kind of a hack, but
21215 ;; does do the trick.
21216 (if (looking-at "#[^\r\n]*")
21217 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
21218 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
21219 (append-to-buffer buffer (1+ (match-beginning 0))
21220 (min (point-max) (1+ (match-end 0))))))
21221 (set-buffer buffer)
21222 (let ((buffer-file-name file)
21223 (org-inhibit-startup t))
21224 (org-mode)
21225 (show-all)
21226 (unless keepp (funcall binding arg))))
21227 (if (not keepp)
21228 (kill-buffer buffer)
21229 (switch-to-buffer-other-window buffer)
21230 (goto-char (point-min)))))
21232 (defun org-find-visible ()
21233 (let ((s (point)))
21234 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
21235 (get-char-property s 'invisible)))
21237 (defun org-find-invisible ()
21238 (let ((s (point)))
21239 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
21240 (not (get-char-property s 'invisible))))
21243 ;;; HTML export
21245 (defun org-get-current-options ()
21246 "Return a string with current options as keyword options.
21247 Does include HTML export options as well as TODO and CATEGORY stuff."
21248 (format
21249 "#+TITLE: %s
21250 #+AUTHOR: %s
21251 #+EMAIL: %s
21252 #+LANGUAGE: %s
21253 #+TEXT: Some descriptive text to be emitted. Several lines OK.
21254 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s p:%s
21255 #+CATEGORY: %s
21256 #+SEQ_TODO: %s
21257 #+TYP_TODO: %s
21258 #+PRIORITIES: %c %c %c
21259 #+STARTUP: %s %s %s %s %s
21260 #+TAGS: %s
21261 #+ARCHIVE: %s
21262 #+LINK: %s
21264 (buffer-name) (user-full-name) user-mail-address org-export-default-language
21265 org-export-headline-levels
21266 org-export-with-section-numbers
21267 org-export-with-toc
21268 org-export-preserve-breaks
21269 org-export-html-expand
21270 org-export-with-fixed-width
21271 org-export-with-tables
21272 org-export-with-sub-superscripts
21273 org-export-with-footnotes
21274 org-export-with-emphasize
21275 org-export-with-TeX-macros
21276 org-export-with-LaTeX-fragments
21277 org-export-skip-text-before-1st-heading
21278 org-export-with-property-drawer
21279 (file-name-nondirectory buffer-file-name)
21280 "TODO FEEDBACK VERIFY DONE"
21281 "Me Jason Marie DONE"
21282 org-highest-priority org-lowest-priority org-default-priority
21283 (cdr (assoc org-startup-folded
21284 '((nil . "showall") (t . "overview") (content . "content"))))
21285 (if org-odd-levels-only "odd" "oddeven")
21286 (if org-hide-leading-stars "hidestars" "showstars")
21287 (if org-startup-align-all-tables "align" "noalign")
21288 (cond ((eq t org-log-done) "logdone")
21289 ((not org-log-done) "nologging")
21290 ((listp org-log-done)
21291 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
21292 org-log-done " ")))
21293 (or (mapconcat (lambda (x)
21294 (cond
21295 ((equal '(:startgroup) x) "{")
21296 ((equal '(:endgroup) x) "}")
21297 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
21298 (t (car x))))
21299 (or org-tag-alist (org-get-buffer-tags)) " ") "")
21300 org-archive-location
21301 "org file:~/org/%s.org"
21304 (defun org-insert-export-options-template ()
21305 "Insert into the buffer a template with information for exporting."
21306 (interactive)
21307 (if (not (bolp)) (newline))
21308 (let ((s (org-get-current-options)))
21309 (and (string-match "#\\+CATEGORY" s)
21310 (setq s (substring s 0 (match-beginning 0))))
21311 (insert s)))
21313 (defun org-toggle-fixed-width-section (arg)
21314 "Toggle the fixed-width export.
21315 If there is no active region, the QUOTE keyword at the current headline is
21316 inserted or removed. When present, it causes the text between this headline
21317 and the next to be exported as fixed-width text, and unmodified.
21318 If there is an active region, this command adds or removes a colon as the
21319 first character of this line. If the first character of a line is a colon,
21320 this line is also exported in fixed-width font."
21321 (interactive "P")
21322 (let* ((cc 0)
21323 (regionp (org-region-active-p))
21324 (beg (if regionp (region-beginning) (point)))
21325 (end (if regionp (region-end)))
21326 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21327 (re "[ \t]*\\(:\\)")
21328 off)
21329 (if regionp
21330 (save-excursion
21331 (goto-char beg)
21332 (setq cc (current-column))
21333 (beginning-of-line 1)
21334 (setq off (looking-at re))
21335 (while (> nlines 0)
21336 (setq nlines (1- nlines))
21337 (beginning-of-line 1)
21338 (cond
21339 (arg
21340 (move-to-column cc t)
21341 (insert ":\n")
21342 (forward-line -1))
21343 ((and off (looking-at re))
21344 (replace-match "" t t nil 1))
21345 ((not off) (move-to-column cc t) (insert ":")))
21346 (forward-line 1)))
21347 (save-excursion
21348 (org-back-to-heading)
21349 (if (looking-at (concat outline-regexp
21350 "\\( *\\<" org-quote-string "\\>\\)"))
21351 (replace-match "" t t nil 1)
21352 (if (looking-at outline-regexp)
21353 (progn
21354 (goto-char (match-end 0))
21355 (insert org-quote-string " "))))))))
21357 (defun org-export-as-html-and-open (arg)
21358 "Export the outline as HTML and immediately open it with a browser.
21359 If there is an active region, export only the region.
21360 The prefix ARG specifies how many levels of the outline should become
21361 headlines. The default is 3. Lower levels will become bulleted lists."
21362 (interactive "P")
21363 (org-export-as-html arg 'hidden)
21364 (org-open-file buffer-file-name))
21366 (defun org-export-as-html-batch ()
21367 "Call `org-export-as-html', may be used in batch processing as
21368 emacs --batch
21369 --load=$HOME/lib/emacs/org.el
21370 --eval \"(setq org-export-headline-levels 2)\"
21371 --visit=MyFile --funcall org-export-as-html-batch"
21372 (org-export-as-html org-export-headline-levels 'hidden))
21374 (defun org-export-as-html-to-buffer (arg)
21375 "Call `org-exort-as-html` with output to a temporary buffer.
21376 No file is created. The prefix ARG is passed through to `org-export-as-html'."
21377 (interactive "P")
21378 (org-export-as-html arg nil nil "*Org HTML Export*")
21379 (switch-to-buffer-other-window "*Org HTML Export*"))
21381 (defun org-replace-region-by-html (beg end)
21382 "Assume the current region has org-mode syntax, and convert it to HTML.
21383 This can be used in any buffer. For example, you could write an
21384 itemized list in org-mode syntax in an HTML buffer and then use this
21385 command to convert it."
21386 (interactive "r")
21387 (let (reg html buf)
21388 (save-window-excursion
21389 (if (org-mode-p)
21390 (setq html (org-export-region-as-html
21391 beg end t 'string))
21392 (setq reg (buffer-substring beg end)
21393 buf (get-buffer-create "*Org tmp*"))
21394 (with-current-buffer buf
21395 (erase-buffer)
21396 (insert reg)
21397 (org-mode)
21398 (setq html (org-export-region-as-html
21399 (point-min) (point-max) t 'string)))
21400 (kill-buffer buf)))
21401 (delete-region beg end)
21402 (insert html)))
21404 (defun org-export-region-as-html (beg end &optional body-only buffer)
21405 "Convert region from BEG to END in org-mode buffer to HTML.
21406 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
21407 contents, and only produce the region of converted text, useful for
21408 cut-and-paste operations.
21409 If BUFFER is a buffer or a string, use/create that buffer as a target
21410 of the converted HTML. If BUFFER is the symbol `string', return the
21411 produced HTML as a string and leave not buffer behind. For example,
21412 a Lisp program could call this function in the following way:
21414 (setq html (org-export-region-as-html beg end t 'string))
21416 When called interactively, the output buffer is selected, and shown
21417 in a window. A non-interactive call will only retunr the buffer."
21418 (interactive "r\nP")
21419 (when (interactive-p)
21420 (setq buffer "*Org HTML Export*"))
21421 (let ((transient-mark-mode t) (zmacs-regions t)
21422 rtn)
21423 (goto-char end)
21424 (set-mark (point)) ;; to activate the region
21425 (goto-char beg)
21426 (setq rtn (org-export-as-html
21427 nil nil nil
21428 buffer body-only))
21429 (if (fboundp 'deactivate-mark) (deactivate-mark))
21430 (if (and (interactive-p) (bufferp rtn))
21431 (switch-to-buffer-other-window rtn)
21432 rtn)))
21434 (defun org-export-as-html (arg &optional hidden ext-plist
21435 to-buffer body-only)
21436 "Export the outline as a pretty HTML file.
21437 If there is an active region, export only the region. The prefix
21438 ARG specifies how many levels of the outline should become
21439 headlines. The default is 3. Lower levels will become bulleted
21440 lists. When HIDDEN is non-nil, don't display the HTML buffer.
21441 EXT-PLIST is a property list with external parameters overriding
21442 org-mode's default settings, but still inferior to file-local
21443 settings. When TO-BUFFER is non-nil, create a buffer with that
21444 name and export to that buffer. If TO-BUFFER is the symbol `string',
21445 don't leave any buffer behind but just return the resulting HTML as
21446 a string. When BODY-ONLY is set, don't produce the file header and footer,
21447 simply return the content of <body>...</body>, without even
21448 the body tags themselves."
21449 (interactive "P")
21451 ;; Make sure we have a file name when we need it.
21452 (when (and (not (or to-buffer body-only))
21453 (not buffer-file-name))
21454 (if (buffer-base-buffer)
21455 (org-set-local 'buffer-file-name
21456 (with-current-buffer (buffer-base-buffer)
21457 buffer-file-name))
21458 (error "Need a file name to be able to export.")))
21460 (message "Exporting...")
21461 (setq-default org-todo-line-regexp org-todo-line-regexp)
21462 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
21463 (setq-default org-done-keywords org-done-keywords)
21464 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
21465 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
21466 ext-plist
21467 (org-infile-export-plist)))
21469 (style (plist-get opt-plist :style))
21470 (link-validate (plist-get opt-plist :link-validation-function))
21471 valid thetoc have-headings first-heading-pos
21472 (odd org-odd-levels-only)
21473 (region-p (org-region-active-p))
21474 (subtree-p
21475 (when region-p
21476 (save-excursion
21477 (goto-char (region-beginning))
21478 (and (org-at-heading-p)
21479 (>= (org-end-of-subtree t t) (region-end))))))
21480 ;; The following two are dynamically scoped into other
21481 ;; routines below.
21482 (org-current-export-dir (org-export-directory :html opt-plist))
21483 (org-current-export-file buffer-file-name)
21484 (level 0) (line "") (origline "") txt todo
21485 (umax nil)
21486 (umax-toc nil)
21487 (filename (if to-buffer nil
21488 (concat (file-name-as-directory
21489 (org-export-directory :html opt-plist))
21490 (file-name-sans-extension
21491 (or (and subtree-p
21492 (org-entry-get (region-beginning)
21493 "EXPORT_FILE_NAME" t))
21494 (file-name-nondirectory buffer-file-name)))
21495 ".html")))
21496 (current-dir (if buffer-file-name
21497 (file-name-directory buffer-file-name)
21498 default-directory))
21499 (buffer (if to-buffer
21500 (cond
21501 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
21502 (t (get-buffer-create to-buffer)))
21503 (find-file-noselect filename)))
21504 (org-levels-open (make-vector org-level-max nil))
21505 (date (format-time-string "%Y/%m/%d" (current-time)))
21506 (time (format-time-string "%X" (org-current-time)))
21507 (author (plist-get opt-plist :author))
21508 (title (or (and subtree-p (org-export-get-title-from-subtree))
21509 (plist-get opt-plist :title)
21510 (and (not
21511 (plist-get opt-plist :skip-before-1st-heading))
21512 (org-export-grab-title-from-buffer))
21513 (and buffer-file-name
21514 (file-name-sans-extension
21515 (file-name-nondirectory buffer-file-name)))
21516 "UNTITLED"))
21517 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
21518 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
21519 (inquote nil)
21520 (infixed nil)
21521 (in-local-list nil)
21522 (local-list-num nil)
21523 (local-list-indent nil)
21524 (llt org-plain-list-ordered-item-terminator)
21525 (email (plist-get opt-plist :email))
21526 (language (plist-get opt-plist :language))
21527 (lang-words nil)
21528 (target-alist nil) tg
21529 (head-count 0) cnt
21530 (start 0)
21531 (coding-system (and (boundp 'buffer-file-coding-system)
21532 buffer-file-coding-system))
21533 (coding-system-for-write (or org-export-html-coding-system
21534 coding-system))
21535 (save-buffer-coding-system (or org-export-html-coding-system
21536 coding-system))
21537 (charset (and coding-system-for-write
21538 (fboundp 'coding-system-get)
21539 (coding-system-get coding-system-for-write
21540 'mime-charset)))
21541 (region
21542 (buffer-substring
21543 (if region-p (region-beginning) (point-min))
21544 (if region-p (region-end) (point-max))))
21545 (lines
21546 (org-split-string
21547 (org-cleaned-string-for-export
21548 region
21549 :emph-multiline t
21550 :for-html t
21551 :skip-before-1st-heading
21552 (plist-get opt-plist :skip-before-1st-heading)
21553 :archived-trees
21554 (plist-get opt-plist :archived-trees)
21555 :add-text
21556 (plist-get opt-plist :text)
21557 :LaTeX-fragments
21558 (plist-get opt-plist :LaTeX-fragments))
21559 "[\r\n]"))
21560 table-open type
21561 table-buffer table-orig-buffer
21562 ind start-is-num starter didclose
21563 rpl path desc descp desc1 desc2 link
21566 (let ((inhibit-read-only t))
21567 (org-unmodified
21568 (remove-text-properties (point-min) (point-max)
21569 '(:org-license-to-kill t))))
21571 (message "Exporting...")
21573 (setq org-min-level (org-get-min-level lines))
21574 (setq org-last-level org-min-level)
21575 (org-init-section-numbers)
21577 ;; Get the language-dependent settings
21578 (setq lang-words (or (assoc language org-export-language-setup)
21579 (assoc "en" org-export-language-setup)))
21581 ;; Switch to the output buffer
21582 (set-buffer buffer)
21583 (erase-buffer)
21584 (fundamental-mode)
21586 (and (fboundp 'set-buffer-file-coding-system)
21587 (set-buffer-file-coding-system coding-system-for-write))
21589 (let ((case-fold-search nil)
21590 (org-odd-levels-only odd))
21591 ;; create local variables for all options, to make sure all called
21592 ;; functions get the correct information
21593 (mapcar (lambda (x)
21594 (set (make-local-variable (cdr x))
21595 (plist-get opt-plist (car x))))
21596 org-export-plist-vars)
21597 (setq umax (if arg (prefix-numeric-value arg)
21598 org-export-headline-levels))
21599 (setq umax-toc (if (integerp org-export-with-toc)
21600 (min org-export-with-toc umax)
21601 umax))
21602 (unless body-only
21603 ;; File header
21604 (insert (format
21605 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
21606 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
21607 <html xmlns=\"http://www.w3.org/1999/xhtml\"
21608 lang=\"%s\" xml:lang=\"%s\">
21609 <head>
21610 <title>%s</title>
21611 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
21612 <meta name=\"generator\" content=\"Org-mode\"/>
21613 <meta name=\"generated\" content=\"%s %s\"/>
21614 <meta name=\"author\" content=\"%s\"/>
21616 </head><body>
21618 language language (org-html-expand title)
21619 (or charset "iso-8859-1") date time author style))
21621 (insert (or (plist-get opt-plist :preamble) ""))
21623 (when (plist-get opt-plist :auto-preamble)
21624 (if title (insert (format org-export-html-title-format
21625 (org-html-expand title))))))
21627 (if (and org-export-with-toc (not body-only))
21628 (progn
21629 (push (format "<h%d>%s</h%d>\n"
21630 org-export-html-toplevel-hlevel
21631 (nth 3 lang-words)
21632 org-export-html-toplevel-hlevel)
21633 thetoc)
21634 (push "<ul>\n<li>" thetoc)
21635 (setq lines
21636 (mapcar '(lambda (line)
21637 (if (string-match org-todo-line-regexp line)
21638 ;; This is a headline
21639 (progn
21640 (setq have-headings t)
21641 (setq level (- (match-end 1) (match-beginning 1))
21642 level (org-tr-level level)
21643 txt (save-match-data
21644 (org-html-expand
21645 (org-export-cleanup-toc-line
21646 (match-string 3 line))))
21647 todo
21648 (or (and org-export-mark-todo-in-toc
21649 (match-beginning 2)
21650 (not (member (match-string 2 line)
21651 org-done-keywords)))
21652 ; TODO, not DONE
21653 (and org-export-mark-todo-in-toc
21654 (= level umax-toc)
21655 (org-search-todo-below
21656 line lines level))))
21657 (if (and (memq org-export-with-tags '(not-in-toc nil))
21658 (string-match
21659 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
21660 txt))
21661 (setq txt (replace-match "" t t txt)))
21662 (if (string-match quote-re0 txt)
21663 (setq txt (replace-match "" t t txt)))
21664 (if org-export-with-section-numbers
21665 (setq txt (concat (org-section-number level)
21666 " " txt)))
21667 (if (<= level (max umax umax-toc))
21668 (setq head-count (+ head-count 1)))
21669 (if (<= level umax-toc)
21670 (progn
21671 (if (> level org-last-level)
21672 (progn
21673 (setq cnt (- level org-last-level))
21674 (while (>= (setq cnt (1- cnt)) 0)
21675 (push "\n<ul>\n<li>" thetoc))
21676 (push "\n" thetoc)))
21677 (if (< level org-last-level)
21678 (progn
21679 (setq cnt (- org-last-level level))
21680 (while (>= (setq cnt (1- cnt)) 0)
21681 (push "</li>\n</ul>" thetoc))
21682 (push "\n" thetoc)))
21683 ;; Check for targets
21684 (while (string-match org-target-regexp line)
21685 (setq tg (match-string 1 line)
21686 line (replace-match
21687 (concat "@<span class=\"target\">" tg "@</span> ")
21688 t t line))
21689 (push (cons (org-solidify-link-text tg)
21690 (format "sec-%d" head-count))
21691 target-alist))
21692 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
21693 (setq txt (replace-match "" t t txt)))
21694 (push
21695 (format
21696 (if todo
21697 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
21698 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
21699 head-count txt) thetoc)
21701 (setq org-last-level level))
21703 line)
21704 lines))
21705 (while (> org-last-level (1- org-min-level))
21706 (setq org-last-level (1- org-last-level))
21707 (push "</li>\n</ul>\n" thetoc))
21708 (setq thetoc (if have-headings (nreverse thetoc) nil))))
21710 (setq head-count 0)
21711 (org-init-section-numbers)
21713 (while (setq line (pop lines) origline line)
21714 (catch 'nextline
21716 ;; end of quote section?
21717 (when (and inquote (string-match "^\\*+ " line))
21718 (insert "</pre>\n")
21719 (setq inquote nil))
21720 ;; inside a quote section?
21721 (when inquote
21722 (insert (org-html-protect line) "\n")
21723 (throw 'nextline nil))
21725 ;; verbatim lines
21726 (when (and org-export-with-fixed-width
21727 (string-match "^[ \t]*:\\(.*\\)" line))
21728 (when (not infixed)
21729 (setq infixed t)
21730 (insert "<pre>\n"))
21731 (insert (org-html-protect (match-string 1 line)) "\n")
21732 (when (and lines
21733 (not (string-match "^[ \t]*\\(:.*\\)"
21734 (car lines))))
21735 (setq infixed nil)
21736 (insert "</pre>\n"))
21737 (throw 'nextline nil))
21739 ;; Protected HTML
21740 (when (get-text-property 0 'org-protected line)
21741 (let (par)
21742 (when (re-search-backward
21743 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
21744 (setq par (match-string 1))
21745 (replace-match "\\2\n"))
21746 (insert line "\n")
21747 (while (and lines
21748 (get-text-property 0 'org-protected (car lines)))
21749 (insert (pop lines) "\n"))
21750 (and par (insert "<p>\n")))
21751 (throw 'nextline nil))
21753 ;; Horizontal line
21754 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
21755 (insert "\n<hr/>\n")
21756 (throw 'nextline nil))
21758 ;; make targets to anchors
21759 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
21760 (cond
21761 ((match-end 2)
21762 (setq line (replace-match
21763 (concat "@<a name=\""
21764 (org-solidify-link-text (match-string 1 line))
21765 "\">\\nbsp@</a>")
21766 t t line)))
21767 ((and org-export-with-toc (equal (string-to-char line) ?*))
21768 (setq line (replace-match
21769 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
21770 ; (concat "@<i>" (match-string 1 line) "@</i> ")
21771 t t line)))
21773 (setq line (replace-match
21774 (concat "@<a name=\""
21775 (org-solidify-link-text (match-string 1 line))
21776 "\" class=\"target\">" (match-string 1 line) "@</a> ")
21777 t t line)))))
21779 (setq line (org-html-handle-time-stamps line))
21781 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
21782 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
21783 ;; Also handle sub_superscripts and checkboxes
21784 (setq line (org-html-expand line))
21786 ;; Format the links
21787 (setq start 0)
21788 (while (string-match org-bracket-link-analytic-regexp line start)
21789 (setq start (match-beginning 0))
21790 (setq type (if (match-end 2) (match-string 2 line) "internal"))
21791 (setq path (match-string 3 line))
21792 (setq desc1 (if (match-end 5) (match-string 5 line))
21793 desc2 (if (match-end 2) (concat type ":" path) path)
21794 descp (and desc1 (not (equal desc1 desc2)))
21795 desc (or desc1 desc2))
21796 ;; Make an image out of the description if that is so wanted
21797 (when (and descp (org-file-image-p desc))
21798 (save-match-data
21799 (if (string-match "^file:" desc)
21800 (setq desc (substring desc (match-end 0)))))
21801 (setq desc (concat "<img src=\"" desc "\"/>")))
21802 ;; FIXME: do we need to unescape here somewhere?
21803 (cond
21804 ((equal type "internal")
21805 (setq rpl
21806 (concat
21807 "<a href=\"#"
21808 (org-solidify-link-text
21809 (save-match-data (org-link-unescape path)) target-alist)
21810 "\">" desc "</a>")))
21811 ((member type '("http" "https")) ; FIXME: need to test this.
21812 ;; standard URL, just check if we need to inline an image
21813 (if (and (or (eq t org-export-html-inline-images)
21814 (and org-export-html-inline-images (not descp)))
21815 (org-file-image-p path))
21816 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
21817 (setq link (concat type ":" path))
21818 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
21819 ((member type '("ftp" "mailto" "news"))
21820 ;; standard URL
21821 (setq link (concat type ":" path))
21822 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
21823 ((string= type "file")
21824 ;; FILE link
21825 (let* ((filename path)
21826 (abs-p (file-name-absolute-p filename))
21827 thefile file-is-image-p search)
21828 (save-match-data
21829 (if (string-match "::\\(.*\\)" filename)
21830 (setq search (match-string 1 filename)
21831 filename (replace-match "" t nil filename)))
21832 (setq valid
21833 (if (functionp link-validate)
21834 (funcall link-validate filename current-dir)
21836 (setq file-is-image-p (org-file-image-p filename))
21837 (setq thefile (if abs-p (expand-file-name filename) filename))
21838 (when (and org-export-html-link-org-files-as-html
21839 (string-match "\\.org$" thefile))
21840 (setq thefile (concat (substring thefile 0
21841 (match-beginning 0))
21842 ".html"))
21843 (if (and search
21844 ;; make sure this is can be used as target search
21845 (not (string-match "^[0-9]*$" search))
21846 (not (string-match "^\\*" search))
21847 (not (string-match "^/.*/$" search)))
21848 (setq thefile (concat thefile "#"
21849 (org-solidify-link-text
21850 (org-link-unescape search)))))
21851 (when (string-match "^file:" desc)
21852 (setq desc (replace-match "" t t desc))
21853 (if (string-match "\\.org$" desc)
21854 (setq desc (replace-match "" t t desc))))))
21855 (setq rpl (if (and file-is-image-p
21856 (or (eq t org-export-html-inline-images)
21857 (and org-export-html-inline-images
21858 (not descp))))
21859 (concat "<img src=\"" thefile "\"/>")
21860 (concat "<a href=\"" thefile "\">" desc "</a>")))
21861 (if (not valid) (setq rpl desc))))
21862 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
21863 (setq rpl (concat "<i>&lt;" type ":"
21864 (save-match-data (org-link-unescape path))
21865 "&gt;</i>"))))
21866 (setq line (replace-match rpl t t line)
21867 start (+ start (length rpl))))
21869 ;; TODO items
21870 (if (and (string-match org-todo-line-regexp line)
21871 (match-beginning 2))
21873 (setq line
21874 (concat (substring line 0 (match-beginning 2))
21875 "<span class=\""
21876 (if (member (match-string 2 line)
21877 org-done-keywords)
21878 "done" "todo")
21879 "\">" (match-string 2 line)
21880 "</span>" (substring line (match-end 2)))))
21882 ;; Does this contain a reference to a footnote?
21883 (when org-export-with-footnotes
21884 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line)
21885 (let ((n (match-string 2 line)))
21886 (setq line
21887 (replace-match
21888 (format
21889 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
21890 (match-string 1 line) n n n)
21891 t t line)))))
21893 (cond
21894 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
21895 ;; This is a headline
21896 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
21897 txt (match-string 2 line))
21898 (if (string-match quote-re0 txt)
21899 (setq txt (replace-match "" t t txt)))
21900 (if (<= level (max umax umax-toc))
21901 (setq head-count (+ head-count 1)))
21902 (when in-local-list
21903 ;; Close any local lists before inserting a new header line
21904 (while local-list-num
21905 (org-close-li)
21906 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
21907 (pop local-list-num))
21908 (setq local-list-indent nil
21909 in-local-list nil))
21910 (setq first-heading-pos (or first-heading-pos (point)))
21911 (org-html-level-start level txt umax
21912 (and org-export-with-toc (<= level umax))
21913 head-count)
21914 ;; QUOTES
21915 (when (string-match quote-re line)
21916 (insert "<pre>")
21917 (setq inquote t)))
21919 ((and org-export-with-tables
21920 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
21921 (if (not table-open)
21922 ;; New table starts
21923 (setq table-open t table-buffer nil table-orig-buffer nil))
21924 ;; Accumulate lines
21925 (setq table-buffer (cons line table-buffer)
21926 table-orig-buffer (cons origline table-orig-buffer))
21927 (when (or (not lines)
21928 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
21929 (car lines))))
21930 (setq table-open nil
21931 table-buffer (nreverse table-buffer)
21932 table-orig-buffer (nreverse table-orig-buffer))
21933 (org-close-par-maybe)
21934 (insert (org-format-table-html table-buffer table-orig-buffer))))
21936 ;; Normal lines
21937 (when (string-match
21938 (cond
21939 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
21940 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
21941 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
21942 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
21943 line)
21944 (setq ind (org-get-string-indentation line)
21945 start-is-num (match-beginning 4)
21946 starter (if (match-beginning 2)
21947 (substring (match-string 2 line) 0 -1))
21948 line (substring line (match-beginning 5)))
21949 (unless (string-match "[^ \t]" line)
21950 ;; empty line. Pretend indentation is large.
21951 (setq ind (if org-empty-line-terminates-plain-lists
21953 (1+ (or (car local-list-indent) 1)))))
21954 (setq didclose nil)
21955 (while (and in-local-list
21956 (or (and (= ind (car local-list-indent))
21957 (not starter))
21958 (< ind (car local-list-indent))))
21959 (setq didclose t)
21960 (org-close-li)
21961 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
21962 (pop local-list-num) (pop local-list-indent)
21963 (setq in-local-list local-list-indent))
21964 (cond
21965 ((and starter
21966 (or (not in-local-list)
21967 (> ind (car local-list-indent))))
21968 ;; Start new (level of) list
21969 (org-close-par-maybe)
21970 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
21971 (push start-is-num local-list-num)
21972 (push ind local-list-indent)
21973 (setq in-local-list t))
21974 (starter
21975 ;; continue current list
21976 (org-close-li)
21977 (insert "<li>\n"))
21978 (didclose
21979 ;; we did close a list, normal text follows: need <p>
21980 (org-open-par)))
21981 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
21982 (setq line
21983 (replace-match
21984 (if (equal (match-string 1 line) "X")
21985 "<b>[X]</b>"
21986 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
21987 t t line))))
21989 ;; Empty lines start a new paragraph. If hand-formatted lists
21990 ;; are not fully interpreted, lines starting with "-", "+", "*"
21991 ;; also start a new paragraph.
21992 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
21994 ;; Is this the start of a footnote?
21995 (when org-export-with-footnotes
21996 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
21997 (org-close-par-maybe)
21998 (let ((n (match-string 1 line)))
21999 (setq line (replace-match
22000 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
22002 ;; Check if the line break needs to be conserved
22003 (cond
22004 ((string-match "\\\\\\\\[ \t]*$" line)
22005 (setq line (replace-match "<br/>" t t line)))
22006 (org-export-preserve-breaks
22007 (setq line (concat line "<br/>"))))
22009 (insert line "\n")))))
22011 ;; Properly close all local lists and other lists
22012 (when inquote (insert "</pre>\n"))
22013 (when in-local-list
22014 ;; Close any local lists before inserting a new header line
22015 (while local-list-num
22016 (org-close-li)
22017 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
22018 (pop local-list-num))
22019 (setq local-list-indent nil
22020 in-local-list nil))
22021 (org-html-level-start 1 nil umax
22022 (and org-export-with-toc (<= level umax))
22023 head-count)
22025 (unless body-only
22026 (when (plist-get opt-plist :auto-postamble)
22027 (when (and org-export-author-info author)
22028 (insert "<p class=\"author\"> "
22029 (nth 1 lang-words) ": " author "\n")
22030 (when email
22031 (insert "<a href=\"mailto:" email "\">&lt;"
22032 email "&gt;</a>\n"))
22033 (insert "</p>\n"))
22034 (when (and date time org-export-time-stamp-file)
22035 (insert "<p class=\"date\"> "
22036 (nth 2 lang-words) ": "
22037 date " " time "</p>\n")))
22039 (if org-export-html-with-timestamp
22040 (insert org-export-html-html-helper-timestamp))
22041 (insert (or (plist-get opt-plist :postamble) ""))
22042 (insert "</body>\n</html>\n"))
22044 (normal-mode)
22045 (if (eq major-mode default-major-mode) (html-mode))
22047 ;; insert the table of contents
22048 (goto-char (point-min))
22049 (when thetoc
22050 (if (or (re-search-forward
22051 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
22052 (re-search-forward
22053 "\\[TABLE-OF-CONTENTS\\]" nil t))
22054 (progn
22055 (goto-char (match-beginning 0))
22056 (replace-match ""))
22057 (goto-char first-heading-pos)
22058 (when (looking-at "\\s-*</p>")
22059 (goto-char (match-end 0))
22060 (insert "\n")))
22061 (mapc 'insert thetoc))
22062 ;; remove empty paragraphs and lists
22063 (goto-char (point-min))
22064 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
22065 (replace-match ""))
22066 (goto-char (point-min))
22067 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
22068 (replace-match ""))
22069 (or to-buffer (save-buffer))
22070 (goto-char (point-min))
22071 (message "Exporting... done")
22072 (if (eq to-buffer 'string)
22073 (prog1 (buffer-substring (point-min) (point-max))
22074 (kill-buffer (current-buffer)))
22075 (current-buffer)))))
22077 (defvar org-table-colgroup-info nil) ;; FIXME: mode to a better place
22078 (defun org-format-table-ascii (lines)
22079 "Format a table for ascii export."
22080 (if (stringp lines)
22081 (setq lines (org-split-string lines "\n")))
22082 (if (not (string-match "^[ \t]*|" (car lines)))
22083 ;; Table made by table.el - test for spanning
22084 lines
22086 ;; A normal org table
22087 ;; Get rid of hlines at beginning and end
22088 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
22089 (setq lines (nreverse lines))
22090 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
22091 (setq lines (nreverse lines))
22092 (when org-export-table-remove-special-lines
22093 ;; Check if the table has a marking column. If yes remove the
22094 ;; column and the special lines
22095 (setq lines (org-table-clean-before-export lines)))
22096 ;; Get rid of the vertical lines except for grouping
22097 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
22098 rtn line vl1 start)
22099 (while (setq line (pop lines))
22100 (if (string-match org-table-hline-regexp line)
22101 (and (string-match "|\\(.*\\)|" line)
22102 (setq line (replace-match " \\1" t nil line)))
22103 (setq start 0 vl1 vl)
22104 (while (string-match "|" line start)
22105 (setq start (match-end 0))
22106 (or (pop vl1) (setq line (replace-match " " t t line)))))
22107 (push line rtn))
22108 (nreverse rtn))))
22110 (defun org-colgroup-info-to-vline-list (info)
22111 (let (vl new last)
22112 (while info
22113 (setq last new new (pop info))
22114 (if (or (memq last '(:end :startend))
22115 (memq new '(:start :startend)))
22116 (push t vl)
22117 (push nil vl)))
22118 (setq vl (cons nil (nreverse vl)))))
22121 (defun org-format-table-html (lines olines)
22122 "Find out which HTML converter to use and return the HTML code."
22123 (if (stringp lines)
22124 (setq lines (org-split-string lines "\n")))
22125 (if (string-match "^[ \t]*|" (car lines))
22126 ;; A normal org table
22127 (org-format-org-table-html lines)
22128 ;; Table made by table.el - test for spanning
22129 (let* ((hlines (delq nil (mapcar
22130 (lambda (x)
22131 (if (string-match "^[ \t]*\\+-" x) x
22132 nil))
22133 lines)))
22134 (first (car hlines))
22135 (ll (and (string-match "\\S-+" first)
22136 (match-string 0 first)))
22137 (re (concat "^[ \t]*" (regexp-quote ll)))
22138 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
22139 hlines))))
22140 (if (and (not spanning)
22141 (not org-export-prefer-native-exporter-for-tables))
22142 ;; We can use my own converter with HTML conversions
22143 (org-format-table-table-html lines)
22144 ;; Need to use the code generator in table.el, with the original text.
22145 (org-format-table-table-html-using-table-generate-source olines)))))
22147 (defun org-format-org-table-html (lines &optional splice)
22148 "Format a table into HTML."
22149 ;; Get rid of hlines at beginning and end
22150 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
22151 (setq lines (nreverse lines))
22152 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
22153 (setq lines (nreverse lines))
22154 (when org-export-table-remove-special-lines
22155 ;; Check if the table has a marking column. If yes remove the
22156 ;; column and the special lines
22157 (setq lines (org-table-clean-before-export lines)))
22159 (let ((head (and org-export-highlight-first-table-line
22160 (delq nil (mapcar
22161 (lambda (x) (string-match "^[ \t]*|-" x))
22162 (cdr lines)))))
22163 (nlines 0) fnum i
22164 tbopen line fields html gr colgropen)
22165 (if splice (setq head nil))
22166 (unless splice (push (if head "<thead>" "<tbody>") html))
22167 (setq tbopen t)
22168 (while (setq line (pop lines))
22169 (catch 'next-line
22170 (if (string-match "^[ \t]*|-" line)
22171 (progn
22172 (unless splice
22173 (push (if head "</thead>" "</tbody>") html)
22174 (if lines (push "<tbody>" html) (setq tbopen nil)))
22175 (setq head nil) ;; head ends here, first time around
22176 ;; ignore this line
22177 (throw 'next-line t)))
22178 ;; Break the line into fields
22179 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
22180 (unless fnum (setq fnum (make-vector (length fields) 0)))
22181 (setq nlines (1+ nlines) i -1)
22182 (push (concat "<tr>"
22183 (mapconcat
22184 (lambda (x)
22185 (setq i (1+ i))
22186 (if (and (< i nlines)
22187 (string-match org-table-number-regexp x))
22188 (incf (aref fnum i)))
22189 (if head
22190 (concat (car org-export-table-header-tags) x
22191 (cdr org-export-table-header-tags))
22192 (concat (car org-export-table-data-tags) x
22193 (cdr org-export-table-data-tags))))
22194 fields "")
22195 "</tr>")
22196 html)))
22197 (unless splice (if tbopen (push "</tbody>" html)))
22198 (unless splice (push "</table>\n" html))
22199 (setq html (nreverse html))
22200 (unless splice
22201 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
22202 (push (mapconcat
22203 (lambda (x)
22204 (setq gr (pop org-table-colgroup-info))
22205 (format "%s<COL align=\"%s\"></COL>%s"
22206 (if (memq gr '(:start :startend))
22207 (prog1
22208 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
22209 (setq colgropen t))
22211 (if (> (/ (float x) nlines) org-table-number-fraction)
22212 "right" "left")
22213 (if (memq gr '(:end :startend))
22214 (progn (setq colgropen nil) "</colgroup>")
22215 "")))
22216 fnum "")
22217 html)
22218 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
22219 (push org-export-html-table-tag html))
22220 (concat (mapconcat 'identity html "\n") "\n")))
22222 (defun org-table-clean-before-export (lines)
22223 "Check if the table has a marking column.
22224 If yes remove the column and the special lines."
22225 (setq org-table-colgroup-info nil)
22226 (if (memq nil
22227 (mapcar
22228 (lambda (x) (or (string-match "^[ \t]*|-" x)
22229 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
22230 lines))
22231 (progn
22232 (setq org-table-clean-did-remove-column nil)
22233 (delq nil
22234 (mapcar
22235 (lambda (x)
22236 (cond
22237 ((string-match "^[ \t]*| */ *|" x)
22238 (setq org-table-colgroup-info
22239 (mapcar (lambda (x)
22240 (cond ((member x '("<" "&lt;")) :start)
22241 ((member x '(">" "&gt;")) :end)
22242 ((member x '("<>" "&lt;&gt;")) :startend)
22243 (t nil)))
22244 (org-split-string x "[ \t]*|[ \t]*")))
22245 nil)
22246 (t x)))
22247 lines)))
22248 (setq org-table-clean-did-remove-column t)
22249 (delq nil
22250 (mapcar
22251 (lambda (x)
22252 (cond
22253 ((string-match "^[ \t]*| */ *|" x)
22254 (setq org-table-colgroup-info
22255 (mapcar (lambda (x)
22256 (cond ((member x '("<" "&lt;")) :start)
22257 ((member x '(">" "&gt;")) :end)
22258 ((member x '("<>" "&lt;&gt;")) :startend)
22259 (t nil)))
22260 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
22261 nil)
22262 ((string-match "^[ \t]*| *[!_^/] *|" x)
22263 nil) ; ignore this line
22264 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
22265 (string-match "^\\([ \t]*\\)|[^|]*|" x))
22266 ;; remove the first column
22267 (replace-match "\\1|" t nil x))
22268 (t (error "This should not happen"))))
22269 lines))))
22271 (defun org-format-table-table-html (lines)
22272 "Format a table generated by table.el into HTML.
22273 This conversion does *not* use `table-generate-source' from table.el.
22274 This has the advantage that Org-mode's HTML conversions can be used.
22275 But it has the disadvantage, that no cell- or row-spanning is allowed."
22276 (let (line field-buffer
22277 (head org-export-highlight-first-table-line)
22278 fields html empty)
22279 (setq html (concat org-export-html-table-tag "\n"))
22280 (while (setq line (pop lines))
22281 (setq empty "&nbsp;")
22282 (catch 'next-line
22283 (if (string-match "^[ \t]*\\+-" line)
22284 (progn
22285 (if field-buffer
22286 (progn
22287 (setq
22288 html
22289 (concat
22290 html
22291 "<tr>"
22292 (mapconcat
22293 (lambda (x)
22294 (if (equal x "") (setq x empty))
22295 (if head
22296 (concat (car org-export-table-header-tags) x
22297 (cdr org-export-table-header-tags))
22298 (concat (car org-export-table-data-tags) x
22299 (cdr org-export-table-data-tags))))
22300 field-buffer "\n")
22301 "</tr>\n"))
22302 (setq head nil)
22303 (setq field-buffer nil)))
22304 ;; Ignore this line
22305 (throw 'next-line t)))
22306 ;; Break the line into fields and store the fields
22307 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
22308 (if field-buffer
22309 (setq field-buffer (mapcar
22310 (lambda (x)
22311 (concat x "<br/>" (pop fields)))
22312 field-buffer))
22313 (setq field-buffer fields))))
22314 (setq html (concat html "</table>\n"))
22315 html))
22317 (defun org-format-table-table-html-using-table-generate-source (lines)
22318 "Format a table into html, using `table-generate-source' from table.el.
22319 This has the advantage that cell- or row-spanning is allowed.
22320 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
22321 (require 'table)
22322 (with-current-buffer (get-buffer-create " org-tmp1 ")
22323 (erase-buffer)
22324 (insert (mapconcat 'identity lines "\n"))
22325 (goto-char (point-min))
22326 (if (not (re-search-forward "|[^+]" nil t))
22327 (error "Error processing table"))
22328 (table-recognize-table)
22329 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
22330 (table-generate-source 'html " org-tmp2 ")
22331 (set-buffer " org-tmp2 ")
22332 (buffer-substring (point-min) (point-max))))
22334 (defun org-html-handle-time-stamps (s)
22335 "Format time stamps in string S, or remove them."
22336 (catch 'exit
22337 (let (r b)
22338 (while (string-match org-maybe-keyword-time-regexp s)
22339 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
22340 ;; never export CLOCK
22341 (throw 'exit ""))
22342 (or b (setq b (substring s 0 (match-beginning 0))))
22343 (if (not org-export-with-timestamps)
22344 (setq r (concat r (substring s 0 (match-beginning 0)))
22345 s (substring s (match-end 0)))
22346 (setq r (concat
22347 r (substring s 0 (match-beginning 0))
22348 (if (match-end 1)
22349 (format "@<span class=\"timestamp-kwd\">%s @</span>"
22350 (match-string 1 s)))
22351 (format " @<span class=\"timestamp\">%s@</span>"
22352 (substring
22353 (org-translate-time (match-string 3 s)) 1 -1)))
22354 s (substring s (match-end 0)))))
22355 ;; Line break if line started and ended with time stamp stuff
22356 (if (not r)
22358 (setq r (concat r s))
22359 (unless (string-match "\\S-" (concat b s))
22360 (setq r (concat r "@<br/>")))
22361 r))))
22363 (defun org-html-protect (s)
22364 ;; convert & to &amp;, < to &lt; and > to &gt;
22365 (let ((start 0))
22366 (while (string-match "&" s start)
22367 (setq s (replace-match "&amp;" t t s)
22368 start (1+ (match-beginning 0))))
22369 (while (string-match "<" s)
22370 (setq s (replace-match "&lt;" t t s)))
22371 (while (string-match ">" s)
22372 (setq s (replace-match "&gt;" t t s))))
22375 (defun org-export-cleanup-toc-line (s)
22376 "Remove tags and time staps from lines going into the toc."
22377 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
22378 (setq s (replace-match "" t t s)))
22379 (when org-export-remove-timestamps-from-toc
22380 (while (string-match org-maybe-keyword-time-regexp s)
22381 (setq s (replace-match "" t t s))))
22382 (while (string-match org-bracket-link-regexp s)
22383 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
22384 t t s)))
22387 (defun org-html-expand (string)
22388 "Prepare STRING for HTML export. Applies all active conversions.
22389 If there are links in the string, don't modify these."
22390 (let* (m s l res)
22391 (while (setq m (string-match org-bracket-link-regexp string))
22392 (setq s (substring string 0 m)
22393 l (match-string 0 string)
22394 string (substring string (match-end 0)))
22395 (push (org-html-do-expand s) res)
22396 (push l res))
22397 (push (org-html-do-expand string) res)
22398 (apply 'concat (nreverse res))))
22400 (defun org-html-do-expand (s)
22401 "Apply all active conversions to translate special ASCII to HTML."
22402 (setq s (org-html-protect s))
22403 (if org-export-html-expand
22404 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
22405 (setq s (replace-match "<\\1>" t nil s))))
22406 (if org-export-with-emphasize
22407 (setq s (org-export-html-convert-emphasize s)))
22408 (if org-export-with-sub-superscripts
22409 (setq s (org-export-html-convert-sub-super s)))
22410 (if org-export-with-TeX-macros
22411 (let ((start 0) wd ass)
22412 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
22413 (setq wd (match-string 1 s))
22414 (if (setq ass (assoc wd org-html-entities))
22415 (setq s (replace-match (or (cdr ass)
22416 (concat "&" (car ass) ";"))
22417 t t s))
22418 (setq start (+ start (length wd)))))))
22421 (defun org-create-multibrace-regexp (left right n)
22422 "Create a regular expression which will match a balanced sexp.
22423 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
22424 as single character strings.
22425 The regexp returned will match the entire expression including the
22426 delimiters. It will also define a single group which contains the
22427 match except for the outermost delimiters. The maximum depth of
22428 stacked delimiters is N. Escaping delimiters is not possible."
22429 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
22430 (or "\\|")
22431 (re nothing)
22432 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
22433 (while (> n 1)
22434 (setq n (1- n)
22435 re (concat re or next)
22436 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
22437 (concat left "\\(" re "\\)" right)))
22439 (defvar org-match-substring-regexp
22440 (concat
22441 "\\([^\\]\\)\\([_^]\\)\\("
22442 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
22443 "\\|"
22444 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
22445 "\\|"
22446 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
22447 "The regular expression matching a sub- or superscript.")
22449 ;(let ((s "a\\_b"))
22450 ; (and (string-match org-match-substring-regexp s)
22451 ; (conca t (match-string 1 s) ":::" (match-string 2 s))))
22453 (defun org-export-html-convert-sub-super (string)
22454 "Convert sub- and superscripts in STRING to HTML."
22455 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
22456 (while (string-match org-match-substring-regexp string s)
22457 (if (and requireb (match-end 8))
22458 (setq s (match-end 2))
22459 (setq s (match-end 1)
22460 key (if (string= (match-string 2 string) "_") "sub" "sup")
22461 c (or (match-string 8 string)
22462 (match-string 6 string)
22463 (match-string 5 string))
22464 string (replace-match
22465 (concat (match-string 1 string)
22466 "<" key ">" c "</" key ">")
22467 t t string))))
22468 (while (string-match "\\\\\\([_^]\\)" string)
22469 (setq string (replace-match (match-string 1 string) t t string)))
22470 string))
22472 (defun org-export-html-convert-emphasize (string)
22473 "Apply emphasis."
22474 (let ((s 0))
22475 (while (string-match org-emph-re string s)
22476 (if (not (equal
22477 (substring string (match-beginning 3) (1+ (match-beginning 3)))
22478 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
22479 (setq string (replace-match
22480 (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
22481 "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist))
22482 "\\5") t nil string))
22483 (setq s (1+ s))))
22484 string))
22486 (defvar org-par-open nil)
22487 (defun org-open-par ()
22488 "Insert <p>, but first close previous paragraph if any."
22489 (org-close-par-maybe)
22490 (insert "\n<p>")
22491 (setq org-par-open t))
22492 (defun org-close-par-maybe ()
22493 "Close paragraph if there is one open."
22494 (when org-par-open
22495 (insert "</p>")
22496 (setq org-par-open nil)))
22497 (defun org-close-li ()
22498 "Close <li> if necessary."
22499 (org-close-par-maybe)
22500 (insert "</li>\n"))
22502 (defvar body-only) ; dynamically scoped into this.
22503 (defun org-html-level-start (level title umax with-toc head-count)
22504 "Insert a new level in HTML export.
22505 When TITLE is nil, just close all open levels."
22506 (org-close-par-maybe)
22507 (let ((l (1+ (max level umax))))
22508 (while (<= l org-level-max)
22509 (if (aref org-levels-open (1- l))
22510 (progn
22511 (org-html-level-close l)
22512 (aset org-levels-open (1- l) nil)))
22513 (setq l (1+ l)))
22514 (when title
22515 ;; If title is nil, this means this function is called to close
22516 ;; all levels, so the rest is done only if title is given
22517 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
22518 (setq title (replace-match
22519 (if org-export-with-tags
22520 (save-match-data
22521 (concat
22522 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
22523 (mapconcat 'identity (org-split-string
22524 (match-string 1 title) ":")
22525 "&nbsp;")
22526 "</span>"))
22528 t t title)))
22529 (if (> level umax)
22530 (progn
22531 (if (aref org-levels-open (1- level))
22532 (progn
22533 (org-close-li)
22534 (insert "<li>" title "<br/>\n"))
22535 (aset org-levels-open (1- level) t)
22536 (org-close-par-maybe)
22537 (insert "<ul>\n<li>" title "<br/>\n")))
22538 (if (and org-export-with-section-numbers (not body-only))
22539 (setq title (concat (org-section-number level) " " title)))
22540 (setq level (+ level org-export-html-toplevel-hlevel -1))
22541 (if with-toc
22542 (insert (format "\n<h%d id=\"sec-%d\">%s</h%d>\n"
22543 level head-count title level))
22544 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
22545 (org-open-par)))))
22547 (defun org-html-level-close (&rest args)
22548 "Terminate one level in HTML export."
22549 (org-close-li)
22550 (insert "</ul>\n"))
22552 ;;; iCalendar export
22554 ;;;###autoload
22555 (defun org-export-icalendar-this-file ()
22556 "Export current file as an iCalendar file.
22557 The iCalendar file will be located in the same directory as the Org-mode
22558 file, but with extension `.ics'."
22559 (interactive)
22560 (org-export-icalendar nil buffer-file-name))
22562 ;;;###autoload
22563 (defun org-export-icalendar-all-agenda-files ()
22564 "Export all files in `org-agenda-files' to iCalendar .ics files.
22565 Each iCalendar file will be located in the same directory as the Org-mode
22566 file, but with extension `.ics'."
22567 (interactive)
22568 (apply 'org-export-icalendar nil (org-agenda-files t)))
22570 ;;;###autoload
22571 (defun org-export-icalendar-combine-agenda-files ()
22572 "Export all files in `org-agenda-files' to a single combined iCalendar file.
22573 The file is stored under the name `org-combined-agenda-icalendar-file'."
22574 (interactive)
22575 (apply 'org-export-icalendar t (org-agenda-files t)))
22577 (defun org-export-icalendar (combine &rest files)
22578 "Create iCalendar files for all elements of FILES.
22579 If COMBINE is non-nil, combine all calendar entries into a single large
22580 file and store it under the name `org-combined-agenda-icalendar-file'."
22581 (save-excursion
22582 (org-prepare-agenda-buffers files)
22583 (let* ((dir (org-export-directory
22584 :ical (list :publishing-directory
22585 org-export-publishing-directory)))
22586 file ical-file ical-buffer category started org-agenda-new-buffers)
22588 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
22589 (when combine
22590 (setq ical-file
22591 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
22592 org-combined-agenda-icalendar-file
22593 (expand-file-name org-combined-agenda-icalendar-file dir))
22594 ical-buffer (org-get-agenda-file-buffer ical-file))
22595 (set-buffer ical-buffer) (erase-buffer))
22596 (while (setq file (pop files))
22597 (catch 'nextfile
22598 (org-check-agenda-file file)
22599 (set-buffer (org-get-agenda-file-buffer file))
22600 (unless combine
22601 (setq ical-file (concat (file-name-as-directory dir)
22602 (file-name-sans-extension
22603 (file-name-nondirectory buffer-file-name))
22604 ".ics"))
22605 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
22606 (with-current-buffer ical-buffer (erase-buffer)))
22607 (setq category (or org-category
22608 (file-name-sans-extension
22609 (file-name-nondirectory buffer-file-name))))
22610 (if (symbolp category) (setq category (symbol-name category)))
22611 (let ((standard-output ical-buffer))
22612 (if combine
22613 (and (not started) (setq started t)
22614 (org-start-icalendar-file org-icalendar-combined-name))
22615 (org-start-icalendar-file category))
22616 (org-print-icalendar-entries combine)
22617 (when (or (and combine (not files)) (not combine))
22618 (org-finish-icalendar-file)
22619 (set-buffer ical-buffer)
22620 (save-buffer)
22621 (run-hooks 'org-after-save-iCalendar-file-hook)))))
22622 (org-release-buffers org-agenda-new-buffers))))
22624 (defvar org-after-save-iCalendar-file-hook nil
22625 "Hook run after an iCalendar file has been saved.
22626 The iCalendar buffer is still current when this hook is run.
22627 A good way to use this is to tell a desktop calenndar application to re-read
22628 the iCalendar file.")
22630 (defun org-print-icalendar-entries (&optional combine)
22631 "Print iCalendar entries for the current Org-mode file to `standard-output'.
22632 When COMBINE is non nil, add the category to each line."
22633 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
22634 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
22635 (org-category-table (org-get-category-table))
22636 (dts (org-ical-ts-to-string
22637 (format-time-string (cdr org-time-stamp-formats) (current-time))
22638 "DTSTART"))
22639 hd ts ts2 state status (inc t) pos b sexp rrule
22640 scheduledp deadlinep tmp pri category
22641 (sexp-buffer (get-buffer-create "*ical-tmp*")))
22642 (save-excursion
22643 (goto-char (point-min))
22644 (while (re-search-forward re1 nil t)
22645 (catch :skip
22646 (org-agenda-skip)
22647 (setq pos (match-beginning 0)
22648 ts (match-string 0)
22649 inc t
22650 hd (org-get-heading)
22651 category (org-get-category))
22652 (if (looking-at re2)
22653 (progn
22654 (goto-char (match-end 0))
22655 (setq ts2 (match-string 1) inc nil))
22656 (setq tmp (buffer-substring (max (point-min)
22657 (- pos org-ds-keyword-length))
22658 pos)
22659 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
22660 (progn
22661 (setq inc nil)
22662 (replace-match "\\1" t nil ts))
22664 deadlinep (string-match org-deadline-regexp tmp)
22665 scheduledp (string-match org-scheduled-regexp tmp)
22666 ;; donep (org-entry-is-done-p)
22668 (if (or (string-match org-tr-regexp hd)
22669 (string-match org-ts-regexp hd))
22670 (setq hd (replace-match "" t t hd)))
22671 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
22672 (setq rrule
22673 (concat "\nRRULE:FREQ="
22674 (cdr (assoc
22675 (match-string 2 ts)
22676 '(("d" . "DAILY")("w" . "WEEKLY")
22677 ("m" . "MONTHLY")("y" . "YEARLY"))))
22678 ";INTERVAL=" (match-string 1 ts)))
22679 (setq rrule ""))
22680 (if (string-match org-bracket-link-regexp hd)
22681 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
22682 (match-string 1 hd))
22683 t t hd)))
22684 (if deadlinep (setq hd (concat "DL: " hd)))
22685 (if scheduledp (setq hd (concat "S: " hd)))
22686 (if (string-match "\\`<%%" ts)
22687 (with-current-buffer sexp-buffer
22688 (insert (substring ts 1 -1) " " hd "\n"))
22689 (princ (format "BEGIN:VEVENT
22691 %s%s
22692 SUMMARY:%s
22693 CATEGORIES:%s
22694 END:VEVENT\n"
22695 (org-ical-ts-to-string ts "DTSTART")
22696 (org-ical-ts-to-string ts2 "DTEND" inc)
22697 rrule hd category)))))
22699 (when (and org-icalendar-include-sexps
22700 (condition-case nil (require 'icalendar) (error nil))
22701 (fboundp 'icalendar-export-region))
22702 ;; Get all the literal sexps
22703 (goto-char (point-min))
22704 (while (re-search-forward "^&?%%(" nil t)
22705 (catch :skip
22706 (org-agenda-skip)
22707 (setq b (match-beginning 0))
22708 (goto-char (1- (match-end 0)))
22709 (forward-sexp 1)
22710 (end-of-line 1)
22711 (setq sexp (buffer-substring b (point)))
22712 (with-current-buffer sexp-buffer
22713 (insert sexp "\n"))
22714 (princ (org-diary-to-ical-string sexp-buffer)))))
22716 (when org-icalendar-include-todo
22717 (goto-char (point-min))
22718 (while (re-search-forward org-todo-line-regexp nil t)
22719 (catch :skip
22720 (org-agenda-skip)
22721 (setq state (match-string 2))
22722 (setq status (if (member state org-done-keywords)
22723 "COMPLETED" "NEEDS-ACTION"))
22724 (when (and state
22725 (or (not (member state org-done-keywords))
22726 (eq org-icalendar-include-todo 'all))
22727 (not (member org-archive-tag (org-get-tags-at)))
22729 (setq hd (match-string 3))
22730 (if (string-match org-bracket-link-regexp hd)
22731 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
22732 (match-string 1 hd))
22733 t t hd)))
22734 (if (string-match org-priority-regexp hd)
22735 (setq pri (string-to-char (match-string 2 hd))
22736 hd (concat (substring hd 0 (match-beginning 1))
22737 (substring hd (match-end 1))))
22738 (setq pri org-default-priority))
22739 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
22740 (- org-lowest-priority org-highest-priority))))))
22742 (princ (format "BEGIN:VTODO
22744 SUMMARY:%s
22745 CATEGORIES:%s
22746 SEQUENCE:1
22747 PRIORITY:%d
22748 STATUS:%s
22749 END:VTODO\n"
22750 dts hd category pri status)))))))))
22752 (defun org-start-icalendar-file (name)
22753 "Start an iCalendar file by inserting the header."
22754 (let ((user user-full-name)
22755 (name (or name "unknown"))
22756 (timezone (cadr (current-time-zone))))
22757 (princ
22758 (format "BEGIN:VCALENDAR
22759 VERSION:2.0
22760 X-WR-CALNAME:%s
22761 PRODID:-//%s//Emacs with Org-mode//EN
22762 X-WR-TIMEZONE:%s
22763 CALSCALE:GREGORIAN\n" name user timezone))))
22765 (defun org-finish-icalendar-file ()
22766 "Finish an iCalendar file by inserting the END statement."
22767 (princ "END:VCALENDAR\n"))
22769 (defun org-ical-ts-to-string (s keyword &optional inc)
22770 "Take a time string S and convert it to iCalendar format.
22771 KEYWORD is added in front, to make a complete line like DTSTART....
22772 When INC is non-nil, increase the hour by two (if time string contains
22773 a time), or the day by one (if it does not contain a time)."
22774 (let ((t1 (org-parse-time-string s 'nodefault))
22775 t2 fmt have-time time)
22776 (if (and (car t1) (nth 1 t1) (nth 2 t1))
22777 (setq t2 t1 have-time t)
22778 (setq t2 (org-parse-time-string s)))
22779 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
22780 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
22781 (when inc
22782 (if have-time
22783 (if org-agenda-default-appointment-duration
22784 (setq mi (+ org-agenda-default-appointment-duration mi))
22785 (setq h (+ 2 h)))
22786 (setq d (1+ d))))
22787 (setq time (encode-time s mi h d m y)))
22788 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
22789 (concat keyword (format-time-string fmt time))))
22791 ;;; XOXO export
22793 (defun org-export-as-xoxo-insert-into (buffer &rest output)
22794 (with-current-buffer buffer
22795 (apply 'insert output)))
22796 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
22798 (defun org-export-as-xoxo (&optional buffer)
22799 "Export the org buffer as XOXO.
22800 The XOXO buffer is named *xoxo-<source buffer name>*"
22801 (interactive (list (current-buffer)))
22802 ;; A quickie abstraction
22804 ;; Output everything as XOXO
22805 (with-current-buffer (get-buffer buffer)
22806 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
22807 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
22808 (org-infile-export-plist)))
22809 (filename (concat (file-name-as-directory
22810 (org-export-directory :xoxo opt-plist))
22811 (file-name-sans-extension
22812 (file-name-nondirectory buffer-file-name))
22813 ".html"))
22814 (out (find-file-noselect filename))
22815 (last-level 1)
22816 (hanging-li nil))
22817 ;; Check the output buffer is empty.
22818 (with-current-buffer out (erase-buffer))
22819 ;; Kick off the output
22820 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
22821 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
22822 (let* ((hd (match-string-no-properties 1))
22823 (level (length hd))
22824 (text (concat
22825 (match-string-no-properties 2)
22826 (save-excursion
22827 (goto-char (match-end 0))
22828 (let ((str ""))
22829 (catch 'loop
22830 (while 't
22831 (forward-line)
22832 (if (looking-at "^[ \t]\\(.*\\)")
22833 (setq str (concat str (match-string-no-properties 1)))
22834 (throw 'loop str)))))))))
22836 ;; Handle level rendering
22837 (cond
22838 ((> level last-level)
22839 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
22841 ((< level last-level)
22842 (dotimes (- (- last-level level) 1)
22843 (if hanging-li
22844 (org-export-as-xoxo-insert-into out "</li>\n"))
22845 (org-export-as-xoxo-insert-into out "</ol>\n"))
22846 (when hanging-li
22847 (org-export-as-xoxo-insert-into out "</li>\n")
22848 (setq hanging-li nil)))
22850 ((equal level last-level)
22851 (if hanging-li
22852 (org-export-as-xoxo-insert-into out "</li>\n")))
22855 (setq last-level level)
22857 ;; And output the new li
22858 (setq hanging-li 't)
22859 (if (equal ?+ (elt text 0))
22860 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
22861 (org-export-as-xoxo-insert-into out "<li>" text))))
22863 ;; Finally finish off the ol
22864 (dotimes (- last-level 1)
22865 (if hanging-li
22866 (org-export-as-xoxo-insert-into out "</li>\n"))
22867 (org-export-as-xoxo-insert-into out "</ol>\n"))
22869 ;; Finish the buffer off and clean it up.
22870 (switch-to-buffer-other-window out)
22871 (indent-region (point-min) (point-max) nil)
22872 (save-buffer)
22873 (goto-char (point-min))
22877 ;;;; Key bindings
22879 ;; Make `C-c C-x' a prefix key
22880 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
22882 ;; TAB key with modifiers
22883 (org-defkey org-mode-map "\C-i" 'org-cycle)
22884 (org-defkey org-mode-map [(tab)] 'org-cycle)
22885 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
22886 (org-defkey org-mode-map [(meta tab)] 'org-complete)
22887 (org-defkey org-mode-map "\M-\t" 'org-complete)
22888 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
22889 ;; The following line is necessary under Suse GNU/Linux
22890 (unless (featurep 'xemacs)
22891 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
22892 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
22893 (define-key org-mode-map (kbd "<backtab>") 'org-shifttab)
22895 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
22896 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
22897 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
22899 ;; Cursor keys with modifiers
22900 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
22901 (org-defkey org-mode-map [(meta right)] 'org-metaright)
22902 (org-defkey org-mode-map [(meta up)] 'org-metaup)
22903 (org-defkey org-mode-map [(meta down)] 'org-metadown)
22905 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
22906 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
22907 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
22908 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
22910 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
22911 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
22912 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
22913 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
22915 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
22916 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
22918 ;;; Extra keys for tty access.
22919 ;; We only set them when really needed because otherwise the
22920 ;; menus don't show the simple keys
22922 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
22923 (not window-system))
22924 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
22925 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
22926 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
22927 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
22928 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
22929 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
22930 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
22931 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
22932 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
22933 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
22934 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
22935 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
22936 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
22937 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
22938 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
22939 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
22940 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
22941 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
22942 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
22943 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
22944 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
22945 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
22947 ;; All the other keys
22949 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
22950 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
22951 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
22952 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
22953 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
22954 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
22955 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
22956 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
22957 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
22958 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
22959 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
22960 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
22961 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
22962 (org-defkey org-mode-map "\C-c\C-w" 'org-check-deadlines)
22963 (org-defkey org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
22964 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
22965 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
22966 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
22967 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
22968 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
22969 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
22970 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
22971 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
22972 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
22973 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
22974 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
22975 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
22976 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
22977 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
22978 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
22979 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
22980 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
22981 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
22982 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
22983 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
22984 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
22985 (org-defkey org-mode-map "\C-c^" 'org-sort)
22986 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
22987 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
22988 (org-defkey org-mode-map "\C-m" 'org-return)
22989 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
22990 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
22991 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
22992 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
22993 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
22994 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
22995 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
22996 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
22997 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
22998 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
22999 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
23000 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
23001 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
23002 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
23003 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
23004 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
23006 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
23007 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
23008 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
23009 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
23011 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
23012 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
23013 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
23014 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
23015 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
23016 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
23017 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
23018 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
23019 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
23021 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
23023 (when (featurep 'xemacs)
23024 (org-defkey org-mode-map 'button3 'popup-mode-menu))
23026 (defsubst org-table-p () (org-at-table-p))
23028 (defun org-self-insert-command (N)
23029 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
23030 If the cursor is in a table looking at whitespace, the whitespace is
23031 overwritten, and the table is not marked as requiring realignment."
23032 (interactive "p")
23033 (if (and (org-table-p)
23034 (progn
23035 ;; check if we blank the field, and if that triggers align
23036 (and org-table-auto-blank-field
23037 (member last-command
23038 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
23039 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
23040 ;; got extra space, this field does not determine column width
23041 (let (org-table-may-need-update) (org-table-blank-field))
23042 ;; no extra space, this field may determine column width
23043 (org-table-blank-field)))
23045 (eq N 1)
23046 (looking-at "[^|\n]* |"))
23047 (let (org-table-may-need-update)
23048 (goto-char (1- (match-end 0)))
23049 (delete-backward-char 1)
23050 (goto-char (match-beginning 0))
23051 (self-insert-command N))
23052 (setq org-table-may-need-update t)
23053 (self-insert-command N)
23054 (org-fix-tags-on-the-fly)))
23056 (defun org-fix-tags-on-the-fly ()
23057 (when (and (equal (char-after (point-at-bol)) ?*)
23058 (org-on-heading-p))
23059 (org-align-tags-here org-tags-column)))
23061 (defun org-delete-backward-char (N)
23062 "Like `delete-backward-char', insert whitespace at field end in tables.
23063 When deleting backwards, in tables this function will insert whitespace in
23064 front of the next \"|\" separator, to keep the table aligned. The table will
23065 still be marked for re-alignment if the field did fill the entire column,
23066 because, in this case the deletion might narrow the column."
23067 (interactive "p")
23068 (if (and (org-table-p)
23069 (eq N 1)
23070 (string-match "|" (buffer-substring (point-at-bol) (point)))
23071 (looking-at ".*?|"))
23072 (let ((pos (point))
23073 (noalign (looking-at "[^|\n\r]* |"))
23074 (c org-table-may-need-update))
23075 (backward-delete-char N)
23076 (skip-chars-forward "^|")
23077 (insert " ")
23078 (goto-char (1- pos))
23079 ;; noalign: if there were two spaces at the end, this field
23080 ;; does not determine the width of the column.
23081 (if noalign (setq org-table-may-need-update c)))
23082 (backward-delete-char N)
23083 (org-fix-tags-on-the-fly)))
23085 (defun org-delete-char (N)
23086 "Like `delete-char', but insert whitespace at field end in tables.
23087 When deleting characters, in tables this function will insert whitespace in
23088 front of the next \"|\" separator, to keep the table aligned. The table will
23089 still be marked for re-alignment if the field did fill the entire column,
23090 because, in this case the deletion might narrow the column."
23091 (interactive "p")
23092 (if (and (org-table-p)
23093 (not (bolp))
23094 (not (= (char-after) ?|))
23095 (eq N 1))
23096 (if (looking-at ".*?|")
23097 (let ((pos (point))
23098 (noalign (looking-at "[^|\n\r]* |"))
23099 (c org-table-may-need-update))
23100 (replace-match (concat
23101 (substring (match-string 0) 1 -1)
23102 " |"))
23103 (goto-char pos)
23104 ;; noalign: if there were two spaces at the end, this field
23105 ;; does not determine the width of the column.
23106 (if noalign (setq org-table-may-need-update c)))
23107 (delete-char N))
23108 (delete-char N)
23109 (org-fix-tags-on-the-fly)))
23111 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
23112 (put 'org-self-insert-command 'delete-selection t)
23113 (put 'orgtbl-self-insert-command 'delete-selection t)
23114 (put 'org-delete-char 'delete-selection 'supersede)
23115 (put 'org-delete-backward-char 'delete-selection 'supersede)
23117 ;; Make `flyspell-mode' delay after some commands
23118 (put 'org-self-insert-command 'flyspell-delayed t)
23119 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
23120 (put 'org-delete-char 'flyspell-delayed t)
23121 (put 'org-delete-backward-char 'flyspell-delayed t)
23123 ;; How to do this: Measure non-white length of current string
23124 ;; If equal to column width, we should realign.
23126 (defun org-remap (map &rest commands)
23127 "In MAP, remap the functions given in COMMANDS.
23128 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
23129 (let (new old)
23130 (while commands
23131 (setq old (pop commands) new (pop commands))
23132 (if (fboundp 'command-remapping)
23133 (org-defkey map (vector 'remap old) new)
23134 (substitute-key-definition old new map global-map)))))
23136 (when (eq org-enable-table-editor 'optimized)
23137 ;; If the user wants maximum table support, we need to hijack
23138 ;; some standard editing functions
23139 (org-remap org-mode-map
23140 'self-insert-command 'org-self-insert-command
23141 'delete-char 'org-delete-char
23142 'delete-backward-char 'org-delete-backward-char)
23143 (org-defkey org-mode-map "|" 'org-force-self-insert))
23145 (defun org-shiftcursor-error ()
23146 "Throw an error because Shift-Cursor command was applied in wrong context."
23147 (error "This command is active in special context like tables, headlines or timestamps"))
23149 (defun org-shifttab (&optional arg)
23150 "Global visibility cycling or move to previous table field.
23151 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
23152 on context.
23153 See the individual commands for more information."
23154 (interactive "P")
23155 (cond
23156 ((org-at-table-p) (call-interactively 'org-table-previous-field))
23157 (arg (message "Content view to level: ")
23158 (org-content (prefix-numeric-value arg))
23159 (setq org-cycle-global-status 'overview))
23160 (t (call-interactively 'org-global-cycle))))
23162 (defun org-shiftmetaleft ()
23163 "Promote subtree or delete table column.
23164 Calls `org-promote-subtree', `org-outdent-item',
23165 or `org-table-delete-column', depending on context.
23166 See the individual commands for more information."
23167 (interactive)
23168 (cond
23169 ((org-at-table-p) (call-interactively 'org-table-delete-column))
23170 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
23171 ((org-at-item-p) (call-interactively 'org-outdent-item))
23172 (t (org-shiftcursor-error))))
23174 (defun org-shiftmetaright ()
23175 "Demote subtree or insert table column.
23176 Calls `org-demote-subtree', `org-indent-item',
23177 or `org-table-insert-column', depending on context.
23178 See the individual commands for more information."
23179 (interactive)
23180 (cond
23181 ((org-at-table-p) (call-interactively 'org-table-insert-column))
23182 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
23183 ((org-at-item-p) (call-interactively 'org-indent-item))
23184 (t (org-shiftcursor-error))))
23186 (defun org-shiftmetaup (&optional arg)
23187 "Move subtree up or kill table row.
23188 Calls `org-move-subtree-up' or `org-table-kill-row' or
23189 `org-move-item-up' depending on context. See the individual commands
23190 for more information."
23191 (interactive "P")
23192 (cond
23193 ((org-at-table-p) (call-interactively 'org-table-kill-row))
23194 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
23195 ((org-at-item-p) (call-interactively 'org-move-item-up))
23196 (t (org-shiftcursor-error))))
23197 (defun org-shiftmetadown (&optional arg)
23198 "Move subtree down or insert table row.
23199 Calls `org-move-subtree-down' or `org-table-insert-row' or
23200 `org-move-item-down', depending on context. See the individual
23201 commands for more information."
23202 (interactive "P")
23203 (cond
23204 ((org-at-table-p) (call-interactively 'org-table-insert-row))
23205 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
23206 ((org-at-item-p) (call-interactively 'org-move-item-down))
23207 (t (org-shiftcursor-error))))
23209 (defun org-metaleft (&optional arg)
23210 "Promote heading or move table column to left.
23211 Calls `org-do-promote' or `org-table-move-column', depending on context.
23212 With no specific context, calls the Emacs default `backward-word'.
23213 See the individual commands for more information."
23214 (interactive "P")
23215 (cond
23216 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
23217 ((or (org-on-heading-p) (org-region-active-p))
23218 (call-interactively 'org-do-promote))
23219 ((org-at-item-p) (call-interactively 'org-outdent-item))
23220 (t (call-interactively 'backward-word))))
23222 (defun org-metaright (&optional arg)
23223 "Demote subtree or move table column to right.
23224 Calls `org-do-demote' or `org-table-move-column', depending on context.
23225 With no specific context, calls the Emacs default `forward-word'.
23226 See the individual commands for more information."
23227 (interactive "P")
23228 (cond
23229 ((org-at-table-p) (call-interactively 'org-table-move-column))
23230 ((or (org-on-heading-p) (org-region-active-p))
23231 (call-interactively 'org-do-demote))
23232 ((org-at-item-p) (call-interactively 'org-indent-item))
23233 (t (call-interactively 'forward-word))))
23235 (defun org-metaup (&optional arg)
23236 "Move subtree up or move table row up.
23237 Calls `org-move-subtree-up' or `org-table-move-row' or
23238 `org-move-item-up', depending on context. See the individual commands
23239 for more information."
23240 (interactive "P")
23241 (cond
23242 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
23243 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
23244 ((org-at-item-p) (call-interactively 'org-move-item-up))
23245 (t (org-shiftcursor-error))))
23247 (defun org-metadown (&optional arg)
23248 "Move subtree down or move table row down.
23249 Calls `org-move-subtree-down' or `org-table-move-row' or
23250 `org-move-item-down', depending on context. See the individual
23251 commands for more information."
23252 (interactive "P")
23253 (cond
23254 ((org-at-table-p) (call-interactively 'org-table-move-row))
23255 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
23256 ((org-at-item-p) (call-interactively 'org-move-item-down))
23257 (t (org-shiftcursor-error))))
23259 (defun org-shiftup (&optional arg)
23260 "Increase item in timestamp or increase priority of current headline.
23261 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
23262 depending on context. See the individual commands for more information."
23263 (interactive "P")
23264 (cond
23265 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
23266 ((org-on-heading-p) (call-interactively 'org-priority-up))
23267 ((org-at-item-p) (call-interactively 'org-previous-item))
23268 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
23270 (defun org-shiftdown (&optional arg)
23271 "Decrease item in timestamp or decrease priority of current headline.
23272 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
23273 depending on context. See the individual commands for more information."
23274 (interactive "P")
23275 (cond
23276 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
23277 ((org-on-heading-p) (call-interactively 'org-priority-down))
23278 (t (call-interactively 'org-next-item))))
23280 (defun org-shiftright ()
23281 "Next TODO keyword or timestamp one day later, depending on context."
23282 (interactive)
23283 (cond
23284 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
23285 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
23286 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
23287 (t (org-shiftcursor-error))))
23289 (defun org-shiftleft ()
23290 "Previous TODO keyword or timestamp one day earlier, depending on context."
23291 (interactive)
23292 (cond
23293 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
23294 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
23295 ((org-at-property-p)
23296 (call-interactively 'org-property-previous-allowed-value))
23297 (t (org-shiftcursor-error))))
23299 (defun org-shiftcontrolright ()
23300 "Switch to next TODO set."
23301 (interactive)
23302 (cond
23303 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
23304 (t (org-shiftcursor-error))))
23306 (defun org-shiftcontrolleft ()
23307 "Switch to previous TODO set."
23308 (interactive)
23309 (cond
23310 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
23311 (t (org-shiftcursor-error))))
23313 (defun org-ctrl-c-ret ()
23314 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
23315 (interactive)
23316 (cond
23317 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
23318 (t (call-interactively 'org-insert-heading))))
23320 (defun org-copy-special ()
23321 "Copy region in table or copy current subtree.
23322 Calls `org-table-copy' or `org-copy-subtree', depending on context.
23323 See the individual commands for more information."
23324 (interactive)
23325 (call-interactively
23326 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
23328 (defun org-cut-special ()
23329 "Cut region in table or cut current subtree.
23330 Calls `org-table-copy' or `org-cut-subtree', depending on context.
23331 See the individual commands for more information."
23332 (interactive)
23333 (call-interactively
23334 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
23336 (defun org-paste-special (arg)
23337 "Paste rectangular region into table, or past subtree relative to level.
23338 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
23339 See the individual commands for more information."
23340 (interactive "P")
23341 (if (org-at-table-p)
23342 (org-table-paste-rectangle)
23343 (org-paste-subtree arg)))
23345 (defun org-ctrl-c-ctrl-c (&optional arg)
23346 "Set tags in headline, or update according to changed information at point.
23348 This command does many different things, depending on context:
23350 - If the cursor is in a headline, prompt for tags and insert them
23351 into the current line, aligned to `org-tags-column'. When called
23352 with prefix arg, realign all tags in the current buffer.
23354 - If the cursor is in one of the special #+KEYWORD lines, this
23355 triggers scanning the buffer for these lines and updating the
23356 information.
23358 - If the cursor is inside a table, realign the table. This command
23359 works even if the automatic table editor has been turned off.
23361 - If the cursor is on a #+TBLFM line, re-apply the formulas to
23362 the entire table.
23364 - If the cursor is inside a table created by the table.el package,
23365 activate that table.
23367 - If the current buffer is a remember buffer, close note and file it.
23368 with a prefix argument, file it without further interaction to the default
23369 location.
23371 - If the cursor is on a <<<target>>>, update radio targets and corresponding
23372 links in this buffer.
23374 - If the cursor is on a numbered item in a plain list, renumber the
23375 ordered list."
23376 (interactive "P")
23377 (let ((org-enable-table-editor t))
23378 (cond
23379 ((or org-clock-overlays
23380 org-occur-highlights
23381 org-latex-fragment-image-overlays)
23382 (org-remove-clock-overlays)
23383 (org-remove-occur-highlights)
23384 (org-remove-latex-fragment-image-overlays)
23385 (message "Temporary highlights/overlays removed from current buffer"))
23386 ((and (local-variable-p 'org-finish-function (current-buffer))
23387 (fboundp org-finish-function))
23388 (funcall org-finish-function))
23389 ((org-at-property-p)
23390 (call-interactively 'org-property-action))
23391 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
23392 ((org-on-heading-p) (call-interactively 'org-set-tags))
23393 ((org-at-table.el-p)
23394 (require 'table)
23395 (beginning-of-line 1)
23396 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
23397 (call-interactively 'table-recognize-table))
23398 ((org-at-table-p)
23399 (org-table-maybe-eval-formula)
23400 (if arg
23401 (call-interactively 'org-table-recalculate)
23402 (org-table-maybe-recalculate-line))
23403 (call-interactively 'org-table-align))
23404 ((org-at-item-checkbox-p)
23405 (call-interactively 'org-toggle-checkbox))
23406 ((org-at-item-p)
23407 (call-interactively 'org-maybe-renumber-ordered-list))
23408 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
23409 (cond
23410 ((equal (match-string 1) "TBLFM")
23411 ;; Recalculate the table before this line
23412 (save-excursion
23413 (beginning-of-line 1)
23414 (skip-chars-backward " \r\n\t")
23415 (if (org-at-table-p)
23416 (org-call-with-arg 'org-table-recalculate t))))
23418 (call-interactively 'org-mode-restart))))
23419 (t (error "C-c C-c can do nothing useful at this location.")))))
23421 (defun org-mode-restart ()
23422 "Restart Org-mode, to scan again for special lines.
23423 Also updates the keyword regular expressions."
23424 (interactive)
23425 (let ((org-inhibit-startup t)) (org-mode))
23426 (message "Org-mode restarted to refresh keyword and special line setup"))
23428 (defun org-return ()
23429 "Goto next table row or insert a newline.
23430 Calls `org-table-next-row' or `newline', depending on context.
23431 See the individual commands for more information."
23432 (interactive)
23433 (cond
23434 ((bobp) (newline))
23435 ((org-at-table-p)
23436 (org-table-justify-field-maybe)
23437 (call-interactively 'org-table-next-row))
23438 (t (newline))))
23440 (defun org-ctrl-c-minus ()
23441 "Insert separator line in table or modify bullet type in list.
23442 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
23443 depending on context."
23444 (interactive)
23445 (cond
23446 ((org-at-table-p)
23447 (call-interactively 'org-table-insert-hline))
23448 ((org-in-item-p)
23449 (call-interactively 'org-cycle-list-bullet))
23450 (t (error "`C-c -' does have no function here."))))
23452 (defun org-meta-return (&optional arg)
23453 "Insert a new heading or wrap a region in a table.
23454 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
23455 See the individual commands for more information."
23456 (interactive "P")
23457 (cond
23458 ((org-at-table-p)
23459 (call-interactively 'org-table-wrap-region))
23460 (t (call-interactively 'org-insert-heading))))
23462 ;;; Menu entries
23464 ;; Define the Org-mode menus
23465 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
23466 '("Tbl"
23467 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
23468 ["Next Field" org-cycle (org-at-table-p)]
23469 ["Previous Field" org-shifttab (org-at-table-p)]
23470 ["Next Row" org-return (org-at-table-p)]
23471 "--"
23472 ["Blank Field" org-table-blank-field (org-at-table-p)]
23473 ["Edit Field" org-table-edit-field (org-at-table-p)]
23474 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
23475 "--"
23476 ("Column"
23477 ["Move Column Left" org-metaleft (org-at-table-p)]
23478 ["Move Column Right" org-metaright (org-at-table-p)]
23479 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
23480 ["Insert Column" org-shiftmetaright (org-at-table-p)])
23481 ("Row"
23482 ["Move Row Up" org-metaup (org-at-table-p)]
23483 ["Move Row Down" org-metadown (org-at-table-p)]
23484 ["Delete Row" org-shiftmetaup (org-at-table-p)]
23485 ["Insert Row" org-shiftmetadown (org-at-table-p)]
23486 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
23487 "--"
23488 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
23489 ("Rectangle"
23490 ["Copy Rectangle" org-copy-special (org-at-table-p)]
23491 ["Cut Rectangle" org-cut-special (org-at-table-p)]
23492 ["Paste Rectangle" org-paste-special (org-at-table-p)]
23493 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
23494 "--"
23495 ("Calculate"
23496 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
23497 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
23498 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
23499 "--"
23500 ["Recalculate line" org-table-recalculate (org-at-table-p)]
23501 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
23502 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
23503 "--"
23504 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
23505 "--"
23506 ["Sum Column/Rectangle" org-table-sum
23507 (or (org-at-table-p) (org-region-active-p))]
23508 ["Which Column?" org-table-current-column (org-at-table-p)])
23509 ["Debug Formulas"
23510 org-table-toggle-formula-debugger
23511 :style toggle :selected org-table-formula-debug]
23512 ["Show Col/Row Numbers"
23513 org-table-toggle-coordinate-overlays
23514 :style toggle :selected org-table-overlay-coordinates]
23515 "--"
23516 ["Create" org-table-create (and (not (org-at-table-p))
23517 org-enable-table-editor)]
23518 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
23519 ["Import from File" org-table-import (not (org-at-table-p))]
23520 ["Export to File" org-table-export (org-at-table-p)]
23521 "--"
23522 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
23524 (easy-menu-define org-org-menu org-mode-map "Org menu"
23525 '("Org"
23526 ("Show/Hide"
23527 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
23528 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
23529 ["Sparse Tree" org-occur t]
23530 ["Reveal Context" org-reveal t]
23531 ["Show All" show-all t]
23532 "--"
23533 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
23534 "--"
23535 ["New Heading" org-insert-heading t]
23536 ("Navigate Headings"
23537 ["Up" outline-up-heading t]
23538 ["Next" outline-next-visible-heading t]
23539 ["Previous" outline-previous-visible-heading t]
23540 ["Next Same Level" outline-forward-same-level t]
23541 ["Previous Same Level" outline-backward-same-level t]
23542 "--"
23543 ["Jump" org-goto t])
23544 ("Edit Structure"
23545 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
23546 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
23547 "--"
23548 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
23549 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
23550 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
23551 "--"
23552 ["Promote Heading" org-metaleft (not (org-at-table-p))]
23553 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
23554 ["Demote Heading" org-metaright (not (org-at-table-p))]
23555 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
23556 "--"
23557 ["Sort Region/Children" org-sort (not (org-at-table-p))]
23558 "--"
23559 ["Convert to odd levels" org-convert-to-odd-levels t]
23560 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
23561 ("Editing"
23562 ["Emphasis..." org-emphasize t])
23563 ("Archive"
23564 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
23565 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
23566 ; :active t :keys "C-u C-c C-x C-a"]
23567 ["Sparse trees open ARCHIVE trees"
23568 (setq org-sparse-tree-open-archived-trees
23569 (not org-sparse-tree-open-archived-trees))
23570 :style toggle :selected org-sparse-tree-open-archived-trees]
23571 ["Cycling opens ARCHIVE trees"
23572 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
23573 :style toggle :selected org-cycle-open-archived-trees]
23574 ["Agenda includes ARCHIVE trees"
23575 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
23576 :style toggle :selected (not org-agenda-skip-archived-trees)]
23577 "--"
23578 ["Move Subtree to Archive" org-advertized-archive-subtree t]
23579 ; ["Check and Move Children" (org-archive-subtree '(4))
23580 ; :active t :keys "C-u C-c C-x C-s"]
23582 "--"
23583 ("TODO Lists"
23584 ["TODO/DONE/-" org-todo t]
23585 ("Select keyword"
23586 ["Next keyword" org-shiftright (org-on-heading-p)]
23587 ["Previous keyword" org-shiftleft (org-on-heading-p)]
23588 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
23589 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
23590 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
23591 ["Show TODO Tree" org-show-todo-tree t]
23592 ["Global TODO list" org-todo-list t]
23593 "--"
23594 ["Set Priority" org-priority t]
23595 ["Priority Up" org-shiftup t]
23596 ["Priority Down" org-shiftdown t])
23597 ("TAGS and Properties"
23598 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
23599 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)] ;FIXME
23600 ["Column view of properties" org-columns t])
23601 ("Dates and Scheduling"
23602 ["Timestamp" org-time-stamp t]
23603 ["Timestamp (inactive)" org-time-stamp-inactive t]
23604 ("Change Date"
23605 ["1 Day Later" org-shiftright t]
23606 ["1 Day Earlier" org-shiftleft t]
23607 ["1 ... Later" org-shiftup t]
23608 ["1 ... Earlier" org-shiftdown t])
23609 ["Compute Time Range" org-evaluate-time-range t]
23610 ["Schedule Item" org-schedule t]
23611 ["Deadline" org-deadline t]
23612 "--"
23613 ["Custom time format" org-toggle-time-stamp-overlays
23614 :style radio :selected org-display-custom-times]
23615 "--"
23616 ["Goto Calendar" org-goto-calendar t]
23617 ["Date from Calendar" org-date-from-calendar t])
23618 ("Logging work"
23619 ["Clock in" org-clock-in t]
23620 ["Clock out" org-clock-out t]
23621 ["Clock cancel" org-clock-cancel t]
23622 ["Display times" org-clock-display t]
23623 ["Create clock table" org-clock-report t]
23624 "--"
23625 ["Record DONE time"
23626 (progn (setq org-log-done (not org-log-done))
23627 (message "Switching to %s will %s record a timestamp"
23628 (car org-done-keywords)
23629 (if org-log-done "automatically" "not")))
23630 :style toggle :selected org-log-done])
23631 "--"
23632 ["Agenda Command..." org-agenda t]
23633 ("File List for Agenda")
23634 ("Special views current file"
23635 ["TODO Tree" org-show-todo-tree t]
23636 ["Check Deadlines" org-check-deadlines t]
23637 ["Timeline" org-timeline t]
23638 ["Tags Tree" org-tags-sparse-tree t])
23639 "--"
23640 ("Hyperlinks"
23641 ["Store Link (Global)" org-store-link t]
23642 ["Insert Link" org-insert-link t]
23643 ["Follow Link" org-open-at-point t]
23644 "--"
23645 ["Next link" org-next-link t]
23646 ["Previous link" org-previous-link t]
23647 "--"
23648 ["Descriptive Links"
23649 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
23650 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
23651 ["Literal Links"
23652 (progn
23653 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
23654 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
23655 "--"
23656 ["Export/Publish..." org-export t]
23657 ("LaTeX"
23658 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
23659 :selected org-cdlatex-mode]
23660 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
23661 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
23662 ["Modify math symbol" org-cdlatex-math-modify
23663 (org-inside-LaTeX-fragment-p)]
23664 ["Export LaTeX fragments as images"
23665 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
23666 :style toggle :selected org-export-with-LaTeX-fragments])
23667 "--"
23668 ("Documentation"
23669 ["Show Version" org-version t]
23670 ["Info Documentation" org-info t])
23671 ("Customize"
23672 ["Browse Org Group" org-customize t]
23673 "--"
23674 ["Expand This Menu" org-create-customize-menu
23675 (fboundp 'customize-menu-create)])
23676 "--"
23677 ["Refresh setup" org-mode-restart t]
23680 (defun org-info (&optional node)
23681 "Read documentation for Org-mode in the info system.
23682 With optional NODE, go directly to that node."
23683 (interactive)
23684 (require 'info)
23685 (Info-goto-node (format "(org)%s" (or node ""))))
23687 (defun org-install-agenda-files-menu ()
23688 (let ((bl (buffer-list)))
23689 (save-excursion
23690 (while bl
23691 (set-buffer (pop bl))
23692 (if (org-mode-p) (setq bl nil)))
23693 (when (org-mode-p)
23694 (easy-menu-change
23695 '("Org") "File List for Agenda"
23696 (append
23697 (list
23698 ["Edit File List" (org-edit-agenda-file-list) t]
23699 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
23700 ["Remove Current File from List" org-remove-file t]
23701 ["Cycle through agenda files" org-cycle-agenda-files t]
23702 "--")
23703 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
23705 ;;;; Documentation
23707 (defun org-customize ()
23708 "Call the customize function with org as argument."
23709 (interactive)
23710 (customize-browse 'org))
23712 (defun org-create-customize-menu ()
23713 "Create a full customization menu for Org-mode, insert it into the menu."
23714 (interactive)
23715 (if (fboundp 'customize-menu-create)
23716 (progn
23717 (easy-menu-change
23718 '("Org") "Customize"
23719 `(["Browse Org group" org-customize t]
23720 "--"
23721 ,(customize-menu-create 'org)
23722 ["Set" Custom-set t]
23723 ["Save" Custom-save t]
23724 ["Reset to Current" Custom-reset-current t]
23725 ["Reset to Saved" Custom-reset-saved t]
23726 ["Reset to Standard Settings" Custom-reset-standard t]))
23727 (message "\"Org\"-menu now contains full customization menu"))
23728 (error "Cannot expand menu (outdated version of cus-edit.el)")))
23730 ;;;; Miscellaneous stuff
23733 ;;; Generally useful functions
23735 (defun org-context ()
23736 "Return a list of contexts of the current cursor position.
23737 If several contexts apply, all are returned.
23738 Each context entry is a list with a symbol naming the context, and
23739 two positions indicating start and end of the context. Possible
23740 contexts are:
23742 :headline anywhere in a headline
23743 :headline-stars on the leading stars in a headline
23744 :todo-keyword on a TODO keyword (including DONE) in a headline
23745 :tags on the TAGS in a headline
23746 :priority on the priority cookie in a headline
23747 :item on the first line of a plain list item
23748 :item-bullet on the bullet/number of a plain list item
23749 :checkbox on the checkbox in a plain list item
23750 :table in an org-mode table
23751 :table-special on a special filed in a table
23752 :table-table in a table.el table
23753 :link on a hyperlink
23754 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
23755 :target on a <<target>>
23756 :radio-target on a <<<radio-target>>>
23757 :latex-fragment on a LaTeX fragment
23758 :latex-preview on a LaTeX fragment with overlayed preview image
23760 This function expects the position to be visible because it uses font-lock
23761 faces as a help to recognize the following contexts: :table-special, :link,
23762 and :keyword."
23763 (let* ((f (get-text-property (point) 'face))
23764 (faces (if (listp f) f (list f)))
23765 (p (point)) clist o)
23766 ;; First the large context
23767 (cond
23768 ((org-on-heading-p t)
23769 (push (list :headline (point-at-bol) (point-at-eol)) clist)
23770 (when (progn
23771 (beginning-of-line 1)
23772 (looking-at org-todo-line-tags-regexp))
23773 (push (org-point-in-group p 1 :headline-stars) clist)
23774 (push (org-point-in-group p 2 :todo-keyword) clist)
23775 (push (org-point-in-group p 4 :tags) clist))
23776 (goto-char p)
23777 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
23778 (if (looking-at "\\[#[A-Z0-9]\\]")
23779 (push (org-point-in-group p 0 :priority) clist)))
23781 ((org-at-item-p)
23782 (push (org-point-in-group p 2 :item-bullet) clist)
23783 (push (list :item (point-at-bol)
23784 (save-excursion (org-end-of-item) (point)))
23785 clist)
23786 (and (org-at-item-checkbox-p)
23787 (push (org-point-in-group p 0 :checkbox) clist)))
23789 ((org-at-table-p)
23790 (push (list :table (org-table-begin) (org-table-end)) clist)
23791 (if (memq 'org-formula faces)
23792 (push (list :table-special
23793 (previous-single-property-change p 'face)
23794 (next-single-property-change p 'face)) clist)))
23795 ((org-at-table-p 'any)
23796 (push (list :table-table) clist)))
23797 (goto-char p)
23799 ;; Now the small context
23800 (cond
23801 ((org-at-timestamp-p)
23802 (push (org-point-in-group p 0 :timestamp) clist))
23803 ((memq 'org-link faces)
23804 (push (list :link
23805 (previous-single-property-change p 'face)
23806 (next-single-property-change p 'face)) clist))
23807 ((memq 'org-special-keyword faces)
23808 (push (list :keyword
23809 (previous-single-property-change p 'face)
23810 (next-single-property-change p 'face)) clist))
23811 ((org-on-target-p)
23812 (push (org-point-in-group p 0 :target) clist)
23813 (goto-char (1- (match-beginning 0)))
23814 (if (looking-at org-radio-target-regexp)
23815 (push (org-point-in-group p 0 :radio-target) clist))
23816 (goto-char p))
23817 ((setq o (car (delq nil
23818 (mapcar
23819 (lambda (x)
23820 (if (memq x org-latex-fragment-image-overlays) x))
23821 (org-overlays-at (point))))))
23822 (push (list :latex-fragment
23823 (org-overlay-start o) (org-overlay-end o)) clist)
23824 (push (list :latex-preview
23825 (org-overlay-start o) (org-overlay-end o)) clist))
23826 ((org-inside-LaTeX-fragment-p)
23827 ;; FIXME: positions wrong.
23828 (push (list :latex-fragment (point) (point)) clist)))
23830 (setq clist (nreverse (delq nil clist)))
23831 clist))
23833 ;; FIXME Compare with at-regexp-p
23834 (defun org-in-regexp (re &optional nlines visually)
23835 "Check if point is inside a match of regexp.
23836 Normally only the current line is checked, but you can include NLINES extra
23837 lines both before and after point into the search.
23838 If VISUALLY is set, require that the cursor is not after the match but
23839 really on, so that the block visually is on the match."
23840 (catch 'exit
23841 (let ((pos (point))
23842 (eol (point-at-eol (+ 1 (or nlines 0))))
23843 (inc (if visually 1 0)))
23844 (save-excursion
23845 (beginning-of-line (- 1 (or nlines 0)))
23846 (while (re-search-forward re eol t)
23847 (if (and (<= (match-beginning 0) pos)
23848 (>= (+ inc (match-end 0)) pos))
23849 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
23851 (defun org-at-regexp-p (regexp)
23852 "Is point inside a match of REGEXP in the current line?"
23853 (catch 'exit
23854 (save-excursion
23855 (let ((pos (point)) (end (point-at-eol)))
23856 (beginning-of-line 1)
23857 (while (re-search-forward regexp end t)
23858 (if (and (<= (match-beginning 0) pos)
23859 (>= (match-end 0) pos))
23860 (throw 'exit t)))
23861 nil))))
23863 (defun org-uniquify (list)
23864 "Remove duplicate elements from LIST."
23865 (let (res)
23866 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
23867 res))
23869 (defun org-delete-all (elts list)
23870 "Remove all elements in ELTS from LIST."
23871 (while elts
23872 (setq list (delete (pop elts) list)))
23873 list)
23875 (defun org-point-in-group (point group &optional context)
23876 "Check if POINT is in match-group GROUP.
23877 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
23878 match. If the match group does ot exist or point is not inside it,
23879 return nil."
23880 (and (match-beginning group)
23881 (>= point (match-beginning group))
23882 (<= point (match-end group))
23883 (if context
23884 (list context (match-beginning group) (match-end group))
23885 t)))
23887 (defun org-combine-plists (&rest plists)
23888 "Create a single property list from all plists in PLISTS.
23889 The process starts by copying the first list, and then setting properties
23890 from the other lists. Settings in the last list are the most significant
23891 ones and overrule settings in the other lists."
23892 (let ((rtn (copy-sequence (pop plists)))
23893 p v ls)
23894 (while plists
23895 (setq ls (pop plists))
23896 (while ls
23897 (setq p (pop ls) v (pop ls))
23898 (setq rtn (plist-put rtn p v))))
23899 rtn))
23901 (defun org-move-line-down (arg)
23902 "Move the current line down. With prefix argument, move it past ARG lines."
23903 (interactive "p")
23904 (let ((col (current-column))
23905 beg end pos)
23906 (beginning-of-line 1) (setq beg (point))
23907 (beginning-of-line 2) (setq end (point))
23908 (beginning-of-line (+ 1 arg))
23909 (setq pos (move-marker (make-marker) (point)))
23910 (insert (delete-and-extract-region beg end))
23911 (goto-char pos)
23912 (move-to-column col)))
23914 (defun org-move-line-up (arg)
23915 "Move the current line up. With prefix argument, move it past ARG lines."
23916 (interactive "p")
23917 (let ((col (current-column))
23918 beg end pos)
23919 (beginning-of-line 1) (setq beg (point))
23920 (beginning-of-line 2) (setq end (point))
23921 (beginning-of-line (- arg))
23922 (setq pos (move-marker (make-marker) (point)))
23923 (insert (delete-and-extract-region beg end))
23924 (goto-char pos)
23925 (move-to-column col)))
23927 (defun org-replace-escapes (string table)
23928 "Replace %-escapes in STRING with values in TABLE.
23929 TABLE is an association list with keys line \"%a\" and string values.
23930 The sequences in STRING may contain normal field width and padding information,
23931 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
23932 so values can contain further %-escapes if they are define later in TABLE."
23933 (let ((case-fold-search nil)
23934 e re rpl)
23935 (while (setq e (pop table))
23936 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
23937 (while (string-match re string)
23938 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
23939 (cdr e)))
23940 (setq string (replace-match rpl t t string))))
23941 string))
23944 (defun org-sublist (list start end)
23945 "Return a section of LIST, from START to END.
23946 Counting starts at 1."
23947 (let (rtn (c start))
23948 (setq list (nthcdr (1- start) list))
23949 (while (and list (<= c end))
23950 (push (pop list) rtn)
23951 (setq c (1+ c)))
23952 (nreverse rtn)))
23954 (defun org-find-base-buffer-visiting (file)
23955 "Like `find-buffer-visiting' but alway return the base buffer and
23956 not an indirect buffer"
23957 (let ((buf (find-buffer-visiting file)))
23958 (or (buffer-base-buffer buf) buf)))
23960 (defun org-image-file-name-regexp ()
23961 "Return regexp matching the file names of images."
23962 (if (fboundp 'image-file-name-regexp)
23963 (image-file-name-regexp)
23964 (let ((image-file-name-extensions
23965 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
23966 "xbm" "xpm" "pbm" "pgm" "ppm")))
23967 (concat "\\."
23968 (regexp-opt (nconc (mapcar 'upcase
23969 image-file-name-extensions)
23970 image-file-name-extensions)
23972 "\\'"))))
23974 (defun org-file-image-p (file)
23975 "Return non-nil if FILE is an image."
23976 (save-match-data
23977 (string-match (org-image-file-name-regexp) file)))
23979 ;;; Paragraph filling stuff.
23980 ;; We want this to be just right, so use the full arsenal.
23982 (defun org-indent-line-function ()
23983 "Indent line like previous, but further if previous was headline or item."
23984 (interactive)
23985 (let* ((pos (point))
23986 (itemp (org-at-item-p))
23987 column bpos bcol tpos tcol bullet btype bullet-type)
23988 ;; Find the previous relevant line
23989 (beginning-of-line 1)
23990 (cond
23991 ((looking-at "#") (setq column 0))
23992 ((looking-at "\\*+ ") (setq column 0))
23994 (beginning-of-line 0)
23995 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
23996 (beginning-of-line 0))
23997 (cond
23998 ((looking-at "\\*+[ \t]+")
23999 (goto-char (match-end 0))
24000 (setq column (current-column)))
24001 ((org-in-item-p)
24002 (org-beginning-of-item)
24003 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
24004 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
24005 (setq bpos (match-beginning 1) tpos (match-end 0)
24006 bcol (progn (goto-char bpos) (current-column))
24007 tcol (progn (goto-char tpos) (current-column))
24008 bullet (match-string 1)
24009 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
24010 (if (not itemp)
24011 (setq column tcol)
24012 (goto-char pos)
24013 (beginning-of-line 1)
24014 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
24015 (setq bullet (match-string 1)
24016 btype (if (string-match "[0-9]" bullet) "n" bullet))
24017 (setq column (if (equal btype bullet-type) bcol tcol))))
24018 (t (setq column (org-get-indentation))))))
24019 (goto-char pos)
24020 (if (<= (current-column) (current-indentation))
24021 (indent-line-to column)
24022 (save-excursion (indent-line-to column)))
24023 (setq column (current-column))
24024 (beginning-of-line 1)
24025 (if (looking-at
24026 "\\([ \t]+\\)\\(:[0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
24027 (replace-match (concat "\\1" (format org-property-format
24028 (match-string 2) (match-string 3)))
24029 t nil))
24030 (move-to-column column)))
24032 (defun org-set-autofill-regexps ()
24033 (interactive)
24034 ;; In the paragraph separator we include headlines, because filling
24035 ;; text in a line directly attached to a headline would otherwise
24036 ;; fill the headline as well.
24037 (org-set-local 'comment-start-skip "^#+[ \t]*")
24038 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
24039 ;; FIXME!!!!!!! (org-set-local 'paragraph-separate "\f\\|[ ]*$")
24040 ;; The paragraph starter includes hand-formatted lists.
24041 (org-set-local 'paragraph-start
24042 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
24043 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
24044 ;; But only if the user has not turned off tables or fixed-width regions
24045 (org-set-local
24046 'auto-fill-inhibit-regexp
24047 (concat "\\*+ \\|#\\+"
24048 "\\|[ \t]*" org-keyword-time-regexp
24049 (if (or org-enable-table-editor org-enable-fixed-width-editor)
24050 (concat
24051 "\\|[ \t]*["
24052 (if org-enable-table-editor "|" "")
24053 (if org-enable-fixed-width-editor ":" "")
24054 "]"))))
24055 ;; We use our own fill-paragraph function, to make sure that tables
24056 ;; and fixed-width regions are not wrapped. That function will pass
24057 ;; through to `fill-paragraph' when appropriate.
24058 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
24059 ; Adaptive filling: To get full control, first make sure that
24060 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
24061 (org-set-local 'adaptive-fill-regexp "\000")
24062 (org-set-local 'adaptive-fill-function
24063 'org-adaptive-fill-function))
24065 (defun org-fill-paragraph (&optional justify)
24066 "Re-align a table, pass through to fill-paragraph if no table."
24067 (let ((table-p (org-at-table-p))
24068 (table.el-p (org-at-table.el-p)))
24069 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
24070 (table.el-p t) ; skip table.el tables
24071 (table-p (org-table-align) t) ; align org-mode tables
24072 (t nil)))) ; call paragraph-fill
24074 ;; For reference, this is the default value of adaptive-fill-regexp
24075 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
24077 (defun org-adaptive-fill-function ()
24078 "Return a fill prefix for org-mode files.
24079 In particular, this makes sure hanging paragraphs for hand-formatted lists
24080 work correctly."
24081 (cond ((looking-at "#[ \t]+")
24082 (match-string 0))
24083 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
24084 (save-excursion
24085 (goto-char (match-end 0))
24086 (make-string (current-column) ?\ )))
24087 (t nil)))
24089 ;;;; Functions extending outline functionality
24091 (defun org-beginning-of-line (&optional arg)
24092 "Go to the beginning of the current line. If that is invisible, continue
24093 to a visible line beginning. This makes the function of C-a more intuitive.
24094 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
24095 first attempt, and only move to after the tags when the cursor is already
24096 beyond the end of the headline."
24097 (interactive "P")
24098 (let ((pos (point)))
24099 (beginning-of-line 1)
24100 (if (bobp)
24102 (backward-char 1)
24103 (if (org-invisible-p)
24104 (while (and (not (bobp)) (org-invisible-p))
24105 (backward-char 1)
24106 (beginning-of-line 1))
24107 (forward-char 1)))
24108 (when org-special-ctrl-a/e
24109 (cond
24110 ((and (looking-at org-todo-line-regexp)
24111 (= (char-after (match-end 1)) ?\ ))
24112 (goto-char
24113 (if (eq org-special-ctrl-a/e t)
24114 (cond ((> pos (match-beginning 3)) (match-beginning 3))
24115 ((= pos (point)) (match-beginning 3))
24116 (t (point)))
24117 (cond ((> pos (point)) (point))
24118 ((not (eq last-command this-command)) (point))
24119 (t (match-beginning 3))))))
24120 ((org-at-item-p)
24121 (goto-char
24122 (if (eq org-special-ctrl-a/e t)
24123 (cond ((> pos (match-end 4)) (match-end 4))
24124 ((= pos (point)) (match-end 4))
24125 (t (point)))
24126 (cond ((> pos (point)) (point))
24127 ((not (eq last-command this-command)) (point))
24128 (t (match-end 4))))))))))
24130 (defun org-end-of-line (&optional arg)
24131 "Go to the end of the line.
24132 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
24133 first attempt, and only move to after the tags when the cursor is already
24134 beyond the end of the headline."
24135 (interactive "P")
24136 (if (or (not org-special-ctrl-a/e)
24137 (not (org-on-heading-p)))
24138 (end-of-line arg)
24139 (let ((pos (point)))
24140 (beginning-of-line 1)
24141 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
24142 (if (eq org-special-ctrl-a/e t)
24143 (if (or (< pos (match-beginning 1))
24144 (= pos (match-end 0)))
24145 (goto-char (match-beginning 1))
24146 (goto-char (match-end 0)))
24147 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
24148 (goto-char (match-end 0))
24149 (goto-char (match-beginning 1))))
24150 (end-of-line arg)))))
24152 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
24153 (define-key org-mode-map "\C-e" 'org-end-of-line)
24155 (defun org-invisible-p ()
24156 "Check if point is at a character currently not visible."
24157 ;; Early versions of noutline don't have `outline-invisible-p'.
24158 (if (fboundp 'outline-invisible-p)
24159 (outline-invisible-p)
24160 (get-char-property (point) 'invisible)))
24162 (defun org-invisible-p2 ()
24163 "Check if point is at a character currently not visible."
24164 (save-excursion
24165 (if (and (eolp) (not (bobp))) (backward-char 1))
24166 ;; Early versions of noutline don't have `outline-invisible-p'.
24167 (if (fboundp 'outline-invisible-p)
24168 (outline-invisible-p)
24169 (get-char-property (point) 'invisible))))
24171 (defalias 'org-back-to-heading 'outline-back-to-heading)
24172 (defalias 'org-on-heading-p 'outline-on-heading-p)
24173 (defalias 'org-at-heading-p 'outline-on-heading-p)
24174 (defun org-at-heading-or-item-p ()
24175 (or (org-on-heading-p) (org-at-item-p)))
24177 (defun org-on-target-p ()
24178 (or (org-in-regexp org-radio-target-regexp)
24179 (org-in-regexp org-target-regexp)))
24181 (defun org-up-heading-all (arg)
24182 "Move to the heading line of which the present line is a subheading.
24183 This function considers both visible and invisible heading lines.
24184 With argument, move up ARG levels."
24185 (if (fboundp 'outline-up-heading-all)
24186 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24187 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24189 (defun org-goto-sibling (&optional previous)
24190 "Goto the next sibling, even if it is invisible.
24191 When PREVIOUS is set, go to the previous sibling instead. Returns t
24192 when a sibling was found. When none is found, return nil and don't
24193 move point."
24194 (let ((fun (if previous 're-search-backward 're-search-forward))
24195 (pos (point))
24196 (re (concat "^" outline-regexp))
24197 level l)
24198 (when (condition-case nil (org-back-to-heading t) (error nil))
24199 (setq level (funcall outline-level))
24200 (catch 'exit
24201 (or previous (forward-char 1))
24202 (while (funcall fun re nil t)
24203 (setq l (funcall outline-level))
24204 (when (< l level) (goto-char pos) (throw 'exit nil))
24205 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24206 (goto-char pos)
24207 nil))))
24209 (defun org-show-siblings ()
24210 "Show all siblings of the current headline."
24211 (save-excursion
24212 (while (org-goto-sibling) (org-flag-heading nil)))
24213 (save-excursion
24214 (while (org-goto-sibling 'previous)
24215 (org-flag-heading nil))))
24217 (defun org-show-hidden-entry ()
24218 "Show an entry where even the heading is hidden."
24219 (save-excursion
24220 (org-show-entry)))
24222 (defun org-flag-heading (flag &optional entry)
24223 "Flag the current heading. FLAG non-nil means make invisible.
24224 When ENTRY is non-nil, show the entire entry."
24225 (save-excursion
24226 (org-back-to-heading t)
24227 ;; Check if we should show the entire entry
24228 (if entry
24229 (progn
24230 (org-show-entry)
24231 (save-excursion
24232 (and (outline-next-heading)
24233 (org-flag-heading nil))))
24234 (outline-flag-region (max (point-min) (1- (point)))
24235 (save-excursion (outline-end-of-heading) (point))
24236 flag))))
24238 (defun org-end-of-subtree (&optional invisible-OK to-heading)
24239 ;; This is an exact copy of the original function, but it uses
24240 ;; `org-back-to-heading', to make it work also in invisible
24241 ;; trees. And is uses an invisible-OK argument.
24242 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24243 (org-back-to-heading invisible-OK)
24244 (let ((first t)
24245 (level (funcall outline-level)))
24246 (while (and (not (eobp))
24247 (or first (> (funcall outline-level) level)))
24248 (setq first nil)
24249 (outline-next-heading))
24250 (unless to-heading
24251 (if (memq (preceding-char) '(?\n ?\^M))
24252 (progn
24253 ;; Go to end of line before heading
24254 (forward-char -1)
24255 (if (memq (preceding-char) '(?\n ?\^M))
24256 ;; leave blank line before heading
24257 (forward-char -1))))))
24258 (point))
24260 (defun org-show-subtree ()
24261 "Show everything after this heading at deeper levels."
24262 (outline-flag-region
24263 (point)
24264 (save-excursion
24265 (outline-end-of-subtree) (outline-next-heading) (point))
24266 nil))
24268 (defun org-show-entry ()
24269 "Show the body directly following this heading.
24270 Show the heading too, if it is currently invisible."
24271 (interactive)
24272 (save-excursion
24273 (org-back-to-heading t)
24274 (outline-flag-region
24275 (max (point-min) (1- (point)))
24276 (save-excursion
24277 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
24278 (or (match-beginning 1) (point-max)))
24279 nil)))
24281 (defun org-make-options-regexp (kwds)
24282 "Make a regular expression for keyword lines."
24283 (concat
24285 "#?[ \t]*\\+\\("
24286 (mapconcat 'regexp-quote kwds "\\|")
24287 "\\):[ \t]*"
24288 "\\(.+\\)"))
24290 ;; Make isearch reveal the necessary context
24291 (defun org-isearch-end ()
24292 "Reveal context after isearch exits."
24293 (when isearch-success ; only if search was successful
24294 (if (featurep 'xemacs)
24295 ;; Under XEmacs, the hook is run in the correct place,
24296 ;; we directly show the context.
24297 (org-show-context 'isearch)
24298 ;; In Emacs the hook runs *before* restoring the overlays.
24299 ;; So we have to use a one-time post-command-hook to do this.
24300 ;; (Emacs 22 has a special variable, see function `org-mode')
24301 (unless (and (boundp 'isearch-mode-end-hook-quit)
24302 isearch-mode-end-hook-quit)
24303 ;; Only when the isearch was not quitted.
24304 (org-add-hook 'post-command-hook 'org-isearch-post-command
24305 'append 'local)))))
24307 (defun org-isearch-post-command ()
24308 "Remove self from hook, and show context."
24309 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24310 (org-show-context 'isearch))
24313 ;;;; Address problems with some other packages
24315 ;; Make flyspell not check words in links, to not mess up our keymap
24316 (defun org-mode-flyspell-verify ()
24317 "Don't let flyspell put overlays at active buttons."
24318 (not (get-text-property (point) 'keymap)))
24320 ;; Make `bookmark-jump' show the jump location if it was hidden.
24321 (eval-after-load "bookmark"
24322 '(if (boundp 'bookmark-after-jump-hook)
24323 ;; We can use the hook
24324 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24325 ;; Hook not available, use advice
24326 (defadvice bookmark-jump (after org-make-visible activate)
24327 "Make the position visible."
24328 (org-bookmark-jump-unhide))))
24330 (defun org-bookmark-jump-unhide ()
24331 "Unhide the current position, to show the bookmark location."
24332 (and (org-mode-p)
24333 (or (org-invisible-p)
24334 (save-excursion (goto-char (max (point-min) (1- (point))))
24335 (org-invisible-p)))
24336 (org-show-context 'bookmark-jump)))
24338 ;; Make session.el ignore our circular variable
24339 (eval-after-load "session"
24340 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24342 ;;;; Experimental code
24344 ;; Make appt aware of appointments from the agenda
24345 (defun org-agenda-to-appt ()
24346 "Activate appointments found in `org-agenda-files'."
24347 (interactive)
24348 (require 'org)
24349 (let* ((today (org-date-to-gregorian
24350 (time-to-days (current-time))))
24351 (files org-agenda-files) entries file)
24352 (while (setq file (pop files))
24353 (setq entries (append entries (org-agenda-get-day-entries
24354 file today :timestamp))))
24355 (setq entries (delq nil entries))
24356 (mapc (lambda(x)
24357 (let* ((event (org-trim (get-text-property 1 'txt x)))
24358 (time-of-day (get-text-property 1 'time-of-day x)) tod)
24359 (when time-of-day
24360 (setq tod (number-to-string time-of-day)
24361 tod (when (string-match
24362 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
24363 (concat (match-string 1 tod) ":"
24364 (match-string 2 tod))))
24365 (if tod (appt-add tod event))))) entries)))
24367 (defun org-closed-in-range ()
24368 "Sparse tree of items closed in a certain time range.
24369 Still experimental, may disappear in the furture."
24370 (interactive)
24371 ;; Get the time interval from the user.
24372 (let* ((time1 (time-to-seconds
24373 (org-read-date nil 'to-time nil "Starting date: ")))
24374 (time2 (time-to-seconds
24375 (org-read-date nil 'to-time nil "End date:")))
24376 ;; callback function
24377 (callback (lambda ()
24378 (let ((time
24379 (time-to-seconds
24380 (apply 'encode-time
24381 (org-parse-time-string
24382 (match-string 1))))))
24383 ;; check if time in interval
24384 (and (>= time time1) (<= time time2))))))
24385 ;; make tree, check each match with the callback
24386 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
24388 (defun org-fill-paragraph-experimental (&optional justify)
24389 "Re-align a table, pass through to fill-paragraph if no table."
24390 (let ((table-p (org-at-table-p))
24391 (table.el-p (org-at-table.el-p)))
24392 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
24393 (table.el-p t) ; skip table.el tables
24394 (table-p (org-table-align) t) ; align org-mode tables
24395 ((save-excursion
24396 (let ((pos (1+ (point-at-eol))))
24397 (backward-paragraph 1)
24398 (re-search-forward "\\\\\\\\[ \t]*$" pos t)))
24399 (save-excursion
24400 (save-restriction
24401 (narrow-to-region (1+ (match-end 0)) (point-max))
24402 (fill-paragraph nil)
24403 t)))
24404 (t nil)))) ; call paragraph-fill
24406 (defun org-get-min-level (lines)
24407 (let ((re "^\\(\\*+\\) ") l min)
24408 (catch 'exit
24409 (while (setq l (pop lines))
24410 (if (string-match re l)
24411 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24412 1)))
24414 ;;;; Finish up
24416 (provide 'org)
24418 (run-hooks 'org-load-hook)
24420 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
24421 ;;; org.el ends here