Release 5.06b
[org-mode/org-tableheadings.git] / org.el
blob763e7c4eca2a22d3305e4670160dd32c72749144
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.06b
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.06b"
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-undo-list)
3949 (defvar org-agenda-pending-undo-list)
3950 (defvar org-agenda-overriding-header)
3951 (defvar orgtbl-mode)
3952 (defvar org-html-entities)
3953 (defvar org-struct-menu)
3954 (defvar org-org-menu)
3955 (defvar org-tbl-menu)
3956 (defvar org-agenda-keymap)
3957 (defvar org-category-table)
3959 ;;;; Emacs/XEmacs compatibility
3961 ;; Overlay compatibility functions
3962 (defun org-make-overlay (beg end &optional buffer)
3963 (if (featurep 'xemacs)
3964 (make-extent beg end buffer)
3965 (make-overlay beg end buffer)))
3966 (defun org-delete-overlay (ovl)
3967 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
3968 (defun org-detach-overlay (ovl)
3969 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
3970 (defun org-move-overlay (ovl beg end &optional buffer)
3971 (if (featurep 'xemacs)
3972 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
3973 (move-overlay ovl beg end buffer)))
3974 (defun org-overlay-put (ovl prop value)
3975 (if (featurep 'xemacs)
3976 (set-extent-property ovl prop value)
3977 (overlay-put ovl prop value)))
3978 (defun org-overlay-display (ovl text &optional face evap)
3979 "Make overlay OVL display TEXT with face FACE."
3980 (if (featurep 'xemacs)
3981 (let ((gl (make-glyph text)))
3982 (and face (set-glyph-face gl face))
3983 (set-extent-property ovl 'invisible t)
3984 (set-extent-property ovl 'end-glyph gl))
3985 (overlay-put ovl 'display text)
3986 (if face (overlay-put ovl 'face face))
3987 (if evap (overlay-put ovl 'evaporate t))))
3988 (defun org-overlay-before-string (ovl text &optional face evap)
3989 "Make overlay OVL display TEXT with face FACE."
3990 (if (featurep 'xemacs)
3991 (let ((gl (make-glyph text)))
3992 (and face (set-glyph-face gl face))
3993 (set-extent-property ovl 'begin-glyph gl))
3994 (if face (org-add-props text nil 'face face))
3995 (overlay-put ovl 'before-string text)
3996 (if evap (overlay-put ovl 'evaporate t))))
3997 (defun org-overlay-get (ovl prop)
3998 (if (featurep 'xemacs)
3999 (extent-property ovl prop)
4000 (overlay-get ovl prop)))
4001 (defun org-overlays-at (pos)
4002 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4003 ;; FIXME: this is currently not used
4004 (defun org-overlays-in (&optional start end)
4005 (if (featurep 'xemacs)
4006 (extent-list nil start end)
4007 (overlays-in start end)))
4008 (defun org-overlay-start (o)
4009 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4010 (defun org-overlay-end (o)
4011 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4012 ;; FIXME: this is currently not used
4013 (defun org-find-overlays (prop &optional pos delete)
4014 "Find all overlays specifying PROP at POS or point.
4015 If DELETE is non-nil, delete all those overlays."
4016 (let ((overlays (org-overlays-at (or pos (point))))
4017 ov found)
4018 (while (setq ov (pop overlays))
4019 (if (org-overlay-get ov prop)
4020 (if delete (org-delete-overlay ov) (push ov found))))
4021 found))
4023 ;; Region compatibility
4025 (defun org-add-hook (hook function &optional append local)
4026 "Add-hook, compatible with both Emacsen."
4027 (if (and local (featurep 'xemacs))
4028 (add-local-hook hook function append)
4029 (add-hook hook function append local)))
4031 (defvar org-ignore-region nil
4032 "To temporarily disable the active region.")
4034 (defun org-region-active-p ()
4035 "Is `transient-mark-mode' on and the region active?
4036 Works on both Emacs and XEmacs."
4037 (if org-ignore-region
4039 (if (featurep 'xemacs)
4040 (and zmacs-regions (region-active-p))
4041 (and transient-mark-mode mark-active))))
4043 ;; Invisibility compatibility
4045 (defun org-add-to-invisibility-spec (arg)
4046 "Add elements to `buffer-invisibility-spec'.
4047 See documentation for `buffer-invisibility-spec' for the kind of elements
4048 that can be added."
4049 (cond
4050 ((fboundp 'add-to-invisibility-spec)
4051 (add-to-invisibility-spec arg))
4052 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4053 (setq buffer-invisibility-spec (list arg)))
4055 (setq buffer-invisibility-spec
4056 (cons arg buffer-invisibility-spec)))))
4058 (defun org-remove-from-invisibility-spec (arg)
4059 "Remove elements from `buffer-invisibility-spec'."
4060 (if (fboundp 'remove-from-invisibility-spec)
4061 (remove-from-invisibility-spec arg)
4062 (if (consp buffer-invisibility-spec)
4063 (setq buffer-invisibility-spec
4064 (delete arg buffer-invisibility-spec)))))
4066 ;; FIXME: this is currently not used
4067 (defun org-in-invisibility-spec-p (arg)
4068 "Is ARG a member of `buffer-invisibility-spec'?"
4069 (if (consp buffer-invisibility-spec)
4070 (member arg buffer-invisibility-spec)
4071 nil))
4073 ;;;; Define the Org-mode
4075 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4076 (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."))
4079 ;; We use a before-change function to check if a table might need
4080 ;; an update.
4081 (defvar org-table-may-need-update t
4082 "Indicates that a table might need an update.
4083 This variable is set by `org-before-change-function'.
4084 `org-table-align' sets it back to nil.")
4085 (defvar org-mode-map)
4086 (defvar org-mode-hook nil)
4087 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4088 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4089 (defvar org-table-buffer-is-an nil)
4092 ;;;###autoload
4093 (define-derived-mode org-mode outline-mode "Org"
4094 "Outline-based notes management and organizer, alias
4095 \"Carsten's outline-mode for keeping track of everything.\"
4097 Org-mode develops organizational tasks around a NOTES file which
4098 contains information about projects as plain text. Org-mode is
4099 implemented on top of outline-mode, which is ideal to keep the content
4100 of large files well structured. It supports ToDo items, deadlines and
4101 time stamps, which magically appear in the diary listing of the Emacs
4102 calendar. Tables are easily created with a built-in table editor.
4103 Plain text URL-like links connect to websites, emails (VM), Usenet
4104 messages (Gnus), BBDB entries, and any files related to the project.
4105 For printing and sharing of notes, an Org-mode file (or a part of it)
4106 can be exported as a structured ASCII or HTML file.
4108 The following commands are available:
4110 \\{org-mode-map}"
4112 ;; Get rid of Outline menus, they are not needed
4113 ;; Need to do this here because define-derived-mode sets up
4114 ;; the keymap so late. Still, it is a waste to call this each time
4115 ;; we switch another buffer into org-mode.
4116 (if (featurep 'xemacs)
4117 (when (boundp 'outline-mode-menu-heading)
4118 ;; Assume this is Greg's port, it used easymenu
4119 (easy-menu-remove outline-mode-menu-heading)
4120 (easy-menu-remove outline-mode-menu-show)
4121 (easy-menu-remove outline-mode-menu-hide))
4122 (define-key org-mode-map [menu-bar headings] 'undefined)
4123 (define-key org-mode-map [menu-bar hide] 'undefined)
4124 (define-key org-mode-map [menu-bar show] 'undefined))
4126 (easy-menu-add org-org-menu)
4127 (easy-menu-add org-tbl-menu)
4128 (org-install-agenda-files-menu)
4129 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4130 (org-add-to-invisibility-spec '(org-cwidth))
4131 (when (featurep 'xemacs)
4132 (org-set-local 'line-move-ignore-invisible t))
4133 (org-set-local 'outline-regexp "\\*+ ")
4134 (setq outline-level 'org-outline-level)
4135 (when (and org-ellipsis (stringp org-ellipsis)
4136 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table))
4137 (unless org-display-table
4138 (setq org-display-table (make-display-table)))
4139 (set-display-table-slot org-display-table
4140 4 (string-to-vector org-ellipsis))
4141 (setq buffer-display-table org-display-table))
4142 (org-set-regexps-and-options)
4143 ;; Calc embedded
4144 (org-set-local 'calc-embedded-open-mode "# ")
4145 (modify-syntax-entry ?# "<")
4146 (modify-syntax-entry ?@ "w")
4147 (if org-startup-truncated (setq truncate-lines t))
4148 (org-set-local 'font-lock-unfontify-region-function
4149 'org-unfontify-region)
4150 ;; Activate before-change-function
4151 (org-set-local 'org-table-may-need-update t)
4152 (org-add-hook 'before-change-functions 'org-before-change-function nil
4153 'local)
4154 ;; Check for running clock before killing a buffer
4155 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4156 ;; Paragraphs and auto-filling
4157 (org-set-autofill-regexps)
4158 (setq indent-line-function 'org-indent-line-function)
4159 (org-update-radio-target-regexp)
4161 ;; Comment characters
4162 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4163 (org-set-local 'comment-padding " ")
4165 ;; Make isearch reveal context
4166 (if (or (featurep 'xemacs)
4167 (not (boundp 'outline-isearch-open-invisible-function)))
4168 ;; Emacs 21 and XEmacs make use of the hook
4169 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4170 ;; Emacs 22 deals with this through a special variable
4171 (org-set-local 'outline-isearch-open-invisible-function
4172 (lambda (&rest ignore) (org-show-context 'isearch))))
4174 ;; If empty file that did not turn on org-mode automatically, make it to.
4175 (if (and org-insert-mode-line-in-empty-file
4176 (interactive-p)
4177 (= (point-min) (point-max)))
4178 (insert "# -*- mode: org -*-\n\n"))
4180 (unless org-inhibit-startup
4181 (when org-startup-align-all-tables
4182 (let ((bmp (buffer-modified-p)))
4183 (org-table-map-tables 'org-table-align)
4184 (set-buffer-modified-p bmp)))
4185 (org-cycle-hide-drawers 'all)
4186 (cond
4187 ((eq org-startup-folded t)
4188 (org-cycle '(4)))
4189 ((eq org-startup-folded 'content)
4190 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4191 (org-cycle '(4)) (org-cycle '(4)))))))
4193 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4195 (defsubst org-call-with-arg (command arg)
4196 "Call COMMAND interactively, but pretend prefix are was ARG."
4197 (let ((current-prefix-arg arg)) (call-interactively command)))
4199 (defsubst org-current-line (&optional pos)
4200 (save-excursion
4201 (and pos (goto-char pos))
4202 ;; works also in narrowed buffer, because we start at 1, not point-min
4203 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4205 (defun org-current-time ()
4206 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4207 (if (> org-time-stamp-rounding-minutes 0)
4208 (let ((r org-time-stamp-rounding-minutes)
4209 (time (decode-time)))
4210 (apply 'encode-time
4211 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4212 (nthcdr 2 time))))
4213 (current-time)))
4215 (defun org-add-props (string plist &rest props)
4216 "Add text properties to entire string, from beginning to end.
4217 PLIST may be a list of properties, PROPS are individual properties and values
4218 that will be added to PLIST. Returns the string that was modified."
4219 (add-text-properties
4220 0 (length string) (if props (append plist props) plist) string)
4221 string)
4222 (put 'org-add-props 'lisp-indent-function 2)
4225 ;;;; Font-Lock stuff, including the activators
4227 (defvar org-mouse-map (make-sparse-keymap))
4228 (org-defkey org-mouse-map
4229 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4230 (org-defkey org-mouse-map
4231 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4232 (when org-mouse-1-follows-link
4233 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4234 (when org-tab-follows-link
4235 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4236 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4237 (when org-return-follows-link
4238 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4239 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4241 (require 'font-lock)
4243 (defconst org-non-link-chars "]\t\n\r<>")
4244 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4245 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4246 (defvar org-link-re-with-space nil
4247 "Matches a link with spaces, optional angular brackets around it.")
4248 (defvar org-link-re-with-space2 nil
4249 "Matches a link with spaces, optional angular brackets around it.")
4250 (defvar org-angle-link-re nil
4251 "Matches link with angular brackets, spaces are allowed.")
4252 (defvar org-plain-link-re nil
4253 "Matches plain link, without spaces.")
4254 (defvar org-bracket-link-regexp nil
4255 "Matches a link in double brackets.")
4256 (defvar org-bracket-link-analytic-regexp nil
4257 "Regular expression used to analyze links.
4258 Here is what the match groups contain after a match:
4259 1: http:
4260 2: http
4261 3: path
4262 4: [desc]
4263 5: desc")
4264 (defvar org-any-link-re nil
4265 "Regular expression matching any link.")
4267 (defun org-make-link-regexps ()
4268 "Update the link regular expressions.
4269 This should be called after the variable `org-link-types' has changed."
4270 (setq org-link-re-with-space
4271 (concat
4272 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4273 "\\([^" org-non-link-chars " ]"
4274 "[^" org-non-link-chars "]*"
4275 "[^" org-non-link-chars " ]\\)>?")
4276 org-link-re-with-space2
4277 (concat
4278 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4279 "\\([^" org-non-link-chars " ]"
4280 "[^]\t\n\r]*"
4281 "[^" org-non-link-chars " ]\\)>?")
4282 org-angle-link-re
4283 (concat
4284 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4285 "\\([^" org-non-link-chars " ]"
4286 "[^" org-non-link-chars "]*"
4287 "\\)>")
4288 org-plain-link-re
4289 (concat
4290 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4291 "\\([^]\t\n\r<>,;() ]+\\)")
4292 org-bracket-link-regexp
4293 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4294 org-bracket-link-analytic-regexp
4295 (concat
4296 "\\[\\["
4297 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4298 "\\([^]]+\\)"
4299 "\\]"
4300 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4301 "\\]")
4302 org-any-link-re
4303 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4304 org-angle-link-re "\\)\\|\\("
4305 org-plain-link-re "\\)")))
4307 (org-make-link-regexps)
4309 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4310 "Regular expression for fast time stamp matching.")
4311 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4312 "Regular expression for fast time stamp matching.")
4313 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4314 "Regular expression matching time strings for analysis.
4315 This one does not require the space after the date.")
4316 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4317 "Regular expression matching time strings for analysis.")
4318 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,11\\}>")
4319 "Regular expression matching time stamps, with groups.")
4320 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,11\\}[]>]")
4321 "Regular expression matching time stamps (also [..]), with groups.")
4322 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4323 "Regular expression matching a time stamp range.")
4324 (defconst org-tr-regexp-both
4325 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4326 "Regular expression matching a time stamp range.")
4327 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4328 org-ts-regexp "\\)?")
4329 "Regular expression matching a time stamp or time stamp range.")
4330 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4331 org-ts-regexp-both "\\)?")
4332 "Regular expression matching a time stamp or time stamp range.
4333 The time stamps may be either active or inactive.")
4335 (defvar org-emph-face nil)
4337 (defun org-do-emphasis-faces (limit)
4338 "Run through the buffer and add overlays to links."
4339 (let (rtn)
4340 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4341 (if (not (= (char-after (match-beginning 3))
4342 (char-after (match-beginning 4))))
4343 (progn
4344 (setq rtn t)
4345 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4346 'face
4347 (nth 1 (assoc (match-string 3)
4348 org-emphasis-alist)))
4349 (add-text-properties (match-beginning 2) (match-end 2)
4350 '(font-lock-multiline t))
4351 (backward-char 1))))
4352 rtn))
4354 (defun org-emphasize (&optional char)
4355 "Insert or change an emphasis, i.e. a font like bold or italic.
4356 If there is an active region, change that region to a new emphasis.
4357 If there is no region, just insert the marker characters and position
4358 the cursor between them.
4359 CHAR should be either the marker character, or the first character of the
4360 HTML tag associated with that emphasis. If CHAR is a space, the means
4361 to remove the emphasis of the selected region.
4362 If char is not given (for example in an interactive call) it
4363 will be prompted for."
4364 (interactive)
4365 (let ((eal org-emphasis-alist) e det
4366 (erc org-emphasis-regexp-components)
4367 (prompt "")
4368 (string "") beg end move tag c s)
4369 (if (org-region-active-p)
4370 (setq beg (region-beginning) end (region-end)
4371 string (buffer-substring beg end))
4372 (setq move t))
4374 (while (setq e (pop eal))
4375 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4376 c (aref tag 0))
4377 (push (cons c (string-to-char (car e))) det)
4378 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4379 (substring tag 1)))))
4380 (unless char
4381 (message "%s" (concat "Emphasis marker or tag:" prompt))
4382 (setq char (read-char-exclusive)))
4383 (setq char (or (cdr (assoc char det)) char))
4384 (if (equal char ?\ )
4385 (setq s "" move nil)
4386 (unless (assoc (char-to-string char) org-emphasis-alist)
4387 (error "No such emphasis marker: \"%c\"" char))
4388 (setq s (char-to-string char)))
4389 (while (and (> (length string) 1)
4390 (equal (substring string 0 1) (substring string -1))
4391 (assoc (substring string 0 1) org-emphasis-alist))
4392 (setq string (substring string 1 -1)))
4393 (setq string (concat s string s))
4394 (if beg (delete-region beg end))
4395 (unless (or (bolp)
4396 (string-match (concat "[" (nth 0 erc) "\n]")
4397 (char-to-string (char-before (point)))))
4398 (insert " "))
4399 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4400 (char-to-string (char-after (point))))
4401 (insert " ") (backward-char 1))
4402 (insert string)
4403 (and move (backward-char 1))))
4405 (defun org-activate-plain-links (limit)
4406 "Run through the buffer and add overlays to links."
4407 (catch 'exit
4408 (let (f)
4409 (while (re-search-forward org-plain-link-re limit t)
4410 (setq f (get-text-property (match-beginning 0) 'face))
4411 (if (or (eq f 'org-tag)
4412 (and (listp f) (memq 'org-tag f)))
4414 (add-text-properties (match-beginning 0) (match-end 0)
4415 (list 'mouse-face 'highlight
4416 'rear-nonsticky t
4417 'keymap org-mouse-map
4419 (throw 'exit t))))))
4421 (defun org-activate-angle-links (limit)
4422 "Run through the buffer and add overlays to links."
4423 (if (re-search-forward org-angle-link-re limit t)
4424 (progn
4425 (add-text-properties (match-beginning 0) (match-end 0)
4426 (list 'mouse-face 'highlight
4427 'rear-nonsticky t
4428 'keymap org-mouse-map
4430 t)))
4432 (defmacro org-maybe-intangible (props)
4433 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
4434 In emacs 21, invisible text is not avoided by the command loop, so the
4435 intangible property is needed to make sure point skips this text.
4436 In Emacs 22, this is not necessary. The intangible text property has
4437 led to problems with flyspell. These problems are fixed in flyspell.el,
4438 but we still avoid setting the property in Emacs 22 and later.
4439 We use a macro so that the test can happen at compilation time."
4440 (if (< emacs-major-version 22)
4441 `(append '(intangible t) ,props)
4442 props))
4444 (defun org-activate-bracket-links (limit)
4445 "Run through the buffer and add overlays to bracketed links."
4446 (if (re-search-forward org-bracket-link-regexp limit t)
4447 (let* ((help (concat "LINK: "
4448 (org-match-string-no-properties 1)))
4449 ;; FIXME: above we should remove the escapes.
4450 ;; but that requires another match, protecting match data,
4451 ;; a lot of overhead for font-lock.
4452 (ip (org-maybe-intangible
4453 (list 'invisible 'org-link 'rear-nonsticky t
4454 'keymap org-mouse-map 'mouse-face 'highlight
4455 'help-echo help)))
4456 (vp (list 'rear-nonsticky t
4457 'keymap org-mouse-map 'mouse-face 'highlight
4458 'help-echo help)))
4459 ;; We need to remove the invisible property here. Table narrowing
4460 ;; may have made some of this invisible.
4461 (remove-text-properties (match-beginning 0) (match-end 0)
4462 '(invisible nil))
4463 (if (match-end 3)
4464 (progn
4465 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4466 (add-text-properties (match-beginning 3) (match-end 3) vp)
4467 (add-text-properties (match-end 3) (match-end 0) ip))
4468 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4469 (add-text-properties (match-beginning 1) (match-end 1) vp)
4470 (add-text-properties (match-end 1) (match-end 0) ip))
4471 t)))
4473 (defun org-activate-dates (limit)
4474 "Run through the buffer and add overlays to dates."
4475 (if (re-search-forward org-tsr-regexp-both limit t)
4476 (progn
4477 (add-text-properties (match-beginning 0) (match-end 0)
4478 (list 'mouse-face 'highlight
4479 'rear-nonsticky t
4480 'keymap org-mouse-map))
4481 (when org-display-custom-times
4482 (if (match-end 3)
4483 (org-display-custom-time (match-beginning 3) (match-end 3)))
4484 (org-display-custom-time (match-beginning 1) (match-end 1)))
4485 t)))
4487 (defvar org-target-link-regexp nil
4488 "Regular expression matching radio targets in plain text.")
4489 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4490 "Regular expression matching a link target.")
4491 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4492 "Regular expression matching a radio target.")
4493 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4494 "Regular expression matching any target.")
4496 (defun org-activate-target-links (limit)
4497 "Run through the buffer and add overlays to target matches."
4498 (when org-target-link-regexp
4499 (let ((case-fold-search t))
4500 (if (re-search-forward org-target-link-regexp limit t)
4501 (progn
4502 (add-text-properties (match-beginning 0) (match-end 0)
4503 (list 'mouse-face 'highlight
4504 'rear-nonsticky t
4505 'keymap org-mouse-map
4506 'help-echo "Radio target link"
4507 'org-linked-text t))
4508 t)))))
4510 (defun org-update-radio-target-regexp ()
4511 "Find all radio targets in this file and update the regular expression."
4512 (interactive)
4513 (when (memq 'radio org-activate-links)
4514 (setq org-target-link-regexp
4515 (org-make-target-link-regexp (org-all-targets 'radio)))
4516 (org-restart-font-lock)))
4518 (defun org-hide-wide-columns (limit)
4519 (let (s e)
4520 (setq s (text-property-any (point) (or limit (point-max))
4521 'org-cwidth t))
4522 (when s
4523 (setq e (next-single-property-change s 'org-cwidth))
4524 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4525 (goto-char e)
4526 t)))
4528 (defun org-restart-font-lock ()
4529 "Restart font-lock-mode, to force refontification."
4530 (when (and (boundp 'font-lock-mode) font-lock-mode)
4531 ;; FIXME: Could font-lock-fontify-buffer be enough???
4532 (font-lock-mode -1)
4533 (font-lock-mode 1)))
4535 (defun org-all-targets (&optional radio)
4536 "Return a list of all targets in this file.
4537 With optional argument RADIO, only find radio targets."
4538 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4539 rtn)
4540 (save-excursion
4541 (goto-char (point-min))
4542 (while (re-search-forward re nil t)
4543 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4544 rtn)))
4546 (defun org-make-target-link-regexp (targets)
4547 "Make regular expression matching all strings in TARGETS.
4548 The regular expression finds the targets also if there is a line break
4549 between words."
4550 (and targets
4551 (concat
4552 "\\<\\("
4553 (mapconcat
4554 (lambda (x)
4555 (while (string-match " +" x)
4556 (setq x (replace-match "\\s-+" t t x)))
4558 targets
4559 "\\|")
4560 "\\)\\>")))
4562 (defun org-activate-tags (limit)
4563 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4564 (progn
4565 (add-text-properties (match-beginning 1) (match-end 1)
4566 (list 'mouse-face 'highlight
4567 'rear-nonsticky t
4568 'keymap org-mouse-map))
4569 t)))
4571 (defun org-outline-level ()
4572 (save-excursion
4573 (looking-at outline-regexp)
4574 (if (match-beginning 1)
4575 (+ (org-get-string-indentation (match-string 1)) 1000)
4576 (1- (- (match-end 0) (match-beginning 0))))))
4578 (defvar org-font-lock-keywords nil)
4580 (defconst org-property-re "^[ \t]*\\(:\\([a-zA-Z_0-9]+\\):\\)[ \t]*\\(\\S-.*\\)"
4581 "Regular expression matching a property line.")
4583 (defun org-set-font-lock-defaults ()
4584 (let* ((em org-fontify-emphasized-text)
4585 (lk org-activate-links)
4586 (org-font-lock-extra-keywords
4587 ;; Headlines
4588 (list
4589 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4590 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4591 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4592 (1 'org-table))
4593 ;; Links
4594 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4595 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4596 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4597 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4598 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4599 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4600 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4601 '(org-hide-wide-columns (0 nil append))
4602 ;; TODO lines
4603 (list (concat "^\\*+[ \t]+" org-not-done-regexp)
4604 '(1 'org-todo t))
4605 ;; Priorities
4606 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4607 ;; Special keywords
4608 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4609 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4610 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4611 (list (concat "\\<" org-archived-string) '(0 'org-special-keyword t))
4612 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4613 ;; Emphasis
4614 (if em
4615 (if (featurep 'xemacs)
4616 '(org-do-emphasis-faces (0 nil append))
4617 '(org-do-emphasis-faces)))
4618 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
4619 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4620 2 'bold prepend)
4621 (if org-provide-checkbox-statistics
4622 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4623 (0 (org-get-checkbox-statistics-face) t)))
4624 ;; COMMENT
4625 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4626 "\\|" org-quote-string "\\)\\>")
4627 '(1 'org-special-keyword t))
4628 '("^#.*" (0 'font-lock-comment-face t))
4629 ;; DONE
4630 (if org-fontify-done-headline
4631 (list (concat "^[*]+ +\\<\\("
4632 (mapconcat 'regexp-quote org-done-keywords "\\|")
4633 "\\)\\(.*\\)")
4634 '(1 'org-done t) '(2 'org-headline-done t))
4635 (list (concat "^[*]+ +\\<\\("
4636 (mapconcat 'regexp-quote org-done-keywords "\\|")
4637 "\\)\\>")
4638 '(1 'org-done t)))
4639 ;; Code
4640 '("^[ \t]*\\(:.*\\)" (1 'org-code t))
4641 ;; Table
4642 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4643 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4644 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4645 ;; Drawers
4646 (list org-drawer-regexp '(0 'org-special-keyword t))
4647 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4648 ;; Properties
4649 (list org-property-re
4650 '(1 'org-special-keyword t)
4651 '(3 'org-property-value t))
4652 (if org-format-transports-properties-p
4653 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4654 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
4656 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4657 ;; Now set the full font-lock-keywords
4658 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4659 (org-set-local 'font-lock-defaults
4660 '(org-font-lock-keywords t nil nil backward-paragraph))
4661 (kill-local-variable 'font-lock-keywords) nil))
4663 (defvar org-m nil)
4664 (defvar org-l nil)
4665 (defvar org-f nil)
4666 (defun org-get-level-face (n)
4667 "Get the right face for match N in font-lock matching of healdines."
4668 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4669 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4670 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4671 (cond
4672 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4673 ((eq n 2) org-f)
4674 (t (if org-level-color-stars-only nil org-f))))
4676 (defun org-unfontify-region (beg end &optional maybe_loudly)
4677 "Remove fontification and activation overlays from links."
4678 (font-lock-default-unfontify-region beg end)
4679 (let* ((buffer-undo-list t)
4680 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4681 (inhibit-modification-hooks t)
4682 deactivate-mark buffer-file-name buffer-file-truename)
4683 (remove-text-properties beg end
4684 '(mouse-face t keymap t org-linked-text t
4685 rear-nonsticky t
4686 invisible t intangible t))))
4688 ;;;; Visibility cycling, including org-goto and indirect buffer
4690 ;;; Cycling
4692 (defvar org-cycle-global-status nil)
4693 (make-variable-buffer-local 'org-cycle-global-status)
4694 (defvar org-cycle-subtree-status nil)
4695 (make-variable-buffer-local 'org-cycle-subtree-status)
4697 ;;;###autoload
4698 (defun org-cycle (&optional arg)
4699 "Visibility cycling for Org-mode.
4701 - When this function is called with a prefix argument, rotate the entire
4702 buffer through 3 states (global cycling)
4703 1. OVERVIEW: Show only top-level headlines.
4704 2. CONTENTS: Show all headlines of all levels, but no body text.
4705 3. SHOW ALL: Show everything.
4707 - When point is at the beginning of a headline, rotate the subtree started
4708 by this line through 3 different states (local cycling)
4709 1. FOLDED: Only the main headline is shown.
4710 2. CHILDREN: The main headline and the direct children are shown.
4711 From this state, you can move to one of the children
4712 and zoom in further.
4713 3. SUBTREE: Show the entire subtree, including body text.
4715 - When there is a numeric prefix, go up to a heading with level ARG, do
4716 a `show-subtree' and return to the previous cursor position. If ARG
4717 is negative, go up that many levels.
4719 - When point is not at the beginning of a headline, execute
4720 `indent-relative', like TAB normally does. See the option
4721 `org-cycle-emulate-tab' for details.
4723 - Special case: if point is at the beginning of the buffer and there is
4724 no headline in line 1, this function will act as if called with prefix arg."
4725 (interactive "P")
4726 (let* ((outline-regexp
4727 (if (and (org-mode-p) org-cycle-include-plain-lists)
4728 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4729 outline-regexp))
4730 (bob-special (and org-cycle-global-at-bob (bobp)
4731 (not (looking-at outline-regexp))))
4732 (org-cycle-hook
4733 (if bob-special
4734 (delq 'org-optimize-window-after-visibility-change
4735 (copy-sequence org-cycle-hook))
4736 org-cycle-hook))
4737 (pos (point)))
4739 (if (or bob-special (equal arg '(4)))
4740 ;; special case: use global cycling
4741 (setq arg t))
4743 (cond
4745 ((org-at-table-p 'any)
4746 ;; Enter the table or move to the next field in the table
4747 (or (org-table-recognize-table.el)
4748 (progn
4749 (if arg (org-table-edit-field t)
4750 (org-table-justify-field-maybe)
4751 (call-interactively 'org-table-next-field)))))
4753 ((eq arg t) ;; Global cycling
4755 (cond
4756 ((and (eq last-command this-command)
4757 (eq org-cycle-global-status 'overview))
4758 ;; We just created the overview - now do table of contents
4759 ;; This can be slow in very large buffers, so indicate action
4760 (message "CONTENTS...")
4761 (org-content)
4762 (message "CONTENTS...done")
4763 (setq org-cycle-global-status 'contents)
4764 (run-hook-with-args 'org-cycle-hook 'contents))
4766 ((and (eq last-command this-command)
4767 (eq org-cycle-global-status 'contents))
4768 ;; We just showed the table of contents - now show everything
4769 (show-all)
4770 (message "SHOW ALL")
4771 (setq org-cycle-global-status 'all)
4772 (run-hook-with-args 'org-cycle-hook 'all))
4775 ;; Default action: go to overview
4776 (org-overview)
4777 (message "OVERVIEW")
4778 (setq org-cycle-global-status 'overview)
4779 (run-hook-with-args 'org-cycle-hook 'overview))))
4781 ((and org-drawers
4782 (save-excursion
4783 (beginning-of-line 1)
4784 (looking-at org-drawer-regexp)))
4785 ;; Toggle block visibility
4786 (org-flag-drawer
4787 (not (get-char-property (match-end 0) 'invisible))))
4789 ((integerp arg)
4790 ;; Show-subtree, ARG levels up from here.
4791 (save-excursion
4792 (org-back-to-heading)
4793 (outline-up-heading (if (< arg 0) (- arg)
4794 (- (funcall outline-level) arg)))
4795 (org-show-subtree)))
4797 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4798 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4799 ;; At a heading: rotate between three different views
4800 (org-back-to-heading)
4801 (let ((goal-column 0) eoh eol eos)
4802 ;; First, some boundaries
4803 (save-excursion
4804 (org-back-to-heading)
4805 (save-excursion
4806 (beginning-of-line 2)
4807 (while (and (not (eobp)) ;; this is like `next-line'
4808 (get-char-property (1- (point)) 'invisible))
4809 (beginning-of-line 2)) (setq eol (point)))
4810 (outline-end-of-heading) (setq eoh (point))
4811 (org-end-of-subtree t)
4812 (unless (eobp)
4813 (skip-chars-forward " \t\n")
4814 (beginning-of-line 1) ; in case this is an item
4816 (setq eos (1- (point))))
4817 ;; Find out what to do next and set `this-command'
4818 (cond
4819 ((= eos eoh)
4820 ;; Nothing is hidden behind this heading
4821 (message "EMPTY ENTRY")
4822 (setq org-cycle-subtree-status nil)
4823 (save-excursion
4824 (goto-char eos)
4825 (outline-next-heading)
4826 (if (org-invisible-p) (org-flag-heading nil))))
4827 ((or (>= eol eos)
4828 (not (string-match "\\S-" (buffer-substring eol eos))))
4829 ;; Entire subtree is hidden in one line: open it
4830 (org-show-entry)
4831 (show-children)
4832 (message "CHILDREN")
4833 (save-excursion
4834 (goto-char eos)
4835 (outline-next-heading)
4836 (if (org-invisible-p) (org-flag-heading nil)))
4837 (setq org-cycle-subtree-status 'children)
4838 (run-hook-with-args 'org-cycle-hook 'children))
4839 ((and (eq last-command this-command)
4840 (eq org-cycle-subtree-status 'children))
4841 ;; We just showed the children, now show everything.
4842 (org-show-subtree)
4843 (message "SUBTREE")
4844 (setq org-cycle-subtree-status 'subtree)
4845 (run-hook-with-args 'org-cycle-hook 'subtree))
4847 ;; Default action: hide the subtree.
4848 (hide-subtree)
4849 (message "FOLDED")
4850 (setq org-cycle-subtree-status 'folded)
4851 (run-hook-with-args 'org-cycle-hook 'folded)))))
4853 ;; TAB emulation
4854 (buffer-read-only (org-back-to-heading))
4856 ((org-try-cdlatex-tab))
4858 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4859 (or (not (bolp))
4860 (not (looking-at outline-regexp))))
4861 (call-interactively (global-key-binding "\t")))
4863 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4864 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4865 (or (and (eq org-cycle-emulate-tab 'white)
4866 (= (match-end 0) (point-at-eol)))
4867 (and (eq org-cycle-emulate-tab 'whitestart)
4868 (>= (match-end 0) pos))))
4870 (eq org-cycle-emulate-tab t))
4871 (if (and (looking-at "[ \n\r\t]")
4872 (string-match "^[ \t]*$" (buffer-substring
4873 (point-at-bol) (point))))
4874 (progn
4875 (beginning-of-line 1)
4876 (and (looking-at "[ \t]+") (replace-match ""))))
4877 (call-interactively (global-key-binding "\t")))
4879 (t (save-excursion
4880 (org-back-to-heading)
4881 (org-cycle))))))
4883 ;;;###autoload
4884 (defun org-global-cycle (&optional arg)
4885 "Cycle the global visibility. For details see `org-cycle'."
4886 (interactive "P")
4887 (let ((org-cycle-include-plain-lists
4888 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4889 (if (integerp arg)
4890 (progn
4891 (show-all)
4892 (hide-sublevels arg)
4893 (setq org-cycle-global-status 'contents))
4894 (org-cycle '(4)))))
4896 (defun org-overview ()
4897 "Switch to overview mode, shoing only top-level headlines.
4898 Really, this shows all headlines with level equal or greater than the level
4899 of the first headline in the buffer. This is important, because if the
4900 first headline is not level one, then (hide-sublevels 1) gives confusing
4901 results."
4902 (interactive)
4903 (let ((level (save-excursion
4904 (goto-char (point-min))
4905 (if (re-search-forward (concat "^" outline-regexp) nil t)
4906 (progn
4907 (goto-char (match-beginning 0))
4908 (funcall outline-level))))))
4909 (and level (hide-sublevels level))))
4911 (defun org-content (&optional arg)
4912 "Show all headlines in the buffer, like a table of contents.
4913 With numerical argument N, show content up to level N."
4914 (interactive "P")
4915 (save-excursion
4916 ;; Visit all headings and show their offspring
4917 (and (integerp arg) (org-overview))
4918 (goto-char (point-max))
4919 (catch 'exit
4920 (while (and (progn (condition-case nil
4921 (outline-previous-visible-heading 1)
4922 (error (goto-char (point-min))))
4924 (looking-at outline-regexp))
4925 (if (integerp arg)
4926 (show-children (1- arg))
4927 (show-branches))
4928 (if (bobp) (throw 'exit nil))))))
4931 (defun org-optimize-window-after-visibility-change (state)
4932 "Adjust the window after a change in outline visibility.
4933 This function is the default value of the hook `org-cycle-hook'."
4934 (when (get-buffer-window (current-buffer))
4935 (cond
4936 ; ((eq state 'overview) (org-first-headline-recenter 1))
4937 ; ((eq state 'overview) (org-beginning-of-line))
4938 ((eq state 'content) nil)
4939 ((eq state 'all) nil)
4940 ((eq state 'folded) nil)
4941 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4942 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4945 (defun org-cycle-show-empty-lines (state)
4946 "Show empty lines above all visible headlines.
4947 The region to be covered depends on STATE when called through
4948 `org-cycle-hook'. Lisp program can use t for STATE to get the
4949 entire buffer covered. Note that an empty line is only shown if there
4950 are at least `org-cycle-separator-lines' empty lines before the headeline."
4951 (when (> org-cycle-separator-lines 0)
4952 (save-excursion
4953 (let* ((n org-cycle-separator-lines)
4954 (re (cond
4955 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4956 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4957 (t (let ((ns (number-to-string (- n 2))))
4958 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4959 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4960 beg end)
4961 (cond
4962 ((memq state '(overview contents t))
4963 (setq beg (point-min) end (point-max)))
4964 ((memq state '(children folded))
4965 (setq beg (point) end (progn (org-end-of-subtree t t)
4966 (beginning-of-line 2)
4967 (point)))))
4968 (when beg
4969 (goto-char beg)
4970 (while (re-search-forward re end t)
4971 (if (not (get-char-property (match-end 1) 'invisible))
4972 (outline-flag-region
4973 (match-beginning 1) (match-end 1) nil)))))))
4974 ;; Never hide empty lines at the end of the file.
4975 (save-excursion
4976 (goto-char (point-max))
4977 (outline-previous-heading)
4978 (outline-end-of-heading)
4979 (if (and (looking-at "[ \t\n]+")
4980 (= (match-end 0) (point-max)))
4981 (outline-flag-region (point) (match-end 0) nil))))
4983 (defun org-subtree-end-visible-p ()
4984 "Is the end of the current subtree visible?"
4985 (pos-visible-in-window-p
4986 (save-excursion (org-end-of-subtree t) (point))))
4988 (defun org-first-headline-recenter (&optional N)
4989 "Move cursor to the first headline and recenter the headline.
4990 Optional argument N means, put the headline into the Nth line of the window."
4991 (goto-char (point-min))
4992 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4993 (beginning-of-line)
4994 (recenter (prefix-numeric-value N))))
4996 ;;; Org-goto
4998 (defvar org-goto-window-configuration nil)
4999 (defvar org-goto-marker nil)
5000 (defvar org-goto-map
5001 (let ((map (make-sparse-keymap)))
5002 (let ((cmds '(isearch-forward isearch-backward)) cmd)
5003 (while (setq cmd (pop cmds))
5004 (substitute-key-definition cmd cmd map global-map)))
5005 (org-defkey map "\C-m" 'org-goto-ret)
5006 (org-defkey map [(left)] 'org-goto-left)
5007 (org-defkey map [(right)] 'org-goto-right)
5008 (org-defkey map [(?q)] 'org-goto-quit)
5009 (org-defkey map [(control ?g)] 'org-goto-quit)
5010 (org-defkey map "\C-i" 'org-cycle)
5011 (org-defkey map [(tab)] 'org-cycle)
5012 (org-defkey map [(down)] 'outline-next-visible-heading)
5013 (org-defkey map [(up)] 'outline-previous-visible-heading)
5014 (org-defkey map "n" 'outline-next-visible-heading)
5015 (org-defkey map "p" 'outline-previous-visible-heading)
5016 (org-defkey map "f" 'outline-forward-same-level)
5017 (org-defkey map "b" 'outline-backward-same-level)
5018 (org-defkey map "u" 'outline-up-heading)
5019 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5020 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5021 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5022 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5023 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5024 ;; FIXME: Could we use suppress-keymap?
5025 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
5026 (while l (org-defkey map (int-to-string (pop l)) 'digit-argument)))
5027 map))
5029 (defconst org-goto-help
5030 "Select a location to jump to, press RET
5031 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
5033 (defun org-goto ()
5034 "Go to a different location of the document, keeping current visibility.
5036 When you want to go to a different location in a document, the fastest way
5037 is often to fold the entire buffer and then dive into the tree. This
5038 method has the disadvantage, that the previous location will be folded,
5039 which may not be what you want.
5041 This command works around this by showing a copy of the current buffer in
5042 overview mode. You can dive into the tree in that copy, to find the
5043 location you want to reach. When pressing RET, the command returns to the
5044 original buffer in which the visibility is still unchanged. It then jumps
5045 to the new location, making it and the headline hierarchy above it visible."
5046 (interactive)
5047 (let* ((org-goto-start-pos (point))
5048 (selected-point
5049 (org-get-location (current-buffer) org-goto-help)))
5050 (if selected-point
5051 (progn
5052 (org-mark-ring-push org-goto-start-pos)
5053 (goto-char selected-point)
5054 (if (or (org-invisible-p) (org-invisible-p2))
5055 (org-show-context 'org-goto)))
5056 (error "Quit"))))
5058 (defvar org-selected-point nil) ; dynamically scoped parameter
5060 (defun org-get-location (buf help)
5061 "Let the user select a location in the Org-mode buffer BUF.
5062 This function uses a recursive edit. It returns the selected position
5063 or nil."
5064 (let (org-selected-point)
5065 (save-excursion
5066 (save-window-excursion
5067 (delete-other-windows)
5068 (switch-to-buffer (get-buffer-create "*org-goto*"))
5069 (with-output-to-temp-buffer "*Help*"
5070 (princ help))
5071 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5072 (setq buffer-read-only nil)
5073 (erase-buffer)
5074 (insert-buffer-substring buf)
5075 (let ((org-startup-truncated t)
5076 (org-startup-folded t)
5077 (org-startup-align-all-tables nil))
5078 (org-mode))
5079 (setq buffer-read-only t)
5080 (if (and (boundp 'org-goto-start-pos)
5081 (integer-or-marker-p org-goto-start-pos))
5082 (let ((org-show-hierarchy-above t)
5083 (org-show-siblings t)
5084 (org-show-following-heading t))
5085 (goto-char org-goto-start-pos)
5086 (and (org-invisible-p) (org-show-context)))
5087 (goto-char (point-min)))
5088 (org-beginning-of-line)
5089 (message "Select location and press RET")
5090 ;; now we make sure that during selection, ony very few keys work
5091 ;; and that it is impossible to switch to another window.
5092 (let ((gm (current-global-map))
5093 (overriding-local-map org-goto-map))
5094 (unwind-protect
5095 (progn
5096 (use-global-map org-goto-map)
5097 (recursive-edit))
5098 (use-global-map gm)))))
5099 (kill-buffer "*org-goto*")
5100 org-selected-point))
5102 (defun org-goto-ret (&optional arg)
5103 "Finish `org-goto' by going to the new location."
5104 (interactive "P")
5105 (setq org-selected-point (point)
5106 current-prefix-arg arg)
5107 (throw 'exit nil))
5109 (defun org-goto-left ()
5110 "Finish `org-goto' by going to the new location."
5111 (interactive)
5112 (if (org-on-heading-p)
5113 (progn
5114 (beginning-of-line 1)
5115 (setq org-selected-point (point)
5116 current-prefix-arg (- (match-end 0) (match-beginning 0)))
5117 (throw 'exit nil))
5118 (error "Not on a heading")))
5120 (defun org-goto-right ()
5121 "Finish `org-goto' by going to the new location."
5122 (interactive)
5123 (if (org-on-heading-p)
5124 (progn
5125 (outline-end-of-subtree)
5126 (or (eobp) (forward-char 1))
5127 (setq org-selected-point (point)
5128 current-prefix-arg (- (match-end 0) (match-beginning 0)))
5129 (throw 'exit nil))
5130 (error "Not on a heading")))
5132 (defun org-goto-quit ()
5133 "Finish `org-goto' without cursor motion."
5134 (interactive)
5135 (setq org-selected-point nil)
5136 (throw 'exit nil))
5138 ;;; Indirect buffer display of subtrees
5140 (defvar org-indirect-dedicated-frame nil
5141 "This is the frame being used for indirect tree display.")
5142 (defvar org-last-indirect-buffer nil)
5144 (defun org-tree-to-indirect-buffer (&optional arg)
5145 "Create indirect buffer and narrow it to current subtree.
5146 With numerical prefix ARG, go up to this level and then take that tree.
5147 If ARG is negative, go up that many levels.
5148 Normally this command removes the indirect buffer previously made
5149 with this command. However, when called with a C-u prefix, the last buffer
5150 is kept so that you can work with several indirect buffers at the same time.
5151 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5152 requests that a new frame be made for the new buffer, so that the dedicated
5153 frame is not changed."
5154 (interactive "P")
5155 (let ((cbuf (current-buffer))
5156 (cwin (selected-window))
5157 (pos (point))
5158 beg end level heading ibuf)
5159 (save-excursion
5160 (org-back-to-heading t)
5161 (when (numberp arg)
5162 (setq level (org-outline-level))
5163 (if (< arg 0) (setq arg (+ level arg)))
5164 (while (> (setq level (org-outline-level)) arg)
5165 (outline-up-heading 1 t)))
5166 (setq beg (point)
5167 heading (org-get-heading))
5168 (org-end-of-subtree t) (setq end (point)))
5169 (if (and (not arg)
5170 (buffer-live-p org-last-indirect-buffer))
5171 (kill-buffer org-last-indirect-buffer))
5172 (setq ibuf (org-get-indirect-buffer cbuf)
5173 org-last-indirect-buffer ibuf)
5174 (cond
5175 ((or (eq org-indirect-buffer-display 'new-frame)
5176 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5177 (select-frame (make-frame))
5178 (delete-other-windows)
5179 (switch-to-buffer ibuf)
5180 (org-set-frame-title heading))
5181 ((eq org-indirect-buffer-display 'dedicated-frame)
5182 (raise-frame
5183 (select-frame (or (and org-indirect-dedicated-frame
5184 (frame-live-p org-indirect-dedicated-frame)
5185 org-indirect-dedicated-frame)
5186 (setq org-indirect-dedicated-frame (make-frame)))))
5187 (delete-other-windows)
5188 (switch-to-buffer ibuf)
5189 (org-set-frame-title (concat "Indirect: " heading)))
5190 ((eq org-indirect-buffer-display 'current-window)
5191 (switch-to-buffer ibuf))
5192 ((eq org-indirect-buffer-display 'other-window)
5193 (pop-to-buffer ibuf))
5194 (t (error "Invalid value.")))
5195 (if (featurep 'xemacs)
5196 (save-excursion (org-mode) (turn-on-font-lock)))
5197 (narrow-to-region beg end)
5198 (show-all)
5199 (goto-char pos)
5200 (and (window-live-p cwin) (select-window cwin))))
5202 (defun org-get-indirect-buffer (&optional buffer)
5203 (setq buffer (or buffer (current-buffer)))
5204 (let ((n 1) (base (buffer-name buffer)) bname)
5205 (while (buffer-live-p
5206 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5207 (setq n (1+ n)))
5208 (condition-case nil
5209 (make-indirect-buffer buffer bname 'clone)
5210 (error (make-indirect-buffer buffer bname)))))
5212 (defun org-set-frame-title (title)
5213 "Set the title of the current frame to the string TITLE."
5214 ;; FIXME: how to name a single frame in XEmacs???
5215 (unless (featurep 'xemacs)
5216 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5218 ;;;; Structure editing
5220 ;;; Inserting headlines
5222 (defun org-insert-heading (&optional force-heading)
5223 "Insert a new heading or item with same depth at point.
5224 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5225 If point is at the beginning of a headline, insert a sibling before the
5226 current headline. If point is in the middle of a headline, split the headline
5227 at that position and make the rest of the headline part of the sibling below
5228 the current headline."
5229 (interactive "P")
5230 (if (= (buffer-size) 0)
5231 (insert "\n* ")
5232 (when (or force-heading (not (org-insert-item)))
5233 (let* ((head (save-excursion
5234 (condition-case nil
5235 (progn
5236 (org-back-to-heading)
5237 (match-string 0))
5238 (error "*"))))
5239 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5240 pos)
5241 (cond
5242 ((and (org-on-heading-p) (bolp)
5243 (or (bobp)
5244 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5245 (open-line (if blank 2 1)))
5246 ((and (bolp)
5247 (or (bobp)
5248 (save-excursion
5249 (backward-char 1) (not (org-invisible-p)))))
5250 nil)
5251 (t (newline (if blank 2 1))))
5252 (insert head) (just-one-space)
5253 (setq pos (point))
5254 (end-of-line 1)
5255 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5256 (run-hooks 'org-insert-heading-hook)))))
5258 (defun org-insert-todo-heading (arg)
5259 "Insert a new heading with the same level and TODO state as current heading.
5260 If the heading has no TODO state, or if the state is DONE, use the first
5261 state (TODO by default). Also with prefix arg, force first state."
5262 (interactive "P")
5263 (when (not (org-insert-item 'checkbox))
5264 (org-insert-heading)
5265 (save-excursion
5266 (org-back-to-heading)
5267 (outline-previous-heading)
5268 (looking-at org-todo-line-regexp))
5269 (if (or arg
5270 (not (match-beginning 2))
5271 (member (match-string 2) org-done-keywords))
5272 (insert (car org-todo-keywords-1) " ")
5273 (insert (match-string 2) " "))))
5275 (defun org-insert-subheading (arg)
5276 "Insert a new subheading and demote it.
5277 Works for outline headings and for plain lists alike."
5278 (interactive "P")
5279 (org-insert-heading arg)
5280 (cond
5281 ((org-on-heading-p) (org-do-demote))
5282 ((org-at-item-p) (org-indent-item 1))))
5284 (defun org-insert-todo-subheading (arg)
5285 "Insert a new subheading with TODO keyword or checkbox and demote it.
5286 Works for outline headings and for plain lists alike."
5287 (interactive "P")
5288 (org-insert-todo-heading arg)
5289 (cond
5290 ((org-on-heading-p) (org-do-demote))
5291 ((org-at-item-p) (org-indent-item 1))))
5293 ;;; Promotion and Demotion
5295 (defun org-promote-subtree ()
5296 "Promote the entire subtree.
5297 See also `org-promote'."
5298 (interactive)
5299 (save-excursion
5300 (org-map-tree 'org-promote))
5301 (org-fix-position-after-promote))
5303 (defun org-demote-subtree ()
5304 "Demote the entire subtree. See `org-demote'.
5305 See also `org-promote'."
5306 (interactive)
5307 (save-excursion
5308 (org-map-tree 'org-demote))
5309 (org-fix-position-after-promote))
5312 (defun org-do-promote ()
5313 "Promote the current heading higher up the tree.
5314 If the region is active in `transient-mark-mode', promote all headings
5315 in the region."
5316 (interactive)
5317 (save-excursion
5318 (if (org-region-active-p)
5319 (org-map-region 'org-promote (region-beginning) (region-end))
5320 (org-promote)))
5321 (org-fix-position-after-promote))
5323 (defun org-do-demote ()
5324 "Demote the current heading lower down the tree.
5325 If the region is active in `transient-mark-mode', demote all headings
5326 in the region."
5327 (interactive)
5328 (save-excursion
5329 (if (org-region-active-p)
5330 (org-map-region 'org-demote (region-beginning) (region-end))
5331 (org-demote)))
5332 (org-fix-position-after-promote))
5334 (defun org-fix-position-after-promote ()
5335 "Make sure that after pro/demotion cursor position is right."
5336 (let ((pos (point)))
5337 (when (save-excursion
5338 (beginning-of-line 1)
5339 (looking-at org-todo-line-regexp)
5340 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5341 (cond ((eobp) (insert " "))
5342 ((eolp) (insert " "))
5343 ((equal (char-after) ?\ ) (forward-char 1))))))
5345 (defun org-reduced-level (l)
5346 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5348 (defun org-get-legal-level (level &optional change)
5349 "Rectify a level change under the influence of `org-odd-levels-only'
5350 LEVEL is a current level, CHANGE is by how much the level should be
5351 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5352 even level numbers will become the next higher odd number."
5353 (if org-odd-levels-only
5354 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5355 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5356 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5357 (max 1 (+ level change))))
5359 (defun org-promote ()
5360 "Promote the current heading higher up the tree.
5361 If the region is active in `transient-mark-mode', promote all headings
5362 in the region."
5363 (org-back-to-heading t)
5364 (let* ((level (save-match-data (funcall outline-level)))
5365 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
5366 (diff (abs (- level (length up-head) -1))))
5367 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5368 (replace-match up-head nil t)
5369 ;; Fixup tag positioning
5370 (and org-auto-align-tags (org-set-tags nil t))
5371 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5373 (defun org-demote ()
5374 "Demote the current heading lower down the tree.
5375 If the region is active in `transient-mark-mode', demote all headings
5376 in the region."
5377 (org-back-to-heading t)
5378 (let* ((level (save-match-data (funcall outline-level)))
5379 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
5380 (diff (abs (- level (length down-head) -1))))
5381 (replace-match down-head nil t)
5382 ;; Fixup tag positioning
5383 (and org-auto-align-tags (org-set-tags nil t))
5384 (if org-adapt-indentation (org-fixup-indentation diff))))
5386 (defun org-map-tree (fun)
5387 "Call FUN for every heading underneath the current one."
5388 (org-back-to-heading)
5389 (let ((level (funcall outline-level)))
5390 (save-excursion
5391 (funcall fun)
5392 (while (and (progn
5393 (outline-next-heading)
5394 (> (funcall outline-level) level))
5395 (not (eobp)))
5396 (funcall fun)))))
5398 (defun org-map-region (fun beg end)
5399 "Call FUN for every heading between BEG and END."
5400 (let ((org-ignore-region t))
5401 (save-excursion
5402 (setq end (copy-marker end))
5403 (goto-char beg)
5404 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5405 (< (point) end))
5406 (funcall fun))
5407 (while (and (progn
5408 (outline-next-heading)
5409 (< (point) end))
5410 (not (eobp)))
5411 (funcall fun)))))
5413 (defun org-fixup-indentation (diff)
5414 "Change the indentation in the current entry by DIFF
5415 However, if any line in the current entry has no indentation, or if it
5416 would end up with no indentation after the change, nothing at all is done."
5417 (save-excursion
5418 (let ((end (save-excursion (outline-next-heading)
5419 (point-marker)))
5420 (prohibit (if (> diff 0)
5421 "^\\S-"
5422 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5423 col)
5424 (unless (save-excursion (end-of-line 1)
5425 (re-search-forward prohibit end t))
5426 (while (re-search-forward "^[ \t]+" end t)
5427 (goto-char (match-end 0))
5428 (setq col (current-column))
5429 (if (< diff 0) (replace-match ""))
5430 (indent-to (+ diff col))))
5431 (move-marker end nil))))
5433 (defun org-convert-to-odd-levels ()
5434 "Convert an org-mode file with all levels allowed to one with odd levels.
5435 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5436 level 5 etc."
5437 (interactive)
5438 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5439 (let ((org-odd-levels-only nil) n)
5440 (save-excursion
5441 (goto-char (point-min))
5442 (while (re-search-forward "^\\*\\*+ " nil t)
5443 (setq n (- (length (match-string 0)) 2))
5444 (while (>= (setq n (1- n)) 0)
5445 (org-demote))
5446 (end-of-line 1))))))
5449 (defun org-convert-to-oddeven-levels ()
5450 "Convert an org-mode file with only odd levels to one with odd and even levels.
5451 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5452 section with an even level, conversion would destroy the structure of the file. An error
5453 is signaled in this case."
5454 (interactive)
5455 (goto-char (point-min))
5456 ;; First check if there are no even levels
5457 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5458 (org-show-context t)
5459 (error "Not all levels are odd in this file. Conversion not possible."))
5460 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5461 (let ((org-odd-levels-only nil) n)
5462 (save-excursion
5463 (goto-char (point-min))
5464 (while (re-search-forward "^\\*\\*+ " nil t)
5465 (setq n (/ (length (1- (match-string 0))) 2))
5466 (while (>= (setq n (1- n)) 0)
5467 (org-promote))
5468 (end-of-line 1))))))
5470 (defun org-tr-level (n)
5471 "Make N odd if required."
5472 (if org-odd-levels-only (1+ (/ n 2)) n))
5474 ;;; Vertical tree motion, cutting and pasting of subtrees
5476 (defun org-move-subtree-up (&optional arg)
5477 "Move the current subtree up past ARG headlines of the same level."
5478 (interactive "p")
5479 (org-move-subtree-down (- (prefix-numeric-value arg))))
5481 (defun org-move-subtree-down (&optional arg)
5482 "Move the current subtree down past ARG headlines of the same level."
5483 (interactive "p")
5484 (setq arg (prefix-numeric-value arg))
5485 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5486 'outline-get-last-sibling))
5487 (ins-point (make-marker))
5488 (cnt (abs arg))
5489 beg end txt folded)
5490 ;; Select the tree
5491 (org-back-to-heading)
5492 (setq beg (point))
5493 (save-match-data
5494 (save-excursion (outline-end-of-heading)
5495 (setq folded (org-invisible-p)))
5496 (outline-end-of-subtree))
5497 (outline-next-heading)
5498 (setq end (point))
5499 ;; Find insertion point, with error handling
5500 (goto-char beg)
5501 (while (> cnt 0)
5502 (or (and (funcall movfunc) (looking-at outline-regexp))
5503 (progn (goto-char beg)
5504 (error "Cannot move past superior level or buffer limit")))
5505 (setq cnt (1- cnt)))
5506 (if (> arg 0)
5507 ;; Moving forward - still need to move over subtree
5508 (progn (outline-end-of-subtree)
5509 (outline-next-heading)
5510 (if (not (or (looking-at (concat "^" outline-regexp))
5511 (bolp)))
5512 (newline))))
5513 (move-marker ins-point (point))
5514 (setq txt (buffer-substring beg end))
5515 (delete-region beg end)
5516 (insert txt)
5517 (or (bolp) (insert "\n"))
5518 (goto-char ins-point)
5519 (if folded (hide-subtree))
5520 (move-marker ins-point nil)))
5522 (defvar org-subtree-clip ""
5523 "Clipboard for cut and paste of subtrees.
5524 This is actually only a copy of the kill, because we use the normal kill
5525 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5527 (defvar org-subtree-clip-folded nil
5528 "Was the last copied subtree folded?
5529 This is used to fold the tree back after pasting.")
5531 (defun org-cut-subtree ()
5532 "Cut the current subtree into the clipboard.
5533 This is a short-hand for marking the subtree and then cutting it."
5534 (interactive)
5535 (org-copy-subtree 'cut))
5537 (defun org-copy-subtree (&optional cut)
5538 "Cut the current subtree into the clipboard.
5539 This is a short-hand for marking the subtree and then copying it.
5540 If CUT is non-nil, actually cut the subtree."
5541 (interactive)
5542 (let (beg end folded)
5543 (if (interactive-p)
5544 (org-back-to-heading nil) ; take what looks like a subtree
5545 (org-back-to-heading t)) ; take what is really there
5546 (setq beg (point))
5547 (save-match-data
5548 (save-excursion (outline-end-of-heading)
5549 (setq folded (org-invisible-p)))
5550 (outline-end-of-subtree))
5551 (if (equal (char-after) ?\n) (forward-char 1))
5552 (setq end (point))
5553 (goto-char beg)
5554 (when (> end beg)
5555 (setq org-subtree-clip-folded folded)
5556 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5557 (setq org-subtree-clip (current-kill 0))
5558 (message "%s: Subtree with %d characters"
5559 (if cut "Cut" "Copied")
5560 (length org-subtree-clip)))))
5562 (defun org-paste-subtree (&optional level tree)
5563 "Paste the clipboard as a subtree, with modification of headline level.
5564 The entire subtree is promoted or demoted in order to match a new headline
5565 level. By default, the new level is derived from the visible headings
5566 before and after the insertion point, and taken to be the inferior headline
5567 level of the two. So if the previous visible heading is level 3 and the
5568 next is level 4 (or vice versa), level 4 will be used for insertion.
5569 This makes sure that the subtree remains an independent subtree and does
5570 not swallow low level entries.
5572 You can also force a different level, either by using a numeric prefix
5573 argument, or by inserting the heading marker by hand. For example, if the
5574 cursor is after \"*****\", then the tree will be shifted to level 5.
5576 If you want to insert the tree as is, just use \\[yank].
5578 If optional TREE is given, use this text instead of the kill ring."
5579 (interactive "P")
5580 (unless (org-kill-is-subtree-p tree)
5581 (error
5582 (substitute-command-keys
5583 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5584 (let* ((txt (or tree (and kill-ring (current-kill 0))))
5585 (^re (concat "^\\(" outline-regexp "\\)"))
5586 (re (concat "\\(" outline-regexp "\\)"))
5587 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
5589 (old-level (if (string-match ^re txt)
5590 (- (match-end 0) (match-beginning 0) 1)
5591 -1))
5592 (force-level (cond (level (prefix-numeric-value level))
5593 ((string-match
5594 ^re_ (buffer-substring (point-at-bol) (point)))
5595 (- (match-end 0) (match-beginning 0)))
5596 (t nil)))
5597 (previous-level (save-excursion
5598 (condition-case nil
5599 (progn
5600 (outline-previous-visible-heading 1)
5601 (if (looking-at re)
5602 (- (match-end 0) (match-beginning 0))
5604 (error 1))))
5605 (next-level (save-excursion
5606 (condition-case nil
5607 (progn
5608 (outline-next-visible-heading 1)
5609 (if (looking-at re)
5610 (- (match-end 0) (match-beginning 0))
5612 (error 1))))
5613 (new-level (or force-level (max previous-level next-level)))
5614 (shift (if (or (= old-level -1)
5615 (= new-level -1)
5616 (= old-level new-level))
5618 (- new-level old-level)))
5619 (shift1 shift)
5620 (delta (if (> shift 0) -1 1))
5621 (func (if (> shift 0) 'org-demote 'org-promote))
5622 (org-odd-levels-only nil)
5623 beg end)
5624 ;; Remove the forces level indicator
5625 (if force-level
5626 (delete-region (point-at-bol) (point)))
5627 ;; Make sure we start at the beginning of an empty line
5628 (if (not (bolp)) (insert "\n"))
5629 (if (not (looking-at "[ \t]*$"))
5630 (progn (insert "\n") (backward-char 1)))
5631 ;; Paste
5632 (setq beg (point))
5633 (if (string-match "[ \t\r\n]+\\'" txt)
5634 (setq txt (replace-match "\n" t t txt)))
5635 (insert txt)
5636 (setq end (point))
5637 (if (looking-at "[ \t\r\n]+")
5638 (replace-match "\n"))
5639 (goto-char beg)
5640 ;; Shift if necessary
5641 (if (= shift 0)
5642 (message "Pasted at level %d, without shift" new-level)
5643 (save-restriction
5644 (narrow-to-region beg end)
5645 (while (not (= shift 0))
5646 (org-map-region func (point-min) (point-max))
5647 (setq shift (+ delta shift)))
5648 (goto-char (point-min))
5649 (message "Pasted at level %d, with shift by %d levels"
5650 new-level shift1)))
5651 (if (and kill-ring
5652 (eq org-subtree-clip (current-kill 0))
5653 org-subtree-clip-folded)
5654 ;; The tree was folded before it was killed/copied
5655 (hide-subtree))))
5657 (defun org-kill-is-subtree-p (&optional txt)
5658 "Check if the current kill is an outline subtree, or a set of trees.
5659 Returns nil if kill does not start with a headline, or if the first
5660 headline level is not the largest headline level in the tree.
5661 So this will actually accept several entries of equal levels as well,
5662 which is OK for `org-paste-subtree'.
5663 If optional TXT is given, check this string instead of the current kill."
5664 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5665 (start-level (and kill
5666 (string-match (concat "\\`" outline-regexp) kill)
5667 (- (match-end 0) (match-beginning 0))))
5668 (re (concat "^" outline-regexp))
5669 (start 1))
5670 (if (not start-level)
5671 nil ;; does not even start with a heading
5672 (catch 'exit
5673 (while (setq start (string-match re kill (1+ start)))
5674 (if (< (- (match-end 0) (match-beginning 0)) start-level)
5675 (throw 'exit nil)))
5676 t))))
5678 (defun org-narrow-to-subtree ()
5679 "Narrow buffer to the current subtree."
5680 (interactive)
5681 (save-excursion
5682 (narrow-to-region
5683 (progn (org-back-to-heading) (point))
5684 (progn (org-end-of-subtree t t) (point)))))
5687 ;;; Outline Sorting
5689 (defun org-sort (with-case)
5690 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
5691 (interactive "P")
5692 (if (org-at-table-p)
5693 (org-call-with-arg 'org-table-sort-lines with-case)
5694 (org-call-with-arg 'org-sort-entries with-case)))
5696 (defun org-sort-entries (&optional with-case sorting-type)
5697 "Sort entries on a certain level of an outline tree.
5698 If there is an active region, the entries in the region are sorted.
5699 Else, if the cursor is before the first entry, sort the top-level items.
5700 Else, the children of the entry at point are sorted.
5702 Sorting can be alphabetically, numerically, and by date/time as given by
5703 the first time stamp in the entry. The command prompts for the sorting
5704 type unless it has been given to the function through the SORTING-TYPE
5705 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
5707 Comparing entries ignores case by default. However, with an optional argument
5708 WITH-CASE, the sorting considers case as well. With two prefix arguments
5709 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
5710 (interactive "P")
5711 (let ((unique (equal with-case '(16)))
5712 start beg end entries stars re re2 p nentries (nremoved 0)
5713 last txt what)
5714 ;; Find beginning and end of region to sort
5715 (cond
5716 ((org-region-active-p)
5717 ;; we will sort the region
5718 (setq end (region-end)
5719 what "region")
5720 (goto-char (region-beginning))
5721 (if (not (org-on-heading-p)) (outline-next-heading))
5722 (setq start (point)))
5723 ((or (org-on-heading-p)
5724 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5725 ;; we will sort the children of the current headline
5726 (org-back-to-heading)
5727 (setq start (point) end (org-end-of-subtree) what "children")
5728 (goto-char start)
5729 (show-subtree)
5730 (outline-next-heading))
5732 ;; we will sort the top-level entries in this file
5733 (goto-char (point-min))
5734 (or (org-on-heading-p) (outline-next-heading))
5735 (setq start (point) end (point-max) what "top-level")
5736 (goto-char start)
5737 (show-all)))
5738 (setq beg (point))
5739 (if (>= (point) end) (error "Nothing to sort"))
5740 (looking-at "\\(\\*+\\)")
5741 (setq stars (match-string 1)
5742 re (concat "^" (regexp-quote stars) " +")
5743 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5744 txt (buffer-substring beg end))
5745 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5746 (if (and (not (equal stars "*")) (string-match re2 txt))
5747 (error "Region to sort contains a level above the first entry"))
5748 ;; Make a list that can be sorted.
5749 ;; The car is the string for comparison, the cdr is the subtree
5750 (message "Sorting entries...")
5751 (setq entries
5752 (mapcar
5753 (lambda (x)
5754 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
5755 (cons (match-string 0 x) x))
5756 (org-split-string txt re)))
5758 ;; Sort the list
5759 (save-excursion
5760 (goto-char start)
5761 (setq entries (org-do-sort entries what with-case sorting-type)))
5763 ;; Delete the old stuff
5764 (goto-char beg)
5765 (kill-region beg end)
5766 (setq nentries (length entries))
5767 ;; Insert the sorted entries, and remove duplicates if this is required
5768 (while (setq p (pop entries))
5769 (if (and unique (equal last (setq last (org-trim (cdr p)))))
5770 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
5771 (insert stars " " (cdr p))))
5772 (goto-char start)
5773 (message "Sorting entries...done (%d entries%s)"
5774 nentries
5775 (if unique (format ", %d duplicates removed" nremoved) ""))))
5777 (defun org-do-sort (table what &optional with-case sorting-type)
5778 "Sort TABLE of WHAT according to SORTING-TYPE.
5779 The user will be prompted for the SORTING-TYPE if the call to this
5780 function does not specify it. WHAT is only for the prompt, to indicate
5781 what is being sorted. The sorting key will be extracted from
5782 the car of the elements of the table.
5783 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5784 (unless sorting-type
5785 (message
5786 "Sort %s: [a]lphabetically [n]umerically [t]ime. A/N/T means reversed:"
5787 what)
5788 (setq sorting-type (read-char-exclusive)))
5789 (let ((dcst (downcase sorting-type))
5790 extractfun comparefun)
5791 ;; Define the appropriate functions
5792 (cond
5793 ((= dcst ?n)
5794 (setq extractfun 'string-to-number
5795 comparefun (if (= dcst sorting-type) '< '>)))
5796 ((= dcst ?a)
5797 (setq extractfun (if with-case 'identity 'downcase)
5798 comparefun (if (= dcst sorting-type)
5799 'string<
5800 (lambda (a b) (and (not (string< a b))
5801 (not (string= a b)))))))
5802 ((= dcst ?t)
5803 (setq extractfun
5804 (lambda (x)
5805 (if (string-match org-ts-regexp x)
5806 (time-to-seconds
5807 (org-time-string-to-time (match-string 0 x)))
5809 comparefun (if (= dcst sorting-type) '< '>)))
5810 (t (error "Invalid sorting type `%c'" sorting-type)))
5812 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5813 table)
5814 (lambda (a b) (funcall comparefun (car a) (car b))))))
5816 ;;;; Plain list items, including checkboxes
5818 ;;; Plain list items
5820 (defun org-at-item-p ()
5821 "Is point in a line starting a hand-formatted item?"
5822 (let ((llt org-plain-list-ordered-item-terminator))
5823 (save-excursion
5824 (goto-char (point-at-bol))
5825 (looking-at
5826 (cond
5827 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5828 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5829 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5830 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5832 (defun org-in-item-p ()
5833 "It the cursor inside a plain list item.
5834 Does not have to be the first line."
5835 (save-excursion
5836 (condition-case nil
5837 (progn
5838 (org-beginning-of-item)
5839 (org-at-item-p)
5841 (error nil))))
5843 (defun org-insert-item (&optional checkbox)
5844 "Insert a new item at the current level.
5845 Return t when things worked, nil when we are not in an item."
5846 (when (save-excursion
5847 (condition-case nil
5848 (progn
5849 (org-beginning-of-item)
5850 (org-at-item-p)
5851 (if (org-invisible-p) (error "Invisible item"))
5853 (error nil)))
5854 (let* ((bul (match-string 0))
5855 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5856 (match-end 0)))
5857 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5858 pos)
5859 (cond
5860 ((and (org-at-item-p) (<= (point) eow))
5861 ;; before the bullet
5862 (beginning-of-line 1)
5863 (open-line (if blank 2 1)))
5864 ((<= (point) eow)
5865 (beginning-of-line 1))
5866 (t (newline (if blank 2 1))))
5867 (insert bul (if checkbox "[ ]" ""))
5868 (just-one-space)
5869 (setq pos (point))
5870 (end-of-line 1)
5871 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5872 (org-maybe-renumber-ordered-list)
5873 (and checkbox (org-update-checkbox-count-maybe))
5876 ;;; Checkboxes
5878 (defun org-at-item-checkbox-p ()
5879 "Is point at a line starting a plain-list item with a checklet?"
5880 (and (org-at-item-p)
5881 (save-excursion
5882 (goto-char (match-end 0))
5883 (skip-chars-forward " \t")
5884 (looking-at "\\[[- X]\\]"))))
5886 (defun org-toggle-checkbox (&optional arg)
5887 "Toggle the checkbox in the current line."
5888 (interactive "P")
5889 (catch 'exit
5890 (let (beg end status (firstnew 'unknown))
5891 (cond
5892 ((org-region-active-p)
5893 (setq beg (region-beginning) end (region-end)))
5894 ((org-on-heading-p)
5895 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5896 ((org-at-item-checkbox-p)
5897 (save-excursion
5898 (replace-match
5899 (cond (arg "[-]")
5900 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5901 (t "[ ]"))
5902 t t))
5903 (throw 'exit t))
5904 (t (error "Not at a checkbox or heading, and no active region")))
5905 (save-excursion
5906 (goto-char beg)
5907 (while (< (point) end)
5908 (when (org-at-item-checkbox-p)
5909 (setq status (equal (match-string 0) "[X]"))
5910 (when (eq firstnew 'unknown)
5911 (setq firstnew (not status)))
5912 (replace-match
5913 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5914 (beginning-of-line 2)))))
5915 (org-update-checkbox-count-maybe))
5917 (defun org-update-checkbox-count-maybe ()
5918 "Update checkbox statistics unless turned off by user."
5919 (when org-provide-checkbox-statistics
5920 (org-update-checkbox-count)))
5922 (defun org-update-checkbox-count (&optional all)
5923 "Update the checkbox statistics in the current section.
5924 This will find all statistic cookies like [57%] and [6/12] and update them
5925 with the current numbers. With optional prefix argument ALL, do this for
5926 the whole buffer."
5927 (interactive "P")
5928 (save-excursion
5929 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5930 (beg (condition-case nil
5931 (progn (outline-back-to-heading) (point))
5932 (error (point-min))))
5933 (end (move-marker (make-marker)
5934 (progn (outline-next-heading) (point))))
5935 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
5936 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5937 b1 e1 f1 c-on c-off lim (cstat 0))
5938 (when all
5939 (goto-char (point-min))
5940 (outline-next-heading)
5941 (setq beg (point) end (point-max)))
5942 (goto-char beg)
5943 (while (re-search-forward re end t)
5944 (setq cstat (1+ cstat)
5945 b1 (match-beginning 0)
5946 e1 (match-end 0)
5947 f1 (match-beginning 1)
5948 lim (cond
5949 ((org-on-heading-p) (outline-next-heading) (point))
5950 ((org-at-item-p) (org-end-of-item) (point))
5951 (t nil))
5952 c-on 0 c-off 0)
5953 (goto-char e1)
5954 (when lim
5955 (while (re-search-forward re-box lim t)
5956 (if (member (match-string 2) '("[ ]" "[-]"))
5957 (setq c-off (1+ c-off))
5958 (setq c-on (1+ c-on))))
5959 ; (delete-region b1 e1)
5960 (goto-char b1)
5961 (insert (if f1
5962 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5963 (format "[%d/%d]" c-on (+ c-on c-off))))
5964 (and (looking-at "\\[.*?\\]")
5965 (replace-match ""))))
5966 (when (interactive-p)
5967 (message "Checkbox satistics updated %s (%d places)"
5968 (if all "in entire file" "in current outline entry") cstat)))))
5970 (defun org-get-checkbox-statistics-face ()
5971 "Select the face for checkbox statistics.
5972 The face will be `org-done' when all relevant boxes are checked. Otherwise
5973 it will be `org-todo'."
5974 (if (match-end 1)
5975 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5976 (if (and (> (match-end 2) (match-beginning 2))
5977 (equal (match-string 2) (match-string 3)))
5978 'org-done
5979 'org-todo)))
5981 (defun org-get-indentation (&optional line)
5982 "Get the indentation of the current line, interpreting tabs.
5983 When LINE is given, assume it represents a line and compute its indentation."
5984 (if line
5985 (if (string-match "^ *" (org-remove-tabs line))
5986 (match-end 0))
5987 (save-excursion
5988 (beginning-of-line 1)
5989 (skip-chars-forward " \t")
5990 (current-column))))
5992 (defun org-remove-tabs (s &optional width)
5993 "Replace tabulators in S with spaces.
5994 Assumes that s is a single line, starting in column 0."
5995 (setq width (or width tab-width))
5996 (while (string-match "\t" s)
5997 (setq s (replace-match
5998 (make-string
5999 (- (* width (/ (+ (match-beginning 0) width) width))
6000 (match-beginning 0)) ?\ )
6001 t t s)))
6004 (defun org-fix-indentation (line ind)
6005 "Fix indentation in LINE.
6006 IND is a cons cell with target and minimum indentation.
6007 If the current indenation in LINE is smaller than the minimum,
6008 leave it alone. If it is larger than ind, set it to the target."
6009 (let* ((l (org-remove-tabs line))
6010 (i (org-get-indentation l))
6011 (i1 (car ind)) (i2 (cdr ind)))
6012 (if (>= i i2) (setq l (substring line i2)))
6013 (if (> i1 0)
6014 (concat (make-string i1 ?\ ) l)
6015 l)))
6017 (defcustom org-empty-line-terminates-plain-lists nil
6018 "Non-nil means, an empty line ends all plain list levels.
6019 When nil, empty lines are part of the preceeding item."
6020 :group 'org-plain-lists
6021 :type 'boolean)
6023 (defun org-beginning-of-item ()
6024 "Go to the beginning of the current hand-formatted item.
6025 If the cursor is not in an item, throw an error."
6026 (interactive)
6027 (let ((pos (point))
6028 (limit (save-excursion
6029 (condition-case nil
6030 (progn
6031 (org-back-to-heading)
6032 (beginning-of-line 2) (point))
6033 (error (point-min)))))
6034 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6035 ind ind1)
6036 (if (org-at-item-p)
6037 (beginning-of-line 1)
6038 (beginning-of-line 1)
6039 (skip-chars-forward " \t")
6040 (setq ind (current-column))
6041 (if (catch 'exit
6042 (while t
6043 (beginning-of-line 0)
6044 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6046 (if (looking-at "[ \t]*$")
6047 (setq ind1 ind-empty)
6048 (skip-chars-forward " \t")
6049 (setq ind1 (current-column)))
6050 (if (< ind1 ind)
6051 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6053 (goto-char pos)
6054 (error "Not in an item")))))
6056 (defun org-end-of-item ()
6057 "Go to the end of the current hand-formatted item.
6058 If the cursor is not in an item, throw an error."
6059 (interactive)
6060 (let* ((pos (point))
6061 ind1
6062 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6063 (limit (save-excursion (outline-next-heading) (point)))
6064 (ind (save-excursion
6065 (org-beginning-of-item)
6066 (skip-chars-forward " \t")
6067 (current-column)))
6068 (end (catch 'exit
6069 (while t
6070 (beginning-of-line 2)
6071 (if (eobp) (throw 'exit (point)))
6072 (if (>= (point) limit) (throw 'exit (point-at-bol)))
6073 (if (looking-at "[ \t]*$")
6074 (setq ind1 ind-empty)
6075 (skip-chars-forward " \t")
6076 (setq ind1 (current-column)))
6077 (if (<= ind1 ind)
6078 (throw 'exit (point-at-bol)))))))
6079 (if end
6080 (goto-char end)
6081 (goto-char pos)
6082 (error "Not in an item"))))
6084 (defun org-next-item ()
6085 "Move to the beginning of the next item in the current plain list.
6086 Error if not at a plain list, or if this is the last item in the list."
6087 (interactive)
6088 (let (ind ind1 (pos (point)))
6089 (org-beginning-of-item)
6090 (setq ind (org-get-indentation))
6091 (org-end-of-item)
6092 (setq ind1 (org-get-indentation))
6093 (unless (and (org-at-item-p) (= ind ind1))
6094 (goto-char pos)
6095 (error "On last item"))))
6097 (defun org-previous-item ()
6098 "Move to the beginning of the previous item in the current plain list.
6099 Error if not at a plain list, or if this is the first item in the list."
6100 (interactive)
6101 (let (beg ind ind1 (pos (point)))
6102 (org-beginning-of-item)
6103 (setq beg (point))
6104 (setq ind (org-get-indentation))
6105 (goto-char beg)
6106 (catch 'exit
6107 (while t
6108 (beginning-of-line 0)
6109 (if (looking-at "[ \t]*$")
6111 (if (<= (setq ind1 (org-get-indentation)) ind)
6112 (throw 'exit t)))))
6113 (condition-case nil
6114 (if (or (not (org-at-item-p))
6115 (< ind1 (1- ind)))
6116 (error "")
6117 (org-beginning-of-item))
6118 (error (goto-char pos)
6119 (error "On first item")))))
6121 (defun org-move-item-down ()
6122 "Move the plain list item at point down, i.e. swap with following item.
6123 Subitems (items with larger indentation) are considered part of the item,
6124 so this really moves item trees."
6125 (interactive)
6126 (let (beg end ind ind1 (pos (point)) txt)
6127 (org-beginning-of-item)
6128 (setq beg (point))
6129 (setq ind (org-get-indentation))
6130 (org-end-of-item)
6131 (setq end (point))
6132 (setq ind1 (org-get-indentation))
6133 (if (and (org-at-item-p) (= ind ind1))
6134 (progn
6135 (org-end-of-item)
6136 (setq txt (buffer-substring beg end))
6137 (save-excursion
6138 (delete-region beg end))
6139 (setq pos (point))
6140 (insert txt)
6141 (goto-char pos)
6142 (org-maybe-renumber-ordered-list))
6143 (goto-char pos)
6144 (error "Cannot move this item further down"))))
6146 (defun org-move-item-up (arg)
6147 "Move the plain list item at point up, i.e. swap with previous item.
6148 Subitems (items with larger indentation) are considered part of the item,
6149 so this really moves item trees."
6150 (interactive "p")
6151 (let (beg end ind ind1 (pos (point)) txt)
6152 (org-beginning-of-item)
6153 (setq beg (point))
6154 (setq ind (org-get-indentation))
6155 (org-end-of-item)
6156 (setq end (point))
6157 (goto-char beg)
6158 (catch 'exit
6159 (while t
6160 (beginning-of-line 0)
6161 (if (looking-at "[ \t]*$")
6162 (if org-empty-line-terminates-plain-lists
6163 (progn
6164 (goto-char pos)
6165 (error "Cannot move this item further up"))
6166 nil)
6167 (if (<= (setq ind1 (org-get-indentation)) ind)
6168 (throw 'exit t)))))
6169 (condition-case nil
6170 (org-beginning-of-item)
6171 (error (goto-char beg)
6172 (error "Cannot move this item further up")))
6173 (setq ind1 (org-get-indentation))
6174 (if (and (org-at-item-p) (= ind ind1))
6175 (progn
6176 (setq txt (buffer-substring beg end))
6177 (save-excursion
6178 (delete-region beg end))
6179 (setq pos (point))
6180 (insert txt)
6181 (goto-char pos)
6182 (org-maybe-renumber-ordered-list))
6183 (goto-char pos)
6184 (error "Cannot move this item further up"))))
6186 (defun org-maybe-renumber-ordered-list ()
6187 "Renumber the ordered list at point if setup allows it.
6188 This tests the user option `org-auto-renumber-ordered-lists' before
6189 doing the renumbering."
6190 (interactive)
6191 (when (and org-auto-renumber-ordered-lists
6192 (org-at-item-p))
6193 (if (match-beginning 3)
6194 (org-renumber-ordered-list 1)
6195 (org-fix-bullet-type 1))))
6197 (defun org-maybe-renumber-ordered-list-safe ()
6198 (condition-case nil
6199 (save-excursion
6200 (org-maybe-renumber-ordered-list))
6201 (error nil)))
6203 (defun org-cycle-list-bullet (&optional which)
6204 "Cycle through the different itemize/enumerate bullets.
6205 This cycle the entire list level through the sequence:
6207 `-' -> `+' -> `*' -> `1.' -> `1)'
6209 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6210 0 meand `-', 1 means `+' etc."
6211 (interactive "P")
6212 (org-preserve-lc
6213 (org-beginning-of-item-list)
6214 (org-at-item-p)
6215 (beginning-of-line 1)
6216 (let ((current (match-string 0)) new)
6217 (setq new (cond
6218 ((and which (nth (1- which) '("-" "+" "*" "1." "1)"))))
6219 ((string-match "-" current) "+")
6220 ((string-match "\\+" current)
6221 (if (looking-at "\\S-") "1." "*"))
6222 ((string-match "\\*" current) "1.")
6223 ((string-match "\\." current) "1)")
6224 ((string-match ")" current) "-")
6225 (t (error "This should not happen"))))
6226 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6227 (org-fix-bullet-type 1)
6228 (org-maybe-renumber-ordered-list))))
6230 (defun org-get-string-indentation (s)
6231 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6232 (let ((n -1) (i 0) (w tab-width) c)
6233 (catch 'exit
6234 (while (< (setq n (1+ n)) (length s))
6235 (setq c (aref s n))
6236 (cond ((= c ?\ ) (setq i (1+ i)))
6237 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6238 (t (throw 'exit t)))))
6241 (defun org-renumber-ordered-list (arg)
6242 "Renumber an ordered plain list.
6243 Cursor needs to be in the first line of an item, the line that starts
6244 with something like \"1.\" or \"2)\"."
6245 (interactive "p")
6246 (unless (and (org-at-item-p)
6247 (match-beginning 3))
6248 (error "This is not an ordered list"))
6249 (let ((line (org-current-line))
6250 (col (current-column))
6251 (ind (org-get-string-indentation
6252 (buffer-substring (point-at-bol) (match-beginning 3))))
6253 ;; (term (substring (match-string 3) -1))
6254 ind1 (n (1- arg))
6255 fmt)
6256 ;; find where this list begins
6257 (org-beginning-of-item-list)
6258 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6259 (setq fmt (concat "%d" (match-string 1)))
6260 (beginning-of-line 0)
6261 ;; walk forward and replace these numbers
6262 (catch 'exit
6263 (while t
6264 (catch 'next
6265 (beginning-of-line 2)
6266 (if (eobp) (throw 'exit nil))
6267 (if (looking-at "[ \t]*$") (throw 'next nil))
6268 (skip-chars-forward " \t") (setq ind1 (current-column))
6269 (if (> ind1 ind) (throw 'next t))
6270 (if (< ind1 ind) (throw 'exit t))
6271 (if (not (org-at-item-p)) (throw 'exit nil))
6272 (delete-region (match-beginning 2) (match-end 2))
6273 (goto-char (match-beginning 2))
6274 (insert (format fmt (setq n (1+ n)))))))
6275 (goto-line line)
6276 (move-to-column col)))
6278 (defun org-fix-bullet-type (arg)
6279 "Make sure all items in this list have the same bullet."
6280 (interactive "p")
6281 (unless (org-at-item-p) (error "This is not a list"))
6282 (let ((line (org-current-line))
6283 (col (current-column))
6284 (ind (current-indentation))
6285 ind1 bullet)
6286 ;; find where this list begins
6287 (org-beginning-of-item-list)
6288 (beginning-of-line 1)
6289 ;; find out what the bullet type is
6290 (looking-at "[ \t]*\\(\\S-+\\)")
6291 (setq bullet (match-string 1))
6292 ;; walk forward and replace these numbers
6293 (beginning-of-line 0)
6294 (catch 'exit
6295 (while t
6296 (catch 'next
6297 (beginning-of-line 2)
6298 (if (eobp) (throw 'exit nil))
6299 (if (looking-at "[ \t]*$") (throw 'next nil))
6300 (skip-chars-forward " \t") (setq ind1 (current-column))
6301 (if (> ind1 ind) (throw 'next t))
6302 (if (< ind1 ind) (throw 'exit t))
6303 (if (not (org-at-item-p)) (throw 'exit nil))
6304 (skip-chars-forward " \t")
6305 (looking-at "\\S-+")
6306 (replace-match bullet))))
6307 (goto-line line)
6308 (move-to-column col)
6309 (if (string-match "[0-9]" bullet)
6310 (org-renumber-ordered-list 1))))
6312 (defun org-beginning-of-item-list ()
6313 "Go to the beginning of the current item list.
6314 I.e. to the first item in this list."
6315 (interactive)
6316 (org-beginning-of-item)
6317 (let ((pos (point-at-bol))
6318 (ind (org-get-indentation))
6319 ind1)
6320 ;; find where this list begins
6321 (catch 'exit
6322 (while t
6323 (catch 'next
6324 (beginning-of-line 0)
6325 (if (looking-at "[ \t]*$")
6326 (throw (if (bobp) 'exit 'next) t))
6327 (skip-chars-forward " \t") (setq ind1 (current-column))
6328 (if (or (< ind1 ind)
6329 (and (= ind1 ind)
6330 (not (org-at-item-p)))
6331 (bobp))
6332 (throw 'exit t)
6333 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6334 (goto-char pos)))
6336 (defvar org-last-indent-begin-marker (make-marker))
6337 (defvar org-last-indent-end-marker (make-marker))
6339 (defun org-outdent-item (arg)
6340 "Outdent a local list item."
6341 (interactive "p")
6342 (org-indent-item (- arg)))
6344 (defun org-indent-item (arg)
6345 "Indent a local list item."
6346 (interactive "p")
6347 (unless (org-at-item-p)
6348 (error "Not on an item"))
6349 (save-excursion
6350 (let (beg end ind ind1 tmp delta ind-down ind-up)
6351 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6352 (setq beg org-last-indent-begin-marker
6353 end org-last-indent-end-marker)
6354 (org-beginning-of-item)
6355 (setq beg (move-marker org-last-indent-begin-marker (point)))
6356 (org-end-of-item)
6357 (setq end (move-marker org-last-indent-end-marker (point))))
6358 (goto-char beg)
6359 (setq tmp (org-item-indent-positions)
6360 ind (car tmp)
6361 ind-down (nth 2 tmp)
6362 ind-up (nth 1 tmp)
6363 delta (if (> arg 0)
6364 (if ind-down (- ind-down ind) 2)
6365 (if ind-up (- ind-up ind) -2)))
6366 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6367 (while (< (point) end)
6368 (beginning-of-line 1)
6369 (skip-chars-forward " \t") (setq ind1 (current-column))
6370 (delete-region (point-at-bol) (point))
6371 (or (eolp) (indent-to-column (+ ind1 delta)))
6372 (beginning-of-line 2))))
6373 (org-maybe-renumber-ordered-list-safe)
6374 (save-excursion
6375 (beginning-of-line 0)
6376 (condition-case nil (org-beginning-of-item) (error nil))
6377 (org-maybe-renumber-ordered-list-safe)))
6380 (defun org-item-indent-positions ()
6381 "Assumes cursor in item line. FIXME"
6382 (let* ((bolpos (point-at-bol))
6383 (ind (org-get-indentation))
6384 ind-down ind-up pos)
6385 (save-excursion
6386 (org-beginning-of-item-list)
6387 (skip-chars-backward "\n\r \t")
6388 (when (org-in-item-p)
6389 (org-beginning-of-item)
6390 (setq ind-up (org-get-indentation))))
6391 (setq pos (point))
6392 (save-excursion
6393 (cond
6394 ((and (condition-case nil (progn (org-previous-item) t)
6395 (error nil))
6396 (or (forward-char 1) t)
6397 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6398 (setq ind-down (org-get-indentation)))
6399 ((and (goto-char pos)
6400 (org-at-item-p))
6401 (goto-char (match-end 0))
6402 (skip-chars-forward " \t")
6403 (setq ind-down (current-column)))))
6404 (list ind ind-up ind-down)))
6406 ;;; The orgstruct minor mode
6408 ;; Define a minor mode which can be used in other modes in order to
6409 ;; integrate the org-mode structure editing commands.
6411 ;; This is really a hack, because the org-mode structure commands use
6412 ;; keys which normally belong to the major mode. Here is how it
6413 ;; works: The minor mode defines all the keys necessary to operate the
6414 ;; structure commands, but wraps the commands into a function which
6415 ;; tests if the cursor is currently at a headline or a plain list
6416 ;; item. If that is the case, the structure command is used,
6417 ;; temporarily setting many Org-mode variables like regular
6418 ;; expressions for filling etc. However, when any of those keys is
6419 ;; used at a different location, function uses `key-binding' to look
6420 ;; up if the key has an associated command in another currently active
6421 ;; keymap (minor modes, major mode, global), and executes that
6422 ;; command. There might be problems if any of the keys is otherwise
6423 ;; used as a prefix key.
6425 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6426 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6427 ;; addresses this by checking explicitly for both bindings.
6429 (defvar orgstruct-mode-map (make-sparse-keymap)
6430 "Keymap for the minor `orgstruct-mode'.")
6432 ;;;###autoload
6433 (define-minor-mode orgstruct-mode
6434 "Toggle the minor more `orgstruct-mode'.
6435 This mode is for using Org-mode structure commands in other modes.
6436 The following key behave as if Org-mode was active, if the cursor
6437 is on a headline, or on a plain list item (both in the definition
6438 of Org-mode).
6440 M-up Move entry/item up
6441 M-down Move entry/item down
6442 M-left Promote
6443 M-right Demote
6444 M-S-up Move entry/item up
6445 M-S-down Move entry/item down
6446 M-S-left Promote subtree
6447 M-S-right Demote subtree
6448 M-q Fill paragraph and items like in Org-mode
6449 C-c ^ Sort entries
6450 C-c - Cycle list bullet
6451 TAB Cycle item visibility
6452 M-RET Insert new heading/item
6453 S-M-RET Insert new TODO heading / Chekbox item
6454 C-c C-c Set tags / toggle checkbox"
6455 nil " OrgStruct" nil
6456 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6458 ;;;###autoload
6459 (defun turn-on-orgstruct ()
6460 "Unconditionally turn on `orgstruct-mode'."
6461 (orgstruct-mode 1))
6463 (defun orgstruct-error ()
6464 "Error when there is no default binding for a structure key."
6465 (interactive)
6466 (error "This key is has no function outside structure elements"))
6468 (defvar org-local-vars nil
6469 "List of local variables, for use by `orgstruct-mode'")
6471 (defun orgstruct-setup ()
6472 "Setup orgstruct keymaps."
6473 (let ((nfunc 0)
6474 (bindings
6475 (list
6476 '([(meta up)] org-metaup)
6477 '([(meta down)] org-metadown)
6478 '([(meta left)] org-metaleft)
6479 '([(meta right)] org-metaright)
6480 '([(meta shift up)] org-shiftmetaup)
6481 '([(meta shift down)] org-shiftmetadown)
6482 '([(meta shift left)] org-shiftmetaleft)
6483 '([(meta shift right)] org-shiftmetaright)
6484 '([(shift up)] org-shiftup)
6485 '([(shift down)] org-shiftdown)
6486 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6487 '("\M-q" fill-paragraph)
6488 '("\C-c^" org-sort)
6489 '("\C-c-" org-cycle-list-bullet)))
6490 elt key fun cmd)
6491 (while (setq elt (pop bindings))
6492 (setq nfunc (1+ nfunc))
6493 (setq key (org-key (car elt))
6494 fun (nth 1 elt)
6495 cmd (orgstruct-make-binding fun nfunc key))
6496 (org-defkey orgstruct-mode-map key cmd))
6498 ;; Special treatment needed for TAB and RET
6499 (org-defkey orgstruct-mode-map [(tab)]
6500 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6501 (org-defkey orgstruct-mode-map "\C-i"
6502 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6504 (org-defkey orgstruct-mode-map "\M-\C-m"
6505 (orgstruct-make-binding 'org-insert-heading 105
6506 "\M-\C-m" [(meta return)]))
6507 (org-defkey orgstruct-mode-map [(meta return)]
6508 (orgstruct-make-binding 'org-insert-heading 106
6509 [(meta return)] "\M-\C-m"))
6511 (org-defkey orgstruct-mode-map [(shift meta return)]
6512 (orgstruct-make-binding 'org-insert-todo-heading 107
6513 [(meta return)] "\M-\C-m"))
6515 (unless org-local-vars
6516 (setq org-local-vars (org-get-local-variables)))
6520 (defun orgstruct-make-binding (fun n &rest keys)
6521 "Create a function for binding in the structure minor mode.
6522 FUN is the command to call inside a table. N is used to create a unique
6523 command name. KEYS are keys that should be checked in for a command
6524 to execute outside of tables."
6525 (eval
6526 (list 'defun
6527 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6528 '(arg)
6529 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6530 "Outside of structure, run the binding of `"
6531 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6532 "'.")
6533 '(interactive "p")
6534 (list 'if
6535 '(org-context-p 'headline 'item)
6536 (list 'org-run-like-in-org-mode (list 'quote fun))
6537 (list 'let '(orgstruct-mode)
6538 (list 'call-interactively
6539 (append '(or)
6540 (mapcar (lambda (k)
6541 (list 'key-binding k))
6542 keys)
6543 '('orgstruct-error))))))))
6545 (defun org-context-p (&rest contexts)
6546 "FIXME:"
6547 (let ((pos (point)))
6548 (goto-char (point-at-bol))
6549 (prog1 (or (and (memq 'table contexts)
6550 (looking-at "[ \t]*|"))
6551 (and (memq 'headline contexts)
6552 (looking-at "\\*+"))
6553 (and (memq 'item contexts)
6554 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6555 (goto-char pos))))
6557 (defun org-get-local-variables ()
6558 "Return a list of all local variables in an org-mode buffer."
6559 (let (varlist)
6560 (with-current-buffer (get-buffer-create "*Org tmp*")
6561 (erase-buffer)
6562 (org-mode)
6563 (setq varlist (buffer-local-variables)))
6564 (kill-buffer "*Org tmp*")
6565 (delq nil
6566 (mapcar
6567 (lambda (x)
6568 (setq x
6569 (if (symbolp x)
6570 (list x)
6571 (list (car x) (list 'quote (cdr x)))))
6572 (if (string-match
6573 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6574 (symbol-name (car x)))
6575 x nil))
6576 varlist))))
6578 ;;;###autoload
6579 (defun org-run-like-in-org-mode (cmd)
6580 (unless org-local-vars
6581 (setq org-local-vars (org-get-local-variables)))
6582 (eval (list 'let org-local-vars
6583 (list 'call-interactively (list 'quote cmd)))))
6585 ;;;; Archiving
6587 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
6589 (defun org-archive-subtree (&optional find-done)
6590 "Move the current subtree to the archive.
6591 The archive can be a certain top-level heading in the current file, or in
6592 a different file. The tree will be moved to that location, the subtree
6593 heading be marked DONE, and the current time will be added.
6595 When called with prefix argument FIND-DONE, find whole trees without any
6596 open TODO items and archive them (after getting confirmation from the user).
6597 If the cursor is not at a headline when this comand is called, try all level
6598 1 trees. If the cursor is on a headline, only try the direct children of
6599 this heading."
6600 (interactive "P")
6601 (if find-done
6602 (org-archive-all-done)
6603 ;; Save all relevant TODO keyword-relatex variables
6605 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
6606 (tr-org-todo-keywords-1 org-todo-keywords-1)
6607 (tr-org-todo-kwd-alist org-todo-kwd-alist)
6608 (tr-org-done-keywords org-done-keywords)
6609 (tr-org-todo-regexp org-todo-regexp)
6610 (tr-org-todo-line-regexp org-todo-line-regexp)
6611 (tr-org-odd-levels-only org-odd-levels-only)
6612 (this-buffer (current-buffer))
6613 (org-archive-location org-archive-location)
6614 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
6615 file heading buffer level newfile-p)
6617 ;; Try to find a local archive location
6618 (save-excursion
6619 (save-restriction
6620 (widen)
6621 (if (or (re-search-backward re nil t) (re-search-forward re nil t))
6622 (setq org-archive-location (match-string 1)))))
6624 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
6625 (progn
6626 (setq file (format (match-string 1 org-archive-location)
6627 (file-name-nondirectory buffer-file-name))
6628 heading (match-string 2 org-archive-location)))
6629 (error "Invalid `org-archive-location'"))
6630 (if (> (length file) 0)
6631 (setq newfile-p (not (file-exists-p file))
6632 buffer (find-file-noselect file))
6633 (setq buffer (current-buffer)))
6634 (unless buffer
6635 (error "Cannot access file \"%s\"" file))
6636 (if (and (> (length heading) 0)
6637 (string-match "^\\*+" heading))
6638 (setq level (match-end 0))
6639 (setq heading nil level 0))
6640 (save-excursion
6641 ;; We first only copy, in case something goes wrong
6642 ;; we need to protect this-command, to avoid kill-region sets it,
6643 ;; which would lead to duplication of subtrees
6644 (let (this-command) (org-copy-subtree))
6645 (set-buffer buffer)
6646 ;; Enforce org-mode for the archive buffer
6647 (if (not (org-mode-p))
6648 ;; Force the mode for future visits.
6649 (let ((org-insert-mode-line-in-empty-file t)
6650 (org-inhibit-startup t))
6651 (call-interactively 'org-mode)))
6652 (when newfile-p
6653 (goto-char (point-max))
6654 (insert (format "\nArchived entries from file %s\n\n"
6655 (buffer-file-name this-buffer))))
6656 ;; Force the TODO keywords of the original buffer
6657 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
6658 (org-todo-keywords-1 tr-org-todo-keywords-1)
6659 (org-todo-kwd-alist tr-org-todo-kwd-alist)
6660 (org-done-keywords tr-org-done-keywords)
6661 (org-todo-regexp tr-org-todo-regexp)
6662 (org-todo-line-regexp tr-org-todo-line-regexp)
6663 (org-odd-levels-only
6664 (if (local-variable-p 'org-odd-levels-only (current-buffer))
6665 org-odd-levels-only
6666 tr-org-odd-levels-only)))
6667 (goto-char (point-min))
6668 (if heading
6669 (progn
6670 (if (re-search-forward
6671 (concat "^" (regexp-quote heading)
6672 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
6673 nil t)
6674 (goto-char (match-end 0))
6675 ;; Heading not found, just insert it at the end
6676 (goto-char (point-max))
6677 (or (bolp) (insert "\n"))
6678 (insert "\n" heading "\n")
6679 (end-of-line 0))
6680 ;; Make the subtree visible
6681 (show-subtree)
6682 (org-end-of-subtree t)
6683 (skip-chars-backward " \t\r\n")
6684 (and (looking-at "[ \t\r\n]*")
6685 (replace-match "\n\n")))
6686 ;; No specific heading, just go to end of file.
6687 (goto-char (point-max)) (insert "\n"))
6688 ;; Paste
6689 (org-paste-subtree (org-get-legal-level level 1))
6691 ;; Mark the entry as done
6692 (when (and org-archive-mark-done
6693 (looking-at org-todo-line-regexp)
6694 (or (not (match-end 2))
6695 (not (member (match-string 2) org-done-keywords))))
6696 (let (org-log-done)
6697 (org-todo
6698 (car (or (member org-archive-mark-done org-done-keywords)
6699 org-done-keywords)))))
6701 ;; Move cursor to right after the TODO keyword
6702 (when org-archive-stamp-time
6703 (org-add-planning-info 'archived (org-current-time)))
6704 ;; Save the buffer, if it is not the same buffer.
6705 (if (not (eq this-buffer buffer)) (save-buffer))))
6706 ;; Here we are back in the original buffer. Everything seems to have
6707 ;; worked. So now cut the tree and finish up.
6708 (let (this-command) (org-cut-subtree))
6709 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
6710 (message "Subtree archived %s"
6711 (if (eq this-buffer buffer)
6712 (concat "under heading: " heading)
6713 (concat "in file: " (abbreviate-file-name file)))))))
6715 (defun org-archive-all-done (&optional tag)
6716 "Archive sublevels of the current tree without open TODO items.
6717 If the cursor is not on a headline, try all level 1 trees. If
6718 it is on a headline, try all direct children.
6719 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
6720 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
6721 (rea (concat ".*:" org-archive-tag ":"))
6722 (begm (make-marker))
6723 (endm (make-marker))
6724 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
6725 "Move subtree to archive (no open TODO items)? "))
6726 beg end (cntarch 0))
6727 (if (org-on-heading-p)
6728 (progn
6729 (setq re1 (concat "^" (regexp-quote
6730 (make-string
6731 (1+ (- (match-end 0) (match-beginning 0)))
6732 ?*))
6733 " "))
6734 (move-marker begm (point))
6735 (move-marker endm (org-end-of-subtree t)))
6736 (setq re1 "^* ")
6737 (move-marker begm (point-min))
6738 (move-marker endm (point-max)))
6739 (save-excursion
6740 (goto-char begm)
6741 (while (re-search-forward re1 endm t)
6742 (setq beg (match-beginning 0)
6743 end (save-excursion (org-end-of-subtree t) (point)))
6744 (goto-char beg)
6745 (if (re-search-forward re end t)
6746 (goto-char end)
6747 (goto-char beg)
6748 (if (and (or (not tag) (not (looking-at rea)))
6749 (y-or-n-p question))
6750 (progn
6751 (if tag
6752 (org-toggle-tag org-archive-tag 'on)
6753 (org-archive-subtree))
6754 (setq cntarch (1+ cntarch)))
6755 (goto-char end)))))
6756 (message "%d trees archived" cntarch)))
6758 (defun org-cycle-hide-drawers (state)
6759 "Re-hide all drawers after a visibility state change."
6760 (when (not (memq state '(overview folded)))
6761 (save-excursion
6762 (let* ((globalp (memq state '(contents all)))
6763 (beg (if globalp (point-min) (point)))
6764 (end (if globalp (point-max) (org-end-of-subtree t))))
6765 (goto-char beg)
6766 (while (re-search-forward org-drawer-regexp end t)
6767 (org-flag-drawer t))))))
6769 (defun org-flag-drawer (flag)
6770 (save-excursion
6771 (beginning-of-line 1)
6772 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6773 (let ((b (match-end 0)))
6774 (if (re-search-forward
6775 "^[ \t]*:END:"
6776 (save-excursion (outline-next-heading) (point)) t)
6777 (outline-flag-region b (point-at-eol) flag)
6778 (error ":END: line missing"))))))
6780 (defun org-cycle-hide-archived-subtrees (state)
6781 "Re-hide all archived subtrees after a visibility state change."
6782 (when (and (not org-cycle-open-archived-trees)
6783 (not (memq state '(overview folded))))
6784 (save-excursion
6785 (let* ((globalp (memq state '(contents all)))
6786 (beg (if globalp (point-min) (point)))
6787 (end (if globalp (point-max) (org-end-of-subtree t))))
6788 (org-hide-archived-subtrees beg end)
6789 (goto-char beg)
6790 (if (looking-at (concat ".*:" org-archive-tag ":"))
6791 (message (substitute-command-keys
6792 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
6794 (defun org-force-cycle-archived ()
6795 "Cycle subtree even if it is archived."
6796 (interactive)
6797 (setq this-command 'org-cycle)
6798 (let ((org-cycle-open-archived-trees t))
6799 (call-interactively 'org-cycle)))
6801 (defun org-hide-archived-subtrees (beg end)
6802 "Re-hide all archived subtrees after a visibility state change."
6803 (save-excursion
6804 (let* ((re (concat ":" org-archive-tag ":")))
6805 (goto-char beg)
6806 (while (re-search-forward re end t)
6807 (and (org-on-heading-p) (hide-subtree))
6808 (org-end-of-subtree t)))))
6810 (defun org-toggle-tag (tag &optional onoff)
6811 "Toggle the tag TAG for the current line.
6812 If ONOFF is `on' or `off', don't toggle but set to this state."
6813 (unless (org-on-heading-p t) (error "Not on headling"))
6814 (let (res current)
6815 (save-excursion
6816 (beginning-of-line)
6817 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
6818 (point-at-eol) t)
6819 (progn
6820 (setq current (match-string 1))
6821 (replace-match ""))
6822 (setq current ""))
6823 (setq current (nreverse (org-split-string current ":")))
6824 (cond
6825 ((eq onoff 'on)
6826 (setq res t)
6827 (or (member tag current) (push tag current)))
6828 ((eq onoff 'off)
6829 (or (not (member tag current)) (setq current (delete tag current))))
6830 (t (if (member tag current)
6831 (setq current (delete tag current))
6832 (setq res t)
6833 (push tag current))))
6834 (end-of-line 1)
6835 (when current
6836 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
6837 (org-set-tags nil t))
6838 res))
6840 (defun org-toggle-archive-tag (&optional arg)
6841 "Toggle the archive tag for the current headline.
6842 With prefix ARG, check all children of current headline and offer tagging
6843 the children that do not contain any open TODO items."
6844 (interactive "P")
6845 (if arg
6846 (org-archive-all-done 'tag)
6847 (let (set)
6848 (save-excursion
6849 (org-back-to-heading t)
6850 (setq set (org-toggle-tag org-archive-tag))
6851 (when set (hide-subtree)))
6852 (and set (beginning-of-line 1))
6853 (message "Subtree %s" (if set "archived" "unarchived")))))
6856 ;;;; Tables
6858 ;;; The table editor
6860 ;; Watch out: Here we are talking about two different kind of tables.
6861 ;; Most of the code is for the tables created with the Org-mode table editor.
6862 ;; Sometimes, we talk about tables created and edited with the table.el
6863 ;; Emacs package. We call the former org-type tables, and the latter
6864 ;; table.el-type tables.
6866 (defun org-before-change-function (beg end)
6867 "Every change indicates that a table might need an update."
6868 (setq org-table-may-need-update t))
6870 (defconst org-table-line-regexp "^[ \t]*|"
6871 "Detects an org-type table line.")
6872 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
6873 "Detects an org-type table line.")
6874 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
6875 "Detects a table line marked for automatic recalculation.")
6876 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
6877 "Detects a table line marked for automatic recalculation.")
6878 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
6879 "Detects a table line marked for automatic recalculation.")
6880 (defconst org-table-hline-regexp "^[ \t]*|-"
6881 "Detects an org-type table hline.")
6882 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
6883 "Detects a table-type table hline.")
6884 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
6885 "Detects an org-type or table-type table.")
6886 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
6887 "Searching from within a table (any type) this finds the first line
6888 outside the table.")
6889 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
6890 "Searching from within a table (any type) this finds the first line
6891 outside the table.")
6893 (defvar org-table-last-highlighted-reference nil)
6894 (defvar org-table-formula-history nil)
6896 (defvar org-table-column-names nil
6897 "Alist with column names, derived from the `!' line.")
6898 (defvar org-table-column-name-regexp nil
6899 "Regular expression matching the current column names.")
6900 (defvar org-table-local-parameters nil
6901 "Alist with parameter names, derived from the `$' line.")
6902 (defvar org-table-named-field-locations nil
6903 "Alist with locations of named fields.")
6905 (defvar org-table-current-line-types nil
6906 "Table row types, non-nil only for the duration of a comand.")
6907 (defvar org-table-current-begin-line nil
6908 "Table begin line, non-nil only for the duration of a comand.")
6909 (defvar org-table-current-begin-pos nil
6910 "Table begin position, non-nil only for the duration of a comand.")
6911 (defvar org-table-dlines nil
6912 "Vector of data line line numbers in the current table.")
6913 (defvar org-table-hlines nil
6914 "Vector of hline line numbers in the current table.")
6916 (defconst org-table-range-regexp
6917 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
6918 ;; 1 2 3 4 5
6919 "Regular expression for matching ranges in formulas.")
6921 (defconst org-table-range-regexp2
6922 (concat
6923 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
6924 "\\.\\."
6925 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
6926 "Match a range for reference display.")
6928 (defconst org-table-translate-regexp
6929 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
6930 "Match a reference that needs translation, for reference display.")
6932 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
6934 (defun org-table-create-with-table.el ()
6935 "Use the table.el package to insert a new table.
6936 If there is already a table at point, convert between Org-mode tables
6937 and table.el tables."
6938 (interactive)
6939 (require 'table)
6940 (cond
6941 ((org-at-table.el-p)
6942 (if (y-or-n-p "Convert table to Org-mode table? ")
6943 (org-table-convert)))
6944 ((org-at-table-p)
6945 (if (y-or-n-p "Convert table to table.el table? ")
6946 (org-table-convert)))
6947 (t (call-interactively 'table-insert))))
6949 (defun org-table-create-or-convert-from-region (arg)
6950 "Convert region to table, or create an empty table.
6951 If there is an active region, convert it to a table, using the function
6952 `org-table-convert-region'.
6953 If there is no such region, create an empty table with `org-table-create'."
6954 (interactive "P")
6955 (if (org-region-active-p)
6956 (org-table-convert-region (region-beginning) (region-end) arg)
6957 (org-table-create arg)))
6959 (defun org-table-create (&optional size)
6960 "Query for a size and insert a table skeleton.
6961 SIZE is a string Columns x Rows like for example \"3x2\"."
6962 (interactive "P")
6963 (unless size
6964 (setq size (read-string
6965 (concat "Table size Columns x Rows [e.g. "
6966 org-table-default-size "]: ")
6967 "" nil org-table-default-size)))
6969 (let* ((pos (point))
6970 (indent (make-string (current-column) ?\ ))
6971 (split (org-split-string size " *x *"))
6972 (rows (string-to-number (nth 1 split)))
6973 (columns (string-to-number (car split)))
6974 (line (concat (apply 'concat indent "|" (make-list columns " |"))
6975 "\n")))
6976 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
6977 (point-at-bol) (point)))
6978 (beginning-of-line 1)
6979 (newline))
6980 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
6981 (dotimes (i rows) (insert line))
6982 (goto-char pos)
6983 (if (> rows 1)
6984 ;; Insert a hline after the first row.
6985 (progn
6986 (end-of-line 1)
6987 (insert "\n|-")
6988 (goto-char pos)))
6989 (org-table-align)))
6991 (defun org-table-convert-region (beg0 end0 &optional nspace)
6992 "Convert region to a table.
6993 The region goes from BEG0 to END0, but these borders will be moved
6994 slightly, to make sure a beginning of line in the first line is included.
6995 When NSPACE is non-nil, it indicates the minimum number of spaces that
6996 separate columns. By default, the function first checks if every line
6997 contains at lease one TAB. If yes, it assumes that the material is TAB
6998 separated. If not, it assumes a single space as separator."
6999 (interactive "rP")
7000 (let* ((beg (min beg0 end0))
7001 (end (max beg0 end0))
7002 (tabsep t)
7004 (goto-char beg)
7005 (beginning-of-line 1)
7006 (setq beg (move-marker (make-marker) (point)))
7007 (goto-char end)
7008 (if (bolp) (backward-char 1) (end-of-line 1))
7009 (setq end (move-marker (make-marker) (point)))
7010 ;; Lets see if this is tab-separated material. If every nonempty line
7011 ;; contains a tab, we will assume that it is tab-separated material
7012 (if nspace
7013 (setq tabsep nil)
7014 (goto-char beg)
7015 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
7016 (if nspace (setq tabsep nil))
7017 (if tabsep
7018 (setq re "^\\|\t")
7019 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
7020 (max 1 (prefix-numeric-value nspace)))))
7021 (goto-char beg)
7022 (while (re-search-forward re end t)
7023 (replace-match "| " t t))
7024 (goto-char beg)
7025 (insert " ")
7026 (org-table-align)))
7028 (defun org-table-import (file arg)
7029 "Import FILE as a table.
7030 The file is assumed to be tab-separated. Such files can be produced by most
7031 spreadsheet and database applications. If no tabs (at least one per line)
7032 are found, lines will be split on whitespace into fields."
7033 (interactive "f\nP")
7034 (or (bolp) (newline))
7035 (let ((beg (point))
7036 (pm (point-max)))
7037 (insert-file-contents file)
7038 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7040 (defun org-table-export ()
7041 "Export table as a tab-separated file.
7042 Such a file can be imported into a spreadsheet program like Excel."
7043 (interactive)
7044 (let* ((beg (org-table-begin))
7045 (end (org-table-end))
7046 (table (buffer-substring beg end))
7047 (file (read-file-name "Export table to: "))
7048 buf)
7049 (unless (or (not (file-exists-p file))
7050 (y-or-n-p (format "Overwrite file %s? " file)))
7051 (error "Abort"))
7052 (with-current-buffer (find-file-noselect file)
7053 (setq buf (current-buffer))
7054 (erase-buffer)
7055 (fundamental-mode)
7056 (insert table)
7057 (goto-char (point-min))
7058 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7059 (replace-match "" t t)
7060 (end-of-line 1))
7061 (goto-char (point-min))
7062 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7063 (replace-match "" t t)
7064 (goto-char (min (1+ (point)) (point-max))))
7065 (goto-char (point-min))
7066 (while (re-search-forward "^-[-+]*$" nil t)
7067 (replace-match "")
7068 (if (looking-at "\n")
7069 (delete-char 1)))
7070 (goto-char (point-min))
7071 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7072 (replace-match "\t" t t))
7073 (save-buffer))
7074 (kill-buffer buf)))
7076 (defvar org-table-aligned-begin-marker (make-marker)
7077 "Marker at the beginning of the table last aligned.
7078 Used to check if cursor still is in that table, to minimize realignment.")
7079 (defvar org-table-aligned-end-marker (make-marker)
7080 "Marker at the end of the table last aligned.
7081 Used to check if cursor still is in that table, to minimize realignment.")
7082 (defvar org-table-last-alignment nil
7083 "List of flags for flushright alignment, from the last re-alignment.
7084 This is being used to correctly align a single field after TAB or RET.")
7085 (defvar org-table-last-column-widths nil
7086 "List of max width of fields in each column.
7087 This is being used to correctly align a single field after TAB or RET.")
7088 (defvar org-table-overlay-coordinates nil
7089 "Overlay coordinates after each align of a table.")
7090 (make-variable-buffer-local 'org-table-overlay-coordinates)
7092 (defvar org-last-recalc-line nil)
7093 (defconst org-narrow-column-arrow "=>"
7094 "Used as display property in narrowed table columns.")
7096 (defun org-table-align ()
7097 "Align the table at point by aligning all vertical bars."
7098 (interactive)
7099 (let* (
7100 ;; Limits of table
7101 (beg (org-table-begin))
7102 (end (org-table-end))
7103 ;; Current cursor position
7104 (linepos (org-current-line))
7105 (colpos (org-table-current-column))
7106 (winstart (window-start))
7107 (winstartline (org-current-line (min winstart (1- (point-max)))))
7108 lines (new "") lengths l typenums ty fields maxfields i
7109 column
7110 (indent "") cnt frac
7111 rfmt hfmt
7112 (spaces '(1 . 1))
7113 (sp1 (car spaces))
7114 (sp2 (cdr spaces))
7115 (rfmt1 (concat
7116 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7117 (hfmt1 (concat
7118 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7119 emptystrings links dates narrow fmax f1 len c e)
7120 (untabify beg end)
7121 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
7122 ;; Check if we have links or dates
7123 (goto-char beg)
7124 (setq links (re-search-forward org-bracket-link-regexp end t))
7125 (goto-char beg)
7126 (setq dates (and org-display-custom-times
7127 (re-search-forward org-ts-regexp-both end t)))
7128 ;; Make sure the link properties are right
7129 (when links (goto-char beg) (while (org-activate-bracket-links end)))
7130 ;; Make sure the date properties are right
7131 (when dates (goto-char beg) (while (org-activate-dates end)))
7133 ;; Check if we are narrowing any columns
7134 (goto-char beg)
7135 (setq narrow (and org-format-transports-properties-p
7136 (re-search-forward "<[0-9]+>" end t)))
7137 ;; Get the rows
7138 (setq lines (org-split-string
7139 (buffer-substring beg end) "\n"))
7140 ;; Store the indentation of the first line
7141 (if (string-match "^ *" (car lines))
7142 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7143 ;; Mark the hlines by setting the corresponding element to nil
7144 ;; At the same time, we remove trailing space.
7145 (setq lines (mapcar (lambda (l)
7146 (if (string-match "^ *|-" l)
7148 (if (string-match "[ \t]+$" l)
7149 (substring l 0 (match-beginning 0))
7150 l)))
7151 lines))
7152 ;; Get the data fields by splitting the lines.
7153 (setq fields (mapcar
7154 (lambda (l)
7155 (org-split-string l " *| *"))
7156 (delq nil (copy-sequence lines))))
7157 ;; How many fields in the longest line?
7158 (condition-case nil
7159 (setq maxfields (apply 'max (mapcar 'length fields)))
7160 (error
7161 (kill-region beg end)
7162 (org-table-create org-table-default-size)
7163 (error "Empty table - created default table")))
7164 ;; A list of empty strings to fill any short rows on output
7165 (setq emptystrings (make-list maxfields ""))
7166 ;; Check for special formatting.
7167 (setq i -1)
7168 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7169 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7170 ;; Check if there is an explicit width specified
7171 (when narrow
7172 (setq c column fmax nil)
7173 (while c
7174 (setq e (pop c))
7175 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
7176 (setq fmax (string-to-number (match-string 1 e)) c nil)))
7177 ;; Find fields that are wider than fmax, and shorten them
7178 (when fmax
7179 (loop for xx in column do
7180 (when (and (stringp xx)
7181 (> (org-string-width xx) fmax))
7182 (org-add-props xx nil
7183 'help-echo
7184 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
7185 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
7186 (unless (> f1 1)
7187 (error "Cannot narrow field starting with wide link \"%s\""
7188 (match-string 0 xx)))
7189 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
7190 (add-text-properties (- f1 2) f1
7191 (list 'display org-narrow-column-arrow)
7192 xx)))))
7193 ;; Get the maximum width for each column
7194 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
7195 ;; Get the fraction of numbers, to decide about alignment of the column
7196 (setq cnt 0 frac 0.0)
7197 (loop for x in column do
7198 (if (equal x "")
7200 (setq frac ( / (+ (* frac cnt)
7201 (if (string-match org-table-number-regexp x) 1 0))
7202 (setq cnt (1+ cnt))))))
7203 (push (>= frac org-table-number-fraction) typenums))
7204 (setq lengths (nreverse lengths) typenums (nreverse typenums))
7206 ;; Store the alignment of this table, for later editing of single fields
7207 (setq org-table-last-alignment typenums
7208 org-table-last-column-widths lengths)
7210 ;; With invisible characters, `format' does not get the field width right
7211 ;; So we need to make these fields wide by hand.
7212 (when links
7213 (loop for i from 0 upto (1- maxfields) do
7214 (setq len (nth i lengths))
7215 (loop for j from 0 upto (1- (length fields)) do
7216 (setq c (nthcdr i (car (nthcdr j fields))))
7217 (if (and (stringp (car c))
7218 (string-match org-bracket-link-regexp (car c))
7219 (< (org-string-width (car c)) len))
7220 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
7222 ;; Compute the formats needed for output of the table
7223 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7224 (while (setq l (pop lengths))
7225 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7226 (setq rfmt (concat rfmt (format rfmt1 ty l))
7227 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7228 (setq rfmt (concat rfmt "\n")
7229 hfmt (concat (substring hfmt 0 -1) "|\n"))
7231 (setq new (mapconcat
7232 (lambda (l)
7233 (if l (apply 'format rfmt
7234 (append (pop fields) emptystrings))
7235 hfmt))
7236 lines ""))
7237 ;; Replace the old one
7238 (delete-region beg end)
7239 (move-marker end nil)
7240 (move-marker org-table-aligned-begin-marker (point))
7241 (insert new)
7242 (move-marker org-table-aligned-end-marker (point))
7243 (when (and orgtbl-mode (not (org-mode-p)))
7244 (goto-char org-table-aligned-begin-marker)
7245 (while (org-hide-wide-columns org-table-aligned-end-marker)))
7246 ;; Try to move to the old location
7247 (goto-line winstartline)
7248 (setq winstart (point-at-bol))
7249 (goto-line linepos)
7250 (set-window-start (selected-window) winstart 'noforce)
7251 (org-table-goto-column colpos)
7252 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
7253 (setq org-table-may-need-update nil)
7256 (defun org-string-width (s)
7257 "Compute width of string, ignoring invisible characters.
7258 This ignores character with invisibility property `org-link', and also
7259 characters with property `org-cwidth', because these will become invisible
7260 upon the next fontification round."
7261 (let (b l)
7262 (when (or (eq t buffer-invisibility-spec)
7263 (assq 'org-link buffer-invisibility-spec))
7264 (while (setq b (text-property-any 0 (length s)
7265 'invisible 'org-link s))
7266 (setq s (concat (substring s 0 b)
7267 (substring s (or (next-single-property-change
7268 b 'invisible s) (length s)))))))
7269 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
7270 (setq s (concat (substring s 0 b)
7271 (substring s (or (next-single-property-change
7272 b 'org-cwidth s) (length s))))))
7273 (setq l (string-width s) b -1)
7274 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
7275 (setq l (- l (get-text-property b 'org-dwidth-n s))))
7278 (defun org-table-begin (&optional table-type)
7279 "Find the beginning of the table and return its position.
7280 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7281 (save-excursion
7282 (if (not (re-search-backward
7283 (if table-type org-table-any-border-regexp
7284 org-table-border-regexp)
7285 nil t))
7286 (progn (goto-char (point-min)) (point))
7287 (goto-char (match-beginning 0))
7288 (beginning-of-line 2)
7289 (point))))
7291 (defun org-table-end (&optional table-type)
7292 "Find the end of the table and return its position.
7293 With argument TABLE-TYPE, go to the end of a table.el-type table."
7294 (save-excursion
7295 (if (not (re-search-forward
7296 (if table-type org-table-any-border-regexp
7297 org-table-border-regexp)
7298 nil t))
7299 (goto-char (point-max))
7300 (goto-char (match-beginning 0)))
7301 (point-marker)))
7303 (defun org-table-justify-field-maybe (&optional new)
7304 "Justify the current field, text to left, number to right.
7305 Optional argument NEW may specify text to replace the current field content."
7306 (cond
7307 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7308 ((org-at-table-hline-p))
7309 ((and (not new)
7310 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7311 (current-buffer)))
7312 (< (point) org-table-aligned-begin-marker)
7313 (>= (point) org-table-aligned-end-marker)))
7314 ;; This is not the same table, force a full re-align
7315 (setq org-table-may-need-update t))
7316 (t ;; realign the current field, based on previous full realign
7317 (let* ((pos (point)) s
7318 (col (org-table-current-column))
7319 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
7320 l f n o e)
7321 (when (> col 0)
7322 (skip-chars-backward "^|\n")
7323 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7324 (progn
7325 (setq s (match-string 1)
7326 o (match-string 0)
7327 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7328 e (not (= (match-beginning 2) (match-end 2))))
7329 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7330 l (if e "|" (setq org-table-may-need-update t) ""))
7331 n (format f s))
7332 (if new
7333 (if (<= (length new) l) ;; FIXME: length -> str-width?
7334 (setq n (format f new))
7335 (setq n (concat new "|") org-table-may-need-update t)))
7336 (or (equal n o)
7337 (let (org-table-may-need-update)
7338 (replace-match n t t))))
7339 (setq org-table-may-need-update t))
7340 (goto-char pos))))))
7342 (defun org-table-next-field ()
7343 "Go to the next field in the current table, creating new lines as needed.
7344 Before doing so, re-align the table if necessary."
7345 (interactive)
7346 (org-table-maybe-eval-formula)
7347 (org-table-maybe-recalculate-line)
7348 (if (and org-table-automatic-realign
7349 org-table-may-need-update)
7350 (org-table-align))
7351 (let ((end (org-table-end)))
7352 (if (org-at-table-hline-p)
7353 (end-of-line 1))
7354 (condition-case nil
7355 (progn
7356 (re-search-forward "|" end)
7357 (if (looking-at "[ \t]*$")
7358 (re-search-forward "|" end))
7359 (if (and (looking-at "-")
7360 org-table-tab-jumps-over-hlines
7361 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7362 (goto-char (match-beginning 1)))
7363 (if (looking-at "-")
7364 (progn
7365 (beginning-of-line 0)
7366 (org-table-insert-row 'below))
7367 (if (looking-at " ") (forward-char 1))))
7368 (error
7369 (org-table-insert-row 'below)))))
7371 (defun org-table-previous-field ()
7372 "Go to the previous field in the table.
7373 Before doing so, re-align the table if necessary."
7374 (interactive)
7375 (org-table-justify-field-maybe)
7376 (org-table-maybe-recalculate-line)
7377 (if (and org-table-automatic-realign
7378 org-table-may-need-update)
7379 (org-table-align))
7380 (if (org-at-table-hline-p)
7381 (end-of-line 1))
7382 (re-search-backward "|" (org-table-begin))
7383 (re-search-backward "|" (org-table-begin))
7384 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7385 (re-search-backward "|" (org-table-begin)))
7386 (if (looking-at "| ?")
7387 (goto-char (match-end 0))))
7389 (defun org-table-next-row ()
7390 "Go to the next row (same column) in the current table.
7391 Before doing so, re-align the table if necessary."
7392 (interactive)
7393 (org-table-maybe-eval-formula)
7394 (org-table-maybe-recalculate-line)
7395 (if (or (looking-at "[ \t]*$")
7396 (save-excursion (skip-chars-backward " \t") (bolp)))
7397 (newline)
7398 (if (and org-table-automatic-realign
7399 org-table-may-need-update)
7400 (org-table-align))
7401 (let ((col (org-table-current-column)))
7402 (beginning-of-line 2)
7403 (if (or (not (org-at-table-p))
7404 (org-at-table-hline-p))
7405 (progn
7406 (beginning-of-line 0)
7407 (org-table-insert-row 'below)))
7408 (org-table-goto-column col)
7409 (skip-chars-backward "^|\n\r")
7410 (if (looking-at " ") (forward-char 1)))))
7412 (defun org-table-copy-down (n)
7413 "Copy a field down in the current column.
7414 If the field at the cursor is empty, copy into it the content of the nearest
7415 non-empty field above. With argument N, use the Nth non-empty field.
7416 If the current field is not empty, it is copied down to the next row, and
7417 the cursor is moved with it. Therefore, repeating this command causes the
7418 column to be filled row-by-row.
7419 If the variable `org-table-copy-increment' is non-nil and the field is an
7420 integer or a timestamp, it will be incremented while copying. In the case of
7421 a timestamp, if the cursor is on the year, change the year. If it is on the
7422 month or the day, change that. Point will stay on the current date field
7423 in order to easily repeat the interval."
7424 (interactive "p")
7425 (let* ((colpos (org-table-current-column))
7426 (col (current-column))
7427 (field (org-table-get-field))
7428 (non-empty (string-match "[^ \t]" field))
7429 (beg (org-table-begin))
7430 txt)
7431 (org-table-check-inside-data-field)
7432 (if non-empty
7433 (progn
7434 (setq txt (org-trim field))
7435 (org-table-next-row)
7436 (org-table-blank-field))
7437 (save-excursion
7438 (setq txt
7439 (catch 'exit
7440 (while (progn (beginning-of-line 1)
7441 (re-search-backward org-table-dataline-regexp
7442 beg t))
7443 (org-table-goto-column colpos t)
7444 (if (and (looking-at
7445 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7446 (= (setq n (1- n)) 0))
7447 (throw 'exit (match-string 1))))))))
7448 (if txt
7449 (progn
7450 (if (and org-table-copy-increment
7451 (string-match "^[0-9]+$" txt))
7452 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7453 (insert txt)
7454 (move-to-column col)
7455 (if (and org-table-copy-increment (org-at-timestamp-p t))
7456 (org-timestamp-up 1)
7457 (org-table-maybe-recalculate-line))
7458 (org-table-align)
7459 (move-to-column col))
7460 (error "No non-empty field found"))))
7462 (defun org-table-check-inside-data-field ()
7463 "Is point inside a table data field?
7464 I.e. not on a hline or before the first or after the last column?
7465 This actually throws an error, so it aborts the current command."
7466 (if (or (not (org-at-table-p))
7467 (= (org-table-current-column) 0)
7468 (org-at-table-hline-p)
7469 (looking-at "[ \t]*$"))
7470 (error "Not in table data field")))
7472 (defvar org-table-clip nil
7473 "Clipboard for table regions.")
7475 (defun org-table-blank-field ()
7476 "Blank the current table field or active region."
7477 (interactive)
7478 (org-table-check-inside-data-field)
7479 (if (and (interactive-p) (org-region-active-p))
7480 (let (org-table-clip)
7481 (org-table-cut-region (region-beginning) (region-end)))
7482 (skip-chars-backward "^|")
7483 (backward-char 1)
7484 (if (looking-at "|[^|\n]+")
7485 (let* ((pos (match-beginning 0))
7486 (match (match-string 0))
7487 (len (org-string-width match)))
7488 (replace-match (concat "|" (make-string (1- len) ?\ )))
7489 (goto-char (+ 2 pos))
7490 (substring match 1)))))
7492 (defun org-table-get-field (&optional n replace)
7493 "Return the value of the field in column N of current row.
7494 N defaults to current field.
7495 If REPLACE is a string, replace field with this value. The return value
7496 is always the old value."
7497 (and n (org-table-goto-column n))
7498 (skip-chars-backward "^|\n")
7499 (backward-char 1)
7500 (if (looking-at "|[^|\r\n]*")
7501 (let* ((pos (match-beginning 0))
7502 (val (buffer-substring (1+ pos) (match-end 0))))
7503 (if replace
7504 (replace-match (concat "|" replace) t t))
7505 (goto-char (min (point-at-eol) (+ 2 pos)))
7506 val)
7507 (forward-char 1) ""))
7509 (defun org-table-field-info (arg)
7510 "Show info about the current field, and highlight any reference at point."
7511 (interactive "P")
7512 (org-table-get-specials)
7513 (save-excursion
7514 (let* ((pos (point))
7515 (col (org-table-current-column))
7516 (cname (car (rassoc (int-to-string col) org-table-column-names)))
7517 (name (car (rassoc (list (org-current-line) col)
7518 org-table-named-field-locations)))
7519 (eql (org-table-get-stored-formulas))
7520 (dline (org-table-current-dline))
7521 (ref (format "@%d$%d" dline col))
7522 (ref1 (org-table-convert-refs-to-an ref))
7523 (fequation (or (assoc name eql) (assoc ref eql)))
7524 (cequation (assoc (int-to-string col) eql))
7525 (eqn (or fequation cequation)))
7526 (goto-char pos)
7527 (condition-case nil
7528 (org-table-show-reference 'local)
7529 (error nil))
7530 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
7531 dline col
7532 (if cname (concat " or $" cname) "")
7533 dline col ref1
7534 (if name (concat " or $" name) "")
7535 ;; FIXME: formula info not correct if special table line
7536 (if eqn
7537 (concat ", formula: "
7538 (org-table-formula-to-user
7539 (concat
7540 (if (string-match "^[$@]"(car eqn)) "" "$")
7541 (car eqn) "=" (cdr eqn))))
7542 "")))))
7544 (defun org-table-current-column ()
7545 "Find out which column we are in.
7546 When called interactively, column is also displayed in echo area."
7547 (interactive)
7548 (if (interactive-p) (org-table-check-inside-data-field))
7549 (save-excursion
7550 (let ((cnt 0) (pos (point)))
7551 (beginning-of-line 1)
7552 (while (search-forward "|" pos t)
7553 (setq cnt (1+ cnt)))
7554 (if (interactive-p) (message "This is table column %d" cnt))
7555 cnt)))
7557 (defun org-table-current-dline ()
7558 "Find out what table data line we are in.
7559 Only datalins count for this."
7560 (interactive)
7561 (if (interactive-p) (org-table-check-inside-data-field))
7562 (save-excursion
7563 (let ((cnt 0) (pos (point)))
7564 (goto-char (org-table-begin))
7565 (while (<= (point) pos)
7566 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
7567 (beginning-of-line 2))
7568 (if (interactive-p) (message "This is table line %d" cnt))
7569 cnt)))
7571 (defun org-table-goto-column (n &optional on-delim force)
7572 "Move the cursor to the Nth column in the current table line.
7573 With optional argument ON-DELIM, stop with point before the left delimiter
7574 of the field.
7575 If there are less than N fields, just go to after the last delimiter.
7576 However, when FORCE is non-nil, create new columns if necessary."
7577 (interactive "p")
7578 (let ((pos (point-at-eol)))
7579 (beginning-of-line 1)
7580 (when (> n 0)
7581 (while (and (> (setq n (1- n)) -1)
7582 (or (search-forward "|" pos t)
7583 (and force
7584 (progn (end-of-line 1)
7585 (skip-chars-backward "^|")
7586 (insert " | "))))))
7587 ; (backward-char 2) t)))))
7588 (when (and force (not (looking-at ".*|")))
7589 (save-excursion (end-of-line 1) (insert " | ")))
7590 (if on-delim
7591 (backward-char 1)
7592 (if (looking-at " ") (forward-char 1))))))
7594 (defun org-at-table-p (&optional table-type)
7595 "Return t if the cursor is inside an org-type table.
7596 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7597 (if org-enable-table-editor
7598 (save-excursion
7599 (beginning-of-line 1)
7600 (looking-at (if table-type org-table-any-line-regexp
7601 org-table-line-regexp)))
7602 nil))
7604 (defun org-at-table.el-p ()
7605 "Return t if and only if we are at a table.el table."
7606 (and (org-at-table-p 'any)
7607 (save-excursion
7608 (goto-char (org-table-begin 'any))
7609 (looking-at org-table1-hline-regexp))))
7611 (defun org-table-recognize-table.el ()
7612 "If there is a table.el table nearby, recognize it and move into it."
7613 (if org-table-tab-recognizes-table.el
7614 (if (org-at-table.el-p)
7615 (progn
7616 (beginning-of-line 1)
7617 (if (looking-at org-table-dataline-regexp)
7619 (if (looking-at org-table1-hline-regexp)
7620 (progn
7621 (beginning-of-line 2)
7622 (if (looking-at org-table-any-border-regexp)
7623 (beginning-of-line -1)))))
7624 (if (re-search-forward "|" (org-table-end t) t)
7625 (progn
7626 (require 'table)
7627 (if (table--at-cell-p (point))
7629 (message "recognizing table.el table...")
7630 (table-recognize-table)
7631 (message "recognizing table.el table...done")))
7632 (error "This should not happen..."))
7634 nil)
7635 nil))
7637 (defun org-at-table-hline-p ()
7638 "Return t if the cursor is inside a hline in a table."
7639 (if org-enable-table-editor
7640 (save-excursion
7641 (beginning-of-line 1)
7642 (looking-at org-table-hline-regexp))
7643 nil))
7645 (defun org-table-insert-column ()
7646 "Insert a new column into the table."
7647 (interactive)
7648 (if (not (org-at-table-p))
7649 (error "Not at a table"))
7650 (org-table-find-dataline)
7651 (let* ((col (max 1 (org-table-current-column)))
7652 (beg (org-table-begin))
7653 (end (org-table-end))
7654 ;; Current cursor position
7655 (linepos (org-current-line))
7656 (colpos col))
7657 (goto-char beg)
7658 (while (< (point) end)
7659 (if (org-at-table-hline-p)
7661 (org-table-goto-column col t)
7662 (insert "| "))
7663 (beginning-of-line 2))
7664 (move-marker end nil)
7665 (goto-line linepos)
7666 (org-table-goto-column colpos)
7667 (org-table-align)
7668 (org-table-fix-formulas "$" nil (1- col) 1)))
7670 (defun org-table-find-dataline ()
7671 "Find a dataline in the current table, which is needed for column commands."
7672 (if (and (org-at-table-p)
7673 (not (org-at-table-hline-p)))
7675 (let ((col (current-column))
7676 (end (org-table-end)))
7677 (move-to-column col)
7678 (while (and (< (point) end)
7679 (or (not (= (current-column) col))
7680 (org-at-table-hline-p)))
7681 (beginning-of-line 2)
7682 (move-to-column col))
7683 (if (and (org-at-table-p)
7684 (not (org-at-table-hline-p)))
7686 (error
7687 "Please position cursor in a data line for column operations")))))
7689 (defun org-table-delete-column ()
7690 "Delete a column from the table."
7691 (interactive)
7692 (if (not (org-at-table-p))
7693 (error "Not at a table"))
7694 (org-table-find-dataline)
7695 (org-table-check-inside-data-field)
7696 (let* ((col (org-table-current-column))
7697 (beg (org-table-begin))
7698 (end (org-table-end))
7699 ;; Current cursor position
7700 (linepos (org-current-line))
7701 (colpos col))
7702 (goto-char beg)
7703 (while (< (point) end)
7704 (if (org-at-table-hline-p)
7706 (org-table-goto-column col t)
7707 (and (looking-at "|[^|\n]+|")
7708 (replace-match "|")))
7709 (beginning-of-line 2))
7710 (move-marker end nil)
7711 (goto-line linepos)
7712 (org-table-goto-column colpos)
7713 (org-table-align)
7714 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
7715 col -1 col)))
7717 (defun org-table-move-column-right ()
7718 "Move column to the right."
7719 (interactive)
7720 (org-table-move-column nil))
7721 (defun org-table-move-column-left ()
7722 "Move column to the left."
7723 (interactive)
7724 (org-table-move-column 'left))
7726 (defun org-table-move-column (&optional left)
7727 "Move the current column to the right. With arg LEFT, move to the left."
7728 (interactive "P")
7729 (if (not (org-at-table-p))
7730 (error "Not at a table"))
7731 (org-table-find-dataline)
7732 (org-table-check-inside-data-field)
7733 (let* ((col (org-table-current-column))
7734 (col1 (if left (1- col) col))
7735 (beg (org-table-begin))
7736 (end (org-table-end))
7737 ;; Current cursor position
7738 (linepos (org-current-line))
7739 (colpos (if left (1- col) (1+ col))))
7740 (if (and left (= col 1))
7741 (error "Cannot move column further left"))
7742 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
7743 (error "Cannot move column further right"))
7744 (goto-char beg)
7745 (while (< (point) end)
7746 (if (org-at-table-hline-p)
7748 (org-table-goto-column col1 t)
7749 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
7750 (replace-match "|\\2|\\1|")))
7751 (beginning-of-line 2))
7752 (move-marker end nil)
7753 (goto-line linepos)
7754 (org-table-goto-column colpos)
7755 (org-table-align)
7756 (org-table-fix-formulas
7757 "$" (list (cons (number-to-string col) (number-to-string colpos))
7758 (cons (number-to-string colpos) (number-to-string col))))))
7760 (defun org-table-move-row-down ()
7761 "Move table row down."
7762 (interactive)
7763 (org-table-move-row nil))
7764 (defun org-table-move-row-up ()
7765 "Move table row up."
7766 (interactive)
7767 (org-table-move-row 'up))
7769 (defun org-table-move-row (&optional up)
7770 "Move the current table line down. With arg UP, move it up."
7771 (interactive "P")
7772 (let* ((col (current-column))
7773 (pos (point))
7774 (hline1p (save-excursion (beginning-of-line 1)
7775 (looking-at org-table-hline-regexp)))
7776 (dline1 (org-table-current-dline))
7777 (dline2 (+ dline1 (if up -1 1)))
7778 (tonew (if up 0 2))
7779 txt hline2p)
7780 (beginning-of-line tonew)
7781 (unless (org-at-table-p)
7782 (goto-char pos)
7783 (error "Cannot move row further"))
7784 (setq hline2p (looking-at org-table-hline-regexp))
7785 (goto-char pos)
7786 (beginning-of-line 1)
7787 (setq pos (point))
7788 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
7789 (delete-region (point) (1+ (point-at-eol)))
7790 (beginning-of-line tonew)
7791 (insert txt)
7792 (beginning-of-line 0)
7793 (move-to-column col)
7794 (unless (or hline1p hline2p)
7795 (org-table-fix-formulas
7796 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
7797 (cons (number-to-string dline2) (number-to-string dline1)))))))
7799 (defun org-table-insert-row (&optional arg)
7800 "Insert a new row above the current line into the table.
7801 With prefix ARG, insert below the current line."
7802 (interactive "P")
7803 (if (not (org-at-table-p))
7804 (error "Not at a table"))
7805 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
7806 (new (org-table-clean-line line)))
7807 ;; Fix the first field if necessary
7808 (if (string-match "^[ \t]*| *[#$] *|" line)
7809 (setq new (replace-match (match-string 0 line) t t new)))
7810 (beginning-of-line (if arg 2 1))
7811 (let (org-table-may-need-update) (insert-before-markers new "\n"))
7812 (beginning-of-line 0)
7813 (re-search-forward "| ?" (point-at-eol) t)
7814 (and (or org-table-may-need-update org-table-overlay-coordinates)
7815 (org-table-align))
7816 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
7818 (defun org-table-insert-hline (&optional above)
7819 "Insert a horizontal-line below the current line into the table.
7820 With prefix ABOVE, insert above the current line."
7821 (interactive "P")
7822 (if (not (org-at-table-p))
7823 (error "Not at a table"))
7824 (let ((line (org-table-clean-line
7825 (buffer-substring (point-at-bol) (point-at-eol))))
7826 (col (current-column)))
7827 (while (string-match "|\\( +\\)|" line)
7828 (setq line (replace-match
7829 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
7830 ?-) "|") t t line)))
7831 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
7832 (beginning-of-line (if above 1 2))
7833 (insert line "\n")
7834 (beginning-of-line (if above 1 -1))
7835 (move-to-column col)
7836 (and org-table-overlay-coordinates (org-table-align))))
7838 (defun org-table-hline-and-move (&optional same-column)
7839 "Insert a hline and move to the row below that line."
7840 (interactive "P")
7841 (let ((col (org-table-current-column)))
7842 (org-table-maybe-eval-formula)
7843 (org-table-maybe-recalculate-line)
7844 (org-table-insert-hline)
7845 (end-of-line 2)
7846 (if (looking-at "\n[ \t]*|-")
7847 (progn (insert "\n|") (org-table-align))
7848 (org-table-next-field))
7849 (if same-column (org-table-goto-column col))))
7851 (defun org-table-clean-line (s)
7852 "Convert a table line S into a string with only \"|\" and space.
7853 In particular, this does handle wide and invisible characters."
7854 (if (string-match "^[ \t]*|-" s)
7855 ;; It's a hline, just map the characters
7856 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
7857 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
7858 (setq s (replace-match
7859 (concat "|" (make-string (org-string-width (match-string 1 s))
7860 ?\ ) "|")
7861 t t s)))
7864 (defun org-table-kill-row ()
7865 "Delete the current row or horizontal line from the table."
7866 (interactive)
7867 (if (not (org-at-table-p))
7868 (error "Not at a table"))
7869 (let ((col (current-column))
7870 (dline (org-table-current-dline)))
7871 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
7872 (if (not (org-at-table-p)) (beginning-of-line 0))
7873 (move-to-column col)
7874 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
7875 dline -1 dline)))
7878 (defun org-table-sort-lines (with-case &optional sorting-type)
7879 "Sort table lines according to the column at point.
7881 The position of point indicates the column to be used for
7882 sorting, and the range of lines is the range between the nearest
7883 horizontal separator lines, or the entire table of no such lines
7884 exist. If point is before the first column, you will be prompted
7885 for the sorting column. If there is an active region, the mark
7886 specifies the first line and the sorting column, while point
7887 should be in the last line to be included into the sorting.
7889 The command then prompts for the sorting type which can be
7890 alphabetically, numerically, or by time (as given in a time stamp
7891 in the field). Sorting in reverse order is also possible.
7893 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
7895 If SORTING-TYPE is specified when this function is called from a Lisp
7896 program, no prompting will take place. SORTING-TYPE must be a character,
7897 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
7898 should be done in reverse order."
7899 (interactive "P")
7900 (let* ((thisline (org-current-line))
7901 (thiscol (org-table-current-column))
7902 beg end bcol ecol tend tbeg column lns pos)
7903 (when (equal thiscol 0)
7904 (if (interactive-p)
7905 (setq thiscol
7906 (string-to-number
7907 (read-string "Use column N for sorting: ")))
7908 (setq thiscol 1))
7909 (org-table-goto-column thiscol))
7910 (org-table-check-inside-data-field)
7911 (if (org-region-active-p)
7912 (progn
7913 (setq beg (region-beginning) end (region-end))
7914 (goto-char beg)
7915 (setq column (org-table-current-column)
7916 beg (point-at-bol))
7917 (goto-char end)
7918 (setq end (point-at-bol 2)))
7919 (setq column (org-table-current-column)
7920 pos (point)
7921 tbeg (org-table-begin)
7922 tend (org-table-end))
7923 (if (re-search-backward org-table-hline-regexp tbeg t)
7924 (setq beg (point-at-bol 2))
7925 (goto-char tbeg)
7926 (setq beg (point-at-bol 1)))
7927 (goto-char pos)
7928 (if (re-search-forward org-table-hline-regexp tend t)
7929 (setq end (point-at-bol 1))
7930 (goto-char tend)
7931 (setq end (point-at-bol))))
7932 (setq beg (move-marker (make-marker) beg)
7933 end (move-marker (make-marker) end))
7934 (untabify beg end)
7935 (goto-char beg)
7936 (org-table-goto-column column)
7937 (skip-chars-backward "^|")
7938 (setq bcol (current-column))
7939 (org-table-goto-column (1+ column))
7940 (skip-chars-backward "^|")
7941 (setq ecol (1- (current-column)))
7942 (org-table-goto-column column)
7943 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
7944 (org-split-string (buffer-substring beg end) "\n")))
7945 (setq lns (org-do-sort lns "Table" with-case sorting-type))
7946 (delete-region beg end)
7947 (move-marker beg nil)
7948 (move-marker end nil)
7949 (insert (mapconcat 'cdr lns "\n") "\n")
7950 (goto-line thisline)
7951 (org-table-goto-column thiscol)
7952 (message "%d lines sorted, based on column %d" (length lns) column)))
7954 (defun org-table-cut-region (beg end)
7955 "Copy region in table to the clipboard and blank all relevant fields."
7956 (interactive "r")
7957 (org-table-copy-region beg end 'cut))
7959 (defun org-table-copy-region (beg end &optional cut)
7960 "Copy rectangular region in table to clipboard.
7961 A special clipboard is used which can only be accessed
7962 with `org-table-paste-rectangle'."
7963 (interactive "rP")
7964 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
7965 region cols
7966 (rpl (if cut " " nil)))
7967 (goto-char beg)
7968 (org-table-check-inside-data-field)
7969 (setq l01 (org-current-line)
7970 c01 (org-table-current-column))
7971 (goto-char end)
7972 (org-table-check-inside-data-field)
7973 (setq l02 (org-current-line)
7974 c02 (org-table-current-column))
7975 (setq l1 (min l01 l02) l2 (max l01 l02)
7976 c1 (min c01 c02) c2 (max c01 c02))
7977 (catch 'exit
7978 (while t
7979 (catch 'nextline
7980 (if (> l1 l2) (throw 'exit t))
7981 (goto-line l1)
7982 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
7983 (setq cols nil ic1 c1 ic2 c2)
7984 (while (< ic1 (1+ ic2))
7985 (push (org-table-get-field ic1 rpl) cols)
7986 (setq ic1 (1+ ic1)))
7987 (push (nreverse cols) region)
7988 (setq l1 (1+ l1)))))
7989 (setq org-table-clip (nreverse region))
7990 (if cut (org-table-align))
7991 org-table-clip))
7993 (defun org-table-paste-rectangle ()
7994 "Paste a rectangular region into a table.
7995 The upper right corner ends up in the current field. All involved fields
7996 will be overwritten. If the rectangle does not fit into the present table,
7997 the table is enlarged as needed. The process ignores horizontal separator
7998 lines."
7999 (interactive)
8000 (unless (and org-table-clip (listp org-table-clip))
8001 (error "First cut/copy a region to paste!"))
8002 (org-table-check-inside-data-field)
8003 (let* ((clip org-table-clip)
8004 (line (org-current-line))
8005 (col (org-table-current-column))
8006 (org-enable-table-editor t)
8007 (org-table-automatic-realign nil)
8008 c cols field)
8009 (while (setq cols (pop clip))
8010 (while (org-at-table-hline-p) (beginning-of-line 2))
8011 (if (not (org-at-table-p))
8012 (progn (end-of-line 0) (org-table-next-field)))
8013 (setq c col)
8014 (while (setq field (pop cols))
8015 (org-table-goto-column c nil 'force)
8016 (org-table-get-field nil field)
8017 (setq c (1+ c)))
8018 (beginning-of-line 2))
8019 (goto-line line)
8020 (org-table-goto-column col)
8021 (org-table-align)))
8023 (defun org-table-convert ()
8024 "Convert from `org-mode' table to table.el and back.
8025 Obviously, this only works within limits. When an Org-mode table is
8026 converted to table.el, all horizontal separator lines get lost, because
8027 table.el uses these as cell boundaries and has no notion of horizontal lines.
8028 A table.el table can be converted to an Org-mode table only if it does not
8029 do row or column spanning. Multiline cells will become multiple cells.
8030 Beware, Org-mode does not test if the table can be successfully converted - it
8031 blindly applies a recipe that works for simple tables."
8032 (interactive)
8033 (require 'table)
8034 (if (org-at-table.el-p)
8035 ;; convert to Org-mode table
8036 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8037 (end (move-marker (make-marker) (org-table-end t))))
8038 (table-unrecognize-region beg end)
8039 (goto-char beg)
8040 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8041 (replace-match ""))
8042 (goto-char beg))
8043 (if (org-at-table-p)
8044 ;; convert to table.el table
8045 (let ((beg (move-marker (make-marker) (org-table-begin)))
8046 (end (move-marker (make-marker) (org-table-end))))
8047 ;; first, get rid of all horizontal lines
8048 (goto-char beg)
8049 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8050 (replace-match ""))
8051 ;; insert a hline before first
8052 (goto-char beg)
8053 (org-table-insert-hline 'above)
8054 (beginning-of-line -1)
8055 ;; insert a hline after each line
8056 (while (progn (beginning-of-line 3) (< (point) end))
8057 (org-table-insert-hline))
8058 (goto-char beg)
8059 (setq end (move-marker end (org-table-end)))
8060 ;; replace "+" at beginning and ending of hlines
8061 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8062 (replace-match "\\1+-"))
8063 (goto-char beg)
8064 (while (re-search-forward "-|[ \t]*$" end t)
8065 (replace-match "-+"))
8066 (goto-char beg)))))
8068 (defun org-table-wrap-region (arg)
8069 "Wrap several fields in a column like a paragraph.
8070 This is useful if you'd like to spread the contents of a field over several
8071 lines, in order to keep the table compact.
8073 If there is an active region, and both point and mark are in the same column,
8074 the text in the column is wrapped to minimum width for the given number of
8075 lines. Generally, this makes the table more compact. A prefix ARG may be
8076 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8077 formats the selected text to two lines. If the region was longer than two
8078 lines, the remaining lines remain empty. A negative prefix argument reduces
8079 the current number of lines by that amount. The wrapped text is pasted back
8080 into the table. If you formatted it to more lines than it was before, fields
8081 further down in the table get overwritten - so you might need to make space in
8082 the table first.
8084 If there is no region, the current field is split at the cursor position and
8085 the text fragment to the right of the cursor is prepended to the field one
8086 line down.
8088 If there is no region, but you specify a prefix ARG, the current field gets
8089 blank, and the content is appended to the field above."
8090 (interactive "P")
8091 (org-table-check-inside-data-field)
8092 (if (org-region-active-p)
8093 ;; There is a region: fill as a paragraph
8094 (let* ((beg (region-beginning))
8095 (cline (save-excursion (goto-char beg) (org-current-line)))
8096 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
8097 nlines)
8098 (org-table-cut-region (region-beginning) (region-end))
8099 (if (> (length (car org-table-clip)) 1)
8100 (error "Region must be limited to single column"))
8101 (setq nlines (if arg
8102 (if (< arg 1)
8103 (+ (length org-table-clip) arg)
8104 arg)
8105 (length org-table-clip)))
8106 (setq org-table-clip
8107 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8108 nil nlines)))
8109 (goto-line cline)
8110 (org-table-goto-column ccol)
8111 (org-table-paste-rectangle))
8112 ;; No region, split the current field at point
8113 (if arg
8114 ;; combine with field above
8115 (let ((s (org-table-blank-field))
8116 (col (org-table-current-column)))
8117 (beginning-of-line 0)
8118 (while (org-at-table-hline-p) (beginning-of-line 0))
8119 (org-table-goto-column col)
8120 (skip-chars-forward "^|")
8121 (skip-chars-backward " ")
8122 (insert " " (org-trim s))
8123 (org-table-align))
8124 ;; split field
8125 (when (looking-at "\\([^|]+\\)+|")
8126 (let ((s (match-string 1)))
8127 (replace-match " |")
8128 (goto-char (match-beginning 0))
8129 (org-table-next-row)
8130 (insert (org-trim s) " ")
8131 (org-table-align))))))
8133 (defvar org-field-marker nil)
8135 (defun org-table-edit-field (arg)
8136 "Edit table field in a different window.
8137 This is mainly useful for fields that contain hidden parts.
8138 When called with a \\[universal-argument] prefix, just make the full field visible so that
8139 it can be edited in place."
8140 (interactive "P")
8141 (if arg
8142 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
8143 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
8144 (remove-text-properties b e '(org-cwidth t invisible t
8145 display t intangible t))
8146 (if (and (boundp 'font-lock-mode) font-lock-mode)
8147 (font-lock-fontify-block)))
8148 (let ((pos (move-marker (make-marker) (point)))
8149 (field (org-table-get-field))
8150 (cw (current-window-configuration))
8152 (switch-to-buffer-other-window "*Org tmp*")
8153 (erase-buffer)
8154 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
8155 (let ((org-inhibit-startup t)) (org-mode))
8156 (goto-char (setq p (point-max)))
8157 (insert (org-trim field))
8158 (remove-text-properties p (point-max)
8159 '(invisible t org-cwidth t display t
8160 intangible t))
8161 (goto-char p)
8162 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
8163 (org-set-local 'org-window-configuration cw)
8164 (org-set-local 'org-field-marker pos)
8165 (message "Edit and finish with C-c C-c"))))
8167 (defun org-table-finish-edit-field ()
8168 "Finish editing a table data field.
8169 Remove all newline characters, insert the result into the table, realign
8170 the table and kill the editing buffer."
8171 (let ((pos org-field-marker)
8172 (cw org-window-configuration)
8173 (cb (current-buffer))
8174 text)
8175 (goto-char (point-min))
8176 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
8177 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
8178 (replace-match " "))
8179 (setq text (org-trim (buffer-string)))
8180 (set-window-configuration cw)
8181 (kill-buffer cb)
8182 (select-window (get-buffer-window (marker-buffer pos)))
8183 (goto-char pos)
8184 (move-marker pos nil)
8185 (org-table-check-inside-data-field)
8186 (org-table-get-field nil text)
8187 (org-table-align)
8188 (message "New field value inserted")))
8190 (defun org-trim (s)
8191 "Remove whitespace at beginning and end of string."
8192 (if (string-match "^[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
8193 (if (string-match "[ \t\n\r]+$" s) (setq s (replace-match "" t t s)))
8196 (defun org-wrap (string &optional width lines)
8197 "Wrap string to either a number of lines, or a width in characters.
8198 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8199 that costs. If there is a word longer than WIDTH, the text is actually
8200 wrapped to the length of that word.
8201 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8202 many lines, whatever width that takes.
8203 The return value is a list of lines, without newlines at the end."
8204 (let* ((words (org-split-string string "[ \t\n]+"))
8205 (maxword (apply 'max (mapcar 'org-string-width words)))
8206 w ll)
8207 (cond (width
8208 (org-do-wrap words (max maxword width)))
8209 (lines
8210 (setq w maxword)
8211 (setq ll (org-do-wrap words maxword))
8212 (if (<= (length ll) lines)
8214 (setq ll words)
8215 (while (> (length ll) lines)
8216 (setq w (1+ w))
8217 (setq ll (org-do-wrap words w)))
8218 ll))
8219 (t (error "Cannot wrap this")))))
8222 (defun org-do-wrap (words width)
8223 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8224 (let (lines line)
8225 (while words
8226 (setq line (pop words))
8227 (while (and words (< (+ (length line) (length (car words))) width))
8228 (setq line (concat line " " (pop words))))
8229 (setq lines (push line lines)))
8230 (nreverse lines)))
8232 (defun org-split-string (string &optional separators)
8233 "Splits STRING into substrings at SEPARATORS.
8234 No empty strings are returned if there are matches at the beginning
8235 and end of string."
8236 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8237 (start 0)
8238 notfirst
8239 (list nil))
8240 (while (and (string-match rexp string
8241 (if (and notfirst
8242 (= start (match-beginning 0))
8243 (< start (length string)))
8244 (1+ start) start))
8245 (< (match-beginning 0) (length string)))
8246 (setq notfirst t)
8247 (or (eq (match-beginning 0) 0)
8248 (and (eq (match-beginning 0) (match-end 0))
8249 (eq (match-beginning 0) start))
8250 (setq list
8251 (cons (substring string start (match-beginning 0))
8252 list)))
8253 (setq start (match-end 0)))
8254 (or (eq start (length string))
8255 (setq list
8256 (cons (substring string start)
8257 list)))
8258 (nreverse list)))
8260 (defun org-table-map-tables (function)
8261 "Apply FUNCTION to the start of all tables in the buffer."
8262 (save-excursion
8263 (save-restriction
8264 (widen)
8265 (goto-char (point-min))
8266 (while (re-search-forward org-table-any-line-regexp nil t)
8267 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8268 (beginning-of-line 1)
8269 (if (looking-at org-table-line-regexp)
8270 (save-excursion (funcall function)))
8271 (re-search-forward org-table-any-border-regexp nil 1))))
8272 (message "Mapping tables: done"))
8274 (defvar org-timecnt) ; dynamically scoped parameter
8276 (defun org-table-sum (&optional beg end nlast)
8277 "Sum numbers in region of current table column.
8278 The result will be displayed in the echo area, and will be available
8279 as kill to be inserted with \\[yank].
8281 If there is an active region, it is interpreted as a rectangle and all
8282 numbers in that rectangle will be summed. If there is no active
8283 region and point is located in a table column, sum all numbers in that
8284 column.
8286 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8287 numbers are assumed to be times as well (in decimal hours) and the
8288 numbers are added as such.
8290 If NLAST is a number, only the NLAST fields will actually be summed."
8291 (interactive)
8292 (save-excursion
8293 (let (col (org-timecnt 0) diff h m s org-table-clip)
8294 (cond
8295 ((and beg end)) ; beg and end given explicitly
8296 ((org-region-active-p)
8297 (setq beg (region-beginning) end (region-end)))
8299 (setq col (org-table-current-column))
8300 (goto-char (org-table-begin))
8301 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8302 (error "No table data"))
8303 (org-table-goto-column col)
8304 (setq beg (point))
8305 (goto-char (org-table-end))
8306 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8307 (error "No table data"))
8308 (org-table-goto-column col)
8309 (setq end (point))))
8310 (let* ((items (apply 'append (org-table-copy-region beg end)))
8311 (items1 (cond ((not nlast) items)
8312 ((>= nlast (length items)) items)
8313 (t (setq items (reverse items))
8314 (setcdr (nthcdr (1- nlast) items) nil)
8315 (nreverse items))))
8316 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8317 items1)))
8318 (res (apply '+ numbers))
8319 (sres (if (= org-timecnt 0)
8320 (format "%g" res)
8321 (setq diff (* 3600 res)
8322 h (floor (/ diff 3600)) diff (mod diff 3600)
8323 m (floor (/ diff 60)) diff (mod diff 60)
8324 s diff)
8325 (format "%d:%02d:%02d" h m s))))
8326 (kill-new sres)
8327 (if (interactive-p)
8328 (message "%s"
8329 (substitute-command-keys
8330 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8331 (length numbers) sres))))
8332 sres))))
8334 (defun org-table-get-number-for-summing (s)
8335 (let (n)
8336 (if (string-match "^ *|? *" s)
8337 (setq s (replace-match "" nil nil s)))
8338 (if (string-match " *|? *$" s)
8339 (setq s (replace-match "" nil nil s)))
8340 (setq n (string-to-number s))
8341 (cond
8342 ((and (string-match "0" s)
8343 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8344 ((string-match "\\`[ \t]+\\'" s) nil)
8345 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8346 (let ((h (string-to-number (or (match-string 1 s) "0")))
8347 (m (string-to-number (or (match-string 2 s) "0")))
8348 (s (string-to-number (or (match-string 4 s) "0"))))
8349 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
8350 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8351 ((equal n 0) nil)
8352 (t n))))
8354 (defun org-table-current-field-formula (&optional key noerror)
8355 "Return the formula active for the current field.
8356 Assumes that specials are in place.
8357 If KEY is given, return the key to this formula.
8358 Otherwise return the formula preceeded with \"=\" or \":=\"."
8359 (let* ((name (car (rassoc (list (org-current-line)
8360 (org-table-current-column))
8361 org-table-named-field-locations)))
8362 (col (org-table-current-column))
8363 (scol (int-to-string col))
8364 (ref (format "@%d$%d" (org-table-current-dline) col))
8365 (stored-list (org-table-get-stored-formulas noerror))
8366 (ass (or (assoc name stored-list)
8367 (assoc ref stored-list)
8368 (assoc scol stored-list))))
8369 (if key
8370 (car ass)
8371 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
8372 (cdr ass))))))
8374 (defun org-table-get-formula (&optional equation named)
8375 "Read a formula from the minibuffer, offer stored formula as default.
8376 When NAMED is non-nil, look for a named equation."
8377 (let* ((stored-list (org-table-get-stored-formulas))
8378 (name (car (rassoc (list (org-current-line)
8379 (org-table-current-column))
8380 org-table-named-field-locations)))
8381 (ref (format "@%d$%d" (org-table-current-dline)
8382 (org-table-current-column)))
8383 (refass (assoc ref stored-list))
8384 (scol (if named
8385 (if name name ref)
8386 (int-to-string (org-table-current-column))))
8387 (dummy (and (or name refass) (not named)
8388 (not (y-or-n-p "Replace field formula with column formula? " ))
8389 (error "Abort")))
8390 (name (or name ref))
8391 (org-table-may-need-update nil)
8392 (stored (cdr (assoc scol stored-list)))
8393 (eq (cond
8394 ((and stored equation (string-match "^ *=? *$" equation))
8395 stored)
8396 ((stringp equation)
8397 equation)
8398 (t (org-table-formula-from-user
8399 (read-string
8400 (org-table-formula-to-user
8401 (format "%s formula %s%s="
8402 (if named "Field" "Column")
8403 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
8404 scol))
8405 (if stored (org-table-formula-to-user stored) "")
8406 'org-table-formula-history
8407 )))))
8408 mustsave)
8409 (when (not (string-match "\\S-" eq))
8410 ;; remove formula
8411 (setq stored-list (delq (assoc scol stored-list) stored-list))
8412 (org-table-store-formulas stored-list)
8413 (error "Formula removed"))
8414 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8415 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8416 (if (and name (not named))
8417 ;; We set the column equation, delete the named one.
8418 (setq stored-list (delq (assoc name stored-list) stored-list)
8419 mustsave t))
8420 (if stored
8421 (setcdr (assoc scol stored-list) eq)
8422 (setq stored-list (cons (cons scol eq) stored-list)))
8423 (if (or mustsave (not (equal stored eq)))
8424 (org-table-store-formulas stored-list))
8425 eq))
8427 (defun org-table-store-formulas (alist)
8428 "Store the list of formulas below the current table."
8429 (setq alist (sort alist 'org-table-formula-less-p))
8430 (save-excursion
8431 (goto-char (org-table-end))
8432 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
8433 (progn
8434 ;; don't overwrite TBLFM, we might use text properties to store stuff
8435 (goto-char (match-beginning 2))
8436 (delete-region (match-beginning 2) (match-end 0)))
8437 (insert "#+TBLFM:"))
8438 (insert " "
8439 (mapconcat (lambda (x)
8440 (concat
8441 (if (equal (string-to-char (car x)) ?@) "" "$")
8442 (car x) "=" (cdr x)))
8443 alist "::")
8444 "\n")))
8446 (defsubst org-table-formula-make-cmp-string (a)
8447 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
8448 (concat
8449 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
8450 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
8451 (if (match-end 5) (concat "@@" (match-string 5 a))))))
8453 (defun org-table-formula-less-p (a b)
8454 "Compare two formulas for sorting."
8455 (let ((as (org-table-formula-make-cmp-string (car a)))
8456 (bs (org-table-formula-make-cmp-string (car b))))
8457 (and as bs (string< as bs))))
8459 (defun org-table-get-stored-formulas (&optional noerror)
8460 "Return an alist with the stored formulas directly after current table."
8461 (interactive)
8462 (let (scol eq eq-alist strings string seen)
8463 (save-excursion
8464 (goto-char (org-table-end))
8465 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8466 (setq strings (org-split-string (match-string 2) " *:: *"))
8467 (while (setq string (pop strings))
8468 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
8469 (setq scol (if (match-end 2)
8470 (match-string 2 string)
8471 (match-string 1 string))
8472 eq (match-string 3 string)
8473 eq-alist (cons (cons scol eq) eq-alist))
8474 (if (member scol seen)
8475 (if noerror
8476 (progn
8477 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8478 (ding)
8479 (sit-for 2))
8480 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
8481 (push scol seen))))))
8482 (nreverse eq-alist)))
8484 (defun org-table-fix-formulas (key replace &optional limit delta remove)
8485 "Modify the equations after the table structure has been edited.
8486 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
8487 For all numbers larger than LIMIT, shift them by DELTA."
8488 (save-excursion
8489 (goto-char (org-table-end))
8490 (when (looking-at "#\\+TBLFM:")
8491 (let ((re (concat key "\\([0-9]+\\)"))
8492 (re2
8493 (when remove
8494 (if (equal key "$")
8495 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
8496 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
8497 s n a)
8498 (when remove
8499 (while (re-search-forward re2 (point-at-eol) t)
8500 (replace-match "")))
8501 (while (re-search-forward re (point-at-eol) t)
8502 (setq s (match-string 1) n (string-to-number s))
8503 (cond
8504 ((setq a (assoc s replace))
8505 (replace-match (concat key (cdr a)) t t))
8506 ((and limit (> n limit))
8507 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
8509 (defun org-table-get-specials ()
8510 "Get the column names and local parameters for this table."
8511 (save-excursion
8512 (let ((beg (org-table-begin)) (end (org-table-end))
8513 names name fields fields1 field cnt
8514 c v l line col types dlines hlines)
8515 (setq org-table-column-names nil
8516 org-table-local-parameters nil
8517 org-table-named-field-locations nil
8518 org-table-current-begin-line nil
8519 org-table-current-begin-pos nil
8520 org-table-current-line-types nil)
8521 (goto-char beg)
8522 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8523 (setq names (org-split-string (match-string 1) " *| *")
8524 cnt 1)
8525 (while (setq name (pop names))
8526 (setq cnt (1+ cnt))
8527 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8528 (push (cons name (int-to-string cnt)) org-table-column-names))))
8529 (setq org-table-column-names (nreverse org-table-column-names))
8530 (setq org-table-column-name-regexp
8531 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8532 (goto-char beg)
8533 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8534 (setq fields (org-split-string (match-string 1) " *| *"))
8535 (while (setq field (pop fields))
8536 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8537 (push (cons (match-string 1 field) (match-string 2 field))
8538 org-table-local-parameters))))
8539 (goto-char beg)
8540 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8541 (setq c (match-string 1)
8542 fields (org-split-string (match-string 2) " *| *"))
8543 (save-excursion
8544 (beginning-of-line (if (equal c "_") 2 0))
8545 (setq line (org-current-line) col 1)
8546 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8547 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8548 (while (and fields1 (setq field (pop fields)))
8549 (setq v (pop fields1) col (1+ col))
8550 (when (and (stringp field) (stringp v)
8551 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8552 (push (cons field v) org-table-local-parameters)
8553 (push (list field line col) org-table-named-field-locations))))
8554 ;; Analyse the line types
8555 (goto-char beg)
8556 (setq org-table-current-begin-line (org-current-line)
8557 org-table-current-begin-pos (point)
8558 l org-table-current-begin-line)
8559 (while (looking-at "[ \t]*|\\(-\\)?")
8560 (push (if (match-end 1) 'hline 'dline) types)
8561 (if (match-end 1) (push l hlines) (push l dlines))
8562 (beginning-of-line 2)
8563 (setq l (1+ l)))
8564 (setq org-table-current-line-types (apply 'vector (nreverse types))
8565 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
8566 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
8568 (defun org-table-maybe-eval-formula ()
8569 "Check if the current field starts with \"=\" or \":=\".
8570 If yes, store the formula and apply it."
8571 ;; We already know we are in a table. Get field will only return a formula
8572 ;; when appropriate. It might return a separator line, but no problem.
8573 (when org-table-formula-evaluate-inline
8574 (let* ((field (org-trim (or (org-table-get-field) "")))
8575 named eq)
8576 (when (string-match "^:?=\\(.*\\)" field)
8577 (setq named (equal (string-to-char field) ?:)
8578 eq (match-string 1 field))
8579 (if (or (fboundp 'calc-eval)
8580 (equal (substring eq 0 (min 2 (length eq))) "'("))
8581 (org-table-eval-formula (if named '(4) nil)
8582 (org-table-formula-from-user eq))
8583 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
8585 (defvar org-recalc-commands nil
8586 "List of commands triggering the recalculation of a line.
8587 Will be filled automatically during use.")
8589 (defvar org-recalc-marks
8590 '((" " . "Unmarked: no special line, no automatic recalculation")
8591 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
8592 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
8593 ("!" . "Column name definition line. Reference in formula as $name.")
8594 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8595 ("_" . "Names for values in row below this one.")
8596 ("^" . "Names for values in row above this one.")))
8598 (defun org-table-rotate-recalc-marks (&optional newchar)
8599 "Rotate the recalculation mark in the first column.
8600 If in any row, the first field is not consistent with a mark,
8601 insert a new column for the markers.
8602 When there is an active region, change all the lines in the region,
8603 after prompting for the marking character.
8604 After each change, a message will be displayed indicating the meaning
8605 of the new mark."
8606 (interactive)
8607 (unless (org-at-table-p) (error "Not at a table"))
8608 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8609 (beg (org-table-begin))
8610 (end (org-table-end))
8611 (l (org-current-line))
8612 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8613 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8614 (have-col
8615 (save-excursion
8616 (goto-char beg)
8617 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8618 (col (org-table-current-column))
8619 (forcenew (car (assoc newchar org-recalc-marks)))
8620 epos new)
8621 (when l1
8622 (message "Change region to what mark? Type # * ! $ or SPC: ")
8623 (setq newchar (char-to-string (read-char-exclusive))
8624 forcenew (car (assoc newchar org-recalc-marks))))
8625 (if (and newchar (not forcenew))
8626 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8627 newchar))
8628 (if l1 (goto-line l1))
8629 (save-excursion
8630 (beginning-of-line 1)
8631 (unless (looking-at org-table-dataline-regexp)
8632 (error "Not at a table data line")))
8633 (unless have-col
8634 (org-table-goto-column 1)
8635 (org-table-insert-column)
8636 (org-table-goto-column (1+ col)))
8637 (setq epos (point-at-eol))
8638 (save-excursion
8639 (beginning-of-line 1)
8640 (org-table-get-field
8641 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8642 (concat " "
8643 (setq new (or forcenew
8644 (cadr (member (match-string 1) marks))))
8645 " ")
8646 " # ")))
8647 (if (and l1 l2)
8648 (progn
8649 (goto-line l1)
8650 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8651 (and (looking-at org-table-dataline-regexp)
8652 (org-table-get-field 1 (concat " " new " "))))
8653 (goto-line l1)))
8654 (if (not (= epos (point-at-eol))) (org-table-align))
8655 (goto-line l)
8656 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
8658 (defun org-table-maybe-recalculate-line ()
8659 "Recompute the current line if marked for it, and if we haven't just done it."
8660 (interactive)
8661 (and org-table-allow-automatic-line-recalculation
8662 (not (and (memq last-command org-recalc-commands)
8663 (equal org-last-recalc-line (org-current-line))))
8664 (save-excursion (beginning-of-line 1)
8665 (looking-at org-table-auto-recalculate-regexp))
8666 (org-table-recalculate) t))
8668 (defvar org-table-formula-debug nil
8669 "Non-nil means, debug table formulas.
8670 When nil, simply write \"#ERROR\" in corrupted fields.")
8671 (make-variable-buffer-local 'org-table-formula-debug)
8673 (defvar modes)
8674 (defsubst org-set-calc-mode (var &optional value)
8675 (if (stringp var)
8676 (setq var (assoc var '(("D" calc-angle-mode deg)
8677 ("R" calc-angle-mode rad)
8678 ("F" calc-prefer-frac t)
8679 ("S" calc-symbolic-mode t)))
8680 value (nth 2 var) var (nth 1 var)))
8681 (if (memq var modes)
8682 (setcar (cdr (memq var modes)) value)
8683 (cons var (cons value modes)))
8684 modes)
8686 (defun org-table-eval-formula (&optional arg equation
8687 suppress-align suppress-const
8688 suppress-store suppress-analysis)
8689 "Replace the table field value at the cursor by the result of a calculation.
8691 This function makes use of Dave Gillespie's Calc package, in my view the
8692 most exciting program ever written for GNU Emacs. So you need to have Calc
8693 installed in order to use this function.
8695 In a table, this command replaces the value in the current field with the
8696 result of a formula. It also installs the formula as the \"current\" column
8697 formula, by storing it in a special line below the table. When called
8698 with a `C-u' prefix, the current field must ba a named field, and the
8699 formula is installed as valid in only this specific field.
8701 When called with two `C-u' prefixes, insert the active equation
8702 for the field back into the current field, so that it can be
8703 edited there. This is useful in order to use \\[org-table-show-reference]
8704 to check the referenced fields.
8706 When called, the command first prompts for a formula, which is read in
8707 the minibuffer. Previously entered formulas are available through the
8708 history list, and the last used formula is offered as a default.
8709 These stored formulas are adapted correctly when moving, inserting, or
8710 deleting columns with the corresponding commands.
8712 The formula can be any algebraic expression understood by the Calc package.
8713 For details, see the Org-mode manual.
8715 This function can also be called from Lisp programs and offers
8716 additional arguments: EQUATION can be the formula to apply. If this
8717 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
8718 used to speed-up recursive calls by by-passing unnecessary aligns.
8719 SUPPRESS-CONST suppresses the interpretation of constants in the
8720 formula, assuming that this has been done already outside the function.
8721 SUPPRESS-STORE means the formula should not be stored, either because
8722 it is already stored, or because it is a modified equation that should
8723 not overwrite the stored one."
8724 (interactive "P")
8725 (org-table-check-inside-data-field)
8726 (or suppress-analysis (org-table-get-specials))
8727 (if (equal arg '(16))
8728 (let ((eq (org-table-current-field-formula)))
8729 (or eq (error "No equation active for current field"))
8730 (org-table-get-field nil eq)
8731 (org-table-align)
8732 (setq org-table-may-need-update t))
8733 (let* (fields
8734 (ndown (if (integerp arg) arg 1))
8735 (org-table-automatic-realign nil)
8736 (case-fold-search nil)
8737 (down (> ndown 1))
8738 (formula (if (and equation suppress-store)
8739 equation
8740 (org-table-get-formula equation (equal arg '(4)))))
8741 (n0 (org-table-current-column))
8742 (modes (copy-sequence org-calc-default-modes))
8743 (numbers nil) ; was a variable, now fixed default
8744 (keep-empty nil)
8745 n form form0 bw fmt x ev orig c lispp literal)
8746 ;; Parse the format string. Since we have a lot of modes, this is
8747 ;; a lot of work. However, I think calc still uses most of the time.
8748 (if (string-match ";" formula)
8749 (let ((tmp (org-split-string formula ";")))
8750 (setq formula (car tmp)
8751 fmt (concat (cdr (assoc "%" org-table-local-parameters))
8752 (nth 1 tmp)))
8753 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
8754 (setq c (string-to-char (match-string 1 fmt))
8755 n (string-to-number (match-string 2 fmt)))
8756 (if (= c ?p)
8757 (setq modes (org-set-calc-mode 'calc-internal-prec n))
8758 (setq modes (org-set-calc-mode
8759 'calc-float-format
8760 (list (cdr (assoc c '((?n . float) (?f . fix)
8761 (?s . sci) (?e . eng))))
8762 n))))
8763 (setq fmt (replace-match "" t t fmt)))
8764 (if (string-match "[NT]" fmt)
8765 (setq numbers (equal (match-string 0 fmt) "N")
8766 fmt (replace-match "" t t fmt)))
8767 (if (string-match "L" fmt)
8768 (setq literal t
8769 fmt (replace-match "" t t fmt)))
8770 (if (string-match "E" fmt)
8771 (setq keep-empty t
8772 fmt (replace-match "" t t fmt)))
8773 (while (string-match "[DRFS]" fmt)
8774 (setq modes (org-set-calc-mode (match-string 0 fmt)))
8775 (setq fmt (replace-match "" t t fmt)))
8776 (unless (string-match "\\S-" fmt)
8777 (setq fmt nil))))
8778 (if (and (not suppress-const) org-table-formula-use-constants)
8779 (setq formula (org-table-formula-substitute-names formula)))
8780 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
8781 (while (> ndown 0)
8782 (setq fields (org-split-string
8783 (org-no-properties
8784 (buffer-substring (point-at-bol) (point-at-eol)))
8785 " *| *"))
8786 (if (eq numbers t)
8787 (setq fields (mapcar
8788 (lambda (x) (number-to-string (string-to-number x)))
8789 fields)))
8790 (setq ndown (1- ndown))
8791 (setq form (copy-sequence formula)
8792 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
8793 (if (and lispp literal) (setq lispp 'literal))
8794 ;; Check for old vertical references
8795 (setq form (org-rewrite-old-row-references form))
8796 ;; Insert complex ranges
8797 (while (string-match org-table-range-regexp form)
8798 (setq form
8799 (replace-match
8800 (save-match-data
8801 (org-table-make-reference
8802 (org-table-get-range (match-string 0 form) nil n0)
8803 keep-empty numbers lispp))
8804 t t form)))
8805 ;; Insert simple ranges
8806 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
8807 (setq form
8808 (replace-match
8809 (save-match-data
8810 (org-table-make-reference
8811 (org-sublist
8812 fields (string-to-number (match-string 1 form))
8813 (string-to-number (match-string 2 form)))
8814 keep-empty numbers lispp))
8815 t t form)))
8816 (setq form0 form)
8817 ;; Insert the references to fields in same row
8818 (while (string-match "\\$\\([0-9]+\\)" form)
8819 (setq n (string-to-number (match-string 1 form))
8820 x (nth (1- (if (= n 0) n0 n)) fields))
8821 (unless x (error "Invalid field specifier \"%s\""
8822 (match-string 0 form)))
8823 (setq form (replace-match
8824 (save-match-data
8825 (org-table-make-reference x nil numbers lispp))
8826 t t form)))
8828 (if lispp
8829 (setq ev (condition-case nil
8830 (eval (eval (read form)))
8831 (error "#ERROR"))
8832 ev (if (numberp ev) (number-to-string ev) ev))
8833 (or (fboundp 'calc-eval)
8834 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
8835 (setq ev (calc-eval (cons form modes)
8836 (if numbers 'num))))
8838 (when org-table-formula-debug
8839 (with-output-to-temp-buffer "*Substitution History*"
8840 (princ (format "Substitution history of formula
8841 Orig: %s
8842 $xyz-> %s
8843 @r$c-> %s
8844 $1-> %s\n" orig formula form0 form))
8845 (if (listp ev)
8846 (princ (format " %s^\nError: %s"
8847 (make-string (car ev) ?\-) (nth 1 ev)))
8848 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
8849 ev (or fmt "NONE")
8850 (if fmt (format fmt (string-to-number ev)) ev)))))
8851 (setq bw (get-buffer-window "*Substitution History*"))
8852 (shrink-window-if-larger-than-buffer bw)
8853 (unless (and (interactive-p) (not ndown))
8854 (unless (let (inhibit-redisplay)
8855 (y-or-n-p "Debugging Formula. Continue to next? "))
8856 (org-table-align)
8857 (error "Abort"))
8858 (delete-window bw)
8859 (message "")))
8860 (if (listp ev) (setq fmt nil ev "#ERROR"))
8861 (org-table-justify-field-maybe
8862 (if fmt (format fmt (string-to-number ev)) ev))
8863 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
8864 (call-interactively 'org-return)
8865 (setq ndown 0)))
8866 (and down (org-table-maybe-recalculate-line))
8867 (or suppress-align (and org-table-may-need-update
8868 (org-table-align))))))
8870 (defun org-table-put-field-property (prop value)
8871 (save-excursion
8872 (put-text-property (progn (skip-chars-backward "^|") (point))
8873 (progn (skip-chars-forward "^|") (point))
8874 prop value)))
8876 (defun org-table-get-range (desc &optional tbeg col highlight)
8877 "Get a calc vector from a column, accorting to descriptor DESC.
8878 Optional arguments TBEG and COL can give the beginning of the table and
8879 the current column, to avoid unnecessary parsing.
8880 HIGHLIGHT means, just highlight the range."
8881 (if (not (equal (string-to-char desc) ?@))
8882 (setq desc (concat "@" desc)))
8883 (save-excursion
8884 (or tbeg (setq tbeg (org-table-begin)))
8885 (or col (setq col (org-table-current-column)))
8886 (let ((thisline (org-current-line))
8887 beg end c1 c2 r1 r2 rangep tmp)
8888 (unless (string-match org-table-range-regexp desc)
8889 (error "Invalid table range specifier `%s'" desc))
8890 (setq rangep (match-end 3)
8891 r1 (and (match-end 1) (match-string 1 desc))
8892 r2 (and (match-end 4) (match-string 4 desc))
8893 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
8894 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
8896 (and c1 (setq c1 (+ (string-to-number c1)
8897 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
8898 (and c2 (setq c2 (+ (string-to-number c2)
8899 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
8900 (if (equal r1 "") (setq r1 nil))
8901 (if (equal r2 "") (setq r2 nil))
8902 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
8903 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
8904 ; (setq r2 (or r2 r1) c2 (or c2 c1))
8905 (if (not r1) (setq r1 thisline))
8906 (if (not r2) (setq r2 thisline))
8907 (if (not c1) (setq c1 col))
8908 (if (not c2) (setq c2 col))
8909 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
8910 ;; just one field
8911 (progn
8912 (goto-line r1)
8913 (while (not (looking-at org-table-dataline-regexp))
8914 (beginning-of-line 2))
8915 (prog1 (org-trim (org-table-get-field c1))
8916 (if highlight (org-table-highlight-rectangle (point) (point)))))
8917 ;; A range, return a vector
8918 ;; First sort the numbers to get a regular ractangle
8919 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
8920 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
8921 (goto-line r1)
8922 (while (not (looking-at org-table-dataline-regexp))
8923 (beginning-of-line 2))
8924 (org-table-goto-column c1)
8925 (setq beg (point))
8926 (goto-line r2)
8927 (while (not (looking-at org-table-dataline-regexp))
8928 (beginning-of-line 0))
8929 (org-table-goto-column c2)
8930 (setq end (point))
8931 (if highlight
8932 (org-table-highlight-rectangle
8933 beg (progn (skip-chars-forward "^|\n") (point))))
8934 ;; return string representation of calc vector
8935 (mapcar 'org-trim
8936 (apply 'append (org-table-copy-region beg end)))))))
8938 (defun org-table-get-descriptor-line (desc &optional cline bline table)
8939 "Analyze descriptor DESC and retrieve the corresponding line number.
8940 The cursor is currently in line CLINE, the table begins in line BLINE,
8941 and TABLE is a vector with line types."
8942 (if (string-match "^[0-9]+$" desc)
8943 (aref org-table-dlines (string-to-number desc))
8944 (setq cline (or cline (org-current-line))
8945 bline (or bline org-table-current-begin-line)
8946 table (or table org-table-current-line-types))
8947 (if (or
8948 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
8949 ;; 1 2 3 4 5 6
8950 (and (not (match-end 3)) (not (match-end 6)))
8951 (and (match-end 3) (match-end 6) (not (match-end 5))))
8952 (error "invalid row descriptor `%s'" desc))
8953 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
8954 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
8955 (odir (and (match-end 5) (match-string 5 desc)))
8956 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
8957 (i (- cline bline))
8958 (rel (and (match-end 6)
8959 (or (and (match-end 1) (not (match-end 3)))
8960 (match-end 5)))))
8961 (if (and hn (not hdir))
8962 (progn
8963 (setq i 0 hdir "+")
8964 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
8965 (if (and (not hn) on (not odir))
8966 (error "should never happen");;(aref org-table-dlines on)
8967 (if (and hn (> hn 0))
8968 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
8969 (if on
8970 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
8971 (+ bline i)))))
8973 (defun org-find-row-type (table i type backwards relative n)
8974 (let ((l (length table)))
8975 (while (> n 0)
8976 (while (and (setq i (+ i (if backwards -1 1)))
8977 (>= i 0) (< i l)
8978 (not (eq (aref table i) type))
8979 (if (and relative (eq (aref table i) 'hline))
8980 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
8981 t)))
8982 (setq n (1- n)))
8983 (if (or (< i 0) (>= i l))
8984 (error "Row descriptior leads outside table")
8985 i)))
8987 (defun org-rewrite-old-row-references (s)
8988 (if (string-match "&[-+0-9I]" s)
8989 (error "Formula contains old &row reference, please rewrite using @-syntax")
8992 (defun org-table-make-reference (elements keep-empty numbers lispp)
8993 "Convert list ELEMENTS to something appropriate to insert into formula.
8994 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
8995 NUMBERS indicates that everything should be converted to numbers.
8996 LISPP means to return something appropriate for a Lisp list."
8997 (if (stringp elements) ; just a single val
8998 (if lispp
8999 (if (eq lispp 'literal)
9000 elements
9001 (prin1-to-string (if numbers (string-to-number elements) elements)))
9002 (if (equal elements "") (setq elements "0"))
9003 (if numbers (number-to-string (string-to-number elements)) elements))
9004 (unless keep-empty
9005 (setq elements
9006 (delq nil
9007 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
9008 elements))))
9009 (setq elements (or elements '("0")))
9010 (if lispp
9011 (mapconcat
9012 (lambda (x)
9013 (if (eq lispp 'literal)
9015 (prin1-to-string (if numbers (string-to-number x) x))))
9016 elements " ")
9017 (concat "[" (mapconcat
9018 (lambda (x)
9019 (if numbers (number-to-string (string-to-number x)) x))
9020 elements
9021 ",") "]"))))
9023 (defun org-table-recalculate (&optional all noalign)
9024 "Recalculate the current table line by applying all stored formulas.
9025 With prefix arg ALL, do this for all lines in the table."
9026 (interactive "P")
9027 (or (memq this-command org-recalc-commands)
9028 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9029 (unless (org-at-table-p) (error "Not at a table"))
9030 (if (equal all '(16))
9031 (org-table-iterate)
9032 (org-table-get-specials)
9033 (let* ((eqlist (sort (org-table-get-stored-formulas)
9034 (lambda (a b) (string< (car a) (car b)))))
9035 (inhibit-redisplay (not debug-on-error))
9036 (line-re org-table-dataline-regexp)
9037 (thisline (org-current-line))
9038 (thiscol (org-table-current-column))
9039 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
9040 ;; Insert constants in all formulas
9041 (setq eqlist
9042 (mapcar (lambda (x)
9043 (setcdr x (org-table-formula-substitute-names (cdr x)))
9045 eqlist))
9046 ;; Split the equation list
9047 (while (setq eq (pop eqlist))
9048 (if (<= (string-to-char (car eq)) ?9)
9049 (push eq eqlnum)
9050 (push eq eqlname)))
9051 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9052 (if all
9053 (progn
9054 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9055 (goto-char (setq beg (org-table-begin)))
9056 (if (re-search-forward org-table-calculate-mark-regexp end t)
9057 ;; This is a table with marked lines, compute selected lines
9058 (setq line-re org-table-recalculate-regexp)
9059 ;; Move forward to the first non-header line
9060 (if (and (re-search-forward org-table-dataline-regexp end t)
9061 (re-search-forward org-table-hline-regexp end t)
9062 (re-search-forward org-table-dataline-regexp end t))
9063 (setq beg (match-beginning 0))
9064 nil))) ;; just leave beg where it is
9065 (setq beg (point-at-bol)
9066 end (move-marker (make-marker) (1+ (point-at-eol)))))
9067 (goto-char beg)
9068 (and all (message "Re-applying formulas to full table..."))
9070 ;; First find the named fields, and mark them untouchanble
9071 (remove-text-properties beg end '(org-untouchable t))
9072 (while (setq eq (pop eqlname))
9073 (setq name (car eq)
9074 a (assoc name org-table-named-field-locations))
9075 (and (not a)
9076 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
9077 (setq a (list name
9078 (aref org-table-dlines
9079 (string-to-number (match-string 1 name)))
9080 (string-to-number (match-string 2 name)))))
9081 (when (and a (or all (equal (nth 1 a) thisline)))
9082 (message "Re-applying formula to field: %s" name)
9083 (goto-line (nth 1 a))
9084 (org-table-goto-column (nth 2 a))
9085 (push (append a (list (cdr eq))) eqlname1)
9086 ;; FIXME (org-table-eval-formula nil (cdr eq) 'noalign 'nocst
9087 ;; FIXME 'nostore 'noanalysis)
9088 (org-table-put-field-property :org-untouchable t)))
9090 ;; Now evauluate the column formulas, but skip fields covered by
9091 ;; field formulas
9092 (goto-char beg)
9093 (while (re-search-forward line-re end t)
9094 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
9095 ;; Unprotected line, recalculate
9096 (and all (message "Re-applying formulas to full table...(line %d)"
9097 (setq cnt (1+ cnt))))
9098 (setq org-last-recalc-line (org-current-line))
9099 (setq eql eqlnum)
9100 (while (setq entry (pop eql))
9101 (goto-line org-last-recalc-line)
9102 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9103 (unless (get-text-property (point) :org-untouchable)
9104 (org-table-eval-formula nil (cdr entry)
9105 'noalign 'nocst 'nostore 'noanalysis)))))
9107 ;; Now evaluate the field formulas
9108 (while (setq eq (pop eqlname1))
9109 (message "Re-applying formula to field: %s" (car eq))
9110 (goto-line (nth 1 eq))
9111 (org-table-goto-column (nth 2 eq))
9112 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
9113 'nostore 'noanalysis))
9115 (goto-line thisline)
9116 (org-table-goto-column thiscol)
9117 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
9118 (or noalign (and org-table-may-need-update (org-table-align))
9119 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9121 ;; back to initial position
9122 (message "Re-applying formulas...done")
9123 (goto-line thisline)
9124 (org-table-goto-column thiscol)
9125 (or noalign (and org-table-may-need-update (org-table-align))
9126 (and all (message "Re-applying formulas...done"))))))
9128 (defun org-table-iterate (&optional arg)
9129 "Recalculate the table until it does not change anymore."
9130 (interactive "P")
9131 (let ((imax (if arg (prefix-numeric-value arg) 10))
9132 (i 0)
9133 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
9134 thistbl)
9135 (catch 'exit
9136 (while (< i imax)
9137 (setq i (1+ i))
9138 (org-table-recalculate 'all)
9139 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
9140 (if (not (string= lasttbl thistbl))
9141 (setq lasttbl thistbl)
9142 (if (> i 1)
9143 (message "Convergence after %d iterations" i)
9144 (message "Table was already stable"))
9145 (throw 'exit t)))
9146 (error "No convergence after %d iterations" i))))
9148 (defun org-table-formula-substitute-names (f)
9149 "Replace $const with values in string F."
9150 (let ((start 0) a (f1 f))
9151 ;; First, check for column names
9152 (while (setq start (string-match org-table-column-name-regexp f start))
9153 (setq start (1+ start))
9154 (setq a (assoc (match-string 1 f) org-table-column-names))
9155 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9156 ;; Parameters and constants
9157 (setq start 0)
9158 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
9159 (setq start (1+ start))
9160 (if (setq a (save-match-data
9161 (org-table-get-constant (match-string 1 f))))
9162 (setq f (replace-match (concat "(" a ")") t t f))))
9163 (if org-table-formula-debug
9164 (put-text-property 0 (length f) :orig-formula f1 f))
9167 (defun org-table-get-constant (const)
9168 "Find the value for a parameter or constant in a formula.
9169 Parameters get priority."
9170 (or (cdr (assoc const org-table-local-parameters))
9171 (cdr (assoc const org-table-formula-constants-local))
9172 (cdr (assoc const org-table-formula-constants))
9173 (and (fboundp 'constants-get) (constants-get const))
9174 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
9175 (org-entry-get nil (substring const 5) 'inherit))
9176 "#UNDEFINED_NAME"))
9178 (defvar org-table-fedit-map
9179 (let ((map (make-sparse-keymap)))
9180 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
9181 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
9182 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
9183 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
9184 (org-defkey map "\C-c?" 'org-table-show-reference)
9185 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
9186 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
9187 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
9188 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
9189 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
9190 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
9191 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
9192 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
9193 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
9194 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
9195 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
9196 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
9197 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
9198 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
9199 map))
9201 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
9202 '("Edit-Formulas"
9203 ["Finish and Install" org-table-fedit-finish t]
9204 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
9205 ["Abort" org-table-fedit-abort t]
9206 "--"
9207 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
9208 ["Complete Lisp Symbol" lisp-complete-symbol t]
9209 "--"
9210 "Shift Reference at Point"
9211 ["Up" org-table-fedit-ref-up t]
9212 ["Down" org-table-fedit-ref-down t]
9213 ["Left" org-table-fedit-ref-left t]
9214 ["Right" org-table-fedit-ref-right t]
9216 "Change Test Row for Column Formulas"
9217 ["Up" org-table-fedit-line-up t]
9218 ["Down" org-table-fedit-line-down t]
9219 "--"
9220 ["Scroll Table Window" org-table-fedit-scroll t]
9221 ["Scroll Table Window down" org-table-fedit-scroll-down t]
9222 ["Show Table Grid" org-table-fedit-toggle-coordinates
9223 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
9224 org-table-overlay-coordinates)]
9225 "--"
9226 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
9227 :style toggle :selected org-table-buffer-is-an]))
9229 (defvar org-pos)
9231 (defun org-table-edit-formulas ()
9232 "Edit the formulas of the current table in a separate buffer."
9233 (interactive)
9234 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
9235 (beginning-of-line 0))
9236 (unless (org-at-table-p) (error "Not at a table"))
9237 (org-table-get-specials)
9238 (let ((key (org-table-current-field-formula 'key 'noerror))
9239 (eql (sort (org-table-get-stored-formulas 'noerror)
9240 'org-table-formula-less-p))
9241 (pos (move-marker (make-marker) (point)))
9242 (startline 1)
9243 (wc (current-window-configuration))
9244 (titles '((column . "# Column Formulas\n")
9245 (field . "# Field Formulas\n")
9246 (named . "# Named Field Formulas\n")))
9247 entry s type title)
9248 (switch-to-buffer-other-window "*Edit Formulas*")
9249 (erase-buffer)
9250 ;; Keep global-font-lock-mode from turning on font-lock-mode
9251 (let ((font-lock-global-modes '(not fundamental-mode)))
9252 (fundamental-mode))
9253 (org-set-local 'font-lock-global-modes (list 'not major-mode))
9254 (org-set-local 'org-pos pos)
9255 (org-set-local 'org-window-configuration wc)
9256 (use-local-map org-table-fedit-map)
9257 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
9258 (easy-menu-add org-table-fedit-menu)
9259 (setq startline (org-current-line))
9260 (while (setq entry (pop eql))
9261 (setq type (cond
9262 ((equal (string-to-char (car entry)) ?@) 'field)
9263 ((string-match "^[0-9]" (car entry)) 'column)
9264 (t 'named)))
9265 (when (setq title (assq type titles))
9266 (or (bobp) (insert "\n"))
9267 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
9268 (setq titles (delq title titles)))
9269 (if (equal key (car entry)) (setq startline (org-current-line)))
9270 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
9271 (car entry) " = " (cdr entry) "\n"))
9272 (remove-text-properties 0 (length s) '(face nil) s)
9273 (insert s))
9274 (if (eq org-table-use-standard-references t)
9275 (org-table-fedit-toggle-ref-type))
9276 (goto-line startline)
9277 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
9279 (defun org-table-fedit-post-command ()
9280 (when (not (memq this-command '(lisp-complete-symbol)))
9281 (let ((win (selected-window)))
9282 (save-excursion
9283 (condition-case nil
9284 (org-table-show-reference)
9285 (error nil))
9286 (select-window win)))))
9288 (defun org-table-formula-to-user (s)
9289 "Convert a formula from internal to user representation."
9290 (if (eq org-table-use-standard-references t)
9291 (org-table-convert-refs-to-an s)
9294 (defun org-table-formula-from-user (s)
9295 "Convert a formula from user to internal representation."
9296 (if org-table-use-standard-references
9297 (org-table-convert-refs-to-rc s)
9300 (defun org-table-convert-refs-to-rc (s)
9301 "Convert spreadsheet references from AB7 to @7$28.
9302 Works for single references, but also for entire formulas and even the
9303 full TBLFM line."
9304 (let ((start 0))
9305 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
9306 (cond
9307 ((match-end 3)
9308 ;; format match, just advance
9309 (setq start (match-end 0)))
9310 ((and (> (match-beginning 0) 0)
9311 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
9312 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
9313 ;; 3.e5 or something like this. FIXME: is this ok????
9314 (setq start (match-end 0)))
9316 (setq start (match-beginning 0)
9317 s (replace-match
9318 (if (equal (match-string 2 s) "&")
9319 (format "$%d" (org-letters-to-number (match-string 1 s)))
9320 (format "@%d$%d"
9321 (string-to-number (match-string 2 s))
9322 (org-letters-to-number (match-string 1 s))))
9323 t t s)))))
9326 (defun org-table-convert-refs-to-an (s)
9327 "Convert spreadsheet references from to @7$28 to AB7.
9328 Works for single references, but also for entire formulas and even the
9329 full TBLFM line."
9330 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
9331 (setq s (replace-match
9332 (format "%s%d"
9333 (org-number-to-letters
9334 (string-to-number (match-string 2 s)))
9335 (string-to-number (match-string 1 s)))
9336 t t s)))
9337 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
9338 (setq s (replace-match (concat "\\1"
9339 (org-number-to-letters
9340 (string-to-number (match-string 2 s))) "&")
9341 t nil s)))
9344 (defun org-letters-to-number (s)
9345 "Convert a base 26 number represented by letters into an integer.
9346 For example: AB -> 28."
9347 (let ((n 0))
9348 (setq s (upcase s))
9349 (while (> (length s) 0)
9350 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
9351 s (substring s 1)))
9354 (defun org-number-to-letters (n)
9355 "Convert an integer into a base 26 number represented by letters.
9356 For example: 28 -> AB."
9357 (let ((s ""))
9358 (while (> n 0)
9359 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
9360 n (/ (1- n) 26)))
9363 (defun org-table-fedit-convert-buffer (function)
9364 "Convert all references in this buffer, using FUNTION."
9365 (let ((line (org-current-line)))
9366 (goto-char (point-min))
9367 (while (not (eobp))
9368 (insert (funcall function (buffer-substring (point) (point-at-eol))))
9369 (delete-region (point) (point-at-eol))
9370 (or (eobp) (forward-char 1)))
9371 (goto-line line)))
9373 (defun org-table-fedit-toggle-ref-type ()
9374 "Convert all references in the buffer from B3 to @3$2 and back."
9375 (interactive)
9376 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
9377 (org-table-fedit-convert-buffer
9378 (if org-table-buffer-is-an
9379 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
9380 (message "Reference type switched to %s"
9381 (if org-table-buffer-is-an "A1 etc" "@row$column")))
9383 (defun org-table-fedit-ref-up ()
9384 "Shift the reference at point one row/hline up."
9385 (interactive)
9386 (org-table-fedit-shift-reference 'up))
9387 (defun org-table-fedit-ref-down ()
9388 "Shift the reference at point one row/hline down."
9389 (interactive)
9390 (org-table-fedit-shift-reference 'down))
9391 (defun org-table-fedit-ref-left ()
9392 "Shift the reference at point one field to the left."
9393 (interactive)
9394 (org-table-fedit-shift-reference 'left))
9395 (defun org-table-fedit-ref-right ()
9396 "Shift the reference at point one field to the right."
9397 (interactive)
9398 (org-table-fedit-shift-reference 'right))
9400 (defun org-table-fedit-shift-reference (dir)
9401 (cond
9402 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
9403 (if (memq dir '(left right))
9404 (org-rematch-and-replace 1 (eq dir 'left))
9405 (error "Cannot shift reference in this direction")))
9406 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
9407 ;; A B3-like reference
9408 (if (memq dir '(up down))
9409 (org-rematch-and-replace 2 (eq dir 'up))
9410 (org-rematch-and-replace 1 (eq dir 'left))))
9411 ((org-at-regexp-p
9412 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
9413 ;; An internal reference
9414 (if (memq dir '(up down))
9415 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
9416 (org-rematch-and-replace 5 (eq dir 'left))))))
9418 (defun org-rematch-and-replace (n &optional decr hline)
9419 "Re-match the group N, and replace it with the shifted refrence."
9420 (or (match-end n) (error "Cannot shift reference in this direction"))
9421 (goto-char (match-beginning n))
9422 (and (looking-at (regexp-quote (match-string n)))
9423 (replace-match (org-shift-refpart (match-string 0) decr hline)
9424 t t)))
9426 (defun org-shift-refpart (ref &optional decr hline)
9427 "Shift a refrence part REF.
9428 If DECR is set, decrease the references row/column, else increase.
9429 If HLINE is set, this may be a hline reference, it certainly is not
9430 a translation reference."
9431 (save-match-data
9432 (let* ((sign (string-match "^[-+]" ref)) n)
9434 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
9435 (cond
9436 ((and hline (string-match "^I+" ref))
9437 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
9438 (setq n (+ n (if decr -1 1)))
9439 (if (= n 0) (setq n (+ n (if decr -1 1))))
9440 (if sign
9441 (setq sign (if (< n 0) "-" "+") n (abs n))
9442 (setq n (max 1 n)))
9443 (concat sign (make-string n ?I)))
9445 ((string-match "^[0-9]+" ref)
9446 (setq n (string-to-number (concat sign ref)))
9447 (setq n (+ n (if decr -1 1)))
9448 (if sign
9449 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
9450 (number-to-string (max 1 n))))
9452 ((string-match "^[a-zA-Z]+" ref)
9453 (org-number-to-letters
9454 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
9456 (t (error "Cannot shift reference"))))))
9458 (defun org-table-fedit-toggle-coordinates ()
9459 "Toggle the display of coordinates in the refrenced table."
9460 (interactive)
9461 (let ((pos (marker-position org-pos)))
9462 (with-current-buffer (marker-buffer org-pos)
9463 (save-excursion
9464 (goto-char pos)
9465 (org-table-toggle-coordinate-overlays)))))
9467 (defun org-table-fedit-finish (&optional arg)
9468 "Parse the buffer for formula definitions and install them.
9469 With prefix ARG, apply the new formulas to the table."
9470 (interactive "P")
9471 (org-table-remove-rectangle-highlight)
9472 (if org-table-use-standard-references
9473 (progn
9474 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
9475 (setq org-table-buffer-is-an nil)))
9476 (let ((pos org-pos) eql var form)
9477 (goto-char (point-min))
9478 (while (re-search-forward
9479 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
9480 nil t)
9481 (setq var (if (match-end 2) (match-string 2) (match-string 1))
9482 form (match-string 3))
9483 (setq form (org-trim form))
9484 (when (not (equal form ""))
9485 (while (string-match "[ \t]*\n[ \t]*" form)
9486 (setq form (replace-match " " t t form)))
9487 (when (assoc var eql)
9488 (error "Double formulas for %s" var))
9489 (push (cons var form) eql)))
9490 (setq org-pos nil)
9491 (set-window-configuration org-window-configuration)
9492 (select-window (get-buffer-window (marker-buffer pos)))
9493 (goto-char pos)
9494 (unless (org-at-table-p)
9495 (error "Lost table position - cannot install formulae"))
9496 (org-table-store-formulas eql)
9497 (move-marker pos nil)
9498 (kill-buffer "*Edit Formulas*")
9499 (if arg
9500 (org-table-recalculate 'all)
9501 (message "New formulas installed - press C-u C-c C-c to apply."))))
9503 (defun org-table-fedit-abort ()
9504 "Abort editing formulas, without installing the changes."
9505 (interactive)
9506 (org-table-remove-rectangle-highlight)
9507 (let ((pos org-pos))
9508 (set-window-configuration org-window-configuration)
9509 (select-window (get-buffer-window (marker-buffer pos)))
9510 (goto-char pos)
9511 (move-marker pos nil)
9512 (message "Formula editing aborted without installing changes")))
9514 (defun org-table-fedit-lisp-indent ()
9515 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
9516 (interactive)
9517 (let ((pos (point)) beg end ind)
9518 (beginning-of-line 1)
9519 (cond
9520 ((looking-at "[ \t]")
9521 (goto-char pos)
9522 (call-interactively 'lisp-indent-line))
9523 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
9524 ((not (fboundp 'pp-buffer))
9525 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
9526 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
9527 (goto-char (- (match-end 0) 2))
9528 (setq beg (point))
9529 (setq ind (make-string (current-column) ?\ ))
9530 (condition-case nil (forward-sexp 1)
9531 (error
9532 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
9533 (setq end (point))
9534 (save-restriction
9535 (narrow-to-region beg end)
9536 (if (eq last-command this-command)
9537 (progn
9538 (goto-char (point-min))
9539 (setq this-command nil)
9540 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
9541 (replace-match " ")))
9542 (pp-buffer)
9543 (untabify (point-min) (point-max))
9544 (goto-char (1+ (point-min)))
9545 (while (re-search-forward "^." nil t)
9546 (beginning-of-line 1)
9547 (insert ind))
9548 (goto-char (point-max))
9549 (backward-delete-char 1)))
9550 (goto-char beg))
9551 (t nil))))
9553 (defvar org-show-positions nil)
9555 (defun org-table-show-reference (&optional local)
9556 "Show the location/value of the $ expression at point."
9557 (interactive)
9558 (org-table-remove-rectangle-highlight)
9559 (catch 'exit
9560 (let ((pos (if local (point) org-pos))
9561 (face2 'highlight)
9562 (org-inhibit-highlight-removal t)
9563 (win (selected-window))
9564 (org-show-positions nil)
9565 var name e what match dest)
9566 (if local (org-table-get-specials))
9567 (setq what (cond
9568 ((or (org-at-regexp-p org-table-range-regexp2)
9569 (org-at-regexp-p org-table-translate-regexp)
9570 (org-at-regexp-p org-table-range-regexp))
9571 (setq match
9572 (save-match-data
9573 (org-table-convert-refs-to-rc (match-string 0))))
9574 'range)
9575 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
9576 ((org-at-regexp-p "\\$[0-9]+") 'column)
9577 ((not local) nil)
9578 (t (error "No reference at point")))
9579 match (and what (or match (match-string 0))))
9580 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
9581 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
9582 'secondary-selection))
9583 (org-add-hook 'before-change-functions
9584 'org-table-remove-rectangle-highlight)
9585 (if (eq what 'name) (setq var (substring match 1)))
9586 (when (eq what 'range)
9587 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
9588 (setq match (org-table-formula-substitute-names match)))
9589 (unless local
9590 (save-excursion
9591 (end-of-line 1)
9592 (re-search-backward "^\\S-" nil t)
9593 (beginning-of-line 1)
9594 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
9595 (setq dest
9596 (save-match-data
9597 (org-table-convert-refs-to-rc (match-string 1))))
9598 (org-table-add-rectangle-overlay
9599 (match-beginning 1) (match-end 1) face2))))
9600 (if (and (markerp pos) (marker-buffer pos))
9601 (if (get-buffer-window (marker-buffer pos))
9602 (select-window (get-buffer-window (marker-buffer pos)))
9603 (switch-to-buffer-other-window (get-buffer-window
9604 (marker-buffer pos)))))
9605 (goto-char pos)
9606 (org-table-force-dataline)
9607 (when dest
9608 (setq name (substring dest 1))
9609 (cond
9610 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
9611 (setq e (assoc name org-table-named-field-locations))
9612 (goto-line (nth 1 e))
9613 (org-table-goto-column (nth 2 e)))
9614 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
9615 (let ((l (string-to-number (match-string 1 dest)))
9616 (c (string-to-number (match-string 2 dest))))
9617 (goto-line (aref org-table-dlines l))
9618 (org-table-goto-column c)))
9619 (t (org-table-goto-column (string-to-number name))))
9620 (move-marker pos (point))
9621 (org-table-highlight-rectangle nil nil face2))
9622 (cond
9623 ((equal dest match))
9624 ((not match))
9625 ((eq what 'range)
9626 (condition-case nil
9627 (save-excursion
9628 (org-table-get-range match nil nil 'highlight))
9629 (error nil)))
9630 ((setq e (assoc var org-table-named-field-locations))
9631 (goto-line (nth 1 e))
9632 (org-table-goto-column (nth 2 e))
9633 (org-table-highlight-rectangle (point) (point))
9634 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9635 ((setq e (assoc var org-table-column-names))
9636 (org-table-goto-column (string-to-number (cdr e)))
9637 (org-table-highlight-rectangle (point) (point))
9638 (goto-char (org-table-begin))
9639 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9640 (org-table-end) t)
9641 (progn
9642 (goto-char (match-beginning 1))
9643 (org-table-highlight-rectangle)
9644 (message "Named column (column %s)" (cdr e)))
9645 (error "Column name not found")))
9646 ((eq what 'column)
9647 ;; column number
9648 (org-table-goto-column (string-to-number (substring match 1)))
9649 (org-table-highlight-rectangle (point) (point))
9650 (message "Column %s" (substring match 1)))
9651 ((setq e (assoc var org-table-local-parameters))
9652 (goto-char (org-table-begin))
9653 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9654 (progn
9655 (goto-char (match-beginning 1))
9656 (org-table-highlight-rectangle)
9657 (message "Local parameter."))
9658 (error "Parameter not found")))
9660 (cond
9661 ((not var) (error "No reference at point"))
9662 ((setq e (assoc var org-table-formula-constants-local))
9663 (message "Local Constant: $%s=%s in #+CONSTANTS line."
9664 var (cdr e)))
9665 ((setq e (assoc var org-table-formula-constants))
9666 (message "Constant: $%s=%s in `org-table-formula-constants'."
9667 var (cdr e)))
9668 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9669 (message "Constant: $%s=%s, from `constants.el'%s."
9670 var e (format " (%s units)" constants-unit-system)))
9671 (t (error "Undefined name $%s" var)))))
9672 (goto-char pos)
9673 (when (and org-show-positions
9674 (not (memq this-command '(org-table-fedit-scroll
9675 org-table-fedit-scroll-down))))
9676 (push pos org-show-positions)
9677 (push org-table-current-begin-pos org-show-positions)
9678 (let ((min (apply 'min org-show-positions))
9679 (max (apply 'max org-show-positions)))
9680 (goto-char min) (recenter 0)
9681 (goto-char max)
9682 (or (pos-visible-in-window-p max) (recenter -1))))
9683 (select-window win))))
9685 (defun org-table-force-dataline ()
9686 "Make sure the cursor is in a dataline in a table."
9687 (unless (save-excursion
9688 (beginning-of-line 1)
9689 (looking-at org-table-dataline-regexp))
9690 (let* ((re org-table-dataline-regexp)
9691 (p1 (save-excursion (re-search-forward re nil 'move)))
9692 (p2 (save-excursion (re-search-backward re nil 'move))))
9693 (cond ((and p1 p2)
9694 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
9695 p1 p2)))
9696 ((or p1 p2) (goto-char (or p1 p2)))
9697 (t (error "No table dataline around here"))))))
9699 (defun org-table-fedit-line-up ()
9700 "Move cursor one line up in the window showing the table."
9701 (interactive)
9702 (org-table-fedit-move 'previous-line))
9704 (defun org-table-fedit-line-down ()
9705 "Move cursor one line down in the window showing the table."
9706 (interactive)
9707 (org-table-fedit-move 'next-line))
9709 (defun org-table-fedit-move (command)
9710 "Move the cursor in the window shoinw the table.
9711 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
9712 (let ((org-table-allow-automatic-line-recalculation nil)
9713 (pos org-pos) (win (selected-window)) p)
9714 (select-window (get-buffer-window (marker-buffer org-pos)))
9715 (setq p (point))
9716 (call-interactively command)
9717 (while (and (org-at-table-p)
9718 (org-at-table-hline-p))
9719 (call-interactively command))
9720 (or (org-at-table-p) (goto-char p))
9721 (move-marker pos (point))
9722 (select-window win)))
9724 (defun org-table-fedit-scroll (N)
9725 (interactive "p")
9726 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
9727 (scroll-other-window N)))
9729 (defun org-table-fedit-scroll-down (N)
9730 (interactive "p")
9731 (org-table-fedit-scroll (- N)))
9733 (defvar org-table-rectangle-overlays nil)
9735 (defun org-table-add-rectangle-overlay (beg end &optional face)
9736 "Add a new overlay."
9737 (let ((ov (org-make-overlay beg end)))
9738 (org-overlay-put ov 'face (or face 'secondary-selection))
9739 (push ov org-table-rectangle-overlays)))
9741 (defun org-table-highlight-rectangle (&optional beg end face)
9742 "Highlight rectangular region in a table."
9743 (setq beg (or beg (point)) end (or end (point)))
9744 (let ((b (min beg end))
9745 (e (max beg end))
9746 l1 c1 l2 c2 tmp)
9747 (and (boundp 'org-show-positions)
9748 (setq org-show-positions (cons b (cons e org-show-positions))))
9749 (goto-char (min beg end))
9750 (setq l1 (org-current-line)
9751 c1 (org-table-current-column))
9752 (goto-char (max beg end))
9753 (setq l2 (org-current-line)
9754 c2 (org-table-current-column))
9755 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
9756 (goto-line l1)
9757 (beginning-of-line 1)
9758 (loop for line from l1 to l2 do
9759 (when (looking-at org-table-dataline-regexp)
9760 (org-table-goto-column c1)
9761 (skip-chars-backward "^|\n") (setq beg (point))
9762 (org-table-goto-column c2)
9763 (skip-chars-forward "^|\n") (setq end (point))
9764 (org-table-add-rectangle-overlay beg end face))
9765 (beginning-of-line 2))
9766 (goto-char b))
9767 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
9769 (defun org-table-remove-rectangle-highlight (&rest ignore)
9770 "Remove the rectangle overlays."
9771 (unless org-inhibit-highlight-removal
9772 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
9773 (mapc 'org-delete-overlay org-table-rectangle-overlays)
9774 (setq org-table-rectangle-overlays nil)))
9776 (defvar org-table-coordinate-overlays nil
9777 "Collects the cooordinate grid overlays, so that they can be removed.")
9778 (make-variable-buffer-local 'org-table-coordinate-overlays)
9780 (defun org-table-overlay-coordinates ()
9781 "Add overlays to the table at point, to show row/column coordinates."
9782 (interactive)
9783 (mapc 'org-delete-overlay org-table-coordinate-overlays)
9784 (setq org-table-coordinate-overlays nil)
9785 (save-excursion
9786 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
9787 (goto-char (org-table-begin))
9788 (while (org-at-table-p)
9789 (setq eol (point-at-eol))
9790 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
9791 (push ov org-table-coordinate-overlays)
9792 (setq hline (looking-at org-table-hline-regexp))
9793 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
9794 (format "%4d" (setq id (1+ id)))))
9795 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
9796 (when hline
9797 (setq ic 0)
9798 (while (re-search-forward "[+|]\\(-+\\)" eol t)
9799 (setq beg (1+ (match-beginning 0))
9800 ic (1+ ic)
9801 s1 (concat "$" (int-to-string ic))
9802 s2 (org-number-to-letters ic)
9803 str (if (eq org-table-use-standard-references t) s2 s1))
9804 (setq ov (org-make-overlay beg (+ beg (length str))))
9805 (push ov org-table-coordinate-overlays)
9806 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
9807 (beginning-of-line 2)))))
9809 (defun org-table-toggle-coordinate-overlays ()
9810 "Toggle the display of Row/Column numbers in tables."
9811 (interactive)
9812 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
9813 (message "Row/Column number display turned %s"
9814 (if org-table-overlay-coordinates "on" "off"))
9815 (if (and (org-at-table-p) org-table-overlay-coordinates)
9816 (org-table-align))
9817 (unless org-table-overlay-coordinates
9818 (mapc 'org-delete-overlay org-table-coordinate-overlays)
9819 (setq org-table-coordinate-overlays nil)))
9821 (defun org-table-toggle-formula-debugger ()
9822 "Toggle the formula debugger in tables."
9823 (interactive)
9824 (setq org-table-formula-debug (not org-table-formula-debug))
9825 (message "Formula debugging has been turned %s"
9826 (if org-table-formula-debug "on" "off")))
9828 ;;; The orgtbl minor mode
9830 ;; Define a minor mode which can be used in other modes in order to
9831 ;; integrate the org-mode table editor.
9833 ;; This is really a hack, because the org-mode table editor uses several
9834 ;; keys which normally belong to the major mode, for example the TAB and
9835 ;; RET keys. Here is how it works: The minor mode defines all the keys
9836 ;; necessary to operate the table editor, but wraps the commands into a
9837 ;; function which tests if the cursor is currently inside a table. If that
9838 ;; is the case, the table editor command is executed. However, when any of
9839 ;; those keys is used outside a table, the function uses `key-binding' to
9840 ;; look up if the key has an associated command in another currently active
9841 ;; keymap (minor modes, major mode, global), and executes that command.
9842 ;; There might be problems if any of the keys used by the table editor is
9843 ;; otherwise used as a prefix key.
9845 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9846 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9847 ;; addresses this by checking explicitly for both bindings.
9849 ;; The optimized version (see variable `orgtbl-optimized') takes over
9850 ;; all keys which are bound to `self-insert-command' in the *global map*.
9851 ;; Some modes bind other commands to simple characters, for example
9852 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9853 ;; active, this binding is ignored inside tables and replaced with a
9854 ;; modified self-insert.
9856 (defvar orgtbl-mode nil
9857 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9858 table editor in arbitrary modes.")
9859 (make-variable-buffer-local 'orgtbl-mode)
9861 (defvar orgtbl-mode-map (make-keymap)
9862 "Keymap for `orgtbl-mode'.")
9864 ;;;###autoload
9865 (defun turn-on-orgtbl ()
9866 "Unconditionally turn on `orgtbl-mode'."
9867 (orgtbl-mode 1))
9869 (defvar org-old-auto-fill-inhibit-regexp nil
9870 "Local variable used by `orgtbl-mode'")
9872 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
9873 "Matches a line belonging to an orgtbl.")
9875 (defconst orgtbl-extra-font-lock-keywords
9876 (list (list (concat "^" orgtbl-line-start-regexp ".*")
9877 0 (quote 'org-table) 'prepend))
9878 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
9880 ;;;###autoload
9881 (defun orgtbl-mode (&optional arg)
9882 "The `org-mode' table editor as a minor mode for use in other modes."
9883 (interactive)
9884 (if (org-mode-p)
9885 ;; Exit without error, in case some hook functions calls this
9886 ;; by accident in org-mode.
9887 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9888 (setq orgtbl-mode
9889 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9890 (if orgtbl-mode
9891 (progn
9892 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9893 ;; Make sure we are first in minor-mode-map-alist
9894 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9895 (and c (setq minor-mode-map-alist
9896 (cons c (delq c minor-mode-map-alist)))))
9897 (org-set-local (quote org-table-may-need-update) t)
9898 (org-add-hook 'before-change-functions 'org-before-change-function
9899 nil 'local)
9900 (org-set-local 'org-old-auto-fill-inhibit-regexp
9901 auto-fill-inhibit-regexp)
9902 (org-set-local 'auto-fill-inhibit-regexp
9903 (if auto-fill-inhibit-regexp
9904 (concat orgtbl-line-start-regexp "\\|"
9905 auto-fill-inhibit-regexp)
9906 orgtbl-line-start-regexp))
9907 (org-add-to-invisibility-spec '(org-cwidth))
9908 (when (fboundp 'font-lock-add-keywords)
9909 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
9910 (org-restart-font-lock))
9911 (easy-menu-add orgtbl-mode-menu)
9912 (run-hooks 'orgtbl-mode-hook))
9913 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9914 (org-cleanup-narrow-column-properties)
9915 (org-remove-from-invisibility-spec '(org-cwidth))
9916 (remove-hook 'before-change-functions 'org-before-change-function t)
9917 (when (fboundp 'font-lock-remove-keywords)
9918 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
9919 (org-restart-font-lock))
9920 (easy-menu-remove orgtbl-mode-menu)
9921 (force-mode-line-update 'all))))
9923 (defun org-cleanup-narrow-column-properties ()
9924 "Remove all properties related to narrow-column invisibility."
9925 (let ((s 1))
9926 (while (setq s (text-property-any s (point-max)
9927 'display org-narrow-column-arrow))
9928 (remove-text-properties s (1+ s) '(display t)))
9929 (setq s 1)
9930 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
9931 (remove-text-properties s (1+ s) '(org-cwidth t)))
9932 (setq s 1)
9933 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
9934 (remove-text-properties s (1+ s) '(invisible t)))))
9936 ;; Install it as a minor mode.
9937 (put 'orgtbl-mode :included t)
9938 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9939 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9941 (defun orgtbl-make-binding (fun n &rest keys)
9942 "Create a function for binding in the table minor mode.
9943 FUN is the command to call inside a table. N is used to create a unique
9944 command name. KEYS are keys that should be checked in for a command
9945 to execute outside of tables."
9946 (eval
9947 (list 'defun
9948 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9949 '(arg)
9950 (concat "In tables, run `" (symbol-name fun) "'.\n"
9951 "Outside of tables, run the binding of `"
9952 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9953 "'.")
9954 '(interactive "p")
9955 (list 'if
9956 '(org-at-table-p)
9957 (list 'call-interactively (list 'quote fun))
9958 (list 'let '(orgtbl-mode)
9959 (list 'call-interactively
9960 (append '(or)
9961 (mapcar (lambda (k)
9962 (list 'key-binding k))
9963 keys)
9964 '('orgtbl-error))))))))
9966 (defun orgtbl-error ()
9967 "Error when there is no default binding for a table key."
9968 (interactive)
9969 (error "This key is has no function outside tables"))
9971 (defun orgtbl-setup ()
9972 "Setup orgtbl keymaps."
9973 (let ((nfunc 0)
9974 (bindings
9975 (list
9976 '([(meta shift left)] org-table-delete-column)
9977 '([(meta left)] org-table-move-column-left)
9978 '([(meta right)] org-table-move-column-right)
9979 '([(meta shift right)] org-table-insert-column)
9980 '([(meta shift up)] org-table-kill-row)
9981 '([(meta shift down)] org-table-insert-row)
9982 '([(meta up)] org-table-move-row-up)
9983 '([(meta down)] org-table-move-row-down)
9984 '("\C-c\C-w" org-table-cut-region)
9985 '("\C-c\M-w" org-table-copy-region)
9986 '("\C-c\C-y" org-table-paste-rectangle)
9987 '("\C-c-" org-table-insert-hline)
9988 '("\C-c}" org-table-toggle-coordinate-overlays)
9989 '("\C-c{" org-table-toggle-formula-debugger)
9990 '("\C-m" org-table-next-row)
9991 '([(shift return)] org-table-copy-down)
9992 '("\C-c\C-q" org-table-wrap-region)
9993 '("\C-c?" org-table-field-info)
9994 '("\C-c " org-table-blank-field)
9995 '("\C-c+" org-table-sum)
9996 '("\C-c=" org-table-eval-formula)
9997 '("\C-c'" org-table-edit-formulas)
9998 '("\C-c`" org-table-edit-field)
9999 '("\C-c*" org-table-recalculate)
10000 '("\C-c|" org-table-create-or-convert-from-region)
10001 '("\C-c^" org-table-sort-lines)
10002 '([(control ?#)] org-table-rotate-recalc-marks)))
10003 elt key fun cmd)
10004 (while (setq elt (pop bindings))
10005 (setq nfunc (1+ nfunc))
10006 (setq key (org-key (car elt))
10007 fun (nth 1 elt)
10008 cmd (orgtbl-make-binding fun nfunc key))
10009 (org-defkey orgtbl-mode-map key cmd))
10011 ;; Special treatment needed for TAB and RET
10012 (org-defkey orgtbl-mode-map [(return)]
10013 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10014 (org-defkey orgtbl-mode-map "\C-m"
10015 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10017 (org-defkey orgtbl-mode-map [(tab)]
10018 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10019 (org-defkey orgtbl-mode-map "\C-i"
10020 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
10022 (org-defkey orgtbl-mode-map [(shift tab)]
10023 (orgtbl-make-binding 'org-table-previous-field 104
10024 [(shift tab)] [(tab)] "\C-i"))
10026 (org-defkey orgtbl-mode-map "\M-\C-m"
10027 (orgtbl-make-binding 'org-table-wrap-region 105
10028 "\M-\C-m" [(meta return)]))
10029 (org-defkey orgtbl-mode-map [(meta return)]
10030 (orgtbl-make-binding 'org-table-wrap-region 106
10031 [(meta return)] "\M-\C-m"))
10033 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
10034 (when orgtbl-optimized
10035 ;; If the user wants maximum table support, we need to hijack
10036 ;; some standard editing functions
10037 (org-remap orgtbl-mode-map
10038 'self-insert-command 'orgtbl-self-insert-command
10039 'delete-char 'org-delete-char
10040 'delete-backward-char 'org-delete-backward-char)
10041 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
10042 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10043 '("OrgTbl"
10044 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10045 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10046 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10047 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10048 "--"
10049 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10050 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10051 ["Copy Field from Above"
10052 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10053 "--"
10054 ("Column"
10055 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10056 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10057 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10058 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10059 ("Row"
10060 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10061 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10062 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10063 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10064 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10065 "--"
10066 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10067 ("Rectangle"
10068 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10069 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10070 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10071 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10072 "--"
10073 ("Radio tables"
10074 ["Insert table template" orgtbl-insert-radio-table
10075 (assq major-mode orgtbl-radio-table-templates)]
10076 ["Comment/uncomment table" orgtbl-toggle-comment t])
10077 "--"
10078 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10079 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10080 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10081 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10082 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10083 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
10084 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10085 ["Sum Column/Rectangle" org-table-sum
10086 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10087 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10088 ["Debug Formulas"
10089 org-table-toggle-formula-debugger :active (org-at-table-p)
10090 :keys "C-c {"
10091 :style toggle :selected org-table-formula-debug]
10092 ["Show Col/Row Numbers"
10093 org-table-toggle-coordinate-overlays :active (org-at-table-p)
10094 :keys "C-c }"
10095 :style toggle :selected org-table-overlay-coordinates]
10099 (defun orgtbl-ctrl-c-ctrl-c (arg)
10100 "If the cursor is inside a table, realign the table.
10101 It it is a table to be sent away to a receiver, do it.
10102 With prefix arg, also recompute table."
10103 (interactive "P")
10104 (let ((pos (point)) action)
10105 (save-excursion
10106 (beginning-of-line 1)
10107 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
10108 ((looking-at "[ \t]*|") pos)
10109 ((looking-at "#\\+TBLFM:") 'recalc))))
10110 (cond
10111 ((integerp action)
10112 (goto-char action)
10113 (org-table-maybe-eval-formula)
10114 (if arg
10115 (call-interactively 'org-table-recalculate)
10116 (org-table-maybe-recalculate-line))
10117 (call-interactively 'org-table-align)
10118 (orgtbl-send-table 'maybe))
10119 ((eq action 'recalc)
10120 (save-excursion
10121 (beginning-of-line 1)
10122 (skip-chars-backward " \r\n\t")
10123 (if (org-at-table-p)
10124 (org-call-with-arg 'org-table-recalculate t))))
10125 (t (let (orgtbl-mode)
10126 (call-interactively (key-binding "\C-c\C-c")))))))
10128 (defun orgtbl-tab (arg)
10129 "Justification and field motion for `orgtbl-mode'."
10130 (interactive "P")
10131 (if arg (org-table-edit-field t)
10132 (org-table-justify-field-maybe)
10133 (org-table-next-field)))
10135 (defun orgtbl-ret ()
10136 "Justification and field motion for `orgtbl-mode'."
10137 (interactive)
10138 (org-table-justify-field-maybe)
10139 (org-table-next-row))
10141 (defun orgtbl-self-insert-command (N)
10142 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10143 If the cursor is in a table looking at whitespace, the whitespace is
10144 overwritten, and the table is not marked as requiring realignment."
10145 (interactive "p")
10146 (if (and (org-at-table-p)
10148 (and org-table-auto-blank-field
10149 (member last-command
10150 '(orgtbl-hijacker-command-100
10151 orgtbl-hijacker-command-101
10152 orgtbl-hijacker-command-102
10153 orgtbl-hijacker-command-103
10154 orgtbl-hijacker-command-104
10155 orgtbl-hijacker-command-105))
10156 (org-table-blank-field))
10158 (eq N 1)
10159 (looking-at "[^|\n]* +|"))
10160 (let (org-table-may-need-update)
10161 (goto-char (1- (match-end 0)))
10162 (delete-backward-char 1)
10163 (goto-char (match-beginning 0))
10164 (self-insert-command N))
10165 (setq org-table-may-need-update t)
10166 (let (orgtbl-mode)
10167 (call-interactively (key-binding (vector last-input-event))))))
10169 (defun org-force-self-insert (N)
10170 "Needed to enforce self-insert under remapping."
10171 (interactive "p")
10172 (self-insert-command N))
10174 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
10175 "Regula expression matching exponentials as produced by calc.")
10177 (defvar org-table-clean-did-remove-column nil)
10179 (defun orgtbl-export (table target)
10180 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
10181 (lines (org-split-string table "[ \t]*\n[ \t]*"))
10182 org-table-last-alignment org-table-last-column-widths
10183 maxcol column)
10184 (if (not (fboundp func))
10185 (error "Cannot export orgtbl table to %s" target))
10186 (setq lines (org-table-clean-before-export lines))
10187 (setq table
10188 (mapcar
10189 (lambda (x)
10190 (if (string-match org-table-hline-regexp x)
10191 'hline
10192 (org-split-string (org-trim x) "\\s-*|\\s-*")))
10193 lines))
10194 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
10195 table)))
10196 (loop for i from (1- maxcol) downto 0 do
10197 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
10198 (setq column (delq nil column))
10199 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
10200 (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))
10201 (funcall func table nil)))
10203 (defun orgtbl-send-table (&optional maybe)
10204 "Send a tranformed version of this table to the receiver position.
10205 With argument MAYBE, fail quietly if no transformation is defined for
10206 this table."
10207 (interactive)
10208 (catch 'exit
10209 (unless (org-at-table-p) (error "Not at a table"))
10210 ;; when non-interactive, we assume align has just happened.
10211 (when (interactive-p) (org-table-align))
10212 (save-excursion
10213 (goto-char (org-table-begin))
10214 (beginning-of-line 0)
10215 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
10216 (if maybe
10217 (throw 'exit nil)
10218 (error "Don't know how to transform this table."))))
10219 (let* ((name (match-string 1))
10221 (transform (intern (match-string 2)))
10222 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
10223 (skip (plist-get params :skip))
10224 (skipcols (plist-get params :skipcols))
10225 (txt (buffer-substring-no-properties
10226 (org-table-begin) (org-table-end)))
10227 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
10228 (lines (org-table-clean-before-export lines))
10229 (i0 (if org-table-clean-did-remove-column 2 1))
10230 (table (mapcar
10231 (lambda (x)
10232 (if (string-match org-table-hline-regexp x)
10233 'hline
10234 (org-remove-by-index
10235 (org-split-string (org-trim x) "\\s-*|\\s-*")
10236 skipcols i0)))
10237 lines))
10238 (fun (if (= i0 2) 'cdr 'identity))
10239 (org-table-last-alignment
10240 (org-remove-by-index (funcall fun org-table-last-alignment)
10241 skipcols i0))
10242 (org-table-last-column-widths
10243 (org-remove-by-index (funcall fun org-table-last-column-widths)
10244 skipcols i0)))
10246 (unless (fboundp transform)
10247 (error "No such transformation function %s" transform))
10248 (setq txt (funcall transform table params))
10249 ;; Find the insertion place
10250 (save-excursion
10251 (goto-char (point-min))
10252 (unless (re-search-forward
10253 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
10254 (error "Don't know where to insert translated table"))
10255 (goto-char (match-beginning 0))
10256 (beginning-of-line 2)
10257 (setq beg (point))
10258 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
10259 (error "Cannot find end of insertion region"))
10260 (beginning-of-line 1)
10261 (delete-region beg (point))
10262 (goto-char beg)
10263 (insert txt "\n"))
10264 (message "Table converted and installed at receiver location"))))
10266 (defun org-remove-by-index (list indices &optional i0)
10267 "Remove the elements in LIST with indices in INDICES.
10268 First element has index 0, or I0 if given."
10269 (if (not indices)
10270 list
10271 (if (integerp indices) (setq indices (list indices)))
10272 (setq i0 (1- (or i0 0)))
10273 (delq :rm (mapcar (lambda (x)
10274 (setq i0 (1+ i0))
10275 (if (memq i0 indices) :rm x))
10276 list))))
10278 (defun orgtbl-toggle-comment ()
10279 "Comment or uncomment the orgtbl at point."
10280 (interactive)
10281 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
10282 (re2 (concat "^" orgtbl-line-start-regexp))
10283 (commented (save-excursion (beginning-of-line 1)
10284 (cond ((looking-at re1) t)
10285 ((looking-at re2) nil)
10286 (t (error "Not at an org table")))))
10287 (re (if commented re1 re2))
10288 beg end)
10289 (save-excursion
10290 (beginning-of-line 1)
10291 (while (looking-at re) (beginning-of-line 0))
10292 (beginning-of-line 2)
10293 (setq beg (point))
10294 (while (looking-at re) (beginning-of-line 2))
10295 (setq end (point)))
10296 (comment-region beg end (if commented '(4) nil))))
10298 (defun orgtbl-insert-radio-table ()
10299 "Insert a radio table template appropriate for this major mode."
10300 (interactive)
10301 (let* ((e (assq major-mode orgtbl-radio-table-templates))
10302 (txt (nth 1 e))
10303 name pos)
10304 (unless e (error "No radio table setup defined for %s" major-mode))
10305 (setq name (read-string "Table name: "))
10306 (while (string-match "%n" txt)
10307 (setq txt (replace-match name t t txt)))
10308 (or (bolp) (insert "\n"))
10309 (setq pos (point))
10310 (insert txt)
10311 (goto-char pos)))
10313 (defun org-get-param (params header i sym &optional hsym)
10314 "Get parameter value for symbol SYM.
10315 If this is a header line, actually get the value for the symbol with an
10316 additional \"h\" inserted after the colon.
10317 If the value is a protperty list, get the element for the current column.
10318 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
10319 (let ((val (plist-get params sym)))
10320 (and hsym header (setq val (or (plist-get params hsym) val)))
10321 (if (consp val) (plist-get val i) val)))
10323 (defun orgtbl-to-generic (table params)
10324 "Convert the orgtbl-mode TABLE to some other format.
10325 This generic routine can be used for many standard cases.
10326 TABLE is a list, each entry either the symbol `hline' for a horizontal
10327 separator line, or a list of fields for that line.
10328 PARAMS is a property list of parameters that can influence the conversion.
10329 For the generic converter, some parameters are obligatory: You need to
10330 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
10331 :splice, you must have :tstart and :tend.
10333 Valid parameters are
10335 :tstart String to start the table. Ignored when :splice is t.
10336 :tend String to end the table. Ignored when :splice is t.
10338 :splice When set to t, return only table body lines, don't wrap
10339 them into :tstart and :tend. Default is nil.
10341 :hline String to be inserted on horizontal separation lines.
10342 May be nil to ignore hlines.
10344 :lstart String to start a new table line.
10345 :lend String to end a table line
10346 :sep Separator between two fields
10347 :lfmt Format for entire line, with enough %s to capture all fields.
10348 If this is present, :lstart, :lend, and :sep are ignored.
10349 :fmt A format to be used to wrap the field, should contain
10350 %s for the original field value. For example, to wrap
10351 everything in dollars, you could use :fmt \"$%s$\".
10352 This may also be a property list with column numbers and
10353 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10355 :hlstart :hlend :hlsep :hlfmt :hfmt
10356 Same as above, specific for the header lines in the table.
10357 All lines before the first hline are treated as header.
10358 If any of these is not present, the data line value is used.
10360 :efmt Use this format to print numbers with exponentials.
10361 The format should have %s twice for inserting mantissa
10362 and exponent, for example \"%s\\\\times10^{%s}\". This
10363 may also be a property list with column numbers and
10364 formats. :fmt will still be applied after :efmt.
10366 In addition to this, the parameters :skip and :skipcols are always handled
10367 directly by `orgtbl-send-table'. See manual."
10368 (interactive)
10369 (let* ((p params)
10370 (splicep (plist-get p :splice))
10371 (hline (plist-get p :hline))
10372 rtn line i fm efm lfmt h)
10374 ;; Do we have a header?
10375 (if (and (not splicep) (listp (car table)) (memq 'hline table))
10376 (setq h t))
10378 ;; Put header
10379 (unless splicep
10380 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
10382 ;; Now loop over all lines
10383 (while (setq line (pop table))
10384 (if (eq line 'hline)
10385 ;; A horizontal separator line
10386 (progn (if hline (push hline rtn))
10387 (setq h nil)) ; no longer in header
10388 ;; A normal line. Convert the fields, push line onto the result list
10389 (setq i 0)
10390 (setq line
10391 (mapcar
10392 (lambda (f)
10393 (setq i (1+ i)
10394 fm (org-get-param p h i :fmt :hfmt)
10395 efm (org-get-param p h i :efmt))
10396 (if (and efm (string-match orgtbl-exp-regexp f))
10397 (setq f (format
10398 efm (match-string 1 f) (match-string 2 f))))
10399 (if fm (setq f (format fm f)))
10401 line))
10402 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
10403 (push (apply 'format lfmt line) rtn)
10404 (push (concat
10405 (org-get-param p h i :lstart :hlstart)
10406 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
10407 (org-get-param p h i :lend :hlend))
10408 rtn))))
10410 (unless splicep
10411 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
10413 (mapconcat 'identity (nreverse rtn) "\n")))
10415 (defun orgtbl-to-latex (table params)
10416 "Convert the orgtbl-mode TABLE to LaTeX.
10417 TABLE is a list, each entry either the symbol `hline' for a horizontal
10418 separator line, or a list of fields for that line.
10419 PARAMS is a property list of parameters that can influence the conversion.
10420 Supports all parameters from `orgtbl-to-generic'. Most important for
10421 LaTeX are:
10423 :splice When set to t, return only table body lines, don't wrap
10424 them into a tabular environment. Default is nil.
10426 :fmt A format to be used to wrap the field, should contain %s for the
10427 original field value. For example, to wrap everything in dollars,
10428 use :fmt \"$%s$\". This may also be a property list with column
10429 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10431 :efmt Format for transforming numbers with exponentials. The format
10432 should have %s twice for inserting mantissa and exponent, for
10433 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
10434 This may also be a property list with column numbers and formats.
10436 The general parameters :skip and :skipcols have already been applied when
10437 this function is called."
10438 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
10439 org-table-last-alignment ""))
10440 (params2
10441 (list
10442 :tstart (concat "\\begin{tabular}{" alignment "}")
10443 :tend "\\end{tabular}"
10444 :lstart "" :lend " \\\\" :sep " & "
10445 :efmt "%s\\,(%s)" :hline "\\hline")))
10446 (orgtbl-to-generic table (org-combine-plists params2 params))))
10448 (defun orgtbl-to-html (table params)
10449 "Convert the orgtbl-mode TABLE to LaTeX.
10450 TABLE is a list, each entry either the symbol `hline' for a horizontal
10451 separator line, or a list of fields for that line.
10452 PARAMS is a property list of parameters that can influence the conversion.
10453 Currently this function recognizes the following parameters:
10455 :splice When set to t, return only table body lines, don't wrap
10456 them into a <table> environment. Default is nil.
10458 The general parameters :skip and :skipcols have already been applied when
10459 this function is called. The function does *not* use `orgtbl-to-generic',
10460 so you cannot specify parameters for it."
10461 (let* ((splicep (plist-get params :splice))
10462 html)
10463 ;; Just call the formatter we already have
10464 ;; We need to make text lines for it, so put the fields back together.
10465 (setq html (org-format-org-table-html
10466 (mapcar
10467 (lambda (x)
10468 (if (eq x 'hline)
10469 "|----+----|"
10470 (concat "| " (mapconcat 'identity x " | ") " |")))
10471 table)
10472 splicep))
10473 (if (string-match "\n+\\'" html)
10474 (setq html (replace-match "" t t html)))
10475 html))
10477 (defun orgtbl-to-texinfo (table params)
10478 "Convert the orgtbl-mode TABLE to TeXInfo.
10479 TABLE is a list, each entry either the symbol `hline' for a horizontal
10480 separator line, or a list of fields for that line.
10481 PARAMS is a property list of parameters that can influence the conversion.
10482 Supports all parameters from `orgtbl-to-generic'. Most important for
10483 TeXInfo are:
10485 :splice nil/t When set to t, return only table body lines, don't wrap
10486 them into a multitable environment. Default is nil.
10488 :fmt fmt A format to be used to wrap the field, should contain
10489 %s for the original field value. For example, to wrap
10490 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
10491 This may also be a property list with column numbers and
10492 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
10494 :cf \"f1 f2..\" The column fractions for the table. Bye default these
10495 are computed automatically from the width of the columns
10496 under org-mode.
10498 The general parameters :skip and :skipcols have already been applied when
10499 this function is called."
10500 (let* ((total (float (apply '+ org-table-last-column-widths)))
10501 (colfrac (or (plist-get params :cf)
10502 (mapconcat
10503 (lambda (x) (format "%.3f" (/ (float x) total)))
10504 org-table-last-column-widths " ")))
10505 (params2
10506 (list
10507 :tstart (concat "@multitable @columnfractions " colfrac)
10508 :tend "@end multitable"
10509 :lstart "@item " :lend "" :sep " @tab "
10510 :hlstart "@headitem ")))
10511 (orgtbl-to-generic table (org-combine-plists params2 params))))
10513 ;;;; Link Stuff
10515 ;;; Link abbreviations
10517 (defun org-link-expand-abbrev (link)
10518 "Apply replacements as defined in `org-link-abbrev-alist."
10519 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
10520 (let* ((key (match-string 1 link))
10521 (as (or (assoc key org-link-abbrev-alist-local)
10522 (assoc key org-link-abbrev-alist)))
10523 (tag (and (match-end 2) (match-string 3 link)))
10524 rpl)
10525 (if (not as)
10526 link
10527 (setq rpl (cdr as))
10528 (cond
10529 ((symbolp rpl) (funcall rpl tag))
10530 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
10531 (t (concat rpl tag)))))
10532 link))
10534 ;;; Storing and inserting links
10536 (defvar org-insert-link-history nil
10537 "Minibuffer history for links inserted with `org-insert-link'.")
10539 (defvar org-stored-links nil
10540 "Contains the links stored with `org-store-link'.")
10542 (defvar org-store-link-plist nil
10543 "Plist with info about the most recently link created with `org-store-link'.")
10545 (defvar org-link-protocols nil
10546 "Link protocols added to Org-mode using `org-add-link-type'.")
10548 (defvar org-store-link-functions nil
10549 "List of functions that are called to create and store a link.
10550 Each function will be called in turn until one returns a non-nil
10551 value. Each function should check if it is responsible for creating
10552 this link (for example by looking at the major mode).
10553 If not, it must exit and return nil.
10554 If yes, it should return a non-nil value after a calling
10555 `org-store-link-properties' with a list of properties and values.
10556 Special properties are:
10558 :type The link prefix. like \"http\". This must be given.
10559 :link The link, like \"http://www.astro.uva.nl/~dominik\".
10560 This is obligatory as well.
10561 :description Optional default description for the second pair
10562 of brackets in an Org-mode link. The user can still change
10563 this when inserting this link into an Org-mode buffer.
10565 In addition to these, any additional properties can be specified
10566 and then used in remember templates.")
10568 (defun org-add-link-type (type &optional follow publish)
10569 "Add TYPE to the list of `org-link-types'.
10570 Re-compute all regular expressions depending on `org-link-types'
10571 FOLLOW and PUBLISH are two functions. Both take the link path as
10572 an argument.
10573 FOLLOW should do whatever is necessary to follow the link, for example
10574 to find a file or display a mail message.
10575 PUBLISH takes the path and retuns the string that should be used when
10576 this document is published."
10577 (add-to-list 'org-link-types type t)
10578 (org-make-link-regexps)
10579 (add-to-list 'org-link-protocols
10580 (list type follow publish)))
10582 (defun org-add-agenda-custom-command (entry)
10583 "Replace or add a command in `org-agenda-custom-commands'.
10584 This is mostly for hacking and trying a new command - once the command
10585 works you probably want to add it to `org-agenda-custom-commands' for good."
10586 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
10587 (if ass
10588 (setcdr ass (cdr entry))
10589 (push entry org-agenda-custom-commands))))
10591 ;;;###autoload
10592 (defun org-store-link (arg)
10593 "\\<org-mode-map>Store an org-link to the current location.
10594 This link can later be inserted into an org-buffer with
10595 \\[org-insert-link].
10596 For some link types, a prefix arg is interpreted:
10597 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
10598 For file links, arg negates `org-context-in-file-links'."
10599 (interactive "P")
10600 (setq org-store-link-plist nil) ; reset
10601 (let (link cpltxt desc description search txt)
10602 (cond
10604 ((run-hook-with-args-until-success 'org-store-link-functions)
10605 (setq link (plist-get org-store-link-plist :link)
10606 desc (or (plist-get org-store-link-plist :description) link)))
10608 ((eq major-mode 'bbdb-mode)
10609 (let ((name (bbdb-record-name (bbdb-current-record)))
10610 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
10611 (setq cpltxt (concat "bbdb:" (or name company))
10612 link (org-make-link cpltxt))
10613 (org-store-link-props :type "bbdb" :name name :company company)))
10615 ((eq major-mode 'Info-mode)
10616 (setq link (org-make-link "info:"
10617 (file-name-nondirectory Info-current-file)
10618 ":" Info-current-node))
10619 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
10620 ":" Info-current-node))
10621 (org-store-link-props :type "info" :file Info-current-file
10622 :node Info-current-node))
10624 ((eq major-mode 'calendar-mode)
10625 (let ((cd (calendar-cursor-to-date)))
10626 (setq link
10627 (format-time-string
10628 (car org-time-stamp-formats)
10629 (apply 'encode-time
10630 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
10631 nil nil nil))))
10632 (org-store-link-props :type "calendar" :date cd)))
10634 ((or (eq major-mode 'vm-summary-mode)
10635 (eq major-mode 'vm-presentation-mode))
10636 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
10637 (vm-follow-summary-cursor)
10638 (save-excursion
10639 (vm-select-folder-buffer)
10640 (let* ((message (car vm-message-pointer))
10641 (folder buffer-file-name)
10642 (subject (vm-su-subject message))
10643 (to (vm-get-header-contents message "To"))
10644 (from (vm-get-header-contents message "From"))
10645 (message-id (vm-su-message-id message)))
10646 (org-store-link-props :type "vm" :from from :to to :subject subject
10647 :message-id message-id)
10648 (setq message-id (org-remove-angle-brackets message-id))
10649 (setq folder (abbreviate-file-name folder))
10650 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
10651 folder)
10652 (setq folder (replace-match "" t t folder)))
10653 (setq cpltxt (org-email-link-description))
10654 (setq link (org-make-link "vm:" folder "#" message-id)))))
10656 ((eq major-mode 'wl-summary-mode)
10657 (let* ((msgnum (wl-summary-message-number))
10658 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
10659 msgnum 'message-id))
10660 (wl-message-entity
10661 (if (fboundp 'elmo-message-entity)
10662 (elmo-message-entity
10663 wl-summary-buffer-elmo-folder msgnum)
10664 (elmo-msgdb-overview-get-entity
10665 msgnum (wl-summary-buffer-msgdb))))
10666 (from (wl-summary-line-from))
10667 (to (car (elmo-message-entity-field wl-message-entity 'to)))
10668 (subject (let (wl-thr-indent-string wl-parent-message-entity)
10669 (wl-summary-line-subject))))
10670 (org-store-link-props :type "wl" :from from :to to
10671 :subject subject :message-id message-id)
10672 (setq message-id (org-remove-angle-brackets message-id))
10673 (setq cpltxt (org-email-link-description))
10674 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
10675 "#" message-id))))
10677 ((or (equal major-mode 'mh-folder-mode)
10678 (equal major-mode 'mh-show-mode))
10679 (let ((from (org-mhe-get-header "From:"))
10680 (to (org-mhe-get-header "To:"))
10681 (message-id (org-mhe-get-header "Message-Id:"))
10682 (subject (org-mhe-get-header "Subject:")))
10683 (org-store-link-props :type "mh" :from from :to to
10684 :subject subject :message-id message-id)
10685 (setq cpltxt (org-email-link-description))
10686 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
10687 (org-remove-angle-brackets message-id)))))
10689 ((eq major-mode 'rmail-mode)
10690 (save-excursion
10691 (save-restriction
10692 (rmail-narrow-to-non-pruned-header)
10693 (let ((folder buffer-file-name)
10694 (message-id (mail-fetch-field "message-id"))
10695 (from (mail-fetch-field "from"))
10696 (to (mail-fetch-field "to"))
10697 (subject (mail-fetch-field "subject")))
10698 (org-store-link-props
10699 :type "rmail" :from from :to to
10700 :subject subject :message-id message-id)
10701 (setq message-id (org-remove-angle-brackets message-id))
10702 (setq cpltxt (org-email-link-description))
10703 (setq link (org-make-link "rmail:" folder "#" message-id))))))
10705 ((eq major-mode 'gnus-group-mode)
10706 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
10707 (gnus-group-group-name)) ; version
10708 ((fboundp 'gnus-group-name)
10709 (gnus-group-name))
10710 (t "???"))))
10711 (unless group (error "Not on a group"))
10712 (org-store-link-props :type "gnus" :group group)
10713 (setq cpltxt (concat
10714 (if (org-xor arg org-usenet-links-prefer-google)
10715 "http://groups.google.com/groups?group="
10716 "gnus:")
10717 group)
10718 link (org-make-link cpltxt))))
10720 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
10721 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
10722 (let* ((group gnus-newsgroup-name)
10723 (article (gnus-summary-article-number))
10724 (header (gnus-summary-article-header article))
10725 (from (mail-header-from header))
10726 (message-id (mail-header-id header))
10727 (date (mail-header-date header))
10728 (subject (gnus-summary-subject-string)))
10729 (org-store-link-props :type "gnus" :from from :subject subject
10730 :message-id message-id :group group)
10731 (setq cpltxt (org-email-link-description))
10732 (if (org-xor arg org-usenet-links-prefer-google)
10733 (setq link
10734 (concat
10735 cpltxt "\n "
10736 (format "http://groups.google.com/groups?as_umsgid=%s"
10737 (org-fixup-message-id-for-http message-id))))
10738 (setq link (org-make-link "gnus:" group
10739 "#" (number-to-string article))))))
10741 ((eq major-mode 'w3-mode)
10742 (setq cpltxt (url-view-url t)
10743 link (org-make-link cpltxt))
10744 (org-store-link-props :type "w3" :url (url-view-url t)))
10746 ((eq major-mode 'w3m-mode)
10747 (setq cpltxt (or w3m-current-title w3m-current-url)
10748 link (org-make-link w3m-current-url))
10749 (org-store-link-props :type "w3m" :url (url-view-url t)))
10751 ((setq search (run-hook-with-args-until-success
10752 'org-create-file-search-functions))
10753 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10754 "::" search))
10755 (setq cpltxt (or description link)))
10757 ((eq major-mode 'image-mode)
10758 (setq cpltxt (concat "file:"
10759 (abbreviate-file-name buffer-file-name))
10760 link (org-make-link cpltxt))
10761 (org-store-link-props :type "image" :file buffer-file-name))
10763 ((eq major-mode 'dired-mode)
10764 ;; link to the file in the current line
10765 (setq cpltxt (concat "file:"
10766 (abbreviate-file-name
10767 (expand-file-name
10768 (dired-get-filename nil t))))
10769 link (org-make-link cpltxt)))
10771 ((and buffer-file-name (org-mode-p))
10772 ;; Just link to current headline
10773 (setq cpltxt (concat "file:"
10774 (abbreviate-file-name buffer-file-name)))
10775 ;; Add a context search string
10776 (when (org-xor org-context-in-file-links arg)
10777 ;; Check if we are on a target
10778 (if (org-in-regexp "<<\\(.*?\\)>>")
10779 (setq cpltxt (concat cpltxt "::" (match-string 1)))
10780 (setq txt (cond
10781 ((org-on-heading-p) nil)
10782 ((org-region-active-p)
10783 (buffer-substring (region-beginning) (region-end)))
10784 (t (buffer-substring (point-at-bol) (point-at-eol)))))
10785 (when (or (null txt) (string-match "\\S-" txt))
10786 (setq cpltxt
10787 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10788 desc "NONE"))))
10789 (if (string-match "::\\'" cpltxt)
10790 (setq cpltxt (substring cpltxt 0 -2)))
10791 (setq link (org-make-link cpltxt)))
10793 (buffer-file-name
10794 ;; Just link to this file here.
10795 (setq cpltxt (concat "file:"
10796 (abbreviate-file-name buffer-file-name)))
10797 ;; Add a context string
10798 (when (org-xor org-context-in-file-links arg)
10799 (setq txt (if (org-region-active-p)
10800 (buffer-substring (region-beginning) (region-end))
10801 (buffer-substring (point-at-bol) (point-at-eol))))
10802 ;; Only use search option if there is some text.
10803 (when (string-match "\\S-" txt)
10804 (setq cpltxt
10805 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10806 desc "NONE")))
10807 (setq link (org-make-link cpltxt)))
10809 ((interactive-p)
10810 (error "Cannot link to a buffer which is not visiting a file"))
10812 (t (setq link nil)))
10814 (if (consp link) (setq cpltxt (car link) link (cdr link)))
10815 (setq link (or link cpltxt)
10816 desc (or desc cpltxt))
10817 (if (equal desc "NONE") (setq desc nil))
10819 (if (and (interactive-p) link)
10820 (progn
10821 (setq org-stored-links
10822 (cons (list cpltxt link desc) org-stored-links))
10823 (message "Stored: %s" (or cpltxt link)))
10824 (org-make-link-string link desc))))
10826 (defun org-store-link-props (&rest plist)
10827 "Store link properties, extract names and addresses."
10828 (let (x adr)
10829 (when (setq x (plist-get plist :from))
10830 (setq adr (mail-extract-address-components x))
10831 (plist-put plist :fromname (car adr))
10832 (plist-put plist :fromaddress (nth 1 adr)))
10833 (when (setq x (plist-get plist :to))
10834 (setq adr (mail-extract-address-components x))
10835 (plist-put plist :toname (car adr))
10836 (plist-put plist :toaddress (nth 1 adr))))
10837 (let ((from (plist-get plist :from))
10838 (to (plist-get plist :to)))
10839 (when (and from to org-from-is-user-regexp)
10840 (plist-put plist :fromto
10841 (if (string-match org-from-is-user-regexp from)
10842 (concat "to %t")
10843 (concat "from %f")))))
10844 (setq org-store-link-plist plist))
10846 (defun org-email-link-description (&optional fmt)
10847 "Return the description part of an email link.
10848 This takes information from `org-store-link-plist' and formats it
10849 according to FMT (default from `org-email-link-description-format')."
10850 (setq fmt (or fmt org-email-link-description-format))
10851 (let* ((p org-store-link-plist)
10852 (to (plist-get p :toaddress))
10853 (from (plist-get p :fromaddress))
10854 (table
10855 (list
10856 (cons "%c" (plist-get p :fromto))
10857 (cons "%F" (plist-get p :from))
10858 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10859 (cons "%T" (plist-get p :to))
10860 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10861 (cons "%s" (plist-get p :subject))
10862 (cons "%m" (plist-get p :message-id)))))
10863 (when (string-match "%c" fmt)
10864 ;; Check if the user wrote this message
10865 (if (and org-from-is-user-regexp from to
10866 (save-match-data (string-match org-from-is-user-regexp from)))
10867 (setq fmt (replace-match "to %t" t t fmt))
10868 (setq fmt (replace-match "from %f" t t fmt))))
10869 (org-replace-escapes fmt table)))
10871 (defun org-make-org-heading-search-string (&optional string heading)
10872 "Make search string for STRING or current headline."
10873 (interactive)
10874 (let ((s (or string (org-get-heading))))
10875 (unless (and string (not heading))
10876 ;; We are using a headline, clean up garbage in there.
10877 (if (string-match org-todo-regexp s)
10878 (setq s (replace-match "" t t s)))
10879 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
10880 (setq s (replace-match "" t t s)))
10881 (setq s (org-trim s))
10882 (if (string-match (concat "^\\(" org-quote-string "\\|"
10883 org-comment-string "\\)") s)
10884 (setq s (replace-match "" t t s)))
10885 (while (string-match org-ts-regexp s)
10886 (setq s (replace-match "" t t s))))
10887 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
10888 (setq s (replace-match " " t t s)))
10889 (or string (setq s (concat "*" s))) ; Add * for headlines
10890 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10892 (defun org-make-link (&rest strings)
10893 "Concatenate STRINGS."
10894 (apply 'concat strings))
10896 (defun org-make-link-string (link &optional description)
10897 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10898 (unless (string-match "\\S-" link)
10899 (error "Empty link"))
10900 (when (stringp description)
10901 ;; Remove brackets from the description, they are fatal.
10902 (while (string-match "\\[\\|\\]" description)
10903 (setq description (replace-match "" t t description))))
10904 (when (equal (org-link-escape link) description)
10905 ;; No description needed, it is identical
10906 (setq description nil))
10907 (when (and (not description)
10908 (not (equal link (org-link-escape link))))
10909 (setq description link))
10910 (concat "[[" (org-link-escape link) "]"
10911 (if description (concat "[" description "]") "")
10912 "]"))
10914 (defconst org-link-escape-chars
10915 '((" " . "%20") ("\340" . "%E0")
10916 ("\342" . "%E2") ("\347" . "%E7")
10917 ("\350" . "%E8") ("\351" . "%E9")
10918 ("\352" . "%EA") ("\356" . "%EE")
10919 ("\364" . "%F4") ("\371" . "%F9")
10920 ("\373" . "%FB") (";" . "%3B")
10921 ("?" . "%3F") ("=" . "%3D")
10922 ("+" . "%2B"))
10923 "Association list of escapes for some characters problematic in links.")
10925 (defun org-link-escape (text)
10926 "Escape charaters in TEXT that are problematic for links."
10927 (when text
10928 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
10929 org-link-escape-chars "\\|")))
10930 (while (string-match re text)
10931 (setq text
10932 (replace-match
10933 (cdr (assoc (match-string 0 text) org-link-escape-chars))
10934 t t text)))
10935 text)))
10937 (defun org-link-unescape (text)
10938 "Reverse the action of `org-link-escape'."
10939 (when text
10940 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
10941 org-link-escape-chars "\\|")))
10942 (while (string-match re text)
10943 (setq text
10944 (replace-match
10945 (car (rassoc (match-string 0 text) org-link-escape-chars))
10946 t t text)))
10947 text)))
10949 (defun org-xor (a b)
10950 "Exclusive or."
10951 (if a (not b) b))
10953 (defun org-get-header (header)
10954 "Find a header field in the current buffer."
10955 (save-excursion
10956 (goto-char (point-min))
10957 (let ((case-fold-search t) s)
10958 (cond
10959 ((eq header 'from)
10960 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
10961 (setq s (match-string 1)))
10962 (while (string-match "\"" s)
10963 (setq s (replace-match "" t t s)))
10964 (if (string-match "[<(].*" s)
10965 (setq s (replace-match "" t t s))))
10966 ((eq header 'message-id)
10967 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
10968 (setq s (match-string 1))))
10969 ((eq header 'subject)
10970 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
10971 (setq s (match-string 1)))))
10972 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
10973 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
10974 s)))
10977 (defun org-fixup-message-id-for-http (s)
10978 "Replace special characters in a message id, so it can be used in an http query."
10979 (while (string-match "<" s)
10980 (setq s (replace-match "%3C" t t s)))
10981 (while (string-match ">" s)
10982 (setq s (replace-match "%3E" t t s)))
10983 (while (string-match "@" s)
10984 (setq s (replace-match "%40" t t s)))
10987 ;;;###autoload
10988 (defun org-insert-link-global ()
10989 "Insert a link like Org-mode does.
10990 This command can be called in any mode to insert a link in Org-mode syntax."
10991 (interactive)
10992 (org-run-like-in-org-mode 'org-insert-link))
10994 (defun org-insert-link (&optional complete-file)
10995 "Insert a link. At the prompt, enter the link.
10997 Completion can be used to select a link previously stored with
10998 `org-store-link'. When the empty string is entered (i.e. if you just
10999 press RET at the prompt), the link defaults to the most recently
11000 stored link. As SPC triggers completion in the minibuffer, you need to
11001 use M-SPC or C-q SPC to force the insertion of a space character.
11003 You will also be prompted for a description, and if one is given, it will
11004 be displayed in the buffer instead of the link.
11006 If there is already a link at point, this command will allow you to edit link
11007 and description parts.
11009 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11010 selected using completion. The path to the file will be relative to
11011 the current directory if the file is in the current directory or a
11012 subdirectory. Otherwise, the link will be the absolute path as
11013 completed in the minibuffer (i.e. normally ~/path/to/file).
11015 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11016 is in the current directory or below.
11017 With three \\[universal-argument] prefixes, negate the meaning of
11018 `org-keep-stored-link-after-insertion'."
11019 (interactive "P")
11020 (let ((wcf (current-window-configuration))
11021 (region (if (org-region-active-p)
11022 (prog1 (buffer-substring (region-beginning) (region-end))
11023 (delete-region (region-beginning) (region-end)))))
11024 tmphist ; byte-compile incorrectly complains about this
11025 link desc entry remove file)
11026 (cond
11027 ((org-in-regexp org-bracket-link-regexp 1)
11028 ;; We do have a link at point, and we are going to edit it.
11029 (setq remove (list (match-beginning 0) (match-end 0)))
11030 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11031 (setq link (read-string "Link: "
11032 (org-link-unescape
11033 (org-match-string-no-properties 1)))))
11034 ((or (org-in-regexp org-angle-link-re)
11035 (org-in-regexp org-plain-link-re))
11036 ;; Convert to bracket link
11037 (setq remove (list (match-beginning 0) (match-end 0))
11038 link (read-string "Link: "
11039 (org-remove-angle-brackets (match-string 0)))))
11040 ((equal complete-file '(4))
11041 ;; Completing read for file names.
11042 (setq file (read-file-name "File: "))
11043 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11044 (pwd1 (file-name-as-directory (abbreviate-file-name
11045 (expand-file-name ".")))))
11046 (cond
11047 ((equal complete-file '(16))
11048 (setq link (org-make-link
11049 "file:"
11050 (abbreviate-file-name (expand-file-name file)))))
11051 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11052 (setq link (org-make-link "file:" (match-string 1 file))))
11053 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11054 (expand-file-name file))
11055 (setq link (org-make-link
11056 "file:" (match-string 1 (expand-file-name file)))))
11057 (t (setq link (org-make-link "file:" file))))))
11059 ;; Read link, with completion for stored links.
11060 (with-output-to-temp-buffer "*Org Links*"
11061 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
11062 (when org-stored-links
11063 (princ "\nStored links are available with <up>/<down> (most recent with RET):\n\n")
11064 (princ (mapconcat 'car (reverse org-stored-links) "\n"))))
11065 (let ((cw (selected-window)))
11066 (select-window (get-buffer-window "*Org Links*"))
11067 (shrink-window-if-larger-than-buffer)
11068 (setq truncate-lines t)
11069 (select-window cw))
11070 ;; Fake a link history, containing the stored links.
11071 (setq tmphist (append (mapcar 'car org-stored-links)
11072 org-insert-link-history))
11073 (unwind-protect
11074 (setq link (org-completing-read
11075 "Link: "
11076 (append
11077 (mapcar (lambda (x) (list (concat (car x) ":")))
11078 (append org-link-abbrev-alist-local org-link-abbrev-alist))
11079 (mapcar (lambda (x) (list (concat x ":")))
11080 org-link-types))
11081 nil nil nil
11082 'tmphist
11083 (or (car (car org-stored-links)))))
11084 (set-window-configuration wcf)
11085 (kill-buffer "*Org Links*"))
11086 (setq entry (assoc link org-stored-links))
11087 (or entry (push link org-insert-link-history))
11088 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11089 (not org-keep-stored-link-after-insertion))
11090 (setq org-stored-links (delq (assoc link org-stored-links)
11091 org-stored-links)))
11092 (setq link (if entry (nth 1 entry) link)
11093 desc (or region desc (nth 2 entry)))))
11095 (if (string-match org-plain-link-re link)
11096 ;; URL-like link, normalize the use of angular brackets.
11097 (setq link (org-make-link (org-remove-angle-brackets link))))
11099 ;; Check if we are linking to the current file with a search option
11100 ;; If yes, simplify the link by using only the search option.
11101 (when (and buffer-file-name
11102 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11103 (let* ((path (match-string 1 link))
11104 (case-fold-search nil)
11105 (search (match-string 2 link)))
11106 (save-match-data
11107 (if (equal (file-truename buffer-file-name) (file-truename path))
11108 ;; We are linking to this same file, with a search option
11109 (setq link search)))))
11111 ;; Check if we can/should use a relative path. If yes, simplify the link
11112 (when (string-match "\\<file:\\(.*\\)" link)
11113 (let* ((path (match-string 1 link))
11114 (case-fold-search nil))
11115 (cond
11116 ((eq org-link-file-path-type 'absolute)
11117 (setq path (abbreviate-file-name (expand-file-name path))))
11118 ((eq org-link-file-path-type 'noabbrev)
11119 (setq path (expand-file-name path)))
11120 ((eq org-link-file-path-type 'relative)
11121 (setq path (file-relative-name path)))
11123 (save-match-data
11124 (if (string-match (concat "^" (regexp-quote
11125 (file-name-as-directory
11126 (expand-file-name "."))))
11127 (expand-file-name path))
11128 ;; We are linking a file with relative path name.
11129 (setq path (substring (expand-file-name path)
11130 (match-end 0)))))))
11131 (setq link (concat "file:" path))))
11133 (setq desc (read-string "Description: " desc))
11134 (unless (string-match "\\S-" desc) (setq desc nil))
11135 (if remove (apply 'delete-region remove))
11136 (insert (org-make-link-string link desc))))
11138 (defun org-completing-read (&rest args)
11139 (let ((minibuffer-local-completion-map
11140 (copy-keymap minibuffer-local-completion-map)))
11141 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
11142 (apply 'completing-read args)))
11144 ;;; Opening/following a link
11145 (defvar org-link-search-failed nil)
11147 (defun org-next-link ()
11148 "Move forward to the next link.
11149 If the link is in hidden text, expose it."
11150 (interactive)
11151 (when (and org-link-search-failed (eq this-command last-command))
11152 (goto-char (point-min))
11153 (message "Link search wrapped back to beginning of buffer"))
11154 (setq org-link-search-failed nil)
11155 (let* ((pos (point))
11156 (ct (org-context))
11157 (a (assoc :link ct)))
11158 (if a (goto-char (nth 2 a)))
11159 (if (re-search-forward org-any-link-re nil t)
11160 (progn
11161 (goto-char (match-beginning 0))
11162 (if (org-invisible-p) (org-show-context)))
11163 (goto-char pos)
11164 (setq org-link-search-failed t)
11165 (error "No further link found"))))
11167 (defun org-previous-link ()
11168 "Move backward to the previous link.
11169 If the link is in hidden text, expose it."
11170 (interactive)
11171 (when (and org-link-search-failed (eq this-command last-command))
11172 (goto-char (point-max))
11173 (message "Link search wrapped back to end of buffer"))
11174 (setq org-link-search-failed nil)
11175 (let* ((pos (point))
11176 (ct (org-context))
11177 (a (assoc :link ct)))
11178 (if a (goto-char (nth 1 a)))
11179 (if (re-search-backward org-any-link-re nil t)
11180 (progn
11181 (goto-char (match-beginning 0))
11182 (if (org-invisible-p) (org-show-context)))
11183 (goto-char pos)
11184 (setq org-link-search-failed t)
11185 (error "No further link found"))))
11187 (defun org-find-file-at-mouse (ev)
11188 "Open file link or URL at mouse."
11189 (interactive "e")
11190 (mouse-set-point ev)
11191 (org-open-at-point 'in-emacs))
11193 (defun org-open-at-mouse (ev)
11194 "Open file link or URL at mouse."
11195 (interactive "e")
11196 (mouse-set-point ev)
11197 (org-open-at-point))
11199 (defvar org-window-config-before-follow-link nil
11200 "The window configuration before following a link.
11201 This is saved in case the need arises to restore it.")
11203 (defvar org-open-link-marker (make-marker)
11204 "Marker pointing to the location where `org-open-at-point; was called.")
11206 ;;;###autoload
11207 (defun org-open-at-point-global ()
11208 "Follow a link like Org-mode does.
11209 This command can be called in any mode to follow a link that has
11210 Org-mode syntax."
11211 (interactive)
11212 (org-run-like-in-org-mode 'org-open-at-point))
11214 (defun org-open-at-point (&optional in-emacs)
11215 "Open link at or after point.
11216 If there is no link at point, this function will search forward up to
11217 the end of the current subtree.
11218 Normally, files will be opened by an appropriate application. If the
11219 optional argument IN-EMACS is non-nil, Emacs will visit the file."
11220 (interactive "P")
11221 (move-marker org-open-link-marker (point))
11222 (setq org-window-config-before-follow-link (current-window-configuration))
11223 (org-remove-occur-highlights nil nil t)
11224 (if (org-at-timestamp-p t)
11225 (org-follow-timestamp-link)
11226 (let (type path link line search (pos (point)))
11227 (catch 'match
11228 (save-excursion
11229 (skip-chars-forward "^]\n\r")
11230 (when (org-in-regexp org-bracket-link-regexp)
11231 (setq link (org-link-unescape (org-match-string-no-properties 1)))
11232 (while (string-match " *\n *" link)
11233 (setq link (replace-match " " t t link)))
11234 (setq link (org-link-expand-abbrev link))
11235 (if (string-match org-link-re-with-space2 link)
11236 (setq type (match-string 1 link) path (match-string 2 link))
11237 (setq type "thisfile" path link))
11238 (throw 'match t)))
11240 (when (get-text-property (point) 'org-linked-text)
11241 (setq type "thisfile"
11242 pos (if (get-text-property (1+ (point)) 'org-linked-text)
11243 (1+ (point)) (point))
11244 path (buffer-substring
11245 (previous-single-property-change pos 'org-linked-text)
11246 (next-single-property-change pos 'org-linked-text)))
11247 (throw 'match t))
11249 (save-excursion
11250 (when (or (org-in-regexp org-angle-link-re)
11251 (org-in-regexp org-plain-link-re))
11252 (setq type (match-string 1) path (match-string 2))
11253 (throw 'match t)))
11254 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
11255 (setq type "tree-match"
11256 path (match-string 1))
11257 (throw 'match t))
11258 (save-excursion
11259 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
11260 (setq type "tags"
11261 path (match-string 1))
11262 (while (string-match ":" path)
11263 (setq path (replace-match "+" t t path)))
11264 (throw 'match t))))
11265 (unless path
11266 (error "No link found"))
11267 ;; Remove any trailing spaces in path
11268 (if (string-match " +\\'" path)
11269 (setq path (replace-match "" t t path)))
11271 (cond
11273 ((assoc type org-link-protocols)
11274 (funcall (nth 1 (assoc type org-link-protocols)) path))
11276 ((equal type "mailto")
11277 (let ((cmd (car org-link-mailto-program))
11278 (args (cdr org-link-mailto-program)) args1
11279 (address path) (subject "") a)
11280 (if (string-match "\\(.*\\)::\\(.*\\)" path)
11281 (setq address (match-string 1 path)
11282 subject (org-link-escape (match-string 2 path))))
11283 (while args
11284 (cond
11285 ((not (stringp (car args))) (push (pop args) args1))
11286 (t (setq a (pop args))
11287 (if (string-match "%a" a)
11288 (setq a (replace-match address t t a)))
11289 (if (string-match "%s" a)
11290 (setq a (replace-match subject t t a)))
11291 (push a args1))))
11292 (apply cmd (nreverse args1))))
11294 ((member type '("http" "https" "ftp" "news"))
11295 (browse-url (concat type ":" path)))
11297 ((string= type "tags")
11298 (org-tags-view in-emacs path))
11299 ((string= type "thisfile")
11300 (if in-emacs
11301 (switch-to-buffer-other-window
11302 (org-get-buffer-for-internal-link (current-buffer)))
11303 (org-mark-ring-push))
11304 (let ((cmd `(org-link-search
11305 ,path
11306 ,(cond ((equal in-emacs '(4)) 'occur)
11307 ((equal in-emacs '(16)) 'org-occur)
11308 (t nil))
11309 ,pos)))
11310 (condition-case nil (eval cmd)
11311 (error (progn (widen) (eval cmd))))))
11313 ((string= type "tree-match")
11314 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
11316 ((string= type "file")
11317 (if (string-match "::\\([0-9]+\\)\\'" path)
11318 (setq line (string-to-number (match-string 1 path))
11319 path (substring path 0 (match-beginning 0)))
11320 (if (string-match "::\\(.+\\)\\'" path)
11321 (setq search (match-string 1 path)
11322 path (substring path 0 (match-beginning 0)))))
11323 (org-open-file path in-emacs line search))
11325 ((string= type "news")
11326 (org-follow-gnus-link path))
11328 ((string= type "bbdb")
11329 (org-follow-bbdb-link path))
11331 ((string= type "info")
11332 (org-follow-info-link path))
11334 ((string= type "gnus")
11335 (let (group article)
11336 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11337 (error "Error in Gnus link"))
11338 (setq group (match-string 1 path)
11339 article (match-string 3 path))
11340 (org-follow-gnus-link group article)))
11342 ((string= type "vm")
11343 (let (folder article)
11344 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11345 (error "Error in VM link"))
11346 (setq folder (match-string 1 path)
11347 article (match-string 3 path))
11348 ;; in-emacs is the prefix arg, will be interpreted as read-only
11349 (org-follow-vm-link folder article in-emacs)))
11351 ((string= type "wl")
11352 (let (folder article)
11353 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11354 (error "Error in Wanderlust link"))
11355 (setq folder (match-string 1 path)
11356 article (match-string 3 path))
11357 (org-follow-wl-link folder article)))
11359 ((string= type "mhe")
11360 (let (folder article)
11361 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11362 (error "Error in MHE link"))
11363 (setq folder (match-string 1 path)
11364 article (match-string 3 path))
11365 (org-follow-mhe-link folder article)))
11367 ((string= type "rmail")
11368 (let (folder article)
11369 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11370 (error "Error in RMAIL link"))
11371 (setq folder (match-string 1 path)
11372 article (match-string 3 path))
11373 (org-follow-rmail-link folder article)))
11375 ((string= type "shell")
11376 (let ((cmd path))
11377 ;; FIXME: the following is only for backward compatibility
11378 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
11379 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
11380 (if (or (not org-confirm-shell-link-function)
11381 (funcall org-confirm-shell-link-function
11382 (format "Execute \"%s\" in shell? "
11383 (org-add-props cmd nil
11384 'face 'org-warning))))
11385 (progn
11386 (message "Executing %s" cmd)
11387 (shell-command cmd))
11388 (error "Abort"))))
11390 ((string= type "elisp")
11391 (let ((cmd path))
11392 (if (or (not org-confirm-elisp-link-function)
11393 (funcall org-confirm-elisp-link-function
11394 (format "Execute \"%s\" as elisp? "
11395 (org-add-props cmd nil
11396 'face 'org-warning))))
11397 (message "%s => %s" cmd (eval (read cmd)))
11398 (error "Abort"))))
11401 (browse-url-at-point)))))
11402 (move-marker org-open-link-marker nil))
11405 ;;; File search
11407 (defvar org-create-file-search-functions nil
11408 "List of functions to construct the right search string for a file link.
11409 These functions are called in turn with point at the location to
11410 which the link should point.
11412 A function in the hook should first test if it would like to
11413 handle this file type, for example by checking the major-mode or
11414 the file extension. If it decides not to handle this file, it
11415 should just return nil to give other functions a chance. If it
11416 does handle the file, it must return the search string to be used
11417 when following the link. The search string will be part of the
11418 file link, given after a double colon, and `org-open-at-point'
11419 will automatically search for it. If special measures must be
11420 taken to make the search successful, another function should be
11421 added to the companion hook `org-execute-file-search-functions',
11422 which see.
11424 A function in this hook may also use `setq' to set the variable
11425 `description' to provide a suggestion for the descriptive text to
11426 be used for this link when it gets inserted into an Org-mode
11427 buffer with \\[org-insert-link].")
11429 (defvar org-execute-file-search-functions nil
11430 "List of functions to execute a file search triggered by a link.
11432 Functions added to this hook must accept a single argument, the
11433 search string that was part of the file link, the part after the
11434 double colon. The function must first check if it would like to
11435 handle this search, for example by checking the major-mode or the
11436 file extension. If it decides not to handle this search, it
11437 should just return nil to give other functions a chance. If it
11438 does handle the search, it must return a non-nil value to keep
11439 other functions from trying.
11441 Each function can access the current prefix argument through the
11442 variable `current-prefix-argument'. Note that a single prefix is
11443 used to force opening a link in Emacs, so it may be good to only
11444 use a numeric or double prefix to guide the search function.
11446 In case this is needed, a function in this hook can also restore
11447 the window configuration before `org-open-at-point' was called using:
11449 (set-window-configuration org-window-config-before-follow-link)")
11451 (defun org-link-search (s &optional type avoid-pos)
11452 "Search for a link search option.
11453 If S is surrounded by forward slashes, it is interpreted as a
11454 regular expression. In org-mode files, this will create an `org-occur'
11455 sparse tree. In ordinary files, `occur' will be used to list matches.
11456 If the current buffer is in `dired-mode', grep will be used to search
11457 in all files. If AVOID-POS is given, ignore matches near that position."
11458 (let ((case-fold-search t)
11459 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
11460 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
11461 (append '(("") (" ") ("\t") ("\n"))
11462 org-emphasis-alist)
11463 "\\|") "\\)"))
11464 (pos (point))
11465 (pre "") (post "")
11466 words re0 re1 re2 re3 re4 re5 re2a reall)
11467 (cond
11468 ;; First check if there are any special
11469 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11470 ;; Now try the builtin stuff
11471 ((save-excursion
11472 (goto-char (point-min))
11473 (and
11474 (re-search-forward
11475 (concat "<<" (regexp-quote s0) ">>") nil t)
11476 (setq pos (match-beginning 0))))
11477 ;; There is an exact target for this
11478 (goto-char pos))
11479 ((string-match "^/\\(.*\\)/$" s)
11480 ;; A regular expression
11481 (cond
11482 ((org-mode-p)
11483 (org-occur (match-string 1 s)))
11484 ;;((eq major-mode 'dired-mode)
11485 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
11486 (t (org-do-occur (match-string 1 s)))))
11488 ;; A normal search strings
11489 (when (equal (string-to-char s) ?*)
11490 ;; Anchor on headlines, post may include tags.
11491 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11492 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
11493 s (substring s 1)))
11494 (remove-text-properties
11495 0 (length s)
11496 '(face nil mouse-face nil keymap nil fontified nil) s)
11497 ;; Make a series of regular expressions to find a match
11498 (setq words (org-split-string s "[ \n\r\t]+")
11499 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11500 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11501 "\\)" markers)
11502 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
11503 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11504 re1 (concat pre re2 post)
11505 re3 (concat pre re4 post)
11506 re5 (concat pre ".*" re4)
11507 re2 (concat pre re2)
11508 re2a (concat pre re2a)
11509 re4 (concat pre re4)
11510 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11511 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11512 re5 "\\)"
11514 (cond
11515 ((eq type 'org-occur) (org-occur reall))
11516 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11517 (t (goto-char (point-min))
11518 (if (or (org-search-not-self 1 re0 nil t)
11519 (org-search-not-self 1 re1 nil t)
11520 (org-search-not-self 1 re2 nil t)
11521 (org-search-not-self 1 re2a nil t)
11522 (org-search-not-self 1 re3 nil t)
11523 (org-search-not-self 1 re4 nil t)
11524 (org-search-not-self 1 re5 nil t)
11526 (goto-char (match-beginning 1))
11527 (goto-char pos)
11528 (error "No match")))))
11530 ;; Normal string-search
11531 (goto-char (point-min))
11532 (if (search-forward s nil t)
11533 (goto-char (match-beginning 0))
11534 (error "No match"))))
11535 (and (org-mode-p) (org-show-context 'link-search))))
11537 (defun org-search-not-self (group &rest args)
11538 "Execute `re-search-forward', but only accept matches that do not
11539 enclose the position of `org-open-link-marker'."
11540 (let ((m org-open-link-marker))
11541 (catch 'exit
11542 (while (apply 're-search-forward args)
11543 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11544 (goto-char (match-end group))
11545 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11546 (> (match-beginning 0) (marker-position m))
11547 (< (match-end 0) (marker-position m)))
11548 (save-match-data
11549 (or (not (org-in-regexp
11550 org-bracket-link-analytic-regexp 1))
11551 (not (match-end 4)) ; no description
11552 (and (<= (match-beginning 4) (point))
11553 (>= (match-end 4) (point))))))
11554 (throw 'exit (point))))))))
11556 (defun org-get-buffer-for-internal-link (buffer)
11557 "Return a buffer to be used for displaying the link target of internal links."
11558 (cond
11559 ((not org-display-internal-link-with-indirect-buffer)
11560 buffer)
11561 ((string-match "(Clone)$" (buffer-name buffer))
11562 (message "Buffer is already a clone, not making another one")
11563 ;; we also do not modify visibility in this case
11564 buffer)
11565 (t ; make a new indirect buffer for displaying the link
11566 (let* ((bn (buffer-name buffer))
11567 (ibn (concat bn "(Clone)"))
11568 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11569 (with-current-buffer ib (org-overview))
11570 ib))))
11572 (defun org-do-occur (regexp &optional cleanup)
11573 "Call the Emacs command `occur'.
11574 If CLEANUP is non-nil, remove the printout of the regular expression
11575 in the *Occur* buffer. This is useful if the regex is long and not useful
11576 to read."
11577 (occur regexp)
11578 (when cleanup
11579 (let ((cwin (selected-window)) win beg end)
11580 (when (setq win (get-buffer-window "*Occur*"))
11581 (select-window win))
11582 (goto-char (point-min))
11583 (when (re-search-forward "match[a-z]+" nil t)
11584 (setq beg (match-end 0))
11585 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11586 (setq end (1- (match-beginning 0)))))
11587 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11588 (goto-char (point-min))
11589 (select-window cwin))))
11591 ;;; The mark ring for links jumps
11593 (defvar org-mark-ring nil
11594 "Mark ring for positions before jumps in Org-mode.")
11595 (defvar org-mark-ring-last-goto nil
11596 "Last position in the mark ring used to go back.")
11597 ;; Fill and close the ring
11598 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11599 (loop for i from 1 to org-mark-ring-length do
11600 (push (make-marker) org-mark-ring))
11601 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11602 org-mark-ring)
11604 (defun org-mark-ring-push (&optional pos buffer)
11605 "Put the current position or POS into the mark ring and rotate it."
11606 (interactive)
11607 (setq pos (or pos (point)))
11608 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11609 (move-marker (car org-mark-ring)
11610 (or pos (point))
11611 (or buffer (current-buffer)))
11612 (message
11613 (substitute-command-keys
11614 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11616 (defun org-mark-ring-goto (&optional n)
11617 "Jump to the previous position in the mark ring.
11618 With prefix arg N, jump back that many stored positions. When
11619 called several times in succession, walk through the entire ring.
11620 Org-mode commands jumping to a different position in the current file,
11621 or to another Org-mode file, automatically push the old position
11622 onto the ring."
11623 (interactive "p")
11624 (let (p m)
11625 (if (eq last-command this-command)
11626 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11627 (setq p org-mark-ring))
11628 (setq org-mark-ring-last-goto p)
11629 (setq m (car p))
11630 (switch-to-buffer (marker-buffer m))
11631 (goto-char m)
11632 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11634 (defun org-remove-angle-brackets (s)
11635 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11636 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11638 (defun org-add-angle-brackets (s)
11639 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11640 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11643 ;;; Following specific links
11645 (defun org-follow-timestamp-link ()
11646 (cond
11647 ((org-at-date-range-p t)
11648 (let ((org-agenda-start-on-weekday)
11649 (t1 (match-string 1))
11650 (t2 (match-string 2)))
11651 (setq t1 (time-to-days (org-time-string-to-time t1))
11652 t2 (time-to-days (org-time-string-to-time t2)))
11653 (org-agenda-list nil t1 (1+ (- t2 t1)))))
11654 ((org-at-timestamp-p t)
11655 (org-agenda-list nil (time-to-days (org-time-string-to-time
11656 (substring (match-string 1) 0 10)))
11658 (t (error "This should not happen"))))
11661 (defun org-follow-bbdb-link (name)
11662 "Follow a BBDB link to NAME."
11663 (require 'bbdb)
11664 (let ((inhibit-redisplay (not debug-on-error))
11665 (bbdb-electric-p nil))
11666 (catch 'exit
11667 ;; Exact match on name
11668 (bbdb-name (concat "\\`" name "\\'") nil)
11669 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11670 ;; Exact match on name
11671 (bbdb-company (concat "\\`" name "\\'") nil)
11672 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11673 ;; Partial match on name
11674 (bbdb-name name nil)
11675 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11676 ;; Partial match on company
11677 (bbdb-company name nil)
11678 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11679 ;; General match including network address and notes
11680 (bbdb name nil)
11681 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
11682 (delete-window (get-buffer-window "*BBDB*"))
11683 (error "No matching BBDB record")))))
11685 (defun org-follow-info-link (name)
11686 "Follow an info file & node link to NAME."
11687 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
11688 (string-match "\\(.*\\)" name))
11689 (progn
11690 (require 'info)
11691 (if (match-string 2 name) ; If there isn't a node, choose "Top"
11692 (Info-find-node (match-string 1 name) (match-string 2 name))
11693 (Info-find-node (match-string 1 name) "Top")))
11694 (message (concat "Could not open: " name))))
11696 (defun org-follow-gnus-link (&optional group article)
11697 "Follow a Gnus link to GROUP and ARTICLE."
11698 (require 'gnus)
11699 (funcall (cdr (assq 'gnus org-link-frame-setup)))
11700 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
11701 (cond ((and group article)
11702 (gnus-group-read-group 1 nil group)
11703 (gnus-summary-goto-article (string-to-number article) nil t))
11704 (group (gnus-group-jump-to-group group))))
11706 (defun org-follow-vm-link (&optional folder article readonly)
11707 "Follow a VM link to FOLDER and ARTICLE."
11708 (require 'vm)
11709 (setq article (org-add-angle-brackets article))
11710 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
11711 ;; ange-ftp or efs or tramp access
11712 (let ((user (or (match-string 1 folder) (user-login-name)))
11713 (host (match-string 2 folder))
11714 (file (match-string 3 folder)))
11715 (cond
11716 ((featurep 'tramp)
11717 ;; use tramp to access the file
11718 (if (featurep 'xemacs)
11719 (setq folder (format "[%s@%s]%s" user host file))
11720 (setq folder (format "/%s@%s:%s" user host file))))
11722 ;; use ange-ftp or efs
11723 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
11724 (setq folder (format "/%s@%s:%s" user host file))))))
11725 (when folder
11726 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
11727 (sit-for 0.1)
11728 (when article
11729 (vm-select-folder-buffer)
11730 (widen)
11731 (let ((case-fold-search t))
11732 (goto-char (point-min))
11733 (if (not (re-search-forward
11734 (concat "^" "message-id: *" (regexp-quote article))))
11735 (error "Could not find the specified message in this folder"))
11736 (vm-isearch-update)
11737 (vm-isearch-narrow)
11738 (vm-beginning-of-message)
11739 (vm-summarize)))))
11741 (defun org-follow-wl-link (folder article)
11742 "Follow a Wanderlust link to FOLDER and ARTICLE."
11743 (if (and (string= folder "%")
11744 article
11745 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
11746 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
11747 ;; Thus, we recompose folder and article ids.
11748 (setq folder (format "%s#%s" folder (match-string 1 article))
11749 article (match-string 3 article)))
11750 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
11751 (error "No such folder: %s" folder))
11752 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
11753 (and article
11754 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
11755 (wl-summary-redisplay)))
11757 (defun org-follow-rmail-link (folder article)
11758 "Follow an RMAIL link to FOLDER and ARTICLE."
11759 (setq article (org-add-angle-brackets article))
11760 (let (message-number)
11761 (save-excursion
11762 (save-window-excursion
11763 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
11764 (setq message-number
11765 (save-restriction
11766 (widen)
11767 (goto-char (point-max))
11768 (if (re-search-backward
11769 (concat "^Message-ID:\\s-+" (regexp-quote
11770 (or article "")))
11771 nil t)
11772 (rmail-what-message))))))
11773 (if message-number
11774 (progn
11775 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
11776 (rmail-show-message message-number)
11777 message-number)
11778 (error "Message not found"))))
11780 ;;; mh-e integration based on planner-mode
11781 (defun org-mhe-get-message-real-folder ()
11782 "Return the name of the current message real folder, so if you use
11783 sequences, it will now work."
11784 (save-excursion
11785 (let* ((folder
11786 (if (equal major-mode 'mh-folder-mode)
11787 mh-current-folder
11788 ;; Refer to the show buffer
11789 mh-show-folder-buffer))
11790 (end-index
11791 (if (boundp 'mh-index-folder)
11792 (min (length mh-index-folder) (length folder))))
11794 ;; a simple test on mh-index-data does not work, because
11795 ;; mh-index-data is always nil in a show buffer.
11796 (if (and (boundp 'mh-index-folder)
11797 (string= mh-index-folder (substring folder 0 end-index)))
11798 (if (equal major-mode 'mh-show-mode)
11799 (save-window-excursion
11800 (when (buffer-live-p (get-buffer folder))
11801 (progn
11802 (pop-to-buffer folder)
11803 (org-mhe-get-message-folder-from-index)
11806 (org-mhe-get-message-folder-from-index)
11808 folder
11812 (defun org-mhe-get-message-folder-from-index ()
11813 "Returns the name of the message folder in a index folder buffer."
11814 (save-excursion
11815 (mh-index-previous-folder)
11816 (re-search-forward "^\\(+.*\\)$" nil t)
11817 (message (match-string 1))))
11819 (defun org-mhe-get-message-folder ()
11820 "Return the name of the current message folder. Be careful if you
11821 use sequences."
11822 (save-excursion
11823 (if (equal major-mode 'mh-folder-mode)
11824 mh-current-folder
11825 ;; Refer to the show buffer
11826 mh-show-folder-buffer)))
11828 (defun org-mhe-get-message-num ()
11829 "Return the number of the current message. Be careful if you
11830 use sequences."
11831 (save-excursion
11832 (if (equal major-mode 'mh-folder-mode)
11833 (mh-get-msg-num nil)
11834 ;; Refer to the show buffer
11835 (mh-show-buffer-message-number))))
11837 (defun org-mhe-get-header (header)
11838 "Return a header of the message in folder mode. This will create a
11839 show buffer for the corresponding message. If you have a more clever
11840 idea..."
11841 (let* ((folder (org-mhe-get-message-folder))
11842 (num (org-mhe-get-message-num))
11843 (buffer (get-buffer-create (concat "show-" folder)))
11844 (header-field))
11845 (with-current-buffer buffer
11846 (mh-display-msg num folder)
11847 (if (equal major-mode 'mh-folder-mode)
11848 (mh-header-display)
11849 (mh-show-header-display))
11850 (set-buffer buffer)
11851 (setq header-field (mh-get-header-field header))
11852 (if (equal major-mode 'mh-folder-mode)
11853 (mh-show)
11854 (mh-show-show))
11855 header-field)))
11857 (defun org-follow-mhe-link (folder article)
11858 "Follow an MHE link to FOLDER and ARTICLE.
11859 If ARTICLE is nil FOLDER is shown. If the configuration variable
11860 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
11861 ARTICLE is searched in all folders. Indexed searches (swish++,
11862 namazu, and others supported by MH-E) will always search in all
11863 folders."
11864 (require 'mh-e)
11865 (require 'mh-search)
11866 (require 'mh-utils)
11867 (mh-find-path)
11868 (if (not article)
11869 (mh-visit-folder (mh-normalize-folder-name folder))
11870 (setq article (org-add-angle-brackets article))
11871 (mh-search-choose)
11872 (if (equal mh-searcher 'pick)
11873 (progn
11874 (mh-search folder (list "--message-id" article))
11875 (when (and org-mhe-search-all-folders
11876 (not (org-mhe-get-message-real-folder)))
11877 (kill-this-buffer)
11878 (mh-search "+" (list "--message-id" article))))
11879 (mh-search "+" article))
11880 (if (org-mhe-get-message-real-folder)
11881 (mh-show-msg 1)
11882 (kill-this-buffer)
11883 (error "Message not found"))))
11885 ;;; BibTeX links
11887 ;; Use the custom search meachnism to construct and use search strings for
11888 ;; file links to BibTeX database entries.
11890 (defun org-create-file-search-in-bibtex ()
11891 "Create the search string and description for a BibTeX database entry."
11892 (when (eq major-mode 'bibtex-mode)
11893 ;; yes, we want to construct this search string.
11894 ;; Make a good description for this entry, using names, year and the title
11895 ;; Put it into the `description' variable which is dynamically scoped.
11896 (let ((bibtex-autokey-names 1)
11897 (bibtex-autokey-names-stretch 1)
11898 (bibtex-autokey-name-case-convert-function 'identity)
11899 (bibtex-autokey-name-separator " & ")
11900 (bibtex-autokey-additional-names " et al.")
11901 (bibtex-autokey-year-length 4)
11902 (bibtex-autokey-name-year-separator " ")
11903 (bibtex-autokey-titlewords 3)
11904 (bibtex-autokey-titleword-separator " ")
11905 (bibtex-autokey-titleword-case-convert-function 'identity)
11906 (bibtex-autokey-titleword-length 'infty)
11907 (bibtex-autokey-year-title-separator ": "))
11908 (setq description (bibtex-generate-autokey)))
11909 ;; Now parse the entry, get the key and return it.
11910 (save-excursion
11911 (bibtex-beginning-of-entry)
11912 (cdr (assoc "=key=" (bibtex-parse-entry))))))
11914 (defun org-execute-file-search-in-bibtex (s)
11915 "Find the link search string S as a key for a database entry."
11916 (when (eq major-mode 'bibtex-mode)
11917 ;; Yes, we want to do the search in this file.
11918 ;; We construct a regexp that searches for "@entrytype{" followed by the key
11919 (goto-char (point-min))
11920 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
11921 (regexp-quote s) "[ \t\n]*,") nil t)
11922 (goto-char (match-beginning 0)))
11923 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
11924 ;; Use double prefix to indicate that any web link should be browsed
11925 (let ((b (current-buffer)) (p (point)))
11926 ;; Restore the window configuration because we just use the web link
11927 (set-window-configuration org-window-config-before-follow-link)
11928 (save-excursion (set-buffer b) (goto-char p)
11929 (bibtex-url)))
11930 (recenter 0)) ; Move entry start to beginning of window
11931 ;; return t to indicate that the search is done.
11934 ;; Finally add the functions to the right hooks.
11935 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
11936 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
11938 ;; end of Bibtex link setup
11940 ;;; Following file links
11942 (defun org-open-file (path &optional in-emacs line search)
11943 "Open the file at PATH.
11944 First, this expands any special file name abbreviations. Then the
11945 configuration variable `org-file-apps' is checked if it contains an
11946 entry for this file type, and if yes, the corresponding command is launched.
11947 If no application is found, Emacs simply visits the file.
11948 With optional argument IN-EMACS, Emacs will visit the file.
11949 Optional LINE specifies a line to go to, optional SEARCH a string to
11950 search for. If LINE or SEARCH is given, the file will always be
11951 opened in Emacs.
11952 If the file does not exist, an error is thrown."
11953 (setq in-emacs (or in-emacs line search))
11954 (let* ((file (if (equal path "")
11955 buffer-file-name
11956 (substitute-in-file-name (expand-file-name path))))
11957 (apps (append org-file-apps (org-default-apps)))
11958 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11959 (dirp (if remp nil (file-directory-p file)))
11960 (dfile (downcase file))
11961 (old-buffer (current-buffer))
11962 (old-pos (point))
11963 (old-mode major-mode)
11964 ext cmd)
11965 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11966 (setq ext (match-string 1 dfile))
11967 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11968 (setq ext (match-string 1 dfile))))
11969 (if in-emacs
11970 (setq cmd 'emacs)
11971 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11972 (and dirp (cdr (assoc 'directory apps)))
11973 (cdr (assoc ext apps))
11974 (cdr (assoc t apps)))))
11975 (when (eq cmd 'mailcap)
11976 (require 'mailcap)
11977 (mailcap-parse-mailcaps)
11978 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11979 (command (mailcap-mime-info mime-type)))
11980 (if (stringp command)
11981 (setq cmd command)
11982 (setq cmd 'emacs))))
11983 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11984 (not (file-exists-p file))
11985 (not org-open-non-existing-files))
11986 (error "No such file: %s" file))
11987 (cond
11988 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11989 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11990 (if (string-match "['\"]%s['\"]" cmd)
11991 (setq cmd (replace-match "%s" t t cmd)))
11992 (setq cmd (format cmd (shell-quote-argument file)))
11993 (save-window-excursion
11994 (shell-command (concat cmd " &"))))
11995 ((or (stringp cmd)
11996 (eq cmd 'emacs))
11997 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11998 (widen)
11999 (if line (goto-line line)
12000 (if search (org-link-search search))))
12001 ((consp cmd)
12002 (eval cmd))
12003 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
12004 (and (org-mode-p) (eq old-mode 'org-mode)
12005 (or (not (equal old-buffer (current-buffer)))
12006 (not (equal old-pos (point))))
12007 (org-mark-ring-push old-pos old-buffer))))
12009 (defun org-default-apps ()
12010 "Return the default applications for this operating system."
12011 (cond
12012 ((eq system-type 'darwin)
12013 org-file-apps-defaults-macosx)
12014 ((eq system-type 'windows-nt)
12015 org-file-apps-defaults-windowsnt)
12016 (t org-file-apps-defaults-gnu)))
12018 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
12019 (defun org-file-remote-p (file)
12020 "Test whether FILE specifies a location on a remote system.
12021 Return non-nil if the location is indeed remote.
12023 For example, the filename \"/user@host:/foo\" specifies a location
12024 on the system \"/user@host:\"."
12025 (cond ((fboundp 'file-remote-p)
12026 (file-remote-p file))
12027 ((fboundp 'tramp-handle-file-remote-p)
12028 (tramp-handle-file-remote-p file))
12029 ((and (boundp 'ange-ftp-name-format)
12030 (string-match (car ange-ftp-name-format) file))
12032 (t nil)))
12035 ;;;; Hooks for remember.el
12037 ;;;###autoload
12038 (defun org-remember-annotation ()
12039 "Return a link to the current location as an annotation for remember.el.
12040 If you are using Org-mode files as target for data storage with
12041 remember.el, then the annotations should include a link compatible with the
12042 conventions in Org-mode. This function returns such a link."
12043 (org-store-link nil))
12045 (defconst org-remember-help
12046 "Select a destination location for the note.
12047 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
12048 RET at beg-of-buf -> Append to file as level 2 headline
12049 RET on headline -> Store as sublevel entry to current headline
12050 <left>/<right> -> before/after current headline, same headings level")
12052 ;;;###autoload
12053 (defun org-remember-apply-template (&optional use-char skip-interactive)
12054 "Initialize *remember* buffer with template, invoke `org-mode'.
12055 This function should be placed into `remember-mode-hook' and in fact requires
12056 to be run from that hook to fucntion properly."
12057 (if org-remember-templates
12059 (let* ((char (or use-char
12060 (if (= (length org-remember-templates) 1)
12061 (caar org-remember-templates)
12062 (message "Select template: %s"
12063 (mapconcat
12064 (lambda (x) (char-to-string (car x)))
12065 org-remember-templates " "))
12066 (read-char-exclusive))))
12067 (entry (cdr (assoc char org-remember-templates)))
12068 (tpl (car entry))
12069 (plist-p (if org-store-link-plist t nil))
12070 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
12071 (string-match "\\S-" (nth 1 entry)))
12072 (nth 1 entry)
12073 org-default-notes-file))
12074 (headline (nth 2 entry))
12075 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
12076 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
12077 (v-u (concat "[" (substring v-t 1 -1) "]"))
12078 (v-U (concat "[" (substring v-T 1 -1) "]"))
12079 (v-i initial) ; defined in `remember-mode'
12080 (v-a (if (equal annotation "[[]]") "" annotation)) ; likewise
12081 (v-n user-full-name)
12082 (org-startup-folded nil)
12083 org-time-was-given org-end-time-was-given x prompt char time)
12084 (setq org-store-link-plist
12085 (append (list :annotation v-a :initial v-i)
12086 org-store-link-plist))
12087 (unless tpl (setq tpl "") (message "No template") (ding))
12088 (erase-buffer)
12089 (insert (substitute-command-keys
12090 (format
12091 "## `C-c C-c' to file interactively, `C-u C-c C-c' to file directly.
12092 ## Target file \"%s\", headline \"%s\"
12093 ## To switch templates, use `\\[org-remember]'.\n\n"
12094 (abbreviate-file-name (or file org-default-notes-file))
12095 (or headline ""))))
12096 (insert tpl) (goto-char (point-min))
12097 ;; Simple %-escapes
12098 (while (re-search-forward "%\\([tTuUai]\\)" nil t)
12099 (when (and initial (equal (match-string 0) "%i"))
12100 (save-match-data
12101 (let* ((lead (buffer-substring
12102 (point-at-bol) (match-beginning 0))))
12103 (setq v-i (mapconcat 'identity
12104 (org-split-string initial "\n")
12105 (concat "\n" lead))))))
12106 (replace-match
12107 (or (eval (intern (concat "v-" (match-string 1)))) "")
12108 t t))
12109 ;; From the property list
12110 (when plist-p
12111 (goto-char (point-min))
12112 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
12113 (and (setq x (plist-get org-store-link-plist
12114 (intern (match-string 1))))
12115 (replace-match x t t))))
12116 ;; Turn on org-mode in the remember buffer, set local variables
12117 (org-mode)
12118 (org-set-local 'org-finish-function 'remember-buffer)
12119 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
12120 (org-set-local 'org-default-notes-file file))
12121 (if (and headline (stringp headline) (string-match "\\S-" headline))
12122 (org-set-local 'org-remember-default-headline headline))
12123 ;; Interactive template entries
12124 (goto-char (point-min))
12125 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
12126 (setq char (if (match-end 3) (match-string 3))
12127 prompt (if (match-end 2) (match-string 2)))
12128 (goto-char (match-beginning 0))
12129 (replace-match "")
12130 (cond
12131 ((member char '("G" "g"))
12132 (let* ((org-last-tags-completion-table
12133 (org-global-tags-completion-table
12134 (if (equal char "G") (org-agenda-files) (and file (list file)))))
12135 (org-add-colon-after-tag-completion t)
12136 (ins (completing-read
12137 (if prompt (concat prompt ": ") "Tags: ")
12138 'org-tags-completion-function nil nil nil
12139 'org-tags-history)))
12140 (setq ins (mapconcat 'identity
12141 (org-split-string ins (org-re "[^[:alnum:]]+"))
12142 ":"))
12143 (when (string-match "\\S-" ins)
12144 (or (equal (char-before) ?:) (insert ":"))
12145 (insert ins)
12146 (or (equal (char-after) ?:) (insert ":")))))
12147 (char
12148 (setq org-time-was-given (equal (upcase char) char))
12149 (setq time (org-read-date (equal (upcase char) "U") t nil
12150 prompt))
12151 (org-insert-time-stamp time org-time-was-given
12152 (member char '("u" "U"))
12153 nil nil (list org-end-time-was-given)))
12155 (insert (read-string
12156 (if prompt (concat prompt ": ") "Enter string"))))))
12157 (goto-char (point-min))
12158 (if (re-search-forward "%\\?" nil t)
12159 (replace-match "")
12160 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
12161 (org-mode)
12162 (org-set-local 'org-finish-function 'remember-buffer)))
12164 ;;;###autoload
12165 (defun org-remember ()
12166 "Call `remember'. If this is already a remember buffer, re-apply template.
12167 If there is an active region, make sure remember uses it as initial content
12168 of the remember buffer."
12169 (interactive)
12170 (if (eq org-finish-function 'remember-buffer)
12171 (progn
12172 (when (< (length org-remember-templates) 2)
12173 (error "No other template available"))
12174 (erase-buffer)
12175 (let ((annotation (plist-get org-store-link-plist :annotation))
12176 (initial (plist-get org-store-link-plist :initial)))
12177 (org-remember-apply-template))
12178 (message "Press C-c C-c to remember data"))
12179 (if (org-region-active-p)
12180 (remember (buffer-substring (point) (mark)))
12181 (call-interactively 'remember))))
12183 ;;;###autoload
12184 (defun org-remember-handler ()
12185 "Store stuff from remember.el into an org file.
12186 First prompts for an org file. If the user just presses return, the value
12187 of `org-default-notes-file' is used.
12188 Then the command offers the headings tree of the selected file in order to
12189 file the text at a specific location.
12190 You can either immediately press RET to get the note appended to the
12191 file, or you can use vertical cursor motion and visibility cycling (TAB) to
12192 find a better place. Then press RET or <left> or <right> in insert the note.
12194 Key Cursor position Note gets inserted
12195 -----------------------------------------------------------------------------
12196 RET buffer-start as level 2 heading at end of file
12197 RET on headline as sublevel of the heading at cursor
12198 RET no heading at cursor position, level taken from context.
12199 Or use prefix arg to specify level manually.
12200 <left> on headline as same level, before current heading
12201 <right> on headline as same level, after current heading
12203 So the fastest way to store the note is to press RET RET to append it to
12204 the default file. This way your current train of thought is not
12205 interrupted, in accordance with the principles of remember.el.
12206 You can also get the fast execution without prompting by using
12207 C-u C-c C-c to exit the remember buffer. See also the variable
12208 `org-remember-store-without-prompt'.
12210 Before being stored away, the function ensures that the text has a
12211 headline, i.e. a first line that starts with a \"*\". If not, a headline
12212 is constructed from the current date and some additional data.
12214 If the variable `org-adapt-indentation' is non-nil, the entire text is
12215 also indented so that it starts in the same column as the headline
12216 \(i.e. after the stars).
12218 See also the variable `org-reverse-note-order'."
12219 (goto-char (point-min))
12220 (while (looking-at "^[ \t]*\n\\|^##.*\n")
12221 (replace-match ""))
12222 (catch 'quit
12223 (let* ((txt (buffer-substring (point-min) (point-max)))
12224 (fastp (org-xor (equal current-prefix-arg '(4))
12225 org-remember-store-without-prompt))
12226 (file (if fastp org-default-notes-file (org-get-org-file)))
12227 (heading org-remember-default-headline)
12228 (visiting (org-find-base-buffer-visiting file))
12229 (org-startup-folded nil)
12230 (org-startup-align-all-tables nil)
12231 (org-goto-start-pos 1)
12232 spos level indent reversed)
12233 (setq current-prefix-arg nil)
12234 ;; Modify text so that it becomes a nice subtree which can be inserted
12235 ;; into an org tree.
12236 (let* ((lines (split-string txt "\n"))
12237 first)
12238 (setq first (car lines) lines (cdr lines))
12239 (if (string-match "^\\*+ " first)
12240 ;; Is already a headline
12241 (setq indent nil)
12242 ;; We need to add a headline: Use time and first buffer line
12243 (setq lines (cons first lines)
12244 first (concat "* " (current-time-string)
12245 " (" (remember-buffer-desc) ")")
12246 indent " "))
12247 (if (and org-adapt-indentation indent)
12248 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
12249 (setq txt (concat first "\n"
12250 (mapconcat 'identity lines "\n"))))
12251 ;; Find the file
12252 (if (not visiting) (find-file-noselect file))
12253 (with-current-buffer (or visiting (get-file-buffer file))
12254 (save-excursion
12255 (save-restriction
12256 (widen)
12257 (and (goto-char (point-min))
12258 (not (re-search-forward "^\\* " nil t))
12259 (insert "\n* Notes\n"))
12260 (setq reversed (org-notes-order-reversed-p))
12262 ;; Find the default location
12263 (when (and heading (stringp heading) (string-match "\\S-" heading))
12264 (goto-char (point-min))
12265 (if (re-search-forward
12266 (concat "^\\*+[ \t]+" (regexp-quote heading)
12267 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
12268 nil t)
12269 (setq org-goto-start-pos (match-beginning 0))))
12271 ;; Ask the User for a location
12272 (setq spos (if fastp
12273 org-goto-start-pos
12274 (org-get-location (current-buffer) org-remember-help)))
12275 (if (not spos) (throw 'quit nil)) ; return nil to show we did
12276 ; not handle this note
12277 (goto-char spos)
12278 (cond ((and (bobp) (not reversed))
12279 ;; Put it at the end, one level below level 1
12280 (save-restriction
12281 (widen)
12282 (goto-char (point-max))
12283 (if (not (bolp)) (newline))
12284 (org-paste-subtree (org-get-legal-level 1 1) txt)))
12285 ((and (bobp) reversed)
12286 ;; Put it at the start, as level 1
12287 (save-restriction
12288 (widen)
12289 (goto-char (point-min))
12290 (re-search-forward "^\\*+ " nil t)
12291 (beginning-of-line 1)
12292 (org-paste-subtree 1 txt)))
12293 ((and (org-on-heading-p t) (not current-prefix-arg))
12294 ;; Put it below this entry, at the beg/end of the subtree
12295 (org-back-to-heading t)
12296 (setq level (funcall outline-level))
12297 (if reversed
12298 (outline-next-heading)
12299 (org-end-of-subtree t))
12300 (if (not (bolp)) (newline))
12301 (beginning-of-line 1)
12302 (org-paste-subtree (org-get-legal-level level 1) txt))
12304 ;; Put it right there, with automatic level determined by
12305 ;; org-paste-subtree or from prefix arg
12306 (org-paste-subtree
12307 (if (numberp current-prefix-arg) current-prefix-arg)
12308 txt)))
12309 (when remember-save-after-remembering
12310 (save-buffer)
12311 (if (not visiting) (kill-buffer (current-buffer)))))))))
12312 t) ;; return t to indicate that we took care of this note.
12314 (defun org-get-org-file ()
12315 "Read a filename, with default directory `org-directory'."
12316 (let ((default (or org-default-notes-file remember-data-file)))
12317 (read-file-name (format "File name [%s]: " default)
12318 (file-name-as-directory org-directory)
12319 default)))
12321 (defun org-notes-order-reversed-p ()
12322 "Check if the current file should receive notes in reversed order."
12323 (cond
12324 ((not org-reverse-note-order) nil)
12325 ((eq t org-reverse-note-order) t)
12326 ((not (listp org-reverse-note-order)) nil)
12327 (t (catch 'exit
12328 (let ((all org-reverse-note-order)
12329 entry)
12330 (while (setq entry (pop all))
12331 (if (string-match (car entry) buffer-file-name)
12332 (throw 'exit (cdr entry))))
12333 nil)))))
12335 ;;;; Dynamic blocks
12337 (defun org-find-dblock (name)
12338 "Find the first dynamic block with name NAME in the buffer.
12339 If not found, stay at current position and return nil."
12340 (let (pos)
12341 (save-excursion
12342 (goto-char (point-min))
12343 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
12344 nil t)
12345 (match-beginning 0))))
12346 (if pos (goto-char pos))
12347 pos))
12349 (defconst org-dblock-start-re
12350 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
12351 "Matches the startline of a dynamic block, with parameters.")
12353 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
12354 "Matches the end of a dyhamic block.")
12356 (defun org-create-dblock (plist)
12357 "Create a dynamic block section, with parameters taken from PLIST.
12358 PLIST must containe a :name entry which is used as name of the block."
12359 (unless (bolp) (newline))
12360 (let ((name (plist-get plist :name)))
12361 (insert "#+BEGIN: " name)
12362 (while plist
12363 (if (eq (car plist) :name)
12364 (setq plist (cddr plist))
12365 (insert " " (prin1-to-string (pop plist)))))
12366 (insert "\n\n#+END:\n")
12367 (beginning-of-line -2)))
12369 (defun org-prepare-dblock ()
12370 "Prepare dynamic block for refresh.
12371 This empties the block, puts the cursor at the insert position and returns
12372 the property list including an extra property :name with the block name."
12373 (unless (looking-at org-dblock-start-re)
12374 (error "Not at a dynamic block"))
12375 (let* ((begdel (1+ (match-end 0)))
12376 (name (match-string 1))
12377 (params (append (list :name name)
12378 (read (concat "(" (match-string 3) ")")))))
12379 (unless (re-search-forward org-dblock-end-re nil t)
12380 (error "Dynamic block not terminated"))
12381 (delete-region begdel (match-beginning 0))
12382 (goto-char begdel)
12383 (open-line 1)
12384 params))
12386 (defun org-map-dblocks (&optional command)
12387 "Apply COMMAND to all dynamic blocks in the current buffer.
12388 If COMMAND is not given, use `org-update-dblock'."
12389 (let ((cmd (or command 'org-update-dblock))
12390 pos)
12391 (save-excursion
12392 (goto-char (point-min))
12393 (while (re-search-forward org-dblock-start-re nil t)
12394 (goto-char (setq pos (match-beginning 0)))
12395 (condition-case nil
12396 (funcall cmd)
12397 (error (message "Error during update of dynamic block")))
12398 (goto-char pos)
12399 (unless (re-search-forward org-dblock-end-re nil t)
12400 (error "Dynamic block not terminated"))))))
12402 (defun org-dblock-update (&optional arg)
12403 "User command for updating dynamic blocks.
12404 Update the dynamic block at point. With prefix ARG, update all dynamic
12405 blocks in the buffer."
12406 (interactive "P")
12407 (if arg
12408 (org-update-all-dblocks)
12409 (or (looking-at org-dblock-start-re)
12410 (org-beginning-of-dblock))
12411 (org-update-dblock)))
12413 (defun org-update-dblock ()
12414 "Update the dynamic block at point
12415 This means to empty the block, parse for parameters and then call
12416 the correct writing function."
12417 (let* ((pos (point))
12418 (params (org-prepare-dblock))
12419 (name (plist-get params :name))
12420 (cmd (intern (concat "org-dblock-write:" name))))
12421 (funcall cmd params)
12422 (goto-char pos)))
12424 (defun org-beginning-of-dblock ()
12425 "Find the beginning of the dynamic block at point.
12426 Error if there is no scuh block at point."
12427 (let ((pos (point))
12428 beg)
12429 (end-of-line 1)
12430 (if (and (re-search-backward org-dblock-start-re nil t)
12431 (setq beg (match-beginning 0))
12432 (re-search-forward org-dblock-end-re nil t)
12433 (> (match-end 0) pos))
12434 (goto-char beg)
12435 (goto-char pos)
12436 (error "Not in a dynamic block"))))
12438 (defun org-update-all-dblocks ()
12439 "Update all dynamic blocks in the buffer.
12440 This function can be used in a hook."
12441 (when (org-mode-p)
12442 (org-map-dblocks 'org-update-dblock)))
12445 ;;;; Completion
12447 (defun org-complete (&optional arg)
12448 "Perform completion on word at point.
12449 At the beginning of a headline, this completes TODO keywords as given in
12450 `org-todo-keywords'.
12451 If the current word is preceded by a backslash, completes the TeX symbols
12452 that are supported for HTML support.
12453 If the current word is preceded by \"#+\", completes special words for
12454 setting file options.
12455 In the line after \"#+STARTUP:, complete valid keywords.\"
12456 At all other locations, this simply calls `ispell-complete-word'."
12457 (interactive "P")
12458 (catch 'exit
12459 (let* ((end (point))
12460 (beg1 (save-excursion
12461 (skip-chars-backward (org-re "[:alnum:]_@"))
12462 (point)))
12463 (beg (save-excursion
12464 (skip-chars-backward "a-zA-Z0-9_:$")
12465 (point)))
12466 (confirm (lambda (x) (stringp (car x))))
12467 (searchhead (equal (char-before beg) ?*))
12468 (tag (and (equal (char-before beg1) ?:)
12469 (equal (char-after (point-at-bol)) ?*)))
12470 (prop (and (equal (char-before beg1) ?:)
12471 (not (equal (char-after (point-at-bol)) ?*))))
12472 (texp (equal (char-before beg) ?\\))
12473 (link (equal (char-before beg) ?\[))
12474 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
12475 beg)
12476 "#+"))
12477 (startup (string-match "^#\\+STARTUP:.*"
12478 (buffer-substring (point-at-bol) (point))))
12479 (completion-ignore-case opt)
12480 (type nil)
12481 (tbl nil)
12482 (table (cond
12483 (opt
12484 (setq type :opt)
12485 (mapcar (lambda (x)
12486 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
12487 (cons (match-string 2 x) (match-string 1 x)))
12488 (org-split-string (org-get-current-options) "\n")))
12489 (startup
12490 (setq type :startup)
12491 org-startup-options)
12492 (link (append org-link-abbrev-alist-local
12493 org-link-abbrev-alist))
12494 (texp
12495 (setq type :tex)
12496 org-html-entities)
12497 ((string-match "\\`\\*+[ \t]+\\'"
12498 (buffer-substring (point-at-bol) beg))
12499 (setq type :todo)
12500 (mapcar 'list org-todo-keywords-1))
12501 (searchhead
12502 (setq type :searchhead)
12503 (save-excursion
12504 (goto-char (point-min))
12505 (while (re-search-forward org-todo-line-regexp nil t)
12506 (push (list
12507 (org-make-org-heading-search-string
12508 (match-string 3) t))
12509 tbl)))
12510 tbl)
12511 (tag (setq type :tag beg beg1)
12512 (or org-tag-alist (org-get-buffer-tags)))
12513 (prop (setq type :prop beg beg1)
12514 (mapcar 'list (org-buffer-property-keys)))
12515 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
12516 (pattern (buffer-substring-no-properties beg end))
12517 (completion (try-completion pattern table confirm)))
12518 (cond ((eq completion t)
12519 (if (equal type :opt)
12520 (insert (substring (cdr (assoc (upcase pattern) table))
12521 (length pattern)))
12522 (if (memq type '(:tag :prop)) (insert ":"))))
12523 ((null completion)
12524 (message "Can't find completion for \"%s\"" pattern)
12525 (ding))
12526 ((not (string= pattern completion))
12527 (delete-region beg end)
12528 (if (string-match " +$" completion)
12529 (setq completion (replace-match "" t t completion)))
12530 (insert completion)
12531 (if (get-buffer-window "*Completions*")
12532 (delete-window (get-buffer-window "*Completions*")))
12533 (if (assoc completion table)
12534 (if (eq type :todo) (insert " ")
12535 (if (memq type '(:tag :prop)) (insert ":"))))
12536 (if (and (equal type :opt) (assoc completion table))
12537 (message "%s" (substitute-command-keys
12538 "Press \\[org-complete] again to insert example settings"))))
12540 (message "Making completion list...")
12541 (let ((list (sort (all-completions pattern table confirm)
12542 'string<)))
12543 (with-output-to-temp-buffer "*Completions*"
12544 (condition-case nil
12545 ;; Protection needed for XEmacs and emacs 21
12546 (display-completion-list list pattern)
12547 (error (display-completion-list list)))))
12548 (message "Making completion list...%s" "done"))))))
12550 ;;;; TODO, DEADLINE, Comments
12552 (defun org-toggle-comment ()
12553 "Change the COMMENT state of an entry."
12554 (interactive)
12555 (save-excursion
12556 (org-back-to-heading)
12557 (if (looking-at (concat outline-regexp
12558 "\\( *\\<" org-comment-string "\\>\\)"))
12559 (replace-match "" t t nil 1)
12560 (if (looking-at outline-regexp)
12561 (progn
12562 (goto-char (match-end 0))
12563 (insert org-comment-string " "))))))
12565 (defvar org-last-todo-state-is-todo nil
12566 "This is non-nil when the last TODO state change led to a TODO state.
12567 If the last change removed the TODO tag or switched to DONE, then
12568 this is nil.")
12570 (defun org-todo (&optional arg)
12571 "Change the TODO state of an item.
12572 The state of an item is given by a keyword at the start of the heading,
12573 like
12574 *** TODO Write paper
12575 *** DONE Call mom
12577 The different keywords are specified in the variable `org-todo-keywords'.
12578 By default the available states are \"TODO\" and \"DONE\".
12579 So for this example: when the item starts with TODO, it is changed to DONE.
12580 When it starts with DONE, the DONE is removed. And when neither TODO nor
12581 DONE are present, add TODO at the beginning of the heading.
12583 With C-u prefix arg, use completion to determine the new state.
12584 With numeric prefix arg, switch to that state.
12586 For calling through lisp, arg is also interpreted in the following way:
12587 'none -> empty state
12588 \"\"(empty string) -> switch to empty state
12589 'done -> switch to DONE
12590 'nextset -> switch to the next set of keywords
12591 'previousset -> switch to the previous set of keywords
12592 \"WAITING\" -> switch to the specified keyword, but only if it
12593 really is a member of `org-todo-keywords'."
12594 (interactive "P")
12595 (save-excursion
12596 (org-back-to-heading)
12597 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
12598 (or (looking-at (concat " +" org-todo-regexp " *"))
12599 (looking-at " *"))
12600 (let* ((this (match-string 1))
12601 (head (org-get-todo-sequence-head this))
12602 (ass (assoc head org-todo-kwd-alist))
12603 (interpret (nth 1 ass))
12604 (done-word (nth 3 ass))
12605 (final-done-word (nth 4 ass))
12606 (last-state (or this ""))
12607 (completion-ignore-case t)
12608 (member (member this org-todo-keywords-1))
12609 (tail (cdr member))
12610 (state (cond
12611 ((equal arg '(4))
12612 ;; Read a state with completion
12613 (completing-read "State: " (mapcar (lambda(x) (list x))
12614 org-todo-keywords-1)
12615 nil t))
12616 ((eq arg 'right)
12617 (if this
12618 (if tail (car tail) nil)
12619 (car org-todo-keywords-1)))
12620 ((eq arg 'left)
12621 (if (equal member org-todo-keywords-1)
12623 (if this
12624 (nth (- (length org-todo-keywords-1) (length tail) 2)
12625 org-todo-keywords-1)
12626 (org-last org-todo-keywords-1))))
12627 (arg
12628 ;; user or caller requests a specific state
12629 (cond
12630 ((equal arg "") nil)
12631 ((eq arg 'none) nil)
12632 ((eq arg 'done) (or done-word (car org-done-keywords)))
12633 ((eq arg 'nextset)
12634 (or (car (cdr (member head org-todo-heads)))
12635 (car org-todo-heads)))
12636 ((eq arg 'previousset)
12637 (let ((org-todo-heads (reverse org-todo-heads)))
12638 (or (car (cdr (member head org-todo-heads)))
12639 (car org-todo-heads))))
12640 ((car (member arg org-todo-keywords-1)))
12641 ((nth (1- (prefix-numeric-value arg))
12642 org-todo-keywords-1))))
12643 ((null member) (or head (car org-todo-keywords-1)))
12644 ((equal this final-done-word) nil) ;; -> make empty
12645 ((null tail) nil) ;; -> first entry
12646 ((eq interpret 'sequence)
12647 (car tail))
12648 ((memq interpret '(type priority))
12649 (if (eq this-command last-command)
12650 (car tail)
12651 (if (> (length tail) 0)
12652 (or done-word (car org-done-keywords))
12653 nil)))
12654 (t nil)))
12655 (next (if state (concat " " state " ") " "))
12656 dostates)
12657 (replace-match next t t)
12658 (unless head
12659 (setq head (org-get-todo-sequence-head state)
12660 ass (assoc head org-todo-kwd-alist)
12661 interpret (nth 1 ass)
12662 done-word (nth 3 ass)
12663 final-done-word (nth 4 ass)))
12664 (when (memq arg '(nextset previousset))
12665 (message "Keyword-Set %d/%d: %s"
12666 (- (length org-todo-sets) -1
12667 (length (memq (assoc state org-todo-sets) org-todo-sets)))
12668 (length org-todo-sets)
12669 (mapconcat 'identity (assoc state org-todo-sets) " ")))
12670 (setq org-last-todo-state-is-todo
12671 (not (member state org-done-keywords)))
12672 (when (and org-log-done (not (memq arg '(nextset previousset))))
12673 (setq dostates (and (eq interpret 'sequence)
12674 (listp org-log-done) (memq 'state org-log-done)))
12675 (cond
12676 ((and state (not this))
12677 ;; FIXME: should we remove CLOSED already then state is nil?
12678 (org-add-planning-info nil nil 'closed)
12679 (and dostates (org-add-log-maybe 'state state 'findpos)))
12680 ((and state dostates)
12681 (org-add-log-maybe 'state state 'findpos))
12682 ((member state org-done-keywords)
12683 ;; Planning info calls the note-setting command.
12684 (org-add-planning-info 'closed (org-current-time)
12685 (if (org-get-repeat) nil 'scheduled))
12686 (org-add-log-maybe 'done state 'findpos))))
12687 ;; Fixup tag positioning
12688 (and org-auto-align-tags (org-set-tags nil t))
12689 (run-hooks 'org-after-todo-state-change-hook)
12690 (and (member state org-done-keywords) (org-auto-repeat-maybe))
12691 (if (and arg (not (member state org-done-keywords)))
12692 (setq head (org-get-todo-sequence-head state)))
12693 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)))
12694 ;; Fixup cursor location if close to the keyword
12695 (if (and (outline-on-heading-p)
12696 (not (bolp))
12697 (save-excursion (beginning-of-line 1)
12698 (looking-at org-todo-line-regexp))
12699 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12700 (progn
12701 (goto-char (or (match-end 2) (match-end 1)))
12702 (just-one-space))))
12704 (defun org-get-todo-sequence-head (kwd)
12705 "Return the head of the TODO sequence to which KWD belongs.
12706 If KWD is not set, check if there is a text property remembering the
12707 right sequence."
12708 (let (p)
12709 (cond
12710 ((not kwd)
12711 (or (get-text-property (point-at-bol) 'org-todo-head)
12712 (progn
12713 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12714 nil (point-at-eol)))
12715 (get-text-property p 'org-todo-head))))
12716 ((not (member kwd org-todo-keywords-1))
12717 (car org-todo-keywords-1))
12718 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12720 (defun org-get-repeat ()
12721 "Check if tere is a deadline/schedule with repeater in this entry."
12722 (save-match-data
12723 (save-excursion
12724 (org-back-to-heading t)
12725 (if (re-search-forward
12726 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
12727 (match-string 1)))))
12729 (defvar org-last-changed-timestamp)
12730 (defvar org-log-post-message)
12731 (defun org-auto-repeat-maybe ()
12732 "Check if the current headline contains a repeated deadline/schedule.
12733 If yes, set TODO state back to what it was and change the base date
12734 of repeating deadline/scheduled time stamps to new date.
12735 This function should be run in the `org-after-todo-state-change-hook'."
12736 ;; last-state is dynamically scoped into this function
12737 (let* ((repeat (org-get-repeat))
12738 (aa (assoc last-state org-todo-kwd-alist))
12739 (interpret (nth 1 aa))
12740 (head (nth 2 aa))
12741 (done-word (nth 3 aa))
12742 (whata '(("d" . day) ("m" . month) ("y" . year)))
12743 (msg "Entry repeats: ")
12744 (org-log-done)
12745 re type n what ts)
12746 (when repeat
12747 (org-todo (if (eq interpret 'type) last-state head))
12748 (when (and org-log-repeat
12749 (not (memq 'org-add-log-note
12750 (default-value 'post-command-hook))))
12751 ;; Make sure a note is taken
12752 (let ((org-log-done '(done)))
12753 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
12754 'findpos)))
12755 (org-back-to-heading t)
12756 (org-add-planning-info nil nil 'closed)
12757 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12758 org-deadline-time-regexp "\\)"))
12759 (while (re-search-forward
12760 re (save-excursion (outline-next-heading) (point)) t)
12761 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
12762 ts (match-string (if (match-end 2) 2 4)))
12763 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
12764 (setq n (string-to-number (match-string 1 ts))
12765 what (match-string 2 ts))
12766 (if (equal what "w") (setq n (* n 7) what "d"))
12767 (org-timestamp-change n (cdr (assoc what whata))))
12768 (setq msg (concat msg type org-last-changed-timestamp " ")))
12769 (setq org-log-post-message msg)
12770 (message msg))))
12772 (defun org-show-todo-tree (arg)
12773 "Make a compact tree which shows all headlines marked with TODO.
12774 The tree will show the lines where the regexp matches, and all higher
12775 headlines above the match.
12776 With \\[universal-argument] prefix, also show the DONE entries.
12777 With a numeric prefix N, construct a sparse tree for the Nth element
12778 of `org-todo-keywords-1'."
12779 (interactive "P")
12780 (let ((case-fold-search nil)
12781 (kwd-re
12782 (cond ((null arg) org-not-done-regexp)
12783 ((equal arg '(4))
12784 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
12785 (mapcar 'list org-todo-keywords-1))))
12786 (concat "\\("
12787 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12788 "\\)\\>")))
12789 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12790 (regexp-quote (nth (1- (prefix-numeric-value arg))
12791 org-todo-keywords-1)))
12792 (t (error "Invalid prefix argument: %s" arg)))))
12793 (message "%d TODO entries found"
12794 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
12796 (defun org-deadline ()
12797 "Insert the DEADLINE: string to make a deadline.
12798 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
12799 to modify it to the correct date."
12800 (interactive)
12801 (org-add-planning-info 'deadline nil 'closed))
12803 (defun org-schedule ()
12804 "Insert the SCHEDULED: string to schedule a TODO item.
12805 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
12806 to modify it to the correct date."
12807 (interactive)
12808 (org-add-planning-info 'scheduled nil 'closed))
12810 (defun org-add-planning-info (what &optional time &rest remove)
12811 "Insert new timestamp with keyword in the line directly after the headline.
12812 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
12813 If non is given, the user is prompted for a date.
12814 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12815 be removed."
12816 (interactive)
12817 (let (org-time-was-given org-end-time-was-given)
12818 (when what (setq time (or time (org-read-date nil 'to-time))))
12819 (when (and org-insert-labeled-timestamps-at-point
12820 (member what '(scheduled deadline)))
12821 (insert
12822 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12823 (org-insert-time-stamp time org-time-was-given
12824 nil nil nil (list org-end-time-was-given))
12825 (setq what nil))
12826 (save-excursion
12827 (save-restriction
12828 (let (col list elt ts buffer-invisibility-spec)
12829 (org-back-to-heading t)
12830 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
12831 (goto-char (match-end 1))
12832 (setq col (current-column))
12833 (goto-char (match-end 0))
12834 (if (eobp) (insert "\n"))
12835 (forward-char 1)
12836 (when (and (not org-insert-labeled-timestamps-before-properties-drawer)
12837 (looking-at "[ \t]*:PROPERTIES:[ \t]*$"))
12838 (goto-char (match-end 0))
12839 (if (eobp) (insert "\n"))
12840 (forward-char 1))
12841 (if (and (not (looking-at outline-regexp))
12842 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12843 "[^\r\n]*"))
12844 (not (equal (match-string 1) org-clock-string)))
12845 (narrow-to-region (match-beginning 0) (match-end 0))
12846 (insert-before-markers "\n")
12847 (backward-char 1)
12848 (narrow-to-region (point) (point))
12849 (indent-to-column col))
12850 ;; Check if we have to remove something.
12851 (setq list (cons what remove))
12852 (while list
12853 (setq elt (pop list))
12854 (goto-char (point-min))
12855 (when (or (and (eq elt 'scheduled)
12856 (re-search-forward org-scheduled-time-regexp nil t))
12857 (and (eq elt 'deadline)
12858 (re-search-forward org-deadline-time-regexp nil t))
12859 (and (eq elt 'closed)
12860 (re-search-forward org-closed-time-regexp nil t)))
12861 (replace-match "")
12862 (if (looking-at "--+<[^>]+>") (replace-match ""))
12863 (if (looking-at " +") (replace-match ""))))
12864 (goto-char (point-max))
12865 (when what
12866 (insert
12867 (if (not (equal (char-before) ?\ )) " " "")
12868 (cond ((eq what 'scheduled) org-scheduled-string)
12869 ((eq what 'deadline) org-deadline-string)
12870 ((eq what 'closed) org-closed-string)
12871 ((eq what 'archived) org-archived-string))
12872 " ")
12873 (org-insert-time-stamp
12874 time
12875 (or org-time-was-given
12876 (and (eq what 'closed) org-log-done-with-time))
12877 (eq what 'closed)
12878 nil nil (list org-end-time-was-given))
12879 (end-of-line 1))
12880 (goto-char (point-min))
12881 (widen)
12882 (if (looking-at "[ \t]+\r?\n")
12883 (replace-match ""))
12884 ts)))))
12886 (defvar org-log-note-marker (make-marker))
12887 (defvar org-log-note-purpose nil)
12888 (defvar org-log-note-state nil)
12889 (defvar org-log-note-window-configuration nil)
12890 (defvar org-log-note-return-to (make-marker))
12891 (defvar org-log-post-message nil
12892 "Message to be displayed after a log note has been stored.
12893 The auto-repeater uses this.")
12895 (defun org-add-log-maybe (&optional purpose state findpos)
12896 "Set up the post command hook to take a note."
12897 (save-excursion
12898 (when (and (listp org-log-done)
12899 (memq purpose org-log-done))
12900 (when findpos
12901 (org-back-to-heading t)
12902 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
12903 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12904 "[^\r\n]*\\)?"))
12905 (goto-char (match-end 0))
12906 (unless org-log-states-order-reversed
12907 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12908 (while (looking-at "[ \t]*- State")
12909 (condition-case nil
12910 (org-next-item)
12911 (error (org-end-of-item))))
12912 (skip-chars-backward " \t\n\r")))
12913 (move-marker org-log-note-marker (point))
12914 (setq org-log-note-purpose purpose)
12915 (setq org-log-note-state state)
12916 (add-hook 'post-command-hook 'org-add-log-note 'append))))
12918 (defun org-add-log-note (&optional purpose)
12919 "Pop up a window for taking a note, and add this note later at point."
12920 (remove-hook 'post-command-hook 'org-add-log-note)
12921 (setq org-log-note-window-configuration (current-window-configuration))
12922 (delete-other-windows)
12923 (move-marker org-log-note-return-to (point))
12924 (switch-to-buffer (marker-buffer org-log-note-marker))
12925 (goto-char org-log-note-marker)
12926 (switch-to-buffer-other-window "*Org Note*")
12927 (erase-buffer)
12928 (let ((org-inhibit-startup t)) (org-mode))
12929 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
12930 (cond
12931 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12932 ((eq org-log-note-purpose 'done) "closed todo item")
12933 ((eq org-log-note-purpose 'state) "state change")
12934 (t (error "This should not happen")))))
12935 (org-set-local 'org-finish-function 'org-store-log-note))
12937 (defun org-store-log-note ()
12938 "Finish taking a log note, and insert it to where it belongs."
12939 (let ((txt (buffer-string))
12940 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12941 lines ind)
12942 (kill-buffer (current-buffer))
12943 (if (string-match "^#.*\n[ \t\n]*" txt)
12944 (setq txt (replace-match "" t t txt)))
12945 (if (string-match "\\s-+\\'" txt)
12946 (setq txt (replace-match "" t t txt)))
12947 (setq lines (org-split-string txt "\n"))
12948 (when (and note (string-match "\\S-" note))
12949 (setq note
12950 (org-replace-escapes
12951 note
12952 (list (cons "%u" (user-login-name))
12953 (cons "%U" user-full-name)
12954 (cons "%t" (format-time-string
12955 (org-time-stamp-format 'long 'inactive)
12956 (current-time)))
12957 (cons "%s" (if org-log-note-state
12958 (concat "\"" org-log-note-state "\"")
12959 "")))))
12960 (if lines (setq note (concat note " \\\\")))
12961 (push note lines))
12962 (when lines
12963 (save-excursion
12964 (set-buffer (marker-buffer org-log-note-marker))
12965 (save-excursion
12966 (goto-char org-log-note-marker)
12967 (move-marker org-log-note-marker nil)
12968 (end-of-line 1)
12969 (if (not (bolp)) (insert "\n")) (indent-relative nil)
12970 (insert " - " (pop lines))
12971 (org-indent-line-function)
12972 (beginning-of-line 1)
12973 (looking-at "[ \t]*")
12974 (setq ind (concat (match-string 0) " "))
12975 (end-of-line 1)
12976 (while lines (insert "\n" ind (pop lines)))))))
12977 (set-window-configuration org-log-note-window-configuration)
12978 (with-current-buffer (marker-buffer org-log-note-return-to)
12979 (goto-char org-log-note-return-to))
12980 (move-marker org-log-note-return-to nil)
12981 (and org-log-post-message (message org-log-post-message)))
12983 (defvar org-occur-highlights nil)
12984 (make-variable-buffer-local 'org-occur-highlights)
12986 (defun org-occur (regexp &optional keep-previous callback)
12987 "Make a compact tree which shows all matches of REGEXP.
12988 The tree will show the lines where the regexp matches, and all higher
12989 headlines above the match. It will also show the heading after the match,
12990 to make sure editing the matching entry is easy.
12991 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12992 call to `org-occur' will be kept, to allow stacking of calls to this
12993 command.
12994 If CALLBACK is non-nil, it is a function which is called to confirm
12995 that the match should indeed be shown."
12996 (interactive "sRegexp: \nP")
12997 (or keep-previous (org-remove-occur-highlights nil nil t))
12998 (let ((cnt 0))
12999 (save-excursion
13000 (goto-char (point-min))
13001 (if (or (not keep-previous) ; do not want to keep
13002 (not org-occur-highlights)) ; no previous matches
13003 ;; hide everything
13004 (org-overview))
13005 (while (re-search-forward regexp nil t)
13006 (when (or (not callback)
13007 (save-match-data (funcall callback)))
13008 (setq cnt (1+ cnt))
13009 (when org-highlight-sparse-tree-matches
13010 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13011 (org-show-context 'occur-tree))))
13012 (when org-remove-highlights-with-change
13013 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13014 nil 'local))
13015 (unless org-sparse-tree-open-archived-trees
13016 (org-hide-archived-subtrees (point-min) (point-max)))
13017 (run-hooks 'org-occur-hook)
13018 (if (interactive-p)
13019 (message "%d match(es) for regexp %s" cnt regexp))
13020 cnt))
13022 (defun org-show-context (&optional key)
13023 "Make sure point and context and visible.
13024 How much context is shown depends upon the variables
13025 `org-show-hierarchy-above', `org-show-following-heading'. and
13026 `org-show-siblings'."
13027 (let ((heading-p (org-on-heading-p t))
13028 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13029 (following-p (org-get-alist-option org-show-following-heading key))
13030 (siblings-p (org-get-alist-option org-show-siblings key)))
13031 (catch 'exit
13032 ;; Show heading or entry text
13033 (if heading-p
13034 (org-flag-heading nil) ; only show the heading
13035 (and (or (org-invisible-p) (org-invisible-p2))
13036 (org-show-hidden-entry))) ; show entire entry
13037 (when following-p
13038 ;; Show next sibling, or heading below text
13039 (save-excursion
13040 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13041 (org-flag-heading nil))))
13042 (when siblings-p (org-show-siblings))
13043 (when hierarchy-p
13044 ;; show all higher headings, possibly with siblings
13045 (save-excursion
13046 (while (and (condition-case nil
13047 (progn (org-up-heading-all 1) t)
13048 (error nil))
13049 (not (bobp)))
13050 (org-flag-heading nil)
13051 (when siblings-p (org-show-siblings))))))))
13053 (defun org-reveal (&optional siblings)
13054 "Show current entry, hierarchy above it, and the following headline.
13055 This can be used to show a consistent set of context around locations
13056 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13057 not t for the search context.
13059 With optional argument SIBLINGS, on each level of the hierarchy all
13060 siblings are shown. This repairs the tree structure to what it would
13061 look like when opened with hierarchical calls to `org-cycle'."
13062 (interactive "P")
13063 (let ((org-show-hierarchy-above t)
13064 (org-show-following-heading t)
13065 (org-show-siblings (if siblings t org-show-siblings)))
13066 (org-show-context nil)))
13068 (defun org-highlight-new-match (beg end)
13069 "Highlight from BEG to END and mark the highlight is an occur headline."
13070 (let ((ov (org-make-overlay beg end)))
13071 (org-overlay-put ov 'face 'secondary-selection)
13072 (push ov org-occur-highlights)))
13074 (defun org-remove-occur-highlights (&optional beg end noremove)
13075 "Remove the occur highlights from the buffer.
13076 BEG and END are ignored. If NOREMOVE is nil, remove this function
13077 from the `before-change-functions' in the current buffer."
13078 (interactive)
13079 (unless org-inhibit-highlight-removal
13080 (mapc 'org-delete-overlay org-occur-highlights)
13081 (setq org-occur-highlights nil)
13082 (unless noremove
13083 (remove-hook 'before-change-functions
13084 'org-remove-occur-highlights 'local))))
13086 ;;;; Priorities
13088 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13089 "Regular expression matching the priority indicator.")
13091 (defvar org-remove-priority-next-time nil)
13093 (defun org-priority-up ()
13094 "Increase the priority of the current item."
13095 (interactive)
13096 (org-priority 'up))
13098 (defun org-priority-down ()
13099 "Decrease the priority of the current item."
13100 (interactive)
13101 (org-priority 'down))
13103 (defun org-priority (&optional action)
13104 "Change the priority of an item by ARG.
13105 ACTION can be `set', `up', `down', or a character."
13106 (interactive)
13107 (setq action (or action 'set))
13108 (let (current new news have remove)
13109 (save-excursion
13110 (org-back-to-heading)
13111 (if (looking-at org-priority-regexp)
13112 (setq current (string-to-char (match-string 2))
13113 have t)
13114 (setq current org-default-priority))
13115 (cond
13116 ((or (eq action 'set) (integerp action))
13117 (if (integerp action)
13118 (setq new action)
13119 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
13120 (setq new (read-char-exclusive)))
13121 (cond ((equal new ?\ ) (setq remove t))
13122 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13123 (error "Priority must be between `%c' and `%c'"
13124 org-highest-priority org-lowest-priority))))
13125 ((eq action 'up)
13126 (setq new (1- current)))
13127 ((eq action 'down)
13128 (setq new (1+ current)))
13129 (t (error "Invalid action")))
13130 (setq new (min (max org-highest-priority (upcase new)) org-lowest-priority))
13131 (setq news (format "%c" new))
13132 (if have
13133 (if remove
13134 (replace-match "" t t nil 1)
13135 (replace-match news t t nil 2))
13136 (if remove
13137 (error "No priority cookie found in line")
13138 (looking-at org-todo-line-regexp)
13139 (if (match-end 2)
13140 (progn
13141 (goto-char (match-end 2))
13142 (insert " [#" news "]"))
13143 (goto-char (match-beginning 3))
13144 (insert "[#" news "] ")))))
13145 (org-preserve-lc (org-set-tags nil 'align))
13146 (if remove
13147 (message "Priority removed")
13148 (message "Priority of current item set to %s" news))))
13151 (defun org-get-priority (s)
13152 "Find priority cookie and return priority."
13153 (save-match-data
13154 (if (not (string-match org-priority-regexp s))
13155 (* 1000 (- org-lowest-priority org-default-priority))
13156 (* 1000 (- org-lowest-priority
13157 (string-to-char (match-string 2 s)))))))
13159 ;;;; Tags
13161 (defun org-scan-tags (action matcher &optional todo-only)
13162 "Scan headline tags with inheritance and produce output ACTION.
13163 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
13164 evaluated, testing if a given set of tags qualifies a headline for
13165 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
13166 are included in the output."
13167 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
13168 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13169 (org-re
13170 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
13171 (props (list 'face nil
13172 'done-face 'org-done
13173 'undone-face nil
13174 'mouse-face 'highlight
13175 'org-not-done-regexp org-not-done-regexp
13176 'org-todo-regexp org-todo-regexp
13177 'keymap org-agenda-keymap
13178 'help-echo
13179 (format "mouse-2 or RET jump to org file %s"
13180 (abbreviate-file-name buffer-file-name))))
13181 (case-fold-search nil)
13182 lspos
13183 tags tags-list tags-alist (llast 0) rtn level category i txt
13184 todo marker entry priority)
13185 (save-excursion
13186 (goto-char (point-min))
13187 (when (eq action 'sparse-tree) (org-overview))
13188 (while (re-search-forward re nil t)
13189 (catch :skip
13190 (setq todo (if (match-end 1) (match-string 2))
13191 tags (if (match-end 4) (match-string 4)))
13192 (goto-char (setq lspos (1+ (match-beginning 0))))
13193 (setq level (org-reduced-level (funcall outline-level))
13194 category (org-get-category))
13195 (setq i llast llast level)
13196 ;; remove tag lists from same and sublevels
13197 (while (>= i level)
13198 (when (setq entry (assoc i tags-alist))
13199 (setq tags-alist (delete entry tags-alist)))
13200 (setq i (1- i)))
13201 ;; add the nex tags
13202 (when tags
13203 (setq tags (mapcar 'downcase (org-split-string tags ":"))
13204 tags-alist
13205 (cons (cons level tags) tags-alist)))
13206 ;; compile tags for current headline
13207 (setq tags-list
13208 (if org-use-tag-inheritance
13209 (apply 'append (mapcar 'cdr tags-alist))
13210 tags))
13211 (when (and (or (not todo-only) (member todo org-not-done-keywords))
13212 (eval matcher)
13213 (or (not org-agenda-skip-archived-trees)
13214 (not (member org-archive-tag tags-list))))
13215 (and (eq action 'agenda) (org-agenda-skip))
13216 ;; list this headline
13217 (if (eq action 'sparse-tree)
13218 (progn
13219 (org-show-context 'tags-tree))
13220 (setq txt (org-format-agenda-item
13222 (concat
13223 (if org-tags-match-list-sublevels
13224 (make-string (1- level) ?.) "")
13225 (org-get-heading))
13226 category tags-list)
13227 priority (org-get-priority txt))
13228 (goto-char lspos)
13229 (setq marker (org-agenda-new-marker))
13230 (org-add-props txt props
13231 'org-marker marker 'org-hd-marker marker 'org-category category
13232 'priority priority 'type "tagsmatch")
13233 (push txt rtn))
13234 ;; if we are to skip sublevels, jump to end of subtree
13235 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
13236 (when (and (eq action 'sparse-tree)
13237 (not org-sparse-tree-open-archived-trees))
13238 (org-hide-archived-subtrees (point-min) (point-max)))
13239 (nreverse rtn)))
13241 (defvar todo-only) ;; dynamically scoped
13243 (defun org-tags-sparse-tree (&optional todo-only match)
13244 "Create a sparse tree according to tags string MATCH.
13245 MATCH can contain positive and negative selection of tags, like
13246 \"+WORK+URGENT-WITHBOSS\".
13247 If optional argument TODO_ONLY is non-nil, only select lines that are
13248 also TODO lines."
13249 (interactive "P")
13250 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13252 (defvar org-cached-props nil)
13253 (defun org-cached-entry-get (pom property)
13254 (cdr (assoc property (or org-cached-props
13255 (setq org-cached-props
13256 (org-entry-properties pom))))))
13258 (defun org-global-tags-completion-table (&optional files)
13259 "Return the list of all tags in all agenda buffer/files."
13260 (save-excursion
13261 (org-uniquify
13262 (apply 'append
13263 (mapcar
13264 (lambda (file)
13265 (set-buffer (find-file-noselect file))
13266 (org-get-buffer-tags))
13267 (if (and files (car files))
13268 files
13269 (org-agenda-files)))))))
13271 (defun org-make-tags-matcher (match)
13272 "Create the TAGS//TODO matcher form for the selection string MATCH."
13273 ;; todo-only is scoped dynamically into this function, and the function
13274 ;; may change it it the matcher asksk for it.
13275 (unless match
13276 ;; Get a new match request, with completion
13277 (let ((org-last-tags-completion-table
13278 (org-global-tags-completion-table)))
13279 (setq match (completing-read
13280 "Match: " 'org-tags-completion-function nil nil nil
13281 'org-tags-history))))
13283 ;; Parse the string and create a lisp form
13284 (let ((match0 match)
13285 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
13286 minus tag mm
13287 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13288 orterms term orlist re-p level-p prop-p pn pv)
13289 (if (string-match "/+" match)
13290 ;; match contains also a todo-matching request
13291 (progn
13292 (setq tagsmatch (substring match 0 (match-beginning 0))
13293 todomatch (substring match (match-end 0)))
13294 (if (string-match "^!" todomatch)
13295 (setq todo-only t todomatch (substring todomatch 1)))
13296 (if (string-match "^\\s-*$" todomatch)
13297 (setq todomatch nil)))
13298 ;; only matching tags
13299 (setq tagsmatch match todomatch nil))
13301 ;; Make the tags matcher
13302 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13303 (setq tagsmatcher t)
13304 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13305 (while (setq term (pop orterms))
13306 (while (and (equal (substring term -1) "\\") orterms)
13307 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13308 (while (string-match re term)
13309 (setq minus (and (match-end 1)
13310 (equal (match-string 1 term) "-"))
13311 tag (match-string 2 term)
13312 re-p (equal (string-to-char tag) ?{)
13313 level-p (match-end 3)
13314 prop-p (match-end 4)
13315 mm (cond
13316 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13317 (level-p `(= level ,(string-to-number
13318 (match-string 3 term))))
13319 (prop-p
13320 (setq pn (match-string 4 term)
13321 pv (match-string 5 term)
13322 re-p (equal (string-to-char pv) ?{)
13323 pv (substring pv 1 -1))
13324 (if re-p
13325 `(string-match ,pv (org-cached-entry-get nil ,pn))
13326 `(equal ,pv (org-cached-entry-get nil ,pn))))
13327 (t `(member ,(downcase tag) tags-list)))
13328 mm (if minus (list 'not mm) mm)
13329 term (substring term (match-end 0)))
13330 (push mm tagsmatcher))
13331 (push (if (> (length tagsmatcher) 1)
13332 (cons 'and tagsmatcher)
13333 (car tagsmatcher))
13334 orlist)
13335 (setq tagsmatcher nil))
13336 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13337 (setq tagsmatcher
13338 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13340 ;; Make the todo matcher
13341 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13342 (setq todomatcher t)
13343 (setq orterms (org-split-string todomatch "|") orlist nil)
13344 (while (setq term (pop orterms))
13345 (while (string-match re term)
13346 (setq minus (and (match-end 1)
13347 (equal (match-string 1 term) "-"))
13348 kwd (match-string 2 term)
13349 re-p (equal (string-to-char kwd) ?{)
13350 term (substring term (match-end 0))
13351 mm (if re-p
13352 `(string-match ,(substring kwd 1 -1) todo)
13353 (list 'equal 'todo kwd))
13354 mm (if minus (list 'not mm) mm))
13355 (push mm todomatcher))
13356 (push (if (> (length todomatcher) 1)
13357 (cons 'and todomatcher)
13358 (car todomatcher))
13359 orlist)
13360 (setq todomatcher nil))
13361 (setq todomatcher (if (> (length orlist) 1)
13362 (cons 'or orlist) (car orlist))))
13364 ;; Return the string and lisp forms of the matcher
13365 (setq matcher (if todomatcher
13366 (list 'and tagsmatcher todomatcher)
13367 tagsmatcher))
13368 (cons match0 matcher)))
13370 (defun org-match-any-p (re list)
13371 "Does re match any element of list?"
13372 (setq list (mapcar (lambda (x) (string-match re x)) list))
13373 (delq nil list))
13375 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
13376 (defvar org-tags-overlay (org-make-overlay 1 1))
13377 (org-detach-overlay org-tags-overlay)
13379 (defun org-align-tags-here (to-col)
13380 ;; Assumes that this is a headline
13381 (let ((pos (point)) (col (current-column)) tags)
13382 (beginning-of-line 1)
13383 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13384 (< pos (match-beginning 2)))
13385 (progn
13386 (setq tags (match-string 2))
13387 (goto-char (match-beginning 1))
13388 (insert " ")
13389 (delete-region (point) (1+ (match-end 0)))
13390 (backward-char 1)
13391 (move-to-column
13392 (max (1+ (current-column))
13393 (1+ col)
13394 (if (> to-col 0)
13395 to-col
13396 (- (abs to-col) (length tags))))
13398 (insert tags)
13399 (move-to-column (min (current-column) col) t))
13400 (goto-char pos))))
13402 (defun org-set-tags (&optional arg just-align)
13403 "Set the tags for the current headline.
13404 With prefix ARG, realign all tags in headings in the current buffer."
13405 (interactive "P")
13406 (let* ((re (concat "^" outline-regexp))
13407 (current (org-get-tags))
13408 table current-tags inherited-tags ; computed below when needed
13409 tags p0 c0 c1 rpl)
13410 (if arg
13411 (save-excursion
13412 (goto-char (point-min))
13413 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13414 (while (re-search-forward re nil t)
13415 (org-set-tags nil t)
13416 (end-of-line 1)))
13417 (message "All tags realigned to column %d" org-tags-column))
13418 (if just-align
13419 (setq tags current)
13420 ;; Get a new set of tags from the user
13421 (save-excursion
13422 (setq table (or org-tag-alist (org-get-buffer-tags))
13423 org-last-tags-completion-table table
13424 current-tags (org-split-string current ":")
13425 inherited-tags (nreverse
13426 (nthcdr (length current-tags)
13427 (nreverse (org-get-tags-at))))
13428 tags
13429 (if (or (eq t org-use-fast-tag-selection)
13430 (and org-use-fast-tag-selection
13431 (delq nil (mapcar 'cdr table))))
13432 (org-fast-tag-selection current-tags inherited-tags table)
13433 (let ((org-add-colon-after-tag-completion t))
13434 (org-trim
13435 (completing-read "Tags: " 'org-tags-completion-function
13436 nil nil current 'org-tags-history))))))
13437 (while (string-match "[-+&]+" tags)
13438 ;; No boolean logic, just a list
13439 (setq tags (replace-match ":" t t tags))))
13441 (if (string-match "\\`[\t ]*\\'" tags)
13442 (setq tags "")
13443 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13444 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13446 ;; Insert new tags at the correct column
13447 (beginning-of-line 1)
13448 (cond
13449 ((and (equal current "") (equal tags "")))
13450 ((re-search-forward
13451 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13452 (point-at-eol) t)
13453 (if (equal tags "")
13454 (setq rpl "")
13455 (goto-char (match-beginning 0))
13456 (setq c0 (current-column) p0 (point)
13457 c1 (max (1+ c0) (if (> org-tags-column 0)
13458 org-tags-column
13459 (- (- org-tags-column) (length tags))))
13460 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13461 (replace-match rpl t t)
13462 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
13463 tags)
13464 (t (error "Tags alignment failed"))))))
13466 (defun org-change-tag-in-region (beg end tag off)
13467 "Add or remove TAG for each entry in the region.
13468 This works in the agenda, and also in an org-mode buffer."
13469 (interactive
13470 (list (region-beginning) (region-end)
13471 (let ((org-last-tags-completion-table
13472 (if (org-mode-p)
13473 (org-get-buffer-tags)
13474 (org-global-tags-completion-table))))
13475 (completing-read
13476 "Tag: " 'org-tags-completion-function nil nil nil
13477 'org-tags-history))
13478 (progn
13479 (message "[s]et or [r]emove? ")
13480 (equal (read-char-exclusive) ?r))))
13481 (if (fboundp 'deactivate-mark) (deactivate-mark))
13482 (let ((agendap (equal major-mode 'org-agenda-mode))
13483 l1 l2 m buf pos newhead (cnt 0))
13484 (goto-char end)
13485 (setq l2 (1- (org-current-line)))
13486 (goto-char beg)
13487 (setq l1 (org-current-line))
13488 (loop for l from l1 to l2 do
13489 (goto-line l)
13490 (setq m (get-text-property (point) 'org-hd-marker))
13491 (when (or (and (org-mode-p) (org-on-heading-p))
13492 (and agendap m))
13493 (setq buf (if agendap (marker-buffer m) (current-buffer))
13494 pos (if agendap m (point)))
13495 (with-current-buffer buf
13496 (save-excursion
13497 (save-restriction
13498 (goto-char pos)
13499 (setq cnt (1+ cnt))
13500 (org-toggle-tag tag (if off 'off 'on))
13501 (setq newhead (org-get-heading)))))
13502 (and agendap (org-agenda-change-all-lines newhead m))))
13503 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13505 (defun org-tags-completion-function (string predicate &optional flag)
13506 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13507 (confirm (lambda (x) (stringp (car x)))))
13508 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
13509 (setq s1 (match-string 1 string)
13510 s2 (match-string 2 string))
13511 (setq s1 "" s2 string))
13512 (cond
13513 ((eq flag nil)
13514 ;; try completion
13515 (setq rtn (try-completion s2 ctable confirm))
13516 (if (stringp rtn)
13517 (setq rtn
13518 (concat s1 s2 (substring rtn (length s2))
13519 (if (and org-add-colon-after-tag-completion
13520 (assoc rtn ctable))
13521 ":" ""))))
13522 rtn)
13523 ((eq flag t)
13524 ;; all-completions
13525 (all-completions s2 ctable confirm)
13527 ((eq flag 'lambda)
13528 ;; exact match?
13529 (assoc s2 ctable)))
13532 (defun org-fast-tag-insert (kwd tags face &optional end)
13533 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
13534 (insert (format "%-12s" (concat kwd ":"))
13535 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13536 (or end "")))
13538 (defun org-fast-tag-show-exit (flag)
13539 (save-excursion
13540 (goto-line 3)
13541 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13542 (replace-match ""))
13543 (when flag
13544 (end-of-line 1)
13545 (move-to-column (- (window-width) 19) t)
13546 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13548 (defun org-set-current-tags-overlay (current prefix)
13549 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13550 (if (featurep 'xemacs)
13551 (org-overlay-display org-tags-overlay (concat prefix s)
13552 'secondary-selection)
13553 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13554 (org-overlay-display org-tags-overlay (concat prefix s)))))
13556 (defun org-fast-tag-selection (current inherited table)
13557 "Fast tag selection with single keys.
13558 CURRENT is the current list of tags in the headline, INHERITED is the
13559 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13560 possibly with grouping information.
13561 If the keys are nil, a-z are automatically assigned.
13562 Returns the new tags string, or nil to not change the current settings."
13563 (let* ((maxlen (apply 'max (mapcar
13564 (lambda (x)
13565 (if (stringp (car x)) (string-width (car x)) 0))
13566 table)))
13567 (buf (current-buffer))
13568 (expert (eq org-fast-tag-selection-single-key 'expert))
13569 (buffer-tags nil)
13570 (fwidth (+ maxlen 3 1 3))
13571 (ncol (/ (- (window-width) 4) fwidth))
13572 (i-face 'org-done)
13573 (c-face 'org-todo)
13574 tg cnt e c char c1 c2 ntable tbl rtn
13575 ov-start ov-end ov-prefix
13576 (exit-after-next org-fast-tag-selection-single-key)
13577 groups ingroup)
13578 (save-excursion
13579 (beginning-of-line 1)
13580 (if (looking-at
13581 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13582 (setq ov-start (match-beginning 1)
13583 ov-end (match-end 1)
13584 ov-prefix "")
13585 (setq ov-start (1- (point-at-eol))
13586 ov-end (1+ ov-start))
13587 (skip-chars-forward "^\n\r")
13588 (setq ov-prefix
13589 (concat
13590 (buffer-substring (1- (point)) (point))
13591 (if (> (current-column) org-tags-column)
13593 (make-string (- org-tags-column (current-column)) ?\ ))))))
13594 (org-move-overlay org-tags-overlay ov-start ov-end)
13595 (save-window-excursion
13596 (if expert
13597 (set-buffer (get-buffer-create " *Org tags*"))
13598 (delete-other-windows)
13599 (split-window-vertically)
13600 (switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13601 (erase-buffer)
13602 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13603 (org-fast-tag-insert "Current" current c-face "\n\n")
13604 (org-fast-tag-show-exit exit-after-next)
13605 (org-set-current-tags-overlay current ov-prefix)
13606 (setq tbl table char ?a cnt 0)
13607 (while (setq e (pop tbl))
13608 (cond
13609 ((equal e '(:startgroup))
13610 (push '() groups) (setq ingroup t)
13611 (when (not (= cnt 0))
13612 (setq cnt 0)
13613 (insert "\n"))
13614 (insert "{ "))
13615 ((equal e '(:endgroup))
13616 (setq ingroup nil cnt 0)
13617 (insert "}\n"))
13619 (setq tg (car e) c2 nil)
13620 (if (cdr e)
13621 (setq c (cdr e))
13622 ;; automatically assign a character.
13623 (setq c1 (string-to-char
13624 (downcase (substring
13625 tg (if (= (string-to-char tg) ?@) 1 0)))))
13626 (if (or (rassoc c1 ntable) (rassoc c1 table))
13627 (while (or (rassoc char ntable) (rassoc char table))
13628 (setq char (1+ char)))
13629 (setq c2 c1))
13630 (setq c (or c2 char)))
13631 (if ingroup (push tg (car groups)))
13632 (setq tg (org-add-props tg nil 'face
13633 (cond
13634 ((member tg current) c-face)
13635 ((member tg inherited) i-face)
13636 (t nil))))
13637 (if (and (= cnt 0) (not ingroup)) (insert " "))
13638 (insert "[" c "] " tg (make-string
13639 (- fwidth 4 (length tg)) ?\ ))
13640 (push (cons tg c) ntable)
13641 (when (= (setq cnt (1+ cnt)) ncol)
13642 (insert "\n")
13643 (if ingroup (insert " "))
13644 (setq cnt 0)))))
13645 (setq ntable (nreverse ntable))
13646 (insert "\n")
13647 (goto-char (point-min))
13648 (if (and (not expert) (fboundp 'fit-window-to-buffer))
13649 (fit-window-to-buffer))
13650 (setq rtn
13651 (catch 'exit
13652 (while t
13653 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
13654 (if groups " [!] no groups" " [!]groups")
13655 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13656 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13657 (cond
13658 ((= c ?\r) (throw 'exit t))
13659 ((= c ?!)
13660 (setq groups (not groups))
13661 (goto-char (point-min))
13662 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13663 ((= c ?\C-c)
13664 (if (not expert)
13665 (org-fast-tag-show-exit
13666 (setq exit-after-next (not exit-after-next)))
13667 (setq expert nil)
13668 (delete-other-windows)
13669 (split-window-vertically)
13670 (switch-to-buffer-other-window " *Org tags*")
13671 (and (fboundp 'fit-window-to-buffer)
13672 (fit-window-to-buffer))))
13673 ((or (= c ?\C-g)
13674 (and (= c ?q) (not (rassoc c ntable))))
13675 (org-detach-overlay org-tags-overlay)
13676 (setq quit-flag t))
13677 ((= c ?\ )
13678 (setq current nil)
13679 (if exit-after-next (setq exit-after-next 'now)))
13680 ((= c ?\t)
13681 (condition-case nil
13682 (setq tg (completing-read
13683 "Tag: "
13684 (or buffer-tags
13685 (with-current-buffer buf
13686 (org-get-buffer-tags)))))
13687 (quit (setq tg "")))
13688 (when (string-match "\\S-" tg)
13689 (add-to-list 'buffer-tags (list tg))
13690 (if (member tg current)
13691 (setq current (delete tg current))
13692 (push tg current)))
13693 (if exit-after-next (setq exit-after-next 'now)))
13694 ((setq e (rassoc c ntable) tg (car e))
13695 (if (member tg current)
13696 (setq current (delete tg current))
13697 (loop for g in groups do
13698 (if (member tg g)
13699 (mapcar (lambda (x)
13700 (setq current (delete x current)))
13701 g)))
13702 (push tg current))
13703 (if exit-after-next (setq exit-after-next 'now))))
13705 ;; Create a sorted list
13706 (setq current
13707 (sort current
13708 (lambda (a b)
13709 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13710 (if (eq exit-after-next 'now) (throw 'exit t))
13711 (goto-char (point-min))
13712 (beginning-of-line 2)
13713 (delete-region (point) (point-at-eol))
13714 (org-fast-tag-insert "Current" current c-face)
13715 (org-set-current-tags-overlay current ov-prefix)
13716 (while (re-search-forward
13717 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
13718 (setq tg (match-string 1))
13719 (add-text-properties (match-beginning 1) (match-end 1)
13720 (list 'face
13721 (cond
13722 ((member tg current) c-face)
13723 ((member tg inherited) i-face)
13724 (t nil)))))
13725 (goto-char (point-min)))))
13726 (org-detach-overlay org-tags-overlay)
13727 (if rtn
13728 (mapconcat 'identity current ":")
13729 nil))))
13731 (defun org-get-tags ()
13732 "Get the TAGS string in the current headline."
13733 (unless (org-on-heading-p t)
13734 (error "Not on a heading"))
13735 (save-excursion
13736 (beginning-of-line 1)
13737 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13738 (org-match-string-no-properties 1)
13739 "")))
13741 (defun org-get-buffer-tags ()
13742 "Get a table of all tags used in the buffer, for completion."
13743 (let (tags)
13744 (save-excursion
13745 (goto-char (point-min))
13746 (while (re-search-forward
13747 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
13748 (when (equal (char-after (point-at-bol 0)) ?*)
13749 (mapc (lambda (x) (add-to-list 'tags x))
13750 (org-split-string (org-match-string-no-properties 1) ":")))))
13751 (mapcar 'list tags)))
13754 ;;;; Properties
13756 ;;; Setting and retrieving properties
13758 (defconst org-special-properties
13759 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED"
13760 "CLOCK" "PRIORITY")
13761 "The special properties valid in Org-mode.
13763 These are properties that are not defined in the property drawer,
13764 but in some other way.")
13766 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13767 "Regular expression matching the first line of a property drawer.")
13769 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13770 "Regular expression matching the first line of a property drawer.")
13772 (defun org-property-action ()
13773 "Do an action on properties."
13774 (interactive)
13775 (let (c prop)
13776 (org-at-property-p)
13777 (setq prop (match-string 2))
13778 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13779 (setq c (read-char-exclusive))
13780 (cond
13781 ((equal c ?s)
13782 (call-interactively 'org-set-property))
13783 ((equal c ?d)
13784 (call-interactively 'org-delete-property))
13785 ((equal c ?D)
13786 (call-interactively 'org-delete-property-globally))
13787 ((equal c ?c)
13788 (call-interactively 'org-compute-property-at-point))
13789 (t (error "No such property action %c" c)))))
13791 (defun org-at-property-p ()
13792 "Is the cursor in a property line?"
13793 ;; FIXME: Does not check if we are actually in the drawer.
13794 ;; FIXME: also returns true on any drawers.....
13795 ;; This is used by C-c C-c for property action.
13796 (save-excursion
13797 (beginning-of-line 1)
13798 (looking-at "^[ \t]*\\(:\\([a-zA-Z_0-9]+\\):\\)[ \t]*\\(.*\\)")))
13800 (defmacro org-with-point-at (pom &rest body)
13801 "Move to buffer and point of point-or-marker POM for the duration of BODY."
13802 (declare (indent 1) (debug t))
13803 `(save-excursion
13804 (if (markerp pom) (set-buffer (marker-buffer pom)))
13805 (save-excursion
13806 (goto-char (or pom (point)))
13807 ,@body)))
13809 (defun org-get-property-block (&optional beg end force)
13810 "Return the (beg . end) range of the body of the property drawer.
13811 BEG and END can be beginning and end of subtree, if not given
13812 they will be found.
13813 If the drawer does not exist and FORCE is non-nil, create the drawer."
13814 (catch 'exit
13815 (save-excursion
13816 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13817 (end (or end (progn (outline-next-heading) (point)))))
13818 (goto-char beg)
13819 (if (re-search-forward org-property-start-re end t)
13820 (setq beg (1+ (match-end 0)))
13821 (if force
13822 (save-excursion
13823 (org-insert-property-drawer)
13824 (setq end (progn (outline-next-heading) (point))))
13825 (throw 'exit nil))
13826 (goto-char beg)
13827 (if (re-search-forward org-property-start-re end t)
13828 (setq beg (1+ (match-end 0)))))
13829 (if (re-search-forward org-property-end-re end t)
13830 (setq end (match-beginning 0))
13831 (or force (throw 'exit nil))
13832 (goto-char beg)
13833 (setq end beg)
13834 (org-indent-line-function)
13835 (insert ":END:\n"))
13836 (cons beg end)))))
13838 (defun org-entry-properties (&optional pom which)
13839 "Get all properties of the entry at point-or-marker POM.
13840 This includes the TODO keyword, the tags, time strings for deadline,
13841 scheduled, and clocking, and any additional properties defined in the
13842 entry. The return value is an alist, keys may occur multiple times
13843 if the property key was used several times.
13844 POM may also be nil, in which case the current entry is used.
13845 If WHICH is nil or `all', get all properties. If WHICH is
13846 `special' or `standard', only get that subclass."
13847 (setq which (or which 'all))
13848 (org-with-point-at pom
13849 (let ((clockstr (substring org-clock-string 0 -1))
13850 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
13851 beg end range props sum-props key value)
13852 (save-excursion
13853 (when (condition-case nil (org-back-to-heading t) (error nil))
13854 (setq beg (point))
13855 (setq sum-props (get-text-property (point) 'org-summaries))
13856 (outline-next-heading)
13857 (setq end (point))
13858 (when (memq which '(all special))
13859 ;; Get the special properties, like TODO and tags
13860 (goto-char beg)
13861 (when (and (looking-at org-todo-line-regexp) (match-end 2))
13862 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13863 (when (looking-at org-priority-regexp)
13864 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13865 (when (and (setq value (org-get-tags)) (string-match "\\S-" value))
13866 (push (cons "TAGS" value) props))
13867 (when (setq value (org-get-tags-at))
13868 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
13869 props))
13870 (while (re-search-forward org-keyword-time-regexp end t)
13871 (setq key (substring (org-match-string-no-properties 1) 0 -1))
13872 (unless (member key excluded) (push key excluded))
13873 (push (cons key
13874 (if (equal key clockstr)
13875 (org-no-properties
13876 (org-trim
13877 (buffer-substring
13878 (match-beginning 2) (point-at-eol))))
13879 (org-match-string-no-properties 2)))
13880 props)))
13881 (when (memq which '(all standard))
13882 ;; Get the standard properties, like :PORP: ...
13883 (setq range (org-get-property-block beg end))
13884 (when range
13885 (goto-char (car range))
13886 (while (re-search-forward
13887 "^[ \t]*:\\([a-zA-Z][a-zA-Z_0-9]*\\):[ \t]*\\(\\S-.*\\)?"
13888 (cdr range) t)
13889 (setq key (org-match-string-no-properties 1)
13890 value (org-trim (or (org-match-string-no-properties 2) "")))
13891 (unless (member key excluded)
13892 (push (cons key (or value "")) props)))))
13893 (append sum-props (nreverse props)))))))
13895 (defun org-entry-get (pom property &optional inherit)
13896 "Get value of PROPERTY for entry at point-or-marker POM.
13897 If INHERIT is non-nil and the entry does not have the property,
13898 then also check higher levels of the hierarchy.
13899 If the property is present but empty, the return value is the empty string.
13900 If the property is not present at all, nil is returned."
13901 (org-with-point-at pom
13902 (if inherit
13903 (org-entry-get-with-inheritance property)
13904 (if (member property org-special-properties)
13905 ;; We need a special property. Use brute force, get all properties.
13906 (cdr (assoc property (org-entry-properties nil 'special)))
13907 (let ((range (org-get-property-block)))
13908 (if (and range
13909 (goto-char (car range))
13910 (re-search-forward
13911 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
13912 (cdr range) t))
13913 ;; Found the property, return it.
13914 (if (match-end 1)
13915 (org-match-string-no-properties 1)
13916 "")))))))
13918 (defun org-entry-delete (pom property)
13919 "Delete the property PROPERTY from entry at point-or-marker POM."
13920 (org-with-point-at pom
13921 (if (member property org-special-properties)
13922 nil ; cannot delete these properties.
13923 (let ((range (org-get-property-block)))
13924 (if (and range
13925 (goto-char (car range))
13926 (re-search-forward
13927 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
13928 (cdr range) t))
13929 (progn
13930 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13932 nil)))))
13934 (defvar org-entry-property-inherited-from (make-marker))
13936 (defun org-entry-get-with-inheritance (property)
13937 "Get entry property, and search higher levels if not present."
13938 (let (tmp)
13939 (save-excursion
13940 (catch 'ex
13941 (while t
13942 (when (setq tmp (org-entry-get nil property))
13943 (org-back-to-heading t)
13944 (move-marker org-entry-property-inherited-from (point))
13945 (throw 'ex tmp))
13946 (condition-case nil
13947 (org-up-heading-all 1)
13948 (error (throw 'ex nil))))))
13949 (or tmp (cdr (assoc property org-local-properties))
13950 (cdr (assoc property org-global-properties)))))
13952 (defun org-entry-put (pom property value)
13953 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13954 (org-with-point-at pom
13955 (org-back-to-heading t)
13956 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13957 range)
13958 (cond
13959 ((equal property "TODO")
13960 (when (and (stringp value) (string-match "\\S-" value)
13961 (not (member value org-todo-keywords-1)))
13962 (error "\"%s\" is not a valid TODO state" value))
13963 (if (or (not value)
13964 (not (string-match "\\S-" value)))
13965 (setq value 'none))
13966 (org-todo value)
13967 (org-set-tags nil 'align))
13968 ((equal property "PRIORITY")
13969 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13970 (string-to-char value) ?\ ))
13971 (org-set-tags nil 'align))
13972 ((equal property "SCHEDULED")
13973 (if (re-search-forward org-scheduled-time-regexp end t)
13974 (cond
13975 ((eq value 'earlier) (org-timestamp-change -1 'day))
13976 ((eq value 'later) (org-timestamp-change 1 'day))
13977 (t (call-interactively 'org-schedule)))
13978 (call-interactively 'org-schedule)))
13979 ((equal property "DEADLINE")
13980 (if (re-search-forward org-deadline-time-regexp end t)
13981 (cond
13982 ((eq value 'earlier) (org-timestamp-change -1 'day))
13983 ((eq value 'later) (org-timestamp-change 1 'day))
13984 (t (call-interactively 'org-deadline)))
13985 (call-interactively 'org-deadline)))
13986 ((member property org-special-properties)
13987 (error "The %s property can not yet be set with `org-entry-put'"
13988 property))
13989 (t ; a non-special property
13990 (setq range (org-get-property-block beg end 'force))
13991 (goto-char (car range))
13992 (if (re-search-forward
13993 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13994 (progn
13995 (delete-region (match-beginning 1) (match-end 1))
13996 (goto-char (match-beginning 1)))
13997 (goto-char (cdr range))
13998 (insert "\n")
13999 (backward-char 1)
14000 (org-indent-line-function)
14001 (insert ":" property ":"))
14002 (and value (insert " " value))
14003 (org-indent-line-function))))))
14005 (defun org-buffer-property-keys (&optional include-specials)
14006 "Get all property keys in the current buffer."
14007 (let (rtn range)
14008 (save-excursion
14009 (save-restriction
14010 (widen)
14011 (goto-char (point-min))
14012 (while (re-search-forward org-property-start-re nil t)
14013 (setq range (org-get-property-block))
14014 (goto-char (car range))
14015 (while (re-search-forward "^[ \t]*:\\([a-zA-Z0-9]+\\):" (cdr range) t)
14016 (add-to-list 'rtn (org-match-string-no-properties 1)))
14017 (outline-next-heading))))
14018 (when include-specials
14019 (setq rtn (append org-special-properties rtn)))
14020 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14022 (defun org-insert-property-drawer ()
14023 "Insert a property drawer into the current entry."
14024 (interactive)
14025 (org-back-to-heading t)
14026 (let ((beg (point))
14027 (re (concat "^[ \t]*" org-keyword-time-regexp))
14028 end hiddenp)
14029 (outline-next-heading)
14030 (setq end (point))
14031 (goto-char beg)
14032 (while (re-search-forward re end t))
14033 (setq hiddenp (org-invisible-p))
14034 (end-of-line 1)
14035 (insert "\n:PROPERTIES:\n:END:")
14036 (beginning-of-line 0)
14037 (org-indent-line-function)
14038 (beginning-of-line 2)
14039 (org-indent-line-function)
14040 (beginning-of-line 0)
14041 (if hiddenp
14042 (save-excursion
14043 (org-back-to-heading t)
14044 (hide-entry))
14045 (org-flag-drawer t))))
14047 (defun org-set-property (property value)
14048 "In the current entry, set PROPERTY to VALUE."
14049 (interactive
14050 (let* ((prop (completing-read "Property: "
14051 (mapcar 'list (org-buffer-property-keys))))
14052 (cur (org-entry-get nil prop))
14053 (allowed (org-property-get-allowed-values nil prop 'table))
14054 (val (if allowed
14055 (completing-read "Value: " allowed nil 'req-match)
14056 (read-string
14057 (concat "Value" (if (and cur (string-match "\\S-" cur))
14058 (concat "[" cur "]") "")
14059 ": ")
14060 "" cur))))
14061 (list prop (if (equal val "") cur val))))
14062 (unless (equal (org-entry-get nil property) value)
14063 (org-entry-put nil property value)))
14065 (defun org-delete-property (property)
14066 "In the current entry, delete PROPERTY."
14067 (interactive
14068 (let* ((prop (completing-read
14069 "Property: " (org-entry-properties nil 'standard))))
14070 (list prop)))
14071 (message (concat "Property " property
14072 (if (org-entry-delete nil property)
14073 " deleted"
14074 " was not present in the entry"))))
14076 (defun org-delete-property-globally (property)
14077 "Remove PROPERTY globally, from all entries."
14078 (interactive
14079 (let* ((prop (completing-read
14080 "Globally remove property: "
14081 (mapcar 'list (org-buffer-property-keys)))))
14082 (list prop)))
14083 (save-excursion
14084 (save-restriction
14085 (widen)
14086 (goto-char (point-min))
14087 (let ((cnt 0))
14088 (while (re-search-forward
14089 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
14090 nil t)
14091 (setq cnt (1+ cnt))
14092 (replace-match ""))
14093 (message "Property \"%s\" removed from %d entries" property cnt)))))
14095 (defvar org-columns-current-fmt-compiled) ; defined below
14097 (defun org-compute-property-at-point ()
14098 "FIXME:"
14099 (interactive)
14100 (unless (org-at-property-p)
14101 (error "Not at a property"))
14102 (let ((prop (org-match-string-no-properties 2)))
14103 (org-columns-get-format-and-top-level)
14104 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14105 (error "No operator defined for property %s" prop))
14106 (org-columns-compute prop)))
14108 (defun org-property-get-allowed-values (pom property &optional table)
14109 "Get allowed values for the property PROPERTY.
14110 When TABLE is non-nil, return an alist that can directly be used for
14111 completion."
14112 (let (vals)
14113 (cond
14114 ((equal property "TODO")
14115 (setq vals (org-with-point-at pom
14116 (append org-todo-keywords-1 '("")))))
14117 ((equal property "PRIORITY")
14118 (let ((n org-lowest-priority))
14119 (while (>= n org-highest-priority)
14120 (push (char-to-string n) vals)
14121 (setq n (1- n)))))
14122 ((member property org-special-properties))
14124 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14126 (when (and vals (string-match "\\S-" vals))
14127 (setq vals (car (read-from-string (concat "(" vals ")"))))
14128 (setq vals (mapcar (lambda (x)
14129 (cond ((stringp x) x)
14130 ((numberp x) (number-to-string x))
14131 ((symbolp x) (symbol-name x))
14132 (t "???")))
14133 vals)))))
14134 (if table (mapcar 'list vals) vals)))
14136 (defun org-property-previous-allowed-value (&optional previous)
14137 "Switch to the next allowed value for this property."
14138 (interactive)
14139 (org-property-next-allowed-value t))
14141 (defun org-property-next-allowed-value (&optional previous)
14142 "Switch to the next allowed value for this property."
14143 (interactive)
14144 (unless (org-at-property-p)
14145 (error "Not at a property"))
14146 (let* ((key (match-string 2))
14147 (value (match-string 3))
14148 (allowed (or (org-property-get-allowed-values (point) key)
14149 (and (member value '("[ ]" "[-]" "[X]"))
14150 '("[ ]" "[X]"))))
14151 nval)
14152 (unless allowed
14153 (error "Allowed values for this property have not been defined"))
14154 (if previous (setq allowed (reverse allowed)))
14155 (if (member value allowed)
14156 (setq nval (car (cdr (member value allowed)))))
14157 (setq nval (or nval (car allowed)))
14158 (if (equal nval value)
14159 (error "Only one allowed value for this property"))
14160 (org-at-property-p)
14161 (replace-match (concat " :" key ": " nval) t t)
14162 (org-indent-line-function)
14163 (beginning-of-line 1)
14164 (skip-chars-forward " \t")))
14166 ;;; Column View
14168 (defvar org-columns-overlays nil
14169 "Holds the list of current column overlays.")
14171 (defvar org-columns-current-fmt nil
14172 "Local variable, holds the currently active column format.")
14173 (defvar org-columns-current-fmt-compiled nil
14174 "Local variable, holds the currently active column format.
14175 This is the compiled version of the format.")
14176 (defvar org-columns-current-maxwidths nil
14177 "Loval variable, holds the currently active maximum column widths.")
14178 (defvar org-columns-begin-marker (make-marker)
14179 "Points to the position where last a column creation command was called.")
14180 (defvar org-columns-top-level-marker (make-marker)
14181 "Points to the position where current columns region starts.")
14183 (defvar org-columns-map (make-sparse-keymap)
14184 "The keymap valid in column display.")
14186 (defun org-columns-content ()
14187 "Switch to contents view while in columns view."
14188 (interactive)
14189 (org-overview)
14190 (org-content))
14192 (org-defkey org-columns-map "c" 'org-columns-content)
14193 (org-defkey org-columns-map "o" 'org-overview)
14194 (org-defkey org-columns-map "e" 'org-columns-edit-value)
14195 (org-defkey org-columns-map "v" 'org-columns-show-value)
14196 (org-defkey org-columns-map "q" 'org-columns-quit)
14197 (org-defkey org-columns-map "r" 'org-columns-redo)
14198 (org-defkey org-columns-map [left] 'backward-char)
14199 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
14200 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
14201 (org-defkey org-columns-map [right] 'forward-char)
14202 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
14203 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
14204 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-next-allowed-value)
14205 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
14206 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
14207 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
14208 (org-defkey org-columns-map "<" 'org-columns-narrow)
14209 (org-defkey org-columns-map ">" 'org-columns-widen)
14210 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
14211 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
14212 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
14213 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
14215 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
14216 '("Column"
14217 ["Edit property" org-columns-edit-value t]
14218 ["Next allowed value" org-columns-next-allowed-value t]
14219 ["Previous allowed value" org-columns-previous-allowed-value t]
14220 ["Show full value" org-columns-show-value t]
14221 ["Edit allowed" org-columns-edit-allowed t]
14222 "--"
14223 ["Edit column attributes" org-columns-edit-attributes t]
14224 ["Increase column width" org-columns-widen t]
14225 ["Decrease column width" org-columns-narrow t]
14226 "--"
14227 ["Move column right" org-columns-move-right t]
14228 ["Move column left" org-columns-move-left t]
14229 ["Add column" org-columns-new t]
14230 ["Delete column" org-columns-delete t]
14231 "--"
14232 ["CONTENTS" org-columns-content t]
14233 ["OVERVIEW" org-overview t]
14234 ["Refresh columns display" org-columns-redo t]
14235 "--"
14236 ["Quit" org-columns-quit t]))
14238 (defun org-columns-new-overlay (beg end &optional string face)
14239 "Create a new column overlay and add it to the list."
14240 (let ((ov (org-make-overlay beg end)))
14241 (org-overlay-put ov 'face (or face 'secondary-selection))
14242 (org-overlay-display ov string face)
14243 (push ov org-columns-overlays)
14244 ov))
14246 (defun org-columns-display-here (&optional props)
14247 "Overlay the current line with column display."
14248 (interactive)
14249 (let* ((fmt org-columns-current-fmt-compiled)
14250 (beg (point-at-bol))
14251 (level-face (save-excursion
14252 (beginning-of-line 1)
14253 (looking-at "\\(\\**\\)\\(\\* \\)")
14254 (org-get-level-face 2)))
14255 (color (list :foreground
14256 (face-attribute (or level-face 'default) :foreground)))
14257 props pom property ass width f string ov column)
14258 ;; Check if the entry is in another buffer.
14259 (unless props
14260 (if (eq major-mode 'org-agenda-mode)
14261 (setq pom (or (get-text-property (point) 'org-hd-marker)
14262 (get-text-property (point) 'org-marker))
14263 props (if pom (org-entry-properties pom) nil))
14264 (setq props (org-entry-properties nil))))
14265 ;; Walk the format
14266 (while (setq column (pop fmt))
14267 (setq property (car column)
14268 ass (if (equal property "ITEM")
14269 (cons "ITEM"
14270 (save-match-data
14271 (org-no-properties
14272 (org-remove-tabs
14273 (buffer-substring-no-properties
14274 (point-at-bol) (point-at-eol))))))
14275 (assoc property props))
14276 width (or (cdr (assoc property org-columns-current-maxwidths))
14277 (nth 2 column))
14278 f (format "%%-%d.%ds | " width width)
14279 string (format f (or (cdr ass) "")))
14280 ;; Create the overlay
14281 (org-unmodified
14282 (setq ov (org-columns-new-overlay
14283 beg (setq beg (1+ beg)) string
14284 (list color 'org-column)))
14285 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
14286 (org-overlay-put ov 'keymap org-columns-map)
14287 (org-overlay-put ov 'org-columns-key property)
14288 (org-overlay-put ov 'org-columns-value (cdr ass))
14289 (org-overlay-put ov 'org-columns-pom pom)
14290 (org-overlay-put ov 'org-columns-format f))
14291 (if (or (not (char-after beg))
14292 (equal (char-after beg) ?\n))
14293 (let ((inhibit-read-only t))
14294 (save-excursion
14295 (goto-char beg)
14296 (insert " ")))))
14297 ;; Make the rest of the line disappear.
14298 (org-unmodified
14299 (setq ov (org-columns-new-overlay beg (point-at-eol)))
14300 (org-overlay-put ov 'invisible t)
14301 (org-overlay-put ov 'keymap org-columns-map)
14302 (org-overlay-put ov 'intangible t)
14303 (push ov org-columns-overlays)
14304 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
14305 (org-overlay-put ov 'keymap org-columns-map)
14306 (push ov org-columns-overlays)
14307 (let ((inhibit-read-only t))
14308 (put-text-property (max (point-min) (1- (point-at-bol)))
14309 (min (point-max) (1+ (point-at-eol)))
14310 'read-only "Type `e' to edit property")))))
14312 (defvar org-previous-header-line-format nil
14313 "The header line format before column view was turned on.")
14314 (defvar org-columns-inhibit-recalculation nil
14315 "Inhibit recomputing of columns on column view startup.")
14317 (defvar header-line-format)
14318 (defun org-columns-display-here-title ()
14319 "Overlay the newline before the current line with the table title."
14320 (interactive)
14321 (let ((fmt org-columns-current-fmt-compiled)
14322 string (title "")
14323 property width f column str)
14324 (while (setq column (pop fmt))
14325 (setq property (car column)
14326 str (or (nth 1 column) property)
14327 width (or (cdr (assoc property org-columns-current-maxwidths))
14328 (nth 2 column))
14329 f (format "%%-%d.%ds | " width width)
14330 string (format f str)
14331 title (concat title string)))
14332 (setq title (concat
14333 (org-add-props " " nil 'display '(space :align-to 0))
14334 (org-add-props title nil 'face '(:weight bold :underline t))))
14335 (org-set-local 'org-previous-header-line-format header-line-format)
14336 (setq header-line-format title)))
14338 (defun org-columns-remove-overlays ()
14339 "Remove all currently active column overlays."
14340 (interactive)
14341 (when (marker-buffer org-columns-begin-marker)
14342 (with-current-buffer (marker-buffer org-columns-begin-marker)
14343 (when (local-variable-p 'org-previous-header-line-format)
14344 (setq header-line-format org-previous-header-line-format)
14345 (kill-local-variable 'org-previous-header-line-format))
14346 (move-marker org-columns-begin-marker nil)
14347 (move-marker org-columns-top-level-marker nil)
14348 (org-unmodified
14349 (mapc 'org-delete-overlay org-columns-overlays)
14350 (setq org-columns-overlays nil)
14351 (let ((inhibit-read-only t))
14352 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
14354 (defun org-columns-show-value ()
14355 "Show the full value of the property."
14356 (interactive)
14357 (let ((value (get-char-property (point) 'org-columns-value)))
14358 (message "Value is: %s" (or value ""))))
14360 (defun org-columns-quit ()
14361 "Remove the column overlays and in this way exit column editing."
14362 (interactive)
14363 (org-unmodified
14364 (org-columns-remove-overlays)
14365 (let ((inhibit-read-only t))
14366 ;; FIXME: is this safe???
14367 ;; or are there other reasons why there may be a read-only property????
14368 (remove-text-properties (point-min) (point-max) '(read-only t))))
14369 (when (eq major-mode 'org-agenda-mode)
14370 (message "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
14372 (defun org-columns-edit-value ()
14373 "Edit the value of the property at point in column view.
14374 Where possible, use the standard interface for changing this line."
14375 (interactive)
14376 (let* ((col (current-column))
14377 (key (get-char-property (point) 'org-columns-key))
14378 (value (get-char-property (point) 'org-columns-value))
14379 (bol (point-at-bol)) (eol (point-at-eol))
14380 (pom (or (get-text-property bol 'org-hd-marker)
14381 (point))) ; keep despite of compiler waring
14382 (line-overlays
14383 (delq nil (mapcar (lambda (x)
14384 (and (eq (overlay-buffer x) (current-buffer))
14385 (>= (overlay-start x) bol)
14386 (<= (overlay-start x) eol)
14388 org-columns-overlays)))
14389 nval eval allowed)
14390 (when (equal key "ITEM")
14391 (error "Cannot edit item headline from here"))
14393 (cond
14394 ((equal key "TODO")
14395 (setq eval '(org-with-point-at pom
14396 (let ((current-prefix-arg '(4))) (org-todo '(4))))))
14397 ((equal key "PRIORITY")
14398 (setq eval '(org-with-point-at pom
14399 (call-interactively 'org-priority))))
14400 ((equal key "TAGS")
14401 (setq eval '(org-with-point-at pom
14402 (let ((org-fast-tag-selection-single-key
14403 (if (eq org-fast-tag-selection-single-key 'expert)
14404 t org-fast-tag-selection-single-key)))
14405 (call-interactively 'org-set-tags)))))
14406 ((equal key "DEADLINE")
14407 (setq eval '(org-with-point-at pom
14408 (call-interactively 'org-deadline))))
14409 ((equal key "SCHEDULED")
14410 (setq eval '(org-with-point-at pom
14411 (call-interactively 'org-schedule))))
14413 (setq allowed (org-property-get-allowed-values pom key 'table))
14414 (if allowed
14415 (setq nval (completing-read "Value: " allowed nil t))
14416 (setq nval (read-string "Edit: " value)))
14417 (setq nval (org-trim nval))
14418 (when (not (equal nval value))
14419 (setq eval '(org-entry-put pom key nval)))))
14420 (when eval
14421 (let ((inhibit-read-only t))
14422 (remove-text-properties (1- bol) eol '(read-only t))
14423 (unwind-protect
14424 (progn
14425 (setq org-columns-overlays
14426 (org-delete-all line-overlays org-columns-overlays))
14427 (mapc 'org-delete-overlay line-overlays)
14428 (org-columns-eval eval))
14429 (org-columns-display-here))))
14430 (move-to-column col)
14431 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
14432 (org-columns-update key))))
14434 (defun org-columns-edit-allowed ()
14435 "Edit the list of allowed values for the current property."
14436 (interactive)
14437 (let* ((col (current-column))
14438 (key (get-char-property (point) 'org-columns-key))
14439 (key1 (concat key "_ALL"))
14440 (value (get-char-property (point) 'org-columns-value))
14441 (allowed (org-entry-get (point) key1 t))
14442 nval)
14443 (setq nval (read-string "Allowed: " allowed))
14444 (org-entry-put
14445 (cond ((marker-position org-entry-property-inherited-from)
14446 org-entry-property-inherited-from)
14447 ((marker-position org-columns-top-level-marker)
14448 org-columns-top-level-marker))
14449 key1 nval)))
14451 (defun org-columns-eval (form)
14452 (let (hidep)
14453 (save-excursion
14454 (beginning-of-line 1)
14455 (next-line 1)
14456 (setq hidep (org-on-heading-p 1)))
14457 (eval form)
14458 (and hidep (hide-entry))))
14460 (defun org-columns-previous-allowed-value ()
14461 "Switch to the previous allowed value for this column."
14462 (interactive)
14463 (org-columns-next-allowed-value t))
14465 (defun org-columns-next-allowed-value (&optional previous)
14466 "Switch to the next allowed value for this column."
14467 (interactive)
14468 (let* ((col (current-column))
14469 (key (get-char-property (point) 'org-columns-key))
14470 (value (get-char-property (point) 'org-columns-value))
14471 (bol (point-at-bol)) (eol (point-at-eol))
14472 (pom (or (get-text-property bol 'org-hd-marker)
14473 (point))) ; keep despite of compiler waring
14474 (line-overlays
14475 (delq nil (mapcar (lambda (x)
14476 (and (eq (overlay-buffer x) (current-buffer))
14477 (>= (overlay-start x) bol)
14478 (<= (overlay-start x) eol)
14480 org-columns-overlays)))
14481 (allowed (or (org-property-get-allowed-values pom key)
14482 (and (equal
14483 (nth 4 (assoc key org-columns-current-fmt-compiled))
14484 'checkbox) '("[ ]" "[X]"))))
14485 nval)
14486 (when (equal key "ITEM")
14487 (error "Cannot edit item headline from here"))
14488 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
14489 (error "Allowed values for this property have not been defined"))
14490 (if (member key '("SCHEDULED" "DEADLINE"))
14491 (setq nval (if previous 'earlier 'later))
14492 (if previous (setq allowed (reverse allowed)))
14493 (if (member value allowed)
14494 (setq nval (car (cdr (member value allowed)))))
14495 (setq nval (or nval (car allowed)))
14496 (if (equal nval value)
14497 (error "Only one allowed value for this property")))
14498 (let ((inhibit-read-only t))
14499 (remove-text-properties (1- bol) eol '(read-only t))
14500 (unwind-protect
14501 (progn
14502 (setq org-columns-overlays
14503 (org-delete-all line-overlays org-columns-overlays))
14504 (mapc 'org-delete-overlay line-overlays)
14505 (org-columns-eval '(org-entry-put pom key nval)))
14506 (org-columns-display-here)))
14507 (move-to-column col)
14508 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
14509 (org-columns-update key))))
14511 (defun org-verify-version (task)
14512 (cond
14513 ((eq task 'columns)
14514 (if (or (featurep 'xemacs)
14515 (< emacs-major-version 22))
14516 (error "Emacs 22 is required for the columns feature")))))
14518 (defun org-columns-get-format-and-top-level ()
14519 (let (fmt)
14520 (when (condition-case nil (org-back-to-heading) (error nil))
14521 (move-marker org-entry-property-inherited-from nil)
14522 (setq fmt (org-entry-get nil "COLUMNS" t)))
14523 (setq fmt (or fmt org-columns-default-format))
14524 (org-set-local 'org-columns-current-fmt fmt)
14525 (org-columns-compile-format fmt)
14526 (if (marker-position org-entry-property-inherited-from)
14527 (move-marker org-columns-top-level-marker
14528 org-entry-property-inherited-from)
14529 (move-marker org-columns-top-level-marker (point)))
14530 fmt))
14532 (defun org-columns ()
14533 "Turn on column view on an org-mode file."
14534 (interactive)
14535 (org-verify-version 'columns)
14536 (org-columns-remove-overlays)
14537 (move-marker org-columns-begin-marker (point))
14538 (let (beg end fmt cache maxwidths)
14539 (setq fmt (org-columns-get-format-and-top-level))
14540 (save-excursion
14541 (goto-char org-columns-top-level-marker)
14542 (setq beg (point))
14543 (unless org-columns-inhibit-recalculation
14544 (org-columns-compute-all))
14545 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
14546 (point-max)))
14547 (goto-char beg)
14548 ;; Get and cache the properties
14549 (while (re-search-forward (concat "^" outline-regexp) end t)
14550 (push (cons (org-current-line) (org-entry-properties)) cache))
14551 (when cache
14552 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
14553 (org-set-local 'org-columns-current-maxwidths maxwidths)
14554 (org-columns-display-here-title)
14555 (mapc (lambda (x)
14556 (goto-line (car x))
14557 (org-columns-display-here (cdr x)))
14558 cache)))))
14560 (defun org-columns-new (&optional prop title width op fmt)
14561 "Insert a new column, to the leeft o the current column."
14562 (interactive)
14563 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
14564 cell)
14565 (setq prop (completing-read
14566 "Property: " (mapcar 'list (org-buffer-property-keys t))
14567 nil nil prop))
14568 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
14569 (setq width (read-string "Column width: " (if width (number-to-string width))))
14570 (if (string-match "\\S-" width)
14571 (setq width (string-to-number width))
14572 (setq width nil))
14573 (setq fmt (completing-read "Summary [none]: "
14574 '(("none") ("add_numbers") ("add_times") ("checkbox"))
14575 nil t))
14576 (if (string-match "\\S-" fmt)
14577 (setq fmt (intern fmt))
14578 (setq fmt nil))
14579 (if (eq fmt 'none) (setq fmt nil))
14580 (if editp
14581 (progn
14582 (setcar editp prop)
14583 (setcdr editp (list title width nil fmt)))
14584 (setq cell (nthcdr (1- (current-column))
14585 org-columns-current-fmt-compiled))
14586 (setcdr cell (cons (list prop title width nil fmt)
14587 (cdr cell))))
14588 (org-columns-store-format)
14589 (org-columns-redo)))
14591 (defun org-columns-delete ()
14592 "Delete the column at point from columns view."
14593 (interactive)
14594 (let* ((n (current-column))
14595 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
14596 (when (y-or-n-p
14597 (format "Are you sure you want to remove column \"%s\"? " title))
14598 (setq org-columns-current-fmt-compiled
14599 (delq (nth n org-columns-current-fmt-compiled)
14600 org-columns-current-fmt-compiled))
14601 (org-columns-store-format)
14602 (org-columns-redo)
14603 (if (>= (current-column) (length org-columns-current-fmt-compiled))
14604 (backward-char 1)))))
14606 (defun org-columns-edit-attributes ()
14607 "Edit the attributes of the current column."
14608 (interactive)
14609 (let* ((n (current-column))
14610 (info (nth n org-columns-current-fmt-compiled)))
14611 (apply 'org-columns-new info)))
14613 (defun org-columns-widen (arg)
14614 "Make the column wider by ARG characters."
14615 (interactive "p")
14616 (let* ((n (current-column))
14617 (entry (nth n org-columns-current-fmt-compiled))
14618 (width (or (nth 2 entry)
14619 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
14620 (setq width (max 1 (+ width arg)))
14621 (setcar (nthcdr 2 entry) width)
14622 (org-columns-store-format)
14623 (org-columns-redo)))
14625 (defun org-columns-narrow (arg)
14626 "Make the column nrrower by ARG characters."
14627 (interactive "p")
14628 (org-columns-widen (- arg)))
14630 (defun org-columns-move-right ()
14631 "Swap this column with the one to the right."
14632 (interactive)
14633 (let* ((n (current-column))
14634 (cell (nthcdr n org-columns-current-fmt-compiled))
14636 (when (>= n (1- (length org-columns-current-fmt-compiled)))
14637 (error "Cannot shift this column further to the right"))
14638 (setq e (car cell))
14639 (setcar cell (car (cdr cell)))
14640 (setcdr cell (cons e (cdr (cdr cell))))
14641 (org-columns-store-format)
14642 (org-columns-redo)
14643 (forward-char 1)))
14645 (defun org-columns-move-left ()
14646 "Swap this column with the one to the left."
14647 (interactive)
14648 (let* ((n (current-column)))
14649 (when (= n 0)
14650 (error "Cannot shift this column further to the left"))
14651 (backward-char 1)
14652 (org-columns-move-right)
14653 (backward-char 1)))
14655 (defun org-columns-store-format ()
14656 "Store the text version of the current columns format in appropriate place.
14657 This is either in the COLUMNS property of the node starting the current column
14658 display, or in the #+COLUMNS line of the current buffer."
14659 (let (fmt)
14660 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
14661 (if (marker-position org-columns-top-level-marker)
14662 (save-excursion
14663 (goto-char org-columns-top-level-marker)
14664 (if (org-entry-get nil "COLUMNS")
14665 (org-entry-put nil "COLUMNS" fmt)
14666 (goto-char (point-min))
14667 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
14668 (replace-match (concat "#+COLUMNS: " fmt t t)))))
14669 (setq org-columns-current-fmt fmt))))
14671 (defvar org-overriding-columns-format nil
14672 "When set, overrides any other definition.")
14673 (defvar org-agenda-view-columns-initially nil
14674 "When set, switch to columns view immediately after creating the agenda.")
14676 (defun org-agenda-columns ()
14677 "Turn on column view in the agenda."
14678 (interactive)
14679 (org-verify-version 'columns)
14680 (org-columns-remove-overlays)
14681 (move-marker org-columns-begin-marker (point))
14682 (let (fmt cache maxwidths m)
14683 (cond
14684 ((and (local-variable-p 'org-overriding-columns-format)
14685 org-overriding-columns-format)
14686 (setq fmt org-overriding-columns-format))
14687 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
14688 (setq fmt (org-entry-get m "COLUMNS" t)))
14689 ((and (boundp 'org-columns-current-fmt)
14690 (local-variable-p 'org-columns-current-fmt)
14691 org-columns-current-fmt)
14692 (setq fmt org-columns-current-fmt))
14693 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
14694 (setq m (get-text-property m 'org-hd-marker))
14695 (setq fmt (org-entry-get m "COLUMNS" t))))
14696 (setq fmt (or fmt org-columns-default-format))
14697 (org-set-local 'org-columns-current-fmt fmt)
14698 (org-columns-compile-format fmt)
14699 (save-excursion
14700 ;; Get and cache the properties
14701 (goto-char (point-min))
14702 (while (not (eobp))
14703 (when (setq m (or (get-text-property (point) 'org-hd-marker)
14704 (get-text-property (point) 'org-marker)))
14705 (push (cons (org-current-line) (org-entry-properties m)) cache))
14706 (beginning-of-line 2))
14707 (when cache
14708 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
14709 (org-set-local 'org-columns-current-maxwidths maxwidths)
14710 (org-columns-display-here-title)
14711 (mapc (lambda (x)
14712 (goto-line (car x))
14713 (org-columns-display-here (cdr x)))
14714 cache)))))
14716 (defun org-columns-get-autowidth-alist (s cache)
14717 "Derive the maximum column widths from the format and the cache."
14718 (let ((start 0) rtn)
14719 (while (string-match "%\\([a-zA-Z]\\S-*\\)" s start)
14720 (push (cons (match-string 1 s) 1) rtn)
14721 (setq start (match-end 0)))
14722 (mapc (lambda (x)
14723 (setcdr x (apply 'max
14724 (mapcar
14725 (lambda (y)
14726 (length (or (cdr (assoc (car x) (cdr y))) " ")))
14727 cache))))
14728 rtn)
14729 rtn))
14731 (defun org-columns-compute-all ()
14732 "Compute all columns that have operators defined."
14733 (org-unmodified
14734 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
14735 (let ((columns org-columns-current-fmt-compiled) col)
14736 (while (setq col (pop columns))
14737 (when (nth 3 col)
14738 (save-excursion
14739 (org-columns-compute (car col)))))))
14741 (defun org-columns-update (property)
14742 "Recompute PROPERTY, and update the columns display for it."
14743 (org-columns-compute property)
14744 (let (fmt val pos)
14745 (save-excursion
14746 (mapc (lambda (ov)
14747 (when (equal (org-overlay-get ov 'org-columns-key) property)
14748 (setq pos (org-overlay-start ov))
14749 (goto-char pos)
14750 (when (setq val (cdr (assoc property
14751 (get-text-property (point-at-bol) 'org-summaries))))
14752 (setq fmt (org-overlay-get ov 'org-columns-format))
14753 (org-overlay-put ov 'display (format fmt val)))))
14754 org-columns-overlays))))
14756 (defun org-columns-compute (property)
14757 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
14758 (interactive)
14759 (let* ((re (concat "^" outline-regexp))
14760 (lmax 30) ; Does anyone use deeper levels???
14761 (lsum (make-vector lmax 0))
14762 (level 0)
14763 (ass (assoc property org-columns-current-fmt-compiled))
14764 (format (nth 4 ass))
14765 (beg org-columns-top-level-marker)
14766 last-level val end sumpos sum-alist sum str)
14767 (save-excursion
14768 ;; Find the region to compute
14769 (goto-char beg)
14770 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
14771 (goto-char end)
14772 ;; Walk the tree from the back and do the computations
14773 (while (re-search-backward re beg t)
14774 (setq sumpos (match-beginning 0)
14775 last-level level
14776 level (org-outline-level)
14777 val (org-entry-get nil property))
14778 (cond
14779 ((< level last-level)
14780 ;; put the sum of lower levels here as a property
14781 (setq sum (aref lsum last-level)
14782 str (org-column-number-to-string sum format)
14783 sum-alist (get-text-property sumpos 'org-summaries))
14784 (if (assoc property sum-alist)
14785 (setcdr (assoc property sum-alist) str)
14786 (push (cons property str) sum-alist)
14787 (org-unmodified
14788 (add-text-properties sumpos (1+ sumpos)
14789 (list 'org-summaries sum-alist))))
14790 (when val ;?????????????????????????????????? and force?????
14791 (org-entry-put nil property str))
14792 ;; add current to current level accumulator
14793 (aset lsum level (+ (aref lsum level) sum))
14794 ;; clear accumulators for deeper levels
14795 (loop for l from (1+ level) to (1- lmax) do (aset lsum l 0)))
14796 ((>= level last-level)
14797 ;; add what we have here to the accumulator for this level
14798 (aset lsum level (+ (aref lsum level)
14799 (org-column-string-to-number (or val "0") format))))
14800 (t (error "This should not happen")))))))
14802 (defun org-columns-redo ()
14803 "Construct the column display again."
14804 (interactive)
14805 (message "Recomputing columns...")
14806 (save-excursion
14807 (if (marker-position org-columns-begin-marker)
14808 (goto-char org-columns-begin-marker))
14809 (org-columns-remove-overlays)
14810 (if (org-mode-p)
14811 (call-interactively 'org-columns)
14812 (call-interactively 'org-agenda-columns)))
14813 (message "Recomputing columns...done"))
14815 (defun org-columns-not-in-agenda ()
14816 (if (eq major-mode 'org-agenda-mode)
14817 (error "This command is only allowed in Org-mode buffers")))
14820 (defun org-string-to-number (s)
14821 "Convert string to number, and interpret hh:mm:ss."
14822 (if (not (string-match ":" s))
14823 (string-to-number s)
14824 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
14825 (while l
14826 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
14827 sum)))
14829 (defun org-column-number-to-string (n fmt)
14830 "Convert a computed column number to a string value, according to FMT."
14831 (cond
14832 ((eq fmt 'add_times)
14833 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
14834 (format "%d:%02d" h m)))
14835 ((eq fmt 'checkbox)
14836 (cond ((= n (floor n)) "[X]")
14837 ((> n 1.) "[-]")
14838 (t "[ ]")))
14839 (t (number-to-string n))))
14841 (defun org-column-string-to-number (s fmt)
14842 "Convert a column value to a number that can be used for column computing."
14843 (cond
14844 ((string-match ":" s)
14845 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
14846 (while l
14847 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
14848 sum))
14849 ((eq fmt 'checkbox)
14850 (if (equal s "[X]") 1. 0.000001))
14851 (t (string-to-number s))))
14853 (defun org-columns-uncompile-format (cfmt)
14854 "Turn the compiled columns format back into a string representation."
14855 (let ((rtn "") e s prop title op width fmt)
14856 (while (setq e (pop cfmt))
14857 (setq prop (car e)
14858 title (nth 1 e)
14859 width (nth 2 e)
14860 op (nth 3 e)
14861 fmt (nth 4 e))
14862 (cond
14863 ((eq fmt 'add_times) (setq op ":"))
14864 ((eq fmt 'checkbox) (setq op "X"))
14865 ((eq fmt 'add_numbers) (setq op "+")))
14866 (if (equal title prop) (setq title nil))
14867 (setq s (concat "%" (if width (number-to-string width))
14868 prop
14869 (if title (concat "(" title ")"))
14870 (if op (concat "{" op "}"))))
14871 (setq rtn (concat rtn " " s)))
14872 (org-trim rtn)))
14874 (defun org-columns-compile-format (fmt)
14875 "FIXME"
14876 (let ((start 0) width prop title op f)
14877 (setq org-columns-current-fmt-compiled nil)
14878 (while (string-match "%\\([0-9]+\\)?\\([a-zA-Z_0-9]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*"
14879 fmt start)
14880 (setq start (match-end 0)
14881 width (match-string 1 fmt)
14882 prop (match-string 2 fmt)
14883 title (or (match-string 3 fmt) prop)
14884 op (match-string 4 fmt)
14885 f nil)
14886 (if width (setq width (string-to-number width)))
14887 (cond
14888 ((equal op "+") (setq f 'add_numbers))
14889 ((equal op ":") (setq f 'add_times))
14890 ((equal op "X") (setq f 'checkbox)))
14891 (push (list prop title width op f) org-columns-current-fmt-compiled))
14892 (setq org-columns-current-fmt-compiled
14893 (nreverse org-columns-current-fmt-compiled))))
14895 ;;;; Timestamps
14897 (defvar org-last-changed-timestamp nil)
14898 (defvar org-time-was-given) ; dynamically scoped parameter
14899 (defvar org-end-time-was-given) ; dynamically scoped parameter
14900 (defvar org-ts-what) ; dynamically scoped parameter
14902 (defun org-time-stamp (arg)
14903 "Prompt for a date/time and insert a time stamp.
14904 If the user specifies a time like HH:MM, or if this command is called
14905 with a prefix argument, the time stamp will contain date and time.
14906 Otherwise, only the date will be included. All parts of a date not
14907 specified by the user will be filled in from the current date/time.
14908 So if you press just return without typing anything, the time stamp
14909 will represent the current date/time. If there is already a timestamp
14910 at the cursor, it will be modified."
14911 (interactive "P")
14912 (let (org-time-was-given org-end-time-was-given time)
14913 (cond
14914 ((and (org-at-timestamp-p)
14915 (eq last-command 'org-time-stamp)
14916 (eq this-command 'org-time-stamp))
14917 (insert "--")
14918 (setq time (let ((this-command this-command))
14919 (org-read-date arg 'totime)))
14920 (org-insert-time-stamp time (or org-time-was-given arg)))
14921 ((org-at-timestamp-p)
14922 (setq time (let ((this-command this-command))
14923 (org-read-date arg 'totime)))
14924 (when (org-at-timestamp-p) ; just to get the match data
14925 (replace-match "")
14926 (setq org-last-changed-timestamp
14927 (org-insert-time-stamp
14928 time (or org-time-was-given arg)
14929 nil nil nil (list org-end-time-was-given))))
14930 (message "Timestamp updated"))
14932 (setq time (let ((this-command this-command))
14933 (org-read-date arg 'totime)))
14934 (org-insert-time-stamp time (or org-time-was-given arg)
14935 nil nil nil (list org-end-time-was-given))))))
14937 (defun org-time-stamp-inactive (&optional arg)
14938 "Insert an inactive time stamp.
14939 An inactive time stamp is enclosed in square brackets instead of angle
14940 brackets. It is inactive in the sense that it does not trigger agenda entries,
14941 does not link to the calendar and cannot be changed with the S-cursor keys.
14942 So these are more for recording a certain time/date."
14943 (interactive "P")
14944 (let (org-time-was-given org-end-time-was-given time)
14945 (setq time (org-read-date arg 'totime))
14946 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
14947 nil nil (list org-end-time-was-given))))
14949 (defvar org-date-ovl (org-make-overlay 1 1))
14950 (org-overlay-put org-date-ovl 'face 'org-warning)
14951 (org-detach-overlay org-date-ovl)
14953 (defvar org-ans1) ; dynamically scoped parameter
14954 (defvar org-ans2) ; dynamically scoped parameter
14956 (defvar org-plain-time-of-day-regexp) ; defined below
14957 (defun org-read-date (&optional with-time to-time from-string prompt)
14958 "Read a date and make things smooth for the user.
14959 The prompt will suggest to enter an ISO date, but you can also enter anything
14960 which will at least partially be understood by `parse-time-string'.
14961 Unrecognized parts of the date will default to the current day, month, year,
14962 hour and minute. For example,
14963 3-2-5 --> 2003-02-05
14964 feb 15 --> currentyear-02-15
14965 sep 12 9 --> 2009-09-12
14966 12:45 --> today 12:45
14967 22 sept 0:34 --> currentyear-09-22 0:34
14968 12 --> currentyear-currentmonth-12
14969 Fri --> nearest Friday (today or later)
14970 +4 --> four days from today (only if +N is the only thing given)
14971 etc.
14972 The function understands only English month and weekday abbreviations,
14973 but this can be configured with the variables `parse-time-months' and
14974 `parse-time-weekdays'.
14976 While prompting, a calendar is popped up - you can also select the
14977 date with the mouse (button 1). The calendar shows a period of three
14978 months. To scroll it to other months, use the keys `>' and `<'.
14979 If you don't like the calendar, turn it off with
14980 \(setq org-popup-calendar-for-date-prompt nil)
14982 With optional argument TO-TIME, the date will immediately be converted
14983 to an internal time.
14984 With an optional argument WITH-TIME, the prompt will suggest to also
14985 insert a time. Note that when WITH-TIME is not set, you can still
14986 enter a time, and this function will inform the calling routine about
14987 this change. The calling routine may then choose to change the format
14988 used to insert the time stamp into the buffer to include the time."
14989 (require 'parse-time)
14990 (let* ((org-time-stamp-rounding-minutes
14991 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
14992 (ct (org-current-time))
14993 (default-time
14994 ;; Default time is either today, or, when entering a range,
14995 ;; the range start.
14996 (if (save-excursion
14997 (re-search-backward
14998 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14999 (- (point) 20) t))
15000 (apply
15001 'encode-time
15002 (mapcar (lambda(x) (or x 0))
15003 (parse-time-string (match-string 1))))
15004 ct))
15005 (calendar-move-hook nil)
15006 (view-diary-entries-initially nil)
15007 (view-calendar-holidays-initially nil)
15008 (timestr (format-time-string
15009 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
15010 (prompt (concat (if prompt (concat prompt " ") "")
15011 (format "Date and/or time (default [%s]): " timestr)))
15012 ans (org-ans0 "") org-ans1 org-ans2 (deltadays 0)
15013 second minute hour day month year tl wday wday1 pm)
15015 (cond
15016 (from-string (setq ans from-string))
15017 (org-popup-calendar-for-date-prompt
15018 (save-excursion
15019 (save-window-excursion
15020 (calendar)
15021 (calendar-forward-day (- (time-to-days default-time)
15022 (calendar-absolute-from-gregorian
15023 (calendar-current-date))))
15024 (org-eval-in-calendar nil t)
15025 (let* ((old-map (current-local-map))
15026 (map (copy-keymap calendar-mode-map))
15027 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15028 (org-defkey map (kbd "RET") 'org-calendar-select)
15029 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
15030 'org-calendar-select-mouse)
15031 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
15032 'org-calendar-select-mouse)
15033 (org-defkey minibuffer-local-map [(meta shift left)]
15034 (lambda () (interactive)
15035 (org-eval-in-calendar '(calendar-backward-month 1))))
15036 (org-defkey minibuffer-local-map [(meta shift right)]
15037 (lambda () (interactive)
15038 (org-eval-in-calendar '(calendar-forward-month 1))))
15039 (org-defkey minibuffer-local-map [(shift up)]
15040 (lambda () (interactive)
15041 (org-eval-in-calendar '(calendar-backward-week 1))))
15042 (org-defkey minibuffer-local-map [(shift down)]
15043 (lambda () (interactive)
15044 (org-eval-in-calendar '(calendar-forward-week 1))))
15045 (org-defkey minibuffer-local-map [(shift left)]
15046 (lambda () (interactive)
15047 (org-eval-in-calendar '(calendar-backward-day 1))))
15048 (org-defkey minibuffer-local-map [(shift right)]
15049 (lambda () (interactive)
15050 (org-eval-in-calendar '(calendar-forward-day 1))))
15051 (org-defkey minibuffer-local-map ">"
15052 (lambda () (interactive)
15053 (org-eval-in-calendar '(scroll-calendar-left 1))))
15054 (org-defkey minibuffer-local-map "<"
15055 (lambda () (interactive)
15056 (org-eval-in-calendar '(scroll-calendar-right 1))))
15057 (unwind-protect
15058 (progn
15059 (use-local-map map)
15060 (setq org-ans0 (read-string prompt "" nil nil))
15061 ;; org-ans0: from prompt
15062 ;; org-ans1: from mouse click
15063 ;; org-ans2: from calendar motion
15064 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15065 (use-local-map old-map))))))
15066 (t ; Naked prompt only
15067 (setq ans (read-string prompt "" nil timestr))))
15068 (org-detach-overlay org-date-ovl)
15070 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" org-ans0)
15071 (setq deltadays (string-to-number ans) ans ""))
15073 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
15074 (when (string-match
15075 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15076 (setq year (if (match-end 2)
15077 (string-to-number (match-string 2 ans))
15078 (string-to-number (format-time-string "%Y")))
15079 month (string-to-number (match-string 3 ans))
15080 day (string-to-number (match-string 4 ans)))
15081 (if (< year 100) (setq year (+ 2000 year)))
15082 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15083 t nil ans)))
15084 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15085 ;; If there is a time with am/pm, and *no* time without it, we convert
15086 ;; so that matching will be successful.
15087 ;; FIXME: make this replace twice, so that we catch the end time.
15088 (when (and (not (string-match "[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15089 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15090 (setq hour (string-to-number (match-string 1 ans))
15091 minute (if (match-end 3) (string-to-number (match-string 3 ans)) 0)
15092 pm (equal ?p (string-to-char (downcase (match-string 4 ans)))))
15093 (if (and (= hour 12) (not pm))
15094 (setq hour 0)
15095 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15096 (setq ans (replace-match (format "%02d:%02d" hour minute) t t ans)))
15098 ;; Check if there is a time range
15099 (when (and (boundp 'org-end-time-was-given)
15100 (string-match org-plain-time-of-day-regexp ans)
15101 (match-end 8))
15102 (setq org-end-time-was-given (match-string 8 ans))
15103 (setq ans (concat (substring ans 0 (match-beginning 7))
15104 (substring ans (match-end 7)))))
15106 (setq tl (parse-time-string ans)
15107 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
15108 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
15109 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
15110 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
15111 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
15112 second (or (nth 0 tl) 0)
15113 wday (nth 6 tl))
15114 (setq day (+ day deltadays))
15115 (when (and wday (not (nth 3 tl)))
15116 ;; Weekday was given, but no day, so pick that day in the week
15117 ;; on or after the derived date.
15118 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15119 (unless (equal wday wday1)
15120 (setq day (+ day (% (- wday wday1 -7) 7)))))
15121 (if (and (boundp 'org-time-was-given)
15122 (nth 2 tl))
15123 (setq org-time-was-given t))
15124 (if (< year 100) (setq year (+ 2000 year)))
15125 (if to-time
15126 (encode-time second minute hour day month year)
15127 (if (or (nth 1 tl) (nth 2 tl))
15128 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
15129 (format "%04d-%02d-%02d" year month day)))))
15131 (defun org-eval-in-calendar (form &optional keepdate)
15132 "Eval FORM in the calendar window and return to current window.
15133 Also, store the cursor date in variable org-ans2."
15134 (let ((sw (selected-window)))
15135 (select-window (get-buffer-window "*Calendar*"))
15136 (eval form)
15137 (when (and (not keepdate) (calendar-cursor-to-date))
15138 (let* ((date (calendar-cursor-to-date))
15139 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15140 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15141 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15142 (select-window sw)
15143 ;; Update the prompt to show new default date
15144 (save-excursion
15145 (goto-char (point-min))
15146 (when (and org-ans2
15147 (re-search-forward "\\[[-0-9]+\\]" nil t)
15148 (get-text-property (match-end 0) 'field))
15149 (let ((inhibit-read-only t))
15150 (replace-match (concat "[" org-ans2 "]") t t)
15151 (add-text-properties (point-min) (1+ (match-end 0))
15152 (text-properties-at (1+ (point-min)))))))))
15154 (defun org-calendar-select ()
15155 "Return to `org-read-date' with the date currently selected.
15156 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15157 (interactive)
15158 (when (calendar-cursor-to-date)
15159 (let* ((date (calendar-cursor-to-date))
15160 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15161 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15162 (if (active-minibuffer-window) (exit-minibuffer))))
15164 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15165 "Insert a date stamp for the date given by the internal TIME.
15166 WITH-HM means, use the stamp format that includes the time of the day.
15167 INACTIVE means use square brackets instead of angular ones, so that the
15168 stamp will not contribute to the agenda.
15169 PRE and POST are optional strings to be inserted before and after the
15170 stamp.
15171 The command returns the inserted time stamp."
15172 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15173 stamp)
15174 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15175 (insert (or pre ""))
15176 (insert (setq stamp (format-time-string fmt time)))
15177 (when (listp extra)
15178 (setq extra (car extra))
15179 (if (and (stringp extra)
15180 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15181 (setq extra (format "-%02d:%02d"
15182 (string-to-number (match-string 1 extra))
15183 (string-to-number (match-string 2 extra))))
15184 (setq extra nil)))
15185 (when extra
15186 (backward-char 1)
15187 (insert extra)
15188 (forward-char 1))
15189 (insert (or post ""))
15190 stamp))
15192 (defun org-toggle-time-stamp-overlays ()
15193 "Toggle the use of custom time stamp formats."
15194 (interactive)
15195 (setq org-display-custom-times (not org-display-custom-times))
15196 (unless org-display-custom-times
15197 (let ((p (point-min)) (bmp (buffer-modified-p)))
15198 (while (setq p (next-single-property-change p 'display))
15199 (if (and (get-text-property p 'display)
15200 (eq (get-text-property p 'face) 'org-date))
15201 (remove-text-properties
15202 p (setq p (next-single-property-change p 'display))
15203 '(display t))))
15204 (set-buffer-modified-p bmp)))
15205 (if (featurep 'xemacs)
15206 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15207 (org-restart-font-lock)
15208 (setq org-table-may-need-update t)
15209 (if org-display-custom-times
15210 (message "Time stamps are overlayed with custom format")
15211 (message "Time stamp overlays removed")))
15213 (defun org-display-custom-time (beg end)
15214 "Overlay modified time stamp format over timestamp between BED and END."
15215 (let* ((ts (buffer-substring beg end))
15216 t1 w1 with-hm tf time str w2 (off 0))
15217 (save-match-data
15218 (setq t1 (org-parse-time-string ts t))
15219 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
15220 (setq off (- (match-end 0) (match-beginning 0)))))
15221 (setq end (- end off))
15222 (setq w1 (- end beg)
15223 with-hm (and (nth 1 t1) (nth 2 t1))
15224 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15225 time (org-fix-decoded-time t1)
15226 str (org-add-props
15227 (format-time-string
15228 (substring tf 1 -1) (apply 'encode-time time))
15229 nil 'mouse-face 'highlight)
15230 w2 (length str))
15231 (if (not (= w2 w1))
15232 (add-text-properties (1+ beg) (+ 2 beg)
15233 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15234 (if (featurep 'xemacs)
15235 (progn
15236 (put-text-property beg end 'invisible t)
15237 (put-text-property beg end 'end-glyph (make-glyph str)))
15238 (put-text-property beg end 'display str))))
15240 (defun org-translate-time (string)
15241 "Translate all timestamps in STRING to custom format.
15242 But do this only if the variable `org-display-custom-times' is set."
15243 (when org-display-custom-times
15244 (save-match-data
15245 (let* ((start 0)
15246 (re org-ts-regexp-both)
15247 t1 with-hm inactive tf time str beg end)
15248 (while (setq start (string-match re string start))
15249 (setq beg (match-beginning 0)
15250 end (match-end 0)
15251 t1 (save-match-data
15252 (org-parse-time-string (substring string beg end) t))
15253 with-hm (and (nth 1 t1) (nth 2 t1))
15254 inactive (equal (substring string beg (1+ beg)) "[")
15255 tf (funcall (if with-hm 'cdr 'car)
15256 org-time-stamp-custom-formats)
15257 time (org-fix-decoded-time t1)
15258 str (format-time-string
15259 (concat
15260 (if inactive "[" "<") (substring tf 1 -1)
15261 (if inactive "]" ">"))
15262 (apply 'encode-time time))
15263 string (replace-match str t t string)
15264 start (+ start (length str)))))))
15265 string)
15267 (defun org-fix-decoded-time (time)
15268 "Set 0 instead of nil for the first 6 elements of time.
15269 Don't touch the rest."
15270 (let ((n 0))
15271 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15273 (defun org-days-to-time (timestamp-string)
15274 "Difference between TIMESTAMP-STRING and now in days."
15275 (- (time-to-days (org-time-string-to-time timestamp-string))
15276 (time-to-days (current-time))))
15278 (defun org-deadline-close (timestamp-string &optional ndays)
15279 "Is the time in TIMESTAMP-STRING close to the current date?"
15280 (and (< (org-days-to-time timestamp-string)
15281 (or ndays org-deadline-warning-days))
15282 (not (org-entry-is-done-p))))
15284 (defun org-calendar-select-mouse (ev)
15285 "Return to `org-read-date' with the date currently selected.
15286 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15287 (interactive "e")
15288 (mouse-set-point ev)
15289 (when (calendar-cursor-to-date)
15290 (let* ((date (calendar-cursor-to-date))
15291 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15292 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15293 (if (active-minibuffer-window) (exit-minibuffer))))
15295 (defun org-check-deadlines (ndays)
15296 "Check if there are any deadlines due or past due.
15297 A deadline is considered due if it happens within `org-deadline-warning-days'
15298 days from today's date. If the deadline appears in an entry marked DONE,
15299 it is not shown. The prefix arg NDAYS can be used to test that many
15300 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15301 (interactive "P")
15302 (let* ((org-warn-days
15303 (cond
15304 ((equal ndays '(4)) 100000)
15305 (ndays (prefix-numeric-value ndays))
15306 (t org-deadline-warning-days)))
15307 (case-fold-search nil)
15308 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15309 (callback
15310 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15312 (message "%d deadlines past-due or due within %d days"
15313 (org-occur regexp nil callback)
15314 org-warn-days)))
15316 (defun org-evaluate-time-range (&optional to-buffer)
15317 "Evaluate a time range by computing the difference between start and end.
15318 Normally the result is just printed in the echo area, but with prefix arg
15319 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15320 If the time range is actually in a table, the result is inserted into the
15321 next column.
15322 For time difference computation, a year is assumed to be exactly 365
15323 days in order to avoid rounding problems."
15324 (interactive "P")
15326 (org-clock-update-time-maybe)
15327 (save-excursion
15328 (unless (org-at-date-range-p)
15329 (goto-char (point-at-bol))
15330 (re-search-forward org-tr-regexp (point-at-eol) t))
15331 (if (not (org-at-date-range-p))
15332 (error "Not at a time-stamp range, and none found in current line")))
15333 (let* ((ts1 (match-string 1))
15334 (ts2 (match-string 2))
15335 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15336 (match-end (match-end 0))
15337 (time1 (org-time-string-to-time ts1))
15338 (time2 (org-time-string-to-time ts2))
15339 (t1 (time-to-seconds time1))
15340 (t2 (time-to-seconds time2))
15341 (diff (abs (- t2 t1)))
15342 (negative (< (- t2 t1) 0))
15343 ;; (ys (floor (* 365 24 60 60)))
15344 (ds (* 24 60 60))
15345 (hs (* 60 60))
15346 (fy "%dy %dd %02d:%02d")
15347 (fy1 "%dy %dd")
15348 (fd "%dd %02d:%02d")
15349 (fd1 "%dd")
15350 (fh "%02d:%02d")
15351 y d h m align)
15352 (if havetime
15353 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15355 d (floor (/ diff ds)) diff (mod diff ds)
15356 h (floor (/ diff hs)) diff (mod diff hs)
15357 m (floor (/ diff 60)))
15358 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15360 d (floor (+ (/ diff ds) 0.5))
15361 h 0 m 0))
15362 (if (not to-buffer)
15363 (message (org-make-tdiff-string y d h m))
15364 (when (org-at-table-p)
15365 (goto-char match-end)
15366 (setq align t)
15367 (and (looking-at " *|") (goto-char (match-end 0))))
15368 (if (looking-at
15369 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15370 (replace-match ""))
15371 (if negative (insert " -"))
15372 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15373 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15374 (insert " " (format fh h m))))
15375 (if align (org-table-align))
15376 (message "Time difference inserted")))))
15378 (defun org-make-tdiff-string (y d h m)
15379 (let ((fmt "")
15380 (l nil))
15381 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15382 l (push y l)))
15383 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15384 l (push d l)))
15385 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15386 l (push h l)))
15387 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15388 l (push m l)))
15389 (apply 'format fmt (nreverse l))))
15391 (defun org-time-string-to-time (s)
15392 (apply 'encode-time (org-parse-time-string s)))
15394 (defun org-time-string-to-absolute (s &optional daynr)
15395 "Convert a time stamp to an absolute day number.
15396 If there is a specifyer for a cyclic time stamp, get the closest date to
15397 DAYNR."
15398 (cond
15399 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15400 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15401 daynr
15402 (+ daynr 1000)))
15403 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15404 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15405 (time-to-days (current-time))) (match-string 0 s)))
15406 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15408 (defun org-calendar-holiday ()
15409 "List of holidays, for Diary display in Org-mode."
15410 (let ((hl (check-calendar-holidays date)))
15411 (if hl (mapconcat 'identity hl "; "))))
15413 (defun org-diary-sexp-entry (sexp entry date)
15414 "Process a SEXP diary ENTRY for DATE."
15415 (require 'diary-lib)
15416 (let ((result (if calendar-debug-sexp
15417 (let ((stack-trace-on-error t))
15418 (eval (car (read-from-string sexp))))
15419 (condition-case nil
15420 (eval (car (read-from-string sexp)))
15421 (error
15422 (beep)
15423 (message "Bad sexp at line %d in %s: %s"
15424 (org-current-line)
15425 (buffer-file-name) sexp)
15426 (sleep-for 2))))))
15427 (cond ((stringp result) result)
15428 ((and (consp result)
15429 (stringp (cdr result))) (cdr result))
15430 (result entry)
15431 (t nil))))
15433 (defun org-diary-to-ical-string (frombuf)
15434 "FIXME"
15435 (let* ((tmpdir (if (featurep 'xemacs)
15436 (temp-directory)
15437 temporary-file-directory))
15438 (tmpfile (make-temp-name
15439 (expand-file-name "orgics" tmpdir)))
15440 buf rtn b e)
15441 (save-excursion
15442 (set-buffer frombuf)
15443 (icalendar-export-region (point-min) (point-max) tmpfile)
15444 (setq buf (find-buffer-visiting tmpfile))
15445 (set-buffer buf)
15446 (goto-char (point-min))
15447 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15448 (setq b (match-beginning 0)))
15449 (goto-char (point-max))
15450 (if (re-search-backward "^END:VEVENT" nil t)
15451 (setq e (match-end 0)))
15452 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15453 (kill-buffer buf)
15454 (kill-buffer frombuf)
15455 (delete-file tmpfile)
15456 rtn))
15458 (defun org-closest-date (start current change)
15459 "Find the date closest to CURRENT that is consistent with START and CHANGE."
15460 ;; Make the proper lists from the dates
15461 (catch 'exit
15462 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15463 dn dw sday cday n1 n2
15464 d m y y1 y2 date1 date2 nmonths nm ny m2)
15466 (setq start (org-date-to-gregorian start)
15467 current (org-date-to-gregorian
15468 (if org-agenda-repeating-timestamp-show-all
15469 current
15470 (time-to-days (current-time))))
15471 sday (calendar-absolute-from-gregorian start)
15472 cday (calendar-absolute-from-gregorian current))
15474 (if (<= cday sday) (throw 'exit sday))
15476 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15477 (setq dn (string-to-number (match-string 1 change))
15478 dw (cdr (assoc (match-string 2 change) a1)))
15479 (error "Invalid change specifyer: %s" change))
15480 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15481 (cond
15482 ((eq dw 'day)
15483 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15484 n2 (+ n1 dn)))
15485 ((eq dw 'year)
15486 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15487 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15488 (setq date1 (list m d y1)
15489 n1 (calendar-absolute-from-gregorian date1)
15490 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15491 n2 (calendar-absolute-from-gregorian date2)))
15492 ((eq dw 'month)
15493 ;; approx number of month between the tow dates
15494 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15495 ;; How often does dn fit in there?
15496 (setq d (nth 1 start) m (car start) y (nth 2 start)
15497 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15498 m (+ m nm)
15499 ny (floor (/ m 12))
15500 y (+ y ny)
15501 m (- m (* ny 12)))
15502 (while (> m 12) (setq m (- m 12) y (1+ y)))
15503 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15504 (setq m2 (+ m dn) y2 y)
15505 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15506 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15507 (while (< n2 cday)
15508 (setq n1 n2 m m2 y y2)
15509 (setq m2 (+ m dn) y2 y)
15510 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15511 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15513 (if org-agenda-repeating-timestamp-show-all
15514 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
15515 (if (= cday n1) n1 n2)))))
15517 (defun org-date-to-gregorian (date)
15518 "Turn any specification of DATE into a gregorian date for the calendar."
15519 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15520 ((and (listp date) (= (length date) 3)) date)
15521 ((stringp date)
15522 (setq date (org-parse-time-string date))
15523 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15524 ((listp date)
15525 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15527 (defun org-parse-time-string (s &optional nodefault)
15528 "Parse the standard Org-mode time string.
15529 This should be a lot faster than the normal `parse-time-string'.
15530 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15531 hour and minute fields will be nil if not given."
15532 (if (string-match org-ts-regexp0 s)
15533 (list 0
15534 (if (or (match-beginning 8) (not nodefault))
15535 (string-to-number (or (match-string 8 s) "0")))
15536 (if (or (match-beginning 7) (not nodefault))
15537 (string-to-number (or (match-string 7 s) "0")))
15538 (string-to-number (match-string 4 s))
15539 (string-to-number (match-string 3 s))
15540 (string-to-number (match-string 2 s))
15541 nil nil nil)
15542 (make-list 9 0)))
15544 (defun org-timestamp-up (&optional arg)
15545 "Increase the date item at the cursor by one.
15546 If the cursor is on the year, change the year. If it is on the month or
15547 the day, change that.
15548 With prefix ARG, change by that many units."
15549 (interactive "p")
15550 (org-timestamp-change (prefix-numeric-value arg)))
15552 (defun org-timestamp-down (&optional arg)
15553 "Decrease the date item at the cursor by one.
15554 If the cursor is on the year, change the year. If it is on the month or
15555 the day, change that.
15556 With prefix ARG, change by that many units."
15557 (interactive "p")
15558 (org-timestamp-change (- (prefix-numeric-value arg))))
15560 (defun org-timestamp-up-day (&optional arg)
15561 "Increase the date in the time stamp by one day.
15562 With prefix ARG, change that many days."
15563 (interactive "p")
15564 (if (and (not (org-at-timestamp-p t))
15565 (org-on-heading-p))
15566 (org-todo 'up)
15567 (org-timestamp-change (prefix-numeric-value arg) 'day)))
15569 (defun org-timestamp-down-day (&optional arg)
15570 "Decrease the date in the time stamp by one day.
15571 With prefix ARG, change that many days."
15572 (interactive "p")
15573 (if (and (not (org-at-timestamp-p t))
15574 (org-on-heading-p))
15575 (org-todo 'down)
15576 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
15578 (defsubst org-pos-in-match-range (pos n)
15579 (and (match-beginning n)
15580 (<= (match-beginning n) pos)
15581 (>= (match-end n) pos)))
15583 (defun org-at-timestamp-p (&optional inactive-ok)
15584 "Determine if the cursor is in or at a timestamp."
15585 (interactive)
15586 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15587 (pos (point))
15588 (ans (or (looking-at tsr)
15589 (save-excursion
15590 (skip-chars-backward "^[<\n\r\t")
15591 (if (> (point) 1) (backward-char 1))
15592 (and (looking-at tsr)
15593 (> (- (match-end 0) pos) -1))))))
15594 (and (boundp 'org-ts-what)
15595 (setq org-ts-what
15596 (cond
15597 ((org-pos-in-match-range pos 2) 'year)
15598 ((org-pos-in-match-range pos 3) 'month)
15599 ((org-pos-in-match-range pos 7) 'hour)
15600 ((org-pos-in-match-range pos 8) 'minute)
15601 ((or (org-pos-in-match-range pos 4)
15602 (org-pos-in-match-range pos 5)) 'day)
15603 ((and (> pos (or (match-end 8) (match-end 5)))
15604 (< pos (match-end 0)))
15605 (- pos (or (match-end 8) (match-end 5))))
15606 (t 'day))))
15607 ans))
15609 (defun org-timestamp-change (n &optional what)
15610 "Change the date in the time stamp at point.
15611 The date will be changed by N times WHAT. WHAT can be `day', `month',
15612 `year', `minute', `second'. If WHAT is not given, the cursor position
15613 in the timestamp determines what will be changed."
15614 (let ((pos (point))
15615 with-hm inactive
15616 org-ts-what
15617 extra
15618 ts time time0)
15619 (if (not (org-at-timestamp-p t))
15620 (error "Not at a timestamp"))
15621 (if (and (not what) (not (eq org-ts-what 'day))
15622 org-display-custom-times
15623 (get-text-property (point) 'display)
15624 (not (get-text-property (1- (point)) 'display)))
15625 (setq org-ts-what 'day))
15626 (setq org-ts-what (or what org-ts-what)
15627 inactive (= (char-after (match-beginning 0)) ?\[)
15628 ts (match-string 0))
15629 (replace-match "")
15630 (if (string-match
15631 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
15633 (setq extra (match-string 1 ts)))
15634 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15635 (setq with-hm t))
15636 (setq time0 (org-parse-time-string ts))
15637 (setq time
15638 (apply 'encode-time
15639 (append
15640 (list (or (car time0) 0))
15641 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
15642 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
15643 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
15644 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
15645 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
15646 (nthcdr 6 time0))))
15647 (when (integerp org-ts-what)
15648 (setq extra (org-modify-ts-extra extra org-ts-what n)))
15649 (if (eq what 'calendar)
15650 (let ((cal-date
15651 (save-excursion
15652 (save-match-data
15653 (set-buffer "*Calendar*")
15654 (calendar-cursor-to-date)))))
15655 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15656 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15657 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15658 (setcar time0 (or (car time0) 0))
15659 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15660 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
15661 (setq time (apply 'encode-time time0))))
15662 (setq org-last-changed-timestamp
15663 (org-insert-time-stamp time with-hm inactive nil nil extra))
15664 (org-clock-update-time-maybe)
15665 (goto-char pos)
15666 ;; Try to recenter the calendar window, if any
15667 (if (and org-calendar-follow-timestamp-change
15668 (get-buffer-window "*Calendar*" t)
15669 (memq org-ts-what '(day month year)))
15670 (org-recenter-calendar (time-to-days time)))))
15672 (defun org-modify-ts-extra (s pos n)
15673 "FIXME"
15674 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15675 ng h m new)
15676 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15677 (cond
15678 ((or (org-pos-in-match-range pos 2)
15679 (org-pos-in-match-range pos 3))
15680 (setq m (string-to-number (match-string 3 s))
15681 h (string-to-number (match-string 2 s)))
15682 (if (org-pos-in-match-range pos 2)
15683 (setq h (+ h n))
15684 (setq m (+ m n)))
15685 (if (< m 0) (setq m (+ m 60) h (1- h)))
15686 (if (> m 59) (setq m (- m 60) h (1+ h)))
15687 (setq h (min 24 (max 0 h)))
15688 (setq ng 1 new (format "-%02d:%02d" h m)))
15689 ((org-pos-in-match-range pos 6)
15690 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15691 ((org-pos-in-match-range pos 5)
15692 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
15694 (when ng
15695 (setq s (concat
15696 (substring s 0 (match-beginning ng))
15698 (substring s (match-end ng))))))
15701 (defun org-recenter-calendar (date)
15702 "If the calendar is visible, recenter it to DATE."
15703 (let* ((win (selected-window))
15704 (cwin (get-buffer-window "*Calendar*" t))
15705 (calendar-move-hook nil))
15706 (when cwin
15707 (select-window cwin)
15708 (calendar-goto-date (if (listp date) date
15709 (calendar-gregorian-from-absolute date)))
15710 (select-window win))))
15712 (defun org-goto-calendar (&optional arg)
15713 "Go to the Emacs calendar at the current date.
15714 If there is a time stamp in the current line, go to that date.
15715 A prefix ARG can be used to force the current date."
15716 (interactive "P")
15717 (let ((tsr org-ts-regexp) diff
15718 (calendar-move-hook nil)
15719 (view-calendar-holidays-initially nil)
15720 (view-diary-entries-initially nil))
15721 (if (or (org-at-timestamp-p)
15722 (save-excursion
15723 (beginning-of-line 1)
15724 (looking-at (concat ".*" tsr))))
15725 (let ((d1 (time-to-days (current-time)))
15726 (d2 (time-to-days
15727 (org-time-string-to-time (match-string 1)))))
15728 (setq diff (- d2 d1))))
15729 (calendar)
15730 (calendar-goto-today)
15731 (if (and diff (not arg)) (calendar-forward-day diff))))
15733 (defun org-date-from-calendar ()
15734 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15735 If there is already a time stamp at the cursor position, update it."
15736 (interactive)
15737 (org-timestamp-change 0 'calendar))
15739 ;;; The clock for measuring work time.
15741 (defvar org-mode-line-string "")
15742 (put 'org-mode-line-string 'risky-local-variable t)
15744 (defvar org-mode-line-timer nil)
15745 (defvar org-clock-heading "")
15746 (defvar org-clock-start-time "")
15748 (defun org-update-mode-line ()
15749 (let* ((delta (- (time-to-seconds (current-time))
15750 (time-to-seconds org-clock-start-time)))
15751 (h (floor delta 3600))
15752 (m (floor (- delta (* 3600 h)) 60)))
15753 (setq org-mode-line-string
15754 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
15755 'help-echo "Org-mode clock is running"))
15756 (force-mode-line-update)))
15758 (defvar org-clock-marker (make-marker)
15759 "Marker recording the last clock-in.")
15760 (defvar org-clock-mode-line-entry nil
15761 "Information for the modeline about the running clock.")
15763 (defun org-clock-in ()
15764 "Start the clock on the current item.
15765 If necessary, clock-out of the currently active clock."
15766 (interactive)
15767 (org-clock-out t)
15768 (let (ts)
15769 (save-excursion
15770 (org-back-to-heading t)
15771 (if (looking-at org-todo-line-regexp)
15772 (setq org-clock-heading (match-string 3))
15773 (setq org-clock-heading "???"))
15774 (setq org-clock-heading (propertize org-clock-heading 'face nil))
15775 (beginning-of-line 2)
15776 (while
15777 (or (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
15778 (not (equal (match-string 1) org-clock-string)))
15779 (and (looking-at "[ \t]*:PROPERTIES:")
15780 (not org-insert-labeled-timestamps-before-properties-drawer)))
15781 ;; Scheduling info, or properties drawer, move one line further
15782 (beginning-of-line 2)
15783 (or (bolp) (newline)))
15784 (insert "\n") (backward-char 1)
15785 (indent-relative)
15786 (insert org-clock-string " ")
15787 (setq org-clock-start-time (current-time))
15788 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
15789 (move-marker org-clock-marker (point) (buffer-base-buffer))
15790 (or global-mode-string (setq global-mode-string '("")))
15791 (or (memq 'org-mode-line-string global-mode-string)
15792 (setq global-mode-string
15793 (append global-mode-string '(org-mode-line-string))))
15794 (org-update-mode-line)
15795 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
15796 (message "Clock started at %s" ts))))
15798 (defun org-clock-out (&optional fail-quietly)
15799 "Stop the currently running clock.
15800 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
15801 (interactive)
15802 (catch 'exit
15803 (if (not (marker-buffer org-clock-marker))
15804 (if fail-quietly (throw 'exit t) (error "No active clock")))
15805 (let (ts te s h m)
15806 (save-excursion
15807 (set-buffer (marker-buffer org-clock-marker))
15808 (goto-char org-clock-marker)
15809 (beginning-of-line 1)
15810 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
15811 (equal (match-string 1) org-clock-string))
15812 (setq ts (match-string 2))
15813 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
15814 (goto-char (match-end 0))
15815 (delete-region (point) (point-at-eol))
15816 (insert "--")
15817 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
15818 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
15819 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
15820 h (floor (/ s 3600))
15821 s (- s (* 3600 h))
15822 m (floor (/ s 60))
15823 s (- s (* 60 s)))
15824 (insert " => " (format "%2d:%02d" h m))
15825 (move-marker org-clock-marker nil)
15826 (org-add-log-maybe 'clock-out)
15827 (when org-mode-line-timer
15828 (cancel-timer org-mode-line-timer)
15829 (setq org-mode-line-timer nil))
15830 (setq global-mode-string
15831 (delq 'org-mode-line-string global-mode-string))
15832 (force-mode-line-update)
15833 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
15835 (defun org-clock-cancel ()
15836 "Cancel the running clock be removing the start timestamp."
15837 (interactive)
15838 (if (not (marker-buffer org-clock-marker))
15839 (error "No active clock"))
15840 (save-excursion
15841 (set-buffer (marker-buffer org-clock-marker))
15842 (goto-char org-clock-marker)
15843 (delete-region (1- (point-at-bol)) (point-at-eol)))
15844 (message "Clock canceled"))
15846 (defvar org-clock-file-total-minutes nil
15847 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
15848 (make-variable-buffer-local 'org-clock-file-total-minutes)
15850 (defun org-clock-sum (&optional tstart tend)
15851 "Sum the times for each subtree.
15852 Puts the resulting times in minutes as a text property on each headline."
15853 (interactive)
15854 (let* ((bmp (buffer-modified-p))
15855 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
15856 org-clock-string
15857 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
15858 (lmax 30)
15859 (ltimes (make-vector lmax 0))
15860 (t1 0)
15861 (level 0)
15862 ts te dt
15863 time)
15864 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
15865 (save-excursion
15866 (goto-char (point-max))
15867 (while (re-search-backward re nil t)
15868 (cond
15869 ((match-end 2)
15870 ;; Two time stamps
15871 (setq ts (match-string 2)
15872 te (match-string 3)
15873 ts (time-to-seconds
15874 (apply 'encode-time (org-parse-time-string ts)))
15875 te (time-to-seconds
15876 (apply 'encode-time (org-parse-time-string te)))
15877 ts (if tstart (max ts tstart) ts)
15878 te (if tend (min te tend) te)
15879 dt (- te ts)
15880 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
15881 ((match-end 4)
15882 ;; A naket time
15883 (setq t1 (+ t1 (string-to-number (match-string 5))
15884 (* 60 (string-to-number (match-string 4))))))
15885 (t ;; A headline
15886 (setq level (- (match-end 1) (match-beginning 1)))
15887 (when (or (> t1 0) (> (aref ltimes level) 0))
15888 (loop for l from 0 to level do
15889 (aset ltimes l (+ (aref ltimes l) t1)))
15890 (setq t1 0 time (aref ltimes level))
15891 (loop for l from level to (1- lmax) do
15892 (aset ltimes l 0))
15893 (goto-char (match-beginning 0))
15894 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
15895 (setq org-clock-file-total-minutes (aref ltimes 0)))
15896 (set-buffer-modified-p bmp)))
15898 (defun org-clock-display (&optional total-only)
15899 "Show subtree times in the entire buffer.
15900 If TOTAL-ONLY is non-nil, only show the total time for the entire file
15901 in the echo area."
15902 (interactive)
15903 (org-remove-clock-overlays)
15904 (let (time h m p)
15905 (org-clock-sum)
15906 (unless total-only
15907 (save-excursion
15908 (goto-char (point-min))
15909 (while (setq p (next-single-property-change (point) :org-clock-minutes))
15910 (goto-char p)
15911 (when (setq time (get-text-property p :org-clock-minutes))
15912 (org-put-clock-overlay time (funcall outline-level))))
15913 (setq h (/ org-clock-file-total-minutes 60)
15914 m (- org-clock-file-total-minutes (* 60 h)))
15915 ;; Arrange to remove the overlays upon next change.
15916 (when org-remove-highlights-with-change
15917 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
15918 nil 'local))))
15919 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
15921 (defvar org-clock-overlays nil)
15922 (make-variable-buffer-local 'org-clock-overlays)
15924 (defun org-put-clock-overlay (time &optional level)
15925 "Put an overlays on the current line, displaying TIME.
15926 If LEVEL is given, prefix time with a corresponding number of stars.
15927 This creates a new overlay and stores it in `org-clock-overlays', so that it
15928 will be easy to remove."
15929 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
15930 (l (if level (org-get-legal-level level 0) 0))
15931 (off 0)
15932 ov tx)
15933 (move-to-column c)
15934 (unless (eolp) (skip-chars-backward "^ \t"))
15935 (skip-chars-backward " \t")
15936 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
15937 tx (concat (buffer-substring (1- (point)) (point))
15938 (make-string (+ off (max 0 (- c (current-column)))) ?.)
15939 (org-add-props (format "%s %2d:%02d%s"
15940 (make-string l ?*) h m
15941 (make-string (- 10 l) ?\ ))
15942 '(face secondary-selection))
15943 ""))
15944 (if (not (featurep 'xemacs))
15945 (org-overlay-put ov 'display tx)
15946 (org-overlay-put ov 'invisible t)
15947 (org-overlay-put ov 'end-glyph (make-glyph tx)))
15948 (push ov org-clock-overlays)))
15950 (defun org-remove-clock-overlays (&optional beg end noremove)
15951 "Remove the occur highlights from the buffer.
15952 BEG and END are ignored. If NOREMOVE is nil, remove this function
15953 from the `before-change-functions' in the current buffer."
15954 (interactive)
15955 (unless org-inhibit-highlight-removal
15956 (mapc 'org-delete-overlay org-clock-overlays)
15957 (setq org-clock-overlays nil)
15958 (unless noremove
15959 (remove-hook 'before-change-functions
15960 'org-remove-clock-overlays 'local))))
15962 (defun org-clock-out-if-current ()
15963 "Clock out if the current entry contains the running clock.
15964 This is used to stop the clock after a TODO entry is marked DONE,
15965 and is only done if the variable `org-clock-out-when-done' is not nil."
15966 (when (and org-clock-out-when-done
15967 (member state org-done-keywords)
15968 (equal (marker-buffer org-clock-marker) (current-buffer))
15969 (< (point) org-clock-marker)
15970 (> (save-excursion (outline-next-heading) (point))
15971 org-clock-marker))
15972 ;; Clock out, but don't accept a logging message for this.
15973 (let ((org-log-done (if (and (listp org-log-done)
15974 (member 'clock-out org-log-done))
15975 '(done)
15976 org-log-done)))
15977 (org-clock-out))))
15979 (add-hook 'org-after-todo-state-change-hook
15980 'org-clock-out-if-current)
15982 (defun org-check-running-clock ()
15983 "Check if the current buffer contains the running clock.
15984 If yes, offer to stop it and to save the buffer with the changes."
15985 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
15986 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
15987 (buffer-name))))
15988 (org-clock-out)
15989 (when (y-or-n-p "Save changed buffer?")
15990 (save-buffer))))
15992 (defun org-clock-report ()
15993 "Create a table containing a report about clocked time.
15994 If the buffer contains lines
15995 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
15997 #+END: clocktable
15998 then the table will be inserted between these lines, replacing whatever
15999 is was there before. If these lines are not in the buffer, the table
16000 is inserted at point, surrounded by the special lines.
16001 The BEGIN line can contain parameters. Allowed are:
16002 :maxlevel The maximum level to be included in the table. Default is 3.
16003 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
16004 (interactive)
16005 (org-remove-clock-overlays)
16006 (unless (org-find-dblock "clocktable")
16007 (org-create-dblock (list :name "clocktable"
16008 :maxlevel 2 :emphasize nil)))
16009 (org-update-dblock))
16011 (defun org-clock-update-time-maybe ()
16012 "If this is a CLOCK line, update it and return t.
16013 Otherwise, return nil."
16014 (interactive)
16015 (save-excursion
16016 (beginning-of-line 1)
16017 (skip-chars-forward " \t")
16018 (when (looking-at org-clock-string)
16019 (let ((re (concat "[ \t]*" org-clock-string
16020 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
16021 "\\([ \t]*=>.*\\)?"))
16022 ts te h m s)
16023 (if (not (looking-at re))
16025 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
16026 (end-of-line 1)
16027 (setq ts (match-string 1)
16028 te (match-string 2))
16029 (setq s (- (time-to-seconds
16030 (apply 'encode-time (org-parse-time-string te)))
16031 (time-to-seconds
16032 (apply 'encode-time (org-parse-time-string ts))))
16033 h (floor (/ s 3600))
16034 s (- s (* 3600 h))
16035 m (floor (/ s 60))
16036 s (- s (* 60 s)))
16037 (insert " => " (format "%2d:%02d" h m))
16038 t)))))
16040 (defun org-clock-special-range (key &optional time as-strings)
16041 "Return two times bordering a special time range.
16042 Key is a symbol specifying the range and can be one of `today', `yesterday',
16043 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
16044 A week starts Monday 0:00 and ends Sunday 24:00.
16045 The range is determined relative to TIME. TIME defaults to the current time.
16046 The return value is a cons cell with two internal times like the ones
16047 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
16048 the returned times will be formatted strings."
16049 (let* ((tm (decode-time (or time (current-time))))
16050 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
16051 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
16052 (dow (nth 6 tm))
16053 s1 m1 h1 d1 month1 y1 diff ts te fm)
16054 (cond
16055 ((eq key 'today)
16056 (setq h 0 m 0 h1 24 m1 0))
16057 ((eq key 'yesterday)
16058 (setq d (1- d) h 0 m 0 h1 24 m1 0))
16059 ((eq key 'thisweek)
16060 (setq diff (if (= dow 0) 6 (1- dow))
16061 m 0 h 0 d (- d diff) d1 (+ 7 d)))
16062 ((eq key 'lastweek)
16063 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
16064 m 0 h 0 d (- d diff) d1 (+ 7 d)))
16065 ((eq key 'thismonth)
16066 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
16067 ((eq key 'lastmonth)
16068 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
16069 ((eq key 'thisyear)
16070 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
16071 ((eq key 'lastyear)
16072 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
16073 (t (error "No such time block %s" key)))
16074 (setq ts (encode-time s m h d month y)
16075 te (encode-time (or s1 s) (or m1 m) (or h1 h)
16076 (or d1 d) (or month1 month) (or y1 y)))
16077 (setq fm (cdr org-time-stamp-formats))
16078 (if as-strings
16079 (cons (format-time-string fm ts) (format-time-string fm te))
16080 (cons ts te))))
16082 (defun org-dblock-write:clocktable (params)
16083 "Write the standard clocktable."
16084 (let ((hlchars '((1 . "*") (2 . ?/)))
16085 (emph nil)
16086 (ins (make-marker))
16087 ipos time h m p level hlc hdl maxlevel
16088 ts te cc block)
16089 (setq maxlevel (or (plist-get params :maxlevel) 3)
16090 emph (plist-get params :emphasize)
16091 ts (plist-get params :tstart)
16092 te (plist-get params :tend)
16093 block (plist-get params :block))
16094 (when block
16095 (setq cc (org-clock-special-range block nil t)
16096 ts (car cc) te (cdr cc)))
16097 (if ts (setq ts (time-to-seconds
16098 (apply 'encode-time (org-parse-time-string ts)))))
16099 (if te (setq te (time-to-seconds
16100 (apply 'encode-time (org-parse-time-string te)))))
16101 (move-marker ins (point))
16102 (setq ipos (point))
16103 (insert-before-markers "Clock summary at ["
16104 (substring
16105 (format-time-string (cdr org-time-stamp-formats))
16106 1 -1)
16107 "]."
16108 (if block
16109 (format " Considered range is /%s/." block)
16111 "\n\n|L|Headline|Time|\n")
16112 (org-clock-sum ts te)
16113 (setq h (/ org-clock-file-total-minutes 60)
16114 m (- org-clock-file-total-minutes (* 60 h)))
16115 (insert-before-markers "|-\n|0|" "*Total file time*| "
16116 (format "*%d:%02d*" h m)
16117 "|\n")
16118 (goto-char (point-min))
16119 (while (setq p (next-single-property-change (point) :org-clock-minutes))
16120 (goto-char p)
16121 (when (setq time (get-text-property p :org-clock-minutes))
16122 (save-excursion
16123 (beginning-of-line 1)
16124 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
16125 (setq level (- (match-end 1) (match-beginning 1)))
16126 (<= level maxlevel))
16127 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
16128 hdl (match-string 2)
16129 h (/ time 60)
16130 m (- time (* 60 h)))
16131 (goto-char ins)
16132 (if (= level 1) (insert-before-markers "|-\n"))
16133 (insert-before-markers
16134 "| " (int-to-string level) "|" hlc hdl hlc " |"
16135 (make-string (1- level) ?|)
16137 (format "%d:%02d" h m)
16139 " |\n")))))
16140 (goto-char ins)
16141 (backward-delete-char 1)
16142 (goto-char ipos)
16143 (skip-chars-forward "^|")
16144 (org-table-align)))
16146 ;; FIXME: I don't think anybody uses this, ask David
16147 (defun org-collect-clock-time-entries ()
16148 "Return an internal list with clocking information.
16149 This list has one entry for each CLOCK interval.
16150 FIXME: describe the elements."
16151 (interactive)
16152 (let ((re (concat "^[ \t]*" org-clock-string
16153 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
16154 rtn beg end next cont level title total closedp leafp
16155 clockpos titlepos h m donep)
16156 (save-excursion
16157 (org-clock-sum)
16158 (goto-char (point-min))
16159 (while (re-search-forward re nil t)
16160 (setq clockpos (match-beginning 0)
16161 beg (match-string 1) end (match-string 2)
16162 cont (match-end 0))
16163 (setq beg (apply 'encode-time (org-parse-time-string beg))
16164 end (apply 'encode-time (org-parse-time-string end)))
16165 (org-back-to-heading t)
16166 (setq donep (org-entry-is-done-p))
16167 (setq titlepos (point)
16168 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
16169 h (/ total 60) m (- total (* 60 h))
16170 total (cons h m))
16171 (looking-at "\\(\\*+\\) +\\(.*\\)")
16172 (setq level (- (match-end 1) (match-beginning 1))
16173 title (org-match-string-no-properties 2))
16174 (save-excursion (outline-next-heading) (setq next (point)))
16175 (setq closedp (re-search-forward org-closed-time-regexp next t))
16176 (goto-char next)
16177 (setq leafp (and (looking-at "^\\*+ ")
16178 (<= (- (match-end 0) (point)) level)))
16179 (push (list beg end clockpos closedp donep
16180 total title titlepos level leafp)
16181 rtn)
16182 (goto-char cont)))
16183 (nreverse rtn)))
16185 ;;;; Agenda, and Diary Integration
16187 ;;; Define the Org-agenda-mode
16189 (defvar org-agenda-mode-map (make-sparse-keymap)
16190 "Keymap for `org-agenda-mode'.")
16192 (defvar org-agenda-menu) ; defined later in this file.
16193 (defvar org-agenda-follow-mode nil)
16194 (defvar org-agenda-show-log nil)
16195 (defvar org-agenda-redo-command nil)
16196 (defvar org-agenda-mode-hook nil)
16197 (defvar org-agenda-type nil)
16198 (defvar org-agenda-force-single-file nil)
16200 (defun org-agenda-mode ()
16201 "Mode for time-sorted view on action items in Org-mode files.
16203 The following commands are available:
16205 \\{org-agenda-mode-map}"
16206 (interactive)
16207 (kill-all-local-variables)
16208 (setq org-agenda-undo-list nil
16209 org-agenda-pending-undo-list nil)
16210 (setq major-mode 'org-agenda-mode)
16211 ;; Keep global-font-lock-mode from turning on font-lock-mode
16212 (org-set-local 'font-lock-global-modes (list 'not major-mode))
16213 (setq mode-name "Org-Agenda")
16214 (use-local-map org-agenda-mode-map)
16215 (easy-menu-add org-agenda-menu)
16216 (if org-startup-truncated (setq truncate-lines t))
16217 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
16218 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
16219 ;; Make sure properties are removed when copying text
16220 (when (boundp 'buffer-substring-filters)
16221 (org-set-local 'buffer-substring-filters
16222 (cons (lambda (x)
16223 (set-text-properties 0 (length x) nil x) x)
16224 buffer-substring-filters)))
16225 (unless org-agenda-keep-modes
16226 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
16227 org-agenda-show-log nil))
16228 (easy-menu-change
16229 '("Agenda") "Agenda Files"
16230 (append
16231 (list
16232 (vector
16233 (if (get 'org-agenda-files 'org-restrict)
16234 "Restricted to single file"
16235 "Edit File List")
16236 '(org-edit-agenda-file-list)
16237 (not (get 'org-agenda-files 'org-restrict)))
16238 "--")
16239 (mapcar 'org-file-menu-entry (org-agenda-files))))
16240 (org-agenda-set-mode-name)
16241 (apply
16242 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
16243 (list 'org-agenda-mode-hook)))
16245 (substitute-key-definition 'undo 'org-agenda-undo
16246 org-agenda-mode-map global-map)
16247 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
16248 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
16249 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
16250 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
16251 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
16252 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
16253 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
16254 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
16255 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
16256 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
16257 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
16258 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
16259 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
16260 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
16261 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
16262 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
16263 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
16264 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
16265 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
16266 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
16267 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
16268 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
16269 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
16270 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
16271 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
16272 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
16273 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
16274 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
16275 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
16277 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
16278 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
16279 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
16280 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
16281 (while l (org-defkey org-agenda-mode-map
16282 (int-to-string (pop l)) 'digit-argument)))
16284 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
16285 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
16286 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
16287 (org-defkey org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
16288 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
16289 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
16290 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
16291 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
16292 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
16293 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
16294 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
16295 (org-defkey org-agenda-mode-map "n" 'next-line)
16296 (org-defkey org-agenda-mode-map "p" 'previous-line)
16297 (org-defkey org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
16298 (org-defkey org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
16299 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
16300 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
16301 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
16302 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
16303 (eval-after-load "calendar"
16304 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
16305 'org-calendar-goto-agenda))
16306 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
16307 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
16308 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
16309 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
16310 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
16311 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
16312 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
16313 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
16314 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
16315 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
16316 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
16317 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
16318 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
16319 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
16320 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
16321 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
16322 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
16324 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
16325 "Local keymap for agenda entries from Org-mode.")
16327 (org-defkey org-agenda-keymap
16328 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
16329 (org-defkey org-agenda-keymap
16330 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
16331 (when org-agenda-mouse-1-follows-link
16332 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
16333 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
16334 '("Agenda"
16335 ("Agenda Files")
16336 "--"
16337 ["Show" org-agenda-show t]
16338 ["Go To (other window)" org-agenda-goto t]
16339 ["Go To (this window)" org-agenda-switch-to t]
16340 ["Follow Mode" org-agenda-follow-mode
16341 :style toggle :selected org-agenda-follow-mode :active t]
16342 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
16343 "--"
16344 ["Cycle TODO" org-agenda-todo t]
16345 ["Archive subtree" org-agenda-archive t]
16346 ["Delete subtree" org-agenda-kill t]
16347 "--"
16348 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
16349 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
16350 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
16351 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
16352 "--"
16353 ("Tags and Properties"
16354 ["Show all Tags" org-agenda-show-tags t]
16355 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
16356 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
16357 "--"
16358 ["Column View" org-columns t])
16359 ("Date/Schedule"
16360 ["Schedule" org-agenda-schedule t]
16361 ["Set Deadline" org-agenda-deadline t]
16362 "--"
16363 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
16364 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
16365 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
16366 ("Priority"
16367 ["Set Priority" org-agenda-priority t]
16368 ["Increase Priority" org-agenda-priority-up t]
16369 ["Decrease Priority" org-agenda-priority-down t]
16370 ["Show Priority" org-agenda-show-priority t])
16371 ("Calendar/Diary"
16372 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
16373 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
16374 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
16375 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
16376 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
16377 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
16378 "--"
16379 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
16380 "--"
16381 ("View"
16382 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
16383 :style radio :selected (equal org-agenda-ndays 1)]
16384 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
16385 :style radio :selected (equal org-agenda-ndays 7)]
16386 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
16387 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
16388 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
16389 :style radio :selected (member org-agenda-ndays '(365 366))]
16390 "--"
16391 ["Show Logbook entries" org-agenda-log-mode
16392 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
16393 ["Include Diary" org-agenda-toggle-diary
16394 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
16395 ["Use Time Grid" org-agenda-toggle-time-grid
16396 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
16397 ["Write view to file" org-write-agenda t]
16398 ["Rebuild buffer" org-agenda-redo t]
16399 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
16400 "--"
16401 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
16402 "--"
16403 ["Quit" org-agenda-quit t]
16404 ["Exit and Release Buffers" org-agenda-exit t]
16407 ;;; Agenda undo
16409 (defvar org-agenda-allow-remote-undo t
16410 "Non-nil means, allow remote undo from the agenda buffer.")
16411 (defvar org-agenda-undo-list nil
16412 "List of undoable operations in the agenda since last refresh.")
16413 (defvar org-agenda-undo-has-started-in nil
16414 "Buffers that have already seen `undo-start' in the current undo sequence.")
16415 (defvar org-agenda-pending-undo-list nil
16416 "In a series of undo commands, this is the list of remaning undo items.")
16418 (defmacro org-if-unprotected (&rest body)
16419 "Execute BODY if there is no `org-protected' text property at point."
16420 (declare (debug t))
16421 `(unless (get-text-property (point) 'org-protected)
16422 ,@body))
16424 (defmacro org-with-remote-undo (_buffer &rest _body)
16425 "Execute BODY while recording undo information in two buffers."
16426 (declare (indent 1) (debug t))
16427 `(let ((_cline (org-current-line))
16428 (_cmd this-command)
16429 (_buf1 (current-buffer))
16430 (_buf2 ,_buffer)
16431 (_undo1 buffer-undo-list)
16432 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
16433 _c1 _c2)
16434 ,@_body
16435 (when org-agenda-allow-remote-undo
16436 (setq _c1 (org-verify-change-for-undo
16437 _undo1 (with-current-buffer _buf1 buffer-undo-list))
16438 _c2 (org-verify-change-for-undo
16439 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
16440 (when (or _c1 _c2)
16441 ;; make sure there are undo boundaries
16442 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
16443 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
16444 ;; remember which buffer to undo
16445 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
16446 org-agenda-undo-list)))))
16448 (defun org-agenda-undo ()
16449 "Undo a remote editing step in the agenda.
16450 This undoes changes both in the agenda buffer and in the remote buffer
16451 that have been changed along."
16452 (interactive)
16453 (or org-agenda-allow-remote-undo
16454 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
16455 (if (not (eq this-command last-command))
16456 (setq org-agenda-undo-has-started-in nil
16457 org-agenda-pending-undo-list org-agenda-undo-list))
16458 (if (not org-agenda-pending-undo-list)
16459 (error "No further undo information"))
16460 (let* ((entry (pop org-agenda-pending-undo-list))
16461 buf line cmd rembuf)
16462 (setq cmd (pop entry) line (pop entry))
16463 (setq rembuf (nth 2 entry))
16464 (org-with-remote-undo rembuf
16465 (while (bufferp (setq buf (pop entry)))
16466 (if (pop entry)
16467 (with-current-buffer buf
16468 (let ((last-undo-buffer buf)
16469 (inhibit-read-only t))
16470 (unless (memq buf org-agenda-undo-has-started-in)
16471 (push buf org-agenda-undo-has-started-in)
16472 (make-local-variable 'pending-undo-list)
16473 (undo-start))
16474 (while (and pending-undo-list
16475 (listp pending-undo-list)
16476 (not (car pending-undo-list)))
16477 (pop pending-undo-list))
16478 (undo-more 1))))))
16479 (goto-line line)
16480 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
16482 (defun org-verify-change-for-undo (l1 l2)
16483 "Verify that a real change occurred between the undo lists L1 and L2."
16484 (while (and l1 (listp l1) (null (car l1))) (pop l1))
16485 (while (and l2 (listp l2) (null (car l2))) (pop l2))
16486 (not (eq l1 l2)))
16488 ;;; Agenda dispatch
16490 (defvar org-agenda-restrict nil)
16491 (defvar org-agenda-restrict-begin (make-marker))
16492 (defvar org-agenda-restrict-end (make-marker))
16493 (defvar org-agenda-last-dispatch-buffer nil)
16495 ;;;###autoload
16496 (defun org-agenda (arg)
16497 "Dispatch agenda commands to collect entries to the agenda buffer.
16498 Prompts for a character to select a command. Any prefix arg will be passed
16499 on to the selected command. The default selections are:
16501 a Call `org-agenda-list' to display the agenda for current day or week.
16502 t Call `org-todo-list' to display the global todo list.
16503 T Call `org-todo-list' to display the global todo list, select only
16504 entries with a specific TODO keyword (the user gets a prompt).
16505 m Call `org-tags-view' to display headlines with tags matching
16506 a condition (the user is prompted for the condition).
16507 M Like `m', but select only TODO entries, no ordinary headlines.
16508 L Create a timeline for the current buffer.
16509 e Export views to associated files.
16511 More commands can be added by configuring the variable
16512 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
16513 searches can be pre-defined in this way.
16515 If the current buffer is in Org-mode and visiting a file, you can also
16516 first press `1' to indicate that the agenda should be temporarily (until the
16517 next use of \\[org-agenda]) restricted to the current file."
16518 (interactive "P")
16519 (catch 'exit
16520 (let* ((buf (current-buffer))
16521 (bfn (buffer-file-name (buffer-base-buffer)))
16522 (restrict-ok (and bfn (org-mode-p)))
16523 (custom org-agenda-custom-commands)
16524 c entry key type match lprops)
16525 ;; Turn off restriction
16526 (put 'org-agenda-files 'org-restrict nil)
16527 (setq org-agenda-restrict nil)
16528 (move-marker org-agenda-restrict-begin nil)
16529 (move-marker org-agenda-restrict-end nil)
16530 ;; Delete old local properties
16531 (put 'org-agenda-redo-command 'org-lprops nil)
16532 ;; Remember where this call originated
16533 (setq org-agenda-last-dispatch-buffer (current-buffer))
16534 (save-window-excursion
16535 (delete-other-windows)
16536 (switch-to-buffer-other-window " *Agenda Commands*")
16537 (erase-buffer)
16538 (insert (eval-when-compile
16539 (let ((header
16540 "Press key for an agenda command:
16541 -------------------------------- C Configure custom agenda commands
16542 a Agenda for current week or day e Export agenda views
16543 t List of all TODO entries T Entries with special TODO kwd
16544 m Match a TAGS query M Like m, but only TODO entries
16545 L Timeline for current buffer # List stuck projects (!=configure)
16547 (start 0))
16548 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
16549 (setq start (match-end 0))
16550 (add-text-properties (match-beginning 2) (match-end 2)
16551 '(face bold) header))
16552 header)))
16553 (while (setq entry (pop custom))
16554 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
16555 (insert (format "\n%-4s%-14s: %s"
16556 (org-add-props (copy-sequence key)
16557 '(face bold))
16558 (cond
16559 ((stringp type) type)
16560 ((eq type 'agenda) "Agenda for current week or day")
16561 ((eq type 'alltodo) "List of all TODO entries")
16562 ((eq type 'stuck) "List of stuck projects")
16563 ((eq type 'todo) "TODO keyword")
16564 ((eq type 'tags) "Tags query")
16565 ((eq type 'tags-todo) "Tags (TODO)")
16566 ((eq type 'tags-tree) "Tags tree")
16567 ((eq type 'todo-tree) "TODO kwd tree")
16568 ((eq type 'occur-tree) "Occur tree")
16569 ((functionp type) (symbol-name type))
16570 (t "???"))
16571 (if (stringp match)
16572 (org-add-props match nil 'face 'org-warning)
16573 (format "set of %d commands" (length match))))))
16574 (if restrict-ok
16575 (insert "\n"
16576 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
16577 (goto-char (point-min))
16578 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
16579 (message "Press key for agenda command%s"
16580 (if restrict-ok ", or [1] or [0] to restrict" ""))
16581 (setq c (read-char-exclusive))
16582 (message "")
16583 (when (memq c '(?L ?1 ?0))
16584 (if restrict-ok
16585 (put 'org-agenda-files 'org-restrict (list bfn))
16586 (error "Cannot restrict agenda to current buffer"))
16587 (with-current-buffer " *Agenda Commands*"
16588 (goto-char (point-max))
16589 (delete-region (point-at-bol) (point))
16590 (goto-char (point-min)))
16591 (when (eq c ?0)
16592 (setq org-agenda-restrict t)
16593 (with-current-buffer buf
16594 (if (org-region-active-p)
16595 (progn
16596 (move-marker org-agenda-restrict-begin (region-beginning))
16597 (move-marker org-agenda-restrict-end (region-end)))
16598 (save-excursion
16599 (org-back-to-heading t)
16600 (move-marker org-agenda-restrict-begin (point))
16601 (move-marker org-agenda-restrict-end
16602 (progn (org-end-of-subtree t)))))))
16603 (unless (eq c ?L)
16604 (message "Press key for agenda command%s"
16605 (if restrict-ok " (restricted to current file)" ""))
16606 (setq c (read-char-exclusive)))
16607 (message "")))
16608 (require 'calendar) ; FIXME: can we avoid this for some commands?
16609 ;; For example the todo list should not need it (but does...)
16610 (cond
16611 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
16612 (if (symbolp (nth 1 entry))
16613 (progn
16614 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
16615 lprops (nth 3 entry))
16616 (put 'org-agenda-redo-command 'org-lprops lprops)
16617 (cond
16618 ((eq type 'agenda)
16619 (org-let lprops '(org-agenda-list current-prefix-arg)))
16620 ((eq type 'alltodo)
16621 (org-let lprops '(org-todo-list current-prefix-arg)))
16622 ((eq type 'stuck)
16623 (org-let lprops '(org-agenda-list-stuck-projects
16624 current-prefix-arg)))
16625 ((eq type 'tags)
16626 (org-let lprops '(org-tags-view current-prefix-arg match)))
16627 ((eq type 'tags-todo)
16628 (org-let lprops '(org-tags-view '(4) match)))
16629 ((eq type 'todo)
16630 (org-let lprops '(org-todo-list match)))
16631 ((eq type 'tags-tree)
16632 (org-check-for-org-mode)
16633 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
16634 ((eq type 'todo-tree)
16635 (org-check-for-org-mode)
16636 (org-let lprops
16637 '(org-occur (concat "^" outline-regexp "[ \t]*"
16638 (regexp-quote match) "\\>"))))
16639 ((eq type 'occur-tree)
16640 (org-check-for-org-mode)
16641 (org-let lprops '(org-occur match)))
16642 ((fboundp type)
16643 (org-let lprops '(funcall type match)))
16644 (t (error "Invalid custom agenda command type %s" type))))
16645 (org-run-agenda-series (nth 1 entry) (cddr entry))))
16646 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
16647 ((equal c ?a) (call-interactively 'org-agenda-list))
16648 ((equal c ?t) (call-interactively 'org-todo-list))
16649 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
16650 ((equal c ?m) (call-interactively 'org-tags-view))
16651 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
16652 ((equal c ?e) (call-interactively 'org-store-agenda-views))
16653 ((equal c ?L)
16654 (unless restrict-ok
16655 (error "This is not an Org-mode file"))
16656 (org-call-with-arg 'org-timeline arg))
16657 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
16658 ((equal c ?!) (customize-variable 'org-stuck-projects))
16659 (t (error "Invalid key"))))))
16661 (defun org-run-agenda-series (name series)
16662 (org-prepare-agenda name)
16663 (let* ((org-agenda-multi t)
16664 (redo (list 'org-run-agenda-series name (list 'quote series)))
16665 (cmds (car series))
16666 (gprops (nth 1 series))
16667 match ;; The byte compiler incorrectly complains about this. Keep it!
16668 cmd type lprops)
16669 (while (setq cmd (pop cmds))
16670 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
16671 (cond
16672 ((eq type 'agenda)
16673 (org-let2 gprops lprops
16674 '(call-interactively 'org-agenda-list)))
16675 ((eq type 'alltodo)
16676 (org-let2 gprops lprops
16677 '(call-interactively 'org-todo-list)))
16678 ((eq type 'stuck)
16679 (org-let2 gprops lprops
16680 '(call-interactively 'org-agenda-list-stuck-projects)))
16681 ((eq type 'tags)
16682 (org-let2 gprops lprops
16683 '(org-tags-view current-prefix-arg match)))
16684 ((eq type 'tags-todo)
16685 (org-let2 gprops lprops
16686 '(org-tags-view '(4) match)))
16687 ((eq type 'todo)
16688 (org-let2 gprops lprops
16689 '(org-todo-list match)))
16690 ((fboundp type)
16691 (org-let2 gprops lprops
16692 '(funcall type match)))
16693 (t (error "Invalid type in command series"))))
16694 (widen)
16695 (setq org-agenda-redo-command redo)
16696 (goto-char (point-min)))
16697 (org-finalize-agenda))
16699 ;;;###autoload
16700 (defmacro org-batch-agenda (cmd-key &rest parameters)
16701 "Run an agenda command in batch mode and send the result to STDOUT.
16702 If CMD-KEY is a string of length 1, it is used as a key in
16703 `org-agenda-custom-commands' and triggers this command. If it is a
16704 longer string is is used as a tags/todo match string.
16705 Paramters are alternating variable names and values that will be bound
16706 before running the agenda command."
16707 (let (pars)
16708 (while parameters
16709 (push (list (pop parameters) (if parameters (pop parameters))) pars))
16710 (if (> (length cmd-key) 1)
16711 (eval (list 'let (nreverse pars)
16712 (list 'org-tags-view nil cmd-key)))
16713 (flet ((read-char-exclusive () (string-to-char cmd-key)))
16714 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
16715 (set-buffer "*Org Agenda*")
16716 (princ (org-encode-for-stdout (buffer-string)))))
16718 (defun org-encode-for-stdout (string)
16719 (if (fboundp 'encode-coding-string)
16720 (encode-coding-string string buffer-file-coding-system)
16721 string))
16723 (defvar org-agenda-info nil)
16725 ;;;###autoload
16726 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
16727 "Run an agenda command in batch mode and send the result to STDOUT.
16728 If CMD-KEY is a string of length 1, it is used as a key in
16729 `org-agenda-custom-commands' and triggers this command. If it is a
16730 longer string is is used as a tags/todo match string.
16731 Paramters are alternating variable names and values that will be bound
16732 before running the agenda command.
16734 The output gives a line for each selected agenda item. Each
16735 item is a list of comma-separated values, like this:
16737 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
16739 category The category of the item
16740 head The headline, without TODO kwd, TAGS and PRIORITY
16741 type The type of the agenda entry, can be
16742 todo selected in TODO match
16743 tagsmatch selected in tags match
16744 diary imported from diary
16745 deadline a deadline on given date
16746 scheduled scheduled on given date
16747 timestamp entry has timestamp on given date
16748 closed entry was closed on given date
16749 upcoming-deadline warning about deadline
16750 past-scheduled forwarded scheduled item
16751 block entry has date block including g. date
16752 todo The todo keyword, if any
16753 tags All tags including inherited ones, separated by colons
16754 date The relevant date, like 2007-2-14
16755 time The time, like 15:00-16:50
16756 extra Sting with extra planning info
16757 priority-l The priority letter if any was given
16758 priority-n The computed numerical priority
16759 agenda-day The day in the agenda where this is listed"
16761 (let (pars)
16762 (while parameters
16763 (push (list (pop parameters) (if parameters (pop parameters))) pars))
16764 (push (list 'org-agenda-remove-tags t) pars)
16765 (if (> (length cmd-key) 1)
16766 (eval (list 'let (nreverse pars)
16767 (list 'org-tags-view nil cmd-key)))
16768 (flet ((read-char-exclusive () (string-to-char cmd-key)))
16769 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
16770 (set-buffer "*Org Agenda*")
16771 (let* ((lines (org-split-string (buffer-string) "\n"))
16772 line)
16773 (while (setq line (pop lines))
16774 (catch 'next
16775 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
16776 (setq org-agenda-info
16777 (org-fix-agenda-info (text-properties-at 0 line)))
16778 (princ
16779 (org-encode-for-stdout
16780 (mapconcat 'org-agenda-export-csv-mapper
16781 '(org-category txt type todo tags date time-of-day extra
16782 priority-letter priority agenda-day)
16783 ",")))
16784 (princ "\n"))))))
16786 (defun org-fix-agenda-info (props)
16787 "FIXME"
16788 (let (tmp re)
16789 (when (setq tmp (plist-get props 'tags))
16790 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
16791 (when (setq tmp (plist-get props 'date))
16792 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
16793 (let ((calendar-date-display-form '(year "-" month "-" day)))
16794 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
16796 (setq tmp (calendar-date-string tmp)))
16797 (setq props (plist-put props 'date tmp)))
16798 (when (setq tmp (plist-get props 'day))
16799 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
16800 (let ((calendar-date-display-form '(year "-" month "-" day)))
16801 (setq tmp (calendar-date-string tmp)))
16802 (setq props (plist-put props 'day tmp))
16803 (setq props (plist-put props 'agenda-day tmp)))
16804 (when (setq tmp (plist-get props 'txt))
16805 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
16806 (plist-put props 'priority-letter (match-string 1 tmp))
16807 (setq tmp (replace-match "" t t tmp)))
16808 (when (and (setq re (plist-get props 'org-todo-regexp))
16809 (setq re (concat "\\`\\.*" re " ?"))
16810 (string-match re tmp))
16811 (plist-put props 'todo (match-string 1 tmp))
16812 (setq tmp (replace-match "" t t tmp)))
16813 (plist-put props 'txt tmp)))
16814 props)
16816 (defun org-agenda-export-csv-mapper (prop)
16817 (let ((res (plist-get org-agenda-info prop)))
16818 (setq res
16819 (cond
16820 ((not res) "")
16821 ((stringp res) res)
16822 (t (prin1-to-string res))))
16823 (while (string-match "," res)
16824 (setq res (replace-match ";" t t res)))
16825 (org-trim res)))
16828 ;;;###autoload
16829 (defun org-store-agenda-views (&rest parameters)
16830 (interactive)
16831 (eval (list 'org-batch-store-agenda-views)))
16833 (defvar org-agenda-buffer-name)
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 (org-last 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*")
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 (kill-buffer org-agenda-buffer-name)))))
16863 (defun org-write-agenda (file &optional nosettings)
16864 "Write the current buffer (an agenda view) as a file.
16865 Depending on the extension of the file name, plain text (.txt),
16866 HTML (.html or .htm) or Postscript (.ps) is produced.
16867 If NOSETTINGS is given, do not scope the settings of
16868 `org-agenda-exporter-settings' into the export commands. This is used when
16869 the settings have already been scoped and we do not wish to overrule other,
16870 higher priority settings."
16871 (interactive "FWrite agenda to file: ")
16872 (if (not (file-writable-p file))
16873 (error "Cannot write agenda to file %s" file))
16874 (cond
16875 ((string-match "\\.html?\\'" file) (require 'htmlize))
16876 ((string-match "\\.ps\\'" file) (require 'ps-print)))
16877 (org-let (if nosettings nil org-agenda-exporter-settings)
16878 '(save-excursion
16879 (save-window-excursion
16880 (cond
16881 ((string-match "\\.html?\\'" file)
16882 (set-buffer (htmlize-buffer (current-buffer)))
16884 (when (and org-agenda-export-html-style
16885 (string-match "<style>" org-agenda-export-html-style))
16886 ;; replace <style> section with org-agenda-export-html-style
16887 (goto-char (point-min))
16888 (kill-region (- (search-forward "<style") 6)
16889 (search-forward "</style>"))
16890 (insert org-agenda-export-html-style))
16891 (write-file file)
16892 (kill-buffer (current-buffer))
16893 (message "HTML written to %s" file))
16894 ((string-match "\\.ps\\'" file)
16895 (ps-print-buffer-with-faces file)
16896 (message "Postscript written to %s" file))
16898 (let ((bs (buffer-string)))
16899 (find-file file)
16900 (insert bs)
16901 (save-buffer 0)
16902 (kill-buffer (current-buffer))
16903 (message "Plain text written to %s" file))))))
16904 (set-buffer org-agenda-buffer-name)))
16906 (defmacro org-no-read-only (&rest body)
16907 "Inhibit read-only for BODY."
16908 `(let ((inhibit-read-only t)) ,@body))
16910 (defun org-check-for-org-mode ()
16911 "Make sure current buffer is in org-mode. Error if not."
16912 (or (org-mode-p)
16913 (error "Cannot execute org-mode agenda command on buffer in %s."
16914 major-mode)))
16916 (defun org-fit-agenda-window ()
16917 "Fit the window to the buffer size."
16918 (and (memq org-agenda-window-setup '(reorganize-frame))
16919 (fboundp 'fit-window-to-buffer)
16920 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
16921 (/ (frame-height) 2))))
16923 ;;; Agenda file list
16925 (defun org-agenda-files (&optional unrestricted)
16926 "Get the list of agenda files.
16927 Optional UNRESTRICTED means return the full list even if a restriction
16928 is currently in place."
16929 (cond
16930 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16931 ((stringp org-agenda-files) (org-read-agenda-file-list))
16932 ((listp org-agenda-files) org-agenda-files)
16933 (t (error "Invalid value of `org-agenda-files'"))))
16935 (defun org-edit-agenda-file-list ()
16936 "Edit the list of agenda files.
16937 Depending on setup, this either uses customize to edit the variable
16938 `org-agenda-files', or it visits the file that is holding the list. In the
16939 latter case, the buffer is set up in a way that saving it automatically kills
16940 the buffer and restores the previous window configuration."
16941 (interactive)
16942 (if (stringp org-agenda-files)
16943 (let ((cw (current-window-configuration)))
16944 (find-file org-agenda-files)
16945 (org-set-local 'org-window-configuration cw)
16946 (org-add-hook 'after-save-hook
16947 (lambda ()
16948 (set-window-configuration
16949 (prog1 org-window-configuration
16950 (kill-buffer (current-buffer))))
16951 (org-install-agenda-files-menu)
16952 (message "New agenda file list installed"))
16953 nil 'local)
16954 (message (substitute-command-keys
16955 "Edit list and finish with \\[save-buffer]")))
16956 (customize-variable 'org-agenda-files)))
16958 (defun org-store-new-agenda-file-list (list)
16959 "Set new value for the agenda file list and save it correcly."
16960 (if (stringp org-agenda-files)
16961 (let ((f org-agenda-files) b)
16962 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
16963 (with-temp-file f
16964 (insert (mapconcat 'identity list "\n") "\n")))
16965 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
16966 (setq org-agenda-files list)
16967 (customize-save-variable 'org-agenda-files org-agenda-files))))
16969 (defun org-read-agenda-file-list ()
16970 "Read the list of agenda files from a file."
16971 (when (stringp org-agenda-files)
16972 (with-temp-buffer
16973 (insert-file-contents org-agenda-files)
16974 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
16977 ;;;###autoload
16978 (defun org-cycle-agenda-files ()
16979 "Cycle through the files in `org-agenda-files'.
16980 If the current buffer visits an agenda file, find the next one in the list.
16981 If the current buffer does not, find the first agenda file."
16982 (interactive)
16983 (let* ((fs (org-agenda-files t))
16984 (files (append fs (list (car fs))))
16985 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16986 file)
16987 (unless files (error "No agenda files"))
16988 (catch 'exit
16989 (while (setq file (pop files))
16990 (if (equal (file-truename file) tcf)
16991 (when (car files)
16992 (find-file (car files))
16993 (throw 'exit t))))
16994 (find-file (car fs)))
16995 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
16997 (defun org-agenda-file-to-front (&optional to-end)
16998 "Move/add the current file to the top of the agenda file list.
16999 If the file is not present in the list, it is added to the front. If it is
17000 present, it is moved there. With optional argument TO-END, add/move to the
17001 end of the list."
17002 (interactive "P")
17003 (let ((file-alist (mapcar (lambda (x)
17004 (cons (file-truename x) x))
17005 (org-agenda-files t)))
17006 (ctf (file-truename buffer-file-name))
17007 x had)
17008 (setq x (assoc ctf file-alist) had x)
17010 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17011 (if to-end
17012 (setq file-alist (append (delq x file-alist) (list x)))
17013 (setq file-alist (cons x (delq x file-alist))))
17014 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17015 (org-install-agenda-files-menu)
17016 (message "File %s to %s of agenda file list"
17017 (if had "moved" "added") (if to-end "end" "front"))))
17019 (defun org-remove-file (&optional file)
17020 "Remove current file from the list of files in variable `org-agenda-files'.
17021 These are the files which are being checked for agenda entries.
17022 Optional argument FILE means, use this file instead of the current."
17023 (interactive)
17024 (let* ((file (or file buffer-file-name))
17025 (true-file (file-truename file))
17026 (afile (abbreviate-file-name file))
17027 (files (delq nil (mapcar
17028 (lambda (x)
17029 (if (equal true-file
17030 (file-truename x))
17031 nil x))
17032 (org-agenda-files t)))))
17033 (if (not (= (length files) (length (org-agenda-files t))))
17034 (progn
17035 (org-store-new-agenda-file-list files)
17036 (org-install-agenda-files-menu)
17037 (message "Removed file: %s" afile))
17038 (message "File was not in list: %s" afile))))
17040 (defun org-file-menu-entry (file)
17041 (vector file (list 'find-file file) t))
17043 (defun org-check-agenda-file (file)
17044 "Make sure FILE exists. If not, ask user what to do."
17045 (when (not (file-exists-p file))
17046 (message "non-existent file %s. [R]emove from list or [A]bort?"
17047 (abbreviate-file-name file))
17048 (let ((r (downcase (read-char-exclusive))))
17049 (cond
17050 ((equal r ?r)
17051 (org-remove-file file)
17052 (throw 'nextfile t))
17053 (t (error "Abort"))))))
17055 ;;; Agenda prepare and finalize
17057 (defvar org-agenda-multi nil) ; dynammically scoped
17058 (defvar org-agenda-buffer-name "*Org Agenda*")
17059 (defvar org-pre-agenda-window-conf nil)
17060 (defvar org-agenda-name nil)
17061 (defun org-prepare-agenda (&optional name)
17062 (setq org-todo-keywords-for-agenda nil)
17063 (setq org-done-keywords-for-agenda nil)
17064 (if org-agenda-multi
17065 (progn
17066 (setq buffer-read-only nil)
17067 (goto-char (point-max))
17068 (unless (bobp)
17069 (insert "\n" (make-string (window-width) ?=) "\n"))
17070 (narrow-to-region (point) (point-max)))
17071 (org-agenda-maybe-reset-markers 'force)
17072 (org-prepare-agenda-buffers (org-agenda-files))
17073 (setq org-todo-keywords-for-agenda
17074 (org-uniquify org-todo-keywords-for-agenda))
17075 (setq org-done-keywords-for-agenda
17076 (org-uniquify org-done-keywords-for-agenda))
17077 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
17078 (awin (get-buffer-window abuf)))
17079 (cond
17080 ((equal (current-buffer) abuf) nil)
17081 (awin (select-window awin))
17082 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
17083 ((equal org-agenda-window-setup 'current-window)
17084 (switch-to-buffer abuf))
17085 ((equal org-agenda-window-setup 'other-window)
17086 (switch-to-buffer-other-window abuf))
17087 ((equal org-agenda-window-setup 'other-frame)
17088 (switch-to-buffer-other-frame abuf))
17089 ((equal org-agenda-window-setup 'reorganize-frame)
17090 (delete-other-windows)
17091 (switch-to-buffer-other-window abuf))))
17092 (setq buffer-read-only nil)
17093 (erase-buffer)
17094 (org-agenda-mode)
17095 (and name (not org-agenda-name)
17096 (org-set-local 'org-agenda-name name)))
17097 (setq buffer-read-only nil))
17099 (defun org-finalize-agenda ()
17100 "Finishing touch for the agenda buffer, called just before displaying it."
17101 (unless org-agenda-multi
17102 (save-excursion
17103 (let ((inhibit-read-only t))
17104 (goto-char (point-min))
17105 (while (org-activate-bracket-links (point-max))
17106 (add-text-properties (match-beginning 0) (match-end 0)
17107 '(face org-link)))
17108 (org-agenda-align-tags)
17109 (unless org-agenda-with-colors
17110 (remove-text-properties (point-min) (point-max) '(face nil))))
17111 (if (and (boundp 'org-overriding-columns-format)
17112 org-overriding-columns-format)
17113 (org-set-local 'org-overriding-columns-format
17114 org-overriding-columns-format))
17115 (if (and (boundp 'org-agenda-view-columns-initially)
17116 org-agenda-view-columns-initially)
17117 (org-agenda-columns))
17118 (run-hooks 'org-finalize-agenda-hook))))
17120 (defun org-prepare-agenda-buffers (files)
17121 "Create buffers for all agenda files, protect archived trees and comments."
17122 (interactive)
17123 (let ((pa '(:org-archived t))
17124 (pc '(:org-comment t))
17125 (pall '(:org-archived t :org-comment t))
17126 (inhibit-read-only t)
17127 (rea (concat ":" org-archive-tag ":"))
17128 bmp file re)
17129 (save-excursion
17130 (save-restriction
17131 (while (setq file (pop files))
17132 (org-check-agenda-file file)
17133 (set-buffer (org-get-agenda-file-buffer file))
17134 (widen)
17135 (setq bmp (buffer-modified-p))
17136 (setq org-todo-keywords-for-agenda
17137 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17138 (setq org-done-keywords-for-agenda
17139 (append org-done-keywords-for-agenda org-done-keywords))
17140 (save-excursion
17141 (remove-text-properties (point-min) (point-max) pall)
17142 (when org-agenda-skip-archived-trees
17143 (goto-char (point-min))
17144 (while (re-search-forward rea nil t)
17145 (if (org-on-heading-p t)
17146 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17147 (goto-char (point-min))
17148 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
17149 (while (re-search-forward re nil t)
17150 (add-text-properties
17151 (match-beginning 0) (org-end-of-subtree t) pc)))
17152 (set-buffer-modified-p bmp))))))
17154 (defvar org-agenda-skip-function nil
17155 "Function to be called at each match during agenda construction.
17156 If this function returns nil, the current match should not be skipped.
17157 Otherwise, the function must return a position from where the search
17158 should be continued.
17159 This may also be a Lisp form, it will be evaluated.
17160 Never set this variable using `setq' or so, because then it will apply
17161 to all future agenda commands. Instead, bind it with `let' to scope
17162 it dynamically into the agenda-constructing command. A good way to set
17163 it is through options in org-agenda-custom-commands.")
17165 (defun org-agenda-skip ()
17166 "Throw to `:skip' in places that should be skipped.
17167 Also moves point to the end of the skipped region, so that search can
17168 continue from there."
17169 (let ((p (point-at-bol)) to fp)
17170 (and org-agenda-skip-archived-trees
17171 (get-text-property p :org-archived)
17172 (org-end-of-subtree t)
17173 (throw :skip t))
17174 (and (get-text-property p :org-comment)
17175 (org-end-of-subtree t)
17176 (throw :skip t))
17177 (if (equal (char-after p) ?#) (throw :skip t))
17178 (when (and (or (setq fp (functionp org-agenda-skip-function))
17179 (consp org-agenda-skip-function))
17180 (setq to (save-excursion
17181 (save-match-data
17182 (if fp
17183 (funcall org-agenda-skip-function)
17184 (eval org-agenda-skip-function))))))
17185 (goto-char to)
17186 (throw :skip t))))
17188 (defvar org-agenda-markers nil
17189 "List of all currently active markers created by `org-agenda'.")
17190 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
17191 "Creation time of the last agenda marker.")
17193 (defun org-agenda-new-marker (&optional pos)
17194 "Return a new agenda marker.
17195 Org-mode keeps a list of these markers and resets them when they are
17196 no longer in use."
17197 (let ((m (copy-marker (or pos (point)))))
17198 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
17199 (push m org-agenda-markers)
17202 (defun org-agenda-maybe-reset-markers (&optional force)
17203 "Reset markers created by `org-agenda'. But only if they are old enough."
17204 (if (or (and force (not org-agenda-multi))
17205 (> (- (time-to-seconds (current-time))
17206 org-agenda-last-marker-time)
17208 (while org-agenda-markers
17209 (move-marker (pop org-agenda-markers) nil))))
17211 (defvar org-agenda-new-buffers nil
17212 "Buffers created to visit agenda files.")
17214 (defun org-get-agenda-file-buffer (file)
17215 "Get a buffer visiting FILE. If the buffer needs to be created, add
17216 it to the list of buffers which might be released later."
17217 (let ((buf (org-find-base-buffer-visiting file)))
17218 (if buf
17219 buf ; just return it
17220 ;; Make a new buffer and remember it
17221 (setq buf (find-file-noselect file))
17222 (if buf (push buf org-agenda-new-buffers))
17223 buf)))
17225 (defun org-release-buffers (blist)
17226 "Release all buffers in list, asking the user for confirmation when needed.
17227 When a buffer is unmodified, it is just killed. When modified, it is saved
17228 \(if the user agrees) and then killed."
17229 (let (buf file)
17230 (while (setq buf (pop blist))
17231 (setq file (buffer-file-name buf))
17232 (when (and (buffer-modified-p buf)
17233 file
17234 (y-or-n-p (format "Save file %s? " file)))
17235 (with-current-buffer buf (save-buffer)))
17236 (kill-buffer buf))))
17238 (defvar org-category-table nil)
17239 (defun org-get-category-table ()
17240 "Get the table of categories and positions in current buffer."
17241 (let (tbl)
17242 (save-excursion
17243 (save-restriction
17244 (widen)
17245 (goto-char (point-min))
17246 (while (re-search-forward "^#\\+CATEGORY:[ \t]*\\(.*\\)"
17247 nil t)
17248 (push (cons (match-beginning 1)
17249 (org-trim (match-string 1))) tbl))))
17250 tbl))
17252 (defun org-get-category (&optional pos)
17253 "Get the category applying to position POS."
17254 (if (not org-category-table)
17255 (cond
17256 ((null org-category)
17257 (setq org-category
17258 (if buffer-file-name
17259 (file-name-sans-extension
17260 (file-name-nondirectory buffer-file-name))
17261 "???")))
17262 ((symbolp org-category) (symbol-name org-category))
17263 (t org-category))
17264 (let ((tbl org-category-table)
17265 (pos (or pos (point))))
17266 (while (and tbl (> (caar tbl) pos))
17267 (pop tbl))
17268 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
17269 org-category-table))))))
17270 ;;; Agenda timeline
17272 (defun org-timeline (&optional include-all)
17273 "Show a time-sorted view of the entries in the current org file.
17274 Only entries with a time stamp of today or later will be listed. With
17275 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
17276 under the current date.
17277 If the buffer contains an active region, only check the region for
17278 dates."
17279 (interactive "P")
17280 (require 'calendar)
17281 (org-compile-prefix-format 'timeline)
17282 (org-set-sorting-strategy 'timeline)
17283 (let* ((dopast t)
17284 (dotodo include-all)
17285 (doclosed org-agenda-show-log)
17286 (entry buffer-file-name)
17287 (date (calendar-current-date))
17288 (beg (if (org-region-active-p) (region-beginning) (point-min)))
17289 (end (if (org-region-active-p) (region-end) (point-max)))
17290 (day-numbers (org-get-all-dates beg end 'no-ranges
17291 t doclosed ; always include today
17292 org-timeline-show-empty-dates))
17293 (today (time-to-days (current-time)))
17294 (past t)
17295 args
17296 s e rtn d emptyp)
17297 (setq org-agenda-redo-command
17298 (list 'progn
17299 (list 'switch-to-buffer-other-window (current-buffer))
17300 (list 'org-timeline (list 'quote include-all))))
17301 (if (not dopast)
17302 ;; Remove past dates from the list of dates.
17303 (setq day-numbers (delq nil (mapcar (lambda(x)
17304 (if (>= x today) x nil))
17305 day-numbers))))
17306 (org-prepare-agenda (concat "Timeline "
17307 (file-name-nondirectory buffer-file-name)))
17308 (if doclosed (push :closed args))
17309 (push :timestamp args)
17310 (push :sexp args)
17311 (if dotodo (push :todo args))
17312 (while (setq d (pop day-numbers))
17313 (if (and (listp d) (eq (car d) :omitted))
17314 (progn
17315 (setq s (point))
17316 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
17317 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
17318 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
17319 (if (and (>= d today)
17320 dopast
17321 past)
17322 (progn
17323 (setq past nil)
17324 (insert (make-string 79 ?-) "\n")))
17325 (setq date (calendar-gregorian-from-absolute d))
17326 (setq s (point))
17327 (setq rtn (and (not emptyp)
17328 (apply 'org-agenda-get-day-entries
17329 entry date args)))
17330 (if (or rtn (equal d today) org-timeline-show-empty-dates)
17331 (progn
17332 (insert (calendar-day-name date) " "
17333 (number-to-string (extract-calendar-day date)) " "
17334 (calendar-month-name (extract-calendar-month date)) " "
17335 (number-to-string (extract-calendar-year date)) "\n")
17336 ; FIXME: this gives a timezone problem
17337 ; (insert (format-time-string org-agenda-date-format
17338 ; (calendar-time-from-absolute d 0))
17339 ; "\n")
17340 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
17341 (put-text-property s (1- (point)) 'org-date-line t)
17342 (if (equal d today)
17343 (put-text-property s (1- (point)) 'org-today t))
17344 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
17345 (put-text-property s (1- (point)) 'day d)))))
17346 (goto-char (point-min))
17347 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
17348 (point-min)))
17349 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
17350 (org-finalize-agenda)
17351 (setq buffer-read-only t)))
17353 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
17354 "Return a list of all relevant day numbers from BEG to END buffer positions.
17355 If NO-RANGES is non-nil, include only the start and end dates of a range,
17356 not every single day in the range. If FORCE-TODAY is non-nil, make
17357 sure that TODAY is included in the list. If INACTIVE is non-nil, also
17358 inactive time stamps (those in square brackets) are included.
17359 When EMPTY is non-nil, also include days without any entries."
17360 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
17361 dates dates1 date day day1 day2 ts1 ts2)
17362 (if force-today
17363 (setq dates (list (time-to-days (current-time)))))
17364 (save-excursion
17365 (goto-char beg)
17366 (while (re-search-forward re end t)
17367 (setq day (time-to-days (org-time-string-to-time
17368 (substring (match-string 1) 0 10))))
17369 (or (memq day dates) (push day dates)))
17370 (unless no-ranges
17371 (goto-char beg)
17372 (while (re-search-forward org-tr-regexp end t)
17373 (setq ts1 (substring (match-string 1) 0 10)
17374 ts2 (substring (match-string 2) 0 10)
17375 day1 (time-to-days (org-time-string-to-time ts1))
17376 day2 (time-to-days (org-time-string-to-time ts2)))
17377 (while (< (setq day1 (1+ day1)) day2)
17378 (or (memq day1 dates) (push day1 dates)))))
17379 (setq dates (sort dates '<))
17380 (when empty
17381 (while (setq day (pop dates))
17382 (setq day2 (car dates))
17383 (push day dates1)
17384 (when (and day2 empty)
17385 (if (or (eq empty t)
17386 (and (numberp empty) (<= (- day2 day) empty)))
17387 (while (< (setq day (1+ day)) day2)
17388 (push (list day) dates1))
17389 (push (cons :omitted (- day2 day)) dates1))))
17390 (setq dates (nreverse dates1)))
17391 dates)))
17393 ;;; Agenda Daily/Weekly
17395 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
17396 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
17397 (defvar org-agenda-last-arguments nil
17398 "The arguments of the previous call to org-agenda")
17399 (defvar org-starting-day nil) ; local variable in the agenda buffer
17400 (defvar org-agenda-span nil) ; local variable in the agenda buffer
17401 (defvar org-include-all-loc nil) ; local variable
17404 ;;;###autoload
17405 (defun org-agenda-list (&optional include-all start-day ndays)
17406 "Produce a weekly view from all files in variable `org-agenda-files'.
17407 The view will be for the current week, but from the overview buffer you
17408 will be able to go to other weeks.
17409 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
17410 also be shown, under the current date.
17411 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
17412 on the days are also shown. See the variable `org-log-done' for how
17413 to turn on logging.
17414 START-DAY defaults to TODAY, or to the most recent match for the weekday
17415 given in `org-agenda-start-on-weekday'.
17416 NDAYS defaults to `org-agenda-ndays'."
17417 (interactive "P")
17418 (setq ndays (or ndays org-agenda-ndays)
17419 start-day (or start-day org-agenda-start-day))
17420 (if org-agenda-overriding-arguments
17421 (setq include-all (car org-agenda-overriding-arguments)
17422 start-day (nth 1 org-agenda-overriding-arguments)
17423 ndays (nth 2 org-agenda-overriding-arguments)))
17424 (if (stringp start-day)
17425 ;; Convert to an absolute day number
17426 (setq start-day (time-to-days (org-read-date nil t start-day))))
17427 (setq org-agenda-last-arguments (list include-all start-day ndays))
17428 (org-compile-prefix-format 'agenda)
17429 (org-set-sorting-strategy 'agenda)
17430 (require 'calendar)
17431 (let* ((org-agenda-start-on-weekday
17432 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
17433 org-agenda-start-on-weekday nil))
17434 (thefiles (org-agenda-files))
17435 (files thefiles)
17436 (today (time-to-days (current-time)))
17437 (sd (or start-day today))
17438 (start (if (or (null org-agenda-start-on-weekday)
17439 (< org-agenda-ndays 7))
17441 (let* ((nt (calendar-day-of-week
17442 (calendar-gregorian-from-absolute sd)))
17443 (n1 org-agenda-start-on-weekday)
17444 (d (- nt n1)))
17445 (- sd (+ (if (< d 0) 7 0) d)))))
17446 (day-numbers (list start))
17447 (inhibit-redisplay (not debug-on-error))
17448 s e rtn rtnall file date d start-pos end-pos todayp nd)
17449 (setq org-agenda-redo-command
17450 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
17451 ;; Make the list of days
17452 (setq ndays (or ndays org-agenda-ndays)
17453 nd ndays)
17454 (while (> ndays 1)
17455 (push (1+ (car day-numbers)) day-numbers)
17456 (setq ndays (1- ndays)))
17457 (setq day-numbers (nreverse day-numbers))
17458 (org-prepare-agenda "Day/Week")
17459 (org-set-local 'org-starting-day (car day-numbers))
17460 (org-set-local 'org-include-all-loc include-all)
17461 (org-set-local 'org-agenda-span
17462 (org-agenda-ndays-to-span nd))
17463 (when (and (or include-all org-agenda-include-all-todo)
17464 (member today day-numbers))
17465 (setq files thefiles
17466 rtnall nil)
17467 (while (setq file (pop files))
17468 (catch 'nextfile
17469 (org-check-agenda-file file)
17470 (setq date (calendar-gregorian-from-absolute today)
17471 rtn (org-agenda-get-day-entries
17472 file date :todo))
17473 (setq rtnall (append rtnall rtn))))
17474 (when rtnall
17475 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
17476 (add-text-properties (point-min) (1- (point))
17477 (list 'face 'org-agenda-structure))
17478 (insert (org-finalize-agenda-entries rtnall) "\n")))
17479 (setq s (point))
17480 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
17481 "-agenda:\n")
17482 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
17483 'org-date-line t))
17484 (while (setq d (pop day-numbers))
17485 (setq date (calendar-gregorian-from-absolute d)
17486 s (point))
17487 (if (or (setq todayp (= d today))
17488 (and (not start-pos) (= d sd)))
17489 (setq start-pos (point))
17490 (if (and start-pos (not end-pos))
17491 (setq end-pos (point))))
17492 (setq files thefiles
17493 rtnall nil)
17494 (while (setq file (pop files))
17495 (catch 'nextfile
17496 (org-check-agenda-file file)
17497 (if org-agenda-show-log
17498 (setq rtn (org-agenda-get-day-entries
17499 file date
17500 :deadline :scheduled :timestamp :sexp :closed))
17501 (setq rtn (org-agenda-get-day-entries
17502 file date
17503 :deadline :scheduled :sexp :timestamp)))
17504 (setq rtnall (append rtnall rtn))))
17505 (if org-agenda-include-diary
17506 (progn
17507 (require 'diary-lib)
17508 (setq rtn (org-get-entries-from-diary date))
17509 (setq rtnall (append rtnall rtn))))
17510 (if (or rtnall org-agenda-show-all-dates)
17511 (progn
17512 (insert (format "%-9s %2d %s %4d\n"
17513 (calendar-day-name date)
17514 (extract-calendar-day date)
17515 (calendar-month-name (extract-calendar-month date))
17516 (extract-calendar-year date)))
17517 ; FIXME: this gives a timezone problem
17518 ; (insert (format-time-string org-agenda-date-format
17519 ; (calendar-time-from-absolute d 0)) "\n")
17520 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
17521 (put-text-property s (1- (point)) 'org-date-line t)
17522 (if todayp (put-text-property s (1- (point)) 'org-today t))
17523 (if rtnall (insert
17524 (org-finalize-agenda-entries
17525 (org-agenda-add-time-grid-maybe
17526 rtnall nd todayp))
17527 "\n"))
17528 (put-text-property s (1- (point)) 'day d))))
17529 (goto-char (point-min))
17530 (org-fit-agenda-window)
17531 (unless (and (pos-visible-in-window-p (point-min))
17532 (pos-visible-in-window-p (point-max)))
17533 (goto-char (1- (point-max)))
17534 (recenter -1)
17535 (if (not (pos-visible-in-window-p (or start-pos 1)))
17536 (progn
17537 (goto-char (or start-pos 1))
17538 (recenter 1))))
17539 (goto-char (or start-pos 1))
17540 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
17541 (org-finalize-agenda)
17542 (setq buffer-read-only t)
17543 (message "")))
17545 (defun org-agenda-ndays-to-span (n)
17546 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
17548 ;;; Agenda TODO list
17550 (defvar org-select-this-todo-keyword nil)
17551 (defvar org-last-arg nil)
17553 ;;;###autoload
17554 (defun org-todo-list (arg)
17555 "Show all TODO entries from all agenda file in a single list.
17556 The prefix arg can be used to select a specific TODO keyword and limit
17557 the list to these. When using \\[universal-argument], you will be prompted
17558 for a keyword. A numeric prefix directly selects the Nth keyword in
17559 `org-todo-keywords-1'."
17560 (interactive "P")
17561 (require 'calendar)
17562 (org-compile-prefix-format 'todo)
17563 (org-set-sorting-strategy 'todo)
17564 (org-prepare-agenda "TODO")
17565 (let* ((today (time-to-days (current-time)))
17566 (date (calendar-gregorian-from-absolute today))
17567 (kwds org-todo-keywords-for-agenda)
17568 (completion-ignore-case t)
17569 (org-select-this-todo-keyword
17570 (if (stringp arg) arg
17571 (and arg (integerp arg) (> arg 0)
17572 (nth (1- arg) kwds))))
17573 rtn rtnall files file pos)
17574 (when (equal arg '(4))
17575 (setq org-select-this-todo-keyword
17576 (completing-read "Keyword (or KWD1|K2D2|...): "
17577 (mapcar 'list kwds) nil nil)))
17578 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
17579 (org-set-local 'org-last-arg arg)
17580 (setq org-agenda-redo-command
17581 '(org-todo-list (or current-prefix-arg org-last-arg)))
17582 (setq files (org-agenda-files)
17583 rtnall nil)
17584 (while (setq file (pop files))
17585 (catch 'nextfile
17586 (org-check-agenda-file file)
17587 (setq rtn (org-agenda-get-day-entries file date :todo))
17588 (setq rtnall (append rtnall rtn))))
17589 (if org-agenda-overriding-header
17590 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
17591 nil 'face 'org-agenda-structure) "\n")
17592 (insert "Global list of TODO items of type: ")
17593 (add-text-properties (point-min) (1- (point))
17594 (list 'face 'org-agenda-structure))
17595 (setq pos (point))
17596 (insert (or org-select-this-todo-keyword "ALL") "\n")
17597 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
17598 (setq pos (point))
17599 (unless org-agenda-multi
17600 (insert "Available with `N r': (0)ALL")
17601 (let ((n 0) s)
17602 (mapc (lambda (x)
17603 (setq s (format "(%d)%s" (setq n (1+ n)) x))
17604 (if (> (+ (current-column) (string-width s) 1) (frame-width))
17605 (insert "\n "))
17606 (insert " " s))
17607 kwds))
17608 (insert "\n"))
17609 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
17610 (when rtnall
17611 (insert (org-finalize-agenda-entries rtnall) "\n"))
17612 (goto-char (point-min))
17613 (org-fit-agenda-window)
17614 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
17615 (org-finalize-agenda)
17616 (setq buffer-read-only t)))
17618 ;;; Agenda tags match
17620 ;;;###autoload
17621 (defun org-tags-view (&optional todo-only match)
17622 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
17623 The prefix arg TODO-ONLY limits the search to TODO entries."
17624 (interactive "P")
17625 (org-compile-prefix-format 'tags)
17626 (org-set-sorting-strategy 'tags)
17627 (let* ((org-tags-match-list-sublevels
17628 (if todo-only t org-tags-match-list-sublevels))
17629 (completion-ignore-case t)
17630 rtn rtnall files file pos matcher
17631 buffer)
17632 (setq matcher (org-make-tags-matcher match)
17633 match (car matcher) matcher (cdr matcher))
17634 (org-prepare-agenda (concat "TAGS " match))
17635 (setq org-agenda-redo-command
17636 (list 'org-tags-view (list 'quote todo-only)
17637 (list 'if 'current-prefix-arg nil match)))
17638 (setq files (org-agenda-files)
17639 rtnall nil)
17640 (while (setq file (pop files))
17641 (catch 'nextfile
17642 (org-check-agenda-file file)
17643 (setq buffer (if (file-exists-p file)
17644 (org-get-agenda-file-buffer file)
17645 (error "No such file %s" file)))
17646 (if (not buffer)
17647 ;; If file does not exist, merror message to agenda
17648 (setq rtn (list
17649 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
17650 rtnall (append rtnall rtn))
17651 (with-current-buffer buffer
17652 (unless (org-mode-p)
17653 (error "Agenda file %s is not in `org-mode'" file))
17654 (setq org-category-table (org-get-category-table))
17655 (save-excursion
17656 (save-restriction
17657 (if org-agenda-restrict
17658 (narrow-to-region org-agenda-restrict-begin
17659 org-agenda-restrict-end)
17660 (widen))
17661 (setq rtn (org-scan-tags 'agenda matcher todo-only))
17662 (setq rtnall (append rtnall rtn))))))))
17663 (if org-agenda-overriding-header
17664 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
17665 nil 'face 'org-agenda-structure) "\n")
17666 (insert "Headlines with TAGS match: ")
17667 (add-text-properties (point-min) (1- (point))
17668 (list 'face 'org-agenda-structure))
17669 (setq pos (point))
17670 (insert match "\n")
17671 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
17672 (setq pos (point))
17673 (unless org-agenda-multi
17674 (insert "Press `C-u r' to search again with new search string\n"))
17675 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
17676 (when rtnall
17677 (insert (org-finalize-agenda-entries rtnall) "\n"))
17678 (goto-char (point-min))
17679 (org-fit-agenda-window)
17680 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
17681 (org-finalize-agenda)
17682 (setq buffer-read-only t)))
17684 ;;; Agenda Finding stuck projects
17686 (defvar org-agenda-skip-regexp nil
17687 "Regular expression used in skipping subtrees for the agenda.
17688 This is basically a temporary global variable that can be set and then
17689 used by user-defined selections using `org-agenda-skip-function'.")
17691 (defvar org-agenda-overriding-header nil
17692 "When this is set during todo and tags searches, will replace header.")
17694 (defun org-agenda-skip-subtree-when-regexp-matches ()
17695 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
17696 If yes, it returns the end position of this tree, causing agenda commands
17697 to skip this subtree. This is a function that can be put into
17698 `org-agenda-skip-function' for the duration of a command."
17699 (let ((end (save-excursion (org-end-of-subtree t)))
17700 skip)
17701 (save-excursion
17702 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
17703 (and skip end)))
17705 (defun org-agenda-skip-entry-if (&rest conditions)
17706 "Skip entry is any of CONDITIONS is true.
17707 See `org-agenda-skip-if for details."
17708 (org-agenda-skip-if nil conditions))
17709 (defun org-agenda-skip-subtree-if (&rest conditions)
17710 "Skip entry is any of CONDITIONS is true.
17711 See `org-agenda-skip-if for details."
17712 (org-agenda-skip-if t conditions))
17714 (defun org-agenda-skip-if (subtree conditions)
17715 "Checks current entity for CONDITIONS.
17716 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
17717 the entry, i.e. the text before the next heading is checked.
17719 CONDITIONS is a list of symbols, boolean OR is used to combine the results
17720 from different tests. Valid conditions are:
17722 scheduled Check if there is a scheduled cookie
17723 notscheduled Check if there is no scheduled cookie
17724 deadline Check if there is a deadline
17725 notdeadline Check if there is no deadline
17726 regexp Check if regexp matches
17727 notregexp Check if regexp does not match.
17729 The regexp is taken from the conditions list, it must com right after the
17730 `regexp' of `notregexp' element.
17732 If any of these conditions is met, this function returns the end point of
17733 the entity, causing the search to continue from there. This is a function
17734 that can be put into `org-agenda-skip-function' for the duration of a command."
17735 (let (beg end m r)
17736 (org-back-to-heading t)
17737 (setq beg (point)
17738 end (if subtree
17739 (progn (org-end-of-subtree t) (point))
17740 (progn (outline-next-heading) (1- (point)))))
17741 (goto-char beg)
17742 (and
17744 (and (memq 'scheduled conditions)
17745 (re-search-forward org-scheduled-time-regexp end t))
17746 (and (memq 'notscheduled conditions)
17747 (not (re-search-forward org-scheduled-time-regexp end t)))
17748 (and (memq 'deadline conditions)
17749 (re-search-forward org-deadline-time-regexp end t))
17750 (and (memq 'notdeadline conditions)
17751 (not (re-search-forward org-deadline-time-regexp end t)))
17752 (and (setq m (memq 'regexp conditions))
17753 (stringp (setq r (nth 1 m)))
17754 (re-search-forward (nth 1 m) end t))
17755 (and (setq m (memq 'notregexp conditions))
17756 (stringp (setq r (nth 1 m)))
17757 (not (re-search-forward (nth 1 m) end t))))
17758 end)))
17760 (defun org-agenda-list-stuck-projects (&rest ignore)
17761 "Create agenda view for projects that are stuck.
17762 Stuck projects are project that have no next actions. For the definitions
17763 of what a project is and how to check if it stuck, customize the variable
17764 `org-stuck-projects'.
17765 MATCH is being ignored."
17766 (interactive)
17767 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
17768 ;; FIXME: we could have used org-agenda-skip-if here.
17769 (org-agenda-overriding-header "List of stuck projects: ")
17770 (matcher (nth 0 org-stuck-projects))
17771 (todo (nth 1 org-stuck-projects))
17772 (todo-wds (if (member "*" todo)
17773 (progn
17774 (org-prepare-agenda-buffers (org-agenda-files))
17775 (org-delete-all
17776 org-done-keywords-for-agenda
17777 (copy-sequence org-todo-keywords-for-agenda)))
17778 todo))
17779 (todo-re (concat "^\\*+[ \t]+\\("
17780 (mapconcat 'identity todo-wds "\\|")
17781 "\\)\\>"))
17782 (tags (nth 2 org-stuck-projects))
17783 (tags-re (if (member "*" tags)
17784 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
17785 (concat "^\\*+ .*:\\("
17786 (mapconcat 'identity tags "\\|")
17787 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
17788 (gen-re (nth 3 org-stuck-projects))
17789 (re-list
17790 (delq nil
17791 (list
17792 (if todo todo-re)
17793 (if tags tags-re)
17794 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
17795 gen-re)))))
17796 (setq org-agenda-skip-regexp
17797 (if re-list
17798 (mapconcat 'identity re-list "\\|")
17799 (error "No information how to identify unstuck projects")))
17800 (org-tags-view nil matcher)
17801 (with-current-buffer org-agenda-buffer-name
17802 (setq org-agenda-redo-command
17803 '(org-agenda-list-stuck-projects
17804 (or current-prefix-arg org-last-arg))))))
17806 ;;; Diary integration
17808 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
17810 (defun org-get-entries-from-diary (date)
17811 "Get the (Emacs Calendar) diary entries for DATE."
17812 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
17813 (diary-display-hook '(fancy-diary-display))
17814 (list-diary-entries-hook
17815 (cons 'org-diary-default-entry list-diary-entries-hook))
17816 (diary-file-name-prefix-function nil) ; turn this feature off
17817 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
17818 entries
17819 (org-disable-agenda-to-diary t))
17820 (save-excursion
17821 (save-window-excursion
17822 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
17823 (if (not (get-buffer fancy-diary-buffer))
17824 (setq entries nil)
17825 (with-current-buffer fancy-diary-buffer
17826 (setq buffer-read-only nil)
17827 (if (zerop (buffer-size))
17828 ;; No entries
17829 (setq entries nil)
17830 ;; Omit the date and other unnecessary stuff
17831 (org-agenda-cleanup-fancy-diary)
17832 ;; Add prefix to each line and extend the text properties
17833 (if (zerop (buffer-size))
17834 (setq entries nil)
17835 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
17836 (set-buffer-modified-p nil)
17837 (kill-buffer fancy-diary-buffer)))
17838 (when entries
17839 (setq entries (org-split-string entries "\n"))
17840 (setq entries
17841 (mapcar
17842 (lambda (x)
17843 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
17844 ;; Extend the text properties to the beginning of the line
17845 (org-add-props x (text-properties-at (1- (length x)) x)
17846 'type "diary" 'date date))
17847 entries)))))
17849 (defun org-agenda-cleanup-fancy-diary ()
17850 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
17851 This gets rid of the date, the underline under the date, and
17852 the dummy entry installed by `org-mode' to ensure non-empty diary for each
17853 date. It also removes lines that contain only whitespace."
17854 (goto-char (point-min))
17855 (if (looking-at ".*?:[ \t]*")
17856 (progn
17857 (replace-match "")
17858 (re-search-forward "\n=+$" nil t)
17859 (replace-match "")
17860 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
17861 (re-search-forward "\n=+$" nil t)
17862 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
17863 (goto-char (point-min))
17864 (while (re-search-forward "^ +\n" nil t)
17865 (replace-match ""))
17866 (goto-char (point-min))
17867 (if (re-search-forward "^Org-mode dummy\n?" nil t)
17868 (replace-match "")))
17870 ;; Make sure entries from the diary have the right text properties.
17871 (eval-after-load "diary-lib"
17872 '(if (boundp 'diary-modify-entry-list-string-function)
17873 ;; We can rely on the hook, nothing to do
17875 ;; Hook not avaiable, must use advice to make this work
17876 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
17877 "Make the position visible."
17878 (if (and org-disable-agenda-to-diary ;; called from org-agenda
17879 (stringp string)
17880 buffer-file-name)
17881 (setq string (org-modify-diary-entry-string string))))))
17883 (defun org-modify-diary-entry-string (string)
17884 "Add text properties to string, allowing org-mode to act on it."
17885 (org-add-props string nil
17886 'mouse-face 'highlight
17887 'keymap org-agenda-keymap
17888 'help-echo (if buffer-file-name
17889 (format "mouse-2 or RET jump to diary file %s"
17890 (abbreviate-file-name buffer-file-name))
17892 'org-agenda-diary-link t
17893 'org-marker (org-agenda-new-marker (point-at-bol))))
17895 (defun org-diary-default-entry ()
17896 "Add a dummy entry to the diary.
17897 Needed to avoid empty dates which mess up holiday display."
17898 ;; Catch the error if dealing with the new add-to-diary-alist
17899 (when org-disable-agenda-to-diary
17900 (condition-case nil
17901 (add-to-diary-list original-date "Org-mode dummy" "")
17902 (error
17903 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
17905 ;;;###autoload
17906 (defun org-diary (&rest args)
17907 "Return diary information from org-files.
17908 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
17909 It accesses org files and extracts information from those files to be
17910 listed in the diary. The function accepts arguments specifying what
17911 items should be listed. The following arguments are allowed:
17913 :timestamp List the headlines of items containing a date stamp or
17914 date range matching the selected date. Deadlines will
17915 also be listed, on the expiration day.
17917 :sexp FIXME
17919 :deadline List any deadlines past due, or due within
17920 `org-deadline-warning-days'. The listing occurs only
17921 in the diary for *today*, not at any other date. If
17922 an entry is marked DONE, it is no longer listed.
17924 :scheduled List all items which are scheduled for the given date.
17925 The diary for *today* also contains items which were
17926 scheduled earlier and are not yet marked DONE.
17928 :todo List all TODO items from the org-file. This may be a
17929 long list - so this is not turned on by default.
17930 Like deadlines, these entries only show up in the
17931 diary for *today*, not at any other date.
17933 The call in the diary file should look like this:
17935 &%%(org-diary) ~/path/to/some/orgfile.org
17937 Use a separate line for each org file to check. Or, if you omit the file name,
17938 all files listed in `org-agenda-files' will be checked automatically:
17940 &%%(org-diary)
17942 If you don't give any arguments (as in the example above), the default
17943 arguments (:deadline :scheduled :timestamp :sexp) are used.
17944 So the example above may also be written as
17946 &%%(org-diary :deadline :timestamp :sexp :scheduled)
17948 The function expects the lisp variables `entry' and `date' to be provided
17949 by the caller, because this is how the calendar works. Don't use this
17950 function from a program - use `org-agenda-get-day-entries' instead."
17951 (org-agenda-maybe-reset-markers)
17952 (org-compile-prefix-format 'agenda)
17953 (org-set-sorting-strategy 'agenda)
17954 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
17955 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
17956 (list entry)
17957 (org-agenda-files t)))
17958 file rtn results)
17959 (org-prepare-agenda-buffers files)
17960 ;; If this is called during org-agenda, don't return any entries to
17961 ;; the calendar. Org Agenda will list these entries itself.
17962 (if org-disable-agenda-to-diary (setq files nil))
17963 (while (setq file (pop files))
17964 (setq rtn (apply 'org-agenda-get-day-entries file date args))
17965 (setq results (append results rtn)))
17966 (if results
17967 (concat (org-finalize-agenda-entries results) "\n"))))
17969 ;;; Agenda entry finders
17971 (defun org-agenda-get-day-entries (file date &rest args)
17972 "Does the work for `org-diary' and `org-agenda'.
17973 FILE is the path to a file to be checked for entries. DATE is date like
17974 the one returned by `calendar-current-date'. ARGS are symbols indicating
17975 which kind of entries should be extracted. For details about these, see
17976 the documentation of `org-diary'."
17977 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
17978 (let* ((org-startup-folded nil)
17979 (org-startup-align-all-tables nil)
17980 (buffer (if (file-exists-p file)
17981 (org-get-agenda-file-buffer file)
17982 (error "No such file %s" file)))
17983 arg results rtn)
17984 (if (not buffer)
17985 ;; If file does not exist, make sure an error message ends up in diary
17986 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
17987 (with-current-buffer buffer
17988 (unless (org-mode-p)
17989 (error "Agenda file %s is not in `org-mode'" file))
17990 (setq org-category-table (org-get-category-table))
17991 (let ((case-fold-search nil))
17992 (save-excursion
17993 (save-restriction
17994 (if org-agenda-restrict
17995 (narrow-to-region org-agenda-restrict-begin
17996 org-agenda-restrict-end)
17997 (widen))
17998 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
17999 (while (setq arg (pop args))
18000 (cond
18001 ((and (eq arg :todo)
18002 (equal date (calendar-current-date)))
18003 (setq rtn (org-agenda-get-todos))
18004 (setq results (append results rtn)))
18005 ((eq arg :timestamp)
18006 (setq rtn (org-agenda-get-blocks))
18007 (setq results (append results rtn))
18008 (setq rtn (org-agenda-get-timestamps))
18009 (setq results (append results rtn)))
18010 ((eq arg :sexp)
18011 (setq rtn (org-agenda-get-sexps))
18012 (setq results (append results rtn)))
18013 ((eq arg :scheduled)
18014 (setq rtn (org-agenda-get-scheduled))
18015 (setq results (append results rtn)))
18016 ((eq arg :closed)
18017 (setq rtn (org-agenda-get-closed))
18018 (setq results (append results rtn)))
18019 ((eq arg :deadline)
18020 (setq rtn (org-agenda-get-deadlines))
18021 (setq results (append results rtn))))))))
18022 results))))
18024 ;; FIXME: this works only if the cursor is not at the
18025 ;; beginning of the entry
18026 (defun org-entry-is-done-p ()
18027 "Is the current entry marked DONE?"
18028 (save-excursion
18029 (and (re-search-backward "[\r\n]\\*+ " nil t)
18030 (looking-at org-nl-done-regexp))))
18032 (defun org-at-date-range-p (&optional inactive-ok)
18033 "Is the cursor inside a date range?"
18034 (interactive)
18035 (save-excursion
18036 (catch 'exit
18037 (let ((pos (point)))
18038 (skip-chars-backward "^[<\r\n")
18039 (skip-chars-backward "<[")
18040 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
18041 (>= (match-end 0) pos)
18042 (throw 'exit t))
18043 (skip-chars-backward "^<[\r\n")
18044 (skip-chars-backward "<[")
18045 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
18046 (>= (match-end 0) pos)
18047 (throw 'exit t)))
18048 nil)))
18050 (defun org-agenda-get-todos ()
18051 "Return the TODO information for agenda display."
18052 (let* ((props (list 'face nil
18053 'done-face 'org-done
18054 'org-not-done-regexp org-not-done-regexp
18055 'org-todo-regexp org-todo-regexp
18056 'mouse-face 'highlight
18057 'keymap org-agenda-keymap
18058 'help-echo
18059 (format "mouse-2 or RET jump to org file %s"
18060 (abbreviate-file-name buffer-file-name))))
18061 ;; FIXME: get rid of the \n at some point but watch out
18062 (regexp (concat "^\\*+[ \t]+\\("
18063 (if org-select-this-todo-keyword
18064 (if (equal org-select-this-todo-keyword "*")
18065 org-todo-regexp
18066 (concat "\\<\\("
18067 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
18068 "\\)\\>"))
18069 org-not-done-regexp)
18070 "[^\n\r]*\\)"))
18071 marker priority category tags
18072 ee txt beg end)
18073 (goto-char (point-min))
18074 (while (re-search-forward regexp nil t)
18075 (catch :skip
18076 (save-match-data
18077 (beginning-of-line)
18078 (setq beg (point) end (progn (outline-next-heading) (point)))
18079 (when (or (and org-agenda-todo-ignore-scheduled (goto-char beg)
18080 (re-search-forward org-scheduled-time-regexp end t))
18081 (and org-agenda-todo-ignore-deadlines (goto-char beg)
18082 (re-search-forward org-deadline-time-regexp end t)
18083 (org-deadline-close (match-string 1))))
18084 (goto-char beg)
18085 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
18086 (throw :skip nil)))
18087 (goto-char beg)
18088 (org-agenda-skip)
18089 (goto-char (match-beginning 1))
18090 (setq marker (org-agenda-new-marker (match-beginning 0))
18091 category (org-get-category)
18092 tags (org-get-tags-at (point))
18093 txt (org-format-agenda-item "" (match-string 1) category tags)
18094 priority (1+ (org-get-priority txt)))
18095 (org-add-props txt props
18096 'org-marker marker 'org-hd-marker marker
18097 'priority priority 'org-category category
18098 'type "todo")
18099 (push txt ee)
18100 (if org-agenda-todo-list-sublevels
18101 (goto-char (match-end 1))
18102 (org-end-of-subtree 'invisible))))
18103 (nreverse ee)))
18105 (defconst org-agenda-no-heading-message
18106 "No heading for this item in buffer or region.")
18108 (defun org-agenda-get-timestamps ()
18109 "Return the date stamp information for agenda display."
18110 (let* ((props (list 'face nil
18111 'org-not-done-regexp org-not-done-regexp
18112 'org-todo-regexp org-todo-regexp
18113 'mouse-face 'highlight
18114 'keymap org-agenda-keymap
18115 'help-echo
18116 (format "mouse-2 or RET jump to org file %s"
18117 (abbreviate-file-name buffer-file-name))))
18118 (d1 (calendar-absolute-from-gregorian date))
18119 (regexp
18120 (concat
18121 (regexp-quote
18122 (substring
18123 (format-time-string
18124 (car org-time-stamp-formats)
18125 (apply 'encode-time ; DATE bound by calendar
18126 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
18127 0 11))
18128 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
18129 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
18130 marker hdmarker deadlinep scheduledp donep tmp priority category
18131 ee txt timestr tags b0 b3 e3)
18132 (goto-char (point-min))
18133 (while (re-search-forward regexp nil t)
18134 (setq b0 (match-beginning 0)
18135 b3 (match-beginning 3) e3 (match-end 3))
18136 (catch :skip
18137 (and (org-at-date-range-p) (throw :skip nil))
18138 (org-agenda-skip)
18139 (if (and (match-end 1)
18140 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
18141 (throw :skip nil))
18142 (if (and e3
18143 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
18144 (throw :skip nil))
18145 (setq marker (org-agenda-new-marker b0)
18146 category (org-get-category b0)
18147 tmp (buffer-substring (max (point-min)
18148 (- b0 org-ds-keyword-length))
18150 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
18151 deadlinep (string-match org-deadline-regexp tmp)
18152 scheduledp (string-match org-scheduled-regexp tmp)
18153 donep (org-entry-is-done-p))
18154 (if (or scheduledp deadlinep) (throw :skip t))
18155 (if (string-match ">" timestr)
18156 ;; substring should only run to end of time stamp
18157 (setq timestr (substring timestr 0 (match-end 0))))
18158 (save-excursion
18159 (if (re-search-backward "^\\*+ " nil t)
18160 (progn
18161 (goto-char (match-beginning 0))
18162 (setq hdmarker (org-agenda-new-marker)
18163 tags (org-get-tags-at))
18164 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
18165 (setq txt (org-format-agenda-item
18166 nil (match-string 1) category tags timestr)))
18167 (setq txt org-agenda-no-heading-message))
18168 (setq priority (org-get-priority txt))
18169 (org-add-props txt props
18170 'org-marker marker 'org-hd-marker hdmarker)
18171 (org-add-props txt nil 'priority priority
18172 'org-category category 'date date
18173 'type "timestamp")
18174 (push txt ee))
18175 (outline-next-heading)))
18176 (nreverse ee)))
18178 (defun org-agenda-get-sexps ()
18179 "Return the sexp information for agenda display."
18180 (require 'diary-lib)
18181 (let* ((props (list 'face nil
18182 'mouse-face 'highlight
18183 'keymap org-agenda-keymap
18184 'help-echo
18185 (format "mouse-2 or RET jump to org file %s"
18186 (abbreviate-file-name buffer-file-name))))
18187 (regexp "^&?%%(")
18188 marker category ee txt tags entry result beg b sexp sexp-entry)
18189 (goto-char (point-min))
18190 (while (re-search-forward regexp nil t)
18191 (catch :skip
18192 (org-agenda-skip)
18193 (setq beg (match-beginning 0))
18194 (goto-char (1- (match-end 0)))
18195 (setq b (point))
18196 (forward-sexp 1)
18197 (setq sexp (buffer-substring b (point)))
18198 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
18199 (org-trim (match-string 1))
18200 ""))
18201 (setq result (org-diary-sexp-entry sexp sexp-entry date))
18202 (when result
18203 (setq marker (org-agenda-new-marker beg)
18204 category (org-get-category beg))
18206 (if (string-match "\\S-" result)
18207 (setq txt result)
18208 (setq txt "SEXP entry returned empty string"))
18210 (setq txt (org-format-agenda-item
18211 "" txt category tags 'time))
18212 (org-add-props txt props 'org-marker marker)
18213 (org-add-props txt nil
18214 'org-category category 'date date
18215 'type "sexp")
18216 (push txt ee))))
18217 (nreverse ee)))
18219 (defun org-agenda-get-closed ()
18220 "Return the logged TODO entries for agenda display."
18221 (let* ((props (list 'mouse-face 'highlight
18222 'org-not-done-regexp org-not-done-regexp
18223 'org-todo-regexp org-todo-regexp
18224 'keymap org-agenda-keymap
18225 'help-echo
18226 (format "mouse-2 or RET jump to org file %s"
18227 (abbreviate-file-name buffer-file-name))))
18228 (regexp (concat
18229 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
18230 (regexp-quote
18231 (substring
18232 (format-time-string
18233 (car org-time-stamp-formats)
18234 (apply 'encode-time ; DATE bound by calendar
18235 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
18236 1 11))))
18237 marker hdmarker priority category tags closedp
18238 ee txt timestr)
18239 (goto-char (point-min))
18240 (while (re-search-forward regexp nil t)
18241 (catch :skip
18242 (org-agenda-skip)
18243 (setq marker (org-agenda-new-marker (match-beginning 0))
18244 closedp (equal (match-string 1) org-closed-string)
18245 category (org-get-category (match-beginning 0))
18246 timestr (buffer-substring (match-beginning 0) (point-at-eol))
18247 ;; donep (org-entry-is-done-p)
18249 (if (string-match "\\]" timestr)
18250 ;; substring should only run to end of time stamp
18251 (setq timestr (substring timestr 0 (match-end 0))))
18252 (save-excursion
18253 (if (re-search-backward "^\\*+ " nil t)
18254 (progn
18255 (goto-char (match-beginning 0))
18256 (setq hdmarker (org-agenda-new-marker)
18257 tags (org-get-tags-at))
18258 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
18259 (setq txt (org-format-agenda-item
18260 (if closedp "Closed: " "Clocked: ")
18261 (match-string 1) category tags timestr)))
18262 (setq txt org-agenda-no-heading-message))
18263 (setq priority 100000)
18264 (org-add-props txt props
18265 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
18266 'priority priority 'org-category category
18267 'type "closed" 'date date
18268 'undone-face 'org-warning 'done-face 'org-done)
18269 (push txt ee))
18270 (outline-next-heading)))
18271 (nreverse ee)))
18273 (defun org-agenda-get-deadlines ()
18274 "Return the deadline information for agenda display."
18275 (let* ((props (list 'mouse-face 'highlight
18276 'org-not-done-regexp org-not-done-regexp
18277 'org-todo-regexp org-todo-regexp
18278 'keymap org-agenda-keymap
18279 'help-echo
18280 (format "mouse-2 or RET jump to org file %s"
18281 (abbreviate-file-name buffer-file-name))))
18282 (regexp org-deadline-time-regexp)
18283 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
18284 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
18285 d2 diff dfrac wdays pos pos1 category tags
18286 ee txt head face s upcomingp donep timestr)
18287 (goto-char (point-min))
18288 (while (re-search-forward regexp nil t)
18289 (catch :skip
18290 (org-agenda-skip)
18291 (setq s (match-string 1)
18292 pos (1- (match-beginning 1))
18293 d2 (org-time-string-to-absolute (match-string 1) d1)
18294 diff (- d2 d1))
18295 (if (string-match "-\\([0-9]+\\)\\([dwmy]\\)\\'" s)
18296 (setq wdays
18297 (floor
18298 (* (string-to-number (match-string 1 s))
18299 (cdr (assoc (match-string 2 s)
18300 '(("d" . 1) ("w" . 7)
18301 ("m" . 30.4) ("y" . 365.25)))))))
18302 (setq wdays org-deadline-warning-days))
18303 (setq dfrac (/ (* 1.0 (- wdays diff)) wdays))
18304 (setq upcomingp (and todayp (> diff 0)))
18305 ;; When to show a deadline in the calendar:
18306 ;; If the expiration is within wdays warning time.
18307 ;; Past-due deadlines are only shown on the current date
18308 (if (or (and (<= diff wdays) todayp)
18309 (= diff 0))
18310 (save-excursion
18311 (setq category (org-get-category))
18312 (if (re-search-backward "^\\*+[ \t]+" nil t)
18313 (progn
18314 (goto-char (match-end 0))
18315 (setq pos1 (match-beginning 0))
18316 (setq tags (org-get-tags-at pos1))
18317 (setq head (buffer-substring-no-properties
18318 (point)
18319 (progn (skip-chars-forward "^\r\n")
18320 (point))))
18321 (setq donep (string-match org-looking-at-done-regexp head))
18322 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
18323 (setq timestr (concat (match-string 1 s) " ")))
18324 (if (and donep
18325 (or org-agenda-skip-deadline-if-done
18326 (not (= diff 0))))
18327 (setq txt nil)
18328 (setq txt (org-format-agenda-item
18329 (if (= diff 0)
18330 "Deadline: "
18331 (format "In %3d d.: " diff))
18332 head category tags timestr))))
18333 (setq txt org-agenda-no-heading-message))
18334 (when txt
18335 (setq face (org-agenda-deadline-face dfrac))
18336 (org-add-props txt props
18337 'org-marker (org-agenda-new-marker pos)
18338 'org-hd-marker (org-agenda-new-marker pos1)
18339 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
18340 (org-get-priority txt))
18341 'org-category category
18342 'type (if upcomingp "upcoming-deadline" "deadline")
18343 'date (if upcomingp date d2)
18344 'face (if donep 'org-done face)
18345 'undone-face face 'done-face 'org-done)
18346 (push txt ee))))))
18347 ee))
18349 (defun org-agenda-deadline-face (fraction)
18350 "Return the face to displaying a deadline item.
18351 FRACTION is what fraction of the head-warning time has passed."
18352 (let ((faces org-agenda-deadline-faces) f)
18353 (catch 'exit
18354 (while (setq f (pop faces))
18355 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
18357 (defun org-agenda-get-scheduled ()
18358 "Return the scheduled information for agenda display."
18359 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
18360 'org-todo-regexp org-todo-regexp
18361 'done-face 'org-done
18362 'mouse-face 'highlight
18363 'keymap org-agenda-keymap
18364 'help-echo
18365 (format "mouse-2 or RET jump to org file %s"
18366 (abbreviate-file-name buffer-file-name))))
18367 (regexp org-scheduled-time-regexp)
18368 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
18369 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
18370 d2 diff pos pos1 category tags
18371 ee txt head pastschedp donep face timestr s)
18372 (goto-char (point-min))
18373 (while (re-search-forward regexp nil t)
18374 (catch :skip
18375 (org-agenda-skip)
18376 (setq s (match-string 1)
18377 pos (1- (match-beginning 1))
18378 d2 (org-time-string-to-absolute (match-string 1) d1)
18379 diff (- d2 d1))
18380 (setq pastschedp (and todayp (< diff 0)))
18381 ;; When to show a scheduled item in the calendar:
18382 ;; If it is on or past the date.
18383 (if (or (and (< diff 0) todayp)
18384 (= diff 0))
18385 (save-excursion
18386 (setq category (org-get-category))
18387 (if (re-search-backward "^\\*+[ \t]+" nil t)
18388 (progn
18389 (goto-char (match-end 0))
18390 (setq pos1 (match-beginning 0))
18391 (setq tags (org-get-tags-at))
18392 (setq head (buffer-substring-no-properties
18393 (point)
18394 (progn (skip-chars-forward "^\r\n") (point))))
18395 (setq donep (string-match org-looking-at-done-regexp head))
18396 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
18397 (setq timestr (concat (match-string 1 s) " "))
18398 (setq timestr nil))
18399 (if (and donep
18400 (or org-agenda-skip-scheduled-if-done
18401 (not (= diff 0))))
18402 (setq txt nil)
18403 (setq txt (org-format-agenda-item
18404 (if (= diff 0)
18405 "Scheduled: "
18406 (format "Sched.%2dx: " (- 1 diff)))
18407 head category tags timestr))))
18408 (setq txt org-agenda-no-heading-message))
18409 (when txt
18410 (setq face (if pastschedp
18411 'org-scheduled-previously
18412 'org-scheduled-today))
18413 (org-add-props txt props
18414 'undone-face face
18415 'face (if donep 'org-done face)
18416 'org-marker (org-agenda-new-marker pos)
18417 'org-hd-marker (org-agenda-new-marker pos1)
18418 'type (if pastschedp "past-scheduled" "scheduled")
18419 'date (if pastschedp d2 date)
18420 'priority (+ (- 5 diff) (org-get-priority txt))
18421 'org-category category)
18422 (push txt ee))))))
18423 ee))
18425 (defun org-agenda-get-blocks ()
18426 "Return the date-range information for agenda display."
18427 (let* ((props (list 'face nil
18428 'org-not-done-regexp org-not-done-regexp
18429 'org-todo-regexp org-todo-regexp
18430 'mouse-face 'highlight
18431 'keymap org-agenda-keymap
18432 'help-echo
18433 (format "mouse-2 or RET jump to org file %s"
18434 (abbreviate-file-name buffer-file-name))))
18435 (regexp org-tr-regexp)
18436 (d0 (calendar-absolute-from-gregorian date))
18437 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
18438 (goto-char (point-min))
18439 (while (re-search-forward regexp nil t)
18440 (catch :skip
18441 (org-agenda-skip)
18442 (setq pos (point))
18443 (setq timestr (match-string 0)
18444 s1 (match-string 1)
18445 s2 (match-string 2)
18446 d1 (time-to-days (org-time-string-to-time s1))
18447 d2 (time-to-days (org-time-string-to-time s2)))
18448 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
18449 ;; Only allow days between the limits, because the normal
18450 ;; date stamps will catch the limits.
18451 (save-excursion
18452 (setq marker (org-agenda-new-marker (point)))
18453 (setq category (org-get-category))
18454 (if (re-search-backward "^\\*+ " nil t)
18455 (progn
18456 (goto-char (match-beginning 0))
18457 (setq hdmarker (org-agenda-new-marker (point)))
18458 (setq tags (org-get-tags-at))
18459 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
18460 (setq txt (org-format-agenda-item
18461 (format (if (= d1 d2) "" "(%d/%d): ")
18462 (1+ (- d0 d1)) (1+ (- d2 d1)))
18463 (match-string 1) category tags
18464 (if (= d0 d1) timestr))))
18465 (setq txt org-agenda-no-heading-message))
18466 (org-add-props txt props
18467 'org-marker marker 'org-hd-marker hdmarker
18468 'type "block" 'date date
18469 'priority (org-get-priority txt) 'org-category category)
18470 (push txt ee)))
18471 (goto-char pos)))
18472 ;; Sort the entries by expiration date.
18473 (nreverse ee)))
18475 ;;; Agenda presentation and sorting
18477 (defconst org-plain-time-of-day-regexp
18478 (concat
18479 "\\(\\<[012]?[0-9]"
18480 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
18481 "\\(--?"
18482 "\\(\\<[012]?[0-9]"
18483 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
18484 "\\)?")
18485 "Regular expression to match a plain time or time range.
18486 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
18487 groups carry important information:
18488 0 the full match
18489 1 the first time, range or not
18490 8 the second time, if it is a range.")
18492 (defconst org-stamp-time-of-day-regexp
18493 (concat
18494 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
18495 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
18496 "\\(--?"
18497 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
18498 "Regular expression to match a timestamp time or time range.
18499 After a match, the following groups carry important information:
18500 0 the full match
18501 1 date plus weekday, for backreferencing to make sure both times on same day
18502 2 the first time, range or not
18503 4 the second time, if it is a range.")
18505 (defvar org-prefix-has-time nil
18506 "A flag, set by `org-compile-prefix-format'.
18507 The flag is set if the currently compiled format contains a `%t'.")
18508 (defvar org-prefix-has-tag nil
18509 "A flag, set by `org-compile-prefix-format'.
18510 The flag is set if the currently compiled format contains a `%T'.")
18512 (defun org-format-agenda-item (extra txt &optional category tags dotime
18513 noprefix)
18514 "Format TXT to be inserted into the agenda buffer.
18515 In particular, it adds the prefix and corresponding text properties. EXTRA
18516 must be a string and replaces the `%s' specifier in the prefix format.
18517 CATEGORY (string, symbol or nil) may be used to overrule the default
18518 category taken from local variable or file name. It will replace the `%c'
18519 specifier in the format. DOTIME, when non-nil, indicates that a
18520 time-of-day should be extracted from TXT for sorting of this entry, and for
18521 the `%t' specifier in the format. When DOTIME is a string, this string is
18522 searched for a time before TXT is. NOPREFIX is a flag and indicates that
18523 only the correctly processes TXT should be returned - this is used by
18524 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
18525 (save-match-data
18526 ;; Diary entries sometimes have extra whitespace at the beginning
18527 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
18528 (let* ((category (or category
18529 org-category
18530 (if buffer-file-name
18531 (file-name-sans-extension
18532 (file-name-nondirectory buffer-file-name))
18533 "")))
18534 (tag (if tags (nth (1- (length tags)) tags) ""))
18535 time ; time and tag are needed for the eval of the prefix format
18536 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
18537 (time-of-day (and dotime (org-get-time-of-day ts)))
18538 stamp plain s0 s1 s2 rtn srp)
18539 (when (and dotime time-of-day org-prefix-has-time)
18540 ;; Extract starting and ending time and move them to prefix
18541 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
18542 (setq plain (string-match org-plain-time-of-day-regexp ts)))
18543 (setq s0 (match-string 0 ts)
18544 srp (and stamp (match-end 3))
18545 s1 (match-string (if plain 1 2) ts)
18546 s2 (match-string (if plain 8 (if srp 4 6)) ts))
18548 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
18549 ;; them, we might want to remove them there to avoid duplication.
18550 ;; The user can turn this off with a variable.
18551 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
18552 (string-match (concat (regexp-quote s0) " *") txt)
18553 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
18554 (= (match-beginning 0) 0)
18556 (setq txt (replace-match "" nil nil txt))))
18557 ;; Normalize the time(s) to 24 hour
18558 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
18559 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
18561 (when (and s1 (not s2) org-agenda-default-appointment-duration
18562 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
18563 (let ((m (+ (string-to-number (match-string 2 s1))
18564 (* 60 (string-to-number (match-string 1 s1)))
18565 org-agenda-default-appointment-duration))
18567 (setq h (/ m 60) m (- m (* h 60)))
18568 (setq s2 (format "%02d:%02d" h m))))
18570 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
18571 txt)
18572 ;; Tags are in the string
18573 (if (or (eq org-agenda-remove-tags t)
18574 (and org-agenda-remove-tags
18575 org-prefix-has-tag))
18576 (setq txt (replace-match "" t t txt))
18577 (setq txt (replace-match
18578 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
18579 (match-string 2 txt))
18580 t t txt))))
18582 ;; Create the final string
18583 (if noprefix
18584 (setq rtn txt)
18585 ;; Prepare the variables needed in the eval of the compiled format
18586 (setq time (cond (s2 (concat s1 "-" s2))
18587 (s1 (concat s1 "......"))
18588 (t ""))
18589 extra (or extra "")
18590 category (if (symbolp category) (symbol-name category) category))
18591 ;; Evaluate the compiled format
18592 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
18594 ;; And finally add the text properties
18595 (org-add-props rtn nil
18596 'org-category (downcase category) 'tags tags
18597 'prefix-length (- (length rtn) (length txt))
18598 'time-of-day time-of-day
18599 'txt txt
18600 'time time
18601 'extra extra
18602 'dotime dotime))))
18604 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
18605 (defvar org-agenda-sorting-strategy-selected nil)
18607 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
18608 (catch 'exit
18609 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
18610 ((and todayp (member 'today (car org-agenda-time-grid))))
18611 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
18612 ((member 'weekly (car org-agenda-time-grid)))
18613 (t (throw 'exit list)))
18614 (let* ((have (delq nil (mapcar
18615 (lambda (x) (get-text-property 1 'time-of-day x))
18616 list)))
18617 (string (nth 1 org-agenda-time-grid))
18618 (gridtimes (nth 2 org-agenda-time-grid))
18619 (req (car org-agenda-time-grid))
18620 (remove (member 'remove-match req))
18621 new time)
18622 (if (and (member 'require-timed req) (not have))
18623 ;; don't show empty grid
18624 (throw 'exit list))
18625 (while (setq time (pop gridtimes))
18626 (unless (and remove (member time have))
18627 (setq time (int-to-string time))
18628 (push (org-format-agenda-item
18629 nil string "" nil
18630 (concat (substring time 0 -2) ":" (substring time -2)))
18631 new)
18632 (put-text-property
18633 1 (length (car new)) 'face 'org-time-grid (car new))))
18634 (if (member 'time-up org-agenda-sorting-strategy-selected)
18635 (append new list)
18636 (append list new)))))
18638 (defun org-compile-prefix-format (key)
18639 "Compile the prefix format into a Lisp form that can be evaluated.
18640 The resulting form is returned and stored in the variable
18641 `org-prefix-format-compiled'."
18642 (setq org-prefix-has-time nil org-prefix-has-tag nil)
18643 (let ((s (cond
18644 ((stringp org-agenda-prefix-format)
18645 org-agenda-prefix-format)
18646 ((assq key org-agenda-prefix-format)
18647 (cdr (assq key org-agenda-prefix-format)))
18648 (t " %-12:c%?-12t% s")))
18649 (start 0)
18650 varform vars var e c f opt)
18651 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
18652 s start)
18653 (setq var (cdr (assoc (match-string 4 s)
18654 '(("c" . category) ("t" . time) ("s" . extra)
18655 ("T" . tag))))
18656 c (or (match-string 3 s) "")
18657 opt (match-beginning 1)
18658 start (1+ (match-beginning 0)))
18659 (if (equal var 'time) (setq org-prefix-has-time t))
18660 (if (equal var 'tag) (setq org-prefix-has-tag t))
18661 (setq f (concat "%" (match-string 2 s) "s"))
18662 (if opt
18663 (setq varform
18664 `(if (equal "" ,var)
18666 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
18667 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
18668 (setq s (replace-match "%s" t nil s))
18669 (push varform vars))
18670 (setq vars (nreverse vars))
18671 (setq org-prefix-format-compiled `(format ,s ,@vars))))
18673 (defun org-set-sorting-strategy (key)
18674 (if (symbolp (car org-agenda-sorting-strategy))
18675 ;; the old format
18676 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
18677 (setq org-agenda-sorting-strategy-selected
18678 (or (cdr (assq key org-agenda-sorting-strategy))
18679 (cdr (assq 'agenda org-agenda-sorting-strategy))
18680 '(time-up category-keep priority-down)))))
18682 (defun org-get-time-of-day (s &optional string mod24)
18683 "Check string S for a time of day.
18684 If found, return it as a military time number between 0 and 2400.
18685 If not found, return nil.
18686 The optional STRING argument forces conversion into a 5 character wide string
18687 HH:MM."
18688 (save-match-data
18689 (when
18691 (string-match
18692 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
18693 (string-match
18694 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
18695 (let* ((h (string-to-number (match-string 1 s)))
18696 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
18697 (ampm (if (match-end 4) (downcase (match-string 4 s))))
18698 (am-p (equal ampm "am"))
18699 (h1 (cond ((not ampm) h)
18700 ((= h 12) (if am-p 0 12))
18701 (t (+ h (if am-p 0 12)))))
18702 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
18703 (mod h1 24) h1))
18704 (t0 (+ (* 100 h2) m))
18705 (t1 (concat (if (>= h1 24) "+" " ")
18706 (if (< t0 100) "0" "")
18707 (if (< t0 10) "0" "")
18708 (int-to-string t0))))
18709 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
18711 (defun org-finalize-agenda-entries (list &optional nosort)
18712 "Sort and concatenate the agenda items."
18713 (setq list (mapcar 'org-agenda-highlight-todo list))
18714 (if nosort
18715 list
18716 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
18718 (defun org-agenda-highlight-todo (x)
18719 (let (re pl)
18720 (if (eq x 'line)
18721 (save-excursion
18722 (beginning-of-line 1)
18723 (setq re (get-text-property (point) 'org-not-done-regexp))
18724 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
18725 (and (looking-at (concat "[ \t]*\\.*" re))
18726 (add-text-properties (match-beginning 0) (match-end 0)
18727 '(face org-todo))))
18728 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
18729 pl (get-text-property 0 'prefix-length x))
18730 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
18731 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
18732 '(face org-todo) x))
18733 x)))
18735 (defsubst org-cmp-priority (a b)
18736 "Compare the priorities of string A and B."
18737 (let ((pa (or (get-text-property 1 'priority a) 0))
18738 (pb (or (get-text-property 1 'priority b) 0)))
18739 (cond ((> pa pb) +1)
18740 ((< pa pb) -1)
18741 (t nil))))
18743 (defsubst org-cmp-category (a b)
18744 "Compare the string values of categories of strings A and B."
18745 (let ((ca (or (get-text-property 1 'org-category a) ""))
18746 (cb (or (get-text-property 1 'org-category b) "")))
18747 (cond ((string-lessp ca cb) -1)
18748 ((string-lessp cb ca) +1)
18749 (t nil))))
18751 (defsubst org-cmp-tag (a b)
18752 "Compare the string values of categories of strings A and B."
18753 (let ((ta (car (last (get-text-property 1 'tags a))))
18754 (tb (car (last (get-text-property 1 'tags b)))))
18755 (cond ((not ta) +1)
18756 ((not tb) -1)
18757 ((string-lessp ta tb) -1)
18758 ((string-lessp tb ta) +1)
18759 (t nil))))
18761 (defsubst org-cmp-time (a b)
18762 "Compare the time-of-day values of strings A and B."
18763 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
18764 (ta (or (get-text-property 1 'time-of-day a) def))
18765 (tb (or (get-text-property 1 'time-of-day b) def)))
18766 (cond ((< ta tb) -1)
18767 ((< tb ta) +1)
18768 (t nil))))
18770 (defun org-entries-lessp (a b)
18771 "Predicate for sorting agenda entries."
18772 ;; The following variables will be used when the form is evaluated.
18773 ;; So even though the compiler complains, keep them.
18774 (let* ((time-up (org-cmp-time a b))
18775 (time-down (if time-up (- time-up) nil))
18776 (priority-up (org-cmp-priority a b))
18777 (priority-down (if priority-up (- priority-up) nil))
18778 (category-up (org-cmp-category a b))
18779 (category-down (if category-up (- category-up) nil))
18780 (category-keep (if category-up +1 nil))
18781 (tag-up (org-cmp-tag a b))
18782 (tag-down (if tag-up (- tag-up) nil)))
18783 (cdr (assoc
18784 (eval (cons 'or org-agenda-sorting-strategy-selected))
18785 '((-1 . t) (1 . nil) (nil . nil))))))
18787 ;;; Agenda commands
18789 (defun org-agenda-check-type (error &rest types)
18790 "Check if agenda buffer is of allowed type.
18791 If ERROR is non-nil, throw an error, otherwise just return nil."
18792 (if (memq org-agenda-type types)
18794 (if error
18795 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
18796 nil)))
18798 (defun org-agenda-quit ()
18799 "Exit agenda by removing the window or the buffer."
18800 (interactive)
18801 (let ((buf (current-buffer)))
18802 (if (not (one-window-p)) (delete-window))
18803 (kill-buffer buf)
18804 (org-agenda-maybe-reset-markers 'force)
18805 (org-columns-remove-overlays))
18806 ;; Maybe restore the pre-agenda window configuration.
18807 (and org-agenda-restore-windows-after-quit
18808 (not (eq org-agenda-window-setup 'other-frame))
18809 org-pre-agenda-window-conf
18810 (set-window-configuration org-pre-agenda-window-conf)))
18812 (defun org-agenda-exit ()
18813 "Exit agenda by removing the window or the buffer.
18814 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
18815 Org-mode buffers visited directly by the user will not be touched."
18816 (interactive)
18817 (org-release-buffers org-agenda-new-buffers)
18818 (setq org-agenda-new-buffers nil)
18819 (org-agenda-quit))
18821 (defun org-save-all-org-buffers ()
18822 "Save all Org-mode buffers without user confirmation."
18823 (interactive)
18824 (message "Saving all Org-mode buffers...")
18825 (save-some-buffers t 'org-mode-p)
18826 (message "Saving all Org-mode buffers... done"))
18828 (defun org-agenda-redo ()
18829 "Rebuild Agenda.
18830 When this is the global TODO list, a prefix argument will be interpreted."
18831 (interactive)
18832 (let* ((org-agenda-keep-modes t)
18833 (line (org-current-line))
18834 (window-line (- line (org-current-line (window-start))))
18835 (lprops (get 'org-agenda-redo-command 'org-lprops)))
18836 (message "Rebuilding agenda buffer...")
18837 (org-let lprops '(eval org-agenda-redo-command))
18838 (setq org-agenda-undo-list nil
18839 org-agenda-pending-undo-list nil)
18840 (message "Rebuilding agenda buffer...done")
18841 (goto-line line)
18842 (recenter window-line)))
18844 (defun org-agenda-goto-date (date)
18845 "Jump to DATE in agenda."
18846 (interactive (list (org-read-date)))
18847 (org-agenda-list nil date))
18849 (defun org-agenda-goto-today ()
18850 "Go to today."
18851 (interactive)
18852 (org-agenda-check-type t 'timeline 'agenda)
18853 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
18854 (cond
18855 (tdpos (goto-char tdpos))
18856 ((eq org-agenda-type 'agenda)
18857 (let* ((sd (time-to-days (current-time)))
18858 (comp (org-agenda-compute-time-span sd org-agenda-span))
18859 (org-agenda-overriding-arguments org-agenda-last-arguments))
18860 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
18861 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
18862 (org-agenda-redo)
18863 (org-agenda-find-today-or-agenda)))
18864 (t (error "Cannot find today")))))
18866 (defun org-agenda-find-today-or-agenda ()
18867 (goto-char
18868 (or (text-property-any (point-min) (point-max) 'org-today t)
18869 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
18870 (point-min))))
18872 (defun org-agenda-later (arg)
18873 "Go forward in time by thee current span.
18874 With prefix ARG, go forward that many times the current span."
18875 (interactive "p")
18876 (org-agenda-check-type t 'agenda)
18877 (let* ((span org-agenda-span)
18878 (sd org-starting-day)
18879 (greg (calendar-gregorian-from-absolute sd))
18880 greg2 nd)
18881 (cond
18882 ((eq span 'day)
18883 (setq sd (+ arg sd) nd 1))
18884 ((eq span 'week)
18885 (setq sd (+ (* 7 arg) sd) nd 7))
18886 ((eq span 'month)
18887 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
18888 sd (calendar-absolute-from-gregorian greg2))
18889 (setcar greg2 (1+ (car greg2)))
18890 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
18891 ((eq span 'year)
18892 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
18893 sd (calendar-absolute-from-gregorian greg2))
18894 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
18895 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
18896 (let ((org-agenda-overriding-arguments
18897 (list (car org-agenda-last-arguments) sd nd t)))
18898 (org-agenda-redo)
18899 (org-agenda-find-today-or-agenda))))
18901 (defun org-agenda-earlier (arg)
18902 "Go backward in time by the current span.
18903 With prefix ARG, go backward that many times the current span."
18904 (interactive "p")
18905 (org-agenda-later (- arg)))
18907 (defun org-agenda-day-view ()
18908 "Switch to daily view for agenda."
18909 (interactive)
18910 (setq org-agenda-ndays 1)
18911 (org-agenda-change-time-span 'day))
18912 (defun org-agenda-week-view ()
18913 "Switch to daily view for agenda."
18914 (interactive)
18915 (setq org-agenda-ndays 7)
18916 (org-agenda-change-time-span 'week))
18917 (defun org-agenda-month-view ()
18918 "Switch to daily view for agenda."
18919 (interactive)
18920 (org-agenda-change-time-span 'month))
18921 (defun org-agenda-year-view ()
18922 "Switch to daily view for agenda."
18923 (interactive)
18924 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
18925 (org-agenda-change-time-span 'year)
18926 (error "Abort")))
18928 (defun org-agenda-change-time-span (span)
18929 "Change the agenda view to SPAN.
18930 SPAN may be `day', `week', `month', `year'."
18931 (org-agenda-check-type t 'agenda)
18932 (if (equal org-agenda-span span)
18933 (error "Viewing span is already \"%s\"" span))
18934 (let* ((sd (or (get-text-property (point) 'day)
18935 org-starting-day))
18936 (computed (org-agenda-compute-time-span sd span))
18937 (org-agenda-overriding-arguments
18938 (list (car org-agenda-last-arguments)
18939 (car computed) (cdr computed) t)))
18940 (org-agenda-redo)
18941 (org-agenda-find-today-or-agenda))
18942 (org-agenda-set-mode-name)
18943 (message "Switched to %s view" span))
18945 (defun org-agenda-compute-time-span (sd span)
18946 "Compute starting date and number of days for agenda.
18947 SPAN may be `day', `week', `month', `year'. The return value
18948 is a cons cell with the starting date and the number of days,
18949 so that the date SD will be in that range."
18950 (let* ((greg (calendar-gregorian-from-absolute sd))
18952 (cond
18953 ((eq span 'day)
18954 (setq nd 1))
18955 ((eq span 'week)
18956 (let* ((nt (calendar-day-of-week
18957 (calendar-gregorian-from-absolute sd)))
18958 (d (if org-agenda-start-on-weekday
18959 (- nt org-agenda-start-on-weekday)
18960 0)))
18961 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
18962 (setq nd 7)))
18963 ((eq span 'month)
18964 (setq sd (calendar-absolute-from-gregorian
18965 (list (car greg) 1 (nth 2 greg)))
18966 nd (- (calendar-absolute-from-gregorian
18967 (list (1+ (car greg)) 1 (nth 2 greg)))
18968 sd)))
18969 ((eq span 'year)
18970 (setq sd (calendar-absolute-from-gregorian
18971 (list 1 1 (nth 2 greg)))
18972 nd (- (calendar-absolute-from-gregorian
18973 (list 1 1 (1+ (nth 2 greg))))
18974 sd))))
18975 (cons sd nd)))
18977 ;; FIXME: this no longer works if user make date format that starts with a blank
18978 (defun org-agenda-next-date-line (&optional arg)
18979 "Jump to the next line indicating a date in agenda buffer."
18980 (interactive "p")
18981 (org-agenda-check-type t 'agenda 'timeline)
18982 (beginning-of-line 1)
18983 (if (looking-at "^\\S-") (forward-char 1))
18984 (if (not (re-search-forward "^\\S-" nil t arg))
18985 (progn
18986 (backward-char 1)
18987 (error "No next date after this line in this buffer")))
18988 (goto-char (match-beginning 0)))
18990 (defun org-agenda-previous-date-line (&optional arg)
18991 "Jump to the previous line indicating a date in agenda buffer."
18992 (interactive "p")
18993 (org-agenda-check-type t 'agenda 'timeline)
18994 (beginning-of-line 1)
18995 (if (not (re-search-backward "^\\S-" nil t arg))
18996 (error "No previous date before this line in this buffer")))
18998 ;; Initialize the highlight
18999 (defvar org-hl (org-make-overlay 1 1))
19000 (org-overlay-put org-hl 'face 'highlight)
19002 (defun org-highlight (begin end &optional buffer)
19003 "Highlight a region with overlay."
19004 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
19005 org-hl begin end (or buffer (current-buffer))))
19007 (defun org-unhighlight ()
19008 "Detach overlay INDEX."
19009 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
19011 ;; FIXME this is currently not used.
19012 (defun org-highlight-until-next-command (beg end &optional buffer)
19013 (org-highlight beg end buffer)
19014 (add-hook 'pre-command-hook 'org-unhighlight-once))
19016 (defun org-unhighlight-once ()
19017 (remove-hook 'pre-command-hook 'org-unhighlight-once)
19018 (org-unhighlight))
19020 (defun org-agenda-follow-mode ()
19021 "Toggle follow mode in an agenda buffer."
19022 (interactive)
19023 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
19024 (org-agenda-set-mode-name)
19025 (message "Follow mode is %s"
19026 (if org-agenda-follow-mode "on" "off")))
19028 (defun org-agenda-log-mode ()
19029 "Toggle log mode in an agenda buffer."
19030 (interactive)
19031 (org-agenda-check-type t 'agenda 'timeline)
19032 (setq org-agenda-show-log (not org-agenda-show-log))
19033 (org-agenda-set-mode-name)
19034 (org-agenda-redo)
19035 (message "Log mode is %s"
19036 (if org-agenda-show-log "on" "off")))
19038 (defun org-agenda-toggle-diary ()
19039 "Toggle diary inclusion in an agenda buffer."
19040 (interactive)
19041 (org-agenda-check-type t 'agenda)
19042 (setq org-agenda-include-diary (not org-agenda-include-diary))
19043 (org-agenda-redo)
19044 (org-agenda-set-mode-name)
19045 (message "Diary inclusion turned %s"
19046 (if org-agenda-include-diary "on" "off")))
19048 (defun org-agenda-toggle-time-grid ()
19049 "Toggle time grid in an agenda buffer."
19050 (interactive)
19051 (org-agenda-check-type t 'agenda)
19052 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
19053 (org-agenda-redo)
19054 (org-agenda-set-mode-name)
19055 (message "Time-grid turned %s"
19056 (if org-agenda-use-time-grid "on" "off")))
19058 (defun org-agenda-set-mode-name ()
19059 "Set the mode name to indicate all the small mode settings."
19060 (setq mode-name
19061 (concat "Org-Agenda"
19062 (if (equal org-agenda-ndays 1) " Day" "")
19063 (if (equal org-agenda-ndays 7) " Week" "")
19064 (if org-agenda-follow-mode " Follow" "")
19065 (if org-agenda-include-diary " Diary" "")
19066 (if org-agenda-use-time-grid " Grid" "")
19067 (if org-agenda-show-log " Log" "")))
19068 (force-mode-line-update))
19070 (defun org-agenda-post-command-hook ()
19071 (and (eolp) (not (bolp)) (backward-char 1))
19072 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
19073 (if (and org-agenda-follow-mode
19074 (get-text-property (point) 'org-marker))
19075 (org-agenda-show)))
19077 (defun org-agenda-show-priority ()
19078 "Show the priority of the current item.
19079 This priority is composed of the main priority given with the [#A] cookies,
19080 and by additional input from the age of a schedules or deadline entry."
19081 (interactive)
19082 (let* ((pri (get-text-property (point-at-bol) 'priority)))
19083 (message "Priority is %d" (if pri pri -1000))))
19085 (defun org-agenda-show-tags ()
19086 "Show the tags applicable to the current item."
19087 (interactive)
19088 (let* ((tags (get-text-property (point-at-bol) 'tags)))
19089 (if tags
19090 (message "Tags are :%s:"
19091 (org-no-properties (mapconcat 'identity tags ":")))
19092 (message "No tags associated with this line"))))
19094 (defun org-agenda-goto (&optional highlight)
19095 "Go to the Org-mode file which contains the item at point."
19096 (interactive)
19097 (let* ((marker (or (get-text-property (point) 'org-marker)
19098 (org-agenda-error)))
19099 (buffer (marker-buffer marker))
19100 (pos (marker-position marker)))
19101 (switch-to-buffer-other-window buffer)
19102 (widen)
19103 (goto-char pos)
19104 (when (org-mode-p)
19105 (org-show-context 'agenda)
19106 (save-excursion
19107 (and (outline-next-heading)
19108 (org-flag-heading nil)))) ; show the next heading
19109 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
19111 (defun org-agenda-kill ()
19112 "Kill the entry or subtree belonging to the current agenda entry."
19113 (interactive)
19114 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
19115 (let* ((marker (or (get-text-property (point) 'org-marker)
19116 (org-agenda-error)))
19117 (buffer (marker-buffer marker))
19118 (pos (marker-position marker))
19119 (type (get-text-property (point) 'type))
19120 dbeg dend (n 0) conf)
19121 (org-with-remote-undo buffer
19122 (with-current-buffer buffer
19123 (save-excursion
19124 (goto-char pos)
19125 (if (and (org-mode-p) (not (member type '("sexp"))))
19126 (setq dbeg (progn (org-back-to-heading t) (point))
19127 dend (org-end-of-subtree t t))
19128 (setq dbeg (point-at-bol)
19129 dend (min (point-max) (1+ (point-at-eol)))))
19130 (goto-char dbeg)
19131 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
19132 (setq conf (or (eq t org-agenda-confirm-kill)
19133 (and (numberp org-agenda-confirm-kill)
19134 (> n org-agenda-confirm-kill))))
19135 (and conf
19136 (not (y-or-n-p
19137 (format "Delete entry with %d lines in buffer \"%s\"? "
19138 n (buffer-name buffer))))
19139 (error "Abort"))
19140 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
19141 (with-current-buffer buffer (delete-region dbeg dend))
19142 (message "Agenda item and source killed"))))
19144 (defun org-agenda-archive ()
19145 "Kill the entry or subtree belonging to the current agenda entry."
19146 (interactive)
19147 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
19148 (let* ((marker (or (get-text-property (point) 'org-marker)
19149 (org-agenda-error)))
19150 (buffer (marker-buffer marker))
19151 (pos (marker-position marker)))
19152 (org-with-remote-undo buffer
19153 (with-current-buffer buffer
19154 (if (org-mode-p)
19155 (save-excursion
19156 (goto-char pos)
19157 (org-remove-subtree-entries-from-agenda)
19158 (org-back-to-heading t)
19159 (org-archive-subtree))
19160 (error "Archiving works only in Org-mode files"))))))
19162 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
19163 "Remove all lines in the agenda that correspond to a given subtree.
19164 The subtree is the one in buffer BUF, starting at BEG and ending at END.
19165 If this information is not given, the function uses the tree at point."
19166 (let ((buf (or buf (current-buffer))) m p)
19167 (save-excursion
19168 (unless (and beg end)
19169 (org-back-to-heading t)
19170 (setq beg (point))
19171 (org-end-of-subtree t)
19172 (setq end (point)))
19173 (set-buffer (get-buffer org-agenda-buffer-name))
19174 (save-excursion
19175 (goto-char (point-max))
19176 (beginning-of-line 1)
19177 (while (not (bobp))
19178 (when (and (setq m (get-text-property (point) 'org-marker))
19179 (equal buf (marker-buffer m))
19180 (setq p (marker-position m))
19181 (>= p beg)
19182 (<= p end))
19183 (let ((inhibit-read-only t))
19184 (delete-region (point-at-bol) (1+ (point-at-eol)))))
19185 (beginning-of-line 0))))))
19187 (defun org-agenda-open-link ()
19188 "Follow the link in the current line, if any."
19189 (interactive)
19190 (let ((eol (point-at-eol)))
19191 (save-excursion
19192 (if (or (re-search-forward org-bracket-link-regexp eol t)
19193 (re-search-forward org-angle-link-re eol t)
19194 (re-search-forward org-plain-link-re eol t))
19195 (call-interactively 'org-open-at-point)
19196 (error "No link in current line")))))
19198 (defun org-agenda-switch-to (&optional delete-other-windows)
19199 "Go to the Org-mode file which contains the item at point."
19200 (interactive)
19201 (let* ((marker (or (get-text-property (point) 'org-marker)
19202 (org-agenda-error)))
19203 (buffer (marker-buffer marker))
19204 (pos (marker-position marker)))
19205 (switch-to-buffer buffer)
19206 (and delete-other-windows (delete-other-windows))
19207 (widen)
19208 (goto-char pos)
19209 (when (org-mode-p)
19210 (org-show-context 'agenda)
19211 (save-excursion
19212 (and (outline-next-heading)
19213 (org-flag-heading nil)))))) ; show the next heading
19215 (defun org-agenda-goto-mouse (ev)
19216 "Go to the Org-mode file which contains the item at the mouse click."
19217 (interactive "e")
19218 (mouse-set-point ev)
19219 (org-agenda-goto))
19221 (defun org-agenda-show ()
19222 "Display the Org-mode file which contains the item at point."
19223 (interactive)
19224 (let ((win (selected-window)))
19225 (org-agenda-goto t)
19226 (select-window win)))
19228 (defun org-agenda-recenter (arg)
19229 "Display the Org-mode file which contains the item at point and recenter."
19230 (interactive "P")
19231 (let ((win (selected-window)))
19232 (org-agenda-goto t)
19233 (recenter arg)
19234 (select-window win)))
19236 (defun org-agenda-show-mouse (ev)
19237 "Display the Org-mode file which contains the item at the mouse click."
19238 (interactive "e")
19239 (mouse-set-point ev)
19240 (org-agenda-show))
19242 (defun org-agenda-check-no-diary ()
19243 "Check if the entry is a diary link and abort if yes."
19244 (if (get-text-property (point) 'org-agenda-diary-link)
19245 (org-agenda-error)))
19247 (defun org-agenda-error ()
19248 (error "Command not allowed in this line"))
19250 (defun org-agenda-tree-to-indirect-buffer ()
19251 "Show the subtree corresponding to the current entry in an indirect buffer.
19252 This calls the command `org-tree-to-indirect-buffer' from the original
19253 Org-mode buffer.
19254 With numerical prefix arg ARG, go up to this level and then take that tree.
19255 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
19256 dedicated frame)."
19257 (interactive)
19258 (org-agenda-check-no-diary)
19259 (let* ((marker (or (get-text-property (point) 'org-marker)
19260 (org-agenda-error)))
19261 (buffer (marker-buffer marker))
19262 (pos (marker-position marker)))
19263 (with-current-buffer buffer
19264 (save-excursion
19265 (goto-char pos)
19266 (call-interactively 'org-tree-to-indirect-buffer)))))
19268 (defvar org-last-heading-marker (make-marker)
19269 "Marker pointing to the headline that last changed its TODO state
19270 by a remote command from the agenda.")
19272 (defun org-agenda-todo-nextset ()
19273 "Switch TODO entry to next sequence."
19274 (interactive)
19275 (org-agenda-todo 'nextset))
19277 (defun org-agenda-todo-previousset ()
19278 "Switch TODO entry to previous sequence."
19279 (interactive)
19280 (org-agenda-todo 'previousset))
19282 (defun org-agenda-todo (&optional arg)
19283 "Cycle TODO state of line at point, also in Org-mode file.
19284 This changes the line at point, all other lines in the agenda referring to
19285 the same tree node, and the headline of the tree node in the Org-mode file."
19286 (interactive "P")
19287 (org-agenda-check-no-diary)
19288 (let* ((col (current-column))
19289 (marker (or (get-text-property (point) 'org-marker)
19290 (org-agenda-error)))
19291 (buffer (marker-buffer marker))
19292 (pos (marker-position marker))
19293 (hdmarker (get-text-property (point) 'org-hd-marker))
19294 (inhibit-read-only t)
19295 newhead)
19296 (org-with-remote-undo buffer
19297 (with-current-buffer buffer
19298 (widen)
19299 (goto-char pos)
19300 (org-show-context 'agenda)
19301 (save-excursion
19302 (and (outline-next-heading)
19303 (org-flag-heading nil))) ; show the next heading
19304 (org-todo arg)
19305 (and (bolp) (forward-char 1))
19306 (setq newhead (org-get-heading))
19307 (save-excursion
19308 (org-back-to-heading)
19309 (move-marker org-last-heading-marker (point))))
19310 (beginning-of-line 1)
19311 (save-excursion
19312 (org-agenda-change-all-lines newhead hdmarker 'fixface))
19313 (move-to-column col))))
19315 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
19316 "Change all lines in the agenda buffer which match HDMARKER.
19317 The new content of the line will be NEWHEAD (as modified by
19318 `org-format-agenda-item'). HDMARKER is checked with
19319 `equal' against all `org-hd-marker' text properties in the file.
19320 If FIXFACE is non-nil, the face of each item is modified acording to
19321 the new TODO state."
19322 (let* ((inhibit-read-only t)
19323 props m pl undone-face done-face finish new dotime cat tags)
19324 (save-excursion
19325 (goto-char (point-max))
19326 (beginning-of-line 1)
19327 (while (not finish)
19328 (setq finish (bobp))
19329 (when (and (setq m (get-text-property (point) 'org-hd-marker))
19330 (equal m hdmarker))
19331 (setq props (text-properties-at (point))
19332 dotime (get-text-property (point) 'dotime)
19333 cat (get-text-property (point) 'org-category)
19334 tags (get-text-property (point) 'tags)
19335 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
19336 pl (get-text-property (point) 'prefix-length)
19337 undone-face (get-text-property (point) 'undone-face)
19338 done-face (get-text-property (point) 'done-face))
19339 (move-to-column pl)
19340 (cond
19341 ((equal new "")
19342 (beginning-of-line 1)
19343 (and (looking-at ".*\n?") (replace-match "")))
19344 ((looking-at ".*")
19345 (replace-match new t t)
19346 (beginning-of-line 1)
19347 (add-text-properties (point-at-bol) (point-at-eol) props)
19348 (when fixface
19349 (add-text-properties
19350 (point-at-bol) (point-at-eol)
19351 (list 'face
19352 (if org-last-todo-state-is-todo
19353 undone-face done-face))))
19354 (org-agenda-highlight-todo 'line)
19355 (beginning-of-line 1))
19356 (t (error "Line update did not work"))))
19357 (beginning-of-line 0)))
19358 (org-finalize-agenda)))
19360 ;; FIXME: allow negative value for org-agenda-align-tags-to-column
19361 ;; See the code in set-tags for the way to do this.
19362 (defun org-agenda-align-tags (&optional line)
19363 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
19364 (let ((inhibit-read-only t))
19365 (save-excursion
19366 (goto-char (if line (point-at-bol) (point-min)))
19367 (while (re-search-forward (org-re "\\([ \t]+\\):[[:alnum:]_@:]+:[ \t]*$")
19368 (if line (point-at-eol) nil) t)
19369 (delete-region (match-beginning 1) (match-end 1))
19370 (goto-char (match-beginning 1))
19371 (insert (org-add-props
19372 (make-string (max 1 (- org-agenda-align-tags-to-column
19373 (current-column))) ?\ )
19374 (text-properties-at (point))))))))
19376 (defun org-agenda-priority-up ()
19377 "Increase the priority of line at point, also in Org-mode file."
19378 (interactive)
19379 (org-agenda-priority 'up))
19381 (defun org-agenda-priority-down ()
19382 "Decrease the priority of line at point, also in Org-mode file."
19383 (interactive)
19384 (org-agenda-priority 'down))
19386 (defun org-agenda-priority (&optional force-direction)
19387 "Set the priority of line at point, also in Org-mode file.
19388 This changes the line at point, all other lines in the agenda referring to
19389 the same tree node, and the headline of the tree node in the Org-mode file."
19390 (interactive)
19391 (org-agenda-check-no-diary)
19392 (let* ((marker (or (get-text-property (point) 'org-marker)
19393 (org-agenda-error)))
19394 (hdmarker (get-text-property (point) 'org-hd-marker))
19395 (buffer (marker-buffer hdmarker))
19396 (pos (marker-position hdmarker))
19397 (inhibit-read-only t)
19398 newhead)
19399 (org-with-remote-undo buffer
19400 (with-current-buffer buffer
19401 (widen)
19402 (goto-char pos)
19403 (org-show-context 'agenda)
19404 (save-excursion
19405 (and (outline-next-heading)
19406 (org-flag-heading nil))) ; show the next heading
19407 (funcall 'org-priority force-direction)
19408 (end-of-line 1)
19409 (setq newhead (org-get-heading)))
19410 (org-agenda-change-all-lines newhead hdmarker)
19411 (beginning-of-line 1))))
19413 (defun org-get-tags-at (&optional pos)
19414 "Get a list of all headline tags applicable at POS.
19415 POS defaults to point. If tags are inherited, the list contains
19416 the targets in the same sequence as the headlines appear, i.e.
19417 the tags of the current headline come last."
19418 (interactive)
19419 (let (tags)
19420 (save-excursion
19421 (save-restriction
19422 (widen)
19423 (goto-char (or pos (point)))
19424 (save-match-data
19425 (org-back-to-heading t)
19426 (condition-case nil
19427 (while t
19428 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
19429 (setq tags (append (org-split-string
19430 (org-match-string-no-properties 1) ":")
19431 tags)))
19432 (or org-use-tag-inheritance (error ""))
19433 (org-up-heading-all 1))
19434 (error nil))))
19435 tags)))
19437 ;; FIXME: should fix the tags property of the agenda line.
19438 (defun org-agenda-set-tags ()
19439 "Set tags for the current headline."
19440 (interactive)
19441 (org-agenda-check-no-diary)
19442 (if (and (org-region-active-p) (interactive-p))
19443 (call-interactively 'org-change-tag-in-region)
19444 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
19445 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
19446 (org-agenda-error)))
19447 (buffer (marker-buffer hdmarker))
19448 (pos (marker-position hdmarker))
19449 (inhibit-read-only t)
19450 newhead)
19451 (org-with-remote-undo buffer
19452 (with-current-buffer buffer
19453 (widen)
19454 (goto-char pos)
19455 (save-excursion
19456 (org-show-context 'agenda))
19457 (save-excursion
19458 (and (outline-next-heading)
19459 (org-flag-heading nil))) ; show the next heading
19460 (goto-char pos)
19461 (call-interactively 'org-set-tags)
19462 (end-of-line 1)
19463 (setq newhead (org-get-heading)))
19464 (org-agenda-change-all-lines newhead hdmarker)
19465 (beginning-of-line 1)))))
19467 (defun org-agenda-toggle-archive-tag ()
19468 "Toggle the archive tag for the current entry."
19469 (interactive)
19470 (org-agenda-check-no-diary)
19471 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
19472 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
19473 (org-agenda-error)))
19474 (buffer (marker-buffer hdmarker))
19475 (pos (marker-position hdmarker))
19476 (inhibit-read-only t)
19477 newhead)
19478 (org-with-remote-undo buffer
19479 (with-current-buffer buffer
19480 (widen)
19481 (goto-char pos)
19482 (org-show-context 'agenda)
19483 (save-excursion
19484 (and (outline-next-heading)
19485 (org-flag-heading nil))) ; show the next heading
19486 (call-interactively 'org-toggle-archive-tag)
19487 (end-of-line 1)
19488 (setq newhead (org-get-heading)))
19489 (org-agenda-change-all-lines newhead hdmarker)
19490 (beginning-of-line 1))))
19492 (defun org-agenda-date-later (arg &optional what)
19493 "Change the date of this item to one day later."
19494 (interactive "p")
19495 (org-agenda-check-type t 'agenda 'timeline)
19496 (org-agenda-check-no-diary)
19497 (let* ((marker (or (get-text-property (point) 'org-marker)
19498 (org-agenda-error)))
19499 (buffer (marker-buffer marker))
19500 (pos (marker-position marker)))
19501 (org-with-remote-undo buffer
19502 (with-current-buffer buffer
19503 (widen)
19504 (goto-char pos)
19505 (if (not (org-at-timestamp-p))
19506 (error "Cannot find time stamp"))
19507 (org-timestamp-change arg (or what 'day)))
19508 (org-agenda-show-new-time marker org-last-changed-timestamp))
19509 (message "Time stamp changed to %s" org-last-changed-timestamp)))
19511 (defun org-agenda-date-earlier (arg &optional what)
19512 "Change the date of this item to one day earlier."
19513 (interactive "p")
19514 (org-agenda-date-later (- arg) what))
19516 (defun org-agenda-show-new-time (marker stamp)
19517 "Show new date stamp via text properties."
19518 ;; We use text properties to make this undoable
19519 (let ((inhibit-read-only t))
19520 (setq stamp (concat " => " stamp))
19521 (save-excursion
19522 (goto-char (point-max))
19523 (while (not (bobp))
19524 (when (equal marker (get-text-property (point) 'org-marker))
19525 (move-to-column (- (window-width) (length stamp)) t)
19526 (if (featurep 'xemacs)
19527 ;; Use `duplicable' property to trigger undo recording
19528 (let ((ex (make-extent nil nil))
19529 (gl (make-glyph stamp)))
19530 (set-glyph-face gl 'secondary-selection)
19531 (set-extent-properties
19532 ex (list 'invisible t 'end-glyph gl 'duplicable t))
19533 (insert-extent ex (1- (point)) (point-at-eol)))
19534 (add-text-properties
19535 (1- (point)) (point-at-eol)
19536 (list 'display (org-add-props stamp nil
19537 'face 'secondary-selection))))
19538 (beginning-of-line 1))
19539 (beginning-of-line 0)))))
19541 (defun org-agenda-date-prompt (arg)
19542 "Change the date of this item. Date is prompted for, with default today.
19543 The prefix ARG is passed to the `org-time-stamp' command and can therefore
19544 be used to request time specification in the time stamp."
19545 (interactive "P")
19546 (org-agenda-check-type t 'agenda 'timeline)
19547 (org-agenda-check-no-diary)
19548 (let* ((marker (or (get-text-property (point) 'org-marker)
19549 (org-agenda-error)))
19550 (buffer (marker-buffer marker))
19551 (pos (marker-position marker)))
19552 (org-with-remote-undo buffer
19553 (with-current-buffer buffer
19554 (widen)
19555 (goto-char pos)
19556 (if (not (org-at-timestamp-p))
19557 (error "Cannot find time stamp"))
19558 (org-time-stamp arg)
19559 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
19561 (defun org-agenda-schedule (arg)
19562 "Schedule the item at point."
19563 (interactive "P")
19564 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
19565 (org-agenda-check-no-diary)
19566 (let* ((marker (or (get-text-property (point) 'org-marker)
19567 (org-agenda-error)))
19568 (buffer (marker-buffer marker))
19569 (pos (marker-position marker))
19570 (org-insert-labeled-timestamps-at-point nil)
19572 (org-with-remote-undo buffer
19573 (with-current-buffer buffer
19574 (widen)
19575 (goto-char pos)
19576 (setq ts (org-schedule))
19577 (message "Item scheduled for %s" ts)))))
19579 (defun org-agenda-deadline (arg)
19580 "Schedule the item at point."
19581 (interactive "P")
19582 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
19583 (org-agenda-check-no-diary)
19584 (let* ((marker (or (get-text-property (point) 'org-marker)
19585 (org-agenda-error)))
19586 (buffer (marker-buffer marker))
19587 (pos (marker-position marker))
19588 (org-insert-labeled-timestamps-at-point nil)
19590 (org-with-remote-undo buffer
19591 (with-current-buffer buffer
19592 (widen)
19593 (goto-char pos)
19594 (setq ts (org-deadline))
19595 (message "Deadline for this item set to %s" ts)))))
19597 (defun org-get-heading ()
19598 "Return the heading of the current entry, without the stars."
19599 (save-excursion
19600 (org-back-to-heading t)
19601 (if (looking-at "\\*+[ \t]+\\([^\r\n]*\\)") (match-string 1) "")))
19603 (defun org-agenda-clock-in (&optional arg)
19604 "Start the clock on the currently selected item."
19605 (interactive "P")
19606 (org-agenda-check-no-diary)
19607 (let* ((marker (or (get-text-property (point) 'org-marker)
19608 (org-agenda-error)))
19609 (pos (marker-position marker)))
19610 (org-with-remote-undo (marker-buffer marker)
19611 (with-current-buffer (marker-buffer marker)
19612 (widen)
19613 (goto-char pos)
19614 (org-clock-in)))))
19616 (defun org-agenda-clock-out (&optional arg)
19617 "Stop the currently running clock."
19618 (interactive "P")
19619 (unless (marker-buffer org-clock-marker)
19620 (error "No running clock"))
19621 (org-with-remote-undo (marker-buffer org-clock-marker)
19622 (org-clock-out)))
19624 (defun org-agenda-clock-cancel (&optional arg)
19625 "Cancel the currently running clock."
19626 (interactive "P")
19627 (unless (marker-buffer org-clock-marker)
19628 (error "No running clock"))
19629 (org-with-remote-undo (marker-buffer org-clock-marker)
19630 (org-clock-cancel)))
19632 (defun org-agenda-diary-entry ()
19633 "Make a diary entry, like the `i' command from the calendar.
19634 All the standard commands work: block, weekly etc."
19635 (interactive)
19636 (org-agenda-check-type t 'agenda 'timeline)
19637 (require 'diary-lib)
19638 (let* ((char (progn
19639 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
19640 (read-char-exclusive)))
19641 (cmd (cdr (assoc char
19642 '((?d . insert-diary-entry)
19643 (?w . insert-weekly-diary-entry)
19644 (?m . insert-monthly-diary-entry)
19645 (?y . insert-yearly-diary-entry)
19646 (?a . insert-anniversary-diary-entry)
19647 (?b . insert-block-diary-entry)
19648 (?c . insert-cyclic-diary-entry)))))
19649 (oldf (symbol-function 'calendar-cursor-to-date))
19650 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
19651 (point (point))
19652 (mark (or (mark t) (point))))
19653 (unless cmd
19654 (error "No command associated with <%c>" char))
19655 (unless (and (get-text-property point 'day)
19656 (or (not (equal ?b char))
19657 (get-text-property mark 'day)))
19658 (error "Don't know which date to use for diary entry"))
19659 ;; We implement this by hacking the `calendar-cursor-to-date' function
19660 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
19661 (let ((calendar-mark-ring
19662 (list (calendar-gregorian-from-absolute
19663 (or (get-text-property mark 'day)
19664 (get-text-property point 'day))))))
19665 (unwind-protect
19666 (progn
19667 (fset 'calendar-cursor-to-date
19668 (lambda (&optional error)
19669 (calendar-gregorian-from-absolute
19670 (get-text-property point 'day))))
19671 (call-interactively cmd))
19672 (fset 'calendar-cursor-to-date oldf)))))
19675 (defun org-agenda-execute-calendar-command (cmd)
19676 "Execute a calendar command from the agenda, with the date associated to
19677 the cursor position."
19678 (org-agenda-check-type t 'agenda 'timeline)
19679 (require 'diary-lib)
19680 (unless (get-text-property (point) 'day)
19681 (error "Don't know which date to use for calendar command"))
19682 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
19683 (point (point))
19684 (date (calendar-gregorian-from-absolute
19685 (get-text-property point 'day)))
19686 ;; the following 3 vars are needed in the calendar
19687 (displayed-day (extract-calendar-day date))
19688 (displayed-month (extract-calendar-month date))
19689 (displayed-year (extract-calendar-year date)))
19690 (unwind-protect
19691 (progn
19692 (fset 'calendar-cursor-to-date
19693 (lambda (&optional error)
19694 (calendar-gregorian-from-absolute
19695 (get-text-property point 'day))))
19696 (call-interactively cmd))
19697 (fset 'calendar-cursor-to-date oldf))))
19699 (defun org-agenda-phases-of-moon ()
19700 "Display the phases of the moon for the 3 months around the cursor date."
19701 (interactive)
19702 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
19704 (defun org-agenda-holidays ()
19705 "Display the holidays for the 3 months around the cursor date."
19706 (interactive)
19707 (org-agenda-execute-calendar-command 'list-calendar-holidays))
19709 (defun org-agenda-sunrise-sunset (arg)
19710 "Display sunrise and sunset for the cursor date.
19711 Latitude and longitude can be specified with the variables
19712 `calendar-latitude' and `calendar-longitude'. When called with prefix
19713 argument, latitude and longitude will be prompted for."
19714 (interactive "P")
19715 (let ((calendar-longitude (if arg nil calendar-longitude))
19716 (calendar-latitude (if arg nil calendar-latitude))
19717 (calendar-location-name
19718 (if arg "the given coordinates" calendar-location-name)))
19719 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
19721 (defun org-agenda-goto-calendar ()
19722 "Open the Emacs calendar with the date at the cursor."
19723 (interactive)
19724 (org-agenda-check-type t 'agenda 'timeline)
19725 (let* ((day (or (get-text-property (point) 'day)
19726 (error "Don't know which date to open in calendar")))
19727 (date (calendar-gregorian-from-absolute day))
19728 (calendar-move-hook nil)
19729 (view-calendar-holidays-initially nil)
19730 (view-diary-entries-initially nil))
19731 (calendar)
19732 (calendar-goto-date date)))
19734 (defun org-calendar-goto-agenda ()
19735 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
19736 This is a command that has to be installed in `calendar-mode-map'."
19737 (interactive)
19738 (org-agenda-list nil (calendar-absolute-from-gregorian
19739 (calendar-cursor-to-date))
19740 nil))
19742 (defun org-agenda-convert-date ()
19743 (interactive)
19744 (org-agenda-check-type t 'agenda 'timeline)
19745 (let ((day (get-text-property (point) 'day))
19746 date s)
19747 (unless day
19748 (error "Don't know which date to convert"))
19749 (setq date (calendar-gregorian-from-absolute day))
19750 (setq s (concat
19751 "Gregorian: " (calendar-date-string date) "\n"
19752 "ISO: " (calendar-iso-date-string date) "\n"
19753 "Day of Yr: " (calendar-day-of-year-string date) "\n"
19754 "Julian: " (calendar-julian-date-string date) "\n"
19755 "Astron. JD: " (calendar-astro-date-string date)
19756 " (Julian date number at noon UTC)\n"
19757 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
19758 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
19759 "French: " (calendar-french-date-string date) "\n"
19760 "Mayan: " (calendar-mayan-date-string date) "\n"
19761 "Coptic: " (calendar-coptic-date-string date) "\n"
19762 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
19763 "Persian: " (calendar-persian-date-string date) "\n"
19764 "Chinese: " (calendar-chinese-date-string date) "\n"))
19765 (with-output-to-temp-buffer "*Dates*"
19766 (princ s))
19767 (if (fboundp 'fit-window-to-buffer)
19768 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
19771 ;;;; Embedded LaTeX
19773 (defvar org-cdlatex-mode-map (make-sparse-keymap)
19774 "Keymap for the minor `org-cdlatex-mode'.")
19776 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
19777 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
19778 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
19779 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
19780 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
19782 (defvar org-cdlatex-texmathp-advice-is-done nil
19783 "Flag remembering if we have applied the advice to texmathp already.")
19785 (define-minor-mode org-cdlatex-mode
19786 "Toggle the minor `org-cdlatex-mode'.
19787 This mode supports entering LaTeX environment and math in LaTeX fragments
19788 in Org-mode.
19789 \\{org-cdlatex-mode-map}"
19790 nil " OCDL" nil
19791 (when org-cdlatex-mode (require 'cdlatex))
19792 (unless org-cdlatex-texmathp-advice-is-done
19793 (setq org-cdlatex-texmathp-advice-is-done t)
19794 (defadvice texmathp (around org-math-always-on activate)
19795 "Always return t in org-mode buffers.
19796 This is because we want to insert math symbols without dollars even outside
19797 the LaTeX math segments. If Orgmode thinks that point is actually inside
19798 en embedded LaTeX fragement, let texmathp do its job.
19799 \\[org-cdlatex-mode-map]"
19800 (interactive)
19801 (let (p)
19802 (cond
19803 ((not (org-mode-p)) ad-do-it)
19804 ((eq this-command 'cdlatex-math-symbol)
19805 (setq ad-return-value t
19806 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
19808 (let ((p (org-inside-LaTeX-fragment-p)))
19809 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
19810 (setq ad-return-value t
19811 texmathp-why '("Org-mode embedded math" . 0))
19812 (if p ad-do-it)))))))))
19814 (defun turn-on-org-cdlatex ()
19815 "Unconditionally turn on `org-cdlatex-mode'."
19816 (org-cdlatex-mode 1))
19818 (defun org-inside-LaTeX-fragment-p ()
19819 "Test if point is inside a LaTeX fragment.
19820 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19821 sequence appearing also before point.
19822 Even though the matchers for math are configurable, this function assumes
19823 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19824 delimiters are skipped when they have been removed by customization.
19825 The return value is nil, or a cons cell with the delimiter and
19826 and the position of this delimiter.
19828 This function does a reasonably good job, but can locally be fooled by
19829 for example currency specifications. For example it will assume being in
19830 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19831 fragments that are properly closed, but during editing, we have to live
19832 with the uncertainty caused by missing closing delimiters. This function
19833 looks only before point, not after."
19834 (catch 'exit
19835 (let ((pos (point))
19836 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19837 (lim (progn
19838 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19839 (point)))
19840 dd-on str (start 0) m re)
19841 (goto-char pos)
19842 (when dodollar
19843 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19844 re (nth 1 (assoc "$" org-latex-regexps)))
19845 (while (string-match re str start)
19846 (cond
19847 ((= (match-end 0) (length str))
19848 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19849 ((= (match-end 0) (- (length str) 5))
19850 (throw 'exit nil))
19851 (t (setq start (match-end 0))))))
19852 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19853 (goto-char pos)
19854 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19855 (and (match-beginning 2) (throw 'exit nil))
19856 ;; count $$
19857 (while (re-search-backward "\\$\\$" lim t)
19858 (setq dd-on (not dd-on)))
19859 (goto-char pos)
19860 (if dd-on (cons "$$" m))))))
19863 (defun org-try-cdlatex-tab ()
19864 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
19865 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
19866 - inside a LaTeX fragment, or
19867 - after the first word in a line, where an abbreviation expansion could
19868 insert a LaTeX environment."
19869 (when org-cdlatex-mode
19870 (cond
19871 ((save-excursion
19872 (skip-chars-backward "a-zA-Z0-9*")
19873 (skip-chars-backward " \t")
19874 (bolp))
19875 (cdlatex-tab) t)
19876 ((org-inside-LaTeX-fragment-p)
19877 (cdlatex-tab) t)
19878 (t nil))))
19880 (defun org-cdlatex-underscore-caret (&optional arg)
19881 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
19882 Revert to the normal definition outside of these fragments."
19883 (interactive "P")
19884 (if (org-inside-LaTeX-fragment-p)
19885 (call-interactively 'cdlatex-sub-superscript)
19886 (let (org-cdlatex-mode)
19887 (call-interactively (key-binding (vector last-input-event))))))
19889 (defun org-cdlatex-math-modify (&optional arg)
19890 "Execute `cdlatex-math-modify' in LaTeX fragments.
19891 Revert to the normal definition outside of these fragments."
19892 (interactive "P")
19893 (if (org-inside-LaTeX-fragment-p)
19894 (call-interactively 'cdlatex-math-modify)
19895 (let (org-cdlatex-mode)
19896 (call-interactively (key-binding (vector last-input-event))))))
19898 (defvar org-latex-fragment-image-overlays nil
19899 "List of overlays carrying the images of latex fragments.")
19900 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
19902 (defun org-remove-latex-fragment-image-overlays ()
19903 "Remove all overlays with LaTeX fragment images in current buffer."
19904 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
19905 (setq org-latex-fragment-image-overlays nil))
19907 (defun org-preview-latex-fragment (&optional subtree)
19908 "Preview the LaTeX fragment at point, or all locally or globally.
19909 If the cursor is in a LaTeX fragment, create the image and overlay
19910 it over the source code. If there is no fragment at point, display
19911 all fragments in the current text, from one headline to the next. With
19912 prefix SUBTREE, display all fragments in the current subtree. With a
19913 double prefix `C-u C-u', or when the cursor is before the first headline,
19914 display all fragments in the buffer.
19915 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
19916 (interactive "P")
19917 (org-remove-latex-fragment-image-overlays)
19918 (save-excursion
19919 (save-restriction
19920 (let (beg end at msg)
19921 (cond
19922 ((or (equal subtree '(16))
19923 (not (save-excursion
19924 (re-search-backward (concat "^" outline-regexp) nil t))))
19925 (setq beg (point-min) end (point-max)
19926 msg "Creating images for buffer...%s"))
19927 ((equal subtree '(4))
19928 (org-back-to-heading)
19929 (setq beg (point) end (org-end-of-subtree t)
19930 msg "Creating images for subtree...%s"))
19932 (if (setq at (org-inside-LaTeX-fragment-p))
19933 (goto-char (max (point-min) (- (cdr at) 2)))
19934 (org-back-to-heading))
19935 (setq beg (point) end (progn (outline-next-heading) (point))
19936 msg (if at "Creating image...%s"
19937 "Creating images for entry...%s"))))
19938 (message msg "")
19939 (narrow-to-region beg end)
19940 (goto-char beg)
19941 (org-format-latex
19942 (concat "ltxpng/" (file-name-sans-extension
19943 (file-name-nondirectory
19944 buffer-file-name)))
19945 default-directory 'overlays msg at 'forbuffer)
19946 (message msg "done. Use `C-c C-c' to remove images.")))))
19948 (defvar org-latex-regexps
19949 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
19950 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
19951 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
19952 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
19953 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
19954 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
19955 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
19956 "Regular expressions for matching embedded LaTeX.")
19958 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
19959 "Replace LaTeX fragments with links to an image, and produce images."
19960 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19961 (let* ((prefixnodir (file-name-nondirectory prefix))
19962 (absprefix (expand-file-name prefix dir))
19963 (todir (file-name-directory absprefix))
19964 (opt org-format-latex-options)
19965 (matchers (plist-get opt :matchers))
19966 (re-list org-latex-regexps)
19967 (cnt 0) txt link beg end re e checkdir
19968 m n block linkfile movefile ov)
19969 ;; Check if there are old images files with this prefix, and remove them
19970 (when (file-directory-p todir)
19971 (mapc 'delete-file
19972 (directory-files
19973 todir 'full
19974 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
19975 ;; Check the different regular expressions
19976 (while (setq e (pop re-list))
19977 (setq m (car e) re (nth 1 e) n (nth 2 e)
19978 block (if (nth 3 e) "\n\n" ""))
19979 (when (member m matchers)
19980 (goto-char (point-min))
19981 (while (re-search-forward re nil t)
19982 (when (or (not at) (equal (cdr at) (match-beginning n)))
19983 (setq txt (match-string n)
19984 beg (match-beginning n) end (match-end n)
19985 cnt (1+ cnt)
19986 linkfile (format "%s_%04d.png" prefix cnt)
19987 movefile (format "%s_%04d.png" absprefix cnt)
19988 link (concat block "[[file:" linkfile "]]" block))
19989 (if msg (message msg cnt))
19990 (goto-char beg)
19991 (unless checkdir ; make sure the directory exists
19992 (setq checkdir t)
19993 (or (file-directory-p todir) (make-directory todir)))
19994 (org-create-formula-image
19995 txt movefile opt forbuffer)
19996 (if overlays
19997 (progn
19998 (setq ov (org-make-overlay beg end))
19999 (if (featurep 'xemacs)
20000 (progn
20001 (org-overlay-put ov 'invisible t)
20002 (org-overlay-put
20003 ov 'end-glyph
20004 (make-glyph (vector 'png :file movefile))))
20005 (org-overlay-put
20006 ov 'display
20007 (list 'image :type 'png :file movefile :ascent 'center)))
20008 (push ov org-latex-fragment-image-overlays)
20009 (goto-char end))
20010 (delete-region beg end)
20011 (insert link))))))))
20013 ;; This function borrows from Ganesh Swami's latex2png.el
20014 (defun org-create-formula-image (string tofile options buffer)
20015 (let* ((tmpdir (if (featurep 'xemacs)
20016 (temp-directory)
20017 temporary-file-directory))
20018 (texfilebase (make-temp-name
20019 (expand-file-name "orgtex" tmpdir)))
20020 (texfile (concat texfilebase ".tex"))
20021 (dvifile (concat texfilebase ".dvi"))
20022 (pngfile (concat texfilebase ".png"))
20023 (fnh (face-attribute 'default :height nil))
20024 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
20025 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
20026 (fg (or (plist-get options (if buffer :foreground :html-foreground))
20027 "Black"))
20028 (bg (or (plist-get options (if buffer :background :html-background))
20029 "Transparent")))
20030 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
20031 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
20032 (with-temp-file texfile
20033 (insert org-format-latex-header
20034 "\n\\begin{document}\n" string "\n\\end{document}\n"))
20035 (let ((dir default-directory))
20036 (condition-case nil
20037 (progn
20038 (cd tmpdir)
20039 (call-process "latex" nil nil nil texfile))
20040 (error nil))
20041 (cd dir))
20042 (if (not (file-exists-p dvifile))
20043 (progn (message "Failed to create dvi file from %s" texfile) nil)
20044 (call-process "dvipng" nil nil nil
20045 "-E" "-fg" fg "-bg" bg
20046 "-D" dpi
20047 ;;"-x" scale "-y" scale
20048 "-T" "tight"
20049 "-o" pngfile
20050 dvifile)
20051 (if (not (file-exists-p pngfile))
20052 (progn (message "Failed to create png file from %s" texfile) nil)
20053 ;; Use the requested file name and clean up
20054 (copy-file pngfile tofile 'replace)
20055 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
20056 (delete-file (concat texfilebase e)))
20057 pngfile))))
20059 (defun org-dvipng-color (attr)
20060 "Return an rgb color specification for dvipng."
20061 (apply 'format "rgb %s %s %s"
20062 (mapcar 'org-normalize-color
20063 (color-values (face-attribute 'default attr nil)))))
20065 (defun org-normalize-color (value)
20066 "Return string to be used as color value for an RGB component."
20067 (format "%g" (/ value 65535.0)))
20069 ;;;; Exporting
20071 ;;; Variables, constants, and parameter plists
20073 (defconst org-level-max 20)
20075 (defvar org-export-html-preamble nil
20076 "Preamble, to be inserted just after <body>. Set by publishing functions.")
20077 (defvar org-export-html-postamble nil
20078 "Preamble, to be inserted just before </body>. Set by publishing functions.")
20079 (defvar org-export-html-auto-preamble t
20080 "Should default preamble be inserted? Set by publishing functions.")
20081 (defvar org-export-html-auto-postamble t
20082 "Should default postamble be inserted? Set by publishing functions.")
20083 (defvar org-current-export-file nil) ; dynamically scoped parameter
20084 (defvar org-current-export-dir nil) ; dynamically scoped parameter
20087 (defconst org-export-plist-vars
20088 '((:language . org-export-default-language)
20089 (:customtime . org-display-custom-times)
20090 (:headline-levels . org-export-headline-levels)
20091 (:section-numbers . org-export-with-section-numbers)
20092 (:table-of-contents . org-export-with-toc)
20093 (:preserve-breaks . org-export-preserve-breaks)
20094 (:archived-trees . org-export-with-archived-trees)
20095 (:emphasize . org-export-with-emphasize)
20096 (:sub-superscript . org-export-with-sub-superscripts)
20097 (:footnotes . org-export-with-footnotes)
20098 (:property-drawer . org-export-with-property-drawer)
20099 (:TeX-macros . org-export-with-TeX-macros)
20100 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
20101 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
20102 (:fixed-width . org-export-with-fixed-width)
20103 (:timestamps . org-export-with-timestamps)
20104 (:author-info . org-export-author-info)
20105 (:time-stamp-file . org-export-time-stamp-file)
20106 (:tables . org-export-with-tables)
20107 (:table-auto-headline . org-export-highlight-first-table-line)
20108 (:style . org-export-html-style)
20109 (:agenda-style . org-agenda-export-html-style) ;; FIXME: Does this work????
20110 (:convert-org-links . org-export-html-link-org-files-as-html)
20111 (:inline-images . org-export-html-inline-images)
20112 (:expand-quoted-html . org-export-html-expand)
20113 (:timestamp . org-export-html-with-timestamp)
20114 (:publishing-directory . org-export-publishing-directory)
20115 (:preamble . org-export-html-preamble)
20116 (:postamble . org-export-html-postamble)
20117 (:auto-preamble . org-export-html-auto-preamble)
20118 (:auto-postamble . org-export-html-auto-postamble)
20119 (:author . user-full-name)
20120 (:email . user-mail-address)))
20122 (defun org-default-export-plist ()
20123 "Return the property list with default settings for the export variables."
20124 (let ((l org-export-plist-vars) rtn e)
20125 (while (setq e (pop l))
20126 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
20127 rtn))
20129 (defun org-infile-export-plist ()
20130 "Return the property list with file-local settings for export."
20131 (save-excursion
20132 (goto-char 0)
20133 (let ((re (org-make-options-regexp
20134 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
20135 p key val text options)
20136 (while (re-search-forward re nil t)
20137 (setq key (org-match-string-no-properties 1)
20138 val (org-match-string-no-properties 2))
20139 (cond
20140 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
20141 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
20142 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
20143 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
20144 ((string-equal key "TEXT")
20145 (setq text (if text (concat text "\n" val) val)))
20146 ((string-equal key "OPTIONS") (setq options val))))
20147 (setq p (plist-put p :text text))
20148 (when options
20149 (let ((op '(("H" . :headline-levels)
20150 ("num" . :section-numbers)
20151 ("toc" . :table-of-contents)
20152 ("\\n" . :preserve-breaks)
20153 ("@" . :expand-quoted-html)
20154 (":" . :fixed-width)
20155 ("|" . :tables)
20156 ("^" . :sub-superscript)
20157 ("f" . :footnotes)
20158 ("p" . :property-drawer)
20159 ("*" . :emphasize)
20160 ("TeX" . :TeX-macros)
20161 ("LaTeX" . :LaTeX-fragments)
20162 ("skip" . :skip-before-1st-heading)
20163 ("author" . :author-info)
20164 ("timestamp" . :time-stamp-file)))
20166 (while (setq o (pop op))
20167 (if (string-match (concat (regexp-quote (car o))
20168 ":\\([^ \t\n\r;,.]*\\)")
20169 options)
20170 (setq p (plist-put p (cdr o)
20171 (car (read-from-string
20172 (match-string 1 options)))))))))
20173 p)))
20175 (defun org-export-directory (type plist)
20176 (let* ((val (plist-get plist :publishing-directory))
20177 (dir (if (listp val)
20178 (or (cdr (assoc type val)) ".")
20179 val)))
20180 dir))
20182 (defun org-skip-comments (lines)
20183 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
20184 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
20185 (re2 "^\\(\\*+\\)[ \t\n\r]")
20186 (case-fold-search nil)
20187 rtn line level)
20188 (while (setq line (pop lines))
20189 (cond
20190 ((and (string-match re1 line)
20191 (setq level (- (match-end 1) (match-beginning 1))))
20192 ;; Beginning of a COMMENT subtree. Skip it.
20193 (while (and (setq line (pop lines))
20194 (or (not (string-match re2 line))
20195 (> (- (match-end 1) (match-beginning 1)) level))))
20196 (setq lines (cons line lines)))
20197 ((string-match "^#" line)
20198 ;; an ordinary comment line
20200 ((and org-export-table-remove-special-lines
20201 (string-match "^[ \t]*|" line)
20202 (or (string-match "^[ \t]*| *[!_^] *|" line)
20203 (and (string-match "| *<[0-9]+> *|" line)
20204 (not (string-match "| *[^ <|]" line)))))
20205 ;; a special table line that should be removed
20207 (t (setq rtn (cons line rtn)))))
20208 (nreverse rtn)))
20210 (defun org-export (&optional arg)
20211 (interactive)
20212 (let ((help "[t] insert the export option template
20213 \[v] limit export to visible part of outline tree
20215 \[a] export as ASCII
20217 \[h] export as HTML
20218 \[H] export as HTML to temporary buffer
20219 \[R] export region as HTML
20220 \[b] export as HTML and browse immediately
20221 \[x] export as XOXO
20223 \[l] export as LaTeX
20224 \[L] export as LaTeX to temporary buffer
20226 \[i] export current file as iCalendar file
20227 \[I] export all agenda files as iCalendar files
20228 \[c] export agenda files into combined iCalendar file
20230 \[F] publish current file
20231 \[P] publish current project
20232 \[X] publish... (project will be prompted for)
20233 \[A] publish all projects")
20234 (cmds
20235 '((?t . org-insert-export-options-template)
20236 (?v . org-export-visible)
20237 (?a . org-export-as-ascii)
20238 (?h . org-export-as-html)
20239 (?b . org-export-as-html-and-open)
20240 (?H . org-export-as-html-to-buffer)
20241 (?R . org-export-region-as-html)
20242 (?x . org-export-as-xoxo)
20243 (?l . org-export-as-latex)
20244 (?L . org-export-as-latex-to-buffer)
20245 (?i . org-export-icalendar-this-file)
20246 (?I . org-export-icalendar-all-agenda-files)
20247 (?c . org-export-icalendar-combine-agenda-files)
20248 (?F . org-publish-current-file)
20249 (?P . org-publish-current-project)
20250 (?X . org-publish)
20251 (?A . org-publish-all)))
20252 r1 r2 ass)
20253 (save-window-excursion
20254 (delete-other-windows)
20255 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
20256 (princ help))
20257 (message "Select command: ")
20258 (setq r1 (read-char-exclusive)))
20259 (setq r2 (if (< r1 27) (+ r1 96) r1))
20260 (if (setq ass (assq r2 cmds))
20261 (call-interactively (cdr ass))
20262 (error "No command associated with key %c" r1))))
20264 (defconst org-html-entities
20265 '(("nbsp")
20266 ("iexcl")
20267 ("cent")
20268 ("pound")
20269 ("curren")
20270 ("yen")
20271 ("brvbar")
20272 ("vert" . "&#124;")
20273 ("sect")
20274 ("uml")
20275 ("copy")
20276 ("ordf")
20277 ("laquo")
20278 ("not")
20279 ("shy")
20280 ("reg")
20281 ("macr")
20282 ("deg")
20283 ("plusmn")
20284 ("sup2")
20285 ("sup3")
20286 ("acute")
20287 ("micro")
20288 ("para")
20289 ("middot")
20290 ("odot"."o")
20291 ("star"."*")
20292 ("cedil")
20293 ("sup1")
20294 ("ordm")
20295 ("raquo")
20296 ("frac14")
20297 ("frac12")
20298 ("frac34")
20299 ("iquest")
20300 ("Agrave")
20301 ("Aacute")
20302 ("Acirc")
20303 ("Atilde")
20304 ("Auml")
20305 ("Aring") ("AA"."&Aring;")
20306 ("AElig")
20307 ("Ccedil")
20308 ("Egrave")
20309 ("Eacute")
20310 ("Ecirc")
20311 ("Euml")
20312 ("Igrave")
20313 ("Iacute")
20314 ("Icirc")
20315 ("Iuml")
20316 ("ETH")
20317 ("Ntilde")
20318 ("Ograve")
20319 ("Oacute")
20320 ("Ocirc")
20321 ("Otilde")
20322 ("Ouml")
20323 ("times")
20324 ("Oslash")
20325 ("Ugrave")
20326 ("Uacute")
20327 ("Ucirc")
20328 ("Uuml")
20329 ("Yacute")
20330 ("THORN")
20331 ("szlig")
20332 ("agrave")
20333 ("aacute")
20334 ("acirc")
20335 ("atilde")
20336 ("auml")
20337 ("aring")
20338 ("aelig")
20339 ("ccedil")
20340 ("egrave")
20341 ("eacute")
20342 ("ecirc")
20343 ("euml")
20344 ("igrave")
20345 ("iacute")
20346 ("icirc")
20347 ("iuml")
20348 ("eth")
20349 ("ntilde")
20350 ("ograve")
20351 ("oacute")
20352 ("ocirc")
20353 ("otilde")
20354 ("ouml")
20355 ("divide")
20356 ("oslash")
20357 ("ugrave")
20358 ("uacute")
20359 ("ucirc")
20360 ("uuml")
20361 ("yacute")
20362 ("thorn")
20363 ("yuml")
20364 ("fnof")
20365 ("Alpha")
20366 ("Beta")
20367 ("Gamma")
20368 ("Delta")
20369 ("Epsilon")
20370 ("Zeta")
20371 ("Eta")
20372 ("Theta")
20373 ("Iota")
20374 ("Kappa")
20375 ("Lambda")
20376 ("Mu")
20377 ("Nu")
20378 ("Xi")
20379 ("Omicron")
20380 ("Pi")
20381 ("Rho")
20382 ("Sigma")
20383 ("Tau")
20384 ("Upsilon")
20385 ("Phi")
20386 ("Chi")
20387 ("Psi")
20388 ("Omega")
20389 ("alpha")
20390 ("beta")
20391 ("gamma")
20392 ("delta")
20393 ("epsilon")
20394 ("varepsilon"."&epsilon;")
20395 ("zeta")
20396 ("eta")
20397 ("theta")
20398 ("iota")
20399 ("kappa")
20400 ("lambda")
20401 ("mu")
20402 ("nu")
20403 ("xi")
20404 ("omicron")
20405 ("pi")
20406 ("rho")
20407 ("sigmaf") ("varsigma"."&sigmaf;")
20408 ("sigma")
20409 ("tau")
20410 ("upsilon")
20411 ("phi")
20412 ("chi")
20413 ("psi")
20414 ("omega")
20415 ("thetasym") ("vartheta"."&thetasym;")
20416 ("upsih")
20417 ("piv")
20418 ("bull") ("bullet"."&bull;")
20419 ("hellip") ("dots"."&hellip;")
20420 ("prime")
20421 ("Prime")
20422 ("oline")
20423 ("frasl")
20424 ("weierp")
20425 ("image")
20426 ("real")
20427 ("trade")
20428 ("alefsym")
20429 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
20430 ("uarr") ("uparrow"."&uarr;")
20431 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
20432 ("darr")("downarrow"."&darr;")
20433 ("harr") ("leftrightarrow"."&harr;")
20434 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
20435 ("lArr") ("Leftarrow"."&lArr;")
20436 ("uArr") ("Uparrow"."&uArr;")
20437 ("rArr") ("Rightarrow"."&rArr;")
20438 ("dArr") ("Downarrow"."&dArr;")
20439 ("hArr") ("Leftrightarrow"."&hArr;")
20440 ("forall")
20441 ("part") ("partial"."&part;")
20442 ("exist") ("exists"."&exist;")
20443 ("empty") ("emptyset"."&empty;")
20444 ("nabla")
20445 ("isin") ("in"."&isin;")
20446 ("notin")
20447 ("ni")
20448 ("prod")
20449 ("sum")
20450 ("minus")
20451 ("lowast") ("ast"."&lowast;")
20452 ("radic")
20453 ("prop") ("proptp"."&prop;")
20454 ("infin") ("infty"."&infin;")
20455 ("ang") ("angle"."&ang;")
20456 ("and") ("vee"."&and;")
20457 ("or") ("wedge"."&or;")
20458 ("cap")
20459 ("cup")
20460 ("int")
20461 ("there4")
20462 ("sim")
20463 ("cong") ("simeq"."&cong;")
20464 ("asymp")("approx"."&asymp;")
20465 ("ne") ("neq"."&ne;")
20466 ("equiv")
20467 ("le")
20468 ("ge")
20469 ("sub") ("subset"."&sub;")
20470 ("sup") ("supset"."&sup;")
20471 ("nsub")
20472 ("sube")
20473 ("supe")
20474 ("oplus")
20475 ("otimes")
20476 ("perp")
20477 ("sdot") ("cdot"."&sdot;")
20478 ("lceil")
20479 ("rceil")
20480 ("lfloor")
20481 ("rfloor")
20482 ("lang")
20483 ("rang")
20484 ("loz") ("Diamond"."&loz;")
20485 ("spades") ("spadesuit"."&spades;")
20486 ("clubs") ("clubsuit"."&clubs;")
20487 ("hearts") ("diamondsuit"."&hearts;")
20488 ("diams") ("diamondsuit"."&diams;")
20489 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
20490 ("quot")
20491 ("amp")
20492 ("lt")
20493 ("gt")
20494 ("OElig")
20495 ("oelig")
20496 ("Scaron")
20497 ("scaron")
20498 ("Yuml")
20499 ("circ")
20500 ("tilde")
20501 ("ensp")
20502 ("emsp")
20503 ("thinsp")
20504 ("zwnj")
20505 ("zwj")
20506 ("lrm")
20507 ("rlm")
20508 ("ndash")
20509 ("mdash")
20510 ("lsquo")
20511 ("rsquo")
20512 ("sbquo")
20513 ("ldquo")
20514 ("rdquo")
20515 ("bdquo")
20516 ("dagger")
20517 ("Dagger")
20518 ("permil")
20519 ("lsaquo")
20520 ("rsaquo")
20521 ("euro")
20523 ("arccos"."arccos")
20524 ("arcsin"."arcsin")
20525 ("arctan"."arctan")
20526 ("arg"."arg")
20527 ("cos"."cos")
20528 ("cosh"."cosh")
20529 ("cot"."cot")
20530 ("coth"."coth")
20531 ("csc"."csc")
20532 ("deg"."deg")
20533 ("det"."det")
20534 ("dim"."dim")
20535 ("exp"."exp")
20536 ("gcd"."gcd")
20537 ("hom"."hom")
20538 ("inf"."inf")
20539 ("ker"."ker")
20540 ("lg"."lg")
20541 ("lim"."lim")
20542 ("liminf"."liminf")
20543 ("limsup"."limsup")
20544 ("ln"."ln")
20545 ("log"."log")
20546 ("max"."max")
20547 ("min"."min")
20548 ("Pr"."Pr")
20549 ("sec"."sec")
20550 ("sin"."sin")
20551 ("sinh"."sinh")
20552 ("sup"."sup")
20553 ("tan"."tan")
20554 ("tanh"."tanh")
20556 "Entities for TeX->HTML translation.
20557 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
20558 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
20559 In that case, \"\\ent\" will be translated to \"&other;\".
20560 The list contains HTML entities for Latin-1, Greek and other symbols.
20561 It is supplemented by a number of commonly used TeX macros with appropriate
20562 translations. There is currently no way for users to extend this.")
20564 ;;; General functions for all backends
20566 (defun org-cleaned-string-for-export (string &rest parameters)
20567 "Cleanup a buffer STRING so that links can be created safely."
20568 (interactive)
20569 (let* ((re-radio (and org-target-link-regexp
20570 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
20571 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
20572 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
20573 (re-archive (concat ":" org-archive-tag ":"))
20574 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
20575 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
20576 (htmlp (plist-get parameters :for-html))
20577 (asciip (plist-get parameters :for-ascii))
20578 (latexp (plist-get parameters :for-LaTeX))
20579 (commentsp (plist-get parameters :comments))
20580 (archived-trees (plist-get parameters :archived-trees))
20581 (inhibit-read-only t)
20582 (outline-regexp "\\*+ ")
20583 a b xx
20584 rtn p)
20585 (with-current-buffer (get-buffer-create " org-mode-tmp")
20586 (erase-buffer)
20587 (insert string)
20588 ;; Remove license-to-kill stuff
20589 (while (setq p (text-property-any (point-min) (point-max)
20590 :org-license-to-kill t))
20591 (delete-region p (next-single-property-change p :org-license-to-kill)))
20593 (let ((org-inhibit-startup t)) (org-mode))
20594 (untabify (point-min) (point-max))
20596 ;; Get the correct stuff before the first headline
20597 (when (plist-get parameters :skip-before-1st-heading)
20598 (goto-char (point-min))
20599 (when (re-search-forward "^\\*+[ \t]" nil t)
20600 (delete-region (point-min) (match-beginning 0))
20601 (goto-char (point-min))
20602 (insert "\n")))
20603 (when (plist-get parameters :add-text)
20604 (goto-char (point-min))
20605 (insert (plist-get parameters :add-text) "\n"))
20607 ;; Get rid of archived trees
20608 (when (not (eq archived-trees t))
20609 (goto-char (point-min))
20610 (while (re-search-forward re-archive nil t)
20611 (if (not (org-on-heading-p t))
20612 (org-end-of-subtree t)
20613 (beginning-of-line 1)
20614 (setq a (if archived-trees
20615 (1+ (point-at-eol)) (point))
20616 b (org-end-of-subtree t))
20617 (if (> b a) (delete-region a b)))))
20619 ;; Get rid of property drawers
20620 (unless org-export-with-property-drawer
20621 (goto-char (point-min))
20622 (while (re-search-forward "^[ \t]*:PROPERTIES:[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n" nil t)
20623 (replace-match "")))
20625 ;; Find targets in comments and move them out of comments,
20626 ;; but mark them as targets that should be invisible
20627 (goto-char (point-min))
20628 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
20629 (replace-match "\\1(INVISIBLE)"))
20631 ;; Protect backend specific stuff, throw away the others.
20632 (goto-char (point-min))
20633 (let ((formatters
20634 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
20635 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
20636 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
20637 fmt)
20638 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
20639 (add-text-properties (match-beginning 0) (match-end 0)
20640 '(org-protected t)))
20641 (while formatters
20642 (setq fmt (pop formatters))
20643 (when (car fmt)
20644 (goto-char (point-min))
20645 (while (re-search-forward (concat "^#\\+" (cadr fmt)
20646 ":[ \t]*\\(.*\\)") nil t)
20647 (replace-match "\\1" t)
20648 (add-text-properties
20649 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
20650 '(org-protected t))))
20651 (goto-char (point-min))
20652 (while (re-search-forward
20653 (concat "^#\\+"
20654 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
20655 (cadddr fmt) "\\>.*\n?") nil t)
20656 (if (car fmt)
20657 (add-text-properties (match-beginning 1) (1+ (match-end 1))
20658 '(org-protected t))
20659 (delete-region (match-beginning 0) (match-end 0))))))
20661 ;; Protect quoted subtrees
20662 (goto-char (point-min))
20663 (while (re-search-forward re-quote nil t)
20664 (goto-char (match-beginning 0))
20665 (end-of-line 1)
20666 (add-text-properties (point) (org-end-of-subtree t)
20667 '(org-protected t)))
20669 ;; Remove subtrees that are commented
20670 (goto-char (point-min))
20671 (while (re-search-forward re-commented nil t)
20672 (goto-char (match-beginning 0))
20673 (delete-region (point) (org-end-of-subtree t)))
20675 ;; Remove special table lines
20676 (when org-export-table-remove-special-lines
20677 (goto-char (point-min))
20678 (while (re-search-forward "^[ \t]*|" nil t)
20679 (beginning-of-line 1)
20680 (if (or (looking-at "[ \t]*| *[!_^] *|")
20681 (and (looking-at ".*?| *<[0-9]+> *|")
20682 (not (looking-at ".*?| *[^ <|]"))))
20683 (delete-region (max (point-min) (1- (point-at-bol)))
20684 (point-at-eol))
20685 (end-of-line 1))))
20687 ;; Specific LaTeX stuff
20688 (when latexp
20689 (require 'org-export-latex nil t)
20690 (org-export-latex-cleaned-string))
20692 ;; Specific HTML stuff
20693 (when htmlp
20694 ;; Convert LaTeX fragments to images
20695 (when (plist-get parameters :LaTeX-fragments)
20696 (org-format-latex
20697 (concat "ltxpng/" (file-name-sans-extension
20698 (file-name-nondirectory
20699 org-current-export-file)))
20700 org-current-export-dir nil "Creating LaTeX image %s"))
20701 (message "Exporting..."))
20703 ;; Remove or replace comments
20704 ;; FIXME: Does LaTeX export take care of its own comments?
20705 ;; If :comments is set, use this char for commenting out comments and
20706 ;; protect them. otherwise delete them
20707 (goto-char (point-min))
20708 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
20709 (if commentsp
20710 (progn (add-text-properties
20711 (match-beginning 0) (match-end 0) '(org-protected t))
20712 (replace-match (format commentsp (match-string 1)) t t))
20713 (replace-match "")))
20715 ;; Find matches for radio targets and turn them into internal links
20716 (goto-char (point-min))
20717 (when re-radio
20718 (while (re-search-forward re-radio nil t)
20719 (org-if-unprotected
20720 (replace-match "\\1[[\\2]]"))))
20722 ;; Find all links that contain a newline and put them into a single line
20723 (goto-char (point-min))
20724 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
20725 (org-if-unprotected
20726 (replace-match "\\1 \\3")
20727 (goto-char (match-beginning 0))))
20730 ;; Normalize links: Convert angle and plain links into bracket links
20731 ;; Expand link abbreviations
20732 (goto-char (point-min))
20733 (while (re-search-forward re-plain-link nil t)
20734 (goto-char (1- (match-end 0)))
20735 (org-if-unprotected
20736 (let* ((s (concat (match-string 1) "[[" (match-string 2)
20737 ":" (match-string 3) "]]")))
20738 ;; added 'org-link face to links
20739 (put-text-property 0 (length s) 'face 'org-link s)
20740 (replace-match s t t))))
20741 (goto-char (point-min))
20742 (while (re-search-forward re-angle-link nil t)
20743 (goto-char (1- (match-end 0)))
20744 (org-if-unprotected
20745 (let* ((s (concat (match-string 1) "[[" (match-string 2)
20746 ":" (match-string 3) "]]")))
20747 (put-text-property 0 (length s) 'face 'org-link s)
20748 (replace-match s t t))))
20749 (goto-char (point-min))
20750 (while (re-search-forward org-bracket-link-regexp nil t)
20751 (org-if-unprotected
20752 (let* ((s (concat "[[" (setq xx (save-match-data
20753 (org-link-expand-abbrev (match-string 1))))
20755 (if (match-end 3)
20756 (match-string 2)
20757 (concat "[" xx "]"))
20758 "]")))
20759 (put-text-property 0 (length s) 'face 'org-link s)
20760 (replace-match s t t))))
20762 ;; Find multiline emphasis and put them into single line
20763 (when (plist-get parameters :emph-multiline)
20764 (goto-char (point-min))
20765 (while (re-search-forward org-emph-re nil t)
20766 (if (not (= (char-after (match-beginning 3))
20767 (char-after (match-beginning 4))))
20768 (org-if-unprotected
20769 (subst-char-in-region (match-beginning 0) (match-end 0)
20770 ?\n ?\ t)
20771 (goto-char (1- (match-end 0))))
20772 (goto-char (1+ (match-beginning 0))))))
20774 (setq rtn (buffer-string)))
20775 (kill-buffer " org-mode-tmp")
20776 rtn))
20778 (defun org-export-grab-title-from-buffer ()
20779 "Get a title for the current document, from looking at the buffer."
20780 (let ((inhibit-read-only t))
20781 (save-excursion
20782 (goto-char (point-min))
20783 (let ((end (save-excursion (outline-next-heading) (point))))
20784 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
20785 ;; Mark the line so that it will not be exported as normal text.
20786 (org-unmodified
20787 (add-text-properties (match-beginning 0) (match-end 0)
20788 (list :org-license-to-kill t)))
20789 ;; Return the title string
20790 (org-trim (match-string 0)))))))
20792 (defun org-export-get-title-from-subtree ()
20793 "Return subtree title and exclude it from export."
20794 (let (title (m (mark)))
20795 (save-excursion
20796 (goto-char (region-beginning))
20797 (when (and (org-at-heading-p)
20798 (>= (org-end-of-subtree t t) (region-end)))
20799 ;; This is a subtree, we take the title from the first heading
20800 (goto-char (region-beginning))
20801 (looking-at org-todo-line-regexp)
20802 (setq title (match-string 3))
20803 (org-unmodified
20804 (add-text-properties (point) (1+ (point-at-eol))
20805 (list :org-license-to-kill t)))))
20806 title))
20808 (defun org-solidify-link-text (s &optional alist)
20809 "Take link text and make a safe target out of it."
20810 (save-match-data
20811 (let* ((rtn
20812 (mapconcat
20813 'identity
20814 (org-split-string s "[ \t\r\n]+") "--"))
20815 (a (assoc rtn alist)))
20816 (or (cdr a) rtn))))
20818 ;; Variable holding the vector with section numbers
20819 (defvar org-section-numbers (make-vector org-level-max 0))
20821 (defun org-init-section-numbers ()
20822 "Initialize the vector for the section numbers."
20823 (let* ((level -1)
20824 (numbers (nreverse (org-split-string "" "\\.")))
20825 (depth (1- (length org-section-numbers)))
20826 (i depth) number-string)
20827 (while (>= i 0)
20828 (if (> i level)
20829 (aset org-section-numbers i 0)
20830 (setq number-string (or (car numbers) "0"))
20831 (if (string-match "\\`[A-Z]\\'" number-string)
20832 (aset org-section-numbers i
20833 (- (string-to-char number-string) ?A -1))
20834 (aset org-section-numbers i (string-to-number number-string)))
20835 (pop numbers))
20836 (setq i (1- i)))))
20838 (defun org-section-number (&optional level)
20839 "Return a string with the current section number.
20840 When LEVEL is non-nil, increase section numbers on that level."
20841 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
20842 (when level
20843 (when (> level -1)
20844 (aset org-section-numbers
20845 level (1+ (aref org-section-numbers level))))
20846 (setq idx (1+ level))
20847 (while (<= idx depth)
20848 (if (not (= idx 1))
20849 (aset org-section-numbers idx 0))
20850 (setq idx (1+ idx))))
20851 (setq idx 0)
20852 (while (<= idx depth)
20853 (setq n (aref org-section-numbers idx))
20854 (setq string (concat string (if (not (string= string "")) "." "")
20855 (int-to-string n)))
20856 (setq idx (1+ idx)))
20857 (save-match-data
20858 (if (string-match "\\`\\([@0]\\.\\)+" string)
20859 (setq string (replace-match "" t nil string)))
20860 (if (string-match "\\(\\.0\\)+\\'" string)
20861 (setq string (replace-match "" t nil string))))
20862 string))
20864 ;;; ASCII export
20866 (defvar org-last-level nil) ; dynamically scoped variable
20867 (defvar org-min-level nil) ; dynamically scoped variable
20868 (defvar org-levels-open nil) ; dynamically scoped parameter
20869 (defvar org-ascii-current-indentation nil) ; For communication
20871 (defun org-export-as-ascii (arg)
20872 "Export the outline as a pretty ASCII file.
20873 If there is an active region, export only the region.
20874 The prefix ARG specifies how many levels of the outline should become
20875 underlined headlines. The default is 3."
20876 (interactive "P")
20877 (setq-default org-todo-line-regexp org-todo-line-regexp)
20878 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
20879 (org-infile-export-plist)))
20880 (region-p (org-region-active-p))
20881 (subtree-p
20882 (when region-p
20883 (save-excursion
20884 (goto-char (region-beginning))
20885 (and (org-at-heading-p)
20886 (>= (org-end-of-subtree t t) (region-end))))))
20887 (custom-times org-display-custom-times)
20888 (org-ascii-current-indentation '(0 . 0))
20889 (level 0) line txt
20890 (umax nil)
20891 (umax-toc nil)
20892 (case-fold-search nil)
20893 (filename (concat (file-name-as-directory
20894 (org-export-directory :ascii opt-plist))
20895 (file-name-sans-extension
20896 (or (and subtree-p
20897 (org-entry-get (region-beginning)
20898 "EXPORT_FILE_NAME" t))
20899 (file-name-nondirectory buffer-file-name)))
20900 ".txt"))
20901 (filename (if (equal (file-truename filename)
20902 (file-truename buffer-file-name))
20903 (concat filename ".txt")
20904 filename))
20905 (buffer (find-file-noselect filename))
20906 (org-levels-open (make-vector org-level-max nil))
20907 (odd org-odd-levels-only)
20908 (date (format-time-string "%Y/%m/%d" (current-time)))
20909 (time (format-time-string "%X" (org-current-time)))
20910 (author (plist-get opt-plist :author))
20911 (title (or (and subtree-p (org-export-get-title-from-subtree))
20912 (plist-get opt-plist :title)
20913 (and (not
20914 (plist-get opt-plist :skip-before-1st-heading))
20915 (org-export-grab-title-from-buffer))
20916 (file-name-sans-extension
20917 (file-name-nondirectory buffer-file-name))))
20918 (email (plist-get opt-plist :email))
20919 (language (plist-get opt-plist :language))
20920 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
20921 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
20922 (todo nil)
20923 (lang-words nil)
20924 (region
20925 (buffer-substring
20926 (if (org-region-active-p) (region-beginning) (point-min))
20927 (if (org-region-active-p) (region-end) (point-max))))
20928 (lines (org-split-string
20929 (org-cleaned-string-for-export
20930 region
20931 :for-ascii t
20932 :skip-before-1st-heading
20933 (plist-get opt-plist :skip-before-1st-heading)
20934 :archived-trees
20935 (plist-get opt-plist :archived-trees)
20936 :add-text (plist-get opt-plist :text))
20937 "[\r\n]")) ;; FIXME: why \r here???/
20938 thetoc have-headings first-heading-pos
20939 table-open table-buffer)
20941 (let ((inhibit-read-only t))
20942 (org-unmodified
20943 (remove-text-properties (point-min) (point-max)
20944 '(:org-license-to-kill t))))
20946 (setq org-min-level (org-get-min-level lines))
20947 (setq org-last-level org-min-level)
20948 (org-init-section-numbers)
20950 (find-file-noselect filename)
20952 (setq lang-words (or (assoc language org-export-language-setup)
20953 (assoc "en" org-export-language-setup)))
20954 (switch-to-buffer-other-window buffer)
20955 (erase-buffer)
20956 (fundamental-mode)
20957 ;; create local variables for all options, to make sure all called
20958 ;; functions get the correct information
20959 (mapcar (lambda (x)
20960 (set (make-local-variable (cdr x))
20961 (plist-get opt-plist (car x))))
20962 org-export-plist-vars)
20963 (org-set-local 'org-odd-levels-only odd)
20964 (setq umax (if arg (prefix-numeric-value arg)
20965 org-export-headline-levels))
20966 (setq umax-toc (if (integerp org-export-with-toc)
20967 (min org-export-with-toc umax)
20968 umax))
20970 ;; File header
20971 (if title (org-insert-centered title ?=))
20972 (insert "\n")
20973 (if (and (or author email)
20974 org-export-author-info)
20975 (insert (concat (nth 1 lang-words) ": " (or author "")
20976 (if email (concat " <" email ">") "")
20977 "\n")))
20978 (if (and date time org-export-time-stamp-file)
20979 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
20981 (insert "\n\n")
20983 (if org-export-with-toc
20984 (progn
20985 (push (concat (nth 3 lang-words) "\n") thetoc)
20986 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
20987 (mapcar '(lambda (line)
20988 (if (string-match org-todo-line-regexp
20989 line)
20990 ;; This is a headline
20991 (progn
20992 (setq have-headings t)
20993 (setq level (- (match-end 1) (match-beginning 1))
20994 level (org-tr-level level)
20995 txt (match-string 3 line)
20996 todo
20997 (or (and org-export-mark-todo-in-toc
20998 (match-beginning 2)
20999 (not (member (match-string 2 line)
21000 org-done-keywords)))
21001 ; TODO, not DONE
21002 (and org-export-mark-todo-in-toc
21003 (= level umax-toc)
21004 (org-search-todo-below
21005 line lines level))))
21006 (setq txt (org-html-expand-for-ascii txt))
21008 (if (and (memq org-export-with-tags '(not-in-toc nil))
21009 (string-match
21010 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
21011 txt))
21012 (setq txt (replace-match "" t t txt)))
21013 (if (string-match quote-re0 txt)
21014 (setq txt (replace-match "" t t txt)))
21016 (if org-export-with-section-numbers
21017 (setq txt (concat (org-section-number level)
21018 " " txt)))
21019 (if (<= level umax-toc)
21020 (progn
21021 (push
21022 (concat
21023 (make-string
21024 (* (max 0 (- level org-min-level)) 4) ?\ )
21025 (format (if todo "%s (*)\n" "%s\n") txt))
21026 thetoc)
21027 (setq org-last-level level))
21028 ))))
21029 lines)
21030 (setq thetoc (if have-headings (nreverse thetoc) nil))))
21032 (org-init-section-numbers)
21033 (while (setq line (pop lines))
21034 ;; Remove the quoted HTML tags.
21035 (setq line (org-html-expand-for-ascii line))
21036 ;; Remove targets
21037 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
21038 (setq line (replace-match "" t t line)))
21039 ;; Replace internal links
21040 (while (string-match org-bracket-link-regexp line)
21041 (setq line (replace-match
21042 (if (match-end 3) "[\\3]" "[\\1]")
21043 t nil line)))
21044 (when custom-times
21045 (setq line (org-translate-time line)))
21046 (cond
21047 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
21048 ;; a Headline
21049 (setq first-heading-pos (or first-heading-pos (point)))
21050 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
21051 txt (match-string 2 line))
21052 (org-ascii-level-start level txt umax lines))
21054 ((and org-export-with-tables
21055 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
21056 (if (not table-open)
21057 ;; New table starts
21058 (setq table-open t table-buffer nil))
21059 ;; Accumulate lines
21060 (setq table-buffer (cons line table-buffer))
21061 (when (or (not lines)
21062 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
21063 (car lines))))
21064 (setq table-open nil
21065 table-buffer (nreverse table-buffer))
21066 (insert (mapconcat
21067 (lambda (x)
21068 (org-fix-indentation x org-ascii-current-indentation))
21069 (org-format-table-ascii table-buffer)
21070 "\n") "\n")))
21072 (setq line (org-fix-indentation line org-ascii-current-indentation))
21073 (if (and org-export-with-fixed-width
21074 (string-match "^\\([ \t]*\\)\\(:\\)" line))
21075 (setq line (replace-match "\\1" nil nil line)))
21076 (insert line "\n"))))
21078 (normal-mode)
21080 ;; insert the table of contents
21081 (when thetoc
21082 (goto-char (point-min))
21083 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
21084 (progn
21085 (goto-char (match-beginning 0))
21086 (replace-match ""))
21087 (goto-char first-heading-pos))
21088 (mapc 'insert thetoc)
21089 (or (looking-at "[ \t]*\n[ \t]*\n")
21090 (insert "\n\n")))
21092 (save-buffer)
21093 ;; remove display and invisible chars
21094 (let (beg end)
21095 (goto-char (point-min))
21096 (while (setq beg (next-single-property-change (point) 'display))
21097 (setq end (next-single-property-change beg 'display))
21098 (delete-region beg end)
21099 (goto-char beg)
21100 (insert "=>"))
21101 (goto-char (point-min))
21102 (while (setq beg (next-single-property-change (point) 'org-cwidth))
21103 (setq end (next-single-property-change beg 'org-cwidth))
21104 (delete-region beg end)
21105 (goto-char beg)))
21106 (goto-char (point-min))))
21108 (defun org-search-todo-below (line lines level)
21109 "Search the subtree below LINE for any TODO entries."
21110 (let ((rest (cdr (memq line lines)))
21111 (re org-todo-line-regexp)
21112 line lv todo)
21113 (catch 'exit
21114 (while (setq line (pop rest))
21115 (if (string-match re line)
21116 (progn
21117 (setq lv (- (match-end 1) (match-beginning 1))
21118 todo (and (match-beginning 2)
21119 (not (member (match-string 2 line)
21120 org-done-keywords))))
21121 ; TODO, not DONE
21122 (if (<= lv level) (throw 'exit nil))
21123 (if todo (throw 'exit t))))))))
21125 (defun org-html-expand-for-ascii (line)
21126 "Handle quoted HTML for ASCII export."
21127 (if org-export-html-expand
21128 (while (string-match "@<[^<>\n]*>" line)
21129 ;; We just remove the tags for now.
21130 (setq line (replace-match "" nil nil line))))
21131 line)
21133 (defun org-insert-centered (s &optional underline)
21134 "Insert the string S centered and underline it with character UNDERLINE."
21135 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
21136 (insert (make-string ind ?\ ) s "\n")
21137 (if underline
21138 (insert (make-string ind ?\ )
21139 (make-string (string-width s) underline)
21140 "\n"))))
21142 (defun org-ascii-level-start (level title umax &optional lines)
21143 "Insert a new level in ASCII export."
21144 (let (char (n (- level umax 1)) (ind 0))
21145 (if (> level umax)
21146 (progn
21147 (insert (make-string (* 2 n) ?\ )
21148 (char-to-string (nth (% n (length org-export-ascii-bullets))
21149 org-export-ascii-bullets))
21150 " " title "\n")
21151 ;; find the indentation of the next non-empty line
21152 (catch 'stop
21153 (while lines
21154 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
21155 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
21156 (throw 'stop (setq ind (org-get-indentation (car lines)))))
21157 (pop lines)))
21158 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
21159 (if (or (not (equal (char-before) ?\n))
21160 (not (equal (char-before (1- (point))) ?\n)))
21161 (insert "\n"))
21162 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
21163 (unless org-export-with-tags
21164 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
21165 (setq title (replace-match "" t t title))))
21166 (if org-export-with-section-numbers
21167 (setq title (concat (org-section-number level) " " title)))
21168 (insert title "\n" (make-string (string-width title) char) "\n")
21169 (setq org-ascii-current-indentation '(0 . 0)))))
21171 (defun org-export-visible (type arg)
21172 "Create a copy of the visible part of the current buffer, and export it.
21173 The copy is created in a temporary buffer and removed after use.
21174 TYPE is the final key (as a string) that also select the export command in
21175 the `C-c C-e' export dispatcher.
21176 As a special case, if the you type SPC at the prompt, the temporary
21177 org-mode file will not be removed but presented to you so that you can
21178 continue to use it. The prefix arg ARG is passed through to the exporting
21179 command."
21180 (interactive
21181 (list (progn
21182 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
21183 (read-char-exclusive))
21184 current-prefix-arg))
21185 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
21186 (error "Invalid export key"))
21187 (let* ((binding (cdr (assoc type
21188 '((?a . org-export-as-ascii)
21189 (?\C-a . org-export-as-ascii)
21190 (?b . org-export-as-html-and-open)
21191 (?\C-b . org-export-as-html-and-open)
21192 (?h . org-export-as-html)
21193 (?H . org-export-as-html-to-buffer)
21194 (?R . org-export-region-as-html)
21195 (?x . org-export-as-xoxo)))))
21196 (keepp (equal type ?\ ))
21197 (file buffer-file-name)
21198 (buffer (get-buffer-create "*Org Export Visible*"))
21199 s e)
21200 (with-current-buffer buffer (erase-buffer))
21201 (save-excursion
21202 (setq s (goto-char (point-min)))
21203 (while (not (= (point) (point-max)))
21204 (goto-char (org-find-invisible))
21205 (append-to-buffer buffer s (point))
21206 (setq s (goto-char (org-find-visible))))
21207 (goto-char (point-min))
21208 (unless keepp
21209 ;; Copy all comment lines to the end, to make sure #+ settings are
21210 ;; still available for the second export step. Kind of a hack, but
21211 ;; does do the trick.
21212 (if (looking-at "#[^\r\n]*")
21213 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
21214 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
21215 (append-to-buffer buffer (1+ (match-beginning 0))
21216 (min (point-max) (1+ (match-end 0))))))
21217 (set-buffer buffer)
21218 (let ((buffer-file-name file)
21219 (org-inhibit-startup t))
21220 (org-mode)
21221 (show-all)
21222 (unless keepp (funcall binding arg))))
21223 (if (not keepp)
21224 (kill-buffer buffer)
21225 (switch-to-buffer-other-window buffer)
21226 (goto-char (point-min)))))
21228 (defun org-find-visible ()
21229 (let ((s (point)))
21230 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
21231 (get-char-property s 'invisible)))
21233 (defun org-find-invisible ()
21234 (let ((s (point)))
21235 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
21236 (not (get-char-property s 'invisible))))
21239 ;;; HTML export
21241 (defun org-get-current-options ()
21242 "Return a string with current options as keyword options.
21243 Does include HTML export options as well as TODO and CATEGORY stuff."
21244 (format
21245 "#+TITLE: %s
21246 #+AUTHOR: %s
21247 #+EMAIL: %s
21248 #+LANGUAGE: %s
21249 #+TEXT: Some descriptive text to be emitted. Several lines OK.
21250 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s p:%s
21251 #+CATEGORY: %s
21252 #+SEQ_TODO: %s
21253 #+TYP_TODO: %s
21254 #+PRIORITIES: %c %c %c
21255 #+STARTUP: %s %s %s %s %s
21256 #+TAGS: %s
21257 #+ARCHIVE: %s
21258 #+LINK: %s
21260 (buffer-name) (user-full-name) user-mail-address org-export-default-language
21261 org-export-headline-levels
21262 org-export-with-section-numbers
21263 org-export-with-toc
21264 org-export-preserve-breaks
21265 org-export-html-expand
21266 org-export-with-fixed-width
21267 org-export-with-tables
21268 org-export-with-sub-superscripts
21269 org-export-with-footnotes
21270 org-export-with-emphasize
21271 org-export-with-TeX-macros
21272 org-export-with-LaTeX-fragments
21273 org-export-skip-text-before-1st-heading
21274 org-export-with-property-drawer
21275 (file-name-nondirectory buffer-file-name)
21276 "TODO FEEDBACK VERIFY DONE"
21277 "Me Jason Marie DONE"
21278 org-highest-priority org-lowest-priority org-default-priority
21279 (cdr (assoc org-startup-folded
21280 '((nil . "showall") (t . "overview") (content . "content"))))
21281 (if org-odd-levels-only "odd" "oddeven")
21282 (if org-hide-leading-stars "hidestars" "showstars")
21283 (if org-startup-align-all-tables "align" "noalign")
21284 (cond ((eq t org-log-done) "logdone")
21285 ((not org-log-done) "nologging")
21286 ((listp org-log-done)
21287 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
21288 org-log-done " ")))
21289 (or (mapconcat (lambda (x)
21290 (cond
21291 ((equal '(:startgroup) x) "{")
21292 ((equal '(:endgroup) x) "}")
21293 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
21294 (t (car x))))
21295 (or org-tag-alist (org-get-buffer-tags)) " ") "")
21296 org-archive-location
21297 "org file:~/org/%s.org"
21300 (defun org-insert-export-options-template ()
21301 "Insert into the buffer a template with information for exporting."
21302 (interactive)
21303 (if (not (bolp)) (newline))
21304 (let ((s (org-get-current-options)))
21305 (and (string-match "#\\+CATEGORY" s)
21306 (setq s (substring s 0 (match-beginning 0))))
21307 (insert s)))
21309 (defun org-toggle-fixed-width-section (arg)
21310 "Toggle the fixed-width export.
21311 If there is no active region, the QUOTE keyword at the current headline is
21312 inserted or removed. When present, it causes the text between this headline
21313 and the next to be exported as fixed-width text, and unmodified.
21314 If there is an active region, this command adds or removes a colon as the
21315 first character of this line. If the first character of a line is a colon,
21316 this line is also exported in fixed-width font."
21317 (interactive "P")
21318 (let* ((cc 0)
21319 (regionp (org-region-active-p))
21320 (beg (if regionp (region-beginning) (point)))
21321 (end (if regionp (region-end)))
21322 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21323 (re "[ \t]*\\(:\\)")
21324 off)
21325 (if regionp
21326 (save-excursion
21327 (goto-char beg)
21328 (setq cc (current-column))
21329 (beginning-of-line 1)
21330 (setq off (looking-at re))
21331 (while (> nlines 0)
21332 (setq nlines (1- nlines))
21333 (beginning-of-line 1)
21334 (cond
21335 (arg
21336 (move-to-column cc t)
21337 (insert ":\n")
21338 (forward-line -1))
21339 ((and off (looking-at re))
21340 (replace-match "" t t nil 1))
21341 ((not off) (move-to-column cc t) (insert ":")))
21342 (forward-line 1)))
21343 (save-excursion
21344 (org-back-to-heading)
21345 (if (looking-at (concat outline-regexp
21346 "\\( *\\<" org-quote-string "\\>\\)"))
21347 (replace-match "" t t nil 1)
21348 (if (looking-at outline-regexp)
21349 (progn
21350 (goto-char (match-end 0))
21351 (insert org-quote-string " "))))))))
21353 (defun org-export-as-html-and-open (arg)
21354 "Export the outline as HTML and immediately open it with a browser.
21355 If there is an active region, export only the region.
21356 The prefix ARG specifies how many levels of the outline should become
21357 headlines. The default is 3. Lower levels will become bulleted lists."
21358 (interactive "P")
21359 (org-export-as-html arg 'hidden)
21360 (org-open-file buffer-file-name))
21362 (defun org-export-as-html-batch ()
21363 "Call `org-export-as-html', may be used in batch processing as
21364 emacs --batch
21365 --load=$HOME/lib/emacs/org.el
21366 --eval \"(setq org-export-headline-levels 2)\"
21367 --visit=MyFile --funcall org-export-as-html-batch"
21368 (org-export-as-html org-export-headline-levels 'hidden))
21370 (defun org-export-as-html-to-buffer (arg)
21371 "Call `org-exort-as-html` with output to a temporary buffer.
21372 No file is created. The prefix ARG is passed through to `org-export-as-html'."
21373 (interactive "P")
21374 (org-export-as-html arg nil nil "*Org HTML Export*")
21375 (switch-to-buffer-other-window "*Org HTML Export*"))
21377 (defun org-replace-region-by-html (beg end)
21378 "Assume the current region has org-mode syntax, and convert it to HTML.
21379 This can be used in any buffer. For example, you could write an
21380 itemized list in org-mode syntax in an HTML buffer and then use this
21381 command to convert it."
21382 (interactive "r")
21383 (let (reg html buf)
21384 (save-window-excursion
21385 (if (org-mode-p)
21386 (setq html (org-export-region-as-html
21387 beg end t 'string))
21388 (setq reg (buffer-substring beg end)
21389 buf (get-buffer-create "*Org tmp*"))
21390 (with-current-buffer buf
21391 (erase-buffer)
21392 (insert reg)
21393 (org-mode)
21394 (setq html (org-export-region-as-html
21395 (point-min) (point-max) t 'string)))
21396 (kill-buffer buf)))
21397 (delete-region beg end)
21398 (insert html)))
21400 (defun org-export-region-as-html (beg end &optional body-only buffer)
21401 "Convert region from BEG to END in org-mode buffer to HTML.
21402 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
21403 contents, and only produce the region of converted text, useful for
21404 cut-and-paste operations.
21405 If BUFFER is a buffer or a string, use/create that buffer as a target
21406 of the converted HTML. If BUFFER is the symbol `string', return the
21407 produced HTML as a string and leave not buffer behind. For example,
21408 a Lisp program could call this function in the following way:
21410 (setq html (org-export-region-as-html beg end t 'string))
21412 When called interactively, the output buffer is selected, and shown
21413 in a window. A non-interactive call will only retunr the buffer."
21414 (interactive "r\nP")
21415 (when (interactive-p)
21416 (setq buffer "*Org HTML Export*"))
21417 (let ((transient-mark-mode t) (zmacs-regions t)
21418 rtn)
21419 (goto-char end)
21420 (set-mark (point)) ;; to activate the region
21421 (goto-char beg)
21422 (setq rtn (org-export-as-html
21423 nil nil nil
21424 buffer body-only))
21425 (if (fboundp 'deactivate-mark) (deactivate-mark))
21426 (if (and (interactive-p) (bufferp rtn))
21427 (switch-to-buffer-other-window rtn)
21428 rtn)))
21430 (defun org-export-as-html (arg &optional hidden ext-plist
21431 to-buffer body-only)
21432 "Export the outline as a pretty HTML file.
21433 If there is an active region, export only the region. The prefix
21434 ARG specifies how many levels of the outline should become
21435 headlines. The default is 3. Lower levels will become bulleted
21436 lists. When HIDDEN is non-nil, don't display the HTML buffer.
21437 EXT-PLIST is a property list with external parameters overriding
21438 org-mode's default settings, but still inferior to file-local
21439 settings. When TO-BUFFER is non-nil, create a buffer with that
21440 name and export to that buffer. If TO-BUFFER is the symbol `string',
21441 don't leave any buffer behind but just return the resulting HTML as
21442 a string. When BODY-ONLY is set, don't produce the file header and footer,
21443 simply return the content of <body>...</body>, without even
21444 the body tags themselves."
21445 (interactive "P")
21447 ;; Make sure we have a file name when we need it.
21448 (when (and (not (or to-buffer body-only))
21449 (not buffer-file-name))
21450 (if (buffer-base-buffer)
21451 (org-set-local 'buffer-file-name
21452 (with-current-buffer (buffer-base-buffer)
21453 buffer-file-name))
21454 (error "Need a file name to be able to export.")))
21456 (message "Exporting...")
21457 (setq-default org-todo-line-regexp org-todo-line-regexp)
21458 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
21459 (setq-default org-done-keywords org-done-keywords)
21460 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
21461 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
21462 ext-plist
21463 (org-infile-export-plist)))
21465 (style (plist-get opt-plist :style))
21466 (link-validate (plist-get opt-plist :link-validation-function))
21467 valid thetoc have-headings first-heading-pos
21468 (odd org-odd-levels-only)
21469 (region-p (org-region-active-p))
21470 (subtree-p
21471 (when region-p
21472 (save-excursion
21473 (goto-char (region-beginning))
21474 (and (org-at-heading-p)
21475 (>= (org-end-of-subtree t t) (region-end))))))
21476 ;; The following two are dynamically scoped into other
21477 ;; routines below.
21478 (org-current-export-dir (org-export-directory :html opt-plist))
21479 (org-current-export-file buffer-file-name)
21480 (level 0) (line "") (origline "") txt todo
21481 (umax nil)
21482 (umax-toc nil)
21483 (filename (if to-buffer nil
21484 (concat (file-name-as-directory
21485 (org-export-directory :html opt-plist))
21486 (file-name-sans-extension
21487 (or (and subtree-p
21488 (org-entry-get (region-beginning)
21489 "EXPORT_FILE_NAME" t))
21490 (file-name-nondirectory buffer-file-name)))
21491 ".html")))
21492 (current-dir (if buffer-file-name
21493 (file-name-directory buffer-file-name)
21494 default-directory))
21495 (buffer (if to-buffer
21496 (cond
21497 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
21498 (t (get-buffer-create to-buffer)))
21499 (find-file-noselect filename)))
21500 (org-levels-open (make-vector org-level-max nil))
21501 (date (format-time-string "%Y/%m/%d" (current-time)))
21502 (time (format-time-string "%X" (org-current-time)))
21503 (author (plist-get opt-plist :author))
21504 (title (or (and subtree-p (org-export-get-title-from-subtree))
21505 (plist-get opt-plist :title)
21506 (and (not
21507 (plist-get opt-plist :skip-before-1st-heading))
21508 (org-export-grab-title-from-buffer))
21509 (and buffer-file-name
21510 (file-name-sans-extension
21511 (file-name-nondirectory buffer-file-name)))
21512 "UNTITLED"))
21513 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
21514 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
21515 (inquote nil)
21516 (infixed nil)
21517 (in-local-list nil)
21518 (local-list-num nil)
21519 (local-list-indent nil)
21520 (llt org-plain-list-ordered-item-terminator)
21521 (email (plist-get opt-plist :email))
21522 (language (plist-get opt-plist :language))
21523 (lang-words nil)
21524 (target-alist nil) tg
21525 (head-count 0) cnt
21526 (start 0)
21527 (coding-system (and (boundp 'buffer-file-coding-system)
21528 buffer-file-coding-system))
21529 (coding-system-for-write (or org-export-html-coding-system
21530 coding-system))
21531 (save-buffer-coding-system (or org-export-html-coding-system
21532 coding-system))
21533 (charset (and coding-system-for-write
21534 (fboundp 'coding-system-get)
21535 (coding-system-get coding-system-for-write
21536 'mime-charset)))
21537 (region
21538 (buffer-substring
21539 (if region-p (region-beginning) (point-min))
21540 (if region-p (region-end) (point-max))))
21541 (lines
21542 (org-split-string
21543 (org-cleaned-string-for-export
21544 region
21545 :emph-multiline t
21546 :for-html t
21547 :skip-before-1st-heading
21548 (plist-get opt-plist :skip-before-1st-heading)
21549 :archived-trees
21550 (plist-get opt-plist :archived-trees)
21551 :add-text
21552 (plist-get opt-plist :text)
21553 :LaTeX-fragments
21554 (plist-get opt-plist :LaTeX-fragments))
21555 "[\r\n]"))
21556 table-open type
21557 table-buffer table-orig-buffer
21558 ind start-is-num starter didclose
21559 rpl path desc descp desc1 desc2 link
21562 (let ((inhibit-read-only t))
21563 (org-unmodified
21564 (remove-text-properties (point-min) (point-max)
21565 '(:org-license-to-kill t))))
21567 (message "Exporting...")
21569 (setq org-min-level (org-get-min-level lines))
21570 (setq org-last-level org-min-level)
21571 (org-init-section-numbers)
21573 ;; Get the language-dependent settings
21574 (setq lang-words (or (assoc language org-export-language-setup)
21575 (assoc "en" org-export-language-setup)))
21577 ;; Switch to the output buffer
21578 (set-buffer buffer)
21579 (erase-buffer)
21580 (fundamental-mode)
21582 (and (fboundp 'set-buffer-file-coding-system)
21583 (set-buffer-file-coding-system coding-system-for-write))
21585 (let ((case-fold-search nil)
21586 (org-odd-levels-only odd))
21587 ;; create local variables for all options, to make sure all called
21588 ;; functions get the correct information
21589 (mapcar (lambda (x)
21590 (set (make-local-variable (cdr x))
21591 (plist-get opt-plist (car x))))
21592 org-export-plist-vars)
21593 (setq umax (if arg (prefix-numeric-value arg)
21594 org-export-headline-levels))
21595 (setq umax-toc (if (integerp org-export-with-toc)
21596 (min org-export-with-toc umax)
21597 umax))
21598 (unless body-only
21599 ;; File header
21600 (insert (format
21601 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
21602 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
21603 <html xmlns=\"http://www.w3.org/1999/xhtml\"
21604 lang=\"%s\" xml:lang=\"%s\">
21605 <head>
21606 <title>%s</title>
21607 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
21608 <meta name=\"generator\" content=\"Org-mode\"/>
21609 <meta name=\"generated\" content=\"%s %s\"/>
21610 <meta name=\"author\" content=\"%s\"/>
21612 </head><body>
21614 language language (org-html-expand title)
21615 (or charset "iso-8859-1") date time author style))
21617 (insert (or (plist-get opt-plist :preamble) ""))
21619 (when (plist-get opt-plist :auto-preamble)
21620 (if title (insert (format org-export-html-title-format
21621 (org-html-expand title))))))
21623 (if (and org-export-with-toc (not body-only))
21624 (progn
21625 (push (format "<h%d>%s</h%d>\n"
21626 org-export-html-toplevel-hlevel
21627 (nth 3 lang-words)
21628 org-export-html-toplevel-hlevel)
21629 thetoc)
21630 (push "<ul>\n<li>" thetoc)
21631 (setq lines
21632 (mapcar '(lambda (line)
21633 (if (string-match org-todo-line-regexp line)
21634 ;; This is a headline
21635 (progn
21636 (setq have-headings t)
21637 (setq level (- (match-end 1) (match-beginning 1))
21638 level (org-tr-level level)
21639 txt (save-match-data
21640 (org-html-expand
21641 (org-export-cleanup-toc-line
21642 (match-string 3 line))))
21643 todo
21644 (or (and org-export-mark-todo-in-toc
21645 (match-beginning 2)
21646 (not (member (match-string 2 line)
21647 org-done-keywords)))
21648 ; TODO, not DONE
21649 (and org-export-mark-todo-in-toc
21650 (= level umax-toc)
21651 (org-search-todo-below
21652 line lines level))))
21653 (if (and (memq org-export-with-tags '(not-in-toc nil))
21654 (string-match
21655 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
21656 txt))
21657 (setq txt (replace-match "" t t txt)))
21658 (if (string-match quote-re0 txt)
21659 (setq txt (replace-match "" t t txt)))
21660 (if org-export-with-section-numbers
21661 (setq txt (concat (org-section-number level)
21662 " " txt)))
21663 (if (<= level (max umax umax-toc))
21664 (setq head-count (+ head-count 1)))
21665 (if (<= level umax-toc)
21666 (progn
21667 (if (> level org-last-level)
21668 (progn
21669 (setq cnt (- level org-last-level))
21670 (while (>= (setq cnt (1- cnt)) 0)
21671 (push "\n<ul>\n<li>" thetoc))
21672 (push "\n" thetoc)))
21673 (if (< level org-last-level)
21674 (progn
21675 (setq cnt (- org-last-level level))
21676 (while (>= (setq cnt (1- cnt)) 0)
21677 (push "</li>\n</ul>" thetoc))
21678 (push "\n" thetoc)))
21679 ;; Check for targets
21680 (while (string-match org-target-regexp line)
21681 (setq tg (match-string 1 line)
21682 line (replace-match
21683 (concat "@<span class=\"target\">" tg "@</span> ")
21684 t t line))
21685 (push (cons (org-solidify-link-text tg)
21686 (format "sec-%d" head-count))
21687 target-alist))
21688 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
21689 (setq txt (replace-match "" t t txt)))
21690 (push
21691 (format
21692 (if todo
21693 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
21694 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
21695 head-count txt) thetoc)
21697 (setq org-last-level level))
21699 line)
21700 lines))
21701 (while (> org-last-level (1- org-min-level))
21702 (setq org-last-level (1- org-last-level))
21703 (push "</li>\n</ul>\n" thetoc))
21704 (setq thetoc (if have-headings (nreverse thetoc) nil))))
21706 (setq head-count 0)
21707 (org-init-section-numbers)
21709 (while (setq line (pop lines) origline line)
21710 (catch 'nextline
21712 ;; end of quote section?
21713 (when (and inquote (string-match "^\\*+ " line))
21714 (insert "</pre>\n")
21715 (setq inquote nil))
21716 ;; inside a quote section?
21717 (when inquote
21718 (insert (org-html-protect line) "\n")
21719 (throw 'nextline nil))
21721 ;; verbatim lines
21722 (when (and org-export-with-fixed-width
21723 (string-match "^[ \t]*:\\(.*\\)" line))
21724 (when (not infixed)
21725 (setq infixed t)
21726 (insert "<pre>\n"))
21727 (insert (org-html-protect (match-string 1 line)) "\n")
21728 (when (and lines
21729 (not (string-match "^[ \t]*\\(:.*\\)"
21730 (car lines))))
21731 (setq infixed nil)
21732 (insert "</pre>\n"))
21733 (throw 'nextline nil))
21735 ;; Protected HTML
21736 (when (get-text-property 0 'org-protected line)
21737 (let (par)
21738 (when (re-search-backward
21739 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
21740 (setq par (match-string 1))
21741 (replace-match "\\2\n"))
21742 (insert line "\n")
21743 (while (and lines
21744 (get-text-property 0 'org-protected (car lines)))
21745 (insert (pop lines) "\n"))
21746 (and par (insert "<p>\n")))
21747 (throw 'nextline nil))
21749 ;; Horizontal line
21750 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
21751 (insert "\n<hr/>\n")
21752 (throw 'nextline nil))
21754 ;; make targets to anchors
21755 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
21756 (cond
21757 ((match-end 2)
21758 (setq line (replace-match
21759 (concat "@<a name=\""
21760 (org-solidify-link-text (match-string 1 line))
21761 "\">\\nbsp@</a>")
21762 t t line)))
21763 ((and org-export-with-toc (equal (string-to-char line) ?*))
21764 (setq line (replace-match
21765 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
21766 ; (concat "@<i>" (match-string 1 line) "@</i> ")
21767 t t line)))
21769 (setq line (replace-match
21770 (concat "@<a name=\""
21771 (org-solidify-link-text (match-string 1 line))
21772 "\" class=\"target\">" (match-string 1 line) "@</a> ")
21773 t t line)))))
21775 (setq line (org-html-handle-time-stamps line))
21777 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
21778 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
21779 ;; Also handle sub_superscripts and checkboxes
21780 (setq line (org-html-expand line))
21782 ;; Format the links
21783 (setq start 0)
21784 (while (string-match org-bracket-link-analytic-regexp line start)
21785 (setq start (match-beginning 0))
21786 (setq type (if (match-end 2) (match-string 2 line) "internal"))
21787 (setq path (match-string 3 line))
21788 (setq desc1 (if (match-end 5) (match-string 5 line))
21789 desc2 (if (match-end 2) (concat type ":" path) path)
21790 descp (and desc1 (not (equal desc1 desc2)))
21791 desc (or desc1 desc2))
21792 ;; Make an image out of the description if that is so wanted
21793 (when (and descp (org-file-image-p desc))
21794 (save-match-data
21795 (if (string-match "^file:" desc)
21796 (setq desc (substring desc (match-end 0)))))
21797 (setq desc (concat "<img src=\"" desc "\"/>")))
21798 ;; FIXME: do we need to unescape here somewhere?
21799 (cond
21800 ((equal type "internal")
21801 (setq rpl
21802 (concat
21803 "<a href=\"#"
21804 (org-solidify-link-text
21805 (save-match-data (org-link-unescape path)) target-alist)
21806 "\">" desc "</a>")))
21807 ((member type '("http" "https")) ; FIXME: need to test this.
21808 ;; standard URL, just check if we need to inline an image
21809 (if (and (or (eq t org-export-html-inline-images)
21810 (and org-export-html-inline-images (not descp)))
21811 (org-file-image-p path))
21812 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
21813 (setq link (concat type ":" path))
21814 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
21815 ((member type '("ftp" "mailto" "news"))
21816 ;; standard URL
21817 (setq link (concat type ":" path))
21818 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
21819 ((string= type "file")
21820 ;; FILE link
21821 (let* ((filename path)
21822 (abs-p (file-name-absolute-p filename))
21823 thefile file-is-image-p search)
21824 (save-match-data
21825 (if (string-match "::\\(.*\\)" filename)
21826 (setq search (match-string 1 filename)
21827 filename (replace-match "" t nil filename)))
21828 (setq valid
21829 (if (functionp link-validate)
21830 (funcall link-validate filename current-dir)
21832 (setq file-is-image-p (org-file-image-p filename))
21833 (setq thefile (if abs-p (expand-file-name filename) filename))
21834 (when (and org-export-html-link-org-files-as-html
21835 (string-match "\\.org$" thefile))
21836 (setq thefile (concat (substring thefile 0
21837 (match-beginning 0))
21838 ".html"))
21839 (if (and search
21840 ;; make sure this is can be used as target search
21841 (not (string-match "^[0-9]*$" search))
21842 (not (string-match "^\\*" search))
21843 (not (string-match "^/.*/$" search)))
21844 (setq thefile (concat thefile "#"
21845 (org-solidify-link-text
21846 (org-link-unescape search)))))
21847 (when (string-match "^file:" desc)
21848 (setq desc (replace-match "" t t desc))
21849 (if (string-match "\\.org$" desc)
21850 (setq desc (replace-match "" t t desc))))))
21851 (setq rpl (if (and file-is-image-p
21852 (or (eq t org-export-html-inline-images)
21853 (and org-export-html-inline-images
21854 (not descp))))
21855 (concat "<img src=\"" thefile "\"/>")
21856 (concat "<a href=\"" thefile "\">" desc "</a>")))
21857 (if (not valid) (setq rpl desc))))
21858 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
21859 (setq rpl (concat "<i>&lt;" type ":"
21860 (save-match-data (org-link-unescape path))
21861 "&gt;</i>"))))
21862 (setq line (replace-match rpl t t line)
21863 start (+ start (length rpl))))
21865 ;; TODO items
21866 (if (and (string-match org-todo-line-regexp line)
21867 (match-beginning 2))
21869 (setq line
21870 (concat (substring line 0 (match-beginning 2))
21871 "<span class=\""
21872 (if (member (match-string 2 line)
21873 org-done-keywords)
21874 "done" "todo")
21875 "\">" (match-string 2 line)
21876 "</span>" (substring line (match-end 2)))))
21878 ;; Does this contain a reference to a footnote?
21879 (when org-export-with-footnotes
21880 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line)
21881 (let ((n (match-string 2 line)))
21882 (setq line
21883 (replace-match
21884 (format
21885 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
21886 (match-string 1 line) n n n)
21887 t t line)))))
21889 (cond
21890 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
21891 ;; This is a headline
21892 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
21893 txt (match-string 2 line))
21894 (if (string-match quote-re0 txt)
21895 (setq txt (replace-match "" t t txt)))
21896 (if (<= level (max umax umax-toc))
21897 (setq head-count (+ head-count 1)))
21898 (when in-local-list
21899 ;; Close any local lists before inserting a new header line
21900 (while local-list-num
21901 (org-close-li)
21902 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
21903 (pop local-list-num))
21904 (setq local-list-indent nil
21905 in-local-list nil))
21906 (setq first-heading-pos (or first-heading-pos (point)))
21907 (org-html-level-start level txt umax
21908 (and org-export-with-toc (<= level umax))
21909 head-count)
21910 ;; QUOTES
21911 (when (string-match quote-re line)
21912 (insert "<pre>")
21913 (setq inquote t)))
21915 ((and org-export-with-tables
21916 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
21917 (if (not table-open)
21918 ;; New table starts
21919 (setq table-open t table-buffer nil table-orig-buffer nil))
21920 ;; Accumulate lines
21921 (setq table-buffer (cons line table-buffer)
21922 table-orig-buffer (cons origline table-orig-buffer))
21923 (when (or (not lines)
21924 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
21925 (car lines))))
21926 (setq table-open nil
21927 table-buffer (nreverse table-buffer)
21928 table-orig-buffer (nreverse table-orig-buffer))
21929 (org-close-par-maybe)
21930 (insert (org-format-table-html table-buffer table-orig-buffer))))
21932 ;; Normal lines
21933 (when (string-match
21934 (cond
21935 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
21936 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
21937 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
21938 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
21939 line)
21940 (setq ind (org-get-string-indentation line)
21941 start-is-num (match-beginning 4)
21942 starter (if (match-beginning 2)
21943 (substring (match-string 2 line) 0 -1))
21944 line (substring line (match-beginning 5)))
21945 (unless (string-match "[^ \t]" line)
21946 ;; empty line. Pretend indentation is large.
21947 (setq ind (if org-empty-line-terminates-plain-lists
21949 (1+ (or (car local-list-indent) 1)))))
21950 (setq didclose nil)
21951 (while (and in-local-list
21952 (or (and (= ind (car local-list-indent))
21953 (not starter))
21954 (< ind (car local-list-indent))))
21955 (setq didclose t)
21956 (org-close-li)
21957 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
21958 (pop local-list-num) (pop local-list-indent)
21959 (setq in-local-list local-list-indent))
21960 (cond
21961 ((and starter
21962 (or (not in-local-list)
21963 (> ind (car local-list-indent))))
21964 ;; Start new (level of) list
21965 (org-close-par-maybe)
21966 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
21967 (push start-is-num local-list-num)
21968 (push ind local-list-indent)
21969 (setq in-local-list t))
21970 (starter
21971 ;; continue current list
21972 (org-close-li)
21973 (insert "<li>\n"))
21974 (didclose
21975 ;; we did close a list, normal text follows: need <p>
21976 (org-open-par)))
21977 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
21978 (setq line
21979 (replace-match
21980 (if (equal (match-string 1 line) "X")
21981 "<b>[X]</b>"
21982 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
21983 t t line))))
21985 ;; Empty lines start a new paragraph. If hand-formatted lists
21986 ;; are not fully interpreted, lines starting with "-", "+", "*"
21987 ;; also start a new paragraph.
21988 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
21990 ;; Is this the start of a footnote?
21991 (when org-export-with-footnotes
21992 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
21993 (org-close-par-maybe)
21994 (let ((n (match-string 1 line)))
21995 (setq line (replace-match
21996 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
21998 ;; Check if the line break needs to be conserved
21999 (cond
22000 ((string-match "\\\\\\\\[ \t]*$" line)
22001 (setq line (replace-match "<br/>" t t line)))
22002 (org-export-preserve-breaks
22003 (setq line (concat line "<br/>"))))
22005 (insert line "\n")))))
22007 ;; Properly close all local lists and other lists
22008 (when inquote (insert "</pre>\n"))
22009 (when in-local-list
22010 ;; Close any local lists before inserting a new header line
22011 (while local-list-num
22012 (org-close-li)
22013 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
22014 (pop local-list-num))
22015 (setq local-list-indent nil
22016 in-local-list nil))
22017 (org-html-level-start 1 nil umax
22018 (and org-export-with-toc (<= level umax))
22019 head-count)
22021 (unless body-only
22022 (when (plist-get opt-plist :auto-postamble)
22023 (when (and org-export-author-info author)
22024 (insert "<p class=\"author\"> "
22025 (nth 1 lang-words) ": " author "\n")
22026 (when email
22027 (insert "<a href=\"mailto:" email "\">&lt;"
22028 email "&gt;</a>\n"))
22029 (insert "</p>\n"))
22030 (when (and date time org-export-time-stamp-file)
22031 (insert "<p class=\"date\"> "
22032 (nth 2 lang-words) ": "
22033 date " " time "</p>\n")))
22035 (if org-export-html-with-timestamp
22036 (insert org-export-html-html-helper-timestamp))
22037 (insert (or (plist-get opt-plist :postamble) ""))
22038 (insert "</body>\n</html>\n"))
22040 (normal-mode)
22041 (if (eq major-mode default-major-mode) (html-mode))
22043 ;; insert the table of contents
22044 (goto-char (point-min))
22045 (when thetoc
22046 (if (or (re-search-forward
22047 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
22048 (re-search-forward
22049 "\\[TABLE-OF-CONTENTS\\]" nil t))
22050 (progn
22051 (goto-char (match-beginning 0))
22052 (replace-match ""))
22053 (goto-char first-heading-pos)
22054 (when (looking-at "\\s-*</p>")
22055 (goto-char (match-end 0))
22056 (insert "\n")))
22057 (mapc 'insert thetoc))
22058 ;; remove empty paragraphs and lists
22059 (goto-char (point-min))
22060 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
22061 (replace-match ""))
22062 (goto-char (point-min))
22063 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
22064 (replace-match ""))
22065 (or to-buffer (save-buffer))
22066 (goto-char (point-min))
22067 (message "Exporting... done")
22068 (if (eq to-buffer 'string)
22069 (prog1 (buffer-substring (point-min) (point-max))
22070 (kill-buffer (current-buffer)))
22071 (current-buffer)))))
22073 (defvar org-table-colgroup-info nil) ;; FIXME: mode to a better place
22074 (defun org-format-table-ascii (lines)
22075 "Format a table for ascii export."
22076 (if (stringp lines)
22077 (setq lines (org-split-string lines "\n")))
22078 (if (not (string-match "^[ \t]*|" (car lines)))
22079 ;; Table made by table.el - test for spanning
22080 lines
22082 ;; A normal org table
22083 ;; Get rid of hlines at beginning and end
22084 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
22085 (setq lines (nreverse lines))
22086 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
22087 (setq lines (nreverse lines))
22088 (when org-export-table-remove-special-lines
22089 ;; Check if the table has a marking column. If yes remove the
22090 ;; column and the special lines
22091 (setq lines (org-table-clean-before-export lines)))
22092 ;; Get rid of the vertical lines except for grouping
22093 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
22094 rtn line vl1 start)
22095 (while (setq line (pop lines))
22096 (if (string-match org-table-hline-regexp line)
22097 (and (string-match "|\\(.*\\)|" line)
22098 (setq line (replace-match " \\1" t nil line)))
22099 (setq start 0 vl1 vl)
22100 (while (string-match "|" line start)
22101 (setq start (match-end 0))
22102 (or (pop vl1) (setq line (replace-match " " t t line)))))
22103 (push line rtn))
22104 (nreverse rtn))))
22106 (defun org-colgroup-info-to-vline-list (info)
22107 (let (vl new last)
22108 (while info
22109 (setq last new new (pop info))
22110 (if (or (memq last '(:end :startend))
22111 (memq new '(:start :startend)))
22112 (push t vl)
22113 (push nil vl)))
22114 (setq vl (cons nil (nreverse vl)))))
22117 (defun org-format-table-html (lines olines)
22118 "Find out which HTML converter to use and return the HTML code."
22119 (if (stringp lines)
22120 (setq lines (org-split-string lines "\n")))
22121 (if (string-match "^[ \t]*|" (car lines))
22122 ;; A normal org table
22123 (org-format-org-table-html lines)
22124 ;; Table made by table.el - test for spanning
22125 (let* ((hlines (delq nil (mapcar
22126 (lambda (x)
22127 (if (string-match "^[ \t]*\\+-" x) x
22128 nil))
22129 lines)))
22130 (first (car hlines))
22131 (ll (and (string-match "\\S-+" first)
22132 (match-string 0 first)))
22133 (re (concat "^[ \t]*" (regexp-quote ll)))
22134 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
22135 hlines))))
22136 (if (and (not spanning)
22137 (not org-export-prefer-native-exporter-for-tables))
22138 ;; We can use my own converter with HTML conversions
22139 (org-format-table-table-html lines)
22140 ;; Need to use the code generator in table.el, with the original text.
22141 (org-format-table-table-html-using-table-generate-source olines)))))
22143 (defun org-format-org-table-html (lines &optional splice)
22144 "Format a table into HTML."
22145 ;; Get rid of hlines at beginning and end
22146 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
22147 (setq lines (nreverse lines))
22148 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
22149 (setq lines (nreverse lines))
22150 (when org-export-table-remove-special-lines
22151 ;; Check if the table has a marking column. If yes remove the
22152 ;; column and the special lines
22153 (setq lines (org-table-clean-before-export lines)))
22155 (let ((head (and org-export-highlight-first-table-line
22156 (delq nil (mapcar
22157 (lambda (x) (string-match "^[ \t]*|-" x))
22158 (cdr lines)))))
22159 (nlines 0) fnum i
22160 tbopen line fields html gr colgropen)
22161 (if splice (setq head nil))
22162 (unless splice (push (if head "<thead>" "<tbody>") html))
22163 (setq tbopen t)
22164 (while (setq line (pop lines))
22165 (catch 'next-line
22166 (if (string-match "^[ \t]*|-" line)
22167 (progn
22168 (unless splice
22169 (push (if head "</thead>" "</tbody>") html)
22170 (if lines (push "<tbody>" html) (setq tbopen nil)))
22171 (setq head nil) ;; head ends here, first time around
22172 ;; ignore this line
22173 (throw 'next-line t)))
22174 ;; Break the line into fields
22175 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
22176 (unless fnum (setq fnum (make-vector (length fields) 0)))
22177 (setq nlines (1+ nlines) i -1)
22178 (push (concat "<tr>"
22179 (mapconcat
22180 (lambda (x)
22181 (setq i (1+ i))
22182 (if (and (< i nlines)
22183 (string-match org-table-number-regexp x))
22184 (incf (aref fnum i)))
22185 (if head
22186 (concat (car org-export-table-header-tags) x
22187 (cdr org-export-table-header-tags))
22188 (concat (car org-export-table-data-tags) x
22189 (cdr org-export-table-data-tags))))
22190 fields "")
22191 "</tr>")
22192 html)))
22193 (unless splice (if tbopen (push "</tbody>" html)))
22194 (unless splice (push "</table>\n" html))
22195 (setq html (nreverse html))
22196 (unless splice
22197 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
22198 (push (mapconcat
22199 (lambda (x)
22200 (setq gr (pop org-table-colgroup-info))
22201 (format "%s<COL align=\"%s\"></COL>%s"
22202 (if (memq gr '(:start :startend))
22203 (prog1
22204 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
22205 (setq colgropen t))
22207 (if (> (/ (float x) nlines) org-table-number-fraction)
22208 "right" "left")
22209 (if (memq gr '(:end :startend))
22210 (progn (setq colgropen nil) "</colgroup>")
22211 "")))
22212 fnum "")
22213 html)
22214 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
22215 (push org-export-html-table-tag html))
22216 (concat (mapconcat 'identity html "\n") "\n")))
22218 (defun org-table-clean-before-export (lines)
22219 "Check if the table has a marking column.
22220 If yes remove the column and the special lines."
22221 (setq org-table-colgroup-info nil)
22222 (if (memq nil
22223 (mapcar
22224 (lambda (x) (or (string-match "^[ \t]*|-" x)
22225 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
22226 lines))
22227 (progn
22228 (setq org-table-clean-did-remove-column nil)
22229 (delq nil
22230 (mapcar
22231 (lambda (x)
22232 (cond
22233 ((string-match "^[ \t]*| */ *|" x)
22234 (setq org-table-colgroup-info
22235 (mapcar (lambda (x)
22236 (cond ((member x '("<" "&lt;")) :start)
22237 ((member x '(">" "&gt;")) :end)
22238 ((member x '("<>" "&lt;&gt;")) :startend)
22239 (t nil)))
22240 (org-split-string x "[ \t]*|[ \t]*")))
22241 nil)
22242 (t x)))
22243 lines)))
22244 (setq org-table-clean-did-remove-column t)
22245 (delq nil
22246 (mapcar
22247 (lambda (x)
22248 (cond
22249 ((string-match "^[ \t]*| */ *|" x)
22250 (setq org-table-colgroup-info
22251 (mapcar (lambda (x)
22252 (cond ((member x '("<" "&lt;")) :start)
22253 ((member x '(">" "&gt;")) :end)
22254 ((member x '("<>" "&lt;&gt;")) :startend)
22255 (t nil)))
22256 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
22257 nil)
22258 ((string-match "^[ \t]*| *[!_^/] *|" x)
22259 nil) ; ignore this line
22260 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
22261 (string-match "^\\([ \t]*\\)|[^|]*|" x))
22262 ;; remove the first column
22263 (replace-match "\\1|" t nil x))
22264 (t (error "This should not happen"))))
22265 lines))))
22267 (defun org-format-table-table-html (lines)
22268 "Format a table generated by table.el into HTML.
22269 This conversion does *not* use `table-generate-source' from table.el.
22270 This has the advantage that Org-mode's HTML conversions can be used.
22271 But it has the disadvantage, that no cell- or row-spanning is allowed."
22272 (let (line field-buffer
22273 (head org-export-highlight-first-table-line)
22274 fields html empty)
22275 (setq html (concat org-export-html-table-tag "\n"))
22276 (while (setq line (pop lines))
22277 (setq empty "&nbsp;")
22278 (catch 'next-line
22279 (if (string-match "^[ \t]*\\+-" line)
22280 (progn
22281 (if field-buffer
22282 (progn
22283 (setq
22284 html
22285 (concat
22286 html
22287 "<tr>"
22288 (mapconcat
22289 (lambda (x)
22290 (if (equal x "") (setq x empty))
22291 (if head
22292 (concat (car org-export-table-header-tags) x
22293 (cdr org-export-table-header-tags))
22294 (concat (car org-export-table-data-tags) x
22295 (cdr org-export-table-data-tags))))
22296 field-buffer "\n")
22297 "</tr>\n"))
22298 (setq head nil)
22299 (setq field-buffer nil)))
22300 ;; Ignore this line
22301 (throw 'next-line t)))
22302 ;; Break the line into fields and store the fields
22303 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
22304 (if field-buffer
22305 (setq field-buffer (mapcar
22306 (lambda (x)
22307 (concat x "<br/>" (pop fields)))
22308 field-buffer))
22309 (setq field-buffer fields))))
22310 (setq html (concat html "</table>\n"))
22311 html))
22313 (defun org-format-table-table-html-using-table-generate-source (lines)
22314 "Format a table into html, using `table-generate-source' from table.el.
22315 This has the advantage that cell- or row-spanning is allowed.
22316 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
22317 (require 'table)
22318 (with-current-buffer (get-buffer-create " org-tmp1 ")
22319 (erase-buffer)
22320 (insert (mapconcat 'identity lines "\n"))
22321 (goto-char (point-min))
22322 (if (not (re-search-forward "|[^+]" nil t))
22323 (error "Error processing table"))
22324 (table-recognize-table)
22325 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
22326 (table-generate-source 'html " org-tmp2 ")
22327 (set-buffer " org-tmp2 ")
22328 (buffer-substring (point-min) (point-max))))
22330 (defun org-html-handle-time-stamps (s)
22331 "Format time stamps in string S, or remove them."
22332 (catch 'exit
22333 (let (r b)
22334 (while (string-match org-maybe-keyword-time-regexp s)
22335 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
22336 ;; never export CLOCK
22337 (throw 'exit ""))
22338 (or b (setq b (substring s 0 (match-beginning 0))))
22339 (if (not org-export-with-timestamps)
22340 (setq r (concat r (substring s 0 (match-beginning 0)))
22341 s (substring s (match-end 0)))
22342 (setq r (concat
22343 r (substring s 0 (match-beginning 0))
22344 (if (match-end 1)
22345 (format "@<span class=\"timestamp-kwd\">%s @</span>"
22346 (match-string 1 s)))
22347 (format " @<span class=\"timestamp\">%s@</span>"
22348 (substring
22349 (org-translate-time (match-string 3 s)) 1 -1)))
22350 s (substring s (match-end 0)))))
22351 ;; Line break if line started and ended with time stamp stuff
22352 (if (not r)
22354 (setq r (concat r s))
22355 (unless (string-match "\\S-" (concat b s))
22356 (setq r (concat r "@<br/>")))
22357 r))))
22359 (defun org-html-protect (s)
22360 ;; convert & to &amp;, < to &lt; and > to &gt;
22361 (let ((start 0))
22362 (while (string-match "&" s start)
22363 (setq s (replace-match "&amp;" t t s)
22364 start (1+ (match-beginning 0))))
22365 (while (string-match "<" s)
22366 (setq s (replace-match "&lt;" t t s)))
22367 (while (string-match ">" s)
22368 (setq s (replace-match "&gt;" t t s))))
22371 (defun org-export-cleanup-toc-line (s)
22372 "Remove tags and time staps from lines going into the toc."
22373 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
22374 (setq s (replace-match "" t t s)))
22375 (when org-export-remove-timestamps-from-toc
22376 (while (string-match org-maybe-keyword-time-regexp s)
22377 (setq s (replace-match "" t t s))))
22378 (while (string-match org-bracket-link-regexp s)
22379 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
22380 t t s)))
22383 (defun org-html-expand (string)
22384 "Prepare STRING for HTML export. Applies all active conversions.
22385 If there are links in the string, don't modify these."
22386 (let* (m s l res)
22387 (while (setq m (string-match org-bracket-link-regexp string))
22388 (setq s (substring string 0 m)
22389 l (match-string 0 string)
22390 string (substring string (match-end 0)))
22391 (push (org-html-do-expand s) res)
22392 (push l res))
22393 (push (org-html-do-expand string) res)
22394 (apply 'concat (nreverse res))))
22396 (defun org-html-do-expand (s)
22397 "Apply all active conversions to translate special ASCII to HTML."
22398 (setq s (org-html-protect s))
22399 (if org-export-html-expand
22400 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
22401 (setq s (replace-match "<\\1>" t nil s))))
22402 (if org-export-with-emphasize
22403 (setq s (org-export-html-convert-emphasize s)))
22404 (if org-export-with-sub-superscripts
22405 (setq s (org-export-html-convert-sub-super s)))
22406 (if org-export-with-TeX-macros
22407 (let ((start 0) wd ass)
22408 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
22409 (setq wd (match-string 1 s))
22410 (if (setq ass (assoc wd org-html-entities))
22411 (setq s (replace-match (or (cdr ass)
22412 (concat "&" (car ass) ";"))
22413 t t s))
22414 (setq start (+ start (length wd)))))))
22417 (defun org-create-multibrace-regexp (left right n)
22418 "Create a regular expression which will match a balanced sexp.
22419 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
22420 as single character strings.
22421 The regexp returned will match the entire expression including the
22422 delimiters. It will also define a single group which contains the
22423 match except for the outermost delimiters. The maximum depth of
22424 stacked delimiters is N. Escaping delimiters is not possible."
22425 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
22426 (or "\\|")
22427 (re nothing)
22428 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
22429 (while (> n 1)
22430 (setq n (1- n)
22431 re (concat re or next)
22432 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
22433 (concat left "\\(" re "\\)" right)))
22435 (defvar org-match-substring-regexp
22436 (concat
22437 "\\([^\\]\\)\\([_^]\\)\\("
22438 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
22439 "\\|"
22440 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
22441 "\\|"
22442 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
22443 "The regular expression matching a sub- or superscript.")
22445 ;(let ((s "a\\_b"))
22446 ; (and (string-match org-match-substring-regexp s)
22447 ; (conca t (match-string 1 s) ":::" (match-string 2 s))))
22449 (defun org-export-html-convert-sub-super (string)
22450 "Convert sub- and superscripts in STRING to HTML."
22451 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
22452 (while (string-match org-match-substring-regexp string s)
22453 (if (and requireb (match-end 8))
22454 (setq s (match-end 2))
22455 (setq s (match-end 1)
22456 key (if (string= (match-string 2 string) "_") "sub" "sup")
22457 c (or (match-string 8 string)
22458 (match-string 6 string)
22459 (match-string 5 string))
22460 string (replace-match
22461 (concat (match-string 1 string)
22462 "<" key ">" c "</" key ">")
22463 t t string))))
22464 (while (string-match "\\\\\\([_^]\\)" string)
22465 (setq string (replace-match (match-string 1 string) t t string)))
22466 string))
22468 (defun org-export-html-convert-emphasize (string)
22469 "Apply emphasis."
22470 (let ((s 0))
22471 (while (string-match org-emph-re string s)
22472 (if (not (equal
22473 (substring string (match-beginning 3) (1+ (match-beginning 3)))
22474 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
22475 (setq string (replace-match
22476 (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
22477 "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist))
22478 "\\5") t nil string))
22479 (setq s (1+ s))))
22480 string))
22482 (defvar org-par-open nil)
22483 (defun org-open-par ()
22484 "Insert <p>, but first close previous paragraph if any."
22485 (org-close-par-maybe)
22486 (insert "\n<p>")
22487 (setq org-par-open t))
22488 (defun org-close-par-maybe ()
22489 "Close paragraph if there is one open."
22490 (when org-par-open
22491 (insert "</p>")
22492 (setq org-par-open nil)))
22493 (defun org-close-li ()
22494 "Close <li> if necessary."
22495 (org-close-par-maybe)
22496 (insert "</li>\n"))
22498 (defvar body-only) ; dynamically scoped into this.
22499 (defun org-html-level-start (level title umax with-toc head-count)
22500 "Insert a new level in HTML export.
22501 When TITLE is nil, just close all open levels."
22502 (org-close-par-maybe)
22503 (let ((l (1+ (max level umax))))
22504 (while (<= l org-level-max)
22505 (if (aref org-levels-open (1- l))
22506 (progn
22507 (org-html-level-close l)
22508 (aset org-levels-open (1- l) nil)))
22509 (setq l (1+ l)))
22510 (when title
22511 ;; If title is nil, this means this function is called to close
22512 ;; all levels, so the rest is done only if title is given
22513 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
22514 (setq title (replace-match
22515 (if org-export-with-tags
22516 (save-match-data
22517 (concat
22518 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
22519 (mapconcat 'identity (org-split-string
22520 (match-string 1 title) ":")
22521 "&nbsp;")
22522 "</span>"))
22524 t t title)))
22525 (if (> level umax)
22526 (progn
22527 (if (aref org-levels-open (1- level))
22528 (progn
22529 (org-close-li)
22530 (insert "<li>" title "<br/>\n"))
22531 (aset org-levels-open (1- level) t)
22532 (org-close-par-maybe)
22533 (insert "<ul>\n<li>" title "<br/>\n")))
22534 (if (and org-export-with-section-numbers (not body-only))
22535 (setq title (concat (org-section-number level) " " title)))
22536 (setq level (+ level org-export-html-toplevel-hlevel -1))
22537 (if with-toc
22538 (insert (format "\n<h%d id=\"sec-%d\">%s</h%d>\n"
22539 level head-count title level))
22540 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
22541 (org-open-par)))))
22543 (defun org-html-level-close (&rest args)
22544 "Terminate one level in HTML export."
22545 (org-close-li)
22546 (insert "</ul>\n"))
22548 ;;; iCalendar export
22550 ;;;###autoload
22551 (defun org-export-icalendar-this-file ()
22552 "Export current file as an iCalendar file.
22553 The iCalendar file will be located in the same directory as the Org-mode
22554 file, but with extension `.ics'."
22555 (interactive)
22556 (org-export-icalendar nil buffer-file-name))
22558 ;;;###autoload
22559 (defun org-export-icalendar-all-agenda-files ()
22560 "Export all files in `org-agenda-files' to iCalendar .ics files.
22561 Each iCalendar file will be located in the same directory as the Org-mode
22562 file, but with extension `.ics'."
22563 (interactive)
22564 (apply 'org-export-icalendar nil (org-agenda-files t)))
22566 ;;;###autoload
22567 (defun org-export-icalendar-combine-agenda-files ()
22568 "Export all files in `org-agenda-files' to a single combined iCalendar file.
22569 The file is stored under the name `org-combined-agenda-icalendar-file'."
22570 (interactive)
22571 (apply 'org-export-icalendar t (org-agenda-files t)))
22573 (defun org-export-icalendar (combine &rest files)
22574 "Create iCalendar files for all elements of FILES.
22575 If COMBINE is non-nil, combine all calendar entries into a single large
22576 file and store it under the name `org-combined-agenda-icalendar-file'."
22577 (save-excursion
22578 (org-prepare-agenda-buffers files)
22579 (let* ((dir (org-export-directory
22580 :ical (list :publishing-directory
22581 org-export-publishing-directory)))
22582 file ical-file ical-buffer category started org-agenda-new-buffers)
22584 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
22585 (when combine
22586 (setq ical-file
22587 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
22588 org-combined-agenda-icalendar-file
22589 (expand-file-name org-combined-agenda-icalendar-file dir))
22590 ical-buffer (org-get-agenda-file-buffer ical-file))
22591 (set-buffer ical-buffer) (erase-buffer))
22592 (while (setq file (pop files))
22593 (catch 'nextfile
22594 (org-check-agenda-file file)
22595 (set-buffer (org-get-agenda-file-buffer file))
22596 (unless combine
22597 (setq ical-file (concat (file-name-as-directory dir)
22598 (file-name-sans-extension
22599 (file-name-nondirectory buffer-file-name))
22600 ".ics"))
22601 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
22602 (with-current-buffer ical-buffer (erase-buffer)))
22603 (setq category (or org-category
22604 (file-name-sans-extension
22605 (file-name-nondirectory buffer-file-name))))
22606 (if (symbolp category) (setq category (symbol-name category)))
22607 (let ((standard-output ical-buffer))
22608 (if combine
22609 (and (not started) (setq started t)
22610 (org-start-icalendar-file org-icalendar-combined-name))
22611 (org-start-icalendar-file category))
22612 (org-print-icalendar-entries combine)
22613 (when (or (and combine (not files)) (not combine))
22614 (org-finish-icalendar-file)
22615 (set-buffer ical-buffer)
22616 (save-buffer)
22617 (run-hooks 'org-after-save-iCalendar-file-hook)))))
22618 (org-release-buffers org-agenda-new-buffers))))
22620 (defvar org-after-save-iCalendar-file-hook nil
22621 "Hook run after an iCalendar file has been saved.
22622 The iCalendar buffer is still current when this hook is run.
22623 A good way to use this is to tell a desktop calenndar application to re-read
22624 the iCalendar file.")
22626 (defun org-print-icalendar-entries (&optional combine)
22627 "Print iCalendar entries for the current Org-mode file to `standard-output'.
22628 When COMBINE is non nil, add the category to each line."
22629 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
22630 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
22631 (org-category-table (org-get-category-table))
22632 (dts (org-ical-ts-to-string
22633 (format-time-string (cdr org-time-stamp-formats) (current-time))
22634 "DTSTART"))
22635 hd ts ts2 state status (inc t) pos b sexp rrule
22636 scheduledp deadlinep tmp pri category
22637 (sexp-buffer (get-buffer-create "*ical-tmp*")))
22638 (save-excursion
22639 (goto-char (point-min))
22640 (while (re-search-forward re1 nil t)
22641 (catch :skip
22642 (org-agenda-skip)
22643 (setq pos (match-beginning 0)
22644 ts (match-string 0)
22645 inc t
22646 hd (org-get-heading)
22647 category (org-get-category))
22648 (if (looking-at re2)
22649 (progn
22650 (goto-char (match-end 0))
22651 (setq ts2 (match-string 1) inc nil))
22652 (setq tmp (buffer-substring (max (point-min)
22653 (- pos org-ds-keyword-length))
22654 pos)
22655 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
22656 (progn
22657 (setq inc nil)
22658 (replace-match "\\1" t nil ts))
22660 deadlinep (string-match org-deadline-regexp tmp)
22661 scheduledp (string-match org-scheduled-regexp tmp)
22662 ;; donep (org-entry-is-done-p)
22664 (if (or (string-match org-tr-regexp hd)
22665 (string-match org-ts-regexp hd))
22666 (setq hd (replace-match "" t t hd)))
22667 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
22668 (setq rrule
22669 (concat "\nRRULE:FREQ="
22670 (cdr (assoc
22671 (match-string 2 ts)
22672 '(("d" . "DAILY")("w" . "WEEKLY")
22673 ("m" . "MONTHLY")("y" . "YEARLY"))))
22674 ";INTERVAL=" (match-string 1 ts)))
22675 (setq rrule ""))
22676 (if (string-match org-bracket-link-regexp hd)
22677 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
22678 (match-string 1 hd))
22679 t t hd)))
22680 (if deadlinep (setq hd (concat "DL: " hd)))
22681 (if scheduledp (setq hd (concat "S: " hd)))
22682 (if (string-match "\\`<%%" ts)
22683 (with-current-buffer sexp-buffer
22684 (insert (substring ts 1 -1) " " hd "\n"))
22685 (princ (format "BEGIN:VEVENT
22687 %s%s
22688 SUMMARY:%s
22689 CATEGORIES:%s
22690 END:VEVENT\n"
22691 (org-ical-ts-to-string ts "DTSTART")
22692 (org-ical-ts-to-string ts2 "DTEND" inc)
22693 rrule hd category)))))
22695 (when (and org-icalendar-include-sexps
22696 (condition-case nil (require 'icalendar) (error nil))
22697 (fboundp 'icalendar-export-region))
22698 ;; Get all the literal sexps
22699 (goto-char (point-min))
22700 (while (re-search-forward "^&?%%(" nil t)
22701 (catch :skip
22702 (org-agenda-skip)
22703 (setq b (match-beginning 0))
22704 (goto-char (1- (match-end 0)))
22705 (forward-sexp 1)
22706 (end-of-line 1)
22707 (setq sexp (buffer-substring b (point)))
22708 (with-current-buffer sexp-buffer
22709 (insert sexp "\n"))
22710 (princ (org-diary-to-ical-string sexp-buffer)))))
22712 (when org-icalendar-include-todo
22713 (goto-char (point-min))
22714 (while (re-search-forward org-todo-line-regexp nil t)
22715 (catch :skip
22716 (org-agenda-skip)
22717 (setq state (match-string 2))
22718 (setq status (if (member state org-done-keywords)
22719 "COMPLETED" "NEEDS-ACTION"))
22720 (when (and state
22721 (or (not (member state org-done-keywords))
22722 (eq org-icalendar-include-todo 'all))
22723 (not (member org-archive-tag (org-get-tags-at)))
22725 (setq hd (match-string 3))
22726 (if (string-match org-bracket-link-regexp hd)
22727 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
22728 (match-string 1 hd))
22729 t t hd)))
22730 (if (string-match org-priority-regexp hd)
22731 (setq pri (string-to-char (match-string 2 hd))
22732 hd (concat (substring hd 0 (match-beginning 1))
22733 (substring hd (match-end 1))))
22734 (setq pri org-default-priority))
22735 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
22736 (- org-lowest-priority org-highest-priority))))))
22738 (princ (format "BEGIN:VTODO
22740 SUMMARY:%s
22741 CATEGORIES:%s
22742 SEQUENCE:1
22743 PRIORITY:%d
22744 STATUS:%s
22745 END:VTODO\n"
22746 dts hd category pri status)))))))))
22748 (defun org-start-icalendar-file (name)
22749 "Start an iCalendar file by inserting the header."
22750 (let ((user user-full-name)
22751 (name (or name "unknown"))
22752 (timezone (cadr (current-time-zone))))
22753 (princ
22754 (format "BEGIN:VCALENDAR
22755 VERSION:2.0
22756 X-WR-CALNAME:%s
22757 PRODID:-//%s//Emacs with Org-mode//EN
22758 X-WR-TIMEZONE:%s
22759 CALSCALE:GREGORIAN\n" name user timezone))))
22761 (defun org-finish-icalendar-file ()
22762 "Finish an iCalendar file by inserting the END statement."
22763 (princ "END:VCALENDAR\n"))
22765 (defun org-ical-ts-to-string (s keyword &optional inc)
22766 "Take a time string S and convert it to iCalendar format.
22767 KEYWORD is added in front, to make a complete line like DTSTART....
22768 When INC is non-nil, increase the hour by two (if time string contains
22769 a time), or the day by one (if it does not contain a time)."
22770 (let ((t1 (org-parse-time-string s 'nodefault))
22771 t2 fmt have-time time)
22772 (if (and (car t1) (nth 1 t1) (nth 2 t1))
22773 (setq t2 t1 have-time t)
22774 (setq t2 (org-parse-time-string s)))
22775 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
22776 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
22777 (when inc
22778 (if have-time
22779 (if org-agenda-default-appointment-duration
22780 (setq mi (+ org-agenda-default-appointment-duration mi))
22781 (setq h (+ 2 h)))
22782 (setq d (1+ d))))
22783 (setq time (encode-time s mi h d m y)))
22784 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
22785 (concat keyword (format-time-string fmt time))))
22787 ;;; XOXO export
22789 (defun org-export-as-xoxo-insert-into (buffer &rest output)
22790 (with-current-buffer buffer
22791 (apply 'insert output)))
22792 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
22794 (defun org-export-as-xoxo (&optional buffer)
22795 "Export the org buffer as XOXO.
22796 The XOXO buffer is named *xoxo-<source buffer name>*"
22797 (interactive (list (current-buffer)))
22798 ;; A quickie abstraction
22800 ;; Output everything as XOXO
22801 (with-current-buffer (get-buffer buffer)
22802 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
22803 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
22804 (org-infile-export-plist)))
22805 (filename (concat (file-name-as-directory
22806 (org-export-directory :xoxo opt-plist))
22807 (file-name-sans-extension
22808 (file-name-nondirectory buffer-file-name))
22809 ".html"))
22810 (out (find-file-noselect filename))
22811 (last-level 1)
22812 (hanging-li nil))
22813 ;; Check the output buffer is empty.
22814 (with-current-buffer out (erase-buffer))
22815 ;; Kick off the output
22816 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
22817 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
22818 (let* ((hd (match-string-no-properties 1))
22819 (level (length hd))
22820 (text (concat
22821 (match-string-no-properties 2)
22822 (save-excursion
22823 (goto-char (match-end 0))
22824 (let ((str ""))
22825 (catch 'loop
22826 (while 't
22827 (forward-line)
22828 (if (looking-at "^[ \t]\\(.*\\)")
22829 (setq str (concat str (match-string-no-properties 1)))
22830 (throw 'loop str)))))))))
22832 ;; Handle level rendering
22833 (cond
22834 ((> level last-level)
22835 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
22837 ((< level last-level)
22838 (dotimes (- (- last-level level) 1)
22839 (if hanging-li
22840 (org-export-as-xoxo-insert-into out "</li>\n"))
22841 (org-export-as-xoxo-insert-into out "</ol>\n"))
22842 (when hanging-li
22843 (org-export-as-xoxo-insert-into out "</li>\n")
22844 (setq hanging-li nil)))
22846 ((equal level last-level)
22847 (if hanging-li
22848 (org-export-as-xoxo-insert-into out "</li>\n")))
22851 (setq last-level level)
22853 ;; And output the new li
22854 (setq hanging-li 't)
22855 (if (equal ?+ (elt text 0))
22856 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
22857 (org-export-as-xoxo-insert-into out "<li>" text))))
22859 ;; Finally finish off the ol
22860 (dotimes (- last-level 1)
22861 (if hanging-li
22862 (org-export-as-xoxo-insert-into out "</li>\n"))
22863 (org-export-as-xoxo-insert-into out "</ol>\n"))
22865 ;; Finish the buffer off and clean it up.
22866 (switch-to-buffer-other-window out)
22867 (indent-region (point-min) (point-max) nil)
22868 (save-buffer)
22869 (goto-char (point-min))
22873 ;;;; Key bindings
22875 ;; Make `C-c C-x' a prefix key
22876 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
22878 ;; TAB key with modifiers
22879 (org-defkey org-mode-map "\C-i" 'org-cycle)
22880 (org-defkey org-mode-map [(tab)] 'org-cycle)
22881 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
22882 (org-defkey org-mode-map [(meta tab)] 'org-complete)
22883 (org-defkey org-mode-map "\M-\t" 'org-complete)
22884 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
22885 ;; The following line is necessary under Suse GNU/Linux
22886 (unless (featurep 'xemacs)
22887 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
22888 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
22889 (define-key org-mode-map (kbd "<backtab>") 'org-shifttab)
22891 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
22892 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
22893 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
22895 ;; Cursor keys with modifiers
22896 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
22897 (org-defkey org-mode-map [(meta right)] 'org-metaright)
22898 (org-defkey org-mode-map [(meta up)] 'org-metaup)
22899 (org-defkey org-mode-map [(meta down)] 'org-metadown)
22901 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
22902 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
22903 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
22904 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
22906 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
22907 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
22908 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
22909 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
22911 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
22912 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
22914 ;;; Extra keys for tty access.
22915 ;; We only set them when really needed because otherwise the
22916 ;; menus don't show the simple keys
22918 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
22919 (not window-system))
22920 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
22921 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
22922 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
22923 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
22924 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
22925 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
22926 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
22927 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
22928 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
22929 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
22930 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
22931 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
22932 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
22933 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
22934 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
22935 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
22936 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
22937 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
22938 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
22939 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
22940 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
22941 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
22943 ;; All the other keys
22945 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
22946 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
22947 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
22948 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
22949 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
22950 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
22951 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
22952 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
22953 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
22954 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
22955 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
22956 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
22957 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
22958 (org-defkey org-mode-map "\C-c\C-w" 'org-check-deadlines)
22959 (org-defkey org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
22960 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
22961 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
22962 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
22963 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
22964 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
22965 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
22966 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
22967 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
22968 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
22969 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
22970 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
22971 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
22972 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
22973 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
22974 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
22975 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
22976 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
22977 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
22978 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
22979 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
22980 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
22981 (org-defkey org-mode-map "\C-c^" 'org-sort)
22982 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
22983 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
22984 (org-defkey org-mode-map "\C-m" 'org-return)
22985 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
22986 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
22987 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
22988 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
22989 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
22990 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
22991 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
22992 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
22993 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
22994 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
22995 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
22996 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
22997 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
22998 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
22999 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
23000 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
23002 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
23003 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
23004 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
23005 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
23007 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
23008 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
23009 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
23010 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
23011 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
23012 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
23013 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
23014 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
23015 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
23017 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
23019 (when (featurep 'xemacs)
23020 (org-defkey org-mode-map 'button3 'popup-mode-menu))
23022 (defsubst org-table-p () (org-at-table-p))
23024 (defun org-self-insert-command (N)
23025 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
23026 If the cursor is in a table looking at whitespace, the whitespace is
23027 overwritten, and the table is not marked as requiring realignment."
23028 (interactive "p")
23029 (if (and (org-table-p)
23030 (progn
23031 ;; check if we blank the field, and if that triggers align
23032 (and org-table-auto-blank-field
23033 (member last-command
23034 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
23035 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
23036 ;; got extra space, this field does not determine column width
23037 (let (org-table-may-need-update) (org-table-blank-field))
23038 ;; no extra space, this field may determine column width
23039 (org-table-blank-field)))
23041 (eq N 1)
23042 (looking-at "[^|\n]* |"))
23043 (let (org-table-may-need-update)
23044 (goto-char (1- (match-end 0)))
23045 (delete-backward-char 1)
23046 (goto-char (match-beginning 0))
23047 (self-insert-command N))
23048 (setq org-table-may-need-update t)
23049 (self-insert-command N)
23050 (org-fix-tags-on-the-fly)))
23052 (defun org-fix-tags-on-the-fly ()
23053 (when (and (equal (char-after (point-at-bol)) ?*)
23054 (org-on-heading-p))
23055 (org-align-tags-here org-tags-column)))
23057 (defun org-delete-backward-char (N)
23058 "Like `delete-backward-char', insert whitespace at field end in tables.
23059 When deleting backwards, in tables this function will insert whitespace in
23060 front of the next \"|\" separator, to keep the table aligned. The table will
23061 still be marked for re-alignment if the field did fill the entire column,
23062 because, in this case the deletion might narrow the column."
23063 (interactive "p")
23064 (if (and (org-table-p)
23065 (eq N 1)
23066 (string-match "|" (buffer-substring (point-at-bol) (point)))
23067 (looking-at ".*?|"))
23068 (let ((pos (point))
23069 (noalign (looking-at "[^|\n\r]* |"))
23070 (c org-table-may-need-update))
23071 (backward-delete-char N)
23072 (skip-chars-forward "^|")
23073 (insert " ")
23074 (goto-char (1- pos))
23075 ;; noalign: if there were two spaces at the end, this field
23076 ;; does not determine the width of the column.
23077 (if noalign (setq org-table-may-need-update c)))
23078 (backward-delete-char N)
23079 (org-fix-tags-on-the-fly)))
23081 (defun org-delete-char (N)
23082 "Like `delete-char', but insert whitespace at field end in tables.
23083 When deleting characters, in tables this function will insert whitespace in
23084 front of the next \"|\" separator, to keep the table aligned. The table will
23085 still be marked for re-alignment if the field did fill the entire column,
23086 because, in this case the deletion might narrow the column."
23087 (interactive "p")
23088 (if (and (org-table-p)
23089 (not (bolp))
23090 (not (= (char-after) ?|))
23091 (eq N 1))
23092 (if (looking-at ".*?|")
23093 (let ((pos (point))
23094 (noalign (looking-at "[^|\n\r]* |"))
23095 (c org-table-may-need-update))
23096 (replace-match (concat
23097 (substring (match-string 0) 1 -1)
23098 " |"))
23099 (goto-char pos)
23100 ;; noalign: if there were two spaces at the end, this field
23101 ;; does not determine the width of the column.
23102 (if noalign (setq org-table-may-need-update c)))
23103 (delete-char N))
23104 (delete-char N)
23105 (org-fix-tags-on-the-fly)))
23107 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
23108 (put 'org-self-insert-command 'delete-selection t)
23109 (put 'orgtbl-self-insert-command 'delete-selection t)
23110 (put 'org-delete-char 'delete-selection 'supersede)
23111 (put 'org-delete-backward-char 'delete-selection 'supersede)
23113 ;; Make `flyspell-mode' delay after some commands
23114 (put 'org-self-insert-command 'flyspell-delayed t)
23115 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
23116 (put 'org-delete-char 'flyspell-delayed t)
23117 (put 'org-delete-backward-char 'flyspell-delayed t)
23119 ;; How to do this: Measure non-white length of current string
23120 ;; If equal to column width, we should realign.
23122 (defun org-remap (map &rest commands)
23123 "In MAP, remap the functions given in COMMANDS.
23124 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
23125 (let (new old)
23126 (while commands
23127 (setq old (pop commands) new (pop commands))
23128 (if (fboundp 'command-remapping)
23129 (org-defkey map (vector 'remap old) new)
23130 (substitute-key-definition old new map global-map)))))
23132 (when (eq org-enable-table-editor 'optimized)
23133 ;; If the user wants maximum table support, we need to hijack
23134 ;; some standard editing functions
23135 (org-remap org-mode-map
23136 'self-insert-command 'org-self-insert-command
23137 'delete-char 'org-delete-char
23138 'delete-backward-char 'org-delete-backward-char)
23139 (org-defkey org-mode-map "|" 'org-force-self-insert))
23141 (defun org-shiftcursor-error ()
23142 "Throw an error because Shift-Cursor command was applied in wrong context."
23143 (error "This command is active in special context like tables, headlines or timestamps"))
23145 (defun org-shifttab (&optional arg)
23146 "Global visibility cycling or move to previous table field.
23147 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
23148 on context.
23149 See the individual commands for more information."
23150 (interactive "P")
23151 (cond
23152 ((org-at-table-p) (call-interactively 'org-table-previous-field))
23153 (arg (message "Content view to level: ")
23154 (org-content (prefix-numeric-value arg))
23155 (setq org-cycle-global-status 'overview))
23156 (t (call-interactively 'org-global-cycle))))
23158 (defun org-shiftmetaleft ()
23159 "Promote subtree or delete table column.
23160 Calls `org-promote-subtree', `org-outdent-item',
23161 or `org-table-delete-column', depending on context.
23162 See the individual commands for more information."
23163 (interactive)
23164 (cond
23165 ((org-at-table-p) (call-interactively 'org-table-delete-column))
23166 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
23167 ((org-at-item-p) (call-interactively 'org-outdent-item))
23168 (t (org-shiftcursor-error))))
23170 (defun org-shiftmetaright ()
23171 "Demote subtree or insert table column.
23172 Calls `org-demote-subtree', `org-indent-item',
23173 or `org-table-insert-column', depending on context.
23174 See the individual commands for more information."
23175 (interactive)
23176 (cond
23177 ((org-at-table-p) (call-interactively 'org-table-insert-column))
23178 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
23179 ((org-at-item-p) (call-interactively 'org-indent-item))
23180 (t (org-shiftcursor-error))))
23182 (defun org-shiftmetaup (&optional arg)
23183 "Move subtree up or kill table row.
23184 Calls `org-move-subtree-up' or `org-table-kill-row' or
23185 `org-move-item-up' depending on context. See the individual commands
23186 for more information."
23187 (interactive "P")
23188 (cond
23189 ((org-at-table-p) (call-interactively 'org-table-kill-row))
23190 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
23191 ((org-at-item-p) (call-interactively 'org-move-item-up))
23192 (t (org-shiftcursor-error))))
23193 (defun org-shiftmetadown (&optional arg)
23194 "Move subtree down or insert table row.
23195 Calls `org-move-subtree-down' or `org-table-insert-row' or
23196 `org-move-item-down', depending on context. See the individual
23197 commands for more information."
23198 (interactive "P")
23199 (cond
23200 ((org-at-table-p) (call-interactively 'org-table-insert-row))
23201 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
23202 ((org-at-item-p) (call-interactively 'org-move-item-down))
23203 (t (org-shiftcursor-error))))
23205 (defun org-metaleft (&optional arg)
23206 "Promote heading or move table column to left.
23207 Calls `org-do-promote' or `org-table-move-column', depending on context.
23208 With no specific context, calls the Emacs default `backward-word'.
23209 See the individual commands for more information."
23210 (interactive "P")
23211 (cond
23212 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
23213 ((or (org-on-heading-p) (org-region-active-p))
23214 (call-interactively 'org-do-promote))
23215 ((org-at-item-p) (call-interactively 'org-outdent-item))
23216 (t (call-interactively 'backward-word))))
23218 (defun org-metaright (&optional arg)
23219 "Demote subtree or move table column to right.
23220 Calls `org-do-demote' or `org-table-move-column', depending on context.
23221 With no specific context, calls the Emacs default `forward-word'.
23222 See the individual commands for more information."
23223 (interactive "P")
23224 (cond
23225 ((org-at-table-p) (call-interactively 'org-table-move-column))
23226 ((or (org-on-heading-p) (org-region-active-p))
23227 (call-interactively 'org-do-demote))
23228 ((org-at-item-p) (call-interactively 'org-indent-item))
23229 (t (call-interactively 'forward-word))))
23231 (defun org-metaup (&optional arg)
23232 "Move subtree up or move table row up.
23233 Calls `org-move-subtree-up' or `org-table-move-row' or
23234 `org-move-item-up', depending on context. See the individual commands
23235 for more information."
23236 (interactive "P")
23237 (cond
23238 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
23239 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
23240 ((org-at-item-p) (call-interactively 'org-move-item-up))
23241 (t (org-shiftcursor-error))))
23243 (defun org-metadown (&optional arg)
23244 "Move subtree down or move table row down.
23245 Calls `org-move-subtree-down' or `org-table-move-row' or
23246 `org-move-item-down', depending on context. See the individual
23247 commands for more information."
23248 (interactive "P")
23249 (cond
23250 ((org-at-table-p) (call-interactively 'org-table-move-row))
23251 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
23252 ((org-at-item-p) (call-interactively 'org-move-item-down))
23253 (t (org-shiftcursor-error))))
23255 (defun org-shiftup (&optional arg)
23256 "Increase item in timestamp or increase priority of current headline.
23257 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
23258 depending on context. See the individual commands for more information."
23259 (interactive "P")
23260 (cond
23261 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
23262 ((org-on-heading-p) (call-interactively 'org-priority-up))
23263 ((org-at-item-p) (call-interactively 'org-previous-item))
23264 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
23266 (defun org-shiftdown (&optional arg)
23267 "Decrease item in timestamp or decrease priority of current headline.
23268 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
23269 depending on context. See the individual commands for more information."
23270 (interactive "P")
23271 (cond
23272 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
23273 ((org-on-heading-p) (call-interactively 'org-priority-down))
23274 (t (call-interactively 'org-next-item))))
23276 (defun org-shiftright ()
23277 "Next TODO keyword or timestamp one day later, depending on context."
23278 (interactive)
23279 (cond
23280 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
23281 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
23282 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
23283 (t (org-shiftcursor-error))))
23285 (defun org-shiftleft ()
23286 "Previous TODO keyword or timestamp one day earlier, depending on context."
23287 (interactive)
23288 (cond
23289 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
23290 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
23291 ((org-at-property-p)
23292 (call-interactively 'org-property-previous-allowed-value))
23293 (t (org-shiftcursor-error))))
23295 (defun org-shiftcontrolright ()
23296 "Switch to next TODO set."
23297 (interactive)
23298 (cond
23299 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
23300 (t (org-shiftcursor-error))))
23302 (defun org-shiftcontrolleft ()
23303 "Switch to previous TODO set."
23304 (interactive)
23305 (cond
23306 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
23307 (t (org-shiftcursor-error))))
23309 (defun org-ctrl-c-ret ()
23310 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
23311 (interactive)
23312 (cond
23313 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
23314 (t (call-interactively 'org-insert-heading))))
23316 (defun org-copy-special ()
23317 "Copy region in table or copy current subtree.
23318 Calls `org-table-copy' or `org-copy-subtree', depending on context.
23319 See the individual commands for more information."
23320 (interactive)
23321 (call-interactively
23322 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
23324 (defun org-cut-special ()
23325 "Cut region in table or cut current subtree.
23326 Calls `org-table-copy' or `org-cut-subtree', depending on context.
23327 See the individual commands for more information."
23328 (interactive)
23329 (call-interactively
23330 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
23332 (defun org-paste-special (arg)
23333 "Paste rectangular region into table, or past subtree relative to level.
23334 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
23335 See the individual commands for more information."
23336 (interactive "P")
23337 (if (org-at-table-p)
23338 (org-table-paste-rectangle)
23339 (org-paste-subtree arg)))
23341 (defun org-ctrl-c-ctrl-c (&optional arg)
23342 "Set tags in headline, or update according to changed information at point.
23344 This command does many different things, depending on context:
23346 - If the cursor is in a headline, prompt for tags and insert them
23347 into the current line, aligned to `org-tags-column'. When called
23348 with prefix arg, realign all tags in the current buffer.
23350 - If the cursor is in one of the special #+KEYWORD lines, this
23351 triggers scanning the buffer for these lines and updating the
23352 information.
23354 - If the cursor is inside a table, realign the table. This command
23355 works even if the automatic table editor has been turned off.
23357 - If the cursor is on a #+TBLFM line, re-apply the formulas to
23358 the entire table.
23360 - If the cursor is inside a table created by the table.el package,
23361 activate that table.
23363 - If the current buffer is a remember buffer, close note and file it.
23364 with a prefix argument, file it without further interaction to the default
23365 location.
23367 - If the cursor is on a <<<target>>>, update radio targets and corresponding
23368 links in this buffer.
23370 - If the cursor is on a numbered item in a plain list, renumber the
23371 ordered list."
23372 (interactive "P")
23373 (let ((org-enable-table-editor t))
23374 (cond
23375 ((or org-clock-overlays
23376 org-occur-highlights
23377 org-latex-fragment-image-overlays)
23378 (org-remove-clock-overlays)
23379 (org-remove-occur-highlights)
23380 (org-remove-latex-fragment-image-overlays)
23381 (message "Temporary highlights/overlays removed from current buffer"))
23382 ((and (local-variable-p 'org-finish-function (current-buffer))
23383 (fboundp org-finish-function))
23384 (funcall org-finish-function))
23385 ((org-at-property-p)
23386 (call-interactively 'org-property-action))
23387 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
23388 ((org-on-heading-p) (call-interactively 'org-set-tags))
23389 ((org-at-table.el-p)
23390 (require 'table)
23391 (beginning-of-line 1)
23392 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
23393 (call-interactively 'table-recognize-table))
23394 ((org-at-table-p)
23395 (org-table-maybe-eval-formula)
23396 (if arg
23397 (call-interactively 'org-table-recalculate)
23398 (org-table-maybe-recalculate-line))
23399 (call-interactively 'org-table-align))
23400 ((org-at-item-checkbox-p)
23401 (call-interactively 'org-toggle-checkbox))
23402 ((org-at-item-p)
23403 (call-interactively 'org-maybe-renumber-ordered-list))
23404 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
23405 (cond
23406 ((equal (match-string 1) "TBLFM")
23407 ;; Recalculate the table before this line
23408 (save-excursion
23409 (beginning-of-line 1)
23410 (skip-chars-backward " \r\n\t")
23411 (if (org-at-table-p)
23412 (org-call-with-arg 'org-table-recalculate t))))
23414 (call-interactively 'org-mode-restart))))
23415 (t (error "C-c C-c can do nothing useful at this location.")))))
23417 (defun org-mode-restart ()
23418 "Restart Org-mode, to scan again for special lines.
23419 Also updates the keyword regular expressions."
23420 (interactive)
23421 (let ((org-inhibit-startup t)) (org-mode))
23422 (message "Org-mode restarted to refresh keyword and special line setup"))
23424 (defun org-return ()
23425 "Goto next table row or insert a newline.
23426 Calls `org-table-next-row' or `newline', depending on context.
23427 See the individual commands for more information."
23428 (interactive)
23429 (cond
23430 ((bobp) (newline))
23431 ((org-at-table-p)
23432 (org-table-justify-field-maybe)
23433 (call-interactively 'org-table-next-row))
23434 (t (newline))))
23436 (defun org-ctrl-c-minus ()
23437 "Insert separator line in table or modify bullet type in list.
23438 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
23439 depending on context."
23440 (interactive)
23441 (cond
23442 ((org-at-table-p)
23443 (call-interactively 'org-table-insert-hline))
23444 ((org-in-item-p)
23445 (call-interactively 'org-cycle-list-bullet))
23446 (t (error "`C-c -' does have no function here."))))
23448 (defun org-meta-return (&optional arg)
23449 "Insert a new heading or wrap a region in a table.
23450 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
23451 See the individual commands for more information."
23452 (interactive "P")
23453 (cond
23454 ((org-at-table-p)
23455 (call-interactively 'org-table-wrap-region))
23456 (t (call-interactively 'org-insert-heading))))
23458 ;;; Menu entries
23460 ;; Define the Org-mode menus
23461 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
23462 '("Tbl"
23463 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
23464 ["Next Field" org-cycle (org-at-table-p)]
23465 ["Previous Field" org-shifttab (org-at-table-p)]
23466 ["Next Row" org-return (org-at-table-p)]
23467 "--"
23468 ["Blank Field" org-table-blank-field (org-at-table-p)]
23469 ["Edit Field" org-table-edit-field (org-at-table-p)]
23470 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
23471 "--"
23472 ("Column"
23473 ["Move Column Left" org-metaleft (org-at-table-p)]
23474 ["Move Column Right" org-metaright (org-at-table-p)]
23475 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
23476 ["Insert Column" org-shiftmetaright (org-at-table-p)])
23477 ("Row"
23478 ["Move Row Up" org-metaup (org-at-table-p)]
23479 ["Move Row Down" org-metadown (org-at-table-p)]
23480 ["Delete Row" org-shiftmetaup (org-at-table-p)]
23481 ["Insert Row" org-shiftmetadown (org-at-table-p)]
23482 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
23483 "--"
23484 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
23485 ("Rectangle"
23486 ["Copy Rectangle" org-copy-special (org-at-table-p)]
23487 ["Cut Rectangle" org-cut-special (org-at-table-p)]
23488 ["Paste Rectangle" org-paste-special (org-at-table-p)]
23489 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
23490 "--"
23491 ("Calculate"
23492 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
23493 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
23494 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
23495 "--"
23496 ["Recalculate line" org-table-recalculate (org-at-table-p)]
23497 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
23498 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
23499 "--"
23500 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
23501 "--"
23502 ["Sum Column/Rectangle" org-table-sum
23503 (or (org-at-table-p) (org-region-active-p))]
23504 ["Which Column?" org-table-current-column (org-at-table-p)])
23505 ["Debug Formulas"
23506 org-table-toggle-formula-debugger
23507 :style toggle :selected org-table-formula-debug]
23508 ["Show Col/Row Numbers"
23509 org-table-toggle-coordinate-overlays
23510 :style toggle :selected org-table-overlay-coordinates]
23511 "--"
23512 ["Create" org-table-create (and (not (org-at-table-p))
23513 org-enable-table-editor)]
23514 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
23515 ["Import from File" org-table-import (not (org-at-table-p))]
23516 ["Export to File" org-table-export (org-at-table-p)]
23517 "--"
23518 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
23520 (easy-menu-define org-org-menu org-mode-map "Org menu"
23521 '("Org"
23522 ("Show/Hide"
23523 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
23524 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
23525 ["Sparse Tree" org-occur t]
23526 ["Reveal Context" org-reveal t]
23527 ["Show All" show-all t]
23528 "--"
23529 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
23530 "--"
23531 ["New Heading" org-insert-heading t]
23532 ("Navigate Headings"
23533 ["Up" outline-up-heading t]
23534 ["Next" outline-next-visible-heading t]
23535 ["Previous" outline-previous-visible-heading t]
23536 ["Next Same Level" outline-forward-same-level t]
23537 ["Previous Same Level" outline-backward-same-level t]
23538 "--"
23539 ["Jump" org-goto t])
23540 ("Edit Structure"
23541 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
23542 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
23543 "--"
23544 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
23545 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
23546 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
23547 "--"
23548 ["Promote Heading" org-metaleft (not (org-at-table-p))]
23549 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
23550 ["Demote Heading" org-metaright (not (org-at-table-p))]
23551 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
23552 "--"
23553 ["Sort Region/Children" org-sort (not (org-at-table-p))]
23554 "--"
23555 ["Convert to odd levels" org-convert-to-odd-levels t]
23556 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
23557 ("Editing"
23558 ["Emphasis..." org-emphasize t])
23559 ("Archive"
23560 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
23561 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
23562 ; :active t :keys "C-u C-c C-x C-a"]
23563 ["Sparse trees open ARCHIVE trees"
23564 (setq org-sparse-tree-open-archived-trees
23565 (not org-sparse-tree-open-archived-trees))
23566 :style toggle :selected org-sparse-tree-open-archived-trees]
23567 ["Cycling opens ARCHIVE trees"
23568 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
23569 :style toggle :selected org-cycle-open-archived-trees]
23570 ["Agenda includes ARCHIVE trees"
23571 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
23572 :style toggle :selected (not org-agenda-skip-archived-trees)]
23573 "--"
23574 ["Move Subtree to Archive" org-advertized-archive-subtree t]
23575 ; ["Check and Move Children" (org-archive-subtree '(4))
23576 ; :active t :keys "C-u C-c C-x C-s"]
23578 "--"
23579 ("TODO Lists"
23580 ["TODO/DONE/-" org-todo t]
23581 ("Select keyword"
23582 ["Next keyword" org-shiftright (org-on-heading-p)]
23583 ["Previous keyword" org-shiftleft (org-on-heading-p)]
23584 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
23585 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
23586 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
23587 ["Show TODO Tree" org-show-todo-tree t]
23588 ["Global TODO list" org-todo-list t]
23589 "--"
23590 ["Set Priority" org-priority t]
23591 ["Priority Up" org-shiftup t]
23592 ["Priority Down" org-shiftdown t])
23593 ("TAGS and Properties"
23594 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
23595 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)] ;FIXME
23596 ["Column view of properties" org-columns t])
23597 ("Dates and Scheduling"
23598 ["Timestamp" org-time-stamp t]
23599 ["Timestamp (inactive)" org-time-stamp-inactive t]
23600 ("Change Date"
23601 ["1 Day Later" org-shiftright t]
23602 ["1 Day Earlier" org-shiftleft t]
23603 ["1 ... Later" org-shiftup t]
23604 ["1 ... Earlier" org-shiftdown t])
23605 ["Compute Time Range" org-evaluate-time-range t]
23606 ["Schedule Item" org-schedule t]
23607 ["Deadline" org-deadline t]
23608 "--"
23609 ["Custom time format" org-toggle-time-stamp-overlays
23610 :style radio :selected org-display-custom-times]
23611 "--"
23612 ["Goto Calendar" org-goto-calendar t]
23613 ["Date from Calendar" org-date-from-calendar t])
23614 ("Logging work"
23615 ["Clock in" org-clock-in t]
23616 ["Clock out" org-clock-out t]
23617 ["Clock cancel" org-clock-cancel t]
23618 ["Display times" org-clock-display t]
23619 ["Create clock table" org-clock-report t]
23620 "--"
23621 ["Record DONE time"
23622 (progn (setq org-log-done (not org-log-done))
23623 (message "Switching to %s will %s record a timestamp"
23624 (car org-done-keywords)
23625 (if org-log-done "automatically" "not")))
23626 :style toggle :selected org-log-done])
23627 "--"
23628 ["Agenda Command..." org-agenda t]
23629 ("File List for Agenda")
23630 ("Special views current file"
23631 ["TODO Tree" org-show-todo-tree t]
23632 ["Check Deadlines" org-check-deadlines t]
23633 ["Timeline" org-timeline t]
23634 ["Tags Tree" org-tags-sparse-tree t])
23635 "--"
23636 ("Hyperlinks"
23637 ["Store Link (Global)" org-store-link t]
23638 ["Insert Link" org-insert-link t]
23639 ["Follow Link" org-open-at-point t]
23640 "--"
23641 ["Next link" org-next-link t]
23642 ["Previous link" org-previous-link t]
23643 "--"
23644 ["Descriptive Links"
23645 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
23646 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
23647 ["Literal Links"
23648 (progn
23649 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
23650 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
23651 "--"
23652 ["Export/Publish..." org-export t]
23653 ("LaTeX"
23654 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
23655 :selected org-cdlatex-mode]
23656 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
23657 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
23658 ["Modify math symbol" org-cdlatex-math-modify
23659 (org-inside-LaTeX-fragment-p)]
23660 ["Export LaTeX fragments as images"
23661 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
23662 :style toggle :selected org-export-with-LaTeX-fragments])
23663 "--"
23664 ("Documentation"
23665 ["Show Version" org-version t]
23666 ["Info Documentation" org-info t])
23667 ("Customize"
23668 ["Browse Org Group" org-customize t]
23669 "--"
23670 ["Expand This Menu" org-create-customize-menu
23671 (fboundp 'customize-menu-create)])
23672 "--"
23673 ["Refresh setup" org-mode-restart t]
23676 (defun org-info (&optional node)
23677 "Read documentation for Org-mode in the info system.
23678 With optional NODE, go directly to that node."
23679 (interactive)
23680 (require 'info)
23681 (Info-goto-node (format "(org)%s" (or node ""))))
23683 (defun org-install-agenda-files-menu ()
23684 (let ((bl (buffer-list)))
23685 (save-excursion
23686 (while bl
23687 (set-buffer (pop bl))
23688 (if (org-mode-p) (setq bl nil)))
23689 (when (org-mode-p)
23690 (easy-menu-change
23691 '("Org") "File List for Agenda"
23692 (append
23693 (list
23694 ["Edit File List" (org-edit-agenda-file-list) t]
23695 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
23696 ["Remove Current File from List" org-remove-file t]
23697 ["Cycle through agenda files" org-cycle-agenda-files t]
23698 "--")
23699 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
23701 ;;;; Documentation
23703 (defun org-customize ()
23704 "Call the customize function with org as argument."
23705 (interactive)
23706 (customize-browse 'org))
23708 (defun org-create-customize-menu ()
23709 "Create a full customization menu for Org-mode, insert it into the menu."
23710 (interactive)
23711 (if (fboundp 'customize-menu-create)
23712 (progn
23713 (easy-menu-change
23714 '("Org") "Customize"
23715 `(["Browse Org group" org-customize t]
23716 "--"
23717 ,(customize-menu-create 'org)
23718 ["Set" Custom-set t]
23719 ["Save" Custom-save t]
23720 ["Reset to Current" Custom-reset-current t]
23721 ["Reset to Saved" Custom-reset-saved t]
23722 ["Reset to Standard Settings" Custom-reset-standard t]))
23723 (message "\"Org\"-menu now contains full customization menu"))
23724 (error "Cannot expand menu (outdated version of cus-edit.el)")))
23726 ;;;; Miscellaneous stuff
23729 ;;; Generally useful functions
23731 (defun org-context ()
23732 "Return a list of contexts of the current cursor position.
23733 If several contexts apply, all are returned.
23734 Each context entry is a list with a symbol naming the context, and
23735 two positions indicating start and end of the context. Possible
23736 contexts are:
23738 :headline anywhere in a headline
23739 :headline-stars on the leading stars in a headline
23740 :todo-keyword on a TODO keyword (including DONE) in a headline
23741 :tags on the TAGS in a headline
23742 :priority on the priority cookie in a headline
23743 :item on the first line of a plain list item
23744 :item-bullet on the bullet/number of a plain list item
23745 :checkbox on the checkbox in a plain list item
23746 :table in an org-mode table
23747 :table-special on a special filed in a table
23748 :table-table in a table.el table
23749 :link on a hyperlink
23750 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
23751 :target on a <<target>>
23752 :radio-target on a <<<radio-target>>>
23753 :latex-fragment on a LaTeX fragment
23754 :latex-preview on a LaTeX fragment with overlayed preview image
23756 This function expects the position to be visible because it uses font-lock
23757 faces as a help to recognize the following contexts: :table-special, :link,
23758 and :keyword."
23759 (let* ((f (get-text-property (point) 'face))
23760 (faces (if (listp f) f (list f)))
23761 (p (point)) clist o)
23762 ;; First the large context
23763 (cond
23764 ((org-on-heading-p t)
23765 (push (list :headline (point-at-bol) (point-at-eol)) clist)
23766 (when (progn
23767 (beginning-of-line 1)
23768 (looking-at org-todo-line-tags-regexp))
23769 (push (org-point-in-group p 1 :headline-stars) clist)
23770 (push (org-point-in-group p 2 :todo-keyword) clist)
23771 (push (org-point-in-group p 4 :tags) clist))
23772 (goto-char p)
23773 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
23774 (if (looking-at "\\[#[A-Z0-9]\\]")
23775 (push (org-point-in-group p 0 :priority) clist)))
23777 ((org-at-item-p)
23778 (push (org-point-in-group p 2 :item-bullet) clist)
23779 (push (list :item (point-at-bol)
23780 (save-excursion (org-end-of-item) (point)))
23781 clist)
23782 (and (org-at-item-checkbox-p)
23783 (push (org-point-in-group p 0 :checkbox) clist)))
23785 ((org-at-table-p)
23786 (push (list :table (org-table-begin) (org-table-end)) clist)
23787 (if (memq 'org-formula faces)
23788 (push (list :table-special
23789 (previous-single-property-change p 'face)
23790 (next-single-property-change p 'face)) clist)))
23791 ((org-at-table-p 'any)
23792 (push (list :table-table) clist)))
23793 (goto-char p)
23795 ;; Now the small context
23796 (cond
23797 ((org-at-timestamp-p)
23798 (push (org-point-in-group p 0 :timestamp) clist))
23799 ((memq 'org-link faces)
23800 (push (list :link
23801 (previous-single-property-change p 'face)
23802 (next-single-property-change p 'face)) clist))
23803 ((memq 'org-special-keyword faces)
23804 (push (list :keyword
23805 (previous-single-property-change p 'face)
23806 (next-single-property-change p 'face)) clist))
23807 ((org-on-target-p)
23808 (push (org-point-in-group p 0 :target) clist)
23809 (goto-char (1- (match-beginning 0)))
23810 (if (looking-at org-radio-target-regexp)
23811 (push (org-point-in-group p 0 :radio-target) clist))
23812 (goto-char p))
23813 ((setq o (car (delq nil
23814 (mapcar
23815 (lambda (x)
23816 (if (memq x org-latex-fragment-image-overlays) x))
23817 (org-overlays-at (point))))))
23818 (push (list :latex-fragment
23819 (org-overlay-start o) (org-overlay-end o)) clist)
23820 (push (list :latex-preview
23821 (org-overlay-start o) (org-overlay-end o)) clist))
23822 ((org-inside-LaTeX-fragment-p)
23823 ;; FIXME: positions wrong.
23824 (push (list :latex-fragment (point) (point)) clist)))
23826 (setq clist (nreverse (delq nil clist)))
23827 clist))
23829 ;; FIXME Compare with at-regexp-p
23830 (defun org-in-regexp (re &optional nlines visually)
23831 "Check if point is inside a match of regexp.
23832 Normally only the current line is checked, but you can include NLINES extra
23833 lines both before and after point into the search.
23834 If VISUALLY is set, require that the cursor is not after the match but
23835 really on, so that the block visually is on the match."
23836 (catch 'exit
23837 (let ((pos (point))
23838 (eol (point-at-eol (+ 1 (or nlines 0))))
23839 (inc (if visually 1 0)))
23840 (save-excursion
23841 (beginning-of-line (- 1 (or nlines 0)))
23842 (while (re-search-forward re eol t)
23843 (if (and (<= (match-beginning 0) pos)
23844 (>= (+ inc (match-end 0)) pos))
23845 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
23847 (defun org-at-regexp-p (regexp)
23848 "Is point inside a match of REGEXP in the current line?"
23849 (catch 'exit
23850 (save-excursion
23851 (let ((pos (point)) (end (point-at-eol)))
23852 (beginning-of-line 1)
23853 (while (re-search-forward regexp end t)
23854 (if (and (<= (match-beginning 0) pos)
23855 (>= (match-end 0) pos))
23856 (throw 'exit t)))
23857 nil))))
23859 (defun org-uniquify (list)
23860 "Remove duplicate elements from LIST."
23861 (let (res)
23862 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
23863 res))
23865 (defun org-delete-all (elts list)
23866 "Remove all elements in ELTS from LIST."
23867 (while elts
23868 (setq list (delete (pop elts) list)))
23869 list)
23871 (defun org-point-in-group (point group &optional context)
23872 "Check if POINT is in match-group GROUP.
23873 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
23874 match. If the match group does ot exist or point is not inside it,
23875 return nil."
23876 (and (match-beginning group)
23877 (>= point (match-beginning group))
23878 (<= point (match-end group))
23879 (if context
23880 (list context (match-beginning group) (match-end group))
23881 t)))
23883 (defun org-combine-plists (&rest plists)
23884 "Create a single property list from all plists in PLISTS.
23885 The process starts by copying the first list, and then setting properties
23886 from the other lists. Settings in the last list are the most significant
23887 ones and overrule settings in the other lists."
23888 (let ((rtn (copy-sequence (pop plists)))
23889 p v ls)
23890 (while plists
23891 (setq ls (pop plists))
23892 (while ls
23893 (setq p (pop ls) v (pop ls))
23894 (setq rtn (plist-put rtn p v))))
23895 rtn))
23897 (defun org-move-line-down (arg)
23898 "Move the current line down. With prefix argument, move it past ARG lines."
23899 (interactive "p")
23900 (let ((col (current-column))
23901 beg end pos)
23902 (beginning-of-line 1) (setq beg (point))
23903 (beginning-of-line 2) (setq end (point))
23904 (beginning-of-line (+ 1 arg))
23905 (setq pos (move-marker (make-marker) (point)))
23906 (insert (delete-and-extract-region beg end))
23907 (goto-char pos)
23908 (move-to-column col)))
23910 (defun org-move-line-up (arg)
23911 "Move the current line up. With prefix argument, move it past ARG lines."
23912 (interactive "p")
23913 (let ((col (current-column))
23914 beg end pos)
23915 (beginning-of-line 1) (setq beg (point))
23916 (beginning-of-line 2) (setq end (point))
23917 (beginning-of-line (- arg))
23918 (setq pos (move-marker (make-marker) (point)))
23919 (insert (delete-and-extract-region beg end))
23920 (goto-char pos)
23921 (move-to-column col)))
23923 (defun org-replace-escapes (string table)
23924 "Replace %-escapes in STRING with values in TABLE.
23925 TABLE is an association list with keys line \"%a\" and string values.
23926 The sequences in STRING may contain normal field width and padding information,
23927 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
23928 so values can contain further %-escapes if they are define later in TABLE."
23929 (let ((case-fold-search nil)
23930 e re rpl)
23931 (while (setq e (pop table))
23932 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
23933 (while (string-match re string)
23934 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
23935 (cdr e)))
23936 (setq string (replace-match rpl t t string))))
23937 string))
23940 (defun org-sublist (list start end)
23941 "Return a section of LIST, from START to END.
23942 Counting starts at 1."
23943 (let (rtn (c start))
23944 (setq list (nthcdr (1- start) list))
23945 (while (and list (<= c end))
23946 (push (pop list) rtn)
23947 (setq c (1+ c)))
23948 (nreverse rtn)))
23950 (defun org-find-base-buffer-visiting (file)
23951 "Like `find-buffer-visiting' but alway return the base buffer and
23952 not an indirect buffer"
23953 (let ((buf (find-buffer-visiting file)))
23954 (or (buffer-base-buffer buf) buf)))
23956 (defun org-image-file-name-regexp ()
23957 "Return regexp matching the file names of images."
23958 (if (fboundp 'image-file-name-regexp)
23959 (image-file-name-regexp)
23960 (let ((image-file-name-extensions
23961 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
23962 "xbm" "xpm" "pbm" "pgm" "ppm")))
23963 (concat "\\."
23964 (regexp-opt (nconc (mapcar 'upcase
23965 image-file-name-extensions)
23966 image-file-name-extensions)
23968 "\\'"))))
23970 (defun org-file-image-p (file)
23971 "Return non-nil if FILE is an image."
23972 (save-match-data
23973 (string-match (org-image-file-name-regexp) file)))
23975 ;;; Paragraph filling stuff.
23976 ;; We want this to be just right, so use the full arsenal.
23978 (defun org-indent-line-function ()
23979 "Indent line like previous, but further if previous was headline or item."
23980 (interactive)
23981 (let* ((pos (point))
23982 (itemp (org-at-item-p))
23983 column bpos bcol tpos tcol bullet btype bullet-type)
23984 ;; Find the previous relevant line
23985 (beginning-of-line 1)
23986 (cond
23987 ((looking-at "#") (setq column 0))
23988 ((looking-at "\\*+ ") (setq column 0))
23990 (beginning-of-line 0)
23991 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
23992 (beginning-of-line 0))
23993 (cond
23994 ((looking-at "\\*+[ \t]+")
23995 (goto-char (match-end 0))
23996 (setq column (current-column)))
23997 ((org-in-item-p)
23998 (org-beginning-of-item)
23999 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
24000 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
24001 (setq bpos (match-beginning 1) tpos (match-end 0)
24002 bcol (progn (goto-char bpos) (current-column))
24003 tcol (progn (goto-char tpos) (current-column))
24004 bullet (match-string 1)
24005 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
24006 (if (not itemp)
24007 (setq column tcol)
24008 (goto-char pos)
24009 (beginning-of-line 1)
24010 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
24011 (setq bullet (match-string 1)
24012 btype (if (string-match "[0-9]" bullet) "n" bullet))
24013 (setq column (if (equal btype bullet-type) bcol tcol))))
24014 (t (setq column (org-get-indentation))))))
24015 (goto-char pos)
24016 (if (<= (current-column) (current-indentation))
24017 (indent-line-to column)
24018 (save-excursion (indent-line-to column)))
24019 (setq column (current-column))
24020 (beginning-of-line 1)
24021 (if (looking-at
24022 "\\([ \t]+\\)\\(:[0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
24023 (replace-match (concat "\\1" (format org-property-format
24024 (match-string 2) (match-string 3)))
24025 t nil))
24026 (move-to-column column)))
24028 (defun org-set-autofill-regexps ()
24029 (interactive)
24030 ;; In the paragraph separator we include headlines, because filling
24031 ;; text in a line directly attached to a headline would otherwise
24032 ;; fill the headline as well.
24033 (org-set-local 'comment-start-skip "^#+[ \t]*")
24034 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
24035 ;; FIXME!!!!!!! (org-set-local 'paragraph-separate "\f\\|[ ]*$")
24036 ;; The paragraph starter includes hand-formatted lists.
24037 (org-set-local 'paragraph-start
24038 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
24039 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
24040 ;; But only if the user has not turned off tables or fixed-width regions
24041 (org-set-local
24042 'auto-fill-inhibit-regexp
24043 (concat "\\*+ \\|#\\+"
24044 "\\|[ \t]*" org-keyword-time-regexp
24045 (if (or org-enable-table-editor org-enable-fixed-width-editor)
24046 (concat
24047 "\\|[ \t]*["
24048 (if org-enable-table-editor "|" "")
24049 (if org-enable-fixed-width-editor ":" "")
24050 "]"))))
24051 ;; We use our own fill-paragraph function, to make sure that tables
24052 ;; and fixed-width regions are not wrapped. That function will pass
24053 ;; through to `fill-paragraph' when appropriate.
24054 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
24055 ; Adaptive filling: To get full control, first make sure that
24056 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
24057 (org-set-local 'adaptive-fill-regexp "\000")
24058 (org-set-local 'adaptive-fill-function
24059 'org-adaptive-fill-function))
24061 (defun org-fill-paragraph (&optional justify)
24062 "Re-align a table, pass through to fill-paragraph if no table."
24063 (let ((table-p (org-at-table-p))
24064 (table.el-p (org-at-table.el-p)))
24065 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
24066 (table.el-p t) ; skip table.el tables
24067 (table-p (org-table-align) t) ; align org-mode tables
24068 (t nil)))) ; call paragraph-fill
24070 ;; For reference, this is the default value of adaptive-fill-regexp
24071 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
24073 (defun org-adaptive-fill-function ()
24074 "Return a fill prefix for org-mode files.
24075 In particular, this makes sure hanging paragraphs for hand-formatted lists
24076 work correctly."
24077 (cond ((looking-at "#[ \t]+")
24078 (match-string 0))
24079 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
24080 (save-excursion
24081 (goto-char (match-end 0))
24082 (make-string (current-column) ?\ )))
24083 (t nil)))
24085 ;;;; Functions extending outline functionality
24087 (defun org-beginning-of-line (&optional arg)
24088 "Go to the beginning of the current line. If that is invisible, continue
24089 to a visible line beginning. This makes the function of C-a more intuitive.
24090 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
24091 first attempt, and only move to after the tags when the cursor is already
24092 beyond the end of the headline."
24093 (interactive "P")
24094 (let ((pos (point)))
24095 (beginning-of-line 1)
24096 (if (bobp)
24098 (backward-char 1)
24099 (if (org-invisible-p)
24100 (while (and (not (bobp)) (org-invisible-p))
24101 (backward-char 1)
24102 (beginning-of-line 1))
24103 (forward-char 1)))
24104 (when org-special-ctrl-a/e
24105 (cond
24106 ((and (looking-at org-todo-line-regexp)
24107 (= (char-after (match-end 1)) ?\ ))
24108 (goto-char
24109 (if (eq org-special-ctrl-a/e t)
24110 (cond ((> pos (match-beginning 3)) (match-beginning 3))
24111 ((= pos (point)) (match-beginning 3))
24112 (t (point)))
24113 (cond ((> pos (point)) (point))
24114 ((not (eq last-command this-command)) (point))
24115 (t (match-beginning 3))))))
24116 ((org-at-item-p)
24117 (goto-char
24118 (if (eq org-special-ctrl-a/e t)
24119 (cond ((> pos (match-end 4)) (match-end 4))
24120 ((= pos (point)) (match-end 4))
24121 (t (point)))
24122 (cond ((> pos (point)) (point))
24123 ((not (eq last-command this-command)) (point))
24124 (t (match-end 4))))))))))
24126 (defun org-end-of-line (&optional arg)
24127 "Go to the end of the line.
24128 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
24129 first attempt, and only move to after the tags when the cursor is already
24130 beyond the end of the headline."
24131 (interactive "P")
24132 (if (or (not org-special-ctrl-a/e)
24133 (not (org-on-heading-p)))
24134 (end-of-line arg)
24135 (let ((pos (point)))
24136 (beginning-of-line 1)
24137 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
24138 (if (eq org-special-ctrl-a/e t)
24139 (if (or (< pos (match-beginning 1))
24140 (= pos (match-end 0)))
24141 (goto-char (match-beginning 1))
24142 (goto-char (match-end 0)))
24143 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
24144 (goto-char (match-end 0))
24145 (goto-char (match-beginning 1))))
24146 (end-of-line arg)))))
24148 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
24149 (define-key org-mode-map "\C-e" 'org-end-of-line)
24151 (defun org-invisible-p ()
24152 "Check if point is at a character currently not visible."
24153 ;; Early versions of noutline don't have `outline-invisible-p'.
24154 (if (fboundp 'outline-invisible-p)
24155 (outline-invisible-p)
24156 (get-char-property (point) 'invisible)))
24158 (defun org-invisible-p2 ()
24159 "Check if point is at a character currently not visible."
24160 (save-excursion
24161 (if (and (eolp) (not (bobp))) (backward-char 1))
24162 ;; Early versions of noutline don't have `outline-invisible-p'.
24163 (if (fboundp 'outline-invisible-p)
24164 (outline-invisible-p)
24165 (get-char-property (point) 'invisible))))
24167 (defalias 'org-back-to-heading 'outline-back-to-heading)
24168 (defalias 'org-on-heading-p 'outline-on-heading-p)
24169 (defalias 'org-at-heading-p 'outline-on-heading-p)
24170 (defun org-at-heading-or-item-p ()
24171 (or (org-on-heading-p) (org-at-item-p)))
24173 (defun org-on-target-p ()
24174 (or (org-in-regexp org-radio-target-regexp)
24175 (org-in-regexp org-target-regexp)))
24177 (defun org-up-heading-all (arg)
24178 "Move to the heading line of which the present line is a subheading.
24179 This function considers both visible and invisible heading lines.
24180 With argument, move up ARG levels."
24181 (if (fboundp 'outline-up-heading-all)
24182 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24183 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24185 (defun org-goto-sibling (&optional previous)
24186 "Goto the next sibling, even if it is invisible.
24187 When PREVIOUS is set, go to the previous sibling instead. Returns t
24188 when a sibling was found. When none is found, return nil and don't
24189 move point."
24190 (let ((fun (if previous 're-search-backward 're-search-forward))
24191 (pos (point))
24192 (re (concat "^" outline-regexp))
24193 level l)
24194 (when (condition-case nil (org-back-to-heading t) (error nil))
24195 (setq level (funcall outline-level))
24196 (catch 'exit
24197 (or previous (forward-char 1))
24198 (while (funcall fun re nil t)
24199 (setq l (funcall outline-level))
24200 (when (< l level) (goto-char pos) (throw 'exit nil))
24201 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24202 (goto-char pos)
24203 nil))))
24205 (defun org-show-siblings ()
24206 "Show all siblings of the current headline."
24207 (save-excursion
24208 (while (org-goto-sibling) (org-flag-heading nil)))
24209 (save-excursion
24210 (while (org-goto-sibling 'previous)
24211 (org-flag-heading nil))))
24213 (defun org-show-hidden-entry ()
24214 "Show an entry where even the heading is hidden."
24215 (save-excursion
24216 (org-show-entry)))
24218 (defun org-flag-heading (flag &optional entry)
24219 "Flag the current heading. FLAG non-nil means make invisible.
24220 When ENTRY is non-nil, show the entire entry."
24221 (save-excursion
24222 (org-back-to-heading t)
24223 ;; Check if we should show the entire entry
24224 (if entry
24225 (progn
24226 (org-show-entry)
24227 (save-excursion
24228 (and (outline-next-heading)
24229 (org-flag-heading nil))))
24230 (outline-flag-region (max (point-min) (1- (point)))
24231 (save-excursion (outline-end-of-heading) (point))
24232 flag))))
24234 (defun org-end-of-subtree (&optional invisible-OK to-heading)
24235 ;; This is an exact copy of the original function, but it uses
24236 ;; `org-back-to-heading', to make it work also in invisible
24237 ;; trees. And is uses an invisible-OK argument.
24238 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24239 (org-back-to-heading invisible-OK)
24240 (let ((first t)
24241 (level (funcall outline-level)))
24242 (while (and (not (eobp))
24243 (or first (> (funcall outline-level) level)))
24244 (setq first nil)
24245 (outline-next-heading))
24246 (unless to-heading
24247 (if (memq (preceding-char) '(?\n ?\^M))
24248 (progn
24249 ;; Go to end of line before heading
24250 (forward-char -1)
24251 (if (memq (preceding-char) '(?\n ?\^M))
24252 ;; leave blank line before heading
24253 (forward-char -1))))))
24254 (point))
24256 (defun org-show-subtree ()
24257 "Show everything after this heading at deeper levels."
24258 (outline-flag-region
24259 (point)
24260 (save-excursion
24261 (outline-end-of-subtree) (outline-next-heading) (point))
24262 nil))
24264 (defun org-show-entry ()
24265 "Show the body directly following this heading.
24266 Show the heading too, if it is currently invisible."
24267 (interactive)
24268 (save-excursion
24269 (org-back-to-heading t)
24270 (outline-flag-region
24271 (max (point-min) (1- (point)))
24272 (save-excursion
24273 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
24274 (or (match-beginning 1) (point-max)))
24275 nil)))
24277 (defun org-make-options-regexp (kwds)
24278 "Make a regular expression for keyword lines."
24279 (concat
24281 "#?[ \t]*\\+\\("
24282 (mapconcat 'regexp-quote kwds "\\|")
24283 "\\):[ \t]*"
24284 "\\(.+\\)"))
24286 ;; Make isearch reveal the necessary context
24287 (defun org-isearch-end ()
24288 "Reveal context after isearch exits."
24289 (when isearch-success ; only if search was successful
24290 (if (featurep 'xemacs)
24291 ;; Under XEmacs, the hook is run in the correct place,
24292 ;; we directly show the context.
24293 (org-show-context 'isearch)
24294 ;; In Emacs the hook runs *before* restoring the overlays.
24295 ;; So we have to use a one-time post-command-hook to do this.
24296 ;; (Emacs 22 has a special variable, see function `org-mode')
24297 (unless (and (boundp 'isearch-mode-end-hook-quit)
24298 isearch-mode-end-hook-quit)
24299 ;; Only when the isearch was not quitted.
24300 (org-add-hook 'post-command-hook 'org-isearch-post-command
24301 'append 'local)))))
24303 (defun org-isearch-post-command ()
24304 "Remove self from hook, and show context."
24305 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24306 (org-show-context 'isearch))
24309 ;;;; Address problems with some other packages
24311 ;; Make flyspell not check words in links, to not mess up our keymap
24312 (defun org-mode-flyspell-verify ()
24313 "Don't let flyspell put overlays at active buttons."
24314 (not (get-text-property (point) 'keymap)))
24316 ;; Make `bookmark-jump' show the jump location if it was hidden.
24317 (eval-after-load "bookmark"
24318 '(if (boundp 'bookmark-after-jump-hook)
24319 ;; We can use the hook
24320 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24321 ;; Hook not available, use advice
24322 (defadvice bookmark-jump (after org-make-visible activate)
24323 "Make the position visible."
24324 (org-bookmark-jump-unhide))))
24326 (defun org-bookmark-jump-unhide ()
24327 "Unhide the current position, to show the bookmark location."
24328 (and (org-mode-p)
24329 (or (org-invisible-p)
24330 (save-excursion (goto-char (max (point-min) (1- (point))))
24331 (org-invisible-p)))
24332 (org-show-context 'bookmark-jump)))
24334 ;; Make session.el ignore our circular variable
24335 (eval-after-load "session"
24336 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24338 ;;;; Experimental code
24340 ;; Make appt aware of appointments from the agenda
24341 (defun org-agenda-to-appt ()
24342 "Activate appointments found in `org-agenda-files'."
24343 (interactive)
24344 (require 'org)
24345 (let* ((today (org-date-to-gregorian
24346 (time-to-days (current-time))))
24347 (files org-agenda-files) entries file)
24348 (while (setq file (pop files))
24349 (setq entries (append entries (org-agenda-get-day-entries
24350 file today :timestamp))))
24351 (setq entries (delq nil entries))
24352 (mapc (lambda(x)
24353 (let* ((event (org-trim (get-text-property 1 'txt x)))
24354 (time-of-day (get-text-property 1 'time-of-day x)) tod)
24355 (when time-of-day
24356 (setq tod (number-to-string time-of-day)
24357 tod (when (string-match
24358 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
24359 (concat (match-string 1 tod) ":"
24360 (match-string 2 tod))))
24361 (if tod (appt-add tod event))))) entries)))
24363 (defun org-closed-in-range ()
24364 "Sparse tree of items closed in a certain time range.
24365 Still experimental, may disappear in the furture."
24366 (interactive)
24367 ;; Get the time interval from the user.
24368 (let* ((time1 (time-to-seconds
24369 (org-read-date nil 'to-time nil "Starting date: ")))
24370 (time2 (time-to-seconds
24371 (org-read-date nil 'to-time nil "End date:")))
24372 ;; callback function
24373 (callback (lambda ()
24374 (let ((time
24375 (time-to-seconds
24376 (apply 'encode-time
24377 (org-parse-time-string
24378 (match-string 1))))))
24379 ;; check if time in interval
24380 (and (>= time time1) (<= time time2))))))
24381 ;; make tree, check each match with the callback
24382 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
24384 (defun org-fill-paragraph-experimental (&optional justify)
24385 "Re-align a table, pass through to fill-paragraph if no table."
24386 (let ((table-p (org-at-table-p))
24387 (table.el-p (org-at-table.el-p)))
24388 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
24389 (table.el-p t) ; skip table.el tables
24390 (table-p (org-table-align) t) ; align org-mode tables
24391 ((save-excursion
24392 (let ((pos (1+ (point-at-eol))))
24393 (backward-paragraph 1)
24394 (re-search-forward "\\\\\\\\[ \t]*$" pos t)))
24395 (save-excursion
24396 (save-restriction
24397 (narrow-to-region (1+ (match-end 0)) (point-max))
24398 (fill-paragraph nil)
24399 t)))
24400 (t nil)))) ; call paragraph-fill
24402 (defun org-get-min-level (lines)
24403 (let ((re "^\\(\\*+\\) ") l min)
24404 (catch 'exit
24405 (while (setq l (pop lines))
24406 (if (string-match re l)
24407 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24408 1)))
24410 ;;;; Finish up
24412 (provide 'org)
24414 (run-hooks 'org-load-hook)
24416 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
24417 ;;; org.el ends here