Release 5.12
[org-mode.git] / org.el
blob2376044aaad412e2e739bbd4e765437a7d52c51a
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 5.12
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 ;;;; Require other packages
69 (eval-when-compile
70 (require 'cl)
71 (require 'gnus-sum)
72 (require 'calendar))
73 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
74 ;; the file noutline.el being loaded.
75 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
76 ;; We require noutline, which might be provided in outline.el
77 (require 'outline) (require 'noutline)
78 ;; Other stuff we need.
79 (require 'time-date)
80 (require 'easymenu)
82 ;;;; Customization variables
84 ;;; Version
86 (defconst org-version "5.12"
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 (while (string-match "\\[:alpha:\\]" ss)
113 (setq ss (replace-match "a-zA-Z" t t ss)))
114 ss))
117 (defmacro org-preserve-lc (&rest body)
118 `(let ((_line (org-current-line))
119 (_col (current-column)))
120 (unwind-protect
121 (progn ,@body)
122 (goto-line _line)
123 (move-to-column _col))))
125 (defmacro org-without-partial-completion (&rest body)
126 `(let ((pc-mode (and (boundp 'partial-completion-mode)
127 partial-completion-mode)))
128 (unwind-protect
129 (progn
130 (if pc-mode (partial-completion-mode -1))
131 ,@body)
132 (if pc-mode (partial-completion-mode 1)))))
134 ;;; The custom variables
136 (defgroup org nil
137 "Outline-based notes management and organizer."
138 :tag "Org"
139 :group 'outlines
140 :group 'hypermedia
141 :group 'calendar)
143 ;; FIXME: Needs a separate group...
144 (defcustom org-completion-fallback-command 'hippie-expand
145 "The expansion command called by \\[org-complete] in normal context.
146 Normal means, no org-mode-specific context."
147 :group 'org
148 :type 'function)
150 (defgroup org-startup nil
151 "Options concerning startup of Org-mode."
152 :tag "Org Startup"
153 :group 'org)
155 (defcustom org-startup-folded t
156 "Non-nil means, entering Org-mode will switch to OVERVIEW.
157 This can also be configured on a per-file basis by adding one of
158 the following lines anywhere in the buffer:
160 #+STARTUP: fold
161 #+STARTUP: nofold
162 #+STARTUP: content"
163 :group 'org-startup
164 :type '(choice
165 (const :tag "nofold: show all" nil)
166 (const :tag "fold: overview" t)
167 (const :tag "content: all headlines" content)))
169 (defcustom org-startup-truncated t
170 "Non-nil means, entering Org-mode will set `truncate-lines'.
171 This is useful since some lines containing links can be very long and
172 uninteresting. Also tables look terrible when wrapped."
173 :group 'org-startup
174 :type 'boolean)
176 (defcustom org-startup-align-all-tables nil
177 "Non-nil means, align all tables when visiting a file.
178 This is useful when the column width in tables is forced with <N> cookies
179 in table fields. Such tables will look correct only after the first re-align.
180 This can also be configured on a per-file basis by adding one of
181 the following lines anywhere in the buffer:
182 #+STARTUP: align
183 #+STARTUP: noalign"
184 :group 'org-startup
185 :type 'boolean)
187 (defcustom org-insert-mode-line-in-empty-file nil
188 "Non-nil means insert the first line setting Org-mode in empty files.
189 When the function `org-mode' is called interactively in an empty file, this
190 normally means that the file name does not automatically trigger Org-mode.
191 To ensure that the file will always be in Org-mode in the future, a
192 line enforcing Org-mode will be inserted into the buffer, if this option
193 has been set."
194 :group 'org-startup
195 :type 'boolean)
197 (defcustom org-replace-disputed-keys nil
198 "Non-nil means use alternative key bindings for some keys.
199 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
200 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
201 If you want to use Org-mode together with one of these other modes,
202 or more generally if you would like to move some Org-mode commands to
203 other keys, set this variable and configure the keys with the variable
204 `org-disputed-keys'.
206 This option is only relevant at load-time of Org-mode, and must be set
207 *before* org.el is loaded. Changing it requires a restart of Emacs to
208 become effective."
209 :group 'org-startup
210 :type 'boolean)
212 (if (fboundp 'defvaralias)
213 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
215 (defcustom org-disputed-keys
216 '(([(shift up)] . [(meta p)])
217 ([(shift down)] . [(meta n)])
218 ([(shift left)] . [(meta -)])
219 ([(shift right)] . [(meta +)])
220 ([(control shift right)] . [(meta shift +)])
221 ([(control shift left)] . [(meta shift -)]))
222 "Keys for which Org-mode and other modes compete.
223 This is an alist, cars are the default keys, second element specifies
224 the alternative to use when `org-replace-disputed-keys' is t.
226 Keys can be specified in any syntax supported by `define-key'.
227 The value of this option takes effect only at Org-mode's startup,
228 therefore you'll have to restart Emacs to apply it after changing."
229 :group 'org-startup
230 :type 'alist)
232 (defun org-key (key)
233 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
234 Or return the original if not disputed."
235 (if org-replace-disputed-keys
236 (let* ((nkey (key-description key))
237 (x (org-find-if (lambda (x)
238 (equal (key-description (car x)) nkey))
239 org-disputed-keys)))
240 (if x (cdr x) key))
241 key))
243 (defun org-find-if (predicate seq)
244 (catch 'exit
245 (while seq
246 (if (funcall predicate (car seq))
247 (throw 'exit (car seq))
248 (pop seq)))))
250 (defun org-defkey (keymap key def)
251 "Define a key, possibly translated, as returned by `org-key'."
252 (define-key keymap (org-key key) def))
254 (defcustom org-ellipsis 'org-link
255 "The ellipsis to use in the Org-mode outline.
256 When nil, just use the standard three dots. When a string, use that instead,
257 When a face, use the standart 3 dots, but with the specified face.
258 The change affects only Org-mode (which will then use its own display table).
259 Changing this requires executing `M-x org-mode' in a buffer to become
260 effective."
261 :group 'org-startup
262 :type '(choice (const :tag "Default" nil)
263 (face :tag "Face" :value org-warning)
264 (string :tag "String" :value "...#")))
266 (defvar org-display-table nil
267 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
269 (defgroup org-keywords nil
270 "Keywords in Org-mode."
271 :tag "Org Keywords"
272 :group 'org)
274 (defcustom org-deadline-string "DEADLINE:"
275 "String to mark deadline entries.
276 A deadline is this string, followed by a time stamp. Should be a word,
277 terminated by a colon. You can insert a schedule keyword and
278 a timestamp with \\[org-deadline].
279 Changes become only effective after restarting Emacs."
280 :group 'org-keywords
281 :type 'string)
283 (defcustom org-scheduled-string "SCHEDULED:"
284 "String to mark scheduled TODO entries.
285 A schedule is this string, followed by a time stamp. Should be a word,
286 terminated by a colon. You can insert a schedule keyword and
287 a timestamp with \\[org-schedule].
288 Changes become only effective after restarting Emacs."
289 :group 'org-keywords
290 :type 'string)
292 (defcustom org-closed-string "CLOSED:"
293 "String used as the prefix for timestamps logging closing a TODO entry."
294 :group 'org-keywords
295 :type 'string)
297 (defcustom org-clock-string "CLOCK:"
298 "String used as prefix for timestamps clocking work hours on an item."
299 :group 'org-keywords
300 :type 'string)
302 (defcustom org-comment-string "COMMENT"
303 "Entries starting with this keyword will never be exported.
304 An entry can be toggled between COMMENT and normal with
305 \\[org-toggle-comment].
306 Changes become only effective after restarting Emacs."
307 :group 'org-keywords
308 :type 'string)
310 (defcustom org-quote-string "QUOTE"
311 "Entries starting with this keyword will be exported in fixed-width font.
312 Quoting applies only to the text in the entry following the headline, and does
313 not extend beyond the next headline, even if that is lower level.
314 An entry can be toggled between QUOTE and normal with
315 \\[org-toggle-fixed-width-section]."
316 :group 'org-keywords
317 :type 'string)
319 (defconst org-repeat-re
320 (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
321 " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
322 "Regular expression for specifying repeated events.
323 After a match, group 1 contains the repeat expression.")
325 (defgroup org-structure nil
326 "Options concerning the general structure of Org-mode files."
327 :tag "Org Structure"
328 :group 'org)
330 (defgroup org-reveal-location nil
331 "Options about how to make context of a location visible."
332 :tag "Org Reveal Location"
333 :group 'org-structure)
335 (defcustom org-show-hierarchy-above '((default . t))
336 "Non-nil means, show full hierarchy when revealing a location.
337 Org-mode often shows locations in an org-mode file which might have
338 been invisible before. When this is set, the hierarchy of headings
339 above the exposed location is shown.
340 Turning this off for example for sparse trees makes them very compact.
341 Instead of t, this can also be an alist specifying this option for different
342 contexts. Valid contexts are
343 agenda when exposing an entry from the agenda
344 org-goto when using the command `org-goto' on key C-c C-j
345 occur-tree when using the command `org-occur' on key C-c /
346 tags-tree when constructing a sparse tree based on tags matches
347 link-search when exposing search matches associated with a link
348 mark-goto when exposing the jump goal of a mark
349 bookmark-jump when exposing a bookmark location
350 isearch when exiting from an incremental search
351 default default for all contexts not set explicitly"
352 :group 'org-reveal-location
353 :type '(choice
354 (const :tag "Always" t)
355 (const :tag "Never" nil)
356 (repeat :greedy t :tag "Individual contexts"
357 (cons
358 (choice :tag "Context"
359 (const agenda)
360 (const org-goto)
361 (const occur-tree)
362 (const tags-tree)
363 (const link-search)
364 (const mark-goto)
365 (const bookmark-jump)
366 (const isearch)
367 (const default))
368 (boolean)))))
370 (defcustom org-show-following-heading '((default . nil))
371 "Non-nil means, show following heading when revealing a location.
372 Org-mode often shows locations in an org-mode file which might have
373 been invisible before. When this is set, the heading following the
374 match is shown.
375 Turning this off for example for sparse trees makes them very compact,
376 but makes it harder to edit the location of the match. In such a case,
377 use the command \\[org-reveal] to show more context.
378 Instead of t, this can also be an alist specifying this option for different
379 contexts. See `org-show-hierarchy-above' for valid contexts."
380 :group 'org-reveal-location
381 :type '(choice
382 (const :tag "Always" t)
383 (const :tag "Never" nil)
384 (repeat :greedy t :tag "Individual contexts"
385 (cons
386 (choice :tag "Context"
387 (const agenda)
388 (const org-goto)
389 (const occur-tree)
390 (const tags-tree)
391 (const link-search)
392 (const mark-goto)
393 (const bookmark-jump)
394 (const isearch)
395 (const default))
396 (boolean)))))
398 (defcustom org-show-siblings '((default . nil) (isearch t))
399 "Non-nil means, show all sibling heading when revealing a location.
400 Org-mode often shows locations in an org-mode file which might have
401 been invisible before. When this is set, the sibling of the current entry
402 heading are all made visible. If `org-show-hierarchy-above' is t,
403 the same happens on each level of the hierarchy above the current entry.
405 By default this is on for the isearch context, off for all other contexts.
406 Turning this off for example for sparse trees makes them very compact,
407 but makes it harder to edit the location of the match. In such a case,
408 use the command \\[org-reveal] to show more context.
409 Instead of t, this can also be an alist specifying this option for different
410 contexts. See `org-show-hierarchy-above' for valid contexts."
411 :group 'org-reveal-location
412 :type '(choice
413 (const :tag "Always" t)
414 (const :tag "Never" nil)
415 (repeat :greedy t :tag "Individual contexts"
416 (cons
417 (choice :tag "Context"
418 (const agenda)
419 (const org-goto)
420 (const occur-tree)
421 (const tags-tree)
422 (const link-search)
423 (const mark-goto)
424 (const bookmark-jump)
425 (const isearch)
426 (const default))
427 (boolean)))))
429 (defgroup org-cycle nil
430 "Options concerning visibility cycling in Org-mode."
431 :tag "Org Cycle"
432 :group 'org-structure)
434 (defcustom org-drawers '("PROPERTIES" "CLOCK")
435 "Names of drawers. Drawers are not opened by cycling on the headline above.
436 Drawers only open with a TAB on the drawer line itself. A drawer looks like
437 this:
438 :DRAWERNAME:
439 .....
440 :END:
441 The drawer \"PROPERTIES\" is special for capturing properties through
442 the property API."
443 :group 'org-structure
444 :type '(repeat (string :tag "Drawer Name")))
446 (defcustom org-cycle-global-at-bob nil
447 "Cycle globally if cursor is at beginning of buffer and not at a headline.
448 This makes it possible to do global cycling without having to use S-TAB or
449 C-u TAB. For this special case to work, the first line of the buffer
450 must not be a headline - it may be empty ot some other text. When used in
451 this way, `org-cycle-hook' is disables temporarily, to make sure the
452 cursor stays at the beginning of the buffer.
453 When this option is nil, don't do anything special at the beginning
454 of the buffer."
455 :group 'org-cycle
456 :type 'boolean)
458 (defcustom org-cycle-emulate-tab t
459 "Where should `org-cycle' emulate TAB.
460 nil Never
461 white Only in completely white lines
462 whitestart Only at the beginning of lines, before the first non-white char.
463 t Everywhere except in headlines
464 exc-hl-bol Everywhere except at the start of a headline
465 If TAB is used in a place where it does not emulate TAB, the current subtree
466 visibility is cycled."
467 :group 'org-cycle
468 :type '(choice (const :tag "Never" nil)
469 (const :tag "Only in completely white lines" white)
470 (const :tag "Before first char in a line" whitestart)
471 (const :tag "Everywhere except in headlines" t)
472 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
475 (defcustom org-cycle-separator-lines 2
476 "Number of empty lines needed to keep an empty line between collapsed trees.
477 If you leave an empty line between the end of a subtree and the following
478 headline, this empty line is hidden when the subtree is folded.
479 Org-mode will leave (exactly) one empty line visible if the number of
480 empty lines is equal or larger to the number given in this variable.
481 So the default 2 means, at least 2 empty lines after the end of a subtree
482 are needed to produce free space between a collapsed subtree and the
483 following headline.
485 Special case: when 0, never leave empty lines in collapsed view."
486 :group 'org-cycle
487 :type 'integer)
489 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
490 org-cycle-hide-drawers
491 org-cycle-show-empty-lines
492 org-optimize-window-after-visibility-change)
493 "Hook that is run after `org-cycle' has changed the buffer visibility.
494 The function(s) in this hook must accept a single argument which indicates
495 the new state that was set by the most recent `org-cycle' command. The
496 argument is a symbol. After a global state change, it can have the values
497 `overview', `content', or `all'. After a local state change, it can have
498 the values `folded', `children', or `subtree'."
499 :group 'org-cycle
500 :type 'hook)
502 (defgroup org-edit-structure nil
503 "Options concerning structure editing in Org-mode."
504 :tag "Org Edit Structure"
505 :group 'org-structure)
507 (defcustom org-special-ctrl-a/e nil
508 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
509 When t, `C-a' will bring back the cursor to the beginning of the
510 headline text, i.e. after the stars and after a possible TODO keyword.
511 In an item, this will be the position after the bullet.
512 When the cursor is already at that position, another `C-a' will bring
513 it to the beginning of the line.
514 `C-e' will jump to the end of the headline, ignoring the presence of tags
515 in the headline. A second `C-e' will then jump to the true end of the
516 line, after any tags.
517 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
518 and only a directly following, identical keypress will bring the cursor
519 to the special positions."
520 :group 'org-edit-structure
521 :type '(choice
522 (const :tag "off" nil)
523 (const :tag "after bullet first" t)
524 (const :tag "border first" reversed)))
526 (if (fboundp 'defvaralias)
527 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
529 (defcustom org-odd-levels-only nil
530 "Non-nil means, skip even levels and only use odd levels for the outline.
531 This has the effect that two stars are being added/taken away in
532 promotion/demotion commands. It also influences how levels are
533 handled by the exporters.
534 Changing it requires restart of `font-lock-mode' to become effective
535 for fontification also in regions already fontified.
536 You may also set this on a per-file basis by adding one of the following
537 lines to the buffer:
539 #+STARTUP: odd
540 #+STARTUP: oddeven"
541 :group 'org-edit-structure
542 :group 'org-font-lock
543 :type 'boolean)
545 (defcustom org-adapt-indentation t
546 "Non-nil means, adapt indentation when promoting and demoting.
547 When this is set and the *entire* text in an entry is indented, the
548 indentation is increased by one space in a demotion command, and
549 decreased by one in a promotion command. If any line in the entry
550 body starts at column 0, indentation is not changed at all."
551 :group 'org-edit-structure
552 :type 'boolean)
554 (defcustom org-blank-before-new-entry '((heading . nil)
555 (plain-list-item . nil))
556 "Should `org-insert-heading' leave a blank line before new heading/item?
557 The value is an alist, with `heading' and `plain-list-item' as car,
558 and a boolean flag as cdr."
559 :group 'org-edit-structure
560 :type '(list
561 (cons (const heading) (boolean))
562 (cons (const plain-list-item) (boolean))))
564 (defcustom org-insert-heading-hook nil
565 "Hook being run after inserting a new heading."
566 :group 'org-edit-structure
567 :type 'boolean)
569 (defcustom org-enable-fixed-width-editor t
570 "Non-nil means, lines starting with \":\" are treated as fixed-width.
571 This currently only means, they are never auto-wrapped.
572 When nil, such lines will be treated like ordinary lines.
573 See also the QUOTE keyword."
574 :group 'org-edit-structure
575 :type 'boolean)
577 (defgroup org-sparse-trees nil
578 "Options concerning sparse trees in Org-mode."
579 :tag "Org Sparse Trees"
580 :group 'org-structure)
582 (defcustom org-highlight-sparse-tree-matches t
583 "Non-nil means, highlight all matches that define a sparse tree.
584 The highlights will automatically disappear the next time the buffer is
585 changed by an edit command."
586 :group 'org-sparse-trees
587 :type 'boolean)
589 (defcustom org-remove-highlights-with-change t
590 "Non-nil means, any change to the buffer will remove temporary highlights.
591 Such highlights are created by `org-occur' and `org-clock-display'.
592 When nil, `C-c C-c needs to be used to get rid of the highlights.
593 The highlights created by `org-preview-latex-fragment' always need
594 `C-c C-c' to be removed."
595 :group 'org-sparse-trees
596 :group 'org-time
597 :type 'boolean)
600 (defcustom org-occur-hook '(org-first-headline-recenter)
601 "Hook that is run after `org-occur' has constructed a sparse tree.
602 This can be used to recenter the window to show as much of the structure
603 as possible."
604 :group 'org-sparse-trees
605 :type 'hook)
607 (defgroup org-plain-lists nil
608 "Options concerning plain lists in Org-mode."
609 :tag "Org Plain lists"
610 :group 'org-structure)
612 (defcustom org-cycle-include-plain-lists nil
613 "Non-nil means, include plain lists into visibility cycling.
614 This means that during cycling, plain list items will *temporarily* be
615 interpreted as outline headlines with a level given by 1000+i where i is the
616 indentation of the bullet. In all other operations, plain list items are
617 not seen as headlines. For example, you cannot assign a TODO keyword to
618 such an item."
619 :group 'org-plain-lists
620 :type 'boolean)
622 (defcustom org-plain-list-ordered-item-terminator t
623 "The character that makes a line with leading number an ordered list item.
624 Valid values are ?. and ?\). To get both terminators, use t. While
625 ?. may look nicer, it creates the danger that a line with leading
626 number may be incorrectly interpreted as an item. ?\) therefore is
627 the safe choice."
628 :group 'org-plain-lists
629 :type '(choice (const :tag "dot like in \"2.\"" ?.)
630 (const :tag "paren like in \"2)\"" ?\))
631 (const :tab "both" t)))
633 (defcustom org-auto-renumber-ordered-lists t
634 "Non-nil means, automatically renumber ordered plain lists.
635 Renumbering happens when the sequence have been changed with
636 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
637 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
638 :group 'org-plain-lists
639 :type 'boolean)
641 (defcustom org-provide-checkbox-statistics t
642 "Non-nil means, update checkbox statistics after insert and toggle.
643 When this is set, checkbox statistics is updated each time you either insert
644 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
645 with \\[org-ctrl-c-ctrl-c\\]."
646 :group 'org-plain-lists
647 :type 'boolean)
649 (defgroup org-archive nil
650 "Options concerning archiving in Org-mode."
651 :tag "Org Archive"
652 :group 'org-structure)
654 (defcustom org-archive-tag "ARCHIVE"
655 "The tag that marks a subtree as archived.
656 An archived subtree does not open during visibility cycling, and does
657 not contribute to the agenda listings."
658 :group 'org-archive
659 :group 'org-keywords
660 :type 'string)
662 (defcustom org-agenda-skip-archived-trees t
663 "Non-nil means, the agenda will skip any items located in archived trees.
664 An archived tree is a tree marked with the tag ARCHIVE."
665 :group 'org-archive
666 :group 'org-agenda-skip
667 :type 'boolean)
669 (defcustom org-cycle-open-archived-trees nil
670 "Non-nil means, `org-cycle' will open archived trees.
671 An archived tree is a tree marked with the tag ARCHIVE.
672 When nil, archived trees will stay folded. You can still open them with
673 normal outline commands like `show-all', but not with the cycling commands."
674 :group 'org-archive
675 :group 'org-cycle
676 :type 'boolean)
678 (defcustom org-sparse-tree-open-archived-trees nil
679 "Non-nil means sparse tree construction shows matches in archived trees.
680 When nil, matches in these trees are highlighted, but the trees are kept in
681 collapsed state."
682 :group 'org-archive
683 :group 'org-sparse-trees
684 :type 'boolean)
686 (defcustom org-archive-location "%s_archive::"
687 "The location where subtrees should be archived.
688 This string consists of two parts, separated by a double-colon.
690 The first part is a file name - when omitted, archiving happens in the same
691 file. %s will be replaced by the current file name (without directory part).
692 Archiving to a different file is useful to keep archived entries from
693 contributing to the Org-mode Agenda.
695 The part after the double colon is a headline. The archived entries will be
696 filed under that headline. When omitted, the subtrees are simply filed away
697 at the end of the file, as top-level entries.
699 Here are a few examples:
700 \"%s_archive::\"
701 If the current file is Projects.org, archive in file
702 Projects.org_archive, as top-level trees. This is the default.
704 \"::* Archived Tasks\"
705 Archive in the current file, under the top-level headline
706 \"* Archived Tasks\".
708 \"~/org/archive.org::\"
709 Archive in file ~/org/archive.org (absolute path), as top-level trees.
711 \"basement::** Finished Tasks\"
712 Archive in file ./basement (relative path), as level 3 trees
713 below the level 2 heading \"** Finished Tasks\".
715 You may set this option on a per-file basis by adding to the buffer a
716 line like
718 #+ARCHIVE: basement::** Finished Tasks"
719 :group 'org-archive
720 :type 'string)
722 (defcustom org-archive-mark-done t
723 "Non-nil means, mark entries as DONE when they are moved to the archive file.
724 This can be a string to set the keyword to use. When t, Org-mode will
725 use the first keyword in its list that means done."
726 :group 'org-archive
727 :type '(choice
728 (const :tag "No" nil)
729 (const :tag "Yes" t)
730 (string :tag "Use this keyword")))
732 (defcustom org-archive-stamp-time t
733 "Non-nil means, add a time stamp to entries moved to an archive file.
734 This variable is obsolete and has no effect anymore, instead add ot remove
735 `time' from the variablle `org-archive-save-context-info'."
736 :group 'org-archive
737 :type 'boolean)
739 (defcustom org-archive-save-context-info '(time file category todo itags)
740 "Parts of context info that should be stored as properties when archiving.
741 When a subtree is moved to an archive file, it looses information given by
742 context, like inherited tags, the category, and possibly also the TODO
743 state (depending on the variable `org-archive-mark-done').
744 This variable can be a list of any of the following symbols:
746 time The time of archiving.
747 file The file where the entry originates.
748 itags The local tags, in the headline of the subtree.
749 ltags The tags the subtree inherits from further up the hierarchy.
750 todo The pre-archive TODO state.
751 category The category, taken from file name or #+CATEGORY lines.
753 For each symbol present in the list, a property will be created in
754 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
755 information."
756 :group 'org-archive
757 :type '(set :greedy t
758 (const :tag "Time" time)
759 (const :tag "File" file)
760 (const :tag "Category" category)
761 (const :tag "TODO state" todo)
762 (const :tag "TODO state" priority)
763 (const :tag "Inherited tags" itags)
764 (const :tag "Local tags" ltags)))
766 (defgroup org-table nil
767 "Options concerning tables in Org-mode."
768 :tag "Org Table"
769 :group 'org)
771 (defcustom org-enable-table-editor 'optimized
772 "Non-nil means, lines starting with \"|\" are handled by the table editor.
773 When nil, such lines will be treated like ordinary lines.
775 When equal to the symbol `optimized', the table editor will be optimized to
776 do the following:
777 - Automatic overwrite mode in front of whitespace in table fields.
778 This makes the structure of the table stay in tact as long as the edited
779 field does not exceed the column width.
780 - Minimize the number of realigns. Normally, the table is aligned each time
781 TAB or RET are pressed to move to another field. With optimization this
782 happens only if changes to a field might have changed the column width.
783 Optimization requires replacing the functions `self-insert-command',
784 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
785 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
786 very good at guessing when a re-align will be necessary, but you can always
787 force one with \\[org-ctrl-c-ctrl-c].
789 If you would like to use the optimized version in Org-mode, but the
790 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
792 This variable can be used to turn on and off the table editor during a session,
793 but in order to toggle optimization, a restart is required.
795 See also the variable `org-table-auto-blank-field'."
796 :group 'org-table
797 :type '(choice
798 (const :tag "off" nil)
799 (const :tag "on" t)
800 (const :tag "on, optimized" optimized)))
802 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
803 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
804 In the optimized version, the table editor takes over all simple keys that
805 normally just insert a character. In tables, the characters are inserted
806 in a way to minimize disturbing the table structure (i.e. in overwrite mode
807 for empty fields). Outside tables, the correct binding of the keys is
808 restored.
810 The default for this option is t if the optimized version is also used in
811 Org-mode. See the variable `org-enable-table-editor' for details. Changing
812 this variable requires a restart of Emacs to become effective."
813 :group 'org-table
814 :type 'boolean)
816 (defcustom orgtbl-radio-table-templates
817 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
818 % END RECEIVE ORGTBL %n
819 \\begin{comment}
820 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
821 | | |
822 \\end{comment}\n")
823 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
824 @c END RECEIVE ORGTBL %n
825 @ignore
826 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
827 | | |
828 @end ignore\n")
829 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
830 <!-- END RECEIVE ORGTBL %n -->
831 <!--
832 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
833 | | |
834 -->\n"))
835 "Templates for radio tables in different major modes.
836 All occurrences of %n in a template will be replaced with the name of the
837 table, obtained by prompting the user."
838 :group 'org-table
839 :type '(repeat
840 (list (symbol :tag "Major mode")
841 (string :tag "Format"))))
843 (defgroup org-table-settings nil
844 "Settings for tables in Org-mode."
845 :tag "Org Table Settings"
846 :group 'org-table)
848 (defcustom org-table-default-size "5x2"
849 "The default size for newly created tables, Columns x Rows."
850 :group 'org-table-settings
851 :type 'string)
853 (defcustom org-table-number-regexp
854 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
855 "Regular expression for recognizing numbers in table columns.
856 If a table column contains mostly numbers, it will be aligned to the
857 right. If not, it will be aligned to the left.
859 The default value of this option is a regular expression which allows
860 anything which looks remotely like a number as used in scientific
861 context. For example, all of the following will be considered a
862 number:
863 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
865 Other options offered by the customize interface are more restrictive."
866 :group 'org-table-settings
867 :type '(choice
868 (const :tag "Positive Integers"
869 "^[0-9]+$")
870 (const :tag "Integers"
871 "^[-+]?[0-9]+$")
872 (const :tag "Floating Point Numbers"
873 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
874 (const :tag "Floating Point Number or Integer"
875 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
876 (const :tag "Exponential, Floating point, Integer"
877 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
878 (const :tag "Very General Number-Like, including hex"
879 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
880 (string :tag "Regexp:")))
882 (defcustom org-table-number-fraction 0.5
883 "Fraction of numbers in a column required to make the column align right.
884 In a column all non-white fields are considered. If at least this
885 fraction of fields is matched by `org-table-number-fraction',
886 alignment to the right border applies."
887 :group 'org-table-settings
888 :type 'number)
890 (defgroup org-table-editing nil
891 "Bahavior of tables during editing in Org-mode."
892 :tag "Org Table Editing"
893 :group 'org-table)
895 (defcustom org-table-automatic-realign t
896 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
897 When nil, aligning is only done with \\[org-table-align], or after column
898 removal/insertion."
899 :group 'org-table-editing
900 :type 'boolean)
902 (defcustom org-table-auto-blank-field t
903 "Non-nil means, automatically blank table field when starting to type into it.
904 This only happens when typing immediately after a field motion
905 command (TAB, S-TAB or RET).
906 Only relevant when `org-enable-table-editor' is equal to `optimized'."
907 :group 'org-table-editing
908 :type 'boolean)
910 (defcustom org-table-tab-jumps-over-hlines t
911 "Non-nil means, tab in the last column of a table with jump over a hline.
912 If a horizontal separator line is following the current line,
913 `org-table-next-field' can either create a new row before that line, or jump
914 over the line. When this option is nil, a new line will be created before
915 this line."
916 :group 'org-table-editing
917 :type 'boolean)
919 (defcustom org-table-tab-recognizes-table.el t
920 "Non-nil means, TAB will automatically notice a table.el table.
921 When it sees such a table, it moves point into it and - if necessary -
922 calls `table-recognize-table'."
923 :group 'org-table-editing
924 :type 'boolean)
926 (defgroup org-table-calculation nil
927 "Options concerning tables in Org-mode."
928 :tag "Org Table Calculation"
929 :group 'org-table)
931 (defcustom org-table-use-standard-references t
932 "Should org-mode work with table refrences like B3 instead of @3$2?
933 Possible values are:
934 nil never use them
935 from accept as input, do not present for editing
936 t: accept as input and present for editing"
937 :group 'org-table-calculation
938 :type '(choice
939 (const :tag "Never, don't even check unser input for them" nil)
940 (const :tag "Always, both as user input, and when editing" t)
941 (const :tag "Convert user input, don't offer during editing" 'from)))
943 (defcustom org-table-copy-increment t
944 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
945 :group 'org-table-calculation
946 :type 'boolean)
948 (defcustom org-calc-default-modes
949 '(calc-internal-prec 12
950 calc-float-format (float 5)
951 calc-angle-mode deg
952 calc-prefer-frac nil
953 calc-symbolic-mode nil
954 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
955 calc-display-working-message t
957 "List with Calc mode settings for use in calc-eval for table formulas.
958 The list must contain alternating symbols (Calc modes variables and values).
959 Don't remove any of the default settings, just change the values. Org-mode
960 relies on the variables to be present in the list."
961 :group 'org-table-calculation
962 :type 'plist)
964 (defcustom org-table-formula-evaluate-inline t
965 "Non-nil means, TAB and RET evaluate a formula in current table field.
966 If the current field starts with an equal sign, it is assumed to be a formula
967 which should be evaluated as described in the manual and in the documentation
968 string of the command `org-table-eval-formula'. This feature requires the
969 Emacs calc package.
970 When this variable is nil, formula calculation is only available through
971 the command \\[org-table-eval-formula]."
972 :group 'org-table-calculation
973 :type 'boolean)
975 (defcustom org-table-formula-use-constants t
976 "Non-nil means, interpret constants in formulas in tables.
977 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
978 by the value given in `org-table-formula-constants', or by a value obtained
979 from the `constants.el' package."
980 :group 'org-table-calculation
981 :type 'boolean)
983 (defcustom org-table-formula-constants nil
984 "Alist with constant names and values, for use in table formulas.
985 The car of each element is a name of a constant, without the `$' before it.
986 The cdr is the value as a string. For example, if you'd like to use the
987 speed of light in a formula, you would configure
989 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
991 and then use it in an equation like `$1*$c'.
993 Constants can also be defined on a per-file basis using a line like
995 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
996 :group 'org-table-calculation
997 :type '(repeat
998 (cons (string :tag "name")
999 (string :tag "value"))))
1001 (defvar org-table-formula-constants-local nil
1002 "Local version of `org-table-formula-constants'.")
1003 (make-variable-buffer-local 'org-table-formula-constants-local)
1005 (defcustom org-table-allow-automatic-line-recalculation t
1006 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1007 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1008 :group 'org-table-calculation
1009 :type 'boolean)
1011 (defgroup org-link nil
1012 "Options concerning links in Org-mode."
1013 :tag "Org Link"
1014 :group 'org)
1016 (defvar org-link-abbrev-alist-local nil
1017 "Buffer-local version of `org-link-abbrev-alist', which see.
1018 The value of this is taken from the #+LINK lines.")
1019 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1021 (defcustom org-link-abbrev-alist nil
1022 "Alist of link abbreviations.
1023 The car of each element is a string, to be replaced at the start of a link.
1024 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1025 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1027 [[linkkey:tag][description]]
1029 If REPLACE is a string, the tag will simply be appended to create the link.
1030 If the string contains \"%s\", the tag will be inserted there. REPLACE may
1031 also be a function that will be called with the tag as the only argument to
1032 create the link. See the manual for examples."
1033 :group 'org-link
1034 :type 'alist)
1036 (defcustom org-descriptive-links t
1037 "Non-nil means, hide link part and only show description of bracket links.
1038 Bracket links are like [[link][descritpion]]. This variable sets the initial
1039 state in new org-mode buffers. The setting can then be toggled on a
1040 per-buffer basis from the Org->Hyperlinks menu."
1041 :group 'org-link
1042 :type 'boolean)
1044 (defcustom org-link-file-path-type 'adaptive
1045 "How the path name in file links should be stored.
1046 Valid values are:
1048 relative relative to the current directory, i.e. the directory of the file
1049 into which the link is being inserted.
1050 absolute absolute path, if possible with ~ for home directory.
1051 noabbrev absolute path, no abbreviation of home directory.
1052 adaptive Use relative path for files in the current directory and sub-
1053 directories of it. For other files, use an absolute path."
1054 :group 'org-link
1055 :type '(choice
1056 (const relative)
1057 (const absolute)
1058 (const noabbrev)
1059 (const adaptive)))
1061 (defcustom org-activate-links '(bracket angle plain radio tag date)
1062 "Types of links that should be activated in Org-mode files.
1063 This is a list of symbols, each leading to the activation of a certain link
1064 type. In principle, it does not hurt to turn on most link types - there may
1065 be a small gain when turning off unused link types. The types are:
1067 bracket The recommended [[link][description]] or [[link]] links with hiding.
1068 angular Links in angular brackes that may contain whitespace like
1069 <bbdb:Carsten Dominik>.
1070 plain Plain links in normal text, no whitespace, like http://google.com.
1071 radio Text that is matched by a radio target, see manual for details.
1072 tag Tag settings in a headline (link to tag search).
1073 date Time stamps (link to calendar).
1075 Changing this variable requires a restart of Emacs to become effective."
1076 :group 'org-link
1077 :type '(set (const :tag "Double bracket links (new style)" bracket)
1078 (const :tag "Angular bracket links (old style)" angular)
1079 (const :tag "plain text links" plain)
1080 (const :tag "Radio target matches" radio)
1081 (const :tag "Tags" tag)
1082 (const :tag "Tags" target)
1083 (const :tag "Timestamps" date)))
1085 (defgroup org-link-store nil
1086 "Options concerning storing links in Org-mode"
1087 :tag "Org Store Link"
1088 :group 'org-link)
1090 (defcustom org-email-link-description-format "Email %c: %.30s"
1091 "Format of the description part of a link to an email or usenet message.
1092 The following %-excapes will be replaced by corresponding information:
1094 %F full \"From\" field
1095 %f name, taken from \"From\" field, address if no name
1096 %T full \"To\" field
1097 %t first name in \"To\" field, address if no name
1098 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1099 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1100 %s subject
1101 %m message-id.
1103 You may use normal field width specification between the % and the letter.
1104 This is for example useful to limit the length of the subject.
1106 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1107 :group 'org-link-store
1108 :type 'string)
1110 (defcustom org-from-is-user-regexp
1111 (let (r1 r2)
1112 (when (and user-mail-address (not (string= user-mail-address "")))
1113 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1114 (when (and user-full-name (not (string= user-full-name "")))
1115 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1116 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1117 "Regexp mached against the \"From:\" header of an email or usenet message.
1118 It should match if the message is from the user him/herself."
1119 :group 'org-link-store
1120 :type 'regexp)
1122 (defcustom org-context-in-file-links t
1123 "Non-nil means, file links from `org-store-link' contain context.
1124 A search string will be added to the file name with :: as separator and
1125 used to find the context when the link is activated by the command
1126 `org-open-at-point'.
1127 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1128 negates this setting for the duration of the command."
1129 :group 'org-link-store
1130 :type 'boolean)
1132 (defcustom org-keep-stored-link-after-insertion nil
1133 "Non-nil means, keep link in list for entire session.
1135 The command `org-store-link' adds a link pointing to the current
1136 location to an internal list. These links accumulate during a session.
1137 The command `org-insert-link' can be used to insert links into any
1138 Org-mode file (offering completion for all stored links). When this
1139 option is nil, every link which has been inserted once using \\[org-insert-link]
1140 will be removed from the list, to make completing the unused links
1141 more efficient."
1142 :group 'org-link-store
1143 :type 'boolean)
1145 (defcustom org-usenet-links-prefer-google nil
1146 "Non-nil means, `org-store-link' will create web links to Google groups.
1147 When nil, Gnus will be used for such links.
1148 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1149 negates this setting for the duration of the command."
1150 :group 'org-link-store
1151 :type 'boolean)
1153 (defgroup org-link-follow nil
1154 "Options concerning following links in Org-mode"
1155 :tag "Org Follow Link"
1156 :group 'org-link)
1158 (defcustom org-tab-follows-link nil
1159 "Non-nil means, on links TAB will follow the link.
1160 Needs to be set before org.el is loaded."
1161 :group 'org-link-follow
1162 :type 'boolean)
1164 (defcustom org-return-follows-link nil
1165 "Non-nil means, on links RET will follow the link.
1166 Needs to be set before org.el is loaded."
1167 :group 'org-link-follow
1168 :type 'boolean)
1170 (defcustom org-mouse-1-follows-link t
1171 "Non-nil means, mouse-1 on a link will follow the link.
1172 A longer mouse click will still set point. Does not wortk on XEmacs.
1173 Needs to be set before org.el is loaded."
1174 :group 'org-link-follow
1175 :type 'boolean)
1177 (defcustom org-mark-ring-length 4
1178 "Number of different positions to be recorded in the ring
1179 Changing this requires a restart of Emacs to work correctly."
1180 :group 'org-link-follow
1181 :type 'interger)
1183 (defcustom org-link-frame-setup
1184 '((vm . vm-visit-folder-other-frame)
1185 (gnus . gnus-other-frame)
1186 (file . find-file-other-window))
1187 "Setup the frame configuration for following links.
1188 When following a link with Emacs, it may often be useful to display
1189 this link in another window or frame. This variable can be used to
1190 set this up for the different types of links.
1191 For VM, use any of
1192 `vm-visit-folder'
1193 `vm-visit-folder-other-frame'
1194 For Gnus, use any of
1195 `gnus'
1196 `gnus-other-frame'
1197 For FILE, use any of
1198 `find-file'
1199 `find-file-other-window'
1200 `find-file-other-frame'
1201 For the calendar, use the variable `calendar-setup'.
1202 For BBDB, it is currently only possible to display the matches in
1203 another window."
1204 :group 'org-link-follow
1205 :type '(list
1206 (cons (const vm)
1207 (choice
1208 (const vm-visit-folder)
1209 (const vm-visit-folder-other-window)
1210 (const vm-visit-folder-other-frame)))
1211 (cons (const gnus)
1212 (choice
1213 (const gnus)
1214 (const gnus-other-frame)))
1215 (cons (const file)
1216 (choice
1217 (const find-file)
1218 (const find-file-other-window)
1219 (const find-file-other-frame)))))
1221 (defcustom org-display-internal-link-with-indirect-buffer nil
1222 "Non-nil means, use indirect buffer to display infile links.
1223 Activating internal links (from one location in a file to another location
1224 in the same file) normally just jumps to the location. When the link is
1225 activated with a C-u prefix (or with mouse-3), the link is displayed in
1226 another window. When this option is set, the other window actually displays
1227 an indirect buffer clone of the current buffer, to avoid any visibility
1228 changes to the current buffer."
1229 :group 'org-link-follow
1230 :type 'boolean)
1232 (defcustom org-open-non-existing-files nil
1233 "Non-nil means, `org-open-file' will open non-existing files.
1234 When nil, an error will be generated."
1235 :group 'org-link-follow
1236 :type 'boolean)
1238 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1239 "Function and arguments to call for following mailto links.
1240 This is a list with the first element being a lisp function, and the
1241 remaining elements being arguments to the function. In string arguments,
1242 %a will be replaced by the address, and %s will be replaced by the subject
1243 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1244 :group 'org-link-follow
1245 :type '(choice
1246 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1247 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1248 (const :tag "message-mail" (message-mail "%a" "%s"))
1249 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1251 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1252 "Non-nil means, ask for confirmation before executing shell links.
1253 Shell links can be dangerous: just think about a link
1255 [[shell:rm -rf ~/*][Google Search]]
1257 This link would show up in your Org-mode document as \"Google Search\",
1258 but really it would remove your entire home directory.
1259 Therefore we advise against setting this variable to nil.
1260 Just change it to `y-or-n-p' of you want to confirm with a
1261 single keystroke rather than having to type \"yes\"."
1262 :group 'org-link-follow
1263 :type '(choice
1264 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1265 (const :tag "with y-or-n (faster)" y-or-n-p)
1266 (const :tag "no confirmation (dangerous)" nil)))
1268 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1269 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1270 Elisp links can be dangerous: just think about a link
1272 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1274 This link would show up in your Org-mode document as \"Google Search\",
1275 but really it would remove your entire home directory.
1276 Therefore we advise against setting this variable to nil.
1277 Just change it to `y-or-n-p' of you want to confirm with a
1278 single keystroke rather than having to type \"yes\"."
1279 :group 'org-link-follow
1280 :type '(choice
1281 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1282 (const :tag "with y-or-n (faster)" y-or-n-p)
1283 (const :tag "no confirmation (dangerous)" nil)))
1285 (defconst org-file-apps-defaults-gnu
1286 '((remote . emacs)
1287 (t . mailcap))
1288 "Default file applications on a UNIX or GNU/Linux system.
1289 See `org-file-apps'.")
1291 (defconst org-file-apps-defaults-macosx
1292 '((remote . emacs)
1293 (t . "open %s")
1294 ("ps" . "gv %s")
1295 ("ps.gz" . "gv %s")
1296 ("eps" . "gv %s")
1297 ("eps.gz" . "gv %s")
1298 ("dvi" . "xdvi %s")
1299 ("fig" . "xfig %s"))
1300 "Default file applications on a MacOS X system.
1301 The system \"open\" is known as a default, but we use X11 applications
1302 for some files for which the OS does not have a good default.
1303 See `org-file-apps'.")
1305 (defconst org-file-apps-defaults-windowsnt
1306 (list
1307 '(remote . emacs)
1308 (cons t
1309 (list (if (featurep 'xemacs)
1310 'mswindows-shell-execute
1311 'w32-shell-execute)
1312 "open" 'file)))
1313 "Default file applications on a Windows NT system.
1314 The system \"open\" is used for most files.
1315 See `org-file-apps'.")
1317 (defcustom org-file-apps
1319 ("txt" . emacs)
1320 ("tex" . emacs)
1321 ("ltx" . emacs)
1322 ("org" . emacs)
1323 ("el" . emacs)
1324 ("bib" . emacs)
1326 "External applications for opening `file:path' items in a document.
1327 Org-mode uses system defaults for different file types, but
1328 you can use this variable to set the application for a given file
1329 extension. The entries in this list are cons cells where the car identifies
1330 files and the cdr the corresponding command. Possible values for the
1331 file identifier are
1332 \"ext\" A string identifying an extension
1333 `directory' Matches a directory
1334 `remote' Matches a remote file, accessible through tramp or efs.
1335 Remote files most likely should be visited through Emacs
1336 because external applications cannot handle such paths.
1337 t Default for all remaining files
1339 Possible values for the command are:
1340 `emacs' The file will be visited by the current Emacs process.
1341 `default' Use the default application for this file type.
1342 string A command to be executed by a shell; %s will be replaced
1343 by the path to the file.
1344 sexp A Lisp form which will be evaluated. The file path will
1345 be available in the Lisp variable `file'.
1346 For more examples, see the system specific constants
1347 `org-file-apps-defaults-macosx'
1348 `org-file-apps-defaults-windowsnt'
1349 `org-file-apps-defaults-gnu'."
1350 :group 'org-link-follow
1351 :type '(repeat
1352 (cons (choice :value ""
1353 (string :tag "Extension")
1354 (const :tag "Default for unrecognized files" t)
1355 (const :tag "Remote file" remote)
1356 (const :tag "Links to a directory" directory))
1357 (choice :value ""
1358 (const :tag "Visit with Emacs" emacs)
1359 (const :tag "Use system default" default)
1360 (string :tag "Command")
1361 (sexp :tag "Lisp form")))))
1363 (defcustom org-mhe-search-all-folders nil
1364 "Non-nil means, that the search for the mh-message will be extended to
1365 all folders if the message cannot be found in the folder given in the link.
1366 Searching all folders is very efficient with one of the search engines
1367 supported by MH-E, but will be slow with pick."
1368 :group 'org-link-follow
1369 :type 'boolean)
1371 (defgroup org-remember nil
1372 "Options concerning interaction with remember.el."
1373 :tag "Org Remember"
1374 :group 'org)
1376 (defcustom org-directory "~/org"
1377 "Directory with org files.
1378 This directory will be used as default to prompt for org files.
1379 Used by the hooks for remember.el."
1380 :group 'org-remember
1381 :type 'directory)
1383 (defcustom org-default-notes-file "~/.notes"
1384 "Default target for storing notes.
1385 Used by the hooks for remember.el. This can be a string, or nil to mean
1386 the value of `remember-data-file'.
1387 You can set this on a per-template basis with the variable
1388 `org-remember-templates'."
1389 :group 'org-remember
1390 :type '(choice
1391 (const :tag "Default from remember-data-file" nil)
1392 file))
1394 (defcustom org-remember-store-without-prompt t
1395 "Non-nil means, `C-c C-c' stores remember note without further promts.
1396 In this case, you need `C-u C-c C-c' to get the prompts for
1397 note file and headline.
1398 When this variable is nil, `C-c C-c' give you the prompts, and
1399 `C-u C-c C-c' trigger the fasttrack."
1400 :group 'org-remember
1401 :type 'boolean)
1403 (defcustom org-remember-default-headline ""
1404 "The headline that should be the default location in the notes file.
1405 When filing remember notes, the cursor will start at that position.
1406 You can set this on a per-template basis with the variable
1407 `org-remember-templates'."
1408 :group 'org-remember
1409 :type 'string)
1411 (defcustom org-remember-templates nil
1412 "Templates for the creation of remember buffers.
1413 When nil, just let remember make the buffer.
1414 When not nil, this is a list of 5-element lists. In each entry, the first
1415 element is a the name of the template, It should be a single short word.
1416 The second element is a character, a unique key to select this template.
1417 The third element is the template. The forth element is optional and can
1418 specify a destination file for remember items created with this template.
1419 The default file is given by `org-default-notes-file'. An optional fifth
1420 element can specify the headline in that file that should be offered
1421 first when the user is asked to file the entry. The default headline is
1422 given in the variable `org-remember-default-headline'.
1424 The template specifies the structure of the remember buffer. It should have
1425 a first line starting with a star, to act as the org-mode headline.
1426 Furthermore, the following %-escapes will be replaced with content:
1428 %^{prompt} prompt the user for a string and replace this sequence with it.
1429 %t time stamp, date only
1430 %T time stamp with date and time
1431 %u, %U like the above, but inactive time stamps
1432 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1433 You may define a prompt like %^{Please specify birthday}t
1434 %n user name (taken from `user-full-name')
1435 %a annotation, normally the link created with org-store-link
1436 %i initial content, the region when remember is called with C-u.
1437 If %i is indented, the entire inserted text will be indented
1438 as well.
1440 %? After completing the template, position cursor here.
1442 Apart from these general escapes, you can access information specific to the
1443 link type that is created. For example, calling `remember' in emails or gnus
1444 will record the author and the subject of the message, which you can access
1445 with %:author and %:subject, respectively. Here is a complete list of what
1446 is recorded for each link type.
1448 Link type | Available information
1449 -------------------+------------------------------------------------------
1450 bbdb | %:type %:name %:company
1451 vm, wl, mh, rmail | %:type %:subject %:message-id
1452 | %:from %:fromname %:fromaddress
1453 | %:to %:toname %:toaddress
1454 | %:fromto (either \"to NAME\" or \"from NAME\")
1455 gnus | %:group, for messages also all email fields
1456 w3, w3m | %:type %:url
1457 info | %:type %:file %:node
1458 calendar | %:type %:date"
1459 :group 'org-remember
1460 :get (lambda (var) ; Make sure all entries have 5 elements
1461 (mapcar (lambda (x)
1462 (if (not (stringp (car x))) (setq x (cons "" x)))
1463 (cond ((= (length x) 4) (append x '("")))
1464 ((= (length x) 3) (append x '("" "")))
1465 (t x)))
1466 (default-value var)))
1467 :type '(repeat
1468 :tag "enabled"
1469 (list :value ("" ?a "\n" nil nil)
1470 (string :tag "Name")
1471 (character :tag "Selection Key")
1472 (string :tag "Template")
1473 (file :tag "Destination file (optional)")
1474 (string :tag "Destination headline (optional)"))))
1476 (defcustom org-reverse-note-order nil
1477 "Non-nil means, store new notes at the beginning of a file or entry.
1478 When nil, new notes will be filed to the end of a file or entry."
1479 :group 'org-remember
1480 :type '(choice
1481 (const :tag "Reverse always" t)
1482 (const :tag "Reverse never" nil)
1483 (repeat :tag "By file name regexp"
1484 (cons regexp boolean))))
1486 (defgroup org-todo nil
1487 "Options concerning TODO items in Org-mode."
1488 :tag "Org TODO"
1489 :group 'org)
1491 (defgroup org-progress nil
1492 "Options concerning Progress logging in Org-mode."
1493 :tag "Org Progress"
1494 :group 'org-time)
1496 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1497 "List of TODO entry keyword sequences and their interpretation.
1498 \\<org-mode-map>This is a list of sequences.
1500 Each sequence starts with a symbol, either `sequence' or `type',
1501 indicating if the keywords should be interpreted as a sequence of
1502 action steps, or as different types of TODO items. The first
1503 keywords are states requiring action - these states will select a headline
1504 for inclusion into the global TODO list Org-mode produces. If one of
1505 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1506 signify that no further action is necessary. If \"|\" is not found,
1507 the last keyword is treated as the only DONE state of the sequence.
1509 The command \\[org-todo] cycles an entry through these states, and one
1510 additional state where no keyword is present. For details about this
1511 cycling, see the manual.
1513 TODO keywords and interpretation can also be set on a per-file basis with
1514 the special #+SEQ_TODO and #+TYP_TODO lines.
1516 For backward compatibility, this variable may also be just a list
1517 of keywords - in this case the interptetation (sequence or type) will be
1518 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1519 :group 'org-todo
1520 :group 'org-keywords
1521 :type '(choice
1522 (repeat :tag "Old syntax, just keywords"
1523 (string :tag "Keyword"))
1524 (repeat :tag "New syntax"
1525 (cons
1526 (choice
1527 :tag "Interpretation"
1528 (const :tag "Sequence (cycling hits every state)" sequence)
1529 (const :tag "Type (cycling directly to DONE)" type))
1530 (repeat
1531 (string :tag "Keyword"))))))
1533 (defvar org-todo-keywords-1 nil)
1534 (make-variable-buffer-local 'org-todo-keywords-1)
1535 (defvar org-todo-keywords-for-agenda nil)
1536 (defvar org-done-keywords-for-agenda nil)
1537 (defvar org-not-done-keywords nil)
1538 (make-variable-buffer-local 'org-not-done-keywords)
1539 (defvar org-done-keywords nil)
1540 (make-variable-buffer-local 'org-done-keywords)
1541 (defvar org-todo-heads nil)
1542 (make-variable-buffer-local 'org-todo-heads)
1543 (defvar org-todo-sets nil)
1544 (make-variable-buffer-local 'org-todo-sets)
1545 (defvar org-todo-log-states nil)
1546 (make-variable-buffer-local 'org-todo-log-states)
1547 (defvar org-todo-kwd-alist nil)
1548 (make-variable-buffer-local 'org-todo-kwd-alist)
1549 (defvar org-todo-key-alist nil)
1550 (make-variable-buffer-local 'org-todo-key-alist)
1551 (defvar org-todo-key-trigger nil)
1552 (make-variable-buffer-local 'org-todo-key-trigger)
1554 (defcustom org-todo-interpretation 'sequence
1555 "Controls how TODO keywords are interpreted.
1556 This variable is in principle obsolete and is only used for
1557 backward compatibility, if the interpretation of todo keywords is
1558 not given already in `org-todo-keywords'. See that variable for
1559 more information."
1560 :group 'org-todo
1561 :group 'org-keywords
1562 :type '(choice (const sequence)
1563 (const type)))
1565 (defcustom org-use-fast-todo-selection 'prefix
1566 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1567 This variable describes if and under what circumstances the cycling
1568 mechanism for TODO keywords will be replaced by a single-key, direct
1569 selection scheme.
1571 When nil, fast selection is never used.
1573 When the symbol `prefix', it will be used when `org-todo' is called with
1574 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1575 in an agenda buffer.
1577 When t, fast selection is used by default. In this case, the prefix
1578 argument forces cycling instead.
1580 In all cases, the special interface is only used if access keys have actually
1581 been assigned by the user, i.e. if keywords in the configuration are followed
1582 by a letter in parenthesis, like TODO(t)."
1583 :group 'org-todo
1584 :type '(choice
1585 (const :tag "Never" nil)
1586 (const :tag "By default" t)
1587 (const :tag "Only with C-u C-c C-t" prefix)))
1589 (defcustom org-after-todo-state-change-hook nil
1590 "Hook which is run after the state of a TODO item was changed.
1591 The new state (a string with a TODO keyword, or nil) is available in the
1592 Lisp variable `state'."
1593 :group 'org-todo
1594 :type 'hook)
1596 (defcustom org-log-done nil
1597 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1598 When the state of an entry is changed from nothing or a DONE state to
1599 a not-done TODO state, remove a previous closing date.
1601 This can also be a list of symbols indicating under which conditions
1602 the time stamp recording the action should be annotated with a short note.
1603 Valid members of this list are
1605 done Offer to record a note when marking entries done
1606 state Offer to record a note whenever changing the TODO state
1607 of an item. This is only relevant if TODO keywords are
1608 interpreted as sequence, see variable `org-todo-interpretation'.
1609 When `state' is set, this includes tracking `done'.
1610 clock-out Offer to record a note when clocking out of an item.
1612 A separate window will then pop up and allow you to type a note.
1613 After finishing with C-c C-c, the note will be added directly after the
1614 timestamp, as a plain list item. See also the variable
1615 `org-log-note-headings'.
1617 Logging can also be configured on a per-file basis by adding one of
1618 the following lines anywhere in the buffer:
1620 #+STARTUP: logdone
1621 #+STARTUP: nologging
1622 #+STARTUP: lognotedone
1623 #+STARTUP: lognotestate
1624 #+STARTUP: lognoteclock-out
1626 You can have local logging settings for a subtree by setting the LOGGING
1627 property to one or more of these keywords."
1628 :group 'org-todo
1629 :group 'org-progress
1630 :type '(choice
1631 (const :tag "off" nil)
1632 (const :tag "on" t)
1633 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1634 (const :tag "when item is marked DONE" done)
1635 (const :tag "when TODO state changes" state)
1636 (const :tag "when clocking out" clock-out))))
1638 (defcustom org-log-done-with-time t
1639 "Non-nil means, the CLOSED time stamp will contain date and time.
1640 When nil, only the date will be recorded."
1641 :group 'org-progress
1642 :type 'boolean)
1644 (defcustom org-log-note-headings
1645 '((done . "CLOSING NOTE %t")
1646 (state . "State %-12s %t")
1647 (clock-out . ""))
1648 "Headings for notes added when clocking out or closing TODO items.
1649 The value is an alist, with the car being a symbol indicating the note
1650 context, and the cdr is the heading to be used. The heading may also be the
1651 empty string.
1652 %t in the heading will be replaced by a time stamp.
1653 %s will be replaced by the new TODO state, in double quotes.
1654 %u will be replaced by the user name.
1655 %U will be replaced by the full user name."
1656 :group 'org-todo
1657 :group 'org-progress
1658 :type '(list :greedy t
1659 (cons (const :tag "Heading when closing an item" done) string)
1660 (cons (const :tag
1661 "Heading when changing todo state (todo sequence only)"
1662 state) string)
1663 (cons (const :tag "Heading when clocking out" clock-out) string)))
1665 (defcustom org-log-states-order-reversed t
1666 "Non-nil means, the latest state change note will be directly after heading.
1667 When nil, the notes will be orderer according to time."
1668 :group 'org-todo
1669 :group 'org-progress
1670 :type 'boolean)
1672 (defcustom org-log-repeat t
1673 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1674 When nil, no note will be taken.
1675 This option can also be set with on a per-file-basis with
1677 #+STARTUP: logrepeat
1678 #+STARTUP: nologrepeat
1680 You can have local logging settings for a subtree by setting the LOGGING
1681 property to one or more of these keywords."
1682 :group 'org-todo
1683 :group 'org-progress
1684 :type 'boolean)
1686 (defcustom org-clock-into-drawer 2
1687 "Should clocking info be wrapped into a drawer?
1688 When t, clocking info will always be inserted into a :CLOCK: drawer.
1689 If necessary, the drawer will be created.
1690 When nil, the drawer will not be created, but used when present.
1691 When an integer and the number of clocking entries in an item
1692 reaches or exceeds this number, a drawer will be created."
1693 :group 'org-todo
1694 :group 'org-progress
1695 :type '(choice
1696 (const :tag "Always" t)
1697 (const :tag "Only when drawer exists" nil)
1698 (integer :tag "When at least N clock entries")))
1700 (defcustom org-clock-out-when-done t
1701 "When t, the clock will be stopped when the relevant entry is marked DONE.
1702 Nil means, clock will keep running until stopped explicitly with
1703 `C-c C-x C-o', or until the clock is started in a different item."
1704 :group 'org-progress
1705 :type 'boolean)
1707 (defgroup org-priorities nil
1708 "Priorities in Org-mode."
1709 :tag "Org Priorities"
1710 :group 'org-todo)
1712 (defcustom org-highest-priority ?A
1713 "The highest priority of TODO items. A character like ?A, ?B etc.
1714 Must have a smaller ASCII number than `org-lowest-priority'."
1715 :group 'org-priorities
1716 :type 'character)
1718 (defcustom org-lowest-priority ?C
1719 "The lowest priority of TODO items. A character like ?A, ?B etc.
1720 Must have a larger ASCII number than `org-highest-priority'."
1721 :group 'org-priorities
1722 :type 'character)
1724 (defcustom org-default-priority ?B
1725 "The default priority of TODO items.
1726 This is the priority an item get if no explicit priority is given."
1727 :group 'org-priorities
1728 :type 'character)
1730 (defcustom org-priority-start-cycle-with-default t
1731 "Non-nil means, start with default priority when starting to cycle.
1732 When this is nil, the first step in the cycle will be (depending on the
1733 command used) one higher or lower that the default priority."
1734 :group 'org-priorities
1735 :type 'boolean)
1737 (defgroup org-time nil
1738 "Options concerning time stamps and deadlines in Org-mode."
1739 :tag "Org Time"
1740 :group 'org)
1742 (defcustom org-insert-labeled-timestamps-at-point nil
1743 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1744 When nil, these labeled time stamps are forces into the second line of an
1745 entry, just after the headline. When scheduling from the global TODO list,
1746 the time stamp will always be forced into the second line."
1747 :group 'org-time
1748 :type 'boolean)
1750 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1751 "Formats for `format-time-string' which are used for time stamps.
1752 It is not recommended to change this constant.")
1754 (defcustom org-time-stamp-rounding-minutes 0
1755 "Number of minutes to round time stamps to upon insertion.
1756 When zero, insert the time unmodified. Useful rounding numbers
1757 should be factors of 60, so for example 5, 10, 15.
1758 When this is not zero, you can still force an exact time-stamp by using
1759 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1760 :group 'org-time
1761 :type 'integer)
1763 (defcustom org-display-custom-times nil
1764 "Non-nil means, overlay custom formats over all time stamps.
1765 The formats are defined through the variable `org-time-stamp-custom-formats'.
1766 To turn this on on a per-file basis, insert anywhere in the file:
1767 #+STARTUP: customtime"
1768 :group 'org-time
1769 :set 'set-default
1770 :type 'sexp)
1771 (make-variable-buffer-local 'org-display-custom-times)
1773 (defcustom org-time-stamp-custom-formats
1774 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1775 "Custom formats for time stamps. See `format-time-string' for the syntax.
1776 These are overlayed over the default ISO format if the variable
1777 `org-display-custom-times' is set. Time like %H:%M should be at the
1778 end of the second format."
1779 :group 'org-time
1780 :type 'sexp)
1782 (defun org-time-stamp-format (&optional long inactive)
1783 "Get the right format for a time string."
1784 (let ((f (if long (cdr org-time-stamp-formats)
1785 (car org-time-stamp-formats))))
1786 (if inactive
1787 (concat "[" (substring f 1 -1) "]")
1788 f)))
1790 (defcustom org-popup-calendar-for-date-prompt t
1791 "Non-nil means, pop up a calendar when prompting for a date.
1792 In the calendar, the date can be selected with mouse-1. However, the
1793 minibuffer will also be active, and you can simply enter the date as well.
1794 When nil, only the minibuffer will be available."
1795 :group 'org-time
1796 :type 'boolean)
1798 (defcustom org-edit-timestamp-down-means-later nil
1799 "Non-nil means, S-down will increase the time in a time stamp.
1800 When nil, S-up will increase."
1801 :group 'org-time
1802 :type 'boolean)
1804 (defcustom org-calendar-follow-timestamp-change t
1805 "Non-nil means, make the calendar window follow timestamp changes.
1806 When a timestamp is modified and the calendar window is visible, it will be
1807 moved to the new date."
1808 :group 'org-time
1809 :type 'boolean)
1811 (defgroup org-tags nil
1812 "Options concerning tags in Org-mode."
1813 :tag "Org Tags"
1814 :group 'org)
1816 (defcustom org-tag-alist nil
1817 "List of tags allowed in Org-mode files.
1818 When this list is nil, Org-mode will base TAG input on what is already in the
1819 buffer.
1820 The value of this variable is an alist, the car of each entry must be a
1821 keyword as a string, the cdr may be a character that is used to select
1822 that tag through the fast-tag-selection interface.
1823 See the manual for details."
1824 :group 'org-tags
1825 :type '(repeat
1826 (choice
1827 (cons (string :tag "Tag name")
1828 (character :tag "Access char"))
1829 (const :tag "Start radio group" (:startgroup))
1830 (const :tag "End radio group" (:endgroup)))))
1832 (defcustom org-use-fast-tag-selection 'auto
1833 "Non-nil means, use fast tag selection scheme.
1834 This is a special interface to select and deselect tags with single keys.
1835 When nil, fast selection is never used.
1836 When the symbol `auto', fast selection is used if and only if selection
1837 characters for tags have been configured, either through the variable
1838 `org-tag-alist' or through a #+TAGS line in the buffer.
1839 When t, fast selection is always used and selection keys are assigned
1840 automatically if necessary."
1841 :group 'org-tags
1842 :type '(choice
1843 (const :tag "Always" t)
1844 (const :tag "Never" nil)
1845 (const :tag "When selection characters are configured" 'auto)))
1847 (defcustom org-fast-tag-selection-single-key nil
1848 "Non-nil means, fast tag selection exits after first change.
1849 When nil, you have to press RET to exit it.
1850 During fast tag selection, you can toggle this flag with `C-c'.
1851 This variable can also have the value `expert'. In this case, the window
1852 displaying the tags menu is not even shown, until you press C-c again."
1853 :group 'org-tags
1854 :type '(choice
1855 (const :tag "No" nil)
1856 (const :tag "Yes" t)
1857 (const :tag "Expert" expert)))
1859 (defvar org-fast-tag-selection-include-todo nil
1860 "Non-nil means, fast tags selection interface will also offer TODO states.
1861 This is an undocumented feature, you should not rely on it.")
1863 (defcustom org-tags-column -80
1864 "The column to which tags should be indented in a headline.
1865 If this number is positive, it specifies the column. If it is negative,
1866 it means that the tags should be flushright to that column. For example,
1867 -80 works well for a normal 80 character screen."
1868 :group 'org-tags
1869 :type 'integer)
1871 (defcustom org-auto-align-tags t
1872 "Non-nil means, realign tags after pro/demotion of TODO state change.
1873 These operations change the length of a headline and therefore shift
1874 the tags around. With this options turned on, after each such operation
1875 the tags are again aligned to `org-tags-column'."
1876 :group 'org-tags
1877 :type 'boolean)
1879 (defcustom org-use-tag-inheritance t
1880 "Non-nil means, tags in levels apply also for sublevels.
1881 When nil, only the tags directly given in a specific line apply there.
1882 If you turn off this option, you very likely want to turn on the
1883 companion option `org-tags-match-list-sublevels'."
1884 :group 'org-tags
1885 :type 'boolean)
1887 (defcustom org-tags-match-list-sublevels nil
1888 "Non-nil means list also sublevels of headlines matching tag search.
1889 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1890 the sublevels of a headline matching a tag search often also match
1891 the same search. Listing all of them can create very long lists.
1892 Setting this variable to nil causes subtrees of a match to be skipped.
1893 This option is off by default, because inheritance in on. If you turn
1894 inheritance off, you very likely want to turn this option on.
1896 As a special case, if the tag search is restricted to TODO items, the
1897 value of this variable is ignored and sublevels are always checked, to
1898 make sure all corresponding TODO items find their way into the list."
1899 :group 'org-tags
1900 :type 'boolean)
1902 (defvar org-tags-history nil
1903 "History of minibuffer reads for tags.")
1904 (defvar org-last-tags-completion-table nil
1905 "The last used completion table for tags.")
1906 (defvar org-after-tags-change-hook nil
1907 "Hook that is run after the tags in a line have changed.")
1909 (defgroup org-properties nil
1910 "Options concerning properties in Org-mode."
1911 :tag "Org Properties"
1912 :group 'org)
1914 (defcustom org-property-format "%-10s %s"
1915 "How property key/value pairs should be formatted by `indent-line'.
1916 When `indent-line' hits a property definition, it will format the line
1917 according to this format, mainly to make sure that the values are
1918 lined-up with respect to each other."
1919 :group 'org-properties
1920 :type 'string)
1922 (defcustom org-use-property-inheritance nil
1923 "Non-nil means, properties apply also for sublevels.
1924 This can cause significant overhead when doing a search, so this is turned
1925 off by default.
1926 When nil, only the properties directly given in the current entry count.
1928 However, note that some special properties use inheritance under special
1929 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1930 and the properties ending in \"_ALL\" when they are used as descriptor
1931 for valid values of a property."
1932 :group 'org-properties
1933 :type 'boolean)
1935 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1936 "The default column format, if no other format has been defined.
1937 This variable can be set on the per-file basis by inserting a line
1939 #+COLUMNS: %25ITEM ....."
1940 :group 'org-properties
1941 :type 'string)
1943 (defcustom org-global-properties nil
1944 "List of property/value pairs that can be inherited by any entry.
1945 You can set buffer-local values for this by adding lines like
1947 #+PROPERTY: NAME VALUE"
1948 :group 'org-properties
1949 :type '(repeat
1950 (cons (string :tag "Property")
1951 (string :tag "Value"))))
1953 (defvar org-local-properties nil
1954 "List of property/value pairs that can be inherited by any entry.
1955 Valid for the current buffer.
1956 This variable is populated from #+PROPERTY lines.")
1958 (defgroup org-agenda nil
1959 "Options concerning agenda views in Org-mode."
1960 :tag "Org Agenda"
1961 :group 'org)
1963 (defvar org-category nil
1964 "Variable used by org files to set a category for agenda display.
1965 Such files should use a file variable to set it, for example
1967 # -*- mode: org; org-category: \"ELisp\"
1969 or contain a special line
1971 #+CATEGORY: ELisp
1973 If the file does not specify a category, then file's base name
1974 is used instead.")
1975 (make-variable-buffer-local 'org-category)
1977 (defcustom org-agenda-files nil
1978 "The files to be used for agenda display.
1979 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1980 \\[org-remove-file]. You can also use customize to edit the list.
1982 If the value of the variable is not a list but a single file name, then
1983 the list of agenda files is actually stored and maintained in that file, one
1984 agenda file per line."
1985 :group 'org-agenda
1986 :type '(choice
1987 (repeat :tag "List of files" file)
1988 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1990 (defcustom org-agenda-skip-unavailable-files nil
1991 "t means to just skip non-reachable files in `org-agenda-files'.
1992 Nil means to remove them, after a query, from the list."
1993 :group 'org-agenda
1994 :type 'boolean)
1996 (defcustom org-agenda-multi-occur-extra-files nil
1997 "List of extra files to be searched by `org-occur-in-agenda-files'.
1998 The files in `org-agenda-files' are always searched."
1999 :group 'org-agenda
2000 :type '(repeat file))
2002 (defcustom org-agenda-confirm-kill 1
2003 "When set, remote killing from the agenda buffer needs confirmation.
2004 When t, a confirmation is always needed. When a number N, confirmation is
2005 only needed when the text to be killed contains more than N non-white lines."
2006 :group 'org-agenda
2007 :type '(choice
2008 (const :tag "Never" nil)
2009 (const :tag "Always" t)
2010 (number :tag "When more than N lines")))
2012 (defcustom org-calendar-to-agenda-key [?c]
2013 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2014 The command `org-calendar-goto-agenda' will be bound to this key. The
2015 default is the character `c' because then `c' can be used to switch back and
2016 forth between agenda and calendar."
2017 :group 'org-agenda
2018 :type 'sexp)
2020 (defcustom org-agenda-compact-blocks nil
2021 "Non-nil means, make the block agenda more compact.
2022 This is done by leaving out unnecessary lines."
2023 :group 'org-agenda
2024 :type nil)
2026 (defgroup org-agenda-export nil
2027 "Options concerning exporting agenda views in Org-mode."
2028 :tag "Org Agenda Export"
2029 :group 'org-agenda)
2031 (defcustom org-agenda-with-colors t
2032 "Non-nil means, use colors in agenda views."
2033 :group 'org-agenda-export
2034 :type 'boolean)
2036 (defcustom org-agenda-exporter-settings nil
2037 "Alist of variable/value pairs that should be active during agenda export.
2038 This is a good place to set uptions for ps-print and for htmlize."
2039 :group 'org-agenda-export
2040 :type '(repeat
2041 (list
2042 (variable)
2043 (sexp :tag "Value"))))
2045 (defcustom org-agenda-export-html-style ""
2046 "The style specification for exported HTML Agenda files.
2047 If this variable contains a string, it will replace the default <style>
2048 section as produced by `htmlize'.
2049 Since there are different ways of setting style information, this variable
2050 needs to contain the full HTML structure to provide a style, including the
2051 surrounding HTML tags. The style specifications should include definitions
2052 the fonts used by the agenda, here is an example:
2054 <style type=\"text/css\">
2055 p { font-weight: normal; color: gray; }
2056 .org-agenda-structure {
2057 font-size: 110%;
2058 color: #003399;
2059 font-weight: 600;
2061 .org-todo {
2062 color: #cc6666;Week-agenda:
2063 font-weight: bold;
2065 .org-done {
2066 color: #339933;
2068 .title { text-align: center; }
2069 .todo, .deadline { color: red; }
2070 .done { color: green; }
2071 </style>
2073 or, if you want to keep the style in a file,
2075 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2077 As the value of this option simply gets inserted into the HTML <head> header,
2078 you can \"misuse\" it to also add other text to the header. However,
2079 <style>...</style> is required, if not present the variable will be ignored."
2080 :group 'org-agenda-export
2081 :group 'org-export-html
2082 :type 'string)
2084 (defgroup org-agenda-custom-commands nil
2085 "Options concerning agenda views in Org-mode."
2086 :tag "Org Agenda Custom Commands"
2087 :group 'org-agenda)
2089 (defcustom org-agenda-custom-commands nil
2090 "Custom commands for the agenda.
2091 These commands will be offered on the splash screen displayed by the
2092 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2094 (key type match options files)
2096 key The key (a single char as a string) to be associated with the command.
2097 type The command type, any of the following symbols:
2098 todo Entries with a specific TODO keyword, in all agenda files.
2099 tags Tags match in all agenda files.
2100 tags-todo Tags match in all agenda files, TODO entries only.
2101 todo-tree Sparse tree of specific TODO keyword in *current* file.
2102 tags-tree Sparse tree with all tags matches in *current* file.
2103 occur-tree Occur sparse tree for *current* file.
2104 match What to search for:
2105 - a single keyword for TODO keyword searches
2106 - a tags match expression for tags searches
2107 - a regular expression for occur searches
2108 options A list of option settings, similar to that in a let form, so like
2109 this: ((opt1 val1) (opt2 val2) ...)
2110 files A list of files file to write the produced agenda buffer to
2111 with the command `org-store-agenda-views'.
2112 If a file name ends in \".html\", an HTML version of the buffer
2113 is written out. If it ends in \".ps\", a postscript version is
2114 produced. Otherwide, only the plain text is written to the file.
2116 You can also define a set of commands, to create a composite agenda buffer.
2117 In this case, an entry looks like this:
2119 (key desc (cmd1 cmd2 ...) general-options file)
2121 where
2123 desc A description string to be displayed in the dispatcher menu.
2124 cmd An agenda command, similar to the above. However, tree commands
2125 are no allowed, but instead you can get agenda and global todo list.
2126 So valid commands for a set are:
2127 (agenda)
2128 (alltodo)
2129 (stuck)
2130 (todo \"match\" options files)
2131 (tags \"match\" options files)
2132 (tags-todo \"match\" options files)
2134 Each command can carry a list of options, and another set of options can be
2135 given for the whole set of commands. Individual command options take
2136 precedence over the general options."
2137 :group 'org-agenda-custom-commands
2138 :type '(repeat
2139 (choice :value ("a" tags "" nil)
2140 (list :tag "Single command"
2141 (string :tag "Key")
2142 (choice
2143 (const :tag "Agenda" agenda)
2144 (const :tag "TODO list" alltodo)
2145 (const :tag "Stuck projects" stuck)
2146 (const :tag "Tags search (all agenda files)" tags)
2147 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2148 (const :tag "TODO keyword search (all agenda files)" todo)
2149 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2150 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2151 (const :tag "Occur tree (current buffer)" occur-tree)
2152 (symbol :tag "Other, user-defined function"))
2153 (string :tag "Match")
2154 (repeat :tag "Local options"
2155 (list (variable :tag "Option") (sexp :tag "Value")))
2156 (option (repeat :tag "Export" (file :tag "Export to"))))
2157 (list :tag "Command series, all agenda files"
2158 (string :tag "Key")
2159 (string :tag "Description")
2160 (repeat
2161 (choice
2162 (const :tag "Agenda" (agenda))
2163 (const :tag "TODO list" (alltodo))
2164 (const :tag "Stuck projects" (stuck))
2165 (list :tag "Tags search"
2166 (const :format "" tags)
2167 (string :tag "Match")
2168 (repeat :tag "Local options"
2169 (list (variable :tag "Option")
2170 (sexp :tag "Value"))))
2172 (list :tag "Tags search, TODO entries only"
2173 (const :format "" tags-todo)
2174 (string :tag "Match")
2175 (repeat :tag "Local options"
2176 (list (variable :tag "Option")
2177 (sexp :tag "Value"))))
2179 (list :tag "TODO keyword search"
2180 (const :format "" todo)
2181 (string :tag "Match")
2182 (repeat :tag "Local options"
2183 (list (variable :tag "Option")
2184 (sexp :tag "Value"))))
2186 (list :tag "Other, user-defined function"
2187 (symbol :tag "function")
2188 (string :tag "Match")
2189 (repeat :tag "Local options"
2190 (list (variable :tag "Option")
2191 (sexp :tag "Value"))))))
2193 (repeat :tag "General options"
2194 (list (variable :tag "Option")
2195 (sexp :tag "Value")))
2196 (option (repeat :tag "Export" (file :tag "Export to")))))))
2198 (defcustom org-stuck-projects
2199 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2200 "How to identify stuck projects.
2201 This is a list of four items:
2202 1. A tags/todo matcher string that is used to identify a project.
2203 The entire tree below a headline matched by this is considered one project.
2204 2. A list of TODO keywords identifying non-stuck projects.
2205 If the project subtree contains any headline with one of these todo
2206 keywords, the project is considered to be not stuck. If you specify
2207 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2208 3. A list of tags identifying non-stuck projects.
2209 If the project subtree contains any headline with one of these tags,
2210 the project is considered to be not stuck. If you specify \"*\" as
2211 a tag, any tag will mark the project unstuck.
2212 4. An arbitrary regular expression matching non-stuck projects.
2214 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2215 or `C-c a #' to produce the list."
2216 :group 'org-agenda-custom-commands
2217 :type '(list
2218 (string :tag "Tags/TODO match to identify a project")
2219 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2220 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2221 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2224 (defgroup org-agenda-skip nil
2225 "Options concerning skipping parts of agenda files."
2226 :tag "Org Agenda Skip"
2227 :group 'org-agenda)
2229 (defcustom org-agenda-todo-list-sublevels t
2230 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2231 When nil, the sublevels of a TODO entry are not checked, resulting in
2232 potentially much shorter TODO lists."
2233 :group 'org-agenda-skip
2234 :group 'org-todo
2235 :type 'boolean)
2237 (defcustom org-agenda-todo-ignore-scheduled nil
2238 "Non-nil means, don't show scheduled entries in the global todo list.
2239 The idea behind this is that by scheduling it, you have already taken care
2240 of this item."
2241 :group 'org-agenda-skip
2242 :group 'org-todo
2243 :type 'boolean)
2245 (defcustom org-agenda-todo-ignore-deadlines nil
2246 "Non-nil means, don't show near deadline entries in the global todo list.
2247 Near means closer than `org-deadline-warning-days' days.
2248 The idea behind this is that such items will appear in the agenda anyway."
2249 :group 'org-agenda-skip
2250 :group 'org-todo
2251 :type 'boolean)
2253 (defcustom org-agenda-skip-scheduled-if-done nil
2254 "Non-nil means don't show scheduled items in agenda when they are done.
2255 This is relevant for the daily/weekly agenda, not for the TODO list. And
2256 it applies only to the actual date of the scheduling. Warnings about
2257 an item with a past scheduling dates are always turned off when the item
2258 is DONE."
2259 :group 'org-agenda-skip
2260 :type 'boolean)
2262 (defcustom org-agenda-skip-deadline-if-done nil
2263 "Non-nil means don't show deadines when the corresponding item is done.
2264 When nil, the deadline is still shown and should give you a happy feeling.
2265 This is relevant for the daily/weekly agenda. And it applied only to the
2266 actualy date of the deadline. Warnings about approching and past-due
2267 deadlines are always turned off when the item is DONE."
2268 :group 'org-agenda-skip
2269 :type 'boolean)
2271 (defcustom org-timeline-show-empty-dates 3
2272 "Non-nil means, `org-timeline' also shows dates without an entry.
2273 When nil, only the days which actually have entries are shown.
2274 When t, all days between the first and the last date are shown.
2275 When an integer, show also empty dates, but if there is a gap of more than
2276 N days, just insert a special line indicating the size of the gap."
2277 :group 'org-agenda-skip
2278 :type '(choice
2279 (const :tag "None" nil)
2280 (const :tag "All" t)
2281 (number :tag "at most")))
2284 (defgroup org-agenda-startup nil
2285 "Options concerning initial settings in the Agenda in Org Mode."
2286 :tag "Org Agenda Startup"
2287 :group 'org-agenda)
2289 (defcustom org-finalize-agenda-hook nil
2290 "Hook run just before displaying an agenda buffer."
2291 :group 'org-agenda-startup
2292 :type 'hook)
2294 (defcustom org-agenda-mouse-1-follows-link nil
2295 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2296 A longer mouse click will still set point. Does not wortk on XEmacs.
2297 Needs to be set before org.el is loaded."
2298 :group 'org-agenda-startup
2299 :type 'boolean)
2301 (defcustom org-agenda-start-with-follow-mode nil
2302 "The initial value of follow-mode in a newly created agenda window."
2303 :group 'org-agenda-startup
2304 :type 'boolean)
2306 (defgroup org-agenda-windows nil
2307 "Options concerning the windows used by the Agenda in Org Mode."
2308 :tag "Org Agenda Windows"
2309 :group 'org-agenda)
2311 (defcustom org-agenda-window-setup 'reorganize-frame
2312 "How the agenda buffer should be displayed.
2313 Possible values for this option are:
2315 current-window Show agenda in the current window, keeping all other windows.
2316 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2317 other-window Use `switch-to-buffer-other-window' to display agenda.
2318 reorganize-frame Show only two windows on the current frame, the current
2319 window and the agenda.
2320 See also the variable `org-agenda-restore-windows-after-quit'."
2321 :group 'org-agenda-windows
2322 :type '(choice
2323 (const current-window)
2324 (const other-frame)
2325 (const other-window)
2326 (const reorganize-frame)))
2328 (defcustom org-agenda-restore-windows-after-quit nil
2329 "Non-nil means, restore window configuration open exiting agenda.
2330 Before the window configuration is changed for displaying the agenda,
2331 the current status is recorded. When the agenda is exited with
2332 `q' or `x' and this option is set, the old state is restored. If
2333 `org-agenda-window-setup' is `other-frame', the value of this
2334 option will be ignored.."
2335 :group 'org-agenda-windows
2336 :type 'boolean)
2338 (defcustom org-indirect-buffer-display 'other-window
2339 "How should indirect tree buffers be displayed?
2340 This applies to indirect buffers created with the commands
2341 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2342 Valid values are:
2343 current-window Display in the current window
2344 other-window Just display in another window.
2345 dedicated-frame Create one new frame, and re-use it each time.
2346 new-frame Make a new frame each time."
2347 :group 'org-structure
2348 :group 'org-agenda-windows
2349 :type '(choice
2350 (const :tag "In current window" current-window)
2351 (const :tag "In current frame, other window" other-window)
2352 (const :tag "Each time a new frame" new-frame)
2353 (const :tag "One dedicated frame" dedicated-frame)))
2355 (defgroup org-agenda-daily/weekly nil
2356 "Options concerning the daily/weekly agenda."
2357 :tag "Org Agenda Daily/Weekly"
2358 :group 'org-agenda)
2360 (defcustom org-agenda-ndays 7
2361 "Number of days to include in overview display.
2362 Should be 1 or 7."
2363 :group 'org-agenda-daily/weekly
2364 :type 'number)
2366 (defcustom org-agenda-start-on-weekday 1
2367 "Non-nil means, start the overview always on the specified weekday.
2368 0 denotes Sunday, 1 denotes Monday etc.
2369 When nil, always start on the current day."
2370 :group 'org-agenda-daily/weekly
2371 :type '(choice (const :tag "Today" nil)
2372 (number :tag "Weekday No.")))
2374 (defcustom org-agenda-show-all-dates t
2375 "Non-nil means, `org-agenda' shows every day in the selected range.
2376 When nil, only the days which actually have entries are shown."
2377 :group 'org-agenda-daily/weekly
2378 :type 'boolean)
2380 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2381 "Format string for displaying dates in the agenda.
2382 Used by the daily/weekly agenda and by the timeline. This should be
2383 a format string understood by `format-time-string', or a function returning
2384 the formatted date as a string. The function must take a single argument,
2385 a calendar-style date list like (month day year)."
2386 :group 'org-agenda-daily/weekly
2387 :type '(choice
2388 (string :tag "Format string")
2389 (function :tag "Function")))
2391 (defun org-agenda-format-date-aligned (date)
2392 "Format a date string for display in the daily/weekly agenda, or timeline.
2393 This function makes sure that dates are aligned for easy reading."
2394 (format "%-9s %2d %s %4d"
2395 (calendar-day-name date)
2396 (extract-calendar-day date)
2397 (calendar-month-name (extract-calendar-month date))
2398 (extract-calendar-year date)))
2400 (defcustom org-agenda-include-diary nil
2401 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2402 :group 'org-agenda-daily/weekly
2403 :type 'boolean)
2405 (defcustom org-agenda-include-all-todo nil
2406 "Set means weekly/daily agenda will always contain all TODO entries.
2407 The TODO entries will be listed at the top of the agenda, before
2408 the entries for specific days."
2409 :group 'org-agenda-daily/weekly
2410 :type 'boolean)
2412 (defcustom org-agenda-repeating-timestamp-show-all t
2413 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2414 When nil, only one occurence is shown, either today or the
2415 nearest into the future."
2416 :group 'org-agenda-daily/weekly
2417 :type 'boolean)
2419 (defcustom org-deadline-warning-days 14
2420 "No. of days before expiration during which a deadline becomes active.
2421 This variable governs the display in sparse trees and in the agenda.
2422 When negative, it means use this number (the absolute value of it)
2423 even if a deadline has a different individual lead time specified."
2424 :group 'org-time
2425 :group 'org-agenda-daily/weekly
2426 :type 'number)
2428 (defcustom org-scheduled-past-days 10000
2429 "No. of days to continue listing scheduled items that are not marked DONE.
2430 When an item is scheduled on a date, it shows up in the agenda on this
2431 day and will be listed until it is marked done for the number of days
2432 given here."
2433 :group 'org-agenda-daily/weekly
2434 :type 'number)
2436 (defgroup org-agenda-time-grid nil
2437 "Options concerning the time grid in the Org-mode Agenda."
2438 :tag "Org Agenda Time Grid"
2439 :group 'org-agenda)
2441 (defcustom org-agenda-use-time-grid t
2442 "Non-nil means, show a time grid in the agenda schedule.
2443 A time grid is a set of lines for specific times (like every two hours between
2444 8:00 and 20:00). The items scheduled for a day at specific times are
2445 sorted in between these lines.
2446 For details about when the grid will be shown, and what it will look like, see
2447 the variable `org-agenda-time-grid'."
2448 :group 'org-agenda-time-grid
2449 :type 'boolean)
2451 (defcustom org-agenda-time-grid
2452 '((daily today require-timed)
2453 "----------------"
2454 (800 1000 1200 1400 1600 1800 2000))
2456 "The settings for time grid for agenda display.
2457 This is a list of three items. The first item is again a list. It contains
2458 symbols specifying conditions when the grid should be displayed:
2460 daily if the agenda shows a single day
2461 weekly if the agenda shows an entire week
2462 today show grid on current date, independent of daily/weekly display
2463 require-timed show grid only if at least one item has a time specification
2465 The second item is a string which will be places behing the grid time.
2467 The third item is a list of integers, indicating the times that should have
2468 a grid line."
2469 :group 'org-agenda-time-grid
2470 :type
2471 '(list
2472 (set :greedy t :tag "Grid Display Options"
2473 (const :tag "Show grid in single day agenda display" daily)
2474 (const :tag "Show grid in weekly agenda display" weekly)
2475 (const :tag "Always show grid for today" today)
2476 (const :tag "Show grid only if any timed entries are present"
2477 require-timed)
2478 (const :tag "Skip grid times already present in an entry"
2479 remove-match))
2480 (string :tag "Grid String")
2481 (repeat :tag "Grid Times" (integer :tag "Time"))))
2483 (defgroup org-agenda-sorting nil
2484 "Options concerning sorting in the Org-mode Agenda."
2485 :tag "Org Agenda Sorting"
2486 :group 'org-agenda)
2488 (let ((sorting-choice
2489 '(choice
2490 (const time-up) (const time-down)
2491 (const category-keep) (const category-up) (const category-down)
2492 (const tag-down) (const tag-up)
2493 (const priority-up) (const priority-down))))
2495 (defcustom org-agenda-sorting-strategy
2496 '((agenda time-up category-keep priority-down)
2497 (todo category-keep priority-down)
2498 (tags category-keep priority-down))
2499 "Sorting structure for the agenda items of a single day.
2500 This is a list of symbols which will be used in sequence to determine
2501 if an entry should be listed before another entry. The following
2502 symbols are recognized:
2504 time-up Put entries with time-of-day indications first, early first
2505 time-down Put entries with time-of-day indications first, late first
2506 category-keep Keep the default order of categories, corresponding to the
2507 sequence in `org-agenda-files'.
2508 category-up Sort alphabetically by category, A-Z.
2509 category-down Sort alphabetically by category, Z-A.
2510 tag-up Sort alphabetically by last tag, A-Z.
2511 tag-down Sort alphabetically by last tag, Z-A.
2512 priority-up Sort numerically by priority, high priority last.
2513 priority-down Sort numerically by priority, high priority first.
2515 The different possibilities will be tried in sequence, and testing stops
2516 if one comparison returns a \"not-equal\". For example, the default
2517 '(time-up category-keep priority-down)
2518 means: Pull out all entries having a specified time of day and sort them,
2519 in order to make a time schedule for the current day the first thing in the
2520 agenda listing for the day. Of the entries without a time indication, keep
2521 the grouped in categories, don't sort the categories, but keep them in
2522 the sequence given in `org-agenda-files'. Within each category sort by
2523 priority.
2525 Leaving out `category-keep' would mean that items will be sorted across
2526 categories by priority."
2527 :group 'org-agenda-sorting
2528 :type `(choice
2529 (repeat :tag "General" ,sorting-choice)
2530 (list :tag "Individually"
2531 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2532 (repeat ,sorting-choice))
2533 (cons (const :tag "Strategy for TODO lists" todo)
2534 (repeat ,sorting-choice))
2535 (cons (const :tag "Strategy for Tags matches" tags)
2536 (repeat ,sorting-choice))))))
2538 (defcustom org-sort-agenda-notime-is-late t
2539 "Non-nil means, items without time are considered late.
2540 This is only relevant for sorting. When t, items which have no explicit
2541 time like 15:30 will be considered as 99:01, i.e. later than any items which
2542 do have a time. When nil, the default time is before 0:00. You can use this
2543 option to decide if the schedule for today should come before or after timeless
2544 agenda entries."
2545 :group 'org-agenda-sorting
2546 :type 'boolean)
2548 (defgroup org-agenda-line-format nil
2549 "Options concerning the entry prefix in the Org-mode agenda display."
2550 :tag "Org Agenda Line Format"
2551 :group 'org-agenda)
2553 (defcustom org-agenda-prefix-format
2554 '((agenda . " %-12:c%?-12t% s")
2555 (timeline . " % s")
2556 (todo . " %-12:c")
2557 (tags . " %-12:c"))
2558 "Format specifications for the prefix of items in the agenda views.
2559 An alist with four entries, for the different agenda types. The keys to the
2560 sublists are `agenda', `timeline', `todo', and `tags'. The values
2561 are format strings.
2562 This format works similar to a printf format, with the following meaning:
2564 %c the category of the item, \"Diary\" for entries from the diary, or
2565 as given by the CATEGORY keyword or derived from the file name.
2566 %T the *last* tag of the item. Last because inherited tags come
2567 first in the list.
2568 %t the time-of-day specification if one applies to the entry, in the
2569 format HH:MM
2570 %s Scheduling/Deadline information, a short string
2572 All specifiers work basically like the standard `%s' of printf, but may
2573 contain two additional characters: A question mark just after the `%' and
2574 a whitespace/punctuation character just before the final letter.
2576 If the first character after `%' is a question mark, the entire field
2577 will only be included if the corresponding value applies to the
2578 current entry. This is useful for fields which should have fixed
2579 width when present, but zero width when absent. For example,
2580 \"%?-12t\" will result in a 12 character time field if a time of the
2581 day is specified, but will completely disappear in entries which do
2582 not contain a time.
2584 If there is punctuation or whitespace character just before the final
2585 format letter, this character will be appended to the field value if
2586 the value is not empty. For example, the format \"%-12:c\" leads to
2587 \"Diary: \" if the category is \"Diary\". If the category were be
2588 empty, no additional colon would be interted.
2590 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2591 - Indent the line with two space characters
2592 - Give the category in a 12 chars wide field, padded with whitespace on
2593 the right (because of `-'). Append a colon if there is a category
2594 (because of `:').
2595 - If there is a time-of-day, put it into a 12 chars wide field. If no
2596 time, don't put in an empty field, just skip it (because of '?').
2597 - Finally, put the scheduling information and append a whitespace.
2599 As another example, if you don't want the time-of-day of entries in
2600 the prefix, you could use:
2602 (setq org-agenda-prefix-format \" %-11:c% s\")
2604 See also the variables `org-agenda-remove-times-when-in-prefix' and
2605 `org-agenda-remove-tags'."
2606 :type '(choice
2607 (string :tag "General format")
2608 (list :greedy t :tag "View dependent"
2609 (cons (const agenda) (string :tag "Format"))
2610 (cons (const timeline) (string :tag "Format"))
2611 (cons (const todo) (string :tag "Format"))
2612 (cons (const tags) (string :tag "Format"))))
2613 :group 'org-agenda-line-format)
2615 (defvar org-prefix-format-compiled nil
2616 "The compiled version of the most recently used prefix format.
2617 See the variable `org-agenda-prefix-format'.")
2619 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2620 "Text preceeding scheduled items in the agenda view.
2621 THis is a list with two strings. The first applies when the item is
2622 scheduled on the current day. The second applies when it has been scheduled
2623 previously, it may contain a %d to capture how many days ago the item was
2624 scheduled."
2625 :group 'org-agenda-line-format
2626 :type '(list
2627 (string :tag "Scheduled today ")
2628 (string :tag "Scheduled previously")))
2630 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2631 "Text preceeding deadline items in the agenda view.
2632 This is a list with two strings. The first applies when the item has its
2633 deadline on the current day. The second applies when it is in the past or
2634 in the future, it may contain %d to capture how many days away the deadline
2635 is (was)."
2636 :group 'org-agenda-line-format
2637 :type '(list
2638 (string :tag "Deadline today ")
2639 (string :tag "Deadline relative")))
2641 (defcustom org-agenda-remove-times-when-in-prefix t
2642 "Non-nil means, remove duplicate time specifications in agenda items.
2643 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2644 time-of-day specification in a headline or diary entry is extracted and
2645 placed into the prefix. If this option is non-nil, the original specification
2646 \(a timestamp or -range, or just a plain time(range) specification like
2647 11:30-4pm) will be removed for agenda display. This makes the agenda less
2648 cluttered.
2649 The option can be t or nil. It may also be the symbol `beg', indicating
2650 that the time should only be removed what it is located at the beginning of
2651 the headline/diary entry."
2652 :group 'org-agenda-line-format
2653 :type '(choice
2654 (const :tag "Always" t)
2655 (const :tag "Never" nil)
2656 (const :tag "When at beginning of entry" beg)))
2659 (defcustom org-agenda-default-appointment-duration nil
2660 "Default duration for appointments that only have a starting time.
2661 When nil, no duration is specified in such cases.
2662 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2663 :group 'org-agenda-line-format
2664 :type '(choice
2665 (integer :tag "Minutes")
2666 (const :tag "No default duration")))
2669 (defcustom org-agenda-remove-tags nil
2670 "Non-nil means, remove the tags from the headline copy in the agenda.
2671 When this is the symbol `prefix', only remove tags when
2672 `org-agenda-prefix-format' contains a `%T' specifier."
2673 :group 'org-agenda-line-format
2674 :type '(choice
2675 (const :tag "Always" t)
2676 (const :tag "Never" nil)
2677 (const :tag "When prefix format contains %T" prefix)))
2679 (if (fboundp 'defvaralias)
2680 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2681 'org-agenda-remove-tags))
2683 (defcustom org-agenda-tags-column -80
2684 "Shift tags in agenda items to this column.
2685 If this number is positive, it specifies the column. If it is negative,
2686 it means that the tags should be flushright to that column. For example,
2687 -80 works well for a normal 80 character screen."
2688 :group 'org-agenda-line-format
2689 :type 'integer)
2691 (if (fboundp 'defvaralias)
2692 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2694 (defcustom org-agenda-fontify-priorities t
2695 "Non-nil means, highlight low and high priorities in agenda.
2696 The highest priority entries are bold, lowest priority italic."
2697 :group 'org-agenda-line-format
2698 :type 'boolean)
2700 (defgroup org-latex nil
2701 "Options for embedding LaTeX code into Org-mode"
2702 :tag "Org LaTeX"
2703 :group 'org)
2705 (defcustom org-format-latex-options
2706 '(:foreground default :background default :scale 1.0
2707 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2708 :matchers ("begin" "$" "$$" "\\(" "\\["))
2709 "Options for creating images from LaTeX fragments.
2710 This is a property list with the following properties:
2711 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2712 `default' means use the forground of the default face.
2713 :background the background color, or \"Transparent\".
2714 `default' means use the background of the default face.
2715 :scale a scaling factor for the size of the images
2716 :html-foreground, :html-background, :html-scale
2717 The same numbers for HTML export.
2718 :matchers a list indicating which matchers should be used to
2719 find LaTeX fragments. Valid members of this list are:
2720 \"begin\" find environments
2721 \"$\" find math expressions surrounded by $...$
2722 \"$$\" find math expressions surrounded by $$....$$
2723 \"\\(\" find math expressions surrounded by \\(...\\)
2724 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2725 :group 'org-latex
2726 :type 'plist)
2728 (defcustom org-format-latex-header "\\documentclass{article}
2729 \\usepackage{fullpage} % do not remove
2730 \\usepackage{amssymb}
2731 \\usepackage[usenames]{color}
2732 \\usepackage{amsmath}
2733 \\usepackage{latexsym}
2734 \\usepackage[mathscr]{eucal}
2735 \\pagestyle{empty} % do not remove"
2736 "The document header used for processing LaTeX fragments."
2737 :group 'org-latex
2738 :type 'string)
2740 (defgroup org-export nil
2741 "Options for exporting org-listings."
2742 :tag "Org Export"
2743 :group 'org)
2745 (defgroup org-export-general nil
2746 "General options for exporting Org-mode files."
2747 :tag "Org Export General"
2748 :group 'org-export)
2750 (defcustom org-export-publishing-directory "."
2751 "Path to the location where exported files should be located.
2752 This path may be relative to the directory where the Org-mode file lives.
2753 The default is to put them into the same directory as the Org-mode file.
2754 The variable may also be an alist with export types `:html', `:ascii',
2755 `:ical', `:LaTeX', or `:xoxo' and the corresponding directories.
2756 If a directory path is relative, it is interpreted relative to the
2757 directory where the exported Org-mode files lives."
2758 :group 'org-export-general
2759 :type '(choice
2760 (directory)
2761 (repeat
2762 (cons
2763 (choice :tag "Type"
2764 (const :html) (const :LaTeX)
2765 (const :ascii) (const :ical) (const :xoxo))
2766 (directory)))))
2768 (defcustom org-export-language-setup
2769 '(("en" "Author" "Date" "Table of Contents")
2770 ("cs" "Autor" "Datum" "Obsah")
2771 ("da" "Ophavsmand" "Dato" "Indhold")
2772 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2773 ("es" "Autor" "Fecha" "\xcdndice")
2774 ("fr" "Auteur" "Date" "Table des mati\xe8res")
2775 ("it" "Autore" "Data" "Indice")
2776 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2777 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2778 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2779 "Terms used in export text, translated to different languages.
2780 Use the variable `org-export-default-language' to set the language,
2781 or use the +OPTION lines for a per-file setting."
2782 :group 'org-export-general
2783 :type '(repeat
2784 (list
2785 (string :tag "HTML language tag")
2786 (string :tag "Author")
2787 (string :tag "Date")
2788 (string :tag "Table of Contents"))))
2790 (defcustom org-export-default-language "en"
2791 "The default language of HTML export, as a string.
2792 This should have an association in `org-export-language-setup'."
2793 :group 'org-export-general
2794 :type 'string)
2796 (defcustom org-export-skip-text-before-1st-heading t
2797 "Non-nil means, skip all text before the first headline when exporting.
2798 When nil, that text is exported as well."
2799 :group 'org-export-general
2800 :type 'boolean)
2802 (defcustom org-export-headline-levels 3
2803 "The last level which is still exported as a headline.
2804 Inferior levels will produce itemize lists when exported.
2805 Note that a numeric prefix argument to an exporter function overrides
2806 this setting.
2808 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2809 :group 'org-export-general
2810 :type 'number)
2812 (defcustom org-export-with-section-numbers t
2813 "Non-nil means, add section numbers to headlines when exporting.
2815 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2816 :group 'org-export-general
2817 :type 'boolean)
2819 (defcustom org-export-with-toc t
2820 "Non-nil means, create a table of contents in exported files.
2821 The TOC contains headlines with levels up to`org-export-headline-levels'.
2822 When an integer, include levels up to N in the toc, this may then be
2823 different from `org-export-headline-levels', but it will not be allowed
2824 to be larger than the number of headline levels.
2825 When nil, no table of contents is made.
2827 Headlines which contain any TODO items will be marked with \"(*)\" in
2828 ASCII export, and with red color in HTML output, if the option
2829 `org-export-mark-todo-in-toc' is set.
2831 In HTML output, the TOC will be clickable.
2833 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2834 or \"toc:3\"."
2835 :group 'org-export-general
2836 :type '(choice
2837 (const :tag "No Table of Contents" nil)
2838 (const :tag "Full Table of Contents" t)
2839 (integer :tag "TOC to level")))
2841 (defcustom org-export-mark-todo-in-toc nil
2842 "Non-nil means, mark TOC lines that contain any open TODO items."
2843 :group 'org-export-general
2844 :type 'boolean)
2846 (defcustom org-export-preserve-breaks nil
2847 "Non-nil means, preserve all line breaks when exporting.
2848 Normally, in HTML output paragraphs will be reformatted. In ASCII
2849 export, line breaks will always be preserved, regardless of this variable.
2851 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2852 :group 'org-export-general
2853 :type 'boolean)
2855 (defcustom org-export-with-archived-trees 'headline
2856 "Whether subtrees with the ARCHIVE tag should be exported.
2857 This can have three different values
2858 nil Do not export, pretend this tree is not present
2859 t Do export the entire tree
2860 headline Only export the headline, but skip the tree below it."
2861 :group 'org-export-general
2862 :group 'org-archive
2863 :type '(choice
2864 (const :tag "not at all" nil)
2865 (const :tag "headline only" 'headline)
2866 (const :tag "entirely" t)))
2868 (defcustom org-export-author-info t
2869 "Non-nil means, insert author name and email into the exported file.
2871 This option can also be set with the +OPTIONS line,
2872 e.g. \"author-info:nil\"."
2873 :group 'org-export-general
2874 :type 'boolean)
2876 (defcustom org-export-time-stamp-file t
2877 "Non-nil means, insert a time stamp into the exported file.
2878 The time stamp shows when the file was created.
2880 This option can also be set with the +OPTIONS line,
2881 e.g. \"timestamp:nil\"."
2882 :group 'org-export-general
2883 :type 'boolean)
2885 (defcustom org-export-with-timestamps t
2886 "If nil, do not export time stamps and associated keywords."
2887 :group 'org-export-general
2888 :type 'boolean)
2890 (defcustom org-export-remove-timestamps-from-toc t
2891 "If nil, remove timestamps from the table of contents entries."
2892 :group 'org-export-general
2893 :type 'boolean)
2895 (defcustom org-export-with-tags 'not-in-toc
2896 "If nil, do not export tags, just remove them from headlines.
2897 If this is the symbol `not-in-toc', tags will be removed from table of
2898 contents entries, but still be shown in the headlines of the document.
2900 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
2901 :group 'org-export-general
2902 :type '(choice
2903 (const :tag "Off" nil)
2904 (const :tag "Not in TOC" not-in-toc)
2905 (const :tag "On" t)))
2907 (defcustom org-export-with-property-drawer nil
2908 "Non-nil means, export property drawers.
2909 When nil, these drawers are removed before export.
2911 This option can also be set with the +OPTIONS line, e.g. \"p:t\"."
2912 :group 'org-export-general
2913 :type 'boolean)
2915 (defgroup org-export-translation nil
2916 "Options for translating special ascii sequences for the export backends."
2917 :tag "Org Export Translation"
2918 :group 'org-export)
2920 (defcustom org-export-with-emphasize t
2921 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2922 If the export target supports emphasizing text, the word will be
2923 typeset in bold, italic, or underlined, respectively. Works only for
2924 single words, but you can say: I *really* *mean* *this*.
2925 Not all export backends support this.
2927 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2928 :group 'org-export-translation
2929 :type 'boolean)
2931 (defcustom org-export-with-footnotes t
2932 "If nil, export [1] as a footnote marker.
2933 Lines starting with [1] will be formatted as footnotes.
2935 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
2936 :group 'org-export-translation
2937 :type 'boolean)
2939 (defcustom org-export-with-sub-superscripts t
2940 "Non-nil means, interpret \"_\" and \"^\" for export.
2941 When this option is turned on, you can use TeX-like syntax for sub- and
2942 superscripts. Several characters after \"_\" or \"^\" will be
2943 considered as a single item - so grouping with {} is normally not
2944 needed. For example, the following things will be parsed as single
2945 sub- or superscripts.
2947 10^24 or 10^tau several digits will be considered 1 item.
2948 10^-12 or 10^-tau a leading sign with digits or a word
2949 x^2-y^3 will be read as x^2 - y^3, because items are
2950 terminated by almost any nonword/nondigit char.
2951 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2953 Still, ambiguity is possible - so when in doubt use {} to enclose the
2954 sub/superscript. If you set this variable to the symbol `{}',
2955 the braces are *required* in order to trigger interpretations as
2956 sub/superscript. This can be helpful in documents that need \"_\"
2957 frequently in plain text.
2959 Not all export backends support this, but HTML does.
2961 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2962 :group 'org-export-translation
2963 :type '(choice
2964 (const :tag "Always interpret" t)
2965 (const :tag "Only with braces" {})
2966 (const :tag "Never interpret" nil)))
2968 (defcustom org-export-with-TeX-macros t
2969 "Non-nil means, interpret simple TeX-like macros when exporting.
2970 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2971 No only real TeX macros will work here, but the standard HTML entities
2972 for math can be used as macro names as well. For a list of supported
2973 names in HTML export, see the constant `org-html-entities'.
2974 Not all export backends support this.
2976 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2977 :group 'org-export-translation
2978 :group 'org-export-latex
2979 :type 'boolean)
2981 (defcustom org-export-with-LaTeX-fragments nil
2982 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2983 When set, the exporter will find LaTeX environments if the \\begin line is
2984 the first non-white thing on a line. It will also find the math delimiters
2985 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2986 display math.
2988 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2989 :group 'org-export-translation
2990 :group 'org-export-latex
2991 :type 'boolean)
2993 (defcustom org-export-with-fixed-width t
2994 "Non-nil means, lines starting with \":\" will be in fixed width font.
2995 This can be used to have pre-formatted text, fragments of code etc. For
2996 example:
2997 : ;; Some Lisp examples
2998 : (while (defc cnt)
2999 : (ding))
3000 will be looking just like this in also HTML. See also the QUOTE keyword.
3001 Not all export backends support this.
3003 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3004 :group 'org-export-translation
3005 :type 'boolean)
3007 (defcustom org-match-sexp-depth 3
3008 "Number of stacked braces for sub/superscript matching.
3009 This has to be set before loading org.el to be effective."
3010 :group 'org-export-translation
3011 :type 'integer)
3013 (defgroup org-export-tables nil
3014 "Options for exporting tables in Org-mode."
3015 :tag "Org Export Tables"
3016 :group 'org-export)
3018 (defcustom org-export-with-tables t
3019 "If non-nil, lines starting with \"|\" define a table.
3020 For example:
3022 | Name | Address | Birthday |
3023 |-------------+----------+-----------|
3024 | Arthur Dent | England | 29.2.2100 |
3026 Not all export backends support this.
3028 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3029 :group 'org-export-tables
3030 :type 'boolean)
3032 (defcustom org-export-highlight-first-table-line t
3033 "Non-nil means, highlight the first table line.
3034 In HTML export, this means use <th> instead of <td>.
3035 In tables created with table.el, this applies to the first table line.
3036 In Org-mode tables, all lines before the first horizontal separator
3037 line will be formatted with <th> tags."
3038 :group 'org-export-tables
3039 :type 'boolean)
3041 (defcustom org-export-table-remove-special-lines t
3042 "Remove special lines and marking characters in calculating tables.
3043 This removes the special marking character column from tables that are set
3044 up for spreadsheet calculations. It also removes the entire lines
3045 marked with `!', `_', or `^'. The lines with `$' are kept, because
3046 the values of constants may be useful to have."
3047 :group 'org-export-tables
3048 :type 'boolean)
3050 (defcustom org-export-prefer-native-exporter-for-tables nil
3051 "Non-nil means, always export tables created with table.el natively.
3052 Natively means, use the HTML code generator in table.el.
3053 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3054 the table does not use row- or column-spanning). This has the
3055 advantage, that the automatic HTML conversions for math symbols and
3056 sub/superscripts can be applied. Org-mode's HTML generator is also
3057 much faster."
3058 :group 'org-export-tables
3059 :type 'boolean)
3061 (defgroup org-export-ascii nil
3062 "Options specific for ASCII export of Org-mode files."
3063 :tag "Org Export ASCII"
3064 :group 'org-export)
3066 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3067 "Characters for underlining headings in ASCII export.
3068 In the given sequence, these characters will be used for level 1, 2, ..."
3069 :group 'org-export-ascii
3070 :type '(repeat character))
3072 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3073 "Bullet characters for headlines converted to lists in ASCII export.
3074 The first character is is used for the first lest level generated in this
3075 way, and so on. If there are more levels than characters given here,
3076 the list will be repeated.
3077 Note that plain lists will keep the same bullets as the have in the
3078 Org-mode file."
3079 :group 'org-export-ascii
3080 :type '(repeat character))
3082 (defgroup org-export-xml nil
3083 "Options specific for XML export of Org-mode files."
3084 :tag "Org Export XML"
3085 :group 'org-export)
3087 (defgroup org-export-html nil
3088 "Options specific for HTML export of Org-mode files."
3089 :tag "Org Export HTML"
3090 :group 'org-export)
3092 (defcustom org-export-html-coding-system nil
3094 :group 'org-export-html
3095 :type 'coding-system)
3097 (defcustom org-export-html-extension "html"
3098 "The extension for exported HTML files."
3099 :group 'org-export-html
3100 :type 'string)
3102 (defcustom org-export-html-style
3103 "<style type=\"text/css\">
3104 html {
3105 font-family: Times, serif;
3106 font-size: 12pt;
3108 .title { text-align: center; }
3109 .todo { color: red; }
3110 .done { color: green; }
3111 .timestamp { color: grey }
3112 .timestamp-kwd { color: CadetBlue }
3113 .tag { background-color:lightblue; font-weight:normal }
3114 .target { background-color: lavender; }
3115 pre {
3116 border: 1pt solid #AEBDCC;
3117 background-color: #F3F5F7;
3118 padding: 5pt;
3119 font-family: courier, monospace;
3121 table { border-collapse: collapse; }
3122 td, th {
3123 vertical-align: top;
3124 <!--border: 1pt solid #ADB9CC;-->
3126 </style>"
3127 "The default style specification for exported HTML files.
3128 Since there are different ways of setting style information, this variable
3129 needs to contain the full HTML structure to provide a style, including the
3130 surrounding HTML tags. The style specifications should include definitions
3131 for new classes todo, done, title, and deadline. For example, legal values
3132 would be:
3134 <style type=\"text/css\">
3135 p { font-weight: normal; color: gray; }
3136 h1 { color: black; }
3137 .title { text-align: center; }
3138 .todo, .deadline { color: red; }
3139 .done { color: green; }
3140 </style>
3142 or, if you want to keep the style in a file,
3144 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3146 As the value of this option simply gets inserted into the HTML <head> header,
3147 you can \"misuse\" it to add arbitrary text to the header."
3148 :group 'org-export-html
3149 :type 'string)
3152 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3153 "Format for typesetting the document title in HTML export."
3154 :group 'org-export-html
3155 :type 'string)
3157 (defcustom org-export-html-toplevel-hlevel 2
3158 "The <H> level for level 1 headings in HTML export."
3159 :group 'org-export-html
3160 :type 'string)
3162 (defcustom org-export-html-link-org-files-as-html t
3163 "Non-nil means, make file links to `file.org' point to `file.html'.
3164 When org-mode is exporting an org-mode file to HTML, links to
3165 non-html files are directly put into a href tag in HTML.
3166 However, links to other Org-mode files (recognized by the
3167 extension `.org.) should become links to the corresponding html
3168 file, assuming that the linked org-mode file will also be
3169 converted to HTML.
3170 When nil, the links still point to the plain `.org' file."
3171 :group 'org-export-html
3172 :type 'boolean)
3174 (defcustom org-export-html-inline-images 'maybe
3175 "Non-nil means, inline images into exported HTML pages.
3176 This is done using an <img> tag. When nil, an anchor with href is used to
3177 link to the image. If this option is `maybe', then images in links with
3178 an empty description will be inlined, while images with a description will
3179 be linked only."
3180 :group 'org-export-html
3181 :type '(choice (const :tag "Never" nil)
3182 (const :tag "Always" t)
3183 (const :tag "When there is no description" maybe)))
3185 ;; FIXME: rename
3186 (defcustom org-export-html-expand t
3187 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3188 When nil, these tags will be exported as plain text and therefore
3189 not be interpreted by a browser.
3191 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3192 :group 'org-export-html
3193 :type 'boolean)
3195 (defcustom org-export-html-table-tag
3196 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3197 "The HTML tag that is used to start a table.
3198 This must be a <table> tag, but you may change the options like
3199 borders and spacing."
3200 :group 'org-export-html
3201 :type 'string)
3203 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3204 "The opening tag for table header fields.
3205 This is customizable so that alignment options can be specified."
3206 :group 'org-export-tables
3207 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3209 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3210 "The opening tag for table data fields.
3211 This is customizable so that alignment options can be specified."
3212 :group 'org-export-tables
3213 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3215 (defcustom org-export-html-with-timestamp nil
3216 "If non-nil, write `org-export-html-html-helper-timestamp'
3217 into the exported HTML text. Otherwise, the buffer will just be saved
3218 to a file."
3219 :group 'org-export-html
3220 :type 'boolean)
3222 (defcustom org-export-html-html-helper-timestamp
3223 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3224 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3225 :group 'org-export-html
3226 :type 'string)
3228 (defgroup org-export-icalendar nil
3229 "Options specific for iCalendar export of Org-mode files."
3230 :tag "Org Export iCalendar"
3231 :group 'org-export)
3233 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3234 "The file name for the iCalendar file covering all agenda files.
3235 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3236 The file name should be absolute, the file will be overwritten without warning."
3237 :group 'org-export-icalendar
3238 :type 'file)
3240 (defcustom org-icalendar-include-todo nil
3241 "Non-nil means, export to iCalendar files should also cover TODO items."
3242 :group 'org-export-icalendar
3243 :type '(choice
3244 (const :tag "None" nil)
3245 (const :tag "Unfinished" t)
3246 (const :tag "All" all)))
3248 (defcustom org-icalendar-include-sexps t
3249 "Non-nil means, export to iCalendar files should also cover sexp entries.
3250 These are entries like in the diary, but directly in an Org-mode file."
3251 :group 'org-export-icalendar
3252 :type 'boolean)
3254 (defcustom org-icalendar-include-body 100
3255 "Amount of text below headline to be included in iCalendar export.
3256 This is a number of characters that should maximally be included.
3257 Properties, scheduling and clocking lines will always be removed.
3258 The text will be inserted into the DESCRIPTION field."
3259 :group 'org-export-icalendar
3260 :type '(choice
3261 (const :tag "Nothing" nil)
3262 (const :tag "Everything" t)
3263 (integer :tag "Max characters")))
3265 (defcustom org-icalendar-combined-name "OrgMode"
3266 "Calendar name for the combined iCalendar representing all agenda files."
3267 :group 'org-export-icalendar
3268 :type 'string)
3270 (defgroup org-font-lock nil
3271 "Font-lock settings for highlighting in Org-mode."
3272 :tag "Org Font Lock"
3273 :group 'org)
3275 (defcustom org-level-color-stars-only nil
3276 "Non-nil means fontify only the stars in each headline.
3277 When nil, the entire headline is fontified.
3278 Changing it requires restart of `font-lock-mode' to become effective
3279 also in regions already fontified."
3280 :group 'org-font-lock
3281 :type 'boolean)
3283 (defcustom org-hide-leading-stars nil
3284 "Non-nil means, hide the first N-1 stars in a headline.
3285 This works by using the face `org-hide' for these stars. This
3286 face is white for a light background, and black for a dark
3287 background. You may have to customize the face `org-hide' to
3288 make this work.
3289 Changing it requires restart of `font-lock-mode' to become effective
3290 also in regions already fontified.
3291 You may also set this on a per-file basis by adding one of the following
3292 lines to the buffer:
3294 #+STARTUP: hidestars
3295 #+STARTUP: showstars"
3296 :group 'org-font-lock
3297 :type 'boolean)
3299 (defcustom org-fontify-done-headline nil
3300 "Non-nil means, change the face of a headline if it is marked DONE.
3301 Normally, only the TODO/DONE keyword indicates the state of a headline.
3302 When this is non-nil, the headline after the keyword is set to the
3303 `org-headline-done' as an additional indication."
3304 :group 'org-font-lock
3305 :type 'boolean)
3307 (defcustom org-fontify-emphasized-text t
3308 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3309 Changing this variable requires a restart of Emacs to take effect."
3310 :group 'org-font-lock
3311 :type 'boolean)
3313 (defvar org-emph-re nil
3314 "Regular expression for matching emphasis.")
3315 (defvar org-emphasis-regexp-components) ; defined just below
3316 (defvar org-emphasis-alist) ; defined just below
3317 (defun org-set-emph-re (var val)
3318 "Set variable and compute the emphasis regular expression."
3319 (set var val)
3320 (when (and (boundp 'org-emphasis-alist)
3321 (boundp 'org-emphasis-regexp-components)
3322 org-emphasis-alist org-emphasis-regexp-components)
3323 (let* ((e org-emphasis-regexp-components)
3324 (pre (car e))
3325 (post (nth 1 e))
3326 (border (nth 2 e))
3327 (body (nth 3 e))
3328 (nl (nth 4 e))
3329 (stacked (nth 5 e))
3330 (body1 (concat body "*?"))
3331 (markers (mapconcat 'car org-emphasis-alist "")))
3332 ;; make sure special characters appear at the right position in the class
3333 (if (string-match "\\^" markers)
3334 (setq markers (concat (replace-match "" t t markers) "^")))
3335 (if (string-match "-" markers)
3336 (setq markers (concat (replace-match "" t t markers) "-")))
3337 (if (> nl 0)
3338 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3339 (int-to-string nl) "\\}")))
3340 ;; Make the regexp
3341 (setq org-emph-re
3342 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
3343 "\\("
3344 "\\([" markers "]\\)"
3345 "\\("
3346 "[^" border (if (and nil stacked) markers) "]"
3347 body1
3348 "[^" border (if (and nil stacked) markers) "]"
3349 "\\)"
3350 "\\3\\)"
3351 "\\([" post (if stacked markers) "]\\|$\\)")))))
3353 (defcustom org-emphasis-regexp-components
3354 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1 nil)
3355 "Components used to build the reqular expression for emphasis.
3356 This is a list with 6 entries. Terminology: In an emphasis string
3357 like \" *strong word* \", we call the initial space PREMATCH, the final
3358 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3359 and \"trong wor\" is the body. The different components in this variable
3360 specify what is allowed/forbidden in each part:
3362 pre Chars allowed as prematch. Beginning of line will be allowed too.
3363 post Chars allowed as postmatch. End of line will be allowed too.
3364 border The chars *forbidden* as border characters.
3365 body-regexp A regexp like \".\" to match a body character. Don't use
3366 non-shy groups here, and don't allow newline here.
3367 newline The maximum number of newlines allowed in an emphasis exp.
3368 stacked Non-nil means, allow stacked styles. This works only in HTML
3369 export. When this is set, all marker characters (as given in
3370 `org-emphasis-alist') will be allowed as pre/post, aiding
3371 inside-out matching.
3372 Use customize to modify this, or restart Emacs after changing it."
3373 :group 'org-font-lock
3374 :set 'org-set-emph-re
3375 :type '(list
3376 (sexp :tag "Allowed chars in pre ")
3377 (sexp :tag "Allowed chars in post ")
3378 (sexp :tag "Forbidden chars in border ")
3379 (sexp :tag "Regexp for body ")
3380 (integer :tag "number of newlines allowed")
3381 (boolean :tag "Stacking allowed ")))
3383 (defcustom org-emphasis-alist
3384 '(("*" bold "<b>" "</b>")
3385 ("/" italic "<i>" "</i>")
3386 ("_" underline "<u>" "</u>")
3387 ("=" org-code "<code>" "</code>")
3388 ("+" (:strike-through t) "<del>" "</del>")
3390 "Special syntax for emphasized text.
3391 Text starting and ending with a special character will be emphasized, for
3392 example *bold*, _underlined_ and /italic/. This variable sets the marker
3393 characters, the face to be used by font-lock for highlighting in Org-mode
3394 Emacs buffers, and the HTML tags to be used for this.
3395 Use customize to modify this, or restart Emacs after changing it."
3396 :group 'org-font-lock
3397 :set 'org-set-emph-re
3398 :type '(repeat
3399 (list
3400 (string :tag "Marker character")
3401 (choice
3402 (face :tag "Font-lock-face")
3403 (plist :tag "Face property list"))
3404 (string :tag "HTML start tag")
3405 (string :tag "HTML end tag"))))
3407 ;;; The faces
3409 (defgroup org-faces nil
3410 "Faces in Org-mode."
3411 :tag "Org Faces"
3412 :group 'org-font-lock)
3414 (defun org-compatible-face (inherits specs)
3415 "Make a compatible face specification.
3416 If INHERITS is an existing face and if the Emacs version supports it,
3417 just inherit the face. If not, use SPECS to define the face.
3418 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3419 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3420 to the top of the list. The `min-colors' attribute will be removed from
3421 any other entries, and any resulting duplicates will be removed entirely."
3422 (cond
3423 ((and inherits (facep inherits)
3424 (not (featurep 'xemacs)) (> emacs-major-version 22))
3425 ;; In Emacs 23, we use inheritance where possible.
3426 ;; We only do this in Emacs 23, because only there the outline
3427 ;; faces have been changed to the original org-mode-level-faces.
3428 (list (list t :inherit inherits)))
3429 ((or (featurep 'xemacs) (< emacs-major-version 22))
3430 ;; These do not understand the `min-colors' attribute.
3431 (let (r e a)
3432 (while (setq e (pop specs))
3433 (cond
3434 ((memq (car e) '(t default)) (push e r))
3435 ((setq a (member '(min-colors 8) (car e)))
3436 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3437 (cdr e)))))
3438 ((setq a (assq 'min-colors (car e)))
3439 (setq e (cons (delq a (car e)) (cdr e)))
3440 (or (assoc (car e) r) (push e r)))
3441 (t (or (assoc (car e) r) (push e r)))))
3442 (nreverse r)))
3443 (t specs)))
3445 (defface org-hide
3446 '((((background light)) (:foreground "white"))
3447 (((background dark)) (:foreground "black")))
3448 "Face used to hide leading stars in headlines.
3449 The forground color of this face should be equal to the background
3450 color of the frame."
3451 :group 'org-faces)
3453 (defface org-level-1 ;; font-lock-function-name-face
3454 (org-compatible-face
3455 'outline-1
3456 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3457 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3458 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3459 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3460 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3461 (t (:bold t))))
3462 "Face used for level 1 headlines."
3463 :group 'org-faces)
3465 (defface org-level-2 ;; font-lock-variable-name-face
3466 (org-compatible-face
3467 'outline-2
3468 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3469 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3470 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3471 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3472 (t (:bold t))))
3473 "Face used for level 2 headlines."
3474 :group 'org-faces)
3476 (defface org-level-3 ;; font-lock-keyword-face
3477 (org-compatible-face
3478 'outline-3
3479 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3480 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3481 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3482 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3483 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3484 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3485 (t (:bold t))))
3486 "Face used for level 3 headlines."
3487 :group 'org-faces)
3489 (defface org-level-4 ;; font-lock-comment-face
3490 (org-compatible-face
3491 'outline-4
3492 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3493 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3494 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3495 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3496 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3497 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3498 (t (:bold t))))
3499 "Face used for level 4 headlines."
3500 :group 'org-faces)
3502 (defface org-level-5 ;; font-lock-type-face
3503 (org-compatible-face
3504 'outline-5
3505 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3506 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3507 (((class color) (min-colors 8)) (:foreground "green"))))
3508 "Face used for level 5 headlines."
3509 :group 'org-faces)
3511 (defface org-level-6 ;; font-lock-constant-face
3512 (org-compatible-face
3513 'outline-6
3514 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3515 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3516 (((class color) (min-colors 8)) (:foreground "magenta"))))
3517 "Face used for level 6 headlines."
3518 :group 'org-faces)
3520 (defface org-level-7 ;; font-lock-builtin-face
3521 (org-compatible-face
3522 'outline-7
3523 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3524 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3525 (((class color) (min-colors 8)) (:foreground "blue"))))
3526 "Face used for level 7 headlines."
3527 :group 'org-faces)
3529 (defface org-level-8 ;; font-lock-string-face
3530 (org-compatible-face
3531 'outline-8
3532 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3533 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3534 (((class color) (min-colors 8)) (:foreground "green"))))
3535 "Face used for level 8 headlines."
3536 :group 'org-faces)
3538 (defface org-special-keyword ;; font-lock-string-face
3539 (org-compatible-face
3541 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3542 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3543 (t (:italic t))))
3544 "Face used for special keywords."
3545 :group 'org-faces)
3547 (defface org-drawer ;; font-lock-function-name-face
3548 (org-compatible-face
3550 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3551 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3552 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3553 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3554 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3555 (t (:bold t))))
3556 "Face used for drawers."
3557 :group 'org-faces)
3559 (defface org-property-value nil
3560 "Face used for the value of a property."
3561 :group 'org-faces)
3563 (defface org-column
3564 (org-compatible-face
3566 '((((class color) (min-colors 16) (background light))
3567 (:background "grey90"))
3568 (((class color) (min-colors 16) (background dark))
3569 (:background "grey30"))
3570 (((class color) (min-colors 8))
3571 (:background "cyan" :foreground "black"))
3572 (t (:inverse-video t))))
3573 "Face for column display of entry properties."
3574 :group 'org-faces)
3576 (when (fboundp 'set-face-attribute)
3577 ;; Make sure that a fixed-width face is used when we have a column table.
3578 (set-face-attribute 'org-column nil
3579 :height (face-attribute 'default :height)
3580 :family (face-attribute 'default :family)))
3582 (defface org-warning
3583 (org-compatible-face
3584 'font-lock-warning-face
3585 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3586 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3587 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3588 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3589 (t (:bold t))))
3590 "Face for deadlines and TODO keywords."
3591 :group 'org-faces)
3593 (defface org-archived ; similar to shadow
3594 (org-compatible-face
3595 'shadow
3596 '((((class color grayscale) (min-colors 88) (background light))
3597 (:foreground "grey50"))
3598 (((class color grayscale) (min-colors 88) (background dark))
3599 (:foreground "grey70"))
3600 (((class color) (min-colors 8) (background light))
3601 (:foreground "green"))
3602 (((class color) (min-colors 8) (background dark))
3603 (:foreground "yellow"))))
3604 "Face for headline with the ARCHIVE tag."
3605 :group 'org-faces)
3607 (defface org-link
3608 '((((class color) (background light)) (:foreground "Purple" :underline t))
3609 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3610 (t (:underline t)))
3611 "Face for links."
3612 :group 'org-faces)
3614 (defface org-target
3615 '((((class color) (background light)) (:underline t))
3616 (((class color) (background dark)) (:underline t))
3617 (t (:underline t)))
3618 "Face for links."
3619 :group 'org-faces)
3621 (defface org-date
3622 '((((class color) (background light)) (:foreground "Purple" :underline t))
3623 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3624 (t (:underline t)))
3625 "Face for links."
3626 :group 'org-faces)
3628 (defface org-sexp-date
3629 '((((class color) (background light)) (:foreground "Purple"))
3630 (((class color) (background dark)) (:foreground "Cyan"))
3631 (t (:underline t)))
3632 "Face for links."
3633 :group 'org-faces)
3635 (defface org-tag
3636 '((t (:bold t)))
3637 "Face for tags."
3638 :group 'org-faces)
3640 (defface org-todo ; font-lock-warning-face
3641 (org-compatible-face
3643 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3644 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3645 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3646 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3647 (t (:inverse-video t :bold t))))
3648 "Face for TODO keywords."
3649 :group 'org-faces)
3651 (defface org-done ;; font-lock-type-face
3652 (org-compatible-face
3654 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3655 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3656 (((class color) (min-colors 8)) (:foreground "green"))
3657 (t (:bold t))))
3658 "Face used for todo keywords that indicate DONE items."
3659 :group 'org-faces)
3661 (defface org-headline-done ;; font-lock-string-face
3662 (org-compatible-face
3664 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3665 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3666 (((class color) (min-colors 8) (background light)) (:bold nil))))
3667 "Face used to indicate that a headline is DONE.
3668 This face is only used if `org-fontify-done-headline' is set. If applies
3669 to the part of the headline after the DONE keyword."
3670 :group 'org-faces)
3672 (defcustom org-todo-keyword-faces nil
3673 "Faces for specific TODO keywords.
3674 This is a list of cons cells, with TODO keywords in the car
3675 and faces in the cdr. The face can be a symbol, or a property
3676 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3677 :group 'org-faces
3678 :group 'org-todo
3679 :type '(repeat
3680 (cons
3681 (string :tag "keyword")
3682 (sexp :tag "face"))))
3684 (defface org-table ;; font-lock-function-name-face
3685 (org-compatible-face
3687 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3688 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3689 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3690 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3691 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3692 (((class color) (min-colors 8) (background dark)))))
3693 "Face used for tables."
3694 :group 'org-faces)
3696 (defface org-formula
3697 (org-compatible-face
3699 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3700 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3701 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3702 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3703 (t (:bold t :italic t))))
3704 "Face for formulas."
3705 :group 'org-faces)
3707 (defface org-code
3708 (org-compatible-face
3710 '((((class color grayscale) (min-colors 88) (background light))
3711 (:foreground "grey50"))
3712 (((class color grayscale) (min-colors 88) (background dark))
3713 (:foreground "grey70"))
3714 (((class color) (min-colors 8) (background light))
3715 (:foreground "green"))
3716 (((class color) (min-colors 8) (background dark))
3717 (:foreground "yellow"))))
3718 "Face for fixed-with text like code snippets."
3719 :group 'org-faces
3720 :version "22.1")
3722 (defface org-agenda-structure ;; font-lock-function-name-face
3723 (org-compatible-face
3725 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3726 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3727 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3728 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3729 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3730 (t (:bold t))))
3731 "Face used in agenda for captions and dates."
3732 :group 'org-faces)
3734 (defface org-scheduled-today
3735 (org-compatible-face
3737 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3738 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3739 (((class color) (min-colors 8)) (:foreground "green"))
3740 (t (:bold t :italic t))))
3741 "Face for items scheduled for a certain day."
3742 :group 'org-faces)
3744 (defface org-scheduled-previously
3745 (org-compatible-face
3747 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3748 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3749 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3750 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3751 (t (:bold t))))
3752 "Face for items scheduled previously, and not yet done."
3753 :group 'org-faces)
3755 (defface org-upcoming-deadline
3756 (org-compatible-face
3758 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3759 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3760 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3761 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3762 (t (:bold t))))
3763 "Face for items scheduled previously, and not yet done."
3764 :group 'org-faces)
3766 (defcustom org-agenda-deadline-faces
3767 '((1.0 . org-warning)
3768 (0.5 . org-upcoming-deadline)
3769 (0.0 . default))
3770 "Faces for showing deadlines in the agenda.
3771 This is a list of cons cells. The cdr of each cess is a face to be used,
3772 and it can also just be a like like '(:foreground \"yellow\").
3773 Each car is a fraction of the head-warning time that must have passed for
3774 this the face in the cdr to be used for display. The numbers must be
3775 given in descending order. The head-warning time is normally taken
3776 from `org-deadline-warning-days', but can also be specified in the deadline
3777 timestamp itself, like this:
3779 DEADLINE: <2007-08-13 Mon -8d>
3781 You may use d for days, w for weeks, m for months and y for years. Months
3782 and years will only be treated in an approximate fashion (30.4 days for a
3783 month and 365.24 days for a year)."
3784 :group 'org-faces
3785 :group 'org-agenda-daily/weekly
3786 :type '(repeat
3787 (cons
3788 (number :tag "Fraction of head-warning time passed")
3789 (sexp :tag "Face"))))
3791 (defface org-time-grid ;; font-lock-variable-name-face
3792 (org-compatible-face
3794 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3795 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3796 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3797 "Face used for time grids."
3798 :group 'org-faces)
3800 (defconst org-level-faces
3801 '(org-level-1 org-level-2 org-level-3 org-level-4
3802 org-level-5 org-level-6 org-level-7 org-level-8
3805 (defcustom org-n-level-faces (length org-level-faces)
3806 "The number different faces to be used for headlines.
3807 Org-mode defines 8 different headline faces, so this can be at most 8.
3808 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
3809 :type 'number
3810 :group 'org-faces)
3812 ;;; Variables for pre-computed regular expressions, all buffer local
3814 (defvar org-drawer-regexp nil
3815 "Matches first line of a hidden block.")
3816 (make-variable-buffer-local 'org-drawer-regexp)
3817 (defvar org-todo-regexp nil
3818 "Matches any of the TODO state keywords.")
3819 (make-variable-buffer-local 'org-todo-regexp)
3820 (defvar org-not-done-regexp nil
3821 "Matches any of the TODO state keywords except the last one.")
3822 (make-variable-buffer-local 'org-not-done-regexp)
3823 (defvar org-todo-line-regexp nil
3824 "Matches a headline and puts TODO state into group 2 if present.")
3825 (make-variable-buffer-local 'org-todo-line-regexp)
3826 (defvar org-todo-line-tags-regexp nil
3827 "Matches a headline and puts TODO state into group 2 if present.
3828 Also put tags into group 4 if tags are present.")
3829 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3830 (defvar org-nl-done-regexp nil
3831 "Matches newline followed by a headline with the DONE keyword.")
3832 (make-variable-buffer-local 'org-nl-done-regexp)
3833 (defvar org-looking-at-done-regexp nil
3834 "Matches the DONE keyword a point.")
3835 (make-variable-buffer-local 'org-looking-at-done-regexp)
3836 (defvar org-ds-keyword-length 12
3837 "Maximum length of the Deadline and SCHEDULED keywords.")
3838 (make-variable-buffer-local 'org-ds-keyword-length)
3839 (defvar org-deadline-regexp nil
3840 "Matches the DEADLINE keyword.")
3841 (make-variable-buffer-local 'org-deadline-regexp)
3842 (defvar org-deadline-time-regexp nil
3843 "Matches the DEADLINE keyword together with a time stamp.")
3844 (make-variable-buffer-local 'org-deadline-time-regexp)
3845 (defvar org-deadline-line-regexp nil
3846 "Matches the DEADLINE keyword and the rest of the line.")
3847 (make-variable-buffer-local 'org-deadline-line-regexp)
3848 (defvar org-scheduled-regexp nil
3849 "Matches the SCHEDULED keyword.")
3850 (make-variable-buffer-local 'org-scheduled-regexp)
3851 (defvar org-scheduled-time-regexp nil
3852 "Matches the SCHEDULED keyword together with a time stamp.")
3853 (make-variable-buffer-local 'org-scheduled-time-regexp)
3854 (defvar org-closed-time-regexp nil
3855 "Matches the CLOSED keyword together with a time stamp.")
3856 (make-variable-buffer-local 'org-closed-time-regexp)
3858 (defvar org-keyword-time-regexp nil
3859 "Matches any of the 4 keywords, together with the time stamp.")
3860 (make-variable-buffer-local 'org-keyword-time-regexp)
3861 (defvar org-keyword-time-not-clock-regexp nil
3862 "Matches any of the 3 keywords, together with the time stamp.")
3863 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3864 (defvar org-maybe-keyword-time-regexp nil
3865 "Matches a timestamp, possibly preceeded by a keyword.")
3866 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3867 (defvar org-planning-or-clock-line-re nil
3868 "Matches a line with planning or clock info.")
3869 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3871 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3872 rear-nonsticky t mouse-map t fontified t)
3873 "Properties to remove when a string without properties is wanted.")
3875 (defsubst org-match-string-no-properties (num &optional string)
3876 (if (featurep 'xemacs)
3877 (let ((s (match-string num string)))
3878 (remove-text-properties 0 (length s) org-rm-props s)
3880 (match-string-no-properties num string)))
3882 (defsubst org-no-properties (s)
3883 (if (fboundp 'set-text-properties)
3884 (set-text-properties 0 (length s) nil s)
3885 (remove-text-properties 0 (length s) org-rm-props s))
3888 (defsubst org-get-alist-option (option key)
3889 (cond ((eq key t) t)
3890 ((eq option t) t)
3891 ((assoc key option) (cdr (assoc key option)))
3892 (t (cdr (assq 'default option)))))
3894 (defsubst org-inhibit-invisibility ()
3895 "Modified `buffer-invisibility-spec' for Emacs 21.
3896 Some ops with invisible text do not work correctly on Emacs 21. For these
3897 we turn off invisibility temporarily. Use this in a `let' form."
3898 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
3900 (defsubst org-set-local (var value)
3901 "Make VAR local in current buffer and set it to VALUE."
3902 (set (make-variable-buffer-local var) value))
3904 (defsubst org-mode-p ()
3905 "Check if the current buffer is in Org-mode."
3906 (eq major-mode 'org-mode))
3908 (defsubst org-last (list)
3909 "Return the last element of LIST."
3910 (car (last list)))
3912 (defun org-let (list &rest body)
3913 (eval (cons 'let (cons list body))))
3914 (put 'org-let 'lisp-indent-function 1)
3916 (defun org-let2 (list1 list2 &rest body)
3917 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3918 (put 'org-let2 'lisp-indent-function 2)
3919 (defconst org-startup-options
3920 '(("fold" org-startup-folded t)
3921 ("overview" org-startup-folded t)
3922 ("nofold" org-startup-folded nil)
3923 ("showall" org-startup-folded nil)
3924 ("content" org-startup-folded content)
3925 ("hidestars" org-hide-leading-stars t)
3926 ("showstars" org-hide-leading-stars nil)
3927 ("odd" org-odd-levels-only t)
3928 ("oddeven" org-odd-levels-only nil)
3929 ("align" org-startup-align-all-tables t)
3930 ("noalign" org-startup-align-all-tables nil)
3931 ("customtime" org-display-custom-times t)
3932 ("logging" org-log-done t)
3933 ("logdone" org-log-done t)
3934 ("nologging" org-log-done nil)
3935 ("lognotedone" org-log-done done push)
3936 ("lognotestate" org-log-done state push)
3937 ("lognoteclock-out" org-log-done clock-out push)
3938 ("logrepeat" org-log-repeat t)
3939 ("nologrepeat" org-log-repeat nil)
3940 ("constcgs" constants-unit-system cgs)
3941 ("constSI" constants-unit-system SI))
3942 "Variable associated with STARTUP options for org-mode.
3943 Each element is a list of three items: The startup options as written
3944 in the #+STARTUP line, the corresponding variable, and the value to
3945 set this variable to if the option is found. An optional forth element PUSH
3946 means to push this value onto the list in the variable.")
3948 (defun org-set-regexps-and-options ()
3949 "Precompute regular expressions for current buffer."
3950 (when (org-mode-p)
3951 (org-set-local 'org-todo-kwd-alist nil)
3952 (org-set-local 'org-todo-key-alist nil)
3953 (org-set-local 'org-todo-key-trigger nil)
3954 (org-set-local 'org-todo-keywords-1 nil)
3955 (org-set-local 'org-done-keywords nil)
3956 (org-set-local 'org-todo-heads nil)
3957 (org-set-local 'org-todo-sets nil)
3958 (org-set-local 'org-todo-log-states nil)
3959 (let ((re (org-make-options-regexp
3960 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3961 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
3962 "CONSTANTS" "PROPERTY")))
3963 (splitre "[ \t]+")
3964 kwds kws0 kwsa key value cat arch tags const links hw dws
3965 tail sep kws1 prio props
3966 ex log note)
3967 (save-excursion
3968 (save-restriction
3969 (widen)
3970 (goto-char (point-min))
3971 (while (re-search-forward re nil t)
3972 (setq key (match-string 1) value (org-match-string-no-properties 2))
3973 (cond
3974 ((equal key "CATEGORY")
3975 (if (string-match "[ \t]+$" value)
3976 (setq value (replace-match "" t t value)))
3977 (setq cat (intern value)))
3978 ((member key '("SEQ_TODO" "TODO"))
3979 (push (cons 'sequence (org-split-string value splitre)) kwds))
3980 ((equal key "TYP_TODO")
3981 (push (cons 'type (org-split-string value splitre)) kwds))
3982 ((equal key "TAGS")
3983 (setq tags (append tags (org-split-string value splitre))))
3984 ((equal key "COLUMNS")
3985 (org-set-local 'org-columns-default-format value))
3986 ((equal key "LINK")
3987 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3988 (push (cons (match-string 1 value)
3989 (org-trim (match-string 2 value)))
3990 links)))
3991 ((equal key "PRIORITIES")
3992 (setq prio (org-split-string value " +")))
3993 ((equal key "PROPERTY")
3994 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3995 (push (cons (match-string 1 value) (match-string 2 value))
3996 props)))
3997 ((equal key "CONSTANTS")
3998 (setq const (append const (org-split-string value splitre))))
3999 ((equal key "STARTUP")
4000 (let ((opts (org-split-string value splitre))
4001 l var val)
4002 (while (setq l (pop opts))
4003 (when (setq l (assoc l org-startup-options))
4004 (setq var (nth 1 l) val (nth 2 l))
4005 (if (not (nth 3 l))
4006 (set (make-local-variable var) val)
4007 (if (not (listp (symbol-value var)))
4008 (set (make-local-variable var) nil))
4009 (set (make-local-variable var) (symbol-value var))
4010 (add-to-list var val))))))
4011 ((equal key "ARCHIVE")
4012 (string-match " *$" value)
4013 (setq arch (replace-match "" t t value))
4014 (remove-text-properties 0 (length arch)
4015 '(face t fontified t) arch)))
4017 (and cat (org-set-local 'org-category cat))
4018 (when prio
4019 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4020 (setq prio (mapcar 'string-to-char prio))
4021 (org-set-local 'org-highest-priority (nth 0 prio))
4022 (org-set-local 'org-lowest-priority (nth 1 prio))
4023 (org-set-local 'org-default-priority (nth 2 prio)))
4024 (and props (org-set-local 'org-local-properties (nreverse props)))
4025 (and arch (org-set-local 'org-archive-location arch))
4026 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4027 ;; Process the TODO keywords
4028 (unless kwds
4029 ;; Use the global values as if they had been given locally.
4030 (setq kwds (default-value 'org-todo-keywords))
4031 (if (stringp (car kwds))
4032 (setq kwds (list (cons org-todo-interpretation
4033 (default-value 'org-todo-keywords)))))
4034 (setq kwds (reverse kwds)))
4035 (setq kwds (nreverse kwds))
4036 (let (inter kws kw)
4037 (while (setq kws (pop kwds))
4038 (setq inter (pop kws) sep (member "|" kws)
4039 kws0 (delete "|" (copy-sequence kws))
4040 kwsa nil
4041 kws1 (mapcar
4042 (lambda (x)
4043 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4044 (progn
4045 (setq kw (match-string 1 x)
4046 ex (and (match-end 2) (match-string 2 x))
4047 log (and ex (string-match "@" ex))
4048 key (and ex (substring ex 0 1)))
4049 (if (equal key "@") (setq key nil))
4050 (push (cons kw (and key (string-to-char key))) kwsa)
4051 (and log (push kw org-todo-log-states))
4053 (error "Invalid TODO keyword %s" x)))
4054 kws0)
4055 kwsa (if kwsa (append '((:startgroup))
4056 (nreverse kwsa)
4057 '((:endgroup))))
4058 hw (car kws1)
4059 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4060 tail (list inter hw (car dws) (org-last dws)))
4061 (add-to-list 'org-todo-heads hw 'append)
4062 (push kws1 org-todo-sets)
4063 (setq org-done-keywords (append org-done-keywords dws nil))
4064 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4065 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4066 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4067 (setq org-todo-sets (nreverse org-todo-sets)
4068 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4069 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4070 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4071 ;; Process the constants
4072 (when const
4073 (let (e cst)
4074 (while (setq e (pop const))
4075 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4076 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4077 (setq org-table-formula-constants-local cst)))
4079 ;; Process the tags.
4080 (when tags
4081 (let (e tgs)
4082 (while (setq e (pop tags))
4083 (cond
4084 ((equal e "{") (push '(:startgroup) tgs))
4085 ((equal e "}") (push '(:endgroup) tgs))
4086 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4087 (push (cons (match-string 1 e)
4088 (string-to-char (match-string 2 e)))
4089 tgs))
4090 (t (push (list e) tgs))))
4091 (org-set-local 'org-tag-alist nil)
4092 (while (setq e (pop tgs))
4093 (or (and (stringp (car e))
4094 (assoc (car e) org-tag-alist))
4095 (push e org-tag-alist))))))
4097 ;; Compute the regular expressions and other local variables
4098 (if (not org-done-keywords)
4099 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4100 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4101 (length org-scheduled-string)))
4102 org-drawer-regexp
4103 (concat "^[ \t]*:\\("
4104 (mapconcat 'regexp-quote org-drawers "\\|")
4105 "\\):[ \t]*$")
4106 org-not-done-keywords
4107 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4108 org-todo-regexp
4109 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4110 "\\|") "\\)\\>")
4111 org-not-done-regexp
4112 (concat "\\<\\("
4113 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4114 "\\)\\>")
4115 org-todo-line-regexp
4116 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4117 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4118 "\\)\\>\\)?[ \t]*\\(.*\\)")
4119 org-nl-done-regexp
4120 (concat "\n\\*+[ \t]+"
4121 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4122 "\\)" "\\>")
4123 org-todo-line-tags-regexp
4124 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4125 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4126 (org-re
4127 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4128 org-looking-at-done-regexp
4129 (concat "^" "\\(?:"
4130 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4131 "\\>")
4132 org-deadline-regexp (concat "\\<" org-deadline-string)
4133 org-deadline-time-regexp
4134 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4135 org-deadline-line-regexp
4136 (concat "\\<\\(" org-deadline-string "\\).*")
4137 org-scheduled-regexp
4138 (concat "\\<" org-scheduled-string)
4139 org-scheduled-time-regexp
4140 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4141 org-closed-time-regexp
4142 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4143 org-keyword-time-regexp
4144 (concat "\\<\\(" org-scheduled-string
4145 "\\|" org-deadline-string
4146 "\\|" org-closed-string
4147 "\\|" org-clock-string "\\)"
4148 " *[[<]\\([^]>]+\\)[]>]")
4149 org-keyword-time-not-clock-regexp
4150 (concat "\\<\\(" org-scheduled-string
4151 "\\|" org-deadline-string
4152 "\\|" org-closed-string
4153 "\\)"
4154 " *[[<]\\([^]>]+\\)[]>]")
4155 org-maybe-keyword-time-regexp
4156 (concat "\\(\\<\\(" org-scheduled-string
4157 "\\|" org-deadline-string
4158 "\\|" org-closed-string
4159 "\\|" org-clock-string "\\)\\)?"
4160 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4161 org-planning-or-clock-line-re
4162 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4163 "\\|" org-deadline-string
4164 "\\|" org-closed-string "\\|" org-clock-string
4165 "\\)\\>\\)")
4168 (org-set-font-lock-defaults)))
4170 (defun org-remove-keyword-keys (list)
4171 (mapcar (lambda (x)
4172 (if (string-match "(..?)$" x)
4173 (substring x 0 (match-beginning 0))
4175 list))
4177 ;;; Some variables ujsed in various places
4179 (defvar org-window-configuration nil
4180 "Used in various places to store a window configuration.")
4181 (defvar org-finish-function nil
4182 "Function to be called when `C-c C-c' is used.
4183 This is for getting out of special buffers like remember.")
4185 ;;; Foreign variables, to inform the compiler
4187 ;; XEmacs only
4188 (defvar outline-mode-menu-heading)
4189 (defvar outline-mode-menu-show)
4190 (defvar outline-mode-menu-hide)
4191 (defvar zmacs-regions) ; XEmacs regions
4192 ;; Emacs only
4193 (defvar mark-active)
4195 ;; Packages that org-mode interacts with
4196 (defvar calc-embedded-close-formula)
4197 (defvar calc-embedded-open-formula)
4198 (defvar font-lock-unfontify-region-function)
4199 (defvar org-goto-start-pos)
4200 (defvar vm-message-pointer)
4201 (defvar vm-folder-directory)
4202 (defvar wl-summary-buffer-elmo-folder)
4203 (defvar wl-summary-buffer-folder-name)
4204 (defvar gnus-other-frame-object)
4205 (defvar gnus-group-name)
4206 (defvar gnus-article-current)
4207 (defvar w3m-current-url)
4208 (defvar w3m-current-title)
4209 (defvar mh-progs)
4210 (defvar mh-current-folder)
4211 (defvar mh-show-folder-buffer)
4212 (defvar mh-index-folder)
4213 (defvar mh-searcher)
4214 (defvar calendar-mode-map)
4215 (defvar Info-current-file)
4216 (defvar Info-current-node)
4217 (defvar texmathp-why)
4218 (defvar remember-save-after-remembering)
4219 (defvar remember-data-file)
4220 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
4221 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
4222 (defvar org-latex-regexps)
4223 (defvar constants-unit-system)
4225 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4227 ;; FIXME: Occasionally check by commenting these, to make sure
4228 ;; no other functions uses these, forgetting to let-bind them.
4229 (defvar entry)
4230 (defvar state)
4231 (defvar last-state)
4232 (defvar date)
4233 (defvar description)
4236 ;; Defined somewhere in this file, but used before definition.
4237 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4238 (defvar org-agenda-buffer-name)
4239 (defvar org-agenda-undo-list)
4240 (defvar org-agenda-pending-undo-list)
4241 (defvar org-agenda-overriding-header)
4242 (defvar orgtbl-mode)
4243 (defvar org-html-entities)
4244 (defvar org-struct-menu)
4245 (defvar org-org-menu)
4246 (defvar org-tbl-menu)
4247 (defvar org-agenda-keymap)
4249 ;;;; Emacs/XEmacs compatibility
4251 ;; Overlay compatibility functions
4252 (defun org-make-overlay (beg end &optional buffer)
4253 (if (featurep 'xemacs)
4254 (make-extent beg end buffer)
4255 (make-overlay beg end buffer)))
4256 (defun org-delete-overlay (ovl)
4257 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4258 (defun org-detach-overlay (ovl)
4259 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4260 (defun org-move-overlay (ovl beg end &optional buffer)
4261 (if (featurep 'xemacs)
4262 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4263 (move-overlay ovl beg end buffer)))
4264 (defun org-overlay-put (ovl prop value)
4265 (if (featurep 'xemacs)
4266 (set-extent-property ovl prop value)
4267 (overlay-put ovl prop value)))
4268 (defun org-overlay-display (ovl text &optional face evap)
4269 "Make overlay OVL display TEXT with face FACE."
4270 (if (featurep 'xemacs)
4271 (let ((gl (make-glyph text)))
4272 (and face (set-glyph-face gl face))
4273 (set-extent-property ovl 'invisible t)
4274 (set-extent-property ovl 'end-glyph gl))
4275 (overlay-put ovl 'display text)
4276 (if face (overlay-put ovl 'face face))
4277 (if evap (overlay-put ovl 'evaporate t))))
4278 (defun org-overlay-before-string (ovl text &optional face evap)
4279 "Make overlay OVL display TEXT with face FACE."
4280 (if (featurep 'xemacs)
4281 (let ((gl (make-glyph text)))
4282 (and face (set-glyph-face gl face))
4283 (set-extent-property ovl 'begin-glyph gl))
4284 (if face (org-add-props text nil 'face face))
4285 (overlay-put ovl 'before-string text)
4286 (if evap (overlay-put ovl 'evaporate t))))
4287 (defun org-overlay-get (ovl prop)
4288 (if (featurep 'xemacs)
4289 (extent-property ovl prop)
4290 (overlay-get ovl prop)))
4291 (defun org-overlays-at (pos)
4292 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4293 (defun org-overlays-in (&optional start end)
4294 (if (featurep 'xemacs)
4295 (extent-list nil start end)
4296 (overlays-in start end)))
4297 (defun org-overlay-start (o)
4298 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4299 (defun org-overlay-end (o)
4300 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4301 (defun org-find-overlays (prop &optional pos delete)
4302 "Find all overlays specifying PROP at POS or point.
4303 If DELETE is non-nil, delete all those overlays."
4304 (let ((overlays (org-overlays-at (or pos (point))))
4305 ov found)
4306 (while (setq ov (pop overlays))
4307 (if (org-overlay-get ov prop)
4308 (if delete (org-delete-overlay ov) (push ov found))))
4309 found))
4311 ;; Region compatibility
4313 (defun org-add-hook (hook function &optional append local)
4314 "Add-hook, compatible with both Emacsen."
4315 (if (and local (featurep 'xemacs))
4316 (add-local-hook hook function append)
4317 (add-hook hook function append local)))
4319 (defvar org-ignore-region nil
4320 "To temporarily disable the active region.")
4322 (defun org-region-active-p ()
4323 "Is `transient-mark-mode' on and the region active?
4324 Works on both Emacs and XEmacs."
4325 (if org-ignore-region
4327 (if (featurep 'xemacs)
4328 (and zmacs-regions (region-active-p))
4329 (and transient-mark-mode mark-active))))
4331 ;; Invisibility compatibility
4333 (defun org-add-to-invisibility-spec (arg)
4334 "Add elements to `buffer-invisibility-spec'.
4335 See documentation for `buffer-invisibility-spec' for the kind of elements
4336 that can be added."
4337 (cond
4338 ((fboundp 'add-to-invisibility-spec)
4339 (add-to-invisibility-spec arg))
4340 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4341 (setq buffer-invisibility-spec (list arg)))
4343 (setq buffer-invisibility-spec
4344 (cons arg buffer-invisibility-spec)))))
4346 (defun org-remove-from-invisibility-spec (arg)
4347 "Remove elements from `buffer-invisibility-spec'."
4348 (if (fboundp 'remove-from-invisibility-spec)
4349 (remove-from-invisibility-spec arg)
4350 (if (consp buffer-invisibility-spec)
4351 (setq buffer-invisibility-spec
4352 (delete arg buffer-invisibility-spec)))))
4354 (defun org-in-invisibility-spec-p (arg)
4355 "Is ARG a member of `buffer-invisibility-spec'?"
4356 (if (consp buffer-invisibility-spec)
4357 (member arg buffer-invisibility-spec)
4358 nil))
4360 ;;;; Define the Org-mode
4362 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4363 (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."))
4366 ;; We use a before-change function to check if a table might need
4367 ;; an update.
4368 (defvar org-table-may-need-update t
4369 "Indicates that a table might need an update.
4370 This variable is set by `org-before-change-function'.
4371 `org-table-align' sets it back to nil.")
4372 (defvar org-mode-map)
4373 (defvar org-mode-hook nil)
4374 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4375 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4376 (defvar org-table-buffer-is-an nil)
4377 (defconst org-outline-regexp "\\*+ ")
4379 ;;;###autoload
4380 (define-derived-mode org-mode outline-mode "Org"
4381 "Outline-based notes management and organizer, alias
4382 \"Carsten's outline-mode for keeping track of everything.\"
4384 Org-mode develops organizational tasks around a NOTES file which
4385 contains information about projects as plain text. Org-mode is
4386 implemented on top of outline-mode, which is ideal to keep the content
4387 of large files well structured. It supports ToDo items, deadlines and
4388 time stamps, which magically appear in the diary listing of the Emacs
4389 calendar. Tables are easily created with a built-in table editor.
4390 Plain text URL-like links connect to websites, emails (VM), Usenet
4391 messages (Gnus), BBDB entries, and any files related to the project.
4392 For printing and sharing of notes, an Org-mode file (or a part of it)
4393 can be exported as a structured ASCII or HTML file.
4395 The following commands are available:
4397 \\{org-mode-map}"
4399 ;; Get rid of Outline menus, they are not needed
4400 ;; Need to do this here because define-derived-mode sets up
4401 ;; the keymap so late. Still, it is a waste to call this each time
4402 ;; we switch another buffer into org-mode.
4403 (if (featurep 'xemacs)
4404 (when (boundp 'outline-mode-menu-heading)
4405 ;; Assume this is Greg's port, it used easymenu
4406 (easy-menu-remove outline-mode-menu-heading)
4407 (easy-menu-remove outline-mode-menu-show)
4408 (easy-menu-remove outline-mode-menu-hide))
4409 (define-key org-mode-map [menu-bar headings] 'undefined)
4410 (define-key org-mode-map [menu-bar hide] 'undefined)
4411 (define-key org-mode-map [menu-bar show] 'undefined))
4413 (easy-menu-add org-org-menu)
4414 (easy-menu-add org-tbl-menu)
4415 (org-install-agenda-files-menu)
4416 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4417 (org-add-to-invisibility-spec '(org-cwidth))
4418 (when (featurep 'xemacs)
4419 (org-set-local 'line-move-ignore-invisible t))
4420 (org-set-local 'outline-regexp org-outline-regexp)
4421 (org-set-local 'outline-level 'org-outline-level)
4422 (when (and org-ellipsis
4423 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4424 (fboundp 'make-glyph-code))
4425 (unless org-display-table
4426 (setq org-display-table (make-display-table)))
4427 (set-display-table-slot
4428 org-display-table 4
4429 (vconcat (mapcar
4430 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4431 org-ellipsis)))
4432 (if (stringp org-ellipsis) org-ellipsis "..."))))
4433 (setq buffer-display-table org-display-table))
4434 (org-set-regexps-and-options)
4435 ;; Calc embedded
4436 (org-set-local 'calc-embedded-open-mode "# ")
4437 (modify-syntax-entry ?# "<")
4438 (modify-syntax-entry ?@ "w")
4439 (if org-startup-truncated (setq truncate-lines t))
4440 (org-set-local 'font-lock-unfontify-region-function
4441 'org-unfontify-region)
4442 ;; Activate before-change-function
4443 (org-set-local 'org-table-may-need-update t)
4444 (org-add-hook 'before-change-functions 'org-before-change-function nil
4445 'local)
4446 ;; Check for running clock before killing a buffer
4447 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4448 ;; Paragraphs and auto-filling
4449 (org-set-autofill-regexps)
4450 (setq indent-line-function 'org-indent-line-function)
4451 (org-update-radio-target-regexp)
4453 ;; Comment characters
4454 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4455 (org-set-local 'comment-padding " ")
4457 ;; Make isearch reveal context
4458 (if (or (featurep 'xemacs)
4459 (not (boundp 'outline-isearch-open-invisible-function)))
4460 ;; Emacs 21 and XEmacs make use of the hook
4461 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4462 ;; Emacs 22 deals with this through a special variable
4463 (org-set-local 'outline-isearch-open-invisible-function
4464 (lambda (&rest ignore) (org-show-context 'isearch))))
4466 ;; If empty file that did not turn on org-mode automatically, make it to.
4467 (if (and org-insert-mode-line-in-empty-file
4468 (interactive-p)
4469 (= (point-min) (point-max)))
4470 (insert "# -*- mode: org -*-\n\n"))
4472 (unless org-inhibit-startup
4473 (when org-startup-align-all-tables
4474 (let ((bmp (buffer-modified-p)))
4475 (org-table-map-tables 'org-table-align)
4476 (set-buffer-modified-p bmp)))
4477 (org-cycle-hide-drawers 'all)
4478 (cond
4479 ((eq org-startup-folded t)
4480 (org-cycle '(4)))
4481 ((eq org-startup-folded 'content)
4482 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4483 (org-cycle '(4)) (org-cycle '(4)))))))
4485 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4487 (defsubst org-call-with-arg (command arg)
4488 "Call COMMAND interactively, but pretend prefix are was ARG."
4489 (let ((current-prefix-arg arg)) (call-interactively command)))
4491 (defsubst org-current-line (&optional pos)
4492 (save-excursion
4493 (and pos (goto-char pos))
4494 ;; works also in narrowed buffer, because we start at 1, not point-min
4495 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4497 (defun org-current-time ()
4498 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4499 (if (> org-time-stamp-rounding-minutes 0)
4500 (let ((r org-time-stamp-rounding-minutes)
4501 (time (decode-time)))
4502 (apply 'encode-time
4503 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4504 (nthcdr 2 time))))
4505 (current-time)))
4507 (defun org-add-props (string plist &rest props)
4508 "Add text properties to entire string, from beginning to end.
4509 PLIST may be a list of properties, PROPS are individual properties and values
4510 that will be added to PLIST. Returns the string that was modified."
4511 (add-text-properties
4512 0 (length string) (if props (append plist props) plist) string)
4513 string)
4514 (put 'org-add-props 'lisp-indent-function 2)
4517 ;;;; Font-Lock stuff, including the activators
4519 (defvar org-mouse-map (make-sparse-keymap))
4520 (org-defkey org-mouse-map
4521 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4522 (org-defkey org-mouse-map
4523 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4524 (when org-mouse-1-follows-link
4525 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4526 (when org-tab-follows-link
4527 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4528 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4529 (when org-return-follows-link
4530 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4531 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4533 (require 'font-lock)
4535 (defconst org-non-link-chars "]\t\n\r<>")
4536 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4537 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4538 (defvar org-link-re-with-space nil
4539 "Matches a link with spaces, optional angular brackets around it.")
4540 (defvar org-link-re-with-space2 nil
4541 "Matches a link with spaces, optional angular brackets around it.")
4542 (defvar org-angle-link-re nil
4543 "Matches link with angular brackets, spaces are allowed.")
4544 (defvar org-plain-link-re nil
4545 "Matches plain link, without spaces.")
4546 (defvar org-bracket-link-regexp nil
4547 "Matches a link in double brackets.")
4548 (defvar org-bracket-link-analytic-regexp nil
4549 "Regular expression used to analyze links.
4550 Here is what the match groups contain after a match:
4551 1: http:
4552 2: http
4553 3: path
4554 4: [desc]
4555 5: desc")
4556 (defvar org-any-link-re nil
4557 "Regular expression matching any link.")
4559 (defun org-make-link-regexps ()
4560 "Update the link regular expressions.
4561 This should be called after the variable `org-link-types' has changed."
4562 (setq org-link-re-with-space
4563 (concat
4564 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4565 "\\([^" org-non-link-chars " ]"
4566 "[^" org-non-link-chars "]*"
4567 "[^" org-non-link-chars " ]\\)>?")
4568 org-link-re-with-space2
4569 (concat
4570 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4571 "\\([^" org-non-link-chars " ]"
4572 "[^]\t\n\r]*"
4573 "[^" org-non-link-chars " ]\\)>?")
4574 org-angle-link-re
4575 (concat
4576 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4577 "\\([^" org-non-link-chars " ]"
4578 "[^" org-non-link-chars "]*"
4579 "\\)>")
4580 org-plain-link-re
4581 (concat
4582 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4583 "\\([^]\t\n\r<>,;() ]+\\)")
4584 org-bracket-link-regexp
4585 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4586 org-bracket-link-analytic-regexp
4587 (concat
4588 "\\[\\["
4589 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4590 "\\([^]]+\\)"
4591 "\\]"
4592 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4593 "\\]")
4594 org-any-link-re
4595 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4596 org-angle-link-re "\\)\\|\\("
4597 org-plain-link-re "\\)")))
4599 (org-make-link-regexps)
4601 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4602 "Regular expression for fast time stamp matching.")
4603 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4604 "Regular expression for fast time stamp matching.")
4605 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4606 "Regular expression matching time strings for analysis.
4607 This one does not require the space after the date.")
4608 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4609 "Regular expression matching time strings for analysis.")
4610 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4611 "Regular expression matching time stamps, with groups.")
4612 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4613 "Regular expression matching time stamps (also [..]), with groups.")
4614 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4615 "Regular expression matching a time stamp range.")
4616 (defconst org-tr-regexp-both
4617 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4618 "Regular expression matching a time stamp range.")
4619 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4620 org-ts-regexp "\\)?")
4621 "Regular expression matching a time stamp or time stamp range.")
4622 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4623 org-ts-regexp-both "\\)?")
4624 "Regular expression matching a time stamp or time stamp range.
4625 The time stamps may be either active or inactive.")
4627 (defvar org-emph-face nil)
4629 (defun org-do-emphasis-faces (limit)
4630 "Run through the buffer and add overlays to links."
4631 (let (rtn)
4632 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4633 (if (not (= (char-after (match-beginning 3))
4634 (char-after (match-beginning 4))))
4635 (progn
4636 (setq rtn t)
4637 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4638 'face
4639 (nth 1 (assoc (match-string 3)
4640 org-emphasis-alist)))
4641 (add-text-properties (match-beginning 2) (match-end 2)
4642 '(font-lock-multiline t))
4643 (backward-char 1))))
4644 rtn))
4646 (defun org-emphasize (&optional char)
4647 "Insert or change an emphasis, i.e. a font like bold or italic.
4648 If there is an active region, change that region to a new emphasis.
4649 If there is no region, just insert the marker characters and position
4650 the cursor between them.
4651 CHAR should be either the marker character, or the first character of the
4652 HTML tag associated with that emphasis. If CHAR is a space, the means
4653 to remove the emphasis of the selected region.
4654 If char is not given (for example in an interactive call) it
4655 will be prompted for."
4656 (interactive)
4657 (let ((eal org-emphasis-alist) e det
4658 (erc org-emphasis-regexp-components)
4659 (prompt "")
4660 (string "") beg end move tag c s)
4661 (if (org-region-active-p)
4662 (setq beg (region-beginning) end (region-end)
4663 string (buffer-substring beg end))
4664 (setq move t))
4666 (while (setq e (pop eal))
4667 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4668 c (aref tag 0))
4669 (push (cons c (string-to-char (car e))) det)
4670 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4671 (substring tag 1)))))
4672 (unless char
4673 (message "%s" (concat "Emphasis marker or tag:" prompt))
4674 (setq char (read-char-exclusive)))
4675 (setq char (or (cdr (assoc char det)) char))
4676 (if (equal char ?\ )
4677 (setq s "" move nil)
4678 (unless (assoc (char-to-string char) org-emphasis-alist)
4679 (error "No such emphasis marker: \"%c\"" char))
4680 (setq s (char-to-string char)))
4681 (while (and (> (length string) 1)
4682 (equal (substring string 0 1) (substring string -1))
4683 (assoc (substring string 0 1) org-emphasis-alist))
4684 (setq string (substring string 1 -1)))
4685 (setq string (concat s string s))
4686 (if beg (delete-region beg end))
4687 (unless (or (bolp)
4688 (string-match (concat "[" (nth 0 erc) "\n]")
4689 (char-to-string (char-before (point)))))
4690 (insert " "))
4691 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4692 (char-to-string (char-after (point))))
4693 (insert " ") (backward-char 1))
4694 (insert string)
4695 (and move (backward-char 1))))
4697 (defconst org-nonsticky-props
4698 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4701 (defun org-activate-plain-links (limit)
4702 "Run through the buffer and add overlays to links."
4703 (catch 'exit
4704 (let (f)
4705 (while (re-search-forward org-plain-link-re limit t)
4706 (setq f (get-text-property (match-beginning 0) 'face))
4707 (if (or (eq f 'org-tag)
4708 (and (listp f) (memq 'org-tag f)))
4710 (add-text-properties (match-beginning 0) (match-end 0)
4711 (list 'mouse-face 'highlight
4712 'rear-nonsticky org-nonsticky-props
4713 'keymap org-mouse-map
4715 (throw 'exit t))))))
4717 (defun org-activate-code (limit)
4718 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
4719 (unless (get-text-property (match-beginning 1) 'face)
4720 (remove-text-properties (match-beginning 0) (match-end 0)
4721 '(display t invisible t intangible t))
4722 t)))
4724 (defun org-activate-angle-links (limit)
4725 "Run through the buffer and add overlays to links."
4726 (if (re-search-forward org-angle-link-re limit t)
4727 (progn
4728 (add-text-properties (match-beginning 0) (match-end 0)
4729 (list 'mouse-face 'highlight
4730 'rear-nonsticky org-nonsticky-props
4731 'keymap org-mouse-map
4733 t)))
4735 (defmacro org-maybe-intangible (props)
4736 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
4737 In emacs 21, invisible text is not avoided by the command loop, so the
4738 intangible property is needed to make sure point skips this text.
4739 In Emacs 22, this is not necessary. The intangible text property has
4740 led to problems with flyspell. These problems are fixed in flyspell.el,
4741 but we still avoid setting the property in Emacs 22 and later.
4742 We use a macro so that the test can happen at compilation time."
4743 (if (< emacs-major-version 22)
4744 `(append '(intangible t) ,props)
4745 props))
4747 (defun org-activate-bracket-links (limit)
4748 "Run through the buffer and add overlays to bracketed links."
4749 (if (re-search-forward org-bracket-link-regexp limit t)
4750 (let* ((help (concat "LINK: "
4751 (org-match-string-no-properties 1)))
4752 ;; FIXME: above we should remove the escapes.
4753 ;; but that requires another match, protecting match data,
4754 ;; a lot of overhead for font-lock.
4755 (ip (org-maybe-intangible
4756 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4757 'keymap org-mouse-map 'mouse-face 'highlight
4758 'help-echo help)))
4759 (vp (list 'rear-nonsticky org-nonsticky-props
4760 'keymap org-mouse-map 'mouse-face 'highlight
4761 'help-echo help)))
4762 ;; We need to remove the invisible property here. Table narrowing
4763 ;; may have made some of this invisible.
4764 (remove-text-properties (match-beginning 0) (match-end 0)
4765 '(invisible nil))
4766 (if (match-end 3)
4767 (progn
4768 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4769 (add-text-properties (match-beginning 3) (match-end 3) vp)
4770 (add-text-properties (match-end 3) (match-end 0) ip))
4771 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4772 (add-text-properties (match-beginning 1) (match-end 1) vp)
4773 (add-text-properties (match-end 1) (match-end 0) ip))
4774 t)))
4776 (defun org-activate-dates (limit)
4777 "Run through the buffer and add overlays to dates."
4778 (if (re-search-forward org-tsr-regexp-both limit t)
4779 (progn
4780 (add-text-properties (match-beginning 0) (match-end 0)
4781 (list 'mouse-face 'highlight
4782 'rear-nonsticky org-nonsticky-props
4783 'keymap org-mouse-map))
4784 (when org-display-custom-times
4785 (if (match-end 3)
4786 (org-display-custom-time (match-beginning 3) (match-end 3)))
4787 (org-display-custom-time (match-beginning 1) (match-end 1)))
4788 t)))
4790 (defvar org-target-link-regexp nil
4791 "Regular expression matching radio targets in plain text.")
4792 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4793 "Regular expression matching a link target.")
4794 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4795 "Regular expression matching a radio target.")
4796 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4797 "Regular expression matching any target.")
4799 (defun org-activate-target-links (limit)
4800 "Run through the buffer and add overlays to target matches."
4801 (when org-target-link-regexp
4802 (let ((case-fold-search t))
4803 (if (re-search-forward org-target-link-regexp limit t)
4804 (progn
4805 (add-text-properties (match-beginning 0) (match-end 0)
4806 (list 'mouse-face 'highlight
4807 'rear-nonsticky org-nonsticky-props
4808 'keymap org-mouse-map
4809 'help-echo "Radio target link"
4810 'org-linked-text t))
4811 t)))))
4813 (defun org-update-radio-target-regexp ()
4814 "Find all radio targets in this file and update the regular expression."
4815 (interactive)
4816 (when (memq 'radio org-activate-links)
4817 (setq org-target-link-regexp
4818 (org-make-target-link-regexp (org-all-targets 'radio)))
4819 (org-restart-font-lock)))
4821 (defun org-hide-wide-columns (limit)
4822 (let (s e)
4823 (setq s (text-property-any (point) (or limit (point-max))
4824 'org-cwidth t))
4825 (when s
4826 (setq e (next-single-property-change s 'org-cwidth))
4827 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4828 (goto-char e)
4829 t)))
4831 (defun org-restart-font-lock ()
4832 "Restart font-lock-mode, to force refontification."
4833 (when (and (boundp 'font-lock-mode) font-lock-mode)
4834 (font-lock-mode -1)
4835 (font-lock-mode 1)))
4837 (defun org-all-targets (&optional radio)
4838 "Return a list of all targets in this file.
4839 With optional argument RADIO, only find radio targets."
4840 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4841 rtn)
4842 (save-excursion
4843 (goto-char (point-min))
4844 (while (re-search-forward re nil t)
4845 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4846 rtn)))
4848 (defun org-make-target-link-regexp (targets)
4849 "Make regular expression matching all strings in TARGETS.
4850 The regular expression finds the targets also if there is a line break
4851 between words."
4852 (and targets
4853 (concat
4854 "\\<\\("
4855 (mapconcat
4856 (lambda (x)
4857 (while (string-match " +" x)
4858 (setq x (replace-match "\\s-+" t t x)))
4860 targets
4861 "\\|")
4862 "\\)\\>")))
4864 (defun org-activate-tags (limit)
4865 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4866 (progn
4867 (add-text-properties (match-beginning 1) (match-end 1)
4868 (list 'mouse-face 'highlight
4869 'rear-nonsticky org-nonsticky-props
4870 'keymap org-mouse-map))
4871 t)))
4873 (defun org-outline-level ()
4874 (save-excursion
4875 (looking-at outline-regexp)
4876 (if (match-beginning 1)
4877 (+ (org-get-string-indentation (match-string 1)) 1000)
4878 (1- (- (match-end 0) (match-beginning 0))))))
4880 (defvar org-font-lock-keywords nil)
4882 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
4883 "Regular expression matching a property line.")
4885 (defun org-set-font-lock-defaults ()
4886 (let* ((em org-fontify-emphasized-text)
4887 (lk org-activate-links)
4888 (org-font-lock-extra-keywords
4889 (list
4890 ;; Headlines
4891 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4892 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4893 ;; Table lines
4894 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4895 (1 'org-table t))
4896 ;; Table internals
4897 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4898 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4899 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4900 ;; Drawers
4901 (list org-drawer-regexp '(0 'org-special-keyword t))
4902 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4903 ;; Properties
4904 (list org-property-re
4905 '(1 'org-special-keyword t)
4906 '(3 'org-property-value t))
4907 (if org-format-transports-properties-p
4908 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4909 ;; Links
4910 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4911 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4912 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4913 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4914 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4915 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4916 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4917 '(org-hide-wide-columns (0 nil append))
4918 ;; TODO lines
4919 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4920 '(1 (org-get-todo-face 1) t))
4921 ;; DONE
4922 (if org-fontify-done-headline
4923 (list (concat "^[*]+ +\\<\\("
4924 (mapconcat 'regexp-quote org-done-keywords "\\|")
4925 "\\)\\(.*\\)")
4926 '(2 'org-headline-done t))
4927 nil)
4928 ;; Priorities
4929 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4930 ;; Special keywords
4931 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4932 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4933 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4934 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4935 ;; Emphasis
4936 (if em
4937 (if (featurep 'xemacs)
4938 '(org-do-emphasis-faces (0 nil append))
4939 '(org-do-emphasis-faces)))
4940 ;; Checkboxes
4941 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4942 2 'bold prepend)
4943 (if org-provide-checkbox-statistics
4944 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4945 (0 (org-get-checkbox-statistics-face) t)))
4946 ;; COMMENT
4947 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4948 "\\|" org-quote-string "\\)\\>")
4949 '(1 'org-special-keyword t))
4950 '("^#.*" (0 'font-lock-comment-face t))
4951 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
4952 ;; Code
4953 '(org-activate-code (1 'org-code t))
4954 ;; Priorities
4955 '("^\\*+ .*?\\[#A\\].*" (0 'bold prepend))
4956 '("^\\*+ .*?\\[#C\\].*" (0 'italic prepend))
4958 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4959 ;; Now set the full font-lock-keywords
4960 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4961 (org-set-local 'font-lock-defaults
4962 '(org-font-lock-keywords t nil nil backward-paragraph))
4963 (kill-local-variable 'font-lock-keywords) nil))
4965 (defvar org-m nil)
4966 (defvar org-l nil)
4967 (defvar org-f nil)
4968 (defun org-get-level-face (n)
4969 "Get the right face for match N in font-lock matching of healdines."
4970 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4971 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4972 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4973 (cond
4974 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4975 ((eq n 2) org-f)
4976 (t (if org-level-color-stars-only nil org-f))))
4978 (defun org-get-todo-face (kwd)
4979 "Get the right face for a TODO keyword KWD.
4980 If KWD is a number, get the corresponding match group."
4981 (if (numberp kwd) (setq kwd (match-string kwd)))
4982 (or (cdr (assoc kwd org-todo-keyword-faces))
4983 (and (member kwd org-done-keywords) 'org-done)
4984 'org-todo))
4986 (defun org-unfontify-region (beg end &optional maybe_loudly)
4987 "Remove fontification and activation overlays from links."
4988 (font-lock-default-unfontify-region beg end)
4989 (let* ((buffer-undo-list t)
4990 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4991 (inhibit-modification-hooks t)
4992 deactivate-mark buffer-file-name buffer-file-truename)
4993 (remove-text-properties beg end
4994 '(mouse-face t keymap t org-linked-text t
4995 invisible t intangible t))))
4997 ;;;; Visibility cycling, including org-goto and indirect buffer
4999 ;;; Cycling
5001 (defvar org-cycle-global-status nil)
5002 (make-variable-buffer-local 'org-cycle-global-status)
5003 (defvar org-cycle-subtree-status nil)
5004 (make-variable-buffer-local 'org-cycle-subtree-status)
5006 ;;;###autoload
5007 (defun org-cycle (&optional arg)
5008 "Visibility cycling for Org-mode.
5010 - When this function is called with a prefix argument, rotate the entire
5011 buffer through 3 states (global cycling)
5012 1. OVERVIEW: Show only top-level headlines.
5013 2. CONTENTS: Show all headlines of all levels, but no body text.
5014 3. SHOW ALL: Show everything.
5016 - When point is at the beginning of a headline, rotate the subtree started
5017 by this line through 3 different states (local cycling)
5018 1. FOLDED: Only the main headline is shown.
5019 2. CHILDREN: The main headline and the direct children are shown.
5020 From this state, you can move to one of the children
5021 and zoom in further.
5022 3. SUBTREE: Show the entire subtree, including body text.
5024 - When there is a numeric prefix, go up to a heading with level ARG, do
5025 a `show-subtree' and return to the previous cursor position. If ARG
5026 is negative, go up that many levels.
5028 - When point is not at the beginning of a headline, execute
5029 `indent-relative', like TAB normally does. See the option
5030 `org-cycle-emulate-tab' for details.
5032 - Special case: if point is at the beginning of the buffer and there is
5033 no headline in line 1, this function will act as if called with prefix arg.
5034 But only if also the variable `org-cycle-global-at-bob' is t."
5035 (interactive "P")
5036 (let* ((outline-regexp
5037 (if (and (org-mode-p) org-cycle-include-plain-lists)
5038 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5039 outline-regexp))
5040 (bob-special (and org-cycle-global-at-bob (bobp)
5041 (not (looking-at outline-regexp))))
5042 (org-cycle-hook
5043 (if bob-special
5044 (delq 'org-optimize-window-after-visibility-change
5045 (copy-sequence org-cycle-hook))
5046 org-cycle-hook))
5047 (pos (point)))
5049 (if (or bob-special (equal arg '(4)))
5050 ;; special case: use global cycling
5051 (setq arg t))
5053 (cond
5055 ((org-at-table-p 'any)
5056 ;; Enter the table or move to the next field in the table
5057 (or (org-table-recognize-table.el)
5058 (progn
5059 (if arg (org-table-edit-field t)
5060 (org-table-justify-field-maybe)
5061 (call-interactively 'org-table-next-field)))))
5063 ((eq arg t) ;; Global cycling
5065 (cond
5066 ((and (eq last-command this-command)
5067 (eq org-cycle-global-status 'overview))
5068 ;; We just created the overview - now do table of contents
5069 ;; This can be slow in very large buffers, so indicate action
5070 (message "CONTENTS...")
5071 (org-content)
5072 (message "CONTENTS...done")
5073 (setq org-cycle-global-status 'contents)
5074 (run-hook-with-args 'org-cycle-hook 'contents))
5076 ((and (eq last-command this-command)
5077 (eq org-cycle-global-status 'contents))
5078 ;; We just showed the table of contents - now show everything
5079 (show-all)
5080 (message "SHOW ALL")
5081 (setq org-cycle-global-status 'all)
5082 (run-hook-with-args 'org-cycle-hook 'all))
5085 ;; Default action: go to overview
5086 (org-overview)
5087 (message "OVERVIEW")
5088 (setq org-cycle-global-status 'overview)
5089 (run-hook-with-args 'org-cycle-hook 'overview))))
5091 ((and org-drawers org-drawer-regexp
5092 (save-excursion
5093 (beginning-of-line 1)
5094 (looking-at org-drawer-regexp)))
5095 ;; Toggle block visibility
5096 (org-flag-drawer
5097 (not (get-char-property (match-end 0) 'invisible))))
5099 ((integerp arg)
5100 ;; Show-subtree, ARG levels up from here.
5101 (save-excursion
5102 (org-back-to-heading)
5103 (outline-up-heading (if (< arg 0) (- arg)
5104 (- (funcall outline-level) arg)))
5105 (org-show-subtree)))
5107 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5108 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5109 ;; At a heading: rotate between three different views
5110 (org-back-to-heading)
5111 (let ((goal-column 0) eoh eol eos)
5112 ;; First, some boundaries
5113 (save-excursion
5114 (org-back-to-heading)
5115 (save-excursion
5116 (beginning-of-line 2)
5117 (while (and (not (eobp)) ;; this is like `next-line'
5118 (get-char-property (1- (point)) 'invisible))
5119 (beginning-of-line 2)) (setq eol (point)))
5120 (outline-end-of-heading) (setq eoh (point))
5121 (org-end-of-subtree t)
5122 (unless (eobp)
5123 (skip-chars-forward " \t\n")
5124 (beginning-of-line 1) ; in case this is an item
5126 (setq eos (1- (point))))
5127 ;; Find out what to do next and set `this-command'
5128 (cond
5129 ((= eos eoh)
5130 ;; Nothing is hidden behind this heading
5131 (message "EMPTY ENTRY")
5132 (setq org-cycle-subtree-status nil)
5133 (save-excursion
5134 (goto-char eos)
5135 (outline-next-heading)
5136 (if (org-invisible-p) (org-flag-heading nil))))
5137 ((or (>= eol eos)
5138 (not (string-match "\\S-" (buffer-substring eol eos))))
5139 ;; Entire subtree is hidden in one line: open it
5140 (org-show-entry)
5141 (show-children)
5142 (message "CHILDREN")
5143 (save-excursion
5144 (goto-char eos)
5145 (outline-next-heading)
5146 (if (org-invisible-p) (org-flag-heading nil)))
5147 (setq org-cycle-subtree-status 'children)
5148 (run-hook-with-args 'org-cycle-hook 'children))
5149 ((and (eq last-command this-command)
5150 (eq org-cycle-subtree-status 'children))
5151 ;; We just showed the children, now show everything.
5152 (org-show-subtree)
5153 (message "SUBTREE")
5154 (setq org-cycle-subtree-status 'subtree)
5155 (run-hook-with-args 'org-cycle-hook 'subtree))
5157 ;; Default action: hide the subtree.
5158 (hide-subtree)
5159 (message "FOLDED")
5160 (setq org-cycle-subtree-status 'folded)
5161 (run-hook-with-args 'org-cycle-hook 'folded)))))
5163 ;; TAB emulation
5164 (buffer-read-only (org-back-to-heading))
5166 ((org-try-cdlatex-tab))
5168 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5169 (or (not (bolp))
5170 (not (looking-at outline-regexp))))
5171 (call-interactively (global-key-binding "\t")))
5173 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5174 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5175 (or (and (eq org-cycle-emulate-tab 'white)
5176 (= (match-end 0) (point-at-eol)))
5177 (and (eq org-cycle-emulate-tab 'whitestart)
5178 (>= (match-end 0) pos))))
5180 (eq org-cycle-emulate-tab t))
5181 (if (and (looking-at "[ \n\r\t]")
5182 (string-match "^[ \t]*$" (buffer-substring
5183 (point-at-bol) (point))))
5184 (progn
5185 (beginning-of-line 1)
5186 (and (looking-at "[ \t]+") (replace-match ""))))
5187 (call-interactively (global-key-binding "\t")))
5189 (t (save-excursion
5190 (org-back-to-heading)
5191 (org-cycle))))))
5193 ;;;###autoload
5194 (defun org-global-cycle (&optional arg)
5195 "Cycle the global visibility. For details see `org-cycle'."
5196 (interactive "P")
5197 (let ((org-cycle-include-plain-lists
5198 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5199 (if (integerp arg)
5200 (progn
5201 (show-all)
5202 (hide-sublevels arg)
5203 (setq org-cycle-global-status 'contents))
5204 (org-cycle '(4)))))
5206 (defun org-overview ()
5207 "Switch to overview mode, shoing only top-level headlines.
5208 Really, this shows all headlines with level equal or greater than the level
5209 of the first headline in the buffer. This is important, because if the
5210 first headline is not level one, then (hide-sublevels 1) gives confusing
5211 results."
5212 (interactive)
5213 (let ((level (save-excursion
5214 (goto-char (point-min))
5215 (if (re-search-forward (concat "^" outline-regexp) nil t)
5216 (progn
5217 (goto-char (match-beginning 0))
5218 (funcall outline-level))))))
5219 (and level (hide-sublevels level))))
5221 (defun org-content (&optional arg)
5222 "Show all headlines in the buffer, like a table of contents.
5223 With numerical argument N, show content up to level N."
5224 (interactive "P")
5225 (save-excursion
5226 ;; Visit all headings and show their offspring
5227 (and (integerp arg) (org-overview))
5228 (goto-char (point-max))
5229 (catch 'exit
5230 (while (and (progn (condition-case nil
5231 (outline-previous-visible-heading 1)
5232 (error (goto-char (point-min))))
5234 (looking-at outline-regexp))
5235 (if (integerp arg)
5236 (show-children (1- arg))
5237 (show-branches))
5238 (if (bobp) (throw 'exit nil))))))
5241 (defun org-optimize-window-after-visibility-change (state)
5242 "Adjust the window after a change in outline visibility.
5243 This function is the default value of the hook `org-cycle-hook'."
5244 (when (get-buffer-window (current-buffer))
5245 (cond
5246 ; ((eq state 'overview) (org-first-headline-recenter 1))
5247 ; ((eq state 'overview) (org-beginning-of-line))
5248 ((eq state 'content) nil)
5249 ((eq state 'all) nil)
5250 ((eq state 'folded) nil)
5251 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5252 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5255 (defun org-cycle-show-empty-lines (state)
5256 "Show empty lines above all visible headlines.
5257 The region to be covered depends on STATE when called through
5258 `org-cycle-hook'. Lisp program can use t for STATE to get the
5259 entire buffer covered. Note that an empty line is only shown if there
5260 are at least `org-cycle-separator-lines' empty lines before the headeline."
5261 (when (> org-cycle-separator-lines 0)
5262 (save-excursion
5263 (let* ((n org-cycle-separator-lines)
5264 (re (cond
5265 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5266 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5267 (t (let ((ns (number-to-string (- n 2))))
5268 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5269 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5270 beg end)
5271 (cond
5272 ((memq state '(overview contents t))
5273 (setq beg (point-min) end (point-max)))
5274 ((memq state '(children folded))
5275 (setq beg (point) end (progn (org-end-of-subtree t t)
5276 (beginning-of-line 2)
5277 (point)))))
5278 (when beg
5279 (goto-char beg)
5280 (while (re-search-forward re end t)
5281 (if (not (get-char-property (match-end 1) 'invisible))
5282 (outline-flag-region
5283 (match-beginning 1) (match-end 1) nil)))))))
5284 ;; Never hide empty lines at the end of the file.
5285 (save-excursion
5286 (goto-char (point-max))
5287 (outline-previous-heading)
5288 (outline-end-of-heading)
5289 (if (and (looking-at "[ \t\n]+")
5290 (= (match-end 0) (point-max)))
5291 (outline-flag-region (point) (match-end 0) nil))))
5293 (defun org-subtree-end-visible-p ()
5294 "Is the end of the current subtree visible?"
5295 (pos-visible-in-window-p
5296 (save-excursion (org-end-of-subtree t) (point))))
5298 (defun org-first-headline-recenter (&optional N)
5299 "Move cursor to the first headline and recenter the headline.
5300 Optional argument N means, put the headline into the Nth line of the window."
5301 (goto-char (point-min))
5302 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5303 (beginning-of-line)
5304 (recenter (prefix-numeric-value N))))
5306 ;;; Org-goto
5308 (defvar org-goto-window-configuration nil)
5309 (defvar org-goto-marker nil)
5310 (defvar org-goto-map
5311 (let ((map (make-sparse-keymap)))
5312 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5313 (while (setq cmd (pop cmds))
5314 (substitute-key-definition cmd cmd map global-map)))
5315 (suppress-keymap map)
5316 (org-defkey map "\C-m" 'org-goto-ret)
5317 (org-defkey map [(left)] 'org-goto-left)
5318 (org-defkey map [(right)] 'org-goto-right)
5319 (org-defkey map [(?q)] 'org-goto-quit)
5320 (org-defkey map [(control ?g)] 'org-goto-quit)
5321 (org-defkey map "\C-i" 'org-cycle)
5322 (org-defkey map [(tab)] 'org-cycle)
5323 (org-defkey map [(down)] 'outline-next-visible-heading)
5324 (org-defkey map [(up)] 'outline-previous-visible-heading)
5325 (org-defkey map "n" 'outline-next-visible-heading)
5326 (org-defkey map "p" 'outline-previous-visible-heading)
5327 (org-defkey map "f" 'outline-forward-same-level)
5328 (org-defkey map "b" 'outline-backward-same-level)
5329 (org-defkey map "u" 'outline-up-heading)
5330 (org-defkey map "/" 'org-occur)
5331 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5332 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5333 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5334 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5335 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5336 map))
5338 (defconst org-goto-help
5339 "Browse copy of buffer to find location or copy text.
5340 RET=jump to location [Q]uit and return to previous location
5341 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur"
5344 (defun org-goto ()
5345 "Look up a different location in the current file, keeping current visibility.
5347 When you want look-up or go to a different location in a document, the
5348 fastest way is often to fold the entire buffer and then dive into the tree.
5349 This method has the disadvantage, that the previous location will be folded,
5350 which may not be what you want.
5352 This command works around this by showing a copy of the current buffer
5353 in an indirect buffer, in overview mode. You can dive into the tree in
5354 that copy, use org-occur and incremental search to find a location.
5355 When pressing RET or `Q', the command returns to the original buffer in
5356 which the visibility is still unchanged. After RET is will also jump to
5357 the location selected in the indirect buffer and expose the
5358 the headline hierarchy above."
5359 (interactive)
5360 (let* ((org-goto-start-pos (point))
5361 (selected-point
5362 (car (org-get-location (current-buffer) org-goto-help))))
5363 (if selected-point
5364 (progn
5365 (org-mark-ring-push org-goto-start-pos)
5366 (goto-char selected-point)
5367 (if (or (org-invisible-p) (org-invisible-p2))
5368 (org-show-context 'org-goto)))
5369 (message "Quit"))))
5371 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5372 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5374 (defun org-get-location (buf help)
5375 "Let the user select a location in the Org-mode buffer BUF.
5376 This function uses a recursive edit. It returns the selected position
5377 or nil."
5378 (let (org-goto-selected-point org-goto-exit-command)
5379 (save-excursion
5380 (save-window-excursion
5381 (delete-other-windows)
5382 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5383 (switch-to-buffer
5384 (condition-case nil
5385 (make-indirect-buffer (current-buffer) "*org-goto*")
5386 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5387 (with-output-to-temp-buffer "*Help*"
5388 (princ help))
5389 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5390 (setq buffer-read-only nil)
5391 (let ((org-startup-truncated t)
5392 (org-startup-folded nil)
5393 (org-startup-align-all-tables nil))
5394 (org-mode)
5395 (org-overview))
5396 (setq buffer-read-only t)
5397 (if (and (boundp 'org-goto-start-pos)
5398 (integer-or-marker-p org-goto-start-pos))
5399 (let ((org-show-hierarchy-above t)
5400 (org-show-siblings t)
5401 (org-show-following-heading t))
5402 (goto-char org-goto-start-pos)
5403 (and (org-invisible-p) (org-show-context)))
5404 (goto-char (point-min)))
5405 (org-beginning-of-line)
5406 (message "Select location and press RET")
5407 ;; now we make sure that during selection, ony very few keys work
5408 ;; and that it is impossible to switch to another window.
5409 ; (let ((gm (current-global-map))
5410 ; (overriding-local-map org-goto-map))
5411 ; (unwind-protect
5412 ; (progn
5413 ; (use-global-map org-goto-map)
5414 ; (recursive-edit))
5415 ; (use-global-map gm)))
5416 (use-local-map org-goto-map)
5417 (recursive-edit)
5419 (kill-buffer "*org-goto*")
5420 (cons org-goto-selected-point org-goto-exit-command)))
5422 (defun org-goto-ret (&optional arg)
5423 "Finish `org-goto' by going to the new location."
5424 (interactive "P")
5425 (setq org-goto-selected-point (point)
5426 org-goto-exit-command 'return)
5427 (throw 'exit nil))
5429 (defun org-goto-left ()
5430 "Finish `org-goto' by going to the new location."
5431 (interactive)
5432 (if (org-on-heading-p)
5433 (progn
5434 (beginning-of-line 1)
5435 (setq org-goto-selected-point (point)
5436 org-goto-exit-command 'left)
5437 (throw 'exit nil))
5438 (error "Not on a heading")))
5440 (defun org-goto-right ()
5441 "Finish `org-goto' by going to the new location."
5442 (interactive)
5443 (if (org-on-heading-p)
5444 (progn
5445 (setq org-goto-selected-point (point)
5446 org-goto-exit-command 'right)
5447 (throw 'exit nil))
5448 (error "Not on a heading")))
5450 (defun org-goto-quit ()
5451 "Finish `org-goto' without cursor motion."
5452 (interactive)
5453 (setq org-goto-selected-point nil)
5454 (setq org-goto-exit-command 'quit)
5455 (throw 'exit nil))
5457 ;;; Indirect buffer display of subtrees
5459 (defvar org-indirect-dedicated-frame nil
5460 "This is the frame being used for indirect tree display.")
5461 (defvar org-last-indirect-buffer nil)
5463 (defun org-tree-to-indirect-buffer (&optional arg)
5464 "Create indirect buffer and narrow it to current subtree.
5465 With numerical prefix ARG, go up to this level and then take that tree.
5466 If ARG is negative, go up that many levels.
5467 Normally this command removes the indirect buffer previously made
5468 with this command. However, when called with a C-u prefix, the last buffer
5469 is kept so that you can work with several indirect buffers at the same time.
5470 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5471 requests that a new frame be made for the new buffer, so that the dedicated
5472 frame is not changed."
5473 (interactive "P")
5474 (let ((cbuf (current-buffer))
5475 (cwin (selected-window))
5476 (pos (point))
5477 beg end level heading ibuf)
5478 (save-excursion
5479 (org-back-to-heading t)
5480 (when (numberp arg)
5481 (setq level (org-outline-level))
5482 (if (< arg 0) (setq arg (+ level arg)))
5483 (while (> (setq level (org-outline-level)) arg)
5484 (outline-up-heading 1 t)))
5485 (setq beg (point)
5486 heading (org-get-heading))
5487 (org-end-of-subtree t) (setq end (point)))
5488 (if (and (not arg)
5489 (buffer-live-p org-last-indirect-buffer))
5490 (kill-buffer org-last-indirect-buffer))
5491 (setq ibuf (org-get-indirect-buffer cbuf)
5492 org-last-indirect-buffer ibuf)
5493 (cond
5494 ((or (eq org-indirect-buffer-display 'new-frame)
5495 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5496 (select-frame (make-frame))
5497 (delete-other-windows)
5498 (switch-to-buffer ibuf)
5499 (org-set-frame-title heading))
5500 ((eq org-indirect-buffer-display 'dedicated-frame)
5501 (raise-frame
5502 (select-frame (or (and org-indirect-dedicated-frame
5503 (frame-live-p org-indirect-dedicated-frame)
5504 org-indirect-dedicated-frame)
5505 (setq org-indirect-dedicated-frame (make-frame)))))
5506 (delete-other-windows)
5507 (switch-to-buffer ibuf)
5508 (org-set-frame-title (concat "Indirect: " heading)))
5509 ((eq org-indirect-buffer-display 'current-window)
5510 (switch-to-buffer ibuf))
5511 ((eq org-indirect-buffer-display 'other-window)
5512 (pop-to-buffer ibuf))
5513 (t (error "Invalid value.")))
5514 (if (featurep 'xemacs)
5515 (save-excursion (org-mode) (turn-on-font-lock)))
5516 (narrow-to-region beg end)
5517 (show-all)
5518 (goto-char pos)
5519 (and (window-live-p cwin) (select-window cwin))))
5521 (defun org-get-indirect-buffer (&optional buffer)
5522 (setq buffer (or buffer (current-buffer)))
5523 (let ((n 1) (base (buffer-name buffer)) bname)
5524 (while (buffer-live-p
5525 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5526 (setq n (1+ n)))
5527 (condition-case nil
5528 (make-indirect-buffer buffer bname 'clone)
5529 (error (make-indirect-buffer buffer bname)))))
5531 (defun org-set-frame-title (title)
5532 "Set the title of the current frame to the string TITLE."
5533 ;; FIXME: how to name a single frame in XEmacs???
5534 (unless (featurep 'xemacs)
5535 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5537 ;;;; Structure editing
5539 ;;; Inserting headlines
5541 (defun org-insert-heading (&optional force-heading)
5542 "Insert a new heading or item with same depth at point.
5543 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5544 If point is at the beginning of a headline, insert a sibling before the
5545 current headline. If point is in the middle of a headline, split the headline
5546 at that position and make the rest of the headline part of the sibling below
5547 the current headline."
5548 (interactive "P")
5549 (if (= (buffer-size) 0)
5550 (insert "\n* ")
5551 (when (or force-heading (not (org-insert-item)))
5552 (let* ((head (save-excursion
5553 (condition-case nil
5554 (progn
5555 (org-back-to-heading)
5556 (match-string 0))
5557 (error "*"))))
5558 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5559 pos)
5560 (cond
5561 ((and (org-on-heading-p) (bolp)
5562 (or (bobp)
5563 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5564 (open-line (if blank 2 1)))
5565 ((and (bolp)
5566 (or (bobp)
5567 (save-excursion
5568 (backward-char 1) (not (org-invisible-p)))))
5569 nil)
5570 (t (newline (if blank 2 1))))
5571 (insert head) (just-one-space)
5572 (setq pos (point))
5573 (end-of-line 1)
5574 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5575 (run-hooks 'org-insert-heading-hook)))))
5577 (defun org-insert-heading-after-current ()
5578 "Insert a new heading with same level as current, after current subtree."
5579 (interactive)
5580 (org-back-to-heading)
5581 (org-insert-heading)
5582 (org-move-subtree-down)
5583 (end-of-line 1))
5585 (defun org-insert-todo-heading (arg)
5586 "Insert a new heading with the same level and TODO state as current heading.
5587 If the heading has no TODO state, or if the state is DONE, use the first
5588 state (TODO by default). Also with prefix arg, force first state."
5589 (interactive "P")
5590 (when (not (org-insert-item 'checkbox))
5591 (org-insert-heading)
5592 (save-excursion
5593 (org-back-to-heading)
5594 (outline-previous-heading)
5595 (looking-at org-todo-line-regexp))
5596 (if (or arg
5597 (not (match-beginning 2))
5598 (member (match-string 2) org-done-keywords))
5599 (insert (car org-todo-keywords-1) " ")
5600 (insert (match-string 2) " "))))
5602 (defun org-insert-subheading (arg)
5603 "Insert a new subheading and demote it.
5604 Works for outline headings and for plain lists alike."
5605 (interactive "P")
5606 (org-insert-heading arg)
5607 (cond
5608 ((org-on-heading-p) (org-do-demote))
5609 ((org-at-item-p) (org-indent-item 1))))
5611 (defun org-insert-todo-subheading (arg)
5612 "Insert a new subheading with TODO keyword or checkbox and demote it.
5613 Works for outline headings and for plain lists alike."
5614 (interactive "P")
5615 (org-insert-todo-heading arg)
5616 (cond
5617 ((org-on-heading-p) (org-do-demote))
5618 ((org-at-item-p) (org-indent-item 1))))
5620 ;;; Promotion and Demotion
5622 (defun org-promote-subtree ()
5623 "Promote the entire subtree.
5624 See also `org-promote'."
5625 (interactive)
5626 (save-excursion
5627 (org-map-tree 'org-promote))
5628 (org-fix-position-after-promote))
5630 (defun org-demote-subtree ()
5631 "Demote the entire subtree. See `org-demote'.
5632 See also `org-promote'."
5633 (interactive)
5634 (save-excursion
5635 (org-map-tree 'org-demote))
5636 (org-fix-position-after-promote))
5639 (defun org-do-promote ()
5640 "Promote the current heading higher up the tree.
5641 If the region is active in `transient-mark-mode', promote all headings
5642 in the region."
5643 (interactive)
5644 (save-excursion
5645 (if (org-region-active-p)
5646 (org-map-region 'org-promote (region-beginning) (region-end))
5647 (org-promote)))
5648 (org-fix-position-after-promote))
5650 (defun org-do-demote ()
5651 "Demote the current heading lower down the tree.
5652 If the region is active in `transient-mark-mode', demote all headings
5653 in the region."
5654 (interactive)
5655 (save-excursion
5656 (if (org-region-active-p)
5657 (org-map-region 'org-demote (region-beginning) (region-end))
5658 (org-demote)))
5659 (org-fix-position-after-promote))
5661 (defun org-fix-position-after-promote ()
5662 "Make sure that after pro/demotion cursor position is right."
5663 (let ((pos (point)))
5664 (when (save-excursion
5665 (beginning-of-line 1)
5666 (looking-at org-todo-line-regexp)
5667 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5668 (cond ((eobp) (insert " "))
5669 ((eolp) (insert " "))
5670 ((equal (char-after) ?\ ) (forward-char 1))))))
5672 (defun org-reduced-level (l)
5673 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5675 (defun org-get-legal-level (level &optional change)
5676 "Rectify a level change under the influence of `org-odd-levels-only'
5677 LEVEL is a current level, CHANGE is by how much the level should be
5678 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5679 even level numbers will become the next higher odd number."
5680 (if org-odd-levels-only
5681 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5682 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5683 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5684 (max 1 (+ level change))))
5686 (defun org-promote ()
5687 "Promote the current heading higher up the tree.
5688 If the region is active in `transient-mark-mode', promote all headings
5689 in the region."
5690 (org-back-to-heading t)
5691 (let* ((level (save-match-data (funcall outline-level)))
5692 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
5693 (diff (abs (- level (length up-head) -1))))
5694 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5695 (replace-match up-head nil t)
5696 ;; Fixup tag positioning
5697 (and org-auto-align-tags (org-set-tags nil t))
5698 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5700 (defun org-demote ()
5701 "Demote the current heading lower down the tree.
5702 If the region is active in `transient-mark-mode', demote all headings
5703 in the region."
5704 (org-back-to-heading t)
5705 (let* ((level (save-match-data (funcall outline-level)))
5706 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
5707 (diff (abs (- level (length down-head) -1))))
5708 (replace-match down-head nil t)
5709 ;; Fixup tag positioning
5710 (and org-auto-align-tags (org-set-tags nil t))
5711 (if org-adapt-indentation (org-fixup-indentation diff))))
5713 (defun org-map-tree (fun)
5714 "Call FUN for every heading underneath the current one."
5715 (org-back-to-heading)
5716 (let ((level (funcall outline-level)))
5717 (save-excursion
5718 (funcall fun)
5719 (while (and (progn
5720 (outline-next-heading)
5721 (> (funcall outline-level) level))
5722 (not (eobp)))
5723 (funcall fun)))))
5725 (defun org-map-region (fun beg end)
5726 "Call FUN for every heading between BEG and END."
5727 (let ((org-ignore-region t))
5728 (save-excursion
5729 (setq end (copy-marker end))
5730 (goto-char beg)
5731 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5732 (< (point) end))
5733 (funcall fun))
5734 (while (and (progn
5735 (outline-next-heading)
5736 (< (point) end))
5737 (not (eobp)))
5738 (funcall fun)))))
5740 (defun org-fixup-indentation (diff)
5741 "Change the indentation in the current entry by DIFF
5742 However, if any line in the current entry has no indentation, or if it
5743 would end up with no indentation after the change, nothing at all is done."
5744 (save-excursion
5745 (let ((end (save-excursion (outline-next-heading)
5746 (point-marker)))
5747 (prohibit (if (> diff 0)
5748 "^\\S-"
5749 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5750 col)
5751 (unless (save-excursion (end-of-line 1)
5752 (re-search-forward prohibit end t))
5753 (while (re-search-forward "^[ \t]+" end t)
5754 (goto-char (match-end 0))
5755 (setq col (current-column))
5756 (if (< diff 0) (replace-match ""))
5757 (indent-to (+ diff col))))
5758 (move-marker end nil))))
5760 (defun org-convert-to-odd-levels ()
5761 "Convert an org-mode file with all levels allowed to one with odd levels.
5762 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5763 level 5 etc."
5764 (interactive)
5765 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5766 (let ((org-odd-levels-only nil) n)
5767 (save-excursion
5768 (goto-char (point-min))
5769 (while (re-search-forward "^\\*\\*+ " nil t)
5770 (setq n (- (length (match-string 0)) 2))
5771 (while (>= (setq n (1- n)) 0)
5772 (org-demote))
5773 (end-of-line 1))))))
5776 (defun org-convert-to-oddeven-levels ()
5777 "Convert an org-mode file with only odd levels to one with odd and even levels.
5778 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5779 section with an even level, conversion would destroy the structure of the file. An error
5780 is signaled in this case."
5781 (interactive)
5782 (goto-char (point-min))
5783 ;; First check if there are no even levels
5784 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5785 (org-show-context t)
5786 (error "Not all levels are odd in this file. Conversion not possible."))
5787 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5788 (let ((org-odd-levels-only nil) n)
5789 (save-excursion
5790 (goto-char (point-min))
5791 (while (re-search-forward "^\\*\\*+ " nil t)
5792 (setq n (/ (length (1- (match-string 0))) 2))
5793 (while (>= (setq n (1- n)) 0)
5794 (org-promote))
5795 (end-of-line 1))))))
5797 (defun org-tr-level (n)
5798 "Make N odd if required."
5799 (if org-odd-levels-only (1+ (/ n 2)) n))
5801 ;;; Vertical tree motion, cutting and pasting of subtrees
5803 (defun org-move-subtree-up (&optional arg)
5804 "Move the current subtree up past ARG headlines of the same level."
5805 (interactive "p")
5806 (org-move-subtree-down (- (prefix-numeric-value arg))))
5808 (defun org-move-subtree-down (&optional arg)
5809 "Move the current subtree down past ARG headlines of the same level."
5810 (interactive "p")
5811 (setq arg (prefix-numeric-value arg))
5812 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5813 'outline-get-last-sibling))
5814 (ins-point (make-marker))
5815 (cnt (abs arg))
5816 beg end txt folded)
5817 ;; Select the tree
5818 (org-back-to-heading)
5819 (setq beg (point))
5820 (save-match-data
5821 (save-excursion (outline-end-of-heading)
5822 (setq folded (org-invisible-p)))
5823 (outline-end-of-subtree))
5824 (outline-next-heading)
5825 (setq end (point))
5826 ;; Find insertion point, with error handling
5827 (goto-char beg)
5828 (while (> cnt 0)
5829 (or (and (funcall movfunc) (looking-at outline-regexp))
5830 (progn (goto-char beg)
5831 (error "Cannot move past superior level or buffer limit")))
5832 (setq cnt (1- cnt)))
5833 (if (> arg 0)
5834 ;; Moving forward - still need to move over subtree
5835 (progn (outline-end-of-subtree)
5836 (outline-next-heading)
5837 (if (not (or (looking-at (concat "^" outline-regexp))
5838 (bolp)))
5839 (newline))))
5840 (move-marker ins-point (point))
5841 (setq txt (buffer-substring beg end))
5842 (delete-region beg end)
5843 (insert txt)
5844 (or (bolp) (insert "\n"))
5845 (goto-char ins-point)
5846 (if folded (hide-subtree))
5847 (move-marker ins-point nil)))
5849 (defvar org-subtree-clip ""
5850 "Clipboard for cut and paste of subtrees.
5851 This is actually only a copy of the kill, because we use the normal kill
5852 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5854 (defvar org-subtree-clip-folded nil
5855 "Was the last copied subtree folded?
5856 This is used to fold the tree back after pasting.")
5858 (defun org-cut-subtree (&optional n)
5859 "Cut the current subtree into the clipboard.
5860 With prefix arg N, cut this many sequential subtrees.
5861 This is a short-hand for marking the subtree and then cutting it."
5862 (interactive "p")
5863 (org-copy-subtree n 'cut))
5865 (defun org-copy-subtree (&optional n cut)
5866 "Cut the current subtree into the clipboard.
5867 With prefix arg N, cut this many sequential subtrees.
5868 This is a short-hand for marking the subtree and then copying it.
5869 If CUT is non-nil, actually cut the subtree."
5870 (interactive "p")
5871 (let (beg end folded)
5872 (if (interactive-p)
5873 (org-back-to-heading nil) ; take what looks like a subtree
5874 (org-back-to-heading t)) ; take what is really there
5875 (setq beg (point))
5876 (save-match-data
5877 (save-excursion (outline-end-of-heading)
5878 (setq folded (org-invisible-p)))
5879 (condition-case nil
5880 (outline-forward-same-level (1- n))
5881 (error nil))
5882 (org-end-of-subtree t t))
5883 (setq end (point))
5884 (goto-char beg)
5885 (when (> end beg)
5886 (setq org-subtree-clip-folded folded)
5887 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5888 (setq org-subtree-clip (current-kill 0))
5889 (message "%s: Subtree(s) with %d characters"
5890 (if cut "Cut" "Copied")
5891 (length org-subtree-clip)))))
5893 (defun org-paste-subtree (&optional level tree)
5894 "Paste the clipboard as a subtree, with modification of headline level.
5895 The entire subtree is promoted or demoted in order to match a new headline
5896 level. By default, the new level is derived from the visible headings
5897 before and after the insertion point, and taken to be the inferior headline
5898 level of the two. So if the previous visible heading is level 3 and the
5899 next is level 4 (or vice versa), level 4 will be used for insertion.
5900 This makes sure that the subtree remains an independent subtree and does
5901 not swallow low level entries.
5903 You can also force a different level, either by using a numeric prefix
5904 argument, or by inserting the heading marker by hand. For example, if the
5905 cursor is after \"*****\", then the tree will be shifted to level 5.
5907 If you want to insert the tree as is, just use \\[yank].
5909 If optional TREE is given, use this text instead of the kill ring."
5910 (interactive "P")
5911 (unless (org-kill-is-subtree-p tree)
5912 (error
5913 (substitute-command-keys
5914 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5915 (let* ((txt (or tree (and kill-ring (current-kill 0))))
5916 (^re (concat "^\\(" outline-regexp "\\)"))
5917 (re (concat "\\(" outline-regexp "\\)"))
5918 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5920 (old-level (if (string-match ^re txt)
5921 (- (match-end 0) (match-beginning 0) 1)
5922 -1))
5923 (force-level (cond (level (prefix-numeric-value level))
5924 ((string-match
5925 ^re_ (buffer-substring (point-at-bol) (point)))
5926 (- (match-end 1) (match-beginning 1)))
5927 (t nil)))
5928 (previous-level (save-excursion
5929 (condition-case nil
5930 (progn
5931 (outline-previous-visible-heading 1)
5932 (if (looking-at re)
5933 (- (match-end 0) (match-beginning 0) 1)
5935 (error 1))))
5936 (next-level (save-excursion
5937 (condition-case nil
5938 (progn
5939 (or (looking-at outline-regexp)
5940 (outline-next-visible-heading 1))
5941 (if (looking-at re)
5942 (- (match-end 0) (match-beginning 0) 1)
5944 (error 1))))
5945 (new-level (or force-level (max previous-level next-level)))
5946 (shift (if (or (= old-level -1)
5947 (= new-level -1)
5948 (= old-level new-level))
5950 (- new-level old-level)))
5951 (shift1 shift)
5952 (delta (if (> shift 0) -1 1))
5953 (func (if (> shift 0) 'org-demote 'org-promote))
5954 (org-odd-levels-only nil)
5955 beg end)
5956 ;; Remove the forced level indicator
5957 (if force-level
5958 (delete-region (point-at-bol) (point)))
5959 ;; Paste
5960 (beginning-of-line 1)
5961 (setq beg (point))
5962 (insert txt)
5963 (unless (string-match "\n[ \t]*\\'" txt) (insert "\n"))
5964 (setq end (point))
5965 (goto-char beg)
5966 ;; Shift if necessary
5967 (unless (= shift 0)
5968 (save-restriction
5969 (narrow-to-region beg end)
5970 (while (not (= shift 0))
5971 (org-map-region func (point-min) (point-max))
5972 (setq shift (+ delta shift)))
5973 (goto-char (point-min))))
5974 (when (interactive-p)
5975 (message "Clipboard pasted as level %d subtree" new-level))
5976 (if (and kill-ring
5977 (eq org-subtree-clip (current-kill 0))
5978 org-subtree-clip-folded)
5979 ;; The tree was folded before it was killed/copied
5980 (hide-subtree))))
5982 (defun org-kill-is-subtree-p (&optional txt)
5983 "Check if the current kill is an outline subtree, or a set of trees.
5984 Returns nil if kill does not start with a headline, or if the first
5985 headline level is not the largest headline level in the tree.
5986 So this will actually accept several entries of equal levels as well,
5987 which is OK for `org-paste-subtree'.
5988 If optional TXT is given, check this string instead of the current kill."
5989 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5990 (start-level (and kill
5991 (string-match (concat "\\`" org-outline-regexp) kill)
5992 (- (match-end 0) (match-beginning 0) 1)))
5993 (re (concat "^" org-outline-regexp))
5994 (start 1))
5995 (if (not start-level)
5996 (progn
5997 nil) ;; does not even start with a heading
5998 (catch 'exit
5999 (while (setq start (string-match re kill (1+ start)))
6000 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6001 (throw 'exit nil)))
6002 t))))
6004 (defun org-narrow-to-subtree ()
6005 "Narrow buffer to the current subtree."
6006 (interactive)
6007 (save-excursion
6008 (narrow-to-region
6009 (progn (org-back-to-heading) (point))
6010 (progn (org-end-of-subtree t t) (point)))))
6013 ;;; Outline Sorting
6015 (defun org-sort (with-case)
6016 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
6017 (interactive "P")
6018 (if (org-at-table-p)
6019 (org-call-with-arg 'org-table-sort-lines with-case)
6020 (org-call-with-arg 'org-sort-entries with-case)))
6022 (defun org-sort-entries (&optional with-case sorting-type)
6023 "Sort entries on a certain level of an outline tree.
6024 If there is an active region, the entries in the region are sorted.
6025 Else, if the cursor is before the first entry, sort the top-level items.
6026 Else, the children of the entry at point are sorted.
6028 Sorting can be alphabetically, numerically, and by date/time as given by
6029 the first time stamp in the entry. The command prompts for the sorting
6030 type unless it has been given to the function through the SORTING-TYPE
6031 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
6033 Comparing entries ignores case by default. However, with an optional argument
6034 WITH-CASE, the sorting considers case as well. With two prefix arguments
6035 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
6036 (interactive "P")
6037 (let ((unique (equal with-case '(16)))
6038 start beg end entries stars re re2 p nentries (nremoved 0)
6039 last txt what)
6040 ;; Find beginning and end of region to sort
6041 (cond
6042 ((org-region-active-p)
6043 ;; we will sort the region
6044 (setq end (region-end)
6045 what "region")
6046 (goto-char (region-beginning))
6047 (if (not (org-on-heading-p)) (outline-next-heading))
6048 (setq start (point)))
6049 ((or (org-on-heading-p)
6050 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6051 ;; we will sort the children of the current headline
6052 (org-back-to-heading)
6053 (setq start (point) end (org-end-of-subtree) what "children")
6054 (goto-char start)
6055 (show-subtree)
6056 (outline-next-heading))
6058 ;; we will sort the top-level entries in this file
6059 (goto-char (point-min))
6060 (or (org-on-heading-p) (outline-next-heading))
6061 (setq start (point) end (point-max) what "top-level")
6062 (goto-char start)
6063 (show-all)))
6064 (setq beg (point))
6065 (if (>= (point) end) (error "Nothing to sort"))
6066 (looking-at "\\(\\*+\\)")
6067 (setq stars (match-string 1)
6068 re (concat "^" (regexp-quote stars) " +")
6069 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6070 txt (buffer-substring beg end))
6071 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6072 (if (and (not (equal stars "*")) (string-match re2 txt))
6073 (error "Region to sort contains a level above the first entry"))
6074 ;; Make a list that can be sorted.
6075 ;; The car is the string for comparison, the cdr is the subtree
6076 (message "Sorting entries...")
6077 (setq entries
6078 (mapcar
6079 (lambda (x)
6080 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
6081 (cons (match-string 0 x) x))
6082 (org-split-string txt re)))
6084 ;; Sort the list
6085 (save-excursion
6086 (goto-char start)
6087 (setq entries (org-do-sort entries what with-case sorting-type)))
6089 ;; Delete the old stuff
6090 (goto-char beg)
6091 (kill-region beg end)
6092 (setq nentries (length entries))
6093 ;; Insert the sorted entries, and remove duplicates if this is required
6094 (while (setq p (pop entries))
6095 (if (and unique (equal last (setq last (org-trim (cdr p)))))
6096 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
6097 (insert stars " " (cdr p))))
6098 (goto-char start)
6099 (message "Sorting entries...done (%d entries%s)"
6100 nentries
6101 (if unique (format ", %d duplicates removed" nremoved) ""))))
6103 (defvar org-priority-regexp) ; defined later in the file
6105 (defun org-do-sort (table what &optional with-case sorting-type)
6106 "Sort TABLE of WHAT according to SORTING-TYPE.
6107 The user will be prompted for the SORTING-TYPE if the call to this
6108 function does not specify it. WHAT is only for the prompt, to indicate
6109 what is being sorted. The sorting key will be extracted from
6110 the car of the elements of the table.
6111 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6112 (unless sorting-type
6113 (message
6114 "Sort %s: [a]lphabetic. [n]umeric. [t]ime [p]riority. A/N/T/P means reversed:"
6115 what)
6116 (setq sorting-type (read-char-exclusive)))
6117 (let ((dcst (downcase sorting-type))
6118 extractfun comparefun)
6119 ;; Define the appropriate functions
6120 (cond
6121 ((= dcst ?n)
6122 (setq extractfun 'string-to-number
6123 comparefun (if (= dcst sorting-type) '< '>)))
6124 ((= dcst ?a)
6125 (setq extractfun (if with-case 'identity 'downcase)
6126 comparefun (if (= dcst sorting-type)
6127 'string<
6128 (lambda (a b) (and (not (string< a b))
6129 (not (string= a b)))))))
6130 ((= dcst ?t)
6131 (setq extractfun
6132 (lambda (x)
6133 (if (string-match org-ts-regexp x)
6134 (time-to-seconds
6135 (org-time-string-to-time (match-string 0 x)))
6137 comparefun (if (= dcst sorting-type) '< '>)))
6138 ((= dcst ?p)
6139 (setq extractfun
6140 (lambda (x)
6141 (if (string-match org-priority-regexp x)
6142 (string-to-char (match-string 2 x))
6143 org-default-priority))
6144 comparefun (if (= dcst sorting-type) '< '>)))
6145 (t (error "Invalid sorting type `%c'" sorting-type)))
6147 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6148 table)
6149 (lambda (a b) (funcall comparefun (car a) (car b))))))
6151 ;;;; Plain list items, including checkboxes
6153 ;;; Plain list items
6155 (defun org-at-item-p ()
6156 "Is point in a line starting a hand-formatted item?"
6157 (let ((llt org-plain-list-ordered-item-terminator))
6158 (save-excursion
6159 (goto-char (point-at-bol))
6160 (looking-at
6161 (cond
6162 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6163 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6164 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6165 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6167 (defun org-in-item-p ()
6168 "It the cursor inside a plain list item.
6169 Does not have to be the first line."
6170 (save-excursion
6171 (condition-case nil
6172 (progn
6173 (org-beginning-of-item)
6174 (org-at-item-p)
6176 (error nil))))
6178 (defun org-insert-item (&optional checkbox)
6179 "Insert a new item at the current level.
6180 Return t when things worked, nil when we are not in an item."
6181 (when (save-excursion
6182 (condition-case nil
6183 (progn
6184 (org-beginning-of-item)
6185 (org-at-item-p)
6186 (if (org-invisible-p) (error "Invisible item"))
6188 (error nil)))
6189 (let* ((bul (match-string 0))
6190 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6191 (match-end 0)))
6192 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6193 pos)
6194 (cond
6195 ((and (org-at-item-p) (<= (point) eow))
6196 ;; before the bullet
6197 (beginning-of-line 1)
6198 (open-line (if blank 2 1)))
6199 ((<= (point) eow)
6200 (beginning-of-line 1))
6201 (t (newline (if blank 2 1))))
6202 (insert bul (if checkbox "[ ]" ""))
6203 (just-one-space)
6204 (setq pos (point))
6205 (end-of-line 1)
6206 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6207 (org-maybe-renumber-ordered-list)
6208 (and checkbox (org-update-checkbox-count-maybe))
6211 ;;; Checkboxes
6213 (defun org-at-item-checkbox-p ()
6214 "Is point at a line starting a plain-list item with a checklet?"
6215 (and (org-at-item-p)
6216 (save-excursion
6217 (goto-char (match-end 0))
6218 (skip-chars-forward " \t")
6219 (looking-at "\\[[- X]\\]"))))
6221 (defun org-toggle-checkbox (&optional arg)
6222 "Toggle the checkbox in the current line."
6223 (interactive "P")
6224 (catch 'exit
6225 (let (beg end status (firstnew 'unknown))
6226 (cond
6227 ((org-region-active-p)
6228 (setq beg (region-beginning) end (region-end)))
6229 ((org-on-heading-p)
6230 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6231 ((org-at-item-checkbox-p)
6232 (save-excursion
6233 (replace-match
6234 (cond (arg "[-]")
6235 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6236 (t "[ ]"))
6237 t t))
6238 (throw 'exit t))
6239 (t (error "Not at a checkbox or heading, and no active region")))
6240 (save-excursion
6241 (goto-char beg)
6242 (while (< (point) end)
6243 (when (org-at-item-checkbox-p)
6244 (setq status (equal (match-string 0) "[X]"))
6245 (when (eq firstnew 'unknown)
6246 (setq firstnew (not status)))
6247 (replace-match
6248 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6249 (beginning-of-line 2)))))
6250 (org-update-checkbox-count-maybe))
6252 (defun org-update-checkbox-count-maybe ()
6253 "Update checkbox statistics unless turned off by user."
6254 (when org-provide-checkbox-statistics
6255 (org-update-checkbox-count)))
6257 (defun org-update-checkbox-count (&optional all)
6258 "Update the checkbox statistics in the current section.
6259 This will find all statistic cookies like [57%] and [6/12] and update them
6260 with the current numbers. With optional prefix argument ALL, do this for
6261 the whole buffer."
6262 (interactive "P")
6263 (save-excursion
6264 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6265 (beg (condition-case nil
6266 (progn (outline-back-to-heading) (point))
6267 (error (point-min))))
6268 (end (move-marker (make-marker)
6269 (progn (outline-next-heading) (point))))
6270 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6271 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6272 b1 e1 f1 c-on c-off lim (cstat 0))
6273 (when all
6274 (goto-char (point-min))
6275 (outline-next-heading)
6276 (setq beg (point) end (point-max)))
6277 (goto-char beg)
6278 (while (re-search-forward re end t)
6279 (setq cstat (1+ cstat)
6280 b1 (match-beginning 0)
6281 e1 (match-end 0)
6282 f1 (match-beginning 1)
6283 lim (cond
6284 ((org-on-heading-p) (outline-next-heading) (point))
6285 ((org-at-item-p) (org-end-of-item) (point))
6286 (t nil))
6287 c-on 0 c-off 0)
6288 (goto-char e1)
6289 (when lim
6290 (while (re-search-forward re-box lim t)
6291 (if (member (match-string 2) '("[ ]" "[-]"))
6292 (setq c-off (1+ c-off))
6293 (setq c-on (1+ c-on))))
6294 ; (delete-region b1 e1)
6295 (goto-char b1)
6296 (insert (if f1
6297 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6298 (format "[%d/%d]" c-on (+ c-on c-off))))
6299 (and (looking-at "\\[.*?\\]")
6300 (replace-match ""))))
6301 (when (interactive-p)
6302 (message "Checkbox satistics updated %s (%d places)"
6303 (if all "in entire file" "in current outline entry") cstat)))))
6305 (defun org-get-checkbox-statistics-face ()
6306 "Select the face for checkbox statistics.
6307 The face will be `org-done' when all relevant boxes are checked. Otherwise
6308 it will be `org-todo'."
6309 (if (match-end 1)
6310 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6311 (if (and (> (match-end 2) (match-beginning 2))
6312 (equal (match-string 2) (match-string 3)))
6313 'org-done
6314 'org-todo)))
6316 (defun org-get-indentation (&optional line)
6317 "Get the indentation of the current line, interpreting tabs.
6318 When LINE is given, assume it represents a line and compute its indentation."
6319 (if line
6320 (if (string-match "^ *" (org-remove-tabs line))
6321 (match-end 0))
6322 (save-excursion
6323 (beginning-of-line 1)
6324 (skip-chars-forward " \t")
6325 (current-column))))
6327 (defun org-remove-tabs (s &optional width)
6328 "Replace tabulators in S with spaces.
6329 Assumes that s is a single line, starting in column 0."
6330 (setq width (or width tab-width))
6331 (while (string-match "\t" s)
6332 (setq s (replace-match
6333 (make-string
6334 (- (* width (/ (+ (match-beginning 0) width) width))
6335 (match-beginning 0)) ?\ )
6336 t t s)))
6339 (defun org-fix-indentation (line ind)
6340 "Fix indentation in LINE.
6341 IND is a cons cell with target and minimum indentation.
6342 If the current indenation in LINE is smaller than the minimum,
6343 leave it alone. If it is larger than ind, set it to the target."
6344 (let* ((l (org-remove-tabs line))
6345 (i (org-get-indentation l))
6346 (i1 (car ind)) (i2 (cdr ind)))
6347 (if (>= i i2) (setq l (substring line i2)))
6348 (if (> i1 0)
6349 (concat (make-string i1 ?\ ) l)
6350 l)))
6352 (defcustom org-empty-line-terminates-plain-lists nil
6353 "Non-nil means, an empty line ends all plain list levels.
6354 When nil, empty lines are part of the preceeding item."
6355 :group 'org-plain-lists
6356 :type 'boolean)
6358 (defun org-beginning-of-item ()
6359 "Go to the beginning of the current hand-formatted item.
6360 If the cursor is not in an item, throw an error."
6361 (interactive)
6362 (let ((pos (point))
6363 (limit (save-excursion
6364 (condition-case nil
6365 (progn
6366 (org-back-to-heading)
6367 (beginning-of-line 2) (point))
6368 (error (point-min)))))
6369 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6370 ind ind1)
6371 (if (org-at-item-p)
6372 (beginning-of-line 1)
6373 (beginning-of-line 1)
6374 (skip-chars-forward " \t")
6375 (setq ind (current-column))
6376 (if (catch 'exit
6377 (while t
6378 (beginning-of-line 0)
6379 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6381 (if (looking-at "[ \t]*$")
6382 (setq ind1 ind-empty)
6383 (skip-chars-forward " \t")
6384 (setq ind1 (current-column)))
6385 (if (< ind1 ind)
6386 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6388 (goto-char pos)
6389 (error "Not in an item")))))
6391 (defun org-end-of-item ()
6392 "Go to the end of the current hand-formatted item.
6393 If the cursor is not in an item, throw an error."
6394 (interactive)
6395 (let* ((pos (point))
6396 ind1
6397 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6398 (limit (save-excursion (outline-next-heading) (point)))
6399 (ind (save-excursion
6400 (org-beginning-of-item)
6401 (skip-chars-forward " \t")
6402 (current-column)))
6403 (end (catch 'exit
6404 (while t
6405 (beginning-of-line 2)
6406 (if (eobp) (throw 'exit (point)))
6407 (if (>= (point) limit) (throw 'exit (point-at-bol)))
6408 (if (looking-at "[ \t]*$")
6409 (setq ind1 ind-empty)
6410 (skip-chars-forward " \t")
6411 (setq ind1 (current-column)))
6412 (if (<= ind1 ind)
6413 (throw 'exit (point-at-bol)))))))
6414 (if end
6415 (goto-char end)
6416 (goto-char pos)
6417 (error "Not in an item"))))
6419 (defun org-next-item ()
6420 "Move to the beginning of the next item in the current plain list.
6421 Error if not at a plain list, or if this is the last item in the list."
6422 (interactive)
6423 (let (ind ind1 (pos (point)))
6424 (org-beginning-of-item)
6425 (setq ind (org-get-indentation))
6426 (org-end-of-item)
6427 (setq ind1 (org-get-indentation))
6428 (unless (and (org-at-item-p) (= ind ind1))
6429 (goto-char pos)
6430 (error "On last item"))))
6432 (defun org-previous-item ()
6433 "Move to the beginning of the previous item in the current plain list.
6434 Error if not at a plain list, or if this is the first item in the list."
6435 (interactive)
6436 (let (beg ind ind1 (pos (point)))
6437 (org-beginning-of-item)
6438 (setq beg (point))
6439 (setq ind (org-get-indentation))
6440 (goto-char beg)
6441 (catch 'exit
6442 (while t
6443 (beginning-of-line 0)
6444 (if (looking-at "[ \t]*$")
6446 (if (<= (setq ind1 (org-get-indentation)) ind)
6447 (throw 'exit t)))))
6448 (condition-case nil
6449 (if (or (not (org-at-item-p))
6450 (< ind1 (1- ind)))
6451 (error "")
6452 (org-beginning-of-item))
6453 (error (goto-char pos)
6454 (error "On first item")))))
6456 (defun org-move-item-down ()
6457 "Move the plain list item at point down, i.e. swap with following item.
6458 Subitems (items with larger indentation) are considered part of the item,
6459 so this really moves item trees."
6460 (interactive)
6461 (let (beg end ind ind1 (pos (point)) txt)
6462 (org-beginning-of-item)
6463 (setq beg (point))
6464 (setq ind (org-get-indentation))
6465 (org-end-of-item)
6466 (setq end (point))
6467 (setq ind1 (org-get-indentation))
6468 (if (and (org-at-item-p) (= ind ind1))
6469 (progn
6470 (org-end-of-item)
6471 (setq txt (buffer-substring beg end))
6472 (save-excursion
6473 (delete-region beg end))
6474 (setq pos (point))
6475 (insert txt)
6476 (goto-char pos)
6477 (org-maybe-renumber-ordered-list))
6478 (goto-char pos)
6479 (error "Cannot move this item further down"))))
6481 (defun org-move-item-up (arg)
6482 "Move the plain list item at point up, i.e. swap with previous item.
6483 Subitems (items with larger indentation) are considered part of the item,
6484 so this really moves item trees."
6485 (interactive "p")
6486 (let (beg end ind ind1 (pos (point)) txt)
6487 (org-beginning-of-item)
6488 (setq beg (point))
6489 (setq ind (org-get-indentation))
6490 (org-end-of-item)
6491 (setq end (point))
6492 (goto-char beg)
6493 (catch 'exit
6494 (while t
6495 (beginning-of-line 0)
6496 (if (looking-at "[ \t]*$")
6497 (if org-empty-line-terminates-plain-lists
6498 (progn
6499 (goto-char pos)
6500 (error "Cannot move this item further up"))
6501 nil)
6502 (if (<= (setq ind1 (org-get-indentation)) ind)
6503 (throw 'exit t)))))
6504 (condition-case nil
6505 (org-beginning-of-item)
6506 (error (goto-char beg)
6507 (error "Cannot move this item further up")))
6508 (setq ind1 (org-get-indentation))
6509 (if (and (org-at-item-p) (= ind ind1))
6510 (progn
6511 (setq txt (buffer-substring beg end))
6512 (save-excursion
6513 (delete-region beg end))
6514 (setq pos (point))
6515 (insert txt)
6516 (goto-char pos)
6517 (org-maybe-renumber-ordered-list))
6518 (goto-char pos)
6519 (error "Cannot move this item further up"))))
6521 (defun org-maybe-renumber-ordered-list ()
6522 "Renumber the ordered list at point if setup allows it.
6523 This tests the user option `org-auto-renumber-ordered-lists' before
6524 doing the renumbering."
6525 (interactive)
6526 (when (and org-auto-renumber-ordered-lists
6527 (org-at-item-p))
6528 (if (match-beginning 3)
6529 (org-renumber-ordered-list 1)
6530 (org-fix-bullet-type))))
6532 (defun org-maybe-renumber-ordered-list-safe ()
6533 (condition-case nil
6534 (save-excursion
6535 (org-maybe-renumber-ordered-list))
6536 (error nil)))
6538 (defun org-cycle-list-bullet (&optional which)
6539 "Cycle through the different itemize/enumerate bullets.
6540 This cycle the entire list level through the sequence:
6542 `-' -> `+' -> `*' -> `1.' -> `1)'
6544 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6545 0 meand `-', 1 means `+' etc."
6546 (interactive "P")
6547 (org-preserve-lc
6548 (org-beginning-of-item-list)
6549 (org-at-item-p)
6550 (beginning-of-line 1)
6551 (let ((current (match-string 0)) new)
6552 (setq new (cond
6553 ((and which (nth (1- which) '("-" "+" "*" "1." "1)"))))
6554 ((string-match "-" current) "+")
6555 ((string-match "\\+" current)
6556 (if (looking-at "\\S-") "1." "*"))
6557 ((string-match "\\*" current) "1.")
6558 ((string-match "\\." current) "1)")
6559 ((string-match ")" current) "-")
6560 (t (error "This should not happen"))))
6561 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6562 (org-fix-bullet-type)
6563 (org-maybe-renumber-ordered-list))))
6565 (defun org-get-string-indentation (s)
6566 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6567 (let ((n -1) (i 0) (w tab-width) c)
6568 (catch 'exit
6569 (while (< (setq n (1+ n)) (length s))
6570 (setq c (aref s n))
6571 (cond ((= c ?\ ) (setq i (1+ i)))
6572 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6573 (t (throw 'exit t)))))
6576 (defun org-renumber-ordered-list (arg)
6577 "Renumber an ordered plain list.
6578 Cursor needs to be in the first line of an item, the line that starts
6579 with something like \"1.\" or \"2)\"."
6580 (interactive "p")
6581 (unless (and (org-at-item-p)
6582 (match-beginning 3))
6583 (error "This is not an ordered list"))
6584 (let ((line (org-current-line))
6585 (col (current-column))
6586 (ind (org-get-string-indentation
6587 (buffer-substring (point-at-bol) (match-beginning 3))))
6588 ;; (term (substring (match-string 3) -1))
6589 ind1 (n (1- arg))
6590 fmt)
6591 ;; find where this list begins
6592 (org-beginning-of-item-list)
6593 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6594 (setq fmt (concat "%d" (match-string 1)))
6595 (beginning-of-line 0)
6596 ;; walk forward and replace these numbers
6597 (catch 'exit
6598 (while t
6599 (catch 'next
6600 (beginning-of-line 2)
6601 (if (eobp) (throw 'exit nil))
6602 (if (looking-at "[ \t]*$") (throw 'next nil))
6603 (skip-chars-forward " \t") (setq ind1 (current-column))
6604 (if (> ind1 ind) (throw 'next t))
6605 (if (< ind1 ind) (throw 'exit t))
6606 (if (not (org-at-item-p)) (throw 'exit nil))
6607 (delete-region (match-beginning 2) (match-end 2))
6608 (goto-char (match-beginning 2))
6609 (insert (format fmt (setq n (1+ n)))))))
6610 (goto-line line)
6611 (move-to-column col)))
6613 (defun org-fix-bullet-type ()
6614 "Make sure all items in this list have the same bullet as the firsst item."
6615 (interactive)
6616 (unless (org-at-item-p) (error "This is not a list"))
6617 (let ((line (org-current-line))
6618 (col (current-column))
6619 (ind (current-indentation))
6620 ind1 bullet)
6621 ;; find where this list begins
6622 (org-beginning-of-item-list)
6623 (beginning-of-line 1)
6624 ;; find out what the bullet type is
6625 (looking-at "[ \t]*\\(\\S-+\\)")
6626 (setq bullet (match-string 1))
6627 ;; walk forward and replace these numbers
6628 (beginning-of-line 0)
6629 (catch 'exit
6630 (while t
6631 (catch 'next
6632 (beginning-of-line 2)
6633 (if (eobp) (throw 'exit nil))
6634 (if (looking-at "[ \t]*$") (throw 'next nil))
6635 (skip-chars-forward " \t") (setq ind1 (current-column))
6636 (if (> ind1 ind) (throw 'next t))
6637 (if (< ind1 ind) (throw 'exit t))
6638 (if (not (org-at-item-p)) (throw 'exit nil))
6639 (skip-chars-forward " \t")
6640 (looking-at "\\S-+")
6641 (replace-match bullet))))
6642 (goto-line line)
6643 (move-to-column col)
6644 (if (string-match "[0-9]" bullet)
6645 (org-renumber-ordered-list 1))))
6647 (defun org-beginning-of-item-list ()
6648 "Go to the beginning of the current item list.
6649 I.e. to the first item in this list."
6650 (interactive)
6651 (org-beginning-of-item)
6652 (let ((pos (point-at-bol))
6653 (ind (org-get-indentation))
6654 ind1)
6655 ;; find where this list begins
6656 (catch 'exit
6657 (while t
6658 (catch 'next
6659 (beginning-of-line 0)
6660 (if (looking-at "[ \t]*$")
6661 (throw (if (bobp) 'exit 'next) t))
6662 (skip-chars-forward " \t") (setq ind1 (current-column))
6663 (if (or (< ind1 ind)
6664 (and (= ind1 ind)
6665 (not (org-at-item-p)))
6666 (bobp))
6667 (throw 'exit t)
6668 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6669 (goto-char pos)))
6671 (defvar org-last-indent-begin-marker (make-marker))
6672 (defvar org-last-indent-end-marker (make-marker))
6674 (defun org-outdent-item (arg)
6675 "Outdent a local list item."
6676 (interactive "p")
6677 (org-indent-item (- arg)))
6679 (defun org-indent-item (arg)
6680 "Indent a local list item."
6681 (interactive "p")
6682 (unless (org-at-item-p)
6683 (error "Not on an item"))
6684 (save-excursion
6685 (let (beg end ind ind1 tmp delta ind-down ind-up)
6686 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6687 (setq beg org-last-indent-begin-marker
6688 end org-last-indent-end-marker)
6689 (org-beginning-of-item)
6690 (setq beg (move-marker org-last-indent-begin-marker (point)))
6691 (org-end-of-item)
6692 (setq end (move-marker org-last-indent-end-marker (point))))
6693 (goto-char beg)
6694 (setq tmp (org-item-indent-positions)
6695 ind (car tmp)
6696 ind-down (nth 2 tmp)
6697 ind-up (nth 1 tmp)
6698 delta (if (> arg 0)
6699 (if ind-down (- ind-down ind) 2)
6700 (if ind-up (- ind-up ind) -2)))
6701 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6702 (while (< (point) end)
6703 (beginning-of-line 1)
6704 (skip-chars-forward " \t") (setq ind1 (current-column))
6705 (delete-region (point-at-bol) (point))
6706 (or (eolp) (indent-to-column (+ ind1 delta)))
6707 (beginning-of-line 2))))
6708 (org-fix-bullet-type)
6709 (org-maybe-renumber-ordered-list-safe)
6710 (save-excursion
6711 (beginning-of-line 0)
6712 (condition-case nil (org-beginning-of-item) (error nil))
6713 (org-maybe-renumber-ordered-list-safe)))
6715 (defun org-item-indent-positions ()
6716 "Return indentation for plain list items.
6717 This returns a list with three values: The current indentation, the
6718 parent indentation and the indentation a child should habe.
6719 Assumes cursor in item line."
6720 (let* ((bolpos (point-at-bol))
6721 (ind (org-get-indentation))
6722 ind-down ind-up pos)
6723 (save-excursion
6724 (org-beginning-of-item-list)
6725 (skip-chars-backward "\n\r \t")
6726 (when (org-in-item-p)
6727 (org-beginning-of-item)
6728 (setq ind-up (org-get-indentation))))
6729 (setq pos (point))
6730 (save-excursion
6731 (cond
6732 ((and (condition-case nil (progn (org-previous-item) t)
6733 (error nil))
6734 (or (forward-char 1) t)
6735 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6736 (setq ind-down (org-get-indentation)))
6737 ((and (goto-char pos)
6738 (org-at-item-p))
6739 (goto-char (match-end 0))
6740 (skip-chars-forward " \t")
6741 (setq ind-down (current-column)))))
6742 (list ind ind-up ind-down)))
6744 ;;; The orgstruct minor mode
6746 ;; Define a minor mode which can be used in other modes in order to
6747 ;; integrate the org-mode structure editing commands.
6749 ;; This is really a hack, because the org-mode structure commands use
6750 ;; keys which normally belong to the major mode. Here is how it
6751 ;; works: The minor mode defines all the keys necessary to operate the
6752 ;; structure commands, but wraps the commands into a function which
6753 ;; tests if the cursor is currently at a headline or a plain list
6754 ;; item. If that is the case, the structure command is used,
6755 ;; temporarily setting many Org-mode variables like regular
6756 ;; expressions for filling etc. However, when any of those keys is
6757 ;; used at a different location, function uses `key-binding' to look
6758 ;; up if the key has an associated command in another currently active
6759 ;; keymap (minor modes, major mode, global), and executes that
6760 ;; command. There might be problems if any of the keys is otherwise
6761 ;; used as a prefix key.
6763 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6764 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6765 ;; addresses this by checking explicitly for both bindings.
6767 (defvar orgstruct-mode-map (make-sparse-keymap)
6768 "Keymap for the minor `orgstruct-mode'.")
6770 (defvar org-local-vars nil
6771 "List of local variables, for use by `orgstruct-mode'")
6773 ;;;###autoload
6774 (define-minor-mode orgstruct-mode
6775 "Toggle the minor more `orgstruct-mode'.
6776 This mode is for using Org-mode structure commands in other modes.
6777 The following key behave as if Org-mode was active, if the cursor
6778 is on a headline, or on a plain list item (both in the definition
6779 of Org-mode).
6781 M-up Move entry/item up
6782 M-down Move entry/item down
6783 M-left Promote
6784 M-right Demote
6785 M-S-up Move entry/item up
6786 M-S-down Move entry/item down
6787 M-S-left Promote subtree
6788 M-S-right Demote subtree
6789 M-q Fill paragraph and items like in Org-mode
6790 C-c ^ Sort entries
6791 C-c - Cycle list bullet
6792 TAB Cycle item visibility
6793 M-RET Insert new heading/item
6794 S-M-RET Insert new TODO heading / Chekbox item
6795 C-c C-c Set tags / toggle checkbox"
6796 nil " OrgStruct" nil
6797 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6799 ;;;###autoload
6800 (defun turn-on-orgstruct ()
6801 "Unconditionally turn on `orgstruct-mode'."
6802 (orgstruct-mode 1))
6804 ;;;###autoload
6805 (defun turn-on-orgstruct++ ()
6806 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6807 In addition to setting orgstruct-mode, this also exports all indentation and
6808 autofilling variables from org-mode into the buffer. Note that turning
6809 off orgstruct-mode will *not* remove these additonal settings."
6810 (orgstruct-mode 1)
6811 (let (var val)
6812 (mapc
6813 (lambda (x)
6814 (when (string-match
6815 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6816 (symbol-name (car x)))
6817 (setq var (car x) val (nth 1 x))
6818 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6819 org-local-vars)))
6821 (defun orgstruct-error ()
6822 "Error when there is no default binding for a structure key."
6823 (interactive)
6824 (error "This key is has no function outside structure elements"))
6826 (defun orgstruct-setup ()
6827 "Setup orgstruct keymaps."
6828 (let ((nfunc 0)
6829 (bindings
6830 (list
6831 '([(meta up)] org-metaup)
6832 '([(meta down)] org-metadown)
6833 '([(meta left)] org-metaleft)
6834 '([(meta right)] org-metaright)
6835 '([(meta shift up)] org-shiftmetaup)
6836 '([(meta shift down)] org-shiftmetadown)
6837 '([(meta shift left)] org-shiftmetaleft)
6838 '([(meta shift right)] org-shiftmetaright)
6839 '([(shift up)] org-shiftup)
6840 '([(shift down)] org-shiftdown)
6841 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6842 '("\M-q" fill-paragraph)
6843 '("\C-c^" org-sort)
6844 '("\C-c-" org-cycle-list-bullet)))
6845 elt key fun cmd)
6846 (while (setq elt (pop bindings))
6847 (setq nfunc (1+ nfunc))
6848 (setq key (org-key (car elt))
6849 fun (nth 1 elt)
6850 cmd (orgstruct-make-binding fun nfunc key))
6851 (org-defkey orgstruct-mode-map key cmd))
6853 ;; Special treatment needed for TAB and RET
6854 (org-defkey orgstruct-mode-map [(tab)]
6855 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6856 (org-defkey orgstruct-mode-map "\C-i"
6857 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6859 (org-defkey orgstruct-mode-map "\M-\C-m"
6860 (orgstruct-make-binding 'org-insert-heading 105
6861 "\M-\C-m" [(meta return)]))
6862 (org-defkey orgstruct-mode-map [(meta return)]
6863 (orgstruct-make-binding 'org-insert-heading 106
6864 [(meta return)] "\M-\C-m"))
6866 (org-defkey orgstruct-mode-map [(shift meta return)]
6867 (orgstruct-make-binding 'org-insert-todo-heading 107
6868 [(meta return)] "\M-\C-m"))
6870 (unless org-local-vars
6871 (setq org-local-vars (org-get-local-variables)))
6875 (defun orgstruct-make-binding (fun n &rest keys)
6876 "Create a function for binding in the structure minor mode.
6877 FUN is the command to call inside a table. N is used to create a unique
6878 command name. KEYS are keys that should be checked in for a command
6879 to execute outside of tables."
6880 (eval
6881 (list 'defun
6882 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6883 '(arg)
6884 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6885 "Outside of structure, run the binding of `"
6886 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6887 "'.")
6888 '(interactive "p")
6889 (list 'if
6890 '(org-context-p 'headline 'item)
6891 (list 'org-run-like-in-org-mode (list 'quote fun))
6892 (list 'let '(orgstruct-mode)
6893 (list 'call-interactively
6894 (append '(or)
6895 (mapcar (lambda (k)
6896 (list 'key-binding k))
6897 keys)
6898 '('orgstruct-error))))))))
6900 (defun org-context-p (&rest contexts)
6901 "Check if local context is and of CONTEXTS.
6902 Possible values in the list of contexts are `table', `headline', and `item'."
6903 (let ((pos (point)))
6904 (goto-char (point-at-bol))
6905 (prog1 (or (and (memq 'table contexts)
6906 (looking-at "[ \t]*|"))
6907 (and (memq 'headline contexts)
6908 (looking-at "\\*+"))
6909 (and (memq 'item contexts)
6910 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6911 (goto-char pos))))
6913 (defun org-get-local-variables ()
6914 "Return a list of all local variables in an org-mode buffer."
6915 (let (varlist)
6916 (with-current-buffer (get-buffer-create "*Org tmp*")
6917 (erase-buffer)
6918 (org-mode)
6919 (setq varlist (buffer-local-variables)))
6920 (kill-buffer "*Org tmp*")
6921 (delq nil
6922 (mapcar
6923 (lambda (x)
6924 (setq x
6925 (if (symbolp x)
6926 (list x)
6927 (list (car x) (list 'quote (cdr x)))))
6928 (if (string-match
6929 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6930 (symbol-name (car x)))
6931 x nil))
6932 varlist))))
6934 ;;;###autoload
6935 (defun org-run-like-in-org-mode (cmd)
6936 (unless org-local-vars
6937 (setq org-local-vars (org-get-local-variables)))
6938 (eval (list 'let org-local-vars
6939 (list 'call-interactively (list 'quote cmd)))))
6941 ;;;; Archiving
6943 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
6945 (defun org-archive-subtree (&optional find-done)
6946 "Move the current subtree to the archive.
6947 The archive can be a certain top-level heading in the current file, or in
6948 a different file. The tree will be moved to that location, the subtree
6949 heading be marked DONE, and the current time will be added.
6951 When called with prefix argument FIND-DONE, find whole trees without any
6952 open TODO items and archive them (after getting confirmation from the user).
6953 If the cursor is not at a headline when this comand is called, try all level
6954 1 trees. If the cursor is on a headline, only try the direct children of
6955 this heading."
6956 (interactive "P")
6957 (if find-done
6958 (org-archive-all-done)
6959 ;; Save all relevant TODO keyword-relatex variables
6961 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
6962 (tr-org-todo-keywords-1 org-todo-keywords-1)
6963 (tr-org-todo-kwd-alist org-todo-kwd-alist)
6964 (tr-org-done-keywords org-done-keywords)
6965 (tr-org-todo-regexp org-todo-regexp)
6966 (tr-org-todo-line-regexp org-todo-line-regexp)
6967 (tr-org-odd-levels-only org-odd-levels-only)
6968 (this-buffer (current-buffer))
6969 (org-archive-location org-archive-location)
6970 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
6971 (file (abbreviate-file-name (buffer-file-name)))
6972 (time (format-time-string
6973 (substring (cdr org-time-stamp-formats) 1 -1)
6974 (current-time)))
6975 afile heading buffer level newfile-p
6976 category todo priority ltags itags prop)
6978 ;; Try to find a local archive location
6979 (save-excursion
6980 (save-restriction
6981 (widen)
6982 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
6983 (if (and prop (string-match "\\S-" prop))
6984 (setq org-archive-location prop)
6985 (if (or (re-search-backward re nil t)
6986 (re-search-forward re nil t))
6987 (setq org-archive-location (match-string 1))))))
6989 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
6990 (progn
6991 (setq afile (format (match-string 1 org-archive-location)
6992 (file-name-nondirectory buffer-file-name))
6993 heading (match-string 2 org-archive-location)))
6994 (error "Invalid `org-archive-location'"))
6995 (if (> (length afile) 0)
6996 (setq newfile-p (not (file-exists-p afile))
6997 buffer (find-file-noselect afile))
6998 (setq buffer (current-buffer)))
6999 (unless buffer
7000 (error "Cannot access file \"%s\"" afile))
7001 (if (and (> (length heading) 0)
7002 (string-match "^\\*+" heading))
7003 (setq level (match-end 0))
7004 (setq heading nil level 0))
7005 (save-excursion
7006 (org-back-to-heading t)
7007 ;; Get context information that will be lost by moving the tree
7008 (org-refresh-category-properties)
7009 (setq category (org-get-category)
7010 todo (and (looking-at org-todo-line-regexp)
7011 (match-string 2))
7012 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7013 ltags (org-get-tags)
7014 itags (org-delete-all ltags (org-get-tags-at)))
7015 (setq ltags (mapconcat 'identity ltags " ")
7016 itags (mapconcat 'identity itags " "))
7017 ;; We first only copy, in case something goes wrong
7018 ;; we need to protect this-command, to avoid kill-region sets it,
7019 ;; which would lead to duplication of subtrees
7020 (let (this-command) (org-copy-subtree))
7021 (set-buffer buffer)
7022 ;; Enforce org-mode for the archive buffer
7023 (if (not (org-mode-p))
7024 ;; Force the mode for future visits.
7025 (let ((org-insert-mode-line-in-empty-file t)
7026 (org-inhibit-startup t))
7027 (call-interactively 'org-mode)))
7028 (when newfile-p
7029 (goto-char (point-max))
7030 (insert (format "\nArchived entries from file %s\n\n"
7031 (buffer-file-name this-buffer))))
7032 ;; Force the TODO keywords of the original buffer
7033 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7034 (org-todo-keywords-1 tr-org-todo-keywords-1)
7035 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7036 (org-done-keywords tr-org-done-keywords)
7037 (org-todo-regexp tr-org-todo-regexp)
7038 (org-todo-line-regexp tr-org-todo-line-regexp)
7039 (org-odd-levels-only
7040 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7041 org-odd-levels-only
7042 tr-org-odd-levels-only)))
7043 (goto-char (point-min))
7044 (if heading
7045 (progn
7046 (if (re-search-forward
7047 (concat "^" (regexp-quote heading)
7048 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7049 nil t)
7050 (goto-char (match-end 0))
7051 ;; Heading not found, just insert it at the end
7052 (goto-char (point-max))
7053 (or (bolp) (insert "\n"))
7054 (insert "\n" heading "\n")
7055 (end-of-line 0))
7056 ;; Make the subtree visible
7057 (show-subtree)
7058 (org-end-of-subtree t)
7059 (skip-chars-backward " \t\r\n")
7060 (and (looking-at "[ \t\r\n]*")
7061 (replace-match "\n\n")))
7062 ;; No specific heading, just go to end of file.
7063 (goto-char (point-max)) (insert "\n"))
7064 ;; Paste
7065 (org-paste-subtree (org-get-legal-level level 1))
7067 ;; Mark the entry as done
7068 (when (and org-archive-mark-done
7069 (looking-at org-todo-line-regexp)
7070 (or (not (match-end 2))
7071 (not (member (match-string 2) org-done-keywords))))
7072 (let (org-log-done)
7073 (org-todo
7074 (car (or (member org-archive-mark-done org-done-keywords)
7075 org-done-keywords)))))
7077 ;; Add the context info
7078 (when org-archive-save-context-info
7079 (let ((l org-archive-save-context-info) e n v)
7080 (while (setq e (pop l))
7081 (when (and (setq v (symbol-value e))
7082 (stringp v) (string-match "\\S-" v))
7083 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7084 (org-entry-put (point) n v)))))
7086 ;; Save the buffer, if it is not the same buffer.
7087 (if (not (eq this-buffer buffer)) (save-buffer))))
7088 ;; Here we are back in the original buffer. Everything seems to have
7089 ;; worked. So now cut the tree and finish up.
7090 (let (this-command) (org-cut-subtree))
7091 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7092 (message "Subtree archived %s"
7093 (if (eq this-buffer buffer)
7094 (concat "under heading: " heading)
7095 (concat "in file: " (abbreviate-file-name afile)))))))
7097 (defun org-refresh-category-properties ()
7098 "Refresh category text properties in teh buffer."
7099 (let ((def-cat (cond
7100 ((null org-category)
7101 (if buffer-file-name
7102 (file-name-sans-extension
7103 (file-name-nondirectory buffer-file-name))
7104 "???"))
7105 ((symbolp org-category) (symbol-name org-category))
7106 (t org-category)))
7107 beg end cat pos optionp)
7108 (org-unmodified
7109 (save-excursion
7110 (save-restriction
7111 (widen)
7112 (goto-char (point-min))
7113 (put-text-property (point) (point-max) 'org-category def-cat)
7114 (while (re-search-forward
7115 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7116 (setq pos (match-end 0)
7117 optionp (equal (char-after (match-beginning 0)) ?#)
7118 cat (org-trim (match-string 2)))
7119 (if optionp
7120 (setq beg (point-at-bol) end (point-max))
7121 (org-back-to-heading t)
7122 (setq beg (point) end (org-end-of-subtree t t)))
7123 (put-text-property beg end 'org-category cat)
7124 (goto-char pos)))))))
7126 (defun org-archive-all-done (&optional tag)
7127 "Archive sublevels of the current tree without open TODO items.
7128 If the cursor is not on a headline, try all level 1 trees. If
7129 it is on a headline, try all direct children.
7130 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7131 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7132 (rea (concat ".*:" org-archive-tag ":"))
7133 (begm (make-marker))
7134 (endm (make-marker))
7135 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7136 "Move subtree to archive (no open TODO items)? "))
7137 beg end (cntarch 0))
7138 (if (org-on-heading-p)
7139 (progn
7140 (setq re1 (concat "^" (regexp-quote
7141 (make-string
7142 (1+ (- (match-end 0) (match-beginning 0)))
7143 ?*))
7144 " "))
7145 (move-marker begm (point))
7146 (move-marker endm (org-end-of-subtree t)))
7147 (setq re1 "^* ")
7148 (move-marker begm (point-min))
7149 (move-marker endm (point-max)))
7150 (save-excursion
7151 (goto-char begm)
7152 (while (re-search-forward re1 endm t)
7153 (setq beg (match-beginning 0)
7154 end (save-excursion (org-end-of-subtree t) (point)))
7155 (goto-char beg)
7156 (if (re-search-forward re end t)
7157 (goto-char end)
7158 (goto-char beg)
7159 (if (and (or (not tag) (not (looking-at rea)))
7160 (y-or-n-p question))
7161 (progn
7162 (if tag
7163 (org-toggle-tag org-archive-tag 'on)
7164 (org-archive-subtree))
7165 (setq cntarch (1+ cntarch)))
7166 (goto-char end)))))
7167 (message "%d trees archived" cntarch)))
7169 (defun org-cycle-hide-drawers (state)
7170 "Re-hide all drawers after a visibility state change."
7171 (when (and (org-mode-p)
7172 (not (memq state '(overview folded))))
7173 (save-excursion
7174 (let* ((globalp (memq state '(contents all)))
7175 (beg (if globalp (point-min) (point)))
7176 (end (if globalp (point-max) (org-end-of-subtree t))))
7177 (goto-char beg)
7178 (while (re-search-forward org-drawer-regexp end t)
7179 (org-flag-drawer t))))))
7181 (defun org-flag-drawer (flag)
7182 (save-excursion
7183 (beginning-of-line 1)
7184 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7185 (let ((b (match-end 0)))
7186 (if (re-search-forward
7187 "^[ \t]*:END:"
7188 (save-excursion (outline-next-heading) (point)) t)
7189 (outline-flag-region b (point-at-eol) flag)
7190 (error ":END: line missing"))))))
7192 (defun org-cycle-hide-archived-subtrees (state)
7193 "Re-hide all archived subtrees after a visibility state change."
7194 (when (and (not org-cycle-open-archived-trees)
7195 (not (memq state '(overview folded))))
7196 (save-excursion
7197 (let* ((globalp (memq state '(contents all)))
7198 (beg (if globalp (point-min) (point)))
7199 (end (if globalp (point-max) (org-end-of-subtree t))))
7200 (org-hide-archived-subtrees beg end)
7201 (goto-char beg)
7202 (if (looking-at (concat ".*:" org-archive-tag ":"))
7203 (message (substitute-command-keys
7204 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7206 (defun org-force-cycle-archived ()
7207 "Cycle subtree even if it is archived."
7208 (interactive)
7209 (setq this-command 'org-cycle)
7210 (let ((org-cycle-open-archived-trees t))
7211 (call-interactively 'org-cycle)))
7213 (defun org-hide-archived-subtrees (beg end)
7214 "Re-hide all archived subtrees after a visibility state change."
7215 (save-excursion
7216 (let* ((re (concat ":" org-archive-tag ":")))
7217 (goto-char beg)
7218 (while (re-search-forward re end t)
7219 (and (org-on-heading-p) (hide-subtree))
7220 (org-end-of-subtree t)))))
7222 (defun org-toggle-tag (tag &optional onoff)
7223 "Toggle the tag TAG for the current line.
7224 If ONOFF is `on' or `off', don't toggle but set to this state."
7225 (unless (org-on-heading-p t) (error "Not on headling"))
7226 (let (res current)
7227 (save-excursion
7228 (beginning-of-line)
7229 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7230 (point-at-eol) t)
7231 (progn
7232 (setq current (match-string 1))
7233 (replace-match ""))
7234 (setq current ""))
7235 (setq current (nreverse (org-split-string current ":")))
7236 (cond
7237 ((eq onoff 'on)
7238 (setq res t)
7239 (or (member tag current) (push tag current)))
7240 ((eq onoff 'off)
7241 (or (not (member tag current)) (setq current (delete tag current))))
7242 (t (if (member tag current)
7243 (setq current (delete tag current))
7244 (setq res t)
7245 (push tag current))))
7246 (end-of-line 1)
7247 (when current
7248 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
7249 (org-set-tags nil t)
7250 res)
7251 (run-hooks 'org-after-tags-change-hook)))
7253 (defun org-toggle-archive-tag (&optional arg)
7254 "Toggle the archive tag for the current headline.
7255 With prefix ARG, check all children of current headline and offer tagging
7256 the children that do not contain any open TODO items."
7257 (interactive "P")
7258 (if arg
7259 (org-archive-all-done 'tag)
7260 (let (set)
7261 (save-excursion
7262 (org-back-to-heading t)
7263 (setq set (org-toggle-tag org-archive-tag))
7264 (when set (hide-subtree)))
7265 (and set (beginning-of-line 1))
7266 (message "Subtree %s" (if set "archived" "unarchived")))))
7269 ;;;; Tables
7271 ;;; The table editor
7273 ;; Watch out: Here we are talking about two different kind of tables.
7274 ;; Most of the code is for the tables created with the Org-mode table editor.
7275 ;; Sometimes, we talk about tables created and edited with the table.el
7276 ;; Emacs package. We call the former org-type tables, and the latter
7277 ;; table.el-type tables.
7279 (defun org-before-change-function (beg end)
7280 "Every change indicates that a table might need an update."
7281 (setq org-table-may-need-update t))
7283 (defconst org-table-line-regexp "^[ \t]*|"
7284 "Detects an org-type table line.")
7285 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7286 "Detects an org-type table line.")
7287 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7288 "Detects a table line marked for automatic recalculation.")
7289 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7290 "Detects a table line marked for automatic recalculation.")
7291 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7292 "Detects a table line marked for automatic recalculation.")
7293 (defconst org-table-hline-regexp "^[ \t]*|-"
7294 "Detects an org-type table hline.")
7295 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7296 "Detects a table-type table hline.")
7297 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7298 "Detects an org-type or table-type table.")
7299 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7300 "Searching from within a table (any type) this finds the first line
7301 outside the table.")
7302 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7303 "Searching from within a table (any type) this finds the first line
7304 outside the table.")
7306 (defvar org-table-last-highlighted-reference nil)
7307 (defvar org-table-formula-history nil)
7309 (defvar org-table-column-names nil
7310 "Alist with column names, derived from the `!' line.")
7311 (defvar org-table-column-name-regexp nil
7312 "Regular expression matching the current column names.")
7313 (defvar org-table-local-parameters nil
7314 "Alist with parameter names, derived from the `$' line.")
7315 (defvar org-table-named-field-locations nil
7316 "Alist with locations of named fields.")
7318 (defvar org-table-current-line-types nil
7319 "Table row types, non-nil only for the duration of a comand.")
7320 (defvar org-table-current-begin-line nil
7321 "Table begin line, non-nil only for the duration of a comand.")
7322 (defvar org-table-current-begin-pos nil
7323 "Table begin position, non-nil only for the duration of a comand.")
7324 (defvar org-table-dlines nil
7325 "Vector of data line line numbers in the current table.")
7326 (defvar org-table-hlines nil
7327 "Vector of hline line numbers in the current table.")
7329 (defconst org-table-range-regexp
7330 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
7331 ;; 1 2 3 4 5
7332 "Regular expression for matching ranges in formulas.")
7334 (defconst org-table-range-regexp2
7335 (concat
7336 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
7337 "\\.\\."
7338 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
7339 "Match a range for reference display.")
7341 (defconst org-table-translate-regexp
7342 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
7343 "Match a reference that needs translation, for reference display.")
7345 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
7347 (defun org-table-create-with-table.el ()
7348 "Use the table.el package to insert a new table.
7349 If there is already a table at point, convert between Org-mode tables
7350 and table.el tables."
7351 (interactive)
7352 (require 'table)
7353 (cond
7354 ((org-at-table.el-p)
7355 (if (y-or-n-p "Convert table to Org-mode table? ")
7356 (org-table-convert)))
7357 ((org-at-table-p)
7358 (if (y-or-n-p "Convert table to table.el table? ")
7359 (org-table-convert)))
7360 (t (call-interactively 'table-insert))))
7362 (defun org-table-create-or-convert-from-region (arg)
7363 "Convert region to table, or create an empty table.
7364 If there is an active region, convert it to a table, using the function
7365 `org-table-convert-region'. See the documentation of that function
7366 to learn how the prefix argument is interpreted to determine the field
7367 separator.
7368 If there is no such region, create an empty table with `org-table-create'."
7369 (interactive "P")
7370 (if (org-region-active-p)
7371 (org-table-convert-region (region-beginning) (region-end) arg)
7372 (org-table-create arg)))
7374 (defun org-table-create (&optional size)
7375 "Query for a size and insert a table skeleton.
7376 SIZE is a string Columns x Rows like for example \"3x2\"."
7377 (interactive "P")
7378 (unless size
7379 (setq size (read-string
7380 (concat "Table size Columns x Rows [e.g. "
7381 org-table-default-size "]: ")
7382 "" nil org-table-default-size)))
7384 (let* ((pos (point))
7385 (indent (make-string (current-column) ?\ ))
7386 (split (org-split-string size " *x *"))
7387 (rows (string-to-number (nth 1 split)))
7388 (columns (string-to-number (car split)))
7389 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7390 "\n")))
7391 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7392 (point-at-bol) (point)))
7393 (beginning-of-line 1)
7394 (newline))
7395 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7396 (dotimes (i rows) (insert line))
7397 (goto-char pos)
7398 (if (> rows 1)
7399 ;; Insert a hline after the first row.
7400 (progn
7401 (end-of-line 1)
7402 (insert "\n|-")
7403 (goto-char pos)))
7404 (org-table-align)))
7406 (defun org-table-convert-region (beg0 end0 &optional separator)
7407 "Convert region to a table.
7408 The region goes from BEG0 to END0, but these borders will be moved
7409 slightly, to make sure a beginning of line in the first line is included.
7411 SEPARATOR specifies the field separator in the lines. It can have the
7412 following values:
7414 '(4) Use the comma as a field separator
7415 '(16) Use a TAB as field separator
7416 integer When a number, use that many spaces as field separator
7417 nil When nil, the command tries to be smart and figure out the
7418 separator in the following way:
7419 - when each line contains a TAB, assume TAB-separated material
7420 - when each line contains a comme, assume CSV material
7421 - else, assume one or more SPACE charcters as separator."
7422 (interactive "rP")
7423 (let* ((beg (min beg0 end0))
7424 (end (max beg0 end0))
7425 sep-re re)
7426 (goto-char beg)
7427 (beginning-of-line 1)
7428 (setq beg (move-marker (make-marker) (point)))
7429 (goto-char end)
7430 (if (bolp) (backward-char 1) (end-of-line 1))
7431 (setq end (move-marker (make-marker) (point)))
7432 ;; Get the right field separator
7433 (unless separator
7434 (goto-char beg)
7435 (setq separator
7436 (cond
7437 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
7438 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
7439 (t 1))))
7440 (setq re (cond
7441 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
7442 ((equal separator '(16)) "^\\|\t")
7443 ((integerp separator)
7444 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
7445 (t (error "This should not happen"))))
7446 (goto-char beg)
7447 (while (re-search-forward re end t)
7448 (replace-match "| " t t))
7449 (goto-char beg)
7450 (insert " ")
7451 (org-table-align)))
7453 (defun org-table-import (file arg)
7454 "Import FILE as a table.
7455 The file is assumed to be tab-separated. Such files can be produced by most
7456 spreadsheet and database applications. If no tabs (at least one per line)
7457 are found, lines will be split on whitespace into fields."
7458 (interactive "f\nP")
7459 (or (bolp) (newline))
7460 (let ((beg (point))
7461 (pm (point-max)))
7462 (insert-file-contents file)
7463 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7465 (defun org-table-export ()
7466 "Export table as a tab-separated file.
7467 Such a file can be imported into a spreadsheet program like Excel."
7468 (interactive)
7469 (let* ((beg (org-table-begin))
7470 (end (org-table-end))
7471 (table (buffer-substring beg end))
7472 (file (read-file-name "Export table to: "))
7473 buf)
7474 (unless (or (not (file-exists-p file))
7475 (y-or-n-p (format "Overwrite file %s? " file)))
7476 (error "Abort"))
7477 (with-current-buffer (find-file-noselect file)
7478 (setq buf (current-buffer))
7479 (erase-buffer)
7480 (fundamental-mode)
7481 (insert table)
7482 (goto-char (point-min))
7483 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7484 (replace-match "" t t)
7485 (end-of-line 1))
7486 (goto-char (point-min))
7487 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7488 (replace-match "" t t)
7489 (goto-char (min (1+ (point)) (point-max))))
7490 (goto-char (point-min))
7491 (while (re-search-forward "^-[-+]*$" nil t)
7492 (replace-match "")
7493 (if (looking-at "\n")
7494 (delete-char 1)))
7495 (goto-char (point-min))
7496 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7497 (replace-match "\t" t t))
7498 (save-buffer))
7499 (kill-buffer buf)))
7501 (defvar org-table-aligned-begin-marker (make-marker)
7502 "Marker at the beginning of the table last aligned.
7503 Used to check if cursor still is in that table, to minimize realignment.")
7504 (defvar org-table-aligned-end-marker (make-marker)
7505 "Marker at the end of the table last aligned.
7506 Used to check if cursor still is in that table, to minimize realignment.")
7507 (defvar org-table-last-alignment nil
7508 "List of flags for flushright alignment, from the last re-alignment.
7509 This is being used to correctly align a single field after TAB or RET.")
7510 (defvar org-table-last-column-widths nil
7511 "List of max width of fields in each column.
7512 This is being used to correctly align a single field after TAB or RET.")
7513 (defvar org-table-overlay-coordinates nil
7514 "Overlay coordinates after each align of a table.")
7515 (make-variable-buffer-local 'org-table-overlay-coordinates)
7517 (defvar org-last-recalc-line nil)
7518 (defconst org-narrow-column-arrow "=>"
7519 "Used as display property in narrowed table columns.")
7521 (defun org-table-align ()
7522 "Align the table at point by aligning all vertical bars."
7523 (interactive)
7524 (let* (
7525 ;; Limits of table
7526 (beg (org-table-begin))
7527 (end (org-table-end))
7528 ;; Current cursor position
7529 (linepos (org-current-line))
7530 (colpos (org-table-current-column))
7531 (winstart (window-start))
7532 (winstartline (org-current-line (min winstart (1- (point-max)))))
7533 lines (new "") lengths l typenums ty fields maxfields i
7534 column
7535 (indent "") cnt frac
7536 rfmt hfmt
7537 (spaces '(1 . 1))
7538 (sp1 (car spaces))
7539 (sp2 (cdr spaces))
7540 (rfmt1 (concat
7541 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7542 (hfmt1 (concat
7543 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7544 emptystrings links dates narrow fmax f1 len c e)
7545 (untabify beg end)
7546 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
7547 ;; Check if we have links or dates
7548 (goto-char beg)
7549 (setq links (re-search-forward org-bracket-link-regexp end t))
7550 (goto-char beg)
7551 (setq dates (and org-display-custom-times
7552 (re-search-forward org-ts-regexp-both end t)))
7553 ;; Make sure the link properties are right
7554 (when links (goto-char beg) (while (org-activate-bracket-links end)))
7555 ;; Make sure the date properties are right
7556 (when dates (goto-char beg) (while (org-activate-dates end)))
7558 ;; Check if we are narrowing any columns
7559 (goto-char beg)
7560 (setq narrow (and org-format-transports-properties-p
7561 (re-search-forward "<[0-9]+>" end t)))
7562 ;; Get the rows
7563 (setq lines (org-split-string
7564 (buffer-substring beg end) "\n"))
7565 ;; Store the indentation of the first line
7566 (if (string-match "^ *" (car lines))
7567 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7568 ;; Mark the hlines by setting the corresponding element to nil
7569 ;; At the same time, we remove trailing space.
7570 (setq lines (mapcar (lambda (l)
7571 (if (string-match "^ *|-" l)
7573 (if (string-match "[ \t]+$" l)
7574 (substring l 0 (match-beginning 0))
7575 l)))
7576 lines))
7577 ;; Get the data fields by splitting the lines.
7578 (setq fields (mapcar
7579 (lambda (l)
7580 (org-split-string l " *| *"))
7581 (delq nil (copy-sequence lines))))
7582 ;; How many fields in the longest line?
7583 (condition-case nil
7584 (setq maxfields (apply 'max (mapcar 'length fields)))
7585 (error
7586 (kill-region beg end)
7587 (org-table-create org-table-default-size)
7588 (error "Empty table - created default table")))
7589 ;; A list of empty strings to fill any short rows on output
7590 (setq emptystrings (make-list maxfields ""))
7591 ;; Check for special formatting.
7592 (setq i -1)
7593 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7594 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7595 ;; Check if there is an explicit width specified
7596 (when narrow
7597 (setq c column fmax nil)
7598 (while c
7599 (setq e (pop c))
7600 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
7601 (setq fmax (string-to-number (match-string 1 e)) c nil)))
7602 ;; Find fields that are wider than fmax, and shorten them
7603 (when fmax
7604 (loop for xx in column do
7605 (when (and (stringp xx)
7606 (> (org-string-width xx) fmax))
7607 (org-add-props xx nil
7608 'help-echo
7609 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
7610 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
7611 (unless (> f1 1)
7612 (error "Cannot narrow field starting with wide link \"%s\""
7613 (match-string 0 xx)))
7614 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
7615 (add-text-properties (- f1 2) f1
7616 (list 'display org-narrow-column-arrow)
7617 xx)))))
7618 ;; Get the maximum width for each column
7619 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
7620 ;; Get the fraction of numbers, to decide about alignment of the column
7621 (setq cnt 0 frac 0.0)
7622 (loop for x in column do
7623 (if (equal x "")
7625 (setq frac ( / (+ (* frac cnt)
7626 (if (string-match org-table-number-regexp x) 1 0))
7627 (setq cnt (1+ cnt))))))
7628 (push (>= frac org-table-number-fraction) typenums))
7629 (setq lengths (nreverse lengths) typenums (nreverse typenums))
7631 ;; Store the alignment of this table, for later editing of single fields
7632 (setq org-table-last-alignment typenums
7633 org-table-last-column-widths lengths)
7635 ;; With invisible characters, `format' does not get the field width right
7636 ;; So we need to make these fields wide by hand.
7637 (when links
7638 (loop for i from 0 upto (1- maxfields) do
7639 (setq len (nth i lengths))
7640 (loop for j from 0 upto (1- (length fields)) do
7641 (setq c (nthcdr i (car (nthcdr j fields))))
7642 (if (and (stringp (car c))
7643 (string-match org-bracket-link-regexp (car c))
7644 (< (org-string-width (car c)) len))
7645 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
7647 ;; Compute the formats needed for output of the table
7648 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7649 (while (setq l (pop lengths))
7650 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7651 (setq rfmt (concat rfmt (format rfmt1 ty l))
7652 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7653 (setq rfmt (concat rfmt "\n")
7654 hfmt (concat (substring hfmt 0 -1) "|\n"))
7656 (setq new (mapconcat
7657 (lambda (l)
7658 (if l (apply 'format rfmt
7659 (append (pop fields) emptystrings))
7660 hfmt))
7661 lines ""))
7662 ;; Replace the old one
7663 (delete-region beg end)
7664 (move-marker end nil)
7665 (move-marker org-table-aligned-begin-marker (point))
7666 (insert new)
7667 (move-marker org-table-aligned-end-marker (point))
7668 (when (and orgtbl-mode (not (org-mode-p)))
7669 (goto-char org-table-aligned-begin-marker)
7670 (while (org-hide-wide-columns org-table-aligned-end-marker)))
7671 ;; Try to move to the old location
7672 (goto-line winstartline)
7673 (setq winstart (point-at-bol))
7674 (goto-line linepos)
7675 (set-window-start (selected-window) winstart 'noforce)
7676 (org-table-goto-column colpos)
7677 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
7678 (setq org-table-may-need-update nil)
7681 (defun org-string-width (s)
7682 "Compute width of string, ignoring invisible characters.
7683 This ignores character with invisibility property `org-link', and also
7684 characters with property `org-cwidth', because these will become invisible
7685 upon the next fontification round."
7686 (let (b l)
7687 (when (or (eq t buffer-invisibility-spec)
7688 (assq 'org-link buffer-invisibility-spec))
7689 (while (setq b (text-property-any 0 (length s)
7690 'invisible 'org-link s))
7691 (setq s (concat (substring s 0 b)
7692 (substring s (or (next-single-property-change
7693 b 'invisible s) (length s)))))))
7694 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
7695 (setq s (concat (substring s 0 b)
7696 (substring s (or (next-single-property-change
7697 b 'org-cwidth s) (length s))))))
7698 (setq l (string-width s) b -1)
7699 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
7700 (setq l (- l (get-text-property b 'org-dwidth-n s))))
7703 (defun org-table-begin (&optional table-type)
7704 "Find the beginning of the table and return its position.
7705 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7706 (save-excursion
7707 (if (not (re-search-backward
7708 (if table-type org-table-any-border-regexp
7709 org-table-border-regexp)
7710 nil t))
7711 (progn (goto-char (point-min)) (point))
7712 (goto-char (match-beginning 0))
7713 (beginning-of-line 2)
7714 (point))))
7716 (defun org-table-end (&optional table-type)
7717 "Find the end of the table and return its position.
7718 With argument TABLE-TYPE, go to the end of a table.el-type table."
7719 (save-excursion
7720 (if (not (re-search-forward
7721 (if table-type org-table-any-border-regexp
7722 org-table-border-regexp)
7723 nil t))
7724 (goto-char (point-max))
7725 (goto-char (match-beginning 0)))
7726 (point-marker)))
7728 (defun org-table-justify-field-maybe (&optional new)
7729 "Justify the current field, text to left, number to right.
7730 Optional argument NEW may specify text to replace the current field content."
7731 (cond
7732 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7733 ((org-at-table-hline-p))
7734 ((and (not new)
7735 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7736 (current-buffer)))
7737 (< (point) org-table-aligned-begin-marker)
7738 (>= (point) org-table-aligned-end-marker)))
7739 ;; This is not the same table, force a full re-align
7740 (setq org-table-may-need-update t))
7741 (t ;; realign the current field, based on previous full realign
7742 (let* ((pos (point)) s
7743 (col (org-table-current-column))
7744 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
7745 l f n o e)
7746 (when (> col 0)
7747 (skip-chars-backward "^|\n")
7748 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7749 (progn
7750 (setq s (match-string 1)
7751 o (match-string 0)
7752 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7753 e (not (= (match-beginning 2) (match-end 2))))
7754 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7755 l (if e "|" (setq org-table-may-need-update t) ""))
7756 n (format f s))
7757 (if new
7758 (if (<= (length new) l) ;; FIXME: length -> str-width?
7759 (setq n (format f new))
7760 (setq n (concat new "|") org-table-may-need-update t)))
7761 (or (equal n o)
7762 (let (org-table-may-need-update)
7763 (replace-match n t t))))
7764 (setq org-table-may-need-update t))
7765 (goto-char pos))))))
7767 (defun org-table-next-field ()
7768 "Go to the next field in the current table, creating new lines as needed.
7769 Before doing so, re-align the table if necessary."
7770 (interactive)
7771 (org-table-maybe-eval-formula)
7772 (org-table-maybe-recalculate-line)
7773 (if (and org-table-automatic-realign
7774 org-table-may-need-update)
7775 (org-table-align))
7776 (let ((end (org-table-end)))
7777 (if (org-at-table-hline-p)
7778 (end-of-line 1))
7779 (condition-case nil
7780 (progn
7781 (re-search-forward "|" end)
7782 (if (looking-at "[ \t]*$")
7783 (re-search-forward "|" end))
7784 (if (and (looking-at "-")
7785 org-table-tab-jumps-over-hlines
7786 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7787 (goto-char (match-beginning 1)))
7788 (if (looking-at "-")
7789 (progn
7790 (beginning-of-line 0)
7791 (org-table-insert-row 'below))
7792 (if (looking-at " ") (forward-char 1))))
7793 (error
7794 (org-table-insert-row 'below)))))
7796 (defun org-table-previous-field ()
7797 "Go to the previous field in the table.
7798 Before doing so, re-align the table if necessary."
7799 (interactive)
7800 (org-table-justify-field-maybe)
7801 (org-table-maybe-recalculate-line)
7802 (if (and org-table-automatic-realign
7803 org-table-may-need-update)
7804 (org-table-align))
7805 (if (org-at-table-hline-p)
7806 (end-of-line 1))
7807 (re-search-backward "|" (org-table-begin))
7808 (re-search-backward "|" (org-table-begin))
7809 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7810 (re-search-backward "|" (org-table-begin)))
7811 (if (looking-at "| ?")
7812 (goto-char (match-end 0))))
7814 (defun org-table-next-row ()
7815 "Go to the next row (same column) in the current table.
7816 Before doing so, re-align the table if necessary."
7817 (interactive)
7818 (org-table-maybe-eval-formula)
7819 (org-table-maybe-recalculate-line)
7820 (if (or (looking-at "[ \t]*$")
7821 (save-excursion (skip-chars-backward " \t") (bolp)))
7822 (newline)
7823 (if (and org-table-automatic-realign
7824 org-table-may-need-update)
7825 (org-table-align))
7826 (let ((col (org-table-current-column)))
7827 (beginning-of-line 2)
7828 (if (or (not (org-at-table-p))
7829 (org-at-table-hline-p))
7830 (progn
7831 (beginning-of-line 0)
7832 (org-table-insert-row 'below)))
7833 (org-table-goto-column col)
7834 (skip-chars-backward "^|\n\r")
7835 (if (looking-at " ") (forward-char 1)))))
7837 (defun org-table-copy-down (n)
7838 "Copy a field down in the current column.
7839 If the field at the cursor is empty, copy into it the content of the nearest
7840 non-empty field above. With argument N, use the Nth non-empty field.
7841 If the current field is not empty, it is copied down to the next row, and
7842 the cursor is moved with it. Therefore, repeating this command causes the
7843 column to be filled row-by-row.
7844 If the variable `org-table-copy-increment' is non-nil and the field is an
7845 integer or a timestamp, it will be incremented while copying. In the case of
7846 a timestamp, if the cursor is on the year, change the year. If it is on the
7847 month or the day, change that. Point will stay on the current date field
7848 in order to easily repeat the interval."
7849 (interactive "p")
7850 (let* ((colpos (org-table-current-column))
7851 (col (current-column))
7852 (field (org-table-get-field))
7853 (non-empty (string-match "[^ \t]" field))
7854 (beg (org-table-begin))
7855 txt)
7856 (org-table-check-inside-data-field)
7857 (if non-empty
7858 (progn
7859 (setq txt (org-trim field))
7860 (org-table-next-row)
7861 (org-table-blank-field))
7862 (save-excursion
7863 (setq txt
7864 (catch 'exit
7865 (while (progn (beginning-of-line 1)
7866 (re-search-backward org-table-dataline-regexp
7867 beg t))
7868 (org-table-goto-column colpos t)
7869 (if (and (looking-at
7870 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7871 (= (setq n (1- n)) 0))
7872 (throw 'exit (match-string 1))))))))
7873 (if txt
7874 (progn
7875 (if (and org-table-copy-increment
7876 (string-match "^[0-9]+$" txt))
7877 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7878 (insert txt)
7879 (move-to-column col)
7880 (if (and org-table-copy-increment (org-at-timestamp-p t))
7881 (org-timestamp-up 1)
7882 (org-table-maybe-recalculate-line))
7883 (org-table-align)
7884 (move-to-column col))
7885 (error "No non-empty field found"))))
7887 (defun org-table-check-inside-data-field ()
7888 "Is point inside a table data field?
7889 I.e. not on a hline or before the first or after the last column?
7890 This actually throws an error, so it aborts the current command."
7891 (if (or (not (org-at-table-p))
7892 (= (org-table-current-column) 0)
7893 (org-at-table-hline-p)
7894 (looking-at "[ \t]*$"))
7895 (error "Not in table data field")))
7897 (defvar org-table-clip nil
7898 "Clipboard for table regions.")
7900 (defun org-table-blank-field ()
7901 "Blank the current table field or active region."
7902 (interactive)
7903 (org-table-check-inside-data-field)
7904 (if (and (interactive-p) (org-region-active-p))
7905 (let (org-table-clip)
7906 (org-table-cut-region (region-beginning) (region-end)))
7907 (skip-chars-backward "^|")
7908 (backward-char 1)
7909 (if (looking-at "|[^|\n]+")
7910 (let* ((pos (match-beginning 0))
7911 (match (match-string 0))
7912 (len (org-string-width match)))
7913 (replace-match (concat "|" (make-string (1- len) ?\ )))
7914 (goto-char (+ 2 pos))
7915 (substring match 1)))))
7917 (defun org-table-get-field (&optional n replace)
7918 "Return the value of the field in column N of current row.
7919 N defaults to current field.
7920 If REPLACE is a string, replace field with this value. The return value
7921 is always the old value."
7922 (and n (org-table-goto-column n))
7923 (skip-chars-backward "^|\n")
7924 (backward-char 1)
7925 (if (looking-at "|[^|\r\n]*")
7926 (let* ((pos (match-beginning 0))
7927 (val (buffer-substring (1+ pos) (match-end 0))))
7928 (if replace
7929 (replace-match (concat "|" replace) t t))
7930 (goto-char (min (point-at-eol) (+ 2 pos)))
7931 val)
7932 (forward-char 1) ""))
7934 (defun org-table-field-info (arg)
7935 "Show info about the current field, and highlight any reference at point."
7936 (interactive "P")
7937 (org-table-get-specials)
7938 (save-excursion
7939 (let* ((pos (point))
7940 (col (org-table-current-column))
7941 (cname (car (rassoc (int-to-string col) org-table-column-names)))
7942 (name (car (rassoc (list (org-current-line) col)
7943 org-table-named-field-locations)))
7944 (eql (org-table-get-stored-formulas))
7945 (dline (org-table-current-dline))
7946 (ref (format "@%d$%d" dline col))
7947 (ref1 (org-table-convert-refs-to-an ref))
7948 (fequation (or (assoc name eql) (assoc ref eql)))
7949 (cequation (assoc (int-to-string col) eql))
7950 (eqn (or fequation cequation)))
7951 (goto-char pos)
7952 (condition-case nil
7953 (org-table-show-reference 'local)
7954 (error nil))
7955 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
7956 dline col
7957 (if cname (concat " or $" cname) "")
7958 dline col ref1
7959 (if name (concat " or $" name) "")
7960 ;; FIXME: formula info not correct if special table line
7961 (if eqn
7962 (concat ", formula: "
7963 (org-table-formula-to-user
7964 (concat
7965 (if (string-match "^[$@]"(car eqn)) "" "$")
7966 (car eqn) "=" (cdr eqn))))
7967 "")))))
7969 (defun org-table-current-column ()
7970 "Find out which column we are in.
7971 When called interactively, column is also displayed in echo area."
7972 (interactive)
7973 (if (interactive-p) (org-table-check-inside-data-field))
7974 (save-excursion
7975 (let ((cnt 0) (pos (point)))
7976 (beginning-of-line 1)
7977 (while (search-forward "|" pos t)
7978 (setq cnt (1+ cnt)))
7979 (if (interactive-p) (message "This is table column %d" cnt))
7980 cnt)))
7982 (defun org-table-current-dline ()
7983 "Find out what table data line we are in.
7984 Only datalins count for this."
7985 (interactive)
7986 (if (interactive-p) (org-table-check-inside-data-field))
7987 (save-excursion
7988 (let ((cnt 0) (pos (point)))
7989 (goto-char (org-table-begin))
7990 (while (<= (point) pos)
7991 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
7992 (beginning-of-line 2))
7993 (if (interactive-p) (message "This is table line %d" cnt))
7994 cnt)))
7996 (defun org-table-goto-column (n &optional on-delim force)
7997 "Move the cursor to the Nth column in the current table line.
7998 With optional argument ON-DELIM, stop with point before the left delimiter
7999 of the field.
8000 If there are less than N fields, just go to after the last delimiter.
8001 However, when FORCE is non-nil, create new columns if necessary."
8002 (interactive "p")
8003 (let ((pos (point-at-eol)))
8004 (beginning-of-line 1)
8005 (when (> n 0)
8006 (while (and (> (setq n (1- n)) -1)
8007 (or (search-forward "|" pos t)
8008 (and force
8009 (progn (end-of-line 1)
8010 (skip-chars-backward "^|")
8011 (insert " | "))))))
8012 ; (backward-char 2) t)))))
8013 (when (and force (not (looking-at ".*|")))
8014 (save-excursion (end-of-line 1) (insert " | ")))
8015 (if on-delim
8016 (backward-char 1)
8017 (if (looking-at " ") (forward-char 1))))))
8019 (defun org-at-table-p (&optional table-type)
8020 "Return t if the cursor is inside an org-type table.
8021 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8022 (if org-enable-table-editor
8023 (save-excursion
8024 (beginning-of-line 1)
8025 (looking-at (if table-type org-table-any-line-regexp
8026 org-table-line-regexp)))
8027 nil))
8029 (defun org-at-table.el-p ()
8030 "Return t if and only if we are at a table.el table."
8031 (and (org-at-table-p 'any)
8032 (save-excursion
8033 (goto-char (org-table-begin 'any))
8034 (looking-at org-table1-hline-regexp))))
8036 (defun org-table-recognize-table.el ()
8037 "If there is a table.el table nearby, recognize it and move into it."
8038 (if org-table-tab-recognizes-table.el
8039 (if (org-at-table.el-p)
8040 (progn
8041 (beginning-of-line 1)
8042 (if (looking-at org-table-dataline-regexp)
8044 (if (looking-at org-table1-hline-regexp)
8045 (progn
8046 (beginning-of-line 2)
8047 (if (looking-at org-table-any-border-regexp)
8048 (beginning-of-line -1)))))
8049 (if (re-search-forward "|" (org-table-end t) t)
8050 (progn
8051 (require 'table)
8052 (if (table--at-cell-p (point))
8054 (message "recognizing table.el table...")
8055 (table-recognize-table)
8056 (message "recognizing table.el table...done")))
8057 (error "This should not happen..."))
8059 nil)
8060 nil))
8062 (defun org-at-table-hline-p ()
8063 "Return t if the cursor is inside a hline in a table."
8064 (if org-enable-table-editor
8065 (save-excursion
8066 (beginning-of-line 1)
8067 (looking-at org-table-hline-regexp))
8068 nil))
8070 (defun org-table-insert-column ()
8071 "Insert a new column into the table."
8072 (interactive)
8073 (if (not (org-at-table-p))
8074 (error "Not at a table"))
8075 (org-table-find-dataline)
8076 (let* ((col (max 1 (org-table-current-column)))
8077 (beg (org-table-begin))
8078 (end (org-table-end))
8079 ;; Current cursor position
8080 (linepos (org-current-line))
8081 (colpos col))
8082 (goto-char beg)
8083 (while (< (point) end)
8084 (if (org-at-table-hline-p)
8086 (org-table-goto-column col t)
8087 (insert "| "))
8088 (beginning-of-line 2))
8089 (move-marker end nil)
8090 (goto-line linepos)
8091 (org-table-goto-column colpos)
8092 (org-table-align)
8093 (org-table-fix-formulas "$" nil (1- col) 1)))
8095 (defun org-table-find-dataline ()
8096 "Find a dataline in the current table, which is needed for column commands."
8097 (if (and (org-at-table-p)
8098 (not (org-at-table-hline-p)))
8100 (let ((col (current-column))
8101 (end (org-table-end)))
8102 (move-to-column col)
8103 (while (and (< (point) end)
8104 (or (not (= (current-column) col))
8105 (org-at-table-hline-p)))
8106 (beginning-of-line 2)
8107 (move-to-column col))
8108 (if (and (org-at-table-p)
8109 (not (org-at-table-hline-p)))
8111 (error
8112 "Please position cursor in a data line for column operations")))))
8114 (defun org-table-delete-column ()
8115 "Delete a column from the table."
8116 (interactive)
8117 (if (not (org-at-table-p))
8118 (error "Not at a table"))
8119 (org-table-find-dataline)
8120 (org-table-check-inside-data-field)
8121 (let* ((col (org-table-current-column))
8122 (beg (org-table-begin))
8123 (end (org-table-end))
8124 ;; Current cursor position
8125 (linepos (org-current-line))
8126 (colpos col))
8127 (goto-char beg)
8128 (while (< (point) end)
8129 (if (org-at-table-hline-p)
8131 (org-table-goto-column col t)
8132 (and (looking-at "|[^|\n]+|")
8133 (replace-match "|")))
8134 (beginning-of-line 2))
8135 (move-marker end nil)
8136 (goto-line linepos)
8137 (org-table-goto-column colpos)
8138 (org-table-align)
8139 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8140 col -1 col)))
8142 (defun org-table-move-column-right ()
8143 "Move column to the right."
8144 (interactive)
8145 (org-table-move-column nil))
8146 (defun org-table-move-column-left ()
8147 "Move column to the left."
8148 (interactive)
8149 (org-table-move-column 'left))
8151 (defun org-table-move-column (&optional left)
8152 "Move the current column to the right. With arg LEFT, move to the left."
8153 (interactive "P")
8154 (if (not (org-at-table-p))
8155 (error "Not at a table"))
8156 (org-table-find-dataline)
8157 (org-table-check-inside-data-field)
8158 (let* ((col (org-table-current-column))
8159 (col1 (if left (1- col) col))
8160 (beg (org-table-begin))
8161 (end (org-table-end))
8162 ;; Current cursor position
8163 (linepos (org-current-line))
8164 (colpos (if left (1- col) (1+ col))))
8165 (if (and left (= col 1))
8166 (error "Cannot move column further left"))
8167 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8168 (error "Cannot move column further right"))
8169 (goto-char beg)
8170 (while (< (point) end)
8171 (if (org-at-table-hline-p)
8173 (org-table-goto-column col1 t)
8174 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8175 (replace-match "|\\2|\\1|")))
8176 (beginning-of-line 2))
8177 (move-marker end nil)
8178 (goto-line linepos)
8179 (org-table-goto-column colpos)
8180 (org-table-align)
8181 (org-table-fix-formulas
8182 "$" (list (cons (number-to-string col) (number-to-string colpos))
8183 (cons (number-to-string colpos) (number-to-string col))))))
8185 (defun org-table-move-row-down ()
8186 "Move table row down."
8187 (interactive)
8188 (org-table-move-row nil))
8189 (defun org-table-move-row-up ()
8190 "Move table row up."
8191 (interactive)
8192 (org-table-move-row 'up))
8194 (defun org-table-move-row (&optional up)
8195 "Move the current table line down. With arg UP, move it up."
8196 (interactive "P")
8197 (let* ((col (current-column))
8198 (pos (point))
8199 (hline1p (save-excursion (beginning-of-line 1)
8200 (looking-at org-table-hline-regexp)))
8201 (dline1 (org-table-current-dline))
8202 (dline2 (+ dline1 (if up -1 1)))
8203 (tonew (if up 0 2))
8204 txt hline2p)
8205 (beginning-of-line tonew)
8206 (unless (org-at-table-p)
8207 (goto-char pos)
8208 (error "Cannot move row further"))
8209 (setq hline2p (looking-at org-table-hline-regexp))
8210 (goto-char pos)
8211 (beginning-of-line 1)
8212 (setq pos (point))
8213 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8214 (delete-region (point) (1+ (point-at-eol)))
8215 (beginning-of-line tonew)
8216 (insert txt)
8217 (beginning-of-line 0)
8218 (move-to-column col)
8219 (unless (or hline1p hline2p)
8220 (org-table-fix-formulas
8221 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8222 (cons (number-to-string dline2) (number-to-string dline1)))))))
8224 (defun org-table-insert-row (&optional arg)
8225 "Insert a new row above the current line into the table.
8226 With prefix ARG, insert below the current line."
8227 (interactive "P")
8228 (if (not (org-at-table-p))
8229 (error "Not at a table"))
8230 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8231 (new (org-table-clean-line line)))
8232 ;; Fix the first field if necessary
8233 (if (string-match "^[ \t]*| *[#$] *|" line)
8234 (setq new (replace-match (match-string 0 line) t t new)))
8235 (beginning-of-line (if arg 2 1))
8236 (let (org-table-may-need-update) (insert-before-markers new "\n"))
8237 (beginning-of-line 0)
8238 (re-search-forward "| ?" (point-at-eol) t)
8239 (and (or org-table-may-need-update org-table-overlay-coordinates)
8240 (org-table-align))
8241 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8243 (defun org-table-insert-hline (&optional above)
8244 "Insert a horizontal-line below the current line into the table.
8245 With prefix ABOVE, insert above the current line."
8246 (interactive "P")
8247 (if (not (org-at-table-p))
8248 (error "Not at a table"))
8249 (let ((line (org-table-clean-line
8250 (buffer-substring (point-at-bol) (point-at-eol))))
8251 (col (current-column)))
8252 (while (string-match "|\\( +\\)|" line)
8253 (setq line (replace-match
8254 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8255 ?-) "|") t t line)))
8256 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8257 (beginning-of-line (if above 1 2))
8258 (insert line "\n")
8259 (beginning-of-line (if above 1 -1))
8260 (move-to-column col)
8261 (and org-table-overlay-coordinates (org-table-align))))
8263 (defun org-table-hline-and-move (&optional same-column)
8264 "Insert a hline and move to the row below that line."
8265 (interactive "P")
8266 (let ((col (org-table-current-column)))
8267 (org-table-maybe-eval-formula)
8268 (org-table-maybe-recalculate-line)
8269 (org-table-insert-hline)
8270 (end-of-line 2)
8271 (if (looking-at "\n[ \t]*|-")
8272 (progn (insert "\n|") (org-table-align))
8273 (org-table-next-field))
8274 (if same-column (org-table-goto-column col))))
8276 (defun org-table-clean-line (s)
8277 "Convert a table line S into a string with only \"|\" and space.
8278 In particular, this does handle wide and invisible characters."
8279 (if (string-match "^[ \t]*|-" s)
8280 ;; It's a hline, just map the characters
8281 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
8282 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8283 (setq s (replace-match
8284 (concat "|" (make-string (org-string-width (match-string 1 s))
8285 ?\ ) "|")
8286 t t s)))
8289 (defun org-table-kill-row ()
8290 "Delete the current row or horizontal line from the table."
8291 (interactive)
8292 (if (not (org-at-table-p))
8293 (error "Not at a table"))
8294 (let ((col (current-column))
8295 (dline (org-table-current-dline)))
8296 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8297 (if (not (org-at-table-p)) (beginning-of-line 0))
8298 (move-to-column col)
8299 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
8300 dline -1 dline)))
8303 (defun org-table-sort-lines (with-case &optional sorting-type)
8304 "Sort table lines according to the column at point.
8306 The position of point indicates the column to be used for
8307 sorting, and the range of lines is the range between the nearest
8308 horizontal separator lines, or the entire table of no such lines
8309 exist. If point is before the first column, you will be prompted
8310 for the sorting column. If there is an active region, the mark
8311 specifies the first line and the sorting column, while point
8312 should be in the last line to be included into the sorting.
8314 The command then prompts for the sorting type which can be
8315 alphabetically, numerically, or by time (as given in a time stamp
8316 in the field). Sorting in reverse order is also possible.
8318 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
8320 If SORTING-TYPE is specified when this function is called from a Lisp
8321 program, no prompting will take place. SORTING-TYPE must be a character,
8322 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
8323 should be done in reverse order."
8324 (interactive "P")
8325 (let* ((thisline (org-current-line))
8326 (thiscol (org-table-current-column))
8327 beg end bcol ecol tend tbeg column lns pos)
8328 (when (equal thiscol 0)
8329 (if (interactive-p)
8330 (setq thiscol
8331 (string-to-number
8332 (read-string "Use column N for sorting: ")))
8333 (setq thiscol 1))
8334 (org-table-goto-column thiscol))
8335 (org-table-check-inside-data-field)
8336 (if (org-region-active-p)
8337 (progn
8338 (setq beg (region-beginning) end (region-end))
8339 (goto-char beg)
8340 (setq column (org-table-current-column)
8341 beg (point-at-bol))
8342 (goto-char end)
8343 (setq end (point-at-bol 2)))
8344 (setq column (org-table-current-column)
8345 pos (point)
8346 tbeg (org-table-begin)
8347 tend (org-table-end))
8348 (if (re-search-backward org-table-hline-regexp tbeg t)
8349 (setq beg (point-at-bol 2))
8350 (goto-char tbeg)
8351 (setq beg (point-at-bol 1)))
8352 (goto-char pos)
8353 (if (re-search-forward org-table-hline-regexp tend t)
8354 (setq end (point-at-bol 1))
8355 (goto-char tend)
8356 (setq end (point-at-bol))))
8357 (setq beg (move-marker (make-marker) beg)
8358 end (move-marker (make-marker) end))
8359 (untabify beg end)
8360 (goto-char beg)
8361 (org-table-goto-column column)
8362 (skip-chars-backward "^|")
8363 (setq bcol (current-column))
8364 (org-table-goto-column (1+ column))
8365 (skip-chars-backward "^|")
8366 (setq ecol (1- (current-column)))
8367 (org-table-goto-column column)
8368 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8369 (org-split-string (buffer-substring beg end) "\n")))
8370 (setq lns (org-do-sort lns "Table" with-case sorting-type))
8371 (delete-region beg end)
8372 (move-marker beg nil)
8373 (move-marker end nil)
8374 (insert (mapconcat 'cdr lns "\n") "\n")
8375 (goto-line thisline)
8376 (org-table-goto-column thiscol)
8377 (message "%d lines sorted, based on column %d" (length lns) column)))
8379 (defun org-table-cut-region (beg end)
8380 "Copy region in table to the clipboard and blank all relevant fields."
8381 (interactive "r")
8382 (org-table-copy-region beg end 'cut))
8384 (defun org-table-copy-region (beg end &optional cut)
8385 "Copy rectangular region in table to clipboard.
8386 A special clipboard is used which can only be accessed
8387 with `org-table-paste-rectangle'."
8388 (interactive "rP")
8389 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8390 region cols
8391 (rpl (if cut " " nil)))
8392 (goto-char beg)
8393 (org-table-check-inside-data-field)
8394 (setq l01 (org-current-line)
8395 c01 (org-table-current-column))
8396 (goto-char end)
8397 (org-table-check-inside-data-field)
8398 (setq l02 (org-current-line)
8399 c02 (org-table-current-column))
8400 (setq l1 (min l01 l02) l2 (max l01 l02)
8401 c1 (min c01 c02) c2 (max c01 c02))
8402 (catch 'exit
8403 (while t
8404 (catch 'nextline
8405 (if (> l1 l2) (throw 'exit t))
8406 (goto-line l1)
8407 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8408 (setq cols nil ic1 c1 ic2 c2)
8409 (while (< ic1 (1+ ic2))
8410 (push (org-table-get-field ic1 rpl) cols)
8411 (setq ic1 (1+ ic1)))
8412 (push (nreverse cols) region)
8413 (setq l1 (1+ l1)))))
8414 (setq org-table-clip (nreverse region))
8415 (if cut (org-table-align))
8416 org-table-clip))
8418 (defun org-table-paste-rectangle ()
8419 "Paste a rectangular region into a table.
8420 The upper right corner ends up in the current field. All involved fields
8421 will be overwritten. If the rectangle does not fit into the present table,
8422 the table is enlarged as needed. The process ignores horizontal separator
8423 lines."
8424 (interactive)
8425 (unless (and org-table-clip (listp org-table-clip))
8426 (error "First cut/copy a region to paste!"))
8427 (org-table-check-inside-data-field)
8428 (let* ((clip org-table-clip)
8429 (line (org-current-line))
8430 (col (org-table-current-column))
8431 (org-enable-table-editor t)
8432 (org-table-automatic-realign nil)
8433 c cols field)
8434 (while (setq cols (pop clip))
8435 (while (org-at-table-hline-p) (beginning-of-line 2))
8436 (if (not (org-at-table-p))
8437 (progn (end-of-line 0) (org-table-next-field)))
8438 (setq c col)
8439 (while (setq field (pop cols))
8440 (org-table-goto-column c nil 'force)
8441 (org-table-get-field nil field)
8442 (setq c (1+ c)))
8443 (beginning-of-line 2))
8444 (goto-line line)
8445 (org-table-goto-column col)
8446 (org-table-align)))
8448 (defun org-table-convert ()
8449 "Convert from `org-mode' table to table.el and back.
8450 Obviously, this only works within limits. When an Org-mode table is
8451 converted to table.el, all horizontal separator lines get lost, because
8452 table.el uses these as cell boundaries and has no notion of horizontal lines.
8453 A table.el table can be converted to an Org-mode table only if it does not
8454 do row or column spanning. Multiline cells will become multiple cells.
8455 Beware, Org-mode does not test if the table can be successfully converted - it
8456 blindly applies a recipe that works for simple tables."
8457 (interactive)
8458 (require 'table)
8459 (if (org-at-table.el-p)
8460 ;; convert to Org-mode table
8461 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8462 (end (move-marker (make-marker) (org-table-end t))))
8463 (table-unrecognize-region beg end)
8464 (goto-char beg)
8465 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8466 (replace-match ""))
8467 (goto-char beg))
8468 (if (org-at-table-p)
8469 ;; convert to table.el table
8470 (let ((beg (move-marker (make-marker) (org-table-begin)))
8471 (end (move-marker (make-marker) (org-table-end))))
8472 ;; first, get rid of all horizontal lines
8473 (goto-char beg)
8474 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8475 (replace-match ""))
8476 ;; insert a hline before first
8477 (goto-char beg)
8478 (org-table-insert-hline 'above)
8479 (beginning-of-line -1)
8480 ;; insert a hline after each line
8481 (while (progn (beginning-of-line 3) (< (point) end))
8482 (org-table-insert-hline))
8483 (goto-char beg)
8484 (setq end (move-marker end (org-table-end)))
8485 ;; replace "+" at beginning and ending of hlines
8486 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8487 (replace-match "\\1+-"))
8488 (goto-char beg)
8489 (while (re-search-forward "-|[ \t]*$" end t)
8490 (replace-match "-+"))
8491 (goto-char beg)))))
8493 (defun org-table-wrap-region (arg)
8494 "Wrap several fields in a column like a paragraph.
8495 This is useful if you'd like to spread the contents of a field over several
8496 lines, in order to keep the table compact.
8498 If there is an active region, and both point and mark are in the same column,
8499 the text in the column is wrapped to minimum width for the given number of
8500 lines. Generally, this makes the table more compact. A prefix ARG may be
8501 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8502 formats the selected text to two lines. If the region was longer than two
8503 lines, the remaining lines remain empty. A negative prefix argument reduces
8504 the current number of lines by that amount. The wrapped text is pasted back
8505 into the table. If you formatted it to more lines than it was before, fields
8506 further down in the table get overwritten - so you might need to make space in
8507 the table first.
8509 If there is no region, the current field is split at the cursor position and
8510 the text fragment to the right of the cursor is prepended to the field one
8511 line down.
8513 If there is no region, but you specify a prefix ARG, the current field gets
8514 blank, and the content is appended to the field above."
8515 (interactive "P")
8516 (org-table-check-inside-data-field)
8517 (if (org-region-active-p)
8518 ;; There is a region: fill as a paragraph
8519 (let* ((beg (region-beginning))
8520 (cline (save-excursion (goto-char beg) (org-current-line)))
8521 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
8522 nlines)
8523 (org-table-cut-region (region-beginning) (region-end))
8524 (if (> (length (car org-table-clip)) 1)
8525 (error "Region must be limited to single column"))
8526 (setq nlines (if arg
8527 (if (< arg 1)
8528 (+ (length org-table-clip) arg)
8529 arg)
8530 (length org-table-clip)))
8531 (setq org-table-clip
8532 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8533 nil nlines)))
8534 (goto-line cline)
8535 (org-table-goto-column ccol)
8536 (org-table-paste-rectangle))
8537 ;; No region, split the current field at point
8538 (if arg
8539 ;; combine with field above
8540 (let ((s (org-table-blank-field))
8541 (col (org-table-current-column)))
8542 (beginning-of-line 0)
8543 (while (org-at-table-hline-p) (beginning-of-line 0))
8544 (org-table-goto-column col)
8545 (skip-chars-forward "^|")
8546 (skip-chars-backward " ")
8547 (insert " " (org-trim s))
8548 (org-table-align))
8549 ;; split field
8550 (when (looking-at "\\([^|]+\\)+|")
8551 (let ((s (match-string 1)))
8552 (replace-match " |")
8553 (goto-char (match-beginning 0))
8554 (org-table-next-row)
8555 (insert (org-trim s) " ")
8556 (org-table-align))))))
8558 (defvar org-field-marker nil)
8560 (defun org-table-edit-field (arg)
8561 "Edit table field in a different window.
8562 This is mainly useful for fields that contain hidden parts.
8563 When called with a \\[universal-argument] prefix, just make the full field visible so that
8564 it can be edited in place."
8565 (interactive "P")
8566 (if arg
8567 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
8568 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
8569 (remove-text-properties b e '(org-cwidth t invisible t
8570 display t intangible t))
8571 (if (and (boundp 'font-lock-mode) font-lock-mode)
8572 (font-lock-fontify-block)))
8573 (let ((pos (move-marker (make-marker) (point)))
8574 (field (org-table-get-field))
8575 (cw (current-window-configuration))
8577 (org-switch-to-buffer-other-window "*Org tmp*")
8578 (erase-buffer)
8579 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
8580 (let ((org-inhibit-startup t)) (org-mode))
8581 (goto-char (setq p (point-max)))
8582 (insert (org-trim field))
8583 (remove-text-properties p (point-max)
8584 '(invisible t org-cwidth t display t
8585 intangible t))
8586 (goto-char p)
8587 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
8588 (org-set-local 'org-window-configuration cw)
8589 (org-set-local 'org-field-marker pos)
8590 (message "Edit and finish with C-c C-c"))))
8592 (defun org-table-finish-edit-field ()
8593 "Finish editing a table data field.
8594 Remove all newline characters, insert the result into the table, realign
8595 the table and kill the editing buffer."
8596 (let ((pos org-field-marker)
8597 (cw org-window-configuration)
8598 (cb (current-buffer))
8599 text)
8600 (goto-char (point-min))
8601 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
8602 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
8603 (replace-match " "))
8604 (setq text (org-trim (buffer-string)))
8605 (set-window-configuration cw)
8606 (kill-buffer cb)
8607 (select-window (get-buffer-window (marker-buffer pos)))
8608 (goto-char pos)
8609 (move-marker pos nil)
8610 (org-table-check-inside-data-field)
8611 (org-table-get-field nil text)
8612 (org-table-align)
8613 (message "New field value inserted")))
8615 (defun org-trim (s)
8616 "Remove whitespace at beginning and end of string."
8617 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
8618 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
8621 (defun org-wrap (string &optional width lines)
8622 "Wrap string to either a number of lines, or a width in characters.
8623 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8624 that costs. If there is a word longer than WIDTH, the text is actually
8625 wrapped to the length of that word.
8626 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8627 many lines, whatever width that takes.
8628 The return value is a list of lines, without newlines at the end."
8629 (let* ((words (org-split-string string "[ \t\n]+"))
8630 (maxword (apply 'max (mapcar 'org-string-width words)))
8631 w ll)
8632 (cond (width
8633 (org-do-wrap words (max maxword width)))
8634 (lines
8635 (setq w maxword)
8636 (setq ll (org-do-wrap words maxword))
8637 (if (<= (length ll) lines)
8639 (setq ll words)
8640 (while (> (length ll) lines)
8641 (setq w (1+ w))
8642 (setq ll (org-do-wrap words w)))
8643 ll))
8644 (t (error "Cannot wrap this")))))
8647 (defun org-do-wrap (words width)
8648 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8649 (let (lines line)
8650 (while words
8651 (setq line (pop words))
8652 (while (and words (< (+ (length line) (length (car words))) width))
8653 (setq line (concat line " " (pop words))))
8654 (setq lines (push line lines)))
8655 (nreverse lines)))
8657 (defun org-split-string (string &optional separators)
8658 "Splits STRING into substrings at SEPARATORS.
8659 No empty strings are returned if there are matches at the beginning
8660 and end of string."
8661 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8662 (start 0)
8663 notfirst
8664 (list nil))
8665 (while (and (string-match rexp string
8666 (if (and notfirst
8667 (= start (match-beginning 0))
8668 (< start (length string)))
8669 (1+ start) start))
8670 (< (match-beginning 0) (length string)))
8671 (setq notfirst t)
8672 (or (eq (match-beginning 0) 0)
8673 (and (eq (match-beginning 0) (match-end 0))
8674 (eq (match-beginning 0) start))
8675 (setq list
8676 (cons (substring string start (match-beginning 0))
8677 list)))
8678 (setq start (match-end 0)))
8679 (or (eq start (length string))
8680 (setq list
8681 (cons (substring string start)
8682 list)))
8683 (nreverse list)))
8685 (defun org-table-map-tables (function)
8686 "Apply FUNCTION to the start of all tables in the buffer."
8687 (save-excursion
8688 (save-restriction
8689 (widen)
8690 (goto-char (point-min))
8691 (while (re-search-forward org-table-any-line-regexp nil t)
8692 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8693 (beginning-of-line 1)
8694 (if (looking-at org-table-line-regexp)
8695 (save-excursion (funcall function)))
8696 (re-search-forward org-table-any-border-regexp nil 1))))
8697 (message "Mapping tables: done"))
8699 (defvar org-timecnt) ; dynamically scoped parameter
8701 (defun org-table-sum (&optional beg end nlast)
8702 "Sum numbers in region of current table column.
8703 The result will be displayed in the echo area, and will be available
8704 as kill to be inserted with \\[yank].
8706 If there is an active region, it is interpreted as a rectangle and all
8707 numbers in that rectangle will be summed. If there is no active
8708 region and point is located in a table column, sum all numbers in that
8709 column.
8711 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8712 numbers are assumed to be times as well (in decimal hours) and the
8713 numbers are added as such.
8715 If NLAST is a number, only the NLAST fields will actually be summed."
8716 (interactive)
8717 (save-excursion
8718 (let (col (org-timecnt 0) diff h m s org-table-clip)
8719 (cond
8720 ((and beg end)) ; beg and end given explicitly
8721 ((org-region-active-p)
8722 (setq beg (region-beginning) end (region-end)))
8724 (setq col (org-table-current-column))
8725 (goto-char (org-table-begin))
8726 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8727 (error "No table data"))
8728 (org-table-goto-column col)
8729 (setq beg (point))
8730 (goto-char (org-table-end))
8731 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8732 (error "No table data"))
8733 (org-table-goto-column col)
8734 (setq end (point))))
8735 (let* ((items (apply 'append (org-table-copy-region beg end)))
8736 (items1 (cond ((not nlast) items)
8737 ((>= nlast (length items)) items)
8738 (t (setq items (reverse items))
8739 (setcdr (nthcdr (1- nlast) items) nil)
8740 (nreverse items))))
8741 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8742 items1)))
8743 (res (apply '+ numbers))
8744 (sres (if (= org-timecnt 0)
8745 (format "%g" res)
8746 (setq diff (* 3600 res)
8747 h (floor (/ diff 3600)) diff (mod diff 3600)
8748 m (floor (/ diff 60)) diff (mod diff 60)
8749 s diff)
8750 (format "%d:%02d:%02d" h m s))))
8751 (kill-new sres)
8752 (if (interactive-p)
8753 (message "%s"
8754 (substitute-command-keys
8755 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8756 (length numbers) sres))))
8757 sres))))
8759 (defun org-table-get-number-for-summing (s)
8760 (let (n)
8761 (if (string-match "^ *|? *" s)
8762 (setq s (replace-match "" nil nil s)))
8763 (if (string-match " *|? *$" s)
8764 (setq s (replace-match "" nil nil s)))
8765 (setq n (string-to-number s))
8766 (cond
8767 ((and (string-match "0" s)
8768 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8769 ((string-match "\\`[ \t]+\\'" s) nil)
8770 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8771 (let ((h (string-to-number (or (match-string 1 s) "0")))
8772 (m (string-to-number (or (match-string 2 s) "0")))
8773 (s (string-to-number (or (match-string 4 s) "0"))))
8774 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
8775 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8776 ((equal n 0) nil)
8777 (t n))))
8779 (defun org-table-current-field-formula (&optional key noerror)
8780 "Return the formula active for the current field.
8781 Assumes that specials are in place.
8782 If KEY is given, return the key to this formula.
8783 Otherwise return the formula preceeded with \"=\" or \":=\"."
8784 (let* ((name (car (rassoc (list (org-current-line)
8785 (org-table-current-column))
8786 org-table-named-field-locations)))
8787 (col (org-table-current-column))
8788 (scol (int-to-string col))
8789 (ref (format "@%d$%d" (org-table-current-dline) col))
8790 (stored-list (org-table-get-stored-formulas noerror))
8791 (ass (or (assoc name stored-list)
8792 (assoc ref stored-list)
8793 (assoc scol stored-list))))
8794 (if key
8795 (car ass)
8796 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
8797 (cdr ass))))))
8799 (defun org-table-get-formula (&optional equation named)
8800 "Read a formula from the minibuffer, offer stored formula as default.
8801 When NAMED is non-nil, look for a named equation."
8802 (let* ((stored-list (org-table-get-stored-formulas))
8803 (name (car (rassoc (list (org-current-line)
8804 (org-table-current-column))
8805 org-table-named-field-locations)))
8806 (ref (format "@%d$%d" (org-table-current-dline)
8807 (org-table-current-column)))
8808 (refass (assoc ref stored-list))
8809 (scol (if named
8810 (if name name ref)
8811 (int-to-string (org-table-current-column))))
8812 (dummy (and (or name refass) (not named)
8813 (not (y-or-n-p "Replace field formula with column formula? " ))
8814 (error "Abort")))
8815 (name (or name ref))
8816 (org-table-may-need-update nil)
8817 (stored (cdr (assoc scol stored-list)))
8818 (eq (cond
8819 ((and stored equation (string-match "^ *=? *$" equation))
8820 stored)
8821 ((stringp equation)
8822 equation)
8823 (t (org-table-formula-from-user
8824 (read-string
8825 (org-table-formula-to-user
8826 (format "%s formula %s%s="
8827 (if named "Field" "Column")
8828 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
8829 scol))
8830 (if stored (org-table-formula-to-user stored) "")
8831 'org-table-formula-history
8832 )))))
8833 mustsave)
8834 (when (not (string-match "\\S-" eq))
8835 ;; remove formula
8836 (setq stored-list (delq (assoc scol stored-list) stored-list))
8837 (org-table-store-formulas stored-list)
8838 (error "Formula removed"))
8839 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8840 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8841 (if (and name (not named))
8842 ;; We set the column equation, delete the named one.
8843 (setq stored-list (delq (assoc name stored-list) stored-list)
8844 mustsave t))
8845 (if stored
8846 (setcdr (assoc scol stored-list) eq)
8847 (setq stored-list (cons (cons scol eq) stored-list)))
8848 (if (or mustsave (not (equal stored eq)))
8849 (org-table-store-formulas stored-list))
8850 eq))
8852 (defun org-table-store-formulas (alist)
8853 "Store the list of formulas below the current table."
8854 (setq alist (sort alist 'org-table-formula-less-p))
8855 (save-excursion
8856 (goto-char (org-table-end))
8857 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
8858 (progn
8859 ;; don't overwrite TBLFM, we might use text properties to store stuff
8860 (goto-char (match-beginning 2))
8861 (delete-region (match-beginning 2) (match-end 0)))
8862 (insert "#+TBLFM:"))
8863 (insert " "
8864 (mapconcat (lambda (x)
8865 (concat
8866 (if (equal (string-to-char (car x)) ?@) "" "$")
8867 (car x) "=" (cdr x)))
8868 alist "::")
8869 "\n")))
8871 (defsubst org-table-formula-make-cmp-string (a)
8872 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
8873 (concat
8874 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
8875 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
8876 (if (match-end 5) (concat "@@" (match-string 5 a))))))
8878 (defun org-table-formula-less-p (a b)
8879 "Compare two formulas for sorting."
8880 (let ((as (org-table-formula-make-cmp-string (car a)))
8881 (bs (org-table-formula-make-cmp-string (car b))))
8882 (and as bs (string< as bs))))
8884 (defun org-table-get-stored-formulas (&optional noerror)
8885 "Return an alist with the stored formulas directly after current table."
8886 (interactive)
8887 (let (scol eq eq-alist strings string seen)
8888 (save-excursion
8889 (goto-char (org-table-end))
8890 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8891 (setq strings (org-split-string (match-string 2) " *:: *"))
8892 (while (setq string (pop strings))
8893 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
8894 (setq scol (if (match-end 2)
8895 (match-string 2 string)
8896 (match-string 1 string))
8897 eq (match-string 3 string)
8898 eq-alist (cons (cons scol eq) eq-alist))
8899 (if (member scol seen)
8900 (if noerror
8901 (progn
8902 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8903 (ding)
8904 (sit-for 2))
8905 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
8906 (push scol seen))))))
8907 (nreverse eq-alist)))
8909 (defun org-table-fix-formulas (key replace &optional limit delta remove)
8910 "Modify the equations after the table structure has been edited.
8911 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
8912 For all numbers larger than LIMIT, shift them by DELTA."
8913 (save-excursion
8914 (goto-char (org-table-end))
8915 (when (looking-at "#\\+TBLFM:")
8916 (let ((re (concat key "\\([0-9]+\\)"))
8917 (re2
8918 (when remove
8919 (if (equal key "$")
8920 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
8921 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
8922 s n a)
8923 (when remove
8924 (while (re-search-forward re2 (point-at-eol) t)
8925 (replace-match "")))
8926 (while (re-search-forward re (point-at-eol) t)
8927 (setq s (match-string 1) n (string-to-number s))
8928 (cond
8929 ((setq a (assoc s replace))
8930 (replace-match (concat key (cdr a)) t t))
8931 ((and limit (> n limit))
8932 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
8934 (defun org-table-get-specials ()
8935 "Get the column names and local parameters for this table."
8936 (save-excursion
8937 (let ((beg (org-table-begin)) (end (org-table-end))
8938 names name fields fields1 field cnt
8939 c v l line col types dlines hlines)
8940 (setq org-table-column-names nil
8941 org-table-local-parameters nil
8942 org-table-named-field-locations nil
8943 org-table-current-begin-line nil
8944 org-table-current-begin-pos nil
8945 org-table-current-line-types nil)
8946 (goto-char beg)
8947 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8948 (setq names (org-split-string (match-string 1) " *| *")
8949 cnt 1)
8950 (while (setq name (pop names))
8951 (setq cnt (1+ cnt))
8952 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8953 (push (cons name (int-to-string cnt)) org-table-column-names))))
8954 (setq org-table-column-names (nreverse org-table-column-names))
8955 (setq org-table-column-name-regexp
8956 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8957 (goto-char beg)
8958 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8959 (setq fields (org-split-string (match-string 1) " *| *"))
8960 (while (setq field (pop fields))
8961 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8962 (push (cons (match-string 1 field) (match-string 2 field))
8963 org-table-local-parameters))))
8964 (goto-char beg)
8965 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8966 (setq c (match-string 1)
8967 fields (org-split-string (match-string 2) " *| *"))
8968 (save-excursion
8969 (beginning-of-line (if (equal c "_") 2 0))
8970 (setq line (org-current-line) col 1)
8971 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8972 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8973 (while (and fields1 (setq field (pop fields)))
8974 (setq v (pop fields1) col (1+ col))
8975 (when (and (stringp field) (stringp v)
8976 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8977 (push (cons field v) org-table-local-parameters)
8978 (push (list field line col) org-table-named-field-locations))))
8979 ;; Analyse the line types
8980 (goto-char beg)
8981 (setq org-table-current-begin-line (org-current-line)
8982 org-table-current-begin-pos (point)
8983 l org-table-current-begin-line)
8984 (while (looking-at "[ \t]*|\\(-\\)?")
8985 (push (if (match-end 1) 'hline 'dline) types)
8986 (if (match-end 1) (push l hlines) (push l dlines))
8987 (beginning-of-line 2)
8988 (setq l (1+ l)))
8989 (setq org-table-current-line-types (apply 'vector (nreverse types))
8990 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
8991 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
8993 (defun org-table-maybe-eval-formula ()
8994 "Check if the current field starts with \"=\" or \":=\".
8995 If yes, store the formula and apply it."
8996 ;; We already know we are in a table. Get field will only return a formula
8997 ;; when appropriate. It might return a separator line, but no problem.
8998 (when org-table-formula-evaluate-inline
8999 (let* ((field (org-trim (or (org-table-get-field) "")))
9000 named eq)
9001 (when (string-match "^:?=\\(.*\\)" field)
9002 (setq named (equal (string-to-char field) ?:)
9003 eq (match-string 1 field))
9004 (if (or (fboundp 'calc-eval)
9005 (equal (substring eq 0 (min 2 (length eq))) "'("))
9006 (org-table-eval-formula (if named '(4) nil)
9007 (org-table-formula-from-user eq))
9008 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9010 (defvar org-recalc-commands nil
9011 "List of commands triggering the recalculation of a line.
9012 Will be filled automatically during use.")
9014 (defvar org-recalc-marks
9015 '((" " . "Unmarked: no special line, no automatic recalculation")
9016 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9017 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9018 ("!" . "Column name definition line. Reference in formula as $name.")
9019 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9020 ("_" . "Names for values in row below this one.")
9021 ("^" . "Names for values in row above this one.")))
9023 (defun org-table-rotate-recalc-marks (&optional newchar)
9024 "Rotate the recalculation mark in the first column.
9025 If in any row, the first field is not consistent with a mark,
9026 insert a new column for the markers.
9027 When there is an active region, change all the lines in the region,
9028 after prompting for the marking character.
9029 After each change, a message will be displayed indicating the meaning
9030 of the new mark."
9031 (interactive)
9032 (unless (org-at-table-p) (error "Not at a table"))
9033 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9034 (beg (org-table-begin))
9035 (end (org-table-end))
9036 (l (org-current-line))
9037 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9038 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9039 (have-col
9040 (save-excursion
9041 (goto-char beg)
9042 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9043 (col (org-table-current-column))
9044 (forcenew (car (assoc newchar org-recalc-marks)))
9045 epos new)
9046 (when l1
9047 (message "Change region to what mark? Type # * ! $ or SPC: ")
9048 (setq newchar (char-to-string (read-char-exclusive))
9049 forcenew (car (assoc newchar org-recalc-marks))))
9050 (if (and newchar (not forcenew))
9051 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9052 newchar))
9053 (if l1 (goto-line l1))
9054 (save-excursion
9055 (beginning-of-line 1)
9056 (unless (looking-at org-table-dataline-regexp)
9057 (error "Not at a table data line")))
9058 (unless have-col
9059 (org-table-goto-column 1)
9060 (org-table-insert-column)
9061 (org-table-goto-column (1+ col)))
9062 (setq epos (point-at-eol))
9063 (save-excursion
9064 (beginning-of-line 1)
9065 (org-table-get-field
9066 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9067 (concat " "
9068 (setq new (or forcenew
9069 (cadr (member (match-string 1) marks))))
9070 " ")
9071 " # ")))
9072 (if (and l1 l2)
9073 (progn
9074 (goto-line l1)
9075 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9076 (and (looking-at org-table-dataline-regexp)
9077 (org-table-get-field 1 (concat " " new " "))))
9078 (goto-line l1)))
9079 (if (not (= epos (point-at-eol))) (org-table-align))
9080 (goto-line l)
9081 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9083 (defun org-table-maybe-recalculate-line ()
9084 "Recompute the current line if marked for it, and if we haven't just done it."
9085 (interactive)
9086 (and org-table-allow-automatic-line-recalculation
9087 (not (and (memq last-command org-recalc-commands)
9088 (equal org-last-recalc-line (org-current-line))))
9089 (save-excursion (beginning-of-line 1)
9090 (looking-at org-table-auto-recalculate-regexp))
9091 (org-table-recalculate) t))
9093 (defvar org-table-formula-debug nil
9094 "Non-nil means, debug table formulas.
9095 When nil, simply write \"#ERROR\" in corrupted fields.")
9096 (make-variable-buffer-local 'org-table-formula-debug)
9098 (defvar modes)
9099 (defsubst org-set-calc-mode (var &optional value)
9100 (if (stringp var)
9101 (setq var (assoc var '(("D" calc-angle-mode deg)
9102 ("R" calc-angle-mode rad)
9103 ("F" calc-prefer-frac t)
9104 ("S" calc-symbolic-mode t)))
9105 value (nth 2 var) var (nth 1 var)))
9106 (if (memq var modes)
9107 (setcar (cdr (memq var modes)) value)
9108 (cons var (cons value modes)))
9109 modes)
9111 (defun org-table-eval-formula (&optional arg equation
9112 suppress-align suppress-const
9113 suppress-store suppress-analysis)
9114 "Replace the table field value at the cursor by the result of a calculation.
9116 This function makes use of Dave Gillespie's Calc package, in my view the
9117 most exciting program ever written for GNU Emacs. So you need to have Calc
9118 installed in order to use this function.
9120 In a table, this command replaces the value in the current field with the
9121 result of a formula. It also installs the formula as the \"current\" column
9122 formula, by storing it in a special line below the table. When called
9123 with a `C-u' prefix, the current field must ba a named field, and the
9124 formula is installed as valid in only this specific field.
9126 When called with two `C-u' prefixes, insert the active equation
9127 for the field back into the current field, so that it can be
9128 edited there. This is useful in order to use \\[org-table-show-reference]
9129 to check the referenced fields.
9131 When called, the command first prompts for a formula, which is read in
9132 the minibuffer. Previously entered formulas are available through the
9133 history list, and the last used formula is offered as a default.
9134 These stored formulas are adapted correctly when moving, inserting, or
9135 deleting columns with the corresponding commands.
9137 The formula can be any algebraic expression understood by the Calc package.
9138 For details, see the Org-mode manual.
9140 This function can also be called from Lisp programs and offers
9141 additional arguments: EQUATION can be the formula to apply. If this
9142 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9143 used to speed-up recursive calls by by-passing unnecessary aligns.
9144 SUPPRESS-CONST suppresses the interpretation of constants in the
9145 formula, assuming that this has been done already outside the function.
9146 SUPPRESS-STORE means the formula should not be stored, either because
9147 it is already stored, or because it is a modified equation that should
9148 not overwrite the stored one."
9149 (interactive "P")
9150 (org-table-check-inside-data-field)
9151 (or suppress-analysis (org-table-get-specials))
9152 (if (equal arg '(16))
9153 (let ((eq (org-table-current-field-formula)))
9154 (or eq (error "No equation active for current field"))
9155 (org-table-get-field nil eq)
9156 (org-table-align)
9157 (setq org-table-may-need-update t))
9158 (let* (fields
9159 (ndown (if (integerp arg) arg 1))
9160 (org-table-automatic-realign nil)
9161 (case-fold-search nil)
9162 (down (> ndown 1))
9163 (formula (if (and equation suppress-store)
9164 equation
9165 (org-table-get-formula equation (equal arg '(4)))))
9166 (n0 (org-table-current-column))
9167 (modes (copy-sequence org-calc-default-modes))
9168 (numbers nil) ; was a variable, now fixed default
9169 (keep-empty nil)
9170 n form form0 bw fmt x ev orig c lispp literal)
9171 ;; Parse the format string. Since we have a lot of modes, this is
9172 ;; a lot of work. However, I think calc still uses most of the time.
9173 (if (string-match ";" formula)
9174 (let ((tmp (org-split-string formula ";")))
9175 (setq formula (car tmp)
9176 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9177 (nth 1 tmp)))
9178 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9179 (setq c (string-to-char (match-string 1 fmt))
9180 n (string-to-number (match-string 2 fmt)))
9181 (if (= c ?p)
9182 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9183 (setq modes (org-set-calc-mode
9184 'calc-float-format
9185 (list (cdr (assoc c '((?n . float) (?f . fix)
9186 (?s . sci) (?e . eng))))
9187 n))))
9188 (setq fmt (replace-match "" t t fmt)))
9189 (if (string-match "[NT]" fmt)
9190 (setq numbers (equal (match-string 0 fmt) "N")
9191 fmt (replace-match "" t t fmt)))
9192 (if (string-match "L" fmt)
9193 (setq literal t
9194 fmt (replace-match "" t t fmt)))
9195 (if (string-match "E" fmt)
9196 (setq keep-empty t
9197 fmt (replace-match "" t t fmt)))
9198 (while (string-match "[DRFS]" fmt)
9199 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9200 (setq fmt (replace-match "" t t fmt)))
9201 (unless (string-match "\\S-" fmt)
9202 (setq fmt nil))))
9203 (if (and (not suppress-const) org-table-formula-use-constants)
9204 (setq formula (org-table-formula-substitute-names formula)))
9205 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9206 (while (> ndown 0)
9207 (setq fields (org-split-string
9208 (org-no-properties
9209 (buffer-substring (point-at-bol) (point-at-eol)))
9210 " *| *"))
9211 (if (eq numbers t)
9212 (setq fields (mapcar
9213 (lambda (x) (number-to-string (string-to-number x)))
9214 fields)))
9215 (setq ndown (1- ndown))
9216 (setq form (copy-sequence formula)
9217 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9218 (if (and lispp literal) (setq lispp 'literal))
9219 ;; Check for old vertical references
9220 (setq form (org-rewrite-old-row-references form))
9221 ;; Insert complex ranges
9222 (while (string-match org-table-range-regexp form)
9223 (setq form
9224 (replace-match
9225 (save-match-data
9226 (org-table-make-reference
9227 (org-table-get-range (match-string 0 form) nil n0)
9228 keep-empty numbers lispp))
9229 t t form)))
9230 ;; Insert simple ranges
9231 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
9232 (setq form
9233 (replace-match
9234 (save-match-data
9235 (org-table-make-reference
9236 (org-sublist
9237 fields (string-to-number (match-string 1 form))
9238 (string-to-number (match-string 2 form)))
9239 keep-empty numbers lispp))
9240 t t form)))
9241 (setq form0 form)
9242 ;; Insert the references to fields in same row
9243 (while (string-match "\\$\\([0-9]+\\)" form)
9244 (setq n (string-to-number (match-string 1 form))
9245 x (nth (1- (if (= n 0) n0 n)) fields))
9246 (unless x (error "Invalid field specifier \"%s\""
9247 (match-string 0 form)))
9248 (setq form (replace-match
9249 (save-match-data
9250 (org-table-make-reference x nil numbers lispp))
9251 t t form)))
9253 (if lispp
9254 (setq ev (condition-case nil
9255 (eval (eval (read form)))
9256 (error "#ERROR"))
9257 ev (if (numberp ev) (number-to-string ev) ev))
9258 (or (fboundp 'calc-eval)
9259 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
9260 (setq ev (calc-eval (cons form modes)
9261 (if numbers 'num))))
9263 (when org-table-formula-debug
9264 (with-output-to-temp-buffer "*Substitution History*"
9265 (princ (format "Substitution history of formula
9266 Orig: %s
9267 $xyz-> %s
9268 @r$c-> %s
9269 $1-> %s\n" orig formula form0 form))
9270 (if (listp ev)
9271 (princ (format " %s^\nError: %s"
9272 (make-string (car ev) ?\-) (nth 1 ev)))
9273 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9274 ev (or fmt "NONE")
9275 (if fmt (format fmt (string-to-number ev)) ev)))))
9276 (setq bw (get-buffer-window "*Substitution History*"))
9277 (shrink-window-if-larger-than-buffer bw)
9278 (unless (and (interactive-p) (not ndown))
9279 (unless (let (inhibit-redisplay)
9280 (y-or-n-p "Debugging Formula. Continue to next? "))
9281 (org-table-align)
9282 (error "Abort"))
9283 (delete-window bw)
9284 (message "")))
9285 (if (listp ev) (setq fmt nil ev "#ERROR"))
9286 (org-table-justify-field-maybe
9287 (if fmt (format fmt (string-to-number ev)) ev))
9288 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9289 (call-interactively 'org-return)
9290 (setq ndown 0)))
9291 (and down (org-table-maybe-recalculate-line))
9292 (or suppress-align (and org-table-may-need-update
9293 (org-table-align))))))
9295 (defun org-table-put-field-property (prop value)
9296 (save-excursion
9297 (put-text-property (progn (skip-chars-backward "^|") (point))
9298 (progn (skip-chars-forward "^|") (point))
9299 prop value)))
9301 (defun org-table-get-range (desc &optional tbeg col highlight)
9302 "Get a calc vector from a column, accorting to descriptor DESC.
9303 Optional arguments TBEG and COL can give the beginning of the table and
9304 the current column, to avoid unnecessary parsing.
9305 HIGHLIGHT means, just highlight the range."
9306 (if (not (equal (string-to-char desc) ?@))
9307 (setq desc (concat "@" desc)))
9308 (save-excursion
9309 (or tbeg (setq tbeg (org-table-begin)))
9310 (or col (setq col (org-table-current-column)))
9311 (let ((thisline (org-current-line))
9312 beg end c1 c2 r1 r2 rangep tmp)
9313 (unless (string-match org-table-range-regexp desc)
9314 (error "Invalid table range specifier `%s'" desc))
9315 (setq rangep (match-end 3)
9316 r1 (and (match-end 1) (match-string 1 desc))
9317 r2 (and (match-end 4) (match-string 4 desc))
9318 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
9319 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
9321 (and c1 (setq c1 (+ (string-to-number c1)
9322 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
9323 (and c2 (setq c2 (+ (string-to-number c2)
9324 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
9325 (if (equal r1 "") (setq r1 nil))
9326 (if (equal r2 "") (setq r2 nil))
9327 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
9328 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
9329 ; (setq r2 (or r2 r1) c2 (or c2 c1))
9330 (if (not r1) (setq r1 thisline))
9331 (if (not r2) (setq r2 thisline))
9332 (if (not c1) (setq c1 col))
9333 (if (not c2) (setq c2 col))
9334 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
9335 ;; just one field
9336 (progn
9337 (goto-line r1)
9338 (while (not (looking-at org-table-dataline-regexp))
9339 (beginning-of-line 2))
9340 (prog1 (org-trim (org-table-get-field c1))
9341 (if highlight (org-table-highlight-rectangle (point) (point)))))
9342 ;; A range, return a vector
9343 ;; First sort the numbers to get a regular ractangle
9344 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
9345 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
9346 (goto-line r1)
9347 (while (not (looking-at org-table-dataline-regexp))
9348 (beginning-of-line 2))
9349 (org-table-goto-column c1)
9350 (setq beg (point))
9351 (goto-line r2)
9352 (while (not (looking-at org-table-dataline-regexp))
9353 (beginning-of-line 0))
9354 (org-table-goto-column c2)
9355 (setq end (point))
9356 (if highlight
9357 (org-table-highlight-rectangle
9358 beg (progn (skip-chars-forward "^|\n") (point))))
9359 ;; return string representation of calc vector
9360 (mapcar 'org-trim
9361 (apply 'append (org-table-copy-region beg end)))))))
9363 (defun org-table-get-descriptor-line (desc &optional cline bline table)
9364 "Analyze descriptor DESC and retrieve the corresponding line number.
9365 The cursor is currently in line CLINE, the table begins in line BLINE,
9366 and TABLE is a vector with line types."
9367 (if (string-match "^[0-9]+$" desc)
9368 (aref org-table-dlines (string-to-number desc))
9369 (setq cline (or cline (org-current-line))
9370 bline (or bline org-table-current-begin-line)
9371 table (or table org-table-current-line-types))
9372 (if (or
9373 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
9374 ;; 1 2 3 4 5 6
9375 (and (not (match-end 3)) (not (match-end 6)))
9376 (and (match-end 3) (match-end 6) (not (match-end 5))))
9377 (error "invalid row descriptor `%s'" desc))
9378 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
9379 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
9380 (odir (and (match-end 5) (match-string 5 desc)))
9381 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
9382 (i (- cline bline))
9383 (rel (and (match-end 6)
9384 (or (and (match-end 1) (not (match-end 3)))
9385 (match-end 5)))))
9386 (if (and hn (not hdir))
9387 (progn
9388 (setq i 0 hdir "+")
9389 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
9390 (if (and (not hn) on (not odir))
9391 (error "should never happen");;(aref org-table-dlines on)
9392 (if (and hn (> hn 0))
9393 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
9394 (if on
9395 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
9396 (+ bline i)))))
9398 (defun org-find-row-type (table i type backwards relative n)
9399 (let ((l (length table)))
9400 (while (> n 0)
9401 (while (and (setq i (+ i (if backwards -1 1)))
9402 (>= i 0) (< i l)
9403 (not (eq (aref table i) type))
9404 (if (and relative (eq (aref table i) 'hline))
9405 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
9406 t)))
9407 (setq n (1- n)))
9408 (if (or (< i 0) (>= i l))
9409 (error "Row descriptior leads outside table")
9410 i)))
9412 (defun org-rewrite-old-row-references (s)
9413 (if (string-match "&[-+0-9I]" s)
9414 (error "Formula contains old &row reference, please rewrite using @-syntax")
9417 (defun org-table-make-reference (elements keep-empty numbers lispp)
9418 "Convert list ELEMENTS to something appropriate to insert into formula.
9419 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
9420 NUMBERS indicates that everything should be converted to numbers.
9421 LISPP means to return something appropriate for a Lisp list."
9422 (if (stringp elements) ; just a single val
9423 (if lispp
9424 (if (eq lispp 'literal)
9425 elements
9426 (prin1-to-string (if numbers (string-to-number elements) elements)))
9427 (if (equal elements "") (setq elements "0"))
9428 (if numbers (number-to-string (string-to-number elements)) elements))
9429 (unless keep-empty
9430 (setq elements
9431 (delq nil
9432 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
9433 elements))))
9434 (setq elements (or elements '("0")))
9435 (if lispp
9436 (mapconcat
9437 (lambda (x)
9438 (if (eq lispp 'literal)
9440 (prin1-to-string (if numbers (string-to-number x) x))))
9441 elements " ")
9442 (concat "[" (mapconcat
9443 (lambda (x)
9444 (if numbers (number-to-string (string-to-number x)) x))
9445 elements
9446 ",") "]"))))
9448 (defun org-table-recalculate (&optional all noalign)
9449 "Recalculate the current table line by applying all stored formulas.
9450 With prefix arg ALL, do this for all lines in the table."
9451 (interactive "P")
9452 (or (memq this-command org-recalc-commands)
9453 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9454 (unless (org-at-table-p) (error "Not at a table"))
9455 (if (equal all '(16))
9456 (org-table-iterate)
9457 (org-table-get-specials)
9458 (let* ((eqlist (sort (org-table-get-stored-formulas)
9459 (lambda (a b) (string< (car a) (car b)))))
9460 (inhibit-redisplay (not debug-on-error))
9461 (line-re org-table-dataline-regexp)
9462 (thisline (org-current-line))
9463 (thiscol (org-table-current-column))
9464 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
9465 ;; Insert constants in all formulas
9466 (setq eqlist
9467 (mapcar (lambda (x)
9468 (setcdr x (org-table-formula-substitute-names (cdr x)))
9470 eqlist))
9471 ;; Split the equation list
9472 (while (setq eq (pop eqlist))
9473 (if (<= (string-to-char (car eq)) ?9)
9474 (push eq eqlnum)
9475 (push eq eqlname)))
9476 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9477 (if all
9478 (progn
9479 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9480 (goto-char (setq beg (org-table-begin)))
9481 (if (re-search-forward org-table-calculate-mark-regexp end t)
9482 ;; This is a table with marked lines, compute selected lines
9483 (setq line-re org-table-recalculate-regexp)
9484 ;; Move forward to the first non-header line
9485 (if (and (re-search-forward org-table-dataline-regexp end t)
9486 (re-search-forward org-table-hline-regexp end t)
9487 (re-search-forward org-table-dataline-regexp end t))
9488 (setq beg (match-beginning 0))
9489 nil))) ;; just leave beg where it is
9490 (setq beg (point-at-bol)
9491 end (move-marker (make-marker) (1+ (point-at-eol)))))
9492 (goto-char beg)
9493 (and all (message "Re-applying formulas to full table..."))
9495 ;; First find the named fields, and mark them untouchanble
9496 (remove-text-properties beg end '(org-untouchable t))
9497 (while (setq eq (pop eqlname))
9498 (setq name (car eq)
9499 a (assoc name org-table-named-field-locations))
9500 (and (not a)
9501 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
9502 (setq a (list name
9503 (aref org-table-dlines
9504 (string-to-number (match-string 1 name)))
9505 (string-to-number (match-string 2 name)))))
9506 (when (and a (or all (equal (nth 1 a) thisline)))
9507 (message "Re-applying formula to field: %s" name)
9508 (goto-line (nth 1 a))
9509 (org-table-goto-column (nth 2 a))
9510 (push (append a (list (cdr eq))) eqlname1)
9511 (org-table-put-field-property :org-untouchable t)))
9513 ;; Now evauluate the column formulas, but skip fields covered by
9514 ;; field formulas
9515 (goto-char beg)
9516 (while (re-search-forward line-re end t)
9517 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
9518 ;; Unprotected line, recalculate
9519 (and all (message "Re-applying formulas to full table...(line %d)"
9520 (setq cnt (1+ cnt))))
9521 (setq org-last-recalc-line (org-current-line))
9522 (setq eql eqlnum)
9523 (while (setq entry (pop eql))
9524 (goto-line org-last-recalc-line)
9525 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9526 (unless (get-text-property (point) :org-untouchable)
9527 (org-table-eval-formula nil (cdr entry)
9528 'noalign 'nocst 'nostore 'noanalysis)))))
9530 ;; Now evaluate the field formulas
9531 (while (setq eq (pop eqlname1))
9532 (message "Re-applying formula to field: %s" (car eq))
9533 (goto-line (nth 1 eq))
9534 (org-table-goto-column (nth 2 eq))
9535 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
9536 'nostore 'noanalysis))
9538 (goto-line thisline)
9539 (org-table-goto-column thiscol)
9540 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
9541 (or noalign (and org-table-may-need-update (org-table-align))
9542 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9544 ;; back to initial position
9545 (message "Re-applying formulas...done")
9546 (goto-line thisline)
9547 (org-table-goto-column thiscol)
9548 (or noalign (and org-table-may-need-update (org-table-align))
9549 (and all (message "Re-applying formulas...done"))))))
9551 (defun org-table-iterate (&optional arg)
9552 "Recalculate the table until it does not change anymore."
9553 (interactive "P")
9554 (let ((imax (if arg (prefix-numeric-value arg) 10))
9555 (i 0)
9556 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
9557 thistbl)
9558 (catch 'exit
9559 (while (< i imax)
9560 (setq i (1+ i))
9561 (org-table-recalculate 'all)
9562 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
9563 (if (not (string= lasttbl thistbl))
9564 (setq lasttbl thistbl)
9565 (if (> i 1)
9566 (message "Convergence after %d iterations" i)
9567 (message "Table was already stable"))
9568 (throw 'exit t)))
9569 (error "No convergence after %d iterations" i))))
9571 (defun org-table-formula-substitute-names (f)
9572 "Replace $const with values in string F."
9573 (let ((start 0) a (f1 f))
9574 ;; First, check for column names
9575 (while (setq start (string-match org-table-column-name-regexp f start))
9576 (setq start (1+ start))
9577 (setq a (assoc (match-string 1 f) org-table-column-names))
9578 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9579 ;; Parameters and constants
9580 (setq start 0)
9581 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
9582 (setq start (1+ start))
9583 (if (setq a (save-match-data
9584 (org-table-get-constant (match-string 1 f))))
9585 (setq f (replace-match (concat "(" a ")") t t f))))
9586 (if org-table-formula-debug
9587 (put-text-property 0 (length f) :orig-formula f1 f))
9590 (defun org-table-get-constant (const)
9591 "Find the value for a parameter or constant in a formula.
9592 Parameters get priority."
9593 (or (cdr (assoc const org-table-local-parameters))
9594 (cdr (assoc const org-table-formula-constants-local))
9595 (cdr (assoc const org-table-formula-constants))
9596 (and (fboundp 'constants-get) (constants-get const))
9597 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
9598 (org-entry-get nil (substring const 5) 'inherit))
9599 "#UNDEFINED_NAME"))
9601 (defvar org-table-fedit-map
9602 (let ((map (make-sparse-keymap)))
9603 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
9604 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
9605 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
9606 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
9607 (org-defkey map "\C-c?" 'org-table-show-reference)
9608 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
9609 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
9610 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
9611 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
9612 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
9613 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
9614 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
9615 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
9616 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
9617 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
9618 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
9619 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
9620 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
9621 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
9622 map))
9624 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
9625 '("Edit-Formulas"
9626 ["Finish and Install" org-table-fedit-finish t]
9627 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
9628 ["Abort" org-table-fedit-abort t]
9629 "--"
9630 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
9631 ["Complete Lisp Symbol" lisp-complete-symbol t]
9632 "--"
9633 "Shift Reference at Point"
9634 ["Up" org-table-fedit-ref-up t]
9635 ["Down" org-table-fedit-ref-down t]
9636 ["Left" org-table-fedit-ref-left t]
9637 ["Right" org-table-fedit-ref-right t]
9639 "Change Test Row for Column Formulas"
9640 ["Up" org-table-fedit-line-up t]
9641 ["Down" org-table-fedit-line-down t]
9642 "--"
9643 ["Scroll Table Window" org-table-fedit-scroll t]
9644 ["Scroll Table Window down" org-table-fedit-scroll-down t]
9645 ["Show Table Grid" org-table-fedit-toggle-coordinates
9646 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
9647 org-table-overlay-coordinates)]
9648 "--"
9649 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
9650 :style toggle :selected org-table-buffer-is-an]))
9652 (defvar org-pos)
9654 (defun org-table-edit-formulas ()
9655 "Edit the formulas of the current table in a separate buffer."
9656 (interactive)
9657 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
9658 (beginning-of-line 0))
9659 (unless (org-at-table-p) (error "Not at a table"))
9660 (org-table-get-specials)
9661 (let ((key (org-table-current-field-formula 'key 'noerror))
9662 (eql (sort (org-table-get-stored-formulas 'noerror)
9663 'org-table-formula-less-p))
9664 (pos (move-marker (make-marker) (point)))
9665 (startline 1)
9666 (wc (current-window-configuration))
9667 (titles '((column . "# Column Formulas\n")
9668 (field . "# Field Formulas\n")
9669 (named . "# Named Field Formulas\n")))
9670 entry s type title)
9671 (org-switch-to-buffer-other-window "*Edit Formulas*")
9672 (erase-buffer)
9673 ;; Keep global-font-lock-mode from turning on font-lock-mode
9674 (let ((font-lock-global-modes '(not fundamental-mode)))
9675 (fundamental-mode))
9676 (org-set-local 'font-lock-global-modes (list 'not major-mode))
9677 (org-set-local 'org-pos pos)
9678 (org-set-local 'org-window-configuration wc)
9679 (use-local-map org-table-fedit-map)
9680 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
9681 (easy-menu-add org-table-fedit-menu)
9682 (setq startline (org-current-line))
9683 (while (setq entry (pop eql))
9684 (setq type (cond
9685 ((equal (string-to-char (car entry)) ?@) 'field)
9686 ((string-match "^[0-9]" (car entry)) 'column)
9687 (t 'named)))
9688 (when (setq title (assq type titles))
9689 (or (bobp) (insert "\n"))
9690 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
9691 (setq titles (delq title titles)))
9692 (if (equal key (car entry)) (setq startline (org-current-line)))
9693 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
9694 (car entry) " = " (cdr entry) "\n"))
9695 (remove-text-properties 0 (length s) '(face nil) s)
9696 (insert s))
9697 (if (eq org-table-use-standard-references t)
9698 (org-table-fedit-toggle-ref-type))
9699 (goto-line startline)
9700 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
9702 (defun org-table-fedit-post-command ()
9703 (when (not (memq this-command '(lisp-complete-symbol)))
9704 (let ((win (selected-window)))
9705 (save-excursion
9706 (condition-case nil
9707 (org-table-show-reference)
9708 (error nil))
9709 (select-window win)))))
9711 (defun org-table-formula-to-user (s)
9712 "Convert a formula from internal to user representation."
9713 (if (eq org-table-use-standard-references t)
9714 (org-table-convert-refs-to-an s)
9717 (defun org-table-formula-from-user (s)
9718 "Convert a formula from user to internal representation."
9719 (if org-table-use-standard-references
9720 (org-table-convert-refs-to-rc s)
9723 (defun org-table-convert-refs-to-rc (s)
9724 "Convert spreadsheet references from AB7 to @7$28.
9725 Works for single references, but also for entire formulas and even the
9726 full TBLFM line."
9727 (let ((start 0))
9728 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
9729 (cond
9730 ((match-end 3)
9731 ;; format match, just advance
9732 (setq start (match-end 0)))
9733 ((and (> (match-beginning 0) 0)
9734 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
9735 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
9736 ;; 3.e5 or something like this.
9737 (setq start (match-end 0)))
9739 (setq start (match-beginning 0)
9740 s (replace-match
9741 (if (equal (match-string 2 s) "&")
9742 (format "$%d" (org-letters-to-number (match-string 1 s)))
9743 (format "@%d$%d"
9744 (string-to-number (match-string 2 s))
9745 (org-letters-to-number (match-string 1 s))))
9746 t t s)))))
9749 (defun org-table-convert-refs-to-an (s)
9750 "Convert spreadsheet references from to @7$28 to AB7.
9751 Works for single references, but also for entire formulas and even the
9752 full TBLFM line."
9753 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
9754 (setq s (replace-match
9755 (format "%s%d"
9756 (org-number-to-letters
9757 (string-to-number (match-string 2 s)))
9758 (string-to-number (match-string 1 s)))
9759 t t s)))
9760 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
9761 (setq s (replace-match (concat "\\1"
9762 (org-number-to-letters
9763 (string-to-number (match-string 2 s))) "&")
9764 t nil s)))
9767 (defun org-letters-to-number (s)
9768 "Convert a base 26 number represented by letters into an integer.
9769 For example: AB -> 28."
9770 (let ((n 0))
9771 (setq s (upcase s))
9772 (while (> (length s) 0)
9773 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
9774 s (substring s 1)))
9777 (defun org-number-to-letters (n)
9778 "Convert an integer into a base 26 number represented by letters.
9779 For example: 28 -> AB."
9780 (let ((s ""))
9781 (while (> n 0)
9782 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
9783 n (/ (1- n) 26)))
9786 (defun org-table-fedit-convert-buffer (function)
9787 "Convert all references in this buffer, using FUNTION."
9788 (let ((line (org-current-line)))
9789 (goto-char (point-min))
9790 (while (not (eobp))
9791 (insert (funcall function (buffer-substring (point) (point-at-eol))))
9792 (delete-region (point) (point-at-eol))
9793 (or (eobp) (forward-char 1)))
9794 (goto-line line)))
9796 (defun org-table-fedit-toggle-ref-type ()
9797 "Convert all references in the buffer from B3 to @3$2 and back."
9798 (interactive)
9799 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
9800 (org-table-fedit-convert-buffer
9801 (if org-table-buffer-is-an
9802 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
9803 (message "Reference type switched to %s"
9804 (if org-table-buffer-is-an "A1 etc" "@row$column")))
9806 (defun org-table-fedit-ref-up ()
9807 "Shift the reference at point one row/hline up."
9808 (interactive)
9809 (org-table-fedit-shift-reference 'up))
9810 (defun org-table-fedit-ref-down ()
9811 "Shift the reference at point one row/hline down."
9812 (interactive)
9813 (org-table-fedit-shift-reference 'down))
9814 (defun org-table-fedit-ref-left ()
9815 "Shift the reference at point one field to the left."
9816 (interactive)
9817 (org-table-fedit-shift-reference 'left))
9818 (defun org-table-fedit-ref-right ()
9819 "Shift the reference at point one field to the right."
9820 (interactive)
9821 (org-table-fedit-shift-reference 'right))
9823 (defun org-table-fedit-shift-reference (dir)
9824 (cond
9825 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
9826 (if (memq dir '(left right))
9827 (org-rematch-and-replace 1 (eq dir 'left))
9828 (error "Cannot shift reference in this direction")))
9829 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
9830 ;; A B3-like reference
9831 (if (memq dir '(up down))
9832 (org-rematch-and-replace 2 (eq dir 'up))
9833 (org-rematch-and-replace 1 (eq dir 'left))))
9834 ((org-at-regexp-p
9835 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
9836 ;; An internal reference
9837 (if (memq dir '(up down))
9838 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
9839 (org-rematch-and-replace 5 (eq dir 'left))))))
9841 (defun org-rematch-and-replace (n &optional decr hline)
9842 "Re-match the group N, and replace it with the shifted refrence."
9843 (or (match-end n) (error "Cannot shift reference in this direction"))
9844 (goto-char (match-beginning n))
9845 (and (looking-at (regexp-quote (match-string n)))
9846 (replace-match (org-shift-refpart (match-string 0) decr hline)
9847 t t)))
9849 (defun org-shift-refpart (ref &optional decr hline)
9850 "Shift a refrence part REF.
9851 If DECR is set, decrease the references row/column, else increase.
9852 If HLINE is set, this may be a hline reference, it certainly is not
9853 a translation reference."
9854 (save-match-data
9855 (let* ((sign (string-match "^[-+]" ref)) n)
9857 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
9858 (cond
9859 ((and hline (string-match "^I+" ref))
9860 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
9861 (setq n (+ n (if decr -1 1)))
9862 (if (= n 0) (setq n (+ n (if decr -1 1))))
9863 (if sign
9864 (setq sign (if (< n 0) "-" "+") n (abs n))
9865 (setq n (max 1 n)))
9866 (concat sign (make-string n ?I)))
9868 ((string-match "^[0-9]+" ref)
9869 (setq n (string-to-number (concat sign ref)))
9870 (setq n (+ n (if decr -1 1)))
9871 (if sign
9872 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
9873 (number-to-string (max 1 n))))
9875 ((string-match "^[a-zA-Z]+" ref)
9876 (org-number-to-letters
9877 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
9879 (t (error "Cannot shift reference"))))))
9881 (defun org-table-fedit-toggle-coordinates ()
9882 "Toggle the display of coordinates in the refrenced table."
9883 (interactive)
9884 (let ((pos (marker-position org-pos)))
9885 (with-current-buffer (marker-buffer org-pos)
9886 (save-excursion
9887 (goto-char pos)
9888 (org-table-toggle-coordinate-overlays)))))
9890 (defun org-table-fedit-finish (&optional arg)
9891 "Parse the buffer for formula definitions and install them.
9892 With prefix ARG, apply the new formulas to the table."
9893 (interactive "P")
9894 (org-table-remove-rectangle-highlight)
9895 (if org-table-use-standard-references
9896 (progn
9897 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
9898 (setq org-table-buffer-is-an nil)))
9899 (let ((pos org-pos) eql var form)
9900 (goto-char (point-min))
9901 (while (re-search-forward
9902 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
9903 nil t)
9904 (setq var (if (match-end 2) (match-string 2) (match-string 1))
9905 form (match-string 3))
9906 (setq form (org-trim form))
9907 (when (not (equal form ""))
9908 (while (string-match "[ \t]*\n[ \t]*" form)
9909 (setq form (replace-match " " t t form)))
9910 (when (assoc var eql)
9911 (error "Double formulas for %s" var))
9912 (push (cons var form) eql)))
9913 (setq org-pos nil)
9914 (set-window-configuration org-window-configuration)
9915 (select-window (get-buffer-window (marker-buffer pos)))
9916 (goto-char pos)
9917 (unless (org-at-table-p)
9918 (error "Lost table position - cannot install formulae"))
9919 (org-table-store-formulas eql)
9920 (move-marker pos nil)
9921 (kill-buffer "*Edit Formulas*")
9922 (if arg
9923 (org-table-recalculate 'all)
9924 (message "New formulas installed - press C-u C-c C-c to apply."))))
9926 (defun org-table-fedit-abort ()
9927 "Abort editing formulas, without installing the changes."
9928 (interactive)
9929 (org-table-remove-rectangle-highlight)
9930 (let ((pos org-pos))
9931 (set-window-configuration org-window-configuration)
9932 (select-window (get-buffer-window (marker-buffer pos)))
9933 (goto-char pos)
9934 (move-marker pos nil)
9935 (message "Formula editing aborted without installing changes")))
9937 (defun org-table-fedit-lisp-indent ()
9938 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
9939 (interactive)
9940 (let ((pos (point)) beg end ind)
9941 (beginning-of-line 1)
9942 (cond
9943 ((looking-at "[ \t]")
9944 (goto-char pos)
9945 (call-interactively 'lisp-indent-line))
9946 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
9947 ((not (fboundp 'pp-buffer))
9948 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
9949 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
9950 (goto-char (- (match-end 0) 2))
9951 (setq beg (point))
9952 (setq ind (make-string (current-column) ?\ ))
9953 (condition-case nil (forward-sexp 1)
9954 (error
9955 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
9956 (setq end (point))
9957 (save-restriction
9958 (narrow-to-region beg end)
9959 (if (eq last-command this-command)
9960 (progn
9961 (goto-char (point-min))
9962 (setq this-command nil)
9963 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
9964 (replace-match " ")))
9965 (pp-buffer)
9966 (untabify (point-min) (point-max))
9967 (goto-char (1+ (point-min)))
9968 (while (re-search-forward "^." nil t)
9969 (beginning-of-line 1)
9970 (insert ind))
9971 (goto-char (point-max))
9972 (backward-delete-char 1)))
9973 (goto-char beg))
9974 (t nil))))
9976 (defvar org-show-positions nil)
9978 (defun org-table-show-reference (&optional local)
9979 "Show the location/value of the $ expression at point."
9980 (interactive)
9981 (org-table-remove-rectangle-highlight)
9982 (catch 'exit
9983 (let ((pos (if local (point) org-pos))
9984 (face2 'highlight)
9985 (org-inhibit-highlight-removal t)
9986 (win (selected-window))
9987 (org-show-positions nil)
9988 var name e what match dest)
9989 (if local (org-table-get-specials))
9990 (setq what (cond
9991 ((or (org-at-regexp-p org-table-range-regexp2)
9992 (org-at-regexp-p org-table-translate-regexp)
9993 (org-at-regexp-p org-table-range-regexp))
9994 (setq match
9995 (save-match-data
9996 (org-table-convert-refs-to-rc (match-string 0))))
9997 'range)
9998 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
9999 ((org-at-regexp-p "\\$[0-9]+") 'column)
10000 ((not local) nil)
10001 (t (error "No reference at point")))
10002 match (and what (or match (match-string 0))))
10003 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10004 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10005 'secondary-selection))
10006 (org-add-hook 'before-change-functions
10007 'org-table-remove-rectangle-highlight)
10008 (if (eq what 'name) (setq var (substring match 1)))
10009 (when (eq what 'range)
10010 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10011 (setq match (org-table-formula-substitute-names match)))
10012 (unless local
10013 (save-excursion
10014 (end-of-line 1)
10015 (re-search-backward "^\\S-" nil t)
10016 (beginning-of-line 1)
10017 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10018 (setq dest
10019 (save-match-data
10020 (org-table-convert-refs-to-rc (match-string 1))))
10021 (org-table-add-rectangle-overlay
10022 (match-beginning 1) (match-end 1) face2))))
10023 (if (and (markerp pos) (marker-buffer pos))
10024 (if (get-buffer-window (marker-buffer pos))
10025 (select-window (get-buffer-window (marker-buffer pos)))
10026 (org-switch-to-buffer-other-window (get-buffer-window
10027 (marker-buffer pos)))))
10028 (goto-char pos)
10029 (org-table-force-dataline)
10030 (when dest
10031 (setq name (substring dest 1))
10032 (cond
10033 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10034 (setq e (assoc name org-table-named-field-locations))
10035 (goto-line (nth 1 e))
10036 (org-table-goto-column (nth 2 e)))
10037 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10038 (let ((l (string-to-number (match-string 1 dest)))
10039 (c (string-to-number (match-string 2 dest))))
10040 (goto-line (aref org-table-dlines l))
10041 (org-table-goto-column c)))
10042 (t (org-table-goto-column (string-to-number name))))
10043 (move-marker pos (point))
10044 (org-table-highlight-rectangle nil nil face2))
10045 (cond
10046 ((equal dest match))
10047 ((not match))
10048 ((eq what 'range)
10049 (condition-case nil
10050 (save-excursion
10051 (org-table-get-range match nil nil 'highlight))
10052 (error nil)))
10053 ((setq e (assoc var org-table-named-field-locations))
10054 (goto-line (nth 1 e))
10055 (org-table-goto-column (nth 2 e))
10056 (org-table-highlight-rectangle (point) (point))
10057 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10058 ((setq e (assoc var org-table-column-names))
10059 (org-table-goto-column (string-to-number (cdr e)))
10060 (org-table-highlight-rectangle (point) (point))
10061 (goto-char (org-table-begin))
10062 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10063 (org-table-end) t)
10064 (progn
10065 (goto-char (match-beginning 1))
10066 (org-table-highlight-rectangle)
10067 (message "Named column (column %s)" (cdr e)))
10068 (error "Column name not found")))
10069 ((eq what 'column)
10070 ;; column number
10071 (org-table-goto-column (string-to-number (substring match 1)))
10072 (org-table-highlight-rectangle (point) (point))
10073 (message "Column %s" (substring match 1)))
10074 ((setq e (assoc var org-table-local-parameters))
10075 (goto-char (org-table-begin))
10076 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10077 (progn
10078 (goto-char (match-beginning 1))
10079 (org-table-highlight-rectangle)
10080 (message "Local parameter."))
10081 (error "Parameter not found")))
10083 (cond
10084 ((not var) (error "No reference at point"))
10085 ((setq e (assoc var org-table-formula-constants-local))
10086 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10087 var (cdr e)))
10088 ((setq e (assoc var org-table-formula-constants))
10089 (message "Constant: $%s=%s in `org-table-formula-constants'."
10090 var (cdr e)))
10091 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10092 (message "Constant: $%s=%s, from `constants.el'%s."
10093 var e (format " (%s units)" constants-unit-system)))
10094 (t (error "Undefined name $%s" var)))))
10095 (goto-char pos)
10096 (when (and org-show-positions
10097 (not (memq this-command '(org-table-fedit-scroll
10098 org-table-fedit-scroll-down))))
10099 (push pos org-show-positions)
10100 (push org-table-current-begin-pos org-show-positions)
10101 (let ((min (apply 'min org-show-positions))
10102 (max (apply 'max org-show-positions)))
10103 (goto-char min) (recenter 0)
10104 (goto-char max)
10105 (or (pos-visible-in-window-p max) (recenter -1))))
10106 (select-window win))))
10108 (defun org-table-force-dataline ()
10109 "Make sure the cursor is in a dataline in a table."
10110 (unless (save-excursion
10111 (beginning-of-line 1)
10112 (looking-at org-table-dataline-regexp))
10113 (let* ((re org-table-dataline-regexp)
10114 (p1 (save-excursion (re-search-forward re nil 'move)))
10115 (p2 (save-excursion (re-search-backward re nil 'move))))
10116 (cond ((and p1 p2)
10117 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10118 p1 p2)))
10119 ((or p1 p2) (goto-char (or p1 p2)))
10120 (t (error "No table dataline around here"))))))
10122 (defun org-table-fedit-line-up ()
10123 "Move cursor one line up in the window showing the table."
10124 (interactive)
10125 (org-table-fedit-move 'previous-line))
10127 (defun org-table-fedit-line-down ()
10128 "Move cursor one line down in the window showing the table."
10129 (interactive)
10130 (org-table-fedit-move 'next-line))
10132 (defun org-table-fedit-move (command)
10133 "Move the cursor in the window shoinw the table.
10134 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10135 (let ((org-table-allow-automatic-line-recalculation nil)
10136 (pos org-pos) (win (selected-window)) p)
10137 (select-window (get-buffer-window (marker-buffer org-pos)))
10138 (setq p (point))
10139 (call-interactively command)
10140 (while (and (org-at-table-p)
10141 (org-at-table-hline-p))
10142 (call-interactively command))
10143 (or (org-at-table-p) (goto-char p))
10144 (move-marker pos (point))
10145 (select-window win)))
10147 (defun org-table-fedit-scroll (N)
10148 (interactive "p")
10149 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10150 (scroll-other-window N)))
10152 (defun org-table-fedit-scroll-down (N)
10153 (interactive "p")
10154 (org-table-fedit-scroll (- N)))
10156 (defvar org-table-rectangle-overlays nil)
10158 (defun org-table-add-rectangle-overlay (beg end &optional face)
10159 "Add a new overlay."
10160 (let ((ov (org-make-overlay beg end)))
10161 (org-overlay-put ov 'face (or face 'secondary-selection))
10162 (push ov org-table-rectangle-overlays)))
10164 (defun org-table-highlight-rectangle (&optional beg end face)
10165 "Highlight rectangular region in a table."
10166 (setq beg (or beg (point)) end (or end (point)))
10167 (let ((b (min beg end))
10168 (e (max beg end))
10169 l1 c1 l2 c2 tmp)
10170 (and (boundp 'org-show-positions)
10171 (setq org-show-positions (cons b (cons e org-show-positions))))
10172 (goto-char (min beg end))
10173 (setq l1 (org-current-line)
10174 c1 (org-table-current-column))
10175 (goto-char (max beg end))
10176 (setq l2 (org-current-line)
10177 c2 (org-table-current-column))
10178 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10179 (goto-line l1)
10180 (beginning-of-line 1)
10181 (loop for line from l1 to l2 do
10182 (when (looking-at org-table-dataline-regexp)
10183 (org-table-goto-column c1)
10184 (skip-chars-backward "^|\n") (setq beg (point))
10185 (org-table-goto-column c2)
10186 (skip-chars-forward "^|\n") (setq end (point))
10187 (org-table-add-rectangle-overlay beg end face))
10188 (beginning-of-line 2))
10189 (goto-char b))
10190 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10192 (defun org-table-remove-rectangle-highlight (&rest ignore)
10193 "Remove the rectangle overlays."
10194 (unless org-inhibit-highlight-removal
10195 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10196 (mapc 'org-delete-overlay org-table-rectangle-overlays)
10197 (setq org-table-rectangle-overlays nil)))
10199 (defvar org-table-coordinate-overlays nil
10200 "Collects the cooordinate grid overlays, so that they can be removed.")
10201 (make-variable-buffer-local 'org-table-coordinate-overlays)
10203 (defun org-table-overlay-coordinates ()
10204 "Add overlays to the table at point, to show row/column coordinates."
10205 (interactive)
10206 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10207 (setq org-table-coordinate-overlays nil)
10208 (save-excursion
10209 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10210 (goto-char (org-table-begin))
10211 (while (org-at-table-p)
10212 (setq eol (point-at-eol))
10213 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10214 (push ov org-table-coordinate-overlays)
10215 (setq hline (looking-at org-table-hline-regexp))
10216 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10217 (format "%4d" (setq id (1+ id)))))
10218 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10219 (when hline
10220 (setq ic 0)
10221 (while (re-search-forward "[+|]\\(-+\\)" eol t)
10222 (setq beg (1+ (match-beginning 0))
10223 ic (1+ ic)
10224 s1 (concat "$" (int-to-string ic))
10225 s2 (org-number-to-letters ic)
10226 str (if (eq org-table-use-standard-references t) s2 s1))
10227 (setq ov (org-make-overlay beg (+ beg (length str))))
10228 (push ov org-table-coordinate-overlays)
10229 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10230 (beginning-of-line 2)))))
10232 (defun org-table-toggle-coordinate-overlays ()
10233 "Toggle the display of Row/Column numbers in tables."
10234 (interactive)
10235 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10236 (message "Row/Column number display turned %s"
10237 (if org-table-overlay-coordinates "on" "off"))
10238 (if (and (org-at-table-p) org-table-overlay-coordinates)
10239 (org-table-align))
10240 (unless org-table-overlay-coordinates
10241 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10242 (setq org-table-coordinate-overlays nil)))
10244 (defun org-table-toggle-formula-debugger ()
10245 "Toggle the formula debugger in tables."
10246 (interactive)
10247 (setq org-table-formula-debug (not org-table-formula-debug))
10248 (message "Formula debugging has been turned %s"
10249 (if org-table-formula-debug "on" "off")))
10251 ;;; The orgtbl minor mode
10253 ;; Define a minor mode which can be used in other modes in order to
10254 ;; integrate the org-mode table editor.
10256 ;; This is really a hack, because the org-mode table editor uses several
10257 ;; keys which normally belong to the major mode, for example the TAB and
10258 ;; RET keys. Here is how it works: The minor mode defines all the keys
10259 ;; necessary to operate the table editor, but wraps the commands into a
10260 ;; function which tests if the cursor is currently inside a table. If that
10261 ;; is the case, the table editor command is executed. However, when any of
10262 ;; those keys is used outside a table, the function uses `key-binding' to
10263 ;; look up if the key has an associated command in another currently active
10264 ;; keymap (minor modes, major mode, global), and executes that command.
10265 ;; There might be problems if any of the keys used by the table editor is
10266 ;; otherwise used as a prefix key.
10268 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10269 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10270 ;; addresses this by checking explicitly for both bindings.
10272 ;; The optimized version (see variable `orgtbl-optimized') takes over
10273 ;; all keys which are bound to `self-insert-command' in the *global map*.
10274 ;; Some modes bind other commands to simple characters, for example
10275 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10276 ;; active, this binding is ignored inside tables and replaced with a
10277 ;; modified self-insert.
10279 (defvar orgtbl-mode nil
10280 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10281 table editor in arbitrary modes.")
10282 (make-variable-buffer-local 'orgtbl-mode)
10284 (defvar orgtbl-mode-map (make-keymap)
10285 "Keymap for `orgtbl-mode'.")
10287 ;;;###autoload
10288 (defun turn-on-orgtbl ()
10289 "Unconditionally turn on `orgtbl-mode'."
10290 (orgtbl-mode 1))
10292 (defvar org-old-auto-fill-inhibit-regexp nil
10293 "Local variable used by `orgtbl-mode'")
10295 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
10296 "Matches a line belonging to an orgtbl.")
10298 (defconst orgtbl-extra-font-lock-keywords
10299 (list (list (concat "^" orgtbl-line-start-regexp ".*")
10300 0 (quote 'org-table) 'prepend))
10301 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
10303 ;;;###autoload
10304 (defun orgtbl-mode (&optional arg)
10305 "The `org-mode' table editor as a minor mode for use in other modes."
10306 (interactive)
10307 (if (org-mode-p)
10308 ;; Exit without error, in case some hook functions calls this
10309 ;; by accident in org-mode.
10310 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10311 (setq orgtbl-mode
10312 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10313 (if orgtbl-mode
10314 (progn
10315 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10316 ;; Make sure we are first in minor-mode-map-alist
10317 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10318 (and c (setq minor-mode-map-alist
10319 (cons c (delq c minor-mode-map-alist)))))
10320 (org-set-local (quote org-table-may-need-update) t)
10321 (org-add-hook 'before-change-functions 'org-before-change-function
10322 nil 'local)
10323 (org-set-local 'org-old-auto-fill-inhibit-regexp
10324 auto-fill-inhibit-regexp)
10325 (org-set-local 'auto-fill-inhibit-regexp
10326 (if auto-fill-inhibit-regexp
10327 (concat orgtbl-line-start-regexp "\\|"
10328 auto-fill-inhibit-regexp)
10329 orgtbl-line-start-regexp))
10330 (org-add-to-invisibility-spec '(org-cwidth))
10331 (when (fboundp 'font-lock-add-keywords)
10332 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
10333 (org-restart-font-lock))
10334 (easy-menu-add orgtbl-mode-menu)
10335 (run-hooks 'orgtbl-mode-hook))
10336 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10337 (org-cleanup-narrow-column-properties)
10338 (org-remove-from-invisibility-spec '(org-cwidth))
10339 (remove-hook 'before-change-functions 'org-before-change-function t)
10340 (when (fboundp 'font-lock-remove-keywords)
10341 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
10342 (org-restart-font-lock))
10343 (easy-menu-remove orgtbl-mode-menu)
10344 (force-mode-line-update 'all))))
10346 (defun org-cleanup-narrow-column-properties ()
10347 "Remove all properties related to narrow-column invisibility."
10348 (let ((s 1))
10349 (while (setq s (text-property-any s (point-max)
10350 'display org-narrow-column-arrow))
10351 (remove-text-properties s (1+ s) '(display t)))
10352 (setq s 1)
10353 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10354 (remove-text-properties s (1+ s) '(org-cwidth t)))
10355 (setq s 1)
10356 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10357 (remove-text-properties s (1+ s) '(invisible t)))))
10359 ;; Install it as a minor mode.
10360 (put 'orgtbl-mode :included t)
10361 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10362 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10364 (defun orgtbl-make-binding (fun n &rest keys)
10365 "Create a function for binding in the table minor mode.
10366 FUN is the command to call inside a table. N is used to create a unique
10367 command name. KEYS are keys that should be checked in for a command
10368 to execute outside of tables."
10369 (eval
10370 (list 'defun
10371 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10372 '(arg)
10373 (concat "In tables, run `" (symbol-name fun) "'.\n"
10374 "Outside of tables, run the binding of `"
10375 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10376 "'.")
10377 '(interactive "p")
10378 (list 'if
10379 '(org-at-table-p)
10380 (list 'call-interactively (list 'quote fun))
10381 (list 'let '(orgtbl-mode)
10382 (list 'call-interactively
10383 (append '(or)
10384 (mapcar (lambda (k)
10385 (list 'key-binding k))
10386 keys)
10387 '('orgtbl-error))))))))
10389 (defun orgtbl-error ()
10390 "Error when there is no default binding for a table key."
10391 (interactive)
10392 (error "This key is has no function outside tables"))
10394 (defun orgtbl-setup ()
10395 "Setup orgtbl keymaps."
10396 (let ((nfunc 0)
10397 (bindings
10398 (list
10399 '([(meta shift left)] org-table-delete-column)
10400 '([(meta left)] org-table-move-column-left)
10401 '([(meta right)] org-table-move-column-right)
10402 '([(meta shift right)] org-table-insert-column)
10403 '([(meta shift up)] org-table-kill-row)
10404 '([(meta shift down)] org-table-insert-row)
10405 '([(meta up)] org-table-move-row-up)
10406 '([(meta down)] org-table-move-row-down)
10407 '("\C-c\C-w" org-table-cut-region)
10408 '("\C-c\M-w" org-table-copy-region)
10409 '("\C-c\C-y" org-table-paste-rectangle)
10410 '("\C-c-" org-table-insert-hline)
10411 '("\C-c}" org-table-toggle-coordinate-overlays)
10412 '("\C-c{" org-table-toggle-formula-debugger)
10413 '("\C-m" org-table-next-row)
10414 '([(shift return)] org-table-copy-down)
10415 '("\C-c\C-q" org-table-wrap-region)
10416 '("\C-c?" org-table-field-info)
10417 '("\C-c " org-table-blank-field)
10418 '("\C-c+" org-table-sum)
10419 '("\C-c=" org-table-eval-formula)
10420 '("\C-c'" org-table-edit-formulas)
10421 '("\C-c`" org-table-edit-field)
10422 '("\C-c*" org-table-recalculate)
10423 '("\C-c|" org-table-create-or-convert-from-region)
10424 '("\C-c^" org-table-sort-lines)
10425 '([(control ?#)] org-table-rotate-recalc-marks)))
10426 elt key fun cmd)
10427 (while (setq elt (pop bindings))
10428 (setq nfunc (1+ nfunc))
10429 (setq key (org-key (car elt))
10430 fun (nth 1 elt)
10431 cmd (orgtbl-make-binding fun nfunc key))
10432 (org-defkey orgtbl-mode-map key cmd))
10434 ;; Special treatment needed for TAB and RET
10435 (org-defkey orgtbl-mode-map [(return)]
10436 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10437 (org-defkey orgtbl-mode-map "\C-m"
10438 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10440 (org-defkey orgtbl-mode-map [(tab)]
10441 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10442 (org-defkey orgtbl-mode-map "\C-i"
10443 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
10445 (org-defkey orgtbl-mode-map [(shift tab)]
10446 (orgtbl-make-binding 'org-table-previous-field 104
10447 [(shift tab)] [(tab)] "\C-i"))
10449 (org-defkey orgtbl-mode-map "\M-\C-m"
10450 (orgtbl-make-binding 'org-table-wrap-region 105
10451 "\M-\C-m" [(meta return)]))
10452 (org-defkey orgtbl-mode-map [(meta return)]
10453 (orgtbl-make-binding 'org-table-wrap-region 106
10454 [(meta return)] "\M-\C-m"))
10456 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
10457 (when orgtbl-optimized
10458 ;; If the user wants maximum table support, we need to hijack
10459 ;; some standard editing functions
10460 (org-remap orgtbl-mode-map
10461 'self-insert-command 'orgtbl-self-insert-command
10462 'delete-char 'org-delete-char
10463 'delete-backward-char 'org-delete-backward-char)
10464 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
10465 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10466 '("OrgTbl"
10467 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10468 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10469 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10470 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10471 "--"
10472 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10473 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10474 ["Copy Field from Above"
10475 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10476 "--"
10477 ("Column"
10478 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10479 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10480 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10481 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10482 ("Row"
10483 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10484 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10485 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10486 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10487 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10488 "--"
10489 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10490 ("Rectangle"
10491 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10492 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10493 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10494 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10495 "--"
10496 ("Radio tables"
10497 ["Insert table template" orgtbl-insert-radio-table
10498 (assq major-mode orgtbl-radio-table-templates)]
10499 ["Comment/uncomment table" orgtbl-toggle-comment t])
10500 "--"
10501 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10502 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10503 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10504 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10505 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10506 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
10507 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10508 ["Sum Column/Rectangle" org-table-sum
10509 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10510 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10511 ["Debug Formulas"
10512 org-table-toggle-formula-debugger :active (org-at-table-p)
10513 :keys "C-c {"
10514 :style toggle :selected org-table-formula-debug]
10515 ["Show Col/Row Numbers"
10516 org-table-toggle-coordinate-overlays :active (org-at-table-p)
10517 :keys "C-c }"
10518 :style toggle :selected org-table-overlay-coordinates]
10522 (defun orgtbl-ctrl-c-ctrl-c (arg)
10523 "If the cursor is inside a table, realign the table.
10524 It it is a table to be sent away to a receiver, do it.
10525 With prefix arg, also recompute table."
10526 (interactive "P")
10527 (let ((pos (point)) action)
10528 (save-excursion
10529 (beginning-of-line 1)
10530 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
10531 ((looking-at "[ \t]*|") pos)
10532 ((looking-at "#\\+TBLFM:") 'recalc))))
10533 (cond
10534 ((integerp action)
10535 (goto-char action)
10536 (org-table-maybe-eval-formula)
10537 (if arg
10538 (call-interactively 'org-table-recalculate)
10539 (org-table-maybe-recalculate-line))
10540 (call-interactively 'org-table-align)
10541 (orgtbl-send-table 'maybe))
10542 ((eq action 'recalc)
10543 (save-excursion
10544 (beginning-of-line 1)
10545 (skip-chars-backward " \r\n\t")
10546 (if (org-at-table-p)
10547 (org-call-with-arg 'org-table-recalculate t))))
10548 (t (let (orgtbl-mode)
10549 (call-interactively (key-binding "\C-c\C-c")))))))
10551 (defun orgtbl-tab (arg)
10552 "Justification and field motion for `orgtbl-mode'."
10553 (interactive "P")
10554 (if arg (org-table-edit-field t)
10555 (org-table-justify-field-maybe)
10556 (org-table-next-field)))
10558 (defun orgtbl-ret ()
10559 "Justification and field motion for `orgtbl-mode'."
10560 (interactive)
10561 (org-table-justify-field-maybe)
10562 (org-table-next-row))
10564 (defun orgtbl-self-insert-command (N)
10565 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10566 If the cursor is in a table looking at whitespace, the whitespace is
10567 overwritten, and the table is not marked as requiring realignment."
10568 (interactive "p")
10569 (if (and (org-at-table-p)
10571 (and org-table-auto-blank-field
10572 (member last-command
10573 '(orgtbl-hijacker-command-100
10574 orgtbl-hijacker-command-101
10575 orgtbl-hijacker-command-102
10576 orgtbl-hijacker-command-103
10577 orgtbl-hijacker-command-104
10578 orgtbl-hijacker-command-105))
10579 (org-table-blank-field))
10581 (eq N 1)
10582 (looking-at "[^|\n]* +|"))
10583 (let (org-table-may-need-update)
10584 (goto-char (1- (match-end 0)))
10585 (delete-backward-char 1)
10586 (goto-char (match-beginning 0))
10587 (self-insert-command N))
10588 (setq org-table-may-need-update t)
10589 (let (orgtbl-mode)
10590 (call-interactively (key-binding (vector last-input-event))))))
10592 (defun org-force-self-insert (N)
10593 "Needed to enforce self-insert under remapping."
10594 (interactive "p")
10595 (self-insert-command N))
10597 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
10598 "Regula expression matching exponentials as produced by calc.")
10600 (defvar org-table-clean-did-remove-column nil)
10602 (defun orgtbl-export (table target)
10603 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
10604 (lines (org-split-string table "[ \t]*\n[ \t]*"))
10605 org-table-last-alignment org-table-last-column-widths
10606 maxcol column)
10607 (if (not (fboundp func))
10608 (error "Cannot export orgtbl table to %s" target))
10609 (setq lines (org-table-clean-before-export lines))
10610 (setq table
10611 (mapcar
10612 (lambda (x)
10613 (if (string-match org-table-hline-regexp x)
10614 'hline
10615 (org-split-string (org-trim x) "\\s-*|\\s-*")))
10616 lines))
10617 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
10618 table)))
10619 (loop for i from (1- maxcol) downto 0 do
10620 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
10621 (setq column (delq nil column))
10622 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
10623 (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))
10624 (funcall func table nil)))
10626 (defun orgtbl-send-table (&optional maybe)
10627 "Send a tranformed version of this table to the receiver position.
10628 With argument MAYBE, fail quietly if no transformation is defined for
10629 this table."
10630 (interactive)
10631 (catch 'exit
10632 (unless (org-at-table-p) (error "Not at a table"))
10633 ;; when non-interactive, we assume align has just happened.
10634 (when (interactive-p) (org-table-align))
10635 (save-excursion
10636 (goto-char (org-table-begin))
10637 (beginning-of-line 0)
10638 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
10639 (if maybe
10640 (throw 'exit nil)
10641 (error "Don't know how to transform this table."))))
10642 (let* ((name (match-string 1))
10644 (transform (intern (match-string 2)))
10645 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
10646 (skip (plist-get params :skip))
10647 (skipcols (plist-get params :skipcols))
10648 (txt (buffer-substring-no-properties
10649 (org-table-begin) (org-table-end)))
10650 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
10651 (lines (org-table-clean-before-export lines))
10652 (i0 (if org-table-clean-did-remove-column 2 1))
10653 (table (mapcar
10654 (lambda (x)
10655 (if (string-match org-table-hline-regexp x)
10656 'hline
10657 (org-remove-by-index
10658 (org-split-string (org-trim x) "\\s-*|\\s-*")
10659 skipcols i0)))
10660 lines))
10661 (fun (if (= i0 2) 'cdr 'identity))
10662 (org-table-last-alignment
10663 (org-remove-by-index (funcall fun org-table-last-alignment)
10664 skipcols i0))
10665 (org-table-last-column-widths
10666 (org-remove-by-index (funcall fun org-table-last-column-widths)
10667 skipcols i0)))
10669 (unless (fboundp transform)
10670 (error "No such transformation function %s" transform))
10671 (setq txt (funcall transform table params))
10672 ;; Find the insertion place
10673 (save-excursion
10674 (goto-char (point-min))
10675 (unless (re-search-forward
10676 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
10677 (error "Don't know where to insert translated table"))
10678 (goto-char (match-beginning 0))
10679 (beginning-of-line 2)
10680 (setq beg (point))
10681 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
10682 (error "Cannot find end of insertion region"))
10683 (beginning-of-line 1)
10684 (delete-region beg (point))
10685 (goto-char beg)
10686 (insert txt "\n"))
10687 (message "Table converted and installed at receiver location"))))
10689 (defun org-remove-by-index (list indices &optional i0)
10690 "Remove the elements in LIST with indices in INDICES.
10691 First element has index 0, or I0 if given."
10692 (if (not indices)
10693 list
10694 (if (integerp indices) (setq indices (list indices)))
10695 (setq i0 (1- (or i0 0)))
10696 (delq :rm (mapcar (lambda (x)
10697 (setq i0 (1+ i0))
10698 (if (memq i0 indices) :rm x))
10699 list))))
10701 (defun orgtbl-toggle-comment ()
10702 "Comment or uncomment the orgtbl at point."
10703 (interactive)
10704 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
10705 (re2 (concat "^" orgtbl-line-start-regexp))
10706 (commented (save-excursion (beginning-of-line 1)
10707 (cond ((looking-at re1) t)
10708 ((looking-at re2) nil)
10709 (t (error "Not at an org table")))))
10710 (re (if commented re1 re2))
10711 beg end)
10712 (save-excursion
10713 (beginning-of-line 1)
10714 (while (looking-at re) (beginning-of-line 0))
10715 (beginning-of-line 2)
10716 (setq beg (point))
10717 (while (looking-at re) (beginning-of-line 2))
10718 (setq end (point)))
10719 (comment-region beg end (if commented '(4) nil))))
10721 (defun orgtbl-insert-radio-table ()
10722 "Insert a radio table template appropriate for this major mode."
10723 (interactive)
10724 (let* ((e (assq major-mode orgtbl-radio-table-templates))
10725 (txt (nth 1 e))
10726 name pos)
10727 (unless e (error "No radio table setup defined for %s" major-mode))
10728 (setq name (read-string "Table name: "))
10729 (while (string-match "%n" txt)
10730 (setq txt (replace-match name t t txt)))
10731 (or (bolp) (insert "\n"))
10732 (setq pos (point))
10733 (insert txt)
10734 (goto-char pos)))
10736 (defun org-get-param (params header i sym &optional hsym)
10737 "Get parameter value for symbol SYM.
10738 If this is a header line, actually get the value for the symbol with an
10739 additional \"h\" inserted after the colon.
10740 If the value is a protperty list, get the element for the current column.
10741 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
10742 (let ((val (plist-get params sym)))
10743 (and hsym header (setq val (or (plist-get params hsym) val)))
10744 (if (consp val) (plist-get val i) val)))
10746 (defun orgtbl-to-generic (table params)
10747 "Convert the orgtbl-mode TABLE to some other format.
10748 This generic routine can be used for many standard cases.
10749 TABLE is a list, each entry either the symbol `hline' for a horizontal
10750 separator line, or a list of fields for that line.
10751 PARAMS is a property list of parameters that can influence the conversion.
10752 For the generic converter, some parameters are obligatory: You need to
10753 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
10754 :splice, you must have :tstart and :tend.
10756 Valid parameters are
10758 :tstart String to start the table. Ignored when :splice is t.
10759 :tend String to end the table. Ignored when :splice is t.
10761 :splice When set to t, return only table body lines, don't wrap
10762 them into :tstart and :tend. Default is nil.
10764 :hline String to be inserted on horizontal separation lines.
10765 May be nil to ignore hlines.
10767 :lstart String to start a new table line.
10768 :lend String to end a table line
10769 :sep Separator between two fields
10770 :lfmt Format for entire line, with enough %s to capture all fields.
10771 If this is present, :lstart, :lend, and :sep are ignored.
10772 :fmt A format to be used to wrap the field, should contain
10773 %s for the original field value. For example, to wrap
10774 everything in dollars, you could use :fmt \"$%s$\".
10775 This may also be a property list with column numbers and
10776 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10778 :hlstart :hlend :hlsep :hlfmt :hfmt
10779 Same as above, specific for the header lines in the table.
10780 All lines before the first hline are treated as header.
10781 If any of these is not present, the data line value is used.
10783 :efmt Use this format to print numbers with exponentials.
10784 The format should have %s twice for inserting mantissa
10785 and exponent, for example \"%s\\\\times10^{%s}\". This
10786 may also be a property list with column numbers and
10787 formats. :fmt will still be applied after :efmt.
10789 In addition to this, the parameters :skip and :skipcols are always handled
10790 directly by `orgtbl-send-table'. See manual."
10791 (interactive)
10792 (let* ((p params)
10793 (splicep (plist-get p :splice))
10794 (hline (plist-get p :hline))
10795 rtn line i fm efm lfmt h)
10797 ;; Do we have a header?
10798 (if (and (not splicep) (listp (car table)) (memq 'hline table))
10799 (setq h t))
10801 ;; Put header
10802 (unless splicep
10803 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
10805 ;; Now loop over all lines
10806 (while (setq line (pop table))
10807 (if (eq line 'hline)
10808 ;; A horizontal separator line
10809 (progn (if hline (push hline rtn))
10810 (setq h nil)) ; no longer in header
10811 ;; A normal line. Convert the fields, push line onto the result list
10812 (setq i 0)
10813 (setq line
10814 (mapcar
10815 (lambda (f)
10816 (setq i (1+ i)
10817 fm (org-get-param p h i :fmt :hfmt)
10818 efm (org-get-param p h i :efmt))
10819 (if (and efm (string-match orgtbl-exp-regexp f))
10820 (setq f (format
10821 efm (match-string 1 f) (match-string 2 f))))
10822 (if fm (setq f (format fm f)))
10824 line))
10825 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
10826 (push (apply 'format lfmt line) rtn)
10827 (push (concat
10828 (org-get-param p h i :lstart :hlstart)
10829 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
10830 (org-get-param p h i :lend :hlend))
10831 rtn))))
10833 (unless splicep
10834 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
10836 (mapconcat 'identity (nreverse rtn) "\n")))
10838 (defun orgtbl-to-latex (table params)
10839 "Convert the orgtbl-mode TABLE to LaTeX.
10840 TABLE is a list, each entry either the symbol `hline' for a horizontal
10841 separator line, or a list of fields for that line.
10842 PARAMS is a property list of parameters that can influence the conversion.
10843 Supports all parameters from `orgtbl-to-generic'. Most important for
10844 LaTeX are:
10846 :splice When set to t, return only table body lines, don't wrap
10847 them into a tabular environment. Default is nil.
10849 :fmt A format to be used to wrap the field, should contain %s for the
10850 original field value. For example, to wrap everything in dollars,
10851 use :fmt \"$%s$\". This may also be a property list with column
10852 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10854 :efmt Format for transforming numbers with exponentials. The format
10855 should have %s twice for inserting mantissa and exponent, for
10856 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
10857 This may also be a property list with column numbers and formats.
10859 The general parameters :skip and :skipcols have already been applied when
10860 this function is called."
10861 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
10862 org-table-last-alignment ""))
10863 (params2
10864 (list
10865 :tstart (concat "\\begin{tabular}{" alignment "}")
10866 :tend "\\end{tabular}"
10867 :lstart "" :lend " \\\\" :sep " & "
10868 :efmt "%s\\,(%s)" :hline "\\hline")))
10869 (orgtbl-to-generic table (org-combine-plists params2 params))))
10871 (defun orgtbl-to-html (table params)
10872 "Convert the orgtbl-mode TABLE to LaTeX.
10873 TABLE is a list, each entry either the symbol `hline' for a horizontal
10874 separator line, or a list of fields for that line.
10875 PARAMS is a property list of parameters that can influence the conversion.
10876 Currently this function recognizes the following parameters:
10878 :splice When set to t, return only table body lines, don't wrap
10879 them into a <table> environment. Default is nil.
10881 The general parameters :skip and :skipcols have already been applied when
10882 this function is called. The function does *not* use `orgtbl-to-generic',
10883 so you cannot specify parameters for it."
10884 (let* ((splicep (plist-get params :splice))
10885 html)
10886 ;; Just call the formatter we already have
10887 ;; We need to make text lines for it, so put the fields back together.
10888 (setq html (org-format-org-table-html
10889 (mapcar
10890 (lambda (x)
10891 (if (eq x 'hline)
10892 "|----+----|"
10893 (concat "| " (mapconcat 'identity x " | ") " |")))
10894 table)
10895 splicep))
10896 (if (string-match "\n+\\'" html)
10897 (setq html (replace-match "" t t html)))
10898 html))
10900 (defun orgtbl-to-texinfo (table params)
10901 "Convert the orgtbl-mode TABLE to TeXInfo.
10902 TABLE is a list, each entry either the symbol `hline' for a horizontal
10903 separator line, or a list of fields for that line.
10904 PARAMS is a property list of parameters that can influence the conversion.
10905 Supports all parameters from `orgtbl-to-generic'. Most important for
10906 TeXInfo are:
10908 :splice nil/t When set to t, return only table body lines, don't wrap
10909 them into a multitable environment. Default is nil.
10911 :fmt fmt A format to be used to wrap the field, should contain
10912 %s for the original field value. For example, to wrap
10913 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
10914 This may also be a property list with column numbers and
10915 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
10917 :cf \"f1 f2..\" The column fractions for the table. Bye default these
10918 are computed automatically from the width of the columns
10919 under org-mode.
10921 The general parameters :skip and :skipcols have already been applied when
10922 this function is called."
10923 (let* ((total (float (apply '+ org-table-last-column-widths)))
10924 (colfrac (or (plist-get params :cf)
10925 (mapconcat
10926 (lambda (x) (format "%.3f" (/ (float x) total)))
10927 org-table-last-column-widths " ")))
10928 (params2
10929 (list
10930 :tstart (concat "@multitable @columnfractions " colfrac)
10931 :tend "@end multitable"
10932 :lstart "@item " :lend "" :sep " @tab "
10933 :hlstart "@headitem ")))
10934 (orgtbl-to-generic table (org-combine-plists params2 params))))
10936 ;;;; Link Stuff
10938 ;;; Link abbreviations
10940 (defun org-link-expand-abbrev (link)
10941 "Apply replacements as defined in `org-link-abbrev-alist."
10942 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
10943 (let* ((key (match-string 1 link))
10944 (as (or (assoc key org-link-abbrev-alist-local)
10945 (assoc key org-link-abbrev-alist)))
10946 (tag (and (match-end 2) (match-string 3 link)))
10947 rpl)
10948 (if (not as)
10949 link
10950 (setq rpl (cdr as))
10951 (cond
10952 ((symbolp rpl) (funcall rpl tag))
10953 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
10954 (t (concat rpl tag)))))
10955 link))
10957 ;;; Storing and inserting links
10959 (defvar org-insert-link-history nil
10960 "Minibuffer history for links inserted with `org-insert-link'.")
10962 (defvar org-stored-links nil
10963 "Contains the links stored with `org-store-link'.")
10965 (defvar org-store-link-plist nil
10966 "Plist with info about the most recently link created with `org-store-link'.")
10968 (defvar org-link-protocols nil
10969 "Link protocols added to Org-mode using `org-add-link-type'.")
10971 (defvar org-store-link-functions nil
10972 "List of functions that are called to create and store a link.
10973 Each function will be called in turn until one returns a non-nil
10974 value. Each function should check if it is responsible for creating
10975 this link (for example by looking at the major mode).
10976 If not, it must exit and return nil.
10977 If yes, it should return a non-nil value after a calling
10978 `org-store-link-properties' with a list of properties and values.
10979 Special properties are:
10981 :type The link prefix. like \"http\". This must be given.
10982 :link The link, like \"http://www.astro.uva.nl/~dominik\".
10983 This is obligatory as well.
10984 :description Optional default description for the second pair
10985 of brackets in an Org-mode link. The user can still change
10986 this when inserting this link into an Org-mode buffer.
10988 In addition to these, any additional properties can be specified
10989 and then used in remember templates.")
10991 (defun org-add-link-type (type &optional follow publish)
10992 "Add TYPE to the list of `org-link-types'.
10993 Re-compute all regular expressions depending on `org-link-types'
10994 FOLLOW and PUBLISH are two functions. Both take the link path as
10995 an argument.
10996 FOLLOW should do whatever is necessary to follow the link, for example
10997 to find a file or display a mail message.
10998 PUBLISH takes the path and retuns the string that should be used when
10999 this document is published."
11000 (add-to-list 'org-link-types type t)
11001 (org-make-link-regexps)
11002 (add-to-list 'org-link-protocols
11003 (list type follow publish)))
11005 (defun org-add-agenda-custom-command (entry)
11006 "Replace or add a command in `org-agenda-custom-commands'.
11007 This is mostly for hacking and trying a new command - once the command
11008 works you probably want to add it to `org-agenda-custom-commands' for good."
11009 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11010 (if ass
11011 (setcdr ass (cdr entry))
11012 (push entry org-agenda-custom-commands))))
11014 ;;;###autoload
11015 (defun org-store-link (arg)
11016 "\\<org-mode-map>Store an org-link to the current location.
11017 This link can later be inserted into an org-buffer with
11018 \\[org-insert-link].
11019 For some link types, a prefix arg is interpreted:
11020 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11021 For file links, arg negates `org-context-in-file-links'."
11022 (interactive "P")
11023 (setq org-store-link-plist nil) ; reset
11024 (let (link cpltxt desc description search txt)
11025 (cond
11027 ((run-hook-with-args-until-success 'org-store-link-functions)
11028 (setq link (plist-get org-store-link-plist :link)
11029 desc (or (plist-get org-store-link-plist :description) link)))
11031 ((eq major-mode 'bbdb-mode)
11032 (let ((name (bbdb-record-name (bbdb-current-record)))
11033 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11034 (setq cpltxt (concat "bbdb:" (or name company))
11035 link (org-make-link cpltxt))
11036 (org-store-link-props :type "bbdb" :name name :company company)))
11038 ((eq major-mode 'Info-mode)
11039 (setq link (org-make-link "info:"
11040 (file-name-nondirectory Info-current-file)
11041 ":" Info-current-node))
11042 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11043 ":" Info-current-node))
11044 (org-store-link-props :type "info" :file Info-current-file
11045 :node Info-current-node))
11047 ((eq major-mode 'calendar-mode)
11048 (let ((cd (calendar-cursor-to-date)))
11049 (setq link
11050 (format-time-string
11051 (car org-time-stamp-formats)
11052 (apply 'encode-time
11053 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11054 nil nil nil))))
11055 (org-store-link-props :type "calendar" :date cd)))
11057 ((or (eq major-mode 'vm-summary-mode)
11058 (eq major-mode 'vm-presentation-mode))
11059 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11060 (vm-follow-summary-cursor)
11061 (save-excursion
11062 (vm-select-folder-buffer)
11063 (let* ((message (car vm-message-pointer))
11064 (folder buffer-file-name)
11065 (subject (vm-su-subject message))
11066 (to (vm-get-header-contents message "To"))
11067 (from (vm-get-header-contents message "From"))
11068 (message-id (vm-su-message-id message)))
11069 (org-store-link-props :type "vm" :from from :to to :subject subject
11070 :message-id message-id)
11071 (setq message-id (org-remove-angle-brackets message-id))
11072 (setq folder (abbreviate-file-name folder))
11073 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11074 folder)
11075 (setq folder (replace-match "" t t folder)))
11076 (setq cpltxt (org-email-link-description))
11077 (setq link (org-make-link "vm:" folder "#" message-id)))))
11079 ((eq major-mode 'wl-summary-mode)
11080 (let* ((msgnum (wl-summary-message-number))
11081 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11082 msgnum 'message-id))
11083 (wl-message-entity
11084 (if (fboundp 'elmo-message-entity)
11085 (elmo-message-entity
11086 wl-summary-buffer-elmo-folder msgnum)
11087 (elmo-msgdb-overview-get-entity
11088 msgnum (wl-summary-buffer-msgdb))))
11089 (from (wl-summary-line-from))
11090 (to (elmo-message-entity-field wl-message-entity 'to))
11091 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11092 (wl-summary-line-subject))))
11093 (org-store-link-props :type "wl" :from from :to to
11094 :subject subject :message-id message-id)
11095 (setq message-id (org-remove-angle-brackets message-id))
11096 (setq cpltxt (org-email-link-description))
11097 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11098 "#" message-id))))
11100 ((or (equal major-mode 'mh-folder-mode)
11101 (equal major-mode 'mh-show-mode))
11102 (let ((from (org-mhe-get-header "From:"))
11103 (to (org-mhe-get-header "To:"))
11104 (message-id (org-mhe-get-header "Message-Id:"))
11105 (subject (org-mhe-get-header "Subject:")))
11106 (org-store-link-props :type "mh" :from from :to to
11107 :subject subject :message-id message-id)
11108 (setq cpltxt (org-email-link-description))
11109 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11110 (org-remove-angle-brackets message-id)))))
11112 ((eq major-mode 'rmail-mode)
11113 (save-excursion
11114 (save-restriction
11115 (rmail-narrow-to-non-pruned-header)
11116 (let ((folder buffer-file-name)
11117 (message-id (mail-fetch-field "message-id"))
11118 (from (mail-fetch-field "from"))
11119 (to (mail-fetch-field "to"))
11120 (subject (mail-fetch-field "subject")))
11121 (org-store-link-props
11122 :type "rmail" :from from :to to
11123 :subject subject :message-id message-id)
11124 (setq message-id (org-remove-angle-brackets message-id))
11125 (setq cpltxt (org-email-link-description))
11126 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11128 ((eq major-mode 'gnus-group-mode)
11129 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11130 (gnus-group-group-name)) ; version
11131 ((fboundp 'gnus-group-name)
11132 (gnus-group-name))
11133 (t "???"))))
11134 (unless group (error "Not on a group"))
11135 (org-store-link-props :type "gnus" :group group)
11136 (setq cpltxt (concat
11137 (if (org-xor arg org-usenet-links-prefer-google)
11138 "http://groups.google.com/groups?group="
11139 "gnus:")
11140 group)
11141 link (org-make-link cpltxt))))
11143 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11144 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11145 (let* ((group gnus-newsgroup-name)
11146 (article (gnus-summary-article-number))
11147 (header (gnus-summary-article-header article))
11148 (from (mail-header-from header))
11149 (message-id (mail-header-id header))
11150 (date (mail-header-date header))
11151 (subject (gnus-summary-subject-string)))
11152 (org-store-link-props :type "gnus" :from from :subject subject
11153 :message-id message-id :group group)
11154 (setq cpltxt (org-email-link-description))
11155 (if (org-xor arg org-usenet-links-prefer-google)
11156 (setq link
11157 (concat
11158 cpltxt "\n "
11159 (format "http://groups.google.com/groups?as_umsgid=%s"
11160 (org-fixup-message-id-for-http message-id))))
11161 (setq link (org-make-link "gnus:" group
11162 "#" (number-to-string article))))))
11164 ((eq major-mode 'w3-mode)
11165 (setq cpltxt (url-view-url t)
11166 link (org-make-link cpltxt))
11167 (org-store-link-props :type "w3" :url (url-view-url t)))
11169 ((eq major-mode 'w3m-mode)
11170 (setq cpltxt (or w3m-current-title w3m-current-url)
11171 link (org-make-link w3m-current-url))
11172 (org-store-link-props :type "w3m" :url (url-view-url t)))
11174 ((setq search (run-hook-with-args-until-success
11175 'org-create-file-search-functions))
11176 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11177 "::" search))
11178 (setq cpltxt (or description link)))
11180 ((eq major-mode 'image-mode)
11181 (setq cpltxt (concat "file:"
11182 (abbreviate-file-name buffer-file-name))
11183 link (org-make-link cpltxt))
11184 (org-store-link-props :type "image" :file buffer-file-name))
11186 ((eq major-mode 'dired-mode)
11187 ;; link to the file in the current line
11188 (setq cpltxt (concat "file:"
11189 (abbreviate-file-name
11190 (expand-file-name
11191 (dired-get-filename nil t))))
11192 link (org-make-link cpltxt)))
11194 ((and buffer-file-name (org-mode-p))
11195 ;; Just link to current headline
11196 (setq cpltxt (concat "file:"
11197 (abbreviate-file-name buffer-file-name)))
11198 ;; Add a context search string
11199 (when (org-xor org-context-in-file-links arg)
11200 ;; Check if we are on a target
11201 (if (org-in-regexp "<<\\(.*?\\)>>")
11202 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11203 (setq txt (cond
11204 ((org-on-heading-p) nil)
11205 ((org-region-active-p)
11206 (buffer-substring (region-beginning) (region-end)))
11207 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11208 (when (or (null txt) (string-match "\\S-" txt))
11209 (setq cpltxt
11210 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11211 desc "NONE"))))
11212 (if (string-match "::\\'" cpltxt)
11213 (setq cpltxt (substring cpltxt 0 -2)))
11214 (setq link (org-make-link cpltxt)))
11216 ((buffer-file-name (buffer-base-buffer))
11217 ;; Just link to this file here.
11218 (setq cpltxt (concat "file:"
11219 (abbreviate-file-name
11220 (buffer-file-name (buffer-base-buffer)))))
11221 ;; Add a context string
11222 (when (org-xor org-context-in-file-links arg)
11223 (setq txt (if (org-region-active-p)
11224 (buffer-substring (region-beginning) (region-end))
11225 (buffer-substring (point-at-bol) (point-at-eol))))
11226 ;; Only use search option if there is some text.
11227 (when (string-match "\\S-" txt)
11228 (setq cpltxt
11229 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11230 desc "NONE")))
11231 (setq link (org-make-link cpltxt)))
11233 ((interactive-p)
11234 (error "Cannot link to a buffer which is not visiting a file"))
11236 (t (setq link nil)))
11238 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11239 (setq link (or link cpltxt)
11240 desc (or desc cpltxt))
11241 (if (equal desc "NONE") (setq desc nil))
11243 (if (and (interactive-p) link)
11244 (progn
11245 (setq org-stored-links
11246 (cons (list link desc) org-stored-links))
11247 (message "Stored: %s" (or desc link)))
11248 (and link (org-make-link-string link desc)))))
11250 (defun org-store-link-props (&rest plist)
11251 "Store link properties, extract names and addresses."
11252 (let (x adr)
11253 (when (setq x (plist-get plist :from))
11254 (setq adr (mail-extract-address-components x))
11255 (plist-put plist :fromname (car adr))
11256 (plist-put plist :fromaddress (nth 1 adr)))
11257 (when (setq x (plist-get plist :to))
11258 (setq adr (mail-extract-address-components x))
11259 (plist-put plist :toname (car adr))
11260 (plist-put plist :toaddress (nth 1 adr))))
11261 (let ((from (plist-get plist :from))
11262 (to (plist-get plist :to)))
11263 (when (and from to org-from-is-user-regexp)
11264 (plist-put plist :fromto
11265 (if (string-match org-from-is-user-regexp from)
11266 (concat "to %t")
11267 (concat "from %f")))))
11268 (setq org-store-link-plist plist))
11270 (defun org-email-link-description (&optional fmt)
11271 "Return the description part of an email link.
11272 This takes information from `org-store-link-plist' and formats it
11273 according to FMT (default from `org-email-link-description-format')."
11274 (setq fmt (or fmt org-email-link-description-format))
11275 (let* ((p org-store-link-plist)
11276 (to (plist-get p :toaddress))
11277 (from (plist-get p :fromaddress))
11278 (table
11279 (list
11280 (cons "%c" (plist-get p :fromto))
11281 (cons "%F" (plist-get p :from))
11282 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
11283 (cons "%T" (plist-get p :to))
11284 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
11285 (cons "%s" (plist-get p :subject))
11286 (cons "%m" (plist-get p :message-id)))))
11287 (when (string-match "%c" fmt)
11288 ;; Check if the user wrote this message
11289 (if (and org-from-is-user-regexp from to
11290 (save-match-data (string-match org-from-is-user-regexp from)))
11291 (setq fmt (replace-match "to %t" t t fmt))
11292 (setq fmt (replace-match "from %f" t t fmt))))
11293 (org-replace-escapes fmt table)))
11295 (defun org-make-org-heading-search-string (&optional string heading)
11296 "Make search string for STRING or current headline."
11297 (interactive)
11298 (let ((s (or string (org-get-heading))))
11299 (unless (and string (not heading))
11300 ;; We are using a headline, clean up garbage in there.
11301 (if (string-match org-todo-regexp s)
11302 (setq s (replace-match "" t t s)))
11303 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
11304 (setq s (replace-match "" t t s)))
11305 (setq s (org-trim s))
11306 (if (string-match (concat "^\\(" org-quote-string "\\|"
11307 org-comment-string "\\)") s)
11308 (setq s (replace-match "" t t s)))
11309 (while (string-match org-ts-regexp s)
11310 (setq s (replace-match "" t t s))))
11311 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
11312 (setq s (replace-match " " t t s)))
11313 (or string (setq s (concat "*" s))) ; Add * for headlines
11314 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
11316 (defun org-make-link (&rest strings)
11317 "Concatenate STRINGS."
11318 (apply 'concat strings))
11320 (defun org-make-link-string (link &optional description)
11321 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11322 (unless (string-match "\\S-" link)
11323 (error "Empty link"))
11324 (when (stringp description)
11325 ;; Remove brackets from the description, they are fatal.
11326 (while (string-match "\\[\\|\\]" description)
11327 (setq description (replace-match "" t t description))))
11328 (when (equal (org-link-escape link) description)
11329 ;; No description needed, it is identical
11330 (setq description nil))
11331 (when (and (not description)
11332 (not (equal link (org-link-escape link))))
11333 (setq description link))
11334 (concat "[[" (org-link-escape link) "]"
11335 (if description (concat "[" description "]") "")
11336 "]"))
11338 (defconst org-link-escape-chars
11339 '((" " . "%20")
11340 ("[" . "%5B")
11341 ("]" . "%5d")
11342 ("\340" . "%E0") ; `a
11343 ("\342" . "%E2") ; ^a
11344 ("\347" . "%E7") ; ,c
11345 ("\350" . "%E8") ; `e
11346 ("\351" . "%E9") ; 'e
11347 ("\352" . "%EA") ; ^e
11348 ("\356" . "%EE") ; ^i
11349 ("\364" . "%F4") ; ^o
11350 ("\371" . "%F9") ; `u
11351 ("\373" . "%FB") ; ^u
11352 (";" . "%3B")
11353 ("?" . "%3F")
11354 ("=" . "%3D")
11355 ("+" . "%2B")
11357 "Association list of escapes for some characters problematic in links.
11358 This is the list that is used for internal purposes.")
11360 (defconst org-link-escape-chars-browser
11361 '((" " . "%20"))
11362 "Association list of escapes for some characters problematic in links.
11363 This is the list that is used before handing over to the browser.")
11365 (defun org-link-escape (text &optional table)
11366 "Escape charaters in TEXT that are problematic for links."
11367 (setq table (or table org-link-escape-chars))
11368 (when text
11369 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
11370 table "\\|")))
11371 (while (string-match re text)
11372 (setq text
11373 (replace-match
11374 (cdr (assoc (match-string 0 text) table))
11375 t t text)))
11376 text)))
11378 (defun org-link-unescape (text &optional table)
11379 "Reverse the action of `org-link-escape'."
11380 (setq table (or table org-link-escape-chars))
11381 (when text
11382 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
11383 table "\\|")))
11384 (while (string-match re text)
11385 (setq text
11386 (replace-match
11387 (car (rassoc (match-string 0 text) table))
11388 t t text)))
11389 text)))
11391 (defun org-xor (a b)
11392 "Exclusive or."
11393 (if a (not b) b))
11395 (defun org-get-header (header)
11396 "Find a header field in the current buffer."
11397 (save-excursion
11398 (goto-char (point-min))
11399 (let ((case-fold-search t) s)
11400 (cond
11401 ((eq header 'from)
11402 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11403 (setq s (match-string 1)))
11404 (while (string-match "\"" s)
11405 (setq s (replace-match "" t t s)))
11406 (if (string-match "[<(].*" s)
11407 (setq s (replace-match "" t t s))))
11408 ((eq header 'message-id)
11409 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11410 (setq s (match-string 1))))
11411 ((eq header 'subject)
11412 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11413 (setq s (match-string 1)))))
11414 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11415 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11416 s)))
11419 (defun org-fixup-message-id-for-http (s)
11420 "Replace special characters in a message id, so it can be used in an http query."
11421 (while (string-match "<" s)
11422 (setq s (replace-match "%3C" t t s)))
11423 (while (string-match ">" s)
11424 (setq s (replace-match "%3E" t t s)))
11425 (while (string-match "@" s)
11426 (setq s (replace-match "%40" t t s)))
11429 ;;;###autoload
11430 (defun org-insert-link-global ()
11431 "Insert a link like Org-mode does.
11432 This command can be called in any mode to insert a link in Org-mode syntax."
11433 (interactive)
11434 (org-run-like-in-org-mode 'org-insert-link))
11436 (defun org-insert-link (&optional complete-file)
11437 "Insert a link. At the prompt, enter the link.
11439 Completion can be used to select a link previously stored with
11440 `org-store-link'. When the empty string is entered (i.e. if you just
11441 press RET at the prompt), the link defaults to the most recently
11442 stored link. As SPC triggers completion in the minibuffer, you need to
11443 use M-SPC or C-q SPC to force the insertion of a space character.
11445 You will also be prompted for a description, and if one is given, it will
11446 be displayed in the buffer instead of the link.
11448 If there is already a link at point, this command will allow you to edit link
11449 and description parts.
11451 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11452 selected using completion. The path to the file will be relative to
11453 the current directory if the file is in the current directory or a
11454 subdirectory. Otherwise, the link will be the absolute path as
11455 completed in the minibuffer (i.e. normally ~/path/to/file).
11457 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11458 is in the current directory or below.
11459 With three \\[universal-argument] prefixes, negate the meaning of
11460 `org-keep-stored-link-after-insertion'."
11461 (interactive "P")
11462 (let* ((wcf (current-window-configuration))
11463 (region (if (org-region-active-p)
11464 (buffer-substring (region-beginning) (region-end))))
11465 (remove (and region (list (region-beginning) (region-end))))
11466 (desc region)
11467 tmphist ; byte-compile incorrectly complains about this
11468 link entry file)
11469 (cond
11470 ((org-in-regexp org-bracket-link-regexp 1)
11471 ;; We do have a link at point, and we are going to edit it.
11472 (setq remove (list (match-beginning 0) (match-end 0)))
11473 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11474 (setq link (read-string "Link: "
11475 (org-link-unescape
11476 (org-match-string-no-properties 1)))))
11477 ((or (org-in-regexp org-angle-link-re)
11478 (org-in-regexp org-plain-link-re))
11479 ;; Convert to bracket link
11480 (setq remove (list (match-beginning 0) (match-end 0))
11481 link (read-string "Link: "
11482 (org-remove-angle-brackets (match-string 0)))))
11483 ((equal complete-file '(4))
11484 ;; Completing read for file names.
11485 (setq file (read-file-name "File: "))
11486 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11487 (pwd1 (file-name-as-directory (abbreviate-file-name
11488 (expand-file-name ".")))))
11489 (cond
11490 ((equal complete-file '(16))
11491 (setq link (org-make-link
11492 "file:"
11493 (abbreviate-file-name (expand-file-name file)))))
11494 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11495 (setq link (org-make-link "file:" (match-string 1 file))))
11496 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11497 (expand-file-name file))
11498 (setq link (org-make-link
11499 "file:" (match-string 1 (expand-file-name file)))))
11500 (t (setq link (org-make-link "file:" file))))))
11502 ;; Read link, with completion for stored links.
11503 (with-output-to-temp-buffer "*Org Links*"
11504 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
11505 (when org-stored-links
11506 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
11507 (princ (mapconcat
11508 (lambda (x)
11509 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
11510 (reverse org-stored-links) "\n"))))
11511 (let ((cw (selected-window)))
11512 (select-window (get-buffer-window "*Org Links*"))
11513 (shrink-window-if-larger-than-buffer)
11514 (setq truncate-lines t)
11515 (select-window cw))
11516 ;; Fake a link history, containing the stored links.
11517 (setq tmphist (append (mapcar 'car org-stored-links)
11518 org-insert-link-history))
11519 (unwind-protect
11520 (setq link (org-completing-read
11521 "Link: "
11522 (append
11523 (mapcar (lambda (x) (list (concat (car x) ":")))
11524 (append org-link-abbrev-alist-local org-link-abbrev-alist))
11525 (mapcar (lambda (x) (list (concat x ":")))
11526 org-link-types))
11527 nil nil nil
11528 'tmphist
11529 (or (car (car org-stored-links)))))
11530 (set-window-configuration wcf)
11531 (kill-buffer "*Org Links*"))
11532 (setq entry (assoc link org-stored-links))
11533 (or entry (push link org-insert-link-history))
11534 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11535 (not org-keep-stored-link-after-insertion))
11536 (setq org-stored-links (delq (assoc link org-stored-links)
11537 org-stored-links)))
11538 (setq desc (or desc (nth 1 entry)))))
11540 (if (string-match org-plain-link-re link)
11541 ;; URL-like link, normalize the use of angular brackets.
11542 (setq link (org-make-link (org-remove-angle-brackets link))))
11544 ;; Check if we are linking to the current file with a search option
11545 ;; If yes, simplify the link by using only the search option.
11546 (when (and buffer-file-name
11547 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11548 (let* ((path (match-string 1 link))
11549 (case-fold-search nil)
11550 (search (match-string 2 link)))
11551 (save-match-data
11552 (if (equal (file-truename buffer-file-name) (file-truename path))
11553 ;; We are linking to this same file, with a search option
11554 (setq link search)))))
11556 ;; Check if we can/should use a relative path. If yes, simplify the link
11557 (when (string-match "\\<file:\\(.*\\)" link)
11558 (let* ((path (match-string 1 link))
11559 (origpath path)
11560 (desc-is-link (equal link desc))
11561 (case-fold-search nil))
11562 (cond
11563 ((eq org-link-file-path-type 'absolute)
11564 (setq path (abbreviate-file-name (expand-file-name path))))
11565 ((eq org-link-file-path-type 'noabbrev)
11566 (setq path (expand-file-name path)))
11567 ((eq org-link-file-path-type 'relative)
11568 (setq path (file-relative-name path)))
11570 (save-match-data
11571 (if (string-match (concat "^" (regexp-quote
11572 (file-name-as-directory
11573 (expand-file-name "."))))
11574 (expand-file-name path))
11575 ;; We are linking a file with relative path name.
11576 (setq path (substring (expand-file-name path)
11577 (match-end 0)))))))
11578 (setq link (concat "file:" path))
11579 (if (equal desc origpath)
11580 (setq desc path))))
11582 (setq desc (read-string "Description: " desc))
11583 (unless (string-match "\\S-" desc) (setq desc nil))
11584 (if remove (apply 'delete-region remove))
11585 (insert (org-make-link-string link desc))))
11587 (defun org-completing-read (&rest args)
11588 (let ((minibuffer-local-completion-map
11589 (copy-keymap minibuffer-local-completion-map)))
11590 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
11591 (apply 'completing-read args)))
11593 ;;; Opening/following a link
11594 (defvar org-link-search-failed nil)
11596 (defun org-next-link ()
11597 "Move forward to the next link.
11598 If the link is in hidden text, expose it."
11599 (interactive)
11600 (when (and org-link-search-failed (eq this-command last-command))
11601 (goto-char (point-min))
11602 (message "Link search wrapped back to beginning of buffer"))
11603 (setq org-link-search-failed nil)
11604 (let* ((pos (point))
11605 (ct (org-context))
11606 (a (assoc :link ct)))
11607 (if a (goto-char (nth 2 a)))
11608 (if (re-search-forward org-any-link-re nil t)
11609 (progn
11610 (goto-char (match-beginning 0))
11611 (if (org-invisible-p) (org-show-context)))
11612 (goto-char pos)
11613 (setq org-link-search-failed t)
11614 (error "No further link found"))))
11616 (defun org-previous-link ()
11617 "Move backward to the previous link.
11618 If the link is in hidden text, expose it."
11619 (interactive)
11620 (when (and org-link-search-failed (eq this-command last-command))
11621 (goto-char (point-max))
11622 (message "Link search wrapped back to end of buffer"))
11623 (setq org-link-search-failed nil)
11624 (let* ((pos (point))
11625 (ct (org-context))
11626 (a (assoc :link ct)))
11627 (if a (goto-char (nth 1 a)))
11628 (if (re-search-backward org-any-link-re nil t)
11629 (progn
11630 (goto-char (match-beginning 0))
11631 (if (org-invisible-p) (org-show-context)))
11632 (goto-char pos)
11633 (setq org-link-search-failed t)
11634 (error "No further link found"))))
11636 (defun org-find-file-at-mouse (ev)
11637 "Open file link or URL at mouse."
11638 (interactive "e")
11639 (mouse-set-point ev)
11640 (org-open-at-point 'in-emacs))
11642 (defun org-open-at-mouse (ev)
11643 "Open file link or URL at mouse."
11644 (interactive "e")
11645 (mouse-set-point ev)
11646 (org-open-at-point))
11648 (defvar org-window-config-before-follow-link nil
11649 "The window configuration before following a link.
11650 This is saved in case the need arises to restore it.")
11652 (defvar org-open-link-marker (make-marker)
11653 "Marker pointing to the location where `org-open-at-point; was called.")
11655 ;;;###autoload
11656 (defun org-open-at-point-global ()
11657 "Follow a link like Org-mode does.
11658 This command can be called in any mode to follow a link that has
11659 Org-mode syntax."
11660 (interactive)
11661 (org-run-like-in-org-mode 'org-open-at-point))
11663 (defun org-open-at-point (&optional in-emacs)
11664 "Open link at or after point.
11665 If there is no link at point, this function will search forward up to
11666 the end of the current subtree.
11667 Normally, files will be opened by an appropriate application. If the
11668 optional argument IN-EMACS is non-nil, Emacs will visit the file."
11669 (interactive "P")
11670 (move-marker org-open-link-marker (point))
11671 (setq org-window-config-before-follow-link (current-window-configuration))
11672 (org-remove-occur-highlights nil nil t)
11673 (if (org-at-timestamp-p t)
11674 (org-follow-timestamp-link)
11675 (let (type path link line search (pos (point)))
11676 (catch 'match
11677 (save-excursion
11678 (skip-chars-forward "^]\n\r")
11679 (when (org-in-regexp org-bracket-link-regexp)
11680 (setq link (org-link-unescape (org-match-string-no-properties 1)))
11681 (while (string-match " *\n *" link)
11682 (setq link (replace-match " " t t link)))
11683 (setq link (org-link-expand-abbrev link))
11684 (if (string-match org-link-re-with-space2 link)
11685 (setq type (match-string 1 link) path (match-string 2 link))
11686 (setq type "thisfile" path link))
11687 (throw 'match t)))
11689 (when (get-text-property (point) 'org-linked-text)
11690 (setq type "thisfile"
11691 pos (if (get-text-property (1+ (point)) 'org-linked-text)
11692 (1+ (point)) (point))
11693 path (buffer-substring
11694 (previous-single-property-change pos 'org-linked-text)
11695 (next-single-property-change pos 'org-linked-text)))
11696 (throw 'match t))
11698 (save-excursion
11699 (when (or (org-in-regexp org-angle-link-re)
11700 (org-in-regexp org-plain-link-re))
11701 (setq type (match-string 1) path (match-string 2))
11702 (throw 'match t)))
11703 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
11704 (setq type "tree-match"
11705 path (match-string 1))
11706 (throw 'match t))
11707 (save-excursion
11708 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
11709 (setq type "tags"
11710 path (match-string 1))
11711 (while (string-match ":" path)
11712 (setq path (replace-match "+" t t path)))
11713 (throw 'match t))))
11714 (unless path
11715 (error "No link found"))
11716 ;; Remove any trailing spaces in path
11717 (if (string-match " +\\'" path)
11718 (setq path (replace-match "" t t path)))
11720 (cond
11722 ((assoc type org-link-protocols)
11723 (funcall (nth 1 (assoc type org-link-protocols)) path))
11725 ((equal type "mailto")
11726 (let ((cmd (car org-link-mailto-program))
11727 (args (cdr org-link-mailto-program)) args1
11728 (address path) (subject "") a)
11729 (if (string-match "\\(.*\\)::\\(.*\\)" path)
11730 (setq address (match-string 1 path)
11731 subject (org-link-escape (match-string 2 path))))
11732 (while args
11733 (cond
11734 ((not (stringp (car args))) (push (pop args) args1))
11735 (t (setq a (pop args))
11736 (if (string-match "%a" a)
11737 (setq a (replace-match address t t a)))
11738 (if (string-match "%s" a)
11739 (setq a (replace-match subject t t a)))
11740 (push a args1))))
11741 (apply cmd (nreverse args1))))
11743 ((member type '("http" "https" "ftp" "news"))
11744 (browse-url (concat type ":" (org-link-escape
11745 path org-link-escape-chars-browser))))
11747 ((string= type "tags")
11748 (org-tags-view in-emacs path))
11749 ((string= type "thisfile")
11750 (if in-emacs
11751 (switch-to-buffer-other-window
11752 (org-get-buffer-for-internal-link (current-buffer)))
11753 (org-mark-ring-push))
11754 (let ((cmd `(org-link-search
11755 ,path
11756 ,(cond ((equal in-emacs '(4)) 'occur)
11757 ((equal in-emacs '(16)) 'org-occur)
11758 (t nil))
11759 ,pos)))
11760 (condition-case nil (eval cmd)
11761 (error (progn (widen) (eval cmd))))))
11763 ((string= type "tree-match")
11764 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
11766 ((string= type "file")
11767 (if (string-match "::\\([0-9]+\\)\\'" path)
11768 (setq line (string-to-number (match-string 1 path))
11769 path (substring path 0 (match-beginning 0)))
11770 (if (string-match "::\\(.+\\)\\'" path)
11771 (setq search (match-string 1 path)
11772 path (substring path 0 (match-beginning 0)))))
11773 (org-open-file path in-emacs line search))
11775 ((string= type "news")
11776 (org-follow-gnus-link path))
11778 ((string= type "bbdb")
11779 (org-follow-bbdb-link path))
11781 ((string= type "info")
11782 (org-follow-info-link path))
11784 ((string= type "gnus")
11785 (let (group article)
11786 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11787 (error "Error in Gnus link"))
11788 (setq group (match-string 1 path)
11789 article (match-string 3 path))
11790 (org-follow-gnus-link group article)))
11792 ((string= type "vm")
11793 (let (folder article)
11794 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11795 (error "Error in VM link"))
11796 (setq folder (match-string 1 path)
11797 article (match-string 3 path))
11798 ;; in-emacs is the prefix arg, will be interpreted as read-only
11799 (org-follow-vm-link folder article in-emacs)))
11801 ((string= type "wl")
11802 (let (folder article)
11803 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11804 (error "Error in Wanderlust link"))
11805 (setq folder (match-string 1 path)
11806 article (match-string 3 path))
11807 (org-follow-wl-link folder article)))
11809 ((string= type "mhe")
11810 (let (folder article)
11811 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11812 (error "Error in MHE link"))
11813 (setq folder (match-string 1 path)
11814 article (match-string 3 path))
11815 (org-follow-mhe-link folder article)))
11817 ((string= type "rmail")
11818 (let (folder article)
11819 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11820 (error "Error in RMAIL link"))
11821 (setq folder (match-string 1 path)
11822 article (match-string 3 path))
11823 (org-follow-rmail-link folder article)))
11825 ((string= type "shell")
11826 (let ((cmd path))
11827 ;; The following is only for backward compatibility
11828 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
11829 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
11830 (if (or (not org-confirm-shell-link-function)
11831 (funcall org-confirm-shell-link-function
11832 (format "Execute \"%s\" in shell? "
11833 (org-add-props cmd nil
11834 'face 'org-warning))))
11835 (progn
11836 (message "Executing %s" cmd)
11837 (shell-command cmd))
11838 (error "Abort"))))
11840 ((string= type "elisp")
11841 (let ((cmd path))
11842 (if (or (not org-confirm-elisp-link-function)
11843 (funcall org-confirm-elisp-link-function
11844 (format "Execute \"%s\" as elisp? "
11845 (org-add-props cmd nil
11846 'face 'org-warning))))
11847 (message "%s => %s" cmd (eval (read cmd)))
11848 (error "Abort"))))
11851 (browse-url-at-point)))))
11852 (move-marker org-open-link-marker nil))
11855 ;;; File search
11857 (defvar org-create-file-search-functions nil
11858 "List of functions to construct the right search string for a file link.
11859 These functions are called in turn with point at the location to
11860 which the link should point.
11862 A function in the hook should first test if it would like to
11863 handle this file type, for example by checking the major-mode or
11864 the file extension. If it decides not to handle this file, it
11865 should just return nil to give other functions a chance. If it
11866 does handle the file, it must return the search string to be used
11867 when following the link. The search string will be part of the
11868 file link, given after a double colon, and `org-open-at-point'
11869 will automatically search for it. If special measures must be
11870 taken to make the search successful, another function should be
11871 added to the companion hook `org-execute-file-search-functions',
11872 which see.
11874 A function in this hook may also use `setq' to set the variable
11875 `description' to provide a suggestion for the descriptive text to
11876 be used for this link when it gets inserted into an Org-mode
11877 buffer with \\[org-insert-link].")
11879 (defvar org-execute-file-search-functions nil
11880 "List of functions to execute a file search triggered by a link.
11882 Functions added to this hook must accept a single argument, the
11883 search string that was part of the file link, the part after the
11884 double colon. The function must first check if it would like to
11885 handle this search, for example by checking the major-mode or the
11886 file extension. If it decides not to handle this search, it
11887 should just return nil to give other functions a chance. If it
11888 does handle the search, it must return a non-nil value to keep
11889 other functions from trying.
11891 Each function can access the current prefix argument through the
11892 variable `current-prefix-argument'. Note that a single prefix is
11893 used to force opening a link in Emacs, so it may be good to only
11894 use a numeric or double prefix to guide the search function.
11896 In case this is needed, a function in this hook can also restore
11897 the window configuration before `org-open-at-point' was called using:
11899 (set-window-configuration org-window-config-before-follow-link)")
11901 (defun org-link-search (s &optional type avoid-pos)
11902 "Search for a link search option.
11903 If S is surrounded by forward slashes, it is interpreted as a
11904 regular expression. In org-mode files, this will create an `org-occur'
11905 sparse tree. In ordinary files, `occur' will be used to list matches.
11906 If the current buffer is in `dired-mode', grep will be used to search
11907 in all files. If AVOID-POS is given, ignore matches near that position."
11908 (let ((case-fold-search t)
11909 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
11910 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
11911 (append '(("") (" ") ("\t") ("\n"))
11912 org-emphasis-alist)
11913 "\\|") "\\)"))
11914 (pos (point))
11915 (pre "") (post "")
11916 words re0 re1 re2 re3 re4 re5 re2a reall)
11917 (cond
11918 ;; First check if there are any special
11919 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11920 ;; Now try the builtin stuff
11921 ((save-excursion
11922 (goto-char (point-min))
11923 (and
11924 (re-search-forward
11925 (concat "<<" (regexp-quote s0) ">>") nil t)
11926 (setq pos (match-beginning 0))))
11927 ;; There is an exact target for this
11928 (goto-char pos))
11929 ((string-match "^/\\(.*\\)/$" s)
11930 ;; A regular expression
11931 (cond
11932 ((org-mode-p)
11933 (org-occur (match-string 1 s)))
11934 ;;((eq major-mode 'dired-mode)
11935 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
11936 (t (org-do-occur (match-string 1 s)))))
11938 ;; A normal search strings
11939 (when (equal (string-to-char s) ?*)
11940 ;; Anchor on headlines, post may include tags.
11941 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11942 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
11943 s (substring s 1)))
11944 (remove-text-properties
11945 0 (length s)
11946 '(face nil mouse-face nil keymap nil fontified nil) s)
11947 ;; Make a series of regular expressions to find a match
11948 (setq words (org-split-string s "[ \n\r\t]+")
11949 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11950 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11951 "\\)" markers)
11952 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
11953 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11954 re1 (concat pre re2 post)
11955 re3 (concat pre re4 post)
11956 re5 (concat pre ".*" re4)
11957 re2 (concat pre re2)
11958 re2a (concat pre re2a)
11959 re4 (concat pre re4)
11960 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11961 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11962 re5 "\\)"
11964 (cond
11965 ((eq type 'org-occur) (org-occur reall))
11966 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11967 (t (goto-char (point-min))
11968 (if (or (org-search-not-self 1 re0 nil t)
11969 (org-search-not-self 1 re1 nil t)
11970 (org-search-not-self 1 re2 nil t)
11971 (org-search-not-self 1 re2a nil t)
11972 (org-search-not-self 1 re3 nil t)
11973 (org-search-not-self 1 re4 nil t)
11974 (org-search-not-self 1 re5 nil t)
11976 (goto-char (match-beginning 1))
11977 (goto-char pos)
11978 (error "No match")))))
11980 ;; Normal string-search
11981 (goto-char (point-min))
11982 (if (search-forward s nil t)
11983 (goto-char (match-beginning 0))
11984 (error "No match"))))
11985 (and (org-mode-p) (org-show-context 'link-search))))
11987 (defun org-search-not-self (group &rest args)
11988 "Execute `re-search-forward', but only accept matches that do not
11989 enclose the position of `org-open-link-marker'."
11990 (let ((m org-open-link-marker))
11991 (catch 'exit
11992 (while (apply 're-search-forward args)
11993 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11994 (goto-char (match-end group))
11995 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11996 (> (match-beginning 0) (marker-position m))
11997 (< (match-end 0) (marker-position m)))
11998 (save-match-data
11999 (or (not (org-in-regexp
12000 org-bracket-link-analytic-regexp 1))
12001 (not (match-end 4)) ; no description
12002 (and (<= (match-beginning 4) (point))
12003 (>= (match-end 4) (point))))))
12004 (throw 'exit (point))))))))
12006 (defun org-get-buffer-for-internal-link (buffer)
12007 "Return a buffer to be used for displaying the link target of internal links."
12008 (cond
12009 ((not org-display-internal-link-with-indirect-buffer)
12010 buffer)
12011 ((string-match "(Clone)$" (buffer-name buffer))
12012 (message "Buffer is already a clone, not making another one")
12013 ;; we also do not modify visibility in this case
12014 buffer)
12015 (t ; make a new indirect buffer for displaying the link
12016 (let* ((bn (buffer-name buffer))
12017 (ibn (concat bn "(Clone)"))
12018 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12019 (with-current-buffer ib (org-overview))
12020 ib))))
12022 (defun org-do-occur (regexp &optional cleanup)
12023 "Call the Emacs command `occur'.
12024 If CLEANUP is non-nil, remove the printout of the regular expression
12025 in the *Occur* buffer. This is useful if the regex is long and not useful
12026 to read."
12027 (occur regexp)
12028 (when cleanup
12029 (let ((cwin (selected-window)) win beg end)
12030 (when (setq win (get-buffer-window "*Occur*"))
12031 (select-window win))
12032 (goto-char (point-min))
12033 (when (re-search-forward "match[a-z]+" nil t)
12034 (setq beg (match-end 0))
12035 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12036 (setq end (1- (match-beginning 0)))))
12037 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12038 (goto-char (point-min))
12039 (select-window cwin))))
12041 ;;; The mark ring for links jumps
12043 (defvar org-mark-ring nil
12044 "Mark ring for positions before jumps in Org-mode.")
12045 (defvar org-mark-ring-last-goto nil
12046 "Last position in the mark ring used to go back.")
12047 ;; Fill and close the ring
12048 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12049 (loop for i from 1 to org-mark-ring-length do
12050 (push (make-marker) org-mark-ring))
12051 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12052 org-mark-ring)
12054 (defun org-mark-ring-push (&optional pos buffer)
12055 "Put the current position or POS into the mark ring and rotate it."
12056 (interactive)
12057 (setq pos (or pos (point)))
12058 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12059 (move-marker (car org-mark-ring)
12060 (or pos (point))
12061 (or buffer (current-buffer)))
12062 (message
12063 (substitute-command-keys
12064 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12066 (defun org-mark-ring-goto (&optional n)
12067 "Jump to the previous position in the mark ring.
12068 With prefix arg N, jump back that many stored positions. When
12069 called several times in succession, walk through the entire ring.
12070 Org-mode commands jumping to a different position in the current file,
12071 or to another Org-mode file, automatically push the old position
12072 onto the ring."
12073 (interactive "p")
12074 (let (p m)
12075 (if (eq last-command this-command)
12076 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12077 (setq p org-mark-ring))
12078 (setq org-mark-ring-last-goto p)
12079 (setq m (car p))
12080 (switch-to-buffer (marker-buffer m))
12081 (goto-char m)
12082 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12084 (defun org-remove-angle-brackets (s)
12085 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12086 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12088 (defun org-add-angle-brackets (s)
12089 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12090 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12093 ;;; Following specific links
12095 (defun org-follow-timestamp-link ()
12096 (cond
12097 ((org-at-date-range-p t)
12098 (let ((org-agenda-start-on-weekday)
12099 (t1 (match-string 1))
12100 (t2 (match-string 2)))
12101 (setq t1 (time-to-days (org-time-string-to-time t1))
12102 t2 (time-to-days (org-time-string-to-time t2)))
12103 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12104 ((org-at-timestamp-p t)
12105 (org-agenda-list nil (time-to-days (org-time-string-to-time
12106 (substring (match-string 1) 0 10)))
12108 (t (error "This should not happen"))))
12111 (defun org-follow-bbdb-link (name)
12112 "Follow a BBDB link to NAME."
12113 (require 'bbdb)
12114 (let ((inhibit-redisplay (not debug-on-error))
12115 (bbdb-electric-p nil))
12116 (catch 'exit
12117 ;; Exact match on name
12118 (bbdb-name (concat "\\`" name "\\'") nil)
12119 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12120 ;; Exact match on name
12121 (bbdb-company (concat "\\`" name "\\'") nil)
12122 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12123 ;; Partial match on name
12124 (bbdb-name name nil)
12125 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12126 ;; Partial match on company
12127 (bbdb-company name nil)
12128 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12129 ;; General match including network address and notes
12130 (bbdb name nil)
12131 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12132 (delete-window (get-buffer-window "*BBDB*"))
12133 (error "No matching BBDB record")))))
12135 (defun org-follow-info-link (name)
12136 "Follow an info file & node link to NAME."
12137 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12138 (string-match "\\(.*\\)" name))
12139 (progn
12140 (require 'info)
12141 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12142 (Info-find-node (match-string 1 name) (match-string 2 name))
12143 (Info-find-node (match-string 1 name) "Top")))
12144 (message (concat "Could not open: " name))))
12146 (defun org-follow-gnus-link (&optional group article)
12147 "Follow a Gnus link to GROUP and ARTICLE."
12148 (require 'gnus)
12149 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12150 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12151 (cond ((and group article)
12152 (gnus-group-read-group 1 nil group)
12153 (gnus-summary-goto-article (string-to-number article) nil t))
12154 (group (gnus-group-jump-to-group group))))
12156 (defun org-follow-vm-link (&optional folder article readonly)
12157 "Follow a VM link to FOLDER and ARTICLE."
12158 (require 'vm)
12159 (setq article (org-add-angle-brackets article))
12160 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12161 ;; ange-ftp or efs or tramp access
12162 (let ((user (or (match-string 1 folder) (user-login-name)))
12163 (host (match-string 2 folder))
12164 (file (match-string 3 folder)))
12165 (cond
12166 ((featurep 'tramp)
12167 ;; use tramp to access the file
12168 (if (featurep 'xemacs)
12169 (setq folder (format "[%s@%s]%s" user host file))
12170 (setq folder (format "/%s@%s:%s" user host file))))
12172 ;; use ange-ftp or efs
12173 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12174 (setq folder (format "/%s@%s:%s" user host file))))))
12175 (when folder
12176 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12177 (sit-for 0.1)
12178 (when article
12179 (vm-select-folder-buffer)
12180 (widen)
12181 (let ((case-fold-search t))
12182 (goto-char (point-min))
12183 (if (not (re-search-forward
12184 (concat "^" "message-id: *" (regexp-quote article))))
12185 (error "Could not find the specified message in this folder"))
12186 (vm-isearch-update)
12187 (vm-isearch-narrow)
12188 (vm-beginning-of-message)
12189 (vm-summarize)))))
12191 (defun org-follow-wl-link (folder article)
12192 "Follow a Wanderlust link to FOLDER and ARTICLE."
12193 (if (and (string= folder "%")
12194 article
12195 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12196 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12197 ;; Thus, we recompose folder and article ids.
12198 (setq folder (format "%s#%s" folder (match-string 1 article))
12199 article (match-string 3 article)))
12200 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12201 (error "No such folder: %s" folder))
12202 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12203 (and article
12204 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12205 (wl-summary-redisplay)))
12207 (defun org-follow-rmail-link (folder article)
12208 "Follow an RMAIL link to FOLDER and ARTICLE."
12209 (setq article (org-add-angle-brackets article))
12210 (let (message-number)
12211 (save-excursion
12212 (save-window-excursion
12213 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12214 (setq message-number
12215 (save-restriction
12216 (widen)
12217 (goto-char (point-max))
12218 (if (re-search-backward
12219 (concat "^Message-ID:\\s-+" (regexp-quote
12220 (or article "")))
12221 nil t)
12222 (rmail-what-message))))))
12223 (if message-number
12224 (progn
12225 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12226 (rmail-show-message message-number)
12227 message-number)
12228 (error "Message not found"))))
12230 ;;; mh-e integration based on planner-mode
12231 (defun org-mhe-get-message-real-folder ()
12232 "Return the name of the current message real folder, so if you use
12233 sequences, it will now work."
12234 (save-excursion
12235 (let* ((folder
12236 (if (equal major-mode 'mh-folder-mode)
12237 mh-current-folder
12238 ;; Refer to the show buffer
12239 mh-show-folder-buffer))
12240 (end-index
12241 (if (boundp 'mh-index-folder)
12242 (min (length mh-index-folder) (length folder))))
12244 ;; a simple test on mh-index-data does not work, because
12245 ;; mh-index-data is always nil in a show buffer.
12246 (if (and (boundp 'mh-index-folder)
12247 (string= mh-index-folder (substring folder 0 end-index)))
12248 (if (equal major-mode 'mh-show-mode)
12249 (save-window-excursion
12250 (let (pop-up-frames)
12251 (when (buffer-live-p (get-buffer folder))
12252 (progn
12253 (pop-to-buffer folder)
12254 (org-mhe-get-message-folder-from-index)
12257 (org-mhe-get-message-folder-from-index)
12259 folder
12263 (defun org-mhe-get-message-folder-from-index ()
12264 "Returns the name of the message folder in a index folder buffer."
12265 (save-excursion
12266 (mh-index-previous-folder)
12267 (re-search-forward "^\\(+.*\\)$" nil t)
12268 (message (match-string 1))))
12270 (defun org-mhe-get-message-folder ()
12271 "Return the name of the current message folder. Be careful if you
12272 use sequences."
12273 (save-excursion
12274 (if (equal major-mode 'mh-folder-mode)
12275 mh-current-folder
12276 ;; Refer to the show buffer
12277 mh-show-folder-buffer)))
12279 (defun org-mhe-get-message-num ()
12280 "Return the number of the current message. Be careful if you
12281 use sequences."
12282 (save-excursion
12283 (if (equal major-mode 'mh-folder-mode)
12284 (mh-get-msg-num nil)
12285 ;; Refer to the show buffer
12286 (mh-show-buffer-message-number))))
12288 (defun org-mhe-get-header (header)
12289 "Return a header of the message in folder mode. This will create a
12290 show buffer for the corresponding message. If you have a more clever
12291 idea..."
12292 (let* ((folder (org-mhe-get-message-folder))
12293 (num (org-mhe-get-message-num))
12294 (buffer (get-buffer-create (concat "show-" folder)))
12295 (header-field))
12296 (with-current-buffer buffer
12297 (mh-display-msg num folder)
12298 (if (equal major-mode 'mh-folder-mode)
12299 (mh-header-display)
12300 (mh-show-header-display))
12301 (set-buffer buffer)
12302 (setq header-field (mh-get-header-field header))
12303 (if (equal major-mode 'mh-folder-mode)
12304 (mh-show)
12305 (mh-show-show))
12306 header-field)))
12308 (defun org-follow-mhe-link (folder article)
12309 "Follow an MHE link to FOLDER and ARTICLE.
12310 If ARTICLE is nil FOLDER is shown. If the configuration variable
12311 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
12312 ARTICLE is searched in all folders. Indexed searches (swish++,
12313 namazu, and others supported by MH-E) will always search in all
12314 folders."
12315 (require 'mh-e)
12316 (require 'mh-search)
12317 (require 'mh-utils)
12318 (mh-find-path)
12319 (if (not article)
12320 (mh-visit-folder (mh-normalize-folder-name folder))
12321 (setq article (org-add-angle-brackets article))
12322 (mh-search-choose)
12323 (if (equal mh-searcher 'pick)
12324 (progn
12325 (mh-search folder (list "--message-id" article))
12326 (when (and org-mhe-search-all-folders
12327 (not (org-mhe-get-message-real-folder)))
12328 (kill-this-buffer)
12329 (mh-search "+" (list "--message-id" article))))
12330 (mh-search "+" article))
12331 (if (org-mhe-get-message-real-folder)
12332 (mh-show-msg 1)
12333 (kill-this-buffer)
12334 (error "Message not found"))))
12336 ;;; BibTeX links
12338 ;; Use the custom search meachnism to construct and use search strings for
12339 ;; file links to BibTeX database entries.
12341 (defun org-create-file-search-in-bibtex ()
12342 "Create the search string and description for a BibTeX database entry."
12343 (when (eq major-mode 'bibtex-mode)
12344 ;; yes, we want to construct this search string.
12345 ;; Make a good description for this entry, using names, year and the title
12346 ;; Put it into the `description' variable which is dynamically scoped.
12347 (let ((bibtex-autokey-names 1)
12348 (bibtex-autokey-names-stretch 1)
12349 (bibtex-autokey-name-case-convert-function 'identity)
12350 (bibtex-autokey-name-separator " & ")
12351 (bibtex-autokey-additional-names " et al.")
12352 (bibtex-autokey-year-length 4)
12353 (bibtex-autokey-name-year-separator " ")
12354 (bibtex-autokey-titlewords 3)
12355 (bibtex-autokey-titleword-separator " ")
12356 (bibtex-autokey-titleword-case-convert-function 'identity)
12357 (bibtex-autokey-titleword-length 'infty)
12358 (bibtex-autokey-year-title-separator ": "))
12359 (setq description (bibtex-generate-autokey)))
12360 ;; Now parse the entry, get the key and return it.
12361 (save-excursion
12362 (bibtex-beginning-of-entry)
12363 (cdr (assoc "=key=" (bibtex-parse-entry))))))
12365 (defun org-execute-file-search-in-bibtex (s)
12366 "Find the link search string S as a key for a database entry."
12367 (when (eq major-mode 'bibtex-mode)
12368 ;; Yes, we want to do the search in this file.
12369 ;; We construct a regexp that searches for "@entrytype{" followed by the key
12370 (goto-char (point-min))
12371 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
12372 (regexp-quote s) "[ \t\n]*,") nil t)
12373 (goto-char (match-beginning 0)))
12374 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
12375 ;; Use double prefix to indicate that any web link should be browsed
12376 (let ((b (current-buffer)) (p (point)))
12377 ;; Restore the window configuration because we just use the web link
12378 (set-window-configuration org-window-config-before-follow-link)
12379 (save-excursion (set-buffer b) (goto-char p)
12380 (bibtex-url)))
12381 (recenter 0)) ; Move entry start to beginning of window
12382 ;; return t to indicate that the search is done.
12385 ;; Finally add the functions to the right hooks.
12386 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
12387 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
12389 ;; end of Bibtex link setup
12391 ;;; Following file links
12393 (defun org-open-file (path &optional in-emacs line search)
12394 "Open the file at PATH.
12395 First, this expands any special file name abbreviations. Then the
12396 configuration variable `org-file-apps' is checked if it contains an
12397 entry for this file type, and if yes, the corresponding command is launched.
12398 If no application is found, Emacs simply visits the file.
12399 With optional argument IN-EMACS, Emacs will visit the file.
12400 Optional LINE specifies a line to go to, optional SEARCH a string to
12401 search for. If LINE or SEARCH is given, the file will always be
12402 opened in Emacs.
12403 If the file does not exist, an error is thrown."
12404 (setq in-emacs (or in-emacs line search))
12405 (let* ((file (if (equal path "")
12406 buffer-file-name
12407 (substitute-in-file-name (expand-file-name path))))
12408 (apps (append org-file-apps (org-default-apps)))
12409 (remp (and (assq 'remote apps) (org-file-remote-p file)))
12410 (dirp (if remp nil (file-directory-p file)))
12411 (dfile (downcase file))
12412 (old-buffer (current-buffer))
12413 (old-pos (point))
12414 (old-mode major-mode)
12415 ext cmd)
12416 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
12417 (setq ext (match-string 1 dfile))
12418 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
12419 (setq ext (match-string 1 dfile))))
12420 (if in-emacs
12421 (setq cmd 'emacs)
12422 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
12423 (and dirp (cdr (assoc 'directory apps)))
12424 (cdr (assoc ext apps))
12425 (cdr (assoc t apps)))))
12426 (when (eq cmd 'mailcap)
12427 (require 'mailcap)
12428 (mailcap-parse-mailcaps)
12429 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
12430 (command (mailcap-mime-info mime-type)))
12431 (if (stringp command)
12432 (setq cmd command)
12433 (setq cmd 'emacs))))
12434 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
12435 (not (file-exists-p file))
12436 (not org-open-non-existing-files))
12437 (error "No such file: %s" file))
12438 (cond
12439 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
12440 ;; Remove quotes around the file name - we'll use shell-quote-argument.
12441 (if (string-match "['\"]%s['\"]" cmd)
12442 (setq cmd (replace-match "%s" t t cmd)))
12443 (setq cmd (format cmd (shell-quote-argument file)))
12444 (save-window-excursion
12445 (start-process-shell-command cmd nil cmd)))
12446 ((or (stringp cmd)
12447 (eq cmd 'emacs))
12448 (funcall (cdr (assq 'file org-link-frame-setup)) file)
12449 (widen)
12450 (if line (goto-line line)
12451 (if search (org-link-search search))))
12452 ((consp cmd)
12453 (eval cmd))
12454 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
12455 (and (org-mode-p) (eq old-mode 'org-mode)
12456 (or (not (equal old-buffer (current-buffer)))
12457 (not (equal old-pos (point))))
12458 (org-mark-ring-push old-pos old-buffer))))
12460 (defun org-default-apps ()
12461 "Return the default applications for this operating system."
12462 (cond
12463 ((eq system-type 'darwin)
12464 org-file-apps-defaults-macosx)
12465 ((eq system-type 'windows-nt)
12466 org-file-apps-defaults-windowsnt)
12467 (t org-file-apps-defaults-gnu)))
12469 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
12470 (defun org-file-remote-p (file)
12471 "Test whether FILE specifies a location on a remote system.
12472 Return non-nil if the location is indeed remote.
12474 For example, the filename \"/user@host:/foo\" specifies a location
12475 on the system \"/user@host:\"."
12476 (cond ((fboundp 'file-remote-p)
12477 (file-remote-p file))
12478 ((fboundp 'tramp-handle-file-remote-p)
12479 (tramp-handle-file-remote-p file))
12480 ((and (boundp 'ange-ftp-name-format)
12481 (string-match (car ange-ftp-name-format) file))
12483 (t nil)))
12486 ;;;; Hooks for remember.el
12488 ;;;###autoload
12489 (defun org-remember-annotation ()
12490 "Return a link to the current location as an annotation for remember.el.
12491 If you are using Org-mode files as target for data storage with
12492 remember.el, then the annotations should include a link compatible with the
12493 conventions in Org-mode. This function returns such a link."
12494 (org-store-link nil))
12496 (defconst org-remember-help
12497 "Select a destination location for the note.
12498 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
12499 RET on headline -> Store as sublevel entry to current headline
12500 RET at beg-of-buf -> Append to file as level 2 headline
12501 <left>/<right> -> before/after current headline, same headings level")
12503 (defvar org-remember-previous-location nil)
12504 (defvar org-force-remember-template-char) ;; dynamically scoped
12506 ;;;###autoload
12507 (defun org-remember-apply-template (&optional use-char skip-interactive)
12508 "Initialize *remember* buffer with template, invoke `org-mode'.
12509 This function should be placed into `remember-mode-hook' and in fact requires
12510 to be run from that hook to fucntion properly."
12511 (if org-remember-templates
12512 (let* ((templates (mapcar (lambda (x)
12513 (if (stringp (car x))
12514 (append (list (nth 1 x) (car x)) (cddr x))
12515 (append (list (car x) "") (cdr x))))
12516 org-remember-templates))
12517 (char (or use-char
12518 (cond
12519 ((= (length templates) 1)
12520 (caar templates))
12521 ((and (boundp 'org-force-remember-template-char)
12522 org-force-remember-template-char)
12523 (if (stringp org-force-remember-template-char)
12524 (string-to-char org-force-remember-template-char)
12525 org-force-remember-template-char))
12527 (message "Select template: %s"
12528 (mapconcat
12529 (lambda (x)
12530 (cond
12531 ((not (string-match "\\S-" (nth 1 x)))
12532 (format "[%c]" (car x)))
12533 ((equal (downcase (car x))
12534 (downcase (aref (nth 1 x) 0)))
12535 (format "[%c]%s" (car x) (substring (nth 1 x) 1)))
12536 (t (format "[%c]%s" (car x) (nth 1 x)))))
12537 templates " "))
12538 (read-char-exclusive)))))
12539 (entry (cddr (assoc char templates)))
12540 (tpl (car entry))
12541 (plist-p (if org-store-link-plist t nil))
12542 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
12543 (string-match "\\S-" (nth 1 entry)))
12544 (nth 1 entry)
12545 org-default-notes-file))
12546 (headline (nth 2 entry))
12547 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
12548 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
12549 (v-u (concat "[" (substring v-t 1 -1) "]"))
12550 (v-U (concat "[" (substring v-T 1 -1) "]"))
12551 ;; `initial' and `annotation' are bound in `remember'
12552 (v-i (if (boundp 'initial) initial))
12553 (v-a (if (and (boundp 'annotation) annotation)
12554 (if (equal annotation "[[]]") "" annotation)
12555 ""))
12556 (v-A (if (and v-a
12557 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
12558 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
12559 v-a))
12560 (v-n user-full-name)
12561 (org-startup-folded nil)
12562 org-time-was-given org-end-time-was-given x prompt char time)
12563 (setq org-store-link-plist
12564 (append (list :annotation v-a :initial v-i)
12565 org-store-link-plist))
12566 (unless tpl (setq tpl "") (message "No template") (ding))
12567 (erase-buffer)
12568 (insert (substitute-command-keys
12569 (format
12570 "## Filing location: Select interactively, default, or last used:
12571 ## %s to select file and header location interactively.
12572 ## %s \"%s\" -> \"* %s\"
12573 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
12574 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
12575 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
12576 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
12577 (abbreviate-file-name (or file org-default-notes-file))
12578 (or headline "")
12579 (or (car org-remember-previous-location) "???")
12580 (or (cdr org-remember-previous-location) "???"))))
12581 (insert tpl) (goto-char (point-min))
12582 ;; Simple %-escapes
12583 (while (re-search-forward "%\\([tTuUaiA]\\)" nil t)
12584 (when (and initial (equal (match-string 0) "%i"))
12585 (save-match-data
12586 (let* ((lead (buffer-substring
12587 (point-at-bol) (match-beginning 0))))
12588 (setq v-i (mapconcat 'identity
12589 (org-split-string initial "\n")
12590 (concat "\n" lead))))))
12591 (replace-match
12592 (or (eval (intern (concat "v-" (match-string 1)))) "")
12593 t t))
12594 ;; From the property list
12595 (when plist-p
12596 (goto-char (point-min))
12597 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
12598 (and (setq x (plist-get org-store-link-plist
12599 (intern (match-string 1))))
12600 (replace-match x t t))))
12601 ;; Turn on org-mode in the remember buffer, set local variables
12602 (org-mode)
12603 (org-set-local 'org-finish-function 'remember-buffer)
12604 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
12605 (org-set-local 'org-default-notes-file file))
12606 (if (and headline (stringp headline) (string-match "\\S-" headline))
12607 (org-set-local 'org-remember-default-headline headline))
12608 ;; Interactive template entries
12609 (goto-char (point-min))
12610 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
12611 (setq char (if (match-end 3) (match-string 3))
12612 prompt (if (match-end 2) (match-string 2)))
12613 (goto-char (match-beginning 0))
12614 (replace-match "")
12615 (cond
12616 ((member char '("G" "g"))
12617 (let* ((org-last-tags-completion-table
12618 (org-global-tags-completion-table
12619 (if (equal char "G") (org-agenda-files) (and file (list file)))))
12620 (org-add-colon-after-tag-completion t)
12621 (ins (completing-read
12622 (if prompt (concat prompt ": ") "Tags: ")
12623 'org-tags-completion-function nil nil nil
12624 'org-tags-history)))
12625 (setq ins (mapconcat 'identity
12626 (org-split-string ins (org-re "[^[:alnum:]]+"))
12627 ":"))
12628 (when (string-match "\\S-" ins)
12629 (or (equal (char-before) ?:) (insert ":"))
12630 (insert ins)
12631 (or (equal (char-after) ?:) (insert ":")))))
12632 (char
12633 (setq org-time-was-given (equal (upcase char) char))
12634 (setq time (org-read-date (equal (upcase char) "U") t nil
12635 prompt))
12636 (org-insert-time-stamp time org-time-was-given
12637 (member char '("u" "U"))
12638 nil nil (list org-end-time-was-given)))
12640 (insert (read-string
12641 (if prompt (concat prompt ": ") "Enter string"))))))
12642 (goto-char (point-min))
12643 (if (re-search-forward "%\\?" nil t)
12644 (replace-match "")
12645 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
12646 (org-mode)
12647 (org-set-local 'org-finish-function 'remember-buffer)))
12649 ;;;###autoload
12650 (defun org-remember (&optional org-force-remember-template-char)
12651 "Call `remember'. If this is already a remember buffer, re-apply template.
12652 If there is an active region, make sure remember uses it as initial content
12653 of the remember buffer."
12654 (interactive)
12655 (if (eq org-finish-function 'remember-buffer)
12656 (progn
12657 (when (< (length org-remember-templates) 2)
12658 (error "No other template available"))
12659 (erase-buffer)
12660 (let ((annotation (plist-get org-store-link-plist :annotation))
12661 (initial (plist-get org-store-link-plist :initial)))
12662 (org-remember-apply-template))
12663 (message "Press C-c C-c to remember data"))
12664 (if (org-region-active-p)
12665 (remember (buffer-substring (point) (mark)))
12666 (call-interactively 'remember))))
12668 (defvar org-note-abort nil) ; dynamically scoped
12670 ;;;###autoload
12671 (defun org-remember-handler ()
12672 "Store stuff from remember.el into an org file.
12673 First prompts for an org file. If the user just presses return, the value
12674 of `org-default-notes-file' is used.
12675 Then the command offers the headings tree of the selected file in order to
12676 file the text at a specific location.
12677 You can either immediately press RET to get the note appended to the
12678 file, or you can use vertical cursor motion and visibility cycling (TAB) to
12679 find a better place. Then press RET or <left> or <right> in insert the note.
12681 Key Cursor position Note gets inserted
12682 -----------------------------------------------------------------------------
12683 RET buffer-start as level 1 heading at end of file
12684 RET on headline as sublevel of the heading at cursor
12685 RET no heading at cursor position, level taken from context.
12686 Or use prefix arg to specify level manually.
12687 <left> on headline as same level, before current heading
12688 <right> on headline as same level, after current heading
12690 So the fastest way to store the note is to press RET RET to append it to
12691 the default file. This way your current train of thought is not
12692 interrupted, in accordance with the principles of remember.el.
12693 You can also get the fast execution without prompting by using
12694 C-u C-c C-c to exit the remember buffer. See also the variable
12695 `org-remember-store-without-prompt'.
12697 Before being stored away, the function ensures that the text has a
12698 headline, i.e. a first line that starts with a \"*\". If not, a headline
12699 is constructed from the current date and some additional data.
12701 If the variable `org-adapt-indentation' is non-nil, the entire text is
12702 also indented so that it starts in the same column as the headline
12703 \(i.e. after the stars).
12705 See also the variable `org-reverse-note-order'."
12706 (goto-char (point-min))
12707 (while (looking-at "^[ \t]*\n\\|^##.*\n")
12708 (replace-match ""))
12709 (goto-char (point-max))
12710 (unless (equal (char-before) ?\n) (insert "\n"))
12711 (catch 'quit
12712 (if org-note-abort (throw 'quit nil))
12713 (let* ((txt (buffer-substring (point-min) (point-max)))
12714 (fastp (org-xor (equal current-prefix-arg '(4))
12715 org-remember-store-without-prompt))
12716 (file (if fastp org-default-notes-file (org-get-org-file)))
12717 (heading org-remember-default-headline)
12718 (visiting (org-find-base-buffer-visiting file))
12719 (org-startup-folded nil)
12720 (org-startup-align-all-tables nil)
12721 (org-goto-start-pos 1)
12722 spos exitcmd level indent reversed)
12723 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
12724 (setq file (car org-remember-previous-location)
12725 heading (cdr org-remember-previous-location)))
12726 (setq current-prefix-arg nil)
12727 ;; Modify text so that it becomes a nice subtree which can be inserted
12728 ;; into an org tree.
12729 (let* ((lines (split-string txt "\n"))
12730 first)
12731 (setq first (car lines) lines (cdr lines))
12732 (if (string-match "^\\*+ " first)
12733 ;; Is already a headline
12734 (setq indent nil)
12735 ;; We need to add a headline: Use time and first buffer line
12736 (setq lines (cons first lines)
12737 first (concat "* " (current-time-string)
12738 " (" (remember-buffer-desc) ")")
12739 indent " "))
12740 (if (and org-adapt-indentation indent)
12741 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
12742 (setq txt (concat first "\n"
12743 (mapconcat 'identity lines "\n"))))
12744 ;; Find the file
12745 (if (not visiting) (find-file-noselect file))
12746 (with-current-buffer (or visiting (get-file-buffer file))
12747 (unless (org-mode-p)
12748 (error "Target files for remember notes must be in Org-mode"))
12749 (save-excursion
12750 (save-restriction
12751 (widen)
12752 (and (goto-char (point-min))
12753 (not (re-search-forward "^\\* " nil t))
12754 (insert "\n* " (or heading "Notes") "\n"))
12755 (setq reversed (org-notes-order-reversed-p))
12757 ;; Find the default location
12758 (when (and heading (stringp heading) (string-match "\\S-" heading))
12759 (goto-char (point-min))
12760 (if (re-search-forward
12761 (concat "^\\*+[ \t]+" (regexp-quote heading)
12762 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
12763 nil t)
12764 (setq org-goto-start-pos (match-beginning 0))
12765 (when fastp
12766 (goto-char (point-max))
12767 (unless (bolp) (newline))
12768 (insert "* " heading "\n")
12769 (setq org-goto-start-pos (point-at-bol 0)))))
12771 ;; Ask the User for a location
12772 (if fastp
12773 (setq spos org-goto-start-pos
12774 exitcmd 'return)
12775 (setq spos (org-get-location (current-buffer) org-remember-help)
12776 exitcmd (cdr spos)
12777 spos (car spos)))
12778 (if (not spos) (throw 'quit nil)) ; return nil to show we did
12779 ; not handle this note
12780 (goto-char spos)
12781 (cond ((org-on-heading-p t)
12782 (org-back-to-heading t)
12783 (setq level (funcall outline-level))
12784 (cond
12785 ((eq exitcmd 'return)
12786 ;; sublevel of current
12787 (setq org-remember-previous-location
12788 (cons (abbreviate-file-name file)
12789 (org-get-heading 'notags)))
12790 (if reversed
12791 (outline-next-heading)
12792 (org-end-of-subtree)
12793 (if (not (bolp))
12794 (if (looking-at "[ \t]*\n")
12795 (beginning-of-line 2)
12796 (end-of-line 1)
12797 (insert "\n"))))
12798 (org-paste-subtree (org-get-legal-level level 1) txt))
12799 ((eq exitcmd 'left)
12800 ;; before current
12801 (org-paste-subtree level txt))
12802 ((eq exitcmd 'right)
12803 ;; after current
12804 (org-end-of-subtree t)
12805 (org-paste-subtree level txt))
12806 (t (error "This should not happen"))))
12808 ((and (bobp) (not reversed))
12809 ;; Put it at the end, one level below level 1
12810 (save-restriction
12811 (widen)
12812 (goto-char (point-max))
12813 (if (not (bolp)) (newline))
12814 (org-paste-subtree (org-get-legal-level 1 1) txt)))
12816 ((and (bobp) reversed)
12817 ;; Put it at the start, as level 1
12818 (save-restriction
12819 (widen)
12820 (goto-char (point-min))
12821 (re-search-forward "^\\*+ " nil t)
12822 (beginning-of-line 1)
12823 (org-paste-subtree 1 txt)))
12825 ;; Put it right there, with automatic level determined by
12826 ;; org-paste-subtree or from prefix arg
12827 (org-paste-subtree
12828 (if (numberp current-prefix-arg) current-prefix-arg)
12829 txt)))
12830 (when remember-save-after-remembering
12831 (save-buffer)
12832 (if (not visiting) (kill-buffer (current-buffer)))))))))
12833 t) ;; return t to indicate that we took care of this note.
12835 (defun org-get-org-file ()
12836 "Read a filename, with default directory `org-directory'."
12837 (let ((default (or org-default-notes-file remember-data-file)))
12838 (read-file-name (format "File name [%s]: " default)
12839 (file-name-as-directory org-directory)
12840 default)))
12842 (defun org-notes-order-reversed-p ()
12843 "Check if the current file should receive notes in reversed order."
12844 (cond
12845 ((not org-reverse-note-order) nil)
12846 ((eq t org-reverse-note-order) t)
12847 ((not (listp org-reverse-note-order)) nil)
12848 (t (catch 'exit
12849 (let ((all org-reverse-note-order)
12850 entry)
12851 (while (setq entry (pop all))
12852 (if (string-match (car entry) buffer-file-name)
12853 (throw 'exit (cdr entry))))
12854 nil)))))
12856 ;;;; Dynamic blocks
12858 (defun org-find-dblock (name)
12859 "Find the first dynamic block with name NAME in the buffer.
12860 If not found, stay at current position and return nil."
12861 (let (pos)
12862 (save-excursion
12863 (goto-char (point-min))
12864 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
12865 nil t)
12866 (match-beginning 0))))
12867 (if pos (goto-char pos))
12868 pos))
12870 (defconst org-dblock-start-re
12871 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
12872 "Matches the startline of a dynamic block, with parameters.")
12874 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
12875 "Matches the end of a dyhamic block.")
12877 (defun org-create-dblock (plist)
12878 "Create a dynamic block section, with parameters taken from PLIST.
12879 PLIST must containe a :name entry which is used as name of the block."
12880 (unless (bolp) (newline))
12881 (let ((name (plist-get plist :name)))
12882 (insert "#+BEGIN: " name)
12883 (while plist
12884 (if (eq (car plist) :name)
12885 (setq plist (cddr plist))
12886 (insert " " (prin1-to-string (pop plist)))))
12887 (insert "\n\n#+END:\n")
12888 (beginning-of-line -2)))
12890 (defun org-prepare-dblock ()
12891 "Prepare dynamic block for refresh.
12892 This empties the block, puts the cursor at the insert position and returns
12893 the property list including an extra property :name with the block name."
12894 (unless (looking-at org-dblock-start-re)
12895 (error "Not at a dynamic block"))
12896 (let* ((begdel (1+ (match-end 0)))
12897 (name (org-no-properties (match-string 1)))
12898 (params (append (list :name name)
12899 (read (concat "(" (match-string 3) ")")))))
12900 (unless (re-search-forward org-dblock-end-re nil t)
12901 (error "Dynamic block not terminated"))
12902 (delete-region begdel (match-beginning 0))
12903 (goto-char begdel)
12904 (open-line 1)
12905 params))
12907 (defun org-map-dblocks (&optional command)
12908 "Apply COMMAND to all dynamic blocks in the current buffer.
12909 If COMMAND is not given, use `org-update-dblock'."
12910 (let ((cmd (or command 'org-update-dblock))
12911 pos)
12912 (save-excursion
12913 (goto-char (point-min))
12914 (while (re-search-forward org-dblock-start-re nil t)
12915 (goto-char (setq pos (match-beginning 0)))
12916 (condition-case nil
12917 (funcall cmd)
12918 (error (message "Error during update of dynamic block")))
12919 (goto-char pos)
12920 (unless (re-search-forward org-dblock-end-re nil t)
12921 (error "Dynamic block not terminated"))))))
12923 (defun org-dblock-update (&optional arg)
12924 "User command for updating dynamic blocks.
12925 Update the dynamic block at point. With prefix ARG, update all dynamic
12926 blocks in the buffer."
12927 (interactive "P")
12928 (if arg
12929 (org-update-all-dblocks)
12930 (or (looking-at org-dblock-start-re)
12931 (org-beginning-of-dblock))
12932 (org-update-dblock)))
12934 (defun org-update-dblock ()
12935 "Update the dynamic block at point
12936 This means to empty the block, parse for parameters and then call
12937 the correct writing function."
12938 (save-window-excursion
12939 (let* ((pos (point))
12940 (line (org-current-line))
12941 (params (org-prepare-dblock))
12942 (name (plist-get params :name))
12943 (cmd (intern (concat "org-dblock-write:" name))))
12944 (message "Updating dynamic block `%s' at line %d..." name line)
12945 (funcall cmd params)
12946 (message "Updating dynamic block `%s' at line %d...done" name line)
12947 (goto-char pos))))
12949 (defun org-beginning-of-dblock ()
12950 "Find the beginning of the dynamic block at point.
12951 Error if there is no scuh block at point."
12952 (let ((pos (point))
12953 beg)
12954 (end-of-line 1)
12955 (if (and (re-search-backward org-dblock-start-re nil t)
12956 (setq beg (match-beginning 0))
12957 (re-search-forward org-dblock-end-re nil t)
12958 (> (match-end 0) pos))
12959 (goto-char beg)
12960 (goto-char pos)
12961 (error "Not in a dynamic block"))))
12963 (defun org-update-all-dblocks ()
12964 "Update all dynamic blocks in the buffer.
12965 This function can be used in a hook."
12966 (when (org-mode-p)
12967 (org-map-dblocks 'org-update-dblock)))
12970 ;;;; Completion
12972 (defconst org-additional-option-like-keywords
12973 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
12974 "ORGTBL" "HTML:" "LaTeX:"))
12976 (defun org-complete (&optional arg)
12977 "Perform completion on word at point.
12978 At the beginning of a headline, this completes TODO keywords as given in
12979 `org-todo-keywords'.
12980 If the current word is preceded by a backslash, completes the TeX symbols
12981 that are supported for HTML support.
12982 If the current word is preceded by \"#+\", completes special words for
12983 setting file options.
12984 In the line after \"#+STARTUP:, complete valid keywords.\"
12985 At all other locations, this simply calls the value of
12986 `org-completion-fallback-command'."
12987 (interactive "P")
12988 (org-without-partial-completion
12989 (catch 'exit
12990 (let* ((end (point))
12991 (beg1 (save-excursion
12992 (skip-chars-backward (org-re "[:alnum:]_@"))
12993 (point)))
12994 (beg (save-excursion
12995 (skip-chars-backward "a-zA-Z0-9_:$")
12996 (point)))
12997 (confirm (lambda (x) (stringp (car x))))
12998 (searchhead (equal (char-before beg) ?*))
12999 (tag (and (equal (char-before beg1) ?:)
13000 (equal (char-after (point-at-bol)) ?*)))
13001 (prop (and (equal (char-before beg1) ?:)
13002 (not (equal (char-after (point-at-bol)) ?*))))
13003 (texp (equal (char-before beg) ?\\))
13004 (link (equal (char-before beg) ?\[))
13005 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
13006 beg)
13007 "#+"))
13008 (startup (string-match "^#\\+STARTUP:.*"
13009 (buffer-substring (point-at-bol) (point))))
13010 (completion-ignore-case opt)
13011 (type nil)
13012 (tbl nil)
13013 (table (cond
13014 (opt
13015 (setq type :opt)
13016 (append
13017 (mapcar
13018 (lambda (x)
13019 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
13020 (cons (match-string 2 x) (match-string 1 x)))
13021 (org-split-string (org-get-current-options) "\n"))
13022 (mapcar 'list org-additional-option-like-keywords)))
13023 (startup
13024 (setq type :startup)
13025 org-startup-options)
13026 (link (append org-link-abbrev-alist-local
13027 org-link-abbrev-alist))
13028 (texp
13029 (setq type :tex)
13030 org-html-entities)
13031 ((string-match "\\`\\*+[ \t]+\\'"
13032 (buffer-substring (point-at-bol) beg))
13033 (setq type :todo)
13034 (mapcar 'list org-todo-keywords-1))
13035 (searchhead
13036 (setq type :searchhead)
13037 (save-excursion
13038 (goto-char (point-min))
13039 (while (re-search-forward org-todo-line-regexp nil t)
13040 (push (list
13041 (org-make-org-heading-search-string
13042 (match-string 3) t))
13043 tbl)))
13044 tbl)
13045 (tag (setq type :tag beg beg1)
13046 (or org-tag-alist (org-get-buffer-tags)))
13047 (prop (setq type :prop beg beg1)
13048 (mapcar 'list (org-buffer-property-keys)))
13049 (t (progn
13050 (call-interactively org-completion-fallback-command)
13051 (throw 'exit nil)))))
13052 (pattern (buffer-substring-no-properties beg end))
13053 (completion (try-completion pattern table confirm)))
13054 (cond ((eq completion t)
13055 (if (not (assoc (upcase pattern) table))
13056 (message "Already complete")
13057 (if (equal type :opt)
13058 (insert (substring (cdr (assoc (upcase pattern) table))
13059 (length pattern)))
13060 (if (memq type '(:tag :prop)) (insert ":")))))
13061 ((null completion)
13062 (message "Can't find completion for \"%s\"" pattern)
13063 (ding))
13064 ((not (string= pattern completion))
13065 (delete-region beg end)
13066 (if (string-match " +$" completion)
13067 (setq completion (replace-match "" t t completion)))
13068 (insert completion)
13069 (if (get-buffer-window "*Completions*")
13070 (delete-window (get-buffer-window "*Completions*")))
13071 (if (assoc completion table)
13072 (if (eq type :todo) (insert " ")
13073 (if (memq type '(:tag :prop)) (insert ":"))))
13074 (if (and (equal type :opt) (assoc completion table))
13075 (message "%s" (substitute-command-keys
13076 "Press \\[org-complete] again to insert example settings"))))
13078 (message "Making completion list...")
13079 (let ((list (sort (all-completions pattern table confirm)
13080 'string<)))
13081 (with-output-to-temp-buffer "*Completions*"
13082 (condition-case nil
13083 ;; Protection needed for XEmacs and emacs 21
13084 (display-completion-list list pattern)
13085 (error (display-completion-list list)))))
13086 (message "Making completion list...%s" "done")))))))
13088 ;;;; TODO, DEADLINE, Comments
13090 (defun org-toggle-comment ()
13091 "Change the COMMENT state of an entry."
13092 (interactive)
13093 (save-excursion
13094 (org-back-to-heading)
13095 (if (looking-at (concat outline-regexp
13096 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
13097 (replace-match "" t t nil 1)
13098 (if (looking-at outline-regexp)
13099 (progn
13100 (goto-char (match-end 0))
13101 (insert org-comment-string " "))))))
13103 (defvar org-last-todo-state-is-todo nil
13104 "This is non-nil when the last TODO state change led to a TODO state.
13105 If the last change removed the TODO tag or switched to DONE, then
13106 this is nil.")
13108 (defvar org-setting-tags nil) ; dynamically skiped
13110 ;; FIXME: better place
13111 (defun org-property-or-variable-value (var &optional inherit)
13112 "Check if there is a property fixing the value of VAR.
13113 If yes, return this value. If not, return the current value of the variable."
13114 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13115 (if (and prop (stringp prop) (string-match "\\S-" prop))
13116 (read prop)
13117 (symbol-value var))))
13119 (defun org-todo (&optional arg)
13120 "Change the TODO state of an item.
13121 The state of an item is given by a keyword at the start of the heading,
13122 like
13123 *** TODO Write paper
13124 *** DONE Call mom
13126 The different keywords are specified in the variable `org-todo-keywords'.
13127 By default the available states are \"TODO\" and \"DONE\".
13128 So for this example: when the item starts with TODO, it is changed to DONE.
13129 When it starts with DONE, the DONE is removed. And when neither TODO nor
13130 DONE are present, add TODO at the beginning of the heading.
13132 With C-u prefix arg, use completion to determine the new state.
13133 With numeric prefix arg, switch to that state.
13135 For calling through lisp, arg is also interpreted in the following way:
13136 'none -> empty state
13137 \"\"(empty string) -> switch to empty state
13138 'done -> switch to DONE
13139 'nextset -> switch to the next set of keywords
13140 'previousset -> switch to the previous set of keywords
13141 \"WAITING\" -> switch to the specified keyword, but only if it
13142 really is a member of `org-todo-keywords'."
13143 (interactive "P")
13144 (save-excursion
13145 (org-back-to-heading)
13146 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
13147 (or (looking-at (concat " +" org-todo-regexp " *"))
13148 (looking-at " *"))
13149 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
13150 (org-log-done (org-parse-local-options logging 'org-log-done))
13151 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
13152 (this (match-string 1))
13153 (hl-pos (match-beginning 0))
13154 (head (org-get-todo-sequence-head this))
13155 (ass (assoc head org-todo-kwd-alist))
13156 (interpret (nth 1 ass))
13157 (done-word (nth 3 ass))
13158 (final-done-word (nth 4 ass))
13159 (last-state (or this ""))
13160 (completion-ignore-case t)
13161 (member (member this org-todo-keywords-1))
13162 (tail (cdr member))
13163 (state (cond
13164 ((and org-todo-key-trigger
13165 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
13166 (and (not arg) org-use-fast-todo-selection
13167 (not (eq org-use-fast-todo-selection 'prefix)))))
13168 ;; Use fast selection
13169 (org-fast-todo-selection))
13170 ((and (equal arg '(4))
13171 (or (not org-use-fast-todo-selection)
13172 (not org-todo-key-trigger)))
13173 ;; Read a state with completion
13174 (completing-read "State: " (mapcar (lambda(x) (list x))
13175 org-todo-keywords-1)
13176 nil t))
13177 ((eq arg 'right)
13178 (if this
13179 (if tail (car tail) nil)
13180 (car org-todo-keywords-1)))
13181 ((eq arg 'left)
13182 (if (equal member org-todo-keywords-1)
13184 (if this
13185 (nth (- (length org-todo-keywords-1) (length tail) 2)
13186 org-todo-keywords-1)
13187 (org-last org-todo-keywords-1))))
13188 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
13189 (setq arg nil))) ; hack to fall back to cycling
13190 (arg
13191 ;; user or caller requests a specific state
13192 (cond
13193 ((equal arg "") nil)
13194 ((eq arg 'none) nil)
13195 ((eq arg 'done) (or done-word (car org-done-keywords)))
13196 ((eq arg 'nextset)
13197 (or (car (cdr (member head org-todo-heads)))
13198 (car org-todo-heads)))
13199 ((eq arg 'previousset)
13200 (let ((org-todo-heads (reverse org-todo-heads)))
13201 (or (car (cdr (member head org-todo-heads)))
13202 (car org-todo-heads))))
13203 ((car (member arg org-todo-keywords-1)))
13204 ((nth (1- (prefix-numeric-value arg))
13205 org-todo-keywords-1))))
13206 ((null member) (or head (car org-todo-keywords-1)))
13207 ((equal this final-done-word) nil) ;; -> make empty
13208 ((null tail) nil) ;; -> first entry
13209 ((eq interpret 'sequence)
13210 (car tail))
13211 ((memq interpret '(type priority))
13212 (if (eq this-command last-command)
13213 (car tail)
13214 (if (> (length tail) 0)
13215 (or done-word (car org-done-keywords))
13216 nil)))
13217 (t nil)))
13218 (next (if state (concat " " state " ") " "))
13219 dostates)
13220 (replace-match next t t)
13221 (unless (pos-visible-in-window-p hl-pos)
13222 (message "TODO state changed to %s" (org-trim next)))
13223 (unless head
13224 (setq head (org-get-todo-sequence-head state)
13225 ass (assoc head org-todo-kwd-alist)
13226 interpret (nth 1 ass)
13227 done-word (nth 3 ass)
13228 final-done-word (nth 4 ass)))
13229 (when (memq arg '(nextset previousset))
13230 (message "Keyword-Set %d/%d: %s"
13231 (- (length org-todo-sets) -1
13232 (length (memq (assoc state org-todo-sets) org-todo-sets)))
13233 (length org-todo-sets)
13234 (mapconcat 'identity (assoc state org-todo-sets) " ")))
13235 (setq org-last-todo-state-is-todo
13236 (not (member state org-done-keywords)))
13237 (when (and org-log-done (not (memq arg '(nextset previousset))))
13238 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
13239 (or (not org-todo-log-states)
13240 (member state org-todo-log-states))))
13242 (cond
13243 ((and state (member state org-not-done-keywords)
13244 (not (member this org-not-done-keywords)))
13245 ;; This is now a todo state and was not one before
13246 ;; Remove any CLOSED timestamp, and possibly log the state change
13247 (org-add-planning-info nil nil 'closed)
13248 (and dostates (org-add-log-maybe 'state state 'findpos)))
13249 ((and state dostates)
13250 ;; This is a non-nil state, and we need to log it
13251 (org-add-log-maybe 'state state 'findpos))
13252 ((and (member state org-done-keywords)
13253 (not (member this org-done-keywords)))
13254 ;; It is now done, and it was not done before
13255 (org-add-planning-info 'closed (org-current-time))
13256 (org-add-log-maybe 'done state 'findpos))))
13257 ;; Fixup tag positioning
13258 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
13259 (run-hooks 'org-after-todo-state-change-hook)
13260 (and (member state org-done-keywords) (org-auto-repeat-maybe))
13261 (if (and arg (not (member state org-done-keywords)))
13262 (setq head (org-get-todo-sequence-head state)))
13263 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)))
13264 ;; Fixup cursor location if close to the keyword
13265 (if (and (outline-on-heading-p)
13266 (not (bolp))
13267 (save-excursion (beginning-of-line 1)
13268 (looking-at org-todo-line-regexp))
13269 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
13270 (progn
13271 (goto-char (or (match-end 2) (match-end 1)))
13272 (just-one-space))))
13274 (defun org-get-todo-sequence-head (kwd)
13275 "Return the head of the TODO sequence to which KWD belongs.
13276 If KWD is not set, check if there is a text property remembering the
13277 right sequence."
13278 (let (p)
13279 (cond
13280 ((not kwd)
13281 (or (get-text-property (point-at-bol) 'org-todo-head)
13282 (progn
13283 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13284 nil (point-at-eol)))
13285 (get-text-property p 'org-todo-head))))
13286 ((not (member kwd org-todo-keywords-1))
13287 (car org-todo-keywords-1))
13288 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13290 (defun org-fast-todo-selection ()
13291 "Fast TODO keyword selection with single keys.
13292 Returns the new TODO keyword, or nil if no state change should occur."
13293 (let* ((fulltable org-todo-key-alist)
13294 (done-keywords org-done-keywords) ;; needed for the faces.
13295 (maxlen (apply 'max (mapcar
13296 (lambda (x)
13297 (if (stringp (car x)) (string-width (car x)) 0))
13298 fulltable)))
13299 (buf (current-buffer))
13300 (expert nil)
13301 (fwidth (+ maxlen 3 1 3))
13302 (ncol (/ (- (window-width) 4) fwidth))
13303 tg cnt e c char c1 c2 ntable tbl rtn
13304 groups ingroup)
13305 (save-window-excursion
13306 (if expert
13307 (set-buffer (get-buffer-create " *Org todo*"))
13308 ; (delete-other-windows)
13309 ; (split-window-vertically)
13310 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13311 (erase-buffer)
13312 (org-set-local 'org-done-keywords done-keywords)
13313 (setq tbl fulltable char ?a cnt 0)
13314 (while (setq e (pop tbl))
13315 (cond
13316 ((equal e '(:startgroup))
13317 (push '() groups) (setq ingroup t)
13318 (when (not (= cnt 0))
13319 (setq cnt 0)
13320 (insert "\n"))
13321 (insert "{ "))
13322 ((equal e '(:endgroup))
13323 (setq ingroup nil cnt 0)
13324 (insert "}\n"))
13326 (setq tg (car e) c (cdr e))
13327 (if ingroup (push tg (car groups)))
13328 (setq tg (org-add-props tg nil 'face
13329 (org-get-todo-face tg)))
13330 (if (and (= cnt 0) (not ingroup)) (insert " "))
13331 (insert "[" c "] " tg (make-string
13332 (- fwidth 4 (length tg)) ?\ ))
13333 (when (= (setq cnt (1+ cnt)) ncol)
13334 (insert "\n")
13335 (if ingroup (insert " "))
13336 (setq cnt 0)))))
13337 (insert "\n")
13338 (goto-char (point-min))
13339 (if (and (not expert) (fboundp 'fit-window-to-buffer))
13340 (fit-window-to-buffer))
13341 (message "[a-z..]:Set [SPC]:clear")
13342 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13343 (cond
13344 ((or (= c ?\C-g)
13345 (and (= c ?q) (not (rassoc c fulltable))))
13346 (setq quit-flag t))
13347 ((= c ?\ ) nil)
13348 ((setq e (rassoc c fulltable) tg (car e))
13350 (t (setq quit-flag t))))))
13352 (defun org-get-repeat ()
13353 "Check if tere is a deadline/schedule with repeater in this entry."
13354 (save-match-data
13355 (save-excursion
13356 (org-back-to-heading t)
13357 (if (re-search-forward
13358 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
13359 (match-string 1)))))
13361 (defvar org-last-changed-timestamp)
13362 (defvar org-log-post-message)
13363 (defun org-auto-repeat-maybe ()
13364 "Check if the current headline contains a repeated deadline/schedule.
13365 If yes, set TODO state back to what it was and change the base date
13366 of repeating deadline/scheduled time stamps to new date.
13367 This function should be run in the `org-after-todo-state-change-hook'."
13368 ;; last-state is dynamically scoped into this function
13369 (let* ((repeat (org-get-repeat))
13370 (aa (assoc last-state org-todo-kwd-alist))
13371 (interpret (nth 1 aa))
13372 (head (nth 2 aa))
13373 (done-word (nth 3 aa))
13374 (whata '(("d" . day) ("m" . month) ("y" . year)))
13375 (msg "Entry repeats: ")
13376 (org-log-done)
13377 re type n what ts)
13378 (when repeat
13379 (org-todo (if (eq interpret 'type) last-state head))
13380 (when (and org-log-repeat
13381 (not (memq 'org-add-log-note
13382 (default-value 'post-command-hook))))
13383 ;; Make sure a note is taken
13384 (let ((org-log-done '(done)))
13385 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
13386 'findpos)))
13387 (org-back-to-heading t)
13388 (org-add-planning-info nil nil 'closed)
13389 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13390 org-deadline-time-regexp "\\)"))
13391 (while (re-search-forward
13392 re (save-excursion (outline-next-heading) (point)) t)
13393 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
13394 ts (match-string (if (match-end 2) 2 4)))
13395 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
13396 (setq n (string-to-number (match-string 1 ts))
13397 what (match-string 2 ts))
13398 (if (equal what "w") (setq n (* n 7) what "d"))
13399 (org-timestamp-change n (cdr (assoc what whata))))
13400 (setq msg (concat msg type org-last-changed-timestamp " ")))
13401 (setq org-log-post-message msg)
13402 (message msg))))
13404 (defun org-show-todo-tree (arg)
13405 "Make a compact tree which shows all headlines marked with TODO.
13406 The tree will show the lines where the regexp matches, and all higher
13407 headlines above the match.
13408 With \\[universal-argument] prefix, also show the DONE entries.
13409 With a numeric prefix N, construct a sparse tree for the Nth element
13410 of `org-todo-keywords-1'."
13411 (interactive "P")
13412 (let ((case-fold-search nil)
13413 (kwd-re
13414 (cond ((null arg) org-not-done-regexp)
13415 ((equal arg '(4))
13416 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
13417 (mapcar 'list org-todo-keywords-1))))
13418 (concat "\\("
13419 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13420 "\\)\\>")))
13421 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13422 (regexp-quote (nth (1- (prefix-numeric-value arg))
13423 org-todo-keywords-1)))
13424 (t (error "Invalid prefix argument: %s" arg)))))
13425 (message "%d TODO entries found"
13426 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
13428 (defun org-deadline (&optional remove)
13429 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13430 With argument REMOVE, remove any deadline from the item."
13431 (interactive "P")
13432 (if remove
13433 (progn
13434 (org-add-planning-info nil nil 'deadline)
13435 (message "Item no longer has a deadline."))
13436 (org-add-planning-info 'deadline nil 'closed)))
13438 (defun org-schedule (&optional remove)
13439 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13440 With argument REMOVE, remove any scheduling date from the item."
13441 (interactive "P")
13442 (if remove
13443 (progn
13444 (org-add-planning-info nil nil 'scheduled)
13445 (message "Item is no longer scheduled."))
13446 (org-add-planning-info 'scheduled nil 'closed)))
13448 (defun org-add-planning-info (what &optional time &rest remove)
13449 "Insert new timestamp with keyword in the line directly after the headline.
13450 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
13451 If non is given, the user is prompted for a date.
13452 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13453 be removed."
13454 (interactive)
13455 (let (org-time-was-given org-end-time-was-given)
13456 (when what (setq time (or time (org-read-date nil 'to-time))))
13457 (when (and org-insert-labeled-timestamps-at-point
13458 (member what '(scheduled deadline)))
13459 (insert
13460 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13461 (org-insert-time-stamp time org-time-was-given
13462 nil nil nil (list org-end-time-was-given))
13463 (setq what nil))
13464 (save-excursion
13465 (save-restriction
13466 (let (col list elt ts buffer-invisibility-spec)
13467 (org-back-to-heading t)
13468 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
13469 (goto-char (match-end 1))
13470 (setq col (current-column))
13471 (goto-char (match-end 0))
13472 (if (eobp) (insert "\n"))
13473 (forward-char 1)
13474 (if (and (not (looking-at outline-regexp))
13475 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13476 "[^\r\n]*"))
13477 (not (equal (match-string 1) org-clock-string)))
13478 (narrow-to-region (match-beginning 0) (match-end 0))
13479 (insert-before-markers "\n")
13480 (backward-char 1)
13481 (narrow-to-region (point) (point))
13482 (indent-to-column col))
13483 ;; Check if we have to remove something.
13484 (setq list (cons what remove))
13485 (while list
13486 (setq elt (pop list))
13487 (goto-char (point-min))
13488 (when (or (and (eq elt 'scheduled)
13489 (re-search-forward org-scheduled-time-regexp nil t))
13490 (and (eq elt 'deadline)
13491 (re-search-forward org-deadline-time-regexp nil t))
13492 (and (eq elt 'closed)
13493 (re-search-forward org-closed-time-regexp nil t)))
13494 (replace-match "")
13495 (if (looking-at "--+<[^>]+>") (replace-match ""))
13496 (if (looking-at " +") (replace-match ""))))
13497 (goto-char (point-max))
13498 (when what
13499 (insert
13500 (if (not (equal (char-before) ?\ )) " " "")
13501 (cond ((eq what 'scheduled) org-scheduled-string)
13502 ((eq what 'deadline) org-deadline-string)
13503 ((eq what 'closed) org-closed-string))
13504 " ")
13505 (setq ts (org-insert-time-stamp
13506 time
13507 (or org-time-was-given
13508 (and (eq what 'closed) org-log-done-with-time))
13509 (eq what 'closed)
13510 nil nil (list org-end-time-was-given)))
13511 (end-of-line 1))
13512 (goto-char (point-min))
13513 (widen)
13514 (if (looking-at "[ \t]+\r?\n")
13515 (replace-match ""))
13516 ts)))))
13518 (defvar org-log-note-marker (make-marker))
13519 (defvar org-log-note-purpose nil)
13520 (defvar org-log-note-state nil)
13521 (defvar org-log-note-window-configuration nil)
13522 (defvar org-log-note-return-to (make-marker))
13523 (defvar org-log-post-message nil
13524 "Message to be displayed after a log note has been stored.
13525 The auto-repeater uses this.")
13527 (defun org-add-log-maybe (&optional purpose state findpos)
13528 "Set up the post command hook to take a note."
13529 (save-excursion
13530 (when (and (listp org-log-done)
13531 (memq purpose org-log-done))
13532 (when findpos
13533 (org-back-to-heading t)
13534 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
13535 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13536 "[^\r\n]*\\)?"))
13537 (goto-char (match-end 0))
13538 (unless org-log-states-order-reversed
13539 (and (= (char-after) ?\n) (forward-char 1))
13540 (org-skip-over-state-notes)
13541 (skip-chars-backward " \t\n\r")))
13542 (move-marker org-log-note-marker (point))
13543 (setq org-log-note-purpose purpose)
13544 (setq org-log-note-state state)
13545 (add-hook 'post-command-hook 'org-add-log-note 'append))))
13547 (defun org-skip-over-state-notes ()
13548 "Skip past the list of State notes in an entry."
13549 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13550 (while (looking-at "[ \t]*- State")
13551 (condition-case nil
13552 (org-next-item)
13553 (error (org-end-of-item)))))
13555 (defun org-add-log-note (&optional purpose)
13556 "Pop up a window for taking a note, and add this note later at point."
13557 (remove-hook 'post-command-hook 'org-add-log-note)
13558 (setq org-log-note-window-configuration (current-window-configuration))
13559 (delete-other-windows)
13560 (move-marker org-log-note-return-to (point))
13561 (switch-to-buffer (marker-buffer org-log-note-marker))
13562 (goto-char org-log-note-marker)
13563 (org-switch-to-buffer-other-window "*Org Note*")
13564 (erase-buffer)
13565 (let ((org-inhibit-startup t)) (org-mode))
13566 (insert (format "# Insert note for %s.
13567 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13568 (cond
13569 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13570 ((eq org-log-note-purpose 'done) "closed todo item")
13571 ((eq org-log-note-purpose 'state)
13572 (format "state change to \"%s\"" org-log-note-state))
13573 (t (error "This should not happen")))))
13574 (org-set-local 'org-finish-function 'org-store-log-note))
13576 (defun org-store-log-note ()
13577 "Finish taking a log note, and insert it to where it belongs."
13578 (let ((txt (buffer-string))
13579 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13580 lines ind)
13581 (kill-buffer (current-buffer))
13582 (while (string-match "\\`#.*\n[ \t\n]*" txt)
13583 (setq txt (replace-match "" t t txt)))
13584 (if (string-match "\\s-+\\'" txt)
13585 (setq txt (replace-match "" t t txt)))
13586 (setq lines (org-split-string txt "\n"))
13587 (when (and note (string-match "\\S-" note))
13588 (setq note
13589 (org-replace-escapes
13590 note
13591 (list (cons "%u" (user-login-name))
13592 (cons "%U" user-full-name)
13593 (cons "%t" (format-time-string
13594 (org-time-stamp-format 'long 'inactive)
13595 (current-time)))
13596 (cons "%s" (if org-log-note-state
13597 (concat "\"" org-log-note-state "\"")
13598 "")))))
13599 (if lines (setq note (concat note " \\\\")))
13600 (push note lines))
13601 (when (or current-prefix-arg org-note-abort (setq lines nil)))
13602 (when lines
13603 (save-excursion
13604 (set-buffer (marker-buffer org-log-note-marker))
13605 (save-excursion
13606 (goto-char org-log-note-marker)
13607 (move-marker org-log-note-marker nil)
13608 (end-of-line 1)
13609 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13610 (indent-relative nil)
13611 (insert " - " (pop lines))
13612 (org-indent-line-function)
13613 (beginning-of-line 1)
13614 (looking-at "[ \t]*")
13615 (setq ind (concat (match-string 0) " "))
13616 (end-of-line 1)
13617 (while lines (insert "\n" ind (pop lines)))))))
13618 (set-window-configuration org-log-note-window-configuration)
13619 (with-current-buffer (marker-buffer org-log-note-return-to)
13620 (goto-char org-log-note-return-to))
13621 (move-marker org-log-note-return-to nil)
13622 (and org-log-post-message (message org-log-post-message)))
13624 (defvar org-occur-highlights nil)
13625 (make-variable-buffer-local 'org-occur-highlights)
13627 (defun org-occur (regexp &optional keep-previous callback)
13628 "Make a compact tree which shows all matches of REGEXP.
13629 The tree will show the lines where the regexp matches, and all higher
13630 headlines above the match. It will also show the heading after the match,
13631 to make sure editing the matching entry is easy.
13632 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13633 call to `org-occur' will be kept, to allow stacking of calls to this
13634 command.
13635 If CALLBACK is non-nil, it is a function which is called to confirm
13636 that the match should indeed be shown."
13637 (interactive "sRegexp: \nP")
13638 (or keep-previous (org-remove-occur-highlights nil nil t))
13639 (let ((cnt 0))
13640 (save-excursion
13641 (goto-char (point-min))
13642 (if (or (not keep-previous) ; do not want to keep
13643 (not org-occur-highlights)) ; no previous matches
13644 ;; hide everything
13645 (org-overview))
13646 (while (re-search-forward regexp nil t)
13647 (when (or (not callback)
13648 (save-match-data (funcall callback)))
13649 (setq cnt (1+ cnt))
13650 (when org-highlight-sparse-tree-matches
13651 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13652 (org-show-context 'occur-tree))))
13653 (when org-remove-highlights-with-change
13654 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13655 nil 'local))
13656 (unless org-sparse-tree-open-archived-trees
13657 (org-hide-archived-subtrees (point-min) (point-max)))
13658 (run-hooks 'org-occur-hook)
13659 (if (interactive-p)
13660 (message "%d match(es) for regexp %s" cnt regexp))
13661 cnt))
13663 (defun org-show-context (&optional key)
13664 "Make sure point and context and visible.
13665 How much context is shown depends upon the variables
13666 `org-show-hierarchy-above', `org-show-following-heading'. and
13667 `org-show-siblings'."
13668 (let ((heading-p (org-on-heading-p t))
13669 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13670 (following-p (org-get-alist-option org-show-following-heading key))
13671 (siblings-p (org-get-alist-option org-show-siblings key)))
13672 (catch 'exit
13673 ;; Show heading or entry text
13674 (if heading-p
13675 (org-flag-heading nil) ; only show the heading
13676 (and (or (org-invisible-p) (org-invisible-p2))
13677 (org-show-hidden-entry))) ; show entire entry
13678 (when following-p
13679 ;; Show next sibling, or heading below text
13680 (save-excursion
13681 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13682 (org-flag-heading nil))))
13683 (when siblings-p (org-show-siblings))
13684 (when hierarchy-p
13685 ;; show all higher headings, possibly with siblings
13686 (save-excursion
13687 (while (and (condition-case nil
13688 (progn (org-up-heading-all 1) t)
13689 (error nil))
13690 (not (bobp)))
13691 (org-flag-heading nil)
13692 (when siblings-p (org-show-siblings))))))))
13694 (defun org-reveal (&optional siblings)
13695 "Show current entry, hierarchy above it, and the following headline.
13696 This can be used to show a consistent set of context around locations
13697 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13698 not t for the search context.
13700 With optional argument SIBLINGS, on each level of the hierarchy all
13701 siblings are shown. This repairs the tree structure to what it would
13702 look like when opened with hierarchical calls to `org-cycle'."
13703 (interactive "P")
13704 (let ((org-show-hierarchy-above t)
13705 (org-show-following-heading t)
13706 (org-show-siblings (if siblings t org-show-siblings)))
13707 (org-show-context nil)))
13709 (defun org-highlight-new-match (beg end)
13710 "Highlight from BEG to END and mark the highlight is an occur headline."
13711 (let ((ov (org-make-overlay beg end)))
13712 (org-overlay-put ov 'face 'secondary-selection)
13713 (push ov org-occur-highlights)))
13715 (defun org-remove-occur-highlights (&optional beg end noremove)
13716 "Remove the occur highlights from the buffer.
13717 BEG and END are ignored. If NOREMOVE is nil, remove this function
13718 from the `before-change-functions' in the current buffer."
13719 (interactive)
13720 (unless org-inhibit-highlight-removal
13721 (mapc 'org-delete-overlay org-occur-highlights)
13722 (setq org-occur-highlights nil)
13723 (unless noremove
13724 (remove-hook 'before-change-functions
13725 'org-remove-occur-highlights 'local))))
13727 ;;;; Priorities
13729 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13730 "Regular expression matching the priority indicator.")
13732 (defvar org-remove-priority-next-time nil)
13734 (defun org-priority-up ()
13735 "Increase the priority of the current item."
13736 (interactive)
13737 (org-priority 'up))
13739 (defun org-priority-down ()
13740 "Decrease the priority of the current item."
13741 (interactive)
13742 (org-priority 'down))
13744 (defun org-priority (&optional action)
13745 "Change the priority of an item by ARG.
13746 ACTION can be `set', `up', `down', or a character."
13747 (interactive)
13748 (setq action (or action 'set))
13749 (let (current new news have remove)
13750 (save-excursion
13751 (org-back-to-heading)
13752 (if (looking-at org-priority-regexp)
13753 (setq current (string-to-char (match-string 2))
13754 have t)
13755 (setq current org-default-priority))
13756 (cond
13757 ((or (eq action 'set) (integerp action))
13758 (if (integerp action)
13759 (setq new action)
13760 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
13761 (setq new (read-char-exclusive)))
13762 (if (and (= (upcase org-highest-priority) org-highest-priority)
13763 (= (upcase org-lowest-priority) org-lowest-priority))
13764 (setq new (upcase new)))
13765 (cond ((equal new ?\ ) (setq remove t))
13766 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13767 (error "Priority must be between `%c' and `%c'"
13768 org-highest-priority org-lowest-priority))))
13769 ((eq action 'up)
13770 (if (and (not have) (eq last-command this-command))
13771 (setq new org-lowest-priority)
13772 (setq new (if (and org-priority-start-cycle-with-default (not have))
13773 org-default-priority (1- current)))))
13774 ((eq action 'down)
13775 (if (and (not have) (eq last-command this-command))
13776 (setq new org-highest-priority)
13777 (setq new (if (and org-priority-start-cycle-with-default (not have))
13778 org-default-priority (1+ current)))))
13779 (t (error "Invalid action")))
13780 (if (or (< (upcase new) org-highest-priority)
13781 (> (upcase new) org-lowest-priority))
13782 (setq remove t))
13783 (setq news (format "%c" new))
13784 (if have
13785 (if remove
13786 (replace-match "" t t nil 1)
13787 (replace-match news t t nil 2))
13788 (if remove
13789 (error "No priority cookie found in line")
13790 (looking-at org-todo-line-regexp)
13791 (if (match-end 2)
13792 (progn
13793 (goto-char (match-end 2))
13794 (insert " [#" news "]"))
13795 (goto-char (match-beginning 3))
13796 (insert "[#" news "] ")))))
13797 (org-preserve-lc (org-set-tags nil 'align))
13798 (if remove
13799 (message "Priority removed")
13800 (message "Priority of current item set to %s" news))))
13803 (defun org-get-priority (s)
13804 "Find priority cookie and return priority."
13805 (save-match-data
13806 (if (not (string-match org-priority-regexp s))
13807 (* 1000 (- org-lowest-priority org-default-priority))
13808 (* 1000 (- org-lowest-priority
13809 (string-to-char (match-string 2 s)))))))
13811 ;;;; Tags
13813 (defun org-scan-tags (action matcher &optional todo-only)
13814 "Scan headline tags with inheritance and produce output ACTION.
13815 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
13816 evaluated, testing if a given set of tags qualifies a headline for
13817 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
13818 are included in the output."
13819 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
13820 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13821 (org-re
13822 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
13823 (props (list 'face nil
13824 'done-face 'org-done
13825 'undone-face nil
13826 'mouse-face 'highlight
13827 'org-not-done-regexp org-not-done-regexp
13828 'org-todo-regexp org-todo-regexp
13829 'keymap org-agenda-keymap
13830 'help-echo
13831 (format "mouse-2 or RET jump to org file %s"
13832 (abbreviate-file-name buffer-file-name))))
13833 (case-fold-search nil)
13834 lspos
13835 tags tags-list tags-alist (llast 0) rtn level category i txt
13836 todo marker entry priority)
13837 (save-excursion
13838 (goto-char (point-min))
13839 (when (eq action 'sparse-tree)
13840 (org-overview)
13841 (org-remove-occur-highlights))
13842 (while (re-search-forward re nil t)
13843 (catch :skip
13844 (setq todo (if (match-end 1) (match-string 2))
13845 tags (if (match-end 4) (match-string 4)))
13846 (goto-char (setq lspos (1+ (match-beginning 0))))
13847 (setq level (org-reduced-level (funcall outline-level))
13848 category (org-get-category))
13849 (setq i llast llast level)
13850 ;; remove tag lists from same and sublevels
13851 (while (>= i level)
13852 (when (setq entry (assoc i tags-alist))
13853 (setq tags-alist (delete entry tags-alist)))
13854 (setq i (1- i)))
13855 ;; add the nex tags
13856 (when tags
13857 (setq tags (mapcar 'downcase (org-split-string tags ":"))
13858 tags-alist
13859 (cons (cons level tags) tags-alist)))
13860 ;; compile tags for current headline
13861 (setq tags-list
13862 (if org-use-tag-inheritance
13863 (apply 'append (mapcar 'cdr tags-alist))
13864 tags))
13865 (when (and (or (not todo-only) (member todo org-not-done-keywords))
13866 (eval matcher)
13867 (or (not org-agenda-skip-archived-trees)
13868 (not (member org-archive-tag tags-list))))
13869 (and (eq action 'agenda) (org-agenda-skip))
13870 ;; list this headline
13872 (if (eq action 'sparse-tree)
13873 (progn
13874 (and org-highlight-sparse-tree-matches
13875 (org-get-heading) (match-end 0)
13876 (org-highlight-new-match
13877 (match-beginning 0) (match-beginning 1)))
13878 (org-show-context 'tags-tree))
13879 (setq txt (org-format-agenda-item
13881 (concat
13882 (if org-tags-match-list-sublevels
13883 (make-string (1- level) ?.) "")
13884 (org-get-heading))
13885 category tags-list)
13886 priority (org-get-priority txt))
13887 (goto-char lspos)
13888 (setq marker (org-agenda-new-marker))
13889 (org-add-props txt props
13890 'org-marker marker 'org-hd-marker marker 'org-category category
13891 'priority priority 'type "tagsmatch")
13892 (push txt rtn))
13893 ;; if we are to skip sublevels, jump to end of subtree
13894 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
13895 (when (and (eq action 'sparse-tree)
13896 (not org-sparse-tree-open-archived-trees))
13897 (org-hide-archived-subtrees (point-min) (point-max)))
13898 (nreverse rtn)))
13900 (defvar todo-only) ;; dynamically scoped
13902 (defun org-tags-sparse-tree (&optional todo-only match)
13903 "Create a sparse tree according to tags string MATCH.
13904 MATCH can contain positive and negative selection of tags, like
13905 \"+WORK+URGENT-WITHBOSS\".
13906 If optional argument TODO_ONLY is non-nil, only select lines that are
13907 also TODO lines."
13908 (interactive "P")
13909 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13911 (defvar org-cached-props nil)
13912 (defun org-cached-entry-get (pom property)
13913 (if org-use-property-inheritance
13914 ;; Caching is not possible, check it directly
13915 (org-entry-get pom property 'inherit)
13916 ;; Get all properties, so that we can do complicated checks easily
13917 (cdr (assoc property (or org-cached-props
13918 (setq org-cached-props
13919 (org-entry-properties pom)))))))
13921 (defun org-global-tags-completion-table (&optional files)
13922 "Return the list of all tags in all agenda buffer/files."
13923 (save-excursion
13924 (org-uniquify
13925 (apply 'append
13926 (mapcar
13927 (lambda (file)
13928 (set-buffer (find-file-noselect file))
13929 (org-get-buffer-tags))
13930 (if (and files (car files))
13931 files
13932 (org-agenda-files)))))))
13934 (defun org-make-tags-matcher (match)
13935 "Create the TAGS//TODO matcher form for the selection string MATCH."
13936 ;; todo-only is scoped dynamically into this function, and the function
13937 ;; may change it it the matcher asksk for it.
13938 (unless match
13939 ;; Get a new match request, with completion
13940 (let ((org-last-tags-completion-table
13941 (org-global-tags-completion-table)))
13942 (setq match (completing-read
13943 "Match: " 'org-tags-completion-function nil nil nil
13944 'org-tags-history))))
13946 ;; Parse the string and create a lisp form
13947 (let ((match0 match)
13948 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
13949 minus tag mm
13950 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13951 orterms term orlist re-p level-p prop-p pn pv)
13952 (if (string-match "/+" match)
13953 ;; match contains also a todo-matching request
13954 (progn
13955 (setq tagsmatch (substring match 0 (match-beginning 0))
13956 todomatch (substring match (match-end 0)))
13957 (if (string-match "^!" todomatch)
13958 (setq todo-only t todomatch (substring todomatch 1)))
13959 (if (string-match "^\\s-*$" todomatch)
13960 (setq todomatch nil)))
13961 ;; only matching tags
13962 (setq tagsmatch match todomatch nil))
13964 ;; Make the tags matcher
13965 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13966 (setq tagsmatcher t)
13967 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13968 (while (setq term (pop orterms))
13969 (while (and (equal (substring term -1) "\\") orterms)
13970 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13971 (while (string-match re term)
13972 (setq minus (and (match-end 1)
13973 (equal (match-string 1 term) "-"))
13974 tag (match-string 2 term)
13975 re-p (equal (string-to-char tag) ?{)
13976 level-p (match-end 3)
13977 prop-p (match-end 4)
13978 mm (cond
13979 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13980 (level-p `(= level ,(string-to-number
13981 (match-string 3 term))))
13982 (prop-p
13983 (setq pn (match-string 4 term)
13984 pv (match-string 5 term)
13985 re-p (equal (string-to-char pv) ?{)
13986 pv (substring pv 1 -1))
13987 (if re-p
13988 `(string-match ,pv (or (org-cached-entry-get nil ,pn) ""))
13989 `(equal ,pv (org-cached-entry-get nil ,pn))))
13990 (t `(member ,(downcase tag) tags-list)))
13991 mm (if minus (list 'not mm) mm)
13992 term (substring term (match-end 0)))
13993 (push mm tagsmatcher))
13994 (push (if (> (length tagsmatcher) 1)
13995 (cons 'and tagsmatcher)
13996 (car tagsmatcher))
13997 orlist)
13998 (setq tagsmatcher nil))
13999 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14000 (setq tagsmatcher
14001 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14003 ;; Make the todo matcher
14004 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14005 (setq todomatcher t)
14006 (setq orterms (org-split-string todomatch "|") orlist nil)
14007 (while (setq term (pop orterms))
14008 (while (string-match re term)
14009 (setq minus (and (match-end 1)
14010 (equal (match-string 1 term) "-"))
14011 kwd (match-string 2 term)
14012 re-p (equal (string-to-char kwd) ?{)
14013 term (substring term (match-end 0))
14014 mm (if re-p
14015 `(string-match ,(substring kwd 1 -1) todo)
14016 (list 'equal 'todo kwd))
14017 mm (if minus (list 'not mm) mm))
14018 (push mm todomatcher))
14019 (push (if (> (length todomatcher) 1)
14020 (cons 'and todomatcher)
14021 (car todomatcher))
14022 orlist)
14023 (setq todomatcher nil))
14024 (setq todomatcher (if (> (length orlist) 1)
14025 (cons 'or orlist) (car orlist))))
14027 ;; Return the string and lisp forms of the matcher
14028 (setq matcher (if todomatcher
14029 (list 'and tagsmatcher todomatcher)
14030 tagsmatcher))
14031 (cons match0 matcher)))
14033 (defun org-match-any-p (re list)
14034 "Does re match any element of list?"
14035 (setq list (mapcar (lambda (x) (string-match re x)) list))
14036 (delq nil list))
14038 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
14039 (defvar org-tags-overlay (org-make-overlay 1 1))
14040 (org-detach-overlay org-tags-overlay)
14042 (defun org-align-tags-here (to-col)
14043 ;; Assumes that this is a headline
14044 (let ((pos (point)) (col (current-column)) tags)
14045 (beginning-of-line 1)
14046 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14047 (< pos (match-beginning 2)))
14048 (progn
14049 (setq tags (match-string 2))
14050 (goto-char (match-beginning 1))
14051 (insert " ")
14052 (delete-region (point) (1+ (match-end 0)))
14053 (backward-char 1)
14054 (move-to-column
14055 (max (1+ (current-column))
14056 (1+ col)
14057 (if (> to-col 0)
14058 to-col
14059 (- (abs to-col) (length tags))))
14061 (insert tags)
14062 (move-to-column (min (current-column) col) t))
14063 (goto-char pos))))
14065 (defun org-set-tags (&optional arg just-align)
14066 "Set the tags for the current headline.
14067 With prefix ARG, realign all tags in headings in the current buffer."
14068 (interactive "P")
14069 (let* ((re (concat "^" outline-regexp))
14070 (current (org-get-tags-string))
14071 (col (current-column))
14072 (org-setting-tags t)
14073 table current-tags inherited-tags ; computed below when needed
14074 tags p0 c0 c1 rpl)
14075 (if arg
14076 (save-excursion
14077 (goto-char (point-min))
14078 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14079 (while (re-search-forward re nil t)
14080 (org-set-tags nil t)
14081 (end-of-line 1)))
14082 (message "All tags realigned to column %d" org-tags-column))
14083 (if just-align
14084 (setq tags current)
14085 ;; Get a new set of tags from the user
14086 (save-excursion
14087 (setq table (or org-tag-alist (org-get-buffer-tags))
14088 org-last-tags-completion-table table
14089 current-tags (org-split-string current ":")
14090 inherited-tags (nreverse
14091 (nthcdr (length current-tags)
14092 (nreverse (org-get-tags-at))))
14093 tags
14094 (if (or (eq t org-use-fast-tag-selection)
14095 (and org-use-fast-tag-selection
14096 (delq nil (mapcar 'cdr table))))
14097 (org-fast-tag-selection
14098 current-tags inherited-tags table
14099 (if org-fast-tag-selection-include-todo org-todo-key-alist))
14100 (let ((org-add-colon-after-tag-completion t))
14101 (org-trim
14102 (org-without-partial-completion
14103 (completing-read "Tags: " 'org-tags-completion-function
14104 nil nil current 'org-tags-history)))))))
14105 (while (string-match "[-+&]+" tags)
14106 ;; No boolean logic, just a list
14107 (setq tags (replace-match ":" t t tags))))
14109 (if (string-match "\\`[\t ]*\\'" tags)
14110 (setq tags "")
14111 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14112 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14114 ;; Insert new tags at the correct column
14115 (beginning-of-line 1)
14116 (cond
14117 ((and (equal current "") (equal tags "")))
14118 ((re-search-forward
14119 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14120 (point-at-eol) t)
14121 (if (equal tags "")
14122 (setq rpl "")
14123 (goto-char (match-beginning 0))
14124 (setq c0 (current-column) p0 (point)
14125 c1 (max (1+ c0) (if (> org-tags-column 0)
14126 org-tags-column
14127 (- (- org-tags-column) (length tags))))
14128 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14129 (replace-match rpl t t)
14130 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
14131 tags)
14132 (t (error "Tags alignment failed")))
14133 (move-to-column col)
14134 (unless just-align
14135 (run-hooks 'org-after-tags-change-hook)))))
14137 (defun org-change-tag-in-region (beg end tag off)
14138 "Add or remove TAG for each entry in the region.
14139 This works in the agenda, and also in an org-mode buffer."
14140 (interactive
14141 (list (region-beginning) (region-end)
14142 (let ((org-last-tags-completion-table
14143 (if (org-mode-p)
14144 (org-get-buffer-tags)
14145 (org-global-tags-completion-table))))
14146 (completing-read
14147 "Tag: " 'org-tags-completion-function nil nil nil
14148 'org-tags-history))
14149 (progn
14150 (message "[s]et or [r]emove? ")
14151 (equal (read-char-exclusive) ?r))))
14152 (if (fboundp 'deactivate-mark) (deactivate-mark))
14153 (let ((agendap (equal major-mode 'org-agenda-mode))
14154 l1 l2 m buf pos newhead (cnt 0))
14155 (goto-char end)
14156 (setq l2 (1- (org-current-line)))
14157 (goto-char beg)
14158 (setq l1 (org-current-line))
14159 (loop for l from l1 to l2 do
14160 (goto-line l)
14161 (setq m (get-text-property (point) 'org-hd-marker))
14162 (when (or (and (org-mode-p) (org-on-heading-p))
14163 (and agendap m))
14164 (setq buf (if agendap (marker-buffer m) (current-buffer))
14165 pos (if agendap m (point)))
14166 (with-current-buffer buf
14167 (save-excursion
14168 (save-restriction
14169 (goto-char pos)
14170 (setq cnt (1+ cnt))
14171 (org-toggle-tag tag (if off 'off 'on))
14172 (setq newhead (org-get-heading)))))
14173 (and agendap (org-agenda-change-all-lines newhead m))))
14174 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14176 (defun org-tags-completion-function (string predicate &optional flag)
14177 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14178 (confirm (lambda (x) (stringp (car x)))))
14179 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
14180 (setq s1 (match-string 1 string)
14181 s2 (match-string 2 string))
14182 (setq s1 "" s2 string))
14183 (cond
14184 ((eq flag nil)
14185 ;; try completion
14186 (setq rtn (try-completion s2 ctable confirm))
14187 (if (stringp rtn)
14188 (setq rtn
14189 (concat s1 s2 (substring rtn (length s2))
14190 (if (and org-add-colon-after-tag-completion
14191 (assoc rtn ctable))
14192 ":" ""))))
14193 rtn)
14194 ((eq flag t)
14195 ;; all-completions
14196 (all-completions s2 ctable confirm)
14198 ((eq flag 'lambda)
14199 ;; exact match?
14200 (assoc s2 ctable)))
14203 (defun org-fast-tag-insert (kwd tags face &optional end)
14204 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
14205 (insert (format "%-12s" (concat kwd ":"))
14206 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14207 (or end "")))
14209 (defun org-fast-tag-show-exit (flag)
14210 (save-excursion
14211 (goto-line 3)
14212 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14213 (replace-match ""))
14214 (when flag
14215 (end-of-line 1)
14216 (move-to-column (- (window-width) 19) t)
14217 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14219 (defun org-set-current-tags-overlay (current prefix)
14220 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14221 (if (featurep 'xemacs)
14222 (org-overlay-display org-tags-overlay (concat prefix s)
14223 'secondary-selection)
14224 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14225 (org-overlay-display org-tags-overlay (concat prefix s)))))
14227 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14228 "Fast tag selection with single keys.
14229 CURRENT is the current list of tags in the headline, INHERITED is the
14230 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14231 possibly with grouping information. TODO-TABLE is a similar table with
14232 TODO keywords, should these have keys assigned to them.
14233 If the keys are nil, a-z are automatically assigned.
14234 Returns the new tags string, or nil to not change the current settings."
14235 (let* ((fulltable (append table todo-table))
14236 (maxlen (apply 'max (mapcar
14237 (lambda (x)
14238 (if (stringp (car x)) (string-width (car x)) 0))
14239 fulltable)))
14240 (buf (current-buffer))
14241 (expert (eq org-fast-tag-selection-single-key 'expert))
14242 (buffer-tags nil)
14243 (fwidth (+ maxlen 3 1 3))
14244 (ncol (/ (- (window-width) 4) fwidth))
14245 (i-face 'org-done)
14246 (c-face 'org-todo)
14247 tg cnt e c char c1 c2 ntable tbl rtn
14248 ov-start ov-end ov-prefix
14249 (exit-after-next org-fast-tag-selection-single-key)
14250 (done-keywords org-done-keywords)
14251 groups ingroup)
14252 (save-excursion
14253 (beginning-of-line 1)
14254 (if (looking-at
14255 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14256 (setq ov-start (match-beginning 1)
14257 ov-end (match-end 1)
14258 ov-prefix "")
14259 (setq ov-start (1- (point-at-eol))
14260 ov-end (1+ ov-start))
14261 (skip-chars-forward "^\n\r")
14262 (setq ov-prefix
14263 (concat
14264 (buffer-substring (1- (point)) (point))
14265 (if (> (current-column) org-tags-column)
14267 (make-string (- org-tags-column (current-column)) ?\ ))))))
14268 (org-move-overlay org-tags-overlay ov-start ov-end)
14269 (save-window-excursion
14270 (if expert
14271 (set-buffer (get-buffer-create " *Org tags*"))
14272 (delete-other-windows)
14273 (split-window-vertically)
14274 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14275 (erase-buffer)
14276 (org-set-local 'org-done-keywords done-keywords)
14277 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14278 (org-fast-tag-insert "Current" current c-face "\n\n")
14279 (org-fast-tag-show-exit exit-after-next)
14280 (org-set-current-tags-overlay current ov-prefix)
14281 (setq tbl fulltable char ?a cnt 0)
14282 (while (setq e (pop tbl))
14283 (cond
14284 ((equal e '(:startgroup))
14285 (push '() groups) (setq ingroup t)
14286 (when (not (= cnt 0))
14287 (setq cnt 0)
14288 (insert "\n"))
14289 (insert "{ "))
14290 ((equal e '(:endgroup))
14291 (setq ingroup nil cnt 0)
14292 (insert "}\n"))
14294 (setq tg (car e) c2 nil)
14295 (if (cdr e)
14296 (setq c (cdr e))
14297 ;; automatically assign a character.
14298 (setq c1 (string-to-char
14299 (downcase (substring
14300 tg (if (= (string-to-char tg) ?@) 1 0)))))
14301 (if (or (rassoc c1 ntable) (rassoc c1 table))
14302 (while (or (rassoc char ntable) (rassoc char table))
14303 (setq char (1+ char)))
14304 (setq c2 c1))
14305 (setq c (or c2 char)))
14306 (if ingroup (push tg (car groups)))
14307 (setq tg (org-add-props tg nil 'face
14308 (cond
14309 ((not (assoc tg table))
14310 (org-get-todo-face tg))
14311 ((member tg current) c-face)
14312 ((member tg inherited) i-face)
14313 (t nil))))
14314 (if (and (= cnt 0) (not ingroup)) (insert " "))
14315 (insert "[" c "] " tg (make-string
14316 (- fwidth 4 (length tg)) ?\ ))
14317 (push (cons tg c) ntable)
14318 (when (= (setq cnt (1+ cnt)) ncol)
14319 (insert "\n")
14320 (if ingroup (insert " "))
14321 (setq cnt 0)))))
14322 (setq ntable (nreverse ntable))
14323 (insert "\n")
14324 (goto-char (point-min))
14325 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14326 (fit-window-to-buffer))
14327 (setq rtn
14328 (catch 'exit
14329 (while t
14330 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
14331 (if groups " [!] no groups" " [!]groups")
14332 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14333 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14334 (cond
14335 ((= c ?\r) (throw 'exit t))
14336 ((= c ?!)
14337 (setq groups (not groups))
14338 (goto-char (point-min))
14339 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14340 ((= c ?\C-c)
14341 (if (not expert)
14342 (org-fast-tag-show-exit
14343 (setq exit-after-next (not exit-after-next)))
14344 (setq expert nil)
14345 (delete-other-windows)
14346 (split-window-vertically)
14347 (org-switch-to-buffer-other-window " *Org tags*")
14348 (and (fboundp 'fit-window-to-buffer)
14349 (fit-window-to-buffer))))
14350 ((or (= c ?\C-g)
14351 (and (= c ?q) (not (rassoc c ntable))))
14352 (org-detach-overlay org-tags-overlay)
14353 (setq quit-flag t))
14354 ((= c ?\ )
14355 (setq current nil)
14356 (if exit-after-next (setq exit-after-next 'now)))
14357 ((= c ?\t)
14358 (condition-case nil
14359 (setq tg (completing-read
14360 "Tag: "
14361 (or buffer-tags
14362 (with-current-buffer buf
14363 (org-get-buffer-tags)))))
14364 (quit (setq tg "")))
14365 (when (string-match "\\S-" tg)
14366 (add-to-list 'buffer-tags (list tg))
14367 (if (member tg current)
14368 (setq current (delete tg current))
14369 (push tg current)))
14370 (if exit-after-next (setq exit-after-next 'now)))
14371 ((setq e (rassoc c todo-table) tg (car e))
14372 (with-current-buffer buf
14373 (save-excursion (org-todo tg)))
14374 (if exit-after-next (setq exit-after-next 'now)))
14375 ((setq e (rassoc c ntable) tg (car e))
14376 (if (member tg current)
14377 (setq current (delete tg current))
14378 (loop for g in groups do
14379 (if (member tg g)
14380 (mapcar (lambda (x)
14381 (setq current (delete x current)))
14382 g)))
14383 (push tg current))
14384 (if exit-after-next (setq exit-after-next 'now))))
14386 ;; Create a sorted list
14387 (setq current
14388 (sort current
14389 (lambda (a b)
14390 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14391 (if (eq exit-after-next 'now) (throw 'exit t))
14392 (goto-char (point-min))
14393 (beginning-of-line 2)
14394 (delete-region (point) (point-at-eol))
14395 (org-fast-tag-insert "Current" current c-face)
14396 (org-set-current-tags-overlay current ov-prefix)
14397 (while (re-search-forward
14398 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
14399 (setq tg (match-string 1))
14400 (add-text-properties
14401 (match-beginning 1) (match-end 1)
14402 (list 'face
14403 (cond
14404 ((member tg current) c-face)
14405 ((member tg inherited) i-face)
14406 (t (get-text-property (match-beginning 1) 'face))))))
14407 (goto-char (point-min)))))
14408 (org-detach-overlay org-tags-overlay)
14409 (if rtn
14410 (mapconcat 'identity current ":")
14411 nil))))
14413 (defun org-get-tags-string ()
14414 "Get the TAGS string in the current headline."
14415 (unless (org-on-heading-p t)
14416 (error "Not on a heading"))
14417 (save-excursion
14418 (beginning-of-line 1)
14419 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14420 (org-match-string-no-properties 1)
14421 "")))
14423 (defun org-get-tags ()
14424 "Get the list of tags specified in the current headline."
14425 (org-split-string (org-get-tags-string) ":"))
14427 (defun org-get-buffer-tags ()
14428 "Get a table of all tags used in the buffer, for completion."
14429 (let (tags)
14430 (save-excursion
14431 (goto-char (point-min))
14432 (while (re-search-forward
14433 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
14434 (when (equal (char-after (point-at-bol 0)) ?*)
14435 (mapc (lambda (x) (add-to-list 'tags x))
14436 (org-split-string (org-match-string-no-properties 1) ":")))))
14437 (mapcar 'list tags)))
14440 ;;;; Properties
14442 ;;; Setting and retrieving properties
14444 (defconst org-special-properties
14445 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY")
14446 "The special properties valid in Org-mode.
14448 These are properties that are not defined in the property drawer,
14449 but in some other way.")
14451 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14452 "Regular expression matching the first line of a property drawer.")
14454 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14455 "Regular expression matching the first line of a property drawer.")
14457 (defun org-property-action ()
14458 "Do an action on properties."
14459 (interactive)
14460 (let (c prop)
14461 (org-at-property-p)
14462 (setq prop (match-string 2))
14463 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14464 (setq c (read-char-exclusive))
14465 (cond
14466 ((equal c ?s)
14467 (call-interactively 'org-set-property))
14468 ((equal c ?d)
14469 (call-interactively 'org-delete-property))
14470 ((equal c ?D)
14471 (call-interactively 'org-delete-property-globally))
14472 ((equal c ?c)
14473 (call-interactively 'org-compute-property-at-point))
14474 (t (error "No such property action %c" c)))))
14476 (defun org-at-property-p ()
14477 "Is the cursor in a property line?"
14478 ;; FIXME: Does not check if we are actually in the drawer.
14479 ;; FIXME: also returns true on any drawers.....
14480 ;; This is used by C-c C-c for property action.
14481 (save-excursion
14482 (beginning-of-line 1)
14483 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
14485 (defmacro org-with-point-at (pom &rest body)
14486 "Move to buffer and point of point-or-marker POM for the duration of BODY."
14487 (declare (indent 1) (debug t))
14488 `(save-excursion
14489 (if (markerp pom) (set-buffer (marker-buffer pom)))
14490 (save-excursion
14491 (goto-char (or pom (point)))
14492 ,@body)))
14494 (defun org-get-property-block (&optional beg end force)
14495 "Return the (beg . end) range of the body of the property drawer.
14496 BEG and END can be beginning and end of subtree, if not given
14497 they will be found.
14498 If the drawer does not exist and FORCE is non-nil, create the drawer."
14499 (catch 'exit
14500 (save-excursion
14501 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14502 (end (or end (progn (outline-next-heading) (point)))))
14503 (goto-char beg)
14504 (if (re-search-forward org-property-start-re end t)
14505 (setq beg (1+ (match-end 0)))
14506 (if force
14507 (save-excursion
14508 (org-insert-property-drawer)
14509 (setq end (progn (outline-next-heading) (point))))
14510 (throw 'exit nil))
14511 (goto-char beg)
14512 (if (re-search-forward org-property-start-re end t)
14513 (setq beg (1+ (match-end 0)))))
14514 (if (re-search-forward org-property-end-re end t)
14515 (setq end (match-beginning 0))
14516 (or force (throw 'exit nil))
14517 (goto-char beg)
14518 (setq end beg)
14519 (org-indent-line-function)
14520 (insert ":END:\n"))
14521 (cons beg end)))))
14523 (defun org-entry-properties (&optional pom which)
14524 "Get all properties of the entry at point-or-marker POM.
14525 This includes the TODO keyword, the tags, time strings for deadline,
14526 scheduled, and clocking, and any additional properties defined in the
14527 entry. The return value is an alist, keys may occur multiple times
14528 if the property key was used several times.
14529 POM may also be nil, in which case the current entry is used.
14530 If WHICH is nil or `all', get all properties. If WHICH is
14531 `special' or `standard', only get that subclass."
14532 (setq which (or which 'all))
14533 (org-with-point-at pom
14534 (let ((clockstr (substring org-clock-string 0 -1))
14535 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
14536 beg end range props sum-props key value)
14537 (save-excursion
14538 (when (condition-case nil (org-back-to-heading t) (error nil))
14539 (setq beg (point))
14540 (setq sum-props (get-text-property (point) 'org-summaries))
14541 (outline-next-heading)
14542 (setq end (point))
14543 (when (memq which '(all special))
14544 ;; Get the special properties, like TODO and tags
14545 (goto-char beg)
14546 (when (and (looking-at org-todo-line-regexp) (match-end 2))
14547 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14548 (when (looking-at org-priority-regexp)
14549 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14550 (when (and (setq value (org-get-tags-string))
14551 (string-match "\\S-" value))
14552 (push (cons "TAGS" value) props))
14553 (when (setq value (org-get-tags-at))
14554 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
14555 props))
14556 (while (re-search-forward org-keyword-time-regexp end t)
14557 (setq key (substring (org-match-string-no-properties 1) 0 -1))
14558 (unless (member key excluded) (push key excluded))
14559 (push (cons key
14560 (if (equal key clockstr)
14561 (org-no-properties
14562 (org-trim
14563 (buffer-substring
14564 (match-beginning 2) (point-at-eol))))
14565 (org-match-string-no-properties 2)))
14566 props)))
14567 (when (memq which '(all standard))
14568 ;; Get the standard properties, like :PORP: ...
14569 (setq range (org-get-property-block beg end))
14570 (when range
14571 (goto-char (car range))
14572 (while (re-search-forward
14573 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14574 (cdr range) t)
14575 (setq key (org-match-string-no-properties 1)
14576 value (org-trim (or (org-match-string-no-properties 2) "")))
14577 (unless (member key excluded)
14578 (push (cons key (or value "")) props)))))
14579 (append sum-props (nreverse props)))))))
14581 (defun org-entry-get (pom property &optional inherit)
14582 "Get value of PROPERTY for entry at point-or-marker POM.
14583 If INHERIT is non-nil and the entry does not have the property,
14584 then also check higher levels of the hierarchy.
14585 If the property is present but empty, the return value is the empty string.
14586 If the property is not present at all, nil is returned."
14587 (org-with-point-at pom
14588 (if inherit
14589 (org-entry-get-with-inheritance property)
14590 (if (member property org-special-properties)
14591 ;; We need a special property. Use brute force, get all properties.
14592 (cdr (assoc property (org-entry-properties nil 'special)))
14593 (let ((range (org-get-property-block)))
14594 (if (and range
14595 (goto-char (car range))
14596 (re-search-forward
14597 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
14598 (cdr range) t))
14599 ;; Found the property, return it.
14600 (if (match-end 1)
14601 (org-match-string-no-properties 1)
14602 "")))))))
14604 (defun org-entry-delete (pom property)
14605 "Delete the property PROPERTY from entry at point-or-marker POM."
14606 (org-with-point-at pom
14607 (if (member property org-special-properties)
14608 nil ; cannot delete these properties.
14609 (let ((range (org-get-property-block)))
14610 (if (and range
14611 (goto-char (car range))
14612 (re-search-forward
14613 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
14614 (cdr range) t))
14615 (progn
14616 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14618 nil)))))
14620 (defvar org-entry-property-inherited-from (make-marker))
14622 (defun org-entry-get-with-inheritance (property)
14623 "Get entry property, and search higher levels if not present."
14624 (let (tmp)
14625 (save-excursion
14626 (catch 'ex
14627 (while t
14628 (when (setq tmp (org-entry-get nil property))
14629 (org-back-to-heading t)
14630 (move-marker org-entry-property-inherited-from (point))
14631 (throw 'ex tmp))
14632 (or (org-up-heading-safe) (throw 'ex nil)))))
14633 (or tmp (cdr (assoc property org-local-properties))
14634 (cdr (assoc property org-global-properties)))))
14636 (defun org-entry-put (pom property value)
14637 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14638 (org-with-point-at pom
14639 (org-back-to-heading t)
14640 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14641 range)
14642 (cond
14643 ((equal property "TODO")
14644 (when (and (stringp value) (string-match "\\S-" value)
14645 (not (member value org-todo-keywords-1)))
14646 (error "\"%s\" is not a valid TODO state" value))
14647 (if (or (not value)
14648 (not (string-match "\\S-" value)))
14649 (setq value 'none))
14650 (org-todo value)
14651 (org-set-tags nil 'align))
14652 ((equal property "PRIORITY")
14653 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14654 (string-to-char value) ?\ ))
14655 (org-set-tags nil 'align))
14656 ((equal property "SCHEDULED")
14657 (if (re-search-forward org-scheduled-time-regexp end t)
14658 (cond
14659 ((eq value 'earlier) (org-timestamp-change -1 'day))
14660 ((eq value 'later) (org-timestamp-change 1 'day))
14661 (t (call-interactively 'org-schedule)))
14662 (call-interactively 'org-schedule)))
14663 ((equal property "DEADLINE")
14664 (if (re-search-forward org-deadline-time-regexp end t)
14665 (cond
14666 ((eq value 'earlier) (org-timestamp-change -1 'day))
14667 ((eq value 'later) (org-timestamp-change 1 'day))
14668 (t (call-interactively 'org-deadline)))
14669 (call-interactively 'org-deadline)))
14670 ((member property org-special-properties)
14671 (error "The %s property can not yet be set with `org-entry-put'"
14672 property))
14673 (t ; a non-special property
14674 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14675 (setq range (org-get-property-block beg end 'force))
14676 (goto-char (car range))
14677 (if (re-search-forward
14678 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
14679 (progn
14680 (delete-region (match-beginning 1) (match-end 1))
14681 (goto-char (match-beginning 1)))
14682 (goto-char (cdr range))
14683 (insert "\n")
14684 (backward-char 1)
14685 (org-indent-line-function)
14686 (insert ":" property ":"))
14687 (and value (insert " " value))
14688 (org-indent-line-function)))))))
14690 (defun org-buffer-property-keys (&optional include-specials include-defaults)
14691 "Get all property keys in the current buffer.
14692 With INCLUDE-SPECIALS, also list the special properties that relect things
14693 like tags and TODO state.
14694 With INCLUDE-DEFAULTS, also include properties that has special meaning
14695 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
14696 (let (rtn range)
14697 (save-excursion
14698 (save-restriction
14699 (widen)
14700 (goto-char (point-min))
14701 (while (re-search-forward org-property-start-re nil t)
14702 (setq range (org-get-property-block))
14703 (goto-char (car range))
14704 (while (re-search-forward
14705 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
14706 (cdr range) t)
14707 (add-to-list 'rtn (org-match-string-no-properties 1)))
14708 (outline-next-heading))))
14709 (when include-specials
14710 (setq rtn (append org-special-properties rtn)))
14711 (when include-defaults
14712 (add-to-list 'rtn "CATEGORY")
14713 (add-to-list 'rtn "ARCHIVE"))
14714 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14716 (defun org-property-values (key)
14717 "Return a list of all values of property KEY."
14718 (save-excursion
14719 (save-restriction
14720 (widen)
14721 (goto-char (point-min))
14722 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
14723 values)
14724 (while (re-search-forward re nil t)
14725 (add-to-list 'values (org-trim (match-string 1))))
14726 (delete "" values)))))
14728 (defun org-insert-property-drawer ()
14729 "Insert a property drawer into the current entry."
14730 (interactive)
14731 (org-back-to-heading t)
14732 (looking-at outline-regexp)
14733 (let ((indent (- (match-end 0)(match-beginning 0)))
14734 (beg (point))
14735 (re (concat "^[ \t]*" org-keyword-time-regexp))
14736 end hiddenp)
14737 (outline-next-heading)
14738 (setq end (point))
14739 (goto-char beg)
14740 (while (re-search-forward re end t))
14741 (setq hiddenp (org-invisible-p))
14742 (end-of-line 1)
14743 (and (= (char-after) ?\n) (forward-char 1))
14744 (org-skip-over-state-notes)
14745 (skip-chars-backward " \t\n\r")
14746 (insert "\n:PROPERTIES:\n:END:")
14747 (beginning-of-line 0)
14748 (indent-to-column indent)
14749 (beginning-of-line 2)
14750 (indent-to-column indent)
14751 (beginning-of-line 0)
14752 (if hiddenp
14753 (save-excursion
14754 (org-back-to-heading t)
14755 (hide-entry))
14756 (org-flag-drawer t))))
14758 (defun org-set-property (property value)
14759 "In the current entry, set PROPERTY to VALUE."
14760 (interactive
14761 (let* ((prop (completing-read "Property: "
14762 (mapcar 'list (org-buffer-property-keys))))
14763 (cur (org-entry-get nil prop))
14764 (allowed (org-property-get-allowed-values nil prop 'table))
14765 (val (if allowed
14766 (completing-read "Value: " allowed nil 'req-match)
14767 (read-string
14768 (concat "Value" (if (and cur (string-match "\\S-" cur))
14769 (concat "[" cur "]") "")
14770 ": ")
14771 "" cur))))
14772 (list prop (if (equal val "") cur val))))
14773 (unless (equal (org-entry-get nil property) value)
14774 (org-entry-put nil property value)))
14776 (defun org-delete-property (property)
14777 "In the current entry, delete PROPERTY."
14778 (interactive
14779 (let* ((prop (completing-read
14780 "Property: " (org-entry-properties nil 'standard))))
14781 (list prop)))
14782 (message (concat "Property " property
14783 (if (org-entry-delete nil property)
14784 " deleted"
14785 " was not present in the entry"))))
14787 (defun org-delete-property-globally (property)
14788 "Remove PROPERTY globally, from all entries."
14789 (interactive
14790 (let* ((prop (completing-read
14791 "Globally remove property: "
14792 (mapcar 'list (org-buffer-property-keys)))))
14793 (list prop)))
14794 (save-excursion
14795 (save-restriction
14796 (widen)
14797 (goto-char (point-min))
14798 (let ((cnt 0))
14799 (while (re-search-forward
14800 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
14801 nil t)
14802 (setq cnt (1+ cnt))
14803 (replace-match ""))
14804 (message "Property \"%s\" removed from %d entries" property cnt)))))
14806 (defvar org-columns-current-fmt-compiled) ; defined below
14808 (defun org-compute-property-at-point ()
14809 "Compute the property at point.
14810 This looks for an enclosing column format, extracts the operator and
14811 then applies it to the proerty in the column format's scope."
14812 (interactive)
14813 (unless (org-at-property-p)
14814 (error "Not at a property"))
14815 (let ((prop (org-match-string-no-properties 2)))
14816 (org-columns-get-format-and-top-level)
14817 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14818 (error "No operator defined for property %s" prop))
14819 (org-columns-compute prop)))
14821 (defun org-property-get-allowed-values (pom property &optional table)
14822 "Get allowed values for the property PROPERTY.
14823 When TABLE is non-nil, return an alist that can directly be used for
14824 completion."
14825 (let (vals)
14826 (cond
14827 ((equal property "TODO")
14828 (setq vals (org-with-point-at pom
14829 (append org-todo-keywords-1 '("")))))
14830 ((equal property "PRIORITY")
14831 (let ((n org-lowest-priority))
14832 (while (>= n org-highest-priority)
14833 (push (char-to-string n) vals)
14834 (setq n (1- n)))))
14835 ((member property org-special-properties))
14837 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14839 (when (and vals (string-match "\\S-" vals))
14840 (setq vals (car (read-from-string (concat "(" vals ")"))))
14841 (setq vals (mapcar (lambda (x)
14842 (cond ((stringp x) x)
14843 ((numberp x) (number-to-string x))
14844 ((symbolp x) (symbol-name x))
14845 (t "???")))
14846 vals)))))
14847 (if table (mapcar 'list vals) vals)))
14849 (defun org-property-previous-allowed-value (&optional previous)
14850 "Switch to the next allowed value for this property."
14851 (interactive)
14852 (org-property-next-allowed-value t))
14854 (defun org-property-next-allowed-value (&optional previous)
14855 "Switch to the next allowed value for this property."
14856 (interactive)
14857 (unless (org-at-property-p)
14858 (error "Not at a property"))
14859 (let* ((key (match-string 2))
14860 (value (match-string 3))
14861 (allowed (or (org-property-get-allowed-values (point) key)
14862 (and (member value '("[ ]" "[-]" "[X]"))
14863 '("[ ]" "[X]"))))
14864 nval)
14865 (unless allowed
14866 (error "Allowed values for this property have not been defined"))
14867 (if previous (setq allowed (reverse allowed)))
14868 (if (member value allowed)
14869 (setq nval (car (cdr (member value allowed)))))
14870 (setq nval (or nval (car allowed)))
14871 (if (equal nval value)
14872 (error "Only one allowed value for this property"))
14873 (org-at-property-p)
14874 (replace-match (concat " :" key ": " nval) t t)
14875 (org-indent-line-function)
14876 (beginning-of-line 1)
14877 (skip-chars-forward " \t")))
14879 ;;; Column View
14881 (defvar org-columns-overlays nil
14882 "Holds the list of current column overlays.")
14884 (defvar org-columns-current-fmt nil
14885 "Local variable, holds the currently active column format.")
14886 (defvar org-columns-current-fmt-compiled nil
14887 "Local variable, holds the currently active column format.
14888 This is the compiled version of the format.")
14889 (defvar org-columns-current-maxwidths nil
14890 "Loval variable, holds the currently active maximum column widths.")
14891 (defvar org-columns-begin-marker (make-marker)
14892 "Points to the position where last a column creation command was called.")
14893 (defvar org-columns-top-level-marker (make-marker)
14894 "Points to the position where current columns region starts.")
14896 (defvar org-columns-map (make-sparse-keymap)
14897 "The keymap valid in column display.")
14899 (defun org-columns-content ()
14900 "Switch to contents view while in columns view."
14901 (interactive)
14902 (org-overview)
14903 (org-content))
14905 (org-defkey org-columns-map "c" 'org-columns-content)
14906 (org-defkey org-columns-map "o" 'org-overview)
14907 (org-defkey org-columns-map "e" 'org-columns-edit-value)
14908 (org-defkey org-columns-map "v" 'org-columns-show-value)
14909 (org-defkey org-columns-map "q" 'org-columns-quit)
14910 (org-defkey org-columns-map "r" 'org-columns-redo)
14911 (org-defkey org-columns-map [left] 'backward-char)
14912 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
14913 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
14914 (org-defkey org-columns-map [right] 'forward-char)
14915 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
14916 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
14917 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-next-allowed-value)
14918 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
14919 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
14920 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
14921 (org-defkey org-columns-map "<" 'org-columns-narrow)
14922 (org-defkey org-columns-map ">" 'org-columns-widen)
14923 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
14924 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
14925 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
14926 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
14928 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
14929 '("Column"
14930 ["Edit property" org-columns-edit-value t]
14931 ["Next allowed value" org-columns-next-allowed-value t]
14932 ["Previous allowed value" org-columns-previous-allowed-value t]
14933 ["Show full value" org-columns-show-value t]
14934 ["Edit allowed" org-columns-edit-allowed t]
14935 "--"
14936 ["Edit column attributes" org-columns-edit-attributes t]
14937 ["Increase column width" org-columns-widen t]
14938 ["Decrease column width" org-columns-narrow t]
14939 "--"
14940 ["Move column right" org-columns-move-right t]
14941 ["Move column left" org-columns-move-left t]
14942 ["Add column" org-columns-new t]
14943 ["Delete column" org-columns-delete t]
14944 "--"
14945 ["CONTENTS" org-columns-content t]
14946 ["OVERVIEW" org-overview t]
14947 ["Refresh columns display" org-columns-redo t]
14948 "--"
14949 ["Quit" org-columns-quit t]))
14951 (defun org-columns-new-overlay (beg end &optional string face)
14952 "Create a new column overlay and add it to the list."
14953 (let ((ov (org-make-overlay beg end)))
14954 (org-overlay-put ov 'face (or face 'secondary-selection))
14955 (org-overlay-display ov string face)
14956 (push ov org-columns-overlays)
14957 ov))
14959 (defun org-columns-display-here (&optional props)
14960 "Overlay the current line with column display."
14961 (interactive)
14962 (let* ((fmt org-columns-current-fmt-compiled)
14963 (beg (point-at-bol))
14964 (level-face (save-excursion
14965 (beginning-of-line 1)
14966 (and (looking-at "\\(\\**\\)\\(\\* \\)")
14967 (org-get-level-face 2))))
14968 (color (list :foreground
14969 (face-attribute (or level-face 'default) :foreground)))
14970 props pom property ass width f string ov column)
14971 ;; Check if the entry is in another buffer.
14972 (unless props
14973 (if (eq major-mode 'org-agenda-mode)
14974 (setq pom (or (get-text-property (point) 'org-hd-marker)
14975 (get-text-property (point) 'org-marker))
14976 props (if pom (org-entry-properties pom) nil))
14977 (setq props (org-entry-properties nil))))
14978 ;; Walk the format
14979 (while (setq column (pop fmt))
14980 (setq property (car column)
14981 ass (if (equal property "ITEM")
14982 (cons "ITEM"
14983 (save-match-data
14984 (org-no-properties
14985 (org-remove-tabs
14986 (buffer-substring-no-properties
14987 (point-at-bol) (point-at-eol))))))
14988 (assoc property props))
14989 width (or (cdr (assoc property org-columns-current-maxwidths))
14990 (nth 2 column))
14991 f (format "%%-%d.%ds | " width width)
14992 string (format f (or (cdr ass) "")))
14993 ;; Create the overlay
14994 (org-unmodified
14995 (setq ov (org-columns-new-overlay
14996 beg (setq beg (1+ beg)) string
14997 (list color 'org-column)))
14998 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
14999 (org-overlay-put ov 'keymap org-columns-map)
15000 (org-overlay-put ov 'org-columns-key property)
15001 (org-overlay-put ov 'org-columns-value (cdr ass))
15002 (org-overlay-put ov 'org-columns-pom pom)
15003 (org-overlay-put ov 'org-columns-format f))
15004 (if (or (not (char-after beg))
15005 (equal (char-after beg) ?\n))
15006 (let ((inhibit-read-only t))
15007 (save-excursion
15008 (goto-char beg)
15009 (insert " ")))))
15010 ;; Make the rest of the line disappear.
15011 (org-unmodified
15012 (setq ov (org-columns-new-overlay beg (point-at-eol)))
15013 (org-overlay-put ov 'invisible t)
15014 (org-overlay-put ov 'keymap org-columns-map)
15015 (org-overlay-put ov 'intangible t)
15016 (push ov org-columns-overlays)
15017 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
15018 (org-overlay-put ov 'keymap org-columns-map)
15019 (push ov org-columns-overlays)
15020 (let ((inhibit-read-only t))
15021 (put-text-property (max (point-min) (1- (point-at-bol)))
15022 (min (point-max) (1+ (point-at-eol)))
15023 'read-only "Type `e' to edit property")))))
15025 (defvar org-previous-header-line-format nil
15026 "The header line format before column view was turned on.")
15027 (defvar org-columns-inhibit-recalculation nil
15028 "Inhibit recomputing of columns on column view startup.")
15030 (defvar header-line-format)
15031 (defun org-columns-display-here-title ()
15032 "Overlay the newline before the current line with the table title."
15033 (interactive)
15034 (let ((fmt org-columns-current-fmt-compiled)
15035 string (title "")
15036 property width f column str)
15037 (while (setq column (pop fmt))
15038 (setq property (car column)
15039 str (or (nth 1 column) property)
15040 width (or (cdr (assoc property org-columns-current-maxwidths))
15041 (nth 2 column))
15042 f (format "%%-%d.%ds | " width width)
15043 string (format f str)
15044 title (concat title string)))
15045 (setq title (concat
15046 (org-add-props " " nil 'display '(space :align-to 0))
15047 (org-add-props title nil 'face '(:weight bold :underline t))))
15048 (org-set-local 'org-previous-header-line-format header-line-format)
15049 (setq header-line-format title)))
15051 (defun org-columns-remove-overlays ()
15052 "Remove all currently active column overlays."
15053 (interactive)
15054 (when (marker-buffer org-columns-begin-marker)
15055 (with-current-buffer (marker-buffer org-columns-begin-marker)
15056 (when (local-variable-p 'org-previous-header-line-format)
15057 (setq header-line-format org-previous-header-line-format)
15058 (kill-local-variable 'org-previous-header-line-format))
15059 (move-marker org-columns-begin-marker nil)
15060 (move-marker org-columns-top-level-marker nil)
15061 (org-unmodified
15062 (mapc 'org-delete-overlay org-columns-overlays)
15063 (setq org-columns-overlays nil)
15064 (let ((inhibit-read-only t))
15065 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
15067 (defun org-columns-show-value ()
15068 "Show the full value of the property."
15069 (interactive)
15070 (let ((value (get-char-property (point) 'org-columns-value)))
15071 (message "Value is: %s" (or value ""))))
15073 (defun org-columns-quit ()
15074 "Remove the column overlays and in this way exit column editing."
15075 (interactive)
15076 (org-unmodified
15077 (org-columns-remove-overlays)
15078 (let ((inhibit-read-only t))
15079 (remove-text-properties (point-min) (point-max) '(read-only t))))
15080 (when (eq major-mode 'org-agenda-mode)
15081 (message
15082 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
15084 (defun org-columns-check-computed ()
15085 "Check if this column value is computed.
15086 If yes, throw an error indicating that changing it does not make sense."
15087 (let ((val (get-char-property (point) 'org-columns-value)))
15088 (when (and (stringp val)
15089 (get-char-property 0 'org-computed val))
15090 (error "This value is computed from the entry's children"))))
15092 (defun org-columns-edit-value ()
15093 "Edit the value of the property at point in column view.
15094 Where possible, use the standard interface for changing this line."
15095 (interactive)
15096 (org-columns-check-computed)
15097 (let* ((col (current-column))
15098 (key (get-char-property (point) 'org-columns-key))
15099 (value (get-char-property (point) 'org-columns-value))
15100 (bol (point-at-bol)) (eol (point-at-eol))
15101 (pom (or (get-text-property bol 'org-hd-marker)
15102 (point))) ; keep despite of compiler waring
15103 (line-overlays
15104 (delq nil (mapcar (lambda (x)
15105 (and (eq (overlay-buffer x) (current-buffer))
15106 (>= (overlay-start x) bol)
15107 (<= (overlay-start x) eol)
15109 org-columns-overlays)))
15110 nval eval allowed)
15111 (when (equal key "ITEM")
15112 (error "Cannot edit item headline from here"))
15114 (cond
15115 ((equal key "TODO")
15116 (setq eval '(org-with-point-at pom
15117 (let ((current-prefix-arg '(4))) (org-todo '(4))))))
15118 ((equal key "PRIORITY")
15119 (setq eval '(org-with-point-at pom
15120 (call-interactively 'org-priority))))
15121 ((equal key "TAGS")
15122 (setq eval '(org-with-point-at pom
15123 (let ((org-fast-tag-selection-single-key
15124 (if (eq org-fast-tag-selection-single-key 'expert)
15125 t org-fast-tag-selection-single-key)))
15126 (call-interactively 'org-set-tags)))))
15127 ((equal key "DEADLINE")
15128 (setq eval '(org-with-point-at pom
15129 (call-interactively 'org-deadline))))
15130 ((equal key "SCHEDULED")
15131 (setq eval '(org-with-point-at pom
15132 (call-interactively 'org-schedule))))
15134 (setq allowed (org-property-get-allowed-values pom key 'table))
15135 (if allowed
15136 (setq nval (completing-read "Value: " allowed nil t))
15137 (setq nval (read-string "Edit: " value)))
15138 (setq nval (org-trim nval))
15139 (when (not (equal nval value))
15140 (setq eval '(org-entry-put pom key nval)))))
15141 (when eval
15142 (let ((inhibit-read-only t))
15143 (remove-text-properties (1- bol) eol '(read-only t))
15144 (unwind-protect
15145 (progn
15146 (setq org-columns-overlays
15147 (org-delete-all line-overlays org-columns-overlays))
15148 (mapc 'org-delete-overlay line-overlays)
15149 (org-columns-eval eval))
15150 (org-columns-display-here))))
15151 (move-to-column col)
15152 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15153 (org-columns-update key))))
15155 (defun org-columns-edit-allowed ()
15156 "Edit the list of allowed values for the current property."
15157 (interactive)
15158 (let* ((col (current-column))
15159 (key (get-char-property (point) 'org-columns-key))
15160 (key1 (concat key "_ALL"))
15161 (value (get-char-property (point) 'org-columns-value))
15162 (allowed (org-entry-get (point) key1 t))
15163 nval)
15164 (setq nval (read-string "Allowed: " allowed))
15165 (org-entry-put
15166 (cond ((marker-position org-entry-property-inherited-from)
15167 org-entry-property-inherited-from)
15168 ((marker-position org-columns-top-level-marker)
15169 org-columns-top-level-marker))
15170 key1 nval)))
15172 (defun org-columns-eval (form)
15173 (let (hidep)
15174 (save-excursion
15175 (beginning-of-line 1)
15176 (next-line 1)
15177 (setq hidep (org-on-heading-p 1)))
15178 (eval form)
15179 (and hidep (hide-entry))))
15181 (defun org-columns-previous-allowed-value ()
15182 "Switch to the previous allowed value for this column."
15183 (interactive)
15184 (org-columns-next-allowed-value t))
15186 (defun org-columns-next-allowed-value (&optional previous)
15187 "Switch to the next allowed value for this column."
15188 (interactive)
15189 (org-columns-check-computed)
15190 (let* ((col (current-column))
15191 (key (get-char-property (point) 'org-columns-key))
15192 (value (get-char-property (point) 'org-columns-value))
15193 (bol (point-at-bol)) (eol (point-at-eol))
15194 (pom (or (get-text-property bol 'org-hd-marker)
15195 (point))) ; keep despite of compiler waring
15196 (line-overlays
15197 (delq nil (mapcar (lambda (x)
15198 (and (eq (overlay-buffer x) (current-buffer))
15199 (>= (overlay-start x) bol)
15200 (<= (overlay-start x) eol)
15202 org-columns-overlays)))
15203 (allowed (or (org-property-get-allowed-values pom key)
15204 (and (equal
15205 (nth 4 (assoc key org-columns-current-fmt-compiled))
15206 'checkbox) '("[ ]" "[X]"))))
15207 nval)
15208 (when (equal key "ITEM")
15209 (error "Cannot edit item headline from here"))
15210 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
15211 (error "Allowed values for this property have not been defined"))
15212 (if (member key '("SCHEDULED" "DEADLINE"))
15213 (setq nval (if previous 'earlier 'later))
15214 (if previous (setq allowed (reverse allowed)))
15215 (if (member value allowed)
15216 (setq nval (car (cdr (member value allowed)))))
15217 (setq nval (or nval (car allowed)))
15218 (if (equal nval value)
15219 (error "Only one allowed value for this property")))
15220 (let ((inhibit-read-only t))
15221 (remove-text-properties (1- bol) eol '(read-only t))
15222 (unwind-protect
15223 (progn
15224 (setq org-columns-overlays
15225 (org-delete-all line-overlays org-columns-overlays))
15226 (mapc 'org-delete-overlay line-overlays)
15227 (org-columns-eval '(org-entry-put pom key nval)))
15228 (org-columns-display-here)))
15229 (move-to-column col)
15230 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15231 (org-columns-update key))))
15233 (defun org-verify-version (task)
15234 (cond
15235 ((eq task 'columns)
15236 (if (or (featurep 'xemacs)
15237 (< emacs-major-version 22))
15238 (error "Emacs 22 is required for the columns feature")))))
15240 (defun org-columns-get-format-and-top-level ()
15241 (let (fmt)
15242 (when (condition-case nil (org-back-to-heading) (error nil))
15243 (move-marker org-entry-property-inherited-from nil)
15244 (setq fmt (org-entry-get nil "COLUMNS" t)))
15245 (setq fmt (or fmt org-columns-default-format))
15246 (org-set-local 'org-columns-current-fmt fmt)
15247 (org-columns-compile-format fmt)
15248 (if (marker-position org-entry-property-inherited-from)
15249 (move-marker org-columns-top-level-marker
15250 org-entry-property-inherited-from)
15251 (move-marker org-columns-top-level-marker (point)))
15252 fmt))
15254 (defun org-columns ()
15255 "Turn on column view on an org-mode file."
15256 (interactive)
15257 (org-verify-version 'columns)
15258 (org-columns-remove-overlays)
15259 (move-marker org-columns-begin-marker (point))
15260 (let (beg end fmt cache maxwidths)
15261 (setq fmt (org-columns-get-format-and-top-level))
15262 (save-excursion
15263 (goto-char org-columns-top-level-marker)
15264 (setq beg (point))
15265 (unless org-columns-inhibit-recalculation
15266 (org-columns-compute-all))
15267 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
15268 (point-max)))
15269 (goto-char beg)
15270 ;; Get and cache the properties
15271 (while (re-search-forward (concat "^" outline-regexp) end t)
15272 (push (cons (org-current-line) (org-entry-properties)) cache))
15273 (when cache
15274 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
15275 (org-set-local 'org-columns-current-maxwidths maxwidths)
15276 (org-columns-display-here-title)
15277 (mapc (lambda (x)
15278 (goto-line (car x))
15279 (org-columns-display-here (cdr x)))
15280 cache)))))
15282 (defun org-columns-new (&optional prop title width op fmt)
15283 "Insert a new column, to the leeft o the current column."
15284 (interactive)
15285 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
15286 cell)
15287 (setq prop (completing-read
15288 "Property: " (mapcar 'list (org-buffer-property-keys t))
15289 nil nil prop))
15290 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
15291 (setq width (read-string "Column width: " (if width (number-to-string width))))
15292 (if (string-match "\\S-" width)
15293 (setq width (string-to-number width))
15294 (setq width nil))
15295 (setq fmt (completing-read "Summary [none]: "
15296 '(("none") ("add_numbers") ("add_times") ("checkbox"))
15297 nil t))
15298 (if (string-match "\\S-" fmt)
15299 (setq fmt (intern fmt))
15300 (setq fmt nil))
15301 (if (eq fmt 'none) (setq fmt nil))
15302 (if editp
15303 (progn
15304 (setcar editp prop)
15305 (setcdr editp (list title width nil fmt)))
15306 (setq cell (nthcdr (1- (current-column))
15307 org-columns-current-fmt-compiled))
15308 (setcdr cell (cons (list prop title width nil fmt)
15309 (cdr cell))))
15310 (org-columns-store-format)
15311 (org-columns-redo)))
15313 (defun org-columns-delete ()
15314 "Delete the column at point from columns view."
15315 (interactive)
15316 (let* ((n (current-column))
15317 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
15318 (when (y-or-n-p
15319 (format "Are you sure you want to remove column \"%s\"? " title))
15320 (setq org-columns-current-fmt-compiled
15321 (delq (nth n org-columns-current-fmt-compiled)
15322 org-columns-current-fmt-compiled))
15323 (org-columns-store-format)
15324 (org-columns-redo)
15325 (if (>= (current-column) (length org-columns-current-fmt-compiled))
15326 (backward-char 1)))))
15328 (defun org-columns-edit-attributes ()
15329 "Edit the attributes of the current column."
15330 (interactive)
15331 (let* ((n (current-column))
15332 (info (nth n org-columns-current-fmt-compiled)))
15333 (apply 'org-columns-new info)))
15335 (defun org-columns-widen (arg)
15336 "Make the column wider by ARG characters."
15337 (interactive "p")
15338 (let* ((n (current-column))
15339 (entry (nth n org-columns-current-fmt-compiled))
15340 (width (or (nth 2 entry)
15341 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
15342 (setq width (max 1 (+ width arg)))
15343 (setcar (nthcdr 2 entry) width)
15344 (org-columns-store-format)
15345 (org-columns-redo)))
15347 (defun org-columns-narrow (arg)
15348 "Make the column nrrower by ARG characters."
15349 (interactive "p")
15350 (org-columns-widen (- arg)))
15352 (defun org-columns-move-right ()
15353 "Swap this column with the one to the right."
15354 (interactive)
15355 (let* ((n (current-column))
15356 (cell (nthcdr n org-columns-current-fmt-compiled))
15358 (when (>= n (1- (length org-columns-current-fmt-compiled)))
15359 (error "Cannot shift this column further to the right"))
15360 (setq e (car cell))
15361 (setcar cell (car (cdr cell)))
15362 (setcdr cell (cons e (cdr (cdr cell))))
15363 (org-columns-store-format)
15364 (org-columns-redo)
15365 (forward-char 1)))
15367 (defun org-columns-move-left ()
15368 "Swap this column with the one to the left."
15369 (interactive)
15370 (let* ((n (current-column)))
15371 (when (= n 0)
15372 (error "Cannot shift this column further to the left"))
15373 (backward-char 1)
15374 (org-columns-move-right)
15375 (backward-char 1)))
15377 (defun org-columns-store-format ()
15378 "Store the text version of the current columns format in appropriate place.
15379 This is either in the COLUMNS property of the node starting the current column
15380 display, or in the #+COLUMNS line of the current buffer."
15381 (let (fmt)
15382 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
15383 (if (marker-position org-columns-top-level-marker)
15384 (save-excursion
15385 (goto-char org-columns-top-level-marker)
15386 (if (org-entry-get nil "COLUMNS")
15387 (org-entry-put nil "COLUMNS" fmt)
15388 (goto-char (point-min))
15389 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
15390 (replace-match (concat "#+COLUMNS: " fmt t t)))))
15391 (setq org-columns-current-fmt fmt))))
15393 (defvar org-overriding-columns-format nil
15394 "When set, overrides any other definition.")
15395 (defvar org-agenda-view-columns-initially nil
15396 "When set, switch to columns view immediately after creating the agenda.")
15398 (defun org-agenda-columns ()
15399 "Turn on column view in the agenda."
15400 (interactive)
15401 (org-verify-version 'columns)
15402 (org-columns-remove-overlays)
15403 (move-marker org-columns-begin-marker (point))
15404 (let (fmt cache maxwidths m)
15405 (cond
15406 ((and (local-variable-p 'org-overriding-columns-format)
15407 org-overriding-columns-format)
15408 (setq fmt org-overriding-columns-format))
15409 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
15410 (setq fmt (org-entry-get m "COLUMNS" t)))
15411 ((and (boundp 'org-columns-current-fmt)
15412 (local-variable-p 'org-columns-current-fmt)
15413 org-columns-current-fmt)
15414 (setq fmt org-columns-current-fmt))
15415 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
15416 (setq m (get-text-property m 'org-hd-marker))
15417 (setq fmt (org-entry-get m "COLUMNS" t))))
15418 (setq fmt (or fmt org-columns-default-format))
15419 (org-set-local 'org-columns-current-fmt fmt)
15420 (org-columns-compile-format fmt)
15421 (save-excursion
15422 ;; Get and cache the properties
15423 (goto-char (point-min))
15424 (while (not (eobp))
15425 (when (setq m (or (get-text-property (point) 'org-hd-marker)
15426 (get-text-property (point) 'org-marker)))
15427 (push (cons (org-current-line) (org-entry-properties m)) cache))
15428 (beginning-of-line 2))
15429 (when cache
15430 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
15431 (org-set-local 'org-columns-current-maxwidths maxwidths)
15432 (org-columns-display-here-title)
15433 (mapc (lambda (x)
15434 (goto-line (car x))
15435 (org-columns-display-here (cdr x)))
15436 cache)))))
15438 (defun org-columns-get-autowidth-alist (s cache)
15439 "Derive the maximum column widths from the format and the cache."
15440 (let ((start 0) rtn)
15441 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
15442 (push (cons (match-string 1 s) 1) rtn)
15443 (setq start (match-end 0)))
15444 (mapc (lambda (x)
15445 (setcdr x (apply 'max
15446 (mapcar
15447 (lambda (y)
15448 (length (or (cdr (assoc (car x) (cdr y))) " ")))
15449 cache))))
15450 rtn)
15451 rtn))
15453 (defun org-columns-compute-all ()
15454 "Compute all columns that have operators defined."
15455 (org-unmodified
15456 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
15457 (let ((columns org-columns-current-fmt-compiled) col)
15458 (while (setq col (pop columns))
15459 (when (nth 3 col)
15460 (save-excursion
15461 (org-columns-compute (car col)))))))
15463 (defun org-columns-update (property)
15464 "Recompute PROPERTY, and update the columns display for it."
15465 (org-columns-compute property)
15466 (let (fmt val pos)
15467 (save-excursion
15468 (mapc (lambda (ov)
15469 (when (equal (org-overlay-get ov 'org-columns-key) property)
15470 (setq pos (org-overlay-start ov))
15471 (goto-char pos)
15472 (when (setq val (cdr (assoc property
15473 (get-text-property
15474 (point-at-bol) 'org-summaries))))
15475 (setq fmt (org-overlay-get ov 'org-columns-format))
15476 (org-overlay-put ov 'org-columns-value val)
15477 (org-overlay-put ov 'display (format fmt val)))))
15478 org-columns-overlays))))
15480 (defun org-columns-compute (property)
15481 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
15482 (interactive)
15483 (let* ((re (concat "^" outline-regexp))
15484 (lmax 30) ; Does anyone use deeper levels???
15485 (lsum (make-vector lmax 0))
15486 (lflag (make-vector lmax nil))
15487 (level 0)
15488 (ass (assoc property org-columns-current-fmt-compiled))
15489 (format (nth 4 ass))
15490 (beg org-columns-top-level-marker)
15491 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
15492 (save-excursion
15493 ;; Find the region to compute
15494 (goto-char beg)
15495 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
15496 (goto-char end)
15497 ;; Walk the tree from the back and do the computations
15498 (while (re-search-backward re beg t)
15499 (setq sumpos (match-beginning 0)
15500 last-level level
15501 level (org-outline-level)
15502 val (org-entry-get nil property)
15503 valflag (and val (string-match "\\S-" val)))
15504 (cond
15505 ((< level last-level)
15506 ;; put the sum of lower levels here as a property
15507 (setq sum (aref lsum last-level) ; current sum
15508 flag (aref lflag last-level) ; any valid entries from children?
15509 str (org-column-number-to-string sum format)
15510 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
15511 useval (if flag str1 (if valflag val ""))
15512 sum-alist (get-text-property sumpos 'org-summaries))
15513 (if (assoc property sum-alist)
15514 (setcdr (assoc property sum-alist) useval)
15515 (push (cons property useval) sum-alist)
15516 (org-unmodified
15517 (add-text-properties sumpos (1+ sumpos)
15518 (list 'org-summaries sum-alist))))
15519 (when val
15520 (org-entry-put nil property (if flag str val)))
15521 ;; add current to current level accumulator
15522 (when (or flag valflag)
15523 ;; FIXME: is this ok?????????
15524 (aset lsum level (+ (aref lsum level)
15525 (if flag sum (org-column-string-to-number
15526 (if flag str val) format))))
15527 (aset lflag level t))
15528 ;; clear accumulators for deeper levels
15529 (loop for l from (1+ level) to (1- lmax) do
15530 (aset lsum l 0)
15531 (aset lflag l nil)))
15532 ((>= level last-level)
15533 ;; add what we have here to the accumulator for this level
15534 (aset lsum level (+ (aref lsum level)
15535 (org-column-string-to-number (or val "0") format)))
15536 (and valflag (aset lflag level t)))
15537 (t (error "This should not happen")))))))
15539 (defun org-columns-redo ()
15540 "Construct the column display again."
15541 (interactive)
15542 (message "Recomputing columns...")
15543 (save-excursion
15544 (if (marker-position org-columns-begin-marker)
15545 (goto-char org-columns-begin-marker))
15546 (org-columns-remove-overlays)
15547 (if (org-mode-p)
15548 (call-interactively 'org-columns)
15549 (call-interactively 'org-agenda-columns)))
15550 (message "Recomputing columns...done"))
15552 (defun org-columns-not-in-agenda ()
15553 (if (eq major-mode 'org-agenda-mode)
15554 (error "This command is only allowed in Org-mode buffers")))
15557 (defun org-string-to-number (s)
15558 "Convert string to number, and interpret hh:mm:ss."
15559 (if (not (string-match ":" s))
15560 (string-to-number s)
15561 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
15562 (while l
15563 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
15564 sum)))
15566 (defun org-column-number-to-string (n fmt)
15567 "Convert a computed column number to a string value, according to FMT."
15568 (cond
15569 ((eq fmt 'add_times)
15570 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
15571 (format "%d:%02d" h m)))
15572 ((eq fmt 'checkbox)
15573 (cond ((= n (floor n)) "[X]")
15574 ((> n 1.) "[-]")
15575 (t "[ ]")))
15576 (t (number-to-string n))))
15578 (defun org-column-string-to-number (s fmt)
15579 "Convert a column value to a number that can be used for column computing."
15580 (cond
15581 ((string-match ":" s)
15582 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
15583 (while l
15584 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
15585 sum))
15586 ((eq fmt 'checkbox)
15587 (if (equal s "[X]") 1. 0.000001))
15588 (t (string-to-number s))))
15590 (defun org-columns-uncompile-format (cfmt)
15591 "Turn the compiled columns format back into a string representation."
15592 (let ((rtn "") e s prop title op width fmt)
15593 (while (setq e (pop cfmt))
15594 (setq prop (car e)
15595 title (nth 1 e)
15596 width (nth 2 e)
15597 op (nth 3 e)
15598 fmt (nth 4 e))
15599 (cond
15600 ((eq fmt 'add_times) (setq op ":"))
15601 ((eq fmt 'checkbox) (setq op "X"))
15602 ((eq fmt 'add_numbers) (setq op "+")))
15603 (if (equal title prop) (setq title nil))
15604 (setq s (concat "%" (if width (number-to-string width))
15605 prop
15606 (if title (concat "(" title ")"))
15607 (if op (concat "{" op "}"))))
15608 (setq rtn (concat rtn " " s)))
15609 (org-trim rtn)))
15611 (defun org-columns-compile-format (fmt)
15612 "Turn a column format string into an alist of specifications.
15613 The alist has one entry for each column in the format. The elements of
15614 that list are:
15615 property the property
15616 title the title field for the columns
15617 width the column width in characters, can be nil for automatic
15618 operator the operator if any
15619 format the output format for computed results, derived from operator"
15620 (let ((start 0) width prop title op f)
15621 (setq org-columns-current-fmt-compiled nil)
15622 (while (string-match
15623 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
15624 fmt start)
15625 (setq start (match-end 0)
15626 width (match-string 1 fmt)
15627 prop (match-string 2 fmt)
15628 title (or (match-string 3 fmt) prop)
15629 op (match-string 4 fmt)
15630 f nil)
15631 (if width (setq width (string-to-number width)))
15632 (cond
15633 ((equal op "+") (setq f 'add_numbers))
15634 ((equal op ":") (setq f 'add_times))
15635 ((equal op "X") (setq f 'checkbox)))
15636 (push (list prop title width op f) org-columns-current-fmt-compiled))
15637 (setq org-columns-current-fmt-compiled
15638 (nreverse org-columns-current-fmt-compiled))))
15640 ;;;; Timestamps
15642 (defvar org-last-changed-timestamp nil)
15643 (defvar org-time-was-given) ; dynamically scoped parameter
15644 (defvar org-end-time-was-given) ; dynamically scoped parameter
15645 (defvar org-ts-what) ; dynamically scoped parameter
15647 (defun org-time-stamp (arg)
15648 "Prompt for a date/time and insert a time stamp.
15649 If the user specifies a time like HH:MM, or if this command is called
15650 with a prefix argument, the time stamp will contain date and time.
15651 Otherwise, only the date will be included. All parts of a date not
15652 specified by the user will be filled in from the current date/time.
15653 So if you press just return without typing anything, the time stamp
15654 will represent the current date/time. If there is already a timestamp
15655 at the cursor, it will be modified."
15656 (interactive "P")
15657 (let ((default-time
15658 ;; Default time is either today, or, when entering a range,
15659 ;; the range start.
15660 (if (or (org-at-timestamp-p t)
15661 (save-excursion
15662 (re-search-backward
15663 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15664 (- (point) 20) t)))
15665 (apply 'encode-time (org-parse-time-string (match-string 1)))
15666 (current-time)))
15667 org-time-was-given org-end-time-was-given time)
15668 (cond
15669 ((and (org-at-timestamp-p)
15670 (eq last-command 'org-time-stamp)
15671 (eq this-command 'org-time-stamp))
15672 (insert "--")
15673 (setq time (let ((this-command this-command))
15674 (org-read-date arg 'totime nil nil default-time)))
15675 (org-insert-time-stamp time (or org-time-was-given arg)))
15676 ((org-at-timestamp-p)
15677 (setq time (let ((this-command this-command))
15678 (org-read-date arg 'totime nil nil default-time)))
15679 (when (org-at-timestamp-p) ; just to get the match data
15680 (replace-match "")
15681 (setq org-last-changed-timestamp
15682 (org-insert-time-stamp
15683 time (or org-time-was-given arg)
15684 nil nil nil (list org-end-time-was-given))))
15685 (message "Timestamp updated"))
15687 (setq time (let ((this-command this-command))
15688 (org-read-date arg 'totime nil nil default-time)))
15689 (org-insert-time-stamp time (or org-time-was-given arg)
15690 nil nil nil (list org-end-time-was-given))))))
15692 (defun org-time-stamp-inactive (&optional arg)
15693 "Insert an inactive time stamp.
15694 An inactive time stamp is enclosed in square brackets instead of angle
15695 brackets. It is inactive in the sense that it does not trigger agenda entries,
15696 does not link to the calendar and cannot be changed with the S-cursor keys.
15697 So these are more for recording a certain time/date."
15698 (interactive "P")
15699 (let (org-time-was-given org-end-time-was-given time)
15700 (setq time (org-read-date arg 'totime))
15701 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
15702 nil nil (list org-end-time-was-given))))
15704 (defvar org-date-ovl (org-make-overlay 1 1))
15705 (org-overlay-put org-date-ovl 'face 'org-warning)
15706 (org-detach-overlay org-date-ovl)
15708 (defvar org-ans1) ; dynamically scoped parameter
15709 (defvar org-ans2) ; dynamically scoped parameter
15711 (defvar org-plain-time-of-day-regexp) ; defined below
15712 (defun org-read-date (&optional with-time to-time from-string prompt
15713 default-time)
15714 "Read a date and make things smooth for the user.
15715 The prompt will suggest to enter an ISO date, but you can also enter anything
15716 which will at least partially be understood by `parse-time-string'.
15717 Unrecognized parts of the date will default to the current day, month, year,
15718 hour and minute. If this command is called to replace a timestamp at point,
15719 of to enter the second timestamp of a range, the default time is taken from the
15720 existing stamp. For example,
15721 3-2-5 --> 2003-02-05
15722 feb 15 --> currentyear-02-15
15723 sep 12 9 --> 2009-09-12
15724 12:45 --> today 12:45
15725 22 sept 0:34 --> currentyear-09-22 0:34
15726 12 --> currentyear-currentmonth-12
15727 Fri --> nearest Friday (today or later)
15728 etc.
15730 Furthermore you can specify a relative date by giving, as the *first* thing
15731 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
15732 change in days weeks, months, years.
15733 With a single plus or minus, the date is relative to today. With a double
15734 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15735 +4d --> four days from today
15736 +4 --> same as above
15737 +2w --> two weeks from today
15738 ++5 --> five days from default date
15740 The function understands only English month and weekday abbreviations,
15741 but this can be configured with the variables `parse-time-months' and
15742 `parse-time-weekdays'.
15744 While prompting, a calendar is popped up - you can also select the
15745 date with the mouse (button 1). The calendar shows a period of three
15746 months. To scroll it to other months, use the keys `>' and `<'.
15747 If you don't like the calendar, turn it off with
15748 \(setq org-popup-calendar-for-date-prompt nil)
15750 With optional argument TO-TIME, the date will immediately be converted
15751 to an internal time.
15752 With an optional argument WITH-TIME, the prompt will suggest to also
15753 insert a time. Note that when WITH-TIME is not set, you can still
15754 enter a time, and this function will inform the calling routine about
15755 this change. The calling routine may then choose to change the format
15756 used to insert the time stamp into the buffer to include the time.
15757 With optional argument FROM-STRING, read fomr this string instead from
15758 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15759 the time/date that is used for everything that is not specified by the
15760 user."
15761 (require 'parse-time)
15762 (let* ((org-time-stamp-rounding-minutes
15763 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
15764 (ct (org-current-time))
15765 (def (or default-time ct))
15766 (calendar-move-hook nil)
15767 (view-diary-entries-initially nil)
15768 (view-calendar-holidays-initially nil)
15769 (timestr (format-time-string
15770 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
15771 (prompt (concat (if prompt (concat prompt " ") "")
15772 (format "Date and/or time (default [%s]): " timestr)))
15773 ans (org-ans0 "") org-ans1 org-ans2 deltan deltaw deltarel
15774 second minute hour day month year tl wday wday1 pm h2 m2)
15776 (cond
15777 (from-string (setq ans from-string))
15778 (org-popup-calendar-for-date-prompt
15779 (save-excursion
15780 (save-window-excursion
15781 (calendar)
15782 (calendar-forward-day (- (time-to-days def)
15783 (calendar-absolute-from-gregorian
15784 (calendar-current-date))))
15785 (org-eval-in-calendar nil t)
15786 (let* ((old-map (current-local-map))
15787 (map (copy-keymap calendar-mode-map))
15788 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15789 (org-defkey map (kbd "RET") 'org-calendar-select)
15790 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
15791 'org-calendar-select-mouse)
15792 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
15793 'org-calendar-select-mouse)
15794 (org-defkey minibuffer-local-map [(meta shift left)]
15795 (lambda () (interactive)
15796 (org-eval-in-calendar '(calendar-backward-month 1))))
15797 (org-defkey minibuffer-local-map [(meta shift right)]
15798 (lambda () (interactive)
15799 (org-eval-in-calendar '(calendar-forward-month 1))))
15800 (org-defkey minibuffer-local-map [(shift up)]
15801 (lambda () (interactive)
15802 (org-eval-in-calendar '(calendar-backward-week 1))))
15803 (org-defkey minibuffer-local-map [(shift down)]
15804 (lambda () (interactive)
15805 (org-eval-in-calendar '(calendar-forward-week 1))))
15806 (org-defkey minibuffer-local-map [(shift left)]
15807 (lambda () (interactive)
15808 (org-eval-in-calendar '(calendar-backward-day 1))))
15809 (org-defkey minibuffer-local-map [(shift right)]
15810 (lambda () (interactive)
15811 (org-eval-in-calendar '(calendar-forward-day 1))))
15812 (org-defkey minibuffer-local-map ">"
15813 (lambda () (interactive)
15814 (org-eval-in-calendar '(scroll-calendar-left 1))))
15815 (org-defkey minibuffer-local-map "<"
15816 (lambda () (interactive)
15817 (org-eval-in-calendar '(scroll-calendar-right 1))))
15818 (unwind-protect
15819 (progn
15820 (use-local-map map)
15821 (setq org-ans0 (read-string prompt "" nil nil))
15822 ;; org-ans0: from prompt
15823 ;; org-ans1: from mouse click
15824 ;; org-ans2: from calendar motion
15825 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15826 (use-local-map old-map))))))
15827 (t ; Naked prompt only
15828 (setq ans (read-string prompt "" nil timestr))))
15829 (org-detach-overlay org-date-ovl)
15831 (when (string-match
15832 "\\`[ \t]*\\([-+]\\)?\\([-+][0-9]+\\)\\([dwmy]?\\)\\([ \t\n]\\|$\\)"
15833 org-ans0)
15834 (setq deltan (string-to-number (match-string 2 ans))
15835 deltaw (match-string 3 ans)
15836 deltarel (match-end 1)))
15838 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
15839 (when (string-match
15840 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15841 (setq year (if (match-end 2)
15842 (string-to-number (match-string 2 ans))
15843 (string-to-number (format-time-string "%Y")))
15844 month (string-to-number (match-string 3 ans))
15845 day (string-to-number (match-string 4 ans)))
15846 (if (< year 100) (setq year (+ 2000 year)))
15847 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15848 t nil ans)))
15849 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15850 ;; If there is a time with am/pm, and *no* time without it, we convert
15851 ;; so that matching will be successful.
15852 (loop for i from 1 to 2 do ; twice, for end time as well
15853 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15854 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15855 (setq hour (string-to-number (match-string 1 ans))
15856 minute (if (match-end 3)
15857 (string-to-number (match-string 3 ans))
15859 pm (equal ?p
15860 (string-to-char (downcase (match-string 4 ans)))))
15861 (if (and (= hour 12) (not pm))
15862 (setq hour 0)
15863 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15864 (setq ans (replace-match (format "%02d:%02d" hour minute)
15865 t t ans))))
15867 ;; Check if a time range is given as a duration
15868 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15869 (setq hour (string-to-number (match-string 1 ans))
15870 h2 (+ hour (string-to-number (match-string 3 ans)))
15871 minute (string-to-number (match-string 2 ans))
15872 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
15873 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
15875 ;; Check if there is a time range
15876 (when (and (boundp 'org-end-time-was-given)
15877 (string-match org-plain-time-of-day-regexp ans)
15878 (match-end 8))
15879 (setq org-end-time-was-given (match-string 8 ans))
15880 (setq ans (concat (substring ans 0 (match-beginning 7))
15881 (substring ans (match-end 7)))))
15883 (setq tl (parse-time-string ans)
15884 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" def)))
15885 month (or (nth 4 tl) (string-to-number (format-time-string "%m" def)))
15886 day (or (nth 3 tl) (string-to-number (format-time-string "%d" def)))
15887 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" def)))
15888 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" def)))
15889 second (or (nth 0 tl) 0)
15890 wday (nth 6 tl))
15891 (when deltan
15892 (unless deltarel
15893 (let ((now (decode-time (current-time))))
15894 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15895 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15896 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15897 ((equal deltaw "m") (setq month (+ month deltan)))
15898 ((equal deltaw "y") (setq year (+ year deltan)))))
15899 (when (and wday (not (nth 3 tl)))
15900 ;; Weekday was given, but no day, so pick that day in the week
15901 ;; on or after the derived date.
15902 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15903 (unless (equal wday wday1)
15904 (setq day (+ day (% (- wday wday1 -7) 7)))))
15905 (if (and (boundp 'org-time-was-given)
15906 (nth 2 tl))
15907 (setq org-time-was-given t))
15908 (if (< year 100) (setq year (+ 2000 year)))
15909 (if to-time
15910 (encode-time second minute hour day month year)
15911 (if (or (nth 1 tl) (nth 2 tl))
15912 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
15913 (format "%04d-%02d-%02d" year month day)))))
15915 (defun org-eval-in-calendar (form &optional keepdate)
15916 "Eval FORM in the calendar window and return to current window.
15917 Also, store the cursor date in variable org-ans2."
15918 (let ((sw (selected-window)))
15919 (select-window (get-buffer-window "*Calendar*"))
15920 (eval form)
15921 (when (and (not keepdate) (calendar-cursor-to-date))
15922 (let* ((date (calendar-cursor-to-date))
15923 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15924 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15925 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15926 (select-window sw)
15927 ;; Update the prompt to show new default date
15928 (save-excursion
15929 (goto-char (point-min))
15930 (when (and org-ans2
15931 (re-search-forward "\\[[-0-9]+\\]" nil t)
15932 (get-text-property (match-end 0) 'field))
15933 (let ((inhibit-read-only t))
15934 (replace-match (concat "[" org-ans2 "]") t t)
15935 (add-text-properties (point-min) (1+ (match-end 0))
15936 (text-properties-at (1+ (point-min)))))))))
15938 (defun org-calendar-select ()
15939 "Return to `org-read-date' with the date currently selected.
15940 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15941 (interactive)
15942 (when (calendar-cursor-to-date)
15943 (let* ((date (calendar-cursor-to-date))
15944 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15945 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15946 (if (active-minibuffer-window) (exit-minibuffer))))
15948 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15949 "Insert a date stamp for the date given by the internal TIME.
15950 WITH-HM means, use the stamp format that includes the time of the day.
15951 INACTIVE means use square brackets instead of angular ones, so that the
15952 stamp will not contribute to the agenda.
15953 PRE and POST are optional strings to be inserted before and after the
15954 stamp.
15955 The command returns the inserted time stamp."
15956 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15957 stamp)
15958 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15959 (insert (or pre ""))
15960 (insert (setq stamp (format-time-string fmt time)))
15961 (when (listp extra)
15962 (setq extra (car extra))
15963 (if (and (stringp extra)
15964 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15965 (setq extra (format "-%02d:%02d"
15966 (string-to-number (match-string 1 extra))
15967 (string-to-number (match-string 2 extra))))
15968 (setq extra nil)))
15969 (when extra
15970 (backward-char 1)
15971 (insert extra)
15972 (forward-char 1))
15973 (insert (or post ""))
15974 stamp))
15976 (defun org-toggle-time-stamp-overlays ()
15977 "Toggle the use of custom time stamp formats."
15978 (interactive)
15979 (setq org-display-custom-times (not org-display-custom-times))
15980 (unless org-display-custom-times
15981 (let ((p (point-min)) (bmp (buffer-modified-p)))
15982 (while (setq p (next-single-property-change p 'display))
15983 (if (and (get-text-property p 'display)
15984 (eq (get-text-property p 'face) 'org-date))
15985 (remove-text-properties
15986 p (setq p (next-single-property-change p 'display))
15987 '(display t))))
15988 (set-buffer-modified-p bmp)))
15989 (if (featurep 'xemacs)
15990 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15991 (org-restart-font-lock)
15992 (setq org-table-may-need-update t)
15993 (if org-display-custom-times
15994 (message "Time stamps are overlayed with custom format")
15995 (message "Time stamp overlays removed")))
15997 (defun org-display-custom-time (beg end)
15998 "Overlay modified time stamp format over timestamp between BED and END."
15999 (let* ((ts (buffer-substring beg end))
16000 t1 w1 with-hm tf time str w2 (off 0))
16001 (save-match-data
16002 (setq t1 (org-parse-time-string ts t))
16003 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
16004 (setq off (- (match-end 0) (match-beginning 0)))))
16005 (setq end (- end off))
16006 (setq w1 (- end beg)
16007 with-hm (and (nth 1 t1) (nth 2 t1))
16008 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16009 time (org-fix-decoded-time t1)
16010 str (org-add-props
16011 (format-time-string
16012 (substring tf 1 -1) (apply 'encode-time time))
16013 nil 'mouse-face 'highlight)
16014 w2 (length str))
16015 (if (not (= w2 w1))
16016 (add-text-properties (1+ beg) (+ 2 beg)
16017 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16018 (if (featurep 'xemacs)
16019 (progn
16020 (put-text-property beg end 'invisible t)
16021 (put-text-property beg end 'end-glyph (make-glyph str)))
16022 (put-text-property beg end 'display str))))
16024 (defun org-translate-time (string)
16025 "Translate all timestamps in STRING to custom format.
16026 But do this only if the variable `org-display-custom-times' is set."
16027 (when org-display-custom-times
16028 (save-match-data
16029 (let* ((start 0)
16030 (re org-ts-regexp-both)
16031 t1 with-hm inactive tf time str beg end)
16032 (while (setq start (string-match re string start))
16033 (setq beg (match-beginning 0)
16034 end (match-end 0)
16035 t1 (save-match-data
16036 (org-parse-time-string (substring string beg end) t))
16037 with-hm (and (nth 1 t1) (nth 2 t1))
16038 inactive (equal (substring string beg (1+ beg)) "[")
16039 tf (funcall (if with-hm 'cdr 'car)
16040 org-time-stamp-custom-formats)
16041 time (org-fix-decoded-time t1)
16042 str (format-time-string
16043 (concat
16044 (if inactive "[" "<") (substring tf 1 -1)
16045 (if inactive "]" ">"))
16046 (apply 'encode-time time))
16047 string (replace-match str t t string)
16048 start (+ start (length str)))))))
16049 string)
16051 (defun org-fix-decoded-time (time)
16052 "Set 0 instead of nil for the first 6 elements of time.
16053 Don't touch the rest."
16054 (let ((n 0))
16055 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16057 (defun org-days-to-time (timestamp-string)
16058 "Difference between TIMESTAMP-STRING and now in days."
16059 (- (time-to-days (org-time-string-to-time timestamp-string))
16060 (time-to-days (current-time))))
16062 (defun org-deadline-close (timestamp-string &optional ndays)
16063 "Is the time in TIMESTAMP-STRING close to the current date?"
16064 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16065 (and (< (org-days-to-time timestamp-string) ndays)
16066 (not (org-entry-is-done-p))))
16068 (defun org-get-wdays (ts)
16069 "Get the deadline lead time appropriate for timestring TS."
16070 (cond
16071 ((<= org-deadline-warning-days 0)
16072 ;; 0 or negative, enforce this value no matter what
16073 (- org-deadline-warning-days))
16074 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
16075 ;; lead time is specified.
16076 (floor (* (string-to-number (match-string 1 ts))
16077 (cdr (assoc (match-string 2 ts)
16078 '(("d" . 1) ("w" . 7)
16079 ("m" . 30.4) ("y" . 365.25)))))))
16080 ;; go for the default.
16081 (t org-deadline-warning-days)))
16083 (defun org-calendar-select-mouse (ev)
16084 "Return to `org-read-date' with the date currently selected.
16085 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16086 (interactive "e")
16087 (mouse-set-point ev)
16088 (when (calendar-cursor-to-date)
16089 (let* ((date (calendar-cursor-to-date))
16090 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16091 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16092 (if (active-minibuffer-window) (exit-minibuffer))))
16094 (defun org-check-deadlines (ndays)
16095 "Check if there are any deadlines due or past due.
16096 A deadline is considered due if it happens within `org-deadline-warning-days'
16097 days from today's date. If the deadline appears in an entry marked DONE,
16098 it is not shown. The prefix arg NDAYS can be used to test that many
16099 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16100 (interactive "P")
16101 (let* ((org-warn-days
16102 (cond
16103 ((equal ndays '(4)) 100000)
16104 (ndays (prefix-numeric-value ndays))
16105 (t (abs org-deadline-warning-days))))
16106 (case-fold-search nil)
16107 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16108 (callback
16109 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16111 (message "%d deadlines past-due or due within %d days"
16112 (org-occur regexp nil callback)
16113 org-warn-days)))
16115 (defun org-evaluate-time-range (&optional to-buffer)
16116 "Evaluate a time range by computing the difference between start and end.
16117 Normally the result is just printed in the echo area, but with prefix arg
16118 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16119 If the time range is actually in a table, the result is inserted into the
16120 next column.
16121 For time difference computation, a year is assumed to be exactly 365
16122 days in order to avoid rounding problems."
16123 (interactive "P")
16125 (org-clock-update-time-maybe)
16126 (save-excursion
16127 (unless (org-at-date-range-p t)
16128 (goto-char (point-at-bol))
16129 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16130 (if (not (org-at-date-range-p t))
16131 (error "Not at a time-stamp range, and none found in current line")))
16132 (let* ((ts1 (match-string 1))
16133 (ts2 (match-string 2))
16134 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16135 (match-end (match-end 0))
16136 (time1 (org-time-string-to-time ts1))
16137 (time2 (org-time-string-to-time ts2))
16138 (t1 (time-to-seconds time1))
16139 (t2 (time-to-seconds time2))
16140 (diff (abs (- t2 t1)))
16141 (negative (< (- t2 t1) 0))
16142 ;; (ys (floor (* 365 24 60 60)))
16143 (ds (* 24 60 60))
16144 (hs (* 60 60))
16145 (fy "%dy %dd %02d:%02d")
16146 (fy1 "%dy %dd")
16147 (fd "%dd %02d:%02d")
16148 (fd1 "%dd")
16149 (fh "%02d:%02d")
16150 y d h m align)
16151 (if havetime
16152 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16154 d (floor (/ diff ds)) diff (mod diff ds)
16155 h (floor (/ diff hs)) diff (mod diff hs)
16156 m (floor (/ diff 60)))
16157 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16159 d (floor (+ (/ diff ds) 0.5))
16160 h 0 m 0))
16161 (if (not to-buffer)
16162 (message (org-make-tdiff-string y d h m))
16163 (when (org-at-table-p)
16164 (goto-char match-end)
16165 (setq align t)
16166 (and (looking-at " *|") (goto-char (match-end 0))))
16167 (if (looking-at
16168 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16169 (replace-match ""))
16170 (if negative (insert " -"))
16171 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16172 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16173 (insert " " (format fh h m))))
16174 (if align (org-table-align))
16175 (message "Time difference inserted")))))
16177 (defun org-make-tdiff-string (y d h m)
16178 (let ((fmt "")
16179 (l nil))
16180 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16181 l (push y l)))
16182 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16183 l (push d l)))
16184 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16185 l (push h l)))
16186 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16187 l (push m l)))
16188 (apply 'format fmt (nreverse l))))
16190 (defun org-time-string-to-time (s)
16191 (apply 'encode-time (org-parse-time-string s)))
16193 (defun org-time-string-to-absolute (s &optional daynr)
16194 "Convert a time stamp to an absolute day number.
16195 If there is a specifyer for a cyclic time stamp, get the closest date to
16196 DAYNR."
16197 (cond
16198 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16199 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16200 daynr
16201 (+ daynr 1000)))
16202 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
16203 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16204 (time-to-days (current-time))) (match-string 0 s)))
16205 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
16207 (defun org-time-from-absolute (d)
16208 "Return the time corresponding to date D.
16209 D may be an absolute day number, or a calendar-type list (month day year)."
16210 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16211 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16213 (defun org-calendar-holiday ()
16214 "List of holidays, for Diary display in Org-mode."
16215 (let ((hl (check-calendar-holidays date)))
16216 (if hl (mapconcat 'identity hl "; "))))
16218 (defun org-diary-sexp-entry (sexp entry date)
16219 "Process a SEXP diary ENTRY for DATE."
16220 (require 'diary-lib)
16221 (let ((result (if calendar-debug-sexp
16222 (let ((stack-trace-on-error t))
16223 (eval (car (read-from-string sexp))))
16224 (condition-case nil
16225 (eval (car (read-from-string sexp)))
16226 (error
16227 (beep)
16228 (message "Bad sexp at line %d in %s: %s"
16229 (org-current-line)
16230 (buffer-file-name) sexp)
16231 (sleep-for 2))))))
16232 (cond ((stringp result) result)
16233 ((and (consp result)
16234 (stringp (cdr result))) (cdr result))
16235 (result entry)
16236 (t nil))))
16238 (defun org-diary-to-ical-string (frombuf)
16239 "Get iCalendar entreis from diary entries in buffer FROMBUF.
16240 This uses the icalendar.el library."
16241 (let* ((tmpdir (if (featurep 'xemacs)
16242 (temp-directory)
16243 temporary-file-directory))
16244 (tmpfile (make-temp-name
16245 (expand-file-name "orgics" tmpdir)))
16246 buf rtn b e)
16247 (save-excursion
16248 (set-buffer frombuf)
16249 (icalendar-export-region (point-min) (point-max) tmpfile)
16250 (setq buf (find-buffer-visiting tmpfile))
16251 (set-buffer buf)
16252 (goto-char (point-min))
16253 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16254 (setq b (match-beginning 0)))
16255 (goto-char (point-max))
16256 (if (re-search-backward "^END:VEVENT" nil t)
16257 (setq e (match-end 0)))
16258 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16259 (kill-buffer buf)
16260 (kill-buffer frombuf)
16261 (delete-file tmpfile)
16262 rtn))
16264 (defun org-closest-date (start current change)
16265 "Find the date closest to CURRENT that is consistent with START and CHANGE."
16266 ;; Make the proper lists from the dates
16267 (catch 'exit
16268 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16269 dn dw sday cday n1 n2
16270 d m y y1 y2 date1 date2 nmonths nm ny m2)
16272 (setq start (org-date-to-gregorian start)
16273 current (org-date-to-gregorian
16274 (if org-agenda-repeating-timestamp-show-all
16275 current
16276 (time-to-days (current-time))))
16277 sday (calendar-absolute-from-gregorian start)
16278 cday (calendar-absolute-from-gregorian current))
16280 (if (<= cday sday) (throw 'exit sday))
16282 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
16283 (setq dn (string-to-number (match-string 1 change))
16284 dw (cdr (assoc (match-string 2 change) a1)))
16285 (error "Invalid change specifyer: %s" change))
16286 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16287 (cond
16288 ((eq dw 'day)
16289 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16290 n2 (+ n1 dn)))
16291 ((eq dw 'year)
16292 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16293 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16294 (setq date1 (list m d y1)
16295 n1 (calendar-absolute-from-gregorian date1)
16296 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16297 n2 (calendar-absolute-from-gregorian date2)))
16298 ((eq dw 'month)
16299 ;; approx number of month between the tow dates
16300 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16301 ;; How often does dn fit in there?
16302 (setq d (nth 1 start) m (car start) y (nth 2 start)
16303 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16304 m (+ m nm)
16305 ny (floor (/ m 12))
16306 y (+ y ny)
16307 m (- m (* ny 12)))
16308 (while (> m 12) (setq m (- m 12) y (1+ y)))
16309 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16310 (setq m2 (+ m dn) y2 y)
16311 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16312 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16313 (while (< n2 cday)
16314 (setq n1 n2 m m2 y y2)
16315 (setq m2 (+ m dn) y2 y)
16316 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16317 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16319 (if org-agenda-repeating-timestamp-show-all
16320 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
16321 (if (= cday n1) n1 n2)))))
16323 (defun org-date-to-gregorian (date)
16324 "Turn any specification of DATE into a gregorian date for the calendar."
16325 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16326 ((and (listp date) (= (length date) 3)) date)
16327 ((stringp date)
16328 (setq date (org-parse-time-string date))
16329 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16330 ((listp date)
16331 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16333 (defun org-parse-time-string (s &optional nodefault)
16334 "Parse the standard Org-mode time string.
16335 This should be a lot faster than the normal `parse-time-string'.
16336 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16337 hour and minute fields will be nil if not given."
16338 (if (string-match org-ts-regexp0 s)
16339 (list 0
16340 (if (or (match-beginning 8) (not nodefault))
16341 (string-to-number (or (match-string 8 s) "0")))
16342 (if (or (match-beginning 7) (not nodefault))
16343 (string-to-number (or (match-string 7 s) "0")))
16344 (string-to-number (match-string 4 s))
16345 (string-to-number (match-string 3 s))
16346 (string-to-number (match-string 2 s))
16347 nil nil nil)
16348 (make-list 9 0)))
16350 (defun org-timestamp-up (&optional arg)
16351 "Increase the date item at the cursor by one.
16352 If the cursor is on the year, change the year. If it is on the month or
16353 the day, change that.
16354 With prefix ARG, change by that many units."
16355 (interactive "p")
16356 (org-timestamp-change (prefix-numeric-value arg)))
16358 (defun org-timestamp-down (&optional arg)
16359 "Decrease the date item at the cursor by one.
16360 If the cursor is on the year, change the year. If it is on the month or
16361 the day, change that.
16362 With prefix ARG, change by that many units."
16363 (interactive "p")
16364 (org-timestamp-change (- (prefix-numeric-value arg))))
16366 (defun org-timestamp-up-day (&optional arg)
16367 "Increase the date in the time stamp by one day.
16368 With prefix ARG, change that many days."
16369 (interactive "p")
16370 (if (and (not (org-at-timestamp-p t))
16371 (org-on-heading-p))
16372 (org-todo 'up)
16373 (org-timestamp-change (prefix-numeric-value arg) 'day)))
16375 (defun org-timestamp-down-day (&optional arg)
16376 "Decrease the date in the time stamp by one day.
16377 With prefix ARG, change that many days."
16378 (interactive "p")
16379 (if (and (not (org-at-timestamp-p t))
16380 (org-on-heading-p))
16381 (org-todo 'down)
16382 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
16384 (defsubst org-pos-in-match-range (pos n)
16385 (and (match-beginning n)
16386 (<= (match-beginning n) pos)
16387 (>= (match-end n) pos)))
16389 (defun org-at-timestamp-p (&optional inactive-ok)
16390 "Determine if the cursor is in or at a timestamp."
16391 (interactive)
16392 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16393 (pos (point))
16394 (ans (or (looking-at tsr)
16395 (save-excursion
16396 (skip-chars-backward "^[<\n\r\t")
16397 (if (> (point) (point-min)) (backward-char 1))
16398 (and (looking-at tsr)
16399 (> (- (match-end 0) pos) -1))))))
16400 (and ans
16401 (boundp 'org-ts-what)
16402 (setq org-ts-what
16403 (cond
16404 ((org-pos-in-match-range pos 2) 'year)
16405 ((org-pos-in-match-range pos 3) 'month)
16406 ((org-pos-in-match-range pos 7) 'hour)
16407 ((org-pos-in-match-range pos 8) 'minute)
16408 ((or (org-pos-in-match-range pos 4)
16409 (org-pos-in-match-range pos 5)) 'day)
16410 ((and (> pos (or (match-end 8) (match-end 5)))
16411 (< pos (match-end 0)))
16412 (- pos (or (match-end 8) (match-end 5))))
16413 (t 'day))))
16414 ans))
16416 (defun org-timestamp-change (n &optional what)
16417 "Change the date in the time stamp at point.
16418 The date will be changed by N times WHAT. WHAT can be `day', `month',
16419 `year', `minute', `second'. If WHAT is not given, the cursor position
16420 in the timestamp determines what will be changed."
16421 (let ((pos (point))
16422 with-hm inactive
16423 org-ts-what
16424 extra
16425 ts time time0)
16426 (if (not (org-at-timestamp-p t))
16427 (error "Not at a timestamp"))
16428 (if (and (not what) (not (eq org-ts-what 'day))
16429 org-display-custom-times
16430 (get-text-property (point) 'display)
16431 (not (get-text-property (1- (point)) 'display)))
16432 (setq org-ts-what 'day))
16433 (setq org-ts-what (or what org-ts-what)
16434 inactive (= (char-after (match-beginning 0)) ?\[)
16435 ts (match-string 0))
16436 (replace-match "")
16437 (if (string-match
16438 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
16440 (setq extra (match-string 1 ts)))
16441 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16442 (setq with-hm t))
16443 (setq time0 (org-parse-time-string ts))
16444 (setq time
16445 (apply 'encode-time
16446 (append
16447 (list (or (car time0) 0))
16448 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
16449 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
16450 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
16451 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
16452 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
16453 (nthcdr 6 time0))))
16454 (when (integerp org-ts-what)
16455 (setq extra (org-modify-ts-extra extra org-ts-what n)))
16456 (if (eq what 'calendar)
16457 (let ((cal-date (org-get-date-from-calendar)))
16458 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16459 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16460 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16461 (setcar time0 (or (car time0) 0))
16462 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16463 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
16464 (setq time (apply 'encode-time time0))))
16465 (setq org-last-changed-timestamp
16466 (org-insert-time-stamp time with-hm inactive nil nil extra))
16467 (org-clock-update-time-maybe)
16468 (goto-char pos)
16469 ;; Try to recenter the calendar window, if any
16470 (if (and org-calendar-follow-timestamp-change
16471 (get-buffer-window "*Calendar*" t)
16472 (memq org-ts-what '(day month year)))
16473 (org-recenter-calendar (time-to-days time)))))
16475 ;; FIXME: does not yet work for lead times
16476 (defun org-modify-ts-extra (s pos n)
16477 "Change the different parts of the lead-time and repeat fields in timestamp."
16478 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16479 ng h m new)
16480 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16481 (cond
16482 ((or (org-pos-in-match-range pos 2)
16483 (org-pos-in-match-range pos 3))
16484 (setq m (string-to-number (match-string 3 s))
16485 h (string-to-number (match-string 2 s)))
16486 (if (org-pos-in-match-range pos 2)
16487 (setq h (+ h n))
16488 (setq m (+ m n)))
16489 (if (< m 0) (setq m (+ m 60) h (1- h)))
16490 (if (> m 59) (setq m (- m 60) h (1+ h)))
16491 (setq h (min 24 (max 0 h)))
16492 (setq ng 1 new (format "-%02d:%02d" h m)))
16493 ((org-pos-in-match-range pos 6)
16494 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16495 ((org-pos-in-match-range pos 5)
16496 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
16498 (when ng
16499 (setq s (concat
16500 (substring s 0 (match-beginning ng))
16502 (substring s (match-end ng))))))
16505 (defun org-recenter-calendar (date)
16506 "If the calendar is visible, recenter it to DATE."
16507 (let* ((win (selected-window))
16508 (cwin (get-buffer-window "*Calendar*" t))
16509 (calendar-move-hook nil))
16510 (when cwin
16511 (select-window cwin)
16512 (calendar-goto-date (if (listp date) date
16513 (calendar-gregorian-from-absolute date)))
16514 (select-window win))))
16516 (defun org-goto-calendar (&optional arg)
16517 "Go to the Emacs calendar at the current date.
16518 If there is a time stamp in the current line, go to that date.
16519 A prefix ARG can be used to force the current date."
16520 (interactive "P")
16521 (let ((tsr org-ts-regexp) diff
16522 (calendar-move-hook nil)
16523 (view-calendar-holidays-initially nil)
16524 (view-diary-entries-initially nil))
16525 (if (or (org-at-timestamp-p)
16526 (save-excursion
16527 (beginning-of-line 1)
16528 (looking-at (concat ".*" tsr))))
16529 (let ((d1 (time-to-days (current-time)))
16530 (d2 (time-to-days
16531 (org-time-string-to-time (match-string 1)))))
16532 (setq diff (- d2 d1))))
16533 (calendar)
16534 (calendar-goto-today)
16535 (if (and diff (not arg)) (calendar-forward-day diff))))
16537 (defun org-get-date-from-calendar ()
16538 "Return a list (month day year) of date at point in calendar."
16539 (with-current-buffer "*Calendar*"
16540 (save-match-data
16541 (calendar-cursor-to-date))))
16543 (defun org-date-from-calendar ()
16544 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16545 If there is already a time stamp at the cursor position, update it."
16546 (interactive)
16547 (if (org-at-timestamp-p t)
16548 (org-timestamp-change 0 'calendar)
16549 (let ((cal-date (org-get-date-from-calendar)))
16550 (org-insert-time-stamp
16551 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16553 ;; Make appt aware of appointments from the agenda
16554 (defun org-agenda-to-appt (&optional filter)
16555 "Activate appointments found in `org-agenda-files'.
16556 When prefixed, prompt for a regular expression and use it as a
16557 filter: only add entries if they match this regular expression.
16559 FILTER can be a string. In this case, use this string as a
16560 regular expression to filter results.
16562 FILTER can also be an alist, with the car of each cell being
16563 either 'headline or 'category. For example:
16565 '((headline \"IMPORTANT\")
16566 (category \"Work\"))
16568 will only add headlines containing IMPORTANT or headlines
16569 belonging to the category \"Work\"."
16570 (interactive "P")
16571 (require 'org)
16572 (if (equal filter '(4))
16573 (setq filter (read-from-minibuffer "Regexp filter: ")))
16574 (let* ((today (org-date-to-gregorian
16575 (time-to-days (current-time))))
16576 (files org-agenda-files) entries file)
16577 (while (setq file (pop files))
16578 (setq entries (append entries (org-agenda-get-day-entries
16579 file today :timestamp))))
16580 (setq entries (delq nil entries))
16581 (mapc
16582 (lambda(x)
16583 (let* ((evt (org-trim (get-text-property 1 'txt x)))
16584 (cat (get-text-property 1 'org-category x))
16585 (tod (get-text-property 1 'time-of-day x))
16586 (ok (or (and (stringp filter) (string-match filter evt))
16587 (and (not (null filter)) (listp filter)
16588 (or (string-match
16589 (cadr (assoc 'category filter)) cat)
16590 (string-match
16591 (cadr (assoc 'headline filter)) evt))))))
16592 ;; (setq evt (set-text-properties 0 (length event) nil evt))
16593 (when (and ok tod)
16594 (setq tod (number-to-string tod)
16595 tod (when (string-match
16596 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
16597 (concat (match-string 1 tod) ":"
16598 (match-string 2 tod))))
16599 (appt-add tod evt)))) entries)
16600 nil))
16602 ;;; The clock for measuring work time.
16604 (defvar org-mode-line-string "")
16605 (put 'org-mode-line-string 'risky-local-variable t)
16607 (defvar org-mode-line-timer nil)
16608 (defvar org-clock-heading "")
16609 (defvar org-clock-start-time "")
16611 (defun org-update-mode-line ()
16612 (let* ((delta (- (time-to-seconds (current-time))
16613 (time-to-seconds org-clock-start-time)))
16614 (h (floor delta 3600))
16615 (m (floor (- delta (* 3600 h)) 60)))
16616 (setq org-mode-line-string
16617 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
16618 'help-echo "Org-mode clock is running"))
16619 (force-mode-line-update)))
16621 (defvar org-clock-marker (make-marker)
16622 "Marker recording the last clock-in.")
16623 (defvar org-clock-mode-line-entry nil
16624 "Information for the modeline about the running clock.")
16626 (defun org-clock-in ()
16627 "Start the clock on the current item.
16628 If necessary, clock-out of the currently active clock."
16629 (interactive)
16630 (org-clock-out t)
16631 (let (ts)
16632 (save-excursion
16633 (org-back-to-heading t)
16634 (if (looking-at org-todo-line-regexp)
16635 (setq org-clock-heading (match-string 3))
16636 (setq org-clock-heading "???"))
16637 (setq org-clock-heading (propertize org-clock-heading 'face nil))
16638 (org-clock-find-position)
16640 (insert "\n") (backward-char 1)
16641 (indent-relative)
16642 (insert org-clock-string " ")
16643 (setq org-clock-start-time (current-time))
16644 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
16645 (move-marker org-clock-marker (point) (buffer-base-buffer))
16646 (or global-mode-string (setq global-mode-string '("")))
16647 (or (memq 'org-mode-line-string global-mode-string)
16648 (setq global-mode-string
16649 (append global-mode-string '(org-mode-line-string))))
16650 (org-update-mode-line)
16651 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
16652 (message "Clock started at %s" ts))))
16654 (defun org-clock-find-position ()
16655 "Find the location where the next clock line should be inserted."
16656 (org-back-to-heading t)
16657 (catch 'exit
16658 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
16659 (re (concat "^[ \t]*" org-clock-string))
16660 (cnt 0)
16661 first last)
16662 (goto-char beg)
16663 (when (eobp) (newline) (setq end (max (point) end)))
16664 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
16665 ;; we seem to have a CLOCK drawer, so go there.
16666 (beginning-of-line 2)
16667 (throw 'exit t))
16668 ;; Lets count the CLOCK lines
16669 (goto-char beg)
16670 (while (re-search-forward re end t)
16671 (setq first (or first (match-beginning 0))
16672 last (match-beginning 0)
16673 cnt (1+ cnt)))
16674 (when (and (integerp org-clock-into-drawer)
16675 (>= (1+ cnt) org-clock-into-drawer))
16676 ;; Wrap current entries into a new drawer
16677 (goto-char last)
16678 (beginning-of-line 2)
16679 (if (org-at-item-p) (org-end-of-item))
16680 (insert ":END:\n")
16681 (beginning-of-line 0)
16682 (org-indent-line-function)
16683 (goto-char first)
16684 (insert ":CLOCK:\n")
16685 (beginning-of-line 0)
16686 (org-indent-line-function)
16687 (org-flag-drawer t)
16688 (beginning-of-line 2)
16689 (throw 'exit nil))
16691 (goto-char beg)
16692 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
16693 (not (equal (match-string 1) org-clock-string)))
16694 ;; Planning info, skip to after it
16695 (beginning-of-line 2)
16696 (or (bolp) (newline)))
16697 (when (eq t org-clock-into-drawer)
16698 (insert ":CLOCK:\n:END:\n")
16699 (beginning-of-line -1)
16700 (org-indent-line-function)
16701 (org-flag-drawer t)
16702 (beginning-of-line 2)
16703 (org-indent-line-function)))))
16705 (defun org-clock-out (&optional fail-quietly)
16706 "Stop the currently running clock.
16707 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
16708 (interactive)
16709 (catch 'exit
16710 (if (not (marker-buffer org-clock-marker))
16711 (if fail-quietly (throw 'exit t) (error "No active clock")))
16712 (let (ts te s h m)
16713 (save-excursion
16714 (set-buffer (marker-buffer org-clock-marker))
16715 (goto-char org-clock-marker)
16716 (beginning-of-line 1)
16717 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
16718 (equal (match-string 1) org-clock-string))
16719 (setq ts (match-string 2))
16720 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
16721 (goto-char (match-end 0))
16722 (delete-region (point) (point-at-eol))
16723 (insert "--")
16724 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
16725 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
16726 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
16727 h (floor (/ s 3600))
16728 s (- s (* 3600 h))
16729 m (floor (/ s 60))
16730 s (- s (* 60 s)))
16731 (insert " => " (format "%2d:%02d" h m))
16732 (move-marker org-clock-marker nil)
16733 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
16734 (org-log-done (org-parse-local-options logging 'org-log-done))
16735 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
16736 (org-add-log-maybe 'clock-out))
16737 (when org-mode-line-timer
16738 (cancel-timer org-mode-line-timer)
16739 (setq org-mode-line-timer nil))
16740 (setq global-mode-string
16741 (delq 'org-mode-line-string global-mode-string))
16742 (force-mode-line-update)
16743 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
16745 (defun org-clock-cancel ()
16746 "Cancel the running clock be removing the start timestamp."
16747 (interactive)
16748 (if (not (marker-buffer org-clock-marker))
16749 (error "No active clock"))
16750 (save-excursion
16751 (set-buffer (marker-buffer org-clock-marker))
16752 (goto-char org-clock-marker)
16753 (delete-region (1- (point-at-bol)) (point-at-eol)))
16754 (message "Clock canceled"))
16756 (defun org-clock-goto (&optional delete-windows)
16757 "Go to the currently clocked-in entry."
16758 (interactive "P")
16759 (if (not (marker-buffer org-clock-marker))
16760 (error "No active clock"))
16761 (switch-to-buffer-other-window
16762 (marker-buffer org-clock-marker))
16763 (if delete-windows (delete-other-windows))
16764 (goto-char org-clock-marker)
16765 (org-show-entry)
16766 (org-back-to-heading)
16767 (recenter))
16769 (defvar org-clock-file-total-minutes nil
16770 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
16771 (make-variable-buffer-local 'org-clock-file-total-minutes)
16773 (defun org-clock-sum (&optional tstart tend)
16774 "Sum the times for each subtree.
16775 Puts the resulting times in minutes as a text property on each headline."
16776 (interactive)
16777 (let* ((bmp (buffer-modified-p))
16778 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
16779 org-clock-string
16780 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
16781 (lmax 30)
16782 (ltimes (make-vector lmax 0))
16783 (t1 0)
16784 (level 0)
16785 ts te dt
16786 time)
16787 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
16788 (save-excursion
16789 (goto-char (point-max))
16790 (while (re-search-backward re nil t)
16791 (cond
16792 ((match-end 2)
16793 ;; Two time stamps
16794 (setq ts (match-string 2)
16795 te (match-string 3)
16796 ts (time-to-seconds
16797 (apply 'encode-time (org-parse-time-string ts)))
16798 te (time-to-seconds
16799 (apply 'encode-time (org-parse-time-string te)))
16800 ts (if tstart (max ts tstart) ts)
16801 te (if tend (min te tend) te)
16802 dt (- te ts)
16803 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
16804 ((match-end 4)
16805 ;; A naket time
16806 (setq t1 (+ t1 (string-to-number (match-string 5))
16807 (* 60 (string-to-number (match-string 4))))))
16808 (t ;; A headline
16809 (setq level (- (match-end 1) (match-beginning 1)))
16810 (when (or (> t1 0) (> (aref ltimes level) 0))
16811 (loop for l from 0 to level do
16812 (aset ltimes l (+ (aref ltimes l) t1)))
16813 (setq t1 0 time (aref ltimes level))
16814 (loop for l from level to (1- lmax) do
16815 (aset ltimes l 0))
16816 (goto-char (match-beginning 0))
16817 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
16818 (setq org-clock-file-total-minutes (aref ltimes 0)))
16819 (set-buffer-modified-p bmp)))
16821 (defun org-clock-display (&optional total-only)
16822 "Show subtree times in the entire buffer.
16823 If TOTAL-ONLY is non-nil, only show the total time for the entire file
16824 in the echo area."
16825 (interactive)
16826 (org-remove-clock-overlays)
16827 (let (time h m p)
16828 (org-clock-sum)
16829 (unless total-only
16830 (save-excursion
16831 (goto-char (point-min))
16832 (while (or (and (equal (setq p (point)) (point-min))
16833 (get-text-property p :org-clock-minutes))
16834 (setq p (next-single-property-change
16835 (point) :org-clock-minutes)))
16836 (goto-char p)
16837 (when (setq time (get-text-property p :org-clock-minutes))
16838 (org-put-clock-overlay time (funcall outline-level))))
16839 (setq h (/ org-clock-file-total-minutes 60)
16840 m (- org-clock-file-total-minutes (* 60 h)))
16841 ;; Arrange to remove the overlays upon next change.
16842 (when org-remove-highlights-with-change
16843 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
16844 nil 'local))))
16845 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
16847 (defvar org-clock-overlays nil)
16848 (make-variable-buffer-local 'org-clock-overlays)
16850 (defun org-put-clock-overlay (time &optional level)
16851 "Put an overlays on the current line, displaying TIME.
16852 If LEVEL is given, prefix time with a corresponding number of stars.
16853 This creates a new overlay and stores it in `org-clock-overlays', so that it
16854 will be easy to remove."
16855 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
16856 (l (if level (org-get-legal-level level 0) 0))
16857 (off 0)
16858 ov tx)
16859 (move-to-column c)
16860 (unless (eolp) (skip-chars-backward "^ \t"))
16861 (skip-chars-backward " \t")
16862 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
16863 tx (concat (buffer-substring (1- (point)) (point))
16864 (make-string (+ off (max 0 (- c (current-column)))) ?.)
16865 (org-add-props (format "%s %2d:%02d%s"
16866 (make-string l ?*) h m
16867 (make-string (- 10 l) ?\ ))
16868 '(face secondary-selection))
16869 ""))
16870 (if (not (featurep 'xemacs))
16871 (org-overlay-put ov 'display tx)
16872 (org-overlay-put ov 'invisible t)
16873 (org-overlay-put ov 'end-glyph (make-glyph tx)))
16874 (push ov org-clock-overlays)))
16876 (defun org-remove-clock-overlays (&optional beg end noremove)
16877 "Remove the occur highlights from the buffer.
16878 BEG and END are ignored. If NOREMOVE is nil, remove this function
16879 from the `before-change-functions' in the current buffer."
16880 (interactive)
16881 (unless org-inhibit-highlight-removal
16882 (mapc 'org-delete-overlay org-clock-overlays)
16883 (setq org-clock-overlays nil)
16884 (unless noremove
16885 (remove-hook 'before-change-functions
16886 'org-remove-clock-overlays 'local))))
16888 (defun org-clock-out-if-current ()
16889 "Clock out if the current entry contains the running clock.
16890 This is used to stop the clock after a TODO entry is marked DONE,
16891 and is only done if the variable `org-clock-out-when-done' is not nil."
16892 (when (and org-clock-out-when-done
16893 (member state org-done-keywords)
16894 (equal (marker-buffer org-clock-marker) (current-buffer))
16895 (< (point) org-clock-marker)
16896 (> (save-excursion (outline-next-heading) (point))
16897 org-clock-marker))
16898 ;; Clock out, but don't accept a logging message for this.
16899 (let ((org-log-done (if (and (listp org-log-done)
16900 (member 'clock-out org-log-done))
16901 '(done)
16902 org-log-done)))
16903 (org-clock-out))))
16905 (add-hook 'org-after-todo-state-change-hook
16906 'org-clock-out-if-current)
16908 (defun org-check-running-clock ()
16909 "Check if the current buffer contains the running clock.
16910 If yes, offer to stop it and to save the buffer with the changes."
16911 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
16912 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
16913 (buffer-name))))
16914 (org-clock-out)
16915 (when (y-or-n-p "Save changed buffer?")
16916 (save-buffer))))
16918 (defun org-clock-report (&optional arg)
16919 "Create a table containing a report about clocked time.
16920 If the cursor is inside an existing clocktable block, then the table
16921 will be updated. If not, a new clocktable will be inserted.
16922 When called with a prefix argument, move to the first clock table in the
16923 buffer and update it."
16924 (interactive "P")
16925 (org-remove-clock-overlays)
16926 (when arg (org-find-dblock "clocktable"))
16927 (if (org-in-clocktable-p)
16928 (goto-char (org-in-clocktable-p))
16929 (org-create-dblock (list :name "clocktable"
16930 :maxlevel 2 :scope 'file)))
16931 (org-update-dblock))
16933 (defun org-in-clocktable-p ()
16934 "Check if the cursor is in a clocktable."
16935 (let ((pos (point)) start)
16936 (save-excursion
16937 (end-of-line 1)
16938 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
16939 (setq start (match-beginning 0))
16940 (re-search-forward "^#\\+END:.*" nil t)
16941 (>= (match-end 0) pos)
16942 start))))
16944 (defun org-clock-update-time-maybe ()
16945 "If this is a CLOCK line, update it and return t.
16946 Otherwise, return nil."
16947 (interactive)
16948 (save-excursion
16949 (beginning-of-line 1)
16950 (skip-chars-forward " \t")
16951 (when (looking-at org-clock-string)
16952 (let ((re (concat "[ \t]*" org-clock-string
16953 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
16954 "\\([ \t]*=>.*\\)?"))
16955 ts te h m s)
16956 (if (not (looking-at re))
16958 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
16959 (end-of-line 1)
16960 (setq ts (match-string 1)
16961 te (match-string 2))
16962 (setq s (- (time-to-seconds
16963 (apply 'encode-time (org-parse-time-string te)))
16964 (time-to-seconds
16965 (apply 'encode-time (org-parse-time-string ts))))
16966 h (floor (/ s 3600))
16967 s (- s (* 3600 h))
16968 m (floor (/ s 60))
16969 s (- s (* 60 s)))
16970 (insert " => " (format "%2d:%02d" h m))
16971 t)))))
16973 (defun org-clock-special-range (key &optional time as-strings)
16974 "Return two times bordering a special time range.
16975 Key is a symbol specifying the range and can be one of `today', `yesterday',
16976 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
16977 A week starts Monday 0:00 and ends Sunday 24:00.
16978 The range is determined relative to TIME. TIME defaults to the current time.
16979 The return value is a cons cell with two internal times like the ones
16980 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
16981 the returned times will be formatted strings."
16982 (let* ((tm (decode-time (or time (current-time))))
16983 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
16984 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
16985 (dow (nth 6 tm))
16986 s1 m1 h1 d1 month1 y1 diff ts te fm)
16987 (cond
16988 ((eq key 'today)
16989 (setq h 0 m 0 h1 24 m1 0))
16990 ((eq key 'yesterday)
16991 (setq d (1- d) h 0 m 0 h1 24 m1 0))
16992 ((eq key 'thisweek)
16993 (setq diff (if (= dow 0) 6 (1- dow))
16994 m 0 h 0 d (- d diff) d1 (+ 7 d)))
16995 ((eq key 'lastweek)
16996 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
16997 m 0 h 0 d (- d diff) d1 (+ 7 d)))
16998 ((eq key 'thismonth)
16999 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
17000 ((eq key 'lastmonth)
17001 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
17002 ((eq key 'thisyear)
17003 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
17004 ((eq key 'lastyear)
17005 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
17006 (t (error "No such time block %s" key)))
17007 (setq ts (encode-time s m h d month y)
17008 te (encode-time (or s1 s) (or m1 m) (or h1 h)
17009 (or d1 d) (or month1 month) (or y1 y)))
17010 (setq fm (cdr org-time-stamp-formats))
17011 (if as-strings
17012 (cons (format-time-string fm ts) (format-time-string fm te))
17013 (cons ts te))))
17015 (defun org-dblock-write:clocktable (params)
17016 "Write the standard clocktable."
17017 (let ((hlchars '((1 . "*") (2 . "/")))
17018 (emph nil)
17019 (ins (make-marker))
17020 (total-time nil)
17021 ipos time h m p level hlc hdl maxlevel
17022 ts te cc block beg end pos scope tbl tostring multifile)
17023 (setq scope (plist-get params :scope)
17024 tostring (plist-get params :tostring)
17025 multifile (plist-get params :multifile)
17026 maxlevel (or (plist-get params :maxlevel) 3)
17027 emph (plist-get params :emphasize)
17028 ts (plist-get params :tstart)
17029 te (plist-get params :tend)
17030 block (plist-get params :block))
17031 (when block
17032 (setq cc (org-clock-special-range block nil t)
17033 ts (car cc) te (cdr cc)))
17034 (if ts (setq ts (time-to-seconds
17035 (apply 'encode-time (org-parse-time-string ts)))))
17036 (if te (setq te (time-to-seconds
17037 (apply 'encode-time (org-parse-time-string te)))))
17038 (move-marker ins (point))
17039 (setq ipos (point))
17041 ;; Get the right scope
17042 (setq pos (point))
17043 (save-restriction
17044 (cond
17045 ((not scope))
17046 ((eq scope 'file) (widen))
17047 ((eq scope 'subtree) (org-narrow-to-subtree))
17048 ((eq scope 'tree)
17049 (while (org-up-heading-safe))
17050 (org-narrow-to-subtree))
17051 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
17052 (symbol-name scope)))
17053 (setq level (string-to-number (match-string 1 (symbol-name scope))))
17054 (catch 'exit
17055 (while (org-up-heading-safe)
17056 (looking-at outline-regexp)
17057 (if (<= (org-reduced-level (funcall outline-level)) level)
17058 (throw 'exit nil))))
17059 (org-narrow-to-subtree))
17060 ((or (listp scope) (eq scope 'agenda))
17061 (let* ((files (if (listp scope) scope (org-agenda-files)))
17062 (scope 'agenda)
17063 (p1 (copy-sequence params))
17064 file)
17065 (plist-put p1 :tostring t)
17066 (plist-put p1 :multifile t)
17067 (plist-put p1 :scope 'file)
17068 (org-prepare-agenda-buffers files)
17069 (while (setq file (pop files))
17070 (with-current-buffer (find-buffer-visiting file)
17071 (push (org-clocktable-add-file
17072 file (org-dblock-write:clocktable p1)) tbl)
17073 (setq total-time (+ (or total-time 0)
17074 org-clock-file-total-minutes)))))))
17075 (goto-char pos)
17077 (unless (eq scope 'agenda)
17078 (org-clock-sum ts te)
17079 (goto-char (point-min))
17080 (while (setq p (next-single-property-change (point) :org-clock-minutes))
17081 (goto-char p)
17082 (when (setq time (get-text-property p :org-clock-minutes))
17083 (save-excursion
17084 (beginning-of-line 1)
17085 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
17086 (setq level (org-reduced-level
17087 (- (match-end 1) (match-beginning 1))))
17088 (<= level maxlevel))
17089 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
17090 hdl (match-string 2)
17091 h (/ time 60)
17092 m (- time (* 60 h)))
17093 (if (and (not multifile) (= level 1)) (push "|-" tbl))
17094 (push (concat
17095 "| " (int-to-string level) "|" hlc hdl hlc " |"
17096 (make-string (1- level) ?|)
17097 hlc (format "%d:%02d" h m) hlc
17098 " |") tbl))))))
17099 (setq tbl (nreverse tbl))
17100 (if tostring
17101 (if tbl (mapconcat 'identity tbl "\n") nil)
17102 (goto-char ins)
17103 (insert-before-markers
17104 "Clock summary at ["
17105 (substring
17106 (format-time-string (cdr org-time-stamp-formats))
17107 1 -1)
17108 "]."
17109 (if block
17110 (format " Considered range is /%s/." block)
17112 "\n\n"
17113 (if (eq scope 'agenda) "|File" "")
17114 "|L|Headline|Time|\n")
17115 (setq total-time (or total-time org-clock-file-total-minutes)
17116 h (/ total-time 60)
17117 m (- total-time (* 60 h)))
17118 (insert-before-markers
17119 "|-\n|"
17120 (if (eq scope 'agenda) "|" "")
17121 "|"
17122 "*Total time*| "
17123 (format "*%d:%02d*" h m)
17124 "|\n|-\n")
17125 (setq tbl (delq nil tbl))
17126 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
17127 (equal (substring (car tbl) 0 2) "|-"))
17128 (pop tbl))
17129 (insert-before-markers (mapconcat
17130 'identity (delq nil tbl)
17131 (if (eq scope 'agenda) "\n|-\n" "\n")))
17132 (backward-delete-char 1)
17133 (goto-char ipos)
17134 (skip-chars-forward "^|")
17135 (org-table-align)))))
17137 (defun org-clocktable-add-file (file table)
17138 (if table
17139 (let ((lines (org-split-string table "\n"))
17140 (ff (file-name-nondirectory file)))
17141 (mapconcat 'identity
17142 (mapcar (lambda (x)
17143 (if (string-match org-table-dataline-regexp x)
17144 (concat "|" ff x)
17146 lines)
17147 "\n"))))
17149 ;; FIXME: I don't think anybody uses this, ask David
17150 (defun org-collect-clock-time-entries ()
17151 "Return an internal list with clocking information.
17152 This list has one entry for each CLOCK interval.
17153 FIXME: describe the elements."
17154 (interactive)
17155 (let ((re (concat "^[ \t]*" org-clock-string
17156 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
17157 rtn beg end next cont level title total closedp leafp
17158 clockpos titlepos h m donep)
17159 (save-excursion
17160 (org-clock-sum)
17161 (goto-char (point-min))
17162 (while (re-search-forward re nil t)
17163 (setq clockpos (match-beginning 0)
17164 beg (match-string 1) end (match-string 2)
17165 cont (match-end 0))
17166 (setq beg (apply 'encode-time (org-parse-time-string beg))
17167 end (apply 'encode-time (org-parse-time-string end)))
17168 (org-back-to-heading t)
17169 (setq donep (org-entry-is-done-p))
17170 (setq titlepos (point)
17171 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
17172 h (/ total 60) m (- total (* 60 h))
17173 total (cons h m))
17174 (looking-at "\\(\\*+\\) +\\(.*\\)")
17175 (setq level (- (match-end 1) (match-beginning 1))
17176 title (org-match-string-no-properties 2))
17177 (save-excursion (outline-next-heading) (setq next (point)))
17178 (setq closedp (re-search-forward org-closed-time-regexp next t))
17179 (goto-char next)
17180 (setq leafp (and (looking-at "^\\*+ ")
17181 (<= (- (match-end 0) (point)) level)))
17182 (push (list beg end clockpos closedp donep
17183 total title titlepos level leafp)
17184 rtn)
17185 (goto-char cont)))
17186 (nreverse rtn)))
17188 ;;;; Agenda, and Diary Integration
17190 ;;; Define the Org-agenda-mode
17192 (defvar org-agenda-mode-map (make-sparse-keymap)
17193 "Keymap for `org-agenda-mode'.")
17195 (defvar org-agenda-menu) ; defined later in this file.
17196 (defvar org-agenda-follow-mode nil)
17197 (defvar org-agenda-show-log nil)
17198 (defvar org-agenda-redo-command nil)
17199 (defvar org-agenda-mode-hook nil)
17200 (defvar org-agenda-type nil)
17201 (defvar org-agenda-force-single-file nil)
17203 (defun org-agenda-mode ()
17204 "Mode for time-sorted view on action items in Org-mode files.
17206 The following commands are available:
17208 \\{org-agenda-mode-map}"
17209 (interactive)
17210 (kill-all-local-variables)
17211 (setq org-agenda-undo-list nil
17212 org-agenda-pending-undo-list nil)
17213 (setq major-mode 'org-agenda-mode)
17214 ;; Keep global-font-lock-mode from turning on font-lock-mode
17215 (org-set-local 'font-lock-global-modes (list 'not major-mode))
17216 (setq mode-name "Org-Agenda")
17217 (use-local-map org-agenda-mode-map)
17218 (easy-menu-add org-agenda-menu)
17219 (if org-startup-truncated (setq truncate-lines t))
17220 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
17221 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
17222 ;; Make sure properties are removed when copying text
17223 (when (boundp 'buffer-substring-filters)
17224 (org-set-local 'buffer-substring-filters
17225 (cons (lambda (x)
17226 (set-text-properties 0 (length x) nil x) x)
17227 buffer-substring-filters)))
17228 (unless org-agenda-keep-modes
17229 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
17230 org-agenda-show-log nil))
17231 (easy-menu-change
17232 '("Agenda") "Agenda Files"
17233 (append
17234 (list
17235 (vector
17236 (if (get 'org-agenda-files 'org-restrict)
17237 "Restricted to single file"
17238 "Edit File List")
17239 '(org-edit-agenda-file-list)
17240 (not (get 'org-agenda-files 'org-restrict)))
17241 "--")
17242 (mapcar 'org-file-menu-entry (org-agenda-files))))
17243 (org-agenda-set-mode-name)
17244 (apply
17245 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
17246 (list 'org-agenda-mode-hook)))
17248 (substitute-key-definition 'undo 'org-agenda-undo
17249 org-agenda-mode-map global-map)
17250 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
17251 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
17252 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
17253 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
17254 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
17255 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
17256 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
17257 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
17258 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
17259 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
17260 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
17261 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
17262 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
17263 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
17264 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
17265 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
17266 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
17267 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
17268 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
17269 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
17270 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
17271 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
17272 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
17273 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
17274 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
17275 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
17276 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
17277 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
17278 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
17280 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
17281 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
17282 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
17283 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
17284 (while l (org-defkey org-agenda-mode-map
17285 (int-to-string (pop l)) 'digit-argument)))
17287 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
17288 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
17289 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
17290 (org-defkey org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
17291 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
17292 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
17293 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
17294 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
17295 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
17296 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
17297 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
17298 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
17299 (org-defkey org-agenda-mode-map "n" 'next-line)
17300 (org-defkey org-agenda-mode-map "p" 'previous-line)
17301 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
17302 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
17303 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
17304 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
17305 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
17306 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
17307 (eval-after-load "calendar"
17308 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
17309 'org-calendar-goto-agenda))
17310 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
17311 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
17312 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
17313 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
17314 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
17315 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
17316 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
17317 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
17318 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
17319 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
17320 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
17321 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17322 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
17323 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
17324 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
17325 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
17326 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
17327 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
17328 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
17329 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
17330 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
17331 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
17333 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
17334 "Local keymap for agenda entries from Org-mode.")
17336 (org-defkey org-agenda-keymap
17337 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
17338 (org-defkey org-agenda-keymap
17339 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
17340 (when org-agenda-mouse-1-follows-link
17341 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
17342 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
17343 '("Agenda"
17344 ("Agenda Files")
17345 "--"
17346 ["Show" org-agenda-show t]
17347 ["Go To (other window)" org-agenda-goto t]
17348 ["Go To (this window)" org-agenda-switch-to t]
17349 ["Follow Mode" org-agenda-follow-mode
17350 :style toggle :selected org-agenda-follow-mode :active t]
17351 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
17352 "--"
17353 ["Cycle TODO" org-agenda-todo t]
17354 ["Archive subtree" org-agenda-archive t]
17355 ["Delete subtree" org-agenda-kill t]
17356 "--"
17357 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
17358 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
17359 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
17360 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
17361 "--"
17362 ("Tags and Properties"
17363 ["Show all Tags" org-agenda-show-tags t]
17364 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
17365 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
17366 "--"
17367 ["Column View" org-columns t])
17368 ("Date/Schedule"
17369 ["Schedule" org-agenda-schedule t]
17370 ["Set Deadline" org-agenda-deadline t]
17371 "--"
17372 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
17373 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
17374 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
17375 ("Clock"
17376 ["Clock in" org-agenda-clock-in t]
17377 ["Clock out" org-agenda-clock-out t]
17378 ["Clock cancel" org-agenda-clock-cancel t]
17379 ["Goto running clock" org-clock-goto t])
17380 ("Priority"
17381 ["Set Priority" org-agenda-priority t]
17382 ["Increase Priority" org-agenda-priority-up t]
17383 ["Decrease Priority" org-agenda-priority-down t]
17384 ["Show Priority" org-agenda-show-priority t])
17385 ("Calendar/Diary"
17386 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
17387 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
17388 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
17389 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
17390 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
17391 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
17392 "--"
17393 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
17394 "--"
17395 ("View"
17396 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
17397 :style radio :selected (equal org-agenda-ndays 1)]
17398 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
17399 :style radio :selected (equal org-agenda-ndays 7)]
17400 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
17401 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
17402 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
17403 :style radio :selected (member org-agenda-ndays '(365 366))]
17404 "--"
17405 ["Show Logbook entries" org-agenda-log-mode
17406 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
17407 ["Include Diary" org-agenda-toggle-diary
17408 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
17409 ["Use Time Grid" org-agenda-toggle-time-grid
17410 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
17411 ["Write view to file" org-write-agenda t]
17412 ["Rebuild buffer" org-agenda-redo t]
17413 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
17414 "--"
17415 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
17416 "--"
17417 ["Quit" org-agenda-quit t]
17418 ["Exit and Release Buffers" org-agenda-exit t]
17421 ;;; Agenda undo
17423 (defvar org-agenda-allow-remote-undo t
17424 "Non-nil means, allow remote undo from the agenda buffer.")
17425 (defvar org-agenda-undo-list nil
17426 "List of undoable operations in the agenda since last refresh.")
17427 (defvar org-agenda-undo-has-started-in nil
17428 "Buffers that have already seen `undo-start' in the current undo sequence.")
17429 (defvar org-agenda-pending-undo-list nil
17430 "In a series of undo commands, this is the list of remaning undo items.")
17432 (defmacro org-if-unprotected (&rest body)
17433 "Execute BODY if there is no `org-protected' text property at point."
17434 (declare (debug t))
17435 `(unless (get-text-property (point) 'org-protected)
17436 ,@body))
17438 (defmacro org-with-remote-undo (_buffer &rest _body)
17439 "Execute BODY while recording undo information in two buffers."
17440 (declare (indent 1) (debug t))
17441 `(let ((_cline (org-current-line))
17442 (_cmd this-command)
17443 (_buf1 (current-buffer))
17444 (_buf2 ,_buffer)
17445 (_undo1 buffer-undo-list)
17446 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
17447 _c1 _c2)
17448 ,@_body
17449 (when org-agenda-allow-remote-undo
17450 (setq _c1 (org-verify-change-for-undo
17451 _undo1 (with-current-buffer _buf1 buffer-undo-list))
17452 _c2 (org-verify-change-for-undo
17453 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
17454 (when (or _c1 _c2)
17455 ;; make sure there are undo boundaries
17456 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
17457 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
17458 ;; remember which buffer to undo
17459 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
17460 org-agenda-undo-list)))))
17462 (defun org-agenda-undo ()
17463 "Undo a remote editing step in the agenda.
17464 This undoes changes both in the agenda buffer and in the remote buffer
17465 that have been changed along."
17466 (interactive)
17467 (or org-agenda-allow-remote-undo
17468 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
17469 (if (not (eq this-command last-command))
17470 (setq org-agenda-undo-has-started-in nil
17471 org-agenda-pending-undo-list org-agenda-undo-list))
17472 (if (not org-agenda-pending-undo-list)
17473 (error "No further undo information"))
17474 (let* ((entry (pop org-agenda-pending-undo-list))
17475 buf line cmd rembuf)
17476 (setq cmd (pop entry) line (pop entry))
17477 (setq rembuf (nth 2 entry))
17478 (org-with-remote-undo rembuf
17479 (while (bufferp (setq buf (pop entry)))
17480 (if (pop entry)
17481 (with-current-buffer buf
17482 (let ((last-undo-buffer buf)
17483 (inhibit-read-only t))
17484 (unless (memq buf org-agenda-undo-has-started-in)
17485 (push buf org-agenda-undo-has-started-in)
17486 (make-local-variable 'pending-undo-list)
17487 (undo-start))
17488 (while (and pending-undo-list
17489 (listp pending-undo-list)
17490 (not (car pending-undo-list)))
17491 (pop pending-undo-list))
17492 (undo-more 1))))))
17493 (goto-line line)
17494 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
17496 (defun org-verify-change-for-undo (l1 l2)
17497 "Verify that a real change occurred between the undo lists L1 and L2."
17498 (while (and l1 (listp l1) (null (car l1))) (pop l1))
17499 (while (and l2 (listp l2) (null (car l2))) (pop l2))
17500 (not (eq l1 l2)))
17502 ;;; Agenda dispatch
17504 (defvar org-agenda-restrict nil)
17505 (defvar org-agenda-restrict-begin (make-marker))
17506 (defvar org-agenda-restrict-end (make-marker))
17507 (defvar org-agenda-last-dispatch-buffer nil)
17509 ;;;###autoload
17510 (defun org-agenda (arg)
17511 "Dispatch agenda commands to collect entries to the agenda buffer.
17512 Prompts for a character to select a command. Any prefix arg will be passed
17513 on to the selected command. The default selections are:
17515 a Call `org-agenda-list' to display the agenda for current day or week.
17516 t Call `org-todo-list' to display the global todo list.
17517 T Call `org-todo-list' to display the global todo list, select only
17518 entries with a specific TODO keyword (the user gets a prompt).
17519 m Call `org-tags-view' to display headlines with tags matching
17520 a condition (the user is prompted for the condition).
17521 M Like `m', but select only TODO entries, no ordinary headlines.
17522 L Create a timeline for the current buffer.
17523 e Export views to associated files.
17525 More commands can be added by configuring the variable
17526 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
17527 searches can be pre-defined in this way.
17529 If the current buffer is in Org-mode and visiting a file, you can also
17530 first press `1' to indicate that the agenda should be temporarily (until the
17531 next use of \\[org-agenda]) restricted to the current file."
17532 (interactive "P")
17533 (catch 'exit
17534 (let* ((buf (current-buffer))
17535 (bfn (buffer-file-name (buffer-base-buffer)))
17536 (restrict-ok (and bfn (org-mode-p)))
17537 (custom org-agenda-custom-commands)
17538 c entry key type match lprops)
17539 ;; Turn off restriction
17540 (put 'org-agenda-files 'org-restrict nil)
17541 (setq org-agenda-restrict nil)
17542 (move-marker org-agenda-restrict-begin nil)
17543 (move-marker org-agenda-restrict-end nil)
17544 ;; Delete old local properties
17545 (put 'org-agenda-redo-command 'org-lprops nil)
17546 ;; Remember where this call originated
17547 (setq org-agenda-last-dispatch-buffer (current-buffer))
17548 (save-window-excursion
17549 (delete-other-windows)
17550 (org-switch-to-buffer-other-window " *Agenda Commands*")
17551 (erase-buffer)
17552 (insert (eval-when-compile
17553 (let ((header
17554 "Press key for an agenda command:
17555 -------------------------------- C Configure custom agenda commands
17556 a Agenda for current week or day e Export agenda views
17557 t List of all TODO entries T Entries with special TODO kwd
17558 m Match a TAGS query M Like m, but only TODO entries
17559 L Timeline for current buffer # List stuck projects (!=configure)
17560 / Multi-occur
17562 (start 0))
17563 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
17564 (setq start (match-end 0))
17565 (add-text-properties (match-beginning 2) (match-end 2)
17566 '(face bold) header))
17567 header)))
17568 (while (setq entry (pop custom))
17569 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
17570 (insert (format "\n%-4s%-14s: %s"
17571 (org-add-props (copy-sequence key)
17572 '(face bold))
17573 (cond
17574 ((stringp type) type)
17575 ((eq type 'agenda) "Agenda for current week or day")
17576 ((eq type 'alltodo) "List of all TODO entries")
17577 ((eq type 'stuck) "List of stuck projects")
17578 ((eq type 'todo) "TODO keyword")
17579 ((eq type 'tags) "Tags query")
17580 ((eq type 'tags-todo) "Tags (TODO)")
17581 ((eq type 'tags-tree) "Tags tree")
17582 ((eq type 'todo-tree) "TODO kwd tree")
17583 ((eq type 'occur-tree) "Occur tree")
17584 ((functionp type) (symbol-name type))
17585 (t "???"))
17586 (if (stringp match)
17587 (org-add-props match nil 'face 'org-warning)
17588 (format "set of %d commands" (length match))))))
17589 (if restrict-ok
17590 (insert "\n"
17591 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
17592 (goto-char (point-min))
17593 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
17594 (message "Press key for agenda command%s"
17595 (if restrict-ok ", or [1] or [0] to restrict" ""))
17596 (setq c (read-char-exclusive))
17597 (message "")
17598 (when (memq c '(?L ?1 ?0))
17599 (if restrict-ok
17600 (put 'org-agenda-files 'org-restrict (list bfn))
17601 (error "Cannot restrict agenda to current buffer"))
17602 (with-current-buffer " *Agenda Commands*"
17603 (goto-char (point-max))
17604 (delete-region (point-at-bol) (point))
17605 (goto-char (point-min)))
17606 (when (eq c ?0)
17607 (setq org-agenda-restrict t)
17608 (with-current-buffer buf
17609 (if (org-region-active-p)
17610 (progn
17611 (move-marker org-agenda-restrict-begin (region-beginning))
17612 (move-marker org-agenda-restrict-end (region-end)))
17613 (save-excursion
17614 (org-back-to-heading t)
17615 (move-marker org-agenda-restrict-begin (point))
17616 (move-marker org-agenda-restrict-end
17617 (progn (org-end-of-subtree t)))))))
17618 (unless (eq c ?L)
17619 (message "Press key for agenda command%s"
17620 (if restrict-ok " (restricted to current file)" ""))
17621 (setq c (read-char-exclusive)))
17622 (message "")))
17623 (require 'calendar) ; FIXME: can we avoid this for some commands?
17624 ;; For example the todo list should not need it (but does...)
17625 (cond
17626 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
17627 (if (symbolp (nth 1 entry))
17628 (progn
17629 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
17630 lprops (nth 3 entry))
17631 (put 'org-agenda-redo-command 'org-lprops lprops)
17632 (cond
17633 ((eq type 'agenda)
17634 (org-let lprops '(org-agenda-list current-prefix-arg)))
17635 ((eq type 'alltodo)
17636 (org-let lprops '(org-todo-list current-prefix-arg)))
17637 ((eq type 'stuck)
17638 (org-let lprops '(org-agenda-list-stuck-projects
17639 current-prefix-arg)))
17640 ((eq type 'tags)
17641 (org-let lprops '(org-tags-view current-prefix-arg match)))
17642 ((eq type 'tags-todo)
17643 (org-let lprops '(org-tags-view '(4) match)))
17644 ((eq type 'todo)
17645 (org-let lprops '(org-todo-list match)))
17646 ((eq type 'tags-tree)
17647 (org-check-for-org-mode)
17648 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
17649 ((eq type 'todo-tree)
17650 (org-check-for-org-mode)
17651 (org-let lprops
17652 '(org-occur (concat "^" outline-regexp "[ \t]*"
17653 (regexp-quote match) "\\>"))))
17654 ((eq type 'occur-tree)
17655 (org-check-for-org-mode)
17656 (org-let lprops '(org-occur match)))
17657 ((fboundp type)
17658 (org-let lprops '(funcall type match)))
17659 (t (error "Invalid custom agenda command type %s" type))))
17660 (org-run-agenda-series (nth 1 entry) (cddr entry))))
17661 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
17662 ((equal c ?a) (call-interactively 'org-agenda-list))
17663 ((equal c ?t) (call-interactively 'org-todo-list))
17664 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
17665 ((equal c ?m) (call-interactively 'org-tags-view))
17666 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
17667 ((equal c ?e) (call-interactively 'org-store-agenda-views))
17668 ((equal c ?L)
17669 (unless restrict-ok
17670 (error "This is not an Org-mode file"))
17671 (org-call-with-arg 'org-timeline arg))
17672 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
17673 ((equal c ?/) (call-interactively 'org-occur-in-agenda-files))
17674 ((equal c ?!) (customize-variable 'org-stuck-projects))
17675 (t (error "Invalid key"))))))
17677 (defun org-run-agenda-series (name series)
17678 (org-prepare-agenda name)
17679 (let* ((org-agenda-multi t)
17680 (redo (list 'org-run-agenda-series name (list 'quote series)))
17681 (cmds (car series))
17682 (gprops (nth 1 series))
17683 match ;; The byte compiler incorrectly complains about this. Keep it!
17684 cmd type lprops)
17685 (while (setq cmd (pop cmds))
17686 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
17687 (cond
17688 ((eq type 'agenda)
17689 (org-let2 gprops lprops
17690 '(call-interactively 'org-agenda-list)))
17691 ((eq type 'alltodo)
17692 (org-let2 gprops lprops
17693 '(call-interactively 'org-todo-list)))
17694 ((eq type 'stuck)
17695 (org-let2 gprops lprops
17696 '(call-interactively 'org-agenda-list-stuck-projects)))
17697 ((eq type 'tags)
17698 (org-let2 gprops lprops
17699 '(org-tags-view current-prefix-arg match)))
17700 ((eq type 'tags-todo)
17701 (org-let2 gprops lprops
17702 '(org-tags-view '(4) match)))
17703 ((eq type 'todo)
17704 (org-let2 gprops lprops
17705 '(org-todo-list match)))
17706 ((fboundp type)
17707 (org-let2 gprops lprops
17708 '(funcall type match)))
17709 (t (error "Invalid type in command series"))))
17710 (widen)
17711 (setq org-agenda-redo-command redo)
17712 (goto-char (point-min)))
17713 (org-finalize-agenda))
17715 ;;;###autoload
17716 (defmacro org-batch-agenda (cmd-key &rest parameters)
17717 "Run an agenda command in batch mode and send the result to STDOUT.
17718 If CMD-KEY is a string of length 1, it is used as a key in
17719 `org-agenda-custom-commands' and triggers this command. If it is a
17720 longer string is is used as a tags/todo match string.
17721 Paramters are alternating variable names and values that will be bound
17722 before running the agenda command."
17723 (let (pars)
17724 (while parameters
17725 (push (list (pop parameters) (if parameters (pop parameters))) pars))
17726 (if (> (length cmd-key) 1)
17727 (eval (list 'let (nreverse pars)
17728 (list 'org-tags-view nil cmd-key)))
17729 (flet ((read-char-exclusive () (string-to-char cmd-key)))
17730 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
17731 (set-buffer org-agenda-buffer-name)
17732 (princ (org-encode-for-stdout (buffer-string)))))
17734 (defun org-encode-for-stdout (string)
17735 (if (fboundp 'encode-coding-string)
17736 (encode-coding-string string buffer-file-coding-system)
17737 string))
17739 (defvar org-agenda-info nil)
17741 ;;;###autoload
17742 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
17743 "Run an agenda command in batch mode and send the result to STDOUT.
17744 If CMD-KEY is a string of length 1, it is used as a key in
17745 `org-agenda-custom-commands' and triggers this command. If it is a
17746 longer string is is used as a tags/todo match string.
17747 Paramters are alternating variable names and values that will be bound
17748 before running the agenda command.
17750 The output gives a line for each selected agenda item. Each
17751 item is a list of comma-separated values, like this:
17753 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
17755 category The category of the item
17756 head The headline, without TODO kwd, TAGS and PRIORITY
17757 type The type of the agenda entry, can be
17758 todo selected in TODO match
17759 tagsmatch selected in tags match
17760 diary imported from diary
17761 deadline a deadline on given date
17762 scheduled scheduled on given date
17763 timestamp entry has timestamp on given date
17764 closed entry was closed on given date
17765 upcoming-deadline warning about deadline
17766 past-scheduled forwarded scheduled item
17767 block entry has date block including g. date
17768 todo The todo keyword, if any
17769 tags All tags including inherited ones, separated by colons
17770 date The relevant date, like 2007-2-14
17771 time The time, like 15:00-16:50
17772 extra Sting with extra planning info
17773 priority-l The priority letter if any was given
17774 priority-n The computed numerical priority
17775 agenda-day The day in the agenda where this is listed"
17777 (let (pars)
17778 (while parameters
17779 (push (list (pop parameters) (if parameters (pop parameters))) pars))
17780 (push (list 'org-agenda-remove-tags t) pars)
17781 (if (> (length cmd-key) 1)
17782 (eval (list 'let (nreverse pars)
17783 (list 'org-tags-view nil cmd-key)))
17784 (flet ((read-char-exclusive () (string-to-char cmd-key)))
17785 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
17786 (set-buffer org-agenda-buffer-name)
17787 (let* ((lines (org-split-string (buffer-string) "\n"))
17788 line)
17789 (while (setq line (pop lines))
17790 (catch 'next
17791 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
17792 (setq org-agenda-info
17793 (org-fix-agenda-info (text-properties-at 0 line)))
17794 (princ
17795 (org-encode-for-stdout
17796 (mapconcat 'org-agenda-export-csv-mapper
17797 '(org-category txt type todo tags date time-of-day extra
17798 priority-letter priority agenda-day)
17799 ",")))
17800 (princ "\n"))))))
17802 (defun org-fix-agenda-info (props)
17803 "Make sure all properties on an agenda item have a canonical form,
17804 so the the export commands caneasily use it."
17805 (let (tmp re)
17806 (when (setq tmp (plist-get props 'tags))
17807 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
17808 (when (setq tmp (plist-get props 'date))
17809 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
17810 (let ((calendar-date-display-form '(year "-" month "-" day)))
17811 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
17813 (setq tmp (calendar-date-string tmp)))
17814 (setq props (plist-put props 'date tmp)))
17815 (when (setq tmp (plist-get props 'day))
17816 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
17817 (let ((calendar-date-display-form '(year "-" month "-" day)))
17818 (setq tmp (calendar-date-string tmp)))
17819 (setq props (plist-put props 'day tmp))
17820 (setq props (plist-put props 'agenda-day tmp)))
17821 (when (setq tmp (plist-get props 'txt))
17822 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
17823 (plist-put props 'priority-letter (match-string 1 tmp))
17824 (setq tmp (replace-match "" t t tmp)))
17825 (when (and (setq re (plist-get props 'org-todo-regexp))
17826 (setq re (concat "\\`\\.*" re " ?"))
17827 (string-match re tmp))
17828 (plist-put props 'todo (match-string 1 tmp))
17829 (setq tmp (replace-match "" t t tmp)))
17830 (plist-put props 'txt tmp)))
17831 props)
17833 (defun org-agenda-export-csv-mapper (prop)
17834 (let ((res (plist-get org-agenda-info prop)))
17835 (setq res
17836 (cond
17837 ((not res) "")
17838 ((stringp res) res)
17839 (t (prin1-to-string res))))
17840 (while (string-match "," res)
17841 (setq res (replace-match ";" t t res)))
17842 (org-trim res)))
17845 ;;;###autoload
17846 (defun org-store-agenda-views (&rest parameters)
17847 (interactive)
17848 (eval (list 'org-batch-store-agenda-views)))
17850 ;; FIXME, why is this a macro?????
17851 ;;;###autoload
17852 (defmacro org-batch-store-agenda-views (&rest parameters)
17853 "Run all custom agenda commands that have a file argument."
17854 (let ((cmds org-agenda-custom-commands)
17855 (pop-up-frames nil)
17856 (dir default-directory)
17857 pars cmd thiscmdkey files opts)
17858 (while parameters
17859 (push (list (pop parameters) (if parameters (pop parameters))) pars))
17860 (setq pars (reverse pars))
17861 (save-window-excursion
17862 (while cmds
17863 (setq cmd (pop cmds)
17864 thiscmdkey (car cmd)
17865 opts (nth 3 cmd)
17866 files (nth 4 cmd))
17867 (if (stringp files) (setq files (list files)))
17868 (when files
17869 (flet ((read-char-exclusive () (string-to-char thiscmdkey)))
17870 (eval (list 'let (append org-agenda-exporter-settings opts pars)
17871 '(org-agenda nil))))
17872 (set-buffer org-agenda-buffer-name)
17873 (while files
17874 (eval (list 'let (append org-agenda-exporter-settings opts pars)
17875 (list 'org-write-agenda
17876 (expand-file-name (pop files) dir) t))))
17877 (and (get-buffer org-agenda-buffer-name)
17878 (kill-buffer org-agenda-buffer-name)))))))
17880 (defun org-write-agenda (file &optional nosettings)
17881 "Write the current buffer (an agenda view) as a file.
17882 Depending on the extension of the file name, plain text (.txt),
17883 HTML (.html or .htm) or Postscript (.ps) is produced.
17884 If NOSETTINGS is given, do not scope the settings of
17885 `org-agenda-exporter-settings' into the export commands. This is used when
17886 the settings have already been scoped and we do not wish to overrule other,
17887 higher priority settings."
17888 (interactive "FWrite agenda to file: ")
17889 (if (not (file-writable-p file))
17890 (error "Cannot write agenda to file %s" file))
17891 (cond
17892 ((string-match "\\.html?\\'" file) (require 'htmlize))
17893 ((string-match "\\.ps\\'" file) (require 'ps-print)))
17894 (org-let (if nosettings nil org-agenda-exporter-settings)
17895 '(save-excursion
17896 (save-window-excursion
17897 (cond
17898 ((string-match "\\.html?\\'" file)
17899 (set-buffer (htmlize-buffer (current-buffer)))
17901 (when (and org-agenda-export-html-style
17902 (string-match "<style>" org-agenda-export-html-style))
17903 ;; replace <style> section with org-agenda-export-html-style
17904 (goto-char (point-min))
17905 (kill-region (- (search-forward "<style") 6)
17906 (search-forward "</style>"))
17907 (insert org-agenda-export-html-style))
17908 (write-file file)
17909 (kill-buffer (current-buffer))
17910 (message "HTML written to %s" file))
17911 ((string-match "\\.ps\\'" file)
17912 (ps-print-buffer-with-faces file)
17913 (message "Postscript written to %s" file))
17915 (let ((bs (buffer-string)))
17916 (find-file file)
17917 (insert bs)
17918 (save-buffer 0)
17919 (kill-buffer (current-buffer))
17920 (message "Plain text written to %s" file))))))
17921 (set-buffer org-agenda-buffer-name)))
17923 (defmacro org-no-read-only (&rest body)
17924 "Inhibit read-only for BODY."
17925 `(let ((inhibit-read-only t)) ,@body))
17927 (defun org-check-for-org-mode ()
17928 "Make sure current buffer is in org-mode. Error if not."
17929 (or (org-mode-p)
17930 (error "Cannot execute org-mode agenda command on buffer in %s."
17931 major-mode)))
17933 (defun org-fit-agenda-window ()
17934 "Fit the window to the buffer size."
17935 (and (memq org-agenda-window-setup '(reorganize-frame))
17936 (fboundp 'fit-window-to-buffer)
17937 (fit-window-to-buffer)))
17939 ;;; Agenda file list
17941 (defun org-agenda-files (&optional unrestricted)
17942 "Get the list of agenda files.
17943 Optional UNRESTRICTED means return the full list even if a restriction
17944 is currently in place."
17945 (let ((files
17946 (cond
17947 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17948 ((stringp org-agenda-files) (org-read-agenda-file-list))
17949 ((listp org-agenda-files) org-agenda-files)
17950 (t (error "Invalid value of `org-agenda-files'")))))
17951 (if org-agenda-skip-unavailable-files
17952 (delq nil
17953 (mapcar (function
17954 (lambda (file)
17955 (and (file-readable-p file) file)))
17956 files))
17957 files))) ; `org-check-agenda-file' will remove them from the list
17959 (defun org-edit-agenda-file-list ()
17960 "Edit the list of agenda files.
17961 Depending on setup, this either uses customize to edit the variable
17962 `org-agenda-files', or it visits the file that is holding the list. In the
17963 latter case, the buffer is set up in a way that saving it automatically kills
17964 the buffer and restores the previous window configuration."
17965 (interactive)
17966 (if (stringp org-agenda-files)
17967 (let ((cw (current-window-configuration)))
17968 (find-file org-agenda-files)
17969 (org-set-local 'org-window-configuration cw)
17970 (org-add-hook 'after-save-hook
17971 (lambda ()
17972 (set-window-configuration
17973 (prog1 org-window-configuration
17974 (kill-buffer (current-buffer))))
17975 (org-install-agenda-files-menu)
17976 (message "New agenda file list installed"))
17977 nil 'local)
17978 (message (substitute-command-keys
17979 "Edit list and finish with \\[save-buffer]")))
17980 (customize-variable 'org-agenda-files)))
17982 (defun org-store-new-agenda-file-list (list)
17983 "Set new value for the agenda file list and save it correcly."
17984 (if (stringp org-agenda-files)
17985 (let ((f org-agenda-files) b)
17986 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
17987 (with-temp-file f
17988 (insert (mapconcat 'identity list "\n") "\n")))
17989 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
17990 (setq org-agenda-files list)
17991 (customize-save-variable 'org-agenda-files org-agenda-files))))
17993 (defun org-read-agenda-file-list ()
17994 "Read the list of agenda files from a file."
17995 (when (stringp org-agenda-files)
17996 (with-temp-buffer
17997 (insert-file-contents org-agenda-files)
17998 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
18001 ;;;###autoload
18002 (defun org-cycle-agenda-files ()
18003 "Cycle through the files in `org-agenda-files'.
18004 If the current buffer visits an agenda file, find the next one in the list.
18005 If the current buffer does not, find the first agenda file."
18006 (interactive)
18007 (let* ((fs (org-agenda-files t))
18008 (files (append fs (list (car fs))))
18009 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18010 file)
18011 (unless files (error "No agenda files"))
18012 (catch 'exit
18013 (while (setq file (pop files))
18014 (if (equal (file-truename file) tcf)
18015 (when (car files)
18016 (find-file (car files))
18017 (throw 'exit t))))
18018 (find-file (car fs)))
18019 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
18021 (defun org-agenda-file-to-front (&optional to-end)
18022 "Move/add the current file to the top of the agenda file list.
18023 If the file is not present in the list, it is added to the front. If it is
18024 present, it is moved there. With optional argument TO-END, add/move to the
18025 end of the list."
18026 (interactive "P")
18027 (let ((org-agenda-skip-unavailable-files nil)
18028 (file-alist (mapcar (lambda (x)
18029 (cons (file-truename x) x))
18030 (org-agenda-files t)))
18031 (ctf (file-truename buffer-file-name))
18032 x had)
18033 (setq x (assoc ctf file-alist) had x)
18035 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18036 (if to-end
18037 (setq file-alist (append (delq x file-alist) (list x)))
18038 (setq file-alist (cons x (delq x file-alist))))
18039 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18040 (org-install-agenda-files-menu)
18041 (message "File %s to %s of agenda file list"
18042 (if had "moved" "added") (if to-end "end" "front"))))
18044 (defun org-remove-file (&optional file)
18045 "Remove current file from the list of files in variable `org-agenda-files'.
18046 These are the files which are being checked for agenda entries.
18047 Optional argument FILE means, use this file instead of the current."
18048 (interactive)
18049 (let* ((org-agenda-skip-unavailable-files nil)
18050 (file (or file buffer-file-name))
18051 (true-file (file-truename file))
18052 (afile (abbreviate-file-name file))
18053 (files (delq nil (mapcar
18054 (lambda (x)
18055 (if (equal true-file
18056 (file-truename x))
18057 nil x))
18058 (org-agenda-files t)))))
18059 (if (not (= (length files) (length (org-agenda-files t))))
18060 (progn
18061 (org-store-new-agenda-file-list files)
18062 (org-install-agenda-files-menu)
18063 (message "Removed file: %s" afile))
18064 (message "File was not in list: %s" afile))))
18066 (defun org-file-menu-entry (file)
18067 (vector file (list 'find-file file) t))
18069 (defun org-check-agenda-file (file)
18070 "Make sure FILE exists. If not, ask user what to do."
18071 (when (not (file-exists-p file))
18072 (message "non-existent file %s. [R]emove from list or [A]bort?"
18073 (abbreviate-file-name file))
18074 (let ((r (downcase (read-char-exclusive))))
18075 (cond
18076 ((equal r ?r)
18077 (org-remove-file file)
18078 (throw 'nextfile t))
18079 (t (error "Abort"))))))
18081 ;;; Agenda prepare and finalize
18083 (defvar org-agenda-multi nil) ; dynammically scoped
18084 (defvar org-agenda-buffer-name "*Org Agenda*")
18085 (defvar org-pre-agenda-window-conf nil)
18086 (defvar org-agenda-name nil)
18087 (defun org-prepare-agenda (&optional name)
18088 (setq org-todo-keywords-for-agenda nil)
18089 (setq org-done-keywords-for-agenda nil)
18090 (if org-agenda-multi
18091 (progn
18092 (setq buffer-read-only nil)
18093 (goto-char (point-max))
18094 (unless (or (bobp) org-agenda-compact-blocks)
18095 (insert "\n" (make-string (window-width) ?=) "\n"))
18096 (narrow-to-region (point) (point-max)))
18097 (org-agenda-maybe-reset-markers 'force)
18098 (org-prepare-agenda-buffers (org-agenda-files))
18099 (setq org-todo-keywords-for-agenda
18100 (org-uniquify org-todo-keywords-for-agenda))
18101 (setq org-done-keywords-for-agenda
18102 (org-uniquify org-done-keywords-for-agenda))
18103 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
18104 (awin (get-buffer-window abuf)))
18105 (cond
18106 ((equal (current-buffer) abuf) nil)
18107 (awin (select-window awin))
18108 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
18109 ((equal org-agenda-window-setup 'current-window)
18110 (switch-to-buffer abuf))
18111 ((equal org-agenda-window-setup 'other-window)
18112 (org-switch-to-buffer-other-window abuf))
18113 ((equal org-agenda-window-setup 'other-frame)
18114 (switch-to-buffer-other-frame abuf))
18115 ((equal org-agenda-window-setup 'reorganize-frame)
18116 (delete-other-windows)
18117 (org-switch-to-buffer-other-window abuf))))
18118 (setq buffer-read-only nil)
18119 (erase-buffer)
18120 (org-agenda-mode)
18121 (and name (not org-agenda-name)
18122 (org-set-local 'org-agenda-name name)))
18123 (setq buffer-read-only nil))
18125 (defun org-finalize-agenda ()
18126 "Finishing touch for the agenda buffer, called just before displaying it."
18127 (unless org-agenda-multi
18128 (save-excursion
18129 (let ((inhibit-read-only t))
18130 (goto-char (point-min))
18131 (while (org-activate-bracket-links (point-max))
18132 (add-text-properties (match-beginning 0) (match-end 0)
18133 '(face org-link)))
18134 (org-agenda-align-tags)
18135 (unless org-agenda-with-colors
18136 (remove-text-properties (point-min) (point-max) '(face nil))))
18137 (if (and (boundp 'org-overriding-columns-format)
18138 org-overriding-columns-format)
18139 (org-set-local 'org-overriding-columns-format
18140 org-overriding-columns-format))
18141 (if (and (boundp 'org-agenda-view-columns-initially)
18142 org-agenda-view-columns-initially)
18143 (org-agenda-columns))
18144 (when org-agenda-fontify-priorities
18145 (org-fontify-priorities))
18146 (run-hooks 'org-finalize-agenda-hook))))
18148 (defun org-fontify-priorities ()
18149 "Make highest priority lines bold, and lowest italic."
18150 (interactive)
18151 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
18152 (org-delete-overlay o)))
18153 (overlays-in (point-min) (point-max)))
18154 (save-excursion
18155 (let ((ovs (org-overlays-in (point-min) (point-max)))
18156 (inhibit-read-only t)
18157 b e p ov h l)
18158 (goto-char (point-min))
18159 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
18160 (setq h (or (get-char-property (point) 'org-highest-priority)
18161 org-highest-priority)
18162 l (or (get-char-property (point) 'org-lowest-priority)
18163 org-lowest-priority)
18164 p (string-to-char (match-string 1))
18165 b (match-beginning 0) e (line-end-position)
18166 ov (org-make-overlay b e))
18167 (org-overlay-put ov 'face (cond ((equal p l) 'italic)
18168 ((equal p h) 'bold)))
18169 (org-overlay-put ov 'org-type 'org-priority)))))
18171 (defun org-prepare-agenda-buffers (files)
18172 "Create buffers for all agenda files, protect archived trees and comments."
18173 (interactive)
18174 (let ((pa '(:org-archived t))
18175 (pc '(:org-comment t))
18176 (pall '(:org-archived t :org-comment t))
18177 (inhibit-read-only t)
18178 (rea (concat ":" org-archive-tag ":"))
18179 bmp file re)
18180 (save-excursion
18181 (save-restriction
18182 (while (setq file (pop files))
18183 (org-check-agenda-file file)
18184 (set-buffer (org-get-agenda-file-buffer file))
18185 (widen)
18186 (setq bmp (buffer-modified-p))
18187 (org-refresh-category-properties)
18188 (setq org-todo-keywords-for-agenda
18189 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18190 (setq org-done-keywords-for-agenda
18191 (append org-done-keywords-for-agenda org-done-keywords))
18192 (save-excursion
18193 (remove-text-properties (point-min) (point-max) pall)
18194 (when org-agenda-skip-archived-trees
18195 (goto-char (point-min))
18196 (while (re-search-forward rea nil t)
18197 (if (org-on-heading-p t)
18198 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18199 (goto-char (point-min))
18200 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
18201 (while (re-search-forward re nil t)
18202 (add-text-properties
18203 (match-beginning 0) (org-end-of-subtree t) pc)))
18204 (set-buffer-modified-p bmp))))))
18206 (defvar org-agenda-skip-function nil
18207 "Function to be called at each match during agenda construction.
18208 If this function returns nil, the current match should not be skipped.
18209 Otherwise, the function must return a position from where the search
18210 should be continued.
18211 This may also be a Lisp form, it will be evaluated.
18212 Never set this variable using `setq' or so, because then it will apply
18213 to all future agenda commands. Instead, bind it with `let' to scope
18214 it dynamically into the agenda-constructing command. A good way to set
18215 it is through options in org-agenda-custom-commands.")
18217 (defun org-agenda-skip ()
18218 "Throw to `:skip' in places that should be skipped.
18219 Also moves point to the end of the skipped region, so that search can
18220 continue from there."
18221 (let ((p (point-at-bol)) to fp)
18222 (and org-agenda-skip-archived-trees
18223 (get-text-property p :org-archived)
18224 (org-end-of-subtree t)
18225 (throw :skip t))
18226 (and (get-text-property p :org-comment)
18227 (org-end-of-subtree t)
18228 (throw :skip t))
18229 (if (equal (char-after p) ?#) (throw :skip t))
18230 (when (and (or (setq fp (functionp org-agenda-skip-function))
18231 (consp org-agenda-skip-function))
18232 (setq to (save-excursion
18233 (save-match-data
18234 (if fp
18235 (funcall org-agenda-skip-function)
18236 (eval org-agenda-skip-function))))))
18237 (goto-char to)
18238 (throw :skip t))))
18240 (defvar org-agenda-markers nil
18241 "List of all currently active markers created by `org-agenda'.")
18242 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
18243 "Creation time of the last agenda marker.")
18245 (defun org-agenda-new-marker (&optional pos)
18246 "Return a new agenda marker.
18247 Org-mode keeps a list of these markers and resets them when they are
18248 no longer in use."
18249 (let ((m (copy-marker (or pos (point)))))
18250 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
18251 (push m org-agenda-markers)
18254 (defun org-agenda-maybe-reset-markers (&optional force)
18255 "Reset markers created by `org-agenda'. But only if they are old enough."
18256 (if (or (and force (not org-agenda-multi))
18257 (> (- (time-to-seconds (current-time))
18258 org-agenda-last-marker-time)
18260 (while org-agenda-markers
18261 (move-marker (pop org-agenda-markers) nil))))
18263 (defvar org-agenda-new-buffers nil
18264 "Buffers created to visit agenda files.")
18266 (defun org-get-agenda-file-buffer (file)
18267 "Get a buffer visiting FILE. If the buffer needs to be created, add
18268 it to the list of buffers which might be released later."
18269 (let ((buf (org-find-base-buffer-visiting file)))
18270 (if buf
18271 buf ; just return it
18272 ;; Make a new buffer and remember it
18273 (setq buf (find-file-noselect file))
18274 (if buf (push buf org-agenda-new-buffers))
18275 buf)))
18277 (defun org-release-buffers (blist)
18278 "Release all buffers in list, asking the user for confirmation when needed.
18279 When a buffer is unmodified, it is just killed. When modified, it is saved
18280 \(if the user agrees) and then killed."
18281 (let (buf file)
18282 (while (setq buf (pop blist))
18283 (setq file (buffer-file-name buf))
18284 (when (and (buffer-modified-p buf)
18285 file
18286 (y-or-n-p (format "Save file %s? " file)))
18287 (with-current-buffer buf (save-buffer)))
18288 (kill-buffer buf))))
18290 (defun org-get-category (&optional pos)
18291 "Get the category applying to position POS."
18292 (get-text-property (or pos (point)) 'org-category))
18294 ;;; Agenda timeline
18296 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
18298 (defun org-timeline (&optional include-all)
18299 "Show a time-sorted view of the entries in the current org file.
18300 Only entries with a time stamp of today or later will be listed. With
18301 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
18302 under the current date.
18303 If the buffer contains an active region, only check the region for
18304 dates."
18305 (interactive "P")
18306 (require 'calendar)
18307 (org-compile-prefix-format 'timeline)
18308 (org-set-sorting-strategy 'timeline)
18309 (let* ((dopast t)
18310 (dotodo include-all)
18311 (doclosed org-agenda-show-log)
18312 (entry buffer-file-name)
18313 (date (calendar-current-date))
18314 (beg (if (org-region-active-p) (region-beginning) (point-min)))
18315 (end (if (org-region-active-p) (region-end) (point-max)))
18316 (day-numbers (org-get-all-dates beg end 'no-ranges
18317 t doclosed ; always include today
18318 org-timeline-show-empty-dates))
18319 (org-deadline-warning-days 0)
18320 (org-agenda-only-exact-dates t)
18321 (today (time-to-days (current-time)))
18322 (past t)
18323 args
18324 s e rtn d emptyp)
18325 (setq org-agenda-redo-command
18326 (list 'progn
18327 (list 'org-switch-to-buffer-other-window (current-buffer))
18328 (list 'org-timeline (list 'quote include-all))))
18329 (if (not dopast)
18330 ;; Remove past dates from the list of dates.
18331 (setq day-numbers (delq nil (mapcar (lambda(x)
18332 (if (>= x today) x nil))
18333 day-numbers))))
18334 (org-prepare-agenda (concat "Timeline "
18335 (file-name-nondirectory buffer-file-name)))
18336 (if doclosed (push :closed args))
18337 (push :timestamp args)
18338 (push :deadline args)
18339 (push :scheduled args)
18340 (push :sexp args)
18341 (if dotodo (push :todo args))
18342 (while (setq d (pop day-numbers))
18343 (if (and (listp d) (eq (car d) :omitted))
18344 (progn
18345 (setq s (point))
18346 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
18347 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
18348 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
18349 (if (and (>= d today)
18350 dopast
18351 past)
18352 (progn
18353 (setq past nil)
18354 (insert (make-string 79 ?-) "\n")))
18355 (setq date (calendar-gregorian-from-absolute d))
18356 (setq s (point))
18357 (setq rtn (and (not emptyp)
18358 (apply 'org-agenda-get-day-entries entry
18359 date args)))
18360 (if (or rtn (equal d today) org-timeline-show-empty-dates)
18361 (progn
18362 (insert
18363 (if (stringp org-agenda-format-date)
18364 (format-time-string org-agenda-format-date
18365 (org-time-from-absolute date))
18366 (funcall org-agenda-format-date date))
18367 "\n")
18368 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
18369 (put-text-property s (1- (point)) 'org-date-line t)
18370 (if (equal d today)
18371 (put-text-property s (1- (point)) 'org-today t))
18372 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
18373 (put-text-property s (1- (point)) 'day d)))))
18374 (goto-char (point-min))
18375 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
18376 (point-min)))
18377 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
18378 (org-finalize-agenda)
18379 (setq buffer-read-only t)))
18381 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
18382 "Return a list of all relevant day numbers from BEG to END buffer positions.
18383 If NO-RANGES is non-nil, include only the start and end dates of a range,
18384 not every single day in the range. If FORCE-TODAY is non-nil, make
18385 sure that TODAY is included in the list. If INACTIVE is non-nil, also
18386 inactive time stamps (those in square brackets) are included.
18387 When EMPTY is non-nil, also include days without any entries."
18388 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
18389 dates dates1 date day day1 day2 ts1 ts2)
18390 (if force-today
18391 (setq dates (list (time-to-days (current-time)))))
18392 (save-excursion
18393 (goto-char beg)
18394 (while (re-search-forward re end t)
18395 (setq day (time-to-days (org-time-string-to-time
18396 (substring (match-string 1) 0 10))))
18397 (or (memq day dates) (push day dates)))
18398 (unless no-ranges
18399 (goto-char beg)
18400 (while (re-search-forward org-tr-regexp end t)
18401 (setq ts1 (substring (match-string 1) 0 10)
18402 ts2 (substring (match-string 2) 0 10)
18403 day1 (time-to-days (org-time-string-to-time ts1))
18404 day2 (time-to-days (org-time-string-to-time ts2)))
18405 (while (< (setq day1 (1+ day1)) day2)
18406 (or (memq day1 dates) (push day1 dates)))))
18407 (setq dates (sort dates '<))
18408 (when empty
18409 (while (setq day (pop dates))
18410 (setq day2 (car dates))
18411 (push day dates1)
18412 (when (and day2 empty)
18413 (if (or (eq empty t)
18414 (and (numberp empty) (<= (- day2 day) empty)))
18415 (while (< (setq day (1+ day)) day2)
18416 (push (list day) dates1))
18417 (push (cons :omitted (- day2 day)) dates1))))
18418 (setq dates (nreverse dates1)))
18419 dates)))
18421 ;;; Agenda Daily/Weekly
18423 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
18424 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
18425 (defvar org-agenda-last-arguments nil
18426 "The arguments of the previous call to org-agenda")
18427 (defvar org-starting-day nil) ; local variable in the agenda buffer
18428 (defvar org-agenda-span nil) ; local variable in the agenda buffer
18429 (defvar org-include-all-loc nil) ; local variable
18430 (defvar org-agenda-remove-date nil) ; dynamically scoped
18432 ;;;###autoload
18433 (defun org-agenda-list (&optional include-all start-day ndays)
18434 "Produce a weekly view from all files in variable `org-agenda-files'.
18435 The view will be for the current week, but from the overview buffer you
18436 will be able to go to other weeks.
18437 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
18438 also be shown, under the current date.
18439 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
18440 on the days are also shown. See the variable `org-log-done' for how
18441 to turn on logging.
18442 START-DAY defaults to TODAY, or to the most recent match for the weekday
18443 given in `org-agenda-start-on-weekday'.
18444 NDAYS defaults to `org-agenda-ndays'."
18445 (interactive "P")
18446 (setq ndays (or ndays org-agenda-ndays)
18447 start-day (or start-day org-agenda-start-day))
18448 (if org-agenda-overriding-arguments
18449 (setq include-all (car org-agenda-overriding-arguments)
18450 start-day (nth 1 org-agenda-overriding-arguments)
18451 ndays (nth 2 org-agenda-overriding-arguments)))
18452 (if (stringp start-day)
18453 ;; Convert to an absolute day number
18454 (setq start-day (time-to-days (org-read-date nil t start-day))))
18455 (setq org-agenda-last-arguments (list include-all start-day ndays))
18456 (org-compile-prefix-format 'agenda)
18457 (org-set-sorting-strategy 'agenda)
18458 (require 'calendar)
18459 (let* ((org-agenda-start-on-weekday
18460 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
18461 org-agenda-start-on-weekday nil))
18462 (thefiles (org-agenda-files))
18463 (files thefiles)
18464 (today (time-to-days (current-time)))
18465 (sd (or start-day today))
18466 (start (if (or (null org-agenda-start-on-weekday)
18467 (< org-agenda-ndays 7))
18469 (let* ((nt (calendar-day-of-week
18470 (calendar-gregorian-from-absolute sd)))
18471 (n1 org-agenda-start-on-weekday)
18472 (d (- nt n1)))
18473 (- sd (+ (if (< d 0) 7 0) d)))))
18474 (day-numbers (list start))
18475 (day-cnt 0)
18476 (inhibit-redisplay (not debug-on-error))
18477 s e rtn rtnall file date d start-pos end-pos todayp nd)
18478 (setq org-agenda-redo-command
18479 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
18480 ;; Make the list of days
18481 (setq ndays (or ndays org-agenda-ndays)
18482 nd ndays)
18483 (while (> ndays 1)
18484 (push (1+ (car day-numbers)) day-numbers)
18485 (setq ndays (1- ndays)))
18486 (setq day-numbers (nreverse day-numbers))
18487 (org-prepare-agenda "Day/Week")
18488 (org-set-local 'org-starting-day (car day-numbers))
18489 (org-set-local 'org-include-all-loc include-all)
18490 (org-set-local 'org-agenda-span
18491 (org-agenda-ndays-to-span nd))
18492 (when (and (or include-all org-agenda-include-all-todo)
18493 (member today day-numbers))
18494 (setq files thefiles
18495 rtnall nil)
18496 (while (setq file (pop files))
18497 (catch 'nextfile
18498 (org-check-agenda-file file)
18499 (setq date (calendar-gregorian-from-absolute today)
18500 rtn (org-agenda-get-day-entries
18501 file date :todo))
18502 (setq rtnall (append rtnall rtn))))
18503 (when rtnall
18504 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
18505 (add-text-properties (point-min) (1- (point))
18506 (list 'face 'org-agenda-structure))
18507 (insert (org-finalize-agenda-entries rtnall) "\n")))
18508 (unless org-agenda-compact-blocks
18509 (setq s (point))
18510 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
18511 "-agenda:\n")
18512 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
18513 'org-date-line t)))
18514 (while (setq d (pop day-numbers))
18515 (setq date (calendar-gregorian-from-absolute d)
18516 s (point))
18517 (if (or (setq todayp (= d today))
18518 (and (not start-pos) (= d sd)))
18519 (setq start-pos (point))
18520 (if (and start-pos (not end-pos))
18521 (setq end-pos (point))))
18522 (setq files thefiles
18523 rtnall nil)
18524 (while (setq file (pop files))
18525 (catch 'nextfile
18526 (org-check-agenda-file file)
18527 (if org-agenda-show-log
18528 (setq rtn (org-agenda-get-day-entries
18529 file date
18530 :deadline :scheduled :timestamp :sexp :closed))
18531 (setq rtn (org-agenda-get-day-entries
18532 file date
18533 :deadline :scheduled :sexp :timestamp)))
18534 (setq rtnall (append rtnall rtn))))
18535 (if org-agenda-include-diary
18536 (progn
18537 (require 'diary-lib)
18538 (setq rtn (org-get-entries-from-diary date))
18539 (setq rtnall (append rtnall rtn))))
18540 (if (or rtnall org-agenda-show-all-dates)
18541 (progn
18542 (setq day-cnt (1+ day-cnt))
18543 (insert
18544 (if (stringp org-agenda-format-date)
18545 (format-time-string org-agenda-format-date
18546 (org-time-from-absolute date))
18547 (funcall org-agenda-format-date date))
18548 "\n")
18549 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
18550 (put-text-property s (1- (point)) 'org-date-line t)
18551 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
18552 (if todayp (put-text-property s (1- (point)) 'org-today t))
18553 (if rtnall (insert
18554 (org-finalize-agenda-entries
18555 (org-agenda-add-time-grid-maybe
18556 rtnall nd todayp))
18557 "\n"))
18558 (put-text-property s (1- (point)) 'day d)
18559 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
18560 (goto-char (point-min))
18561 (org-fit-agenda-window)
18562 (unless (and (pos-visible-in-window-p (point-min))
18563 (pos-visible-in-window-p (point-max)))
18564 (goto-char (1- (point-max)))
18565 (recenter -1)
18566 (if (not (pos-visible-in-window-p (or start-pos 1)))
18567 (progn
18568 (goto-char (or start-pos 1))
18569 (recenter 1))))
18570 (goto-char (or start-pos 1))
18571 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
18572 (org-finalize-agenda)
18573 (setq buffer-read-only t)
18574 (message "")))
18576 (defun org-agenda-ndays-to-span (n)
18577 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
18579 ;;; Agenda TODO list
18581 (defvar org-select-this-todo-keyword nil)
18582 (defvar org-last-arg nil)
18584 ;;;###autoload
18585 (defun org-todo-list (arg)
18586 "Show all TODO entries from all agenda file in a single list.
18587 The prefix arg can be used to select a specific TODO keyword and limit
18588 the list to these. When using \\[universal-argument], you will be prompted
18589 for a keyword. A numeric prefix directly selects the Nth keyword in
18590 `org-todo-keywords-1'."
18591 (interactive "P")
18592 (require 'calendar)
18593 (org-compile-prefix-format 'todo)
18594 (org-set-sorting-strategy 'todo)
18595 (org-prepare-agenda "TODO")
18596 (let* ((today (time-to-days (current-time)))
18597 (date (calendar-gregorian-from-absolute today))
18598 (kwds org-todo-keywords-for-agenda)
18599 (completion-ignore-case t)
18600 (org-select-this-todo-keyword
18601 (if (stringp arg) arg
18602 (and arg (integerp arg) (> arg 0)
18603 (nth (1- arg) kwds))))
18604 rtn rtnall files file pos)
18605 (when (equal arg '(4))
18606 (setq org-select-this-todo-keyword
18607 (completing-read "Keyword (or KWD1|K2D2|...): "
18608 (mapcar 'list kwds) nil nil)))
18609 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
18610 (org-set-local 'org-last-arg arg)
18611 (setq org-agenda-redo-command
18612 '(org-todo-list (or current-prefix-arg org-last-arg)))
18613 (setq files (org-agenda-files)
18614 rtnall nil)
18615 (while (setq file (pop files))
18616 (catch 'nextfile
18617 (org-check-agenda-file file)
18618 (setq rtn (org-agenda-get-day-entries file date :todo))
18619 (setq rtnall (append rtnall rtn))))
18620 (if org-agenda-overriding-header
18621 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
18622 nil 'face 'org-agenda-structure) "\n")
18623 (insert "Global list of TODO items of type: ")
18624 (add-text-properties (point-min) (1- (point))
18625 (list 'face 'org-agenda-structure))
18626 (setq pos (point))
18627 (insert (or org-select-this-todo-keyword "ALL") "\n")
18628 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
18629 (setq pos (point))
18630 (unless org-agenda-multi
18631 (insert "Available with `N r': (0)ALL")
18632 (let ((n 0) s)
18633 (mapc (lambda (x)
18634 (setq s (format "(%d)%s" (setq n (1+ n)) x))
18635 (if (> (+ (current-column) (string-width s) 1) (frame-width))
18636 (insert "\n "))
18637 (insert " " s))
18638 kwds))
18639 (insert "\n"))
18640 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
18641 (when rtnall
18642 (insert (org-finalize-agenda-entries rtnall) "\n"))
18643 (goto-char (point-min))
18644 (org-fit-agenda-window)
18645 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
18646 (org-finalize-agenda)
18647 (setq buffer-read-only t)))
18649 ;;; Agenda tags match
18651 ;;;###autoload
18652 (defun org-tags-view (&optional todo-only match)
18653 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
18654 The prefix arg TODO-ONLY limits the search to TODO entries."
18655 (interactive "P")
18656 (org-compile-prefix-format 'tags)
18657 (org-set-sorting-strategy 'tags)
18658 (let* ((org-tags-match-list-sublevels
18659 (if todo-only t org-tags-match-list-sublevels))
18660 (completion-ignore-case t)
18661 rtn rtnall files file pos matcher
18662 buffer)
18663 (setq matcher (org-make-tags-matcher match)
18664 match (car matcher) matcher (cdr matcher))
18665 (org-prepare-agenda (concat "TAGS " match))
18666 (setq org-agenda-redo-command
18667 (list 'org-tags-view (list 'quote todo-only)
18668 (list 'if 'current-prefix-arg nil match)))
18669 (setq files (org-agenda-files)
18670 rtnall nil)
18671 (while (setq file (pop files))
18672 (catch 'nextfile
18673 (org-check-agenda-file file)
18674 (setq buffer (if (file-exists-p file)
18675 (org-get-agenda-file-buffer file)
18676 (error "No such file %s" file)))
18677 (if (not buffer)
18678 ;; If file does not exist, merror message to agenda
18679 (setq rtn (list
18680 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
18681 rtnall (append rtnall rtn))
18682 (with-current-buffer buffer
18683 (unless (org-mode-p)
18684 (error "Agenda file %s is not in `org-mode'" file))
18685 (save-excursion
18686 (save-restriction
18687 (if org-agenda-restrict
18688 (narrow-to-region org-agenda-restrict-begin
18689 org-agenda-restrict-end)
18690 (widen))
18691 (setq rtn (org-scan-tags 'agenda matcher todo-only))
18692 (setq rtnall (append rtnall rtn))))))))
18693 (if org-agenda-overriding-header
18694 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
18695 nil 'face 'org-agenda-structure) "\n")
18696 (insert "Headlines with TAGS match: ")
18697 (add-text-properties (point-min) (1- (point))
18698 (list 'face 'org-agenda-structure))
18699 (setq pos (point))
18700 (insert match "\n")
18701 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
18702 (setq pos (point))
18703 (unless org-agenda-multi
18704 (insert "Press `C-u r' to search again with new search string\n"))
18705 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
18706 (when rtnall
18707 (insert (org-finalize-agenda-entries rtnall) "\n"))
18708 (goto-char (point-min))
18709 (org-fit-agenda-window)
18710 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
18711 (org-finalize-agenda)
18712 (setq buffer-read-only t)))
18714 ;;; Agenda Finding stuck projects
18716 (defvar org-agenda-skip-regexp nil
18717 "Regular expression used in skipping subtrees for the agenda.
18718 This is basically a temporary global variable that can be set and then
18719 used by user-defined selections using `org-agenda-skip-function'.")
18721 (defvar org-agenda-overriding-header nil
18722 "When this is set during todo and tags searches, will replace header.")
18724 (defun org-agenda-skip-subtree-when-regexp-matches ()
18725 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
18726 If yes, it returns the end position of this tree, causing agenda commands
18727 to skip this subtree. This is a function that can be put into
18728 `org-agenda-skip-function' for the duration of a command."
18729 (let ((end (save-excursion (org-end-of-subtree t)))
18730 skip)
18731 (save-excursion
18732 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
18733 (and skip end)))
18735 (defun org-agenda-skip-entry-if (&rest conditions)
18736 "Skip entry if any of CONDITIONS is true.
18737 See `org-agenda-skip-if for details."
18738 (org-agenda-skip-if nil conditions))
18739 (defun org-agenda-skip-subtree-if (&rest conditions)
18740 "Skip entry if any of CONDITIONS is true.
18741 See `org-agenda-skip-if for details."
18742 (org-agenda-skip-if t conditions))
18744 (defun org-agenda-skip-if (subtree conditions)
18745 "Checks current entity for CONDITIONS.
18746 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
18747 the entry, i.e. the text before the next heading is checked.
18749 CONDITIONS is a list of symbols, boolean OR is used to combine the results
18750 from different tests. Valid conditions are:
18752 scheduled Check if there is a scheduled cookie
18753 notscheduled Check if there is no scheduled cookie
18754 deadline Check if there is a deadline
18755 notdeadline Check if there is no deadline
18756 regexp Check if regexp matches
18757 notregexp Check if regexp does not match.
18759 The regexp is taken from the conditions list, it must com right after the
18760 `regexp' of `notregexp' element.
18762 If any of these conditions is met, this function returns the end point of
18763 the entity, causing the search to continue from there. This is a function
18764 that can be put into `org-agenda-skip-function' for the duration of a command."
18765 (let (beg end m r)
18766 (org-back-to-heading t)
18767 (setq beg (point)
18768 end (if subtree
18769 (progn (org-end-of-subtree t) (point))
18770 (progn (outline-next-heading) (1- (point)))))
18771 (goto-char beg)
18772 (and
18774 (and (memq 'scheduled conditions)
18775 (re-search-forward org-scheduled-time-regexp end t))
18776 (and (memq 'notscheduled conditions)
18777 (not (re-search-forward org-scheduled-time-regexp end t)))
18778 (and (memq 'deadline conditions)
18779 (re-search-forward org-deadline-time-regexp end t))
18780 (and (memq 'notdeadline conditions)
18781 (not (re-search-forward org-deadline-time-regexp end t)))
18782 (and (setq m (memq 'regexp conditions))
18783 (stringp (setq r (nth 1 m)))
18784 (re-search-forward (nth 1 m) end t))
18785 (and (setq m (memq 'notregexp conditions))
18786 (stringp (setq r (nth 1 m)))
18787 (not (re-search-forward (nth 1 m) end t))))
18788 end)))
18790 (defun org-agenda-list-stuck-projects (&rest ignore)
18791 "Create agenda view for projects that are stuck.
18792 Stuck projects are project that have no next actions. For the definitions
18793 of what a project is and how to check if it stuck, customize the variable
18794 `org-stuck-projects'.
18795 MATCH is being ignored."
18796 (interactive)
18797 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
18798 ;; FIXME: we could have used org-agenda-skip-if here.
18799 (org-agenda-overriding-header "List of stuck projects: ")
18800 (matcher (nth 0 org-stuck-projects))
18801 (todo (nth 1 org-stuck-projects))
18802 (todo-wds (if (member "*" todo)
18803 (progn
18804 (org-prepare-agenda-buffers (org-agenda-files))
18805 (org-delete-all
18806 org-done-keywords-for-agenda
18807 (copy-sequence org-todo-keywords-for-agenda)))
18808 todo))
18809 (todo-re (concat "^\\*+[ \t]+\\("
18810 (mapconcat 'identity todo-wds "\\|")
18811 "\\)\\>"))
18812 (tags (nth 2 org-stuck-projects))
18813 (tags-re (if (member "*" tags)
18814 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
18815 (concat "^\\*+ .*:\\("
18816 (mapconcat 'identity tags "\\|")
18817 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
18818 (gen-re (nth 3 org-stuck-projects))
18819 (re-list
18820 (delq nil
18821 (list
18822 (if todo todo-re)
18823 (if tags tags-re)
18824 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
18825 gen-re)))))
18826 (setq org-agenda-skip-regexp
18827 (if re-list
18828 (mapconcat 'identity re-list "\\|")
18829 (error "No information how to identify unstuck projects")))
18830 (org-tags-view nil matcher)
18831 (with-current-buffer org-agenda-buffer-name
18832 (setq org-agenda-redo-command
18833 '(org-agenda-list-stuck-projects
18834 (or current-prefix-arg org-last-arg))))))
18836 ;;; Diary integration
18838 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
18840 (defun org-get-entries-from-diary (date)
18841 "Get the (Emacs Calendar) diary entries for DATE."
18842 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
18843 (diary-display-hook '(fancy-diary-display))
18844 (pop-up-frames nil)
18845 (list-diary-entries-hook
18846 (cons 'org-diary-default-entry list-diary-entries-hook))
18847 (diary-file-name-prefix-function nil) ; turn this feature off
18848 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
18849 entries
18850 (org-disable-agenda-to-diary t))
18851 (save-excursion
18852 (save-window-excursion
18853 (funcall (if (fboundp 'diary-list-entries)
18854 'diary-list-entries 'list-diary-entries)
18855 date 1)))
18856 (if (not (get-buffer fancy-diary-buffer))
18857 (setq entries nil)
18858 (with-current-buffer fancy-diary-buffer
18859 (setq buffer-read-only nil)
18860 (if (zerop (buffer-size))
18861 ;; No entries
18862 (setq entries nil)
18863 ;; Omit the date and other unnecessary stuff
18864 (org-agenda-cleanup-fancy-diary)
18865 ;; Add prefix to each line and extend the text properties
18866 (if (zerop (buffer-size))
18867 (setq entries nil)
18868 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
18869 (set-buffer-modified-p nil)
18870 (kill-buffer fancy-diary-buffer)))
18871 (when entries
18872 (setq entries (org-split-string entries "\n"))
18873 (setq entries
18874 (mapcar
18875 (lambda (x)
18876 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
18877 ;; Extend the text properties to the beginning of the line
18878 (org-add-props x (text-properties-at (1- (length x)) x)
18879 'type "diary" 'date date))
18880 entries)))))
18882 (defun org-agenda-cleanup-fancy-diary ()
18883 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
18884 This gets rid of the date, the underline under the date, and
18885 the dummy entry installed by `org-mode' to ensure non-empty diary for each
18886 date. It also removes lines that contain only whitespace."
18887 (goto-char (point-min))
18888 (if (looking-at ".*?:[ \t]*")
18889 (progn
18890 (replace-match "")
18891 (re-search-forward "\n=+$" nil t)
18892 (replace-match "")
18893 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
18894 (re-search-forward "\n=+$" nil t)
18895 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
18896 (goto-char (point-min))
18897 (while (re-search-forward "^ +\n" nil t)
18898 (replace-match ""))
18899 (goto-char (point-min))
18900 (if (re-search-forward "^Org-mode dummy\n?" nil t)
18901 (replace-match "")))
18903 ;; Make sure entries from the diary have the right text properties.
18904 (eval-after-load "diary-lib"
18905 '(if (boundp 'diary-modify-entry-list-string-function)
18906 ;; We can rely on the hook, nothing to do
18908 ;; Hook not avaiable, must use advice to make this work
18909 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
18910 "Make the position visible."
18911 (if (and org-disable-agenda-to-diary ;; called from org-agenda
18912 (stringp string)
18913 buffer-file-name)
18914 (setq string (org-modify-diary-entry-string string))))))
18916 (defun org-modify-diary-entry-string (string)
18917 "Add text properties to string, allowing org-mode to act on it."
18918 (org-add-props string nil
18919 'mouse-face 'highlight
18920 'keymap org-agenda-keymap
18921 'help-echo (if buffer-file-name
18922 (format "mouse-2 or RET jump to diary file %s"
18923 (abbreviate-file-name buffer-file-name))
18925 'org-agenda-diary-link t
18926 'org-marker (org-agenda-new-marker (point-at-bol))))
18928 (defun org-diary-default-entry ()
18929 "Add a dummy entry to the diary.
18930 Needed to avoid empty dates which mess up holiday display."
18931 ;; Catch the error if dealing with the new add-to-diary-alist
18932 (when org-disable-agenda-to-diary
18933 (condition-case nil
18934 (add-to-diary-list original-date "Org-mode dummy" "")
18935 (error
18936 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
18938 ;;;###autoload
18939 (defun org-diary (&rest args)
18940 "Return diary information from org-files.
18941 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
18942 It accesses org files and extracts information from those files to be
18943 listed in the diary. The function accepts arguments specifying what
18944 items should be listed. The following arguments are allowed:
18946 :timestamp List the headlines of items containing a date stamp or
18947 date range matching the selected date. Deadlines will
18948 also be listed, on the expiration day.
18950 :sexp List entries resulting from diary-like sexps.
18952 :deadline List any deadlines past due, or due within
18953 `org-deadline-warning-days'. The listing occurs only
18954 in the diary for *today*, not at any other date. If
18955 an entry is marked DONE, it is no longer listed.
18957 :scheduled List all items which are scheduled for the given date.
18958 The diary for *today* also contains items which were
18959 scheduled earlier and are not yet marked DONE.
18961 :todo List all TODO items from the org-file. This may be a
18962 long list - so this is not turned on by default.
18963 Like deadlines, these entries only show up in the
18964 diary for *today*, not at any other date.
18966 The call in the diary file should look like this:
18968 &%%(org-diary) ~/path/to/some/orgfile.org
18970 Use a separate line for each org file to check. Or, if you omit the file name,
18971 all files listed in `org-agenda-files' will be checked automatically:
18973 &%%(org-diary)
18975 If you don't give any arguments (as in the example above), the default
18976 arguments (:deadline :scheduled :timestamp :sexp) are used.
18977 So the example above may also be written as
18979 &%%(org-diary :deadline :timestamp :sexp :scheduled)
18981 The function expects the lisp variables `entry' and `date' to be provided
18982 by the caller, because this is how the calendar works. Don't use this
18983 function from a program - use `org-agenda-get-day-entries' instead."
18984 (org-agenda-maybe-reset-markers)
18985 (org-compile-prefix-format 'agenda)
18986 (org-set-sorting-strategy 'agenda)
18987 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
18988 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
18989 (list entry)
18990 (org-agenda-files t)))
18991 file rtn results)
18992 (org-prepare-agenda-buffers files)
18993 ;; If this is called during org-agenda, don't return any entries to
18994 ;; the calendar. Org Agenda will list these entries itself.
18995 (if org-disable-agenda-to-diary (setq files nil))
18996 (while (setq file (pop files))
18997 (setq rtn (apply 'org-agenda-get-day-entries file date args))
18998 (setq results (append results rtn)))
18999 (if results
19000 (concat (org-finalize-agenda-entries results) "\n"))))
19002 ;;; Agenda entry finders
19004 (defun org-agenda-get-day-entries (file date &rest args)
19005 "Does the work for `org-diary' and `org-agenda'.
19006 FILE is the path to a file to be checked for entries. DATE is date like
19007 the one returned by `calendar-current-date'. ARGS are symbols indicating
19008 which kind of entries should be extracted. For details about these, see
19009 the documentation of `org-diary'."
19010 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
19011 (let* ((org-startup-folded nil)
19012 (org-startup-align-all-tables nil)
19013 (buffer (if (file-exists-p file)
19014 (org-get-agenda-file-buffer file)
19015 (error "No such file %s" file)))
19016 arg results rtn)
19017 (if (not buffer)
19018 ;; If file does not exist, make sure an error message ends up in diary
19019 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
19020 (with-current-buffer buffer
19021 (unless (org-mode-p)
19022 (error "Agenda file %s is not in `org-mode'" file))
19023 (let ((case-fold-search nil))
19024 (save-excursion
19025 (save-restriction
19026 (if org-agenda-restrict
19027 (narrow-to-region org-agenda-restrict-begin
19028 org-agenda-restrict-end)
19029 (widen))
19030 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
19031 (while (setq arg (pop args))
19032 (cond
19033 ((and (eq arg :todo)
19034 (equal date (calendar-current-date)))
19035 (setq rtn (org-agenda-get-todos))
19036 (setq results (append results rtn)))
19037 ((eq arg :timestamp)
19038 (setq rtn (org-agenda-get-blocks))
19039 (setq results (append results rtn))
19040 (setq rtn (org-agenda-get-timestamps))
19041 (setq results (append results rtn)))
19042 ((eq arg :sexp)
19043 (setq rtn (org-agenda-get-sexps))
19044 (setq results (append results rtn)))
19045 ((eq arg :scheduled)
19046 (setq rtn (org-agenda-get-scheduled))
19047 (setq results (append results rtn)))
19048 ((eq arg :closed)
19049 (setq rtn (org-agenda-get-closed))
19050 (setq results (append results rtn)))
19051 ((eq arg :deadline)
19052 (setq rtn (org-agenda-get-deadlines))
19053 (setq results (append results rtn))))))))
19054 results))))
19056 ;; FIXME: this works only if the cursor is *not* at the
19057 ;; beginning of the entry
19058 (defun org-entry-is-done-p ()
19059 "Is the current entry marked DONE?"
19060 (save-excursion
19061 (and (re-search-backward "[\r\n]\\*+ " nil t)
19062 (looking-at org-nl-done-regexp))))
19064 (defun org-at-date-range-p (&optional inactive-ok)
19065 "Is the cursor inside a date range?"
19066 (interactive)
19067 (save-excursion
19068 (catch 'exit
19069 (let ((pos (point)))
19070 (skip-chars-backward "^[<\r\n")
19071 (skip-chars-backward "<[")
19072 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
19073 (>= (match-end 0) pos)
19074 (throw 'exit t))
19075 (skip-chars-backward "^<[\r\n")
19076 (skip-chars-backward "<[")
19077 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
19078 (>= (match-end 0) pos)
19079 (throw 'exit t)))
19080 nil)))
19082 (defun org-agenda-get-todos ()
19083 "Return the TODO information for agenda display."
19084 (let* ((props (list 'face nil
19085 'done-face 'org-done
19086 'org-not-done-regexp org-not-done-regexp
19087 'org-todo-regexp org-todo-regexp
19088 'mouse-face 'highlight
19089 'keymap org-agenda-keymap
19090 'help-echo
19091 (format "mouse-2 or RET jump to org file %s"
19092 (abbreviate-file-name buffer-file-name))))
19093 ;; FIXME: get rid of the \n at some point but watch out
19094 (regexp (concat "^\\*+[ \t]+\\("
19095 (if org-select-this-todo-keyword
19096 (if (equal org-select-this-todo-keyword "*")
19097 org-todo-regexp
19098 (concat "\\<\\("
19099 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
19100 "\\)\\>"))
19101 org-not-done-regexp)
19102 "[^\n\r]*\\)"))
19103 marker priority category tags
19104 ee txt beg end)
19105 (goto-char (point-min))
19106 (while (re-search-forward regexp nil t)
19107 (catch :skip
19108 (save-match-data
19109 (beginning-of-line)
19110 (setq beg (point) end (progn (outline-next-heading) (point)))
19111 (when (or (and org-agenda-todo-ignore-scheduled (goto-char beg)
19112 (re-search-forward org-scheduled-time-regexp end t))
19113 (and org-agenda-todo-ignore-deadlines (goto-char beg)
19114 (re-search-forward org-deadline-time-regexp end t)
19115 (org-deadline-close (match-string 1))))
19116 (goto-char (1+ beg))
19117 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
19118 (throw :skip nil)))
19119 (goto-char beg)
19120 (org-agenda-skip)
19121 (goto-char (match-beginning 1))
19122 (setq marker (org-agenda-new-marker (match-beginning 0))
19123 category (org-get-category)
19124 tags (org-get-tags-at (point))
19125 txt (org-format-agenda-item "" (match-string 1) category tags)
19126 priority (1+ (org-get-priority txt)))
19127 (org-add-props txt props
19128 'org-marker marker 'org-hd-marker marker
19129 'priority priority 'org-category category
19130 'type "todo")
19131 (push txt ee)
19132 (if org-agenda-todo-list-sublevels
19133 (goto-char (match-end 1))
19134 (org-end-of-subtree 'invisible))))
19135 (nreverse ee)))
19137 (defconst org-agenda-no-heading-message
19138 "No heading for this item in buffer or region.")
19140 (defun org-agenda-get-timestamps ()
19141 "Return the date stamp information for agenda display."
19142 (let* ((props (list 'face nil
19143 'org-not-done-regexp org-not-done-regexp
19144 'org-todo-regexp org-todo-regexp
19145 'mouse-face 'highlight
19146 'keymap org-agenda-keymap
19147 'help-echo
19148 (format "mouse-2 or RET jump to org file %s"
19149 (abbreviate-file-name buffer-file-name))))
19150 (d1 (calendar-absolute-from-gregorian date))
19151 (remove-re
19152 (concat
19153 (regexp-quote
19154 (format-time-string
19155 "<%Y-%m-%d"
19156 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19157 ".*?>"))
19158 (regexp
19159 (concat
19160 (regexp-quote
19161 (substring
19162 (format-time-string
19163 (car org-time-stamp-formats)
19164 (apply 'encode-time ; DATE bound by calendar
19165 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
19166 0 11))
19167 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
19168 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
19169 marker hdmarker deadlinep scheduledp donep tmp priority category
19170 ee txt timestr tags b0 b3 e3)
19171 (goto-char (point-min))
19172 (while (re-search-forward regexp nil t)
19173 (setq b0 (match-beginning 0)
19174 b3 (match-beginning 3) e3 (match-end 3))
19175 (catch :skip
19176 (and (org-at-date-range-p) (throw :skip nil))
19177 (org-agenda-skip)
19178 (if (and (match-end 1)
19179 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
19180 (throw :skip nil))
19181 (if (and e3
19182 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
19183 (throw :skip nil))
19184 (setq marker (org-agenda-new-marker b0)
19185 category (org-get-category b0)
19186 tmp (buffer-substring (max (point-min)
19187 (- b0 org-ds-keyword-length))
19189 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
19190 deadlinep (string-match org-deadline-regexp tmp)
19191 scheduledp (string-match org-scheduled-regexp tmp)
19192 donep (org-entry-is-done-p))
19193 (if (or scheduledp deadlinep) (throw :skip t))
19194 (if (string-match ">" timestr)
19195 ;; substring should only run to end of time stamp
19196 (setq timestr (substring timestr 0 (match-end 0))))
19197 (save-excursion
19198 (if (re-search-backward "^\\*+ " nil t)
19199 (progn
19200 (goto-char (match-beginning 0))
19201 (setq hdmarker (org-agenda-new-marker)
19202 tags (org-get-tags-at))
19203 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
19204 (setq txt (org-format-agenda-item
19205 nil (match-string 1) category tags timestr nil
19206 remove-re)))
19207 (setq txt org-agenda-no-heading-message))
19208 (setq priority (org-get-priority txt))
19209 (org-add-props txt props
19210 'org-marker marker 'org-hd-marker hdmarker)
19211 (org-add-props txt nil 'priority priority
19212 'org-category category 'date date
19213 'type "timestamp")
19214 (push txt ee))
19215 (outline-next-heading)))
19216 (nreverse ee)))
19218 (defun org-agenda-get-sexps ()
19219 "Return the sexp information for agenda display."
19220 (require 'diary-lib)
19221 (let* ((props (list 'face nil
19222 'mouse-face 'highlight
19223 'keymap org-agenda-keymap
19224 'help-echo
19225 (format "mouse-2 or RET jump to org file %s"
19226 (abbreviate-file-name buffer-file-name))))
19227 (regexp "^&?%%(")
19228 marker category ee txt tags entry result beg b sexp sexp-entry)
19229 (goto-char (point-min))
19230 (while (re-search-forward regexp nil t)
19231 (catch :skip
19232 (org-agenda-skip)
19233 (setq beg (match-beginning 0))
19234 (goto-char (1- (match-end 0)))
19235 (setq b (point))
19236 (forward-sexp 1)
19237 (setq sexp (buffer-substring b (point)))
19238 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
19239 (org-trim (match-string 1))
19240 ""))
19241 (setq result (org-diary-sexp-entry sexp sexp-entry date))
19242 (when result
19243 (setq marker (org-agenda-new-marker beg)
19244 category (org-get-category beg))
19246 (if (string-match "\\S-" result)
19247 (setq txt result)
19248 (setq txt "SEXP entry returned empty string"))
19250 (setq txt (org-format-agenda-item
19251 "" txt category tags 'time))
19252 (org-add-props txt props 'org-marker marker)
19253 (org-add-props txt nil
19254 'org-category category 'date date
19255 'type "sexp")
19256 (push txt ee))))
19257 (nreverse ee)))
19259 (defun org-agenda-get-closed ()
19260 "Return the logged TODO entries for agenda display."
19261 (let* ((props (list 'mouse-face 'highlight
19262 'org-not-done-regexp org-not-done-regexp
19263 'org-todo-regexp org-todo-regexp
19264 'keymap org-agenda-keymap
19265 'help-echo
19266 (format "mouse-2 or RET jump to org file %s"
19267 (abbreviate-file-name buffer-file-name))))
19268 (regexp (concat
19269 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
19270 (regexp-quote
19271 (substring
19272 (format-time-string
19273 (car org-time-stamp-formats)
19274 (apply 'encode-time ; DATE bound by calendar
19275 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
19276 1 11))))
19277 marker hdmarker priority category tags closedp
19278 ee txt timestr)
19279 (goto-char (point-min))
19280 (while (re-search-forward regexp nil t)
19281 (catch :skip
19282 (org-agenda-skip)
19283 (setq marker (org-agenda-new-marker (match-beginning 0))
19284 closedp (equal (match-string 1) org-closed-string)
19285 category (org-get-category (match-beginning 0))
19286 timestr (buffer-substring (match-beginning 0) (point-at-eol))
19287 ;; donep (org-entry-is-done-p)
19289 (if (string-match "\\]" timestr)
19290 ;; substring should only run to end of time stamp
19291 (setq timestr (substring timestr 0 (match-end 0))))
19292 (save-excursion
19293 (if (re-search-backward "^\\*+ " nil t)
19294 (progn
19295 (goto-char (match-beginning 0))
19296 (setq hdmarker (org-agenda-new-marker)
19297 tags (org-get-tags-at))
19298 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
19299 (setq txt (org-format-agenda-item
19300 (if closedp "Closed: " "Clocked: ")
19301 (match-string 1) category tags timestr)))
19302 (setq txt org-agenda-no-heading-message))
19303 (setq priority 100000)
19304 (org-add-props txt props
19305 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
19306 'priority priority 'org-category category
19307 'type "closed" 'date date
19308 'undone-face 'org-warning 'done-face 'org-done)
19309 (push txt ee))
19310 (outline-next-heading)))
19311 (nreverse ee)))
19313 (defun org-agenda-get-deadlines ()
19314 "Return the deadline information for agenda display."
19315 (let* ((props (list 'mouse-face 'highlight
19316 'org-not-done-regexp org-not-done-regexp
19317 'org-todo-regexp org-todo-regexp
19318 'keymap org-agenda-keymap
19319 'help-echo
19320 (format "mouse-2 or RET jump to org file %s"
19321 (abbreviate-file-name buffer-file-name))))
19322 (regexp org-deadline-time-regexp)
19323 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
19324 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
19325 d2 diff dfrac wdays pos pos1 category tags
19326 ee txt head face s upcomingp donep timestr)
19327 (goto-char (point-min))
19328 (while (re-search-forward regexp nil t)
19329 (catch :skip
19330 (org-agenda-skip)
19331 (setq s (match-string 1)
19332 pos (1- (match-beginning 1))
19333 d2 (org-time-string-to-absolute (match-string 1) d1)
19334 diff (- d2 d1)
19335 wdays (org-get-wdays s)
19336 dfrac (/ (* 1.0 (- wdays diff)) wdays)
19337 upcomingp (and todayp (> diff 0)))
19338 ;; When to show a deadline in the calendar:
19339 ;; If the expiration is within wdays warning time.
19340 ;; Past-due deadlines are only shown on the current date
19341 (if (or (and (<= diff wdays)
19342 (and todayp (not org-agenda-only-exact-dates)))
19343 (= diff 0))
19344 (save-excursion
19345 (setq category (org-get-category))
19346 (if (re-search-backward "^\\*+[ \t]+" nil t)
19347 (progn
19348 (goto-char (match-end 0))
19349 (setq pos1 (match-beginning 0))
19350 (setq tags (org-get-tags-at pos1))
19351 (setq head (buffer-substring-no-properties
19352 (point)
19353 (progn (skip-chars-forward "^\r\n")
19354 (point))))
19355 (setq donep (string-match org-looking-at-done-regexp head))
19356 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
19357 (setq timestr
19358 (concat (substring s (match-beginning 1)) " "))
19359 (setq timestr 'time))
19360 (if (and donep
19361 (or org-agenda-skip-deadline-if-done
19362 (not (= diff 0))))
19363 (setq txt nil)
19364 (setq txt (org-format-agenda-item
19365 (if (= diff 0)
19366 (car org-agenda-deadline-leaders)
19367 (format (nth 1 org-agenda-deadline-leaders)
19368 diff))
19369 head category tags timestr))))
19370 (setq txt org-agenda-no-heading-message))
19371 (when txt
19372 (setq face (org-agenda-deadline-face dfrac))
19373 (org-add-props txt props
19374 'org-marker (org-agenda-new-marker pos)
19375 'org-hd-marker (org-agenda-new-marker pos1)
19376 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
19377 (org-get-priority txt))
19378 'org-category category
19379 'type (if upcomingp "upcoming-deadline" "deadline")
19380 'date (if upcomingp date d2)
19381 'face (if donep 'org-done face)
19382 'undone-face face 'done-face 'org-done)
19383 (push txt ee))))))
19384 (nreverse ee)))
19386 (defun org-agenda-deadline-face (fraction)
19387 "Return the face to displaying a deadline item.
19388 FRACTION is what fraction of the head-warning time has passed."
19389 (let ((faces org-agenda-deadline-faces) f)
19390 (catch 'exit
19391 (while (setq f (pop faces))
19392 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
19394 (defun org-agenda-get-scheduled ()
19395 "Return the scheduled information for agenda display."
19396 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
19397 'org-todo-regexp org-todo-regexp
19398 'done-face 'org-done
19399 'mouse-face 'highlight
19400 'keymap org-agenda-keymap
19401 'help-echo
19402 (format "mouse-2 or RET jump to org file %s"
19403 (abbreviate-file-name buffer-file-name))))
19404 (regexp org-scheduled-time-regexp)
19405 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
19406 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
19407 d2 diff pos pos1 category tags
19408 ee txt head pastschedp donep face timestr s)
19409 (goto-char (point-min))
19410 (while (re-search-forward regexp nil t)
19411 (catch :skip
19412 (org-agenda-skip)
19413 (setq s (match-string 1)
19414 pos (1- (match-beginning 1))
19415 d2 (org-time-string-to-absolute (match-string 1) d1)
19416 diff (- d2 d1))
19417 (setq pastschedp (and todayp (< diff 0)))
19418 ;; When to show a scheduled item in the calendar:
19419 ;; If it is on or past the date.
19420 (if (or (and (< diff 0)
19421 (and todayp (not org-agenda-only-exact-dates)))
19422 (= diff 0))
19423 (save-excursion
19424 (setq category (org-get-category))
19425 (if (re-search-backward "^\\*+[ \t]+" nil t)
19426 (progn
19427 (goto-char (match-end 0))
19428 (setq pos1 (match-beginning 0))
19429 (setq tags (org-get-tags-at))
19430 (setq head (buffer-substring-no-properties
19431 (point)
19432 (progn (skip-chars-forward "^\r\n") (point))))
19433 (setq donep (string-match org-looking-at-done-regexp head))
19434 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
19435 (setq timestr
19436 (concat (substring s (match-beginning 1)) " "))
19437 (setq timestr 'time))
19438 (if (and donep
19439 (or org-agenda-skip-scheduled-if-done
19440 (not (= diff 0))))
19441 (setq txt nil)
19442 (setq txt (org-format-agenda-item
19443 (if (= diff 0)
19444 (car org-agenda-scheduled-leaders)
19445 (format (nth 1 org-agenda-scheduled-leaders)
19446 (- 1 diff)))
19447 head category tags timestr))))
19448 (setq txt org-agenda-no-heading-message))
19449 (when txt
19450 (setq face (if pastschedp
19451 'org-scheduled-previously
19452 'org-scheduled-today))
19453 (org-add-props txt props
19454 'undone-face face
19455 'face (if donep 'org-done face)
19456 'org-marker (org-agenda-new-marker pos)
19457 'org-hd-marker (org-agenda-new-marker pos1)
19458 'type (if pastschedp "past-scheduled" "scheduled")
19459 'date (if pastschedp d2 date)
19460 'priority (+ 94 (- 5 diff) (org-get-priority txt))
19461 'org-category category)
19462 (push txt ee))))))
19463 (nreverse ee)))
19465 (defun org-agenda-get-blocks ()
19466 "Return the date-range information for agenda display."
19467 (let* ((props (list 'face nil
19468 'org-not-done-regexp org-not-done-regexp
19469 'org-todo-regexp org-todo-regexp
19470 'mouse-face 'highlight
19471 'keymap org-agenda-keymap
19472 'help-echo
19473 (format "mouse-2 or RET jump to org file %s"
19474 (abbreviate-file-name buffer-file-name))))
19475 (regexp org-tr-regexp)
19476 (d0 (calendar-absolute-from-gregorian date))
19477 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
19478 (goto-char (point-min))
19479 (while (re-search-forward regexp nil t)
19480 (catch :skip
19481 (org-agenda-skip)
19482 (setq pos (point))
19483 (setq timestr (match-string 0)
19484 s1 (match-string 1)
19485 s2 (match-string 2)
19486 d1 (time-to-days (org-time-string-to-time s1))
19487 d2 (time-to-days (org-time-string-to-time s2)))
19488 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
19489 ;; Only allow days between the limits, because the normal
19490 ;; date stamps will catch the limits.
19491 (save-excursion
19492 (setq marker (org-agenda-new-marker (point)))
19493 (setq category (org-get-category))
19494 (if (re-search-backward "^\\*+ " nil t)
19495 (progn
19496 (goto-char (match-beginning 0))
19497 (setq hdmarker (org-agenda-new-marker (point)))
19498 (setq tags (org-get-tags-at))
19499 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
19500 (setq txt (org-format-agenda-item
19501 (format (if (= d1 d2) "" "(%d/%d): ")
19502 (1+ (- d0 d1)) (1+ (- d2 d1)))
19503 (match-string 1) category tags
19504 (if (= d0 d1) timestr))))
19505 (setq txt org-agenda-no-heading-message))
19506 (org-add-props txt props
19507 'org-marker marker 'org-hd-marker hdmarker
19508 'type "block" 'date date
19509 'priority (org-get-priority txt) 'org-category category)
19510 (push txt ee)))
19511 (goto-char pos)))
19512 ;; Sort the entries by expiration date.
19513 (nreverse ee)))
19515 ;;; Agenda presentation and sorting
19517 (defconst org-plain-time-of-day-regexp
19518 (concat
19519 "\\(\\<[012]?[0-9]"
19520 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
19521 "\\(--?"
19522 "\\(\\<[012]?[0-9]"
19523 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
19524 "\\)?")
19525 "Regular expression to match a plain time or time range.
19526 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
19527 groups carry important information:
19528 0 the full match
19529 1 the first time, range or not
19530 8 the second time, if it is a range.")
19532 (defconst org-plain-time-extension-regexp
19533 (concat
19534 "\\(\\<[012]?[0-9]"
19535 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
19536 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
19537 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
19538 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
19539 groups carry important information:
19540 0 the full match
19541 7 hours of duration
19542 9 minutes of duration")
19544 (defconst org-stamp-time-of-day-regexp
19545 (concat
19546 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
19547 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
19548 "\\(--?"
19549 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
19550 "Regular expression to match a timestamp time or time range.
19551 After a match, the following groups carry important information:
19552 0 the full match
19553 1 date plus weekday, for backreferencing to make sure both times on same day
19554 2 the first time, range or not
19555 4 the second time, if it is a range.")
19557 (defvar org-prefix-has-time nil
19558 "A flag, set by `org-compile-prefix-format'.
19559 The flag is set if the currently compiled format contains a `%t'.")
19560 (defvar org-prefix-has-tag nil
19561 "A flag, set by `org-compile-prefix-format'.
19562 The flag is set if the currently compiled format contains a `%T'.")
19564 (defun org-format-agenda-item (extra txt &optional category tags dotime
19565 noprefix remove-re)
19566 "Format TXT to be inserted into the agenda buffer.
19567 In particular, it adds the prefix and corresponding text properties. EXTRA
19568 must be a string and replaces the `%s' specifier in the prefix format.
19569 CATEGORY (string, symbol or nil) may be used to overrule the default
19570 category taken from local variable or file name. It will replace the `%c'
19571 specifier in the format. DOTIME, when non-nil, indicates that a
19572 time-of-day should be extracted from TXT for sorting of this entry, and for
19573 the `%t' specifier in the format. When DOTIME is a string, this string is
19574 searched for a time before TXT is. NOPREFIX is a flag and indicates that
19575 only the correctly processes TXT should be returned - this is used by
19576 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
19577 Any match of REMOVE-RE will be removed from TXT."
19578 (save-match-data
19579 ;; Diary entries sometimes have extra whitespace at the beginning
19580 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
19581 (let* ((category (or category
19582 org-category
19583 (if buffer-file-name
19584 (file-name-sans-extension
19585 (file-name-nondirectory buffer-file-name))
19586 "")))
19587 (tag (if tags (nth (1- (length tags)) tags) ""))
19588 time ; time and tag are needed for the eval of the prefix format
19589 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
19590 (time-of-day (and dotime (org-get-time-of-day ts)))
19591 stamp plain s0 s1 s2 rtn srp)
19592 (when (and dotime time-of-day org-prefix-has-time)
19593 ;; Extract starting and ending time and move them to prefix
19594 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
19595 (setq plain (string-match org-plain-time-of-day-regexp ts)))
19596 (setq s0 (match-string 0 ts)
19597 srp (and stamp (match-end 3))
19598 s1 (match-string (if plain 1 2) ts)
19599 s2 (match-string (if plain 8 (if srp 4 6)) ts))
19601 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
19602 ;; them, we might want to remove them there to avoid duplication.
19603 ;; The user can turn this off with a variable.
19604 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
19605 (string-match (concat (regexp-quote s0) " *") txt)
19606 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
19607 (= (match-beginning 0) 0)
19609 (setq txt (replace-match "" nil nil txt))))
19610 ;; Normalize the time(s) to 24 hour
19611 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
19612 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
19614 (when (and s1 (not s2) org-agenda-default-appointment-duration
19615 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
19616 (let ((m (+ (string-to-number (match-string 2 s1))
19617 (* 60 (string-to-number (match-string 1 s1)))
19618 org-agenda-default-appointment-duration))
19620 (setq h (/ m 60) m (- m (* h 60)))
19621 (setq s2 (format "%02d:%02d" h m))))
19623 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
19624 txt)
19625 ;; Tags are in the string
19626 (if (or (eq org-agenda-remove-tags t)
19627 (and org-agenda-remove-tags
19628 org-prefix-has-tag))
19629 (setq txt (replace-match "" t t txt))
19630 (setq txt (replace-match
19631 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
19632 (match-string 2 txt))
19633 t t txt))))
19635 (when remove-re
19636 (while (string-match remove-re txt)
19637 (setq txt (replace-match "" t t txt))))
19639 ;; Create the final string
19640 (if noprefix
19641 (setq rtn txt)
19642 ;; Prepare the variables needed in the eval of the compiled format
19643 (setq time (cond (s2 (concat s1 "-" s2))
19644 (s1 (concat s1 "......"))
19645 (t ""))
19646 extra (or extra "")
19647 category (if (symbolp category) (symbol-name category) category))
19648 ;; Evaluate the compiled format
19649 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
19651 ;; And finally add the text properties
19652 (org-add-props rtn nil
19653 'org-category (downcase category) 'tags tags
19654 'org-highest-priority org-highest-priority
19655 'org-lowest-priority org-lowest-priority
19656 'prefix-length (- (length rtn) (length txt))
19657 'time-of-day time-of-day
19658 'txt txt
19659 'time time
19660 'extra extra
19661 'dotime dotime))))
19663 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
19664 (defvar org-agenda-sorting-strategy-selected nil)
19666 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
19667 (catch 'exit
19668 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
19669 ((and todayp (member 'today (car org-agenda-time-grid))))
19670 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
19671 ((member 'weekly (car org-agenda-time-grid)))
19672 (t (throw 'exit list)))
19673 (let* ((have (delq nil (mapcar
19674 (lambda (x) (get-text-property 1 'time-of-day x))
19675 list)))
19676 (string (nth 1 org-agenda-time-grid))
19677 (gridtimes (nth 2 org-agenda-time-grid))
19678 (req (car org-agenda-time-grid))
19679 (remove (member 'remove-match req))
19680 new time)
19681 (if (and (member 'require-timed req) (not have))
19682 ;; don't show empty grid
19683 (throw 'exit list))
19684 (while (setq time (pop gridtimes))
19685 (unless (and remove (member time have))
19686 (setq time (int-to-string time))
19687 (push (org-format-agenda-item
19688 nil string "" nil
19689 (concat (substring time 0 -2) ":" (substring time -2)))
19690 new)
19691 (put-text-property
19692 1 (length (car new)) 'face 'org-time-grid (car new))))
19693 (if (member 'time-up org-agenda-sorting-strategy-selected)
19694 (append new list)
19695 (append list new)))))
19697 (defun org-compile-prefix-format (key)
19698 "Compile the prefix format into a Lisp form that can be evaluated.
19699 The resulting form is returned and stored in the variable
19700 `org-prefix-format-compiled'."
19701 (setq org-prefix-has-time nil org-prefix-has-tag nil)
19702 (let ((s (cond
19703 ((stringp org-agenda-prefix-format)
19704 org-agenda-prefix-format)
19705 ((assq key org-agenda-prefix-format)
19706 (cdr (assq key org-agenda-prefix-format)))
19707 (t " %-12:c%?-12t% s")))
19708 (start 0)
19709 varform vars var e c f opt)
19710 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
19711 s start)
19712 (setq var (cdr (assoc (match-string 4 s)
19713 '(("c" . category) ("t" . time) ("s" . extra)
19714 ("T" . tag))))
19715 c (or (match-string 3 s) "")
19716 opt (match-beginning 1)
19717 start (1+ (match-beginning 0)))
19718 (if (equal var 'time) (setq org-prefix-has-time t))
19719 (if (equal var 'tag) (setq org-prefix-has-tag t))
19720 (setq f (concat "%" (match-string 2 s) "s"))
19721 (if opt
19722 (setq varform
19723 `(if (equal "" ,var)
19725 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
19726 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
19727 (setq s (replace-match "%s" t nil s))
19728 (push varform vars))
19729 (setq vars (nreverse vars))
19730 (setq org-prefix-format-compiled `(format ,s ,@vars))))
19732 (defun org-set-sorting-strategy (key)
19733 (if (symbolp (car org-agenda-sorting-strategy))
19734 ;; the old format
19735 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
19736 (setq org-agenda-sorting-strategy-selected
19737 (or (cdr (assq key org-agenda-sorting-strategy))
19738 (cdr (assq 'agenda org-agenda-sorting-strategy))
19739 '(time-up category-keep priority-down)))))
19741 (defun org-get-time-of-day (s &optional string mod24)
19742 "Check string S for a time of day.
19743 If found, return it as a military time number between 0 and 2400.
19744 If not found, return nil.
19745 The optional STRING argument forces conversion into a 5 character wide string
19746 HH:MM."
19747 (save-match-data
19748 (when
19749 (and (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
19750 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
19751 (not (equal (string-to-char (substring s (match-end 0))) ?\])))
19752 (let* ((h (string-to-number (match-string 1 s)))
19753 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
19754 (ampm (if (match-end 4) (downcase (match-string 4 s))))
19755 (am-p (equal ampm "am"))
19756 (h1 (cond ((not ampm) h)
19757 ((= h 12) (if am-p 0 12))
19758 (t (+ h (if am-p 0 12)))))
19759 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
19760 (mod h1 24) h1))
19761 (t0 (+ (* 100 h2) m))
19762 (t1 (concat (if (>= h1 24) "+" " ")
19763 (if (< t0 100) "0" "")
19764 (if (< t0 10) "0" "")
19765 (int-to-string t0))))
19766 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
19768 (defun org-finalize-agenda-entries (list &optional nosort)
19769 "Sort and concatenate the agenda items."
19770 (setq list (mapcar 'org-agenda-highlight-todo list))
19771 (if nosort
19772 list
19773 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
19775 (defun org-agenda-highlight-todo (x)
19776 (let (re pl)
19777 (if (eq x 'line)
19778 (save-excursion
19779 (beginning-of-line 1)
19780 (setq re (get-text-property (point) 'org-todo-regexp))
19781 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
19782 (and (looking-at (concat "[ \t]*\\.*" re))
19783 (add-text-properties (match-beginning 0) (match-end 0)
19784 (list 'face (org-get-todo-face 0)))))
19785 (setq re (concat (get-text-property 0 'org-todo-regexp x))
19786 pl (get-text-property 0 'prefix-length x))
19787 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
19788 (add-text-properties
19789 (or (match-end 1) (match-end 0)) (match-end 0)
19790 (list 'face (org-get-todo-face (match-string 2 x)))
19792 x)))
19794 (defsubst org-cmp-priority (a b)
19795 "Compare the priorities of string A and B."
19796 (let ((pa (or (get-text-property 1 'priority a) 0))
19797 (pb (or (get-text-property 1 'priority b) 0)))
19798 (cond ((> pa pb) +1)
19799 ((< pa pb) -1)
19800 (t nil))))
19802 (defsubst org-cmp-category (a b)
19803 "Compare the string values of categories of strings A and B."
19804 (let ((ca (or (get-text-property 1 'org-category a) ""))
19805 (cb (or (get-text-property 1 'org-category b) "")))
19806 (cond ((string-lessp ca cb) -1)
19807 ((string-lessp cb ca) +1)
19808 (t nil))))
19810 (defsubst org-cmp-tag (a b)
19811 "Compare the string values of categories of strings A and B."
19812 (let ((ta (car (last (get-text-property 1 'tags a))))
19813 (tb (car (last (get-text-property 1 'tags b)))))
19814 (cond ((not ta) +1)
19815 ((not tb) -1)
19816 ((string-lessp ta tb) -1)
19817 ((string-lessp tb ta) +1)
19818 (t nil))))
19820 (defsubst org-cmp-time (a b)
19821 "Compare the time-of-day values of strings A and B."
19822 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
19823 (ta (or (get-text-property 1 'time-of-day a) def))
19824 (tb (or (get-text-property 1 'time-of-day b) def)))
19825 (cond ((< ta tb) -1)
19826 ((< tb ta) +1)
19827 (t nil))))
19829 (defun org-entries-lessp (a b)
19830 "Predicate for sorting agenda entries."
19831 ;; The following variables will be used when the form is evaluated.
19832 ;; So even though the compiler complains, keep them.
19833 (let* ((time-up (org-cmp-time a b))
19834 (time-down (if time-up (- time-up) nil))
19835 (priority-up (org-cmp-priority a b))
19836 (priority-down (if priority-up (- priority-up) nil))
19837 (category-up (org-cmp-category a b))
19838 (category-down (if category-up (- category-up) nil))
19839 (category-keep (if category-up +1 nil))
19840 (tag-up (org-cmp-tag a b))
19841 (tag-down (if tag-up (- tag-up) nil)))
19842 (cdr (assoc
19843 (eval (cons 'or org-agenda-sorting-strategy-selected))
19844 '((-1 . t) (1 . nil) (nil . nil))))))
19846 ;;; Agenda commands
19848 (defun org-agenda-check-type (error &rest types)
19849 "Check if agenda buffer is of allowed type.
19850 If ERROR is non-nil, throw an error, otherwise just return nil."
19851 (if (memq org-agenda-type types)
19853 (if error
19854 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
19855 nil)))
19857 (defun org-agenda-quit ()
19858 "Exit agenda by removing the window or the buffer."
19859 (interactive)
19860 (let ((buf (current-buffer)))
19861 (if (not (one-window-p)) (delete-window))
19862 (kill-buffer buf)
19863 (org-agenda-maybe-reset-markers 'force)
19864 (org-columns-remove-overlays))
19865 ;; Maybe restore the pre-agenda window configuration.
19866 (and org-agenda-restore-windows-after-quit
19867 (not (eq org-agenda-window-setup 'other-frame))
19868 org-pre-agenda-window-conf
19869 (set-window-configuration org-pre-agenda-window-conf)))
19871 (defun org-agenda-exit ()
19872 "Exit agenda by removing the window or the buffer.
19873 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
19874 Org-mode buffers visited directly by the user will not be touched."
19875 (interactive)
19876 (org-release-buffers org-agenda-new-buffers)
19877 (setq org-agenda-new-buffers nil)
19878 (org-agenda-quit))
19880 (defun org-save-all-org-buffers ()
19881 "Save all Org-mode buffers without user confirmation."
19882 (interactive)
19883 (message "Saving all Org-mode buffers...")
19884 (save-some-buffers t 'org-mode-p)
19885 (message "Saving all Org-mode buffers... done"))
19887 (defun org-agenda-redo ()
19888 "Rebuild Agenda.
19889 When this is the global TODO list, a prefix argument will be interpreted."
19890 (interactive)
19891 (let* ((org-agenda-keep-modes t)
19892 (line (org-current-line))
19893 (window-line (- line (org-current-line (window-start))))
19894 (lprops (get 'org-agenda-redo-command 'org-lprops)))
19895 (message "Rebuilding agenda buffer...")
19896 (org-let lprops '(eval org-agenda-redo-command))
19897 (setq org-agenda-undo-list nil
19898 org-agenda-pending-undo-list nil)
19899 (message "Rebuilding agenda buffer...done")
19900 (goto-line line)
19901 (recenter window-line)))
19903 (defun org-agenda-goto-date (date)
19904 "Jump to DATE in agenda."
19905 (interactive (list (org-read-date)))
19906 (org-agenda-list nil date))
19908 (defun org-agenda-goto-today ()
19909 "Go to today."
19910 (interactive)
19911 (org-agenda-check-type t 'timeline 'agenda)
19912 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
19913 (cond
19914 (tdpos (goto-char tdpos))
19915 ((eq org-agenda-type 'agenda)
19916 (let* ((sd (time-to-days (current-time)))
19917 (comp (org-agenda-compute-time-span sd org-agenda-span))
19918 (org-agenda-overriding-arguments org-agenda-last-arguments))
19919 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
19920 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
19921 (org-agenda-redo)
19922 (org-agenda-find-same-or-today-or-agenda)))
19923 (t (error "Cannot find today")))))
19925 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
19926 (goto-char
19927 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
19928 (text-property-any (point-min) (point-max) 'org-today t)
19929 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
19930 (point-min))))
19932 (defun org-agenda-later (arg)
19933 "Go forward in time by thee current span.
19934 With prefix ARG, go forward that many times the current span."
19935 (interactive "p")
19936 (org-agenda-check-type t 'agenda)
19937 (let* ((span org-agenda-span)
19938 (sd org-starting-day)
19939 (greg (calendar-gregorian-from-absolute sd))
19940 (cnt (get-text-property (point) 'org-day-cnt))
19941 greg2 nd)
19942 (cond
19943 ((eq span 'day)
19944 (setq sd (+ arg sd) nd 1))
19945 ((eq span 'week)
19946 (setq sd (+ (* 7 arg) sd) nd 7))
19947 ((eq span 'month)
19948 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
19949 sd (calendar-absolute-from-gregorian greg2))
19950 (setcar greg2 (1+ (car greg2)))
19951 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
19952 ((eq span 'year)
19953 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
19954 sd (calendar-absolute-from-gregorian greg2))
19955 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
19956 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
19957 (let ((org-agenda-overriding-arguments
19958 (list (car org-agenda-last-arguments) sd nd t)))
19959 (org-agenda-redo)
19960 (org-agenda-find-same-or-today-or-agenda cnt))))
19962 (defun org-agenda-earlier (arg)
19963 "Go backward in time by the current span.
19964 With prefix ARG, go backward that many times the current span."
19965 (interactive "p")
19966 (org-agenda-later (- arg)))
19968 (defun org-agenda-day-view ()
19969 "Switch to daily view for agenda."
19970 (interactive)
19971 (setq org-agenda-ndays 1)
19972 (org-agenda-change-time-span 'day))
19973 (defun org-agenda-week-view ()
19974 "Switch to daily view for agenda."
19975 (interactive)
19976 (setq org-agenda-ndays 7)
19977 (org-agenda-change-time-span 'week))
19978 (defun org-agenda-month-view ()
19979 "Switch to daily view for agenda."
19980 (interactive)
19981 (org-agenda-change-time-span 'month))
19982 (defun org-agenda-year-view ()
19983 "Switch to daily view for agenda."
19984 (interactive)
19985 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
19986 (org-agenda-change-time-span 'year)
19987 (error "Abort")))
19989 (defun org-agenda-change-time-span (span)
19990 "Change the agenda view to SPAN.
19991 SPAN may be `day', `week', `month', `year'."
19992 (org-agenda-check-type t 'agenda)
19993 (if (equal org-agenda-span span)
19994 (error "Viewing span is already \"%s\"" span))
19995 (let* ((sd (or (get-text-property (point) 'day)
19996 org-starting-day))
19997 (computed (org-agenda-compute-time-span sd span))
19998 (org-agenda-overriding-arguments
19999 (list (car org-agenda-last-arguments)
20000 (car computed) (cdr computed) t)))
20001 (org-agenda-redo)
20002 (org-agenda-find-same-or-today-or-agenda))
20003 (org-agenda-set-mode-name)
20004 (message "Switched to %s view" span))
20006 (defun org-agenda-compute-time-span (sd span)
20007 "Compute starting date and number of days for agenda.
20008 SPAN may be `day', `week', `month', `year'. The return value
20009 is a cons cell with the starting date and the number of days,
20010 so that the date SD will be in that range."
20011 (let* ((greg (calendar-gregorian-from-absolute sd))
20013 (cond
20014 ((eq span 'day)
20015 (setq nd 1))
20016 ((eq span 'week)
20017 (let* ((nt (calendar-day-of-week
20018 (calendar-gregorian-from-absolute sd)))
20019 (d (if org-agenda-start-on-weekday
20020 (- nt org-agenda-start-on-weekday)
20021 0)))
20022 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
20023 (setq nd 7)))
20024 ((eq span 'month)
20025 (setq sd (calendar-absolute-from-gregorian
20026 (list (car greg) 1 (nth 2 greg)))
20027 nd (- (calendar-absolute-from-gregorian
20028 (list (1+ (car greg)) 1 (nth 2 greg)))
20029 sd)))
20030 ((eq span 'year)
20031 (setq sd (calendar-absolute-from-gregorian
20032 (list 1 1 (nth 2 greg)))
20033 nd (- (calendar-absolute-from-gregorian
20034 (list 1 1 (1+ (nth 2 greg))))
20035 sd))))
20036 (cons sd nd)))
20038 ;; FIXME: does not work if user makes date format that starts with a blank
20039 (defun org-agenda-next-date-line (&optional arg)
20040 "Jump to the next line indicating a date in agenda buffer."
20041 (interactive "p")
20042 (org-agenda-check-type t 'agenda 'timeline)
20043 (beginning-of-line 1)
20044 (if (looking-at "^\\S-") (forward-char 1))
20045 (if (not (re-search-forward "^\\S-" nil t arg))
20046 (progn
20047 (backward-char 1)
20048 (error "No next date after this line in this buffer")))
20049 (goto-char (match-beginning 0)))
20051 (defun org-agenda-previous-date-line (&optional arg)
20052 "Jump to the previous line indicating a date in agenda buffer."
20053 (interactive "p")
20054 (org-agenda-check-type t 'agenda 'timeline)
20055 (beginning-of-line 1)
20056 (if (not (re-search-backward "^\\S-" nil t arg))
20057 (error "No previous date before this line in this buffer")))
20059 ;; Initialize the highlight
20060 (defvar org-hl (org-make-overlay 1 1))
20061 (org-overlay-put org-hl 'face 'highlight)
20063 (defun org-highlight (begin end &optional buffer)
20064 "Highlight a region with overlay."
20065 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
20066 org-hl begin end (or buffer (current-buffer))))
20068 (defun org-unhighlight ()
20069 "Detach overlay INDEX."
20070 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
20072 ;; FIXME this is currently not used.
20073 (defun org-highlight-until-next-command (beg end &optional buffer)
20074 (org-highlight beg end buffer)
20075 (add-hook 'pre-command-hook 'org-unhighlight-once))
20076 (defun org-unhighlight-once ()
20077 (remove-hook 'pre-command-hook 'org-unhighlight-once)
20078 (org-unhighlight))
20080 (defun org-agenda-follow-mode ()
20081 "Toggle follow mode in an agenda buffer."
20082 (interactive)
20083 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
20084 (org-agenda-set-mode-name)
20085 (message "Follow mode is %s"
20086 (if org-agenda-follow-mode "on" "off")))
20088 (defun org-agenda-log-mode ()
20089 "Toggle log mode in an agenda buffer."
20090 (interactive)
20091 (org-agenda-check-type t 'agenda 'timeline)
20092 (setq org-agenda-show-log (not org-agenda-show-log))
20093 (org-agenda-set-mode-name)
20094 (org-agenda-redo)
20095 (message "Log mode is %s"
20096 (if org-agenda-show-log "on" "off")))
20098 (defun org-agenda-toggle-diary ()
20099 "Toggle diary inclusion in an agenda buffer."
20100 (interactive)
20101 (org-agenda-check-type t 'agenda)
20102 (setq org-agenda-include-diary (not org-agenda-include-diary))
20103 (org-agenda-redo)
20104 (org-agenda-set-mode-name)
20105 (message "Diary inclusion turned %s"
20106 (if org-agenda-include-diary "on" "off")))
20108 (defun org-agenda-toggle-time-grid ()
20109 "Toggle time grid in an agenda buffer."
20110 (interactive)
20111 (org-agenda-check-type t 'agenda)
20112 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
20113 (org-agenda-redo)
20114 (org-agenda-set-mode-name)
20115 (message "Time-grid turned %s"
20116 (if org-agenda-use-time-grid "on" "off")))
20118 (defun org-agenda-set-mode-name ()
20119 "Set the mode name to indicate all the small mode settings."
20120 (setq mode-name
20121 (concat "Org-Agenda"
20122 (if (equal org-agenda-ndays 1) " Day" "")
20123 (if (equal org-agenda-ndays 7) " Week" "")
20124 (if org-agenda-follow-mode " Follow" "")
20125 (if org-agenda-include-diary " Diary" "")
20126 (if org-agenda-use-time-grid " Grid" "")
20127 (if org-agenda-show-log " Log" "")))
20128 (force-mode-line-update))
20130 (defun org-agenda-post-command-hook ()
20131 (and (eolp) (not (bolp)) (backward-char 1))
20132 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20133 (if (and org-agenda-follow-mode
20134 (get-text-property (point) 'org-marker))
20135 (org-agenda-show)))
20137 (defun org-agenda-show-priority ()
20138 "Show the priority of the current item.
20139 This priority is composed of the main priority given with the [#A] cookies,
20140 and by additional input from the age of a schedules or deadline entry."
20141 (interactive)
20142 (let* ((pri (get-text-property (point-at-bol) 'priority)))
20143 (message "Priority is %d" (if pri pri -1000))))
20145 (defun org-agenda-show-tags ()
20146 "Show the tags applicable to the current item."
20147 (interactive)
20148 (let* ((tags (get-text-property (point-at-bol) 'tags)))
20149 (if tags
20150 (message "Tags are :%s:"
20151 (org-no-properties (mapconcat 'identity tags ":")))
20152 (message "No tags associated with this line"))))
20154 (defun org-agenda-goto (&optional highlight)
20155 "Go to the Org-mode file which contains the item at point."
20156 (interactive)
20157 (let* ((marker (or (get-text-property (point) 'org-marker)
20158 (org-agenda-error)))
20159 (buffer (marker-buffer marker))
20160 (pos (marker-position marker)))
20161 (switch-to-buffer-other-window buffer)
20162 (widen)
20163 (goto-char pos)
20164 (when (org-mode-p)
20165 (org-show-context 'agenda)
20166 (save-excursion
20167 (and (outline-next-heading)
20168 (org-flag-heading nil)))) ; show the next heading
20169 (run-hooks 'org-agenda-after-show-hook)
20170 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
20172 (defvar org-agenda-after-show-hook nil
20173 "Normal hook run after an item has been shown from the agenda.
20174 Point is in the buffer where the item originated.")
20176 (defun org-agenda-kill ()
20177 "Kill the entry or subtree belonging to the current agenda entry."
20178 (interactive)
20179 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
20180 (let* ((marker (or (get-text-property (point) 'org-marker)
20181 (org-agenda-error)))
20182 (buffer (marker-buffer marker))
20183 (pos (marker-position marker))
20184 (type (get-text-property (point) 'type))
20185 dbeg dend (n 0) conf)
20186 (org-with-remote-undo buffer
20187 (with-current-buffer buffer
20188 (save-excursion
20189 (goto-char pos)
20190 (if (and (org-mode-p) (not (member type '("sexp"))))
20191 (setq dbeg (progn (org-back-to-heading t) (point))
20192 dend (org-end-of-subtree t t))
20193 (setq dbeg (point-at-bol)
20194 dend (min (point-max) (1+ (point-at-eol)))))
20195 (goto-char dbeg)
20196 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
20197 (setq conf (or (eq t org-agenda-confirm-kill)
20198 (and (numberp org-agenda-confirm-kill)
20199 (> n org-agenda-confirm-kill))))
20200 (and conf
20201 (not (y-or-n-p
20202 (format "Delete entry with %d lines in buffer \"%s\"? "
20203 n (buffer-name buffer))))
20204 (error "Abort"))
20205 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
20206 (with-current-buffer buffer (delete-region dbeg dend))
20207 (message "Agenda item and source killed"))))
20209 (defun org-agenda-archive ()
20210 "Kill the entry or subtree belonging to the current agenda entry."
20211 (interactive)
20212 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
20213 (let* ((marker (or (get-text-property (point) 'org-marker)
20214 (org-agenda-error)))
20215 (buffer (marker-buffer marker))
20216 (pos (marker-position marker)))
20217 (org-with-remote-undo buffer
20218 (with-current-buffer buffer
20219 (if (org-mode-p)
20220 (save-excursion
20221 (goto-char pos)
20222 (org-remove-subtree-entries-from-agenda)
20223 (org-back-to-heading t)
20224 (org-archive-subtree))
20225 (error "Archiving works only in Org-mode files"))))))
20227 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
20228 "Remove all lines in the agenda that correspond to a given subtree.
20229 The subtree is the one in buffer BUF, starting at BEG and ending at END.
20230 If this information is not given, the function uses the tree at point."
20231 (let ((buf (or buf (current-buffer))) m p)
20232 (save-excursion
20233 (unless (and beg end)
20234 (org-back-to-heading t)
20235 (setq beg (point))
20236 (org-end-of-subtree t)
20237 (setq end (point)))
20238 (set-buffer (get-buffer org-agenda-buffer-name))
20239 (save-excursion
20240 (goto-char (point-max))
20241 (beginning-of-line 1)
20242 (while (not (bobp))
20243 (when (and (setq m (get-text-property (point) 'org-marker))
20244 (equal buf (marker-buffer m))
20245 (setq p (marker-position m))
20246 (>= p beg)
20247 (<= p end))
20248 (let ((inhibit-read-only t))
20249 (delete-region (point-at-bol) (1+ (point-at-eol)))))
20250 (beginning-of-line 0))))))
20252 (defun org-agenda-open-link ()
20253 "Follow the link in the current line, if any."
20254 (interactive)
20255 (let ((eol (point-at-eol)))
20256 (save-excursion
20257 (if (or (re-search-forward org-bracket-link-regexp eol t)
20258 (re-search-forward org-angle-link-re eol t)
20259 (re-search-forward org-plain-link-re eol t))
20260 (call-interactively 'org-open-at-point)
20261 (error "No link in current line")))))
20263 (defun org-agenda-switch-to (&optional delete-other-windows)
20264 "Go to the Org-mode file which contains the item at point."
20265 (interactive)
20266 (let* ((marker (or (get-text-property (point) 'org-marker)
20267 (org-agenda-error)))
20268 (buffer (marker-buffer marker))
20269 (pos (marker-position marker)))
20270 (switch-to-buffer buffer)
20271 (and delete-other-windows (delete-other-windows))
20272 (widen)
20273 (goto-char pos)
20274 (when (org-mode-p)
20275 (org-show-context 'agenda)
20276 (save-excursion
20277 (and (outline-next-heading)
20278 (org-flag-heading nil)))))) ; show the next heading
20280 (defun org-agenda-goto-mouse (ev)
20281 "Go to the Org-mode file which contains the item at the mouse click."
20282 (interactive "e")
20283 (mouse-set-point ev)
20284 (org-agenda-goto))
20286 (defun org-agenda-show ()
20287 "Display the Org-mode file which contains the item at point."
20288 (interactive)
20289 (let ((win (selected-window)))
20290 (org-agenda-goto t)
20291 (select-window win)))
20293 (defun org-agenda-recenter (arg)
20294 "Display the Org-mode file which contains the item at point and recenter."
20295 (interactive "P")
20296 (let ((win (selected-window)))
20297 (org-agenda-goto t)
20298 (recenter arg)
20299 (select-window win)))
20301 (defun org-agenda-show-mouse (ev)
20302 "Display the Org-mode file which contains the item at the mouse click."
20303 (interactive "e")
20304 (mouse-set-point ev)
20305 (org-agenda-show))
20307 (defun org-agenda-check-no-diary ()
20308 "Check if the entry is a diary link and abort if yes."
20309 (if (get-text-property (point) 'org-agenda-diary-link)
20310 (org-agenda-error)))
20312 (defun org-agenda-error ()
20313 (error "Command not allowed in this line"))
20315 (defun org-agenda-tree-to-indirect-buffer ()
20316 "Show the subtree corresponding to the current entry in an indirect buffer.
20317 This calls the command `org-tree-to-indirect-buffer' from the original
20318 Org-mode buffer.
20319 With numerical prefix arg ARG, go up to this level and then take that tree.
20320 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
20321 dedicated frame)."
20322 (interactive)
20323 (org-agenda-check-no-diary)
20324 (let* ((marker (or (get-text-property (point) 'org-marker)
20325 (org-agenda-error)))
20326 (buffer (marker-buffer marker))
20327 (pos (marker-position marker)))
20328 (with-current-buffer buffer
20329 (save-excursion
20330 (goto-char pos)
20331 (call-interactively 'org-tree-to-indirect-buffer)))))
20333 (defvar org-last-heading-marker (make-marker)
20334 "Marker pointing to the headline that last changed its TODO state
20335 by a remote command from the agenda.")
20337 (defun org-agenda-todo-nextset ()
20338 "Switch TODO entry to next sequence."
20339 (interactive)
20340 (org-agenda-todo 'nextset))
20342 (defun org-agenda-todo-previousset ()
20343 "Switch TODO entry to previous sequence."
20344 (interactive)
20345 (org-agenda-todo 'previousset))
20347 (defun org-agenda-todo (&optional arg)
20348 "Cycle TODO state of line at point, also in Org-mode file.
20349 This changes the line at point, all other lines in the agenda referring to
20350 the same tree node, and the headline of the tree node in the Org-mode file."
20351 (interactive "P")
20352 (org-agenda-check-no-diary)
20353 (let* ((col (current-column))
20354 (marker (or (get-text-property (point) 'org-marker)
20355 (org-agenda-error)))
20356 (buffer (marker-buffer marker))
20357 (pos (marker-position marker))
20358 (hdmarker (get-text-property (point) 'org-hd-marker))
20359 (inhibit-read-only t)
20360 newhead)
20361 (org-with-remote-undo buffer
20362 (with-current-buffer buffer
20363 (widen)
20364 (goto-char pos)
20365 (org-show-context 'agenda)
20366 (save-excursion
20367 (and (outline-next-heading)
20368 (org-flag-heading nil))) ; show the next heading
20369 (org-todo arg)
20370 (and (bolp) (forward-char 1))
20371 (setq newhead (org-get-heading))
20372 (save-excursion
20373 (org-back-to-heading)
20374 (move-marker org-last-heading-marker (point))))
20375 (beginning-of-line 1)
20376 (save-excursion
20377 (org-agenda-change-all-lines newhead hdmarker 'fixface))
20378 (move-to-column col))))
20380 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
20381 "Change all lines in the agenda buffer which match HDMARKER.
20382 The new content of the line will be NEWHEAD (as modified by
20383 `org-format-agenda-item'). HDMARKER is checked with
20384 `equal' against all `org-hd-marker' text properties in the file.
20385 If FIXFACE is non-nil, the face of each item is modified acording to
20386 the new TODO state."
20387 (let* ((inhibit-read-only t)
20388 props m pl undone-face done-face finish new dotime cat tags)
20389 (save-excursion
20390 (goto-char (point-max))
20391 (beginning-of-line 1)
20392 (while (not finish)
20393 (setq finish (bobp))
20394 (when (and (setq m (get-text-property (point) 'org-hd-marker))
20395 (equal m hdmarker))
20396 (setq props (text-properties-at (point))
20397 dotime (get-text-property (point) 'dotime)
20398 cat (get-text-property (point) 'org-category)
20399 tags (get-text-property (point) 'tags)
20400 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
20401 pl (get-text-property (point) 'prefix-length)
20402 undone-face (get-text-property (point) 'undone-face)
20403 done-face (get-text-property (point) 'done-face))
20404 (move-to-column pl)
20405 (cond
20406 ((equal new "")
20407 (beginning-of-line 1)
20408 (and (looking-at ".*\n?") (replace-match "")))
20409 ((looking-at ".*")
20410 (replace-match new t t)
20411 (beginning-of-line 1)
20412 (add-text-properties (point-at-bol) (point-at-eol) props)
20413 (when fixface
20414 (add-text-properties
20415 (point-at-bol) (point-at-eol)
20416 (list 'face
20417 (if org-last-todo-state-is-todo
20418 undone-face done-face))))
20419 (org-agenda-highlight-todo 'line)
20420 (beginning-of-line 1))
20421 (t (error "Line update did not work"))))
20422 (beginning-of-line 0)))
20423 (org-finalize-agenda)))
20425 (defun org-agenda-align-tags (&optional line)
20426 "Align all tags in agenda items to `org-agenda-tags-column'."
20427 (let ((inhibit-read-only t) l c)
20428 (save-excursion
20429 (goto-char (if line (point-at-bol) (point-min)))
20430 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
20431 (if line (point-at-eol) nil) t)
20432 (add-text-properties
20433 (match-beginning 2) (match-end 2)
20434 (list 'face (list 'org-tag (get-text-property
20435 (match-beginning 2) 'face))))
20436 (setq l (- (match-end 2) (match-beginning 2))
20437 c (if (< org-agenda-tags-column 0)
20438 (- (abs org-agenda-tags-column) l)
20439 org-agenda-tags-column))
20440 (delete-region (match-beginning 1) (match-end 1))
20441 (goto-char (match-beginning 1))
20442 (insert (org-add-props
20443 (make-string (max 1 (- c (current-column))) ?\ )
20444 (text-properties-at (point))))))))
20446 (defun org-agenda-priority-up ()
20447 "Increase the priority of line at point, also in Org-mode file."
20448 (interactive)
20449 (org-agenda-priority 'up))
20451 (defun org-agenda-priority-down ()
20452 "Decrease the priority of line at point, also in Org-mode file."
20453 (interactive)
20454 (org-agenda-priority 'down))
20456 (defun org-agenda-priority (&optional force-direction)
20457 "Set the priority of line at point, also in Org-mode file.
20458 This changes the line at point, all other lines in the agenda referring to
20459 the same tree node, and the headline of the tree node in the Org-mode file."
20460 (interactive)
20461 (org-agenda-check-no-diary)
20462 (let* ((marker (or (get-text-property (point) 'org-marker)
20463 (org-agenda-error)))
20464 (hdmarker (get-text-property (point) 'org-hd-marker))
20465 (buffer (marker-buffer hdmarker))
20466 (pos (marker-position hdmarker))
20467 (inhibit-read-only t)
20468 newhead)
20469 (org-with-remote-undo buffer
20470 (with-current-buffer buffer
20471 (widen)
20472 (goto-char pos)
20473 (org-show-context 'agenda)
20474 (save-excursion
20475 (and (outline-next-heading)
20476 (org-flag-heading nil))) ; show the next heading
20477 (funcall 'org-priority force-direction)
20478 (end-of-line 1)
20479 (setq newhead (org-get-heading)))
20480 (org-agenda-change-all-lines newhead hdmarker)
20481 (beginning-of-line 1))))
20483 (defun org-get-tags-at (&optional pos)
20484 "Get a list of all headline tags applicable at POS.
20485 POS defaults to point. If tags are inherited, the list contains
20486 the targets in the same sequence as the headlines appear, i.e.
20487 the tags of the current headline come last."
20488 (interactive)
20489 (let (tags lastpos)
20490 (save-excursion
20491 (save-restriction
20492 (widen)
20493 (goto-char (or pos (point)))
20494 (save-match-data
20495 (org-back-to-heading t)
20496 (condition-case nil
20497 (while (not (equal lastpos (point)))
20498 (setq lastpos (point))
20499 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
20500 (setq tags (append (org-split-string
20501 (org-match-string-no-properties 1) ":")
20502 tags)))
20503 (or org-use-tag-inheritance (error ""))
20504 (org-up-heading-all 1))
20505 (error nil))))
20506 tags)))
20508 ;; FIXME: should fix the tags property of the agenda line.
20509 (defun org-agenda-set-tags ()
20510 "Set tags for the current headline."
20511 (interactive)
20512 (org-agenda-check-no-diary)
20513 (if (and (org-region-active-p) (interactive-p))
20514 (call-interactively 'org-change-tag-in-region)
20515 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
20516 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
20517 (org-agenda-error)))
20518 (buffer (marker-buffer hdmarker))
20519 (pos (marker-position hdmarker))
20520 (inhibit-read-only t)
20521 newhead)
20522 (org-with-remote-undo buffer
20523 (with-current-buffer buffer
20524 (widen)
20525 (goto-char pos)
20526 (save-excursion
20527 (org-show-context 'agenda))
20528 (save-excursion
20529 (and (outline-next-heading)
20530 (org-flag-heading nil))) ; show the next heading
20531 (goto-char pos)
20532 (call-interactively 'org-set-tags)
20533 (end-of-line 1)
20534 (setq newhead (org-get-heading)))
20535 (org-agenda-change-all-lines newhead hdmarker)
20536 (beginning-of-line 1)))))
20538 (defun org-agenda-toggle-archive-tag ()
20539 "Toggle the archive tag for the current entry."
20540 (interactive)
20541 (org-agenda-check-no-diary)
20542 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
20543 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
20544 (org-agenda-error)))
20545 (buffer (marker-buffer hdmarker))
20546 (pos (marker-position hdmarker))
20547 (inhibit-read-only t)
20548 newhead)
20549 (org-with-remote-undo buffer
20550 (with-current-buffer buffer
20551 (widen)
20552 (goto-char pos)
20553 (org-show-context 'agenda)
20554 (save-excursion
20555 (and (outline-next-heading)
20556 (org-flag-heading nil))) ; show the next heading
20557 (call-interactively 'org-toggle-archive-tag)
20558 (end-of-line 1)
20559 (setq newhead (org-get-heading)))
20560 (org-agenda-change-all-lines newhead hdmarker)
20561 (beginning-of-line 1))))
20563 (defun org-agenda-date-later (arg &optional what)
20564 "Change the date of this item to one day later."
20565 (interactive "p")
20566 (org-agenda-check-type t 'agenda 'timeline)
20567 (org-agenda-check-no-diary)
20568 (let* ((marker (or (get-text-property (point) 'org-marker)
20569 (org-agenda-error)))
20570 (buffer (marker-buffer marker))
20571 (pos (marker-position marker)))
20572 (org-with-remote-undo buffer
20573 (with-current-buffer buffer
20574 (widen)
20575 (goto-char pos)
20576 (if (not (org-at-timestamp-p))
20577 (error "Cannot find time stamp"))
20578 (org-timestamp-change arg (or what 'day)))
20579 (org-agenda-show-new-time marker org-last-changed-timestamp))
20580 (message "Time stamp changed to %s" org-last-changed-timestamp)))
20582 (defun org-agenda-date-earlier (arg &optional what)
20583 "Change the date of this item to one day earlier."
20584 (interactive "p")
20585 (org-agenda-date-later (- arg) what))
20587 (defun org-agenda-show-new-time (marker stamp &optional prefix)
20588 "Show new date stamp via text properties."
20589 ;; We use text properties to make this undoable
20590 (let ((inhibit-read-only t))
20591 (setq stamp (concat " " prefix " => " stamp))
20592 (save-excursion
20593 (goto-char (point-max))
20594 (while (not (bobp))
20595 (when (equal marker (get-text-property (point) 'org-marker))
20596 (move-to-column (- (window-width) (length stamp)) t)
20597 (if (featurep 'xemacs)
20598 ;; Use `duplicable' property to trigger undo recording
20599 (let ((ex (make-extent nil nil))
20600 (gl (make-glyph stamp)))
20601 (set-glyph-face gl 'secondary-selection)
20602 (set-extent-properties
20603 ex (list 'invisible t 'end-glyph gl 'duplicable t))
20604 (insert-extent ex (1- (point)) (point-at-eol)))
20605 (add-text-properties
20606 (1- (point)) (point-at-eol)
20607 (list 'display (org-add-props stamp nil
20608 'face 'secondary-selection))))
20609 (beginning-of-line 1))
20610 (beginning-of-line 0)))))
20612 (defun org-agenda-date-prompt (arg)
20613 "Change the date of this item. Date is prompted for, with default today.
20614 The prefix ARG is passed to the `org-time-stamp' command and can therefore
20615 be used to request time specification in the time stamp."
20616 (interactive "P")
20617 (org-agenda-check-type t 'agenda 'timeline)
20618 (org-agenda-check-no-diary)
20619 (let* ((marker (or (get-text-property (point) 'org-marker)
20620 (org-agenda-error)))
20621 (buffer (marker-buffer marker))
20622 (pos (marker-position marker)))
20623 (org-with-remote-undo buffer
20624 (with-current-buffer buffer
20625 (widen)
20626 (goto-char pos)
20627 (if (not (org-at-timestamp-p))
20628 (error "Cannot find time stamp"))
20629 (org-time-stamp arg)
20630 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
20632 (defun org-agenda-schedule (arg)
20633 "Schedule the item at point."
20634 (interactive "P")
20635 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
20636 (org-agenda-check-no-diary)
20637 (let* ((marker (or (get-text-property (point) 'org-marker)
20638 (org-agenda-error)))
20639 (buffer (marker-buffer marker))
20640 (pos (marker-position marker))
20641 (org-insert-labeled-timestamps-at-point nil)
20643 (org-with-remote-undo buffer
20644 (with-current-buffer buffer
20645 (widen)
20646 (goto-char pos)
20647 (setq ts (org-schedule arg)))
20648 (org-agenda-show-new-time marker ts "S"))
20649 (message "Item scheduled for %s" ts)))
20651 (defun org-agenda-deadline (arg)
20652 "Schedule the item at point."
20653 (interactive "P")
20654 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
20655 (org-agenda-check-no-diary)
20656 (let* ((marker (or (get-text-property (point) 'org-marker)
20657 (org-agenda-error)))
20658 (buffer (marker-buffer marker))
20659 (pos (marker-position marker))
20660 (org-insert-labeled-timestamps-at-point nil)
20662 (org-with-remote-undo buffer
20663 (with-current-buffer buffer
20664 (widen)
20665 (goto-char pos)
20666 (setq ts (org-deadline arg)))
20667 (org-agenda-show-new-time marker ts "S"))
20668 (message "Deadline for this item set to %s" ts)))
20670 (defun org-get-heading (&optional no-tags)
20671 "Return the heading of the current entry, without the stars."
20672 (save-excursion
20673 (org-back-to-heading t)
20674 (if (looking-at
20675 (if no-tags
20676 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
20677 "\\*+[ \t]+\\([^\r\n]*\\)"))
20678 (match-string 1) "")))
20680 (defun org-agenda-clock-in (&optional arg)
20681 "Start the clock on the currently selected item."
20682 (interactive "P")
20683 (org-agenda-check-no-diary)
20684 (let* ((marker (or (get-text-property (point) 'org-marker)
20685 (org-agenda-error)))
20686 (pos (marker-position marker)))
20687 (org-with-remote-undo (marker-buffer marker)
20688 (with-current-buffer (marker-buffer marker)
20689 (widen)
20690 (goto-char pos)
20691 (org-clock-in)))))
20693 (defun org-agenda-clock-out (&optional arg)
20694 "Stop the currently running clock."
20695 (interactive "P")
20696 (unless (marker-buffer org-clock-marker)
20697 (error "No running clock"))
20698 (org-with-remote-undo (marker-buffer org-clock-marker)
20699 (org-clock-out)))
20701 (defun org-agenda-clock-cancel (&optional arg)
20702 "Cancel the currently running clock."
20703 (interactive "P")
20704 (unless (marker-buffer org-clock-marker)
20705 (error "No running clock"))
20706 (org-with-remote-undo (marker-buffer org-clock-marker)
20707 (org-clock-cancel)))
20709 (defun org-agenda-diary-entry ()
20710 "Make a diary entry, like the `i' command from the calendar.
20711 All the standard commands work: block, weekly etc."
20712 (interactive)
20713 (org-agenda-check-type t 'agenda 'timeline)
20714 (require 'diary-lib)
20715 (let* ((char (progn
20716 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
20717 (read-char-exclusive)))
20718 (cmd (cdr (assoc char
20719 '((?d . insert-diary-entry)
20720 (?w . insert-weekly-diary-entry)
20721 (?m . insert-monthly-diary-entry)
20722 (?y . insert-yearly-diary-entry)
20723 (?a . insert-anniversary-diary-entry)
20724 (?b . insert-block-diary-entry)
20725 (?c . insert-cyclic-diary-entry)))))
20726 (oldf (symbol-function 'calendar-cursor-to-date))
20727 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
20728 (point (point))
20729 (mark (or (mark t) (point))))
20730 (unless cmd
20731 (error "No command associated with <%c>" char))
20732 (unless (and (get-text-property point 'day)
20733 (or (not (equal ?b char))
20734 (get-text-property mark 'day)))
20735 (error "Don't know which date to use for diary entry"))
20736 ;; We implement this by hacking the `calendar-cursor-to-date' function
20737 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
20738 (let ((calendar-mark-ring
20739 (list (calendar-gregorian-from-absolute
20740 (or (get-text-property mark 'day)
20741 (get-text-property point 'day))))))
20742 (unwind-protect
20743 (progn
20744 (fset 'calendar-cursor-to-date
20745 (lambda (&optional error)
20746 (calendar-gregorian-from-absolute
20747 (get-text-property point 'day))))
20748 (call-interactively cmd))
20749 (fset 'calendar-cursor-to-date oldf)))))
20752 (defun org-agenda-execute-calendar-command (cmd)
20753 "Execute a calendar command from the agenda, with the date associated to
20754 the cursor position."
20755 (org-agenda-check-type t 'agenda 'timeline)
20756 (require 'diary-lib)
20757 (unless (get-text-property (point) 'day)
20758 (error "Don't know which date to use for calendar command"))
20759 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
20760 (point (point))
20761 (date (calendar-gregorian-from-absolute
20762 (get-text-property point 'day)))
20763 ;; the following 3 vars are needed in the calendar
20764 (displayed-day (extract-calendar-day date))
20765 (displayed-month (extract-calendar-month date))
20766 (displayed-year (extract-calendar-year date)))
20767 (unwind-protect
20768 (progn
20769 (fset 'calendar-cursor-to-date
20770 (lambda (&optional error)
20771 (calendar-gregorian-from-absolute
20772 (get-text-property point 'day))))
20773 (call-interactively cmd))
20774 (fset 'calendar-cursor-to-date oldf))))
20776 (defun org-agenda-phases-of-moon ()
20777 "Display the phases of the moon for the 3 months around the cursor date."
20778 (interactive)
20779 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
20781 (defun org-agenda-holidays ()
20782 "Display the holidays for the 3 months around the cursor date."
20783 (interactive)
20784 (org-agenda-execute-calendar-command 'list-calendar-holidays))
20786 (defun org-agenda-sunrise-sunset (arg)
20787 "Display sunrise and sunset for the cursor date.
20788 Latitude and longitude can be specified with the variables
20789 `calendar-latitude' and `calendar-longitude'. When called with prefix
20790 argument, latitude and longitude will be prompted for."
20791 (interactive "P")
20792 (let ((calendar-longitude (if arg nil calendar-longitude))
20793 (calendar-latitude (if arg nil calendar-latitude))
20794 (calendar-location-name
20795 (if arg "the given coordinates" calendar-location-name)))
20796 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
20798 (defun org-agenda-goto-calendar ()
20799 "Open the Emacs calendar with the date at the cursor."
20800 (interactive)
20801 (org-agenda-check-type t 'agenda 'timeline)
20802 (let* ((day (or (get-text-property (point) 'day)
20803 (error "Don't know which date to open in calendar")))
20804 (date (calendar-gregorian-from-absolute day))
20805 (calendar-move-hook nil)
20806 (view-calendar-holidays-initially nil)
20807 (view-diary-entries-initially nil))
20808 (calendar)
20809 (calendar-goto-date date)))
20811 (defun org-calendar-goto-agenda ()
20812 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
20813 This is a command that has to be installed in `calendar-mode-map'."
20814 (interactive)
20815 (org-agenda-list nil (calendar-absolute-from-gregorian
20816 (calendar-cursor-to-date))
20817 nil))
20819 (defun org-agenda-convert-date ()
20820 (interactive)
20821 (org-agenda-check-type t 'agenda 'timeline)
20822 (let ((day (get-text-property (point) 'day))
20823 date s)
20824 (unless day
20825 (error "Don't know which date to convert"))
20826 (setq date (calendar-gregorian-from-absolute day))
20827 (setq s (concat
20828 "Gregorian: " (calendar-date-string date) "\n"
20829 "ISO: " (calendar-iso-date-string date) "\n"
20830 "Day of Yr: " (calendar-day-of-year-string date) "\n"
20831 "Julian: " (calendar-julian-date-string date) "\n"
20832 "Astron. JD: " (calendar-astro-date-string date)
20833 " (Julian date number at noon UTC)\n"
20834 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
20835 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
20836 "French: " (calendar-french-date-string date) "\n"
20837 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
20838 "Mayan: " (calendar-mayan-date-string date) "\n"
20839 "Coptic: " (calendar-coptic-date-string date) "\n"
20840 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
20841 "Persian: " (calendar-persian-date-string date) "\n"
20842 "Chinese: " (calendar-chinese-date-string date) "\n"))
20843 (with-output-to-temp-buffer "*Dates*"
20844 (princ s))
20845 (if (fboundp 'fit-window-to-buffer)
20846 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
20849 ;;;; Embedded LaTeX
20851 (defvar org-cdlatex-mode-map (make-sparse-keymap)
20852 "Keymap for the minor `org-cdlatex-mode'.")
20854 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
20855 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
20856 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
20857 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
20858 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
20860 (defvar org-cdlatex-texmathp-advice-is-done nil
20861 "Flag remembering if we have applied the advice to texmathp already.")
20863 (define-minor-mode org-cdlatex-mode
20864 "Toggle the minor `org-cdlatex-mode'.
20865 This mode supports entering LaTeX environment and math in LaTeX fragments
20866 in Org-mode.
20867 \\{org-cdlatex-mode-map}"
20868 nil " OCDL" nil
20869 (when org-cdlatex-mode (require 'cdlatex))
20870 (unless org-cdlatex-texmathp-advice-is-done
20871 (setq org-cdlatex-texmathp-advice-is-done t)
20872 (defadvice texmathp (around org-math-always-on activate)
20873 "Always return t in org-mode buffers.
20874 This is because we want to insert math symbols without dollars even outside
20875 the LaTeX math segments. If Orgmode thinks that point is actually inside
20876 en embedded LaTeX fragement, let texmathp do its job.
20877 \\[org-cdlatex-mode-map]"
20878 (interactive)
20879 (let (p)
20880 (cond
20881 ((not (org-mode-p)) ad-do-it)
20882 ((eq this-command 'cdlatex-math-symbol)
20883 (setq ad-return-value t
20884 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
20886 (let ((p (org-inside-LaTeX-fragment-p)))
20887 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
20888 (setq ad-return-value t
20889 texmathp-why '("Org-mode embedded math" . 0))
20890 (if p ad-do-it)))))))))
20892 (defun turn-on-org-cdlatex ()
20893 "Unconditionally turn on `org-cdlatex-mode'."
20894 (org-cdlatex-mode 1))
20896 (defun org-inside-LaTeX-fragment-p ()
20897 "Test if point is inside a LaTeX fragment.
20898 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
20899 sequence appearing also before point.
20900 Even though the matchers for math are configurable, this function assumes
20901 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
20902 delimiters are skipped when they have been removed by customization.
20903 The return value is nil, or a cons cell with the delimiter and
20904 and the position of this delimiter.
20906 This function does a reasonably good job, but can locally be fooled by
20907 for example currency specifications. For example it will assume being in
20908 inline math after \"$22.34\". The LaTeX fragment formatter will only format
20909 fragments that are properly closed, but during editing, we have to live
20910 with the uncertainty caused by missing closing delimiters. This function
20911 looks only before point, not after."
20912 (catch 'exit
20913 (let ((pos (point))
20914 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
20915 (lim (progn
20916 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
20917 (point)))
20918 dd-on str (start 0) m re)
20919 (goto-char pos)
20920 (when dodollar
20921 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
20922 re (nth 1 (assoc "$" org-latex-regexps)))
20923 (while (string-match re str start)
20924 (cond
20925 ((= (match-end 0) (length str))
20926 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
20927 ((= (match-end 0) (- (length str) 5))
20928 (throw 'exit nil))
20929 (t (setq start (match-end 0))))))
20930 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
20931 (goto-char pos)
20932 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
20933 (and (match-beginning 2) (throw 'exit nil))
20934 ;; count $$
20935 (while (re-search-backward "\\$\\$" lim t)
20936 (setq dd-on (not dd-on)))
20937 (goto-char pos)
20938 (if dd-on (cons "$$" m))))))
20941 (defun org-try-cdlatex-tab ()
20942 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
20943 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
20944 - inside a LaTeX fragment, or
20945 - after the first word in a line, where an abbreviation expansion could
20946 insert a LaTeX environment."
20947 (when org-cdlatex-mode
20948 (cond
20949 ((save-excursion
20950 (skip-chars-backward "a-zA-Z0-9*")
20951 (skip-chars-backward " \t")
20952 (bolp))
20953 (cdlatex-tab) t)
20954 ((org-inside-LaTeX-fragment-p)
20955 (cdlatex-tab) t)
20956 (t nil))))
20958 (defun org-cdlatex-underscore-caret (&optional arg)
20959 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
20960 Revert to the normal definition outside of these fragments."
20961 (interactive "P")
20962 (if (org-inside-LaTeX-fragment-p)
20963 (call-interactively 'cdlatex-sub-superscript)
20964 (let (org-cdlatex-mode)
20965 (call-interactively (key-binding (vector last-input-event))))))
20967 (defun org-cdlatex-math-modify (&optional arg)
20968 "Execute `cdlatex-math-modify' in LaTeX fragments.
20969 Revert to the normal definition outside of these fragments."
20970 (interactive "P")
20971 (if (org-inside-LaTeX-fragment-p)
20972 (call-interactively 'cdlatex-math-modify)
20973 (let (org-cdlatex-mode)
20974 (call-interactively (key-binding (vector last-input-event))))))
20976 (defvar org-latex-fragment-image-overlays nil
20977 "List of overlays carrying the images of latex fragments.")
20978 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
20980 (defun org-remove-latex-fragment-image-overlays ()
20981 "Remove all overlays with LaTeX fragment images in current buffer."
20982 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
20983 (setq org-latex-fragment-image-overlays nil))
20985 (defun org-preview-latex-fragment (&optional subtree)
20986 "Preview the LaTeX fragment at point, or all locally or globally.
20987 If the cursor is in a LaTeX fragment, create the image and overlay
20988 it over the source code. If there is no fragment at point, display
20989 all fragments in the current text, from one headline to the next. With
20990 prefix SUBTREE, display all fragments in the current subtree. With a
20991 double prefix `C-u C-u', or when the cursor is before the first headline,
20992 display all fragments in the buffer.
20993 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
20994 (interactive "P")
20995 (org-remove-latex-fragment-image-overlays)
20996 (save-excursion
20997 (save-restriction
20998 (let (beg end at msg)
20999 (cond
21000 ((or (equal subtree '(16))
21001 (not (save-excursion
21002 (re-search-backward (concat "^" outline-regexp) nil t))))
21003 (setq beg (point-min) end (point-max)
21004 msg "Creating images for buffer...%s"))
21005 ((equal subtree '(4))
21006 (org-back-to-heading)
21007 (setq beg (point) end (org-end-of-subtree t)
21008 msg "Creating images for subtree...%s"))
21010 (if (setq at (org-inside-LaTeX-fragment-p))
21011 (goto-char (max (point-min) (- (cdr at) 2)))
21012 (org-back-to-heading))
21013 (setq beg (point) end (progn (outline-next-heading) (point))
21014 msg (if at "Creating image...%s"
21015 "Creating images for entry...%s"))))
21016 (message msg "")
21017 (narrow-to-region beg end)
21018 (goto-char beg)
21019 (org-format-latex
21020 (concat "ltxpng/" (file-name-sans-extension
21021 (file-name-nondirectory
21022 buffer-file-name)))
21023 default-directory 'overlays msg at 'forbuffer)
21024 (message msg "done. Use `C-c C-c' to remove images.")))))
21026 (defvar org-latex-regexps
21027 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
21028 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
21029 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
21030 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
21031 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
21032 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
21033 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
21034 "Regular expressions for matching embedded LaTeX.")
21036 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
21037 "Replace LaTeX fragments with links to an image, and produce images."
21038 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
21039 (let* ((prefixnodir (file-name-nondirectory prefix))
21040 (absprefix (expand-file-name prefix dir))
21041 (todir (file-name-directory absprefix))
21042 (opt org-format-latex-options)
21043 (matchers (plist-get opt :matchers))
21044 (re-list org-latex-regexps)
21045 (cnt 0) txt link beg end re e checkdir
21046 m n block linkfile movefile ov)
21047 ;; Check if there are old images files with this prefix, and remove them
21048 (when (file-directory-p todir)
21049 (mapc 'delete-file
21050 (directory-files
21051 todir 'full
21052 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
21053 ;; Check the different regular expressions
21054 (while (setq e (pop re-list))
21055 (setq m (car e) re (nth 1 e) n (nth 2 e)
21056 block (if (nth 3 e) "\n\n" ""))
21057 (when (member m matchers)
21058 (goto-char (point-min))
21059 (while (re-search-forward re nil t)
21060 (when (or (not at) (equal (cdr at) (match-beginning n)))
21061 (setq txt (match-string n)
21062 beg (match-beginning n) end (match-end n)
21063 cnt (1+ cnt)
21064 linkfile (format "%s_%04d.png" prefix cnt)
21065 movefile (format "%s_%04d.png" absprefix cnt)
21066 link (concat block "[[file:" linkfile "]]" block))
21067 (if msg (message msg cnt))
21068 (goto-char beg)
21069 (unless checkdir ; make sure the directory exists
21070 (setq checkdir t)
21071 (or (file-directory-p todir) (make-directory todir)))
21072 (org-create-formula-image
21073 txt movefile opt forbuffer)
21074 (if overlays
21075 (progn
21076 (setq ov (org-make-overlay beg end))
21077 (if (featurep 'xemacs)
21078 (progn
21079 (org-overlay-put ov 'invisible t)
21080 (org-overlay-put
21081 ov 'end-glyph
21082 (make-glyph (vector 'png :file movefile))))
21083 (org-overlay-put
21084 ov 'display
21085 (list 'image :type 'png :file movefile :ascent 'center)))
21086 (push ov org-latex-fragment-image-overlays)
21087 (goto-char end))
21088 (delete-region beg end)
21089 (insert link))))))))
21091 ;; This function borrows from Ganesh Swami's latex2png.el
21092 (defun org-create-formula-image (string tofile options buffer)
21093 (let* ((tmpdir (if (featurep 'xemacs)
21094 (temp-directory)
21095 temporary-file-directory))
21096 (texfilebase (make-temp-name
21097 (expand-file-name "orgtex" tmpdir)))
21098 (texfile (concat texfilebase ".tex"))
21099 (dvifile (concat texfilebase ".dvi"))
21100 (pngfile (concat texfilebase ".png"))
21101 (fnh (face-attribute 'default :height nil))
21102 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
21103 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
21104 (fg (or (plist-get options (if buffer :foreground :html-foreground))
21105 "Black"))
21106 (bg (or (plist-get options (if buffer :background :html-background))
21107 "Transparent")))
21108 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
21109 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
21110 (with-temp-file texfile
21111 (insert org-format-latex-header
21112 "\n\\begin{document}\n" string "\n\\end{document}\n"))
21113 (let ((dir default-directory))
21114 (condition-case nil
21115 (progn
21116 (cd tmpdir)
21117 (call-process "latex" nil nil nil texfile))
21118 (error nil))
21119 (cd dir))
21120 (if (not (file-exists-p dvifile))
21121 (progn (message "Failed to create dvi file from %s" texfile) nil)
21122 (call-process "dvipng" nil nil nil
21123 "-E" "-fg" fg "-bg" bg
21124 "-D" dpi
21125 ;;"-x" scale "-y" scale
21126 "-T" "tight"
21127 "-o" pngfile
21128 dvifile)
21129 (if (not (file-exists-p pngfile))
21130 (progn (message "Failed to create png file from %s" texfile) nil)
21131 ;; Use the requested file name and clean up
21132 (copy-file pngfile tofile 'replace)
21133 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
21134 (delete-file (concat texfilebase e)))
21135 pngfile))))
21137 (defun org-dvipng-color (attr)
21138 "Return an rgb color specification for dvipng."
21139 (apply 'format "rgb %s %s %s"
21140 (mapcar 'org-normalize-color
21141 (color-values (face-attribute 'default attr nil)))))
21143 (defun org-normalize-color (value)
21144 "Return string to be used as color value for an RGB component."
21145 (format "%g" (/ value 65535.0)))
21147 ;;;; Exporting
21149 ;;; Variables, constants, and parameter plists
21151 (defconst org-level-max 20)
21153 (defvar org-export-html-preamble nil
21154 "Preamble, to be inserted just after <body>. Set by publishing functions.")
21155 (defvar org-export-html-postamble nil
21156 "Preamble, to be inserted just before </body>. Set by publishing functions.")
21157 (defvar org-export-html-auto-preamble t
21158 "Should default preamble be inserted? Set by publishing functions.")
21159 (defvar org-export-html-auto-postamble t
21160 "Should default postamble be inserted? Set by publishing functions.")
21161 (defvar org-current-export-file nil) ; dynamically scoped parameter
21162 (defvar org-current-export-dir nil) ; dynamically scoped parameter
21165 (defconst org-export-plist-vars
21166 '((:language . org-export-default-language)
21167 (:customtime . org-display-custom-times)
21168 (:headline-levels . org-export-headline-levels)
21169 (:section-numbers . org-export-with-section-numbers)
21170 (:table-of-contents . org-export-with-toc)
21171 (:preserve-breaks . org-export-preserve-breaks)
21172 (:archived-trees . org-export-with-archived-trees)
21173 (:emphasize . org-export-with-emphasize)
21174 (:sub-superscript . org-export-with-sub-superscripts)
21175 (:footnotes . org-export-with-footnotes)
21176 (:property-drawer . org-export-with-property-drawer)
21177 (:tags . org-export-with-tags)
21178 (:TeX-macros . org-export-with-TeX-macros)
21179 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
21180 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
21181 (:fixed-width . org-export-with-fixed-width)
21182 (:timestamps . org-export-with-timestamps)
21183 (:author-info . org-export-author-info)
21184 (:time-stamp-file . org-export-time-stamp-file)
21185 (:tables . org-export-with-tables)
21186 (:table-auto-headline . org-export-highlight-first-table-line)
21187 (:style . org-export-html-style)
21188 (:agenda-style . org-agenda-export-html-style) ;; FIXME: Does this work????
21189 (:convert-org-links . org-export-html-link-org-files-as-html)
21190 (:inline-images . org-export-html-inline-images)
21191 (:html-extension . org-export-html-extension)
21192 (:expand-quoted-html . org-export-html-expand)
21193 (:timestamp . org-export-html-with-timestamp)
21194 (:publishing-directory . org-export-publishing-directory)
21195 (:preamble . org-export-html-preamble)
21196 (:postamble . org-export-html-postamble)
21197 (:auto-preamble . org-export-html-auto-preamble)
21198 (:auto-postamble . org-export-html-auto-postamble)
21199 (:author . user-full-name)
21200 (:email . user-mail-address)))
21202 (defun org-default-export-plist ()
21203 "Return the property list with default settings for the export variables."
21204 (let ((l org-export-plist-vars) rtn e)
21205 (while (setq e (pop l))
21206 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
21207 rtn))
21209 (defun org-infile-export-plist ()
21210 "Return the property list with file-local settings for export."
21211 (save-excursion
21212 (goto-char 0)
21213 (let ((re (org-make-options-regexp
21214 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
21215 p key val text options)
21216 (while (re-search-forward re nil t)
21217 (setq key (org-match-string-no-properties 1)
21218 val (org-match-string-no-properties 2))
21219 (cond
21220 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
21221 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
21222 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
21223 ((string-equal key "DATE") (setq p (plist-put p :date val)))
21224 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
21225 ((string-equal key "TEXT")
21226 (setq text (if text (concat text "\n" val) val)))
21227 ((string-equal key "OPTIONS") (setq options val))))
21228 (setq p (plist-put p :text text))
21229 (when options
21230 (let ((op '(("H" . :headline-levels)
21231 ("num" . :section-numbers)
21232 ("toc" . :table-of-contents)
21233 ("\\n" . :preserve-breaks)
21234 ("@" . :expand-quoted-html)
21235 (":" . :fixed-width)
21236 ("|" . :tables)
21237 ("^" . :sub-superscript)
21238 ("f" . :footnotes)
21239 ("p" . :property-drawer)
21240 ("tags" . :tags)
21241 ("*" . :emphasize)
21242 ("TeX" . :TeX-macros)
21243 ("LaTeX" . :LaTeX-fragments)
21244 ("skip" . :skip-before-1st-heading)
21245 ("author" . :author-info)
21246 ("timestamp" . :time-stamp-file)))
21248 (while (setq o (pop op))
21249 (if (string-match (concat (regexp-quote (car o))
21250 ":\\([^ \t\n\r;,.]*\\)")
21251 options)
21252 (setq p (plist-put p (cdr o)
21253 (car (read-from-string
21254 (match-string 1 options)))))))))
21255 p)))
21257 (defun org-export-directory (type plist)
21258 (let* ((val (plist-get plist :publishing-directory))
21259 (dir (if (listp val)
21260 (or (cdr (assoc type val)) ".")
21261 val)))
21262 dir))
21264 (defun org-skip-comments (lines)
21265 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
21266 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
21267 (re2 "^\\(\\*+\\)[ \t\n\r]")
21268 (case-fold-search nil)
21269 rtn line level)
21270 (while (setq line (pop lines))
21271 (cond
21272 ((and (string-match re1 line)
21273 (setq level (- (match-end 1) (match-beginning 1))))
21274 ;; Beginning of a COMMENT subtree. Skip it.
21275 (while (and (setq line (pop lines))
21276 (or (not (string-match re2 line))
21277 (> (- (match-end 1) (match-beginning 1)) level))))
21278 (setq lines (cons line lines)))
21279 ((string-match "^#" line)
21280 ;; an ordinary comment line
21282 ((and org-export-table-remove-special-lines
21283 (string-match "^[ \t]*|" line)
21284 (or (string-match "^[ \t]*| *[!_^] *|" line)
21285 (and (string-match "| *<[0-9]+> *|" line)
21286 (not (string-match "| *[^ <|]" line)))))
21287 ;; a special table line that should be removed
21289 (t (setq rtn (cons line rtn)))))
21290 (nreverse rtn)))
21292 (defun org-export (&optional arg)
21293 (interactive)
21294 (let ((help "[t] insert the export option template
21295 \[v] limit export to visible part of outline tree
21297 \[a] export as ASCII
21299 \[h] export as HTML
21300 \[H] export as HTML to temporary buffer
21301 \[R] export region as HTML
21302 \[b] export as HTML and browse immediately
21303 \[x] export as XOXO
21305 \[l] export as LaTeX
21306 \[L] export as LaTeX to temporary buffer
21308 \[i] export current file as iCalendar file
21309 \[I] export all agenda files as iCalendar files
21310 \[c] export agenda files into combined iCalendar file
21312 \[F] publish current file
21313 \[P] publish current project
21314 \[X] publish... (project will be prompted for)
21315 \[A] publish all projects")
21316 (cmds
21317 '((?t . org-insert-export-options-template)
21318 (?v . org-export-visible)
21319 (?a . org-export-as-ascii)
21320 (?h . org-export-as-html)
21321 (?b . org-export-as-html-and-open)
21322 (?H . org-export-as-html-to-buffer)
21323 (?R . org-export-region-as-html)
21324 (?x . org-export-as-xoxo)
21325 (?l . org-export-as-latex)
21326 (?L . org-export-as-latex-to-buffer)
21327 (?i . org-export-icalendar-this-file)
21328 (?I . org-export-icalendar-all-agenda-files)
21329 (?c . org-export-icalendar-combine-agenda-files)
21330 (?F . org-publish-current-file)
21331 (?P . org-publish-current-project)
21332 (?X . org-publish)
21333 (?A . org-publish-all)))
21334 r1 r2 ass)
21335 (save-window-excursion
21336 (delete-other-windows)
21337 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
21338 (princ help))
21339 (message "Select command: ")
21340 (setq r1 (read-char-exclusive)))
21341 (setq r2 (if (< r1 27) (+ r1 96) r1))
21342 (if (setq ass (assq r2 cmds))
21343 (call-interactively (cdr ass))
21344 (error "No command associated with key %c" r1))))
21346 (defconst org-html-entities
21347 '(("nbsp")
21348 ("iexcl")
21349 ("cent")
21350 ("pound")
21351 ("curren")
21352 ("yen")
21353 ("brvbar")
21354 ("vert" . "&#124;")
21355 ("sect")
21356 ("uml")
21357 ("copy")
21358 ("ordf")
21359 ("laquo")
21360 ("not")
21361 ("shy")
21362 ("reg")
21363 ("macr")
21364 ("deg")
21365 ("plusmn")
21366 ("sup2")
21367 ("sup3")
21368 ("acute")
21369 ("micro")
21370 ("para")
21371 ("middot")
21372 ("odot"."o")
21373 ("star"."*")
21374 ("cedil")
21375 ("sup1")
21376 ("ordm")
21377 ("raquo")
21378 ("frac14")
21379 ("frac12")
21380 ("frac34")
21381 ("iquest")
21382 ("Agrave")
21383 ("Aacute")
21384 ("Acirc")
21385 ("Atilde")
21386 ("Auml")
21387 ("Aring") ("AA"."&Aring;")
21388 ("AElig")
21389 ("Ccedil")
21390 ("Egrave")
21391 ("Eacute")
21392 ("Ecirc")
21393 ("Euml")
21394 ("Igrave")
21395 ("Iacute")
21396 ("Icirc")
21397 ("Iuml")
21398 ("ETH")
21399 ("Ntilde")
21400 ("Ograve")
21401 ("Oacute")
21402 ("Ocirc")
21403 ("Otilde")
21404 ("Ouml")
21405 ("times")
21406 ("Oslash")
21407 ("Ugrave")
21408 ("Uacute")
21409 ("Ucirc")
21410 ("Uuml")
21411 ("Yacute")
21412 ("THORN")
21413 ("szlig")
21414 ("agrave")
21415 ("aacute")
21416 ("acirc")
21417 ("atilde")
21418 ("auml")
21419 ("aring")
21420 ("aelig")
21421 ("ccedil")
21422 ("egrave")
21423 ("eacute")
21424 ("ecirc")
21425 ("euml")
21426 ("igrave")
21427 ("iacute")
21428 ("icirc")
21429 ("iuml")
21430 ("eth")
21431 ("ntilde")
21432 ("ograve")
21433 ("oacute")
21434 ("ocirc")
21435 ("otilde")
21436 ("ouml")
21437 ("divide")
21438 ("oslash")
21439 ("ugrave")
21440 ("uacute")
21441 ("ucirc")
21442 ("uuml")
21443 ("yacute")
21444 ("thorn")
21445 ("yuml")
21446 ("fnof")
21447 ("Alpha")
21448 ("Beta")
21449 ("Gamma")
21450 ("Delta")
21451 ("Epsilon")
21452 ("Zeta")
21453 ("Eta")
21454 ("Theta")
21455 ("Iota")
21456 ("Kappa")
21457 ("Lambda")
21458 ("Mu")
21459 ("Nu")
21460 ("Xi")
21461 ("Omicron")
21462 ("Pi")
21463 ("Rho")
21464 ("Sigma")
21465 ("Tau")
21466 ("Upsilon")
21467 ("Phi")
21468 ("Chi")
21469 ("Psi")
21470 ("Omega")
21471 ("alpha")
21472 ("beta")
21473 ("gamma")
21474 ("delta")
21475 ("epsilon")
21476 ("varepsilon"."&epsilon;")
21477 ("zeta")
21478 ("eta")
21479 ("theta")
21480 ("iota")
21481 ("kappa")
21482 ("lambda")
21483 ("mu")
21484 ("nu")
21485 ("xi")
21486 ("omicron")
21487 ("pi")
21488 ("rho")
21489 ("sigmaf") ("varsigma"."&sigmaf;")
21490 ("sigma")
21491 ("tau")
21492 ("upsilon")
21493 ("phi")
21494 ("chi")
21495 ("psi")
21496 ("omega")
21497 ("thetasym") ("vartheta"."&thetasym;")
21498 ("upsih")
21499 ("piv")
21500 ("bull") ("bullet"."&bull;")
21501 ("hellip") ("dots"."&hellip;")
21502 ("prime")
21503 ("Prime")
21504 ("oline")
21505 ("frasl")
21506 ("weierp")
21507 ("image")
21508 ("real")
21509 ("trade")
21510 ("alefsym")
21511 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
21512 ("uarr") ("uparrow"."&uarr;")
21513 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
21514 ("darr")("downarrow"."&darr;")
21515 ("harr") ("leftrightarrow"."&harr;")
21516 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
21517 ("lArr") ("Leftarrow"."&lArr;")
21518 ("uArr") ("Uparrow"."&uArr;")
21519 ("rArr") ("Rightarrow"."&rArr;")
21520 ("dArr") ("Downarrow"."&dArr;")
21521 ("hArr") ("Leftrightarrow"."&hArr;")
21522 ("forall")
21523 ("part") ("partial"."&part;")
21524 ("exist") ("exists"."&exist;")
21525 ("empty") ("emptyset"."&empty;")
21526 ("nabla")
21527 ("isin") ("in"."&isin;")
21528 ("notin")
21529 ("ni")
21530 ("prod")
21531 ("sum")
21532 ("minus")
21533 ("lowast") ("ast"."&lowast;")
21534 ("radic")
21535 ("prop") ("proptp"."&prop;")
21536 ("infin") ("infty"."&infin;")
21537 ("ang") ("angle"."&ang;")
21538 ("and") ("vee"."&and;")
21539 ("or") ("wedge"."&or;")
21540 ("cap")
21541 ("cup")
21542 ("int")
21543 ("there4")
21544 ("sim")
21545 ("cong") ("simeq"."&cong;")
21546 ("asymp")("approx"."&asymp;")
21547 ("ne") ("neq"."&ne;")
21548 ("equiv")
21549 ("le")
21550 ("ge")
21551 ("sub") ("subset"."&sub;")
21552 ("sup") ("supset"."&sup;")
21553 ("nsub")
21554 ("sube")
21555 ("supe")
21556 ("oplus")
21557 ("otimes")
21558 ("perp")
21559 ("sdot") ("cdot"."&sdot;")
21560 ("lceil")
21561 ("rceil")
21562 ("lfloor")
21563 ("rfloor")
21564 ("lang")
21565 ("rang")
21566 ("loz") ("Diamond"."&loz;")
21567 ("spades") ("spadesuit"."&spades;")
21568 ("clubs") ("clubsuit"."&clubs;")
21569 ("hearts") ("diamondsuit"."&hearts;")
21570 ("diams") ("diamondsuit"."&diams;")
21571 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
21572 ("quot")
21573 ("amp")
21574 ("lt")
21575 ("gt")
21576 ("OElig")
21577 ("oelig")
21578 ("Scaron")
21579 ("scaron")
21580 ("Yuml")
21581 ("circ")
21582 ("tilde")
21583 ("ensp")
21584 ("emsp")
21585 ("thinsp")
21586 ("zwnj")
21587 ("zwj")
21588 ("lrm")
21589 ("rlm")
21590 ("ndash")
21591 ("mdash")
21592 ("lsquo")
21593 ("rsquo")
21594 ("sbquo")
21595 ("ldquo")
21596 ("rdquo")
21597 ("bdquo")
21598 ("dagger")
21599 ("Dagger")
21600 ("permil")
21601 ("lsaquo")
21602 ("rsaquo")
21603 ("euro")
21605 ("arccos"."arccos")
21606 ("arcsin"."arcsin")
21607 ("arctan"."arctan")
21608 ("arg"."arg")
21609 ("cos"."cos")
21610 ("cosh"."cosh")
21611 ("cot"."cot")
21612 ("coth"."coth")
21613 ("csc"."csc")
21614 ("deg"."deg")
21615 ("det"."det")
21616 ("dim"."dim")
21617 ("exp"."exp")
21618 ("gcd"."gcd")
21619 ("hom"."hom")
21620 ("inf"."inf")
21621 ("ker"."ker")
21622 ("lg"."lg")
21623 ("lim"."lim")
21624 ("liminf"."liminf")
21625 ("limsup"."limsup")
21626 ("ln"."ln")
21627 ("log"."log")
21628 ("max"."max")
21629 ("min"."min")
21630 ("Pr"."Pr")
21631 ("sec"."sec")
21632 ("sin"."sin")
21633 ("sinh"."sinh")
21634 ("sup"."sup")
21635 ("tan"."tan")
21636 ("tanh"."tanh")
21638 "Entities for TeX->HTML translation.
21639 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
21640 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
21641 In that case, \"\\ent\" will be translated to \"&other;\".
21642 The list contains HTML entities for Latin-1, Greek and other symbols.
21643 It is supplemented by a number of commonly used TeX macros with appropriate
21644 translations. There is currently no way for users to extend this.")
21646 ;;; General functions for all backends
21648 (defun org-cleaned-string-for-export (string &rest parameters)
21649 "Cleanup a buffer STRING so that links can be created safely."
21650 (interactive)
21651 (let* ((re-radio (and org-target-link-regexp
21652 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
21653 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
21654 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
21655 (re-archive (concat ":" org-archive-tag ":"))
21656 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
21657 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
21658 (htmlp (plist-get parameters :for-html))
21659 (asciip (plist-get parameters :for-ascii))
21660 (latexp (plist-get parameters :for-LaTeX))
21661 (commentsp (plist-get parameters :comments))
21662 (archived-trees (plist-get parameters :archived-trees))
21663 (inhibit-read-only t)
21664 (outline-regexp "\\*+ ")
21665 a b xx
21666 rtn p)
21667 (with-current-buffer (get-buffer-create " org-mode-tmp")
21668 (erase-buffer)
21669 (insert string)
21670 ;; Remove license-to-kill stuff
21671 (while (setq p (text-property-any (point-min) (point-max)
21672 :org-license-to-kill t))
21673 (delete-region p (next-single-property-change p :org-license-to-kill)))
21675 (let ((org-inhibit-startup t)) (org-mode))
21676 (untabify (point-min) (point-max))
21678 ;; Get the correct stuff before the first headline
21679 (when (plist-get parameters :skip-before-1st-heading)
21680 (goto-char (point-min))
21681 (when (re-search-forward "^\\*+[ \t]" nil t)
21682 (delete-region (point-min) (match-beginning 0))
21683 (goto-char (point-min))
21684 (insert "\n")))
21685 (when (plist-get parameters :add-text)
21686 (goto-char (point-min))
21687 (insert (plist-get parameters :add-text) "\n"))
21689 ;; Get rid of archived trees
21690 (when (not (eq archived-trees t))
21691 (goto-char (point-min))
21692 (while (re-search-forward re-archive nil t)
21693 (if (not (org-on-heading-p t))
21694 (org-end-of-subtree t)
21695 (beginning-of-line 1)
21696 (setq a (if archived-trees
21697 (1+ (point-at-eol)) (point))
21698 b (org-end-of-subtree t))
21699 (if (> b a) (delete-region a b)))))
21701 ;; Get rid of property drawers
21702 (unless org-export-with-property-drawer
21703 (goto-char (point-min))
21704 (while (re-search-forward "^[ \t]*:PROPERTIES:[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n" nil t)
21705 (replace-match "")))
21707 ;; Find targets in comments and move them out of comments,
21708 ;; but mark them as targets that should be invisible
21709 (goto-char (point-min))
21710 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
21711 (replace-match "\\1(INVISIBLE)"))
21713 ;; Protect backend specific stuff, throw away the others.
21714 (goto-char (point-min))
21715 (let ((formatters
21716 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
21717 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
21718 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
21719 fmt)
21720 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
21721 (add-text-properties (match-beginning 0) (match-end 0)
21722 '(org-protected t)))
21723 (while formatters
21724 (setq fmt (pop formatters))
21725 (when (car fmt)
21726 (goto-char (point-min))
21727 (while (re-search-forward (concat "^#\\+" (cadr fmt)
21728 ":[ \t]*\\(.*\\)") nil t)
21729 (replace-match "\\1" t)
21730 (add-text-properties
21731 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
21732 '(org-protected t))))
21733 (goto-char (point-min))
21734 (while (re-search-forward
21735 (concat "^#\\+"
21736 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
21737 (cadddr fmt) "\\>.*\n?") nil t)
21738 (if (car fmt)
21739 (add-text-properties (match-beginning 1) (1+ (match-end 1))
21740 '(org-protected t))
21741 (delete-region (match-beginning 0) (match-end 0))))))
21743 ;; Protect quoted subtrees
21744 (goto-char (point-min))
21745 (while (re-search-forward re-quote nil t)
21746 (goto-char (match-beginning 0))
21747 (end-of-line 1)
21748 (add-text-properties (point) (org-end-of-subtree t)
21749 '(org-protected t)))
21751 ;; Remove subtrees that are commented
21752 (goto-char (point-min))
21753 (while (re-search-forward re-commented nil t)
21754 (goto-char (match-beginning 0))
21755 (delete-region (point) (org-end-of-subtree t)))
21757 ;; Remove special table lines
21758 (when org-export-table-remove-special-lines
21759 (goto-char (point-min))
21760 (while (re-search-forward "^[ \t]*|" nil t)
21761 (beginning-of-line 1)
21762 (if (or (looking-at "[ \t]*| *[!_^] *|")
21763 (and (looking-at ".*?| *<[0-9]+> *|")
21764 (not (looking-at ".*?| *[^ <|]"))))
21765 (delete-region (max (point-min) (1- (point-at-bol)))
21766 (point-at-eol))
21767 (end-of-line 1))))
21769 ;; Specific LaTeX stuff
21770 (when latexp
21771 (require 'org-export-latex nil)
21772 (org-export-latex-cleaned-string))
21774 ;; Specific HTML stuff
21775 (when htmlp
21776 ;; Convert LaTeX fragments to images
21777 (when (plist-get parameters :LaTeX-fragments)
21778 (org-format-latex
21779 (concat "ltxpng/" (file-name-sans-extension
21780 (file-name-nondirectory
21781 org-current-export-file)))
21782 org-current-export-dir nil "Creating LaTeX image %s"))
21783 (message "Exporting..."))
21785 ;; Remove or replace comments
21786 (goto-char (point-min))
21787 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
21788 (if commentsp
21789 (progn (add-text-properties
21790 (match-beginning 0) (match-end 0) '(org-protected t))
21791 (replace-match (format commentsp (match-string 1)) t t))
21792 (replace-match "")))
21794 ;; Find matches for radio targets and turn them into internal links
21795 (goto-char (point-min))
21796 (when re-radio
21797 (while (re-search-forward re-radio nil t)
21798 (org-if-unprotected
21799 (replace-match "\\1[[\\2]]"))))
21801 ;; Find all links that contain a newline and put them into a single line
21802 (goto-char (point-min))
21803 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
21804 (org-if-unprotected
21805 (replace-match "\\1 \\3")
21806 (goto-char (match-beginning 0))))
21809 ;; Normalize links: Convert angle and plain links into bracket links
21810 ;; Expand link abbreviations
21811 (goto-char (point-min))
21812 (while (re-search-forward re-plain-link nil t)
21813 (goto-char (1- (match-end 0)))
21814 (org-if-unprotected
21815 (let* ((s (concat (match-string 1) "[[" (match-string 2)
21816 ":" (match-string 3) "]]")))
21817 ;; added 'org-link face to links
21818 (put-text-property 0 (length s) 'face 'org-link s)
21819 (replace-match s t t))))
21820 (goto-char (point-min))
21821 (while (re-search-forward re-angle-link nil t)
21822 (goto-char (1- (match-end 0)))
21823 (org-if-unprotected
21824 (let* ((s (concat (match-string 1) "[[" (match-string 2)
21825 ":" (match-string 3) "]]")))
21826 (put-text-property 0 (length s) 'face 'org-link s)
21827 (replace-match s t t))))
21828 (goto-char (point-min))
21829 (while (re-search-forward org-bracket-link-regexp nil t)
21830 (org-if-unprotected
21831 (let* ((s (concat "[[" (setq xx (save-match-data
21832 (org-link-expand-abbrev (match-string 1))))
21834 (if (match-end 3)
21835 (match-string 2)
21836 (concat "[" xx "]"))
21837 "]")))
21838 (put-text-property 0 (length s) 'face 'org-link s)
21839 (replace-match s t t))))
21841 ;; Find multiline emphasis and put them into single line
21842 (when (plist-get parameters :emph-multiline)
21843 (goto-char (point-min))
21844 (while (re-search-forward org-emph-re nil t)
21845 (if (not (= (char-after (match-beginning 3))
21846 (char-after (match-beginning 4))))
21847 (org-if-unprotected
21848 (subst-char-in-region (match-beginning 0) (match-end 0)
21849 ?\n ?\ t)
21850 (goto-char (1- (match-end 0))))
21851 (goto-char (1+ (match-beginning 0))))))
21853 (setq rtn (buffer-string)))
21854 (kill-buffer " org-mode-tmp")
21855 rtn))
21857 (defun org-export-grab-title-from-buffer ()
21858 "Get a title for the current document, from looking at the buffer."
21859 (let ((inhibit-read-only t))
21860 (save-excursion
21861 (goto-char (point-min))
21862 (let ((end (save-excursion (outline-next-heading) (point))))
21863 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
21864 ;; Mark the line so that it will not be exported as normal text.
21865 (org-unmodified
21866 (add-text-properties (match-beginning 0) (match-end 0)
21867 (list :org-license-to-kill t)))
21868 ;; Return the title string
21869 (org-trim (match-string 0)))))))
21871 (defun org-export-get-title-from-subtree ()
21872 "Return subtree title and exclude it from export."
21873 (let (title (m (mark)))
21874 (save-excursion
21875 (goto-char (region-beginning))
21876 (when (and (org-at-heading-p)
21877 (>= (org-end-of-subtree t t) (region-end)))
21878 ;; This is a subtree, we take the title from the first heading
21879 (goto-char (region-beginning))
21880 (looking-at org-todo-line-regexp)
21881 (setq title (match-string 3))
21882 (org-unmodified
21883 (add-text-properties (point) (1+ (point-at-eol))
21884 (list :org-license-to-kill t)))))
21885 title))
21887 (defun org-solidify-link-text (s &optional alist)
21888 "Take link text and make a safe target out of it."
21889 (save-match-data
21890 (let* ((rtn
21891 (mapconcat
21892 'identity
21893 (org-split-string s "[ \t\r\n]+") "--"))
21894 (a (assoc rtn alist)))
21895 (or (cdr a) rtn))))
21897 (defun org-get-min-level (lines)
21898 "Get the minimum level in LINES."
21899 (let ((re "^\\(\\*+\\) ") l min)
21900 (catch 'exit
21901 (while (setq l (pop lines))
21902 (if (string-match re l)
21903 (throw 'exit (org-tr-level (length (match-string 1 l))))))
21904 1)))
21906 ;; Variable holding the vector with section numbers
21907 (defvar org-section-numbers (make-vector org-level-max 0))
21909 (defun org-init-section-numbers ()
21910 "Initialize the vector for the section numbers."
21911 (let* ((level -1)
21912 (numbers (nreverse (org-split-string "" "\\.")))
21913 (depth (1- (length org-section-numbers)))
21914 (i depth) number-string)
21915 (while (>= i 0)
21916 (if (> i level)
21917 (aset org-section-numbers i 0)
21918 (setq number-string (or (car numbers) "0"))
21919 (if (string-match "\\`[A-Z]\\'" number-string)
21920 (aset org-section-numbers i
21921 (- (string-to-char number-string) ?A -1))
21922 (aset org-section-numbers i (string-to-number number-string)))
21923 (pop numbers))
21924 (setq i (1- i)))))
21926 (defun org-section-number (&optional level)
21927 "Return a string with the current section number.
21928 When LEVEL is non-nil, increase section numbers on that level."
21929 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
21930 (when level
21931 (when (> level -1)
21932 (aset org-section-numbers
21933 level (1+ (aref org-section-numbers level))))
21934 (setq idx (1+ level))
21935 (while (<= idx depth)
21936 (if (not (= idx 1))
21937 (aset org-section-numbers idx 0))
21938 (setq idx (1+ idx))))
21939 (setq idx 0)
21940 (while (<= idx depth)
21941 (setq n (aref org-section-numbers idx))
21942 (setq string (concat string (if (not (string= string "")) "." "")
21943 (int-to-string n)))
21944 (setq idx (1+ idx)))
21945 (save-match-data
21946 (if (string-match "\\`\\([@0]\\.\\)+" string)
21947 (setq string (replace-match "" t nil string)))
21948 (if (string-match "\\(\\.0\\)+\\'" string)
21949 (setq string (replace-match "" t nil string))))
21950 string))
21952 ;;; ASCII export
21954 (defvar org-last-level nil) ; dynamically scoped variable
21955 (defvar org-min-level nil) ; dynamically scoped variable
21956 (defvar org-levels-open nil) ; dynamically scoped parameter
21957 (defvar org-ascii-current-indentation nil) ; For communication
21959 (defun org-export-as-ascii (arg)
21960 "Export the outline as a pretty ASCII file.
21961 If there is an active region, export only the region.
21962 The prefix ARG specifies how many levels of the outline should become
21963 underlined headlines. The default is 3."
21964 (interactive "P")
21965 (setq-default org-todo-line-regexp org-todo-line-regexp)
21966 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
21967 (org-infile-export-plist)))
21968 (region-p (org-region-active-p))
21969 (subtree-p
21970 (when region-p
21971 (save-excursion
21972 (goto-char (region-beginning))
21973 (and (org-at-heading-p)
21974 (>= (org-end-of-subtree t t) (region-end))))))
21975 (custom-times org-display-custom-times)
21976 (org-ascii-current-indentation '(0 . 0))
21977 (level 0) line txt
21978 (umax nil)
21979 (umax-toc nil)
21980 (case-fold-search nil)
21981 (filename (concat (file-name-as-directory
21982 (org-export-directory :ascii opt-plist))
21983 (file-name-sans-extension
21984 (or (and subtree-p
21985 (org-entry-get (region-beginning)
21986 "EXPORT_FILE_NAME" t))
21987 (file-name-nondirectory buffer-file-name)))
21988 ".txt"))
21989 (filename (if (equal (file-truename filename)
21990 (file-truename buffer-file-name))
21991 (concat filename ".txt")
21992 filename))
21993 (buffer (find-file-noselect filename))
21994 (org-levels-open (make-vector org-level-max nil))
21995 (odd org-odd-levels-only)
21996 (date (plist-get opt-plist :date))
21997 (author (plist-get opt-plist :author))
21998 (title (or (and subtree-p (org-export-get-title-from-subtree))
21999 (plist-get opt-plist :title)
22000 (and (not
22001 (plist-get opt-plist :skip-before-1st-heading))
22002 (org-export-grab-title-from-buffer))
22003 (file-name-sans-extension
22004 (file-name-nondirectory buffer-file-name))))
22005 (email (plist-get opt-plist :email))
22006 (language (plist-get opt-plist :language))
22007 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
22008 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
22009 (todo nil)
22010 (lang-words nil)
22011 (region
22012 (buffer-substring
22013 (if (org-region-active-p) (region-beginning) (point-min))
22014 (if (org-region-active-p) (region-end) (point-max))))
22015 (lines (org-split-string
22016 (org-cleaned-string-for-export
22017 region
22018 :for-ascii t
22019 :skip-before-1st-heading
22020 (plist-get opt-plist :skip-before-1st-heading)
22021 :archived-trees
22022 (plist-get opt-plist :archived-trees)
22023 :add-text (plist-get opt-plist :text))
22024 "\n"))
22025 thetoc have-headings first-heading-pos
22026 table-open table-buffer)
22028 (let ((inhibit-read-only t))
22029 (org-unmodified
22030 (remove-text-properties (point-min) (point-max)
22031 '(:org-license-to-kill t))))
22033 (setq org-min-level (org-get-min-level lines))
22034 (setq org-last-level org-min-level)
22035 (org-init-section-numbers)
22037 (find-file-noselect filename)
22039 (setq lang-words (or (assoc language org-export-language-setup)
22040 (assoc "en" org-export-language-setup)))
22041 (switch-to-buffer-other-window buffer)
22042 (erase-buffer)
22043 (fundamental-mode)
22044 ;; create local variables for all options, to make sure all called
22045 ;; functions get the correct information
22046 (mapcar (lambda (x)
22047 (set (make-local-variable (cdr x))
22048 (plist-get opt-plist (car x))))
22049 org-export-plist-vars)
22050 (org-set-local 'org-odd-levels-only odd)
22051 (setq umax (if arg (prefix-numeric-value arg)
22052 org-export-headline-levels))
22053 (setq umax-toc (if (integerp org-export-with-toc)
22054 (min org-export-with-toc umax)
22055 umax))
22057 ;; File header
22058 (if title (org-insert-centered title ?=))
22059 (insert "\n")
22060 (if (and (or author email)
22061 org-export-author-info)
22062 (insert (concat (nth 1 lang-words) ": " (or author "")
22063 (if email (concat " <" email ">") "")
22064 "\n")))
22066 (cond
22067 ((and date (string-match "%" date))
22068 (setq date (format-time-string date (current-time))))
22069 (date)
22070 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
22072 (if (and date org-export-time-stamp-file)
22073 (insert (concat (nth 2 lang-words) ": " date"\n")))
22075 (insert "\n\n")
22077 (if org-export-with-toc
22078 (progn
22079 (push (concat (nth 3 lang-words) "\n") thetoc)
22080 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
22081 (mapcar '(lambda (line)
22082 (if (string-match org-todo-line-regexp
22083 line)
22084 ;; This is a headline
22085 (progn
22086 (setq have-headings t)
22087 (setq level (- (match-end 1) (match-beginning 1))
22088 level (org-tr-level level)
22089 txt (match-string 3 line)
22090 todo
22091 (or (and org-export-mark-todo-in-toc
22092 (match-beginning 2)
22093 (not (member (match-string 2 line)
22094 org-done-keywords)))
22095 ; TODO, not DONE
22096 (and org-export-mark-todo-in-toc
22097 (= level umax-toc)
22098 (org-search-todo-below
22099 line lines level))))
22100 (setq txt (org-html-expand-for-ascii txt))
22102 (while (string-match org-bracket-link-regexp txt)
22103 (setq txt
22104 (replace-match
22105 (match-string (if (match-end 2) 3 1) txt)
22106 t t txt)))
22108 (if (and (memq org-export-with-tags '(not-in-toc nil))
22109 (string-match
22110 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
22111 txt))
22112 (setq txt (replace-match "" t t txt)))
22113 (if (string-match quote-re0 txt)
22114 (setq txt (replace-match "" t t txt)))
22116 (if org-export-with-section-numbers
22117 (setq txt (concat (org-section-number level)
22118 " " txt)))
22119 (if (<= level umax-toc)
22120 (progn
22121 (push
22122 (concat
22123 (make-string
22124 (* (max 0 (- level org-min-level)) 4) ?\ )
22125 (format (if todo "%s (*)\n" "%s\n") txt))
22126 thetoc)
22127 (setq org-last-level level))
22128 ))))
22129 lines)
22130 (setq thetoc (if have-headings (nreverse thetoc) nil))))
22132 (org-init-section-numbers)
22133 (while (setq line (pop lines))
22134 ;; Remove the quoted HTML tags.
22135 (setq line (org-html-expand-for-ascii line))
22136 ;; Remove targets
22137 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
22138 (setq line (replace-match "" t t line)))
22139 ;; Replace internal links
22140 (while (string-match org-bracket-link-regexp line)
22141 (setq line (replace-match
22142 (if (match-end 3) "[\\3]" "[\\1]")
22143 t nil line)))
22144 (when custom-times
22145 (setq line (org-translate-time line)))
22146 (cond
22147 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
22148 ;; a Headline
22149 (setq first-heading-pos (or first-heading-pos (point)))
22150 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
22151 txt (match-string 2 line))
22152 (org-ascii-level-start level txt umax lines))
22154 ((and org-export-with-tables
22155 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
22156 (if (not table-open)
22157 ;; New table starts
22158 (setq table-open t table-buffer nil))
22159 ;; Accumulate lines
22160 (setq table-buffer (cons line table-buffer))
22161 (when (or (not lines)
22162 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
22163 (car lines))))
22164 (setq table-open nil
22165 table-buffer (nreverse table-buffer))
22166 (insert (mapconcat
22167 (lambda (x)
22168 (org-fix-indentation x org-ascii-current-indentation))
22169 (org-format-table-ascii table-buffer)
22170 "\n") "\n")))
22172 (setq line (org-fix-indentation line org-ascii-current-indentation))
22173 (if (and org-export-with-fixed-width
22174 (string-match "^\\([ \t]*\\)\\(:\\)" line))
22175 (setq line (replace-match "\\1" nil nil line)))
22176 (insert line "\n"))))
22178 (normal-mode)
22180 ;; insert the table of contents
22181 (when thetoc
22182 (goto-char (point-min))
22183 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
22184 (progn
22185 (goto-char (match-beginning 0))
22186 (replace-match ""))
22187 (goto-char first-heading-pos))
22188 (mapc 'insert thetoc)
22189 (or (looking-at "[ \t]*\n[ \t]*\n")
22190 (insert "\n\n")))
22192 (save-buffer)
22193 ;; remove display and invisible chars
22194 (let (beg end)
22195 (goto-char (point-min))
22196 (while (setq beg (next-single-property-change (point) 'display))
22197 (setq end (next-single-property-change beg 'display))
22198 (delete-region beg end)
22199 (goto-char beg)
22200 (insert "=>"))
22201 (goto-char (point-min))
22202 (while (setq beg (next-single-property-change (point) 'org-cwidth))
22203 (setq end (next-single-property-change beg 'org-cwidth))
22204 (delete-region beg end)
22205 (goto-char beg)))
22206 (goto-char (point-min))))
22208 (defun org-search-todo-below (line lines level)
22209 "Search the subtree below LINE for any TODO entries."
22210 (let ((rest (cdr (memq line lines)))
22211 (re org-todo-line-regexp)
22212 line lv todo)
22213 (catch 'exit
22214 (while (setq line (pop rest))
22215 (if (string-match re line)
22216 (progn
22217 (setq lv (- (match-end 1) (match-beginning 1))
22218 todo (and (match-beginning 2)
22219 (not (member (match-string 2 line)
22220 org-done-keywords))))
22221 ; TODO, not DONE
22222 (if (<= lv level) (throw 'exit nil))
22223 (if todo (throw 'exit t))))))))
22225 (defun org-html-expand-for-ascii (line)
22226 "Handle quoted HTML for ASCII export."
22227 (if org-export-html-expand
22228 (while (string-match "@<[^<>\n]*>" line)
22229 ;; We just remove the tags for now.
22230 (setq line (replace-match "" nil nil line))))
22231 line)
22233 (defun org-insert-centered (s &optional underline)
22234 "Insert the string S centered and underline it with character UNDERLINE."
22235 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
22236 (insert (make-string ind ?\ ) s "\n")
22237 (if underline
22238 (insert (make-string ind ?\ )
22239 (make-string (string-width s) underline)
22240 "\n"))))
22242 (defun org-ascii-level-start (level title umax &optional lines)
22243 "Insert a new level in ASCII export."
22244 (let (char (n (- level umax 1)) (ind 0))
22245 (if (> level umax)
22246 (progn
22247 (insert (make-string (* 2 n) ?\ )
22248 (char-to-string (nth (% n (length org-export-ascii-bullets))
22249 org-export-ascii-bullets))
22250 " " title "\n")
22251 ;; find the indentation of the next non-empty line
22252 (catch 'stop
22253 (while lines
22254 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
22255 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
22256 (throw 'stop (setq ind (org-get-indentation (car lines)))))
22257 (pop lines)))
22258 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
22259 (if (or (not (equal (char-before) ?\n))
22260 (not (equal (char-before (1- (point))) ?\n)))
22261 (insert "\n"))
22262 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
22263 (unless org-export-with-tags
22264 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
22265 (setq title (replace-match "" t t title))))
22266 (if org-export-with-section-numbers
22267 (setq title (concat (org-section-number level) " " title)))
22268 (insert title "\n" (make-string (string-width title) char) "\n")
22269 (setq org-ascii-current-indentation '(0 . 0)))))
22271 (defun org-export-visible (type arg)
22272 "Create a copy of the visible part of the current buffer, and export it.
22273 The copy is created in a temporary buffer and removed after use.
22274 TYPE is the final key (as a string) that also select the export command in
22275 the `C-c C-e' export dispatcher.
22276 As a special case, if the you type SPC at the prompt, the temporary
22277 org-mode file will not be removed but presented to you so that you can
22278 continue to use it. The prefix arg ARG is passed through to the exporting
22279 command."
22280 (interactive
22281 (list (progn
22282 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
22283 (read-char-exclusive))
22284 current-prefix-arg))
22285 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
22286 (error "Invalid export key"))
22287 (let* ((binding (cdr (assoc type
22288 '((?a . org-export-as-ascii)
22289 (?\C-a . org-export-as-ascii)
22290 (?b . org-export-as-html-and-open)
22291 (?\C-b . org-export-as-html-and-open)
22292 (?h . org-export-as-html)
22293 (?H . org-export-as-html-to-buffer)
22294 (?R . org-export-region-as-html)
22295 (?x . org-export-as-xoxo)))))
22296 (keepp (equal type ?\ ))
22297 (file buffer-file-name)
22298 (buffer (get-buffer-create "*Org Export Visible*"))
22299 s e)
22300 ;; Need to hack the drawers here.
22301 (save-excursion
22302 (goto-char (point-min))
22303 (while (re-search-forward org-drawer-regexp nil t)
22304 (goto-char (match-beginning 1))
22305 (or (org-invisible-p) (org-flag-drawer nil))))
22306 (with-current-buffer buffer (erase-buffer))
22307 (save-excursion
22308 (setq s (goto-char (point-min)))
22309 (while (not (= (point) (point-max)))
22310 (goto-char (org-find-invisible))
22311 (append-to-buffer buffer s (point))
22312 (setq s (goto-char (org-find-visible))))
22313 (org-cycle-hide-drawers 'all)
22314 (goto-char (point-min))
22315 (unless keepp
22316 ;; Copy all comment lines to the end, to make sure #+ settings are
22317 ;; still available for the second export step. Kind of a hack, but
22318 ;; does do the trick.
22319 (if (looking-at "#[^\r\n]*")
22320 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
22321 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
22322 (append-to-buffer buffer (1+ (match-beginning 0))
22323 (min (point-max) (1+ (match-end 0))))))
22324 (set-buffer buffer)
22325 (let ((buffer-file-name file)
22326 (org-inhibit-startup t))
22327 (org-mode)
22328 (show-all)
22329 (unless keepp (funcall binding arg))))
22330 (if (not keepp)
22331 (kill-buffer buffer)
22332 (switch-to-buffer-other-window buffer)
22333 (goto-char (point-min)))))
22335 (defun org-find-visible ()
22336 (let ((s (point)))
22337 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
22338 (get-char-property s 'invisible)))
22340 (defun org-find-invisible ()
22341 (let ((s (point)))
22342 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
22343 (not (get-char-property s 'invisible))))
22346 ;;; HTML export
22348 (defun org-get-current-options ()
22349 "Return a string with current options as keyword options.
22350 Does include HTML export options as well as TODO and CATEGORY stuff."
22351 (format
22352 "#+TITLE: %s
22353 #+AUTHOR: %s
22354 #+EMAIL: %s
22355 #+LANGUAGE: %s
22356 #+TEXT: Some descriptive text to be emitted. Several lines OK.
22357 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s p:%s tags:%s
22358 #+CATEGORY: %s
22359 #+SEQ_TODO: %s
22360 #+TYP_TODO: %s
22361 #+PRIORITIES: %c %c %c
22362 #+STARTUP: %s %s %s %s %s
22363 #+TAGS: %s
22364 #+ARCHIVE: %s
22365 #+LINK: %s
22367 (buffer-name) (user-full-name) user-mail-address org-export-default-language
22368 org-export-headline-levels
22369 org-export-with-section-numbers
22370 org-export-with-toc
22371 org-export-preserve-breaks
22372 org-export-html-expand
22373 org-export-with-fixed-width
22374 org-export-with-tables
22375 org-export-with-sub-superscripts
22376 org-export-with-footnotes
22377 org-export-with-emphasize
22378 org-export-with-TeX-macros
22379 org-export-with-LaTeX-fragments
22380 org-export-skip-text-before-1st-heading
22381 org-export-with-property-drawer
22382 org-export-with-tags
22383 (file-name-nondirectory buffer-file-name)
22384 "TODO FEEDBACK VERIFY DONE"
22385 "Me Jason Marie DONE"
22386 org-highest-priority org-lowest-priority org-default-priority
22387 (cdr (assoc org-startup-folded
22388 '((nil . "showall") (t . "overview") (content . "content"))))
22389 (if org-odd-levels-only "odd" "oddeven")
22390 (if org-hide-leading-stars "hidestars" "showstars")
22391 (if org-startup-align-all-tables "align" "noalign")
22392 (cond ((eq t org-log-done) "logdone")
22393 ((not org-log-done) "nologging")
22394 ((listp org-log-done)
22395 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
22396 org-log-done " ")))
22397 (or (mapconcat (lambda (x)
22398 (cond
22399 ((equal '(:startgroup) x) "{")
22400 ((equal '(:endgroup) x) "}")
22401 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
22402 (t (car x))))
22403 (or org-tag-alist (org-get-buffer-tags)) " ") "")
22404 org-archive-location
22405 "org file:~/org/%s.org"
22408 (defun org-insert-export-options-template ()
22409 "Insert into the buffer a template with information for exporting."
22410 (interactive)
22411 (if (not (bolp)) (newline))
22412 (let ((s (org-get-current-options)))
22413 (and (string-match "#\\+CATEGORY" s)
22414 (setq s (substring s 0 (match-beginning 0))))
22415 (insert s)))
22417 (defun org-toggle-fixed-width-section (arg)
22418 "Toggle the fixed-width export.
22419 If there is no active region, the QUOTE keyword at the current headline is
22420 inserted or removed. When present, it causes the text between this headline
22421 and the next to be exported as fixed-width text, and unmodified.
22422 If there is an active region, this command adds or removes a colon as the
22423 first character of this line. If the first character of a line is a colon,
22424 this line is also exported in fixed-width font."
22425 (interactive "P")
22426 (let* ((cc 0)
22427 (regionp (org-region-active-p))
22428 (beg (if regionp (region-beginning) (point)))
22429 (end (if regionp (region-end)))
22430 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22431 (re "[ \t]*\\(:\\)")
22432 off)
22433 (if regionp
22434 (save-excursion
22435 (goto-char beg)
22436 (setq cc (current-column))
22437 (beginning-of-line 1)
22438 (setq off (looking-at re))
22439 (while (> nlines 0)
22440 (setq nlines (1- nlines))
22441 (beginning-of-line 1)
22442 (cond
22443 (arg
22444 (move-to-column cc t)
22445 (insert ":\n")
22446 (forward-line -1))
22447 ((and off (looking-at re))
22448 (replace-match "" t t nil 1))
22449 ((not off) (move-to-column cc t) (insert ":")))
22450 (forward-line 1)))
22451 (save-excursion
22452 (org-back-to-heading)
22453 (if (looking-at (concat outline-regexp
22454 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
22455 (replace-match "" t t nil 1)
22456 (if (looking-at outline-regexp)
22457 (progn
22458 (goto-char (match-end 0))
22459 (insert org-quote-string " "))))))))
22461 (defun org-export-as-html-and-open (arg)
22462 "Export the outline as HTML and immediately open it with a browser.
22463 If there is an active region, export only the region.
22464 The prefix ARG specifies how many levels of the outline should become
22465 headlines. The default is 3. Lower levels will become bulleted lists."
22466 (interactive "P")
22467 (org-export-as-html arg 'hidden)
22468 (org-open-file buffer-file-name))
22470 (defun org-export-as-html-batch ()
22471 "Call `org-export-as-html', may be used in batch processing as
22472 emacs --batch
22473 --load=$HOME/lib/emacs/org.el
22474 --eval \"(setq org-export-headline-levels 2)\"
22475 --visit=MyFile --funcall org-export-as-html-batch"
22476 (org-export-as-html org-export-headline-levels 'hidden))
22478 (defun org-export-as-html-to-buffer (arg)
22479 "Call `org-exort-as-html` with output to a temporary buffer.
22480 No file is created. The prefix ARG is passed through to `org-export-as-html'."
22481 (interactive "P")
22482 (org-export-as-html arg nil nil "*Org HTML Export*")
22483 (switch-to-buffer-other-window "*Org HTML Export*"))
22485 (defun org-replace-region-by-html (beg end)
22486 "Assume the current region has org-mode syntax, and convert it to HTML.
22487 This can be used in any buffer. For example, you could write an
22488 itemized list in org-mode syntax in an HTML buffer and then use this
22489 command to convert it."
22490 (interactive "r")
22491 (let (reg html buf pop-up-frames)
22492 (save-window-excursion
22493 (if (org-mode-p)
22494 (setq html (org-export-region-as-html
22495 beg end t 'string))
22496 (setq reg (buffer-substring beg end)
22497 buf (get-buffer-create "*Org tmp*"))
22498 (with-current-buffer buf
22499 (erase-buffer)
22500 (insert reg)
22501 (org-mode)
22502 (setq html (org-export-region-as-html
22503 (point-min) (point-max) t 'string)))
22504 (kill-buffer buf)))
22505 (delete-region beg end)
22506 (insert html)))
22508 (defun org-export-region-as-html (beg end &optional body-only buffer)
22509 "Convert region from BEG to END in org-mode buffer to HTML.
22510 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
22511 contents, and only produce the region of converted text, useful for
22512 cut-and-paste operations.
22513 If BUFFER is a buffer or a string, use/create that buffer as a target
22514 of the converted HTML. If BUFFER is the symbol `string', return the
22515 produced HTML as a string and leave not buffer behind. For example,
22516 a Lisp program could call this function in the following way:
22518 (setq html (org-export-region-as-html beg end t 'string))
22520 When called interactively, the output buffer is selected, and shown
22521 in a window. A non-interactive call will only retunr the buffer."
22522 (interactive "r\nP")
22523 (when (interactive-p)
22524 (setq buffer "*Org HTML Export*"))
22525 (let ((transient-mark-mode t) (zmacs-regions t)
22526 rtn)
22527 (goto-char end)
22528 (set-mark (point)) ;; to activate the region
22529 (goto-char beg)
22530 (setq rtn (org-export-as-html
22531 nil nil nil
22532 buffer body-only))
22533 (if (fboundp 'deactivate-mark) (deactivate-mark))
22534 (if (and (interactive-p) (bufferp rtn))
22535 (switch-to-buffer-other-window rtn)
22536 rtn)))
22538 (defun org-export-as-html (arg &optional hidden ext-plist
22539 to-buffer body-only)
22540 "Export the outline as a pretty HTML file.
22541 If there is an active region, export only the region. The prefix
22542 ARG specifies how many levels of the outline should become
22543 headlines. The default is 3. Lower levels will become bulleted
22544 lists. When HIDDEN is non-nil, don't display the HTML buffer.
22545 EXT-PLIST is a property list with external parameters overriding
22546 org-mode's default settings, but still inferior to file-local
22547 settings. When TO-BUFFER is non-nil, create a buffer with that
22548 name and export to that buffer. If TO-BUFFER is the symbol `string',
22549 don't leave any buffer behind but just return the resulting HTML as
22550 a string. When BODY-ONLY is set, don't produce the file header and footer,
22551 simply return the content of <body>...</body>, without even
22552 the body tags themselves."
22553 (interactive "P")
22555 ;; Make sure we have a file name when we need it.
22556 (when (and (not (or to-buffer body-only))
22557 (not buffer-file-name))
22558 (if (buffer-base-buffer)
22559 (org-set-local 'buffer-file-name
22560 (with-current-buffer (buffer-base-buffer)
22561 buffer-file-name))
22562 (error "Need a file name to be able to export.")))
22564 (message "Exporting...")
22565 (setq-default org-todo-line-regexp org-todo-line-regexp)
22566 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
22567 (setq-default org-done-keywords org-done-keywords)
22568 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
22569 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
22570 ext-plist
22571 (org-infile-export-plist)))
22573 (style (plist-get opt-plist :style))
22574 (link-validate (plist-get opt-plist :link-validation-function))
22575 valid thetoc have-headings first-heading-pos
22576 (odd org-odd-levels-only)
22577 (region-p (org-region-active-p))
22578 (subtree-p
22579 (when region-p
22580 (save-excursion
22581 (goto-char (region-beginning))
22582 (and (org-at-heading-p)
22583 (>= (org-end-of-subtree t t) (region-end))))))
22584 ;; The following two are dynamically scoped into other
22585 ;; routines below.
22586 (org-current-export-dir (org-export-directory :html opt-plist))
22587 (org-current-export-file buffer-file-name)
22588 (level 0) (line "") (origline "") txt todo
22589 (umax nil)
22590 (umax-toc nil)
22591 (filename (if to-buffer nil
22592 (concat (file-name-as-directory
22593 (org-export-directory :html opt-plist))
22594 (file-name-sans-extension
22595 (or (and subtree-p
22596 (org-entry-get (region-beginning)
22597 "EXPORT_FILE_NAME" t))
22598 (file-name-nondirectory buffer-file-name)))
22599 "." org-export-html-extension)))
22600 (current-dir (if buffer-file-name
22601 (file-name-directory buffer-file-name)
22602 default-directory))
22603 (buffer (if to-buffer
22604 (cond
22605 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
22606 (t (get-buffer-create to-buffer)))
22607 (find-file-noselect filename)))
22608 (org-levels-open (make-vector org-level-max nil))
22609 (date (plist-get opt-plist :date))
22610 (author (plist-get opt-plist :author))
22611 (title (or (and subtree-p (org-export-get-title-from-subtree))
22612 (plist-get opt-plist :title)
22613 (and (not
22614 (plist-get opt-plist :skip-before-1st-heading))
22615 (org-export-grab-title-from-buffer))
22616 (and buffer-file-name
22617 (file-name-sans-extension
22618 (file-name-nondirectory buffer-file-name)))
22619 "UNTITLED"))
22620 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
22621 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
22622 (inquote nil)
22623 (infixed nil)
22624 (in-local-list nil)
22625 (local-list-num nil)
22626 (local-list-indent nil)
22627 (llt org-plain-list-ordered-item-terminator)
22628 (email (plist-get opt-plist :email))
22629 (language (plist-get opt-plist :language))
22630 (lang-words nil)
22631 (target-alist nil) tg
22632 (head-count 0) cnt
22633 (start 0)
22634 (coding-system (and (boundp 'buffer-file-coding-system)
22635 buffer-file-coding-system))
22636 (coding-system-for-write (or org-export-html-coding-system
22637 coding-system))
22638 (save-buffer-coding-system (or org-export-html-coding-system
22639 coding-system))
22640 (charset (and coding-system-for-write
22641 (fboundp 'coding-system-get)
22642 (coding-system-get coding-system-for-write
22643 'mime-charset)))
22644 (region
22645 (buffer-substring
22646 (if region-p (region-beginning) (point-min))
22647 (if region-p (region-end) (point-max))))
22648 (lines
22649 (org-split-string
22650 (org-cleaned-string-for-export
22651 region
22652 :emph-multiline t
22653 :for-html t
22654 :skip-before-1st-heading
22655 (plist-get opt-plist :skip-before-1st-heading)
22656 :archived-trees
22657 (plist-get opt-plist :archived-trees)
22658 :add-text
22659 (plist-get opt-plist :text)
22660 :LaTeX-fragments
22661 (plist-get opt-plist :LaTeX-fragments))
22662 "[\r\n]"))
22663 table-open type
22664 table-buffer table-orig-buffer
22665 ind start-is-num starter didclose
22666 rpl path desc descp desc1 desc2 link
22669 (let ((inhibit-read-only t))
22670 (org-unmodified
22671 (remove-text-properties (point-min) (point-max)
22672 '(:org-license-to-kill t))))
22674 (message "Exporting...")
22676 (setq org-min-level (org-get-min-level lines))
22677 (setq org-last-level org-min-level)
22678 (org-init-section-numbers)
22680 (cond
22681 ((and date (string-match "%" date))
22682 (setq date (format-time-string date (current-time))))
22683 (date)
22684 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
22686 ;; Get the language-dependent settings
22687 (setq lang-words (or (assoc language org-export-language-setup)
22688 (assoc "en" org-export-language-setup)))
22690 ;; Switch to the output buffer
22691 (set-buffer buffer)
22692 (erase-buffer)
22693 (fundamental-mode)
22695 (and (fboundp 'set-buffer-file-coding-system)
22696 (set-buffer-file-coding-system coding-system-for-write))
22698 (let ((case-fold-search nil)
22699 (org-odd-levels-only odd))
22700 ;; create local variables for all options, to make sure all called
22701 ;; functions get the correct information
22702 (mapcar (lambda (x)
22703 (set (make-local-variable (cdr x))
22704 (plist-get opt-plist (car x))))
22705 org-export-plist-vars)
22706 (setq umax (if arg (prefix-numeric-value arg)
22707 org-export-headline-levels))
22708 (setq umax-toc (if (integerp org-export-with-toc)
22709 (min org-export-with-toc umax)
22710 umax))
22711 (unless body-only
22712 ;; File header
22713 (insert (format
22714 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
22715 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
22716 <html xmlns=\"http://www.w3.org/1999/xhtml\"
22717 lang=\"%s\" xml:lang=\"%s\">
22718 <head>
22719 <title>%s</title>
22720 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
22721 <meta name=\"generator\" content=\"Org-mode\"/>
22722 <meta name=\"generated\" content=\"%s\"/>
22723 <meta name=\"author\" content=\"%s\"/>
22725 </head><body>
22727 language language (org-html-expand title)
22728 (or charset "iso-8859-1") date author style))
22730 (insert (or (plist-get opt-plist :preamble) ""))
22732 (when (plist-get opt-plist :auto-preamble)
22733 (if title (insert (format org-export-html-title-format
22734 (org-html-expand title))))))
22736 (if (and org-export-with-toc (not body-only))
22737 (progn
22738 (push (format "<h%d>%s</h%d>\n"
22739 org-export-html-toplevel-hlevel
22740 (nth 3 lang-words)
22741 org-export-html-toplevel-hlevel)
22742 thetoc)
22743 (push "<ul>\n<li>" thetoc)
22744 (setq lines
22745 (mapcar '(lambda (line)
22746 (if (string-match org-todo-line-regexp line)
22747 ;; This is a headline
22748 (progn
22749 (setq have-headings t)
22750 (setq level (- (match-end 1) (match-beginning 1))
22751 level (org-tr-level level)
22752 txt (save-match-data
22753 (org-html-expand
22754 (org-export-cleanup-toc-line
22755 (match-string 3 line))))
22756 todo
22757 (or (and org-export-mark-todo-in-toc
22758 (match-beginning 2)
22759 (not (member (match-string 2 line)
22760 org-done-keywords)))
22761 ; TODO, not DONE
22762 (and org-export-mark-todo-in-toc
22763 (= level umax-toc)
22764 (org-search-todo-below
22765 line lines level))))
22766 (if (and (memq org-export-with-tags '(not-in-toc nil))
22767 (string-match
22768 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
22769 txt))
22770 (setq txt (replace-match "" t t txt)))
22771 (if (string-match quote-re0 txt)
22772 (setq txt (replace-match "" t t txt)))
22773 (if org-export-with-section-numbers
22774 (setq txt (concat (org-section-number level)
22775 " " txt)))
22776 (if (<= level (max umax umax-toc))
22777 (setq head-count (+ head-count 1)))
22778 (if (<= level umax-toc)
22779 (progn
22780 (if (> level org-last-level)
22781 (progn
22782 (setq cnt (- level org-last-level))
22783 (while (>= (setq cnt (1- cnt)) 0)
22784 (push "\n<ul>\n<li>" thetoc))
22785 (push "\n" thetoc)))
22786 (if (< level org-last-level)
22787 (progn
22788 (setq cnt (- org-last-level level))
22789 (while (>= (setq cnt (1- cnt)) 0)
22790 (push "</li>\n</ul>" thetoc))
22791 (push "\n" thetoc)))
22792 ;; Check for targets
22793 (while (string-match org-target-regexp line)
22794 (setq tg (match-string 1 line)
22795 line (replace-match
22796 (concat "@<span class=\"target\">" tg "@</span> ")
22797 t t line))
22798 (push (cons (org-solidify-link-text tg)
22799 (format "sec-%d" head-count))
22800 target-alist))
22801 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
22802 (setq txt (replace-match "" t t txt)))
22803 (push
22804 (format
22805 (if todo
22806 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
22807 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
22808 head-count txt) thetoc)
22810 (setq org-last-level level))
22812 line)
22813 lines))
22814 (while (> org-last-level (1- org-min-level))
22815 (setq org-last-level (1- org-last-level))
22816 (push "</li>\n</ul>\n" thetoc))
22817 (setq thetoc (if have-headings (nreverse thetoc) nil))))
22819 (setq head-count 0)
22820 (org-init-section-numbers)
22822 (while (setq line (pop lines) origline line)
22823 (catch 'nextline
22825 ;; end of quote section?
22826 (when (and inquote (string-match "^\\*+ " line))
22827 (insert "</pre>\n")
22828 (setq inquote nil))
22829 ;; inside a quote section?
22830 (when inquote
22831 (insert (org-html-protect line) "\n")
22832 (throw 'nextline nil))
22834 ;; verbatim lines
22835 (when (and org-export-with-fixed-width
22836 (string-match "^[ \t]*:\\(.*\\)" line))
22837 (when (not infixed)
22838 (setq infixed t)
22839 (insert "<pre>\n"))
22840 (insert (org-html-protect (match-string 1 line)) "\n")
22841 (when (and lines
22842 (not (string-match "^[ \t]*\\(:.*\\)"
22843 (car lines))))
22844 (setq infixed nil)
22845 (insert "</pre>\n"))
22846 (throw 'nextline nil))
22848 ;; Protected HTML
22849 (when (get-text-property 0 'org-protected line)
22850 (let (par)
22851 (when (re-search-backward
22852 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
22853 (setq par (match-string 1))
22854 (replace-match "\\2\n"))
22855 (insert line "\n")
22856 (while (and lines
22857 (get-text-property 0 'org-protected (car lines)))
22858 (insert (pop lines) "\n"))
22859 (and par (insert "<p>\n")))
22860 (throw 'nextline nil))
22862 ;; Horizontal line
22863 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
22864 (insert "\n<hr/>\n")
22865 (throw 'nextline nil))
22867 ;; make targets to anchors
22868 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
22869 (cond
22870 ((match-end 2)
22871 (setq line (replace-match
22872 (concat "@<a name=\""
22873 (org-solidify-link-text (match-string 1 line))
22874 "\">\\nbsp@</a>")
22875 t t line)))
22876 ((and org-export-with-toc (equal (string-to-char line) ?*))
22877 (setq line (replace-match
22878 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
22879 ; (concat "@<i>" (match-string 1 line) "@</i> ")
22880 t t line)))
22882 (setq line (replace-match
22883 (concat "@<a name=\""
22884 (org-solidify-link-text (match-string 1 line))
22885 "\" class=\"target\">" (match-string 1 line) "@</a> ")
22886 t t line)))))
22888 (setq line (org-html-handle-time-stamps line))
22890 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
22891 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
22892 ;; Also handle sub_superscripts and checkboxes
22893 (setq line (org-html-expand line))
22895 ;; Format the links
22896 (setq start 0)
22897 (while (string-match org-bracket-link-analytic-regexp line start)
22898 (setq start (match-beginning 0))
22899 (setq type (if (match-end 2) (match-string 2 line) "internal"))
22900 (setq path (match-string 3 line))
22901 (setq desc1 (if (match-end 5) (match-string 5 line))
22902 desc2 (if (match-end 2) (concat type ":" path) path)
22903 descp (and desc1 (not (equal desc1 desc2)))
22904 desc (or desc1 desc2))
22905 ;; Make an image out of the description if that is so wanted
22906 (when (and descp (org-file-image-p desc))
22907 (save-match-data
22908 (if (string-match "^file:" desc)
22909 (setq desc (substring desc (match-end 0)))))
22910 (setq desc (concat "<img src=\"" desc "\"/>")))
22911 ;; FIXME: do we need to unescape here somewhere?
22912 (cond
22913 ((equal type "internal")
22914 (setq rpl
22915 (concat
22916 "<a href=\"#"
22917 (org-solidify-link-text
22918 (save-match-data (org-link-unescape path)) target-alist)
22919 "\">" desc "</a>")))
22920 ((member type '("http" "https"))
22921 ;; standard URL, just check if we need to inline an image
22922 (if (and (or (eq t org-export-html-inline-images)
22923 (and org-export-html-inline-images (not descp)))
22924 (org-file-image-p path))
22925 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
22926 (setq link (concat type ":" path))
22927 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
22928 ((member type '("ftp" "mailto" "news"))
22929 ;; standard URL
22930 (setq link (concat type ":" path))
22931 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
22932 ((string= type "file")
22933 ;; FILE link
22934 (let* ((filename path)
22935 (abs-p (file-name-absolute-p filename))
22936 thefile file-is-image-p search)
22937 (save-match-data
22938 (if (string-match "::\\(.*\\)" filename)
22939 (setq search (match-string 1 filename)
22940 filename (replace-match "" t nil filename)))
22941 (setq valid
22942 (if (functionp link-validate)
22943 (funcall link-validate filename current-dir)
22945 (setq file-is-image-p (org-file-image-p filename))
22946 (setq thefile (if abs-p (expand-file-name filename) filename))
22947 (when (and org-export-html-link-org-files-as-html
22948 (string-match "\\.org$" thefile))
22949 (setq thefile (concat (substring thefile 0
22950 (match-beginning 0))
22951 "." org-export-html-extension))
22952 (if (and search
22953 ;; make sure this is can be used as target search
22954 (not (string-match "^[0-9]*$" search))
22955 (not (string-match "^\\*" search))
22956 (not (string-match "^/.*/$" search)))
22957 (setq thefile (concat thefile "#"
22958 (org-solidify-link-text
22959 (org-link-unescape search)))))
22960 (when (string-match "^file:" desc)
22961 (setq desc (replace-match "" t t desc))
22962 (if (string-match "\\.org$" desc)
22963 (setq desc (replace-match "" t t desc))))))
22964 (setq rpl (if (and file-is-image-p
22965 (or (eq t org-export-html-inline-images)
22966 (and org-export-html-inline-images
22967 (not descp))))
22968 (concat "<img src=\"" thefile "\"/>")
22969 (concat "<a href=\"" thefile "\">" desc "</a>")))
22970 (if (not valid) (setq rpl desc))))
22971 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
22972 (setq rpl (concat "<i>&lt;" type ":"
22973 (save-match-data (org-link-unescape path))
22974 "&gt;</i>"))))
22975 (setq line (replace-match rpl t t line)
22976 start (+ start (length rpl))))
22978 ;; TODO items
22979 (if (and (string-match org-todo-line-regexp line)
22980 (match-beginning 2))
22982 (setq line
22983 (concat (substring line 0 (match-beginning 2))
22984 "<span class=\""
22985 (if (member (match-string 2 line)
22986 org-done-keywords)
22987 "done" "todo")
22988 "\">" (match-string 2 line)
22989 "</span>" (substring line (match-end 2)))))
22991 ;; Does this contain a reference to a footnote?
22992 (when org-export-with-footnotes
22993 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line)
22994 (let ((n (match-string 2 line)))
22995 (setq line
22996 (replace-match
22997 (format
22998 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
22999 (match-string 1 line) n n n)
23000 t t line)))))
23002 (cond
23003 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
23004 ;; This is a headline
23005 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
23006 txt (match-string 2 line))
23007 (if (string-match quote-re0 txt)
23008 (setq txt (replace-match "" t t txt)))
23009 (if (<= level (max umax umax-toc))
23010 (setq head-count (+ head-count 1)))
23011 (when in-local-list
23012 ;; Close any local lists before inserting a new header line
23013 (while local-list-num
23014 (org-close-li)
23015 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
23016 (pop local-list-num))
23017 (setq local-list-indent nil
23018 in-local-list nil))
23019 (setq first-heading-pos (or first-heading-pos (point)))
23020 (org-html-level-start level txt umax
23021 (and org-export-with-toc (<= level umax))
23022 head-count)
23023 ;; QUOTES
23024 (when (string-match quote-re line)
23025 (insert "<pre>")
23026 (setq inquote t)))
23028 ((and org-export-with-tables
23029 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
23030 (if (not table-open)
23031 ;; New table starts
23032 (setq table-open t table-buffer nil table-orig-buffer nil))
23033 ;; Accumulate lines
23034 (setq table-buffer (cons line table-buffer)
23035 table-orig-buffer (cons origline table-orig-buffer))
23036 (when (or (not lines)
23037 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
23038 (car lines))))
23039 (setq table-open nil
23040 table-buffer (nreverse table-buffer)
23041 table-orig-buffer (nreverse table-orig-buffer))
23042 (org-close-par-maybe)
23043 (insert (org-format-table-html table-buffer table-orig-buffer))))
23045 ;; Normal lines
23046 (when (string-match
23047 (cond
23048 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23049 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23050 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23051 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
23052 line)
23053 (setq ind (org-get-string-indentation line)
23054 start-is-num (match-beginning 4)
23055 starter (if (match-beginning 2)
23056 (substring (match-string 2 line) 0 -1))
23057 line (substring line (match-beginning 5)))
23058 (unless (string-match "[^ \t]" line)
23059 ;; empty line. Pretend indentation is large.
23060 (setq ind (if org-empty-line-terminates-plain-lists
23062 (1+ (or (car local-list-indent) 1)))))
23063 (setq didclose nil)
23064 (while (and in-local-list
23065 (or (and (= ind (car local-list-indent))
23066 (not starter))
23067 (< ind (car local-list-indent))))
23068 (setq didclose t)
23069 (org-close-li)
23070 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
23071 (pop local-list-num) (pop local-list-indent)
23072 (setq in-local-list local-list-indent))
23073 (cond
23074 ((and starter
23075 (or (not in-local-list)
23076 (> ind (car local-list-indent))))
23077 ;; Start new (level of) list
23078 (org-close-par-maybe)
23079 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
23080 (push start-is-num local-list-num)
23081 (push ind local-list-indent)
23082 (setq in-local-list t))
23083 (starter
23084 ;; continue current list
23085 (org-close-li)
23086 (insert "<li>\n"))
23087 (didclose
23088 ;; we did close a list, normal text follows: need <p>
23089 (org-open-par)))
23090 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
23091 (setq line
23092 (replace-match
23093 (if (equal (match-string 1 line) "X")
23094 "<b>[X]</b>"
23095 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
23096 t t line))))
23098 ;; Empty lines start a new paragraph. If hand-formatted lists
23099 ;; are not fully interpreted, lines starting with "-", "+", "*"
23100 ;; also start a new paragraph.
23101 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
23103 ;; Is this the start of a footnote?
23104 (when org-export-with-footnotes
23105 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
23106 (org-close-par-maybe)
23107 (let ((n (match-string 1 line)))
23108 (setq line (replace-match
23109 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
23111 ;; Check if the line break needs to be conserved
23112 (cond
23113 ((string-match "\\\\\\\\[ \t]*$" line)
23114 (setq line (replace-match "<br/>" t t line)))
23115 (org-export-preserve-breaks
23116 (setq line (concat line "<br/>"))))
23118 (insert line "\n")))))
23120 ;; Properly close all local lists and other lists
23121 (when inquote (insert "</pre>\n"))
23122 (when in-local-list
23123 ;; Close any local lists before inserting a new header line
23124 (while local-list-num
23125 (org-close-li)
23126 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
23127 (pop local-list-num))
23128 (setq local-list-indent nil
23129 in-local-list nil))
23130 (org-html-level-start 1 nil umax
23131 (and org-export-with-toc (<= level umax))
23132 head-count)
23134 (unless body-only
23135 (when (plist-get opt-plist :auto-postamble)
23136 (when (and org-export-author-info author)
23137 (insert "<p class=\"author\"> "
23138 (nth 1 lang-words) ": " author "\n")
23139 (when email
23140 (insert "<a href=\"mailto:" email "\">&lt;"
23141 email "&gt;</a>\n"))
23142 (insert "</p>\n"))
23143 (when (and date org-export-time-stamp-file)
23144 (insert "<p class=\"date\"> "
23145 (nth 2 lang-words) ": "
23146 date "</p>\n")))
23148 (if org-export-html-with-timestamp
23149 (insert org-export-html-html-helper-timestamp))
23150 (insert (or (plist-get opt-plist :postamble) ""))
23151 (insert "</body>\n</html>\n"))
23153 (normal-mode)
23154 (if (eq major-mode default-major-mode) (html-mode))
23156 ;; insert the table of contents
23157 (goto-char (point-min))
23158 (when thetoc
23159 (if (or (re-search-forward
23160 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
23161 (re-search-forward
23162 "\\[TABLE-OF-CONTENTS\\]" nil t))
23163 (progn
23164 (goto-char (match-beginning 0))
23165 (replace-match ""))
23166 (goto-char first-heading-pos)
23167 (when (looking-at "\\s-*</p>")
23168 (goto-char (match-end 0))
23169 (insert "\n")))
23170 (mapc 'insert thetoc))
23171 ;; remove empty paragraphs and lists
23172 (goto-char (point-min))
23173 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
23174 (replace-match ""))
23175 (goto-char (point-min))
23176 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
23177 (replace-match ""))
23178 (or to-buffer (save-buffer))
23179 (goto-char (point-min))
23180 (message "Exporting... done")
23181 (if (eq to-buffer 'string)
23182 (prog1 (buffer-substring (point-min) (point-max))
23183 (kill-buffer (current-buffer)))
23184 (current-buffer)))))
23186 (defvar org-table-colgroup-info nil)
23187 (defun org-format-table-ascii (lines)
23188 "Format a table for ascii export."
23189 (if (stringp lines)
23190 (setq lines (org-split-string lines "\n")))
23191 (if (not (string-match "^[ \t]*|" (car lines)))
23192 ;; Table made by table.el - test for spanning
23193 lines
23195 ;; A normal org table
23196 ;; Get rid of hlines at beginning and end
23197 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
23198 (setq lines (nreverse lines))
23199 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
23200 (setq lines (nreverse lines))
23201 (when org-export-table-remove-special-lines
23202 ;; Check if the table has a marking column. If yes remove the
23203 ;; column and the special lines
23204 (setq lines (org-table-clean-before-export lines)))
23205 ;; Get rid of the vertical lines except for grouping
23206 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
23207 rtn line vl1 start)
23208 (while (setq line (pop lines))
23209 (if (string-match org-table-hline-regexp line)
23210 (and (string-match "|\\(.*\\)|" line)
23211 (setq line (replace-match " \\1" t nil line)))
23212 (setq start 0 vl1 vl)
23213 (while (string-match "|" line start)
23214 (setq start (match-end 0))
23215 (or (pop vl1) (setq line (replace-match " " t t line)))))
23216 (push line rtn))
23217 (nreverse rtn))))
23219 (defun org-colgroup-info-to-vline-list (info)
23220 (let (vl new last)
23221 (while info
23222 (setq last new new (pop info))
23223 (if (or (memq last '(:end :startend))
23224 (memq new '(:start :startend)))
23225 (push t vl)
23226 (push nil vl)))
23227 (setq vl (nreverse vl))
23228 (and vl (setcar vl nil))
23229 vl))
23231 (defun org-format-table-html (lines olines)
23232 "Find out which HTML converter to use and return the HTML code."
23233 (if (stringp lines)
23234 (setq lines (org-split-string lines "\n")))
23235 (if (string-match "^[ \t]*|" (car lines))
23236 ;; A normal org table
23237 (org-format-org-table-html lines)
23238 ;; Table made by table.el - test for spanning
23239 (let* ((hlines (delq nil (mapcar
23240 (lambda (x)
23241 (if (string-match "^[ \t]*\\+-" x) x
23242 nil))
23243 lines)))
23244 (first (car hlines))
23245 (ll (and (string-match "\\S-+" first)
23246 (match-string 0 first)))
23247 (re (concat "^[ \t]*" (regexp-quote ll)))
23248 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
23249 hlines))))
23250 (if (and (not spanning)
23251 (not org-export-prefer-native-exporter-for-tables))
23252 ;; We can use my own converter with HTML conversions
23253 (org-format-table-table-html lines)
23254 ;; Need to use the code generator in table.el, with the original text.
23255 (org-format-table-table-html-using-table-generate-source olines)))))
23257 (defun org-format-org-table-html (lines &optional splice)
23258 "Format a table into HTML."
23259 ;; Get rid of hlines at beginning and end
23260 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
23261 (setq lines (nreverse lines))
23262 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
23263 (setq lines (nreverse lines))
23264 (when org-export-table-remove-special-lines
23265 ;; Check if the table has a marking column. If yes remove the
23266 ;; column and the special lines
23267 (setq lines (org-table-clean-before-export lines)))
23269 (let ((head (and org-export-highlight-first-table-line
23270 (delq nil (mapcar
23271 (lambda (x) (string-match "^[ \t]*|-" x))
23272 (cdr lines)))))
23273 (nlines 0) fnum i
23274 tbopen line fields html gr colgropen)
23275 (if splice (setq head nil))
23276 (unless splice (push (if head "<thead>" "<tbody>") html))
23277 (setq tbopen t)
23278 (while (setq line (pop lines))
23279 (catch 'next-line
23280 (if (string-match "^[ \t]*|-" line)
23281 (progn
23282 (unless splice
23283 (push (if head "</thead>" "</tbody>") html)
23284 (if lines (push "<tbody>" html) (setq tbopen nil)))
23285 (setq head nil) ;; head ends here, first time around
23286 ;; ignore this line
23287 (throw 'next-line t)))
23288 ;; Break the line into fields
23289 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
23290 (unless fnum (setq fnum (make-vector (length fields) 0)))
23291 (setq nlines (1+ nlines) i -1)
23292 (push (concat "<tr>"
23293 (mapconcat
23294 (lambda (x)
23295 (setq i (1+ i))
23296 (if (and (< i nlines)
23297 (string-match org-table-number-regexp x))
23298 (incf (aref fnum i)))
23299 (if head
23300 (concat (car org-export-table-header-tags) x
23301 (cdr org-export-table-header-tags))
23302 (concat (car org-export-table-data-tags) x
23303 (cdr org-export-table-data-tags))))
23304 fields "")
23305 "</tr>")
23306 html)))
23307 (unless splice (if tbopen (push "</tbody>" html)))
23308 (unless splice (push "</table>\n" html))
23309 (setq html (nreverse html))
23310 (unless splice
23311 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
23312 (push (mapconcat
23313 (lambda (x)
23314 (setq gr (pop org-table-colgroup-info))
23315 (format "%s<COL align=\"%s\"></COL>%s"
23316 (if (memq gr '(:start :startend))
23317 (prog1
23318 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
23319 (setq colgropen t))
23321 (if (> (/ (float x) nlines) org-table-number-fraction)
23322 "right" "left")
23323 (if (memq gr '(:end :startend))
23324 (progn (setq colgropen nil) "</colgroup>")
23325 "")))
23326 fnum "")
23327 html)
23328 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
23329 (push org-export-html-table-tag html))
23330 (concat (mapconcat 'identity html "\n") "\n")))
23332 (defun org-table-clean-before-export (lines)
23333 "Check if the table has a marking column.
23334 If yes remove the column and the special lines."
23335 (setq org-table-colgroup-info nil)
23336 (if (memq nil
23337 (mapcar
23338 (lambda (x) (or (string-match "^[ \t]*|-" x)
23339 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
23340 lines))
23341 (progn
23342 (setq org-table-clean-did-remove-column nil)
23343 (delq nil
23344 (mapcar
23345 (lambda (x)
23346 (cond
23347 ((string-match "^[ \t]*| */ *|" x)
23348 (setq org-table-colgroup-info
23349 (mapcar (lambda (x)
23350 (cond ((member x '("<" "&lt;")) :start)
23351 ((member x '(">" "&gt;")) :end)
23352 ((member x '("<>" "&lt;&gt;")) :startend)
23353 (t nil)))
23354 (org-split-string x "[ \t]*|[ \t]*")))
23355 nil)
23356 (t x)))
23357 lines)))
23358 (setq org-table-clean-did-remove-column t)
23359 (delq nil
23360 (mapcar
23361 (lambda (x)
23362 (cond
23363 ((string-match "^[ \t]*| */ *|" x)
23364 (setq org-table-colgroup-info
23365 (mapcar (lambda (x)
23366 (cond ((member x '("<" "&lt;")) :start)
23367 ((member x '(">" "&gt;")) :end)
23368 ((member x '("<>" "&lt;&gt;")) :startend)
23369 (t nil)))
23370 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
23371 nil)
23372 ((string-match "^[ \t]*| *[!_^/] *|" x)
23373 nil) ; ignore this line
23374 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
23375 (string-match "^\\([ \t]*\\)|[^|]*|" x))
23376 ;; remove the first column
23377 (replace-match "\\1|" t nil x))
23378 (t (error "This should not happen"))))
23379 lines))))
23381 (defun org-format-table-table-html (lines)
23382 "Format a table generated by table.el into HTML.
23383 This conversion does *not* use `table-generate-source' from table.el.
23384 This has the advantage that Org-mode's HTML conversions can be used.
23385 But it has the disadvantage, that no cell- or row-spanning is allowed."
23386 (let (line field-buffer
23387 (head org-export-highlight-first-table-line)
23388 fields html empty)
23389 (setq html (concat org-export-html-table-tag "\n"))
23390 (while (setq line (pop lines))
23391 (setq empty "&nbsp;")
23392 (catch 'next-line
23393 (if (string-match "^[ \t]*\\+-" line)
23394 (progn
23395 (if field-buffer
23396 (progn
23397 (setq
23398 html
23399 (concat
23400 html
23401 "<tr>"
23402 (mapconcat
23403 (lambda (x)
23404 (if (equal x "") (setq x empty))
23405 (if head
23406 (concat (car org-export-table-header-tags) x
23407 (cdr org-export-table-header-tags))
23408 (concat (car org-export-table-data-tags) x
23409 (cdr org-export-table-data-tags))))
23410 field-buffer "\n")
23411 "</tr>\n"))
23412 (setq head nil)
23413 (setq field-buffer nil)))
23414 ;; Ignore this line
23415 (throw 'next-line t)))
23416 ;; Break the line into fields and store the fields
23417 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
23418 (if field-buffer
23419 (setq field-buffer (mapcar
23420 (lambda (x)
23421 (concat x "<br/>" (pop fields)))
23422 field-buffer))
23423 (setq field-buffer fields))))
23424 (setq html (concat html "</table>\n"))
23425 html))
23427 (defun org-format-table-table-html-using-table-generate-source (lines)
23428 "Format a table into html, using `table-generate-source' from table.el.
23429 This has the advantage that cell- or row-spanning is allowed.
23430 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
23431 (require 'table)
23432 (with-current-buffer (get-buffer-create " org-tmp1 ")
23433 (erase-buffer)
23434 (insert (mapconcat 'identity lines "\n"))
23435 (goto-char (point-min))
23436 (if (not (re-search-forward "|[^+]" nil t))
23437 (error "Error processing table"))
23438 (table-recognize-table)
23439 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
23440 (table-generate-source 'html " org-tmp2 ")
23441 (set-buffer " org-tmp2 ")
23442 (buffer-substring (point-min) (point-max))))
23444 (defun org-html-handle-time-stamps (s)
23445 "Format time stamps in string S, or remove them."
23446 (catch 'exit
23447 (let (r b)
23448 (while (string-match org-maybe-keyword-time-regexp s)
23449 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
23450 ;; never export CLOCK
23451 (throw 'exit ""))
23452 (or b (setq b (substring s 0 (match-beginning 0))))
23453 (if (not org-export-with-timestamps)
23454 (setq r (concat r (substring s 0 (match-beginning 0)))
23455 s (substring s (match-end 0)))
23456 (setq r (concat
23457 r (substring s 0 (match-beginning 0))
23458 (if (match-end 1)
23459 (format "@<span class=\"timestamp-kwd\">%s @</span>"
23460 (match-string 1 s)))
23461 (format " @<span class=\"timestamp\">%s@</span>"
23462 (substring
23463 (org-translate-time (match-string 3 s)) 1 -1)))
23464 s (substring s (match-end 0)))))
23465 ;; Line break if line started and ended with time stamp stuff
23466 (if (not r)
23468 (setq r (concat r s))
23469 (unless (string-match "\\S-" (concat b s))
23470 (setq r (concat r "@<br/>")))
23471 r))))
23473 (defun org-html-protect (s)
23474 ;; convert & to &amp;, < to &lt; and > to &gt;
23475 (let ((start 0))
23476 (while (string-match "&" s start)
23477 (setq s (replace-match "&amp;" t t s)
23478 start (1+ (match-beginning 0))))
23479 (while (string-match "<" s)
23480 (setq s (replace-match "&lt;" t t s)))
23481 (while (string-match ">" s)
23482 (setq s (replace-match "&gt;" t t s))))
23485 (defun org-export-cleanup-toc-line (s)
23486 "Remove tags and time staps from lines going into the toc."
23487 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
23488 (setq s (replace-match "" t t s)))
23489 (when org-export-remove-timestamps-from-toc
23490 (while (string-match org-maybe-keyword-time-regexp s)
23491 (setq s (replace-match "" t t s))))
23492 (while (string-match org-bracket-link-regexp s)
23493 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
23494 t t s)))
23497 (defun org-html-expand (string)
23498 "Prepare STRING for HTML export. Applies all active conversions.
23499 If there are links in the string, don't modify these."
23500 (let* (m s l res)
23501 (while (setq m (string-match org-bracket-link-regexp string))
23502 (setq s (substring string 0 m)
23503 l (match-string 0 string)
23504 string (substring string (match-end 0)))
23505 (push (org-html-do-expand s) res)
23506 (push l res))
23507 (push (org-html-do-expand string) res)
23508 (apply 'concat (nreverse res))))
23510 (defun org-html-do-expand (s)
23511 "Apply all active conversions to translate special ASCII to HTML."
23512 (setq s (org-html-protect s))
23513 (if org-export-html-expand
23514 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
23515 (setq s (replace-match "<\\1>" t nil s))))
23516 (if org-export-with-emphasize
23517 (setq s (org-export-html-convert-emphasize s)))
23518 (if org-export-with-sub-superscripts
23519 (setq s (org-export-html-convert-sub-super s)))
23520 (if org-export-with-TeX-macros
23521 (let ((start 0) wd ass)
23522 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
23523 (setq wd (match-string 1 s))
23524 (if (setq ass (assoc wd org-html-entities))
23525 (setq s (replace-match (or (cdr ass)
23526 (concat "&" (car ass) ";"))
23527 t t s))
23528 (setq start (+ start (length wd)))))))
23531 (defun org-create-multibrace-regexp (left right n)
23532 "Create a regular expression which will match a balanced sexp.
23533 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
23534 as single character strings.
23535 The regexp returned will match the entire expression including the
23536 delimiters. It will also define a single group which contains the
23537 match except for the outermost delimiters. The maximum depth of
23538 stacked delimiters is N. Escaping delimiters is not possible."
23539 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
23540 (or "\\|")
23541 (re nothing)
23542 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
23543 (while (> n 1)
23544 (setq n (1- n)
23545 re (concat re or next)
23546 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
23547 (concat left "\\(" re "\\)" right)))
23549 (defvar org-match-substring-regexp
23550 (concat
23551 "\\([^\\]\\)\\([_^]\\)\\("
23552 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
23553 "\\|"
23554 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
23555 "\\|"
23556 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
23557 "The regular expression matching a sub- or superscript.")
23559 ;(let ((s "a\\_b"))
23560 ; (and (string-match org-match-substring-regexp s)
23561 ; (conca t (match-string 1 s) ":::" (match-string 2 s))))
23563 (defun org-export-html-convert-sub-super (string)
23564 "Convert sub- and superscripts in STRING to HTML."
23565 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
23566 (while (string-match org-match-substring-regexp string s)
23567 (if (and requireb (match-end 8))
23568 (setq s (match-end 2))
23569 (setq s (match-end 1)
23570 key (if (string= (match-string 2 string) "_") "sub" "sup")
23571 c (or (match-string 8 string)
23572 (match-string 6 string)
23573 (match-string 5 string))
23574 string (replace-match
23575 (concat (match-string 1 string)
23576 "<" key ">" c "</" key ">")
23577 t t string))))
23578 (while (string-match "\\\\\\([_^]\\)" string)
23579 (setq string (replace-match (match-string 1 string) t t string)))
23580 string))
23582 (defun org-export-html-convert-emphasize (string)
23583 "Apply emphasis."
23584 (let ((s 0))
23585 (while (string-match org-emph-re string s)
23586 (if (not (equal
23587 (substring string (match-beginning 3) (1+ (match-beginning 3)))
23588 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
23589 (setq string (replace-match
23590 (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
23591 "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist))
23592 "\\5") t nil string))
23593 (setq s (1+ s))))
23594 string))
23596 (defvar org-par-open nil)
23597 (defun org-open-par ()
23598 "Insert <p>, but first close previous paragraph if any."
23599 (org-close-par-maybe)
23600 (insert "\n<p>")
23601 (setq org-par-open t))
23602 (defun org-close-par-maybe ()
23603 "Close paragraph if there is one open."
23604 (when org-par-open
23605 (insert "</p>")
23606 (setq org-par-open nil)))
23607 (defun org-close-li ()
23608 "Close <li> if necessary."
23609 (org-close-par-maybe)
23610 (insert "</li>\n"))
23612 (defvar body-only) ; dynamically scoped into this.
23613 (defun org-html-level-start (level title umax with-toc head-count)
23614 "Insert a new level in HTML export.
23615 When TITLE is nil, just close all open levels."
23616 (org-close-par-maybe)
23617 (let ((l (1+ (max level umax))))
23618 (while (<= l org-level-max)
23619 (if (aref org-levels-open (1- l))
23620 (progn
23621 (org-html-level-close l)
23622 (aset org-levels-open (1- l) nil)))
23623 (setq l (1+ l)))
23624 (when title
23625 ;; If title is nil, this means this function is called to close
23626 ;; all levels, so the rest is done only if title is given
23627 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
23628 (setq title (replace-match
23629 (if org-export-with-tags
23630 (save-match-data
23631 (concat
23632 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
23633 (mapconcat 'identity (org-split-string
23634 (match-string 1 title) ":")
23635 "&nbsp;")
23636 "</span>"))
23638 t t title)))
23639 (if (> level umax)
23640 (progn
23641 (if (aref org-levels-open (1- level))
23642 (progn
23643 (org-close-li)
23644 (insert "<li>" title "<br/>\n"))
23645 (aset org-levels-open (1- level) t)
23646 (org-close-par-maybe)
23647 (insert "<ul>\n<li>" title "<br/>\n")))
23648 (if (and org-export-with-section-numbers (not body-only))
23649 (setq title (concat (org-section-number level) " " title)))
23650 (setq level (+ level org-export-html-toplevel-hlevel -1))
23651 (if with-toc
23652 (insert (format "\n<h%d id=\"sec-%d\">%s</h%d>\n"
23653 level head-count title level))
23654 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
23655 (org-open-par)))))
23657 (defun org-html-level-close (&rest args)
23658 "Terminate one level in HTML export."
23659 (org-close-li)
23660 (insert "</ul>\n"))
23662 ;;; iCalendar export
23664 ;;;###autoload
23665 (defun org-export-icalendar-this-file ()
23666 "Export current file as an iCalendar file.
23667 The iCalendar file will be located in the same directory as the Org-mode
23668 file, but with extension `.ics'."
23669 (interactive)
23670 (org-export-icalendar nil buffer-file-name))
23672 ;;;###autoload
23673 (defun org-export-icalendar-all-agenda-files ()
23674 "Export all files in `org-agenda-files' to iCalendar .ics files.
23675 Each iCalendar file will be located in the same directory as the Org-mode
23676 file, but with extension `.ics'."
23677 (interactive)
23678 (apply 'org-export-icalendar nil (org-agenda-files t)))
23680 ;;;###autoload
23681 (defun org-export-icalendar-combine-agenda-files ()
23682 "Export all files in `org-agenda-files' to a single combined iCalendar file.
23683 The file is stored under the name `org-combined-agenda-icalendar-file'."
23684 (interactive)
23685 (apply 'org-export-icalendar t (org-agenda-files t)))
23687 (defun org-export-icalendar (combine &rest files)
23688 "Create iCalendar files for all elements of FILES.
23689 If COMBINE is non-nil, combine all calendar entries into a single large
23690 file and store it under the name `org-combined-agenda-icalendar-file'."
23691 (save-excursion
23692 (org-prepare-agenda-buffers files)
23693 (let* ((dir (org-export-directory
23694 :ical (list :publishing-directory
23695 org-export-publishing-directory)))
23696 file ical-file ical-buffer category started org-agenda-new-buffers)
23698 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
23699 (when combine
23700 (setq ical-file
23701 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
23702 org-combined-agenda-icalendar-file
23703 (expand-file-name org-combined-agenda-icalendar-file dir))
23704 ical-buffer (org-get-agenda-file-buffer ical-file))
23705 (set-buffer ical-buffer) (erase-buffer))
23706 (while (setq file (pop files))
23707 (catch 'nextfile
23708 (org-check-agenda-file file)
23709 (set-buffer (org-get-agenda-file-buffer file))
23710 (unless combine
23711 (setq ical-file (concat (file-name-as-directory dir)
23712 (file-name-sans-extension
23713 (file-name-nondirectory buffer-file-name))
23714 ".ics"))
23715 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
23716 (with-current-buffer ical-buffer (erase-buffer)))
23717 (setq category (or org-category
23718 (file-name-sans-extension
23719 (file-name-nondirectory buffer-file-name))))
23720 (if (symbolp category) (setq category (symbol-name category)))
23721 (let ((standard-output ical-buffer))
23722 (if combine
23723 (and (not started) (setq started t)
23724 (org-start-icalendar-file org-icalendar-combined-name))
23725 (org-start-icalendar-file category))
23726 (org-print-icalendar-entries combine)
23727 (when (or (and combine (not files)) (not combine))
23728 (org-finish-icalendar-file)
23729 (set-buffer ical-buffer)
23730 (save-buffer)
23731 (run-hooks 'org-after-save-iCalendar-file-hook)))))
23732 (org-release-buffers org-agenda-new-buffers))))
23734 (defvar org-after-save-iCalendar-file-hook nil
23735 "Hook run after an iCalendar file has been saved.
23736 The iCalendar buffer is still current when this hook is run.
23737 A good way to use this is to tell a desktop calenndar application to re-read
23738 the iCalendar file.")
23740 (defun org-print-icalendar-entries (&optional combine)
23741 "Print iCalendar entries for the current Org-mode file to `standard-output'.
23742 When COMBINE is non nil, add the category to each line."
23743 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
23744 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
23745 (dts (org-ical-ts-to-string
23746 (format-time-string (cdr org-time-stamp-formats) (current-time))
23747 "DTSTART"))
23748 hd ts ts2 state status (inc t) pos b sexp rrule
23749 scheduledp deadlinep tmp pri category entry location summary desc
23750 (sexp-buffer (get-buffer-create "*ical-tmp*")))
23751 (org-refresh-category-properties)
23752 (save-excursion
23753 (goto-char (point-min))
23754 (while (re-search-forward re1 nil t)
23755 (catch :skip
23756 (org-agenda-skip)
23757 (setq pos (match-beginning 0)
23758 ts (match-string 0)
23759 inc t
23760 hd (org-get-heading)
23761 summary (org-entry-get nil "SUMMARY")
23762 desc (or (org-entry-get nil "DESCRIPTION")
23763 (org-get-cleaned-entry org-icalendar-include-body))
23764 location (org-entry-get nil "LOCATION")
23765 category (org-get-category))
23766 (if (looking-at re2)
23767 (progn
23768 (goto-char (match-end 0))
23769 (setq ts2 (match-string 1) inc nil))
23770 (setq tmp (buffer-substring (max (point-min)
23771 (- pos org-ds-keyword-length))
23772 pos)
23773 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
23774 (progn
23775 (setq inc nil)
23776 (replace-match "\\1" t nil ts))
23778 deadlinep (string-match org-deadline-regexp tmp)
23779 scheduledp (string-match org-scheduled-regexp tmp)
23780 ;; donep (org-entry-is-done-p)
23782 (if (or (string-match org-tr-regexp hd)
23783 (string-match org-ts-regexp hd))
23784 (setq hd (replace-match "" t t hd)))
23785 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
23786 (setq rrule
23787 (concat "\nRRULE:FREQ="
23788 (cdr (assoc
23789 (match-string 2 ts)
23790 '(("d" . "DAILY")("w" . "WEEKLY")
23791 ("m" . "MONTHLY")("y" . "YEARLY"))))
23792 ";INTERVAL=" (match-string 1 ts)))
23793 (setq rrule ""))
23794 (setq summary (or summary hd))
23795 (if (string-match org-bracket-link-regexp summary)
23796 (setq summary
23797 (replace-match (if (match-end 3)
23798 (match-string 3 summary)
23799 (match-string 1 summary))
23800 t t summary)))
23801 (if deadlinep (setq summary (concat "DL: " summary)))
23802 (if scheduledp (setq summary (concat "S: " summary)))
23803 (if (string-match "\\`<%%" ts)
23804 (with-current-buffer sexp-buffer
23805 (insert (substring ts 1 -1) " " summary "\n"))
23806 (princ (format "BEGIN:VEVENT
23808 %s%s
23809 SUMMARY:%s%s%s
23810 CATEGORIES:%s
23811 END:VEVENT\n"
23812 (org-ical-ts-to-string ts "DTSTART")
23813 (org-ical-ts-to-string ts2 "DTEND" inc)
23814 rrule summary
23815 (if (and desc (string-match "\\S-" desc))
23816 (concat "\nDESCRIPTION: " desc) "")
23817 (if (and location (string-match "\\S-" location))
23818 (concat "\nLOCATION: " location) "")
23819 category)))))
23821 (when (and org-icalendar-include-sexps
23822 (condition-case nil (require 'icalendar) (error nil))
23823 (fboundp 'icalendar-export-region))
23824 ;; Get all the literal sexps
23825 (goto-char (point-min))
23826 (while (re-search-forward "^&?%%(" nil t)
23827 (catch :skip
23828 (org-agenda-skip)
23829 (setq b (match-beginning 0))
23830 (goto-char (1- (match-end 0)))
23831 (forward-sexp 1)
23832 (end-of-line 1)
23833 (setq sexp (buffer-substring b (point)))
23834 (with-current-buffer sexp-buffer
23835 (insert sexp "\n"))
23836 (princ (org-diary-to-ical-string sexp-buffer)))))
23838 (when org-icalendar-include-todo
23839 (goto-char (point-min))
23840 (while (re-search-forward org-todo-line-regexp nil t)
23841 (catch :skip
23842 (org-agenda-skip)
23843 (setq state (match-string 2))
23844 (setq status (if (member state org-done-keywords)
23845 "COMPLETED" "NEEDS-ACTION"))
23846 (when (and state
23847 (or (not (member state org-done-keywords))
23848 (eq org-icalendar-include-todo 'all))
23849 (not (member org-archive-tag (org-get-tags-at)))
23851 (setq hd (match-string 3)
23852 summary (org-entry-get nil "SUMMARY")
23853 desc (or (org-entry-get nil "DESCRIPTION")
23854 (org-get-cleaned-entry org-icalendar-include-body))
23855 location (org-entry-get nil "LOCATION"))
23856 (if (string-match org-bracket-link-regexp hd)
23857 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
23858 (match-string 1 hd))
23859 t t hd)))
23860 (if (string-match org-priority-regexp hd)
23861 (setq pri (string-to-char (match-string 2 hd))
23862 hd (concat (substring hd 0 (match-beginning 1))
23863 (substring hd (match-end 1))))
23864 (setq pri org-default-priority))
23865 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
23866 (- org-lowest-priority org-highest-priority))))))
23868 (princ (format "BEGIN:VTODO
23870 SUMMARY:%s%s%s
23871 CATEGORIES:%s
23872 SEQUENCE:1
23873 PRIORITY:%d
23874 STATUS:%s
23875 END:VTODO\n"
23877 (or summary hd)
23878 (if (and location (string-match "\\S-" location))
23879 (concat "\nLOCATION: " location) "")
23880 (if (and desc (string-match "\\S-" desc))
23881 (concat "\nDESCRIPTION: " desc) "")
23882 category pri status)))))))))
23884 (defun org-get-cleaned-entry (what)
23885 "Clean-up description string."
23886 (when what
23887 (save-excursion
23888 (org-back-to-heading t)
23889 (let ((s (buffer-substring (point-at-bol 2) (org-end-of-subtree t)))
23890 (re (concat org-drawer-regexp "[^\000]*?:END:.*\n?"))
23891 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
23892 (while (string-match re s) (setq s (replace-match "" t t s)))
23893 (while (string-match re2 s) (setq s (replace-match "" t t s)))
23894 (if (string-match "[ \t\r\n]+\\'" s) (setq s (replace-match "" t t s)))
23895 (while (string-match "[ \t]*\n[ \t]*" s)
23896 (setq s (replace-match "\\n" t t s)))
23897 (setq s (org-trim s))
23898 (if (and (numberp what)
23899 (> (length s) what))
23900 (substring s 0 what)
23901 s)))))
23903 (defun org-start-icalendar-file (name)
23904 "Start an iCalendar file by inserting the header."
23905 (let ((user user-full-name)
23906 (name (or name "unknown"))
23907 (timezone (cadr (current-time-zone))))
23908 (princ
23909 (format "BEGIN:VCALENDAR
23910 VERSION:2.0
23911 X-WR-CALNAME:%s
23912 PRODID:-//%s//Emacs with Org-mode//EN
23913 X-WR-TIMEZONE:%s
23914 CALSCALE:GREGORIAN\n" name user timezone))))
23916 (defun org-finish-icalendar-file ()
23917 "Finish an iCalendar file by inserting the END statement."
23918 (princ "END:VCALENDAR\n"))
23920 (defun org-ical-ts-to-string (s keyword &optional inc)
23921 "Take a time string S and convert it to iCalendar format.
23922 KEYWORD is added in front, to make a complete line like DTSTART....
23923 When INC is non-nil, increase the hour by two (if time string contains
23924 a time), or the day by one (if it does not contain a time)."
23925 (let ((t1 (org-parse-time-string s 'nodefault))
23926 t2 fmt have-time time)
23927 (if (and (car t1) (nth 1 t1) (nth 2 t1))
23928 (setq t2 t1 have-time t)
23929 (setq t2 (org-parse-time-string s)))
23930 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
23931 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
23932 (when inc
23933 (if have-time
23934 (if org-agenda-default-appointment-duration
23935 (setq mi (+ org-agenda-default-appointment-duration mi))
23936 (setq h (+ 2 h)))
23937 (setq d (1+ d))))
23938 (setq time (encode-time s mi h d m y)))
23939 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
23940 (concat keyword (format-time-string fmt time))))
23942 ;;; XOXO export
23944 (defun org-export-as-xoxo-insert-into (buffer &rest output)
23945 (with-current-buffer buffer
23946 (apply 'insert output)))
23947 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
23949 (defun org-export-as-xoxo (&optional buffer)
23950 "Export the org buffer as XOXO.
23951 The XOXO buffer is named *xoxo-<source buffer name>*"
23952 (interactive (list (current-buffer)))
23953 ;; A quickie abstraction
23955 ;; Output everything as XOXO
23956 (with-current-buffer (get-buffer buffer)
23957 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
23958 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23959 (org-infile-export-plist)))
23960 (filename (concat (file-name-as-directory
23961 (org-export-directory :xoxo opt-plist))
23962 (file-name-sans-extension
23963 (file-name-nondirectory buffer-file-name))
23964 ".html"))
23965 (out (find-file-noselect filename))
23966 (last-level 1)
23967 (hanging-li nil))
23968 ;; Check the output buffer is empty.
23969 (with-current-buffer out (erase-buffer))
23970 ;; Kick off the output
23971 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
23972 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
23973 (let* ((hd (match-string-no-properties 1))
23974 (level (length hd))
23975 (text (concat
23976 (match-string-no-properties 2)
23977 (save-excursion
23978 (goto-char (match-end 0))
23979 (let ((str ""))
23980 (catch 'loop
23981 (while 't
23982 (forward-line)
23983 (if (looking-at "^[ \t]\\(.*\\)")
23984 (setq str (concat str (match-string-no-properties 1)))
23985 (throw 'loop str)))))))))
23987 ;; Handle level rendering
23988 (cond
23989 ((> level last-level)
23990 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
23992 ((< level last-level)
23993 (dotimes (- (- last-level level) 1)
23994 (if hanging-li
23995 (org-export-as-xoxo-insert-into out "</li>\n"))
23996 (org-export-as-xoxo-insert-into out "</ol>\n"))
23997 (when hanging-li
23998 (org-export-as-xoxo-insert-into out "</li>\n")
23999 (setq hanging-li nil)))
24001 ((equal level last-level)
24002 (if hanging-li
24003 (org-export-as-xoxo-insert-into out "</li>\n")))
24006 (setq last-level level)
24008 ;; And output the new li
24009 (setq hanging-li 't)
24010 (if (equal ?+ (elt text 0))
24011 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
24012 (org-export-as-xoxo-insert-into out "<li>" text))))
24014 ;; Finally finish off the ol
24015 (dotimes (- last-level 1)
24016 (if hanging-li
24017 (org-export-as-xoxo-insert-into out "</li>\n"))
24018 (org-export-as-xoxo-insert-into out "</ol>\n"))
24020 ;; Finish the buffer off and clean it up.
24021 (switch-to-buffer-other-window out)
24022 (indent-region (point-min) (point-max) nil)
24023 (save-buffer)
24024 (goto-char (point-min))
24028 ;;;; Key bindings
24030 ;; Make `C-c C-x' a prefix key
24031 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
24033 ;; TAB key with modifiers
24034 (org-defkey org-mode-map "\C-i" 'org-cycle)
24035 (org-defkey org-mode-map [(tab)] 'org-cycle)
24036 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
24037 (org-defkey org-mode-map [(meta tab)] 'org-complete)
24038 (org-defkey org-mode-map "\M-\t" 'org-complete)
24039 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
24040 ;; The following line is necessary under Suse GNU/Linux
24041 (unless (featurep 'xemacs)
24042 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
24043 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
24044 (define-key org-mode-map (kbd "<backtab>") 'org-shifttab)
24046 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
24047 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
24048 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
24050 ;; Cursor keys with modifiers
24051 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
24052 (org-defkey org-mode-map [(meta right)] 'org-metaright)
24053 (org-defkey org-mode-map [(meta up)] 'org-metaup)
24054 (org-defkey org-mode-map [(meta down)] 'org-metadown)
24056 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
24057 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
24058 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
24059 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
24061 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
24062 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
24063 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
24064 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
24066 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
24067 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
24069 ;;; Extra keys for tty access.
24070 ;; We only set them when really needed because otherwise the
24071 ;; menus don't show the simple keys
24073 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
24074 (not window-system))
24075 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
24076 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
24077 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
24078 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
24079 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
24080 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
24081 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
24082 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
24083 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
24084 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
24085 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
24086 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
24087 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
24088 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
24089 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
24090 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
24091 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
24092 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
24093 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
24094 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
24095 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
24096 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
24098 ;; All the other keys
24100 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
24101 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
24102 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
24103 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
24104 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
24105 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
24106 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
24107 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
24108 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
24109 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
24110 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
24111 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
24112 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
24113 (org-defkey org-mode-map "\C-c\C-w" 'org-check-deadlines)
24114 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
24115 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
24116 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
24117 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
24118 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
24119 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
24120 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
24121 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
24122 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
24123 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
24124 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
24125 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
24126 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
24127 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
24128 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
24129 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
24130 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
24131 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
24132 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
24133 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
24134 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
24135 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
24136 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
24137 (org-defkey org-mode-map "\C-c^" 'org-sort)
24138 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
24139 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
24140 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
24141 (org-defkey org-mode-map "\C-m" 'org-return)
24142 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
24143 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
24144 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
24145 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
24146 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
24147 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
24148 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
24149 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
24150 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
24151 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
24152 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
24153 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
24154 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
24155 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
24156 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
24157 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
24159 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
24160 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
24161 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
24162 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
24164 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
24165 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
24166 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
24167 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
24168 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
24169 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
24170 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
24171 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
24172 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
24173 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
24174 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
24176 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
24178 (when (featurep 'xemacs)
24179 (org-defkey org-mode-map 'button3 'popup-mode-menu))
24181 (defsubst org-table-p () (org-at-table-p))
24183 (defun org-self-insert-command (N)
24184 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
24185 If the cursor is in a table looking at whitespace, the whitespace is
24186 overwritten, and the table is not marked as requiring realignment."
24187 (interactive "p")
24188 (if (and (org-table-p)
24189 (progn
24190 ;; check if we blank the field, and if that triggers align
24191 (and org-table-auto-blank-field
24192 (member last-command
24193 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
24194 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
24195 ;; got extra space, this field does not determine column width
24196 (let (org-table-may-need-update) (org-table-blank-field))
24197 ;; no extra space, this field may determine column width
24198 (org-table-blank-field)))
24200 (eq N 1)
24201 (looking-at "[^|\n]* |"))
24202 (let (org-table-may-need-update)
24203 (goto-char (1- (match-end 0)))
24204 (delete-backward-char 1)
24205 (goto-char (match-beginning 0))
24206 (self-insert-command N))
24207 (setq org-table-may-need-update t)
24208 (self-insert-command N)
24209 (org-fix-tags-on-the-fly)))
24211 (defun org-fix-tags-on-the-fly ()
24212 (when (and (equal (char-after (point-at-bol)) ?*)
24213 (org-on-heading-p))
24214 (org-align-tags-here org-tags-column)))
24216 (defun org-delete-backward-char (N)
24217 "Like `delete-backward-char', insert whitespace at field end in tables.
24218 When deleting backwards, in tables this function will insert whitespace in
24219 front of the next \"|\" separator, to keep the table aligned. The table will
24220 still be marked for re-alignment if the field did fill the entire column,
24221 because, in this case the deletion might narrow the column."
24222 (interactive "p")
24223 (if (and (org-table-p)
24224 (eq N 1)
24225 (string-match "|" (buffer-substring (point-at-bol) (point)))
24226 (looking-at ".*?|"))
24227 (let ((pos (point))
24228 (noalign (looking-at "[^|\n\r]* |"))
24229 (c org-table-may-need-update))
24230 (backward-delete-char N)
24231 (skip-chars-forward "^|")
24232 (insert " ")
24233 (goto-char (1- pos))
24234 ;; noalign: if there were two spaces at the end, this field
24235 ;; does not determine the width of the column.
24236 (if noalign (setq org-table-may-need-update c)))
24237 (backward-delete-char N)
24238 (org-fix-tags-on-the-fly)))
24240 (defun org-delete-char (N)
24241 "Like `delete-char', but insert whitespace at field end in tables.
24242 When deleting characters, in tables this function will insert whitespace in
24243 front of the next \"|\" separator, to keep the table aligned. The table will
24244 still be marked for re-alignment if the field did fill the entire column,
24245 because, in this case the deletion might narrow the column."
24246 (interactive "p")
24247 (if (and (org-table-p)
24248 (not (bolp))
24249 (not (= (char-after) ?|))
24250 (eq N 1))
24251 (if (looking-at ".*?|")
24252 (let ((pos (point))
24253 (noalign (looking-at "[^|\n\r]* |"))
24254 (c org-table-may-need-update))
24255 (replace-match (concat
24256 (substring (match-string 0) 1 -1)
24257 " |"))
24258 (goto-char pos)
24259 ;; noalign: if there were two spaces at the end, this field
24260 ;; does not determine the width of the column.
24261 (if noalign (setq org-table-may-need-update c)))
24262 (delete-char N))
24263 (delete-char N)
24264 (org-fix-tags-on-the-fly)))
24266 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
24267 (put 'org-self-insert-command 'delete-selection t)
24268 (put 'orgtbl-self-insert-command 'delete-selection t)
24269 (put 'org-delete-char 'delete-selection 'supersede)
24270 (put 'org-delete-backward-char 'delete-selection 'supersede)
24272 ;; Make `flyspell-mode' delay after some commands
24273 (put 'org-self-insert-command 'flyspell-delayed t)
24274 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
24275 (put 'org-delete-char 'flyspell-delayed t)
24276 (put 'org-delete-backward-char 'flyspell-delayed t)
24278 (eval-after-load "pabbrev"
24279 '(progn
24280 (add-to-list 'pabbrev-expand-after-command-list
24281 'orgtbl-self-insert-command t)
24282 (add-to-list 'pabbrev-expand-after-command-list
24283 'org-self-insert-command t)))
24285 ;; How to do this: Measure non-white length of current string
24286 ;; If equal to column width, we should realign.
24288 (defun org-remap (map &rest commands)
24289 "In MAP, remap the functions given in COMMANDS.
24290 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
24291 (let (new old)
24292 (while commands
24293 (setq old (pop commands) new (pop commands))
24294 (if (fboundp 'command-remapping)
24295 (org-defkey map (vector 'remap old) new)
24296 (substitute-key-definition old new map global-map)))))
24298 (when (eq org-enable-table-editor 'optimized)
24299 ;; If the user wants maximum table support, we need to hijack
24300 ;; some standard editing functions
24301 (org-remap org-mode-map
24302 'self-insert-command 'org-self-insert-command
24303 'delete-char 'org-delete-char
24304 'delete-backward-char 'org-delete-backward-char)
24305 (org-defkey org-mode-map "|" 'org-force-self-insert))
24307 (defun org-shiftcursor-error ()
24308 "Throw an error because Shift-Cursor command was applied in wrong context."
24309 (error "This command is active in special context like tables, headlines or timestamps"))
24311 (defun org-shifttab (&optional arg)
24312 "Global visibility cycling or move to previous table field.
24313 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
24314 on context.
24315 See the individual commands for more information."
24316 (interactive "P")
24317 (cond
24318 ((org-at-table-p) (call-interactively 'org-table-previous-field))
24319 (arg (message "Content view to level: ")
24320 (org-content (prefix-numeric-value arg))
24321 (setq org-cycle-global-status 'overview))
24322 (t (call-interactively 'org-global-cycle))))
24324 (defun org-shiftmetaleft ()
24325 "Promote subtree or delete table column.
24326 Calls `org-promote-subtree', `org-outdent-item',
24327 or `org-table-delete-column', depending on context.
24328 See the individual commands for more information."
24329 (interactive)
24330 (cond
24331 ((org-at-table-p) (call-interactively 'org-table-delete-column))
24332 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
24333 ((org-at-item-p) (call-interactively 'org-outdent-item))
24334 (t (org-shiftcursor-error))))
24336 (defun org-shiftmetaright ()
24337 "Demote subtree or insert table column.
24338 Calls `org-demote-subtree', `org-indent-item',
24339 or `org-table-insert-column', depending on context.
24340 See the individual commands for more information."
24341 (interactive)
24342 (cond
24343 ((org-at-table-p) (call-interactively 'org-table-insert-column))
24344 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
24345 ((org-at-item-p) (call-interactively 'org-indent-item))
24346 (t (org-shiftcursor-error))))
24348 (defun org-shiftmetaup (&optional arg)
24349 "Move subtree up or kill table row.
24350 Calls `org-move-subtree-up' or `org-table-kill-row' or
24351 `org-move-item-up' depending on context. See the individual commands
24352 for more information."
24353 (interactive "P")
24354 (cond
24355 ((org-at-table-p) (call-interactively 'org-table-kill-row))
24356 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
24357 ((org-at-item-p) (call-interactively 'org-move-item-up))
24358 (t (org-shiftcursor-error))))
24359 (defun org-shiftmetadown (&optional arg)
24360 "Move subtree down or insert table row.
24361 Calls `org-move-subtree-down' or `org-table-insert-row' or
24362 `org-move-item-down', depending on context. See the individual
24363 commands for more information."
24364 (interactive "P")
24365 (cond
24366 ((org-at-table-p) (call-interactively 'org-table-insert-row))
24367 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
24368 ((org-at-item-p) (call-interactively 'org-move-item-down))
24369 (t (org-shiftcursor-error))))
24371 (defun org-metaleft (&optional arg)
24372 "Promote heading or move table column to left.
24373 Calls `org-do-promote' or `org-table-move-column', depending on context.
24374 With no specific context, calls the Emacs default `backward-word'.
24375 See the individual commands for more information."
24376 (interactive "P")
24377 (cond
24378 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
24379 ((or (org-on-heading-p) (org-region-active-p))
24380 (call-interactively 'org-do-promote))
24381 ((org-at-item-p) (call-interactively 'org-outdent-item))
24382 (t (call-interactively 'backward-word))))
24384 (defun org-metaright (&optional arg)
24385 "Demote subtree or move table column to right.
24386 Calls `org-do-demote' or `org-table-move-column', depending on context.
24387 With no specific context, calls the Emacs default `forward-word'.
24388 See the individual commands for more information."
24389 (interactive "P")
24390 (cond
24391 ((org-at-table-p) (call-interactively 'org-table-move-column))
24392 ((or (org-on-heading-p) (org-region-active-p))
24393 (call-interactively 'org-do-demote))
24394 ((org-at-item-p) (call-interactively 'org-indent-item))
24395 (t (call-interactively 'forward-word))))
24397 (defun org-metaup (&optional arg)
24398 "Move subtree up or move table row up.
24399 Calls `org-move-subtree-up' or `org-table-move-row' or
24400 `org-move-item-up', depending on context. See the individual commands
24401 for more information."
24402 (interactive "P")
24403 (cond
24404 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
24405 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
24406 ((org-at-item-p) (call-interactively 'org-move-item-up))
24407 (t (org-shiftcursor-error))))
24409 (defun org-metadown (&optional arg)
24410 "Move subtree down or move table row down.
24411 Calls `org-move-subtree-down' or `org-table-move-row' or
24412 `org-move-item-down', depending on context. See the individual
24413 commands for more information."
24414 (interactive "P")
24415 (cond
24416 ((org-at-table-p) (call-interactively 'org-table-move-row))
24417 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
24418 ((org-at-item-p) (call-interactively 'org-move-item-down))
24419 (t (org-shiftcursor-error))))
24421 (defun org-shiftup (&optional arg)
24422 "Increase item in timestamp or increase priority of current headline.
24423 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
24424 depending on context. See the individual commands for more information."
24425 (interactive "P")
24426 (cond
24427 ((org-at-timestamp-p t)
24428 (call-interactively (if org-edit-timestamp-down-means-later
24429 'org-timestamp-down 'org-timestamp-up)))
24430 ((org-on-heading-p) (call-interactively 'org-priority-up))
24431 ((org-at-item-p) (call-interactively 'org-previous-item))
24432 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
24434 (defun org-shiftdown (&optional arg)
24435 "Decrease item in timestamp or decrease priority of current headline.
24436 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
24437 depending on context. See the individual commands for more information."
24438 (interactive "P")
24439 (cond
24440 ((org-at-timestamp-p t)
24441 (call-interactively (if org-edit-timestamp-down-means-later
24442 'org-timestamp-up 'org-timestamp-down)))
24443 ((org-on-heading-p) (call-interactively 'org-priority-down))
24444 (t (call-interactively 'org-next-item))))
24446 (defun org-shiftright ()
24447 "Next TODO keyword or timestamp one day later, depending on context."
24448 (interactive)
24449 (cond
24450 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
24451 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
24452 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
24453 (t (org-shiftcursor-error))))
24455 (defun org-shiftleft ()
24456 "Previous TODO keyword or timestamp one day earlier, depending on context."
24457 (interactive)
24458 (cond
24459 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
24460 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
24461 ((org-at-property-p)
24462 (call-interactively 'org-property-previous-allowed-value))
24463 (t (org-shiftcursor-error))))
24465 (defun org-shiftcontrolright ()
24466 "Switch to next TODO set."
24467 (interactive)
24468 (cond
24469 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
24470 (t (org-shiftcursor-error))))
24472 (defun org-shiftcontrolleft ()
24473 "Switch to previous TODO set."
24474 (interactive)
24475 (cond
24476 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
24477 (t (org-shiftcursor-error))))
24479 (defun org-ctrl-c-ret ()
24480 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
24481 (interactive)
24482 (cond
24483 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
24484 (t (call-interactively 'org-insert-heading))))
24486 (defun org-copy-special ()
24487 "Copy region in table or copy current subtree.
24488 Calls `org-table-copy' or `org-copy-subtree', depending on context.
24489 See the individual commands for more information."
24490 (interactive)
24491 (call-interactively
24492 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
24494 (defun org-cut-special ()
24495 "Cut region in table or cut current subtree.
24496 Calls `org-table-copy' or `org-cut-subtree', depending on context.
24497 See the individual commands for more information."
24498 (interactive)
24499 (call-interactively
24500 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
24502 (defun org-paste-special (arg)
24503 "Paste rectangular region into table, or past subtree relative to level.
24504 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
24505 See the individual commands for more information."
24506 (interactive "P")
24507 (if (org-at-table-p)
24508 (org-table-paste-rectangle)
24509 (org-paste-subtree arg)))
24511 (defun org-ctrl-c-ctrl-c (&optional arg)
24512 "Set tags in headline, or update according to changed information at point.
24514 This command does many different things, depending on context:
24516 - If the cursor is in a headline, prompt for tags and insert them
24517 into the current line, aligned to `org-tags-column'. When called
24518 with prefix arg, realign all tags in the current buffer.
24520 - If the cursor is in one of the special #+KEYWORD lines, this
24521 triggers scanning the buffer for these lines and updating the
24522 information.
24524 - If the cursor is inside a table, realign the table. This command
24525 works even if the automatic table editor has been turned off.
24527 - If the cursor is on a #+TBLFM line, re-apply the formulas to
24528 the entire table.
24530 - If the cursor is a the beginning of a dynamic block, update it.
24532 - If the cursor is inside a table created by the table.el package,
24533 activate that table.
24535 - If the current buffer is a remember buffer, close note and file it.
24536 with a prefix argument, file it without further interaction to the default
24537 location.
24539 - If the cursor is on a <<<target>>>, update radio targets and corresponding
24540 links in this buffer.
24542 - If the cursor is on a numbered item in a plain list, renumber the
24543 ordered list."
24544 (interactive "P")
24545 (let ((org-enable-table-editor t))
24546 (cond
24547 ((or org-clock-overlays
24548 org-occur-highlights
24549 org-latex-fragment-image-overlays)
24550 (org-remove-clock-overlays)
24551 (org-remove-occur-highlights)
24552 (org-remove-latex-fragment-image-overlays)
24553 (message "Temporary highlights/overlays removed from current buffer"))
24554 ((and (local-variable-p 'org-finish-function (current-buffer))
24555 (fboundp org-finish-function))
24556 (funcall org-finish-function))
24557 ((org-at-property-p)
24558 (call-interactively 'org-property-action))
24559 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
24560 ((org-on-heading-p) (call-interactively 'org-set-tags))
24561 ((org-at-table.el-p)
24562 (require 'table)
24563 (beginning-of-line 1)
24564 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
24565 (call-interactively 'table-recognize-table))
24566 ((org-at-table-p)
24567 (org-table-maybe-eval-formula)
24568 (if arg
24569 (call-interactively 'org-table-recalculate)
24570 (org-table-maybe-recalculate-line))
24571 (call-interactively 'org-table-align))
24572 ((org-at-item-checkbox-p)
24573 (call-interactively 'org-toggle-checkbox))
24574 ((org-at-item-p)
24575 (call-interactively 'org-maybe-renumber-ordered-list))
24576 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
24577 ;; Dynamic block
24578 (beginning-of-line 1)
24579 (org-update-dblock))
24580 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
24581 (cond
24582 ((equal (match-string 1) "TBLFM")
24583 ;; Recalculate the table before this line
24584 (save-excursion
24585 (beginning-of-line 1)
24586 (skip-chars-backward " \r\n\t")
24587 (if (org-at-table-p)
24588 (org-call-with-arg 'org-table-recalculate t))))
24590 (call-interactively 'org-mode-restart))))
24591 (t (error "C-c C-c can do nothing useful at this location.")))))
24593 (defun org-mode-restart ()
24594 "Restart Org-mode, to scan again for special lines.
24595 Also updates the keyword regular expressions."
24596 (interactive)
24597 (let ((org-inhibit-startup t)) (org-mode))
24598 (message "Org-mode restarted to refresh keyword and special line setup"))
24600 (defun org-kill-note-or-show-branches ()
24601 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
24602 (interactive)
24603 (if (not org-finish-function)
24604 (call-interactively 'show-branches)
24605 (let ((org-note-abort t))
24606 (funcall org-finish-function))))
24608 (defun org-return ()
24609 "Goto next table row or insert a newline.
24610 Calls `org-table-next-row' or `newline', depending on context.
24611 See the individual commands for more information."
24612 (interactive)
24613 (cond
24614 ((bobp) (newline))
24615 ((org-at-table-p)
24616 (org-table-justify-field-maybe)
24617 (call-interactively 'org-table-next-row))
24618 (t (newline))))
24620 (defun org-ctrl-c-minus ()
24621 "Insert separator line in table or modify bullet type in list.
24622 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
24623 depending on context."
24624 (interactive)
24625 (cond
24626 ((org-at-table-p)
24627 (call-interactively 'org-table-insert-hline))
24628 ((org-in-item-p)
24629 (call-interactively 'org-cycle-list-bullet))
24630 (t (error "`C-c -' does have no function here."))))
24632 (defun org-meta-return (&optional arg)
24633 "Insert a new heading or wrap a region in a table.
24634 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
24635 See the individual commands for more information."
24636 (interactive "P")
24637 (cond
24638 ((org-at-table-p)
24639 (call-interactively 'org-table-wrap-region))
24640 (t (call-interactively 'org-insert-heading))))
24642 ;;; Menu entries
24644 ;; Define the Org-mode menus
24645 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
24646 '("Tbl"
24647 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
24648 ["Next Field" org-cycle (org-at-table-p)]
24649 ["Previous Field" org-shifttab (org-at-table-p)]
24650 ["Next Row" org-return (org-at-table-p)]
24651 "--"
24652 ["Blank Field" org-table-blank-field (org-at-table-p)]
24653 ["Edit Field" org-table-edit-field (org-at-table-p)]
24654 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
24655 "--"
24656 ("Column"
24657 ["Move Column Left" org-metaleft (org-at-table-p)]
24658 ["Move Column Right" org-metaright (org-at-table-p)]
24659 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
24660 ["Insert Column" org-shiftmetaright (org-at-table-p)])
24661 ("Row"
24662 ["Move Row Up" org-metaup (org-at-table-p)]
24663 ["Move Row Down" org-metadown (org-at-table-p)]
24664 ["Delete Row" org-shiftmetaup (org-at-table-p)]
24665 ["Insert Row" org-shiftmetadown (org-at-table-p)]
24666 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
24667 "--"
24668 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
24669 ("Rectangle"
24670 ["Copy Rectangle" org-copy-special (org-at-table-p)]
24671 ["Cut Rectangle" org-cut-special (org-at-table-p)]
24672 ["Paste Rectangle" org-paste-special (org-at-table-p)]
24673 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
24674 "--"
24675 ("Calculate"
24676 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
24677 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
24678 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
24679 "--"
24680 ["Recalculate line" org-table-recalculate (org-at-table-p)]
24681 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
24682 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
24683 "--"
24684 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
24685 "--"
24686 ["Sum Column/Rectangle" org-table-sum
24687 (or (org-at-table-p) (org-region-active-p))]
24688 ["Which Column?" org-table-current-column (org-at-table-p)])
24689 ["Debug Formulas"
24690 org-table-toggle-formula-debugger
24691 :style toggle :selected org-table-formula-debug]
24692 ["Show Col/Row Numbers"
24693 org-table-toggle-coordinate-overlays
24694 :style toggle :selected org-table-overlay-coordinates]
24695 "--"
24696 ["Create" org-table-create (and (not (org-at-table-p))
24697 org-enable-table-editor)]
24698 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
24699 ["Import from File" org-table-import (not (org-at-table-p))]
24700 ["Export to File" org-table-export (org-at-table-p)]
24701 "--"
24702 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
24704 (easy-menu-define org-org-menu org-mode-map "Org menu"
24705 '("Org"
24706 ("Show/Hide"
24707 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
24708 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
24709 ["Sparse Tree" org-occur t]
24710 ["Reveal Context" org-reveal t]
24711 ["Show All" show-all t]
24712 "--"
24713 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
24714 "--"
24715 ["New Heading" org-insert-heading t]
24716 ("Navigate Headings"
24717 ["Up" outline-up-heading t]
24718 ["Next" outline-next-visible-heading t]
24719 ["Previous" outline-previous-visible-heading t]
24720 ["Next Same Level" outline-forward-same-level t]
24721 ["Previous Same Level" outline-backward-same-level t]
24722 "--"
24723 ["Jump" org-goto t])
24724 ("Edit Structure"
24725 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
24726 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
24727 "--"
24728 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
24729 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
24730 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
24731 "--"
24732 ["Promote Heading" org-metaleft (not (org-at-table-p))]
24733 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
24734 ["Demote Heading" org-metaright (not (org-at-table-p))]
24735 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
24736 "--"
24737 ["Sort Region/Children" org-sort (not (org-at-table-p))]
24738 "--"
24739 ["Convert to odd levels" org-convert-to-odd-levels t]
24740 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
24741 ("Editing"
24742 ["Emphasis..." org-emphasize t])
24743 ("Archive"
24744 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
24745 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
24746 ; :active t :keys "C-u C-c C-x C-a"]
24747 ["Sparse trees open ARCHIVE trees"
24748 (setq org-sparse-tree-open-archived-trees
24749 (not org-sparse-tree-open-archived-trees))
24750 :style toggle :selected org-sparse-tree-open-archived-trees]
24751 ["Cycling opens ARCHIVE trees"
24752 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
24753 :style toggle :selected org-cycle-open-archived-trees]
24754 ["Agenda includes ARCHIVE trees"
24755 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
24756 :style toggle :selected (not org-agenda-skip-archived-trees)]
24757 "--"
24758 ["Move Subtree to Archive" org-advertized-archive-subtree t]
24759 ; ["Check and Move Children" (org-archive-subtree '(4))
24760 ; :active t :keys "C-u C-c C-x C-s"]
24762 "--"
24763 ("TODO Lists"
24764 ["TODO/DONE/-" org-todo t]
24765 ("Select keyword"
24766 ["Next keyword" org-shiftright (org-on-heading-p)]
24767 ["Previous keyword" org-shiftleft (org-on-heading-p)]
24768 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
24769 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
24770 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
24771 ["Show TODO Tree" org-show-todo-tree t]
24772 ["Global TODO list" org-todo-list t]
24773 "--"
24774 ["Set Priority" org-priority t]
24775 ["Priority Up" org-shiftup t]
24776 ["Priority Down" org-shiftdown t])
24777 ("TAGS and Properties"
24778 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
24779 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
24780 "--"
24781 ["Set property" 'org-set-property t]
24782 ["Column view of properties" org-columns t])
24783 ("Dates and Scheduling"
24784 ["Timestamp" org-time-stamp t]
24785 ["Timestamp (inactive)" org-time-stamp-inactive t]
24786 ("Change Date"
24787 ["1 Day Later" org-shiftright t]
24788 ["1 Day Earlier" org-shiftleft t]
24789 ["1 ... Later" org-shiftup t]
24790 ["1 ... Earlier" org-shiftdown t])
24791 ["Compute Time Range" org-evaluate-time-range t]
24792 ["Schedule Item" org-schedule t]
24793 ["Deadline" org-deadline t]
24794 "--"
24795 ["Custom time format" org-toggle-time-stamp-overlays
24796 :style radio :selected org-display-custom-times]
24797 "--"
24798 ["Goto Calendar" org-goto-calendar t]
24799 ["Date from Calendar" org-date-from-calendar t])
24800 ("Logging work"
24801 ["Clock in" org-clock-in t]
24802 ["Clock out" org-clock-out t]
24803 ["Clock cancel" org-clock-cancel t]
24804 ["Goto running clock" org-clock-goto t]
24805 ["Display times" org-clock-display t]
24806 ["Create clock table" org-clock-report t]
24807 "--"
24808 ["Record DONE time"
24809 (progn (setq org-log-done (not org-log-done))
24810 (message "Switching to %s will %s record a timestamp"
24811 (car org-done-keywords)
24812 (if org-log-done "automatically" "not")))
24813 :style toggle :selected org-log-done])
24814 "--"
24815 ["Agenda Command..." org-agenda t]
24816 ("File List for Agenda")
24817 ("Special views current file"
24818 ["TODO Tree" org-show-todo-tree t]
24819 ["Check Deadlines" org-check-deadlines t]
24820 ["Timeline" org-timeline t]
24821 ["Tags Tree" org-tags-sparse-tree t])
24822 "--"
24823 ("Hyperlinks"
24824 ["Store Link (Global)" org-store-link t]
24825 ["Insert Link" org-insert-link t]
24826 ["Follow Link" org-open-at-point t]
24827 "--"
24828 ["Next link" org-next-link t]
24829 ["Previous link" org-previous-link t]
24830 "--"
24831 ["Descriptive Links"
24832 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
24833 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
24834 ["Literal Links"
24835 (progn
24836 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
24837 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
24838 "--"
24839 ["Export/Publish..." org-export t]
24840 ("LaTeX"
24841 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
24842 :selected org-cdlatex-mode]
24843 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
24844 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
24845 ["Modify math symbol" org-cdlatex-math-modify
24846 (org-inside-LaTeX-fragment-p)]
24847 ["Export LaTeX fragments as images"
24848 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
24849 :style toggle :selected org-export-with-LaTeX-fragments])
24850 "--"
24851 ("Documentation"
24852 ["Show Version" org-version t]
24853 ["Info Documentation" org-info t])
24854 ("Customize"
24855 ["Browse Org Group" org-customize t]
24856 "--"
24857 ["Expand This Menu" org-create-customize-menu
24858 (fboundp 'customize-menu-create)])
24859 "--"
24860 ["Refresh setup" org-mode-restart t]
24863 (defun org-info (&optional node)
24864 "Read documentation for Org-mode in the info system.
24865 With optional NODE, go directly to that node."
24866 (interactive)
24867 (require 'info)
24868 (Info-goto-node (format "(org)%s" (or node ""))))
24870 (defun org-install-agenda-files-menu ()
24871 (let ((bl (buffer-list)))
24872 (save-excursion
24873 (while bl
24874 (set-buffer (pop bl))
24875 (if (org-mode-p) (setq bl nil)))
24876 (when (org-mode-p)
24877 (easy-menu-change
24878 '("Org") "File List for Agenda"
24879 (append
24880 (list
24881 ["Edit File List" (org-edit-agenda-file-list) t]
24882 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
24883 ["Remove Current File from List" org-remove-file t]
24884 ["Cycle through agenda files" org-cycle-agenda-files t]
24885 ["Occur in all agenda files" org-occur-in-agenda-files t]
24886 "--")
24887 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
24889 ;;;; Documentation
24891 (defun org-customize ()
24892 "Call the customize function with org as argument."
24893 (interactive)
24894 (customize-browse 'org))
24896 (defun org-create-customize-menu ()
24897 "Create a full customization menu for Org-mode, insert it into the menu."
24898 (interactive)
24899 (if (fboundp 'customize-menu-create)
24900 (progn
24901 (easy-menu-change
24902 '("Org") "Customize"
24903 `(["Browse Org group" org-customize t]
24904 "--"
24905 ,(customize-menu-create 'org)
24906 ["Set" Custom-set t]
24907 ["Save" Custom-save t]
24908 ["Reset to Current" Custom-reset-current t]
24909 ["Reset to Saved" Custom-reset-saved t]
24910 ["Reset to Standard Settings" Custom-reset-standard t]))
24911 (message "\"Org\"-menu now contains full customization menu"))
24912 (error "Cannot expand menu (outdated version of cus-edit.el)")))
24914 ;;;; Miscellaneous stuff
24917 ;;; Generally useful functions
24919 (defun org-context ()
24920 "Return a list of contexts of the current cursor position.
24921 If several contexts apply, all are returned.
24922 Each context entry is a list with a symbol naming the context, and
24923 two positions indicating start and end of the context. Possible
24924 contexts are:
24926 :headline anywhere in a headline
24927 :headline-stars on the leading stars in a headline
24928 :todo-keyword on a TODO keyword (including DONE) in a headline
24929 :tags on the TAGS in a headline
24930 :priority on the priority cookie in a headline
24931 :item on the first line of a plain list item
24932 :item-bullet on the bullet/number of a plain list item
24933 :checkbox on the checkbox in a plain list item
24934 :table in an org-mode table
24935 :table-special on a special filed in a table
24936 :table-table in a table.el table
24937 :link on a hyperlink
24938 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
24939 :target on a <<target>>
24940 :radio-target on a <<<radio-target>>>
24941 :latex-fragment on a LaTeX fragment
24942 :latex-preview on a LaTeX fragment with overlayed preview image
24944 This function expects the position to be visible because it uses font-lock
24945 faces as a help to recognize the following contexts: :table-special, :link,
24946 and :keyword."
24947 (let* ((f (get-text-property (point) 'face))
24948 (faces (if (listp f) f (list f)))
24949 (p (point)) clist o)
24950 ;; First the large context
24951 (cond
24952 ((org-on-heading-p t)
24953 (push (list :headline (point-at-bol) (point-at-eol)) clist)
24954 (when (progn
24955 (beginning-of-line 1)
24956 (looking-at org-todo-line-tags-regexp))
24957 (push (org-point-in-group p 1 :headline-stars) clist)
24958 (push (org-point-in-group p 2 :todo-keyword) clist)
24959 (push (org-point-in-group p 4 :tags) clist))
24960 (goto-char p)
24961 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
24962 (if (looking-at "\\[#[A-Z0-9]\\]")
24963 (push (org-point-in-group p 0 :priority) clist)))
24965 ((org-at-item-p)
24966 (push (org-point-in-group p 2 :item-bullet) clist)
24967 (push (list :item (point-at-bol)
24968 (save-excursion (org-end-of-item) (point)))
24969 clist)
24970 (and (org-at-item-checkbox-p)
24971 (push (org-point-in-group p 0 :checkbox) clist)))
24973 ((org-at-table-p)
24974 (push (list :table (org-table-begin) (org-table-end)) clist)
24975 (if (memq 'org-formula faces)
24976 (push (list :table-special
24977 (previous-single-property-change p 'face)
24978 (next-single-property-change p 'face)) clist)))
24979 ((org-at-table-p 'any)
24980 (push (list :table-table) clist)))
24981 (goto-char p)
24983 ;; Now the small context
24984 (cond
24985 ((org-at-timestamp-p)
24986 (push (org-point-in-group p 0 :timestamp) clist))
24987 ((memq 'org-link faces)
24988 (push (list :link
24989 (previous-single-property-change p 'face)
24990 (next-single-property-change p 'face)) clist))
24991 ((memq 'org-special-keyword faces)
24992 (push (list :keyword
24993 (previous-single-property-change p 'face)
24994 (next-single-property-change p 'face)) clist))
24995 ((org-on-target-p)
24996 (push (org-point-in-group p 0 :target) clist)
24997 (goto-char (1- (match-beginning 0)))
24998 (if (looking-at org-radio-target-regexp)
24999 (push (org-point-in-group p 0 :radio-target) clist))
25000 (goto-char p))
25001 ((setq o (car (delq nil
25002 (mapcar
25003 (lambda (x)
25004 (if (memq x org-latex-fragment-image-overlays) x))
25005 (org-overlays-at (point))))))
25006 (push (list :latex-fragment
25007 (org-overlay-start o) (org-overlay-end o)) clist)
25008 (push (list :latex-preview
25009 (org-overlay-start o) (org-overlay-end o)) clist))
25010 ((org-inside-LaTeX-fragment-p)
25011 ;; FIXME: positions wrong.
25012 (push (list :latex-fragment (point) (point)) clist)))
25014 (setq clist (nreverse (delq nil clist)))
25015 clist))
25017 ;; FIXME: Compare with at-regexp-p Do we need both?
25018 (defun org-in-regexp (re &optional nlines visually)
25019 "Check if point is inside a match of regexp.
25020 Normally only the current line is checked, but you can include NLINES extra
25021 lines both before and after point into the search.
25022 If VISUALLY is set, require that the cursor is not after the match but
25023 really on, so that the block visually is on the match."
25024 (catch 'exit
25025 (let ((pos (point))
25026 (eol (point-at-eol (+ 1 (or nlines 0))))
25027 (inc (if visually 1 0)))
25028 (save-excursion
25029 (beginning-of-line (- 1 (or nlines 0)))
25030 (while (re-search-forward re eol t)
25031 (if (and (<= (match-beginning 0) pos)
25032 (>= (+ inc (match-end 0)) pos))
25033 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
25035 (defun org-at-regexp-p (regexp)
25036 "Is point inside a match of REGEXP in the current line?"
25037 (catch 'exit
25038 (save-excursion
25039 (let ((pos (point)) (end (point-at-eol)))
25040 (beginning-of-line 1)
25041 (while (re-search-forward regexp end t)
25042 (if (and (<= (match-beginning 0) pos)
25043 (>= (match-end 0) pos))
25044 (throw 'exit t)))
25045 nil))))
25047 (defun org-occur-in-agenda-files (regexp &optional nlines)
25048 "Call `multi-occur' with buffers for all agenda files."
25049 (interactive "sOrg-files matching: \np")
25050 (let* ((files (org-agenda-files))
25051 (tnames (mapcar 'file-truename files))
25052 (extra org-agenda-multi-occur-extra-files)
25054 (while (setq f (pop extra))
25055 (unless (member (file-truename f) tnames)
25056 (add-to-list 'files f 'append)
25057 (add-to-list 'tnames (file-truename f) 'append)))
25058 (multi-occur
25059 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
25060 regexp)))
25062 (defun org-uniquify (list)
25063 "Remove duplicate elements from LIST."
25064 (let (res)
25065 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
25066 res))
25068 (defun org-delete-all (elts list)
25069 "Remove all elements in ELTS from LIST."
25070 (while elts
25071 (setq list (delete (pop elts) list)))
25072 list)
25074 (defun org-point-in-group (point group &optional context)
25075 "Check if POINT is in match-group GROUP.
25076 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
25077 match. If the match group does ot exist or point is not inside it,
25078 return nil."
25079 (and (match-beginning group)
25080 (>= point (match-beginning group))
25081 (<= point (match-end group))
25082 (if context
25083 (list context (match-beginning group) (match-end group))
25084 t)))
25086 (defun org-switch-to-buffer-other-window (&rest args)
25087 "Switch to buffer in a second window on the current frame.
25088 In particular, do not allow pop-up frames."
25089 (let (pop-up-frames special-display-buffer-names special-display-regexps
25090 special-display-function)
25091 (apply 'switch-to-buffer-other-window args)))
25093 (defun org-combine-plists (&rest plists)
25094 "Create a single property list from all plists in PLISTS.
25095 The process starts by copying the first list, and then setting properties
25096 from the other lists. Settings in the last list are the most significant
25097 ones and overrule settings in the other lists."
25098 (let ((rtn (copy-sequence (pop plists)))
25099 p v ls)
25100 (while plists
25101 (setq ls (pop plists))
25102 (while ls
25103 (setq p (pop ls) v (pop ls))
25104 (setq rtn (plist-put rtn p v))))
25105 rtn))
25107 (defun org-move-line-down (arg)
25108 "Move the current line down. With prefix argument, move it past ARG lines."
25109 (interactive "p")
25110 (let ((col (current-column))
25111 beg end pos)
25112 (beginning-of-line 1) (setq beg (point))
25113 (beginning-of-line 2) (setq end (point))
25114 (beginning-of-line (+ 1 arg))
25115 (setq pos (move-marker (make-marker) (point)))
25116 (insert (delete-and-extract-region beg end))
25117 (goto-char pos)
25118 (move-to-column col)))
25120 (defun org-move-line-up (arg)
25121 "Move the current line up. With prefix argument, move it past ARG lines."
25122 (interactive "p")
25123 (let ((col (current-column))
25124 beg end pos)
25125 (beginning-of-line 1) (setq beg (point))
25126 (beginning-of-line 2) (setq end (point))
25127 (beginning-of-line (- arg))
25128 (setq pos (move-marker (make-marker) (point)))
25129 (insert (delete-and-extract-region beg end))
25130 (goto-char pos)
25131 (move-to-column col)))
25133 (defun org-replace-escapes (string table)
25134 "Replace %-escapes in STRING with values in TABLE.
25135 TABLE is an association list with keys like \"%a\" and string values.
25136 The sequences in STRING may contain normal field width and padding information,
25137 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
25138 so values can contain further %-escapes if they are define later in TABLE."
25139 (let ((case-fold-search nil)
25140 e re rpl)
25141 (while (setq e (pop table))
25142 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
25143 (while (string-match re string)
25144 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
25145 (cdr e)))
25146 (setq string (replace-match rpl t t string))))
25147 string))
25150 (defun org-sublist (list start end)
25151 "Return a section of LIST, from START to END.
25152 Counting starts at 1."
25153 (let (rtn (c start))
25154 (setq list (nthcdr (1- start) list))
25155 (while (and list (<= c end))
25156 (push (pop list) rtn)
25157 (setq c (1+ c)))
25158 (nreverse rtn)))
25160 (defun org-find-base-buffer-visiting (file)
25161 "Like `find-buffer-visiting' but alway return the base buffer and
25162 not an indirect buffer"
25163 (let ((buf (find-buffer-visiting file)))
25164 (if buf
25165 (or (buffer-base-buffer buf) buf)
25166 nil)))
25168 (defun org-image-file-name-regexp ()
25169 "Return regexp matching the file names of images."
25170 (if (fboundp 'image-file-name-regexp)
25171 (image-file-name-regexp)
25172 (let ((image-file-name-extensions
25173 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
25174 "xbm" "xpm" "pbm" "pgm" "ppm")))
25175 (concat "\\."
25176 (regexp-opt (nconc (mapcar 'upcase
25177 image-file-name-extensions)
25178 image-file-name-extensions)
25180 "\\'"))))
25182 (defun org-file-image-p (file)
25183 "Return non-nil if FILE is an image."
25184 (save-match-data
25185 (string-match (org-image-file-name-regexp) file)))
25187 ;;; Paragraph filling stuff.
25188 ;; We want this to be just right, so use the full arsenal.
25190 (defun org-indent-line-function ()
25191 "Indent line like previous, but further if previous was headline or item."
25192 (interactive)
25193 (let* ((pos (point))
25194 (itemp (org-at-item-p))
25195 column bpos bcol tpos tcol bullet btype bullet-type)
25196 ;; Find the previous relevant line
25197 (beginning-of-line 1)
25198 (cond
25199 ((looking-at "#") (setq column 0))
25200 ((looking-at "\\*+ ") (setq column 0))
25202 (beginning-of-line 0)
25203 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
25204 (beginning-of-line 0))
25205 (cond
25206 ((looking-at "\\*+[ \t]+")
25207 (goto-char (match-end 0))
25208 (setq column (current-column)))
25209 ((org-in-item-p)
25210 (org-beginning-of-item)
25211 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
25212 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
25213 (setq bpos (match-beginning 1) tpos (match-end 0)
25214 bcol (progn (goto-char bpos) (current-column))
25215 tcol (progn (goto-char tpos) (current-column))
25216 bullet (match-string 1)
25217 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
25218 (if (not itemp)
25219 (setq column tcol)
25220 (goto-char pos)
25221 (beginning-of-line 1)
25222 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
25223 (setq bullet (match-string 1)
25224 btype (if (string-match "[0-9]" bullet) "n" bullet))
25225 (setq column (if (equal btype bullet-type) bcol tcol))))
25226 (t (setq column (org-get-indentation))))))
25227 (goto-char pos)
25228 (if (<= (current-column) (current-indentation))
25229 (indent-line-to column)
25230 (save-excursion (indent-line-to column)))
25231 (setq column (current-column))
25232 (beginning-of-line 1)
25233 (if (looking-at
25234 "\\([ \t]+\\)\\(:[0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
25235 (replace-match (concat "\\1" (format org-property-format
25236 (match-string 2) (match-string 3)))
25237 t nil))
25238 (move-to-column column)))
25240 (defun org-set-autofill-regexps ()
25241 (interactive)
25242 ;; In the paragraph separator we include headlines, because filling
25243 ;; text in a line directly attached to a headline would otherwise
25244 ;; fill the headline as well.
25245 (org-set-local 'comment-start-skip "^#+[ \t]*")
25246 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
25247 ;; The paragraph starter includes hand-formatted lists.
25248 (org-set-local 'paragraph-start
25249 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
25250 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
25251 ;; But only if the user has not turned off tables or fixed-width regions
25252 (org-set-local
25253 'auto-fill-inhibit-regexp
25254 (concat "\\*+ \\|#\\+"
25255 "\\|[ \t]*" org-keyword-time-regexp
25256 (if (or org-enable-table-editor org-enable-fixed-width-editor)
25257 (concat
25258 "\\|[ \t]*["
25259 (if org-enable-table-editor "|" "")
25260 (if org-enable-fixed-width-editor ":" "")
25261 "]"))))
25262 ;; We use our own fill-paragraph function, to make sure that tables
25263 ;; and fixed-width regions are not wrapped. That function will pass
25264 ;; through to `fill-paragraph' when appropriate.
25265 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
25266 ; Adaptive filling: To get full control, first make sure that
25267 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
25268 (org-set-local 'adaptive-fill-regexp "\000")
25269 (org-set-local 'adaptive-fill-function
25270 'org-adaptive-fill-function))
25272 (defun org-fill-paragraph (&optional justify)
25273 "Re-align a table, pass through to fill-paragraph if no table."
25274 (let ((table-p (org-at-table-p))
25275 (table.el-p (org-at-table.el-p)))
25276 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
25277 (table.el-p t) ; skip table.el tables
25278 (table-p (org-table-align) t) ; align org-mode tables
25279 (t nil)))) ; call paragraph-fill
25281 ;; For reference, this is the default value of adaptive-fill-regexp
25282 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
25284 (defun org-adaptive-fill-function ()
25285 "Return a fill prefix for org-mode files.
25286 In particular, this makes sure hanging paragraphs for hand-formatted lists
25287 work correctly."
25288 (cond ((looking-at "#[ \t]+")
25289 (match-string 0))
25290 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
25291 (save-excursion
25292 (goto-char (match-end 0))
25293 (make-string (current-column) ?\ )))
25294 (t nil)))
25296 ;;;; Functions extending outline functionality
25298 (defun org-beginning-of-line (&optional arg)
25299 "Go to the beginning of the current line. If that is invisible, continue
25300 to a visible line beginning. This makes the function of C-a more intuitive.
25301 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
25302 first attempt, and only move to after the tags when the cursor is already
25303 beyond the end of the headline."
25304 (interactive "P")
25305 (let ((pos (point)))
25306 (beginning-of-line 1)
25307 (if (bobp)
25309 (backward-char 1)
25310 (if (org-invisible-p)
25311 (while (and (not (bobp)) (org-invisible-p))
25312 (backward-char 1)
25313 (beginning-of-line 1))
25314 (forward-char 1)))
25315 (when org-special-ctrl-a/e
25316 (cond
25317 ((and (looking-at org-todo-line-regexp)
25318 (= (char-after (match-end 1)) ?\ ))
25319 (goto-char
25320 (if (eq org-special-ctrl-a/e t)
25321 (cond ((> pos (match-beginning 3)) (match-beginning 3))
25322 ((= pos (point)) (match-beginning 3))
25323 (t (point)))
25324 (cond ((> pos (point)) (point))
25325 ((not (eq last-command this-command)) (point))
25326 (t (match-beginning 3))))))
25327 ((org-at-item-p)
25328 (goto-char
25329 (if (eq org-special-ctrl-a/e t)
25330 (cond ((> pos (match-end 4)) (match-end 4))
25331 ((= pos (point)) (match-end 4))
25332 (t (point)))
25333 (cond ((> pos (point)) (point))
25334 ((not (eq last-command this-command)) (point))
25335 (t (match-end 4))))))))))
25337 (defun org-end-of-line (&optional arg)
25338 "Go to the end of the line.
25339 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
25340 first attempt, and only move to after the tags when the cursor is already
25341 beyond the end of the headline."
25342 (interactive "P")
25343 (if (or (not org-special-ctrl-a/e)
25344 (not (org-on-heading-p)))
25345 (end-of-line arg)
25346 (let ((pos (point)))
25347 (beginning-of-line 1)
25348 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
25349 (if (eq org-special-ctrl-a/e t)
25350 (if (or (< pos (match-beginning 1))
25351 (= pos (match-end 0)))
25352 (goto-char (match-beginning 1))
25353 (goto-char (match-end 0)))
25354 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
25355 (goto-char (match-end 0))
25356 (goto-char (match-beginning 1))))
25357 (end-of-line arg)))))
25359 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
25360 (define-key org-mode-map "\C-e" 'org-end-of-line)
25362 (defun org-invisible-p ()
25363 "Check if point is at a character currently not visible."
25364 ;; Early versions of noutline don't have `outline-invisible-p'.
25365 (if (fboundp 'outline-invisible-p)
25366 (outline-invisible-p)
25367 (get-char-property (point) 'invisible)))
25369 (defun org-invisible-p2 ()
25370 "Check if point is at a character currently not visible."
25371 (save-excursion
25372 (if (and (eolp) (not (bobp))) (backward-char 1))
25373 ;; Early versions of noutline don't have `outline-invisible-p'.
25374 (if (fboundp 'outline-invisible-p)
25375 (outline-invisible-p)
25376 (get-char-property (point) 'invisible))))
25378 (defalias 'org-back-to-heading 'outline-back-to-heading)
25379 (defalias 'org-on-heading-p 'outline-on-heading-p)
25380 (defalias 'org-at-heading-p 'outline-on-heading-p)
25381 (defun org-at-heading-or-item-p ()
25382 (or (org-on-heading-p) (org-at-item-p)))
25384 (defun org-on-target-p ()
25385 (or (org-in-regexp org-radio-target-regexp)
25386 (org-in-regexp org-target-regexp)))
25388 (defun org-up-heading-all (arg)
25389 "Move to the heading line of which the present line is a subheading.
25390 This function considers both visible and invisible heading lines.
25391 With argument, move up ARG levels."
25392 (if (fboundp 'outline-up-heading-all)
25393 (outline-up-heading-all arg) ; emacs 21 version of outline.el
25394 (outline-up-heading arg t))) ; emacs 22 version of outline.el
25396 (defun org-up-heading-safe ()
25397 "Move to the heading line of which the present line is a subheading.
25398 This version will not throw an error. It will return the level of the
25399 headline found, or nil if no higher level is found."
25400 (let ((pos (point)) start-level level
25401 (re (concat "^" outline-regexp)))
25402 (catch 'exit
25403 (outline-back-to-heading t)
25404 (setq start-level (funcall outline-level))
25405 (if (equal start-level 1) (throw 'exit nil))
25406 (while (re-search-backward re nil t)
25407 (setq level (funcall outline-level))
25408 (if (< level start-level) (throw 'exit level)))
25409 nil)))
25411 (defun org-goto-sibling (&optional previous)
25412 "Goto the next sibling, even if it is invisible.
25413 When PREVIOUS is set, go to the previous sibling instead. Returns t
25414 when a sibling was found. When none is found, return nil and don't
25415 move point."
25416 (let ((fun (if previous 're-search-backward 're-search-forward))
25417 (pos (point))
25418 (re (concat "^" outline-regexp))
25419 level l)
25420 (when (condition-case nil (org-back-to-heading t) (error nil))
25421 (setq level (funcall outline-level))
25422 (catch 'exit
25423 (or previous (forward-char 1))
25424 (while (funcall fun re nil t)
25425 (setq l (funcall outline-level))
25426 (when (< l level) (goto-char pos) (throw 'exit nil))
25427 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
25428 (goto-char pos)
25429 nil))))
25431 (defun org-show-siblings ()
25432 "Show all siblings of the current headline."
25433 (save-excursion
25434 (while (org-goto-sibling) (org-flag-heading nil)))
25435 (save-excursion
25436 (while (org-goto-sibling 'previous)
25437 (org-flag-heading nil))))
25439 (defun org-show-hidden-entry ()
25440 "Show an entry where even the heading is hidden."
25441 (save-excursion
25442 (org-show-entry)))
25444 (defun org-flag-heading (flag &optional entry)
25445 "Flag the current heading. FLAG non-nil means make invisible.
25446 When ENTRY is non-nil, show the entire entry."
25447 (save-excursion
25448 (org-back-to-heading t)
25449 ;; Check if we should show the entire entry
25450 (if entry
25451 (progn
25452 (org-show-entry)
25453 (save-excursion
25454 (and (outline-next-heading)
25455 (org-flag-heading nil))))
25456 (outline-flag-region (max (point-min) (1- (point)))
25457 (save-excursion (outline-end-of-heading) (point))
25458 flag))))
25460 (defun org-end-of-subtree (&optional invisible-OK to-heading)
25461 ;; This is an exact copy of the original function, but it uses
25462 ;; `org-back-to-heading', to make it work also in invisible
25463 ;; trees. And is uses an invisible-OK argument.
25464 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
25465 (org-back-to-heading invisible-OK)
25466 (let ((first t)
25467 (level (funcall outline-level)))
25468 (while (and (not (eobp))
25469 (or first (> (funcall outline-level) level)))
25470 (setq first nil)
25471 (outline-next-heading))
25472 (unless to-heading
25473 (if (memq (preceding-char) '(?\n ?\^M))
25474 (progn
25475 ;; Go to end of line before heading
25476 (forward-char -1)
25477 (if (memq (preceding-char) '(?\n ?\^M))
25478 ;; leave blank line before heading
25479 (forward-char -1))))))
25480 (point))
25482 (defun org-show-subtree ()
25483 "Show everything after this heading at deeper levels."
25484 (outline-flag-region
25485 (point)
25486 (save-excursion
25487 (outline-end-of-subtree) (outline-next-heading) (point))
25488 nil))
25490 (defun org-show-entry ()
25491 "Show the body directly following this heading.
25492 Show the heading too, if it is currently invisible."
25493 (interactive)
25494 (save-excursion
25495 (condition-case nil
25496 (progn
25497 (org-back-to-heading t)
25498 (outline-flag-region
25499 (max (point-min) (1- (point)))
25500 (save-excursion
25501 (re-search-forward
25502 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
25503 (or (match-beginning 1) (point-max)))
25504 nil))
25505 (error nil))))
25507 (defun org-make-options-regexp (kwds)
25508 "Make a regular expression for keyword lines."
25509 (concat
25511 "#?[ \t]*\\+\\("
25512 (mapconcat 'regexp-quote kwds "\\|")
25513 "\\):[ \t]*"
25514 "\\(.+\\)"))
25516 ;; Make isearch reveal the necessary context
25517 (defun org-isearch-end ()
25518 "Reveal context after isearch exits."
25519 (when isearch-success ; only if search was successful
25520 (if (featurep 'xemacs)
25521 ;; Under XEmacs, the hook is run in the correct place,
25522 ;; we directly show the context.
25523 (org-show-context 'isearch)
25524 ;; In Emacs the hook runs *before* restoring the overlays.
25525 ;; So we have to use a one-time post-command-hook to do this.
25526 ;; (Emacs 22 has a special variable, see function `org-mode')
25527 (unless (and (boundp 'isearch-mode-end-hook-quit)
25528 isearch-mode-end-hook-quit)
25529 ;; Only when the isearch was not quitted.
25530 (org-add-hook 'post-command-hook 'org-isearch-post-command
25531 'append 'local)))))
25533 (defun org-isearch-post-command ()
25534 "Remove self from hook, and show context."
25535 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
25536 (org-show-context 'isearch))
25539 ;;;; Address problems with some other packages
25541 ;; Make flyspell not check words in links, to not mess up our keymap
25542 (defun org-mode-flyspell-verify ()
25543 "Don't let flyspell put overlays at active buttons."
25544 (not (get-text-property (point) 'keymap)))
25546 ;; Make `bookmark-jump' show the jump location if it was hidden.
25547 (eval-after-load "bookmark"
25548 '(if (boundp 'bookmark-after-jump-hook)
25549 ;; We can use the hook
25550 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25551 ;; Hook not available, use advice
25552 (defadvice bookmark-jump (after org-make-visible activate)
25553 "Make the position visible."
25554 (org-bookmark-jump-unhide))))
25556 (defun org-bookmark-jump-unhide ()
25557 "Unhide the current position, to show the bookmark location."
25558 (and (org-mode-p)
25559 (or (org-invisible-p)
25560 (save-excursion (goto-char (max (point-min) (1- (point))))
25561 (org-invisible-p)))
25562 (org-show-context 'bookmark-jump)))
25564 ;; Make session.el ignore our circular variable
25565 (eval-after-load "session"
25566 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25568 ;;;; Experimental code
25571 (defun org-closed-in-range ()
25572 "Sparse tree of items closed in a certain time range.
25573 Still experimental, may disappear in the furture."
25574 (interactive)
25575 ;; Get the time interval from the user.
25576 (let* ((time1 (time-to-seconds
25577 (org-read-date nil 'to-time nil "Starting date: ")))
25578 (time2 (time-to-seconds
25579 (org-read-date nil 'to-time nil "End date:")))
25580 ;; callback function
25581 (callback (lambda ()
25582 (let ((time
25583 (time-to-seconds
25584 (apply 'encode-time
25585 (org-parse-time-string
25586 (match-string 1))))))
25587 ;; check if time in interval
25588 (and (>= time time1) (<= time time2))))))
25589 ;; make tree, check each match with the callback
25590 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
25592 (defun org-fill-paragraph-experimental (&optional justify)
25593 "Re-align a table, pass through to fill-paragraph if no table."
25594 (let ((table-p (org-at-table-p))
25595 (table.el-p (org-at-table.el-p)))
25596 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
25597 (table.el-p t) ; skip table.el tables
25598 (table-p (org-table-align) t) ; align org-mode tables
25599 ((save-excursion
25600 (let ((pos (1+ (point-at-eol))))
25601 (backward-paragraph 1)
25602 (re-search-forward "\\\\\\\\[ \t]*$" pos t)))
25603 (save-excursion
25604 (save-restriction
25605 (narrow-to-region (1+ (match-end 0)) (point-max))
25606 (fill-paragraph nil)
25607 t)))
25608 (t nil)))) ; call paragraph-fill
25610 ;; FIXME: this needs a much better algorithm
25611 (defun org-assign-fast-keys (alist)
25612 "Assign fast keys to a keyword-key alist.
25613 Respect keys that are already there."
25614 (let (new e k c c1 c2 (char ?a))
25615 (while (setq e (pop alist))
25616 (cond
25617 ((equal e '(:startgroup)) (push e new))
25618 ((equal e '(:endgroup)) (push e new))
25620 (setq k (car e) c2 nil)
25621 (if (cdr e)
25622 (setq c (cdr e))
25623 ;; automatically assign a character.
25624 (setq c1 (string-to-char
25625 (downcase (substring
25626 k (if (= (string-to-char k) ?@) 1 0)))))
25627 (if (or (rassoc c1 new) (rassoc c1 alist))
25628 (while (or (rassoc char new) (rassoc char alist))
25629 (setq char (1+ char)))
25630 (setq c2 c1))
25631 (setq c (or c2 char)))
25632 (push (cons k c) new))))
25633 (nreverse new)))
25635 (defun org-parse-local-options (string var)
25636 "Parse STRING for startup setting relevant for variable VAR."
25637 (let ((rtn (symbol-value var))
25638 e opts)
25639 (save-match-data
25640 (if (or (not string) (not (string-match "\\S-" string)))
25642 (setq opts (delq nil (mapcar (lambda (x)
25643 (setq e (assoc x org-startup-options))
25644 (if (eq (nth 1 e) var) e nil))
25645 (org-split-string string "[ \t]+"))))
25646 (if (not opts)
25648 (setq rtn nil)
25649 (while (setq e (pop opts))
25650 (if (not (nth 3 e))
25651 (setq rtn (nth 2 e))
25652 (if (not (listp rtn)) (setq rtn nil))
25653 (push (nth 2 e) rtn)))
25654 rtn)))))
25656 ;; FIXME: what else would be useful?
25657 ;; - priority
25658 ;; - date
25660 (defun org-sparse-tree (&optional arg)
25661 "Create a sparse tree, prompt for the details.
25662 This command can create sparse trees. You first need to select the type
25663 of match used to create the tree:
25665 t Show entries with a specific TODO keyword.
25666 T Show entries selected by a tags match.
25667 p Enter a property name and its value (both with completion on existing
25668 names/values) and show entries with that property.
25669 r Show entries matching a regular expression"
25670 (interactive "P")
25671 (let (ans kwd value)
25672 (message "Sparse tree: [r]egexp [t]odo-kwd [T]ag [p]roperty")
25673 (setq ans (read-char-exclusive))
25674 (cond
25675 ((equal ans ?t)
25676 (org-show-todo-tree '(4)))
25677 ((equal ans ?T)
25678 (call-interactively 'org-tags-sparse-tree))
25679 ((member ans '(?p ?P))
25680 (setq kwd (completing-read "Property: "
25681 (mapcar 'list (org-buffer-property-keys))))
25682 (setq value (completing-read "Value: "
25683 (mapcar 'list (org-property-values kwd))))
25684 (unless (string-match "\\`{.*}\\'" value)
25685 (setq value (concat "\"" value "\"")))
25686 (org-tags-sparse-tree arg (concat kwd "=" value)))
25687 ((member ans '(?r ?R))
25688 (call-interactively 'org-occur))
25689 (t (error "No such sparse tree command \"%c\"" ans)))))
25692 ;;;; Finish up
25694 (provide 'org)
25696 (run-hooks 'org-load-hook)
25698 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
25699 ;;; org.el ends here