Release 5.12b
[org-mode.git] / org.el
blob49448e5bd763da7686ca5a98681cea7b97d59e12
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.12a
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.12a"
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))
4955 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4956 ;; Now set the full font-lock-keywords
4957 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4958 (org-set-local 'font-lock-defaults
4959 '(org-font-lock-keywords t nil nil backward-paragraph))
4960 (kill-local-variable 'font-lock-keywords) nil))
4962 (defvar org-m nil)
4963 (defvar org-l nil)
4964 (defvar org-f nil)
4965 (defun org-get-level-face (n)
4966 "Get the right face for match N in font-lock matching of healdines."
4967 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4968 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4969 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4970 (cond
4971 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4972 ((eq n 2) org-f)
4973 (t (if org-level-color-stars-only nil org-f))))
4975 (defun org-get-todo-face (kwd)
4976 "Get the right face for a TODO keyword KWD.
4977 If KWD is a number, get the corresponding match group."
4978 (if (numberp kwd) (setq kwd (match-string kwd)))
4979 (or (cdr (assoc kwd org-todo-keyword-faces))
4980 (and (member kwd org-done-keywords) 'org-done)
4981 'org-todo))
4983 (defun org-unfontify-region (beg end &optional maybe_loudly)
4984 "Remove fontification and activation overlays from links."
4985 (font-lock-default-unfontify-region beg end)
4986 (let* ((buffer-undo-list t)
4987 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4988 (inhibit-modification-hooks t)
4989 deactivate-mark buffer-file-name buffer-file-truename)
4990 (remove-text-properties beg end
4991 '(mouse-face t keymap t org-linked-text t
4992 invisible t intangible t))))
4994 ;;;; Visibility cycling, including org-goto and indirect buffer
4996 ;;; Cycling
4998 (defvar org-cycle-global-status nil)
4999 (make-variable-buffer-local 'org-cycle-global-status)
5000 (defvar org-cycle-subtree-status nil)
5001 (make-variable-buffer-local 'org-cycle-subtree-status)
5003 ;;;###autoload
5004 (defun org-cycle (&optional arg)
5005 "Visibility cycling for Org-mode.
5007 - When this function is called with a prefix argument, rotate the entire
5008 buffer through 3 states (global cycling)
5009 1. OVERVIEW: Show only top-level headlines.
5010 2. CONTENTS: Show all headlines of all levels, but no body text.
5011 3. SHOW ALL: Show everything.
5013 - When point is at the beginning of a headline, rotate the subtree started
5014 by this line through 3 different states (local cycling)
5015 1. FOLDED: Only the main headline is shown.
5016 2. CHILDREN: The main headline and the direct children are shown.
5017 From this state, you can move to one of the children
5018 and zoom in further.
5019 3. SUBTREE: Show the entire subtree, including body text.
5021 - When there is a numeric prefix, go up to a heading with level ARG, do
5022 a `show-subtree' and return to the previous cursor position. If ARG
5023 is negative, go up that many levels.
5025 - When point is not at the beginning of a headline, execute
5026 `indent-relative', like TAB normally does. See the option
5027 `org-cycle-emulate-tab' for details.
5029 - Special case: if point is at the beginning of the buffer and there is
5030 no headline in line 1, this function will act as if called with prefix arg.
5031 But only if also the variable `org-cycle-global-at-bob' is t."
5032 (interactive "P")
5033 (let* ((outline-regexp
5034 (if (and (org-mode-p) org-cycle-include-plain-lists)
5035 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5036 outline-regexp))
5037 (bob-special (and org-cycle-global-at-bob (bobp)
5038 (not (looking-at outline-regexp))))
5039 (org-cycle-hook
5040 (if bob-special
5041 (delq 'org-optimize-window-after-visibility-change
5042 (copy-sequence org-cycle-hook))
5043 org-cycle-hook))
5044 (pos (point)))
5046 (if (or bob-special (equal arg '(4)))
5047 ;; special case: use global cycling
5048 (setq arg t))
5050 (cond
5052 ((org-at-table-p 'any)
5053 ;; Enter the table or move to the next field in the table
5054 (or (org-table-recognize-table.el)
5055 (progn
5056 (if arg (org-table-edit-field t)
5057 (org-table-justify-field-maybe)
5058 (call-interactively 'org-table-next-field)))))
5060 ((eq arg t) ;; Global cycling
5062 (cond
5063 ((and (eq last-command this-command)
5064 (eq org-cycle-global-status 'overview))
5065 ;; We just created the overview - now do table of contents
5066 ;; This can be slow in very large buffers, so indicate action
5067 (message "CONTENTS...")
5068 (org-content)
5069 (message "CONTENTS...done")
5070 (setq org-cycle-global-status 'contents)
5071 (run-hook-with-args 'org-cycle-hook 'contents))
5073 ((and (eq last-command this-command)
5074 (eq org-cycle-global-status 'contents))
5075 ;; We just showed the table of contents - now show everything
5076 (show-all)
5077 (message "SHOW ALL")
5078 (setq org-cycle-global-status 'all)
5079 (run-hook-with-args 'org-cycle-hook 'all))
5082 ;; Default action: go to overview
5083 (org-overview)
5084 (message "OVERVIEW")
5085 (setq org-cycle-global-status 'overview)
5086 (run-hook-with-args 'org-cycle-hook 'overview))))
5088 ((and org-drawers org-drawer-regexp
5089 (save-excursion
5090 (beginning-of-line 1)
5091 (looking-at org-drawer-regexp)))
5092 ;; Toggle block visibility
5093 (org-flag-drawer
5094 (not (get-char-property (match-end 0) 'invisible))))
5096 ((integerp arg)
5097 ;; Show-subtree, ARG levels up from here.
5098 (save-excursion
5099 (org-back-to-heading)
5100 (outline-up-heading (if (< arg 0) (- arg)
5101 (- (funcall outline-level) arg)))
5102 (org-show-subtree)))
5104 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5105 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5106 ;; At a heading: rotate between three different views
5107 (org-back-to-heading)
5108 (let ((goal-column 0) eoh eol eos)
5109 ;; First, some boundaries
5110 (save-excursion
5111 (org-back-to-heading)
5112 (save-excursion
5113 (beginning-of-line 2)
5114 (while (and (not (eobp)) ;; this is like `next-line'
5115 (get-char-property (1- (point)) 'invisible))
5116 (beginning-of-line 2)) (setq eol (point)))
5117 (outline-end-of-heading) (setq eoh (point))
5118 (org-end-of-subtree t)
5119 (unless (eobp)
5120 (skip-chars-forward " \t\n")
5121 (beginning-of-line 1) ; in case this is an item
5123 (setq eos (1- (point))))
5124 ;; Find out what to do next and set `this-command'
5125 (cond
5126 ((= eos eoh)
5127 ;; Nothing is hidden behind this heading
5128 (message "EMPTY ENTRY")
5129 (setq org-cycle-subtree-status nil)
5130 (save-excursion
5131 (goto-char eos)
5132 (outline-next-heading)
5133 (if (org-invisible-p) (org-flag-heading nil))))
5134 ((or (>= eol eos)
5135 (not (string-match "\\S-" (buffer-substring eol eos))))
5136 ;; Entire subtree is hidden in one line: open it
5137 (org-show-entry)
5138 (show-children)
5139 (message "CHILDREN")
5140 (save-excursion
5141 (goto-char eos)
5142 (outline-next-heading)
5143 (if (org-invisible-p) (org-flag-heading nil)))
5144 (setq org-cycle-subtree-status 'children)
5145 (run-hook-with-args 'org-cycle-hook 'children))
5146 ((and (eq last-command this-command)
5147 (eq org-cycle-subtree-status 'children))
5148 ;; We just showed the children, now show everything.
5149 (org-show-subtree)
5150 (message "SUBTREE")
5151 (setq org-cycle-subtree-status 'subtree)
5152 (run-hook-with-args 'org-cycle-hook 'subtree))
5154 ;; Default action: hide the subtree.
5155 (hide-subtree)
5156 (message "FOLDED")
5157 (setq org-cycle-subtree-status 'folded)
5158 (run-hook-with-args 'org-cycle-hook 'folded)))))
5160 ;; TAB emulation
5161 (buffer-read-only (org-back-to-heading))
5163 ((org-try-cdlatex-tab))
5165 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5166 (or (not (bolp))
5167 (not (looking-at outline-regexp))))
5168 (call-interactively (global-key-binding "\t")))
5170 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5171 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5172 (or (and (eq org-cycle-emulate-tab 'white)
5173 (= (match-end 0) (point-at-eol)))
5174 (and (eq org-cycle-emulate-tab 'whitestart)
5175 (>= (match-end 0) pos))))
5177 (eq org-cycle-emulate-tab t))
5178 (if (and (looking-at "[ \n\r\t]")
5179 (string-match "^[ \t]*$" (buffer-substring
5180 (point-at-bol) (point))))
5181 (progn
5182 (beginning-of-line 1)
5183 (and (looking-at "[ \t]+") (replace-match ""))))
5184 (call-interactively (global-key-binding "\t")))
5186 (t (save-excursion
5187 (org-back-to-heading)
5188 (org-cycle))))))
5190 ;;;###autoload
5191 (defun org-global-cycle (&optional arg)
5192 "Cycle the global visibility. For details see `org-cycle'."
5193 (interactive "P")
5194 (let ((org-cycle-include-plain-lists
5195 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5196 (if (integerp arg)
5197 (progn
5198 (show-all)
5199 (hide-sublevels arg)
5200 (setq org-cycle-global-status 'contents))
5201 (org-cycle '(4)))))
5203 (defun org-overview ()
5204 "Switch to overview mode, shoing only top-level headlines.
5205 Really, this shows all headlines with level equal or greater than the level
5206 of the first headline in the buffer. This is important, because if the
5207 first headline is not level one, then (hide-sublevels 1) gives confusing
5208 results."
5209 (interactive)
5210 (let ((level (save-excursion
5211 (goto-char (point-min))
5212 (if (re-search-forward (concat "^" outline-regexp) nil t)
5213 (progn
5214 (goto-char (match-beginning 0))
5215 (funcall outline-level))))))
5216 (and level (hide-sublevels level))))
5218 (defun org-content (&optional arg)
5219 "Show all headlines in the buffer, like a table of contents.
5220 With numerical argument N, show content up to level N."
5221 (interactive "P")
5222 (save-excursion
5223 ;; Visit all headings and show their offspring
5224 (and (integerp arg) (org-overview))
5225 (goto-char (point-max))
5226 (catch 'exit
5227 (while (and (progn (condition-case nil
5228 (outline-previous-visible-heading 1)
5229 (error (goto-char (point-min))))
5231 (looking-at outline-regexp))
5232 (if (integerp arg)
5233 (show-children (1- arg))
5234 (show-branches))
5235 (if (bobp) (throw 'exit nil))))))
5238 (defun org-optimize-window-after-visibility-change (state)
5239 "Adjust the window after a change in outline visibility.
5240 This function is the default value of the hook `org-cycle-hook'."
5241 (when (get-buffer-window (current-buffer))
5242 (cond
5243 ; ((eq state 'overview) (org-first-headline-recenter 1))
5244 ; ((eq state 'overview) (org-beginning-of-line))
5245 ((eq state 'content) nil)
5246 ((eq state 'all) nil)
5247 ((eq state 'folded) nil)
5248 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5249 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5252 (defun org-cycle-show-empty-lines (state)
5253 "Show empty lines above all visible headlines.
5254 The region to be covered depends on STATE when called through
5255 `org-cycle-hook'. Lisp program can use t for STATE to get the
5256 entire buffer covered. Note that an empty line is only shown if there
5257 are at least `org-cycle-separator-lines' empty lines before the headeline."
5258 (when (> org-cycle-separator-lines 0)
5259 (save-excursion
5260 (let* ((n org-cycle-separator-lines)
5261 (re (cond
5262 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5263 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5264 (t (let ((ns (number-to-string (- n 2))))
5265 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5266 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5267 beg end)
5268 (cond
5269 ((memq state '(overview contents t))
5270 (setq beg (point-min) end (point-max)))
5271 ((memq state '(children folded))
5272 (setq beg (point) end (progn (org-end-of-subtree t t)
5273 (beginning-of-line 2)
5274 (point)))))
5275 (when beg
5276 (goto-char beg)
5277 (while (re-search-forward re end t)
5278 (if (not (get-char-property (match-end 1) 'invisible))
5279 (outline-flag-region
5280 (match-beginning 1) (match-end 1) nil)))))))
5281 ;; Never hide empty lines at the end of the file.
5282 (save-excursion
5283 (goto-char (point-max))
5284 (outline-previous-heading)
5285 (outline-end-of-heading)
5286 (if (and (looking-at "[ \t\n]+")
5287 (= (match-end 0) (point-max)))
5288 (outline-flag-region (point) (match-end 0) nil))))
5290 (defun org-subtree-end-visible-p ()
5291 "Is the end of the current subtree visible?"
5292 (pos-visible-in-window-p
5293 (save-excursion (org-end-of-subtree t) (point))))
5295 (defun org-first-headline-recenter (&optional N)
5296 "Move cursor to the first headline and recenter the headline.
5297 Optional argument N means, put the headline into the Nth line of the window."
5298 (goto-char (point-min))
5299 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5300 (beginning-of-line)
5301 (recenter (prefix-numeric-value N))))
5303 ;;; Org-goto
5305 (defvar org-goto-window-configuration nil)
5306 (defvar org-goto-marker nil)
5307 (defvar org-goto-map
5308 (let ((map (make-sparse-keymap)))
5309 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5310 (while (setq cmd (pop cmds))
5311 (substitute-key-definition cmd cmd map global-map)))
5312 (suppress-keymap map)
5313 (org-defkey map "\C-m" 'org-goto-ret)
5314 (org-defkey map [(left)] 'org-goto-left)
5315 (org-defkey map [(right)] 'org-goto-right)
5316 (org-defkey map [(?q)] 'org-goto-quit)
5317 (org-defkey map [(control ?g)] 'org-goto-quit)
5318 (org-defkey map "\C-i" 'org-cycle)
5319 (org-defkey map [(tab)] 'org-cycle)
5320 (org-defkey map [(down)] 'outline-next-visible-heading)
5321 (org-defkey map [(up)] 'outline-previous-visible-heading)
5322 (org-defkey map "n" 'outline-next-visible-heading)
5323 (org-defkey map "p" 'outline-previous-visible-heading)
5324 (org-defkey map "f" 'outline-forward-same-level)
5325 (org-defkey map "b" 'outline-backward-same-level)
5326 (org-defkey map "u" 'outline-up-heading)
5327 (org-defkey map "/" 'org-occur)
5328 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5329 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5330 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5331 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5332 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5333 map))
5335 (defconst org-goto-help
5336 "Browse copy of buffer to find location or copy text.
5337 RET=jump to location [Q]uit and return to previous location
5338 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur"
5341 (defun org-goto ()
5342 "Look up a different location in the current file, keeping current visibility.
5344 When you want look-up or go to a different location in a document, the
5345 fastest way is often to fold the entire buffer and then dive into the tree.
5346 This method has the disadvantage, that the previous location will be folded,
5347 which may not be what you want.
5349 This command works around this by showing a copy of the current buffer
5350 in an indirect buffer, in overview mode. You can dive into the tree in
5351 that copy, use org-occur and incremental search to find a location.
5352 When pressing RET or `Q', the command returns to the original buffer in
5353 which the visibility is still unchanged. After RET is will also jump to
5354 the location selected in the indirect buffer and expose the
5355 the headline hierarchy above."
5356 (interactive)
5357 (let* ((org-goto-start-pos (point))
5358 (selected-point
5359 (car (org-get-location (current-buffer) org-goto-help))))
5360 (if selected-point
5361 (progn
5362 (org-mark-ring-push org-goto-start-pos)
5363 (goto-char selected-point)
5364 (if (or (org-invisible-p) (org-invisible-p2))
5365 (org-show-context 'org-goto)))
5366 (message "Quit"))))
5368 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5369 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5371 (defun org-get-location (buf help)
5372 "Let the user select a location in the Org-mode buffer BUF.
5373 This function uses a recursive edit. It returns the selected position
5374 or nil."
5375 (let (org-goto-selected-point org-goto-exit-command)
5376 (save-excursion
5377 (save-window-excursion
5378 (delete-other-windows)
5379 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5380 (switch-to-buffer
5381 (condition-case nil
5382 (make-indirect-buffer (current-buffer) "*org-goto*")
5383 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5384 (with-output-to-temp-buffer "*Help*"
5385 (princ help))
5386 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5387 (setq buffer-read-only nil)
5388 (let ((org-startup-truncated t)
5389 (org-startup-folded nil)
5390 (org-startup-align-all-tables nil))
5391 (org-mode)
5392 (org-overview))
5393 (setq buffer-read-only t)
5394 (if (and (boundp 'org-goto-start-pos)
5395 (integer-or-marker-p org-goto-start-pos))
5396 (let ((org-show-hierarchy-above t)
5397 (org-show-siblings t)
5398 (org-show-following-heading t))
5399 (goto-char org-goto-start-pos)
5400 (and (org-invisible-p) (org-show-context)))
5401 (goto-char (point-min)))
5402 (org-beginning-of-line)
5403 (message "Select location and press RET")
5404 ;; now we make sure that during selection, ony very few keys work
5405 ;; and that it is impossible to switch to another window.
5406 ; (let ((gm (current-global-map))
5407 ; (overriding-local-map org-goto-map))
5408 ; (unwind-protect
5409 ; (progn
5410 ; (use-global-map org-goto-map)
5411 ; (recursive-edit))
5412 ; (use-global-map gm)))
5413 (use-local-map org-goto-map)
5414 (recursive-edit)
5416 (kill-buffer "*org-goto*")
5417 (cons org-goto-selected-point org-goto-exit-command)))
5419 (defun org-goto-ret (&optional arg)
5420 "Finish `org-goto' by going to the new location."
5421 (interactive "P")
5422 (setq org-goto-selected-point (point)
5423 org-goto-exit-command 'return)
5424 (throw 'exit nil))
5426 (defun org-goto-left ()
5427 "Finish `org-goto' by going to the new location."
5428 (interactive)
5429 (if (org-on-heading-p)
5430 (progn
5431 (beginning-of-line 1)
5432 (setq org-goto-selected-point (point)
5433 org-goto-exit-command 'left)
5434 (throw 'exit nil))
5435 (error "Not on a heading")))
5437 (defun org-goto-right ()
5438 "Finish `org-goto' by going to the new location."
5439 (interactive)
5440 (if (org-on-heading-p)
5441 (progn
5442 (setq org-goto-selected-point (point)
5443 org-goto-exit-command 'right)
5444 (throw 'exit nil))
5445 (error "Not on a heading")))
5447 (defun org-goto-quit ()
5448 "Finish `org-goto' without cursor motion."
5449 (interactive)
5450 (setq org-goto-selected-point nil)
5451 (setq org-goto-exit-command 'quit)
5452 (throw 'exit nil))
5454 ;;; Indirect buffer display of subtrees
5456 (defvar org-indirect-dedicated-frame nil
5457 "This is the frame being used for indirect tree display.")
5458 (defvar org-last-indirect-buffer nil)
5460 (defun org-tree-to-indirect-buffer (&optional arg)
5461 "Create indirect buffer and narrow it to current subtree.
5462 With numerical prefix ARG, go up to this level and then take that tree.
5463 If ARG is negative, go up that many levels.
5464 Normally this command removes the indirect buffer previously made
5465 with this command. However, when called with a C-u prefix, the last buffer
5466 is kept so that you can work with several indirect buffers at the same time.
5467 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5468 requests that a new frame be made for the new buffer, so that the dedicated
5469 frame is not changed."
5470 (interactive "P")
5471 (let ((cbuf (current-buffer))
5472 (cwin (selected-window))
5473 (pos (point))
5474 beg end level heading ibuf)
5475 (save-excursion
5476 (org-back-to-heading t)
5477 (when (numberp arg)
5478 (setq level (org-outline-level))
5479 (if (< arg 0) (setq arg (+ level arg)))
5480 (while (> (setq level (org-outline-level)) arg)
5481 (outline-up-heading 1 t)))
5482 (setq beg (point)
5483 heading (org-get-heading))
5484 (org-end-of-subtree t) (setq end (point)))
5485 (if (and (not arg)
5486 (buffer-live-p org-last-indirect-buffer))
5487 (kill-buffer org-last-indirect-buffer))
5488 (setq ibuf (org-get-indirect-buffer cbuf)
5489 org-last-indirect-buffer ibuf)
5490 (cond
5491 ((or (eq org-indirect-buffer-display 'new-frame)
5492 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5493 (select-frame (make-frame))
5494 (delete-other-windows)
5495 (switch-to-buffer ibuf)
5496 (org-set-frame-title heading))
5497 ((eq org-indirect-buffer-display 'dedicated-frame)
5498 (raise-frame
5499 (select-frame (or (and org-indirect-dedicated-frame
5500 (frame-live-p org-indirect-dedicated-frame)
5501 org-indirect-dedicated-frame)
5502 (setq org-indirect-dedicated-frame (make-frame)))))
5503 (delete-other-windows)
5504 (switch-to-buffer ibuf)
5505 (org-set-frame-title (concat "Indirect: " heading)))
5506 ((eq org-indirect-buffer-display 'current-window)
5507 (switch-to-buffer ibuf))
5508 ((eq org-indirect-buffer-display 'other-window)
5509 (pop-to-buffer ibuf))
5510 (t (error "Invalid value.")))
5511 (if (featurep 'xemacs)
5512 (save-excursion (org-mode) (turn-on-font-lock)))
5513 (narrow-to-region beg end)
5514 (show-all)
5515 (goto-char pos)
5516 (and (window-live-p cwin) (select-window cwin))))
5518 (defun org-get-indirect-buffer (&optional buffer)
5519 (setq buffer (or buffer (current-buffer)))
5520 (let ((n 1) (base (buffer-name buffer)) bname)
5521 (while (buffer-live-p
5522 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5523 (setq n (1+ n)))
5524 (condition-case nil
5525 (make-indirect-buffer buffer bname 'clone)
5526 (error (make-indirect-buffer buffer bname)))))
5528 (defun org-set-frame-title (title)
5529 "Set the title of the current frame to the string TITLE."
5530 ;; FIXME: how to name a single frame in XEmacs???
5531 (unless (featurep 'xemacs)
5532 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5534 ;;;; Structure editing
5536 ;;; Inserting headlines
5538 (defun org-insert-heading (&optional force-heading)
5539 "Insert a new heading or item with same depth at point.
5540 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5541 If point is at the beginning of a headline, insert a sibling before the
5542 current headline. If point is in the middle of a headline, split the headline
5543 at that position and make the rest of the headline part of the sibling below
5544 the current headline."
5545 (interactive "P")
5546 (if (= (buffer-size) 0)
5547 (insert "\n* ")
5548 (when (or force-heading (not (org-insert-item)))
5549 (let* ((head (save-excursion
5550 (condition-case nil
5551 (progn
5552 (org-back-to-heading)
5553 (match-string 0))
5554 (error "*"))))
5555 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5556 pos)
5557 (cond
5558 ((and (org-on-heading-p) (bolp)
5559 (or (bobp)
5560 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5561 (open-line (if blank 2 1)))
5562 ((and (bolp)
5563 (or (bobp)
5564 (save-excursion
5565 (backward-char 1) (not (org-invisible-p)))))
5566 nil)
5567 (t (newline (if blank 2 1))))
5568 (insert head) (just-one-space)
5569 (setq pos (point))
5570 (end-of-line 1)
5571 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5572 (run-hooks 'org-insert-heading-hook)))))
5574 (defun org-insert-heading-after-current ()
5575 "Insert a new heading with same level as current, after current subtree."
5576 (interactive)
5577 (org-back-to-heading)
5578 (org-insert-heading)
5579 (org-move-subtree-down)
5580 (end-of-line 1))
5582 (defun org-insert-todo-heading (arg)
5583 "Insert a new heading with the same level and TODO state as current heading.
5584 If the heading has no TODO state, or if the state is DONE, use the first
5585 state (TODO by default). Also with prefix arg, force first state."
5586 (interactive "P")
5587 (when (not (org-insert-item 'checkbox))
5588 (org-insert-heading)
5589 (save-excursion
5590 (org-back-to-heading)
5591 (outline-previous-heading)
5592 (looking-at org-todo-line-regexp))
5593 (if (or arg
5594 (not (match-beginning 2))
5595 (member (match-string 2) org-done-keywords))
5596 (insert (car org-todo-keywords-1) " ")
5597 (insert (match-string 2) " "))))
5599 (defun org-insert-subheading (arg)
5600 "Insert a new subheading and demote it.
5601 Works for outline headings and for plain lists alike."
5602 (interactive "P")
5603 (org-insert-heading arg)
5604 (cond
5605 ((org-on-heading-p) (org-do-demote))
5606 ((org-at-item-p) (org-indent-item 1))))
5608 (defun org-insert-todo-subheading (arg)
5609 "Insert a new subheading with TODO keyword or checkbox and demote it.
5610 Works for outline headings and for plain lists alike."
5611 (interactive "P")
5612 (org-insert-todo-heading arg)
5613 (cond
5614 ((org-on-heading-p) (org-do-demote))
5615 ((org-at-item-p) (org-indent-item 1))))
5617 ;;; Promotion and Demotion
5619 (defun org-promote-subtree ()
5620 "Promote the entire subtree.
5621 See also `org-promote'."
5622 (interactive)
5623 (save-excursion
5624 (org-map-tree 'org-promote))
5625 (org-fix-position-after-promote))
5627 (defun org-demote-subtree ()
5628 "Demote the entire subtree. See `org-demote'.
5629 See also `org-promote'."
5630 (interactive)
5631 (save-excursion
5632 (org-map-tree 'org-demote))
5633 (org-fix-position-after-promote))
5636 (defun org-do-promote ()
5637 "Promote the current heading higher up the tree.
5638 If the region is active in `transient-mark-mode', promote all headings
5639 in the region."
5640 (interactive)
5641 (save-excursion
5642 (if (org-region-active-p)
5643 (org-map-region 'org-promote (region-beginning) (region-end))
5644 (org-promote)))
5645 (org-fix-position-after-promote))
5647 (defun org-do-demote ()
5648 "Demote the current heading lower down the tree.
5649 If the region is active in `transient-mark-mode', demote all headings
5650 in the region."
5651 (interactive)
5652 (save-excursion
5653 (if (org-region-active-p)
5654 (org-map-region 'org-demote (region-beginning) (region-end))
5655 (org-demote)))
5656 (org-fix-position-after-promote))
5658 (defun org-fix-position-after-promote ()
5659 "Make sure that after pro/demotion cursor position is right."
5660 (let ((pos (point)))
5661 (when (save-excursion
5662 (beginning-of-line 1)
5663 (looking-at org-todo-line-regexp)
5664 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5665 (cond ((eobp) (insert " "))
5666 ((eolp) (insert " "))
5667 ((equal (char-after) ?\ ) (forward-char 1))))))
5669 (defun org-reduced-level (l)
5670 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5672 (defun org-get-legal-level (level &optional change)
5673 "Rectify a level change under the influence of `org-odd-levels-only'
5674 LEVEL is a current level, CHANGE is by how much the level should be
5675 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5676 even level numbers will become the next higher odd number."
5677 (if org-odd-levels-only
5678 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5679 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5680 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5681 (max 1 (+ level change))))
5683 (defun org-promote ()
5684 "Promote the current heading higher up the tree.
5685 If the region is active in `transient-mark-mode', promote all headings
5686 in the region."
5687 (org-back-to-heading t)
5688 (let* ((level (save-match-data (funcall outline-level)))
5689 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
5690 (diff (abs (- level (length up-head) -1))))
5691 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5692 (replace-match up-head nil t)
5693 ;; Fixup tag positioning
5694 (and org-auto-align-tags (org-set-tags nil t))
5695 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5697 (defun org-demote ()
5698 "Demote the current heading lower down the tree.
5699 If the region is active in `transient-mark-mode', demote all headings
5700 in the region."
5701 (org-back-to-heading t)
5702 (let* ((level (save-match-data (funcall outline-level)))
5703 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
5704 (diff (abs (- level (length down-head) -1))))
5705 (replace-match down-head nil t)
5706 ;; Fixup tag positioning
5707 (and org-auto-align-tags (org-set-tags nil t))
5708 (if org-adapt-indentation (org-fixup-indentation diff))))
5710 (defun org-map-tree (fun)
5711 "Call FUN for every heading underneath the current one."
5712 (org-back-to-heading)
5713 (let ((level (funcall outline-level)))
5714 (save-excursion
5715 (funcall fun)
5716 (while (and (progn
5717 (outline-next-heading)
5718 (> (funcall outline-level) level))
5719 (not (eobp)))
5720 (funcall fun)))))
5722 (defun org-map-region (fun beg end)
5723 "Call FUN for every heading between BEG and END."
5724 (let ((org-ignore-region t))
5725 (save-excursion
5726 (setq end (copy-marker end))
5727 (goto-char beg)
5728 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5729 (< (point) end))
5730 (funcall fun))
5731 (while (and (progn
5732 (outline-next-heading)
5733 (< (point) end))
5734 (not (eobp)))
5735 (funcall fun)))))
5737 (defun org-fixup-indentation (diff)
5738 "Change the indentation in the current entry by DIFF
5739 However, if any line in the current entry has no indentation, or if it
5740 would end up with no indentation after the change, nothing at all is done."
5741 (save-excursion
5742 (let ((end (save-excursion (outline-next-heading)
5743 (point-marker)))
5744 (prohibit (if (> diff 0)
5745 "^\\S-"
5746 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5747 col)
5748 (unless (save-excursion (end-of-line 1)
5749 (re-search-forward prohibit end t))
5750 (while (re-search-forward "^[ \t]+" end t)
5751 (goto-char (match-end 0))
5752 (setq col (current-column))
5753 (if (< diff 0) (replace-match ""))
5754 (indent-to (+ diff col))))
5755 (move-marker end nil))))
5757 (defun org-convert-to-odd-levels ()
5758 "Convert an org-mode file with all levels allowed to one with odd levels.
5759 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5760 level 5 etc."
5761 (interactive)
5762 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5763 (let ((org-odd-levels-only nil) n)
5764 (save-excursion
5765 (goto-char (point-min))
5766 (while (re-search-forward "^\\*\\*+ " nil t)
5767 (setq n (- (length (match-string 0)) 2))
5768 (while (>= (setq n (1- n)) 0)
5769 (org-demote))
5770 (end-of-line 1))))))
5773 (defun org-convert-to-oddeven-levels ()
5774 "Convert an org-mode file with only odd levels to one with odd and even levels.
5775 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5776 section with an even level, conversion would destroy the structure of the file. An error
5777 is signaled in this case."
5778 (interactive)
5779 (goto-char (point-min))
5780 ;; First check if there are no even levels
5781 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5782 (org-show-context t)
5783 (error "Not all levels are odd in this file. Conversion not possible."))
5784 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5785 (let ((org-odd-levels-only nil) n)
5786 (save-excursion
5787 (goto-char (point-min))
5788 (while (re-search-forward "^\\*\\*+ " nil t)
5789 (setq n (/ (length (1- (match-string 0))) 2))
5790 (while (>= (setq n (1- n)) 0)
5791 (org-promote))
5792 (end-of-line 1))))))
5794 (defun org-tr-level (n)
5795 "Make N odd if required."
5796 (if org-odd-levels-only (1+ (/ n 2)) n))
5798 ;;; Vertical tree motion, cutting and pasting of subtrees
5800 (defun org-move-subtree-up (&optional arg)
5801 "Move the current subtree up past ARG headlines of the same level."
5802 (interactive "p")
5803 (org-move-subtree-down (- (prefix-numeric-value arg))))
5805 (defun org-move-subtree-down (&optional arg)
5806 "Move the current subtree down past ARG headlines of the same level."
5807 (interactive "p")
5808 (setq arg (prefix-numeric-value arg))
5809 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5810 'outline-get-last-sibling))
5811 (ins-point (make-marker))
5812 (cnt (abs arg))
5813 beg end txt folded)
5814 ;; Select the tree
5815 (org-back-to-heading)
5816 (setq beg (point))
5817 (save-match-data
5818 (save-excursion (outline-end-of-heading)
5819 (setq folded (org-invisible-p)))
5820 (outline-end-of-subtree))
5821 (outline-next-heading)
5822 (setq end (point))
5823 ;; Find insertion point, with error handling
5824 (goto-char beg)
5825 (while (> cnt 0)
5826 (or (and (funcall movfunc) (looking-at outline-regexp))
5827 (progn (goto-char beg)
5828 (error "Cannot move past superior level or buffer limit")))
5829 (setq cnt (1- cnt)))
5830 (if (> arg 0)
5831 ;; Moving forward - still need to move over subtree
5832 (progn (outline-end-of-subtree)
5833 (outline-next-heading)
5834 (if (not (or (looking-at (concat "^" outline-regexp))
5835 (bolp)))
5836 (newline))))
5837 (move-marker ins-point (point))
5838 (setq txt (buffer-substring beg end))
5839 (delete-region beg end)
5840 (insert txt)
5841 (or (bolp) (insert "\n"))
5842 (goto-char ins-point)
5843 (if folded (hide-subtree))
5844 (move-marker ins-point nil)))
5846 (defvar org-subtree-clip ""
5847 "Clipboard for cut and paste of subtrees.
5848 This is actually only a copy of the kill, because we use the normal kill
5849 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5851 (defvar org-subtree-clip-folded nil
5852 "Was the last copied subtree folded?
5853 This is used to fold the tree back after pasting.")
5855 (defun org-cut-subtree (&optional n)
5856 "Cut the current subtree into the clipboard.
5857 With prefix arg N, cut this many sequential subtrees.
5858 This is a short-hand for marking the subtree and then cutting it."
5859 (interactive "p")
5860 (org-copy-subtree n 'cut))
5862 (defun org-copy-subtree (&optional n cut)
5863 "Cut the current subtree into the clipboard.
5864 With prefix arg N, cut this many sequential subtrees.
5865 This is a short-hand for marking the subtree and then copying it.
5866 If CUT is non-nil, actually cut the subtree."
5867 (interactive "p")
5868 (let (beg end folded)
5869 (if (interactive-p)
5870 (org-back-to-heading nil) ; take what looks like a subtree
5871 (org-back-to-heading t)) ; take what is really there
5872 (setq beg (point))
5873 (save-match-data
5874 (save-excursion (outline-end-of-heading)
5875 (setq folded (org-invisible-p)))
5876 (condition-case nil
5877 (outline-forward-same-level (1- n))
5878 (error nil))
5879 (org-end-of-subtree t t))
5880 (setq end (point))
5881 (goto-char beg)
5882 (when (> end beg)
5883 (setq org-subtree-clip-folded folded)
5884 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5885 (setq org-subtree-clip (current-kill 0))
5886 (message "%s: Subtree(s) with %d characters"
5887 (if cut "Cut" "Copied")
5888 (length org-subtree-clip)))))
5890 (defun org-paste-subtree (&optional level tree)
5891 "Paste the clipboard as a subtree, with modification of headline level.
5892 The entire subtree is promoted or demoted in order to match a new headline
5893 level. By default, the new level is derived from the visible headings
5894 before and after the insertion point, and taken to be the inferior headline
5895 level of the two. So if the previous visible heading is level 3 and the
5896 next is level 4 (or vice versa), level 4 will be used for insertion.
5897 This makes sure that the subtree remains an independent subtree and does
5898 not swallow low level entries.
5900 You can also force a different level, either by using a numeric prefix
5901 argument, or by inserting the heading marker by hand. For example, if the
5902 cursor is after \"*****\", then the tree will be shifted to level 5.
5904 If you want to insert the tree as is, just use \\[yank].
5906 If optional TREE is given, use this text instead of the kill ring."
5907 (interactive "P")
5908 (unless (org-kill-is-subtree-p tree)
5909 (error
5910 (substitute-command-keys
5911 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5912 (let* ((txt (or tree (and kill-ring (current-kill 0))))
5913 (^re (concat "^\\(" outline-regexp "\\)"))
5914 (re (concat "\\(" outline-regexp "\\)"))
5915 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5917 (old-level (if (string-match ^re txt)
5918 (- (match-end 0) (match-beginning 0) 1)
5919 -1))
5920 (force-level (cond (level (prefix-numeric-value level))
5921 ((string-match
5922 ^re_ (buffer-substring (point-at-bol) (point)))
5923 (- (match-end 1) (match-beginning 1)))
5924 (t nil)))
5925 (previous-level (save-excursion
5926 (condition-case nil
5927 (progn
5928 (outline-previous-visible-heading 1)
5929 (if (looking-at re)
5930 (- (match-end 0) (match-beginning 0) 1)
5932 (error 1))))
5933 (next-level (save-excursion
5934 (condition-case nil
5935 (progn
5936 (or (looking-at outline-regexp)
5937 (outline-next-visible-heading 1))
5938 (if (looking-at re)
5939 (- (match-end 0) (match-beginning 0) 1)
5941 (error 1))))
5942 (new-level (or force-level (max previous-level next-level)))
5943 (shift (if (or (= old-level -1)
5944 (= new-level -1)
5945 (= old-level new-level))
5947 (- new-level old-level)))
5948 (shift1 shift)
5949 (delta (if (> shift 0) -1 1))
5950 (func (if (> shift 0) 'org-demote 'org-promote))
5951 (org-odd-levels-only nil)
5952 beg end)
5953 ;; Remove the forced level indicator
5954 (if force-level
5955 (delete-region (point-at-bol) (point)))
5956 ;; Paste
5957 (beginning-of-line 1)
5958 (setq beg (point))
5959 (insert txt)
5960 (unless (string-match "\n[ \t]*\\'" txt) (insert "\n"))
5961 (setq end (point))
5962 (goto-char beg)
5963 ;; Shift if necessary
5964 (unless (= shift 0)
5965 (save-restriction
5966 (narrow-to-region beg end)
5967 (while (not (= shift 0))
5968 (org-map-region func (point-min) (point-max))
5969 (setq shift (+ delta shift)))
5970 (goto-char (point-min))))
5971 (when (interactive-p)
5972 (message "Clipboard pasted as level %d subtree" new-level))
5973 (if (and kill-ring
5974 (eq org-subtree-clip (current-kill 0))
5975 org-subtree-clip-folded)
5976 ;; The tree was folded before it was killed/copied
5977 (hide-subtree))))
5979 (defun org-kill-is-subtree-p (&optional txt)
5980 "Check if the current kill is an outline subtree, or a set of trees.
5981 Returns nil if kill does not start with a headline, or if the first
5982 headline level is not the largest headline level in the tree.
5983 So this will actually accept several entries of equal levels as well,
5984 which is OK for `org-paste-subtree'.
5985 If optional TXT is given, check this string instead of the current kill."
5986 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5987 (start-level (and kill
5988 (string-match (concat "\\`" org-outline-regexp) kill)
5989 (- (match-end 0) (match-beginning 0) 1)))
5990 (re (concat "^" org-outline-regexp))
5991 (start 1))
5992 (if (not start-level)
5993 (progn
5994 nil) ;; does not even start with a heading
5995 (catch 'exit
5996 (while (setq start (string-match re kill (1+ start)))
5997 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5998 (throw 'exit nil)))
5999 t))))
6001 (defun org-narrow-to-subtree ()
6002 "Narrow buffer to the current subtree."
6003 (interactive)
6004 (save-excursion
6005 (narrow-to-region
6006 (progn (org-back-to-heading) (point))
6007 (progn (org-end-of-subtree t t) (point)))))
6010 ;;; Outline Sorting
6012 (defun org-sort (with-case)
6013 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
6014 (interactive "P")
6015 (if (org-at-table-p)
6016 (org-call-with-arg 'org-table-sort-lines with-case)
6017 (org-call-with-arg 'org-sort-entries with-case)))
6019 (defun org-sort-entries (&optional with-case sorting-type)
6020 "Sort entries on a certain level of an outline tree.
6021 If there is an active region, the entries in the region are sorted.
6022 Else, if the cursor is before the first entry, sort the top-level items.
6023 Else, the children of the entry at point are sorted.
6025 Sorting can be alphabetically, numerically, and by date/time as given by
6026 the first time stamp in the entry. The command prompts for the sorting
6027 type unless it has been given to the function through the SORTING-TYPE
6028 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
6030 Comparing entries ignores case by default. However, with an optional argument
6031 WITH-CASE, the sorting considers case as well. With two prefix arguments
6032 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
6033 (interactive "P")
6034 (let ((unique (equal with-case '(16)))
6035 start beg end entries stars re re2 p nentries (nremoved 0)
6036 last txt what)
6037 ;; Find beginning and end of region to sort
6038 (cond
6039 ((org-region-active-p)
6040 ;; we will sort the region
6041 (setq end (region-end)
6042 what "region")
6043 (goto-char (region-beginning))
6044 (if (not (org-on-heading-p)) (outline-next-heading))
6045 (setq start (point)))
6046 ((or (org-on-heading-p)
6047 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6048 ;; we will sort the children of the current headline
6049 (org-back-to-heading)
6050 (setq start (point) end (org-end-of-subtree) what "children")
6051 (goto-char start)
6052 (show-subtree)
6053 (outline-next-heading))
6055 ;; we will sort the top-level entries in this file
6056 (goto-char (point-min))
6057 (or (org-on-heading-p) (outline-next-heading))
6058 (setq start (point) end (point-max) what "top-level")
6059 (goto-char start)
6060 (show-all)))
6061 (setq beg (point))
6062 (if (>= (point) end) (error "Nothing to sort"))
6063 (looking-at "\\(\\*+\\)")
6064 (setq stars (match-string 1)
6065 re (concat "^" (regexp-quote stars) " +")
6066 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6067 txt (buffer-substring beg end))
6068 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6069 (if (and (not (equal stars "*")) (string-match re2 txt))
6070 (error "Region to sort contains a level above the first entry"))
6071 ;; Make a list that can be sorted.
6072 ;; The car is the string for comparison, the cdr is the subtree
6073 (message "Sorting entries...")
6074 (setq entries
6075 (mapcar
6076 (lambda (x)
6077 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
6078 (cons (match-string 0 x) x))
6079 (org-split-string txt re)))
6081 ;; Sort the list
6082 (save-excursion
6083 (goto-char start)
6084 (setq entries (org-do-sort entries what with-case sorting-type)))
6086 ;; Delete the old stuff
6087 (goto-char beg)
6088 (kill-region beg end)
6089 (setq nentries (length entries))
6090 ;; Insert the sorted entries, and remove duplicates if this is required
6091 (while (setq p (pop entries))
6092 (if (and unique (equal last (setq last (org-trim (cdr p)))))
6093 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
6094 (insert stars " " (cdr p))))
6095 (goto-char start)
6096 (message "Sorting entries...done (%d entries%s)"
6097 nentries
6098 (if unique (format ", %d duplicates removed" nremoved) ""))))
6100 (defvar org-priority-regexp) ; defined later in the file
6102 (defun org-do-sort (table what &optional with-case sorting-type)
6103 "Sort TABLE of WHAT according to SORTING-TYPE.
6104 The user will be prompted for the SORTING-TYPE if the call to this
6105 function does not specify it. WHAT is only for the prompt, to indicate
6106 what is being sorted. The sorting key will be extracted from
6107 the car of the elements of the table.
6108 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6109 (unless sorting-type
6110 (message
6111 "Sort %s: [a]lphabetic. [n]umeric. [t]ime [p]riority. A/N/T/P means reversed:"
6112 what)
6113 (setq sorting-type (read-char-exclusive)))
6114 (let ((dcst (downcase sorting-type))
6115 extractfun comparefun)
6116 ;; Define the appropriate functions
6117 (cond
6118 ((= dcst ?n)
6119 (setq extractfun 'string-to-number
6120 comparefun (if (= dcst sorting-type) '< '>)))
6121 ((= dcst ?a)
6122 (setq extractfun (if with-case 'identity 'downcase)
6123 comparefun (if (= dcst sorting-type)
6124 'string<
6125 (lambda (a b) (and (not (string< a b))
6126 (not (string= a b)))))))
6127 ((= dcst ?t)
6128 (setq extractfun
6129 (lambda (x)
6130 (if (string-match org-ts-regexp x)
6131 (time-to-seconds
6132 (org-time-string-to-time (match-string 0 x)))
6134 comparefun (if (= dcst sorting-type) '< '>)))
6135 ((= dcst ?p)
6136 (setq extractfun
6137 (lambda (x)
6138 (if (string-match org-priority-regexp x)
6139 (string-to-char (match-string 2 x))
6140 org-default-priority))
6141 comparefun (if (= dcst sorting-type) '< '>)))
6142 (t (error "Invalid sorting type `%c'" sorting-type)))
6144 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6145 table)
6146 (lambda (a b) (funcall comparefun (car a) (car b))))))
6148 ;;;; Plain list items, including checkboxes
6150 ;;; Plain list items
6152 (defun org-at-item-p ()
6153 "Is point in a line starting a hand-formatted item?"
6154 (let ((llt org-plain-list-ordered-item-terminator))
6155 (save-excursion
6156 (goto-char (point-at-bol))
6157 (looking-at
6158 (cond
6159 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6160 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6161 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6162 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6164 (defun org-in-item-p ()
6165 "It the cursor inside a plain list item.
6166 Does not have to be the first line."
6167 (save-excursion
6168 (condition-case nil
6169 (progn
6170 (org-beginning-of-item)
6171 (org-at-item-p)
6173 (error nil))))
6175 (defun org-insert-item (&optional checkbox)
6176 "Insert a new item at the current level.
6177 Return t when things worked, nil when we are not in an item."
6178 (when (save-excursion
6179 (condition-case nil
6180 (progn
6181 (org-beginning-of-item)
6182 (org-at-item-p)
6183 (if (org-invisible-p) (error "Invisible item"))
6185 (error nil)))
6186 (let* ((bul (match-string 0))
6187 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6188 (match-end 0)))
6189 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6190 pos)
6191 (cond
6192 ((and (org-at-item-p) (<= (point) eow))
6193 ;; before the bullet
6194 (beginning-of-line 1)
6195 (open-line (if blank 2 1)))
6196 ((<= (point) eow)
6197 (beginning-of-line 1))
6198 (t (newline (if blank 2 1))))
6199 (insert bul (if checkbox "[ ]" ""))
6200 (just-one-space)
6201 (setq pos (point))
6202 (end-of-line 1)
6203 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6204 (org-maybe-renumber-ordered-list)
6205 (and checkbox (org-update-checkbox-count-maybe))
6208 ;;; Checkboxes
6210 (defun org-at-item-checkbox-p ()
6211 "Is point at a line starting a plain-list item with a checklet?"
6212 (and (org-at-item-p)
6213 (save-excursion
6214 (goto-char (match-end 0))
6215 (skip-chars-forward " \t")
6216 (looking-at "\\[[- X]\\]"))))
6218 (defun org-toggle-checkbox (&optional arg)
6219 "Toggle the checkbox in the current line."
6220 (interactive "P")
6221 (catch 'exit
6222 (let (beg end status (firstnew 'unknown))
6223 (cond
6224 ((org-region-active-p)
6225 (setq beg (region-beginning) end (region-end)))
6226 ((org-on-heading-p)
6227 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6228 ((org-at-item-checkbox-p)
6229 (save-excursion
6230 (replace-match
6231 (cond (arg "[-]")
6232 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6233 (t "[ ]"))
6234 t t))
6235 (throw 'exit t))
6236 (t (error "Not at a checkbox or heading, and no active region")))
6237 (save-excursion
6238 (goto-char beg)
6239 (while (< (point) end)
6240 (when (org-at-item-checkbox-p)
6241 (setq status (equal (match-string 0) "[X]"))
6242 (when (eq firstnew 'unknown)
6243 (setq firstnew (not status)))
6244 (replace-match
6245 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6246 (beginning-of-line 2)))))
6247 (org-update-checkbox-count-maybe))
6249 (defun org-update-checkbox-count-maybe ()
6250 "Update checkbox statistics unless turned off by user."
6251 (when org-provide-checkbox-statistics
6252 (org-update-checkbox-count)))
6254 (defun org-update-checkbox-count (&optional all)
6255 "Update the checkbox statistics in the current section.
6256 This will find all statistic cookies like [57%] and [6/12] and update them
6257 with the current numbers. With optional prefix argument ALL, do this for
6258 the whole buffer."
6259 (interactive "P")
6260 (save-excursion
6261 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6262 (beg (condition-case nil
6263 (progn (outline-back-to-heading) (point))
6264 (error (point-min))))
6265 (end (move-marker (make-marker)
6266 (progn (outline-next-heading) (point))))
6267 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6268 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6269 b1 e1 f1 c-on c-off lim (cstat 0))
6270 (when all
6271 (goto-char (point-min))
6272 (outline-next-heading)
6273 (setq beg (point) end (point-max)))
6274 (goto-char beg)
6275 (while (re-search-forward re end t)
6276 (setq cstat (1+ cstat)
6277 b1 (match-beginning 0)
6278 e1 (match-end 0)
6279 f1 (match-beginning 1)
6280 lim (cond
6281 ((org-on-heading-p) (outline-next-heading) (point))
6282 ((org-at-item-p) (org-end-of-item) (point))
6283 (t nil))
6284 c-on 0 c-off 0)
6285 (goto-char e1)
6286 (when lim
6287 (while (re-search-forward re-box lim t)
6288 (if (member (match-string 2) '("[ ]" "[-]"))
6289 (setq c-off (1+ c-off))
6290 (setq c-on (1+ c-on))))
6291 ; (delete-region b1 e1)
6292 (goto-char b1)
6293 (insert (if f1
6294 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6295 (format "[%d/%d]" c-on (+ c-on c-off))))
6296 (and (looking-at "\\[.*?\\]")
6297 (replace-match ""))))
6298 (when (interactive-p)
6299 (message "Checkbox satistics updated %s (%d places)"
6300 (if all "in entire file" "in current outline entry") cstat)))))
6302 (defun org-get-checkbox-statistics-face ()
6303 "Select the face for checkbox statistics.
6304 The face will be `org-done' when all relevant boxes are checked. Otherwise
6305 it will be `org-todo'."
6306 (if (match-end 1)
6307 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6308 (if (and (> (match-end 2) (match-beginning 2))
6309 (equal (match-string 2) (match-string 3)))
6310 'org-done
6311 'org-todo)))
6313 (defun org-get-indentation (&optional line)
6314 "Get the indentation of the current line, interpreting tabs.
6315 When LINE is given, assume it represents a line and compute its indentation."
6316 (if line
6317 (if (string-match "^ *" (org-remove-tabs line))
6318 (match-end 0))
6319 (save-excursion
6320 (beginning-of-line 1)
6321 (skip-chars-forward " \t")
6322 (current-column))))
6324 (defun org-remove-tabs (s &optional width)
6325 "Replace tabulators in S with spaces.
6326 Assumes that s is a single line, starting in column 0."
6327 (setq width (or width tab-width))
6328 (while (string-match "\t" s)
6329 (setq s (replace-match
6330 (make-string
6331 (- (* width (/ (+ (match-beginning 0) width) width))
6332 (match-beginning 0)) ?\ )
6333 t t s)))
6336 (defun org-fix-indentation (line ind)
6337 "Fix indentation in LINE.
6338 IND is a cons cell with target and minimum indentation.
6339 If the current indenation in LINE is smaller than the minimum,
6340 leave it alone. If it is larger than ind, set it to the target."
6341 (let* ((l (org-remove-tabs line))
6342 (i (org-get-indentation l))
6343 (i1 (car ind)) (i2 (cdr ind)))
6344 (if (>= i i2) (setq l (substring line i2)))
6345 (if (> i1 0)
6346 (concat (make-string i1 ?\ ) l)
6347 l)))
6349 (defcustom org-empty-line-terminates-plain-lists nil
6350 "Non-nil means, an empty line ends all plain list levels.
6351 When nil, empty lines are part of the preceeding item."
6352 :group 'org-plain-lists
6353 :type 'boolean)
6355 (defun org-beginning-of-item ()
6356 "Go to the beginning of the current hand-formatted item.
6357 If the cursor is not in an item, throw an error."
6358 (interactive)
6359 (let ((pos (point))
6360 (limit (save-excursion
6361 (condition-case nil
6362 (progn
6363 (org-back-to-heading)
6364 (beginning-of-line 2) (point))
6365 (error (point-min)))))
6366 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6367 ind ind1)
6368 (if (org-at-item-p)
6369 (beginning-of-line 1)
6370 (beginning-of-line 1)
6371 (skip-chars-forward " \t")
6372 (setq ind (current-column))
6373 (if (catch 'exit
6374 (while t
6375 (beginning-of-line 0)
6376 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6378 (if (looking-at "[ \t]*$")
6379 (setq ind1 ind-empty)
6380 (skip-chars-forward " \t")
6381 (setq ind1 (current-column)))
6382 (if (< ind1 ind)
6383 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6385 (goto-char pos)
6386 (error "Not in an item")))))
6388 (defun org-end-of-item ()
6389 "Go to the end of the current hand-formatted item.
6390 If the cursor is not in an item, throw an error."
6391 (interactive)
6392 (let* ((pos (point))
6393 ind1
6394 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6395 (limit (save-excursion (outline-next-heading) (point)))
6396 (ind (save-excursion
6397 (org-beginning-of-item)
6398 (skip-chars-forward " \t")
6399 (current-column)))
6400 (end (catch 'exit
6401 (while t
6402 (beginning-of-line 2)
6403 (if (eobp) (throw 'exit (point)))
6404 (if (>= (point) limit) (throw 'exit (point-at-bol)))
6405 (if (looking-at "[ \t]*$")
6406 (setq ind1 ind-empty)
6407 (skip-chars-forward " \t")
6408 (setq ind1 (current-column)))
6409 (if (<= ind1 ind)
6410 (throw 'exit (point-at-bol)))))))
6411 (if end
6412 (goto-char end)
6413 (goto-char pos)
6414 (error "Not in an item"))))
6416 (defun org-next-item ()
6417 "Move to the beginning of the next item in the current plain list.
6418 Error if not at a plain list, or if this is the last item in the list."
6419 (interactive)
6420 (let (ind ind1 (pos (point)))
6421 (org-beginning-of-item)
6422 (setq ind (org-get-indentation))
6423 (org-end-of-item)
6424 (setq ind1 (org-get-indentation))
6425 (unless (and (org-at-item-p) (= ind ind1))
6426 (goto-char pos)
6427 (error "On last item"))))
6429 (defun org-previous-item ()
6430 "Move to the beginning of the previous item in the current plain list.
6431 Error if not at a plain list, or if this is the first item in the list."
6432 (interactive)
6433 (let (beg ind ind1 (pos (point)))
6434 (org-beginning-of-item)
6435 (setq beg (point))
6436 (setq ind (org-get-indentation))
6437 (goto-char beg)
6438 (catch 'exit
6439 (while t
6440 (beginning-of-line 0)
6441 (if (looking-at "[ \t]*$")
6443 (if (<= (setq ind1 (org-get-indentation)) ind)
6444 (throw 'exit t)))))
6445 (condition-case nil
6446 (if (or (not (org-at-item-p))
6447 (< ind1 (1- ind)))
6448 (error "")
6449 (org-beginning-of-item))
6450 (error (goto-char pos)
6451 (error "On first item")))))
6453 (defun org-move-item-down ()
6454 "Move the plain list item at point down, i.e. swap with following item.
6455 Subitems (items with larger indentation) are considered part of the item,
6456 so this really moves item trees."
6457 (interactive)
6458 (let (beg end ind ind1 (pos (point)) txt)
6459 (org-beginning-of-item)
6460 (setq beg (point))
6461 (setq ind (org-get-indentation))
6462 (org-end-of-item)
6463 (setq end (point))
6464 (setq ind1 (org-get-indentation))
6465 (if (and (org-at-item-p) (= ind ind1))
6466 (progn
6467 (org-end-of-item)
6468 (setq txt (buffer-substring beg end))
6469 (save-excursion
6470 (delete-region beg end))
6471 (setq pos (point))
6472 (insert txt)
6473 (goto-char pos)
6474 (org-maybe-renumber-ordered-list))
6475 (goto-char pos)
6476 (error "Cannot move this item further down"))))
6478 (defun org-move-item-up (arg)
6479 "Move the plain list item at point up, i.e. swap with previous item.
6480 Subitems (items with larger indentation) are considered part of the item,
6481 so this really moves item trees."
6482 (interactive "p")
6483 (let (beg end ind ind1 (pos (point)) txt)
6484 (org-beginning-of-item)
6485 (setq beg (point))
6486 (setq ind (org-get-indentation))
6487 (org-end-of-item)
6488 (setq end (point))
6489 (goto-char beg)
6490 (catch 'exit
6491 (while t
6492 (beginning-of-line 0)
6493 (if (looking-at "[ \t]*$")
6494 (if org-empty-line-terminates-plain-lists
6495 (progn
6496 (goto-char pos)
6497 (error "Cannot move this item further up"))
6498 nil)
6499 (if (<= (setq ind1 (org-get-indentation)) ind)
6500 (throw 'exit t)))))
6501 (condition-case nil
6502 (org-beginning-of-item)
6503 (error (goto-char beg)
6504 (error "Cannot move this item further up")))
6505 (setq ind1 (org-get-indentation))
6506 (if (and (org-at-item-p) (= ind ind1))
6507 (progn
6508 (setq txt (buffer-substring beg end))
6509 (save-excursion
6510 (delete-region beg end))
6511 (setq pos (point))
6512 (insert txt)
6513 (goto-char pos)
6514 (org-maybe-renumber-ordered-list))
6515 (goto-char pos)
6516 (error "Cannot move this item further up"))))
6518 (defun org-maybe-renumber-ordered-list ()
6519 "Renumber the ordered list at point if setup allows it.
6520 This tests the user option `org-auto-renumber-ordered-lists' before
6521 doing the renumbering."
6522 (interactive)
6523 (when (and org-auto-renumber-ordered-lists
6524 (org-at-item-p))
6525 (if (match-beginning 3)
6526 (org-renumber-ordered-list 1)
6527 (org-fix-bullet-type))))
6529 (defun org-maybe-renumber-ordered-list-safe ()
6530 (condition-case nil
6531 (save-excursion
6532 (org-maybe-renumber-ordered-list))
6533 (error nil)))
6535 (defun org-cycle-list-bullet (&optional which)
6536 "Cycle through the different itemize/enumerate bullets.
6537 This cycle the entire list level through the sequence:
6539 `-' -> `+' -> `*' -> `1.' -> `1)'
6541 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6542 0 meand `-', 1 means `+' etc."
6543 (interactive "P")
6544 (org-preserve-lc
6545 (org-beginning-of-item-list)
6546 (org-at-item-p)
6547 (beginning-of-line 1)
6548 (let ((current (match-string 0)) new)
6549 (setq new (cond
6550 ((and which (nth (1- which) '("-" "+" "*" "1." "1)"))))
6551 ((string-match "-" current) "+")
6552 ((string-match "\\+" current)
6553 (if (looking-at "\\S-") "1." "*"))
6554 ((string-match "\\*" current) "1.")
6555 ((string-match "\\." current) "1)")
6556 ((string-match ")" current) "-")
6557 (t (error "This should not happen"))))
6558 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6559 (org-fix-bullet-type)
6560 (org-maybe-renumber-ordered-list))))
6562 (defun org-get-string-indentation (s)
6563 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6564 (let ((n -1) (i 0) (w tab-width) c)
6565 (catch 'exit
6566 (while (< (setq n (1+ n)) (length s))
6567 (setq c (aref s n))
6568 (cond ((= c ?\ ) (setq i (1+ i)))
6569 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6570 (t (throw 'exit t)))))
6573 (defun org-renumber-ordered-list (arg)
6574 "Renumber an ordered plain list.
6575 Cursor needs to be in the first line of an item, the line that starts
6576 with something like \"1.\" or \"2)\"."
6577 (interactive "p")
6578 (unless (and (org-at-item-p)
6579 (match-beginning 3))
6580 (error "This is not an ordered list"))
6581 (let ((line (org-current-line))
6582 (col (current-column))
6583 (ind (org-get-string-indentation
6584 (buffer-substring (point-at-bol) (match-beginning 3))))
6585 ;; (term (substring (match-string 3) -1))
6586 ind1 (n (1- arg))
6587 fmt)
6588 ;; find where this list begins
6589 (org-beginning-of-item-list)
6590 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6591 (setq fmt (concat "%d" (match-string 1)))
6592 (beginning-of-line 0)
6593 ;; walk forward and replace these numbers
6594 (catch 'exit
6595 (while t
6596 (catch 'next
6597 (beginning-of-line 2)
6598 (if (eobp) (throw 'exit nil))
6599 (if (looking-at "[ \t]*$") (throw 'next nil))
6600 (skip-chars-forward " \t") (setq ind1 (current-column))
6601 (if (> ind1 ind) (throw 'next t))
6602 (if (< ind1 ind) (throw 'exit t))
6603 (if (not (org-at-item-p)) (throw 'exit nil))
6604 (delete-region (match-beginning 2) (match-end 2))
6605 (goto-char (match-beginning 2))
6606 (insert (format fmt (setq n (1+ n)))))))
6607 (goto-line line)
6608 (move-to-column col)))
6610 (defun org-fix-bullet-type ()
6611 "Make sure all items in this list have the same bullet as the firsst item."
6612 (interactive)
6613 (unless (org-at-item-p) (error "This is not a list"))
6614 (let ((line (org-current-line))
6615 (col (current-column))
6616 (ind (current-indentation))
6617 ind1 bullet)
6618 ;; find where this list begins
6619 (org-beginning-of-item-list)
6620 (beginning-of-line 1)
6621 ;; find out what the bullet type is
6622 (looking-at "[ \t]*\\(\\S-+\\)")
6623 (setq bullet (match-string 1))
6624 ;; walk forward and replace these numbers
6625 (beginning-of-line 0)
6626 (catch 'exit
6627 (while t
6628 (catch 'next
6629 (beginning-of-line 2)
6630 (if (eobp) (throw 'exit nil))
6631 (if (looking-at "[ \t]*$") (throw 'next nil))
6632 (skip-chars-forward " \t") (setq ind1 (current-column))
6633 (if (> ind1 ind) (throw 'next t))
6634 (if (< ind1 ind) (throw 'exit t))
6635 (if (not (org-at-item-p)) (throw 'exit nil))
6636 (skip-chars-forward " \t")
6637 (looking-at "\\S-+")
6638 (replace-match bullet))))
6639 (goto-line line)
6640 (move-to-column col)
6641 (if (string-match "[0-9]" bullet)
6642 (org-renumber-ordered-list 1))))
6644 (defun org-beginning-of-item-list ()
6645 "Go to the beginning of the current item list.
6646 I.e. to the first item in this list."
6647 (interactive)
6648 (org-beginning-of-item)
6649 (let ((pos (point-at-bol))
6650 (ind (org-get-indentation))
6651 ind1)
6652 ;; find where this list begins
6653 (catch 'exit
6654 (while t
6655 (catch 'next
6656 (beginning-of-line 0)
6657 (if (looking-at "[ \t]*$")
6658 (throw (if (bobp) 'exit 'next) t))
6659 (skip-chars-forward " \t") (setq ind1 (current-column))
6660 (if (or (< ind1 ind)
6661 (and (= ind1 ind)
6662 (not (org-at-item-p)))
6663 (bobp))
6664 (throw 'exit t)
6665 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6666 (goto-char pos)))
6668 (defvar org-last-indent-begin-marker (make-marker))
6669 (defvar org-last-indent-end-marker (make-marker))
6671 (defun org-outdent-item (arg)
6672 "Outdent a local list item."
6673 (interactive "p")
6674 (org-indent-item (- arg)))
6676 (defun org-indent-item (arg)
6677 "Indent a local list item."
6678 (interactive "p")
6679 (unless (org-at-item-p)
6680 (error "Not on an item"))
6681 (save-excursion
6682 (let (beg end ind ind1 tmp delta ind-down ind-up)
6683 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6684 (setq beg org-last-indent-begin-marker
6685 end org-last-indent-end-marker)
6686 (org-beginning-of-item)
6687 (setq beg (move-marker org-last-indent-begin-marker (point)))
6688 (org-end-of-item)
6689 (setq end (move-marker org-last-indent-end-marker (point))))
6690 (goto-char beg)
6691 (setq tmp (org-item-indent-positions)
6692 ind (car tmp)
6693 ind-down (nth 2 tmp)
6694 ind-up (nth 1 tmp)
6695 delta (if (> arg 0)
6696 (if ind-down (- ind-down ind) 2)
6697 (if ind-up (- ind-up ind) -2)))
6698 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6699 (while (< (point) end)
6700 (beginning-of-line 1)
6701 (skip-chars-forward " \t") (setq ind1 (current-column))
6702 (delete-region (point-at-bol) (point))
6703 (or (eolp) (indent-to-column (+ ind1 delta)))
6704 (beginning-of-line 2))))
6705 (org-fix-bullet-type)
6706 (org-maybe-renumber-ordered-list-safe)
6707 (save-excursion
6708 (beginning-of-line 0)
6709 (condition-case nil (org-beginning-of-item) (error nil))
6710 (org-maybe-renumber-ordered-list-safe)))
6712 (defun org-item-indent-positions ()
6713 "Return indentation for plain list items.
6714 This returns a list with three values: The current indentation, the
6715 parent indentation and the indentation a child should habe.
6716 Assumes cursor in item line."
6717 (let* ((bolpos (point-at-bol))
6718 (ind (org-get-indentation))
6719 ind-down ind-up pos)
6720 (save-excursion
6721 (org-beginning-of-item-list)
6722 (skip-chars-backward "\n\r \t")
6723 (when (org-in-item-p)
6724 (org-beginning-of-item)
6725 (setq ind-up (org-get-indentation))))
6726 (setq pos (point))
6727 (save-excursion
6728 (cond
6729 ((and (condition-case nil (progn (org-previous-item) t)
6730 (error nil))
6731 (or (forward-char 1) t)
6732 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6733 (setq ind-down (org-get-indentation)))
6734 ((and (goto-char pos)
6735 (org-at-item-p))
6736 (goto-char (match-end 0))
6737 (skip-chars-forward " \t")
6738 (setq ind-down (current-column)))))
6739 (list ind ind-up ind-down)))
6741 ;;; The orgstruct minor mode
6743 ;; Define a minor mode which can be used in other modes in order to
6744 ;; integrate the org-mode structure editing commands.
6746 ;; This is really a hack, because the org-mode structure commands use
6747 ;; keys which normally belong to the major mode. Here is how it
6748 ;; works: The minor mode defines all the keys necessary to operate the
6749 ;; structure commands, but wraps the commands into a function which
6750 ;; tests if the cursor is currently at a headline or a plain list
6751 ;; item. If that is the case, the structure command is used,
6752 ;; temporarily setting many Org-mode variables like regular
6753 ;; expressions for filling etc. However, when any of those keys is
6754 ;; used at a different location, function uses `key-binding' to look
6755 ;; up if the key has an associated command in another currently active
6756 ;; keymap (minor modes, major mode, global), and executes that
6757 ;; command. There might be problems if any of the keys is otherwise
6758 ;; used as a prefix key.
6760 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6761 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6762 ;; addresses this by checking explicitly for both bindings.
6764 (defvar orgstruct-mode-map (make-sparse-keymap)
6765 "Keymap for the minor `orgstruct-mode'.")
6767 (defvar org-local-vars nil
6768 "List of local variables, for use by `orgstruct-mode'")
6770 ;;;###autoload
6771 (define-minor-mode orgstruct-mode
6772 "Toggle the minor more `orgstruct-mode'.
6773 This mode is for using Org-mode structure commands in other modes.
6774 The following key behave as if Org-mode was active, if the cursor
6775 is on a headline, or on a plain list item (both in the definition
6776 of Org-mode).
6778 M-up Move entry/item up
6779 M-down Move entry/item down
6780 M-left Promote
6781 M-right Demote
6782 M-S-up Move entry/item up
6783 M-S-down Move entry/item down
6784 M-S-left Promote subtree
6785 M-S-right Demote subtree
6786 M-q Fill paragraph and items like in Org-mode
6787 C-c ^ Sort entries
6788 C-c - Cycle list bullet
6789 TAB Cycle item visibility
6790 M-RET Insert new heading/item
6791 S-M-RET Insert new TODO heading / Chekbox item
6792 C-c C-c Set tags / toggle checkbox"
6793 nil " OrgStruct" nil
6794 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6796 ;;;###autoload
6797 (defun turn-on-orgstruct ()
6798 "Unconditionally turn on `orgstruct-mode'."
6799 (orgstruct-mode 1))
6801 ;;;###autoload
6802 (defun turn-on-orgstruct++ ()
6803 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6804 In addition to setting orgstruct-mode, this also exports all indentation and
6805 autofilling variables from org-mode into the buffer. Note that turning
6806 off orgstruct-mode will *not* remove these additonal settings."
6807 (orgstruct-mode 1)
6808 (let (var val)
6809 (mapc
6810 (lambda (x)
6811 (when (string-match
6812 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6813 (symbol-name (car x)))
6814 (setq var (car x) val (nth 1 x))
6815 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6816 org-local-vars)))
6818 (defun orgstruct-error ()
6819 "Error when there is no default binding for a structure key."
6820 (interactive)
6821 (error "This key is has no function outside structure elements"))
6823 (defun orgstruct-setup ()
6824 "Setup orgstruct keymaps."
6825 (let ((nfunc 0)
6826 (bindings
6827 (list
6828 '([(meta up)] org-metaup)
6829 '([(meta down)] org-metadown)
6830 '([(meta left)] org-metaleft)
6831 '([(meta right)] org-metaright)
6832 '([(meta shift up)] org-shiftmetaup)
6833 '([(meta shift down)] org-shiftmetadown)
6834 '([(meta shift left)] org-shiftmetaleft)
6835 '([(meta shift right)] org-shiftmetaright)
6836 '([(shift up)] org-shiftup)
6837 '([(shift down)] org-shiftdown)
6838 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6839 '("\M-q" fill-paragraph)
6840 '("\C-c^" org-sort)
6841 '("\C-c-" org-cycle-list-bullet)))
6842 elt key fun cmd)
6843 (while (setq elt (pop bindings))
6844 (setq nfunc (1+ nfunc))
6845 (setq key (org-key (car elt))
6846 fun (nth 1 elt)
6847 cmd (orgstruct-make-binding fun nfunc key))
6848 (org-defkey orgstruct-mode-map key cmd))
6850 ;; Special treatment needed for TAB and RET
6851 (org-defkey orgstruct-mode-map [(tab)]
6852 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6853 (org-defkey orgstruct-mode-map "\C-i"
6854 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6856 (org-defkey orgstruct-mode-map "\M-\C-m"
6857 (orgstruct-make-binding 'org-insert-heading 105
6858 "\M-\C-m" [(meta return)]))
6859 (org-defkey orgstruct-mode-map [(meta return)]
6860 (orgstruct-make-binding 'org-insert-heading 106
6861 [(meta return)] "\M-\C-m"))
6863 (org-defkey orgstruct-mode-map [(shift meta return)]
6864 (orgstruct-make-binding 'org-insert-todo-heading 107
6865 [(meta return)] "\M-\C-m"))
6867 (unless org-local-vars
6868 (setq org-local-vars (org-get-local-variables)))
6872 (defun orgstruct-make-binding (fun n &rest keys)
6873 "Create a function for binding in the structure minor mode.
6874 FUN is the command to call inside a table. N is used to create a unique
6875 command name. KEYS are keys that should be checked in for a command
6876 to execute outside of tables."
6877 (eval
6878 (list 'defun
6879 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6880 '(arg)
6881 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6882 "Outside of structure, run the binding of `"
6883 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6884 "'.")
6885 '(interactive "p")
6886 (list 'if
6887 '(org-context-p 'headline 'item)
6888 (list 'org-run-like-in-org-mode (list 'quote fun))
6889 (list 'let '(orgstruct-mode)
6890 (list 'call-interactively
6891 (append '(or)
6892 (mapcar (lambda (k)
6893 (list 'key-binding k))
6894 keys)
6895 '('orgstruct-error))))))))
6897 (defun org-context-p (&rest contexts)
6898 "Check if local context is and of CONTEXTS.
6899 Possible values in the list of contexts are `table', `headline', and `item'."
6900 (let ((pos (point)))
6901 (goto-char (point-at-bol))
6902 (prog1 (or (and (memq 'table contexts)
6903 (looking-at "[ \t]*|"))
6904 (and (memq 'headline contexts)
6905 (looking-at "\\*+"))
6906 (and (memq 'item contexts)
6907 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6908 (goto-char pos))))
6910 (defun org-get-local-variables ()
6911 "Return a list of all local variables in an org-mode buffer."
6912 (let (varlist)
6913 (with-current-buffer (get-buffer-create "*Org tmp*")
6914 (erase-buffer)
6915 (org-mode)
6916 (setq varlist (buffer-local-variables)))
6917 (kill-buffer "*Org tmp*")
6918 (delq nil
6919 (mapcar
6920 (lambda (x)
6921 (setq x
6922 (if (symbolp x)
6923 (list x)
6924 (list (car x) (list 'quote (cdr x)))))
6925 (if (string-match
6926 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6927 (symbol-name (car x)))
6928 x nil))
6929 varlist))))
6931 ;;;###autoload
6932 (defun org-run-like-in-org-mode (cmd)
6933 (unless org-local-vars
6934 (setq org-local-vars (org-get-local-variables)))
6935 (eval (list 'let org-local-vars
6936 (list 'call-interactively (list 'quote cmd)))))
6938 ;;;; Archiving
6940 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
6942 (defun org-archive-subtree (&optional find-done)
6943 "Move the current subtree to the archive.
6944 The archive can be a certain top-level heading in the current file, or in
6945 a different file. The tree will be moved to that location, the subtree
6946 heading be marked DONE, and the current time will be added.
6948 When called with prefix argument FIND-DONE, find whole trees without any
6949 open TODO items and archive them (after getting confirmation from the user).
6950 If the cursor is not at a headline when this comand is called, try all level
6951 1 trees. If the cursor is on a headline, only try the direct children of
6952 this heading."
6953 (interactive "P")
6954 (if find-done
6955 (org-archive-all-done)
6956 ;; Save all relevant TODO keyword-relatex variables
6958 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
6959 (tr-org-todo-keywords-1 org-todo-keywords-1)
6960 (tr-org-todo-kwd-alist org-todo-kwd-alist)
6961 (tr-org-done-keywords org-done-keywords)
6962 (tr-org-todo-regexp org-todo-regexp)
6963 (tr-org-todo-line-regexp org-todo-line-regexp)
6964 (tr-org-odd-levels-only org-odd-levels-only)
6965 (this-buffer (current-buffer))
6966 (org-archive-location org-archive-location)
6967 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
6968 (file (abbreviate-file-name (buffer-file-name)))
6969 (time (format-time-string
6970 (substring (cdr org-time-stamp-formats) 1 -1)
6971 (current-time)))
6972 afile heading buffer level newfile-p
6973 category todo priority ltags itags prop)
6975 ;; Try to find a local archive location
6976 (save-excursion
6977 (save-restriction
6978 (widen)
6979 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
6980 (if (and prop (string-match "\\S-" prop))
6981 (setq org-archive-location prop)
6982 (if (or (re-search-backward re nil t)
6983 (re-search-forward re nil t))
6984 (setq org-archive-location (match-string 1))))))
6986 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
6987 (progn
6988 (setq afile (format (match-string 1 org-archive-location)
6989 (file-name-nondirectory buffer-file-name))
6990 heading (match-string 2 org-archive-location)))
6991 (error "Invalid `org-archive-location'"))
6992 (if (> (length afile) 0)
6993 (setq newfile-p (not (file-exists-p afile))
6994 buffer (find-file-noselect afile))
6995 (setq buffer (current-buffer)))
6996 (unless buffer
6997 (error "Cannot access file \"%s\"" afile))
6998 (if (and (> (length heading) 0)
6999 (string-match "^\\*+" heading))
7000 (setq level (match-end 0))
7001 (setq heading nil level 0))
7002 (save-excursion
7003 (org-back-to-heading t)
7004 ;; Get context information that will be lost by moving the tree
7005 (org-refresh-category-properties)
7006 (setq category (org-get-category)
7007 todo (and (looking-at org-todo-line-regexp)
7008 (match-string 2))
7009 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7010 ltags (org-get-tags)
7011 itags (org-delete-all ltags (org-get-tags-at)))
7012 (setq ltags (mapconcat 'identity ltags " ")
7013 itags (mapconcat 'identity itags " "))
7014 ;; We first only copy, in case something goes wrong
7015 ;; we need to protect this-command, to avoid kill-region sets it,
7016 ;; which would lead to duplication of subtrees
7017 (let (this-command) (org-copy-subtree))
7018 (set-buffer buffer)
7019 ;; Enforce org-mode for the archive buffer
7020 (if (not (org-mode-p))
7021 ;; Force the mode for future visits.
7022 (let ((org-insert-mode-line-in-empty-file t)
7023 (org-inhibit-startup t))
7024 (call-interactively 'org-mode)))
7025 (when newfile-p
7026 (goto-char (point-max))
7027 (insert (format "\nArchived entries from file %s\n\n"
7028 (buffer-file-name this-buffer))))
7029 ;; Force the TODO keywords of the original buffer
7030 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7031 (org-todo-keywords-1 tr-org-todo-keywords-1)
7032 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7033 (org-done-keywords tr-org-done-keywords)
7034 (org-todo-regexp tr-org-todo-regexp)
7035 (org-todo-line-regexp tr-org-todo-line-regexp)
7036 (org-odd-levels-only
7037 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7038 org-odd-levels-only
7039 tr-org-odd-levels-only)))
7040 (goto-char (point-min))
7041 (if heading
7042 (progn
7043 (if (re-search-forward
7044 (concat "^" (regexp-quote heading)
7045 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7046 nil t)
7047 (goto-char (match-end 0))
7048 ;; Heading not found, just insert it at the end
7049 (goto-char (point-max))
7050 (or (bolp) (insert "\n"))
7051 (insert "\n" heading "\n")
7052 (end-of-line 0))
7053 ;; Make the subtree visible
7054 (show-subtree)
7055 (org-end-of-subtree t)
7056 (skip-chars-backward " \t\r\n")
7057 (and (looking-at "[ \t\r\n]*")
7058 (replace-match "\n\n")))
7059 ;; No specific heading, just go to end of file.
7060 (goto-char (point-max)) (insert "\n"))
7061 ;; Paste
7062 (org-paste-subtree (org-get-legal-level level 1))
7064 ;; Mark the entry as done
7065 (when (and org-archive-mark-done
7066 (looking-at org-todo-line-regexp)
7067 (or (not (match-end 2))
7068 (not (member (match-string 2) org-done-keywords))))
7069 (let (org-log-done)
7070 (org-todo
7071 (car (or (member org-archive-mark-done org-done-keywords)
7072 org-done-keywords)))))
7074 ;; Add the context info
7075 (when org-archive-save-context-info
7076 (let ((l org-archive-save-context-info) e n v)
7077 (while (setq e (pop l))
7078 (when (and (setq v (symbol-value e))
7079 (stringp v) (string-match "\\S-" v))
7080 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7081 (org-entry-put (point) n v)))))
7083 ;; Save the buffer, if it is not the same buffer.
7084 (if (not (eq this-buffer buffer)) (save-buffer))))
7085 ;; Here we are back in the original buffer. Everything seems to have
7086 ;; worked. So now cut the tree and finish up.
7087 (let (this-command) (org-cut-subtree))
7088 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7089 (message "Subtree archived %s"
7090 (if (eq this-buffer buffer)
7091 (concat "under heading: " heading)
7092 (concat "in file: " (abbreviate-file-name afile)))))))
7094 (defun org-refresh-category-properties ()
7095 "Refresh category text properties in teh buffer."
7096 (let ((def-cat (cond
7097 ((null org-category)
7098 (if buffer-file-name
7099 (file-name-sans-extension
7100 (file-name-nondirectory buffer-file-name))
7101 "???"))
7102 ((symbolp org-category) (symbol-name org-category))
7103 (t org-category)))
7104 beg end cat pos optionp)
7105 (org-unmodified
7106 (save-excursion
7107 (save-restriction
7108 (widen)
7109 (goto-char (point-min))
7110 (put-text-property (point) (point-max) 'org-category def-cat)
7111 (while (re-search-forward
7112 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7113 (setq pos (match-end 0)
7114 optionp (equal (char-after (match-beginning 0)) ?#)
7115 cat (org-trim (match-string 2)))
7116 (if optionp
7117 (setq beg (point-at-bol) end (point-max))
7118 (org-back-to-heading t)
7119 (setq beg (point) end (org-end-of-subtree t t)))
7120 (put-text-property beg end 'org-category cat)
7121 (goto-char pos)))))))
7123 (defun org-archive-all-done (&optional tag)
7124 "Archive sublevels of the current tree without open TODO items.
7125 If the cursor is not on a headline, try all level 1 trees. If
7126 it is on a headline, try all direct children.
7127 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7128 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7129 (rea (concat ".*:" org-archive-tag ":"))
7130 (begm (make-marker))
7131 (endm (make-marker))
7132 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7133 "Move subtree to archive (no open TODO items)? "))
7134 beg end (cntarch 0))
7135 (if (org-on-heading-p)
7136 (progn
7137 (setq re1 (concat "^" (regexp-quote
7138 (make-string
7139 (1+ (- (match-end 0) (match-beginning 0)))
7140 ?*))
7141 " "))
7142 (move-marker begm (point))
7143 (move-marker endm (org-end-of-subtree t)))
7144 (setq re1 "^* ")
7145 (move-marker begm (point-min))
7146 (move-marker endm (point-max)))
7147 (save-excursion
7148 (goto-char begm)
7149 (while (re-search-forward re1 endm t)
7150 (setq beg (match-beginning 0)
7151 end (save-excursion (org-end-of-subtree t) (point)))
7152 (goto-char beg)
7153 (if (re-search-forward re end t)
7154 (goto-char end)
7155 (goto-char beg)
7156 (if (and (or (not tag) (not (looking-at rea)))
7157 (y-or-n-p question))
7158 (progn
7159 (if tag
7160 (org-toggle-tag org-archive-tag 'on)
7161 (org-archive-subtree))
7162 (setq cntarch (1+ cntarch)))
7163 (goto-char end)))))
7164 (message "%d trees archived" cntarch)))
7166 (defun org-cycle-hide-drawers (state)
7167 "Re-hide all drawers after a visibility state change."
7168 (when (and (org-mode-p)
7169 (not (memq state '(overview folded))))
7170 (save-excursion
7171 (let* ((globalp (memq state '(contents all)))
7172 (beg (if globalp (point-min) (point)))
7173 (end (if globalp (point-max) (org-end-of-subtree t))))
7174 (goto-char beg)
7175 (while (re-search-forward org-drawer-regexp end t)
7176 (org-flag-drawer t))))))
7178 (defun org-flag-drawer (flag)
7179 (save-excursion
7180 (beginning-of-line 1)
7181 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7182 (let ((b (match-end 0)))
7183 (if (re-search-forward
7184 "^[ \t]*:END:"
7185 (save-excursion (outline-next-heading) (point)) t)
7186 (outline-flag-region b (point-at-eol) flag)
7187 (error ":END: line missing"))))))
7189 (defun org-cycle-hide-archived-subtrees (state)
7190 "Re-hide all archived subtrees after a visibility state change."
7191 (when (and (not org-cycle-open-archived-trees)
7192 (not (memq state '(overview folded))))
7193 (save-excursion
7194 (let* ((globalp (memq state '(contents all)))
7195 (beg (if globalp (point-min) (point)))
7196 (end (if globalp (point-max) (org-end-of-subtree t))))
7197 (org-hide-archived-subtrees beg end)
7198 (goto-char beg)
7199 (if (looking-at (concat ".*:" org-archive-tag ":"))
7200 (message (substitute-command-keys
7201 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7203 (defun org-force-cycle-archived ()
7204 "Cycle subtree even if it is archived."
7205 (interactive)
7206 (setq this-command 'org-cycle)
7207 (let ((org-cycle-open-archived-trees t))
7208 (call-interactively 'org-cycle)))
7210 (defun org-hide-archived-subtrees (beg end)
7211 "Re-hide all archived subtrees after a visibility state change."
7212 (save-excursion
7213 (let* ((re (concat ":" org-archive-tag ":")))
7214 (goto-char beg)
7215 (while (re-search-forward re end t)
7216 (and (org-on-heading-p) (hide-subtree))
7217 (org-end-of-subtree t)))))
7219 (defun org-toggle-tag (tag &optional onoff)
7220 "Toggle the tag TAG for the current line.
7221 If ONOFF is `on' or `off', don't toggle but set to this state."
7222 (unless (org-on-heading-p t) (error "Not on headling"))
7223 (let (res current)
7224 (save-excursion
7225 (beginning-of-line)
7226 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7227 (point-at-eol) t)
7228 (progn
7229 (setq current (match-string 1))
7230 (replace-match ""))
7231 (setq current ""))
7232 (setq current (nreverse (org-split-string current ":")))
7233 (cond
7234 ((eq onoff 'on)
7235 (setq res t)
7236 (or (member tag current) (push tag current)))
7237 ((eq onoff 'off)
7238 (or (not (member tag current)) (setq current (delete tag current))))
7239 (t (if (member tag current)
7240 (setq current (delete tag current))
7241 (setq res t)
7242 (push tag current))))
7243 (end-of-line 1)
7244 (when current
7245 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
7246 (org-set-tags nil t)
7247 res)
7248 (run-hooks 'org-after-tags-change-hook)))
7250 (defun org-toggle-archive-tag (&optional arg)
7251 "Toggle the archive tag for the current headline.
7252 With prefix ARG, check all children of current headline and offer tagging
7253 the children that do not contain any open TODO items."
7254 (interactive "P")
7255 (if arg
7256 (org-archive-all-done 'tag)
7257 (let (set)
7258 (save-excursion
7259 (org-back-to-heading t)
7260 (setq set (org-toggle-tag org-archive-tag))
7261 (when set (hide-subtree)))
7262 (and set (beginning-of-line 1))
7263 (message "Subtree %s" (if set "archived" "unarchived")))))
7266 ;;;; Tables
7268 ;;; The table editor
7270 ;; Watch out: Here we are talking about two different kind of tables.
7271 ;; Most of the code is for the tables created with the Org-mode table editor.
7272 ;; Sometimes, we talk about tables created and edited with the table.el
7273 ;; Emacs package. We call the former org-type tables, and the latter
7274 ;; table.el-type tables.
7276 (defun org-before-change-function (beg end)
7277 "Every change indicates that a table might need an update."
7278 (setq org-table-may-need-update t))
7280 (defconst org-table-line-regexp "^[ \t]*|"
7281 "Detects an org-type table line.")
7282 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7283 "Detects an org-type table line.")
7284 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7285 "Detects a table line marked for automatic recalculation.")
7286 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7287 "Detects a table line marked for automatic recalculation.")
7288 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7289 "Detects a table line marked for automatic recalculation.")
7290 (defconst org-table-hline-regexp "^[ \t]*|-"
7291 "Detects an org-type table hline.")
7292 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7293 "Detects a table-type table hline.")
7294 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7295 "Detects an org-type or table-type table.")
7296 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7297 "Searching from within a table (any type) this finds the first line
7298 outside the table.")
7299 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7300 "Searching from within a table (any type) this finds the first line
7301 outside the table.")
7303 (defvar org-table-last-highlighted-reference nil)
7304 (defvar org-table-formula-history nil)
7306 (defvar org-table-column-names nil
7307 "Alist with column names, derived from the `!' line.")
7308 (defvar org-table-column-name-regexp nil
7309 "Regular expression matching the current column names.")
7310 (defvar org-table-local-parameters nil
7311 "Alist with parameter names, derived from the `$' line.")
7312 (defvar org-table-named-field-locations nil
7313 "Alist with locations of named fields.")
7315 (defvar org-table-current-line-types nil
7316 "Table row types, non-nil only for the duration of a comand.")
7317 (defvar org-table-current-begin-line nil
7318 "Table begin line, non-nil only for the duration of a comand.")
7319 (defvar org-table-current-begin-pos nil
7320 "Table begin position, non-nil only for the duration of a comand.")
7321 (defvar org-table-dlines nil
7322 "Vector of data line line numbers in the current table.")
7323 (defvar org-table-hlines nil
7324 "Vector of hline line numbers in the current table.")
7326 (defconst org-table-range-regexp
7327 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
7328 ;; 1 2 3 4 5
7329 "Regular expression for matching ranges in formulas.")
7331 (defconst org-table-range-regexp2
7332 (concat
7333 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
7334 "\\.\\."
7335 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
7336 "Match a range for reference display.")
7338 (defconst org-table-translate-regexp
7339 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
7340 "Match a reference that needs translation, for reference display.")
7342 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
7344 (defun org-table-create-with-table.el ()
7345 "Use the table.el package to insert a new table.
7346 If there is already a table at point, convert between Org-mode tables
7347 and table.el tables."
7348 (interactive)
7349 (require 'table)
7350 (cond
7351 ((org-at-table.el-p)
7352 (if (y-or-n-p "Convert table to Org-mode table? ")
7353 (org-table-convert)))
7354 ((org-at-table-p)
7355 (if (y-or-n-p "Convert table to table.el table? ")
7356 (org-table-convert)))
7357 (t (call-interactively 'table-insert))))
7359 (defun org-table-create-or-convert-from-region (arg)
7360 "Convert region to table, or create an empty table.
7361 If there is an active region, convert it to a table, using the function
7362 `org-table-convert-region'. See the documentation of that function
7363 to learn how the prefix argument is interpreted to determine the field
7364 separator.
7365 If there is no such region, create an empty table with `org-table-create'."
7366 (interactive "P")
7367 (if (org-region-active-p)
7368 (org-table-convert-region (region-beginning) (region-end) arg)
7369 (org-table-create arg)))
7371 (defun org-table-create (&optional size)
7372 "Query for a size and insert a table skeleton.
7373 SIZE is a string Columns x Rows like for example \"3x2\"."
7374 (interactive "P")
7375 (unless size
7376 (setq size (read-string
7377 (concat "Table size Columns x Rows [e.g. "
7378 org-table-default-size "]: ")
7379 "" nil org-table-default-size)))
7381 (let* ((pos (point))
7382 (indent (make-string (current-column) ?\ ))
7383 (split (org-split-string size " *x *"))
7384 (rows (string-to-number (nth 1 split)))
7385 (columns (string-to-number (car split)))
7386 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7387 "\n")))
7388 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7389 (point-at-bol) (point)))
7390 (beginning-of-line 1)
7391 (newline))
7392 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7393 (dotimes (i rows) (insert line))
7394 (goto-char pos)
7395 (if (> rows 1)
7396 ;; Insert a hline after the first row.
7397 (progn
7398 (end-of-line 1)
7399 (insert "\n|-")
7400 (goto-char pos)))
7401 (org-table-align)))
7403 (defun org-table-convert-region (beg0 end0 &optional separator)
7404 "Convert region to a table.
7405 The region goes from BEG0 to END0, but these borders will be moved
7406 slightly, to make sure a beginning of line in the first line is included.
7408 SEPARATOR specifies the field separator in the lines. It can have the
7409 following values:
7411 '(4) Use the comma as a field separator
7412 '(16) Use a TAB as field separator
7413 integer When a number, use that many spaces as field separator
7414 nil When nil, the command tries to be smart and figure out the
7415 separator in the following way:
7416 - when each line contains a TAB, assume TAB-separated material
7417 - when each line contains a comme, assume CSV material
7418 - else, assume one or more SPACE charcters as separator."
7419 (interactive "rP")
7420 (let* ((beg (min beg0 end0))
7421 (end (max beg0 end0))
7422 sep-re re)
7423 (goto-char beg)
7424 (beginning-of-line 1)
7425 (setq beg (move-marker (make-marker) (point)))
7426 (goto-char end)
7427 (if (bolp) (backward-char 1) (end-of-line 1))
7428 (setq end (move-marker (make-marker) (point)))
7429 ;; Get the right field separator
7430 (unless separator
7431 (goto-char beg)
7432 (setq separator
7433 (cond
7434 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
7435 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
7436 (t 1))))
7437 (setq re (cond
7438 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
7439 ((equal separator '(16)) "^\\|\t")
7440 ((integerp separator)
7441 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
7442 (t (error "This should not happen"))))
7443 (goto-char beg)
7444 (while (re-search-forward re end t)
7445 (replace-match "| " t t))
7446 (goto-char beg)
7447 (insert " ")
7448 (org-table-align)))
7450 (defun org-table-import (file arg)
7451 "Import FILE as a table.
7452 The file is assumed to be tab-separated. Such files can be produced by most
7453 spreadsheet and database applications. If no tabs (at least one per line)
7454 are found, lines will be split on whitespace into fields."
7455 (interactive "f\nP")
7456 (or (bolp) (newline))
7457 (let ((beg (point))
7458 (pm (point-max)))
7459 (insert-file-contents file)
7460 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7462 (defun org-table-export ()
7463 "Export table as a tab-separated file.
7464 Such a file can be imported into a spreadsheet program like Excel."
7465 (interactive)
7466 (let* ((beg (org-table-begin))
7467 (end (org-table-end))
7468 (table (buffer-substring beg end))
7469 (file (read-file-name "Export table to: "))
7470 buf)
7471 (unless (or (not (file-exists-p file))
7472 (y-or-n-p (format "Overwrite file %s? " file)))
7473 (error "Abort"))
7474 (with-current-buffer (find-file-noselect file)
7475 (setq buf (current-buffer))
7476 (erase-buffer)
7477 (fundamental-mode)
7478 (insert table)
7479 (goto-char (point-min))
7480 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7481 (replace-match "" t t)
7482 (end-of-line 1))
7483 (goto-char (point-min))
7484 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7485 (replace-match "" t t)
7486 (goto-char (min (1+ (point)) (point-max))))
7487 (goto-char (point-min))
7488 (while (re-search-forward "^-[-+]*$" nil t)
7489 (replace-match "")
7490 (if (looking-at "\n")
7491 (delete-char 1)))
7492 (goto-char (point-min))
7493 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7494 (replace-match "\t" t t))
7495 (save-buffer))
7496 (kill-buffer buf)))
7498 (defvar org-table-aligned-begin-marker (make-marker)
7499 "Marker at the beginning of the table last aligned.
7500 Used to check if cursor still is in that table, to minimize realignment.")
7501 (defvar org-table-aligned-end-marker (make-marker)
7502 "Marker at the end of the table last aligned.
7503 Used to check if cursor still is in that table, to minimize realignment.")
7504 (defvar org-table-last-alignment nil
7505 "List of flags for flushright alignment, from the last re-alignment.
7506 This is being used to correctly align a single field after TAB or RET.")
7507 (defvar org-table-last-column-widths nil
7508 "List of max width of fields in each column.
7509 This is being used to correctly align a single field after TAB or RET.")
7510 (defvar org-table-overlay-coordinates nil
7511 "Overlay coordinates after each align of a table.")
7512 (make-variable-buffer-local 'org-table-overlay-coordinates)
7514 (defvar org-last-recalc-line nil)
7515 (defconst org-narrow-column-arrow "=>"
7516 "Used as display property in narrowed table columns.")
7518 (defun org-table-align ()
7519 "Align the table at point by aligning all vertical bars."
7520 (interactive)
7521 (let* (
7522 ;; Limits of table
7523 (beg (org-table-begin))
7524 (end (org-table-end))
7525 ;; Current cursor position
7526 (linepos (org-current-line))
7527 (colpos (org-table-current-column))
7528 (winstart (window-start))
7529 (winstartline (org-current-line (min winstart (1- (point-max)))))
7530 lines (new "") lengths l typenums ty fields maxfields i
7531 column
7532 (indent "") cnt frac
7533 rfmt hfmt
7534 (spaces '(1 . 1))
7535 (sp1 (car spaces))
7536 (sp2 (cdr spaces))
7537 (rfmt1 (concat
7538 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7539 (hfmt1 (concat
7540 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7541 emptystrings links dates narrow fmax f1 len c e)
7542 (untabify beg end)
7543 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
7544 ;; Check if we have links or dates
7545 (goto-char beg)
7546 (setq links (re-search-forward org-bracket-link-regexp end t))
7547 (goto-char beg)
7548 (setq dates (and org-display-custom-times
7549 (re-search-forward org-ts-regexp-both end t)))
7550 ;; Make sure the link properties are right
7551 (when links (goto-char beg) (while (org-activate-bracket-links end)))
7552 ;; Make sure the date properties are right
7553 (when dates (goto-char beg) (while (org-activate-dates end)))
7555 ;; Check if we are narrowing any columns
7556 (goto-char beg)
7557 (setq narrow (and org-format-transports-properties-p
7558 (re-search-forward "<[0-9]+>" end t)))
7559 ;; Get the rows
7560 (setq lines (org-split-string
7561 (buffer-substring beg end) "\n"))
7562 ;; Store the indentation of the first line
7563 (if (string-match "^ *" (car lines))
7564 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7565 ;; Mark the hlines by setting the corresponding element to nil
7566 ;; At the same time, we remove trailing space.
7567 (setq lines (mapcar (lambda (l)
7568 (if (string-match "^ *|-" l)
7570 (if (string-match "[ \t]+$" l)
7571 (substring l 0 (match-beginning 0))
7572 l)))
7573 lines))
7574 ;; Get the data fields by splitting the lines.
7575 (setq fields (mapcar
7576 (lambda (l)
7577 (org-split-string l " *| *"))
7578 (delq nil (copy-sequence lines))))
7579 ;; How many fields in the longest line?
7580 (condition-case nil
7581 (setq maxfields (apply 'max (mapcar 'length fields)))
7582 (error
7583 (kill-region beg end)
7584 (org-table-create org-table-default-size)
7585 (error "Empty table - created default table")))
7586 ;; A list of empty strings to fill any short rows on output
7587 (setq emptystrings (make-list maxfields ""))
7588 ;; Check for special formatting.
7589 (setq i -1)
7590 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7591 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7592 ;; Check if there is an explicit width specified
7593 (when narrow
7594 (setq c column fmax nil)
7595 (while c
7596 (setq e (pop c))
7597 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
7598 (setq fmax (string-to-number (match-string 1 e)) c nil)))
7599 ;; Find fields that are wider than fmax, and shorten them
7600 (when fmax
7601 (loop for xx in column do
7602 (when (and (stringp xx)
7603 (> (org-string-width xx) fmax))
7604 (org-add-props xx nil
7605 'help-echo
7606 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
7607 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
7608 (unless (> f1 1)
7609 (error "Cannot narrow field starting with wide link \"%s\""
7610 (match-string 0 xx)))
7611 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
7612 (add-text-properties (- f1 2) f1
7613 (list 'display org-narrow-column-arrow)
7614 xx)))))
7615 ;; Get the maximum width for each column
7616 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
7617 ;; Get the fraction of numbers, to decide about alignment of the column
7618 (setq cnt 0 frac 0.0)
7619 (loop for x in column do
7620 (if (equal x "")
7622 (setq frac ( / (+ (* frac cnt)
7623 (if (string-match org-table-number-regexp x) 1 0))
7624 (setq cnt (1+ cnt))))))
7625 (push (>= frac org-table-number-fraction) typenums))
7626 (setq lengths (nreverse lengths) typenums (nreverse typenums))
7628 ;; Store the alignment of this table, for later editing of single fields
7629 (setq org-table-last-alignment typenums
7630 org-table-last-column-widths lengths)
7632 ;; With invisible characters, `format' does not get the field width right
7633 ;; So we need to make these fields wide by hand.
7634 (when links
7635 (loop for i from 0 upto (1- maxfields) do
7636 (setq len (nth i lengths))
7637 (loop for j from 0 upto (1- (length fields)) do
7638 (setq c (nthcdr i (car (nthcdr j fields))))
7639 (if (and (stringp (car c))
7640 (string-match org-bracket-link-regexp (car c))
7641 (< (org-string-width (car c)) len))
7642 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
7644 ;; Compute the formats needed for output of the table
7645 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7646 (while (setq l (pop lengths))
7647 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7648 (setq rfmt (concat rfmt (format rfmt1 ty l))
7649 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7650 (setq rfmt (concat rfmt "\n")
7651 hfmt (concat (substring hfmt 0 -1) "|\n"))
7653 (setq new (mapconcat
7654 (lambda (l)
7655 (if l (apply 'format rfmt
7656 (append (pop fields) emptystrings))
7657 hfmt))
7658 lines ""))
7659 ;; Replace the old one
7660 (delete-region beg end)
7661 (move-marker end nil)
7662 (move-marker org-table-aligned-begin-marker (point))
7663 (insert new)
7664 (move-marker org-table-aligned-end-marker (point))
7665 (when (and orgtbl-mode (not (org-mode-p)))
7666 (goto-char org-table-aligned-begin-marker)
7667 (while (org-hide-wide-columns org-table-aligned-end-marker)))
7668 ;; Try to move to the old location
7669 (goto-line winstartline)
7670 (setq winstart (point-at-bol))
7671 (goto-line linepos)
7672 (set-window-start (selected-window) winstart 'noforce)
7673 (org-table-goto-column colpos)
7674 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
7675 (setq org-table-may-need-update nil)
7678 (defun org-string-width (s)
7679 "Compute width of string, ignoring invisible characters.
7680 This ignores character with invisibility property `org-link', and also
7681 characters with property `org-cwidth', because these will become invisible
7682 upon the next fontification round."
7683 (let (b l)
7684 (when (or (eq t buffer-invisibility-spec)
7685 (assq 'org-link buffer-invisibility-spec))
7686 (while (setq b (text-property-any 0 (length s)
7687 'invisible 'org-link s))
7688 (setq s (concat (substring s 0 b)
7689 (substring s (or (next-single-property-change
7690 b 'invisible s) (length s)))))))
7691 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
7692 (setq s (concat (substring s 0 b)
7693 (substring s (or (next-single-property-change
7694 b 'org-cwidth s) (length s))))))
7695 (setq l (string-width s) b -1)
7696 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
7697 (setq l (- l (get-text-property b 'org-dwidth-n s))))
7700 (defun org-table-begin (&optional table-type)
7701 "Find the beginning of the table and return its position.
7702 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7703 (save-excursion
7704 (if (not (re-search-backward
7705 (if table-type org-table-any-border-regexp
7706 org-table-border-regexp)
7707 nil t))
7708 (progn (goto-char (point-min)) (point))
7709 (goto-char (match-beginning 0))
7710 (beginning-of-line 2)
7711 (point))))
7713 (defun org-table-end (&optional table-type)
7714 "Find the end of the table and return its position.
7715 With argument TABLE-TYPE, go to the end of a table.el-type table."
7716 (save-excursion
7717 (if (not (re-search-forward
7718 (if table-type org-table-any-border-regexp
7719 org-table-border-regexp)
7720 nil t))
7721 (goto-char (point-max))
7722 (goto-char (match-beginning 0)))
7723 (point-marker)))
7725 (defun org-table-justify-field-maybe (&optional new)
7726 "Justify the current field, text to left, number to right.
7727 Optional argument NEW may specify text to replace the current field content."
7728 (cond
7729 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7730 ((org-at-table-hline-p))
7731 ((and (not new)
7732 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7733 (current-buffer)))
7734 (< (point) org-table-aligned-begin-marker)
7735 (>= (point) org-table-aligned-end-marker)))
7736 ;; This is not the same table, force a full re-align
7737 (setq org-table-may-need-update t))
7738 (t ;; realign the current field, based on previous full realign
7739 (let* ((pos (point)) s
7740 (col (org-table-current-column))
7741 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
7742 l f n o e)
7743 (when (> col 0)
7744 (skip-chars-backward "^|\n")
7745 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7746 (progn
7747 (setq s (match-string 1)
7748 o (match-string 0)
7749 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7750 e (not (= (match-beginning 2) (match-end 2))))
7751 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7752 l (if e "|" (setq org-table-may-need-update t) ""))
7753 n (format f s))
7754 (if new
7755 (if (<= (length new) l) ;; FIXME: length -> str-width?
7756 (setq n (format f new))
7757 (setq n (concat new "|") org-table-may-need-update t)))
7758 (or (equal n o)
7759 (let (org-table-may-need-update)
7760 (replace-match n t t))))
7761 (setq org-table-may-need-update t))
7762 (goto-char pos))))))
7764 (defun org-table-next-field ()
7765 "Go to the next field in the current table, creating new lines as needed.
7766 Before doing so, re-align the table if necessary."
7767 (interactive)
7768 (org-table-maybe-eval-formula)
7769 (org-table-maybe-recalculate-line)
7770 (if (and org-table-automatic-realign
7771 org-table-may-need-update)
7772 (org-table-align))
7773 (let ((end (org-table-end)))
7774 (if (org-at-table-hline-p)
7775 (end-of-line 1))
7776 (condition-case nil
7777 (progn
7778 (re-search-forward "|" end)
7779 (if (looking-at "[ \t]*$")
7780 (re-search-forward "|" end))
7781 (if (and (looking-at "-")
7782 org-table-tab-jumps-over-hlines
7783 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7784 (goto-char (match-beginning 1)))
7785 (if (looking-at "-")
7786 (progn
7787 (beginning-of-line 0)
7788 (org-table-insert-row 'below))
7789 (if (looking-at " ") (forward-char 1))))
7790 (error
7791 (org-table-insert-row 'below)))))
7793 (defun org-table-previous-field ()
7794 "Go to the previous field in the table.
7795 Before doing so, re-align the table if necessary."
7796 (interactive)
7797 (org-table-justify-field-maybe)
7798 (org-table-maybe-recalculate-line)
7799 (if (and org-table-automatic-realign
7800 org-table-may-need-update)
7801 (org-table-align))
7802 (if (org-at-table-hline-p)
7803 (end-of-line 1))
7804 (re-search-backward "|" (org-table-begin))
7805 (re-search-backward "|" (org-table-begin))
7806 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7807 (re-search-backward "|" (org-table-begin)))
7808 (if (looking-at "| ?")
7809 (goto-char (match-end 0))))
7811 (defun org-table-next-row ()
7812 "Go to the next row (same column) in the current table.
7813 Before doing so, re-align the table if necessary."
7814 (interactive)
7815 (org-table-maybe-eval-formula)
7816 (org-table-maybe-recalculate-line)
7817 (if (or (looking-at "[ \t]*$")
7818 (save-excursion (skip-chars-backward " \t") (bolp)))
7819 (newline)
7820 (if (and org-table-automatic-realign
7821 org-table-may-need-update)
7822 (org-table-align))
7823 (let ((col (org-table-current-column)))
7824 (beginning-of-line 2)
7825 (if (or (not (org-at-table-p))
7826 (org-at-table-hline-p))
7827 (progn
7828 (beginning-of-line 0)
7829 (org-table-insert-row 'below)))
7830 (org-table-goto-column col)
7831 (skip-chars-backward "^|\n\r")
7832 (if (looking-at " ") (forward-char 1)))))
7834 (defun org-table-copy-down (n)
7835 "Copy a field down in the current column.
7836 If the field at the cursor is empty, copy into it the content of the nearest
7837 non-empty field above. With argument N, use the Nth non-empty field.
7838 If the current field is not empty, it is copied down to the next row, and
7839 the cursor is moved with it. Therefore, repeating this command causes the
7840 column to be filled row-by-row.
7841 If the variable `org-table-copy-increment' is non-nil and the field is an
7842 integer or a timestamp, it will be incremented while copying. In the case of
7843 a timestamp, if the cursor is on the year, change the year. If it is on the
7844 month or the day, change that. Point will stay on the current date field
7845 in order to easily repeat the interval."
7846 (interactive "p")
7847 (let* ((colpos (org-table-current-column))
7848 (col (current-column))
7849 (field (org-table-get-field))
7850 (non-empty (string-match "[^ \t]" field))
7851 (beg (org-table-begin))
7852 txt)
7853 (org-table-check-inside-data-field)
7854 (if non-empty
7855 (progn
7856 (setq txt (org-trim field))
7857 (org-table-next-row)
7858 (org-table-blank-field))
7859 (save-excursion
7860 (setq txt
7861 (catch 'exit
7862 (while (progn (beginning-of-line 1)
7863 (re-search-backward org-table-dataline-regexp
7864 beg t))
7865 (org-table-goto-column colpos t)
7866 (if (and (looking-at
7867 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7868 (= (setq n (1- n)) 0))
7869 (throw 'exit (match-string 1))))))))
7870 (if txt
7871 (progn
7872 (if (and org-table-copy-increment
7873 (string-match "^[0-9]+$" txt))
7874 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7875 (insert txt)
7876 (move-to-column col)
7877 (if (and org-table-copy-increment (org-at-timestamp-p t))
7878 (org-timestamp-up 1)
7879 (org-table-maybe-recalculate-line))
7880 (org-table-align)
7881 (move-to-column col))
7882 (error "No non-empty field found"))))
7884 (defun org-table-check-inside-data-field ()
7885 "Is point inside a table data field?
7886 I.e. not on a hline or before the first or after the last column?
7887 This actually throws an error, so it aborts the current command."
7888 (if (or (not (org-at-table-p))
7889 (= (org-table-current-column) 0)
7890 (org-at-table-hline-p)
7891 (looking-at "[ \t]*$"))
7892 (error "Not in table data field")))
7894 (defvar org-table-clip nil
7895 "Clipboard for table regions.")
7897 (defun org-table-blank-field ()
7898 "Blank the current table field or active region."
7899 (interactive)
7900 (org-table-check-inside-data-field)
7901 (if (and (interactive-p) (org-region-active-p))
7902 (let (org-table-clip)
7903 (org-table-cut-region (region-beginning) (region-end)))
7904 (skip-chars-backward "^|")
7905 (backward-char 1)
7906 (if (looking-at "|[^|\n]+")
7907 (let* ((pos (match-beginning 0))
7908 (match (match-string 0))
7909 (len (org-string-width match)))
7910 (replace-match (concat "|" (make-string (1- len) ?\ )))
7911 (goto-char (+ 2 pos))
7912 (substring match 1)))))
7914 (defun org-table-get-field (&optional n replace)
7915 "Return the value of the field in column N of current row.
7916 N defaults to current field.
7917 If REPLACE is a string, replace field with this value. The return value
7918 is always the old value."
7919 (and n (org-table-goto-column n))
7920 (skip-chars-backward "^|\n")
7921 (backward-char 1)
7922 (if (looking-at "|[^|\r\n]*")
7923 (let* ((pos (match-beginning 0))
7924 (val (buffer-substring (1+ pos) (match-end 0))))
7925 (if replace
7926 (replace-match (concat "|" replace) t t))
7927 (goto-char (min (point-at-eol) (+ 2 pos)))
7928 val)
7929 (forward-char 1) ""))
7931 (defun org-table-field-info (arg)
7932 "Show info about the current field, and highlight any reference at point."
7933 (interactive "P")
7934 (org-table-get-specials)
7935 (save-excursion
7936 (let* ((pos (point))
7937 (col (org-table-current-column))
7938 (cname (car (rassoc (int-to-string col) org-table-column-names)))
7939 (name (car (rassoc (list (org-current-line) col)
7940 org-table-named-field-locations)))
7941 (eql (org-table-get-stored-formulas))
7942 (dline (org-table-current-dline))
7943 (ref (format "@%d$%d" dline col))
7944 (ref1 (org-table-convert-refs-to-an ref))
7945 (fequation (or (assoc name eql) (assoc ref eql)))
7946 (cequation (assoc (int-to-string col) eql))
7947 (eqn (or fequation cequation)))
7948 (goto-char pos)
7949 (condition-case nil
7950 (org-table-show-reference 'local)
7951 (error nil))
7952 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
7953 dline col
7954 (if cname (concat " or $" cname) "")
7955 dline col ref1
7956 (if name (concat " or $" name) "")
7957 ;; FIXME: formula info not correct if special table line
7958 (if eqn
7959 (concat ", formula: "
7960 (org-table-formula-to-user
7961 (concat
7962 (if (string-match "^[$@]"(car eqn)) "" "$")
7963 (car eqn) "=" (cdr eqn))))
7964 "")))))
7966 (defun org-table-current-column ()
7967 "Find out which column we are in.
7968 When called interactively, column is also displayed in echo area."
7969 (interactive)
7970 (if (interactive-p) (org-table-check-inside-data-field))
7971 (save-excursion
7972 (let ((cnt 0) (pos (point)))
7973 (beginning-of-line 1)
7974 (while (search-forward "|" pos t)
7975 (setq cnt (1+ cnt)))
7976 (if (interactive-p) (message "This is table column %d" cnt))
7977 cnt)))
7979 (defun org-table-current-dline ()
7980 "Find out what table data line we are in.
7981 Only datalins count for this."
7982 (interactive)
7983 (if (interactive-p) (org-table-check-inside-data-field))
7984 (save-excursion
7985 (let ((cnt 0) (pos (point)))
7986 (goto-char (org-table-begin))
7987 (while (<= (point) pos)
7988 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
7989 (beginning-of-line 2))
7990 (if (interactive-p) (message "This is table line %d" cnt))
7991 cnt)))
7993 (defun org-table-goto-column (n &optional on-delim force)
7994 "Move the cursor to the Nth column in the current table line.
7995 With optional argument ON-DELIM, stop with point before the left delimiter
7996 of the field.
7997 If there are less than N fields, just go to after the last delimiter.
7998 However, when FORCE is non-nil, create new columns if necessary."
7999 (interactive "p")
8000 (let ((pos (point-at-eol)))
8001 (beginning-of-line 1)
8002 (when (> n 0)
8003 (while (and (> (setq n (1- n)) -1)
8004 (or (search-forward "|" pos t)
8005 (and force
8006 (progn (end-of-line 1)
8007 (skip-chars-backward "^|")
8008 (insert " | "))))))
8009 ; (backward-char 2) t)))))
8010 (when (and force (not (looking-at ".*|")))
8011 (save-excursion (end-of-line 1) (insert " | ")))
8012 (if on-delim
8013 (backward-char 1)
8014 (if (looking-at " ") (forward-char 1))))))
8016 (defun org-at-table-p (&optional table-type)
8017 "Return t if the cursor is inside an org-type table.
8018 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8019 (if org-enable-table-editor
8020 (save-excursion
8021 (beginning-of-line 1)
8022 (looking-at (if table-type org-table-any-line-regexp
8023 org-table-line-regexp)))
8024 nil))
8026 (defun org-at-table.el-p ()
8027 "Return t if and only if we are at a table.el table."
8028 (and (org-at-table-p 'any)
8029 (save-excursion
8030 (goto-char (org-table-begin 'any))
8031 (looking-at org-table1-hline-regexp))))
8033 (defun org-table-recognize-table.el ()
8034 "If there is a table.el table nearby, recognize it and move into it."
8035 (if org-table-tab-recognizes-table.el
8036 (if (org-at-table.el-p)
8037 (progn
8038 (beginning-of-line 1)
8039 (if (looking-at org-table-dataline-regexp)
8041 (if (looking-at org-table1-hline-regexp)
8042 (progn
8043 (beginning-of-line 2)
8044 (if (looking-at org-table-any-border-regexp)
8045 (beginning-of-line -1)))))
8046 (if (re-search-forward "|" (org-table-end t) t)
8047 (progn
8048 (require 'table)
8049 (if (table--at-cell-p (point))
8051 (message "recognizing table.el table...")
8052 (table-recognize-table)
8053 (message "recognizing table.el table...done")))
8054 (error "This should not happen..."))
8056 nil)
8057 nil))
8059 (defun org-at-table-hline-p ()
8060 "Return t if the cursor is inside a hline in a table."
8061 (if org-enable-table-editor
8062 (save-excursion
8063 (beginning-of-line 1)
8064 (looking-at org-table-hline-regexp))
8065 nil))
8067 (defun org-table-insert-column ()
8068 "Insert a new column into the table."
8069 (interactive)
8070 (if (not (org-at-table-p))
8071 (error "Not at a table"))
8072 (org-table-find-dataline)
8073 (let* ((col (max 1 (org-table-current-column)))
8074 (beg (org-table-begin))
8075 (end (org-table-end))
8076 ;; Current cursor position
8077 (linepos (org-current-line))
8078 (colpos col))
8079 (goto-char beg)
8080 (while (< (point) end)
8081 (if (org-at-table-hline-p)
8083 (org-table-goto-column col t)
8084 (insert "| "))
8085 (beginning-of-line 2))
8086 (move-marker end nil)
8087 (goto-line linepos)
8088 (org-table-goto-column colpos)
8089 (org-table-align)
8090 (org-table-fix-formulas "$" nil (1- col) 1)))
8092 (defun org-table-find-dataline ()
8093 "Find a dataline in the current table, which is needed for column commands."
8094 (if (and (org-at-table-p)
8095 (not (org-at-table-hline-p)))
8097 (let ((col (current-column))
8098 (end (org-table-end)))
8099 (move-to-column col)
8100 (while (and (< (point) end)
8101 (or (not (= (current-column) col))
8102 (org-at-table-hline-p)))
8103 (beginning-of-line 2)
8104 (move-to-column col))
8105 (if (and (org-at-table-p)
8106 (not (org-at-table-hline-p)))
8108 (error
8109 "Please position cursor in a data line for column operations")))))
8111 (defun org-table-delete-column ()
8112 "Delete a column from the table."
8113 (interactive)
8114 (if (not (org-at-table-p))
8115 (error "Not at a table"))
8116 (org-table-find-dataline)
8117 (org-table-check-inside-data-field)
8118 (let* ((col (org-table-current-column))
8119 (beg (org-table-begin))
8120 (end (org-table-end))
8121 ;; Current cursor position
8122 (linepos (org-current-line))
8123 (colpos col))
8124 (goto-char beg)
8125 (while (< (point) end)
8126 (if (org-at-table-hline-p)
8128 (org-table-goto-column col t)
8129 (and (looking-at "|[^|\n]+|")
8130 (replace-match "|")))
8131 (beginning-of-line 2))
8132 (move-marker end nil)
8133 (goto-line linepos)
8134 (org-table-goto-column colpos)
8135 (org-table-align)
8136 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8137 col -1 col)))
8139 (defun org-table-move-column-right ()
8140 "Move column to the right."
8141 (interactive)
8142 (org-table-move-column nil))
8143 (defun org-table-move-column-left ()
8144 "Move column to the left."
8145 (interactive)
8146 (org-table-move-column 'left))
8148 (defun org-table-move-column (&optional left)
8149 "Move the current column to the right. With arg LEFT, move to the left."
8150 (interactive "P")
8151 (if (not (org-at-table-p))
8152 (error "Not at a table"))
8153 (org-table-find-dataline)
8154 (org-table-check-inside-data-field)
8155 (let* ((col (org-table-current-column))
8156 (col1 (if left (1- col) col))
8157 (beg (org-table-begin))
8158 (end (org-table-end))
8159 ;; Current cursor position
8160 (linepos (org-current-line))
8161 (colpos (if left (1- col) (1+ col))))
8162 (if (and left (= col 1))
8163 (error "Cannot move column further left"))
8164 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8165 (error "Cannot move column further right"))
8166 (goto-char beg)
8167 (while (< (point) end)
8168 (if (org-at-table-hline-p)
8170 (org-table-goto-column col1 t)
8171 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8172 (replace-match "|\\2|\\1|")))
8173 (beginning-of-line 2))
8174 (move-marker end nil)
8175 (goto-line linepos)
8176 (org-table-goto-column colpos)
8177 (org-table-align)
8178 (org-table-fix-formulas
8179 "$" (list (cons (number-to-string col) (number-to-string colpos))
8180 (cons (number-to-string colpos) (number-to-string col))))))
8182 (defun org-table-move-row-down ()
8183 "Move table row down."
8184 (interactive)
8185 (org-table-move-row nil))
8186 (defun org-table-move-row-up ()
8187 "Move table row up."
8188 (interactive)
8189 (org-table-move-row 'up))
8191 (defun org-table-move-row (&optional up)
8192 "Move the current table line down. With arg UP, move it up."
8193 (interactive "P")
8194 (let* ((col (current-column))
8195 (pos (point))
8196 (hline1p (save-excursion (beginning-of-line 1)
8197 (looking-at org-table-hline-regexp)))
8198 (dline1 (org-table-current-dline))
8199 (dline2 (+ dline1 (if up -1 1)))
8200 (tonew (if up 0 2))
8201 txt hline2p)
8202 (beginning-of-line tonew)
8203 (unless (org-at-table-p)
8204 (goto-char pos)
8205 (error "Cannot move row further"))
8206 (setq hline2p (looking-at org-table-hline-regexp))
8207 (goto-char pos)
8208 (beginning-of-line 1)
8209 (setq pos (point))
8210 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8211 (delete-region (point) (1+ (point-at-eol)))
8212 (beginning-of-line tonew)
8213 (insert txt)
8214 (beginning-of-line 0)
8215 (move-to-column col)
8216 (unless (or hline1p hline2p)
8217 (org-table-fix-formulas
8218 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8219 (cons (number-to-string dline2) (number-to-string dline1)))))))
8221 (defun org-table-insert-row (&optional arg)
8222 "Insert a new row above the current line into the table.
8223 With prefix ARG, insert below the current line."
8224 (interactive "P")
8225 (if (not (org-at-table-p))
8226 (error "Not at a table"))
8227 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8228 (new (org-table-clean-line line)))
8229 ;; Fix the first field if necessary
8230 (if (string-match "^[ \t]*| *[#$] *|" line)
8231 (setq new (replace-match (match-string 0 line) t t new)))
8232 (beginning-of-line (if arg 2 1))
8233 (let (org-table-may-need-update) (insert-before-markers new "\n"))
8234 (beginning-of-line 0)
8235 (re-search-forward "| ?" (point-at-eol) t)
8236 (and (or org-table-may-need-update org-table-overlay-coordinates)
8237 (org-table-align))
8238 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8240 (defun org-table-insert-hline (&optional above)
8241 "Insert a horizontal-line below the current line into the table.
8242 With prefix ABOVE, insert above the current line."
8243 (interactive "P")
8244 (if (not (org-at-table-p))
8245 (error "Not at a table"))
8246 (let ((line (org-table-clean-line
8247 (buffer-substring (point-at-bol) (point-at-eol))))
8248 (col (current-column)))
8249 (while (string-match "|\\( +\\)|" line)
8250 (setq line (replace-match
8251 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8252 ?-) "|") t t line)))
8253 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8254 (beginning-of-line (if above 1 2))
8255 (insert line "\n")
8256 (beginning-of-line (if above 1 -1))
8257 (move-to-column col)
8258 (and org-table-overlay-coordinates (org-table-align))))
8260 (defun org-table-hline-and-move (&optional same-column)
8261 "Insert a hline and move to the row below that line."
8262 (interactive "P")
8263 (let ((col (org-table-current-column)))
8264 (org-table-maybe-eval-formula)
8265 (org-table-maybe-recalculate-line)
8266 (org-table-insert-hline)
8267 (end-of-line 2)
8268 (if (looking-at "\n[ \t]*|-")
8269 (progn (insert "\n|") (org-table-align))
8270 (org-table-next-field))
8271 (if same-column (org-table-goto-column col))))
8273 (defun org-table-clean-line (s)
8274 "Convert a table line S into a string with only \"|\" and space.
8275 In particular, this does handle wide and invisible characters."
8276 (if (string-match "^[ \t]*|-" s)
8277 ;; It's a hline, just map the characters
8278 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
8279 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8280 (setq s (replace-match
8281 (concat "|" (make-string (org-string-width (match-string 1 s))
8282 ?\ ) "|")
8283 t t s)))
8286 (defun org-table-kill-row ()
8287 "Delete the current row or horizontal line from the table."
8288 (interactive)
8289 (if (not (org-at-table-p))
8290 (error "Not at a table"))
8291 (let ((col (current-column))
8292 (dline (org-table-current-dline)))
8293 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8294 (if (not (org-at-table-p)) (beginning-of-line 0))
8295 (move-to-column col)
8296 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
8297 dline -1 dline)))
8300 (defun org-table-sort-lines (with-case &optional sorting-type)
8301 "Sort table lines according to the column at point.
8303 The position of point indicates the column to be used for
8304 sorting, and the range of lines is the range between the nearest
8305 horizontal separator lines, or the entire table of no such lines
8306 exist. If point is before the first column, you will be prompted
8307 for the sorting column. If there is an active region, the mark
8308 specifies the first line and the sorting column, while point
8309 should be in the last line to be included into the sorting.
8311 The command then prompts for the sorting type which can be
8312 alphabetically, numerically, or by time (as given in a time stamp
8313 in the field). Sorting in reverse order is also possible.
8315 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
8317 If SORTING-TYPE is specified when this function is called from a Lisp
8318 program, no prompting will take place. SORTING-TYPE must be a character,
8319 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
8320 should be done in reverse order."
8321 (interactive "P")
8322 (let* ((thisline (org-current-line))
8323 (thiscol (org-table-current-column))
8324 beg end bcol ecol tend tbeg column lns pos)
8325 (when (equal thiscol 0)
8326 (if (interactive-p)
8327 (setq thiscol
8328 (string-to-number
8329 (read-string "Use column N for sorting: ")))
8330 (setq thiscol 1))
8331 (org-table-goto-column thiscol))
8332 (org-table-check-inside-data-field)
8333 (if (org-region-active-p)
8334 (progn
8335 (setq beg (region-beginning) end (region-end))
8336 (goto-char beg)
8337 (setq column (org-table-current-column)
8338 beg (point-at-bol))
8339 (goto-char end)
8340 (setq end (point-at-bol 2)))
8341 (setq column (org-table-current-column)
8342 pos (point)
8343 tbeg (org-table-begin)
8344 tend (org-table-end))
8345 (if (re-search-backward org-table-hline-regexp tbeg t)
8346 (setq beg (point-at-bol 2))
8347 (goto-char tbeg)
8348 (setq beg (point-at-bol 1)))
8349 (goto-char pos)
8350 (if (re-search-forward org-table-hline-regexp tend t)
8351 (setq end (point-at-bol 1))
8352 (goto-char tend)
8353 (setq end (point-at-bol))))
8354 (setq beg (move-marker (make-marker) beg)
8355 end (move-marker (make-marker) end))
8356 (untabify beg end)
8357 (goto-char beg)
8358 (org-table-goto-column column)
8359 (skip-chars-backward "^|")
8360 (setq bcol (current-column))
8361 (org-table-goto-column (1+ column))
8362 (skip-chars-backward "^|")
8363 (setq ecol (1- (current-column)))
8364 (org-table-goto-column column)
8365 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8366 (org-split-string (buffer-substring beg end) "\n")))
8367 (setq lns (org-do-sort lns "Table" with-case sorting-type))
8368 (delete-region beg end)
8369 (move-marker beg nil)
8370 (move-marker end nil)
8371 (insert (mapconcat 'cdr lns "\n") "\n")
8372 (goto-line thisline)
8373 (org-table-goto-column thiscol)
8374 (message "%d lines sorted, based on column %d" (length lns) column)))
8376 (defun org-table-cut-region (beg end)
8377 "Copy region in table to the clipboard and blank all relevant fields."
8378 (interactive "r")
8379 (org-table-copy-region beg end 'cut))
8381 (defun org-table-copy-region (beg end &optional cut)
8382 "Copy rectangular region in table to clipboard.
8383 A special clipboard is used which can only be accessed
8384 with `org-table-paste-rectangle'."
8385 (interactive "rP")
8386 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8387 region cols
8388 (rpl (if cut " " nil)))
8389 (goto-char beg)
8390 (org-table-check-inside-data-field)
8391 (setq l01 (org-current-line)
8392 c01 (org-table-current-column))
8393 (goto-char end)
8394 (org-table-check-inside-data-field)
8395 (setq l02 (org-current-line)
8396 c02 (org-table-current-column))
8397 (setq l1 (min l01 l02) l2 (max l01 l02)
8398 c1 (min c01 c02) c2 (max c01 c02))
8399 (catch 'exit
8400 (while t
8401 (catch 'nextline
8402 (if (> l1 l2) (throw 'exit t))
8403 (goto-line l1)
8404 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8405 (setq cols nil ic1 c1 ic2 c2)
8406 (while (< ic1 (1+ ic2))
8407 (push (org-table-get-field ic1 rpl) cols)
8408 (setq ic1 (1+ ic1)))
8409 (push (nreverse cols) region)
8410 (setq l1 (1+ l1)))))
8411 (setq org-table-clip (nreverse region))
8412 (if cut (org-table-align))
8413 org-table-clip))
8415 (defun org-table-paste-rectangle ()
8416 "Paste a rectangular region into a table.
8417 The upper right corner ends up in the current field. All involved fields
8418 will be overwritten. If the rectangle does not fit into the present table,
8419 the table is enlarged as needed. The process ignores horizontal separator
8420 lines."
8421 (interactive)
8422 (unless (and org-table-clip (listp org-table-clip))
8423 (error "First cut/copy a region to paste!"))
8424 (org-table-check-inside-data-field)
8425 (let* ((clip org-table-clip)
8426 (line (org-current-line))
8427 (col (org-table-current-column))
8428 (org-enable-table-editor t)
8429 (org-table-automatic-realign nil)
8430 c cols field)
8431 (while (setq cols (pop clip))
8432 (while (org-at-table-hline-p) (beginning-of-line 2))
8433 (if (not (org-at-table-p))
8434 (progn (end-of-line 0) (org-table-next-field)))
8435 (setq c col)
8436 (while (setq field (pop cols))
8437 (org-table-goto-column c nil 'force)
8438 (org-table-get-field nil field)
8439 (setq c (1+ c)))
8440 (beginning-of-line 2))
8441 (goto-line line)
8442 (org-table-goto-column col)
8443 (org-table-align)))
8445 (defun org-table-convert ()
8446 "Convert from `org-mode' table to table.el and back.
8447 Obviously, this only works within limits. When an Org-mode table is
8448 converted to table.el, all horizontal separator lines get lost, because
8449 table.el uses these as cell boundaries and has no notion of horizontal lines.
8450 A table.el table can be converted to an Org-mode table only if it does not
8451 do row or column spanning. Multiline cells will become multiple cells.
8452 Beware, Org-mode does not test if the table can be successfully converted - it
8453 blindly applies a recipe that works for simple tables."
8454 (interactive)
8455 (require 'table)
8456 (if (org-at-table.el-p)
8457 ;; convert to Org-mode table
8458 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8459 (end (move-marker (make-marker) (org-table-end t))))
8460 (table-unrecognize-region beg end)
8461 (goto-char beg)
8462 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8463 (replace-match ""))
8464 (goto-char beg))
8465 (if (org-at-table-p)
8466 ;; convert to table.el table
8467 (let ((beg (move-marker (make-marker) (org-table-begin)))
8468 (end (move-marker (make-marker) (org-table-end))))
8469 ;; first, get rid of all horizontal lines
8470 (goto-char beg)
8471 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8472 (replace-match ""))
8473 ;; insert a hline before first
8474 (goto-char beg)
8475 (org-table-insert-hline 'above)
8476 (beginning-of-line -1)
8477 ;; insert a hline after each line
8478 (while (progn (beginning-of-line 3) (< (point) end))
8479 (org-table-insert-hline))
8480 (goto-char beg)
8481 (setq end (move-marker end (org-table-end)))
8482 ;; replace "+" at beginning and ending of hlines
8483 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8484 (replace-match "\\1+-"))
8485 (goto-char beg)
8486 (while (re-search-forward "-|[ \t]*$" end t)
8487 (replace-match "-+"))
8488 (goto-char beg)))))
8490 (defun org-table-wrap-region (arg)
8491 "Wrap several fields in a column like a paragraph.
8492 This is useful if you'd like to spread the contents of a field over several
8493 lines, in order to keep the table compact.
8495 If there is an active region, and both point and mark are in the same column,
8496 the text in the column is wrapped to minimum width for the given number of
8497 lines. Generally, this makes the table more compact. A prefix ARG may be
8498 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8499 formats the selected text to two lines. If the region was longer than two
8500 lines, the remaining lines remain empty. A negative prefix argument reduces
8501 the current number of lines by that amount. The wrapped text is pasted back
8502 into the table. If you formatted it to more lines than it was before, fields
8503 further down in the table get overwritten - so you might need to make space in
8504 the table first.
8506 If there is no region, the current field is split at the cursor position and
8507 the text fragment to the right of the cursor is prepended to the field one
8508 line down.
8510 If there is no region, but you specify a prefix ARG, the current field gets
8511 blank, and the content is appended to the field above."
8512 (interactive "P")
8513 (org-table-check-inside-data-field)
8514 (if (org-region-active-p)
8515 ;; There is a region: fill as a paragraph
8516 (let* ((beg (region-beginning))
8517 (cline (save-excursion (goto-char beg) (org-current-line)))
8518 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
8519 nlines)
8520 (org-table-cut-region (region-beginning) (region-end))
8521 (if (> (length (car org-table-clip)) 1)
8522 (error "Region must be limited to single column"))
8523 (setq nlines (if arg
8524 (if (< arg 1)
8525 (+ (length org-table-clip) arg)
8526 arg)
8527 (length org-table-clip)))
8528 (setq org-table-clip
8529 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8530 nil nlines)))
8531 (goto-line cline)
8532 (org-table-goto-column ccol)
8533 (org-table-paste-rectangle))
8534 ;; No region, split the current field at point
8535 (if arg
8536 ;; combine with field above
8537 (let ((s (org-table-blank-field))
8538 (col (org-table-current-column)))
8539 (beginning-of-line 0)
8540 (while (org-at-table-hline-p) (beginning-of-line 0))
8541 (org-table-goto-column col)
8542 (skip-chars-forward "^|")
8543 (skip-chars-backward " ")
8544 (insert " " (org-trim s))
8545 (org-table-align))
8546 ;; split field
8547 (when (looking-at "\\([^|]+\\)+|")
8548 (let ((s (match-string 1)))
8549 (replace-match " |")
8550 (goto-char (match-beginning 0))
8551 (org-table-next-row)
8552 (insert (org-trim s) " ")
8553 (org-table-align))))))
8555 (defvar org-field-marker nil)
8557 (defun org-table-edit-field (arg)
8558 "Edit table field in a different window.
8559 This is mainly useful for fields that contain hidden parts.
8560 When called with a \\[universal-argument] prefix, just make the full field visible so that
8561 it can be edited in place."
8562 (interactive "P")
8563 (if arg
8564 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
8565 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
8566 (remove-text-properties b e '(org-cwidth t invisible t
8567 display t intangible t))
8568 (if (and (boundp 'font-lock-mode) font-lock-mode)
8569 (font-lock-fontify-block)))
8570 (let ((pos (move-marker (make-marker) (point)))
8571 (field (org-table-get-field))
8572 (cw (current-window-configuration))
8574 (org-switch-to-buffer-other-window "*Org tmp*")
8575 (erase-buffer)
8576 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
8577 (let ((org-inhibit-startup t)) (org-mode))
8578 (goto-char (setq p (point-max)))
8579 (insert (org-trim field))
8580 (remove-text-properties p (point-max)
8581 '(invisible t org-cwidth t display t
8582 intangible t))
8583 (goto-char p)
8584 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
8585 (org-set-local 'org-window-configuration cw)
8586 (org-set-local 'org-field-marker pos)
8587 (message "Edit and finish with C-c C-c"))))
8589 (defun org-table-finish-edit-field ()
8590 "Finish editing a table data field.
8591 Remove all newline characters, insert the result into the table, realign
8592 the table and kill the editing buffer."
8593 (let ((pos org-field-marker)
8594 (cw org-window-configuration)
8595 (cb (current-buffer))
8596 text)
8597 (goto-char (point-min))
8598 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
8599 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
8600 (replace-match " "))
8601 (setq text (org-trim (buffer-string)))
8602 (set-window-configuration cw)
8603 (kill-buffer cb)
8604 (select-window (get-buffer-window (marker-buffer pos)))
8605 (goto-char pos)
8606 (move-marker pos nil)
8607 (org-table-check-inside-data-field)
8608 (org-table-get-field nil text)
8609 (org-table-align)
8610 (message "New field value inserted")))
8612 (defun org-trim (s)
8613 "Remove whitespace at beginning and end of string."
8614 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
8615 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
8618 (defun org-wrap (string &optional width lines)
8619 "Wrap string to either a number of lines, or a width in characters.
8620 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8621 that costs. If there is a word longer than WIDTH, the text is actually
8622 wrapped to the length of that word.
8623 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8624 many lines, whatever width that takes.
8625 The return value is a list of lines, without newlines at the end."
8626 (let* ((words (org-split-string string "[ \t\n]+"))
8627 (maxword (apply 'max (mapcar 'org-string-width words)))
8628 w ll)
8629 (cond (width
8630 (org-do-wrap words (max maxword width)))
8631 (lines
8632 (setq w maxword)
8633 (setq ll (org-do-wrap words maxword))
8634 (if (<= (length ll) lines)
8636 (setq ll words)
8637 (while (> (length ll) lines)
8638 (setq w (1+ w))
8639 (setq ll (org-do-wrap words w)))
8640 ll))
8641 (t (error "Cannot wrap this")))))
8644 (defun org-do-wrap (words width)
8645 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8646 (let (lines line)
8647 (while words
8648 (setq line (pop words))
8649 (while (and words (< (+ (length line) (length (car words))) width))
8650 (setq line (concat line " " (pop words))))
8651 (setq lines (push line lines)))
8652 (nreverse lines)))
8654 (defun org-split-string (string &optional separators)
8655 "Splits STRING into substrings at SEPARATORS.
8656 No empty strings are returned if there are matches at the beginning
8657 and end of string."
8658 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8659 (start 0)
8660 notfirst
8661 (list nil))
8662 (while (and (string-match rexp string
8663 (if (and notfirst
8664 (= start (match-beginning 0))
8665 (< start (length string)))
8666 (1+ start) start))
8667 (< (match-beginning 0) (length string)))
8668 (setq notfirst t)
8669 (or (eq (match-beginning 0) 0)
8670 (and (eq (match-beginning 0) (match-end 0))
8671 (eq (match-beginning 0) start))
8672 (setq list
8673 (cons (substring string start (match-beginning 0))
8674 list)))
8675 (setq start (match-end 0)))
8676 (or (eq start (length string))
8677 (setq list
8678 (cons (substring string start)
8679 list)))
8680 (nreverse list)))
8682 (defun org-table-map-tables (function)
8683 "Apply FUNCTION to the start of all tables in the buffer."
8684 (save-excursion
8685 (save-restriction
8686 (widen)
8687 (goto-char (point-min))
8688 (while (re-search-forward org-table-any-line-regexp nil t)
8689 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8690 (beginning-of-line 1)
8691 (if (looking-at org-table-line-regexp)
8692 (save-excursion (funcall function)))
8693 (re-search-forward org-table-any-border-regexp nil 1))))
8694 (message "Mapping tables: done"))
8696 (defvar org-timecnt) ; dynamically scoped parameter
8698 (defun org-table-sum (&optional beg end nlast)
8699 "Sum numbers in region of current table column.
8700 The result will be displayed in the echo area, and will be available
8701 as kill to be inserted with \\[yank].
8703 If there is an active region, it is interpreted as a rectangle and all
8704 numbers in that rectangle will be summed. If there is no active
8705 region and point is located in a table column, sum all numbers in that
8706 column.
8708 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8709 numbers are assumed to be times as well (in decimal hours) and the
8710 numbers are added as such.
8712 If NLAST is a number, only the NLAST fields will actually be summed."
8713 (interactive)
8714 (save-excursion
8715 (let (col (org-timecnt 0) diff h m s org-table-clip)
8716 (cond
8717 ((and beg end)) ; beg and end given explicitly
8718 ((org-region-active-p)
8719 (setq beg (region-beginning) end (region-end)))
8721 (setq col (org-table-current-column))
8722 (goto-char (org-table-begin))
8723 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8724 (error "No table data"))
8725 (org-table-goto-column col)
8726 (setq beg (point))
8727 (goto-char (org-table-end))
8728 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8729 (error "No table data"))
8730 (org-table-goto-column col)
8731 (setq end (point))))
8732 (let* ((items (apply 'append (org-table-copy-region beg end)))
8733 (items1 (cond ((not nlast) items)
8734 ((>= nlast (length items)) items)
8735 (t (setq items (reverse items))
8736 (setcdr (nthcdr (1- nlast) items) nil)
8737 (nreverse items))))
8738 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8739 items1)))
8740 (res (apply '+ numbers))
8741 (sres (if (= org-timecnt 0)
8742 (format "%g" res)
8743 (setq diff (* 3600 res)
8744 h (floor (/ diff 3600)) diff (mod diff 3600)
8745 m (floor (/ diff 60)) diff (mod diff 60)
8746 s diff)
8747 (format "%d:%02d:%02d" h m s))))
8748 (kill-new sres)
8749 (if (interactive-p)
8750 (message "%s"
8751 (substitute-command-keys
8752 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8753 (length numbers) sres))))
8754 sres))))
8756 (defun org-table-get-number-for-summing (s)
8757 (let (n)
8758 (if (string-match "^ *|? *" s)
8759 (setq s (replace-match "" nil nil s)))
8760 (if (string-match " *|? *$" s)
8761 (setq s (replace-match "" nil nil s)))
8762 (setq n (string-to-number s))
8763 (cond
8764 ((and (string-match "0" s)
8765 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8766 ((string-match "\\`[ \t]+\\'" s) nil)
8767 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8768 (let ((h (string-to-number (or (match-string 1 s) "0")))
8769 (m (string-to-number (or (match-string 2 s) "0")))
8770 (s (string-to-number (or (match-string 4 s) "0"))))
8771 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
8772 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8773 ((equal n 0) nil)
8774 (t n))))
8776 (defun org-table-current-field-formula (&optional key noerror)
8777 "Return the formula active for the current field.
8778 Assumes that specials are in place.
8779 If KEY is given, return the key to this formula.
8780 Otherwise return the formula preceeded with \"=\" or \":=\"."
8781 (let* ((name (car (rassoc (list (org-current-line)
8782 (org-table-current-column))
8783 org-table-named-field-locations)))
8784 (col (org-table-current-column))
8785 (scol (int-to-string col))
8786 (ref (format "@%d$%d" (org-table-current-dline) col))
8787 (stored-list (org-table-get-stored-formulas noerror))
8788 (ass (or (assoc name stored-list)
8789 (assoc ref stored-list)
8790 (assoc scol stored-list))))
8791 (if key
8792 (car ass)
8793 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
8794 (cdr ass))))))
8796 (defun org-table-get-formula (&optional equation named)
8797 "Read a formula from the minibuffer, offer stored formula as default.
8798 When NAMED is non-nil, look for a named equation."
8799 (let* ((stored-list (org-table-get-stored-formulas))
8800 (name (car (rassoc (list (org-current-line)
8801 (org-table-current-column))
8802 org-table-named-field-locations)))
8803 (ref (format "@%d$%d" (org-table-current-dline)
8804 (org-table-current-column)))
8805 (refass (assoc ref stored-list))
8806 (scol (if named
8807 (if name name ref)
8808 (int-to-string (org-table-current-column))))
8809 (dummy (and (or name refass) (not named)
8810 (not (y-or-n-p "Replace field formula with column formula? " ))
8811 (error "Abort")))
8812 (name (or name ref))
8813 (org-table-may-need-update nil)
8814 (stored (cdr (assoc scol stored-list)))
8815 (eq (cond
8816 ((and stored equation (string-match "^ *=? *$" equation))
8817 stored)
8818 ((stringp equation)
8819 equation)
8820 (t (org-table-formula-from-user
8821 (read-string
8822 (org-table-formula-to-user
8823 (format "%s formula %s%s="
8824 (if named "Field" "Column")
8825 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
8826 scol))
8827 (if stored (org-table-formula-to-user stored) "")
8828 'org-table-formula-history
8829 )))))
8830 mustsave)
8831 (when (not (string-match "\\S-" eq))
8832 ;; remove formula
8833 (setq stored-list (delq (assoc scol stored-list) stored-list))
8834 (org-table-store-formulas stored-list)
8835 (error "Formula removed"))
8836 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8837 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8838 (if (and name (not named))
8839 ;; We set the column equation, delete the named one.
8840 (setq stored-list (delq (assoc name stored-list) stored-list)
8841 mustsave t))
8842 (if stored
8843 (setcdr (assoc scol stored-list) eq)
8844 (setq stored-list (cons (cons scol eq) stored-list)))
8845 (if (or mustsave (not (equal stored eq)))
8846 (org-table-store-formulas stored-list))
8847 eq))
8849 (defun org-table-store-formulas (alist)
8850 "Store the list of formulas below the current table."
8851 (setq alist (sort alist 'org-table-formula-less-p))
8852 (save-excursion
8853 (goto-char (org-table-end))
8854 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
8855 (progn
8856 ;; don't overwrite TBLFM, we might use text properties to store stuff
8857 (goto-char (match-beginning 2))
8858 (delete-region (match-beginning 2) (match-end 0)))
8859 (insert "#+TBLFM:"))
8860 (insert " "
8861 (mapconcat (lambda (x)
8862 (concat
8863 (if (equal (string-to-char (car x)) ?@) "" "$")
8864 (car x) "=" (cdr x)))
8865 alist "::")
8866 "\n")))
8868 (defsubst org-table-formula-make-cmp-string (a)
8869 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
8870 (concat
8871 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
8872 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
8873 (if (match-end 5) (concat "@@" (match-string 5 a))))))
8875 (defun org-table-formula-less-p (a b)
8876 "Compare two formulas for sorting."
8877 (let ((as (org-table-formula-make-cmp-string (car a)))
8878 (bs (org-table-formula-make-cmp-string (car b))))
8879 (and as bs (string< as bs))))
8881 (defun org-table-get-stored-formulas (&optional noerror)
8882 "Return an alist with the stored formulas directly after current table."
8883 (interactive)
8884 (let (scol eq eq-alist strings string seen)
8885 (save-excursion
8886 (goto-char (org-table-end))
8887 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8888 (setq strings (org-split-string (match-string 2) " *:: *"))
8889 (while (setq string (pop strings))
8890 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
8891 (setq scol (if (match-end 2)
8892 (match-string 2 string)
8893 (match-string 1 string))
8894 eq (match-string 3 string)
8895 eq-alist (cons (cons scol eq) eq-alist))
8896 (if (member scol seen)
8897 (if noerror
8898 (progn
8899 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8900 (ding)
8901 (sit-for 2))
8902 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
8903 (push scol seen))))))
8904 (nreverse eq-alist)))
8906 (defun org-table-fix-formulas (key replace &optional limit delta remove)
8907 "Modify the equations after the table structure has been edited.
8908 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
8909 For all numbers larger than LIMIT, shift them by DELTA."
8910 (save-excursion
8911 (goto-char (org-table-end))
8912 (when (looking-at "#\\+TBLFM:")
8913 (let ((re (concat key "\\([0-9]+\\)"))
8914 (re2
8915 (when remove
8916 (if (equal key "$")
8917 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
8918 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
8919 s n a)
8920 (when remove
8921 (while (re-search-forward re2 (point-at-eol) t)
8922 (replace-match "")))
8923 (while (re-search-forward re (point-at-eol) t)
8924 (setq s (match-string 1) n (string-to-number s))
8925 (cond
8926 ((setq a (assoc s replace))
8927 (replace-match (concat key (cdr a)) t t))
8928 ((and limit (> n limit))
8929 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
8931 (defun org-table-get-specials ()
8932 "Get the column names and local parameters for this table."
8933 (save-excursion
8934 (let ((beg (org-table-begin)) (end (org-table-end))
8935 names name fields fields1 field cnt
8936 c v l line col types dlines hlines)
8937 (setq org-table-column-names nil
8938 org-table-local-parameters nil
8939 org-table-named-field-locations nil
8940 org-table-current-begin-line nil
8941 org-table-current-begin-pos nil
8942 org-table-current-line-types nil)
8943 (goto-char beg)
8944 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8945 (setq names (org-split-string (match-string 1) " *| *")
8946 cnt 1)
8947 (while (setq name (pop names))
8948 (setq cnt (1+ cnt))
8949 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8950 (push (cons name (int-to-string cnt)) org-table-column-names))))
8951 (setq org-table-column-names (nreverse org-table-column-names))
8952 (setq org-table-column-name-regexp
8953 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8954 (goto-char beg)
8955 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8956 (setq fields (org-split-string (match-string 1) " *| *"))
8957 (while (setq field (pop fields))
8958 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8959 (push (cons (match-string 1 field) (match-string 2 field))
8960 org-table-local-parameters))))
8961 (goto-char beg)
8962 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8963 (setq c (match-string 1)
8964 fields (org-split-string (match-string 2) " *| *"))
8965 (save-excursion
8966 (beginning-of-line (if (equal c "_") 2 0))
8967 (setq line (org-current-line) col 1)
8968 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8969 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8970 (while (and fields1 (setq field (pop fields)))
8971 (setq v (pop fields1) col (1+ col))
8972 (when (and (stringp field) (stringp v)
8973 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8974 (push (cons field v) org-table-local-parameters)
8975 (push (list field line col) org-table-named-field-locations))))
8976 ;; Analyse the line types
8977 (goto-char beg)
8978 (setq org-table-current-begin-line (org-current-line)
8979 org-table-current-begin-pos (point)
8980 l org-table-current-begin-line)
8981 (while (looking-at "[ \t]*|\\(-\\)?")
8982 (push (if (match-end 1) 'hline 'dline) types)
8983 (if (match-end 1) (push l hlines) (push l dlines))
8984 (beginning-of-line 2)
8985 (setq l (1+ l)))
8986 (setq org-table-current-line-types (apply 'vector (nreverse types))
8987 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
8988 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
8990 (defun org-table-maybe-eval-formula ()
8991 "Check if the current field starts with \"=\" or \":=\".
8992 If yes, store the formula and apply it."
8993 ;; We already know we are in a table. Get field will only return a formula
8994 ;; when appropriate. It might return a separator line, but no problem.
8995 (when org-table-formula-evaluate-inline
8996 (let* ((field (org-trim (or (org-table-get-field) "")))
8997 named eq)
8998 (when (string-match "^:?=\\(.*\\)" field)
8999 (setq named (equal (string-to-char field) ?:)
9000 eq (match-string 1 field))
9001 (if (or (fboundp 'calc-eval)
9002 (equal (substring eq 0 (min 2 (length eq))) "'("))
9003 (org-table-eval-formula (if named '(4) nil)
9004 (org-table-formula-from-user eq))
9005 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9007 (defvar org-recalc-commands nil
9008 "List of commands triggering the recalculation of a line.
9009 Will be filled automatically during use.")
9011 (defvar org-recalc-marks
9012 '((" " . "Unmarked: no special line, no automatic recalculation")
9013 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9014 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9015 ("!" . "Column name definition line. Reference in formula as $name.")
9016 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9017 ("_" . "Names for values in row below this one.")
9018 ("^" . "Names for values in row above this one.")))
9020 (defun org-table-rotate-recalc-marks (&optional newchar)
9021 "Rotate the recalculation mark in the first column.
9022 If in any row, the first field is not consistent with a mark,
9023 insert a new column for the markers.
9024 When there is an active region, change all the lines in the region,
9025 after prompting for the marking character.
9026 After each change, a message will be displayed indicating the meaning
9027 of the new mark."
9028 (interactive)
9029 (unless (org-at-table-p) (error "Not at a table"))
9030 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9031 (beg (org-table-begin))
9032 (end (org-table-end))
9033 (l (org-current-line))
9034 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9035 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9036 (have-col
9037 (save-excursion
9038 (goto-char beg)
9039 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9040 (col (org-table-current-column))
9041 (forcenew (car (assoc newchar org-recalc-marks)))
9042 epos new)
9043 (when l1
9044 (message "Change region to what mark? Type # * ! $ or SPC: ")
9045 (setq newchar (char-to-string (read-char-exclusive))
9046 forcenew (car (assoc newchar org-recalc-marks))))
9047 (if (and newchar (not forcenew))
9048 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9049 newchar))
9050 (if l1 (goto-line l1))
9051 (save-excursion
9052 (beginning-of-line 1)
9053 (unless (looking-at org-table-dataline-regexp)
9054 (error "Not at a table data line")))
9055 (unless have-col
9056 (org-table-goto-column 1)
9057 (org-table-insert-column)
9058 (org-table-goto-column (1+ col)))
9059 (setq epos (point-at-eol))
9060 (save-excursion
9061 (beginning-of-line 1)
9062 (org-table-get-field
9063 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9064 (concat " "
9065 (setq new (or forcenew
9066 (cadr (member (match-string 1) marks))))
9067 " ")
9068 " # ")))
9069 (if (and l1 l2)
9070 (progn
9071 (goto-line l1)
9072 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9073 (and (looking-at org-table-dataline-regexp)
9074 (org-table-get-field 1 (concat " " new " "))))
9075 (goto-line l1)))
9076 (if (not (= epos (point-at-eol))) (org-table-align))
9077 (goto-line l)
9078 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9080 (defun org-table-maybe-recalculate-line ()
9081 "Recompute the current line if marked for it, and if we haven't just done it."
9082 (interactive)
9083 (and org-table-allow-automatic-line-recalculation
9084 (not (and (memq last-command org-recalc-commands)
9085 (equal org-last-recalc-line (org-current-line))))
9086 (save-excursion (beginning-of-line 1)
9087 (looking-at org-table-auto-recalculate-regexp))
9088 (org-table-recalculate) t))
9090 (defvar org-table-formula-debug nil
9091 "Non-nil means, debug table formulas.
9092 When nil, simply write \"#ERROR\" in corrupted fields.")
9093 (make-variable-buffer-local 'org-table-formula-debug)
9095 (defvar modes)
9096 (defsubst org-set-calc-mode (var &optional value)
9097 (if (stringp var)
9098 (setq var (assoc var '(("D" calc-angle-mode deg)
9099 ("R" calc-angle-mode rad)
9100 ("F" calc-prefer-frac t)
9101 ("S" calc-symbolic-mode t)))
9102 value (nth 2 var) var (nth 1 var)))
9103 (if (memq var modes)
9104 (setcar (cdr (memq var modes)) value)
9105 (cons var (cons value modes)))
9106 modes)
9108 (defun org-table-eval-formula (&optional arg equation
9109 suppress-align suppress-const
9110 suppress-store suppress-analysis)
9111 "Replace the table field value at the cursor by the result of a calculation.
9113 This function makes use of Dave Gillespie's Calc package, in my view the
9114 most exciting program ever written for GNU Emacs. So you need to have Calc
9115 installed in order to use this function.
9117 In a table, this command replaces the value in the current field with the
9118 result of a formula. It also installs the formula as the \"current\" column
9119 formula, by storing it in a special line below the table. When called
9120 with a `C-u' prefix, the current field must ba a named field, and the
9121 formula is installed as valid in only this specific field.
9123 When called with two `C-u' prefixes, insert the active equation
9124 for the field back into the current field, so that it can be
9125 edited there. This is useful in order to use \\[org-table-show-reference]
9126 to check the referenced fields.
9128 When called, the command first prompts for a formula, which is read in
9129 the minibuffer. Previously entered formulas are available through the
9130 history list, and the last used formula is offered as a default.
9131 These stored formulas are adapted correctly when moving, inserting, or
9132 deleting columns with the corresponding commands.
9134 The formula can be any algebraic expression understood by the Calc package.
9135 For details, see the Org-mode manual.
9137 This function can also be called from Lisp programs and offers
9138 additional arguments: EQUATION can be the formula to apply. If this
9139 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9140 used to speed-up recursive calls by by-passing unnecessary aligns.
9141 SUPPRESS-CONST suppresses the interpretation of constants in the
9142 formula, assuming that this has been done already outside the function.
9143 SUPPRESS-STORE means the formula should not be stored, either because
9144 it is already stored, or because it is a modified equation that should
9145 not overwrite the stored one."
9146 (interactive "P")
9147 (org-table-check-inside-data-field)
9148 (or suppress-analysis (org-table-get-specials))
9149 (if (equal arg '(16))
9150 (let ((eq (org-table-current-field-formula)))
9151 (or eq (error "No equation active for current field"))
9152 (org-table-get-field nil eq)
9153 (org-table-align)
9154 (setq org-table-may-need-update t))
9155 (let* (fields
9156 (ndown (if (integerp arg) arg 1))
9157 (org-table-automatic-realign nil)
9158 (case-fold-search nil)
9159 (down (> ndown 1))
9160 (formula (if (and equation suppress-store)
9161 equation
9162 (org-table-get-formula equation (equal arg '(4)))))
9163 (n0 (org-table-current-column))
9164 (modes (copy-sequence org-calc-default-modes))
9165 (numbers nil) ; was a variable, now fixed default
9166 (keep-empty nil)
9167 n form form0 bw fmt x ev orig c lispp literal)
9168 ;; Parse the format string. Since we have a lot of modes, this is
9169 ;; a lot of work. However, I think calc still uses most of the time.
9170 (if (string-match ";" formula)
9171 (let ((tmp (org-split-string formula ";")))
9172 (setq formula (car tmp)
9173 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9174 (nth 1 tmp)))
9175 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9176 (setq c (string-to-char (match-string 1 fmt))
9177 n (string-to-number (match-string 2 fmt)))
9178 (if (= c ?p)
9179 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9180 (setq modes (org-set-calc-mode
9181 'calc-float-format
9182 (list (cdr (assoc c '((?n . float) (?f . fix)
9183 (?s . sci) (?e . eng))))
9184 n))))
9185 (setq fmt (replace-match "" t t fmt)))
9186 (if (string-match "[NT]" fmt)
9187 (setq numbers (equal (match-string 0 fmt) "N")
9188 fmt (replace-match "" t t fmt)))
9189 (if (string-match "L" fmt)
9190 (setq literal t
9191 fmt (replace-match "" t t fmt)))
9192 (if (string-match "E" fmt)
9193 (setq keep-empty t
9194 fmt (replace-match "" t t fmt)))
9195 (while (string-match "[DRFS]" fmt)
9196 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9197 (setq fmt (replace-match "" t t fmt)))
9198 (unless (string-match "\\S-" fmt)
9199 (setq fmt nil))))
9200 (if (and (not suppress-const) org-table-formula-use-constants)
9201 (setq formula (org-table-formula-substitute-names formula)))
9202 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9203 (while (> ndown 0)
9204 (setq fields (org-split-string
9205 (org-no-properties
9206 (buffer-substring (point-at-bol) (point-at-eol)))
9207 " *| *"))
9208 (if (eq numbers t)
9209 (setq fields (mapcar
9210 (lambda (x) (number-to-string (string-to-number x)))
9211 fields)))
9212 (setq ndown (1- ndown))
9213 (setq form (copy-sequence formula)
9214 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9215 (if (and lispp literal) (setq lispp 'literal))
9216 ;; Check for old vertical references
9217 (setq form (org-rewrite-old-row-references form))
9218 ;; Insert complex ranges
9219 (while (string-match org-table-range-regexp form)
9220 (setq form
9221 (replace-match
9222 (save-match-data
9223 (org-table-make-reference
9224 (org-table-get-range (match-string 0 form) nil n0)
9225 keep-empty numbers lispp))
9226 t t form)))
9227 ;; Insert simple ranges
9228 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
9229 (setq form
9230 (replace-match
9231 (save-match-data
9232 (org-table-make-reference
9233 (org-sublist
9234 fields (string-to-number (match-string 1 form))
9235 (string-to-number (match-string 2 form)))
9236 keep-empty numbers lispp))
9237 t t form)))
9238 (setq form0 form)
9239 ;; Insert the references to fields in same row
9240 (while (string-match "\\$\\([0-9]+\\)" form)
9241 (setq n (string-to-number (match-string 1 form))
9242 x (nth (1- (if (= n 0) n0 n)) fields))
9243 (unless x (error "Invalid field specifier \"%s\""
9244 (match-string 0 form)))
9245 (setq form (replace-match
9246 (save-match-data
9247 (org-table-make-reference x nil numbers lispp))
9248 t t form)))
9250 (if lispp
9251 (setq ev (condition-case nil
9252 (eval (eval (read form)))
9253 (error "#ERROR"))
9254 ev (if (numberp ev) (number-to-string ev) ev))
9255 (or (fboundp 'calc-eval)
9256 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
9257 (setq ev (calc-eval (cons form modes)
9258 (if numbers 'num))))
9260 (when org-table-formula-debug
9261 (with-output-to-temp-buffer "*Substitution History*"
9262 (princ (format "Substitution history of formula
9263 Orig: %s
9264 $xyz-> %s
9265 @r$c-> %s
9266 $1-> %s\n" orig formula form0 form))
9267 (if (listp ev)
9268 (princ (format " %s^\nError: %s"
9269 (make-string (car ev) ?\-) (nth 1 ev)))
9270 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9271 ev (or fmt "NONE")
9272 (if fmt (format fmt (string-to-number ev)) ev)))))
9273 (setq bw (get-buffer-window "*Substitution History*"))
9274 (shrink-window-if-larger-than-buffer bw)
9275 (unless (and (interactive-p) (not ndown))
9276 (unless (let (inhibit-redisplay)
9277 (y-or-n-p "Debugging Formula. Continue to next? "))
9278 (org-table-align)
9279 (error "Abort"))
9280 (delete-window bw)
9281 (message "")))
9282 (if (listp ev) (setq fmt nil ev "#ERROR"))
9283 (org-table-justify-field-maybe
9284 (if fmt (format fmt (string-to-number ev)) ev))
9285 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9286 (call-interactively 'org-return)
9287 (setq ndown 0)))
9288 (and down (org-table-maybe-recalculate-line))
9289 (or suppress-align (and org-table-may-need-update
9290 (org-table-align))))))
9292 (defun org-table-put-field-property (prop value)
9293 (save-excursion
9294 (put-text-property (progn (skip-chars-backward "^|") (point))
9295 (progn (skip-chars-forward "^|") (point))
9296 prop value)))
9298 (defun org-table-get-range (desc &optional tbeg col highlight)
9299 "Get a calc vector from a column, accorting to descriptor DESC.
9300 Optional arguments TBEG and COL can give the beginning of the table and
9301 the current column, to avoid unnecessary parsing.
9302 HIGHLIGHT means, just highlight the range."
9303 (if (not (equal (string-to-char desc) ?@))
9304 (setq desc (concat "@" desc)))
9305 (save-excursion
9306 (or tbeg (setq tbeg (org-table-begin)))
9307 (or col (setq col (org-table-current-column)))
9308 (let ((thisline (org-current-line))
9309 beg end c1 c2 r1 r2 rangep tmp)
9310 (unless (string-match org-table-range-regexp desc)
9311 (error "Invalid table range specifier `%s'" desc))
9312 (setq rangep (match-end 3)
9313 r1 (and (match-end 1) (match-string 1 desc))
9314 r2 (and (match-end 4) (match-string 4 desc))
9315 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
9316 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
9318 (and c1 (setq c1 (+ (string-to-number c1)
9319 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
9320 (and c2 (setq c2 (+ (string-to-number c2)
9321 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
9322 (if (equal r1 "") (setq r1 nil))
9323 (if (equal r2 "") (setq r2 nil))
9324 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
9325 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
9326 ; (setq r2 (or r2 r1) c2 (or c2 c1))
9327 (if (not r1) (setq r1 thisline))
9328 (if (not r2) (setq r2 thisline))
9329 (if (not c1) (setq c1 col))
9330 (if (not c2) (setq c2 col))
9331 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
9332 ;; just one field
9333 (progn
9334 (goto-line r1)
9335 (while (not (looking-at org-table-dataline-regexp))
9336 (beginning-of-line 2))
9337 (prog1 (org-trim (org-table-get-field c1))
9338 (if highlight (org-table-highlight-rectangle (point) (point)))))
9339 ;; A range, return a vector
9340 ;; First sort the numbers to get a regular ractangle
9341 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
9342 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
9343 (goto-line r1)
9344 (while (not (looking-at org-table-dataline-regexp))
9345 (beginning-of-line 2))
9346 (org-table-goto-column c1)
9347 (setq beg (point))
9348 (goto-line r2)
9349 (while (not (looking-at org-table-dataline-regexp))
9350 (beginning-of-line 0))
9351 (org-table-goto-column c2)
9352 (setq end (point))
9353 (if highlight
9354 (org-table-highlight-rectangle
9355 beg (progn (skip-chars-forward "^|\n") (point))))
9356 ;; return string representation of calc vector
9357 (mapcar 'org-trim
9358 (apply 'append (org-table-copy-region beg end)))))))
9360 (defun org-table-get-descriptor-line (desc &optional cline bline table)
9361 "Analyze descriptor DESC and retrieve the corresponding line number.
9362 The cursor is currently in line CLINE, the table begins in line BLINE,
9363 and TABLE is a vector with line types."
9364 (if (string-match "^[0-9]+$" desc)
9365 (aref org-table-dlines (string-to-number desc))
9366 (setq cline (or cline (org-current-line))
9367 bline (or bline org-table-current-begin-line)
9368 table (or table org-table-current-line-types))
9369 (if (or
9370 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
9371 ;; 1 2 3 4 5 6
9372 (and (not (match-end 3)) (not (match-end 6)))
9373 (and (match-end 3) (match-end 6) (not (match-end 5))))
9374 (error "invalid row descriptor `%s'" desc))
9375 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
9376 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
9377 (odir (and (match-end 5) (match-string 5 desc)))
9378 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
9379 (i (- cline bline))
9380 (rel (and (match-end 6)
9381 (or (and (match-end 1) (not (match-end 3)))
9382 (match-end 5)))))
9383 (if (and hn (not hdir))
9384 (progn
9385 (setq i 0 hdir "+")
9386 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
9387 (if (and (not hn) on (not odir))
9388 (error "should never happen");;(aref org-table-dlines on)
9389 (if (and hn (> hn 0))
9390 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
9391 (if on
9392 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
9393 (+ bline i)))))
9395 (defun org-find-row-type (table i type backwards relative n)
9396 (let ((l (length table)))
9397 (while (> n 0)
9398 (while (and (setq i (+ i (if backwards -1 1)))
9399 (>= i 0) (< i l)
9400 (not (eq (aref table i) type))
9401 (if (and relative (eq (aref table i) 'hline))
9402 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
9403 t)))
9404 (setq n (1- n)))
9405 (if (or (< i 0) (>= i l))
9406 (error "Row descriptior leads outside table")
9407 i)))
9409 (defun org-rewrite-old-row-references (s)
9410 (if (string-match "&[-+0-9I]" s)
9411 (error "Formula contains old &row reference, please rewrite using @-syntax")
9414 (defun org-table-make-reference (elements keep-empty numbers lispp)
9415 "Convert list ELEMENTS to something appropriate to insert into formula.
9416 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
9417 NUMBERS indicates that everything should be converted to numbers.
9418 LISPP means to return something appropriate for a Lisp list."
9419 (if (stringp elements) ; just a single val
9420 (if lispp
9421 (if (eq lispp 'literal)
9422 elements
9423 (prin1-to-string (if numbers (string-to-number elements) elements)))
9424 (if (equal elements "") (setq elements "0"))
9425 (if numbers (number-to-string (string-to-number elements)) elements))
9426 (unless keep-empty
9427 (setq elements
9428 (delq nil
9429 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
9430 elements))))
9431 (setq elements (or elements '("0")))
9432 (if lispp
9433 (mapconcat
9434 (lambda (x)
9435 (if (eq lispp 'literal)
9437 (prin1-to-string (if numbers (string-to-number x) x))))
9438 elements " ")
9439 (concat "[" (mapconcat
9440 (lambda (x)
9441 (if numbers (number-to-string (string-to-number x)) x))
9442 elements
9443 ",") "]"))))
9445 (defun org-table-recalculate (&optional all noalign)
9446 "Recalculate the current table line by applying all stored formulas.
9447 With prefix arg ALL, do this for all lines in the table."
9448 (interactive "P")
9449 (or (memq this-command org-recalc-commands)
9450 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9451 (unless (org-at-table-p) (error "Not at a table"))
9452 (if (equal all '(16))
9453 (org-table-iterate)
9454 (org-table-get-specials)
9455 (let* ((eqlist (sort (org-table-get-stored-formulas)
9456 (lambda (a b) (string< (car a) (car b)))))
9457 (inhibit-redisplay (not debug-on-error))
9458 (line-re org-table-dataline-regexp)
9459 (thisline (org-current-line))
9460 (thiscol (org-table-current-column))
9461 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
9462 ;; Insert constants in all formulas
9463 (setq eqlist
9464 (mapcar (lambda (x)
9465 (setcdr x (org-table-formula-substitute-names (cdr x)))
9467 eqlist))
9468 ;; Split the equation list
9469 (while (setq eq (pop eqlist))
9470 (if (<= (string-to-char (car eq)) ?9)
9471 (push eq eqlnum)
9472 (push eq eqlname)))
9473 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9474 (if all
9475 (progn
9476 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9477 (goto-char (setq beg (org-table-begin)))
9478 (if (re-search-forward org-table-calculate-mark-regexp end t)
9479 ;; This is a table with marked lines, compute selected lines
9480 (setq line-re org-table-recalculate-regexp)
9481 ;; Move forward to the first non-header line
9482 (if (and (re-search-forward org-table-dataline-regexp end t)
9483 (re-search-forward org-table-hline-regexp end t)
9484 (re-search-forward org-table-dataline-regexp end t))
9485 (setq beg (match-beginning 0))
9486 nil))) ;; just leave beg where it is
9487 (setq beg (point-at-bol)
9488 end (move-marker (make-marker) (1+ (point-at-eol)))))
9489 (goto-char beg)
9490 (and all (message "Re-applying formulas to full table..."))
9492 ;; First find the named fields, and mark them untouchanble
9493 (remove-text-properties beg end '(org-untouchable t))
9494 (while (setq eq (pop eqlname))
9495 (setq name (car eq)
9496 a (assoc name org-table-named-field-locations))
9497 (and (not a)
9498 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
9499 (setq a (list name
9500 (aref org-table-dlines
9501 (string-to-number (match-string 1 name)))
9502 (string-to-number (match-string 2 name)))))
9503 (when (and a (or all (equal (nth 1 a) thisline)))
9504 (message "Re-applying formula to field: %s" name)
9505 (goto-line (nth 1 a))
9506 (org-table-goto-column (nth 2 a))
9507 (push (append a (list (cdr eq))) eqlname1)
9508 (org-table-put-field-property :org-untouchable t)))
9510 ;; Now evauluate the column formulas, but skip fields covered by
9511 ;; field formulas
9512 (goto-char beg)
9513 (while (re-search-forward line-re end t)
9514 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
9515 ;; Unprotected line, recalculate
9516 (and all (message "Re-applying formulas to full table...(line %d)"
9517 (setq cnt (1+ cnt))))
9518 (setq org-last-recalc-line (org-current-line))
9519 (setq eql eqlnum)
9520 (while (setq entry (pop eql))
9521 (goto-line org-last-recalc-line)
9522 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9523 (unless (get-text-property (point) :org-untouchable)
9524 (org-table-eval-formula nil (cdr entry)
9525 'noalign 'nocst 'nostore 'noanalysis)))))
9527 ;; Now evaluate the field formulas
9528 (while (setq eq (pop eqlname1))
9529 (message "Re-applying formula to field: %s" (car eq))
9530 (goto-line (nth 1 eq))
9531 (org-table-goto-column (nth 2 eq))
9532 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
9533 'nostore 'noanalysis))
9535 (goto-line thisline)
9536 (org-table-goto-column thiscol)
9537 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
9538 (or noalign (and org-table-may-need-update (org-table-align))
9539 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9541 ;; back to initial position
9542 (message "Re-applying formulas...done")
9543 (goto-line thisline)
9544 (org-table-goto-column thiscol)
9545 (or noalign (and org-table-may-need-update (org-table-align))
9546 (and all (message "Re-applying formulas...done"))))))
9548 (defun org-table-iterate (&optional arg)
9549 "Recalculate the table until it does not change anymore."
9550 (interactive "P")
9551 (let ((imax (if arg (prefix-numeric-value arg) 10))
9552 (i 0)
9553 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
9554 thistbl)
9555 (catch 'exit
9556 (while (< i imax)
9557 (setq i (1+ i))
9558 (org-table-recalculate 'all)
9559 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
9560 (if (not (string= lasttbl thistbl))
9561 (setq lasttbl thistbl)
9562 (if (> i 1)
9563 (message "Convergence after %d iterations" i)
9564 (message "Table was already stable"))
9565 (throw 'exit t)))
9566 (error "No convergence after %d iterations" i))))
9568 (defun org-table-formula-substitute-names (f)
9569 "Replace $const with values in string F."
9570 (let ((start 0) a (f1 f))
9571 ;; First, check for column names
9572 (while (setq start (string-match org-table-column-name-regexp f start))
9573 (setq start (1+ start))
9574 (setq a (assoc (match-string 1 f) org-table-column-names))
9575 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9576 ;; Parameters and constants
9577 (setq start 0)
9578 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
9579 (setq start (1+ start))
9580 (if (setq a (save-match-data
9581 (org-table-get-constant (match-string 1 f))))
9582 (setq f (replace-match (concat "(" a ")") t t f))))
9583 (if org-table-formula-debug
9584 (put-text-property 0 (length f) :orig-formula f1 f))
9587 (defun org-table-get-constant (const)
9588 "Find the value for a parameter or constant in a formula.
9589 Parameters get priority."
9590 (or (cdr (assoc const org-table-local-parameters))
9591 (cdr (assoc const org-table-formula-constants-local))
9592 (cdr (assoc const org-table-formula-constants))
9593 (and (fboundp 'constants-get) (constants-get const))
9594 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
9595 (org-entry-get nil (substring const 5) 'inherit))
9596 "#UNDEFINED_NAME"))
9598 (defvar org-table-fedit-map
9599 (let ((map (make-sparse-keymap)))
9600 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
9601 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
9602 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
9603 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
9604 (org-defkey map "\C-c?" 'org-table-show-reference)
9605 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
9606 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
9607 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
9608 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
9609 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
9610 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
9611 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
9612 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
9613 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
9614 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
9615 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
9616 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
9617 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
9618 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
9619 map))
9621 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
9622 '("Edit-Formulas"
9623 ["Finish and Install" org-table-fedit-finish t]
9624 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
9625 ["Abort" org-table-fedit-abort t]
9626 "--"
9627 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
9628 ["Complete Lisp Symbol" lisp-complete-symbol t]
9629 "--"
9630 "Shift Reference at Point"
9631 ["Up" org-table-fedit-ref-up t]
9632 ["Down" org-table-fedit-ref-down t]
9633 ["Left" org-table-fedit-ref-left t]
9634 ["Right" org-table-fedit-ref-right t]
9636 "Change Test Row for Column Formulas"
9637 ["Up" org-table-fedit-line-up t]
9638 ["Down" org-table-fedit-line-down t]
9639 "--"
9640 ["Scroll Table Window" org-table-fedit-scroll t]
9641 ["Scroll Table Window down" org-table-fedit-scroll-down t]
9642 ["Show Table Grid" org-table-fedit-toggle-coordinates
9643 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
9644 org-table-overlay-coordinates)]
9645 "--"
9646 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
9647 :style toggle :selected org-table-buffer-is-an]))
9649 (defvar org-pos)
9651 (defun org-table-edit-formulas ()
9652 "Edit the formulas of the current table in a separate buffer."
9653 (interactive)
9654 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
9655 (beginning-of-line 0))
9656 (unless (org-at-table-p) (error "Not at a table"))
9657 (org-table-get-specials)
9658 (let ((key (org-table-current-field-formula 'key 'noerror))
9659 (eql (sort (org-table-get-stored-formulas 'noerror)
9660 'org-table-formula-less-p))
9661 (pos (move-marker (make-marker) (point)))
9662 (startline 1)
9663 (wc (current-window-configuration))
9664 (titles '((column . "# Column Formulas\n")
9665 (field . "# Field Formulas\n")
9666 (named . "# Named Field Formulas\n")))
9667 entry s type title)
9668 (org-switch-to-buffer-other-window "*Edit Formulas*")
9669 (erase-buffer)
9670 ;; Keep global-font-lock-mode from turning on font-lock-mode
9671 (let ((font-lock-global-modes '(not fundamental-mode)))
9672 (fundamental-mode))
9673 (org-set-local 'font-lock-global-modes (list 'not major-mode))
9674 (org-set-local 'org-pos pos)
9675 (org-set-local 'org-window-configuration wc)
9676 (use-local-map org-table-fedit-map)
9677 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
9678 (easy-menu-add org-table-fedit-menu)
9679 (setq startline (org-current-line))
9680 (while (setq entry (pop eql))
9681 (setq type (cond
9682 ((equal (string-to-char (car entry)) ?@) 'field)
9683 ((string-match "^[0-9]" (car entry)) 'column)
9684 (t 'named)))
9685 (when (setq title (assq type titles))
9686 (or (bobp) (insert "\n"))
9687 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
9688 (setq titles (delq title titles)))
9689 (if (equal key (car entry)) (setq startline (org-current-line)))
9690 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
9691 (car entry) " = " (cdr entry) "\n"))
9692 (remove-text-properties 0 (length s) '(face nil) s)
9693 (insert s))
9694 (if (eq org-table-use-standard-references t)
9695 (org-table-fedit-toggle-ref-type))
9696 (goto-line startline)
9697 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
9699 (defun org-table-fedit-post-command ()
9700 (when (not (memq this-command '(lisp-complete-symbol)))
9701 (let ((win (selected-window)))
9702 (save-excursion
9703 (condition-case nil
9704 (org-table-show-reference)
9705 (error nil))
9706 (select-window win)))))
9708 (defun org-table-formula-to-user (s)
9709 "Convert a formula from internal to user representation."
9710 (if (eq org-table-use-standard-references t)
9711 (org-table-convert-refs-to-an s)
9714 (defun org-table-formula-from-user (s)
9715 "Convert a formula from user to internal representation."
9716 (if org-table-use-standard-references
9717 (org-table-convert-refs-to-rc s)
9720 (defun org-table-convert-refs-to-rc (s)
9721 "Convert spreadsheet references from AB7 to @7$28.
9722 Works for single references, but also for entire formulas and even the
9723 full TBLFM line."
9724 (let ((start 0))
9725 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
9726 (cond
9727 ((match-end 3)
9728 ;; format match, just advance
9729 (setq start (match-end 0)))
9730 ((and (> (match-beginning 0) 0)
9731 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
9732 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
9733 ;; 3.e5 or something like this.
9734 (setq start (match-end 0)))
9736 (setq start (match-beginning 0)
9737 s (replace-match
9738 (if (equal (match-string 2 s) "&")
9739 (format "$%d" (org-letters-to-number (match-string 1 s)))
9740 (format "@%d$%d"
9741 (string-to-number (match-string 2 s))
9742 (org-letters-to-number (match-string 1 s))))
9743 t t s)))))
9746 (defun org-table-convert-refs-to-an (s)
9747 "Convert spreadsheet references from to @7$28 to AB7.
9748 Works for single references, but also for entire formulas and even the
9749 full TBLFM line."
9750 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
9751 (setq s (replace-match
9752 (format "%s%d"
9753 (org-number-to-letters
9754 (string-to-number (match-string 2 s)))
9755 (string-to-number (match-string 1 s)))
9756 t t s)))
9757 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
9758 (setq s (replace-match (concat "\\1"
9759 (org-number-to-letters
9760 (string-to-number (match-string 2 s))) "&")
9761 t nil s)))
9764 (defun org-letters-to-number (s)
9765 "Convert a base 26 number represented by letters into an integer.
9766 For example: AB -> 28."
9767 (let ((n 0))
9768 (setq s (upcase s))
9769 (while (> (length s) 0)
9770 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
9771 s (substring s 1)))
9774 (defun org-number-to-letters (n)
9775 "Convert an integer into a base 26 number represented by letters.
9776 For example: 28 -> AB."
9777 (let ((s ""))
9778 (while (> n 0)
9779 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
9780 n (/ (1- n) 26)))
9783 (defun org-table-fedit-convert-buffer (function)
9784 "Convert all references in this buffer, using FUNTION."
9785 (let ((line (org-current-line)))
9786 (goto-char (point-min))
9787 (while (not (eobp))
9788 (insert (funcall function (buffer-substring (point) (point-at-eol))))
9789 (delete-region (point) (point-at-eol))
9790 (or (eobp) (forward-char 1)))
9791 (goto-line line)))
9793 (defun org-table-fedit-toggle-ref-type ()
9794 "Convert all references in the buffer from B3 to @3$2 and back."
9795 (interactive)
9796 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
9797 (org-table-fedit-convert-buffer
9798 (if org-table-buffer-is-an
9799 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
9800 (message "Reference type switched to %s"
9801 (if org-table-buffer-is-an "A1 etc" "@row$column")))
9803 (defun org-table-fedit-ref-up ()
9804 "Shift the reference at point one row/hline up."
9805 (interactive)
9806 (org-table-fedit-shift-reference 'up))
9807 (defun org-table-fedit-ref-down ()
9808 "Shift the reference at point one row/hline down."
9809 (interactive)
9810 (org-table-fedit-shift-reference 'down))
9811 (defun org-table-fedit-ref-left ()
9812 "Shift the reference at point one field to the left."
9813 (interactive)
9814 (org-table-fedit-shift-reference 'left))
9815 (defun org-table-fedit-ref-right ()
9816 "Shift the reference at point one field to the right."
9817 (interactive)
9818 (org-table-fedit-shift-reference 'right))
9820 (defun org-table-fedit-shift-reference (dir)
9821 (cond
9822 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
9823 (if (memq dir '(left right))
9824 (org-rematch-and-replace 1 (eq dir 'left))
9825 (error "Cannot shift reference in this direction")))
9826 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
9827 ;; A B3-like reference
9828 (if (memq dir '(up down))
9829 (org-rematch-and-replace 2 (eq dir 'up))
9830 (org-rematch-and-replace 1 (eq dir 'left))))
9831 ((org-at-regexp-p
9832 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
9833 ;; An internal reference
9834 (if (memq dir '(up down))
9835 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
9836 (org-rematch-and-replace 5 (eq dir 'left))))))
9838 (defun org-rematch-and-replace (n &optional decr hline)
9839 "Re-match the group N, and replace it with the shifted refrence."
9840 (or (match-end n) (error "Cannot shift reference in this direction"))
9841 (goto-char (match-beginning n))
9842 (and (looking-at (regexp-quote (match-string n)))
9843 (replace-match (org-shift-refpart (match-string 0) decr hline)
9844 t t)))
9846 (defun org-shift-refpart (ref &optional decr hline)
9847 "Shift a refrence part REF.
9848 If DECR is set, decrease the references row/column, else increase.
9849 If HLINE is set, this may be a hline reference, it certainly is not
9850 a translation reference."
9851 (save-match-data
9852 (let* ((sign (string-match "^[-+]" ref)) n)
9854 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
9855 (cond
9856 ((and hline (string-match "^I+" ref))
9857 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
9858 (setq n (+ n (if decr -1 1)))
9859 (if (= n 0) (setq n (+ n (if decr -1 1))))
9860 (if sign
9861 (setq sign (if (< n 0) "-" "+") n (abs n))
9862 (setq n (max 1 n)))
9863 (concat sign (make-string n ?I)))
9865 ((string-match "^[0-9]+" ref)
9866 (setq n (string-to-number (concat sign ref)))
9867 (setq n (+ n (if decr -1 1)))
9868 (if sign
9869 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
9870 (number-to-string (max 1 n))))
9872 ((string-match "^[a-zA-Z]+" ref)
9873 (org-number-to-letters
9874 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
9876 (t (error "Cannot shift reference"))))))
9878 (defun org-table-fedit-toggle-coordinates ()
9879 "Toggle the display of coordinates in the refrenced table."
9880 (interactive)
9881 (let ((pos (marker-position org-pos)))
9882 (with-current-buffer (marker-buffer org-pos)
9883 (save-excursion
9884 (goto-char pos)
9885 (org-table-toggle-coordinate-overlays)))))
9887 (defun org-table-fedit-finish (&optional arg)
9888 "Parse the buffer for formula definitions and install them.
9889 With prefix ARG, apply the new formulas to the table."
9890 (interactive "P")
9891 (org-table-remove-rectangle-highlight)
9892 (if org-table-use-standard-references
9893 (progn
9894 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
9895 (setq org-table-buffer-is-an nil)))
9896 (let ((pos org-pos) eql var form)
9897 (goto-char (point-min))
9898 (while (re-search-forward
9899 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
9900 nil t)
9901 (setq var (if (match-end 2) (match-string 2) (match-string 1))
9902 form (match-string 3))
9903 (setq form (org-trim form))
9904 (when (not (equal form ""))
9905 (while (string-match "[ \t]*\n[ \t]*" form)
9906 (setq form (replace-match " " t t form)))
9907 (when (assoc var eql)
9908 (error "Double formulas for %s" var))
9909 (push (cons var form) eql)))
9910 (setq org-pos nil)
9911 (set-window-configuration org-window-configuration)
9912 (select-window (get-buffer-window (marker-buffer pos)))
9913 (goto-char pos)
9914 (unless (org-at-table-p)
9915 (error "Lost table position - cannot install formulae"))
9916 (org-table-store-formulas eql)
9917 (move-marker pos nil)
9918 (kill-buffer "*Edit Formulas*")
9919 (if arg
9920 (org-table-recalculate 'all)
9921 (message "New formulas installed - press C-u C-c C-c to apply."))))
9923 (defun org-table-fedit-abort ()
9924 "Abort editing formulas, without installing the changes."
9925 (interactive)
9926 (org-table-remove-rectangle-highlight)
9927 (let ((pos org-pos))
9928 (set-window-configuration org-window-configuration)
9929 (select-window (get-buffer-window (marker-buffer pos)))
9930 (goto-char pos)
9931 (move-marker pos nil)
9932 (message "Formula editing aborted without installing changes")))
9934 (defun org-table-fedit-lisp-indent ()
9935 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
9936 (interactive)
9937 (let ((pos (point)) beg end ind)
9938 (beginning-of-line 1)
9939 (cond
9940 ((looking-at "[ \t]")
9941 (goto-char pos)
9942 (call-interactively 'lisp-indent-line))
9943 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
9944 ((not (fboundp 'pp-buffer))
9945 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
9946 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
9947 (goto-char (- (match-end 0) 2))
9948 (setq beg (point))
9949 (setq ind (make-string (current-column) ?\ ))
9950 (condition-case nil (forward-sexp 1)
9951 (error
9952 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
9953 (setq end (point))
9954 (save-restriction
9955 (narrow-to-region beg end)
9956 (if (eq last-command this-command)
9957 (progn
9958 (goto-char (point-min))
9959 (setq this-command nil)
9960 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
9961 (replace-match " ")))
9962 (pp-buffer)
9963 (untabify (point-min) (point-max))
9964 (goto-char (1+ (point-min)))
9965 (while (re-search-forward "^." nil t)
9966 (beginning-of-line 1)
9967 (insert ind))
9968 (goto-char (point-max))
9969 (backward-delete-char 1)))
9970 (goto-char beg))
9971 (t nil))))
9973 (defvar org-show-positions nil)
9975 (defun org-table-show-reference (&optional local)
9976 "Show the location/value of the $ expression at point."
9977 (interactive)
9978 (org-table-remove-rectangle-highlight)
9979 (catch 'exit
9980 (let ((pos (if local (point) org-pos))
9981 (face2 'highlight)
9982 (org-inhibit-highlight-removal t)
9983 (win (selected-window))
9984 (org-show-positions nil)
9985 var name e what match dest)
9986 (if local (org-table-get-specials))
9987 (setq what (cond
9988 ((or (org-at-regexp-p org-table-range-regexp2)
9989 (org-at-regexp-p org-table-translate-regexp)
9990 (org-at-regexp-p org-table-range-regexp))
9991 (setq match
9992 (save-match-data
9993 (org-table-convert-refs-to-rc (match-string 0))))
9994 'range)
9995 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
9996 ((org-at-regexp-p "\\$[0-9]+") 'column)
9997 ((not local) nil)
9998 (t (error "No reference at point")))
9999 match (and what (or match (match-string 0))))
10000 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10001 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10002 'secondary-selection))
10003 (org-add-hook 'before-change-functions
10004 'org-table-remove-rectangle-highlight)
10005 (if (eq what 'name) (setq var (substring match 1)))
10006 (when (eq what 'range)
10007 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10008 (setq match (org-table-formula-substitute-names match)))
10009 (unless local
10010 (save-excursion
10011 (end-of-line 1)
10012 (re-search-backward "^\\S-" nil t)
10013 (beginning-of-line 1)
10014 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10015 (setq dest
10016 (save-match-data
10017 (org-table-convert-refs-to-rc (match-string 1))))
10018 (org-table-add-rectangle-overlay
10019 (match-beginning 1) (match-end 1) face2))))
10020 (if (and (markerp pos) (marker-buffer pos))
10021 (if (get-buffer-window (marker-buffer pos))
10022 (select-window (get-buffer-window (marker-buffer pos)))
10023 (org-switch-to-buffer-other-window (get-buffer-window
10024 (marker-buffer pos)))))
10025 (goto-char pos)
10026 (org-table-force-dataline)
10027 (when dest
10028 (setq name (substring dest 1))
10029 (cond
10030 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10031 (setq e (assoc name org-table-named-field-locations))
10032 (goto-line (nth 1 e))
10033 (org-table-goto-column (nth 2 e)))
10034 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10035 (let ((l (string-to-number (match-string 1 dest)))
10036 (c (string-to-number (match-string 2 dest))))
10037 (goto-line (aref org-table-dlines l))
10038 (org-table-goto-column c)))
10039 (t (org-table-goto-column (string-to-number name))))
10040 (move-marker pos (point))
10041 (org-table-highlight-rectangle nil nil face2))
10042 (cond
10043 ((equal dest match))
10044 ((not match))
10045 ((eq what 'range)
10046 (condition-case nil
10047 (save-excursion
10048 (org-table-get-range match nil nil 'highlight))
10049 (error nil)))
10050 ((setq e (assoc var org-table-named-field-locations))
10051 (goto-line (nth 1 e))
10052 (org-table-goto-column (nth 2 e))
10053 (org-table-highlight-rectangle (point) (point))
10054 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10055 ((setq e (assoc var org-table-column-names))
10056 (org-table-goto-column (string-to-number (cdr e)))
10057 (org-table-highlight-rectangle (point) (point))
10058 (goto-char (org-table-begin))
10059 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10060 (org-table-end) t)
10061 (progn
10062 (goto-char (match-beginning 1))
10063 (org-table-highlight-rectangle)
10064 (message "Named column (column %s)" (cdr e)))
10065 (error "Column name not found")))
10066 ((eq what 'column)
10067 ;; column number
10068 (org-table-goto-column (string-to-number (substring match 1)))
10069 (org-table-highlight-rectangle (point) (point))
10070 (message "Column %s" (substring match 1)))
10071 ((setq e (assoc var org-table-local-parameters))
10072 (goto-char (org-table-begin))
10073 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10074 (progn
10075 (goto-char (match-beginning 1))
10076 (org-table-highlight-rectangle)
10077 (message "Local parameter."))
10078 (error "Parameter not found")))
10080 (cond
10081 ((not var) (error "No reference at point"))
10082 ((setq e (assoc var org-table-formula-constants-local))
10083 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10084 var (cdr e)))
10085 ((setq e (assoc var org-table-formula-constants))
10086 (message "Constant: $%s=%s in `org-table-formula-constants'."
10087 var (cdr e)))
10088 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10089 (message "Constant: $%s=%s, from `constants.el'%s."
10090 var e (format " (%s units)" constants-unit-system)))
10091 (t (error "Undefined name $%s" var)))))
10092 (goto-char pos)
10093 (when (and org-show-positions
10094 (not (memq this-command '(org-table-fedit-scroll
10095 org-table-fedit-scroll-down))))
10096 (push pos org-show-positions)
10097 (push org-table-current-begin-pos org-show-positions)
10098 (let ((min (apply 'min org-show-positions))
10099 (max (apply 'max org-show-positions)))
10100 (goto-char min) (recenter 0)
10101 (goto-char max)
10102 (or (pos-visible-in-window-p max) (recenter -1))))
10103 (select-window win))))
10105 (defun org-table-force-dataline ()
10106 "Make sure the cursor is in a dataline in a table."
10107 (unless (save-excursion
10108 (beginning-of-line 1)
10109 (looking-at org-table-dataline-regexp))
10110 (let* ((re org-table-dataline-regexp)
10111 (p1 (save-excursion (re-search-forward re nil 'move)))
10112 (p2 (save-excursion (re-search-backward re nil 'move))))
10113 (cond ((and p1 p2)
10114 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10115 p1 p2)))
10116 ((or p1 p2) (goto-char (or p1 p2)))
10117 (t (error "No table dataline around here"))))))
10119 (defun org-table-fedit-line-up ()
10120 "Move cursor one line up in the window showing the table."
10121 (interactive)
10122 (org-table-fedit-move 'previous-line))
10124 (defun org-table-fedit-line-down ()
10125 "Move cursor one line down in the window showing the table."
10126 (interactive)
10127 (org-table-fedit-move 'next-line))
10129 (defun org-table-fedit-move (command)
10130 "Move the cursor in the window shoinw the table.
10131 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10132 (let ((org-table-allow-automatic-line-recalculation nil)
10133 (pos org-pos) (win (selected-window)) p)
10134 (select-window (get-buffer-window (marker-buffer org-pos)))
10135 (setq p (point))
10136 (call-interactively command)
10137 (while (and (org-at-table-p)
10138 (org-at-table-hline-p))
10139 (call-interactively command))
10140 (or (org-at-table-p) (goto-char p))
10141 (move-marker pos (point))
10142 (select-window win)))
10144 (defun org-table-fedit-scroll (N)
10145 (interactive "p")
10146 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10147 (scroll-other-window N)))
10149 (defun org-table-fedit-scroll-down (N)
10150 (interactive "p")
10151 (org-table-fedit-scroll (- N)))
10153 (defvar org-table-rectangle-overlays nil)
10155 (defun org-table-add-rectangle-overlay (beg end &optional face)
10156 "Add a new overlay."
10157 (let ((ov (org-make-overlay beg end)))
10158 (org-overlay-put ov 'face (or face 'secondary-selection))
10159 (push ov org-table-rectangle-overlays)))
10161 (defun org-table-highlight-rectangle (&optional beg end face)
10162 "Highlight rectangular region in a table."
10163 (setq beg (or beg (point)) end (or end (point)))
10164 (let ((b (min beg end))
10165 (e (max beg end))
10166 l1 c1 l2 c2 tmp)
10167 (and (boundp 'org-show-positions)
10168 (setq org-show-positions (cons b (cons e org-show-positions))))
10169 (goto-char (min beg end))
10170 (setq l1 (org-current-line)
10171 c1 (org-table-current-column))
10172 (goto-char (max beg end))
10173 (setq l2 (org-current-line)
10174 c2 (org-table-current-column))
10175 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10176 (goto-line l1)
10177 (beginning-of-line 1)
10178 (loop for line from l1 to l2 do
10179 (when (looking-at org-table-dataline-regexp)
10180 (org-table-goto-column c1)
10181 (skip-chars-backward "^|\n") (setq beg (point))
10182 (org-table-goto-column c2)
10183 (skip-chars-forward "^|\n") (setq end (point))
10184 (org-table-add-rectangle-overlay beg end face))
10185 (beginning-of-line 2))
10186 (goto-char b))
10187 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10189 (defun org-table-remove-rectangle-highlight (&rest ignore)
10190 "Remove the rectangle overlays."
10191 (unless org-inhibit-highlight-removal
10192 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10193 (mapc 'org-delete-overlay org-table-rectangle-overlays)
10194 (setq org-table-rectangle-overlays nil)))
10196 (defvar org-table-coordinate-overlays nil
10197 "Collects the cooordinate grid overlays, so that they can be removed.")
10198 (make-variable-buffer-local 'org-table-coordinate-overlays)
10200 (defun org-table-overlay-coordinates ()
10201 "Add overlays to the table at point, to show row/column coordinates."
10202 (interactive)
10203 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10204 (setq org-table-coordinate-overlays nil)
10205 (save-excursion
10206 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10207 (goto-char (org-table-begin))
10208 (while (org-at-table-p)
10209 (setq eol (point-at-eol))
10210 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10211 (push ov org-table-coordinate-overlays)
10212 (setq hline (looking-at org-table-hline-regexp))
10213 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10214 (format "%4d" (setq id (1+ id)))))
10215 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10216 (when hline
10217 (setq ic 0)
10218 (while (re-search-forward "[+|]\\(-+\\)" eol t)
10219 (setq beg (1+ (match-beginning 0))
10220 ic (1+ ic)
10221 s1 (concat "$" (int-to-string ic))
10222 s2 (org-number-to-letters ic)
10223 str (if (eq org-table-use-standard-references t) s2 s1))
10224 (setq ov (org-make-overlay beg (+ beg (length str))))
10225 (push ov org-table-coordinate-overlays)
10226 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10227 (beginning-of-line 2)))))
10229 (defun org-table-toggle-coordinate-overlays ()
10230 "Toggle the display of Row/Column numbers in tables."
10231 (interactive)
10232 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10233 (message "Row/Column number display turned %s"
10234 (if org-table-overlay-coordinates "on" "off"))
10235 (if (and (org-at-table-p) org-table-overlay-coordinates)
10236 (org-table-align))
10237 (unless org-table-overlay-coordinates
10238 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10239 (setq org-table-coordinate-overlays nil)))
10241 (defun org-table-toggle-formula-debugger ()
10242 "Toggle the formula debugger in tables."
10243 (interactive)
10244 (setq org-table-formula-debug (not org-table-formula-debug))
10245 (message "Formula debugging has been turned %s"
10246 (if org-table-formula-debug "on" "off")))
10248 ;;; The orgtbl minor mode
10250 ;; Define a minor mode which can be used in other modes in order to
10251 ;; integrate the org-mode table editor.
10253 ;; This is really a hack, because the org-mode table editor uses several
10254 ;; keys which normally belong to the major mode, for example the TAB and
10255 ;; RET keys. Here is how it works: The minor mode defines all the keys
10256 ;; necessary to operate the table editor, but wraps the commands into a
10257 ;; function which tests if the cursor is currently inside a table. If that
10258 ;; is the case, the table editor command is executed. However, when any of
10259 ;; those keys is used outside a table, the function uses `key-binding' to
10260 ;; look up if the key has an associated command in another currently active
10261 ;; keymap (minor modes, major mode, global), and executes that command.
10262 ;; There might be problems if any of the keys used by the table editor is
10263 ;; otherwise used as a prefix key.
10265 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10266 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10267 ;; addresses this by checking explicitly for both bindings.
10269 ;; The optimized version (see variable `orgtbl-optimized') takes over
10270 ;; all keys which are bound to `self-insert-command' in the *global map*.
10271 ;; Some modes bind other commands to simple characters, for example
10272 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10273 ;; active, this binding is ignored inside tables and replaced with a
10274 ;; modified self-insert.
10276 (defvar orgtbl-mode nil
10277 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10278 table editor in arbitrary modes.")
10279 (make-variable-buffer-local 'orgtbl-mode)
10281 (defvar orgtbl-mode-map (make-keymap)
10282 "Keymap for `orgtbl-mode'.")
10284 ;;;###autoload
10285 (defun turn-on-orgtbl ()
10286 "Unconditionally turn on `orgtbl-mode'."
10287 (orgtbl-mode 1))
10289 (defvar org-old-auto-fill-inhibit-regexp nil
10290 "Local variable used by `orgtbl-mode'")
10292 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
10293 "Matches a line belonging to an orgtbl.")
10295 (defconst orgtbl-extra-font-lock-keywords
10296 (list (list (concat "^" orgtbl-line-start-regexp ".*")
10297 0 (quote 'org-table) 'prepend))
10298 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
10300 ;;;###autoload
10301 (defun orgtbl-mode (&optional arg)
10302 "The `org-mode' table editor as a minor mode for use in other modes."
10303 (interactive)
10304 (if (org-mode-p)
10305 ;; Exit without error, in case some hook functions calls this
10306 ;; by accident in org-mode.
10307 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10308 (setq orgtbl-mode
10309 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10310 (if orgtbl-mode
10311 (progn
10312 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10313 ;; Make sure we are first in minor-mode-map-alist
10314 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10315 (and c (setq minor-mode-map-alist
10316 (cons c (delq c minor-mode-map-alist)))))
10317 (org-set-local (quote org-table-may-need-update) t)
10318 (org-add-hook 'before-change-functions 'org-before-change-function
10319 nil 'local)
10320 (org-set-local 'org-old-auto-fill-inhibit-regexp
10321 auto-fill-inhibit-regexp)
10322 (org-set-local 'auto-fill-inhibit-regexp
10323 (if auto-fill-inhibit-regexp
10324 (concat orgtbl-line-start-regexp "\\|"
10325 auto-fill-inhibit-regexp)
10326 orgtbl-line-start-regexp))
10327 (org-add-to-invisibility-spec '(org-cwidth))
10328 (when (fboundp 'font-lock-add-keywords)
10329 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
10330 (org-restart-font-lock))
10331 (easy-menu-add orgtbl-mode-menu)
10332 (run-hooks 'orgtbl-mode-hook))
10333 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10334 (org-cleanup-narrow-column-properties)
10335 (org-remove-from-invisibility-spec '(org-cwidth))
10336 (remove-hook 'before-change-functions 'org-before-change-function t)
10337 (when (fboundp 'font-lock-remove-keywords)
10338 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
10339 (org-restart-font-lock))
10340 (easy-menu-remove orgtbl-mode-menu)
10341 (force-mode-line-update 'all))))
10343 (defun org-cleanup-narrow-column-properties ()
10344 "Remove all properties related to narrow-column invisibility."
10345 (let ((s 1))
10346 (while (setq s (text-property-any s (point-max)
10347 'display org-narrow-column-arrow))
10348 (remove-text-properties s (1+ s) '(display t)))
10349 (setq s 1)
10350 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10351 (remove-text-properties s (1+ s) '(org-cwidth t)))
10352 (setq s 1)
10353 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10354 (remove-text-properties s (1+ s) '(invisible t)))))
10356 ;; Install it as a minor mode.
10357 (put 'orgtbl-mode :included t)
10358 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10359 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10361 (defun orgtbl-make-binding (fun n &rest keys)
10362 "Create a function for binding in the table minor mode.
10363 FUN is the command to call inside a table. N is used to create a unique
10364 command name. KEYS are keys that should be checked in for a command
10365 to execute outside of tables."
10366 (eval
10367 (list 'defun
10368 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10369 '(arg)
10370 (concat "In tables, run `" (symbol-name fun) "'.\n"
10371 "Outside of tables, run the binding of `"
10372 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10373 "'.")
10374 '(interactive "p")
10375 (list 'if
10376 '(org-at-table-p)
10377 (list 'call-interactively (list 'quote fun))
10378 (list 'let '(orgtbl-mode)
10379 (list 'call-interactively
10380 (append '(or)
10381 (mapcar (lambda (k)
10382 (list 'key-binding k))
10383 keys)
10384 '('orgtbl-error))))))))
10386 (defun orgtbl-error ()
10387 "Error when there is no default binding for a table key."
10388 (interactive)
10389 (error "This key is has no function outside tables"))
10391 (defun orgtbl-setup ()
10392 "Setup orgtbl keymaps."
10393 (let ((nfunc 0)
10394 (bindings
10395 (list
10396 '([(meta shift left)] org-table-delete-column)
10397 '([(meta left)] org-table-move-column-left)
10398 '([(meta right)] org-table-move-column-right)
10399 '([(meta shift right)] org-table-insert-column)
10400 '([(meta shift up)] org-table-kill-row)
10401 '([(meta shift down)] org-table-insert-row)
10402 '([(meta up)] org-table-move-row-up)
10403 '([(meta down)] org-table-move-row-down)
10404 '("\C-c\C-w" org-table-cut-region)
10405 '("\C-c\M-w" org-table-copy-region)
10406 '("\C-c\C-y" org-table-paste-rectangle)
10407 '("\C-c-" org-table-insert-hline)
10408 '("\C-c}" org-table-toggle-coordinate-overlays)
10409 '("\C-c{" org-table-toggle-formula-debugger)
10410 '("\C-m" org-table-next-row)
10411 '([(shift return)] org-table-copy-down)
10412 '("\C-c\C-q" org-table-wrap-region)
10413 '("\C-c?" org-table-field-info)
10414 '("\C-c " org-table-blank-field)
10415 '("\C-c+" org-table-sum)
10416 '("\C-c=" org-table-eval-formula)
10417 '("\C-c'" org-table-edit-formulas)
10418 '("\C-c`" org-table-edit-field)
10419 '("\C-c*" org-table-recalculate)
10420 '("\C-c|" org-table-create-or-convert-from-region)
10421 '("\C-c^" org-table-sort-lines)
10422 '([(control ?#)] org-table-rotate-recalc-marks)))
10423 elt key fun cmd)
10424 (while (setq elt (pop bindings))
10425 (setq nfunc (1+ nfunc))
10426 (setq key (org-key (car elt))
10427 fun (nth 1 elt)
10428 cmd (orgtbl-make-binding fun nfunc key))
10429 (org-defkey orgtbl-mode-map key cmd))
10431 ;; Special treatment needed for TAB and RET
10432 (org-defkey orgtbl-mode-map [(return)]
10433 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10434 (org-defkey orgtbl-mode-map "\C-m"
10435 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10437 (org-defkey orgtbl-mode-map [(tab)]
10438 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10439 (org-defkey orgtbl-mode-map "\C-i"
10440 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
10442 (org-defkey orgtbl-mode-map [(shift tab)]
10443 (orgtbl-make-binding 'org-table-previous-field 104
10444 [(shift tab)] [(tab)] "\C-i"))
10446 (org-defkey orgtbl-mode-map "\M-\C-m"
10447 (orgtbl-make-binding 'org-table-wrap-region 105
10448 "\M-\C-m" [(meta return)]))
10449 (org-defkey orgtbl-mode-map [(meta return)]
10450 (orgtbl-make-binding 'org-table-wrap-region 106
10451 [(meta return)] "\M-\C-m"))
10453 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
10454 (when orgtbl-optimized
10455 ;; If the user wants maximum table support, we need to hijack
10456 ;; some standard editing functions
10457 (org-remap orgtbl-mode-map
10458 'self-insert-command 'orgtbl-self-insert-command
10459 'delete-char 'org-delete-char
10460 'delete-backward-char 'org-delete-backward-char)
10461 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
10462 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10463 '("OrgTbl"
10464 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10465 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10466 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10467 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10468 "--"
10469 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10470 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10471 ["Copy Field from Above"
10472 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10473 "--"
10474 ("Column"
10475 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10476 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10477 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10478 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10479 ("Row"
10480 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10481 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10482 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10483 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10484 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10485 "--"
10486 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10487 ("Rectangle"
10488 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10489 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10490 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10491 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10492 "--"
10493 ("Radio tables"
10494 ["Insert table template" orgtbl-insert-radio-table
10495 (assq major-mode orgtbl-radio-table-templates)]
10496 ["Comment/uncomment table" orgtbl-toggle-comment t])
10497 "--"
10498 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10499 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10500 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10501 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10502 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10503 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
10504 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10505 ["Sum Column/Rectangle" org-table-sum
10506 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10507 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10508 ["Debug Formulas"
10509 org-table-toggle-formula-debugger :active (org-at-table-p)
10510 :keys "C-c {"
10511 :style toggle :selected org-table-formula-debug]
10512 ["Show Col/Row Numbers"
10513 org-table-toggle-coordinate-overlays :active (org-at-table-p)
10514 :keys "C-c }"
10515 :style toggle :selected org-table-overlay-coordinates]
10519 (defun orgtbl-ctrl-c-ctrl-c (arg)
10520 "If the cursor is inside a table, realign the table.
10521 It it is a table to be sent away to a receiver, do it.
10522 With prefix arg, also recompute table."
10523 (interactive "P")
10524 (let ((pos (point)) action)
10525 (save-excursion
10526 (beginning-of-line 1)
10527 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
10528 ((looking-at "[ \t]*|") pos)
10529 ((looking-at "#\\+TBLFM:") 'recalc))))
10530 (cond
10531 ((integerp action)
10532 (goto-char action)
10533 (org-table-maybe-eval-formula)
10534 (if arg
10535 (call-interactively 'org-table-recalculate)
10536 (org-table-maybe-recalculate-line))
10537 (call-interactively 'org-table-align)
10538 (orgtbl-send-table 'maybe))
10539 ((eq action 'recalc)
10540 (save-excursion
10541 (beginning-of-line 1)
10542 (skip-chars-backward " \r\n\t")
10543 (if (org-at-table-p)
10544 (org-call-with-arg 'org-table-recalculate t))))
10545 (t (let (orgtbl-mode)
10546 (call-interactively (key-binding "\C-c\C-c")))))))
10548 (defun orgtbl-tab (arg)
10549 "Justification and field motion for `orgtbl-mode'."
10550 (interactive "P")
10551 (if arg (org-table-edit-field t)
10552 (org-table-justify-field-maybe)
10553 (org-table-next-field)))
10555 (defun orgtbl-ret ()
10556 "Justification and field motion for `orgtbl-mode'."
10557 (interactive)
10558 (org-table-justify-field-maybe)
10559 (org-table-next-row))
10561 (defun orgtbl-self-insert-command (N)
10562 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10563 If the cursor is in a table looking at whitespace, the whitespace is
10564 overwritten, and the table is not marked as requiring realignment."
10565 (interactive "p")
10566 (if (and (org-at-table-p)
10568 (and org-table-auto-blank-field
10569 (member last-command
10570 '(orgtbl-hijacker-command-100
10571 orgtbl-hijacker-command-101
10572 orgtbl-hijacker-command-102
10573 orgtbl-hijacker-command-103
10574 orgtbl-hijacker-command-104
10575 orgtbl-hijacker-command-105))
10576 (org-table-blank-field))
10578 (eq N 1)
10579 (looking-at "[^|\n]* +|"))
10580 (let (org-table-may-need-update)
10581 (goto-char (1- (match-end 0)))
10582 (delete-backward-char 1)
10583 (goto-char (match-beginning 0))
10584 (self-insert-command N))
10585 (setq org-table-may-need-update t)
10586 (let (orgtbl-mode)
10587 (call-interactively (key-binding (vector last-input-event))))))
10589 (defun org-force-self-insert (N)
10590 "Needed to enforce self-insert under remapping."
10591 (interactive "p")
10592 (self-insert-command N))
10594 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
10595 "Regula expression matching exponentials as produced by calc.")
10597 (defvar org-table-clean-did-remove-column nil)
10599 (defun orgtbl-export (table target)
10600 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
10601 (lines (org-split-string table "[ \t]*\n[ \t]*"))
10602 org-table-last-alignment org-table-last-column-widths
10603 maxcol column)
10604 (if (not (fboundp func))
10605 (error "Cannot export orgtbl table to %s" target))
10606 (setq lines (org-table-clean-before-export lines))
10607 (setq table
10608 (mapcar
10609 (lambda (x)
10610 (if (string-match org-table-hline-regexp x)
10611 'hline
10612 (org-split-string (org-trim x) "\\s-*|\\s-*")))
10613 lines))
10614 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
10615 table)))
10616 (loop for i from (1- maxcol) downto 0 do
10617 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
10618 (setq column (delq nil column))
10619 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
10620 (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))
10621 (funcall func table nil)))
10623 (defun orgtbl-send-table (&optional maybe)
10624 "Send a tranformed version of this table to the receiver position.
10625 With argument MAYBE, fail quietly if no transformation is defined for
10626 this table."
10627 (interactive)
10628 (catch 'exit
10629 (unless (org-at-table-p) (error "Not at a table"))
10630 ;; when non-interactive, we assume align has just happened.
10631 (when (interactive-p) (org-table-align))
10632 (save-excursion
10633 (goto-char (org-table-begin))
10634 (beginning-of-line 0)
10635 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
10636 (if maybe
10637 (throw 'exit nil)
10638 (error "Don't know how to transform this table."))))
10639 (let* ((name (match-string 1))
10641 (transform (intern (match-string 2)))
10642 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
10643 (skip (plist-get params :skip))
10644 (skipcols (plist-get params :skipcols))
10645 (txt (buffer-substring-no-properties
10646 (org-table-begin) (org-table-end)))
10647 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
10648 (lines (org-table-clean-before-export lines))
10649 (i0 (if org-table-clean-did-remove-column 2 1))
10650 (table (mapcar
10651 (lambda (x)
10652 (if (string-match org-table-hline-regexp x)
10653 'hline
10654 (org-remove-by-index
10655 (org-split-string (org-trim x) "\\s-*|\\s-*")
10656 skipcols i0)))
10657 lines))
10658 (fun (if (= i0 2) 'cdr 'identity))
10659 (org-table-last-alignment
10660 (org-remove-by-index (funcall fun org-table-last-alignment)
10661 skipcols i0))
10662 (org-table-last-column-widths
10663 (org-remove-by-index (funcall fun org-table-last-column-widths)
10664 skipcols i0)))
10666 (unless (fboundp transform)
10667 (error "No such transformation function %s" transform))
10668 (setq txt (funcall transform table params))
10669 ;; Find the insertion place
10670 (save-excursion
10671 (goto-char (point-min))
10672 (unless (re-search-forward
10673 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
10674 (error "Don't know where to insert translated table"))
10675 (goto-char (match-beginning 0))
10676 (beginning-of-line 2)
10677 (setq beg (point))
10678 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
10679 (error "Cannot find end of insertion region"))
10680 (beginning-of-line 1)
10681 (delete-region beg (point))
10682 (goto-char beg)
10683 (insert txt "\n"))
10684 (message "Table converted and installed at receiver location"))))
10686 (defun org-remove-by-index (list indices &optional i0)
10687 "Remove the elements in LIST with indices in INDICES.
10688 First element has index 0, or I0 if given."
10689 (if (not indices)
10690 list
10691 (if (integerp indices) (setq indices (list indices)))
10692 (setq i0 (1- (or i0 0)))
10693 (delq :rm (mapcar (lambda (x)
10694 (setq i0 (1+ i0))
10695 (if (memq i0 indices) :rm x))
10696 list))))
10698 (defun orgtbl-toggle-comment ()
10699 "Comment or uncomment the orgtbl at point."
10700 (interactive)
10701 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
10702 (re2 (concat "^" orgtbl-line-start-regexp))
10703 (commented (save-excursion (beginning-of-line 1)
10704 (cond ((looking-at re1) t)
10705 ((looking-at re2) nil)
10706 (t (error "Not at an org table")))))
10707 (re (if commented re1 re2))
10708 beg end)
10709 (save-excursion
10710 (beginning-of-line 1)
10711 (while (looking-at re) (beginning-of-line 0))
10712 (beginning-of-line 2)
10713 (setq beg (point))
10714 (while (looking-at re) (beginning-of-line 2))
10715 (setq end (point)))
10716 (comment-region beg end (if commented '(4) nil))))
10718 (defun orgtbl-insert-radio-table ()
10719 "Insert a radio table template appropriate for this major mode."
10720 (interactive)
10721 (let* ((e (assq major-mode orgtbl-radio-table-templates))
10722 (txt (nth 1 e))
10723 name pos)
10724 (unless e (error "No radio table setup defined for %s" major-mode))
10725 (setq name (read-string "Table name: "))
10726 (while (string-match "%n" txt)
10727 (setq txt (replace-match name t t txt)))
10728 (or (bolp) (insert "\n"))
10729 (setq pos (point))
10730 (insert txt)
10731 (goto-char pos)))
10733 (defun org-get-param (params header i sym &optional hsym)
10734 "Get parameter value for symbol SYM.
10735 If this is a header line, actually get the value for the symbol with an
10736 additional \"h\" inserted after the colon.
10737 If the value is a protperty list, get the element for the current column.
10738 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
10739 (let ((val (plist-get params sym)))
10740 (and hsym header (setq val (or (plist-get params hsym) val)))
10741 (if (consp val) (plist-get val i) val)))
10743 (defun orgtbl-to-generic (table params)
10744 "Convert the orgtbl-mode TABLE to some other format.
10745 This generic routine can be used for many standard cases.
10746 TABLE is a list, each entry either the symbol `hline' for a horizontal
10747 separator line, or a list of fields for that line.
10748 PARAMS is a property list of parameters that can influence the conversion.
10749 For the generic converter, some parameters are obligatory: You need to
10750 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
10751 :splice, you must have :tstart and :tend.
10753 Valid parameters are
10755 :tstart String to start the table. Ignored when :splice is t.
10756 :tend String to end the table. Ignored when :splice is t.
10758 :splice When set to t, return only table body lines, don't wrap
10759 them into :tstart and :tend. Default is nil.
10761 :hline String to be inserted on horizontal separation lines.
10762 May be nil to ignore hlines.
10764 :lstart String to start a new table line.
10765 :lend String to end a table line
10766 :sep Separator between two fields
10767 :lfmt Format for entire line, with enough %s to capture all fields.
10768 If this is present, :lstart, :lend, and :sep are ignored.
10769 :fmt A format to be used to wrap the field, should contain
10770 %s for the original field value. For example, to wrap
10771 everything in dollars, you could use :fmt \"$%s$\".
10772 This may also be a property list with column numbers and
10773 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10775 :hlstart :hlend :hlsep :hlfmt :hfmt
10776 Same as above, specific for the header lines in the table.
10777 All lines before the first hline are treated as header.
10778 If any of these is not present, the data line value is used.
10780 :efmt Use this format to print numbers with exponentials.
10781 The format should have %s twice for inserting mantissa
10782 and exponent, for example \"%s\\\\times10^{%s}\". This
10783 may also be a property list with column numbers and
10784 formats. :fmt will still be applied after :efmt.
10786 In addition to this, the parameters :skip and :skipcols are always handled
10787 directly by `orgtbl-send-table'. See manual."
10788 (interactive)
10789 (let* ((p params)
10790 (splicep (plist-get p :splice))
10791 (hline (plist-get p :hline))
10792 rtn line i fm efm lfmt h)
10794 ;; Do we have a header?
10795 (if (and (not splicep) (listp (car table)) (memq 'hline table))
10796 (setq h t))
10798 ;; Put header
10799 (unless splicep
10800 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
10802 ;; Now loop over all lines
10803 (while (setq line (pop table))
10804 (if (eq line 'hline)
10805 ;; A horizontal separator line
10806 (progn (if hline (push hline rtn))
10807 (setq h nil)) ; no longer in header
10808 ;; A normal line. Convert the fields, push line onto the result list
10809 (setq i 0)
10810 (setq line
10811 (mapcar
10812 (lambda (f)
10813 (setq i (1+ i)
10814 fm (org-get-param p h i :fmt :hfmt)
10815 efm (org-get-param p h i :efmt))
10816 (if (and efm (string-match orgtbl-exp-regexp f))
10817 (setq f (format
10818 efm (match-string 1 f) (match-string 2 f))))
10819 (if fm (setq f (format fm f)))
10821 line))
10822 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
10823 (push (apply 'format lfmt line) rtn)
10824 (push (concat
10825 (org-get-param p h i :lstart :hlstart)
10826 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
10827 (org-get-param p h i :lend :hlend))
10828 rtn))))
10830 (unless splicep
10831 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
10833 (mapconcat 'identity (nreverse rtn) "\n")))
10835 (defun orgtbl-to-latex (table params)
10836 "Convert the orgtbl-mode TABLE to LaTeX.
10837 TABLE is a list, each entry either the symbol `hline' for a horizontal
10838 separator line, or a list of fields for that line.
10839 PARAMS is a property list of parameters that can influence the conversion.
10840 Supports all parameters from `orgtbl-to-generic'. Most important for
10841 LaTeX are:
10843 :splice When set to t, return only table body lines, don't wrap
10844 them into a tabular environment. Default is nil.
10846 :fmt A format to be used to wrap the field, should contain %s for the
10847 original field value. For example, to wrap everything in dollars,
10848 use :fmt \"$%s$\". This may also be a property list with column
10849 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10851 :efmt Format for transforming numbers with exponentials. The format
10852 should have %s twice for inserting mantissa and exponent, for
10853 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
10854 This may also be a property list with column numbers and formats.
10856 The general parameters :skip and :skipcols have already been applied when
10857 this function is called."
10858 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
10859 org-table-last-alignment ""))
10860 (params2
10861 (list
10862 :tstart (concat "\\begin{tabular}{" alignment "}")
10863 :tend "\\end{tabular}"
10864 :lstart "" :lend " \\\\" :sep " & "
10865 :efmt "%s\\,(%s)" :hline "\\hline")))
10866 (orgtbl-to-generic table (org-combine-plists params2 params))))
10868 (defun orgtbl-to-html (table params)
10869 "Convert the orgtbl-mode TABLE to LaTeX.
10870 TABLE is a list, each entry either the symbol `hline' for a horizontal
10871 separator line, or a list of fields for that line.
10872 PARAMS is a property list of parameters that can influence the conversion.
10873 Currently this function recognizes the following parameters:
10875 :splice When set to t, return only table body lines, don't wrap
10876 them into a <table> environment. Default is nil.
10878 The general parameters :skip and :skipcols have already been applied when
10879 this function is called. The function does *not* use `orgtbl-to-generic',
10880 so you cannot specify parameters for it."
10881 (let* ((splicep (plist-get params :splice))
10882 html)
10883 ;; Just call the formatter we already have
10884 ;; We need to make text lines for it, so put the fields back together.
10885 (setq html (org-format-org-table-html
10886 (mapcar
10887 (lambda (x)
10888 (if (eq x 'hline)
10889 "|----+----|"
10890 (concat "| " (mapconcat 'identity x " | ") " |")))
10891 table)
10892 splicep))
10893 (if (string-match "\n+\\'" html)
10894 (setq html (replace-match "" t t html)))
10895 html))
10897 (defun orgtbl-to-texinfo (table params)
10898 "Convert the orgtbl-mode TABLE to TeXInfo.
10899 TABLE is a list, each entry either the symbol `hline' for a horizontal
10900 separator line, or a list of fields for that line.
10901 PARAMS is a property list of parameters that can influence the conversion.
10902 Supports all parameters from `orgtbl-to-generic'. Most important for
10903 TeXInfo are:
10905 :splice nil/t When set to t, return only table body lines, don't wrap
10906 them into a multitable environment. Default is nil.
10908 :fmt fmt A format to be used to wrap the field, should contain
10909 %s for the original field value. For example, to wrap
10910 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
10911 This may also be a property list with column numbers and
10912 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
10914 :cf \"f1 f2..\" The column fractions for the table. Bye default these
10915 are computed automatically from the width of the columns
10916 under org-mode.
10918 The general parameters :skip and :skipcols have already been applied when
10919 this function is called."
10920 (let* ((total (float (apply '+ org-table-last-column-widths)))
10921 (colfrac (or (plist-get params :cf)
10922 (mapconcat
10923 (lambda (x) (format "%.3f" (/ (float x) total)))
10924 org-table-last-column-widths " ")))
10925 (params2
10926 (list
10927 :tstart (concat "@multitable @columnfractions " colfrac)
10928 :tend "@end multitable"
10929 :lstart "@item " :lend "" :sep " @tab "
10930 :hlstart "@headitem ")))
10931 (orgtbl-to-generic table (org-combine-plists params2 params))))
10933 ;;;; Link Stuff
10935 ;;; Link abbreviations
10937 (defun org-link-expand-abbrev (link)
10938 "Apply replacements as defined in `org-link-abbrev-alist."
10939 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
10940 (let* ((key (match-string 1 link))
10941 (as (or (assoc key org-link-abbrev-alist-local)
10942 (assoc key org-link-abbrev-alist)))
10943 (tag (and (match-end 2) (match-string 3 link)))
10944 rpl)
10945 (if (not as)
10946 link
10947 (setq rpl (cdr as))
10948 (cond
10949 ((symbolp rpl) (funcall rpl tag))
10950 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
10951 (t (concat rpl tag)))))
10952 link))
10954 ;;; Storing and inserting links
10956 (defvar org-insert-link-history nil
10957 "Minibuffer history for links inserted with `org-insert-link'.")
10959 (defvar org-stored-links nil
10960 "Contains the links stored with `org-store-link'.")
10962 (defvar org-store-link-plist nil
10963 "Plist with info about the most recently link created with `org-store-link'.")
10965 (defvar org-link-protocols nil
10966 "Link protocols added to Org-mode using `org-add-link-type'.")
10968 (defvar org-store-link-functions nil
10969 "List of functions that are called to create and store a link.
10970 Each function will be called in turn until one returns a non-nil
10971 value. Each function should check if it is responsible for creating
10972 this link (for example by looking at the major mode).
10973 If not, it must exit and return nil.
10974 If yes, it should return a non-nil value after a calling
10975 `org-store-link-properties' with a list of properties and values.
10976 Special properties are:
10978 :type The link prefix. like \"http\". This must be given.
10979 :link The link, like \"http://www.astro.uva.nl/~dominik\".
10980 This is obligatory as well.
10981 :description Optional default description for the second pair
10982 of brackets in an Org-mode link. The user can still change
10983 this when inserting this link into an Org-mode buffer.
10985 In addition to these, any additional properties can be specified
10986 and then used in remember templates.")
10988 (defun org-add-link-type (type &optional follow publish)
10989 "Add TYPE to the list of `org-link-types'.
10990 Re-compute all regular expressions depending on `org-link-types'
10991 FOLLOW and PUBLISH are two functions. Both take the link path as
10992 an argument.
10993 FOLLOW should do whatever is necessary to follow the link, for example
10994 to find a file or display a mail message.
10995 PUBLISH takes the path and retuns the string that should be used when
10996 this document is published."
10997 (add-to-list 'org-link-types type t)
10998 (org-make-link-regexps)
10999 (add-to-list 'org-link-protocols
11000 (list type follow publish)))
11002 (defun org-add-agenda-custom-command (entry)
11003 "Replace or add a command in `org-agenda-custom-commands'.
11004 This is mostly for hacking and trying a new command - once the command
11005 works you probably want to add it to `org-agenda-custom-commands' for good."
11006 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11007 (if ass
11008 (setcdr ass (cdr entry))
11009 (push entry org-agenda-custom-commands))))
11011 ;;;###autoload
11012 (defun org-store-link (arg)
11013 "\\<org-mode-map>Store an org-link to the current location.
11014 This link can later be inserted into an org-buffer with
11015 \\[org-insert-link].
11016 For some link types, a prefix arg is interpreted:
11017 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11018 For file links, arg negates `org-context-in-file-links'."
11019 (interactive "P")
11020 (setq org-store-link-plist nil) ; reset
11021 (let (link cpltxt desc description search txt)
11022 (cond
11024 ((run-hook-with-args-until-success 'org-store-link-functions)
11025 (setq link (plist-get org-store-link-plist :link)
11026 desc (or (plist-get org-store-link-plist :description) link)))
11028 ((eq major-mode 'bbdb-mode)
11029 (let ((name (bbdb-record-name (bbdb-current-record)))
11030 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11031 (setq cpltxt (concat "bbdb:" (or name company))
11032 link (org-make-link cpltxt))
11033 (org-store-link-props :type "bbdb" :name name :company company)))
11035 ((eq major-mode 'Info-mode)
11036 (setq link (org-make-link "info:"
11037 (file-name-nondirectory Info-current-file)
11038 ":" Info-current-node))
11039 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11040 ":" Info-current-node))
11041 (org-store-link-props :type "info" :file Info-current-file
11042 :node Info-current-node))
11044 ((eq major-mode 'calendar-mode)
11045 (let ((cd (calendar-cursor-to-date)))
11046 (setq link
11047 (format-time-string
11048 (car org-time-stamp-formats)
11049 (apply 'encode-time
11050 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11051 nil nil nil))))
11052 (org-store-link-props :type "calendar" :date cd)))
11054 ((or (eq major-mode 'vm-summary-mode)
11055 (eq major-mode 'vm-presentation-mode))
11056 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11057 (vm-follow-summary-cursor)
11058 (save-excursion
11059 (vm-select-folder-buffer)
11060 (let* ((message (car vm-message-pointer))
11061 (folder buffer-file-name)
11062 (subject (vm-su-subject message))
11063 (to (vm-get-header-contents message "To"))
11064 (from (vm-get-header-contents message "From"))
11065 (message-id (vm-su-message-id message)))
11066 (org-store-link-props :type "vm" :from from :to to :subject subject
11067 :message-id message-id)
11068 (setq message-id (org-remove-angle-brackets message-id))
11069 (setq folder (abbreviate-file-name folder))
11070 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11071 folder)
11072 (setq folder (replace-match "" t t folder)))
11073 (setq cpltxt (org-email-link-description))
11074 (setq link (org-make-link "vm:" folder "#" message-id)))))
11076 ((eq major-mode 'wl-summary-mode)
11077 (let* ((msgnum (wl-summary-message-number))
11078 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11079 msgnum 'message-id))
11080 (wl-message-entity
11081 (if (fboundp 'elmo-message-entity)
11082 (elmo-message-entity
11083 wl-summary-buffer-elmo-folder msgnum)
11084 (elmo-msgdb-overview-get-entity
11085 msgnum (wl-summary-buffer-msgdb))))
11086 (from (wl-summary-line-from))
11087 (to (elmo-message-entity-field wl-message-entity 'to))
11088 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11089 (wl-summary-line-subject))))
11090 (org-store-link-props :type "wl" :from from :to to
11091 :subject subject :message-id message-id)
11092 (setq message-id (org-remove-angle-brackets message-id))
11093 (setq cpltxt (org-email-link-description))
11094 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11095 "#" message-id))))
11097 ((or (equal major-mode 'mh-folder-mode)
11098 (equal major-mode 'mh-show-mode))
11099 (let ((from (org-mhe-get-header "From:"))
11100 (to (org-mhe-get-header "To:"))
11101 (message-id (org-mhe-get-header "Message-Id:"))
11102 (subject (org-mhe-get-header "Subject:")))
11103 (org-store-link-props :type "mh" :from from :to to
11104 :subject subject :message-id message-id)
11105 (setq cpltxt (org-email-link-description))
11106 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11107 (org-remove-angle-brackets message-id)))))
11109 ((eq major-mode 'rmail-mode)
11110 (save-excursion
11111 (save-restriction
11112 (rmail-narrow-to-non-pruned-header)
11113 (let ((folder buffer-file-name)
11114 (message-id (mail-fetch-field "message-id"))
11115 (from (mail-fetch-field "from"))
11116 (to (mail-fetch-field "to"))
11117 (subject (mail-fetch-field "subject")))
11118 (org-store-link-props
11119 :type "rmail" :from from :to to
11120 :subject subject :message-id message-id)
11121 (setq message-id (org-remove-angle-brackets message-id))
11122 (setq cpltxt (org-email-link-description))
11123 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11125 ((eq major-mode 'gnus-group-mode)
11126 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11127 (gnus-group-group-name)) ; version
11128 ((fboundp 'gnus-group-name)
11129 (gnus-group-name))
11130 (t "???"))))
11131 (unless group (error "Not on a group"))
11132 (org-store-link-props :type "gnus" :group group)
11133 (setq cpltxt (concat
11134 (if (org-xor arg org-usenet-links-prefer-google)
11135 "http://groups.google.com/groups?group="
11136 "gnus:")
11137 group)
11138 link (org-make-link cpltxt))))
11140 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11141 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11142 (let* ((group gnus-newsgroup-name)
11143 (article (gnus-summary-article-number))
11144 (header (gnus-summary-article-header article))
11145 (from (mail-header-from header))
11146 (message-id (mail-header-id header))
11147 (date (mail-header-date header))
11148 (subject (gnus-summary-subject-string)))
11149 (org-store-link-props :type "gnus" :from from :subject subject
11150 :message-id message-id :group group)
11151 (setq cpltxt (org-email-link-description))
11152 (if (org-xor arg org-usenet-links-prefer-google)
11153 (setq link
11154 (concat
11155 cpltxt "\n "
11156 (format "http://groups.google.com/groups?as_umsgid=%s"
11157 (org-fixup-message-id-for-http message-id))))
11158 (setq link (org-make-link "gnus:" group
11159 "#" (number-to-string article))))))
11161 ((eq major-mode 'w3-mode)
11162 (setq cpltxt (url-view-url t)
11163 link (org-make-link cpltxt))
11164 (org-store-link-props :type "w3" :url (url-view-url t)))
11166 ((eq major-mode 'w3m-mode)
11167 (setq cpltxt (or w3m-current-title w3m-current-url)
11168 link (org-make-link w3m-current-url))
11169 (org-store-link-props :type "w3m" :url (url-view-url t)))
11171 ((setq search (run-hook-with-args-until-success
11172 'org-create-file-search-functions))
11173 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11174 "::" search))
11175 (setq cpltxt (or description link)))
11177 ((eq major-mode 'image-mode)
11178 (setq cpltxt (concat "file:"
11179 (abbreviate-file-name buffer-file-name))
11180 link (org-make-link cpltxt))
11181 (org-store-link-props :type "image" :file buffer-file-name))
11183 ((eq major-mode 'dired-mode)
11184 ;; link to the file in the current line
11185 (setq cpltxt (concat "file:"
11186 (abbreviate-file-name
11187 (expand-file-name
11188 (dired-get-filename nil t))))
11189 link (org-make-link cpltxt)))
11191 ((and buffer-file-name (org-mode-p))
11192 ;; Just link to current headline
11193 (setq cpltxt (concat "file:"
11194 (abbreviate-file-name buffer-file-name)))
11195 ;; Add a context search string
11196 (when (org-xor org-context-in-file-links arg)
11197 ;; Check if we are on a target
11198 (if (org-in-regexp "<<\\(.*?\\)>>")
11199 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11200 (setq txt (cond
11201 ((org-on-heading-p) nil)
11202 ((org-region-active-p)
11203 (buffer-substring (region-beginning) (region-end)))
11204 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11205 (when (or (null txt) (string-match "\\S-" txt))
11206 (setq cpltxt
11207 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11208 desc "NONE"))))
11209 (if (string-match "::\\'" cpltxt)
11210 (setq cpltxt (substring cpltxt 0 -2)))
11211 (setq link (org-make-link cpltxt)))
11213 ((buffer-file-name (buffer-base-buffer))
11214 ;; Just link to this file here.
11215 (setq cpltxt (concat "file:"
11216 (abbreviate-file-name
11217 (buffer-file-name (buffer-base-buffer)))))
11218 ;; Add a context string
11219 (when (org-xor org-context-in-file-links arg)
11220 (setq txt (if (org-region-active-p)
11221 (buffer-substring (region-beginning) (region-end))
11222 (buffer-substring (point-at-bol) (point-at-eol))))
11223 ;; Only use search option if there is some text.
11224 (when (string-match "\\S-" txt)
11225 (setq cpltxt
11226 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11227 desc "NONE")))
11228 (setq link (org-make-link cpltxt)))
11230 ((interactive-p)
11231 (error "Cannot link to a buffer which is not visiting a file"))
11233 (t (setq link nil)))
11235 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11236 (setq link (or link cpltxt)
11237 desc (or desc cpltxt))
11238 (if (equal desc "NONE") (setq desc nil))
11240 (if (and (interactive-p) link)
11241 (progn
11242 (setq org-stored-links
11243 (cons (list link desc) org-stored-links))
11244 (message "Stored: %s" (or desc link)))
11245 (and link (org-make-link-string link desc)))))
11247 (defun org-store-link-props (&rest plist)
11248 "Store link properties, extract names and addresses."
11249 (let (x adr)
11250 (when (setq x (plist-get plist :from))
11251 (setq adr (mail-extract-address-components x))
11252 (plist-put plist :fromname (car adr))
11253 (plist-put plist :fromaddress (nth 1 adr)))
11254 (when (setq x (plist-get plist :to))
11255 (setq adr (mail-extract-address-components x))
11256 (plist-put plist :toname (car adr))
11257 (plist-put plist :toaddress (nth 1 adr))))
11258 (let ((from (plist-get plist :from))
11259 (to (plist-get plist :to)))
11260 (when (and from to org-from-is-user-regexp)
11261 (plist-put plist :fromto
11262 (if (string-match org-from-is-user-regexp from)
11263 (concat "to %t")
11264 (concat "from %f")))))
11265 (setq org-store-link-plist plist))
11267 (defun org-email-link-description (&optional fmt)
11268 "Return the description part of an email link.
11269 This takes information from `org-store-link-plist' and formats it
11270 according to FMT (default from `org-email-link-description-format')."
11271 (setq fmt (or fmt org-email-link-description-format))
11272 (let* ((p org-store-link-plist)
11273 (to (plist-get p :toaddress))
11274 (from (plist-get p :fromaddress))
11275 (table
11276 (list
11277 (cons "%c" (plist-get p :fromto))
11278 (cons "%F" (plist-get p :from))
11279 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
11280 (cons "%T" (plist-get p :to))
11281 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
11282 (cons "%s" (plist-get p :subject))
11283 (cons "%m" (plist-get p :message-id)))))
11284 (when (string-match "%c" fmt)
11285 ;; Check if the user wrote this message
11286 (if (and org-from-is-user-regexp from to
11287 (save-match-data (string-match org-from-is-user-regexp from)))
11288 (setq fmt (replace-match "to %t" t t fmt))
11289 (setq fmt (replace-match "from %f" t t fmt))))
11290 (org-replace-escapes fmt table)))
11292 (defun org-make-org-heading-search-string (&optional string heading)
11293 "Make search string for STRING or current headline."
11294 (interactive)
11295 (let ((s (or string (org-get-heading))))
11296 (unless (and string (not heading))
11297 ;; We are using a headline, clean up garbage in there.
11298 (if (string-match org-todo-regexp s)
11299 (setq s (replace-match "" t t s)))
11300 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
11301 (setq s (replace-match "" t t s)))
11302 (setq s (org-trim s))
11303 (if (string-match (concat "^\\(" org-quote-string "\\|"
11304 org-comment-string "\\)") s)
11305 (setq s (replace-match "" t t s)))
11306 (while (string-match org-ts-regexp s)
11307 (setq s (replace-match "" t t s))))
11308 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
11309 (setq s (replace-match " " t t s)))
11310 (or string (setq s (concat "*" s))) ; Add * for headlines
11311 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
11313 (defun org-make-link (&rest strings)
11314 "Concatenate STRINGS."
11315 (apply 'concat strings))
11317 (defun org-make-link-string (link &optional description)
11318 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11319 (unless (string-match "\\S-" link)
11320 (error "Empty link"))
11321 (when (stringp description)
11322 ;; Remove brackets from the description, they are fatal.
11323 (while (string-match "\\[\\|\\]" description)
11324 (setq description (replace-match "" t t description))))
11325 (when (equal (org-link-escape link) description)
11326 ;; No description needed, it is identical
11327 (setq description nil))
11328 (when (and (not description)
11329 (not (equal link (org-link-escape link))))
11330 (setq description link))
11331 (concat "[[" (org-link-escape link) "]"
11332 (if description (concat "[" description "]") "")
11333 "]"))
11335 (defconst org-link-escape-chars
11336 '((" " . "%20")
11337 ("[" . "%5B")
11338 ("]" . "%5d")
11339 ("\340" . "%E0") ; `a
11340 ("\342" . "%E2") ; ^a
11341 ("\347" . "%E7") ; ,c
11342 ("\350" . "%E8") ; `e
11343 ("\351" . "%E9") ; 'e
11344 ("\352" . "%EA") ; ^e
11345 ("\356" . "%EE") ; ^i
11346 ("\364" . "%F4") ; ^o
11347 ("\371" . "%F9") ; `u
11348 ("\373" . "%FB") ; ^u
11349 (";" . "%3B")
11350 ("?" . "%3F")
11351 ("=" . "%3D")
11352 ("+" . "%2B")
11354 "Association list of escapes for some characters problematic in links.
11355 This is the list that is used for internal purposes.")
11357 (defconst org-link-escape-chars-browser
11358 '((" " . "%20"))
11359 "Association list of escapes for some characters problematic in links.
11360 This is the list that is used before handing over to the browser.")
11362 (defun org-link-escape (text &optional table)
11363 "Escape charaters in TEXT that are problematic for links."
11364 (setq table (or table org-link-escape-chars))
11365 (when text
11366 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
11367 table "\\|")))
11368 (while (string-match re text)
11369 (setq text
11370 (replace-match
11371 (cdr (assoc (match-string 0 text) table))
11372 t t text)))
11373 text)))
11375 (defun org-link-unescape (text &optional table)
11376 "Reverse the action of `org-link-escape'."
11377 (setq table (or table org-link-escape-chars))
11378 (when text
11379 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
11380 table "\\|")))
11381 (while (string-match re text)
11382 (setq text
11383 (replace-match
11384 (car (rassoc (match-string 0 text) table))
11385 t t text)))
11386 text)))
11388 (defun org-xor (a b)
11389 "Exclusive or."
11390 (if a (not b) b))
11392 (defun org-get-header (header)
11393 "Find a header field in the current buffer."
11394 (save-excursion
11395 (goto-char (point-min))
11396 (let ((case-fold-search t) s)
11397 (cond
11398 ((eq header 'from)
11399 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11400 (setq s (match-string 1)))
11401 (while (string-match "\"" s)
11402 (setq s (replace-match "" t t s)))
11403 (if (string-match "[<(].*" s)
11404 (setq s (replace-match "" t t s))))
11405 ((eq header 'message-id)
11406 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11407 (setq s (match-string 1))))
11408 ((eq header 'subject)
11409 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11410 (setq s (match-string 1)))))
11411 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11412 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11413 s)))
11416 (defun org-fixup-message-id-for-http (s)
11417 "Replace special characters in a message id, so it can be used in an http query."
11418 (while (string-match "<" s)
11419 (setq s (replace-match "%3C" t t s)))
11420 (while (string-match ">" s)
11421 (setq s (replace-match "%3E" t t s)))
11422 (while (string-match "@" s)
11423 (setq s (replace-match "%40" t t s)))
11426 ;;;###autoload
11427 (defun org-insert-link-global ()
11428 "Insert a link like Org-mode does.
11429 This command can be called in any mode to insert a link in Org-mode syntax."
11430 (interactive)
11431 (org-run-like-in-org-mode 'org-insert-link))
11433 (defun org-insert-link (&optional complete-file)
11434 "Insert a link. At the prompt, enter the link.
11436 Completion can be used to select a link previously stored with
11437 `org-store-link'. When the empty string is entered (i.e. if you just
11438 press RET at the prompt), the link defaults to the most recently
11439 stored link. As SPC triggers completion in the minibuffer, you need to
11440 use M-SPC or C-q SPC to force the insertion of a space character.
11442 You will also be prompted for a description, and if one is given, it will
11443 be displayed in the buffer instead of the link.
11445 If there is already a link at point, this command will allow you to edit link
11446 and description parts.
11448 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11449 selected using completion. The path to the file will be relative to
11450 the current directory if the file is in the current directory or a
11451 subdirectory. Otherwise, the link will be the absolute path as
11452 completed in the minibuffer (i.e. normally ~/path/to/file).
11454 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11455 is in the current directory or below.
11456 With three \\[universal-argument] prefixes, negate the meaning of
11457 `org-keep-stored-link-after-insertion'."
11458 (interactive "P")
11459 (let* ((wcf (current-window-configuration))
11460 (region (if (org-region-active-p)
11461 (buffer-substring (region-beginning) (region-end))))
11462 (remove (and region (list (region-beginning) (region-end))))
11463 (desc region)
11464 tmphist ; byte-compile incorrectly complains about this
11465 link entry file)
11466 (cond
11467 ((org-in-regexp org-bracket-link-regexp 1)
11468 ;; We do have a link at point, and we are going to edit it.
11469 (setq remove (list (match-beginning 0) (match-end 0)))
11470 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11471 (setq link (read-string "Link: "
11472 (org-link-unescape
11473 (org-match-string-no-properties 1)))))
11474 ((or (org-in-regexp org-angle-link-re)
11475 (org-in-regexp org-plain-link-re))
11476 ;; Convert to bracket link
11477 (setq remove (list (match-beginning 0) (match-end 0))
11478 link (read-string "Link: "
11479 (org-remove-angle-brackets (match-string 0)))))
11480 ((equal complete-file '(4))
11481 ;; Completing read for file names.
11482 (setq file (read-file-name "File: "))
11483 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11484 (pwd1 (file-name-as-directory (abbreviate-file-name
11485 (expand-file-name ".")))))
11486 (cond
11487 ((equal complete-file '(16))
11488 (setq link (org-make-link
11489 "file:"
11490 (abbreviate-file-name (expand-file-name file)))))
11491 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11492 (setq link (org-make-link "file:" (match-string 1 file))))
11493 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11494 (expand-file-name file))
11495 (setq link (org-make-link
11496 "file:" (match-string 1 (expand-file-name file)))))
11497 (t (setq link (org-make-link "file:" file))))))
11499 ;; Read link, with completion for stored links.
11500 (with-output-to-temp-buffer "*Org Links*"
11501 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
11502 (when org-stored-links
11503 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
11504 (princ (mapconcat
11505 (lambda (x)
11506 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
11507 (reverse org-stored-links) "\n"))))
11508 (let ((cw (selected-window)))
11509 (select-window (get-buffer-window "*Org Links*"))
11510 (shrink-window-if-larger-than-buffer)
11511 (setq truncate-lines t)
11512 (select-window cw))
11513 ;; Fake a link history, containing the stored links.
11514 (setq tmphist (append (mapcar 'car org-stored-links)
11515 org-insert-link-history))
11516 (unwind-protect
11517 (setq link (org-completing-read
11518 "Link: "
11519 (append
11520 (mapcar (lambda (x) (list (concat (car x) ":")))
11521 (append org-link-abbrev-alist-local org-link-abbrev-alist))
11522 (mapcar (lambda (x) (list (concat x ":")))
11523 org-link-types))
11524 nil nil nil
11525 'tmphist
11526 (or (car (car org-stored-links)))))
11527 (set-window-configuration wcf)
11528 (kill-buffer "*Org Links*"))
11529 (setq entry (assoc link org-stored-links))
11530 (or entry (push link org-insert-link-history))
11531 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11532 (not org-keep-stored-link-after-insertion))
11533 (setq org-stored-links (delq (assoc link org-stored-links)
11534 org-stored-links)))
11535 (setq desc (or desc (nth 1 entry)))))
11537 (if (string-match org-plain-link-re link)
11538 ;; URL-like link, normalize the use of angular brackets.
11539 (setq link (org-make-link (org-remove-angle-brackets link))))
11541 ;; Check if we are linking to the current file with a search option
11542 ;; If yes, simplify the link by using only the search option.
11543 (when (and buffer-file-name
11544 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11545 (let* ((path (match-string 1 link))
11546 (case-fold-search nil)
11547 (search (match-string 2 link)))
11548 (save-match-data
11549 (if (equal (file-truename buffer-file-name) (file-truename path))
11550 ;; We are linking to this same file, with a search option
11551 (setq link search)))))
11553 ;; Check if we can/should use a relative path. If yes, simplify the link
11554 (when (string-match "\\<file:\\(.*\\)" link)
11555 (let* ((path (match-string 1 link))
11556 (origpath path)
11557 (desc-is-link (equal link desc))
11558 (case-fold-search nil))
11559 (cond
11560 ((eq org-link-file-path-type 'absolute)
11561 (setq path (abbreviate-file-name (expand-file-name path))))
11562 ((eq org-link-file-path-type 'noabbrev)
11563 (setq path (expand-file-name path)))
11564 ((eq org-link-file-path-type 'relative)
11565 (setq path (file-relative-name path)))
11567 (save-match-data
11568 (if (string-match (concat "^" (regexp-quote
11569 (file-name-as-directory
11570 (expand-file-name "."))))
11571 (expand-file-name path))
11572 ;; We are linking a file with relative path name.
11573 (setq path (substring (expand-file-name path)
11574 (match-end 0)))))))
11575 (setq link (concat "file:" path))
11576 (if (equal desc origpath)
11577 (setq desc path))))
11579 (setq desc (read-string "Description: " desc))
11580 (unless (string-match "\\S-" desc) (setq desc nil))
11581 (if remove (apply 'delete-region remove))
11582 (insert (org-make-link-string link desc))))
11584 (defun org-completing-read (&rest args)
11585 (let ((minibuffer-local-completion-map
11586 (copy-keymap minibuffer-local-completion-map)))
11587 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
11588 (apply 'completing-read args)))
11590 ;;; Opening/following a link
11591 (defvar org-link-search-failed nil)
11593 (defun org-next-link ()
11594 "Move forward to the next link.
11595 If the link is in hidden text, expose it."
11596 (interactive)
11597 (when (and org-link-search-failed (eq this-command last-command))
11598 (goto-char (point-min))
11599 (message "Link search wrapped back to beginning of buffer"))
11600 (setq org-link-search-failed nil)
11601 (let* ((pos (point))
11602 (ct (org-context))
11603 (a (assoc :link ct)))
11604 (if a (goto-char (nth 2 a)))
11605 (if (re-search-forward org-any-link-re nil t)
11606 (progn
11607 (goto-char (match-beginning 0))
11608 (if (org-invisible-p) (org-show-context)))
11609 (goto-char pos)
11610 (setq org-link-search-failed t)
11611 (error "No further link found"))))
11613 (defun org-previous-link ()
11614 "Move backward to the previous link.
11615 If the link is in hidden text, expose it."
11616 (interactive)
11617 (when (and org-link-search-failed (eq this-command last-command))
11618 (goto-char (point-max))
11619 (message "Link search wrapped back to end of buffer"))
11620 (setq org-link-search-failed nil)
11621 (let* ((pos (point))
11622 (ct (org-context))
11623 (a (assoc :link ct)))
11624 (if a (goto-char (nth 1 a)))
11625 (if (re-search-backward org-any-link-re nil t)
11626 (progn
11627 (goto-char (match-beginning 0))
11628 (if (org-invisible-p) (org-show-context)))
11629 (goto-char pos)
11630 (setq org-link-search-failed t)
11631 (error "No further link found"))))
11633 (defun org-find-file-at-mouse (ev)
11634 "Open file link or URL at mouse."
11635 (interactive "e")
11636 (mouse-set-point ev)
11637 (org-open-at-point 'in-emacs))
11639 (defun org-open-at-mouse (ev)
11640 "Open file link or URL at mouse."
11641 (interactive "e")
11642 (mouse-set-point ev)
11643 (org-open-at-point))
11645 (defvar org-window-config-before-follow-link nil
11646 "The window configuration before following a link.
11647 This is saved in case the need arises to restore it.")
11649 (defvar org-open-link-marker (make-marker)
11650 "Marker pointing to the location where `org-open-at-point; was called.")
11652 ;;;###autoload
11653 (defun org-open-at-point-global ()
11654 "Follow a link like Org-mode does.
11655 This command can be called in any mode to follow a link that has
11656 Org-mode syntax."
11657 (interactive)
11658 (org-run-like-in-org-mode 'org-open-at-point))
11660 (defun org-open-at-point (&optional in-emacs)
11661 "Open link at or after point.
11662 If there is no link at point, this function will search forward up to
11663 the end of the current subtree.
11664 Normally, files will be opened by an appropriate application. If the
11665 optional argument IN-EMACS is non-nil, Emacs will visit the file."
11666 (interactive "P")
11667 (move-marker org-open-link-marker (point))
11668 (setq org-window-config-before-follow-link (current-window-configuration))
11669 (org-remove-occur-highlights nil nil t)
11670 (if (org-at-timestamp-p t)
11671 (org-follow-timestamp-link)
11672 (let (type path link line search (pos (point)))
11673 (catch 'match
11674 (save-excursion
11675 (skip-chars-forward "^]\n\r")
11676 (when (org-in-regexp org-bracket-link-regexp)
11677 (setq link (org-link-unescape (org-match-string-no-properties 1)))
11678 (while (string-match " *\n *" link)
11679 (setq link (replace-match " " t t link)))
11680 (setq link (org-link-expand-abbrev link))
11681 (if (string-match org-link-re-with-space2 link)
11682 (setq type (match-string 1 link) path (match-string 2 link))
11683 (setq type "thisfile" path link))
11684 (throw 'match t)))
11686 (when (get-text-property (point) 'org-linked-text)
11687 (setq type "thisfile"
11688 pos (if (get-text-property (1+ (point)) 'org-linked-text)
11689 (1+ (point)) (point))
11690 path (buffer-substring
11691 (previous-single-property-change pos 'org-linked-text)
11692 (next-single-property-change pos 'org-linked-text)))
11693 (throw 'match t))
11695 (save-excursion
11696 (when (or (org-in-regexp org-angle-link-re)
11697 (org-in-regexp org-plain-link-re))
11698 (setq type (match-string 1) path (match-string 2))
11699 (throw 'match t)))
11700 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
11701 (setq type "tree-match"
11702 path (match-string 1))
11703 (throw 'match t))
11704 (save-excursion
11705 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
11706 (setq type "tags"
11707 path (match-string 1))
11708 (while (string-match ":" path)
11709 (setq path (replace-match "+" t t path)))
11710 (throw 'match t))))
11711 (unless path
11712 (error "No link found"))
11713 ;; Remove any trailing spaces in path
11714 (if (string-match " +\\'" path)
11715 (setq path (replace-match "" t t path)))
11717 (cond
11719 ((assoc type org-link-protocols)
11720 (funcall (nth 1 (assoc type org-link-protocols)) path))
11722 ((equal type "mailto")
11723 (let ((cmd (car org-link-mailto-program))
11724 (args (cdr org-link-mailto-program)) args1
11725 (address path) (subject "") a)
11726 (if (string-match "\\(.*\\)::\\(.*\\)" path)
11727 (setq address (match-string 1 path)
11728 subject (org-link-escape (match-string 2 path))))
11729 (while args
11730 (cond
11731 ((not (stringp (car args))) (push (pop args) args1))
11732 (t (setq a (pop args))
11733 (if (string-match "%a" a)
11734 (setq a (replace-match address t t a)))
11735 (if (string-match "%s" a)
11736 (setq a (replace-match subject t t a)))
11737 (push a args1))))
11738 (apply cmd (nreverse args1))))
11740 ((member type '("http" "https" "ftp" "news"))
11741 (browse-url (concat type ":" (org-link-escape
11742 path org-link-escape-chars-browser))))
11744 ((string= type "tags")
11745 (org-tags-view in-emacs path))
11746 ((string= type "thisfile")
11747 (if in-emacs
11748 (switch-to-buffer-other-window
11749 (org-get-buffer-for-internal-link (current-buffer)))
11750 (org-mark-ring-push))
11751 (let ((cmd `(org-link-search
11752 ,path
11753 ,(cond ((equal in-emacs '(4)) 'occur)
11754 ((equal in-emacs '(16)) 'org-occur)
11755 (t nil))
11756 ,pos)))
11757 (condition-case nil (eval cmd)
11758 (error (progn (widen) (eval cmd))))))
11760 ((string= type "tree-match")
11761 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
11763 ((string= type "file")
11764 (if (string-match "::\\([0-9]+\\)\\'" path)
11765 (setq line (string-to-number (match-string 1 path))
11766 path (substring path 0 (match-beginning 0)))
11767 (if (string-match "::\\(.+\\)\\'" path)
11768 (setq search (match-string 1 path)
11769 path (substring path 0 (match-beginning 0)))))
11770 (org-open-file path in-emacs line search))
11772 ((string= type "news")
11773 (org-follow-gnus-link path))
11775 ((string= type "bbdb")
11776 (org-follow-bbdb-link path))
11778 ((string= type "info")
11779 (org-follow-info-link path))
11781 ((string= type "gnus")
11782 (let (group article)
11783 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11784 (error "Error in Gnus link"))
11785 (setq group (match-string 1 path)
11786 article (match-string 3 path))
11787 (org-follow-gnus-link group article)))
11789 ((string= type "vm")
11790 (let (folder article)
11791 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11792 (error "Error in VM link"))
11793 (setq folder (match-string 1 path)
11794 article (match-string 3 path))
11795 ;; in-emacs is the prefix arg, will be interpreted as read-only
11796 (org-follow-vm-link folder article in-emacs)))
11798 ((string= type "wl")
11799 (let (folder article)
11800 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11801 (error "Error in Wanderlust link"))
11802 (setq folder (match-string 1 path)
11803 article (match-string 3 path))
11804 (org-follow-wl-link folder article)))
11806 ((string= type "mhe")
11807 (let (folder article)
11808 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11809 (error "Error in MHE link"))
11810 (setq folder (match-string 1 path)
11811 article (match-string 3 path))
11812 (org-follow-mhe-link folder article)))
11814 ((string= type "rmail")
11815 (let (folder article)
11816 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11817 (error "Error in RMAIL link"))
11818 (setq folder (match-string 1 path)
11819 article (match-string 3 path))
11820 (org-follow-rmail-link folder article)))
11822 ((string= type "shell")
11823 (let ((cmd path))
11824 ;; The following is only for backward compatibility
11825 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
11826 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
11827 (if (or (not org-confirm-shell-link-function)
11828 (funcall org-confirm-shell-link-function
11829 (format "Execute \"%s\" in shell? "
11830 (org-add-props cmd nil
11831 'face 'org-warning))))
11832 (progn
11833 (message "Executing %s" cmd)
11834 (shell-command cmd))
11835 (error "Abort"))))
11837 ((string= type "elisp")
11838 (let ((cmd path))
11839 (if (or (not org-confirm-elisp-link-function)
11840 (funcall org-confirm-elisp-link-function
11841 (format "Execute \"%s\" as elisp? "
11842 (org-add-props cmd nil
11843 'face 'org-warning))))
11844 (message "%s => %s" cmd (eval (read cmd)))
11845 (error "Abort"))))
11848 (browse-url-at-point)))))
11849 (move-marker org-open-link-marker nil))
11852 ;;; File search
11854 (defvar org-create-file-search-functions nil
11855 "List of functions to construct the right search string for a file link.
11856 These functions are called in turn with point at the location to
11857 which the link should point.
11859 A function in the hook should first test if it would like to
11860 handle this file type, for example by checking the major-mode or
11861 the file extension. If it decides not to handle this file, it
11862 should just return nil to give other functions a chance. If it
11863 does handle the file, it must return the search string to be used
11864 when following the link. The search string will be part of the
11865 file link, given after a double colon, and `org-open-at-point'
11866 will automatically search for it. If special measures must be
11867 taken to make the search successful, another function should be
11868 added to the companion hook `org-execute-file-search-functions',
11869 which see.
11871 A function in this hook may also use `setq' to set the variable
11872 `description' to provide a suggestion for the descriptive text to
11873 be used for this link when it gets inserted into an Org-mode
11874 buffer with \\[org-insert-link].")
11876 (defvar org-execute-file-search-functions nil
11877 "List of functions to execute a file search triggered by a link.
11879 Functions added to this hook must accept a single argument, the
11880 search string that was part of the file link, the part after the
11881 double colon. The function must first check if it would like to
11882 handle this search, for example by checking the major-mode or the
11883 file extension. If it decides not to handle this search, it
11884 should just return nil to give other functions a chance. If it
11885 does handle the search, it must return a non-nil value to keep
11886 other functions from trying.
11888 Each function can access the current prefix argument through the
11889 variable `current-prefix-argument'. Note that a single prefix is
11890 used to force opening a link in Emacs, so it may be good to only
11891 use a numeric or double prefix to guide the search function.
11893 In case this is needed, a function in this hook can also restore
11894 the window configuration before `org-open-at-point' was called using:
11896 (set-window-configuration org-window-config-before-follow-link)")
11898 (defun org-link-search (s &optional type avoid-pos)
11899 "Search for a link search option.
11900 If S is surrounded by forward slashes, it is interpreted as a
11901 regular expression. In org-mode files, this will create an `org-occur'
11902 sparse tree. In ordinary files, `occur' will be used to list matches.
11903 If the current buffer is in `dired-mode', grep will be used to search
11904 in all files. If AVOID-POS is given, ignore matches near that position."
11905 (let ((case-fold-search t)
11906 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
11907 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
11908 (append '(("") (" ") ("\t") ("\n"))
11909 org-emphasis-alist)
11910 "\\|") "\\)"))
11911 (pos (point))
11912 (pre "") (post "")
11913 words re0 re1 re2 re3 re4 re5 re2a reall)
11914 (cond
11915 ;; First check if there are any special
11916 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11917 ;; Now try the builtin stuff
11918 ((save-excursion
11919 (goto-char (point-min))
11920 (and
11921 (re-search-forward
11922 (concat "<<" (regexp-quote s0) ">>") nil t)
11923 (setq pos (match-beginning 0))))
11924 ;; There is an exact target for this
11925 (goto-char pos))
11926 ((string-match "^/\\(.*\\)/$" s)
11927 ;; A regular expression
11928 (cond
11929 ((org-mode-p)
11930 (org-occur (match-string 1 s)))
11931 ;;((eq major-mode 'dired-mode)
11932 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
11933 (t (org-do-occur (match-string 1 s)))))
11935 ;; A normal search strings
11936 (when (equal (string-to-char s) ?*)
11937 ;; Anchor on headlines, post may include tags.
11938 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11939 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
11940 s (substring s 1)))
11941 (remove-text-properties
11942 0 (length s)
11943 '(face nil mouse-face nil keymap nil fontified nil) s)
11944 ;; Make a series of regular expressions to find a match
11945 (setq words (org-split-string s "[ \n\r\t]+")
11946 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11947 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11948 "\\)" markers)
11949 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
11950 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11951 re1 (concat pre re2 post)
11952 re3 (concat pre re4 post)
11953 re5 (concat pre ".*" re4)
11954 re2 (concat pre re2)
11955 re2a (concat pre re2a)
11956 re4 (concat pre re4)
11957 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11958 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11959 re5 "\\)"
11961 (cond
11962 ((eq type 'org-occur) (org-occur reall))
11963 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11964 (t (goto-char (point-min))
11965 (if (or (org-search-not-self 1 re0 nil t)
11966 (org-search-not-self 1 re1 nil t)
11967 (org-search-not-self 1 re2 nil t)
11968 (org-search-not-self 1 re2a nil t)
11969 (org-search-not-self 1 re3 nil t)
11970 (org-search-not-self 1 re4 nil t)
11971 (org-search-not-self 1 re5 nil t)
11973 (goto-char (match-beginning 1))
11974 (goto-char pos)
11975 (error "No match")))))
11977 ;; Normal string-search
11978 (goto-char (point-min))
11979 (if (search-forward s nil t)
11980 (goto-char (match-beginning 0))
11981 (error "No match"))))
11982 (and (org-mode-p) (org-show-context 'link-search))))
11984 (defun org-search-not-self (group &rest args)
11985 "Execute `re-search-forward', but only accept matches that do not
11986 enclose the position of `org-open-link-marker'."
11987 (let ((m org-open-link-marker))
11988 (catch 'exit
11989 (while (apply 're-search-forward args)
11990 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11991 (goto-char (match-end group))
11992 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11993 (> (match-beginning 0) (marker-position m))
11994 (< (match-end 0) (marker-position m)))
11995 (save-match-data
11996 (or (not (org-in-regexp
11997 org-bracket-link-analytic-regexp 1))
11998 (not (match-end 4)) ; no description
11999 (and (<= (match-beginning 4) (point))
12000 (>= (match-end 4) (point))))))
12001 (throw 'exit (point))))))))
12003 (defun org-get-buffer-for-internal-link (buffer)
12004 "Return a buffer to be used for displaying the link target of internal links."
12005 (cond
12006 ((not org-display-internal-link-with-indirect-buffer)
12007 buffer)
12008 ((string-match "(Clone)$" (buffer-name buffer))
12009 (message "Buffer is already a clone, not making another one")
12010 ;; we also do not modify visibility in this case
12011 buffer)
12012 (t ; make a new indirect buffer for displaying the link
12013 (let* ((bn (buffer-name buffer))
12014 (ibn (concat bn "(Clone)"))
12015 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12016 (with-current-buffer ib (org-overview))
12017 ib))))
12019 (defun org-do-occur (regexp &optional cleanup)
12020 "Call the Emacs command `occur'.
12021 If CLEANUP is non-nil, remove the printout of the regular expression
12022 in the *Occur* buffer. This is useful if the regex is long and not useful
12023 to read."
12024 (occur regexp)
12025 (when cleanup
12026 (let ((cwin (selected-window)) win beg end)
12027 (when (setq win (get-buffer-window "*Occur*"))
12028 (select-window win))
12029 (goto-char (point-min))
12030 (when (re-search-forward "match[a-z]+" nil t)
12031 (setq beg (match-end 0))
12032 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12033 (setq end (1- (match-beginning 0)))))
12034 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12035 (goto-char (point-min))
12036 (select-window cwin))))
12038 ;;; The mark ring for links jumps
12040 (defvar org-mark-ring nil
12041 "Mark ring for positions before jumps in Org-mode.")
12042 (defvar org-mark-ring-last-goto nil
12043 "Last position in the mark ring used to go back.")
12044 ;; Fill and close the ring
12045 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12046 (loop for i from 1 to org-mark-ring-length do
12047 (push (make-marker) org-mark-ring))
12048 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12049 org-mark-ring)
12051 (defun org-mark-ring-push (&optional pos buffer)
12052 "Put the current position or POS into the mark ring and rotate it."
12053 (interactive)
12054 (setq pos (or pos (point)))
12055 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12056 (move-marker (car org-mark-ring)
12057 (or pos (point))
12058 (or buffer (current-buffer)))
12059 (message
12060 (substitute-command-keys
12061 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12063 (defun org-mark-ring-goto (&optional n)
12064 "Jump to the previous position in the mark ring.
12065 With prefix arg N, jump back that many stored positions. When
12066 called several times in succession, walk through the entire ring.
12067 Org-mode commands jumping to a different position in the current file,
12068 or to another Org-mode file, automatically push the old position
12069 onto the ring."
12070 (interactive "p")
12071 (let (p m)
12072 (if (eq last-command this-command)
12073 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12074 (setq p org-mark-ring))
12075 (setq org-mark-ring-last-goto p)
12076 (setq m (car p))
12077 (switch-to-buffer (marker-buffer m))
12078 (goto-char m)
12079 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12081 (defun org-remove-angle-brackets (s)
12082 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12083 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12085 (defun org-add-angle-brackets (s)
12086 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12087 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12090 ;;; Following specific links
12092 (defun org-follow-timestamp-link ()
12093 (cond
12094 ((org-at-date-range-p t)
12095 (let ((org-agenda-start-on-weekday)
12096 (t1 (match-string 1))
12097 (t2 (match-string 2)))
12098 (setq t1 (time-to-days (org-time-string-to-time t1))
12099 t2 (time-to-days (org-time-string-to-time t2)))
12100 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12101 ((org-at-timestamp-p t)
12102 (org-agenda-list nil (time-to-days (org-time-string-to-time
12103 (substring (match-string 1) 0 10)))
12105 (t (error "This should not happen"))))
12108 (defun org-follow-bbdb-link (name)
12109 "Follow a BBDB link to NAME."
12110 (require 'bbdb)
12111 (let ((inhibit-redisplay (not debug-on-error))
12112 (bbdb-electric-p nil))
12113 (catch 'exit
12114 ;; Exact match on name
12115 (bbdb-name (concat "\\`" name "\\'") nil)
12116 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12117 ;; Exact match on name
12118 (bbdb-company (concat "\\`" name "\\'") nil)
12119 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12120 ;; Partial match on name
12121 (bbdb-name name nil)
12122 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12123 ;; Partial match on company
12124 (bbdb-company name nil)
12125 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12126 ;; General match including network address and notes
12127 (bbdb name nil)
12128 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12129 (delete-window (get-buffer-window "*BBDB*"))
12130 (error "No matching BBDB record")))))
12132 (defun org-follow-info-link (name)
12133 "Follow an info file & node link to NAME."
12134 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12135 (string-match "\\(.*\\)" name))
12136 (progn
12137 (require 'info)
12138 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12139 (Info-find-node (match-string 1 name) (match-string 2 name))
12140 (Info-find-node (match-string 1 name) "Top")))
12141 (message (concat "Could not open: " name))))
12143 (defun org-follow-gnus-link (&optional group article)
12144 "Follow a Gnus link to GROUP and ARTICLE."
12145 (require 'gnus)
12146 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12147 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12148 (cond ((and group article)
12149 (gnus-group-read-group 1 nil group)
12150 (gnus-summary-goto-article (string-to-number article) nil t))
12151 (group (gnus-group-jump-to-group group))))
12153 (defun org-follow-vm-link (&optional folder article readonly)
12154 "Follow a VM link to FOLDER and ARTICLE."
12155 (require 'vm)
12156 (setq article (org-add-angle-brackets article))
12157 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12158 ;; ange-ftp or efs or tramp access
12159 (let ((user (or (match-string 1 folder) (user-login-name)))
12160 (host (match-string 2 folder))
12161 (file (match-string 3 folder)))
12162 (cond
12163 ((featurep 'tramp)
12164 ;; use tramp to access the file
12165 (if (featurep 'xemacs)
12166 (setq folder (format "[%s@%s]%s" user host file))
12167 (setq folder (format "/%s@%s:%s" user host file))))
12169 ;; use ange-ftp or efs
12170 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12171 (setq folder (format "/%s@%s:%s" user host file))))))
12172 (when folder
12173 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12174 (sit-for 0.1)
12175 (when article
12176 (vm-select-folder-buffer)
12177 (widen)
12178 (let ((case-fold-search t))
12179 (goto-char (point-min))
12180 (if (not (re-search-forward
12181 (concat "^" "message-id: *" (regexp-quote article))))
12182 (error "Could not find the specified message in this folder"))
12183 (vm-isearch-update)
12184 (vm-isearch-narrow)
12185 (vm-beginning-of-message)
12186 (vm-summarize)))))
12188 (defun org-follow-wl-link (folder article)
12189 "Follow a Wanderlust link to FOLDER and ARTICLE."
12190 (if (and (string= folder "%")
12191 article
12192 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12193 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12194 ;; Thus, we recompose folder and article ids.
12195 (setq folder (format "%s#%s" folder (match-string 1 article))
12196 article (match-string 3 article)))
12197 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12198 (error "No such folder: %s" folder))
12199 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12200 (and article
12201 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12202 (wl-summary-redisplay)))
12204 (defun org-follow-rmail-link (folder article)
12205 "Follow an RMAIL link to FOLDER and ARTICLE."
12206 (setq article (org-add-angle-brackets article))
12207 (let (message-number)
12208 (save-excursion
12209 (save-window-excursion
12210 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12211 (setq message-number
12212 (save-restriction
12213 (widen)
12214 (goto-char (point-max))
12215 (if (re-search-backward
12216 (concat "^Message-ID:\\s-+" (regexp-quote
12217 (or article "")))
12218 nil t)
12219 (rmail-what-message))))))
12220 (if message-number
12221 (progn
12222 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12223 (rmail-show-message message-number)
12224 message-number)
12225 (error "Message not found"))))
12227 ;;; mh-e integration based on planner-mode
12228 (defun org-mhe-get-message-real-folder ()
12229 "Return the name of the current message real folder, so if you use
12230 sequences, it will now work."
12231 (save-excursion
12232 (let* ((folder
12233 (if (equal major-mode 'mh-folder-mode)
12234 mh-current-folder
12235 ;; Refer to the show buffer
12236 mh-show-folder-buffer))
12237 (end-index
12238 (if (boundp 'mh-index-folder)
12239 (min (length mh-index-folder) (length folder))))
12241 ;; a simple test on mh-index-data does not work, because
12242 ;; mh-index-data is always nil in a show buffer.
12243 (if (and (boundp 'mh-index-folder)
12244 (string= mh-index-folder (substring folder 0 end-index)))
12245 (if (equal major-mode 'mh-show-mode)
12246 (save-window-excursion
12247 (let (pop-up-frames)
12248 (when (buffer-live-p (get-buffer folder))
12249 (progn
12250 (pop-to-buffer folder)
12251 (org-mhe-get-message-folder-from-index)
12254 (org-mhe-get-message-folder-from-index)
12256 folder
12260 (defun org-mhe-get-message-folder-from-index ()
12261 "Returns the name of the message folder in a index folder buffer."
12262 (save-excursion
12263 (mh-index-previous-folder)
12264 (re-search-forward "^\\(+.*\\)$" nil t)
12265 (message (match-string 1))))
12267 (defun org-mhe-get-message-folder ()
12268 "Return the name of the current message folder. Be careful if you
12269 use sequences."
12270 (save-excursion
12271 (if (equal major-mode 'mh-folder-mode)
12272 mh-current-folder
12273 ;; Refer to the show buffer
12274 mh-show-folder-buffer)))
12276 (defun org-mhe-get-message-num ()
12277 "Return the number of the current message. Be careful if you
12278 use sequences."
12279 (save-excursion
12280 (if (equal major-mode 'mh-folder-mode)
12281 (mh-get-msg-num nil)
12282 ;; Refer to the show buffer
12283 (mh-show-buffer-message-number))))
12285 (defun org-mhe-get-header (header)
12286 "Return a header of the message in folder mode. This will create a
12287 show buffer for the corresponding message. If you have a more clever
12288 idea..."
12289 (let* ((folder (org-mhe-get-message-folder))
12290 (num (org-mhe-get-message-num))
12291 (buffer (get-buffer-create (concat "show-" folder)))
12292 (header-field))
12293 (with-current-buffer buffer
12294 (mh-display-msg num folder)
12295 (if (equal major-mode 'mh-folder-mode)
12296 (mh-header-display)
12297 (mh-show-header-display))
12298 (set-buffer buffer)
12299 (setq header-field (mh-get-header-field header))
12300 (if (equal major-mode 'mh-folder-mode)
12301 (mh-show)
12302 (mh-show-show))
12303 header-field)))
12305 (defun org-follow-mhe-link (folder article)
12306 "Follow an MHE link to FOLDER and ARTICLE.
12307 If ARTICLE is nil FOLDER is shown. If the configuration variable
12308 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
12309 ARTICLE is searched in all folders. Indexed searches (swish++,
12310 namazu, and others supported by MH-E) will always search in all
12311 folders."
12312 (require 'mh-e)
12313 (require 'mh-search)
12314 (require 'mh-utils)
12315 (mh-find-path)
12316 (if (not article)
12317 (mh-visit-folder (mh-normalize-folder-name folder))
12318 (setq article (org-add-angle-brackets article))
12319 (mh-search-choose)
12320 (if (equal mh-searcher 'pick)
12321 (progn
12322 (mh-search folder (list "--message-id" article))
12323 (when (and org-mhe-search-all-folders
12324 (not (org-mhe-get-message-real-folder)))
12325 (kill-this-buffer)
12326 (mh-search "+" (list "--message-id" article))))
12327 (mh-search "+" article))
12328 (if (org-mhe-get-message-real-folder)
12329 (mh-show-msg 1)
12330 (kill-this-buffer)
12331 (error "Message not found"))))
12333 ;;; BibTeX links
12335 ;; Use the custom search meachnism to construct and use search strings for
12336 ;; file links to BibTeX database entries.
12338 (defun org-create-file-search-in-bibtex ()
12339 "Create the search string and description for a BibTeX database entry."
12340 (when (eq major-mode 'bibtex-mode)
12341 ;; yes, we want to construct this search string.
12342 ;; Make a good description for this entry, using names, year and the title
12343 ;; Put it into the `description' variable which is dynamically scoped.
12344 (let ((bibtex-autokey-names 1)
12345 (bibtex-autokey-names-stretch 1)
12346 (bibtex-autokey-name-case-convert-function 'identity)
12347 (bibtex-autokey-name-separator " & ")
12348 (bibtex-autokey-additional-names " et al.")
12349 (bibtex-autokey-year-length 4)
12350 (bibtex-autokey-name-year-separator " ")
12351 (bibtex-autokey-titlewords 3)
12352 (bibtex-autokey-titleword-separator " ")
12353 (bibtex-autokey-titleword-case-convert-function 'identity)
12354 (bibtex-autokey-titleword-length 'infty)
12355 (bibtex-autokey-year-title-separator ": "))
12356 (setq description (bibtex-generate-autokey)))
12357 ;; Now parse the entry, get the key and return it.
12358 (save-excursion
12359 (bibtex-beginning-of-entry)
12360 (cdr (assoc "=key=" (bibtex-parse-entry))))))
12362 (defun org-execute-file-search-in-bibtex (s)
12363 "Find the link search string S as a key for a database entry."
12364 (when (eq major-mode 'bibtex-mode)
12365 ;; Yes, we want to do the search in this file.
12366 ;; We construct a regexp that searches for "@entrytype{" followed by the key
12367 (goto-char (point-min))
12368 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
12369 (regexp-quote s) "[ \t\n]*,") nil t)
12370 (goto-char (match-beginning 0)))
12371 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
12372 ;; Use double prefix to indicate that any web link should be browsed
12373 (let ((b (current-buffer)) (p (point)))
12374 ;; Restore the window configuration because we just use the web link
12375 (set-window-configuration org-window-config-before-follow-link)
12376 (save-excursion (set-buffer b) (goto-char p)
12377 (bibtex-url)))
12378 (recenter 0)) ; Move entry start to beginning of window
12379 ;; return t to indicate that the search is done.
12382 ;; Finally add the functions to the right hooks.
12383 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
12384 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
12386 ;; end of Bibtex link setup
12388 ;;; Following file links
12390 (defun org-open-file (path &optional in-emacs line search)
12391 "Open the file at PATH.
12392 First, this expands any special file name abbreviations. Then the
12393 configuration variable `org-file-apps' is checked if it contains an
12394 entry for this file type, and if yes, the corresponding command is launched.
12395 If no application is found, Emacs simply visits the file.
12396 With optional argument IN-EMACS, Emacs will visit the file.
12397 Optional LINE specifies a line to go to, optional SEARCH a string to
12398 search for. If LINE or SEARCH is given, the file will always be
12399 opened in Emacs.
12400 If the file does not exist, an error is thrown."
12401 (setq in-emacs (or in-emacs line search))
12402 (let* ((file (if (equal path "")
12403 buffer-file-name
12404 (substitute-in-file-name (expand-file-name path))))
12405 (apps (append org-file-apps (org-default-apps)))
12406 (remp (and (assq 'remote apps) (org-file-remote-p file)))
12407 (dirp (if remp nil (file-directory-p file)))
12408 (dfile (downcase file))
12409 (old-buffer (current-buffer))
12410 (old-pos (point))
12411 (old-mode major-mode)
12412 ext cmd)
12413 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
12414 (setq ext (match-string 1 dfile))
12415 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
12416 (setq ext (match-string 1 dfile))))
12417 (if in-emacs
12418 (setq cmd 'emacs)
12419 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
12420 (and dirp (cdr (assoc 'directory apps)))
12421 (cdr (assoc ext apps))
12422 (cdr (assoc t apps)))))
12423 (when (eq cmd 'mailcap)
12424 (require 'mailcap)
12425 (mailcap-parse-mailcaps)
12426 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
12427 (command (mailcap-mime-info mime-type)))
12428 (if (stringp command)
12429 (setq cmd command)
12430 (setq cmd 'emacs))))
12431 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
12432 (not (file-exists-p file))
12433 (not org-open-non-existing-files))
12434 (error "No such file: %s" file))
12435 (cond
12436 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
12437 ;; Remove quotes around the file name - we'll use shell-quote-argument.
12438 (if (string-match "['\"]%s['\"]" cmd)
12439 (setq cmd (replace-match "%s" t t cmd)))
12440 (setq cmd (format cmd (shell-quote-argument file)))
12441 (save-window-excursion
12442 (start-process-shell-command cmd nil cmd)))
12443 ((or (stringp cmd)
12444 (eq cmd 'emacs))
12445 (funcall (cdr (assq 'file org-link-frame-setup)) file)
12446 (widen)
12447 (if line (goto-line line)
12448 (if search (org-link-search search))))
12449 ((consp cmd)
12450 (eval cmd))
12451 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
12452 (and (org-mode-p) (eq old-mode 'org-mode)
12453 (or (not (equal old-buffer (current-buffer)))
12454 (not (equal old-pos (point))))
12455 (org-mark-ring-push old-pos old-buffer))))
12457 (defun org-default-apps ()
12458 "Return the default applications for this operating system."
12459 (cond
12460 ((eq system-type 'darwin)
12461 org-file-apps-defaults-macosx)
12462 ((eq system-type 'windows-nt)
12463 org-file-apps-defaults-windowsnt)
12464 (t org-file-apps-defaults-gnu)))
12466 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
12467 (defun org-file-remote-p (file)
12468 "Test whether FILE specifies a location on a remote system.
12469 Return non-nil if the location is indeed remote.
12471 For example, the filename \"/user@host:/foo\" specifies a location
12472 on the system \"/user@host:\"."
12473 (cond ((fboundp 'file-remote-p)
12474 (file-remote-p file))
12475 ((fboundp 'tramp-handle-file-remote-p)
12476 (tramp-handle-file-remote-p file))
12477 ((and (boundp 'ange-ftp-name-format)
12478 (string-match (car ange-ftp-name-format) file))
12480 (t nil)))
12483 ;;;; Hooks for remember.el
12485 ;;;###autoload
12486 (defun org-remember-annotation ()
12487 "Return a link to the current location as an annotation for remember.el.
12488 If you are using Org-mode files as target for data storage with
12489 remember.el, then the annotations should include a link compatible with the
12490 conventions in Org-mode. This function returns such a link."
12491 (org-store-link nil))
12493 (defconst org-remember-help
12494 "Select a destination location for the note.
12495 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
12496 RET on headline -> Store as sublevel entry to current headline
12497 RET at beg-of-buf -> Append to file as level 2 headline
12498 <left>/<right> -> before/after current headline, same headings level")
12500 (defvar org-remember-previous-location nil)
12501 (defvar org-force-remember-template-char) ;; dynamically scoped
12503 ;;;###autoload
12504 (defun org-remember-apply-template (&optional use-char skip-interactive)
12505 "Initialize *remember* buffer with template, invoke `org-mode'.
12506 This function should be placed into `remember-mode-hook' and in fact requires
12507 to be run from that hook to fucntion properly."
12508 (if org-remember-templates
12509 (let* ((templates (mapcar (lambda (x)
12510 (if (stringp (car x))
12511 (append (list (nth 1 x) (car x)) (cddr x))
12512 (append (list (car x) "") (cdr x))))
12513 org-remember-templates))
12514 (char (or use-char
12515 (cond
12516 ((= (length templates) 1)
12517 (caar templates))
12518 ((and (boundp 'org-force-remember-template-char)
12519 org-force-remember-template-char)
12520 (if (stringp org-force-remember-template-char)
12521 (string-to-char org-force-remember-template-char)
12522 org-force-remember-template-char))
12524 (message "Select template: %s"
12525 (mapconcat
12526 (lambda (x)
12527 (cond
12528 ((not (string-match "\\S-" (nth 1 x)))
12529 (format "[%c]" (car x)))
12530 ((equal (downcase (car x))
12531 (downcase (aref (nth 1 x) 0)))
12532 (format "[%c]%s" (car x) (substring (nth 1 x) 1)))
12533 (t (format "[%c]%s" (car x) (nth 1 x)))))
12534 templates " "))
12535 (read-char-exclusive)))))
12536 (entry (cddr (assoc char templates)))
12537 (tpl (car entry))
12538 (plist-p (if org-store-link-plist t nil))
12539 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
12540 (string-match "\\S-" (nth 1 entry)))
12541 (nth 1 entry)
12542 org-default-notes-file))
12543 (headline (nth 2 entry))
12544 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
12545 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
12546 (v-u (concat "[" (substring v-t 1 -1) "]"))
12547 (v-U (concat "[" (substring v-T 1 -1) "]"))
12548 ;; `initial' and `annotation' are bound in `remember'
12549 (v-i (if (boundp 'initial) initial))
12550 (v-a (if (and (boundp 'annotation) annotation)
12551 (if (equal annotation "[[]]") "" annotation)
12552 ""))
12553 (v-A (if (and v-a
12554 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
12555 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
12556 v-a))
12557 (v-n user-full-name)
12558 (org-startup-folded nil)
12559 org-time-was-given org-end-time-was-given x prompt char time)
12560 (setq org-store-link-plist
12561 (append (list :annotation v-a :initial v-i)
12562 org-store-link-plist))
12563 (unless tpl (setq tpl "") (message "No template") (ding))
12564 (erase-buffer)
12565 (insert (substitute-command-keys
12566 (format
12567 "## Filing location: Select interactively, default, or last used:
12568 ## %s to select file and header location interactively.
12569 ## %s \"%s\" -> \"* %s\"
12570 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
12571 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
12572 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
12573 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
12574 (abbreviate-file-name (or file org-default-notes-file))
12575 (or headline "")
12576 (or (car org-remember-previous-location) "???")
12577 (or (cdr org-remember-previous-location) "???"))))
12578 (insert tpl) (goto-char (point-min))
12579 ;; Simple %-escapes
12580 (while (re-search-forward "%\\([tTuUaiA]\\)" nil t)
12581 (when (and initial (equal (match-string 0) "%i"))
12582 (save-match-data
12583 (let* ((lead (buffer-substring
12584 (point-at-bol) (match-beginning 0))))
12585 (setq v-i (mapconcat 'identity
12586 (org-split-string initial "\n")
12587 (concat "\n" lead))))))
12588 (replace-match
12589 (or (eval (intern (concat "v-" (match-string 1)))) "")
12590 t t))
12591 ;; From the property list
12592 (when plist-p
12593 (goto-char (point-min))
12594 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
12595 (and (setq x (plist-get org-store-link-plist
12596 (intern (match-string 1))))
12597 (replace-match x t t))))
12598 ;; Turn on org-mode in the remember buffer, set local variables
12599 (org-mode)
12600 (org-set-local 'org-finish-function 'remember-buffer)
12601 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
12602 (org-set-local 'org-default-notes-file file))
12603 (if (and headline (stringp headline) (string-match "\\S-" headline))
12604 (org-set-local 'org-remember-default-headline headline))
12605 ;; Interactive template entries
12606 (goto-char (point-min))
12607 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
12608 (setq char (if (match-end 3) (match-string 3))
12609 prompt (if (match-end 2) (match-string 2)))
12610 (goto-char (match-beginning 0))
12611 (replace-match "")
12612 (cond
12613 ((member char '("G" "g"))
12614 (let* ((org-last-tags-completion-table
12615 (org-global-tags-completion-table
12616 (if (equal char "G") (org-agenda-files) (and file (list file)))))
12617 (org-add-colon-after-tag-completion t)
12618 (ins (completing-read
12619 (if prompt (concat prompt ": ") "Tags: ")
12620 'org-tags-completion-function nil nil nil
12621 'org-tags-history)))
12622 (setq ins (mapconcat 'identity
12623 (org-split-string ins (org-re "[^[:alnum:]]+"))
12624 ":"))
12625 (when (string-match "\\S-" ins)
12626 (or (equal (char-before) ?:) (insert ":"))
12627 (insert ins)
12628 (or (equal (char-after) ?:) (insert ":")))))
12629 (char
12630 (setq org-time-was-given (equal (upcase char) char))
12631 (setq time (org-read-date (equal (upcase char) "U") t nil
12632 prompt))
12633 (org-insert-time-stamp time org-time-was-given
12634 (member char '("u" "U"))
12635 nil nil (list org-end-time-was-given)))
12637 (insert (read-string
12638 (if prompt (concat prompt ": ") "Enter string"))))))
12639 (goto-char (point-min))
12640 (if (re-search-forward "%\\?" nil t)
12641 (replace-match "")
12642 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
12643 (org-mode)
12644 (org-set-local 'org-finish-function 'remember-buffer)))
12646 ;;;###autoload
12647 (defun org-remember (&optional org-force-remember-template-char)
12648 "Call `remember'. If this is already a remember buffer, re-apply template.
12649 If there is an active region, make sure remember uses it as initial content
12650 of the remember buffer."
12651 (interactive)
12652 (if (eq org-finish-function 'remember-buffer)
12653 (progn
12654 (when (< (length org-remember-templates) 2)
12655 (error "No other template available"))
12656 (erase-buffer)
12657 (let ((annotation (plist-get org-store-link-plist :annotation))
12658 (initial (plist-get org-store-link-plist :initial)))
12659 (org-remember-apply-template))
12660 (message "Press C-c C-c to remember data"))
12661 (if (org-region-active-p)
12662 (remember (buffer-substring (point) (mark)))
12663 (call-interactively 'remember))))
12665 (defvar org-note-abort nil) ; dynamically scoped
12667 ;;;###autoload
12668 (defun org-remember-handler ()
12669 "Store stuff from remember.el into an org file.
12670 First prompts for an org file. If the user just presses return, the value
12671 of `org-default-notes-file' is used.
12672 Then the command offers the headings tree of the selected file in order to
12673 file the text at a specific location.
12674 You can either immediately press RET to get the note appended to the
12675 file, or you can use vertical cursor motion and visibility cycling (TAB) to
12676 find a better place. Then press RET or <left> or <right> in insert the note.
12678 Key Cursor position Note gets inserted
12679 -----------------------------------------------------------------------------
12680 RET buffer-start as level 1 heading at end of file
12681 RET on headline as sublevel of the heading at cursor
12682 RET no heading at cursor position, level taken from context.
12683 Or use prefix arg to specify level manually.
12684 <left> on headline as same level, before current heading
12685 <right> on headline as same level, after current heading
12687 So the fastest way to store the note is to press RET RET to append it to
12688 the default file. This way your current train of thought is not
12689 interrupted, in accordance with the principles of remember.el.
12690 You can also get the fast execution without prompting by using
12691 C-u C-c C-c to exit the remember buffer. See also the variable
12692 `org-remember-store-without-prompt'.
12694 Before being stored away, the function ensures that the text has a
12695 headline, i.e. a first line that starts with a \"*\". If not, a headline
12696 is constructed from the current date and some additional data.
12698 If the variable `org-adapt-indentation' is non-nil, the entire text is
12699 also indented so that it starts in the same column as the headline
12700 \(i.e. after the stars).
12702 See also the variable `org-reverse-note-order'."
12703 (goto-char (point-min))
12704 (while (looking-at "^[ \t]*\n\\|^##.*\n")
12705 (replace-match ""))
12706 (goto-char (point-max))
12707 (unless (equal (char-before) ?\n) (insert "\n"))
12708 (catch 'quit
12709 (if org-note-abort (throw 'quit nil))
12710 (let* ((txt (buffer-substring (point-min) (point-max)))
12711 (fastp (org-xor (equal current-prefix-arg '(4))
12712 org-remember-store-without-prompt))
12713 (file (if fastp org-default-notes-file (org-get-org-file)))
12714 (heading org-remember-default-headline)
12715 (visiting (org-find-base-buffer-visiting file))
12716 (org-startup-folded nil)
12717 (org-startup-align-all-tables nil)
12718 (org-goto-start-pos 1)
12719 spos exitcmd level indent reversed)
12720 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
12721 (setq file (car org-remember-previous-location)
12722 heading (cdr org-remember-previous-location)))
12723 (setq current-prefix-arg nil)
12724 ;; Modify text so that it becomes a nice subtree which can be inserted
12725 ;; into an org tree.
12726 (let* ((lines (split-string txt "\n"))
12727 first)
12728 (setq first (car lines) lines (cdr lines))
12729 (if (string-match "^\\*+ " first)
12730 ;; Is already a headline
12731 (setq indent nil)
12732 ;; We need to add a headline: Use time and first buffer line
12733 (setq lines (cons first lines)
12734 first (concat "* " (current-time-string)
12735 " (" (remember-buffer-desc) ")")
12736 indent " "))
12737 (if (and org-adapt-indentation indent)
12738 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
12739 (setq txt (concat first "\n"
12740 (mapconcat 'identity lines "\n"))))
12741 ;; Find the file
12742 (if (not visiting) (find-file-noselect file))
12743 (with-current-buffer (or visiting (get-file-buffer file))
12744 (unless (org-mode-p)
12745 (error "Target files for remember notes must be in Org-mode"))
12746 (save-excursion
12747 (save-restriction
12748 (widen)
12749 (and (goto-char (point-min))
12750 (not (re-search-forward "^\\* " nil t))
12751 (insert "\n* " (or heading "Notes") "\n"))
12752 (setq reversed (org-notes-order-reversed-p))
12754 ;; Find the default location
12755 (when (and heading (stringp heading) (string-match "\\S-" heading))
12756 (goto-char (point-min))
12757 (if (re-search-forward
12758 (concat "^\\*+[ \t]+" (regexp-quote heading)
12759 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
12760 nil t)
12761 (setq org-goto-start-pos (match-beginning 0))
12762 (when fastp
12763 (goto-char (point-max))
12764 (unless (bolp) (newline))
12765 (insert "* " heading "\n")
12766 (setq org-goto-start-pos (point-at-bol 0)))))
12768 ;; Ask the User for a location
12769 (if fastp
12770 (setq spos org-goto-start-pos
12771 exitcmd 'return)
12772 (setq spos (org-get-location (current-buffer) org-remember-help)
12773 exitcmd (cdr spos)
12774 spos (car spos)))
12775 (if (not spos) (throw 'quit nil)) ; return nil to show we did
12776 ; not handle this note
12777 (goto-char spos)
12778 (cond ((org-on-heading-p t)
12779 (org-back-to-heading t)
12780 (setq level (funcall outline-level))
12781 (cond
12782 ((eq exitcmd 'return)
12783 ;; sublevel of current
12784 (setq org-remember-previous-location
12785 (cons (abbreviate-file-name file)
12786 (org-get-heading 'notags)))
12787 (if reversed
12788 (outline-next-heading)
12789 (org-end-of-subtree)
12790 (if (not (bolp))
12791 (if (looking-at "[ \t]*\n")
12792 (beginning-of-line 2)
12793 (end-of-line 1)
12794 (insert "\n"))))
12795 (org-paste-subtree (org-get-legal-level level 1) txt))
12796 ((eq exitcmd 'left)
12797 ;; before current
12798 (org-paste-subtree level txt))
12799 ((eq exitcmd 'right)
12800 ;; after current
12801 (org-end-of-subtree t)
12802 (org-paste-subtree level txt))
12803 (t (error "This should not happen"))))
12805 ((and (bobp) (not reversed))
12806 ;; Put it at the end, one level below level 1
12807 (save-restriction
12808 (widen)
12809 (goto-char (point-max))
12810 (if (not (bolp)) (newline))
12811 (org-paste-subtree (org-get-legal-level 1 1) txt)))
12813 ((and (bobp) reversed)
12814 ;; Put it at the start, as level 1
12815 (save-restriction
12816 (widen)
12817 (goto-char (point-min))
12818 (re-search-forward "^\\*+ " nil t)
12819 (beginning-of-line 1)
12820 (org-paste-subtree 1 txt)))
12822 ;; Put it right there, with automatic level determined by
12823 ;; org-paste-subtree or from prefix arg
12824 (org-paste-subtree
12825 (if (numberp current-prefix-arg) current-prefix-arg)
12826 txt)))
12827 (when remember-save-after-remembering
12828 (save-buffer)
12829 (if (not visiting) (kill-buffer (current-buffer)))))))))
12830 t) ;; return t to indicate that we took care of this note.
12832 (defun org-get-org-file ()
12833 "Read a filename, with default directory `org-directory'."
12834 (let ((default (or org-default-notes-file remember-data-file)))
12835 (read-file-name (format "File name [%s]: " default)
12836 (file-name-as-directory org-directory)
12837 default)))
12839 (defun org-notes-order-reversed-p ()
12840 "Check if the current file should receive notes in reversed order."
12841 (cond
12842 ((not org-reverse-note-order) nil)
12843 ((eq t org-reverse-note-order) t)
12844 ((not (listp org-reverse-note-order)) nil)
12845 (t (catch 'exit
12846 (let ((all org-reverse-note-order)
12847 entry)
12848 (while (setq entry (pop all))
12849 (if (string-match (car entry) buffer-file-name)
12850 (throw 'exit (cdr entry))))
12851 nil)))))
12853 ;;;; Dynamic blocks
12855 (defun org-find-dblock (name)
12856 "Find the first dynamic block with name NAME in the buffer.
12857 If not found, stay at current position and return nil."
12858 (let (pos)
12859 (save-excursion
12860 (goto-char (point-min))
12861 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
12862 nil t)
12863 (match-beginning 0))))
12864 (if pos (goto-char pos))
12865 pos))
12867 (defconst org-dblock-start-re
12868 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
12869 "Matches the startline of a dynamic block, with parameters.")
12871 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
12872 "Matches the end of a dyhamic block.")
12874 (defun org-create-dblock (plist)
12875 "Create a dynamic block section, with parameters taken from PLIST.
12876 PLIST must containe a :name entry which is used as name of the block."
12877 (unless (bolp) (newline))
12878 (let ((name (plist-get plist :name)))
12879 (insert "#+BEGIN: " name)
12880 (while plist
12881 (if (eq (car plist) :name)
12882 (setq plist (cddr plist))
12883 (insert " " (prin1-to-string (pop plist)))))
12884 (insert "\n\n#+END:\n")
12885 (beginning-of-line -2)))
12887 (defun org-prepare-dblock ()
12888 "Prepare dynamic block for refresh.
12889 This empties the block, puts the cursor at the insert position and returns
12890 the property list including an extra property :name with the block name."
12891 (unless (looking-at org-dblock-start-re)
12892 (error "Not at a dynamic block"))
12893 (let* ((begdel (1+ (match-end 0)))
12894 (name (org-no-properties (match-string 1)))
12895 (params (append (list :name name)
12896 (read (concat "(" (match-string 3) ")")))))
12897 (unless (re-search-forward org-dblock-end-re nil t)
12898 (error "Dynamic block not terminated"))
12899 (delete-region begdel (match-beginning 0))
12900 (goto-char begdel)
12901 (open-line 1)
12902 params))
12904 (defun org-map-dblocks (&optional command)
12905 "Apply COMMAND to all dynamic blocks in the current buffer.
12906 If COMMAND is not given, use `org-update-dblock'."
12907 (let ((cmd (or command 'org-update-dblock))
12908 pos)
12909 (save-excursion
12910 (goto-char (point-min))
12911 (while (re-search-forward org-dblock-start-re nil t)
12912 (goto-char (setq pos (match-beginning 0)))
12913 (condition-case nil
12914 (funcall cmd)
12915 (error (message "Error during update of dynamic block")))
12916 (goto-char pos)
12917 (unless (re-search-forward org-dblock-end-re nil t)
12918 (error "Dynamic block not terminated"))))))
12920 (defun org-dblock-update (&optional arg)
12921 "User command for updating dynamic blocks.
12922 Update the dynamic block at point. With prefix ARG, update all dynamic
12923 blocks in the buffer."
12924 (interactive "P")
12925 (if arg
12926 (org-update-all-dblocks)
12927 (or (looking-at org-dblock-start-re)
12928 (org-beginning-of-dblock))
12929 (org-update-dblock)))
12931 (defun org-update-dblock ()
12932 "Update the dynamic block at point
12933 This means to empty the block, parse for parameters and then call
12934 the correct writing function."
12935 (save-window-excursion
12936 (let* ((pos (point))
12937 (line (org-current-line))
12938 (params (org-prepare-dblock))
12939 (name (plist-get params :name))
12940 (cmd (intern (concat "org-dblock-write:" name))))
12941 (message "Updating dynamic block `%s' at line %d..." name line)
12942 (funcall cmd params)
12943 (message "Updating dynamic block `%s' at line %d...done" name line)
12944 (goto-char pos))))
12946 (defun org-beginning-of-dblock ()
12947 "Find the beginning of the dynamic block at point.
12948 Error if there is no scuh block at point."
12949 (let ((pos (point))
12950 beg)
12951 (end-of-line 1)
12952 (if (and (re-search-backward org-dblock-start-re nil t)
12953 (setq beg (match-beginning 0))
12954 (re-search-forward org-dblock-end-re nil t)
12955 (> (match-end 0) pos))
12956 (goto-char beg)
12957 (goto-char pos)
12958 (error "Not in a dynamic block"))))
12960 (defun org-update-all-dblocks ()
12961 "Update all dynamic blocks in the buffer.
12962 This function can be used in a hook."
12963 (when (org-mode-p)
12964 (org-map-dblocks 'org-update-dblock)))
12967 ;;;; Completion
12969 (defconst org-additional-option-like-keywords
12970 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
12971 "ORGTBL" "HTML:" "LaTeX:"))
12973 (defun org-complete (&optional arg)
12974 "Perform completion on word at point.
12975 At the beginning of a headline, this completes TODO keywords as given in
12976 `org-todo-keywords'.
12977 If the current word is preceded by a backslash, completes the TeX symbols
12978 that are supported for HTML support.
12979 If the current word is preceded by \"#+\", completes special words for
12980 setting file options.
12981 In the line after \"#+STARTUP:, complete valid keywords.\"
12982 At all other locations, this simply calls the value of
12983 `org-completion-fallback-command'."
12984 (interactive "P")
12985 (org-without-partial-completion
12986 (catch 'exit
12987 (let* ((end (point))
12988 (beg1 (save-excursion
12989 (skip-chars-backward (org-re "[:alnum:]_@"))
12990 (point)))
12991 (beg (save-excursion
12992 (skip-chars-backward "a-zA-Z0-9_:$")
12993 (point)))
12994 (confirm (lambda (x) (stringp (car x))))
12995 (searchhead (equal (char-before beg) ?*))
12996 (tag (and (equal (char-before beg1) ?:)
12997 (equal (char-after (point-at-bol)) ?*)))
12998 (prop (and (equal (char-before beg1) ?:)
12999 (not (equal (char-after (point-at-bol)) ?*))))
13000 (texp (equal (char-before beg) ?\\))
13001 (link (equal (char-before beg) ?\[))
13002 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
13003 beg)
13004 "#+"))
13005 (startup (string-match "^#\\+STARTUP:.*"
13006 (buffer-substring (point-at-bol) (point))))
13007 (completion-ignore-case opt)
13008 (type nil)
13009 (tbl nil)
13010 (table (cond
13011 (opt
13012 (setq type :opt)
13013 (append
13014 (mapcar
13015 (lambda (x)
13016 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
13017 (cons (match-string 2 x) (match-string 1 x)))
13018 (org-split-string (org-get-current-options) "\n"))
13019 (mapcar 'list org-additional-option-like-keywords)))
13020 (startup
13021 (setq type :startup)
13022 org-startup-options)
13023 (link (append org-link-abbrev-alist-local
13024 org-link-abbrev-alist))
13025 (texp
13026 (setq type :tex)
13027 org-html-entities)
13028 ((string-match "\\`\\*+[ \t]+\\'"
13029 (buffer-substring (point-at-bol) beg))
13030 (setq type :todo)
13031 (mapcar 'list org-todo-keywords-1))
13032 (searchhead
13033 (setq type :searchhead)
13034 (save-excursion
13035 (goto-char (point-min))
13036 (while (re-search-forward org-todo-line-regexp nil t)
13037 (push (list
13038 (org-make-org-heading-search-string
13039 (match-string 3) t))
13040 tbl)))
13041 tbl)
13042 (tag (setq type :tag beg beg1)
13043 (or org-tag-alist (org-get-buffer-tags)))
13044 (prop (setq type :prop beg beg1)
13045 (mapcar 'list (org-buffer-property-keys)))
13046 (t (progn
13047 (call-interactively org-completion-fallback-command)
13048 (throw 'exit nil)))))
13049 (pattern (buffer-substring-no-properties beg end))
13050 (completion (try-completion pattern table confirm)))
13051 (cond ((eq completion t)
13052 (if (not (assoc (upcase pattern) table))
13053 (message "Already complete")
13054 (if (equal type :opt)
13055 (insert (substring (cdr (assoc (upcase pattern) table))
13056 (length pattern)))
13057 (if (memq type '(:tag :prop)) (insert ":")))))
13058 ((null completion)
13059 (message "Can't find completion for \"%s\"" pattern)
13060 (ding))
13061 ((not (string= pattern completion))
13062 (delete-region beg end)
13063 (if (string-match " +$" completion)
13064 (setq completion (replace-match "" t t completion)))
13065 (insert completion)
13066 (if (get-buffer-window "*Completions*")
13067 (delete-window (get-buffer-window "*Completions*")))
13068 (if (assoc completion table)
13069 (if (eq type :todo) (insert " ")
13070 (if (memq type '(:tag :prop)) (insert ":"))))
13071 (if (and (equal type :opt) (assoc completion table))
13072 (message "%s" (substitute-command-keys
13073 "Press \\[org-complete] again to insert example settings"))))
13075 (message "Making completion list...")
13076 (let ((list (sort (all-completions pattern table confirm)
13077 'string<)))
13078 (with-output-to-temp-buffer "*Completions*"
13079 (condition-case nil
13080 ;; Protection needed for XEmacs and emacs 21
13081 (display-completion-list list pattern)
13082 (error (display-completion-list list)))))
13083 (message "Making completion list...%s" "done")))))))
13085 ;;;; TODO, DEADLINE, Comments
13087 (defun org-toggle-comment ()
13088 "Change the COMMENT state of an entry."
13089 (interactive)
13090 (save-excursion
13091 (org-back-to-heading)
13092 (if (looking-at (concat outline-regexp
13093 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
13094 (replace-match "" t t nil 1)
13095 (if (looking-at outline-regexp)
13096 (progn
13097 (goto-char (match-end 0))
13098 (insert org-comment-string " "))))))
13100 (defvar org-last-todo-state-is-todo nil
13101 "This is non-nil when the last TODO state change led to a TODO state.
13102 If the last change removed the TODO tag or switched to DONE, then
13103 this is nil.")
13105 (defvar org-setting-tags nil) ; dynamically skiped
13107 ;; FIXME: better place
13108 (defun org-property-or-variable-value (var &optional inherit)
13109 "Check if there is a property fixing the value of VAR.
13110 If yes, return this value. If not, return the current value of the variable."
13111 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13112 (if (and prop (stringp prop) (string-match "\\S-" prop))
13113 (read prop)
13114 (symbol-value var))))
13116 (defun org-todo (&optional arg)
13117 "Change the TODO state of an item.
13118 The state of an item is given by a keyword at the start of the heading,
13119 like
13120 *** TODO Write paper
13121 *** DONE Call mom
13123 The different keywords are specified in the variable `org-todo-keywords'.
13124 By default the available states are \"TODO\" and \"DONE\".
13125 So for this example: when the item starts with TODO, it is changed to DONE.
13126 When it starts with DONE, the DONE is removed. And when neither TODO nor
13127 DONE are present, add TODO at the beginning of the heading.
13129 With C-u prefix arg, use completion to determine the new state.
13130 With numeric prefix arg, switch to that state.
13132 For calling through lisp, arg is also interpreted in the following way:
13133 'none -> empty state
13134 \"\"(empty string) -> switch to empty state
13135 'done -> switch to DONE
13136 'nextset -> switch to the next set of keywords
13137 'previousset -> switch to the previous set of keywords
13138 \"WAITING\" -> switch to the specified keyword, but only if it
13139 really is a member of `org-todo-keywords'."
13140 (interactive "P")
13141 (save-excursion
13142 (org-back-to-heading)
13143 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
13144 (or (looking-at (concat " +" org-todo-regexp " *"))
13145 (looking-at " *"))
13146 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
13147 (org-log-done (org-parse-local-options logging 'org-log-done))
13148 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
13149 (this (match-string 1))
13150 (hl-pos (match-beginning 0))
13151 (head (org-get-todo-sequence-head this))
13152 (ass (assoc head org-todo-kwd-alist))
13153 (interpret (nth 1 ass))
13154 (done-word (nth 3 ass))
13155 (final-done-word (nth 4 ass))
13156 (last-state (or this ""))
13157 (completion-ignore-case t)
13158 (member (member this org-todo-keywords-1))
13159 (tail (cdr member))
13160 (state (cond
13161 ((and org-todo-key-trigger
13162 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
13163 (and (not arg) org-use-fast-todo-selection
13164 (not (eq org-use-fast-todo-selection 'prefix)))))
13165 ;; Use fast selection
13166 (org-fast-todo-selection))
13167 ((and (equal arg '(4))
13168 (or (not org-use-fast-todo-selection)
13169 (not org-todo-key-trigger)))
13170 ;; Read a state with completion
13171 (completing-read "State: " (mapcar (lambda(x) (list x))
13172 org-todo-keywords-1)
13173 nil t))
13174 ((eq arg 'right)
13175 (if this
13176 (if tail (car tail) nil)
13177 (car org-todo-keywords-1)))
13178 ((eq arg 'left)
13179 (if (equal member org-todo-keywords-1)
13181 (if this
13182 (nth (- (length org-todo-keywords-1) (length tail) 2)
13183 org-todo-keywords-1)
13184 (org-last org-todo-keywords-1))))
13185 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
13186 (setq arg nil))) ; hack to fall back to cycling
13187 (arg
13188 ;; user or caller requests a specific state
13189 (cond
13190 ((equal arg "") nil)
13191 ((eq arg 'none) nil)
13192 ((eq arg 'done) (or done-word (car org-done-keywords)))
13193 ((eq arg 'nextset)
13194 (or (car (cdr (member head org-todo-heads)))
13195 (car org-todo-heads)))
13196 ((eq arg 'previousset)
13197 (let ((org-todo-heads (reverse org-todo-heads)))
13198 (or (car (cdr (member head org-todo-heads)))
13199 (car org-todo-heads))))
13200 ((car (member arg org-todo-keywords-1)))
13201 ((nth (1- (prefix-numeric-value arg))
13202 org-todo-keywords-1))))
13203 ((null member) (or head (car org-todo-keywords-1)))
13204 ((equal this final-done-word) nil) ;; -> make empty
13205 ((null tail) nil) ;; -> first entry
13206 ((eq interpret 'sequence)
13207 (car tail))
13208 ((memq interpret '(type priority))
13209 (if (eq this-command last-command)
13210 (car tail)
13211 (if (> (length tail) 0)
13212 (or done-word (car org-done-keywords))
13213 nil)))
13214 (t nil)))
13215 (next (if state (concat " " state " ") " "))
13216 dostates)
13217 (replace-match next t t)
13218 (unless (pos-visible-in-window-p hl-pos)
13219 (message "TODO state changed to %s" (org-trim next)))
13220 (unless head
13221 (setq head (org-get-todo-sequence-head state)
13222 ass (assoc head org-todo-kwd-alist)
13223 interpret (nth 1 ass)
13224 done-word (nth 3 ass)
13225 final-done-word (nth 4 ass)))
13226 (when (memq arg '(nextset previousset))
13227 (message "Keyword-Set %d/%d: %s"
13228 (- (length org-todo-sets) -1
13229 (length (memq (assoc state org-todo-sets) org-todo-sets)))
13230 (length org-todo-sets)
13231 (mapconcat 'identity (assoc state org-todo-sets) " ")))
13232 (setq org-last-todo-state-is-todo
13233 (not (member state org-done-keywords)))
13234 (when (and org-log-done (not (memq arg '(nextset previousset))))
13235 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
13236 (or (not org-todo-log-states)
13237 (member state org-todo-log-states))))
13239 (cond
13240 ((and state (member state org-not-done-keywords)
13241 (not (member this org-not-done-keywords)))
13242 ;; This is now a todo state and was not one before
13243 ;; Remove any CLOSED timestamp, and possibly log the state change
13244 (org-add-planning-info nil nil 'closed)
13245 (and dostates (org-add-log-maybe 'state state 'findpos)))
13246 ((and state dostates)
13247 ;; This is a non-nil state, and we need to log it
13248 (org-add-log-maybe 'state state 'findpos))
13249 ((and (member state org-done-keywords)
13250 (not (member this org-done-keywords)))
13251 ;; It is now done, and it was not done before
13252 (org-add-planning-info 'closed (org-current-time))
13253 (org-add-log-maybe 'done state 'findpos))))
13254 ;; Fixup tag positioning
13255 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
13256 (run-hooks 'org-after-todo-state-change-hook)
13257 (and (member state org-done-keywords) (org-auto-repeat-maybe))
13258 (if (and arg (not (member state org-done-keywords)))
13259 (setq head (org-get-todo-sequence-head state)))
13260 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)))
13261 ;; Fixup cursor location if close to the keyword
13262 (if (and (outline-on-heading-p)
13263 (not (bolp))
13264 (save-excursion (beginning-of-line 1)
13265 (looking-at org-todo-line-regexp))
13266 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
13267 (progn
13268 (goto-char (or (match-end 2) (match-end 1)))
13269 (just-one-space))))
13271 (defun org-get-todo-sequence-head (kwd)
13272 "Return the head of the TODO sequence to which KWD belongs.
13273 If KWD is not set, check if there is a text property remembering the
13274 right sequence."
13275 (let (p)
13276 (cond
13277 ((not kwd)
13278 (or (get-text-property (point-at-bol) 'org-todo-head)
13279 (progn
13280 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13281 nil (point-at-eol)))
13282 (get-text-property p 'org-todo-head))))
13283 ((not (member kwd org-todo-keywords-1))
13284 (car org-todo-keywords-1))
13285 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13287 (defun org-fast-todo-selection ()
13288 "Fast TODO keyword selection with single keys.
13289 Returns the new TODO keyword, or nil if no state change should occur."
13290 (let* ((fulltable org-todo-key-alist)
13291 (done-keywords org-done-keywords) ;; needed for the faces.
13292 (maxlen (apply 'max (mapcar
13293 (lambda (x)
13294 (if (stringp (car x)) (string-width (car x)) 0))
13295 fulltable)))
13296 (buf (current-buffer))
13297 (expert nil)
13298 (fwidth (+ maxlen 3 1 3))
13299 (ncol (/ (- (window-width) 4) fwidth))
13300 tg cnt e c char c1 c2 ntable tbl rtn
13301 groups ingroup)
13302 (save-window-excursion
13303 (if expert
13304 (set-buffer (get-buffer-create " *Org todo*"))
13305 ; (delete-other-windows)
13306 ; (split-window-vertically)
13307 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13308 (erase-buffer)
13309 (org-set-local 'org-done-keywords done-keywords)
13310 (setq tbl fulltable char ?a cnt 0)
13311 (while (setq e (pop tbl))
13312 (cond
13313 ((equal e '(:startgroup))
13314 (push '() groups) (setq ingroup t)
13315 (when (not (= cnt 0))
13316 (setq cnt 0)
13317 (insert "\n"))
13318 (insert "{ "))
13319 ((equal e '(:endgroup))
13320 (setq ingroup nil cnt 0)
13321 (insert "}\n"))
13323 (setq tg (car e) c (cdr e))
13324 (if ingroup (push tg (car groups)))
13325 (setq tg (org-add-props tg nil 'face
13326 (org-get-todo-face tg)))
13327 (if (and (= cnt 0) (not ingroup)) (insert " "))
13328 (insert "[" c "] " tg (make-string
13329 (- fwidth 4 (length tg)) ?\ ))
13330 (when (= (setq cnt (1+ cnt)) ncol)
13331 (insert "\n")
13332 (if ingroup (insert " "))
13333 (setq cnt 0)))))
13334 (insert "\n")
13335 (goto-char (point-min))
13336 (if (and (not expert) (fboundp 'fit-window-to-buffer))
13337 (fit-window-to-buffer))
13338 (message "[a-z..]:Set [SPC]:clear")
13339 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13340 (cond
13341 ((or (= c ?\C-g)
13342 (and (= c ?q) (not (rassoc c fulltable))))
13343 (setq quit-flag t))
13344 ((= c ?\ ) nil)
13345 ((setq e (rassoc c fulltable) tg (car e))
13347 (t (setq quit-flag t))))))
13349 (defun org-get-repeat ()
13350 "Check if tere is a deadline/schedule with repeater in this entry."
13351 (save-match-data
13352 (save-excursion
13353 (org-back-to-heading t)
13354 (if (re-search-forward
13355 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
13356 (match-string 1)))))
13358 (defvar org-last-changed-timestamp)
13359 (defvar org-log-post-message)
13360 (defun org-auto-repeat-maybe ()
13361 "Check if the current headline contains a repeated deadline/schedule.
13362 If yes, set TODO state back to what it was and change the base date
13363 of repeating deadline/scheduled time stamps to new date.
13364 This function should be run in the `org-after-todo-state-change-hook'."
13365 ;; last-state is dynamically scoped into this function
13366 (let* ((repeat (org-get-repeat))
13367 (aa (assoc last-state org-todo-kwd-alist))
13368 (interpret (nth 1 aa))
13369 (head (nth 2 aa))
13370 (done-word (nth 3 aa))
13371 (whata '(("d" . day) ("m" . month) ("y" . year)))
13372 (msg "Entry repeats: ")
13373 (org-log-done)
13374 re type n what ts)
13375 (when repeat
13376 (org-todo (if (eq interpret 'type) last-state head))
13377 (when (and org-log-repeat
13378 (not (memq 'org-add-log-note
13379 (default-value 'post-command-hook))))
13380 ;; Make sure a note is taken
13381 (let ((org-log-done '(done)))
13382 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
13383 'findpos)))
13384 (org-back-to-heading t)
13385 (org-add-planning-info nil nil 'closed)
13386 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13387 org-deadline-time-regexp "\\)"))
13388 (while (re-search-forward
13389 re (save-excursion (outline-next-heading) (point)) t)
13390 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
13391 ts (match-string (if (match-end 2) 2 4)))
13392 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
13393 (setq n (string-to-number (match-string 1 ts))
13394 what (match-string 2 ts))
13395 (if (equal what "w") (setq n (* n 7) what "d"))
13396 (org-timestamp-change n (cdr (assoc what whata))))
13397 (setq msg (concat msg type org-last-changed-timestamp " ")))
13398 (setq org-log-post-message msg)
13399 (message msg))))
13401 (defun org-show-todo-tree (arg)
13402 "Make a compact tree which shows all headlines marked with TODO.
13403 The tree will show the lines where the regexp matches, and all higher
13404 headlines above the match.
13405 With \\[universal-argument] prefix, also show the DONE entries.
13406 With a numeric prefix N, construct a sparse tree for the Nth element
13407 of `org-todo-keywords-1'."
13408 (interactive "P")
13409 (let ((case-fold-search nil)
13410 (kwd-re
13411 (cond ((null arg) org-not-done-regexp)
13412 ((equal arg '(4))
13413 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
13414 (mapcar 'list org-todo-keywords-1))))
13415 (concat "\\("
13416 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13417 "\\)\\>")))
13418 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13419 (regexp-quote (nth (1- (prefix-numeric-value arg))
13420 org-todo-keywords-1)))
13421 (t (error "Invalid prefix argument: %s" arg)))))
13422 (message "%d TODO entries found"
13423 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
13425 (defun org-deadline (&optional remove)
13426 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13427 With argument REMOVE, remove any deadline from the item."
13428 (interactive "P")
13429 (if remove
13430 (progn
13431 (org-add-planning-info nil nil 'deadline)
13432 (message "Item no longer has a deadline."))
13433 (org-add-planning-info 'deadline nil 'closed)))
13435 (defun org-schedule (&optional remove)
13436 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13437 With argument REMOVE, remove any scheduling date from the item."
13438 (interactive "P")
13439 (if remove
13440 (progn
13441 (org-add-planning-info nil nil 'scheduled)
13442 (message "Item is no longer scheduled."))
13443 (org-add-planning-info 'scheduled nil 'closed)))
13445 (defun org-add-planning-info (what &optional time &rest remove)
13446 "Insert new timestamp with keyword in the line directly after the headline.
13447 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
13448 If non is given, the user is prompted for a date.
13449 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13450 be removed."
13451 (interactive)
13452 (let (org-time-was-given org-end-time-was-given)
13453 (when what (setq time (or time (org-read-date nil 'to-time))))
13454 (when (and org-insert-labeled-timestamps-at-point
13455 (member what '(scheduled deadline)))
13456 (insert
13457 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13458 (org-insert-time-stamp time org-time-was-given
13459 nil nil nil (list org-end-time-was-given))
13460 (setq what nil))
13461 (save-excursion
13462 (save-restriction
13463 (let (col list elt ts buffer-invisibility-spec)
13464 (org-back-to-heading t)
13465 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
13466 (goto-char (match-end 1))
13467 (setq col (current-column))
13468 (goto-char (match-end 0))
13469 (if (eobp) (insert "\n"))
13470 (forward-char 1)
13471 (if (and (not (looking-at outline-regexp))
13472 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13473 "[^\r\n]*"))
13474 (not (equal (match-string 1) org-clock-string)))
13475 (narrow-to-region (match-beginning 0) (match-end 0))
13476 (insert-before-markers "\n")
13477 (backward-char 1)
13478 (narrow-to-region (point) (point))
13479 (indent-to-column col))
13480 ;; Check if we have to remove something.
13481 (setq list (cons what remove))
13482 (while list
13483 (setq elt (pop list))
13484 (goto-char (point-min))
13485 (when (or (and (eq elt 'scheduled)
13486 (re-search-forward org-scheduled-time-regexp nil t))
13487 (and (eq elt 'deadline)
13488 (re-search-forward org-deadline-time-regexp nil t))
13489 (and (eq elt 'closed)
13490 (re-search-forward org-closed-time-regexp nil t)))
13491 (replace-match "")
13492 (if (looking-at "--+<[^>]+>") (replace-match ""))
13493 (if (looking-at " +") (replace-match ""))))
13494 (goto-char (point-max))
13495 (when what
13496 (insert
13497 (if (not (equal (char-before) ?\ )) " " "")
13498 (cond ((eq what 'scheduled) org-scheduled-string)
13499 ((eq what 'deadline) org-deadline-string)
13500 ((eq what 'closed) org-closed-string))
13501 " ")
13502 (setq ts (org-insert-time-stamp
13503 time
13504 (or org-time-was-given
13505 (and (eq what 'closed) org-log-done-with-time))
13506 (eq what 'closed)
13507 nil nil (list org-end-time-was-given)))
13508 (end-of-line 1))
13509 (goto-char (point-min))
13510 (widen)
13511 (if (looking-at "[ \t]+\r?\n")
13512 (replace-match ""))
13513 ts)))))
13515 (defvar org-log-note-marker (make-marker))
13516 (defvar org-log-note-purpose nil)
13517 (defvar org-log-note-state nil)
13518 (defvar org-log-note-window-configuration nil)
13519 (defvar org-log-note-return-to (make-marker))
13520 (defvar org-log-post-message nil
13521 "Message to be displayed after a log note has been stored.
13522 The auto-repeater uses this.")
13524 (defun org-add-log-maybe (&optional purpose state findpos)
13525 "Set up the post command hook to take a note."
13526 (save-excursion
13527 (when (and (listp org-log-done)
13528 (memq purpose org-log-done))
13529 (when findpos
13530 (org-back-to-heading t)
13531 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
13532 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13533 "[^\r\n]*\\)?"))
13534 (goto-char (match-end 0))
13535 (unless org-log-states-order-reversed
13536 (and (= (char-after) ?\n) (forward-char 1))
13537 (org-skip-over-state-notes)
13538 (skip-chars-backward " \t\n\r")))
13539 (move-marker org-log-note-marker (point))
13540 (setq org-log-note-purpose purpose)
13541 (setq org-log-note-state state)
13542 (add-hook 'post-command-hook 'org-add-log-note 'append))))
13544 (defun org-skip-over-state-notes ()
13545 "Skip past the list of State notes in an entry."
13546 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13547 (while (looking-at "[ \t]*- State")
13548 (condition-case nil
13549 (org-next-item)
13550 (error (org-end-of-item)))))
13552 (defun org-add-log-note (&optional purpose)
13553 "Pop up a window for taking a note, and add this note later at point."
13554 (remove-hook 'post-command-hook 'org-add-log-note)
13555 (setq org-log-note-window-configuration (current-window-configuration))
13556 (delete-other-windows)
13557 (move-marker org-log-note-return-to (point))
13558 (switch-to-buffer (marker-buffer org-log-note-marker))
13559 (goto-char org-log-note-marker)
13560 (org-switch-to-buffer-other-window "*Org Note*")
13561 (erase-buffer)
13562 (let ((org-inhibit-startup t)) (org-mode))
13563 (insert (format "# Insert note for %s.
13564 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13565 (cond
13566 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13567 ((eq org-log-note-purpose 'done) "closed todo item")
13568 ((eq org-log-note-purpose 'state)
13569 (format "state change to \"%s\"" org-log-note-state))
13570 (t (error "This should not happen")))))
13571 (org-set-local 'org-finish-function 'org-store-log-note))
13573 (defun org-store-log-note ()
13574 "Finish taking a log note, and insert it to where it belongs."
13575 (let ((txt (buffer-string))
13576 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13577 lines ind)
13578 (kill-buffer (current-buffer))
13579 (while (string-match "\\`#.*\n[ \t\n]*" txt)
13580 (setq txt (replace-match "" t t txt)))
13581 (if (string-match "\\s-+\\'" txt)
13582 (setq txt (replace-match "" t t txt)))
13583 (setq lines (org-split-string txt "\n"))
13584 (when (and note (string-match "\\S-" note))
13585 (setq note
13586 (org-replace-escapes
13587 note
13588 (list (cons "%u" (user-login-name))
13589 (cons "%U" user-full-name)
13590 (cons "%t" (format-time-string
13591 (org-time-stamp-format 'long 'inactive)
13592 (current-time)))
13593 (cons "%s" (if org-log-note-state
13594 (concat "\"" org-log-note-state "\"")
13595 "")))))
13596 (if lines (setq note (concat note " \\\\")))
13597 (push note lines))
13598 (when (or current-prefix-arg org-note-abort (setq lines nil)))
13599 (when lines
13600 (save-excursion
13601 (set-buffer (marker-buffer org-log-note-marker))
13602 (save-excursion
13603 (goto-char org-log-note-marker)
13604 (move-marker org-log-note-marker nil)
13605 (end-of-line 1)
13606 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13607 (indent-relative nil)
13608 (insert " - " (pop lines))
13609 (org-indent-line-function)
13610 (beginning-of-line 1)
13611 (looking-at "[ \t]*")
13612 (setq ind (concat (match-string 0) " "))
13613 (end-of-line 1)
13614 (while lines (insert "\n" ind (pop lines)))))))
13615 (set-window-configuration org-log-note-window-configuration)
13616 (with-current-buffer (marker-buffer org-log-note-return-to)
13617 (goto-char org-log-note-return-to))
13618 (move-marker org-log-note-return-to nil)
13619 (and org-log-post-message (message org-log-post-message)))
13621 (defvar org-occur-highlights nil)
13622 (make-variable-buffer-local 'org-occur-highlights)
13624 (defun org-occur (regexp &optional keep-previous callback)
13625 "Make a compact tree which shows all matches of REGEXP.
13626 The tree will show the lines where the regexp matches, and all higher
13627 headlines above the match. It will also show the heading after the match,
13628 to make sure editing the matching entry is easy.
13629 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13630 call to `org-occur' will be kept, to allow stacking of calls to this
13631 command.
13632 If CALLBACK is non-nil, it is a function which is called to confirm
13633 that the match should indeed be shown."
13634 (interactive "sRegexp: \nP")
13635 (or keep-previous (org-remove-occur-highlights nil nil t))
13636 (let ((cnt 0))
13637 (save-excursion
13638 (goto-char (point-min))
13639 (if (or (not keep-previous) ; do not want to keep
13640 (not org-occur-highlights)) ; no previous matches
13641 ;; hide everything
13642 (org-overview))
13643 (while (re-search-forward regexp nil t)
13644 (when (or (not callback)
13645 (save-match-data (funcall callback)))
13646 (setq cnt (1+ cnt))
13647 (when org-highlight-sparse-tree-matches
13648 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13649 (org-show-context 'occur-tree))))
13650 (when org-remove-highlights-with-change
13651 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13652 nil 'local))
13653 (unless org-sparse-tree-open-archived-trees
13654 (org-hide-archived-subtrees (point-min) (point-max)))
13655 (run-hooks 'org-occur-hook)
13656 (if (interactive-p)
13657 (message "%d match(es) for regexp %s" cnt regexp))
13658 cnt))
13660 (defun org-show-context (&optional key)
13661 "Make sure point and context and visible.
13662 How much context is shown depends upon the variables
13663 `org-show-hierarchy-above', `org-show-following-heading'. and
13664 `org-show-siblings'."
13665 (let ((heading-p (org-on-heading-p t))
13666 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13667 (following-p (org-get-alist-option org-show-following-heading key))
13668 (siblings-p (org-get-alist-option org-show-siblings key)))
13669 (catch 'exit
13670 ;; Show heading or entry text
13671 (if heading-p
13672 (org-flag-heading nil) ; only show the heading
13673 (and (or (org-invisible-p) (org-invisible-p2))
13674 (org-show-hidden-entry))) ; show entire entry
13675 (when following-p
13676 ;; Show next sibling, or heading below text
13677 (save-excursion
13678 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13679 (org-flag-heading nil))))
13680 (when siblings-p (org-show-siblings))
13681 (when hierarchy-p
13682 ;; show all higher headings, possibly with siblings
13683 (save-excursion
13684 (while (and (condition-case nil
13685 (progn (org-up-heading-all 1) t)
13686 (error nil))
13687 (not (bobp)))
13688 (org-flag-heading nil)
13689 (when siblings-p (org-show-siblings))))))))
13691 (defun org-reveal (&optional siblings)
13692 "Show current entry, hierarchy above it, and the following headline.
13693 This can be used to show a consistent set of context around locations
13694 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13695 not t for the search context.
13697 With optional argument SIBLINGS, on each level of the hierarchy all
13698 siblings are shown. This repairs the tree structure to what it would
13699 look like when opened with hierarchical calls to `org-cycle'."
13700 (interactive "P")
13701 (let ((org-show-hierarchy-above t)
13702 (org-show-following-heading t)
13703 (org-show-siblings (if siblings t org-show-siblings)))
13704 (org-show-context nil)))
13706 (defun org-highlight-new-match (beg end)
13707 "Highlight from BEG to END and mark the highlight is an occur headline."
13708 (let ((ov (org-make-overlay beg end)))
13709 (org-overlay-put ov 'face 'secondary-selection)
13710 (push ov org-occur-highlights)))
13712 (defun org-remove-occur-highlights (&optional beg end noremove)
13713 "Remove the occur highlights from the buffer.
13714 BEG and END are ignored. If NOREMOVE is nil, remove this function
13715 from the `before-change-functions' in the current buffer."
13716 (interactive)
13717 (unless org-inhibit-highlight-removal
13718 (mapc 'org-delete-overlay org-occur-highlights)
13719 (setq org-occur-highlights nil)
13720 (unless noremove
13721 (remove-hook 'before-change-functions
13722 'org-remove-occur-highlights 'local))))
13724 ;;;; Priorities
13726 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13727 "Regular expression matching the priority indicator.")
13729 (defvar org-remove-priority-next-time nil)
13731 (defun org-priority-up ()
13732 "Increase the priority of the current item."
13733 (interactive)
13734 (org-priority 'up))
13736 (defun org-priority-down ()
13737 "Decrease the priority of the current item."
13738 (interactive)
13739 (org-priority 'down))
13741 (defun org-priority (&optional action)
13742 "Change the priority of an item by ARG.
13743 ACTION can be `set', `up', `down', or a character."
13744 (interactive)
13745 (setq action (or action 'set))
13746 (let (current new news have remove)
13747 (save-excursion
13748 (org-back-to-heading)
13749 (if (looking-at org-priority-regexp)
13750 (setq current (string-to-char (match-string 2))
13751 have t)
13752 (setq current org-default-priority))
13753 (cond
13754 ((or (eq action 'set) (integerp action))
13755 (if (integerp action)
13756 (setq new action)
13757 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
13758 (setq new (read-char-exclusive)))
13759 (if (and (= (upcase org-highest-priority) org-highest-priority)
13760 (= (upcase org-lowest-priority) org-lowest-priority))
13761 (setq new (upcase new)))
13762 (cond ((equal new ?\ ) (setq remove t))
13763 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13764 (error "Priority must be between `%c' and `%c'"
13765 org-highest-priority org-lowest-priority))))
13766 ((eq action 'up)
13767 (if (and (not have) (eq last-command this-command))
13768 (setq new org-lowest-priority)
13769 (setq new (if (and org-priority-start-cycle-with-default (not have))
13770 org-default-priority (1- current)))))
13771 ((eq action 'down)
13772 (if (and (not have) (eq last-command this-command))
13773 (setq new org-highest-priority)
13774 (setq new (if (and org-priority-start-cycle-with-default (not have))
13775 org-default-priority (1+ current)))))
13776 (t (error "Invalid action")))
13777 (if (or (< (upcase new) org-highest-priority)
13778 (> (upcase new) org-lowest-priority))
13779 (setq remove t))
13780 (setq news (format "%c" new))
13781 (if have
13782 (if remove
13783 (replace-match "" t t nil 1)
13784 (replace-match news t t nil 2))
13785 (if remove
13786 (error "No priority cookie found in line")
13787 (looking-at org-todo-line-regexp)
13788 (if (match-end 2)
13789 (progn
13790 (goto-char (match-end 2))
13791 (insert " [#" news "]"))
13792 (goto-char (match-beginning 3))
13793 (insert "[#" news "] ")))))
13794 (org-preserve-lc (org-set-tags nil 'align))
13795 (if remove
13796 (message "Priority removed")
13797 (message "Priority of current item set to %s" news))))
13800 (defun org-get-priority (s)
13801 "Find priority cookie and return priority."
13802 (save-match-data
13803 (if (not (string-match org-priority-regexp s))
13804 (* 1000 (- org-lowest-priority org-default-priority))
13805 (* 1000 (- org-lowest-priority
13806 (string-to-char (match-string 2 s)))))))
13808 ;;;; Tags
13810 (defun org-scan-tags (action matcher &optional todo-only)
13811 "Scan headline tags with inheritance and produce output ACTION.
13812 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
13813 evaluated, testing if a given set of tags qualifies a headline for
13814 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
13815 are included in the output."
13816 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
13817 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13818 (org-re
13819 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
13820 (props (list 'face nil
13821 'done-face 'org-done
13822 'undone-face nil
13823 'mouse-face 'highlight
13824 'org-not-done-regexp org-not-done-regexp
13825 'org-todo-regexp org-todo-regexp
13826 'keymap org-agenda-keymap
13827 'help-echo
13828 (format "mouse-2 or RET jump to org file %s"
13829 (abbreviate-file-name buffer-file-name))))
13830 (case-fold-search nil)
13831 lspos
13832 tags tags-list tags-alist (llast 0) rtn level category i txt
13833 todo marker entry priority)
13834 (save-excursion
13835 (goto-char (point-min))
13836 (when (eq action 'sparse-tree)
13837 (org-overview)
13838 (org-remove-occur-highlights))
13839 (while (re-search-forward re nil t)
13840 (catch :skip
13841 (setq todo (if (match-end 1) (match-string 2))
13842 tags (if (match-end 4) (match-string 4)))
13843 (goto-char (setq lspos (1+ (match-beginning 0))))
13844 (setq level (org-reduced-level (funcall outline-level))
13845 category (org-get-category))
13846 (setq i llast llast level)
13847 ;; remove tag lists from same and sublevels
13848 (while (>= i level)
13849 (when (setq entry (assoc i tags-alist))
13850 (setq tags-alist (delete entry tags-alist)))
13851 (setq i (1- i)))
13852 ;; add the nex tags
13853 (when tags
13854 (setq tags (mapcar 'downcase (org-split-string tags ":"))
13855 tags-alist
13856 (cons (cons level tags) tags-alist)))
13857 ;; compile tags for current headline
13858 (setq tags-list
13859 (if org-use-tag-inheritance
13860 (apply 'append (mapcar 'cdr tags-alist))
13861 tags))
13862 (when (and (or (not todo-only) (member todo org-not-done-keywords))
13863 (eval matcher)
13864 (or (not org-agenda-skip-archived-trees)
13865 (not (member org-archive-tag tags-list))))
13866 (and (eq action 'agenda) (org-agenda-skip))
13867 ;; list this headline
13869 (if (eq action 'sparse-tree)
13870 (progn
13871 (and org-highlight-sparse-tree-matches
13872 (org-get-heading) (match-end 0)
13873 (org-highlight-new-match
13874 (match-beginning 0) (match-beginning 1)))
13875 (org-show-context 'tags-tree))
13876 (setq txt (org-format-agenda-item
13878 (concat
13879 (if org-tags-match-list-sublevels
13880 (make-string (1- level) ?.) "")
13881 (org-get-heading))
13882 category tags-list)
13883 priority (org-get-priority txt))
13884 (goto-char lspos)
13885 (setq marker (org-agenda-new-marker))
13886 (org-add-props txt props
13887 'org-marker marker 'org-hd-marker marker 'org-category category
13888 'priority priority 'type "tagsmatch")
13889 (push txt rtn))
13890 ;; if we are to skip sublevels, jump to end of subtree
13891 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
13892 (when (and (eq action 'sparse-tree)
13893 (not org-sparse-tree-open-archived-trees))
13894 (org-hide-archived-subtrees (point-min) (point-max)))
13895 (nreverse rtn)))
13897 (defvar todo-only) ;; dynamically scoped
13899 (defun org-tags-sparse-tree (&optional todo-only match)
13900 "Create a sparse tree according to tags string MATCH.
13901 MATCH can contain positive and negative selection of tags, like
13902 \"+WORK+URGENT-WITHBOSS\".
13903 If optional argument TODO_ONLY is non-nil, only select lines that are
13904 also TODO lines."
13905 (interactive "P")
13906 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13908 (defvar org-cached-props nil)
13909 (defun org-cached-entry-get (pom property)
13910 (if org-use-property-inheritance
13911 ;; Caching is not possible, check it directly
13912 (org-entry-get pom property 'inherit)
13913 ;; Get all properties, so that we can do complicated checks easily
13914 (cdr (assoc property (or org-cached-props
13915 (setq org-cached-props
13916 (org-entry-properties pom)))))))
13918 (defun org-global-tags-completion-table (&optional files)
13919 "Return the list of all tags in all agenda buffer/files."
13920 (save-excursion
13921 (org-uniquify
13922 (apply 'append
13923 (mapcar
13924 (lambda (file)
13925 (set-buffer (find-file-noselect file))
13926 (org-get-buffer-tags))
13927 (if (and files (car files))
13928 files
13929 (org-agenda-files)))))))
13931 (defun org-make-tags-matcher (match)
13932 "Create the TAGS//TODO matcher form for the selection string MATCH."
13933 ;; todo-only is scoped dynamically into this function, and the function
13934 ;; may change it it the matcher asksk for it.
13935 (unless match
13936 ;; Get a new match request, with completion
13937 (let ((org-last-tags-completion-table
13938 (org-global-tags-completion-table)))
13939 (setq match (completing-read
13940 "Match: " 'org-tags-completion-function nil nil nil
13941 'org-tags-history))))
13943 ;; Parse the string and create a lisp form
13944 (let ((match0 match)
13945 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
13946 minus tag mm
13947 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13948 orterms term orlist re-p level-p prop-p pn pv)
13949 (if (string-match "/+" match)
13950 ;; match contains also a todo-matching request
13951 (progn
13952 (setq tagsmatch (substring match 0 (match-beginning 0))
13953 todomatch (substring match (match-end 0)))
13954 (if (string-match "^!" todomatch)
13955 (setq todo-only t todomatch (substring todomatch 1)))
13956 (if (string-match "^\\s-*$" todomatch)
13957 (setq todomatch nil)))
13958 ;; only matching tags
13959 (setq tagsmatch match todomatch nil))
13961 ;; Make the tags matcher
13962 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13963 (setq tagsmatcher t)
13964 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13965 (while (setq term (pop orterms))
13966 (while (and (equal (substring term -1) "\\") orterms)
13967 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13968 (while (string-match re term)
13969 (setq minus (and (match-end 1)
13970 (equal (match-string 1 term) "-"))
13971 tag (match-string 2 term)
13972 re-p (equal (string-to-char tag) ?{)
13973 level-p (match-end 3)
13974 prop-p (match-end 4)
13975 mm (cond
13976 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13977 (level-p `(= level ,(string-to-number
13978 (match-string 3 term))))
13979 (prop-p
13980 (setq pn (match-string 4 term)
13981 pv (match-string 5 term)
13982 re-p (equal (string-to-char pv) ?{)
13983 pv (substring pv 1 -1))
13984 (if re-p
13985 `(string-match ,pv (or (org-cached-entry-get nil ,pn) ""))
13986 `(equal ,pv (org-cached-entry-get nil ,pn))))
13987 (t `(member ,(downcase tag) tags-list)))
13988 mm (if minus (list 'not mm) mm)
13989 term (substring term (match-end 0)))
13990 (push mm tagsmatcher))
13991 (push (if (> (length tagsmatcher) 1)
13992 (cons 'and tagsmatcher)
13993 (car tagsmatcher))
13994 orlist)
13995 (setq tagsmatcher nil))
13996 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13997 (setq tagsmatcher
13998 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14000 ;; Make the todo matcher
14001 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14002 (setq todomatcher t)
14003 (setq orterms (org-split-string todomatch "|") orlist nil)
14004 (while (setq term (pop orterms))
14005 (while (string-match re term)
14006 (setq minus (and (match-end 1)
14007 (equal (match-string 1 term) "-"))
14008 kwd (match-string 2 term)
14009 re-p (equal (string-to-char kwd) ?{)
14010 term (substring term (match-end 0))
14011 mm (if re-p
14012 `(string-match ,(substring kwd 1 -1) todo)
14013 (list 'equal 'todo kwd))
14014 mm (if minus (list 'not mm) mm))
14015 (push mm todomatcher))
14016 (push (if (> (length todomatcher) 1)
14017 (cons 'and todomatcher)
14018 (car todomatcher))
14019 orlist)
14020 (setq todomatcher nil))
14021 (setq todomatcher (if (> (length orlist) 1)
14022 (cons 'or orlist) (car orlist))))
14024 ;; Return the string and lisp forms of the matcher
14025 (setq matcher (if todomatcher
14026 (list 'and tagsmatcher todomatcher)
14027 tagsmatcher))
14028 (cons match0 matcher)))
14030 (defun org-match-any-p (re list)
14031 "Does re match any element of list?"
14032 (setq list (mapcar (lambda (x) (string-match re x)) list))
14033 (delq nil list))
14035 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
14036 (defvar org-tags-overlay (org-make-overlay 1 1))
14037 (org-detach-overlay org-tags-overlay)
14039 (defun org-align-tags-here (to-col)
14040 ;; Assumes that this is a headline
14041 (let ((pos (point)) (col (current-column)) tags)
14042 (beginning-of-line 1)
14043 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14044 (< pos (match-beginning 2)))
14045 (progn
14046 (setq tags (match-string 2))
14047 (goto-char (match-beginning 1))
14048 (insert " ")
14049 (delete-region (point) (1+ (match-end 0)))
14050 (backward-char 1)
14051 (move-to-column
14052 (max (1+ (current-column))
14053 (1+ col)
14054 (if (> to-col 0)
14055 to-col
14056 (- (abs to-col) (length tags))))
14058 (insert tags)
14059 (move-to-column (min (current-column) col) t))
14060 (goto-char pos))))
14062 (defun org-set-tags (&optional arg just-align)
14063 "Set the tags for the current headline.
14064 With prefix ARG, realign all tags in headings in the current buffer."
14065 (interactive "P")
14066 (let* ((re (concat "^" outline-regexp))
14067 (current (org-get-tags-string))
14068 (col (current-column))
14069 (org-setting-tags t)
14070 table current-tags inherited-tags ; computed below when needed
14071 tags p0 c0 c1 rpl)
14072 (if arg
14073 (save-excursion
14074 (goto-char (point-min))
14075 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14076 (while (re-search-forward re nil t)
14077 (org-set-tags nil t)
14078 (end-of-line 1)))
14079 (message "All tags realigned to column %d" org-tags-column))
14080 (if just-align
14081 (setq tags current)
14082 ;; Get a new set of tags from the user
14083 (save-excursion
14084 (setq table (or org-tag-alist (org-get-buffer-tags))
14085 org-last-tags-completion-table table
14086 current-tags (org-split-string current ":")
14087 inherited-tags (nreverse
14088 (nthcdr (length current-tags)
14089 (nreverse (org-get-tags-at))))
14090 tags
14091 (if (or (eq t org-use-fast-tag-selection)
14092 (and org-use-fast-tag-selection
14093 (delq nil (mapcar 'cdr table))))
14094 (org-fast-tag-selection
14095 current-tags inherited-tags table
14096 (if org-fast-tag-selection-include-todo org-todo-key-alist))
14097 (let ((org-add-colon-after-tag-completion t))
14098 (org-trim
14099 (org-without-partial-completion
14100 (completing-read "Tags: " 'org-tags-completion-function
14101 nil nil current 'org-tags-history)))))))
14102 (while (string-match "[-+&]+" tags)
14103 ;; No boolean logic, just a list
14104 (setq tags (replace-match ":" t t tags))))
14106 (if (string-match "\\`[\t ]*\\'" tags)
14107 (setq tags "")
14108 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14109 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14111 ;; Insert new tags at the correct column
14112 (beginning-of-line 1)
14113 (cond
14114 ((and (equal current "") (equal tags "")))
14115 ((re-search-forward
14116 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14117 (point-at-eol) t)
14118 (if (equal tags "")
14119 (setq rpl "")
14120 (goto-char (match-beginning 0))
14121 (setq c0 (current-column) p0 (point)
14122 c1 (max (1+ c0) (if (> org-tags-column 0)
14123 org-tags-column
14124 (- (- org-tags-column) (length tags))))
14125 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14126 (replace-match rpl t t)
14127 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
14128 tags)
14129 (t (error "Tags alignment failed")))
14130 (move-to-column col)
14131 (unless just-align
14132 (run-hooks 'org-after-tags-change-hook)))))
14134 (defun org-change-tag-in-region (beg end tag off)
14135 "Add or remove TAG for each entry in the region.
14136 This works in the agenda, and also in an org-mode buffer."
14137 (interactive
14138 (list (region-beginning) (region-end)
14139 (let ((org-last-tags-completion-table
14140 (if (org-mode-p)
14141 (org-get-buffer-tags)
14142 (org-global-tags-completion-table))))
14143 (completing-read
14144 "Tag: " 'org-tags-completion-function nil nil nil
14145 'org-tags-history))
14146 (progn
14147 (message "[s]et or [r]emove? ")
14148 (equal (read-char-exclusive) ?r))))
14149 (if (fboundp 'deactivate-mark) (deactivate-mark))
14150 (let ((agendap (equal major-mode 'org-agenda-mode))
14151 l1 l2 m buf pos newhead (cnt 0))
14152 (goto-char end)
14153 (setq l2 (1- (org-current-line)))
14154 (goto-char beg)
14155 (setq l1 (org-current-line))
14156 (loop for l from l1 to l2 do
14157 (goto-line l)
14158 (setq m (get-text-property (point) 'org-hd-marker))
14159 (when (or (and (org-mode-p) (org-on-heading-p))
14160 (and agendap m))
14161 (setq buf (if agendap (marker-buffer m) (current-buffer))
14162 pos (if agendap m (point)))
14163 (with-current-buffer buf
14164 (save-excursion
14165 (save-restriction
14166 (goto-char pos)
14167 (setq cnt (1+ cnt))
14168 (org-toggle-tag tag (if off 'off 'on))
14169 (setq newhead (org-get-heading)))))
14170 (and agendap (org-agenda-change-all-lines newhead m))))
14171 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14173 (defun org-tags-completion-function (string predicate &optional flag)
14174 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14175 (confirm (lambda (x) (stringp (car x)))))
14176 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
14177 (setq s1 (match-string 1 string)
14178 s2 (match-string 2 string))
14179 (setq s1 "" s2 string))
14180 (cond
14181 ((eq flag nil)
14182 ;; try completion
14183 (setq rtn (try-completion s2 ctable confirm))
14184 (if (stringp rtn)
14185 (setq rtn
14186 (concat s1 s2 (substring rtn (length s2))
14187 (if (and org-add-colon-after-tag-completion
14188 (assoc rtn ctable))
14189 ":" ""))))
14190 rtn)
14191 ((eq flag t)
14192 ;; all-completions
14193 (all-completions s2 ctable confirm)
14195 ((eq flag 'lambda)
14196 ;; exact match?
14197 (assoc s2 ctable)))
14200 (defun org-fast-tag-insert (kwd tags face &optional end)
14201 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
14202 (insert (format "%-12s" (concat kwd ":"))
14203 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14204 (or end "")))
14206 (defun org-fast-tag-show-exit (flag)
14207 (save-excursion
14208 (goto-line 3)
14209 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14210 (replace-match ""))
14211 (when flag
14212 (end-of-line 1)
14213 (move-to-column (- (window-width) 19) t)
14214 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14216 (defun org-set-current-tags-overlay (current prefix)
14217 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14218 (if (featurep 'xemacs)
14219 (org-overlay-display org-tags-overlay (concat prefix s)
14220 'secondary-selection)
14221 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14222 (org-overlay-display org-tags-overlay (concat prefix s)))))
14224 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14225 "Fast tag selection with single keys.
14226 CURRENT is the current list of tags in the headline, INHERITED is the
14227 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14228 possibly with grouping information. TODO-TABLE is a similar table with
14229 TODO keywords, should these have keys assigned to them.
14230 If the keys are nil, a-z are automatically assigned.
14231 Returns the new tags string, or nil to not change the current settings."
14232 (let* ((fulltable (append table todo-table))
14233 (maxlen (apply 'max (mapcar
14234 (lambda (x)
14235 (if (stringp (car x)) (string-width (car x)) 0))
14236 fulltable)))
14237 (buf (current-buffer))
14238 (expert (eq org-fast-tag-selection-single-key 'expert))
14239 (buffer-tags nil)
14240 (fwidth (+ maxlen 3 1 3))
14241 (ncol (/ (- (window-width) 4) fwidth))
14242 (i-face 'org-done)
14243 (c-face 'org-todo)
14244 tg cnt e c char c1 c2 ntable tbl rtn
14245 ov-start ov-end ov-prefix
14246 (exit-after-next org-fast-tag-selection-single-key)
14247 (done-keywords org-done-keywords)
14248 groups ingroup)
14249 (save-excursion
14250 (beginning-of-line 1)
14251 (if (looking-at
14252 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14253 (setq ov-start (match-beginning 1)
14254 ov-end (match-end 1)
14255 ov-prefix "")
14256 (setq ov-start (1- (point-at-eol))
14257 ov-end (1+ ov-start))
14258 (skip-chars-forward "^\n\r")
14259 (setq ov-prefix
14260 (concat
14261 (buffer-substring (1- (point)) (point))
14262 (if (> (current-column) org-tags-column)
14264 (make-string (- org-tags-column (current-column)) ?\ ))))))
14265 (org-move-overlay org-tags-overlay ov-start ov-end)
14266 (save-window-excursion
14267 (if expert
14268 (set-buffer (get-buffer-create " *Org tags*"))
14269 (delete-other-windows)
14270 (split-window-vertically)
14271 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14272 (erase-buffer)
14273 (org-set-local 'org-done-keywords done-keywords)
14274 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14275 (org-fast-tag-insert "Current" current c-face "\n\n")
14276 (org-fast-tag-show-exit exit-after-next)
14277 (org-set-current-tags-overlay current ov-prefix)
14278 (setq tbl fulltable char ?a cnt 0)
14279 (while (setq e (pop tbl))
14280 (cond
14281 ((equal e '(:startgroup))
14282 (push '() groups) (setq ingroup t)
14283 (when (not (= cnt 0))
14284 (setq cnt 0)
14285 (insert "\n"))
14286 (insert "{ "))
14287 ((equal e '(:endgroup))
14288 (setq ingroup nil cnt 0)
14289 (insert "}\n"))
14291 (setq tg (car e) c2 nil)
14292 (if (cdr e)
14293 (setq c (cdr e))
14294 ;; automatically assign a character.
14295 (setq c1 (string-to-char
14296 (downcase (substring
14297 tg (if (= (string-to-char tg) ?@) 1 0)))))
14298 (if (or (rassoc c1 ntable) (rassoc c1 table))
14299 (while (or (rassoc char ntable) (rassoc char table))
14300 (setq char (1+ char)))
14301 (setq c2 c1))
14302 (setq c (or c2 char)))
14303 (if ingroup (push tg (car groups)))
14304 (setq tg (org-add-props tg nil 'face
14305 (cond
14306 ((not (assoc tg table))
14307 (org-get-todo-face tg))
14308 ((member tg current) c-face)
14309 ((member tg inherited) i-face)
14310 (t nil))))
14311 (if (and (= cnt 0) (not ingroup)) (insert " "))
14312 (insert "[" c "] " tg (make-string
14313 (- fwidth 4 (length tg)) ?\ ))
14314 (push (cons tg c) ntable)
14315 (when (= (setq cnt (1+ cnt)) ncol)
14316 (insert "\n")
14317 (if ingroup (insert " "))
14318 (setq cnt 0)))))
14319 (setq ntable (nreverse ntable))
14320 (insert "\n")
14321 (goto-char (point-min))
14322 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14323 (fit-window-to-buffer))
14324 (setq rtn
14325 (catch 'exit
14326 (while t
14327 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
14328 (if groups " [!] no groups" " [!]groups")
14329 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14330 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14331 (cond
14332 ((= c ?\r) (throw 'exit t))
14333 ((= c ?!)
14334 (setq groups (not groups))
14335 (goto-char (point-min))
14336 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14337 ((= c ?\C-c)
14338 (if (not expert)
14339 (org-fast-tag-show-exit
14340 (setq exit-after-next (not exit-after-next)))
14341 (setq expert nil)
14342 (delete-other-windows)
14343 (split-window-vertically)
14344 (org-switch-to-buffer-other-window " *Org tags*")
14345 (and (fboundp 'fit-window-to-buffer)
14346 (fit-window-to-buffer))))
14347 ((or (= c ?\C-g)
14348 (and (= c ?q) (not (rassoc c ntable))))
14349 (org-detach-overlay org-tags-overlay)
14350 (setq quit-flag t))
14351 ((= c ?\ )
14352 (setq current nil)
14353 (if exit-after-next (setq exit-after-next 'now)))
14354 ((= c ?\t)
14355 (condition-case nil
14356 (setq tg (completing-read
14357 "Tag: "
14358 (or buffer-tags
14359 (with-current-buffer buf
14360 (org-get-buffer-tags)))))
14361 (quit (setq tg "")))
14362 (when (string-match "\\S-" tg)
14363 (add-to-list 'buffer-tags (list tg))
14364 (if (member tg current)
14365 (setq current (delete tg current))
14366 (push tg current)))
14367 (if exit-after-next (setq exit-after-next 'now)))
14368 ((setq e (rassoc c todo-table) tg (car e))
14369 (with-current-buffer buf
14370 (save-excursion (org-todo tg)))
14371 (if exit-after-next (setq exit-after-next 'now)))
14372 ((setq e (rassoc c ntable) tg (car e))
14373 (if (member tg current)
14374 (setq current (delete tg current))
14375 (loop for g in groups do
14376 (if (member tg g)
14377 (mapcar (lambda (x)
14378 (setq current (delete x current)))
14379 g)))
14380 (push tg current))
14381 (if exit-after-next (setq exit-after-next 'now))))
14383 ;; Create a sorted list
14384 (setq current
14385 (sort current
14386 (lambda (a b)
14387 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14388 (if (eq exit-after-next 'now) (throw 'exit t))
14389 (goto-char (point-min))
14390 (beginning-of-line 2)
14391 (delete-region (point) (point-at-eol))
14392 (org-fast-tag-insert "Current" current c-face)
14393 (org-set-current-tags-overlay current ov-prefix)
14394 (while (re-search-forward
14395 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
14396 (setq tg (match-string 1))
14397 (add-text-properties
14398 (match-beginning 1) (match-end 1)
14399 (list 'face
14400 (cond
14401 ((member tg current) c-face)
14402 ((member tg inherited) i-face)
14403 (t (get-text-property (match-beginning 1) 'face))))))
14404 (goto-char (point-min)))))
14405 (org-detach-overlay org-tags-overlay)
14406 (if rtn
14407 (mapconcat 'identity current ":")
14408 nil))))
14410 (defun org-get-tags-string ()
14411 "Get the TAGS string in the current headline."
14412 (unless (org-on-heading-p t)
14413 (error "Not on a heading"))
14414 (save-excursion
14415 (beginning-of-line 1)
14416 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14417 (org-match-string-no-properties 1)
14418 "")))
14420 (defun org-get-tags ()
14421 "Get the list of tags specified in the current headline."
14422 (org-split-string (org-get-tags-string) ":"))
14424 (defun org-get-buffer-tags ()
14425 "Get a table of all tags used in the buffer, for completion."
14426 (let (tags)
14427 (save-excursion
14428 (goto-char (point-min))
14429 (while (re-search-forward
14430 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
14431 (when (equal (char-after (point-at-bol 0)) ?*)
14432 (mapc (lambda (x) (add-to-list 'tags x))
14433 (org-split-string (org-match-string-no-properties 1) ":")))))
14434 (mapcar 'list tags)))
14437 ;;;; Properties
14439 ;;; Setting and retrieving properties
14441 (defconst org-special-properties
14442 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY")
14443 "The special properties valid in Org-mode.
14445 These are properties that are not defined in the property drawer,
14446 but in some other way.")
14448 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14449 "Regular expression matching the first line of a property drawer.")
14451 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14452 "Regular expression matching the first line of a property drawer.")
14454 (defun org-property-action ()
14455 "Do an action on properties."
14456 (interactive)
14457 (let (c prop)
14458 (org-at-property-p)
14459 (setq prop (match-string 2))
14460 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14461 (setq c (read-char-exclusive))
14462 (cond
14463 ((equal c ?s)
14464 (call-interactively 'org-set-property))
14465 ((equal c ?d)
14466 (call-interactively 'org-delete-property))
14467 ((equal c ?D)
14468 (call-interactively 'org-delete-property-globally))
14469 ((equal c ?c)
14470 (call-interactively 'org-compute-property-at-point))
14471 (t (error "No such property action %c" c)))))
14473 (defun org-at-property-p ()
14474 "Is the cursor in a property line?"
14475 ;; FIXME: Does not check if we are actually in the drawer.
14476 ;; FIXME: also returns true on any drawers.....
14477 ;; This is used by C-c C-c for property action.
14478 (save-excursion
14479 (beginning-of-line 1)
14480 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
14482 (defmacro org-with-point-at (pom &rest body)
14483 "Move to buffer and point of point-or-marker POM for the duration of BODY."
14484 (declare (indent 1) (debug t))
14485 `(save-excursion
14486 (if (markerp pom) (set-buffer (marker-buffer pom)))
14487 (save-excursion
14488 (goto-char (or pom (point)))
14489 ,@body)))
14491 (defun org-get-property-block (&optional beg end force)
14492 "Return the (beg . end) range of the body of the property drawer.
14493 BEG and END can be beginning and end of subtree, if not given
14494 they will be found.
14495 If the drawer does not exist and FORCE is non-nil, create the drawer."
14496 (catch 'exit
14497 (save-excursion
14498 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14499 (end (or end (progn (outline-next-heading) (point)))))
14500 (goto-char beg)
14501 (if (re-search-forward org-property-start-re end t)
14502 (setq beg (1+ (match-end 0)))
14503 (if force
14504 (save-excursion
14505 (org-insert-property-drawer)
14506 (setq end (progn (outline-next-heading) (point))))
14507 (throw 'exit nil))
14508 (goto-char beg)
14509 (if (re-search-forward org-property-start-re end t)
14510 (setq beg (1+ (match-end 0)))))
14511 (if (re-search-forward org-property-end-re end t)
14512 (setq end (match-beginning 0))
14513 (or force (throw 'exit nil))
14514 (goto-char beg)
14515 (setq end beg)
14516 (org-indent-line-function)
14517 (insert ":END:\n"))
14518 (cons beg end)))))
14520 (defun org-entry-properties (&optional pom which)
14521 "Get all properties of the entry at point-or-marker POM.
14522 This includes the TODO keyword, the tags, time strings for deadline,
14523 scheduled, and clocking, and any additional properties defined in the
14524 entry. The return value is an alist, keys may occur multiple times
14525 if the property key was used several times.
14526 POM may also be nil, in which case the current entry is used.
14527 If WHICH is nil or `all', get all properties. If WHICH is
14528 `special' or `standard', only get that subclass."
14529 (setq which (or which 'all))
14530 (org-with-point-at pom
14531 (let ((clockstr (substring org-clock-string 0 -1))
14532 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
14533 beg end range props sum-props key value)
14534 (save-excursion
14535 (when (condition-case nil (org-back-to-heading t) (error nil))
14536 (setq beg (point))
14537 (setq sum-props (get-text-property (point) 'org-summaries))
14538 (outline-next-heading)
14539 (setq end (point))
14540 (when (memq which '(all special))
14541 ;; Get the special properties, like TODO and tags
14542 (goto-char beg)
14543 (when (and (looking-at org-todo-line-regexp) (match-end 2))
14544 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14545 (when (looking-at org-priority-regexp)
14546 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14547 (when (and (setq value (org-get-tags-string))
14548 (string-match "\\S-" value))
14549 (push (cons "TAGS" value) props))
14550 (when (setq value (org-get-tags-at))
14551 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
14552 props))
14553 (while (re-search-forward org-keyword-time-regexp end t)
14554 (setq key (substring (org-match-string-no-properties 1) 0 -1))
14555 (unless (member key excluded) (push key excluded))
14556 (push (cons key
14557 (if (equal key clockstr)
14558 (org-no-properties
14559 (org-trim
14560 (buffer-substring
14561 (match-beginning 2) (point-at-eol))))
14562 (org-match-string-no-properties 2)))
14563 props)))
14564 (when (memq which '(all standard))
14565 ;; Get the standard properties, like :PORP: ...
14566 (setq range (org-get-property-block beg end))
14567 (when range
14568 (goto-char (car range))
14569 (while (re-search-forward
14570 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14571 (cdr range) t)
14572 (setq key (org-match-string-no-properties 1)
14573 value (org-trim (or (org-match-string-no-properties 2) "")))
14574 (unless (member key excluded)
14575 (push (cons key (or value "")) props)))))
14576 (append sum-props (nreverse props)))))))
14578 (defun org-entry-get (pom property &optional inherit)
14579 "Get value of PROPERTY for entry at point-or-marker POM.
14580 If INHERIT is non-nil and the entry does not have the property,
14581 then also check higher levels of the hierarchy.
14582 If the property is present but empty, the return value is the empty string.
14583 If the property is not present at all, nil is returned."
14584 (org-with-point-at pom
14585 (if inherit
14586 (org-entry-get-with-inheritance property)
14587 (if (member property org-special-properties)
14588 ;; We need a special property. Use brute force, get all properties.
14589 (cdr (assoc property (org-entry-properties nil 'special)))
14590 (let ((range (org-get-property-block)))
14591 (if (and range
14592 (goto-char (car range))
14593 (re-search-forward
14594 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
14595 (cdr range) t))
14596 ;; Found the property, return it.
14597 (if (match-end 1)
14598 (org-match-string-no-properties 1)
14599 "")))))))
14601 (defun org-entry-delete (pom property)
14602 "Delete the property PROPERTY from entry at point-or-marker POM."
14603 (org-with-point-at pom
14604 (if (member property org-special-properties)
14605 nil ; cannot delete these properties.
14606 (let ((range (org-get-property-block)))
14607 (if (and range
14608 (goto-char (car range))
14609 (re-search-forward
14610 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
14611 (cdr range) t))
14612 (progn
14613 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14615 nil)))))
14617 (defvar org-entry-property-inherited-from (make-marker))
14619 (defun org-entry-get-with-inheritance (property)
14620 "Get entry property, and search higher levels if not present."
14621 (let (tmp)
14622 (save-excursion
14623 (catch 'ex
14624 (while t
14625 (when (setq tmp (org-entry-get nil property))
14626 (org-back-to-heading t)
14627 (move-marker org-entry-property-inherited-from (point))
14628 (throw 'ex tmp))
14629 (or (org-up-heading-safe) (throw 'ex nil)))))
14630 (or tmp (cdr (assoc property org-local-properties))
14631 (cdr (assoc property org-global-properties)))))
14633 (defun org-entry-put (pom property value)
14634 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14635 (org-with-point-at pom
14636 (org-back-to-heading t)
14637 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14638 range)
14639 (cond
14640 ((equal property "TODO")
14641 (when (and (stringp value) (string-match "\\S-" value)
14642 (not (member value org-todo-keywords-1)))
14643 (error "\"%s\" is not a valid TODO state" value))
14644 (if (or (not value)
14645 (not (string-match "\\S-" value)))
14646 (setq value 'none))
14647 (org-todo value)
14648 (org-set-tags nil 'align))
14649 ((equal property "PRIORITY")
14650 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14651 (string-to-char value) ?\ ))
14652 (org-set-tags nil 'align))
14653 ((equal property "SCHEDULED")
14654 (if (re-search-forward org-scheduled-time-regexp end t)
14655 (cond
14656 ((eq value 'earlier) (org-timestamp-change -1 'day))
14657 ((eq value 'later) (org-timestamp-change 1 'day))
14658 (t (call-interactively 'org-schedule)))
14659 (call-interactively 'org-schedule)))
14660 ((equal property "DEADLINE")
14661 (if (re-search-forward org-deadline-time-regexp end t)
14662 (cond
14663 ((eq value 'earlier) (org-timestamp-change -1 'day))
14664 ((eq value 'later) (org-timestamp-change 1 'day))
14665 (t (call-interactively 'org-deadline)))
14666 (call-interactively 'org-deadline)))
14667 ((member property org-special-properties)
14668 (error "The %s property can not yet be set with `org-entry-put'"
14669 property))
14670 (t ; a non-special property
14671 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14672 (setq range (org-get-property-block beg end 'force))
14673 (goto-char (car range))
14674 (if (re-search-forward
14675 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
14676 (progn
14677 (delete-region (match-beginning 1) (match-end 1))
14678 (goto-char (match-beginning 1)))
14679 (goto-char (cdr range))
14680 (insert "\n")
14681 (backward-char 1)
14682 (org-indent-line-function)
14683 (insert ":" property ":"))
14684 (and value (insert " " value))
14685 (org-indent-line-function)))))))
14687 (defun org-buffer-property-keys (&optional include-specials include-defaults)
14688 "Get all property keys in the current buffer.
14689 With INCLUDE-SPECIALS, also list the special properties that relect things
14690 like tags and TODO state.
14691 With INCLUDE-DEFAULTS, also include properties that has special meaning
14692 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
14693 (let (rtn range)
14694 (save-excursion
14695 (save-restriction
14696 (widen)
14697 (goto-char (point-min))
14698 (while (re-search-forward org-property-start-re nil t)
14699 (setq range (org-get-property-block))
14700 (goto-char (car range))
14701 (while (re-search-forward
14702 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
14703 (cdr range) t)
14704 (add-to-list 'rtn (org-match-string-no-properties 1)))
14705 (outline-next-heading))))
14706 (when include-specials
14707 (setq rtn (append org-special-properties rtn)))
14708 (when include-defaults
14709 (add-to-list 'rtn "CATEGORY")
14710 (add-to-list 'rtn "ARCHIVE"))
14711 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14713 (defun org-property-values (key)
14714 "Return a list of all values of property KEY."
14715 (save-excursion
14716 (save-restriction
14717 (widen)
14718 (goto-char (point-min))
14719 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
14720 values)
14721 (while (re-search-forward re nil t)
14722 (add-to-list 'values (org-trim (match-string 1))))
14723 (delete "" values)))))
14725 (defun org-insert-property-drawer ()
14726 "Insert a property drawer into the current entry."
14727 (interactive)
14728 (org-back-to-heading t)
14729 (looking-at outline-regexp)
14730 (let ((indent (- (match-end 0)(match-beginning 0)))
14731 (beg (point))
14732 (re (concat "^[ \t]*" org-keyword-time-regexp))
14733 end hiddenp)
14734 (outline-next-heading)
14735 (setq end (point))
14736 (goto-char beg)
14737 (while (re-search-forward re end t))
14738 (setq hiddenp (org-invisible-p))
14739 (end-of-line 1)
14740 (and (= (char-after) ?\n) (forward-char 1))
14741 (org-skip-over-state-notes)
14742 (skip-chars-backward " \t\n\r")
14743 (insert "\n:PROPERTIES:\n:END:")
14744 (beginning-of-line 0)
14745 (indent-to-column indent)
14746 (beginning-of-line 2)
14747 (indent-to-column indent)
14748 (beginning-of-line 0)
14749 (if hiddenp
14750 (save-excursion
14751 (org-back-to-heading t)
14752 (hide-entry))
14753 (org-flag-drawer t))))
14755 (defun org-set-property (property value)
14756 "In the current entry, set PROPERTY to VALUE."
14757 (interactive
14758 (let* ((prop (completing-read "Property: "
14759 (mapcar 'list (org-buffer-property-keys))))
14760 (cur (org-entry-get nil prop))
14761 (allowed (org-property-get-allowed-values nil prop 'table))
14762 (val (if allowed
14763 (completing-read "Value: " allowed nil 'req-match)
14764 (read-string
14765 (concat "Value" (if (and cur (string-match "\\S-" cur))
14766 (concat "[" cur "]") "")
14767 ": ")
14768 "" cur))))
14769 (list prop (if (equal val "") cur val))))
14770 (unless (equal (org-entry-get nil property) value)
14771 (org-entry-put nil property value)))
14773 (defun org-delete-property (property)
14774 "In the current entry, delete PROPERTY."
14775 (interactive
14776 (let* ((prop (completing-read
14777 "Property: " (org-entry-properties nil 'standard))))
14778 (list prop)))
14779 (message (concat "Property " property
14780 (if (org-entry-delete nil property)
14781 " deleted"
14782 " was not present in the entry"))))
14784 (defun org-delete-property-globally (property)
14785 "Remove PROPERTY globally, from all entries."
14786 (interactive
14787 (let* ((prop (completing-read
14788 "Globally remove property: "
14789 (mapcar 'list (org-buffer-property-keys)))))
14790 (list prop)))
14791 (save-excursion
14792 (save-restriction
14793 (widen)
14794 (goto-char (point-min))
14795 (let ((cnt 0))
14796 (while (re-search-forward
14797 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
14798 nil t)
14799 (setq cnt (1+ cnt))
14800 (replace-match ""))
14801 (message "Property \"%s\" removed from %d entries" property cnt)))))
14803 (defvar org-columns-current-fmt-compiled) ; defined below
14805 (defun org-compute-property-at-point ()
14806 "Compute the property at point.
14807 This looks for an enclosing column format, extracts the operator and
14808 then applies it to the proerty in the column format's scope."
14809 (interactive)
14810 (unless (org-at-property-p)
14811 (error "Not at a property"))
14812 (let ((prop (org-match-string-no-properties 2)))
14813 (org-columns-get-format-and-top-level)
14814 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14815 (error "No operator defined for property %s" prop))
14816 (org-columns-compute prop)))
14818 (defun org-property-get-allowed-values (pom property &optional table)
14819 "Get allowed values for the property PROPERTY.
14820 When TABLE is non-nil, return an alist that can directly be used for
14821 completion."
14822 (let (vals)
14823 (cond
14824 ((equal property "TODO")
14825 (setq vals (org-with-point-at pom
14826 (append org-todo-keywords-1 '("")))))
14827 ((equal property "PRIORITY")
14828 (let ((n org-lowest-priority))
14829 (while (>= n org-highest-priority)
14830 (push (char-to-string n) vals)
14831 (setq n (1- n)))))
14832 ((member property org-special-properties))
14834 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14836 (when (and vals (string-match "\\S-" vals))
14837 (setq vals (car (read-from-string (concat "(" vals ")"))))
14838 (setq vals (mapcar (lambda (x)
14839 (cond ((stringp x) x)
14840 ((numberp x) (number-to-string x))
14841 ((symbolp x) (symbol-name x))
14842 (t "???")))
14843 vals)))))
14844 (if table (mapcar 'list vals) vals)))
14846 (defun org-property-previous-allowed-value (&optional previous)
14847 "Switch to the next allowed value for this property."
14848 (interactive)
14849 (org-property-next-allowed-value t))
14851 (defun org-property-next-allowed-value (&optional previous)
14852 "Switch to the next allowed value for this property."
14853 (interactive)
14854 (unless (org-at-property-p)
14855 (error "Not at a property"))
14856 (let* ((key (match-string 2))
14857 (value (match-string 3))
14858 (allowed (or (org-property-get-allowed-values (point) key)
14859 (and (member value '("[ ]" "[-]" "[X]"))
14860 '("[ ]" "[X]"))))
14861 nval)
14862 (unless allowed
14863 (error "Allowed values for this property have not been defined"))
14864 (if previous (setq allowed (reverse allowed)))
14865 (if (member value allowed)
14866 (setq nval (car (cdr (member value allowed)))))
14867 (setq nval (or nval (car allowed)))
14868 (if (equal nval value)
14869 (error "Only one allowed value for this property"))
14870 (org-at-property-p)
14871 (replace-match (concat " :" key ": " nval) t t)
14872 (org-indent-line-function)
14873 (beginning-of-line 1)
14874 (skip-chars-forward " \t")))
14876 ;;; Column View
14878 (defvar org-columns-overlays nil
14879 "Holds the list of current column overlays.")
14881 (defvar org-columns-current-fmt nil
14882 "Local variable, holds the currently active column format.")
14883 (defvar org-columns-current-fmt-compiled nil
14884 "Local variable, holds the currently active column format.
14885 This is the compiled version of the format.")
14886 (defvar org-columns-current-maxwidths nil
14887 "Loval variable, holds the currently active maximum column widths.")
14888 (defvar org-columns-begin-marker (make-marker)
14889 "Points to the position where last a column creation command was called.")
14890 (defvar org-columns-top-level-marker (make-marker)
14891 "Points to the position where current columns region starts.")
14893 (defvar org-columns-map (make-sparse-keymap)
14894 "The keymap valid in column display.")
14896 (defun org-columns-content ()
14897 "Switch to contents view while in columns view."
14898 (interactive)
14899 (org-overview)
14900 (org-content))
14902 (org-defkey org-columns-map "c" 'org-columns-content)
14903 (org-defkey org-columns-map "o" 'org-overview)
14904 (org-defkey org-columns-map "e" 'org-columns-edit-value)
14905 (org-defkey org-columns-map "v" 'org-columns-show-value)
14906 (org-defkey org-columns-map "q" 'org-columns-quit)
14907 (org-defkey org-columns-map "r" 'org-columns-redo)
14908 (org-defkey org-columns-map [left] 'backward-char)
14909 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
14910 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
14911 (org-defkey org-columns-map [right] 'forward-char)
14912 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
14913 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
14914 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-next-allowed-value)
14915 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
14916 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
14917 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
14918 (org-defkey org-columns-map "<" 'org-columns-narrow)
14919 (org-defkey org-columns-map ">" 'org-columns-widen)
14920 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
14921 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
14922 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
14923 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
14925 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
14926 '("Column"
14927 ["Edit property" org-columns-edit-value t]
14928 ["Next allowed value" org-columns-next-allowed-value t]
14929 ["Previous allowed value" org-columns-previous-allowed-value t]
14930 ["Show full value" org-columns-show-value t]
14931 ["Edit allowed" org-columns-edit-allowed t]
14932 "--"
14933 ["Edit column attributes" org-columns-edit-attributes t]
14934 ["Increase column width" org-columns-widen t]
14935 ["Decrease column width" org-columns-narrow t]
14936 "--"
14937 ["Move column right" org-columns-move-right t]
14938 ["Move column left" org-columns-move-left t]
14939 ["Add column" org-columns-new t]
14940 ["Delete column" org-columns-delete t]
14941 "--"
14942 ["CONTENTS" org-columns-content t]
14943 ["OVERVIEW" org-overview t]
14944 ["Refresh columns display" org-columns-redo t]
14945 "--"
14946 ["Quit" org-columns-quit t]))
14948 (defun org-columns-new-overlay (beg end &optional string face)
14949 "Create a new column overlay and add it to the list."
14950 (let ((ov (org-make-overlay beg end)))
14951 (org-overlay-put ov 'face (or face 'secondary-selection))
14952 (org-overlay-display ov string face)
14953 (push ov org-columns-overlays)
14954 ov))
14956 (defun org-columns-display-here (&optional props)
14957 "Overlay the current line with column display."
14958 (interactive)
14959 (let* ((fmt org-columns-current-fmt-compiled)
14960 (beg (point-at-bol))
14961 (level-face (save-excursion
14962 (beginning-of-line 1)
14963 (and (looking-at "\\(\\**\\)\\(\\* \\)")
14964 (org-get-level-face 2))))
14965 (color (list :foreground
14966 (face-attribute (or level-face 'default) :foreground)))
14967 props pom property ass width f string ov column)
14968 ;; Check if the entry is in another buffer.
14969 (unless props
14970 (if (eq major-mode 'org-agenda-mode)
14971 (setq pom (or (get-text-property (point) 'org-hd-marker)
14972 (get-text-property (point) 'org-marker))
14973 props (if pom (org-entry-properties pom) nil))
14974 (setq props (org-entry-properties nil))))
14975 ;; Walk the format
14976 (while (setq column (pop fmt))
14977 (setq property (car column)
14978 ass (if (equal property "ITEM")
14979 (cons "ITEM"
14980 (save-match-data
14981 (org-no-properties
14982 (org-remove-tabs
14983 (buffer-substring-no-properties
14984 (point-at-bol) (point-at-eol))))))
14985 (assoc property props))
14986 width (or (cdr (assoc property org-columns-current-maxwidths))
14987 (nth 2 column))
14988 f (format "%%-%d.%ds | " width width)
14989 string (format f (or (cdr ass) "")))
14990 ;; Create the overlay
14991 (org-unmodified
14992 (setq ov (org-columns-new-overlay
14993 beg (setq beg (1+ beg)) string
14994 (list color 'org-column)))
14995 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
14996 (org-overlay-put ov 'keymap org-columns-map)
14997 (org-overlay-put ov 'org-columns-key property)
14998 (org-overlay-put ov 'org-columns-value (cdr ass))
14999 (org-overlay-put ov 'org-columns-pom pom)
15000 (org-overlay-put ov 'org-columns-format f))
15001 (if (or (not (char-after beg))
15002 (equal (char-after beg) ?\n))
15003 (let ((inhibit-read-only t))
15004 (save-excursion
15005 (goto-char beg)
15006 (insert " ")))))
15007 ;; Make the rest of the line disappear.
15008 (org-unmodified
15009 (setq ov (org-columns-new-overlay beg (point-at-eol)))
15010 (org-overlay-put ov 'invisible t)
15011 (org-overlay-put ov 'keymap org-columns-map)
15012 (org-overlay-put ov 'intangible t)
15013 (push ov org-columns-overlays)
15014 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
15015 (org-overlay-put ov 'keymap org-columns-map)
15016 (push ov org-columns-overlays)
15017 (let ((inhibit-read-only t))
15018 (put-text-property (max (point-min) (1- (point-at-bol)))
15019 (min (point-max) (1+ (point-at-eol)))
15020 'read-only "Type `e' to edit property")))))
15022 (defvar org-previous-header-line-format nil
15023 "The header line format before column view was turned on.")
15024 (defvar org-columns-inhibit-recalculation nil
15025 "Inhibit recomputing of columns on column view startup.")
15027 (defvar header-line-format)
15028 (defun org-columns-display-here-title ()
15029 "Overlay the newline before the current line with the table title."
15030 (interactive)
15031 (let ((fmt org-columns-current-fmt-compiled)
15032 string (title "")
15033 property width f column str)
15034 (while (setq column (pop fmt))
15035 (setq property (car column)
15036 str (or (nth 1 column) property)
15037 width (or (cdr (assoc property org-columns-current-maxwidths))
15038 (nth 2 column))
15039 f (format "%%-%d.%ds | " width width)
15040 string (format f str)
15041 title (concat title string)))
15042 (setq title (concat
15043 (org-add-props " " nil 'display '(space :align-to 0))
15044 (org-add-props title nil 'face '(:weight bold :underline t))))
15045 (org-set-local 'org-previous-header-line-format header-line-format)
15046 (setq header-line-format title)))
15048 (defun org-columns-remove-overlays ()
15049 "Remove all currently active column overlays."
15050 (interactive)
15051 (when (marker-buffer org-columns-begin-marker)
15052 (with-current-buffer (marker-buffer org-columns-begin-marker)
15053 (when (local-variable-p 'org-previous-header-line-format)
15054 (setq header-line-format org-previous-header-line-format)
15055 (kill-local-variable 'org-previous-header-line-format))
15056 (move-marker org-columns-begin-marker nil)
15057 (move-marker org-columns-top-level-marker nil)
15058 (org-unmodified
15059 (mapc 'org-delete-overlay org-columns-overlays)
15060 (setq org-columns-overlays nil)
15061 (let ((inhibit-read-only t))
15062 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
15064 (defun org-columns-show-value ()
15065 "Show the full value of the property."
15066 (interactive)
15067 (let ((value (get-char-property (point) 'org-columns-value)))
15068 (message "Value is: %s" (or value ""))))
15070 (defun org-columns-quit ()
15071 "Remove the column overlays and in this way exit column editing."
15072 (interactive)
15073 (org-unmodified
15074 (org-columns-remove-overlays)
15075 (let ((inhibit-read-only t))
15076 (remove-text-properties (point-min) (point-max) '(read-only t))))
15077 (when (eq major-mode 'org-agenda-mode)
15078 (message
15079 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
15081 (defun org-columns-check-computed ()
15082 "Check if this column value is computed.
15083 If yes, throw an error indicating that changing it does not make sense."
15084 (let ((val (get-char-property (point) 'org-columns-value)))
15085 (when (and (stringp val)
15086 (get-char-property 0 'org-computed val))
15087 (error "This value is computed from the entry's children"))))
15089 (defun org-columns-edit-value ()
15090 "Edit the value of the property at point in column view.
15091 Where possible, use the standard interface for changing this line."
15092 (interactive)
15093 (org-columns-check-computed)
15094 (let* ((col (current-column))
15095 (key (get-char-property (point) 'org-columns-key))
15096 (value (get-char-property (point) 'org-columns-value))
15097 (bol (point-at-bol)) (eol (point-at-eol))
15098 (pom (or (get-text-property bol 'org-hd-marker)
15099 (point))) ; keep despite of compiler waring
15100 (line-overlays
15101 (delq nil (mapcar (lambda (x)
15102 (and (eq (overlay-buffer x) (current-buffer))
15103 (>= (overlay-start x) bol)
15104 (<= (overlay-start x) eol)
15106 org-columns-overlays)))
15107 nval eval allowed)
15108 (when (equal key "ITEM")
15109 (error "Cannot edit item headline from here"))
15111 (cond
15112 ((equal key "TODO")
15113 (setq eval '(org-with-point-at pom
15114 (let ((current-prefix-arg '(4))) (org-todo '(4))))))
15115 ((equal key "PRIORITY")
15116 (setq eval '(org-with-point-at pom
15117 (call-interactively 'org-priority))))
15118 ((equal key "TAGS")
15119 (setq eval '(org-with-point-at pom
15120 (let ((org-fast-tag-selection-single-key
15121 (if (eq org-fast-tag-selection-single-key 'expert)
15122 t org-fast-tag-selection-single-key)))
15123 (call-interactively 'org-set-tags)))))
15124 ((equal key "DEADLINE")
15125 (setq eval '(org-with-point-at pom
15126 (call-interactively 'org-deadline))))
15127 ((equal key "SCHEDULED")
15128 (setq eval '(org-with-point-at pom
15129 (call-interactively 'org-schedule))))
15131 (setq allowed (org-property-get-allowed-values pom key 'table))
15132 (if allowed
15133 (setq nval (completing-read "Value: " allowed nil t))
15134 (setq nval (read-string "Edit: " value)))
15135 (setq nval (org-trim nval))
15136 (when (not (equal nval value))
15137 (setq eval '(org-entry-put pom key nval)))))
15138 (when eval
15139 (let ((inhibit-read-only t))
15140 (remove-text-properties (1- bol) eol '(read-only t))
15141 (unwind-protect
15142 (progn
15143 (setq org-columns-overlays
15144 (org-delete-all line-overlays org-columns-overlays))
15145 (mapc 'org-delete-overlay line-overlays)
15146 (org-columns-eval eval))
15147 (org-columns-display-here))))
15148 (move-to-column col)
15149 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15150 (org-columns-update key))))
15152 (defun org-columns-edit-allowed ()
15153 "Edit the list of allowed values for the current property."
15154 (interactive)
15155 (let* ((col (current-column))
15156 (key (get-char-property (point) 'org-columns-key))
15157 (key1 (concat key "_ALL"))
15158 (value (get-char-property (point) 'org-columns-value))
15159 (allowed (org-entry-get (point) key1 t))
15160 nval)
15161 (setq nval (read-string "Allowed: " allowed))
15162 (org-entry-put
15163 (cond ((marker-position org-entry-property-inherited-from)
15164 org-entry-property-inherited-from)
15165 ((marker-position org-columns-top-level-marker)
15166 org-columns-top-level-marker))
15167 key1 nval)))
15169 (defun org-columns-eval (form)
15170 (let (hidep)
15171 (save-excursion
15172 (beginning-of-line 1)
15173 (next-line 1)
15174 (setq hidep (org-on-heading-p 1)))
15175 (eval form)
15176 (and hidep (hide-entry))))
15178 (defun org-columns-previous-allowed-value ()
15179 "Switch to the previous allowed value for this column."
15180 (interactive)
15181 (org-columns-next-allowed-value t))
15183 (defun org-columns-next-allowed-value (&optional previous)
15184 "Switch to the next allowed value for this column."
15185 (interactive)
15186 (org-columns-check-computed)
15187 (let* ((col (current-column))
15188 (key (get-char-property (point) 'org-columns-key))
15189 (value (get-char-property (point) 'org-columns-value))
15190 (bol (point-at-bol)) (eol (point-at-eol))
15191 (pom (or (get-text-property bol 'org-hd-marker)
15192 (point))) ; keep despite of compiler waring
15193 (line-overlays
15194 (delq nil (mapcar (lambda (x)
15195 (and (eq (overlay-buffer x) (current-buffer))
15196 (>= (overlay-start x) bol)
15197 (<= (overlay-start x) eol)
15199 org-columns-overlays)))
15200 (allowed (or (org-property-get-allowed-values pom key)
15201 (and (equal
15202 (nth 4 (assoc key org-columns-current-fmt-compiled))
15203 'checkbox) '("[ ]" "[X]"))))
15204 nval)
15205 (when (equal key "ITEM")
15206 (error "Cannot edit item headline from here"))
15207 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
15208 (error "Allowed values for this property have not been defined"))
15209 (if (member key '("SCHEDULED" "DEADLINE"))
15210 (setq nval (if previous 'earlier 'later))
15211 (if previous (setq allowed (reverse allowed)))
15212 (if (member value allowed)
15213 (setq nval (car (cdr (member value allowed)))))
15214 (setq nval (or nval (car allowed)))
15215 (if (equal nval value)
15216 (error "Only one allowed value for this property")))
15217 (let ((inhibit-read-only t))
15218 (remove-text-properties (1- bol) eol '(read-only t))
15219 (unwind-protect
15220 (progn
15221 (setq org-columns-overlays
15222 (org-delete-all line-overlays org-columns-overlays))
15223 (mapc 'org-delete-overlay line-overlays)
15224 (org-columns-eval '(org-entry-put pom key nval)))
15225 (org-columns-display-here)))
15226 (move-to-column col)
15227 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15228 (org-columns-update key))))
15230 (defun org-verify-version (task)
15231 (cond
15232 ((eq task 'columns)
15233 (if (or (featurep 'xemacs)
15234 (< emacs-major-version 22))
15235 (error "Emacs 22 is required for the columns feature")))))
15237 (defun org-columns-get-format-and-top-level ()
15238 (let (fmt)
15239 (when (condition-case nil (org-back-to-heading) (error nil))
15240 (move-marker org-entry-property-inherited-from nil)
15241 (setq fmt (org-entry-get nil "COLUMNS" t)))
15242 (setq fmt (or fmt org-columns-default-format))
15243 (org-set-local 'org-columns-current-fmt fmt)
15244 (org-columns-compile-format fmt)
15245 (if (marker-position org-entry-property-inherited-from)
15246 (move-marker org-columns-top-level-marker
15247 org-entry-property-inherited-from)
15248 (move-marker org-columns-top-level-marker (point)))
15249 fmt))
15251 (defun org-columns ()
15252 "Turn on column view on an org-mode file."
15253 (interactive)
15254 (org-verify-version 'columns)
15255 (org-columns-remove-overlays)
15256 (move-marker org-columns-begin-marker (point))
15257 (let (beg end fmt cache maxwidths)
15258 (setq fmt (org-columns-get-format-and-top-level))
15259 (save-excursion
15260 (goto-char org-columns-top-level-marker)
15261 (setq beg (point))
15262 (unless org-columns-inhibit-recalculation
15263 (org-columns-compute-all))
15264 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
15265 (point-max)))
15266 (goto-char beg)
15267 ;; Get and cache the properties
15268 (while (re-search-forward (concat "^" outline-regexp) end t)
15269 (push (cons (org-current-line) (org-entry-properties)) cache))
15270 (when cache
15271 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
15272 (org-set-local 'org-columns-current-maxwidths maxwidths)
15273 (org-columns-display-here-title)
15274 (mapc (lambda (x)
15275 (goto-line (car x))
15276 (org-columns-display-here (cdr x)))
15277 cache)))))
15279 (defun org-columns-new (&optional prop title width op fmt)
15280 "Insert a new column, to the leeft o the current column."
15281 (interactive)
15282 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
15283 cell)
15284 (setq prop (completing-read
15285 "Property: " (mapcar 'list (org-buffer-property-keys t))
15286 nil nil prop))
15287 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
15288 (setq width (read-string "Column width: " (if width (number-to-string width))))
15289 (if (string-match "\\S-" width)
15290 (setq width (string-to-number width))
15291 (setq width nil))
15292 (setq fmt (completing-read "Summary [none]: "
15293 '(("none") ("add_numbers") ("add_times") ("checkbox"))
15294 nil t))
15295 (if (string-match "\\S-" fmt)
15296 (setq fmt (intern fmt))
15297 (setq fmt nil))
15298 (if (eq fmt 'none) (setq fmt nil))
15299 (if editp
15300 (progn
15301 (setcar editp prop)
15302 (setcdr editp (list title width nil fmt)))
15303 (setq cell (nthcdr (1- (current-column))
15304 org-columns-current-fmt-compiled))
15305 (setcdr cell (cons (list prop title width nil fmt)
15306 (cdr cell))))
15307 (org-columns-store-format)
15308 (org-columns-redo)))
15310 (defun org-columns-delete ()
15311 "Delete the column at point from columns view."
15312 (interactive)
15313 (let* ((n (current-column))
15314 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
15315 (when (y-or-n-p
15316 (format "Are you sure you want to remove column \"%s\"? " title))
15317 (setq org-columns-current-fmt-compiled
15318 (delq (nth n org-columns-current-fmt-compiled)
15319 org-columns-current-fmt-compiled))
15320 (org-columns-store-format)
15321 (org-columns-redo)
15322 (if (>= (current-column) (length org-columns-current-fmt-compiled))
15323 (backward-char 1)))))
15325 (defun org-columns-edit-attributes ()
15326 "Edit the attributes of the current column."
15327 (interactive)
15328 (let* ((n (current-column))
15329 (info (nth n org-columns-current-fmt-compiled)))
15330 (apply 'org-columns-new info)))
15332 (defun org-columns-widen (arg)
15333 "Make the column wider by ARG characters."
15334 (interactive "p")
15335 (let* ((n (current-column))
15336 (entry (nth n org-columns-current-fmt-compiled))
15337 (width (or (nth 2 entry)
15338 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
15339 (setq width (max 1 (+ width arg)))
15340 (setcar (nthcdr 2 entry) width)
15341 (org-columns-store-format)
15342 (org-columns-redo)))
15344 (defun org-columns-narrow (arg)
15345 "Make the column nrrower by ARG characters."
15346 (interactive "p")
15347 (org-columns-widen (- arg)))
15349 (defun org-columns-move-right ()
15350 "Swap this column with the one to the right."
15351 (interactive)
15352 (let* ((n (current-column))
15353 (cell (nthcdr n org-columns-current-fmt-compiled))
15355 (when (>= n (1- (length org-columns-current-fmt-compiled)))
15356 (error "Cannot shift this column further to the right"))
15357 (setq e (car cell))
15358 (setcar cell (car (cdr cell)))
15359 (setcdr cell (cons e (cdr (cdr cell))))
15360 (org-columns-store-format)
15361 (org-columns-redo)
15362 (forward-char 1)))
15364 (defun org-columns-move-left ()
15365 "Swap this column with the one to the left."
15366 (interactive)
15367 (let* ((n (current-column)))
15368 (when (= n 0)
15369 (error "Cannot shift this column further to the left"))
15370 (backward-char 1)
15371 (org-columns-move-right)
15372 (backward-char 1)))
15374 (defun org-columns-store-format ()
15375 "Store the text version of the current columns format in appropriate place.
15376 This is either in the COLUMNS property of the node starting the current column
15377 display, or in the #+COLUMNS line of the current buffer."
15378 (let (fmt)
15379 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
15380 (if (marker-position org-columns-top-level-marker)
15381 (save-excursion
15382 (goto-char org-columns-top-level-marker)
15383 (if (org-entry-get nil "COLUMNS")
15384 (org-entry-put nil "COLUMNS" fmt)
15385 (goto-char (point-min))
15386 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
15387 (replace-match (concat "#+COLUMNS: " fmt t t)))))
15388 (setq org-columns-current-fmt fmt))))
15390 (defvar org-overriding-columns-format nil
15391 "When set, overrides any other definition.")
15392 (defvar org-agenda-view-columns-initially nil
15393 "When set, switch to columns view immediately after creating the agenda.")
15395 (defun org-agenda-columns ()
15396 "Turn on column view in the agenda."
15397 (interactive)
15398 (org-verify-version 'columns)
15399 (org-columns-remove-overlays)
15400 (move-marker org-columns-begin-marker (point))
15401 (let (fmt cache maxwidths m)
15402 (cond
15403 ((and (local-variable-p 'org-overriding-columns-format)
15404 org-overriding-columns-format)
15405 (setq fmt org-overriding-columns-format))
15406 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
15407 (setq fmt (org-entry-get m "COLUMNS" t)))
15408 ((and (boundp 'org-columns-current-fmt)
15409 (local-variable-p 'org-columns-current-fmt)
15410 org-columns-current-fmt)
15411 (setq fmt org-columns-current-fmt))
15412 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
15413 (setq m (get-text-property m 'org-hd-marker))
15414 (setq fmt (org-entry-get m "COLUMNS" t))))
15415 (setq fmt (or fmt org-columns-default-format))
15416 (org-set-local 'org-columns-current-fmt fmt)
15417 (org-columns-compile-format fmt)
15418 (save-excursion
15419 ;; Get and cache the properties
15420 (goto-char (point-min))
15421 (while (not (eobp))
15422 (when (setq m (or (get-text-property (point) 'org-hd-marker)
15423 (get-text-property (point) 'org-marker)))
15424 (push (cons (org-current-line) (org-entry-properties m)) cache))
15425 (beginning-of-line 2))
15426 (when cache
15427 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
15428 (org-set-local 'org-columns-current-maxwidths maxwidths)
15429 (org-columns-display-here-title)
15430 (mapc (lambda (x)
15431 (goto-line (car x))
15432 (org-columns-display-here (cdr x)))
15433 cache)))))
15435 (defun org-columns-get-autowidth-alist (s cache)
15436 "Derive the maximum column widths from the format and the cache."
15437 (let ((start 0) rtn)
15438 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
15439 (push (cons (match-string 1 s) 1) rtn)
15440 (setq start (match-end 0)))
15441 (mapc (lambda (x)
15442 (setcdr x (apply 'max
15443 (mapcar
15444 (lambda (y)
15445 (length (or (cdr (assoc (car x) (cdr y))) " ")))
15446 cache))))
15447 rtn)
15448 rtn))
15450 (defun org-columns-compute-all ()
15451 "Compute all columns that have operators defined."
15452 (org-unmodified
15453 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
15454 (let ((columns org-columns-current-fmt-compiled) col)
15455 (while (setq col (pop columns))
15456 (when (nth 3 col)
15457 (save-excursion
15458 (org-columns-compute (car col)))))))
15460 (defun org-columns-update (property)
15461 "Recompute PROPERTY, and update the columns display for it."
15462 (org-columns-compute property)
15463 (let (fmt val pos)
15464 (save-excursion
15465 (mapc (lambda (ov)
15466 (when (equal (org-overlay-get ov 'org-columns-key) property)
15467 (setq pos (org-overlay-start ov))
15468 (goto-char pos)
15469 (when (setq val (cdr (assoc property
15470 (get-text-property
15471 (point-at-bol) 'org-summaries))))
15472 (setq fmt (org-overlay-get ov 'org-columns-format))
15473 (org-overlay-put ov 'org-columns-value val)
15474 (org-overlay-put ov 'display (format fmt val)))))
15475 org-columns-overlays))))
15477 (defun org-columns-compute (property)
15478 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
15479 (interactive)
15480 (let* ((re (concat "^" outline-regexp))
15481 (lmax 30) ; Does anyone use deeper levels???
15482 (lsum (make-vector lmax 0))
15483 (lflag (make-vector lmax nil))
15484 (level 0)
15485 (ass (assoc property org-columns-current-fmt-compiled))
15486 (format (nth 4 ass))
15487 (beg org-columns-top-level-marker)
15488 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
15489 (save-excursion
15490 ;; Find the region to compute
15491 (goto-char beg)
15492 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
15493 (goto-char end)
15494 ;; Walk the tree from the back and do the computations
15495 (while (re-search-backward re beg t)
15496 (setq sumpos (match-beginning 0)
15497 last-level level
15498 level (org-outline-level)
15499 val (org-entry-get nil property)
15500 valflag (and val (string-match "\\S-" val)))
15501 (cond
15502 ((< level last-level)
15503 ;; put the sum of lower levels here as a property
15504 (setq sum (aref lsum last-level) ; current sum
15505 flag (aref lflag last-level) ; any valid entries from children?
15506 str (org-column-number-to-string sum format)
15507 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
15508 useval (if flag str1 (if valflag val ""))
15509 sum-alist (get-text-property sumpos 'org-summaries))
15510 (if (assoc property sum-alist)
15511 (setcdr (assoc property sum-alist) useval)
15512 (push (cons property useval) sum-alist)
15513 (org-unmodified
15514 (add-text-properties sumpos (1+ sumpos)
15515 (list 'org-summaries sum-alist))))
15516 (when val
15517 (org-entry-put nil property (if flag str val)))
15518 ;; add current to current level accumulator
15519 (when (or flag valflag)
15520 ;; FIXME: is this ok?????????
15521 (aset lsum level (+ (aref lsum level)
15522 (if flag sum (org-column-string-to-number
15523 (if flag str val) format))))
15524 (aset lflag level t))
15525 ;; clear accumulators for deeper levels
15526 (loop for l from (1+ level) to (1- lmax) do
15527 (aset lsum l 0)
15528 (aset lflag l nil)))
15529 ((>= level last-level)
15530 ;; add what we have here to the accumulator for this level
15531 (aset lsum level (+ (aref lsum level)
15532 (org-column-string-to-number (or val "0") format)))
15533 (and valflag (aset lflag level t)))
15534 (t (error "This should not happen")))))))
15536 (defun org-columns-redo ()
15537 "Construct the column display again."
15538 (interactive)
15539 (message "Recomputing columns...")
15540 (save-excursion
15541 (if (marker-position org-columns-begin-marker)
15542 (goto-char org-columns-begin-marker))
15543 (org-columns-remove-overlays)
15544 (if (org-mode-p)
15545 (call-interactively 'org-columns)
15546 (call-interactively 'org-agenda-columns)))
15547 (message "Recomputing columns...done"))
15549 (defun org-columns-not-in-agenda ()
15550 (if (eq major-mode 'org-agenda-mode)
15551 (error "This command is only allowed in Org-mode buffers")))
15554 (defun org-string-to-number (s)
15555 "Convert string to number, and interpret hh:mm:ss."
15556 (if (not (string-match ":" s))
15557 (string-to-number s)
15558 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
15559 (while l
15560 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
15561 sum)))
15563 (defun org-column-number-to-string (n fmt)
15564 "Convert a computed column number to a string value, according to FMT."
15565 (cond
15566 ((eq fmt 'add_times)
15567 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
15568 (format "%d:%02d" h m)))
15569 ((eq fmt 'checkbox)
15570 (cond ((= n (floor n)) "[X]")
15571 ((> n 1.) "[-]")
15572 (t "[ ]")))
15573 (t (number-to-string n))))
15575 (defun org-column-string-to-number (s fmt)
15576 "Convert a column value to a number that can be used for column computing."
15577 (cond
15578 ((string-match ":" s)
15579 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
15580 (while l
15581 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
15582 sum))
15583 ((eq fmt 'checkbox)
15584 (if (equal s "[X]") 1. 0.000001))
15585 (t (string-to-number s))))
15587 (defun org-columns-uncompile-format (cfmt)
15588 "Turn the compiled columns format back into a string representation."
15589 (let ((rtn "") e s prop title op width fmt)
15590 (while (setq e (pop cfmt))
15591 (setq prop (car e)
15592 title (nth 1 e)
15593 width (nth 2 e)
15594 op (nth 3 e)
15595 fmt (nth 4 e))
15596 (cond
15597 ((eq fmt 'add_times) (setq op ":"))
15598 ((eq fmt 'checkbox) (setq op "X"))
15599 ((eq fmt 'add_numbers) (setq op "+")))
15600 (if (equal title prop) (setq title nil))
15601 (setq s (concat "%" (if width (number-to-string width))
15602 prop
15603 (if title (concat "(" title ")"))
15604 (if op (concat "{" op "}"))))
15605 (setq rtn (concat rtn " " s)))
15606 (org-trim rtn)))
15608 (defun org-columns-compile-format (fmt)
15609 "Turn a column format string into an alist of specifications.
15610 The alist has one entry for each column in the format. The elements of
15611 that list are:
15612 property the property
15613 title the title field for the columns
15614 width the column width in characters, can be nil for automatic
15615 operator the operator if any
15616 format the output format for computed results, derived from operator"
15617 (let ((start 0) width prop title op f)
15618 (setq org-columns-current-fmt-compiled nil)
15619 (while (string-match
15620 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
15621 fmt start)
15622 (setq start (match-end 0)
15623 width (match-string 1 fmt)
15624 prop (match-string 2 fmt)
15625 title (or (match-string 3 fmt) prop)
15626 op (match-string 4 fmt)
15627 f nil)
15628 (if width (setq width (string-to-number width)))
15629 (cond
15630 ((equal op "+") (setq f 'add_numbers))
15631 ((equal op ":") (setq f 'add_times))
15632 ((equal op "X") (setq f 'checkbox)))
15633 (push (list prop title width op f) org-columns-current-fmt-compiled))
15634 (setq org-columns-current-fmt-compiled
15635 (nreverse org-columns-current-fmt-compiled))))
15637 ;;;; Timestamps
15639 (defvar org-last-changed-timestamp nil)
15640 (defvar org-time-was-given) ; dynamically scoped parameter
15641 (defvar org-end-time-was-given) ; dynamically scoped parameter
15642 (defvar org-ts-what) ; dynamically scoped parameter
15644 (defun org-time-stamp (arg)
15645 "Prompt for a date/time and insert a time stamp.
15646 If the user specifies a time like HH:MM, or if this command is called
15647 with a prefix argument, the time stamp will contain date and time.
15648 Otherwise, only the date will be included. All parts of a date not
15649 specified by the user will be filled in from the current date/time.
15650 So if you press just return without typing anything, the time stamp
15651 will represent the current date/time. If there is already a timestamp
15652 at the cursor, it will be modified."
15653 (interactive "P")
15654 (let ((default-time
15655 ;; Default time is either today, or, when entering a range,
15656 ;; the range start.
15657 (if (or (org-at-timestamp-p t)
15658 (save-excursion
15659 (re-search-backward
15660 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15661 (- (point) 20) t)))
15662 (apply 'encode-time (org-parse-time-string (match-string 1)))
15663 (current-time)))
15664 org-time-was-given org-end-time-was-given time)
15665 (cond
15666 ((and (org-at-timestamp-p)
15667 (eq last-command 'org-time-stamp)
15668 (eq this-command 'org-time-stamp))
15669 (insert "--")
15670 (setq time (let ((this-command this-command))
15671 (org-read-date arg 'totime nil nil default-time)))
15672 (org-insert-time-stamp time (or org-time-was-given arg)))
15673 ((org-at-timestamp-p)
15674 (setq time (let ((this-command this-command))
15675 (org-read-date arg 'totime nil nil default-time)))
15676 (when (org-at-timestamp-p) ; just to get the match data
15677 (replace-match "")
15678 (setq org-last-changed-timestamp
15679 (org-insert-time-stamp
15680 time (or org-time-was-given arg)
15681 nil nil nil (list org-end-time-was-given))))
15682 (message "Timestamp updated"))
15684 (setq time (let ((this-command this-command))
15685 (org-read-date arg 'totime nil nil default-time)))
15686 (org-insert-time-stamp time (or org-time-was-given arg)
15687 nil nil nil (list org-end-time-was-given))))))
15689 (defun org-time-stamp-inactive (&optional arg)
15690 "Insert an inactive time stamp.
15691 An inactive time stamp is enclosed in square brackets instead of angle
15692 brackets. It is inactive in the sense that it does not trigger agenda entries,
15693 does not link to the calendar and cannot be changed with the S-cursor keys.
15694 So these are more for recording a certain time/date."
15695 (interactive "P")
15696 (let (org-time-was-given org-end-time-was-given time)
15697 (setq time (org-read-date arg 'totime))
15698 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
15699 nil nil (list org-end-time-was-given))))
15701 (defvar org-date-ovl (org-make-overlay 1 1))
15702 (org-overlay-put org-date-ovl 'face 'org-warning)
15703 (org-detach-overlay org-date-ovl)
15705 (defvar org-ans1) ; dynamically scoped parameter
15706 (defvar org-ans2) ; dynamically scoped parameter
15708 (defvar org-plain-time-of-day-regexp) ; defined below
15709 (defun org-read-date (&optional with-time to-time from-string prompt
15710 default-time)
15711 "Read a date and make things smooth for the user.
15712 The prompt will suggest to enter an ISO date, but you can also enter anything
15713 which will at least partially be understood by `parse-time-string'.
15714 Unrecognized parts of the date will default to the current day, month, year,
15715 hour and minute. If this command is called to replace a timestamp at point,
15716 of to enter the second timestamp of a range, the default time is taken from the
15717 existing stamp. For example,
15718 3-2-5 --> 2003-02-05
15719 feb 15 --> currentyear-02-15
15720 sep 12 9 --> 2009-09-12
15721 12:45 --> today 12:45
15722 22 sept 0:34 --> currentyear-09-22 0:34
15723 12 --> currentyear-currentmonth-12
15724 Fri --> nearest Friday (today or later)
15725 etc.
15727 Furthermore you can specify a relative date by giving, as the *first* thing
15728 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
15729 change in days weeks, months, years.
15730 With a single plus or minus, the date is relative to today. With a double
15731 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15732 +4d --> four days from today
15733 +4 --> same as above
15734 +2w --> two weeks from today
15735 ++5 --> five days from default date
15737 The function understands only English month and weekday abbreviations,
15738 but this can be configured with the variables `parse-time-months' and
15739 `parse-time-weekdays'.
15741 While prompting, a calendar is popped up - you can also select the
15742 date with the mouse (button 1). The calendar shows a period of three
15743 months. To scroll it to other months, use the keys `>' and `<'.
15744 If you don't like the calendar, turn it off with
15745 \(setq org-popup-calendar-for-date-prompt nil)
15747 With optional argument TO-TIME, the date will immediately be converted
15748 to an internal time.
15749 With an optional argument WITH-TIME, the prompt will suggest to also
15750 insert a time. Note that when WITH-TIME is not set, you can still
15751 enter a time, and this function will inform the calling routine about
15752 this change. The calling routine may then choose to change the format
15753 used to insert the time stamp into the buffer to include the time.
15754 With optional argument FROM-STRING, read fomr this string instead from
15755 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15756 the time/date that is used for everything that is not specified by the
15757 user."
15758 (require 'parse-time)
15759 (let* ((org-time-stamp-rounding-minutes
15760 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
15761 (ct (org-current-time))
15762 (def (or default-time ct))
15763 (calendar-move-hook nil)
15764 (view-diary-entries-initially nil)
15765 (view-calendar-holidays-initially nil)
15766 (timestr (format-time-string
15767 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
15768 (prompt (concat (if prompt (concat prompt " ") "")
15769 (format "Date and/or time (default [%s]): " timestr)))
15770 ans (org-ans0 "") org-ans1 org-ans2 deltan deltaw deltarel
15771 second minute hour day month year tl wday wday1 pm h2 m2)
15773 (cond
15774 (from-string (setq ans from-string))
15775 (org-popup-calendar-for-date-prompt
15776 (save-excursion
15777 (save-window-excursion
15778 (calendar)
15779 (calendar-forward-day (- (time-to-days def)
15780 (calendar-absolute-from-gregorian
15781 (calendar-current-date))))
15782 (org-eval-in-calendar nil t)
15783 (let* ((old-map (current-local-map))
15784 (map (copy-keymap calendar-mode-map))
15785 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15786 (org-defkey map (kbd "RET") 'org-calendar-select)
15787 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
15788 'org-calendar-select-mouse)
15789 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
15790 'org-calendar-select-mouse)
15791 (org-defkey minibuffer-local-map [(meta shift left)]
15792 (lambda () (interactive)
15793 (org-eval-in-calendar '(calendar-backward-month 1))))
15794 (org-defkey minibuffer-local-map [(meta shift right)]
15795 (lambda () (interactive)
15796 (org-eval-in-calendar '(calendar-forward-month 1))))
15797 (org-defkey minibuffer-local-map [(shift up)]
15798 (lambda () (interactive)
15799 (org-eval-in-calendar '(calendar-backward-week 1))))
15800 (org-defkey minibuffer-local-map [(shift down)]
15801 (lambda () (interactive)
15802 (org-eval-in-calendar '(calendar-forward-week 1))))
15803 (org-defkey minibuffer-local-map [(shift left)]
15804 (lambda () (interactive)
15805 (org-eval-in-calendar '(calendar-backward-day 1))))
15806 (org-defkey minibuffer-local-map [(shift right)]
15807 (lambda () (interactive)
15808 (org-eval-in-calendar '(calendar-forward-day 1))))
15809 (org-defkey minibuffer-local-map ">"
15810 (lambda () (interactive)
15811 (org-eval-in-calendar '(scroll-calendar-left 1))))
15812 (org-defkey minibuffer-local-map "<"
15813 (lambda () (interactive)
15814 (org-eval-in-calendar '(scroll-calendar-right 1))))
15815 (unwind-protect
15816 (progn
15817 (use-local-map map)
15818 (setq org-ans0 (read-string prompt "" nil nil))
15819 ;; org-ans0: from prompt
15820 ;; org-ans1: from mouse click
15821 ;; org-ans2: from calendar motion
15822 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15823 (use-local-map old-map))))))
15824 (t ; Naked prompt only
15825 (setq ans (read-string prompt "" nil timestr))))
15826 (org-detach-overlay org-date-ovl)
15828 (when (string-match
15829 "\\`[ \t]*\\([-+]\\)?\\([-+][0-9]+\\)\\([dwmy]?\\)\\([ \t\n]\\|$\\)"
15830 org-ans0)
15831 (setq deltan (string-to-number (match-string 2 ans))
15832 deltaw (match-string 3 ans)
15833 deltarel (match-end 1)))
15835 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
15836 (when (string-match
15837 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15838 (setq year (if (match-end 2)
15839 (string-to-number (match-string 2 ans))
15840 (string-to-number (format-time-string "%Y")))
15841 month (string-to-number (match-string 3 ans))
15842 day (string-to-number (match-string 4 ans)))
15843 (if (< year 100) (setq year (+ 2000 year)))
15844 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15845 t nil ans)))
15846 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15847 ;; If there is a time with am/pm, and *no* time without it, we convert
15848 ;; so that matching will be successful.
15849 (loop for i from 1 to 2 do ; twice, for end time as well
15850 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15851 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15852 (setq hour (string-to-number (match-string 1 ans))
15853 minute (if (match-end 3)
15854 (string-to-number (match-string 3 ans))
15856 pm (equal ?p
15857 (string-to-char (downcase (match-string 4 ans)))))
15858 (if (and (= hour 12) (not pm))
15859 (setq hour 0)
15860 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15861 (setq ans (replace-match (format "%02d:%02d" hour minute)
15862 t t ans))))
15864 ;; Check if a time range is given as a duration
15865 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15866 (setq hour (string-to-number (match-string 1 ans))
15867 h2 (+ hour (string-to-number (match-string 3 ans)))
15868 minute (string-to-number (match-string 2 ans))
15869 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
15870 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
15872 ;; Check if there is a time range
15873 (when (and (boundp 'org-end-time-was-given)
15874 (string-match org-plain-time-of-day-regexp ans)
15875 (match-end 8))
15876 (setq org-end-time-was-given (match-string 8 ans))
15877 (setq ans (concat (substring ans 0 (match-beginning 7))
15878 (substring ans (match-end 7)))))
15880 (setq tl (parse-time-string ans)
15881 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" def)))
15882 month (or (nth 4 tl) (string-to-number (format-time-string "%m" def)))
15883 day (or (nth 3 tl) (string-to-number (format-time-string "%d" def)))
15884 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" def)))
15885 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" def)))
15886 second (or (nth 0 tl) 0)
15887 wday (nth 6 tl))
15888 (when deltan
15889 (unless deltarel
15890 (let ((now (decode-time (current-time))))
15891 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15892 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15893 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15894 ((equal deltaw "m") (setq month (+ month deltan)))
15895 ((equal deltaw "y") (setq year (+ year deltan)))))
15896 (when (and wday (not (nth 3 tl)))
15897 ;; Weekday was given, but no day, so pick that day in the week
15898 ;; on or after the derived date.
15899 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15900 (unless (equal wday wday1)
15901 (setq day (+ day (% (- wday wday1 -7) 7)))))
15902 (if (and (boundp 'org-time-was-given)
15903 (nth 2 tl))
15904 (setq org-time-was-given t))
15905 (if (< year 100) (setq year (+ 2000 year)))
15906 (if to-time
15907 (encode-time second minute hour day month year)
15908 (if (or (nth 1 tl) (nth 2 tl))
15909 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
15910 (format "%04d-%02d-%02d" year month day)))))
15912 (defun org-eval-in-calendar (form &optional keepdate)
15913 "Eval FORM in the calendar window and return to current window.
15914 Also, store the cursor date in variable org-ans2."
15915 (let ((sw (selected-window)))
15916 (select-window (get-buffer-window "*Calendar*"))
15917 (eval form)
15918 (when (and (not keepdate) (calendar-cursor-to-date))
15919 (let* ((date (calendar-cursor-to-date))
15920 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15921 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15922 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15923 (select-window sw)
15924 ;; Update the prompt to show new default date
15925 (save-excursion
15926 (goto-char (point-min))
15927 (when (and org-ans2
15928 (re-search-forward "\\[[-0-9]+\\]" nil t)
15929 (get-text-property (match-end 0) 'field))
15930 (let ((inhibit-read-only t))
15931 (replace-match (concat "[" org-ans2 "]") t t)
15932 (add-text-properties (point-min) (1+ (match-end 0))
15933 (text-properties-at (1+ (point-min)))))))))
15935 (defun org-calendar-select ()
15936 "Return to `org-read-date' with the date currently selected.
15937 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15938 (interactive)
15939 (when (calendar-cursor-to-date)
15940 (let* ((date (calendar-cursor-to-date))
15941 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15942 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15943 (if (active-minibuffer-window) (exit-minibuffer))))
15945 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15946 "Insert a date stamp for the date given by the internal TIME.
15947 WITH-HM means, use the stamp format that includes the time of the day.
15948 INACTIVE means use square brackets instead of angular ones, so that the
15949 stamp will not contribute to the agenda.
15950 PRE and POST are optional strings to be inserted before and after the
15951 stamp.
15952 The command returns the inserted time stamp."
15953 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15954 stamp)
15955 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15956 (insert-before-markers (or pre ""))
15957 (insert-before-markers (setq stamp (format-time-string fmt time)))
15958 (when (listp extra)
15959 (setq extra (car extra))
15960 (if (and (stringp extra)
15961 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15962 (setq extra (format "-%02d:%02d"
15963 (string-to-number (match-string 1 extra))
15964 (string-to-number (match-string 2 extra))))
15965 (setq extra nil)))
15966 (when extra
15967 (backward-char 1)
15968 (insert-before-markers extra)
15969 (forward-char 1))
15970 (insert-before-markers (or post ""))
15971 stamp))
15973 (defun org-toggle-time-stamp-overlays ()
15974 "Toggle the use of custom time stamp formats."
15975 (interactive)
15976 (setq org-display-custom-times (not org-display-custom-times))
15977 (unless org-display-custom-times
15978 (let ((p (point-min)) (bmp (buffer-modified-p)))
15979 (while (setq p (next-single-property-change p 'display))
15980 (if (and (get-text-property p 'display)
15981 (eq (get-text-property p 'face) 'org-date))
15982 (remove-text-properties
15983 p (setq p (next-single-property-change p 'display))
15984 '(display t))))
15985 (set-buffer-modified-p bmp)))
15986 (if (featurep 'xemacs)
15987 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15988 (org-restart-font-lock)
15989 (setq org-table-may-need-update t)
15990 (if org-display-custom-times
15991 (message "Time stamps are overlayed with custom format")
15992 (message "Time stamp overlays removed")))
15994 (defun org-display-custom-time (beg end)
15995 "Overlay modified time stamp format over timestamp between BED and END."
15996 (let* ((ts (buffer-substring beg end))
15997 t1 w1 with-hm tf time str w2 (off 0))
15998 (save-match-data
15999 (setq t1 (org-parse-time-string ts t))
16000 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
16001 (setq off (- (match-end 0) (match-beginning 0)))))
16002 (setq end (- end off))
16003 (setq w1 (- end beg)
16004 with-hm (and (nth 1 t1) (nth 2 t1))
16005 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16006 time (org-fix-decoded-time t1)
16007 str (org-add-props
16008 (format-time-string
16009 (substring tf 1 -1) (apply 'encode-time time))
16010 nil 'mouse-face 'highlight)
16011 w2 (length str))
16012 (if (not (= w2 w1))
16013 (add-text-properties (1+ beg) (+ 2 beg)
16014 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16015 (if (featurep 'xemacs)
16016 (progn
16017 (put-text-property beg end 'invisible t)
16018 (put-text-property beg end 'end-glyph (make-glyph str)))
16019 (put-text-property beg end 'display str))))
16021 (defun org-translate-time (string)
16022 "Translate all timestamps in STRING to custom format.
16023 But do this only if the variable `org-display-custom-times' is set."
16024 (when org-display-custom-times
16025 (save-match-data
16026 (let* ((start 0)
16027 (re org-ts-regexp-both)
16028 t1 with-hm inactive tf time str beg end)
16029 (while (setq start (string-match re string start))
16030 (setq beg (match-beginning 0)
16031 end (match-end 0)
16032 t1 (save-match-data
16033 (org-parse-time-string (substring string beg end) t))
16034 with-hm (and (nth 1 t1) (nth 2 t1))
16035 inactive (equal (substring string beg (1+ beg)) "[")
16036 tf (funcall (if with-hm 'cdr 'car)
16037 org-time-stamp-custom-formats)
16038 time (org-fix-decoded-time t1)
16039 str (format-time-string
16040 (concat
16041 (if inactive "[" "<") (substring tf 1 -1)
16042 (if inactive "]" ">"))
16043 (apply 'encode-time time))
16044 string (replace-match str t t string)
16045 start (+ start (length str)))))))
16046 string)
16048 (defun org-fix-decoded-time (time)
16049 "Set 0 instead of nil for the first 6 elements of time.
16050 Don't touch the rest."
16051 (let ((n 0))
16052 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16054 (defun org-days-to-time (timestamp-string)
16055 "Difference between TIMESTAMP-STRING and now in days."
16056 (- (time-to-days (org-time-string-to-time timestamp-string))
16057 (time-to-days (current-time))))
16059 (defun org-deadline-close (timestamp-string &optional ndays)
16060 "Is the time in TIMESTAMP-STRING close to the current date?"
16061 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16062 (and (< (org-days-to-time timestamp-string) ndays)
16063 (not (org-entry-is-done-p))))
16065 (defun org-get-wdays (ts)
16066 "Get the deadline lead time appropriate for timestring TS."
16067 (cond
16068 ((<= org-deadline-warning-days 0)
16069 ;; 0 or negative, enforce this value no matter what
16070 (- org-deadline-warning-days))
16071 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
16072 ;; lead time is specified.
16073 (floor (* (string-to-number (match-string 1 ts))
16074 (cdr (assoc (match-string 2 ts)
16075 '(("d" . 1) ("w" . 7)
16076 ("m" . 30.4) ("y" . 365.25)))))))
16077 ;; go for the default.
16078 (t org-deadline-warning-days)))
16080 (defun org-calendar-select-mouse (ev)
16081 "Return to `org-read-date' with the date currently selected.
16082 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16083 (interactive "e")
16084 (mouse-set-point ev)
16085 (when (calendar-cursor-to-date)
16086 (let* ((date (calendar-cursor-to-date))
16087 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16088 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16089 (if (active-minibuffer-window) (exit-minibuffer))))
16091 (defun org-check-deadlines (ndays)
16092 "Check if there are any deadlines due or past due.
16093 A deadline is considered due if it happens within `org-deadline-warning-days'
16094 days from today's date. If the deadline appears in an entry marked DONE,
16095 it is not shown. The prefix arg NDAYS can be used to test that many
16096 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16097 (interactive "P")
16098 (let* ((org-warn-days
16099 (cond
16100 ((equal ndays '(4)) 100000)
16101 (ndays (prefix-numeric-value ndays))
16102 (t (abs org-deadline-warning-days))))
16103 (case-fold-search nil)
16104 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16105 (callback
16106 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16108 (message "%d deadlines past-due or due within %d days"
16109 (org-occur regexp nil callback)
16110 org-warn-days)))
16112 (defun org-evaluate-time-range (&optional to-buffer)
16113 "Evaluate a time range by computing the difference between start and end.
16114 Normally the result is just printed in the echo area, but with prefix arg
16115 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16116 If the time range is actually in a table, the result is inserted into the
16117 next column.
16118 For time difference computation, a year is assumed to be exactly 365
16119 days in order to avoid rounding problems."
16120 (interactive "P")
16122 (org-clock-update-time-maybe)
16123 (save-excursion
16124 (unless (org-at-date-range-p t)
16125 (goto-char (point-at-bol))
16126 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16127 (if (not (org-at-date-range-p t))
16128 (error "Not at a time-stamp range, and none found in current line")))
16129 (let* ((ts1 (match-string 1))
16130 (ts2 (match-string 2))
16131 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16132 (match-end (match-end 0))
16133 (time1 (org-time-string-to-time ts1))
16134 (time2 (org-time-string-to-time ts2))
16135 (t1 (time-to-seconds time1))
16136 (t2 (time-to-seconds time2))
16137 (diff (abs (- t2 t1)))
16138 (negative (< (- t2 t1) 0))
16139 ;; (ys (floor (* 365 24 60 60)))
16140 (ds (* 24 60 60))
16141 (hs (* 60 60))
16142 (fy "%dy %dd %02d:%02d")
16143 (fy1 "%dy %dd")
16144 (fd "%dd %02d:%02d")
16145 (fd1 "%dd")
16146 (fh "%02d:%02d")
16147 y d h m align)
16148 (if havetime
16149 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16151 d (floor (/ diff ds)) diff (mod diff ds)
16152 h (floor (/ diff hs)) diff (mod diff hs)
16153 m (floor (/ diff 60)))
16154 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16156 d (floor (+ (/ diff ds) 0.5))
16157 h 0 m 0))
16158 (if (not to-buffer)
16159 (message (org-make-tdiff-string y d h m))
16160 (when (org-at-table-p)
16161 (goto-char match-end)
16162 (setq align t)
16163 (and (looking-at " *|") (goto-char (match-end 0))))
16164 (if (looking-at
16165 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16166 (replace-match ""))
16167 (if negative (insert " -"))
16168 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16169 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16170 (insert " " (format fh h m))))
16171 (if align (org-table-align))
16172 (message "Time difference inserted")))))
16174 (defun org-make-tdiff-string (y d h m)
16175 (let ((fmt "")
16176 (l nil))
16177 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16178 l (push y l)))
16179 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16180 l (push d l)))
16181 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16182 l (push h l)))
16183 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16184 l (push m l)))
16185 (apply 'format fmt (nreverse l))))
16187 (defun org-time-string-to-time (s)
16188 (apply 'encode-time (org-parse-time-string s)))
16190 (defun org-time-string-to-absolute (s &optional daynr)
16191 "Convert a time stamp to an absolute day number.
16192 If there is a specifyer for a cyclic time stamp, get the closest date to
16193 DAYNR."
16194 (cond
16195 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16196 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16197 daynr
16198 (+ daynr 1000)))
16199 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
16200 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16201 (time-to-days (current-time))) (match-string 0 s)))
16202 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
16204 (defun org-time-from-absolute (d)
16205 "Return the time corresponding to date D.
16206 D may be an absolute day number, or a calendar-type list (month day year)."
16207 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16208 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16210 (defun org-calendar-holiday ()
16211 "List of holidays, for Diary display in Org-mode."
16212 (let ((hl (check-calendar-holidays date)))
16213 (if hl (mapconcat 'identity hl "; "))))
16215 (defun org-diary-sexp-entry (sexp entry date)
16216 "Process a SEXP diary ENTRY for DATE."
16217 (require 'diary-lib)
16218 (let ((result (if calendar-debug-sexp
16219 (let ((stack-trace-on-error t))
16220 (eval (car (read-from-string sexp))))
16221 (condition-case nil
16222 (eval (car (read-from-string sexp)))
16223 (error
16224 (beep)
16225 (message "Bad sexp at line %d in %s: %s"
16226 (org-current-line)
16227 (buffer-file-name) sexp)
16228 (sleep-for 2))))))
16229 (cond ((stringp result) result)
16230 ((and (consp result)
16231 (stringp (cdr result))) (cdr result))
16232 (result entry)
16233 (t nil))))
16235 (defun org-diary-to-ical-string (frombuf)
16236 "Get iCalendar entreis from diary entries in buffer FROMBUF.
16237 This uses the icalendar.el library."
16238 (let* ((tmpdir (if (featurep 'xemacs)
16239 (temp-directory)
16240 temporary-file-directory))
16241 (tmpfile (make-temp-name
16242 (expand-file-name "orgics" tmpdir)))
16243 buf rtn b e)
16244 (save-excursion
16245 (set-buffer frombuf)
16246 (icalendar-export-region (point-min) (point-max) tmpfile)
16247 (setq buf (find-buffer-visiting tmpfile))
16248 (set-buffer buf)
16249 (goto-char (point-min))
16250 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16251 (setq b (match-beginning 0)))
16252 (goto-char (point-max))
16253 (if (re-search-backward "^END:VEVENT" nil t)
16254 (setq e (match-end 0)))
16255 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16256 (kill-buffer buf)
16257 (kill-buffer frombuf)
16258 (delete-file tmpfile)
16259 rtn))
16261 (defun org-closest-date (start current change)
16262 "Find the date closest to CURRENT that is consistent with START and CHANGE."
16263 ;; Make the proper lists from the dates
16264 (catch 'exit
16265 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16266 dn dw sday cday n1 n2
16267 d m y y1 y2 date1 date2 nmonths nm ny m2)
16269 (setq start (org-date-to-gregorian start)
16270 current (org-date-to-gregorian
16271 (if org-agenda-repeating-timestamp-show-all
16272 current
16273 (time-to-days (current-time))))
16274 sday (calendar-absolute-from-gregorian start)
16275 cday (calendar-absolute-from-gregorian current))
16277 (if (<= cday sday) (throw 'exit sday))
16279 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
16280 (setq dn (string-to-number (match-string 1 change))
16281 dw (cdr (assoc (match-string 2 change) a1)))
16282 (error "Invalid change specifyer: %s" change))
16283 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16284 (cond
16285 ((eq dw 'day)
16286 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16287 n2 (+ n1 dn)))
16288 ((eq dw 'year)
16289 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16290 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16291 (setq date1 (list m d y1)
16292 n1 (calendar-absolute-from-gregorian date1)
16293 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16294 n2 (calendar-absolute-from-gregorian date2)))
16295 ((eq dw 'month)
16296 ;; approx number of month between the tow dates
16297 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16298 ;; How often does dn fit in there?
16299 (setq d (nth 1 start) m (car start) y (nth 2 start)
16300 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16301 m (+ m nm)
16302 ny (floor (/ m 12))
16303 y (+ y ny)
16304 m (- m (* ny 12)))
16305 (while (> m 12) (setq m (- m 12) y (1+ y)))
16306 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16307 (setq m2 (+ m dn) y2 y)
16308 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16309 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16310 (while (< n2 cday)
16311 (setq n1 n2 m m2 y y2)
16312 (setq m2 (+ m dn) y2 y)
16313 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16314 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16316 (if org-agenda-repeating-timestamp-show-all
16317 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
16318 (if (= cday n1) n1 n2)))))
16320 (defun org-date-to-gregorian (date)
16321 "Turn any specification of DATE into a gregorian date for the calendar."
16322 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16323 ((and (listp date) (= (length date) 3)) date)
16324 ((stringp date)
16325 (setq date (org-parse-time-string date))
16326 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16327 ((listp date)
16328 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16330 (defun org-parse-time-string (s &optional nodefault)
16331 "Parse the standard Org-mode time string.
16332 This should be a lot faster than the normal `parse-time-string'.
16333 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16334 hour and minute fields will be nil if not given."
16335 (if (string-match org-ts-regexp0 s)
16336 (list 0
16337 (if (or (match-beginning 8) (not nodefault))
16338 (string-to-number (or (match-string 8 s) "0")))
16339 (if (or (match-beginning 7) (not nodefault))
16340 (string-to-number (or (match-string 7 s) "0")))
16341 (string-to-number (match-string 4 s))
16342 (string-to-number (match-string 3 s))
16343 (string-to-number (match-string 2 s))
16344 nil nil nil)
16345 (make-list 9 0)))
16347 (defun org-timestamp-up (&optional arg)
16348 "Increase the date item at the cursor by one.
16349 If the cursor is on the year, change the year. If it is on the month or
16350 the day, change that.
16351 With prefix ARG, change by that many units."
16352 (interactive "p")
16353 (org-timestamp-change (prefix-numeric-value arg)))
16355 (defun org-timestamp-down (&optional arg)
16356 "Decrease the date item at the cursor by one.
16357 If the cursor is on the year, change the year. If it is on the month or
16358 the day, change that.
16359 With prefix ARG, change by that many units."
16360 (interactive "p")
16361 (org-timestamp-change (- (prefix-numeric-value arg))))
16363 (defun org-timestamp-up-day (&optional arg)
16364 "Increase the date in the time stamp by one day.
16365 With prefix ARG, change that many days."
16366 (interactive "p")
16367 (if (and (not (org-at-timestamp-p t))
16368 (org-on-heading-p))
16369 (org-todo 'up)
16370 (org-timestamp-change (prefix-numeric-value arg) 'day)))
16372 (defun org-timestamp-down-day (&optional arg)
16373 "Decrease the date in the time stamp by one day.
16374 With prefix ARG, change that many days."
16375 (interactive "p")
16376 (if (and (not (org-at-timestamp-p t))
16377 (org-on-heading-p))
16378 (org-todo 'down)
16379 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
16381 (defsubst org-pos-in-match-range (pos n)
16382 (and (match-beginning n)
16383 (<= (match-beginning n) pos)
16384 (>= (match-end n) pos)))
16386 (defun org-at-timestamp-p (&optional inactive-ok)
16387 "Determine if the cursor is in or at a timestamp."
16388 (interactive)
16389 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16390 (pos (point))
16391 (ans (or (looking-at tsr)
16392 (save-excursion
16393 (skip-chars-backward "^[<\n\r\t")
16394 (if (> (point) (point-min)) (backward-char 1))
16395 (and (looking-at tsr)
16396 (> (- (match-end 0) pos) -1))))))
16397 (and ans
16398 (boundp 'org-ts-what)
16399 (setq org-ts-what
16400 (cond
16401 ((org-pos-in-match-range pos 2) 'year)
16402 ((org-pos-in-match-range pos 3) 'month)
16403 ((org-pos-in-match-range pos 7) 'hour)
16404 ((org-pos-in-match-range pos 8) 'minute)
16405 ((or (org-pos-in-match-range pos 4)
16406 (org-pos-in-match-range pos 5)) 'day)
16407 ((and (> pos (or (match-end 8) (match-end 5)))
16408 (< pos (match-end 0)))
16409 (- pos (or (match-end 8) (match-end 5))))
16410 (t 'day))))
16411 ans))
16413 (defun org-timestamp-change (n &optional what)
16414 "Change the date in the time stamp at point.
16415 The date will be changed by N times WHAT. WHAT can be `day', `month',
16416 `year', `minute', `second'. If WHAT is not given, the cursor position
16417 in the timestamp determines what will be changed."
16418 (let ((pos (point))
16419 with-hm inactive
16420 org-ts-what
16421 extra
16422 ts time time0)
16423 (if (not (org-at-timestamp-p t))
16424 (error "Not at a timestamp"))
16425 (if (and (not what) (not (eq org-ts-what 'day))
16426 org-display-custom-times
16427 (get-text-property (point) 'display)
16428 (not (get-text-property (1- (point)) 'display)))
16429 (setq org-ts-what 'day))
16430 (setq org-ts-what (or what org-ts-what)
16431 inactive (= (char-after (match-beginning 0)) ?\[)
16432 ts (match-string 0))
16433 (replace-match "")
16434 (if (string-match
16435 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
16437 (setq extra (match-string 1 ts)))
16438 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16439 (setq with-hm t))
16440 (setq time0 (org-parse-time-string ts))
16441 (setq time
16442 (encode-time (or (car time0) 0)
16443 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16444 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16445 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16446 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16447 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16448 (nthcdr 6 time0)))
16449 (when (integerp org-ts-what)
16450 (setq extra (org-modify-ts-extra extra org-ts-what n)))
16451 (if (eq what 'calendar)
16452 (let ((cal-date (org-get-date-from-calendar)))
16453 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16454 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16455 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16456 (setcar time0 (or (car time0) 0))
16457 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16458 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16459 (setq time (apply 'encode-time time0))))
16460 (setq org-last-changed-timestamp
16461 (org-insert-time-stamp time with-hm inactive nil nil extra))
16462 (org-clock-update-time-maybe)
16463 (goto-char pos)
16464 ;; Try to recenter the calendar window, if any
16465 (if (and org-calendar-follow-timestamp-change
16466 (get-buffer-window "*Calendar*" t)
16467 (memq org-ts-what '(day month year)))
16468 (org-recenter-calendar (time-to-days time)))))
16470 ;; FIXME: does not yet work for lead times
16471 (defun org-modify-ts-extra (s pos n)
16472 "Change the different parts of the lead-time and repeat fields in timestamp."
16473 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16474 ng h m new)
16475 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16476 (cond
16477 ((or (org-pos-in-match-range pos 2)
16478 (org-pos-in-match-range pos 3))
16479 (setq m (string-to-number (match-string 3 s))
16480 h (string-to-number (match-string 2 s)))
16481 (if (org-pos-in-match-range pos 2)
16482 (setq h (+ h n))
16483 (setq m (+ m n)))
16484 (if (< m 0) (setq m (+ m 60) h (1- h)))
16485 (if (> m 59) (setq m (- m 60) h (1+ h)))
16486 (setq h (min 24 (max 0 h)))
16487 (setq ng 1 new (format "-%02d:%02d" h m)))
16488 ((org-pos-in-match-range pos 6)
16489 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16490 ((org-pos-in-match-range pos 5)
16491 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
16493 (when ng
16494 (setq s (concat
16495 (substring s 0 (match-beginning ng))
16497 (substring s (match-end ng))))))
16500 (defun org-recenter-calendar (date)
16501 "If the calendar is visible, recenter it to DATE."
16502 (let* ((win (selected-window))
16503 (cwin (get-buffer-window "*Calendar*" t))
16504 (calendar-move-hook nil))
16505 (when cwin
16506 (select-window cwin)
16507 (calendar-goto-date (if (listp date) date
16508 (calendar-gregorian-from-absolute date)))
16509 (select-window win))))
16511 (defun org-goto-calendar (&optional arg)
16512 "Go to the Emacs calendar at the current date.
16513 If there is a time stamp in the current line, go to that date.
16514 A prefix ARG can be used to force the current date."
16515 (interactive "P")
16516 (let ((tsr org-ts-regexp) diff
16517 (calendar-move-hook nil)
16518 (view-calendar-holidays-initially nil)
16519 (view-diary-entries-initially nil))
16520 (if (or (org-at-timestamp-p)
16521 (save-excursion
16522 (beginning-of-line 1)
16523 (looking-at (concat ".*" tsr))))
16524 (let ((d1 (time-to-days (current-time)))
16525 (d2 (time-to-days
16526 (org-time-string-to-time (match-string 1)))))
16527 (setq diff (- d2 d1))))
16528 (calendar)
16529 (calendar-goto-today)
16530 (if (and diff (not arg)) (calendar-forward-day diff))))
16532 (defun org-get-date-from-calendar ()
16533 "Return a list (month day year) of date at point in calendar."
16534 (with-current-buffer "*Calendar*"
16535 (save-match-data
16536 (calendar-cursor-to-date))))
16538 (defun org-date-from-calendar ()
16539 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16540 If there is already a time stamp at the cursor position, update it."
16541 (interactive)
16542 (if (org-at-timestamp-p t)
16543 (org-timestamp-change 0 'calendar)
16544 (let ((cal-date (org-get-date-from-calendar)))
16545 (org-insert-time-stamp
16546 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16548 ;; Make appt aware of appointments from the agenda
16549 (defun org-agenda-to-appt (&optional filter)
16550 "Activate appointments found in `org-agenda-files'.
16551 When prefixed, prompt for a regular expression and use it as a
16552 filter: only add entries if they match this regular expression.
16554 FILTER can be a string. In this case, use this string as a
16555 regular expression to filter results.
16557 FILTER can also be an alist, with the car of each cell being
16558 either 'headline or 'category. For example:
16560 '((headline \"IMPORTANT\")
16561 (category \"Work\"))
16563 will only add headlines containing IMPORTANT or headlines
16564 belonging to the category \"Work\"."
16565 (interactive "P")
16566 (require 'org)
16567 (if (equal filter '(4))
16568 (setq filter (read-from-minibuffer "Regexp filter: ")))
16569 (let* ((today (org-date-to-gregorian
16570 (time-to-days (current-time))))
16571 (files org-agenda-files) entries file)
16572 (while (setq file (pop files))
16573 (setq entries (append entries (org-agenda-get-day-entries
16574 file today :timestamp))))
16575 (setq entries (delq nil entries))
16576 (mapc
16577 (lambda(x)
16578 (let* ((evt (org-trim (get-text-property 1 'txt x)))
16579 (cat (get-text-property 1 'org-category x))
16580 (tod (get-text-property 1 'time-of-day x))
16581 (ok (or (and (stringp filter) (string-match filter evt))
16582 (and (not (null filter)) (listp filter)
16583 (or (string-match
16584 (cadr (assoc 'category filter)) cat)
16585 (string-match
16586 (cadr (assoc 'headline filter)) evt))))))
16587 ;; (setq evt (set-text-properties 0 (length event) nil evt))
16588 (when (and ok tod)
16589 (setq tod (number-to-string tod)
16590 tod (when (string-match
16591 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
16592 (concat (match-string 1 tod) ":"
16593 (match-string 2 tod))))
16594 (appt-add tod evt)))) entries)
16595 nil))
16597 ;;; The clock for measuring work time.
16599 (defvar org-mode-line-string "")
16600 (put 'org-mode-line-string 'risky-local-variable t)
16602 (defvar org-mode-line-timer nil)
16603 (defvar org-clock-heading "")
16604 (defvar org-clock-start-time "")
16606 (defun org-update-mode-line ()
16607 (let* ((delta (- (time-to-seconds (current-time))
16608 (time-to-seconds org-clock-start-time)))
16609 (h (floor delta 3600))
16610 (m (floor (- delta (* 3600 h)) 60)))
16611 (setq org-mode-line-string
16612 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
16613 'help-echo "Org-mode clock is running"))
16614 (force-mode-line-update)))
16616 (defvar org-clock-marker (make-marker)
16617 "Marker recording the last clock-in.")
16618 (defvar org-clock-mode-line-entry nil
16619 "Information for the modeline about the running clock.")
16621 (defun org-clock-in ()
16622 "Start the clock on the current item.
16623 If necessary, clock-out of the currently active clock."
16624 (interactive)
16625 (org-clock-out t)
16626 (let (ts)
16627 (save-excursion
16628 (org-back-to-heading t)
16629 (if (looking-at org-todo-line-regexp)
16630 (setq org-clock-heading (match-string 3))
16631 (setq org-clock-heading "???"))
16632 (setq org-clock-heading (propertize org-clock-heading 'face nil))
16633 (org-clock-find-position)
16635 (insert "\n") (backward-char 1)
16636 (indent-relative)
16637 (insert org-clock-string " ")
16638 (setq org-clock-start-time (current-time))
16639 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
16640 (move-marker org-clock-marker (point) (buffer-base-buffer))
16641 (or global-mode-string (setq global-mode-string '("")))
16642 (or (memq 'org-mode-line-string global-mode-string)
16643 (setq global-mode-string
16644 (append global-mode-string '(org-mode-line-string))))
16645 (org-update-mode-line)
16646 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
16647 (message "Clock started at %s" ts))))
16649 (defun org-clock-find-position ()
16650 "Find the location where the next clock line should be inserted."
16651 (org-back-to-heading t)
16652 (catch 'exit
16653 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
16654 (re (concat "^[ \t]*" org-clock-string))
16655 (cnt 0)
16656 first last)
16657 (goto-char beg)
16658 (when (eobp) (newline) (setq end (max (point) end)))
16659 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
16660 ;; we seem to have a CLOCK drawer, so go there.
16661 (beginning-of-line 2)
16662 (throw 'exit t))
16663 ;; Lets count the CLOCK lines
16664 (goto-char beg)
16665 (while (re-search-forward re end t)
16666 (setq first (or first (match-beginning 0))
16667 last (match-beginning 0)
16668 cnt (1+ cnt)))
16669 (when (and (integerp org-clock-into-drawer)
16670 (>= (1+ cnt) org-clock-into-drawer))
16671 ;; Wrap current entries into a new drawer
16672 (goto-char last)
16673 (beginning-of-line 2)
16674 (if (org-at-item-p) (org-end-of-item))
16675 (insert ":END:\n")
16676 (beginning-of-line 0)
16677 (org-indent-line-function)
16678 (goto-char first)
16679 (insert ":CLOCK:\n")
16680 (beginning-of-line 0)
16681 (org-indent-line-function)
16682 (org-flag-drawer t)
16683 (beginning-of-line 2)
16684 (throw 'exit nil))
16686 (goto-char beg)
16687 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
16688 (not (equal (match-string 1) org-clock-string)))
16689 ;; Planning info, skip to after it
16690 (beginning-of-line 2)
16691 (or (bolp) (newline)))
16692 (when (eq t org-clock-into-drawer)
16693 (insert ":CLOCK:\n:END:\n")
16694 (beginning-of-line -1)
16695 (org-indent-line-function)
16696 (org-flag-drawer t)
16697 (beginning-of-line 2)
16698 (org-indent-line-function)))))
16700 (defun org-clock-out (&optional fail-quietly)
16701 "Stop the currently running clock.
16702 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
16703 (interactive)
16704 (catch 'exit
16705 (if (not (marker-buffer org-clock-marker))
16706 (if fail-quietly (throw 'exit t) (error "No active clock")))
16707 (let (ts te s h m)
16708 (save-excursion
16709 (set-buffer (marker-buffer org-clock-marker))
16710 (goto-char org-clock-marker)
16711 (beginning-of-line 1)
16712 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
16713 (equal (match-string 1) org-clock-string))
16714 (setq ts (match-string 2))
16715 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
16716 (goto-char (match-end 0))
16717 (delete-region (point) (point-at-eol))
16718 (insert "--")
16719 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
16720 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
16721 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
16722 h (floor (/ s 3600))
16723 s (- s (* 3600 h))
16724 m (floor (/ s 60))
16725 s (- s (* 60 s)))
16726 (insert " => " (format "%2d:%02d" h m))
16727 (move-marker org-clock-marker nil)
16728 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
16729 (org-log-done (org-parse-local-options logging 'org-log-done))
16730 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
16731 (org-add-log-maybe 'clock-out))
16732 (when org-mode-line-timer
16733 (cancel-timer org-mode-line-timer)
16734 (setq org-mode-line-timer nil))
16735 (setq global-mode-string
16736 (delq 'org-mode-line-string global-mode-string))
16737 (force-mode-line-update)
16738 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
16740 (defun org-clock-cancel ()
16741 "Cancel the running clock be removing the start timestamp."
16742 (interactive)
16743 (if (not (marker-buffer org-clock-marker))
16744 (error "No active clock"))
16745 (save-excursion
16746 (set-buffer (marker-buffer org-clock-marker))
16747 (goto-char org-clock-marker)
16748 (delete-region (1- (point-at-bol)) (point-at-eol)))
16749 (message "Clock canceled"))
16751 (defun org-clock-goto (&optional delete-windows)
16752 "Go to the currently clocked-in entry."
16753 (interactive "P")
16754 (if (not (marker-buffer org-clock-marker))
16755 (error "No active clock"))
16756 (switch-to-buffer-other-window
16757 (marker-buffer org-clock-marker))
16758 (if delete-windows (delete-other-windows))
16759 (goto-char org-clock-marker)
16760 (org-show-entry)
16761 (org-back-to-heading)
16762 (recenter))
16764 (defvar org-clock-file-total-minutes nil
16765 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
16766 (make-variable-buffer-local 'org-clock-file-total-minutes)
16768 (defun org-clock-sum (&optional tstart tend)
16769 "Sum the times for each subtree.
16770 Puts the resulting times in minutes as a text property on each headline."
16771 (interactive)
16772 (let* ((bmp (buffer-modified-p))
16773 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
16774 org-clock-string
16775 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
16776 (lmax 30)
16777 (ltimes (make-vector lmax 0))
16778 (t1 0)
16779 (level 0)
16780 ts te dt
16781 time)
16782 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
16783 (save-excursion
16784 (goto-char (point-max))
16785 (while (re-search-backward re nil t)
16786 (cond
16787 ((match-end 2)
16788 ;; Two time stamps
16789 (setq ts (match-string 2)
16790 te (match-string 3)
16791 ts (time-to-seconds
16792 (apply 'encode-time (org-parse-time-string ts)))
16793 te (time-to-seconds
16794 (apply 'encode-time (org-parse-time-string te)))
16795 ts (if tstart (max ts tstart) ts)
16796 te (if tend (min te tend) te)
16797 dt (- te ts)
16798 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
16799 ((match-end 4)
16800 ;; A naket time
16801 (setq t1 (+ t1 (string-to-number (match-string 5))
16802 (* 60 (string-to-number (match-string 4))))))
16803 (t ;; A headline
16804 (setq level (- (match-end 1) (match-beginning 1)))
16805 (when (or (> t1 0) (> (aref ltimes level) 0))
16806 (loop for l from 0 to level do
16807 (aset ltimes l (+ (aref ltimes l) t1)))
16808 (setq t1 0 time (aref ltimes level))
16809 (loop for l from level to (1- lmax) do
16810 (aset ltimes l 0))
16811 (goto-char (match-beginning 0))
16812 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
16813 (setq org-clock-file-total-minutes (aref ltimes 0)))
16814 (set-buffer-modified-p bmp)))
16816 (defun org-clock-display (&optional total-only)
16817 "Show subtree times in the entire buffer.
16818 If TOTAL-ONLY is non-nil, only show the total time for the entire file
16819 in the echo area."
16820 (interactive)
16821 (org-remove-clock-overlays)
16822 (let (time h m p)
16823 (org-clock-sum)
16824 (unless total-only
16825 (save-excursion
16826 (goto-char (point-min))
16827 (while (or (and (equal (setq p (point)) (point-min))
16828 (get-text-property p :org-clock-minutes))
16829 (setq p (next-single-property-change
16830 (point) :org-clock-minutes)))
16831 (goto-char p)
16832 (when (setq time (get-text-property p :org-clock-minutes))
16833 (org-put-clock-overlay time (funcall outline-level))))
16834 (setq h (/ org-clock-file-total-minutes 60)
16835 m (- org-clock-file-total-minutes (* 60 h)))
16836 ;; Arrange to remove the overlays upon next change.
16837 (when org-remove-highlights-with-change
16838 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
16839 nil 'local))))
16840 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
16842 (defvar org-clock-overlays nil)
16843 (make-variable-buffer-local 'org-clock-overlays)
16845 (defun org-put-clock-overlay (time &optional level)
16846 "Put an overlays on the current line, displaying TIME.
16847 If LEVEL is given, prefix time with a corresponding number of stars.
16848 This creates a new overlay and stores it in `org-clock-overlays', so that it
16849 will be easy to remove."
16850 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
16851 (l (if level (org-get-legal-level level 0) 0))
16852 (off 0)
16853 ov tx)
16854 (move-to-column c)
16855 (unless (eolp) (skip-chars-backward "^ \t"))
16856 (skip-chars-backward " \t")
16857 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
16858 tx (concat (buffer-substring (1- (point)) (point))
16859 (make-string (+ off (max 0 (- c (current-column)))) ?.)
16860 (org-add-props (format "%s %2d:%02d%s"
16861 (make-string l ?*) h m
16862 (make-string (- 10 l) ?\ ))
16863 '(face secondary-selection))
16864 ""))
16865 (if (not (featurep 'xemacs))
16866 (org-overlay-put ov 'display tx)
16867 (org-overlay-put ov 'invisible t)
16868 (org-overlay-put ov 'end-glyph (make-glyph tx)))
16869 (push ov org-clock-overlays)))
16871 (defun org-remove-clock-overlays (&optional beg end noremove)
16872 "Remove the occur highlights from the buffer.
16873 BEG and END are ignored. If NOREMOVE is nil, remove this function
16874 from the `before-change-functions' in the current buffer."
16875 (interactive)
16876 (unless org-inhibit-highlight-removal
16877 (mapc 'org-delete-overlay org-clock-overlays)
16878 (setq org-clock-overlays nil)
16879 (unless noremove
16880 (remove-hook 'before-change-functions
16881 'org-remove-clock-overlays 'local))))
16883 (defun org-clock-out-if-current ()
16884 "Clock out if the current entry contains the running clock.
16885 This is used to stop the clock after a TODO entry is marked DONE,
16886 and is only done if the variable `org-clock-out-when-done' is not nil."
16887 (when (and org-clock-out-when-done
16888 (member state org-done-keywords)
16889 (equal (marker-buffer org-clock-marker) (current-buffer))
16890 (< (point) org-clock-marker)
16891 (> (save-excursion (outline-next-heading) (point))
16892 org-clock-marker))
16893 ;; Clock out, but don't accept a logging message for this.
16894 (let ((org-log-done (if (and (listp org-log-done)
16895 (member 'clock-out org-log-done))
16896 '(done)
16897 org-log-done)))
16898 (org-clock-out))))
16900 (add-hook 'org-after-todo-state-change-hook
16901 'org-clock-out-if-current)
16903 (defun org-check-running-clock ()
16904 "Check if the current buffer contains the running clock.
16905 If yes, offer to stop it and to save the buffer with the changes."
16906 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
16907 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
16908 (buffer-name))))
16909 (org-clock-out)
16910 (when (y-or-n-p "Save changed buffer?")
16911 (save-buffer))))
16913 (defun org-clock-report (&optional arg)
16914 "Create a table containing a report about clocked time.
16915 If the cursor is inside an existing clocktable block, then the table
16916 will be updated. If not, a new clocktable will be inserted.
16917 When called with a prefix argument, move to the first clock table in the
16918 buffer and update it."
16919 (interactive "P")
16920 (org-remove-clock-overlays)
16921 (when arg (org-find-dblock "clocktable"))
16922 (if (org-in-clocktable-p)
16923 (goto-char (org-in-clocktable-p))
16924 (org-create-dblock (list :name "clocktable"
16925 :maxlevel 2 :scope 'file)))
16926 (org-update-dblock))
16928 (defun org-in-clocktable-p ()
16929 "Check if the cursor is in a clocktable."
16930 (let ((pos (point)) start)
16931 (save-excursion
16932 (end-of-line 1)
16933 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
16934 (setq start (match-beginning 0))
16935 (re-search-forward "^#\\+END:.*" nil t)
16936 (>= (match-end 0) pos)
16937 start))))
16939 (defun org-clock-update-time-maybe ()
16940 "If this is a CLOCK line, update it and return t.
16941 Otherwise, return nil."
16942 (interactive)
16943 (save-excursion
16944 (beginning-of-line 1)
16945 (skip-chars-forward " \t")
16946 (when (looking-at org-clock-string)
16947 (let ((re (concat "[ \t]*" org-clock-string
16948 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
16949 "\\([ \t]*=>.*\\)?"))
16950 ts te h m s)
16951 (if (not (looking-at re))
16953 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
16954 (end-of-line 1)
16955 (setq ts (match-string 1)
16956 te (match-string 2))
16957 (setq s (- (time-to-seconds
16958 (apply 'encode-time (org-parse-time-string te)))
16959 (time-to-seconds
16960 (apply 'encode-time (org-parse-time-string ts))))
16961 h (floor (/ s 3600))
16962 s (- s (* 3600 h))
16963 m (floor (/ s 60))
16964 s (- s (* 60 s)))
16965 (insert " => " (format "%2d:%02d" h m))
16966 t)))))
16968 (defun org-clock-special-range (key &optional time as-strings)
16969 "Return two times bordering a special time range.
16970 Key is a symbol specifying the range and can be one of `today', `yesterday',
16971 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
16972 A week starts Monday 0:00 and ends Sunday 24:00.
16973 The range is determined relative to TIME. TIME defaults to the current time.
16974 The return value is a cons cell with two internal times like the ones
16975 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
16976 the returned times will be formatted strings."
16977 (let* ((tm (decode-time (or time (current-time))))
16978 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
16979 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
16980 (dow (nth 6 tm))
16981 s1 m1 h1 d1 month1 y1 diff ts te fm)
16982 (cond
16983 ((eq key 'today)
16984 (setq h 0 m 0 h1 24 m1 0))
16985 ((eq key 'yesterday)
16986 (setq d (1- d) h 0 m 0 h1 24 m1 0))
16987 ((eq key 'thisweek)
16988 (setq diff (if (= dow 0) 6 (1- dow))
16989 m 0 h 0 d (- d diff) d1 (+ 7 d)))
16990 ((eq key 'lastweek)
16991 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
16992 m 0 h 0 d (- d diff) d1 (+ 7 d)))
16993 ((eq key 'thismonth)
16994 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
16995 ((eq key 'lastmonth)
16996 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
16997 ((eq key 'thisyear)
16998 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
16999 ((eq key 'lastyear)
17000 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
17001 (t (error "No such time block %s" key)))
17002 (setq ts (encode-time s m h d month y)
17003 te (encode-time (or s1 s) (or m1 m) (or h1 h)
17004 (or d1 d) (or month1 month) (or y1 y)))
17005 (setq fm (cdr org-time-stamp-formats))
17006 (if as-strings
17007 (cons (format-time-string fm ts) (format-time-string fm te))
17008 (cons ts te))))
17010 (defun org-dblock-write:clocktable (params)
17011 "Write the standard clocktable."
17012 (let ((hlchars '((1 . "*") (2 . "/")))
17013 (emph nil)
17014 (ins (make-marker))
17015 (total-time nil)
17016 ipos time h m p level hlc hdl maxlevel
17017 ts te cc block beg end pos scope tbl tostring multifile)
17018 (setq scope (plist-get params :scope)
17019 tostring (plist-get params :tostring)
17020 multifile (plist-get params :multifile)
17021 maxlevel (or (plist-get params :maxlevel) 3)
17022 emph (plist-get params :emphasize)
17023 ts (plist-get params :tstart)
17024 te (plist-get params :tend)
17025 block (plist-get params :block))
17026 (when block
17027 (setq cc (org-clock-special-range block nil t)
17028 ts (car cc) te (cdr cc)))
17029 (if ts (setq ts (time-to-seconds
17030 (apply 'encode-time (org-parse-time-string ts)))))
17031 (if te (setq te (time-to-seconds
17032 (apply 'encode-time (org-parse-time-string te)))))
17033 (move-marker ins (point))
17034 (setq ipos (point))
17036 ;; Get the right scope
17037 (setq pos (point))
17038 (save-restriction
17039 (cond
17040 ((not scope))
17041 ((eq scope 'file) (widen))
17042 ((eq scope 'subtree) (org-narrow-to-subtree))
17043 ((eq scope 'tree)
17044 (while (org-up-heading-safe))
17045 (org-narrow-to-subtree))
17046 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
17047 (symbol-name scope)))
17048 (setq level (string-to-number (match-string 1 (symbol-name scope))))
17049 (catch 'exit
17050 (while (org-up-heading-safe)
17051 (looking-at outline-regexp)
17052 (if (<= (org-reduced-level (funcall outline-level)) level)
17053 (throw 'exit nil))))
17054 (org-narrow-to-subtree))
17055 ((or (listp scope) (eq scope 'agenda))
17056 (let* ((files (if (listp scope) scope (org-agenda-files)))
17057 (scope 'agenda)
17058 (p1 (copy-sequence params))
17059 file)
17060 (plist-put p1 :tostring t)
17061 (plist-put p1 :multifile t)
17062 (plist-put p1 :scope 'file)
17063 (org-prepare-agenda-buffers files)
17064 (while (setq file (pop files))
17065 (with-current-buffer (find-buffer-visiting file)
17066 (push (org-clocktable-add-file
17067 file (org-dblock-write:clocktable p1)) tbl)
17068 (setq total-time (+ (or total-time 0)
17069 org-clock-file-total-minutes)))))))
17070 (goto-char pos)
17072 (unless (eq scope 'agenda)
17073 (org-clock-sum ts te)
17074 (goto-char (point-min))
17075 (while (setq p (next-single-property-change (point) :org-clock-minutes))
17076 (goto-char p)
17077 (when (setq time (get-text-property p :org-clock-minutes))
17078 (save-excursion
17079 (beginning-of-line 1)
17080 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
17081 (setq level (org-reduced-level
17082 (- (match-end 1) (match-beginning 1))))
17083 (<= level maxlevel))
17084 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
17085 hdl (match-string 2)
17086 h (/ time 60)
17087 m (- time (* 60 h)))
17088 (if (and (not multifile) (= level 1)) (push "|-" tbl))
17089 (push (concat
17090 "| " (int-to-string level) "|" hlc hdl hlc " |"
17091 (make-string (1- level) ?|)
17092 hlc (format "%d:%02d" h m) hlc
17093 " |") tbl))))))
17094 (setq tbl (nreverse tbl))
17095 (if tostring
17096 (if tbl (mapconcat 'identity tbl "\n") nil)
17097 (goto-char ins)
17098 (insert-before-markers
17099 "Clock summary at ["
17100 (substring
17101 (format-time-string (cdr org-time-stamp-formats))
17102 1 -1)
17103 "]."
17104 (if block
17105 (format " Considered range is /%s/." block)
17107 "\n\n"
17108 (if (eq scope 'agenda) "|File" "")
17109 "|L|Headline|Time|\n")
17110 (setq total-time (or total-time org-clock-file-total-minutes)
17111 h (/ total-time 60)
17112 m (- total-time (* 60 h)))
17113 (insert-before-markers
17114 "|-\n|"
17115 (if (eq scope 'agenda) "|" "")
17116 "|"
17117 "*Total time*| "
17118 (format "*%d:%02d*" h m)
17119 "|\n|-\n")
17120 (setq tbl (delq nil tbl))
17121 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
17122 (equal (substring (car tbl) 0 2) "|-"))
17123 (pop tbl))
17124 (insert-before-markers (mapconcat
17125 'identity (delq nil tbl)
17126 (if (eq scope 'agenda) "\n|-\n" "\n")))
17127 (backward-delete-char 1)
17128 (goto-char ipos)
17129 (skip-chars-forward "^|")
17130 (org-table-align)))))
17132 (defun org-clocktable-add-file (file table)
17133 (if table
17134 (let ((lines (org-split-string table "\n"))
17135 (ff (file-name-nondirectory file)))
17136 (mapconcat 'identity
17137 (mapcar (lambda (x)
17138 (if (string-match org-table-dataline-regexp x)
17139 (concat "|" ff x)
17141 lines)
17142 "\n"))))
17144 ;; FIXME: I don't think anybody uses this, ask David
17145 (defun org-collect-clock-time-entries ()
17146 "Return an internal list with clocking information.
17147 This list has one entry for each CLOCK interval.
17148 FIXME: describe the elements."
17149 (interactive)
17150 (let ((re (concat "^[ \t]*" org-clock-string
17151 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
17152 rtn beg end next cont level title total closedp leafp
17153 clockpos titlepos h m donep)
17154 (save-excursion
17155 (org-clock-sum)
17156 (goto-char (point-min))
17157 (while (re-search-forward re nil t)
17158 (setq clockpos (match-beginning 0)
17159 beg (match-string 1) end (match-string 2)
17160 cont (match-end 0))
17161 (setq beg (apply 'encode-time (org-parse-time-string beg))
17162 end (apply 'encode-time (org-parse-time-string end)))
17163 (org-back-to-heading t)
17164 (setq donep (org-entry-is-done-p))
17165 (setq titlepos (point)
17166 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
17167 h (/ total 60) m (- total (* 60 h))
17168 total (cons h m))
17169 (looking-at "\\(\\*+\\) +\\(.*\\)")
17170 (setq level (- (match-end 1) (match-beginning 1))
17171 title (org-match-string-no-properties 2))
17172 (save-excursion (outline-next-heading) (setq next (point)))
17173 (setq closedp (re-search-forward org-closed-time-regexp next t))
17174 (goto-char next)
17175 (setq leafp (and (looking-at "^\\*+ ")
17176 (<= (- (match-end 0) (point)) level)))
17177 (push (list beg end clockpos closedp donep
17178 total title titlepos level leafp)
17179 rtn)
17180 (goto-char cont)))
17181 (nreverse rtn)))
17183 ;;;; Agenda, and Diary Integration
17185 ;;; Define the Org-agenda-mode
17187 (defvar org-agenda-mode-map (make-sparse-keymap)
17188 "Keymap for `org-agenda-mode'.")
17190 (defvar org-agenda-menu) ; defined later in this file.
17191 (defvar org-agenda-follow-mode nil)
17192 (defvar org-agenda-show-log nil)
17193 (defvar org-agenda-redo-command nil)
17194 (defvar org-agenda-mode-hook nil)
17195 (defvar org-agenda-type nil)
17196 (defvar org-agenda-force-single-file nil)
17198 (defun org-agenda-mode ()
17199 "Mode for time-sorted view on action items in Org-mode files.
17201 The following commands are available:
17203 \\{org-agenda-mode-map}"
17204 (interactive)
17205 (kill-all-local-variables)
17206 (setq org-agenda-undo-list nil
17207 org-agenda-pending-undo-list nil)
17208 (setq major-mode 'org-agenda-mode)
17209 ;; Keep global-font-lock-mode from turning on font-lock-mode
17210 (org-set-local 'font-lock-global-modes (list 'not major-mode))
17211 (setq mode-name "Org-Agenda")
17212 (use-local-map org-agenda-mode-map)
17213 (easy-menu-add org-agenda-menu)
17214 (if org-startup-truncated (setq truncate-lines t))
17215 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
17216 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
17217 ;; Make sure properties are removed when copying text
17218 (when (boundp 'buffer-substring-filters)
17219 (org-set-local 'buffer-substring-filters
17220 (cons (lambda (x)
17221 (set-text-properties 0 (length x) nil x) x)
17222 buffer-substring-filters)))
17223 (unless org-agenda-keep-modes
17224 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
17225 org-agenda-show-log nil))
17226 (easy-menu-change
17227 '("Agenda") "Agenda Files"
17228 (append
17229 (list
17230 (vector
17231 (if (get 'org-agenda-files 'org-restrict)
17232 "Restricted to single file"
17233 "Edit File List")
17234 '(org-edit-agenda-file-list)
17235 (not (get 'org-agenda-files 'org-restrict)))
17236 "--")
17237 (mapcar 'org-file-menu-entry (org-agenda-files))))
17238 (org-agenda-set-mode-name)
17239 (apply
17240 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
17241 (list 'org-agenda-mode-hook)))
17243 (substitute-key-definition 'undo 'org-agenda-undo
17244 org-agenda-mode-map global-map)
17245 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
17246 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
17247 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
17248 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
17249 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
17250 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
17251 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
17252 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
17253 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
17254 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
17255 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
17256 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
17257 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
17258 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
17259 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
17260 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
17261 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
17262 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
17263 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
17264 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
17265 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
17266 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
17267 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
17268 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
17269 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
17270 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
17271 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
17272 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
17273 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
17275 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
17276 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
17277 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
17278 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
17279 (while l (org-defkey org-agenda-mode-map
17280 (int-to-string (pop l)) 'digit-argument)))
17282 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
17283 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
17284 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
17285 (org-defkey org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
17286 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
17287 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
17288 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
17289 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
17290 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
17291 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
17292 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
17293 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
17294 (org-defkey org-agenda-mode-map "n" 'next-line)
17295 (org-defkey org-agenda-mode-map "p" 'previous-line)
17296 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
17297 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
17298 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
17299 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
17300 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
17301 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
17302 (eval-after-load "calendar"
17303 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
17304 'org-calendar-goto-agenda))
17305 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
17306 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
17307 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
17308 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
17309 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
17310 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
17311 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
17312 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
17313 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
17314 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
17315 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
17316 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17317 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
17318 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
17319 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
17320 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
17321 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
17322 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
17323 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
17324 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
17325 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
17326 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
17328 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
17329 "Local keymap for agenda entries from Org-mode.")
17331 (org-defkey org-agenda-keymap
17332 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
17333 (org-defkey org-agenda-keymap
17334 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
17335 (when org-agenda-mouse-1-follows-link
17336 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
17337 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
17338 '("Agenda"
17339 ("Agenda Files")
17340 "--"
17341 ["Show" org-agenda-show t]
17342 ["Go To (other window)" org-agenda-goto t]
17343 ["Go To (this window)" org-agenda-switch-to t]
17344 ["Follow Mode" org-agenda-follow-mode
17345 :style toggle :selected org-agenda-follow-mode :active t]
17346 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
17347 "--"
17348 ["Cycle TODO" org-agenda-todo t]
17349 ["Archive subtree" org-agenda-archive t]
17350 ["Delete subtree" org-agenda-kill t]
17351 "--"
17352 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
17353 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
17354 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
17355 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
17356 "--"
17357 ("Tags and Properties"
17358 ["Show all Tags" org-agenda-show-tags t]
17359 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
17360 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
17361 "--"
17362 ["Column View" org-columns t])
17363 ("Date/Schedule"
17364 ["Schedule" org-agenda-schedule t]
17365 ["Set Deadline" org-agenda-deadline t]
17366 "--"
17367 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
17368 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
17369 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
17370 ("Clock"
17371 ["Clock in" org-agenda-clock-in t]
17372 ["Clock out" org-agenda-clock-out t]
17373 ["Clock cancel" org-agenda-clock-cancel t]
17374 ["Goto running clock" org-clock-goto t])
17375 ("Priority"
17376 ["Set Priority" org-agenda-priority t]
17377 ["Increase Priority" org-agenda-priority-up t]
17378 ["Decrease Priority" org-agenda-priority-down t]
17379 ["Show Priority" org-agenda-show-priority t])
17380 ("Calendar/Diary"
17381 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
17382 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
17383 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
17384 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
17385 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
17386 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
17387 "--"
17388 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
17389 "--"
17390 ("View"
17391 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
17392 :style radio :selected (equal org-agenda-ndays 1)]
17393 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
17394 :style radio :selected (equal org-agenda-ndays 7)]
17395 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
17396 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
17397 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
17398 :style radio :selected (member org-agenda-ndays '(365 366))]
17399 "--"
17400 ["Show Logbook entries" org-agenda-log-mode
17401 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
17402 ["Include Diary" org-agenda-toggle-diary
17403 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
17404 ["Use Time Grid" org-agenda-toggle-time-grid
17405 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
17406 ["Write view to file" org-write-agenda t]
17407 ["Rebuild buffer" org-agenda-redo t]
17408 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
17409 "--"
17410 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
17411 "--"
17412 ["Quit" org-agenda-quit t]
17413 ["Exit and Release Buffers" org-agenda-exit t]
17416 ;;; Agenda undo
17418 (defvar org-agenda-allow-remote-undo t
17419 "Non-nil means, allow remote undo from the agenda buffer.")
17420 (defvar org-agenda-undo-list nil
17421 "List of undoable operations in the agenda since last refresh.")
17422 (defvar org-agenda-undo-has-started-in nil
17423 "Buffers that have already seen `undo-start' in the current undo sequence.")
17424 (defvar org-agenda-pending-undo-list nil
17425 "In a series of undo commands, this is the list of remaning undo items.")
17427 (defmacro org-if-unprotected (&rest body)
17428 "Execute BODY if there is no `org-protected' text property at point."
17429 (declare (debug t))
17430 `(unless (get-text-property (point) 'org-protected)
17431 ,@body))
17433 (defmacro org-with-remote-undo (_buffer &rest _body)
17434 "Execute BODY while recording undo information in two buffers."
17435 (declare (indent 1) (debug t))
17436 `(let ((_cline (org-current-line))
17437 (_cmd this-command)
17438 (_buf1 (current-buffer))
17439 (_buf2 ,_buffer)
17440 (_undo1 buffer-undo-list)
17441 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
17442 _c1 _c2)
17443 ,@_body
17444 (when org-agenda-allow-remote-undo
17445 (setq _c1 (org-verify-change-for-undo
17446 _undo1 (with-current-buffer _buf1 buffer-undo-list))
17447 _c2 (org-verify-change-for-undo
17448 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
17449 (when (or _c1 _c2)
17450 ;; make sure there are undo boundaries
17451 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
17452 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
17453 ;; remember which buffer to undo
17454 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
17455 org-agenda-undo-list)))))
17457 (defun org-agenda-undo ()
17458 "Undo a remote editing step in the agenda.
17459 This undoes changes both in the agenda buffer and in the remote buffer
17460 that have been changed along."
17461 (interactive)
17462 (or org-agenda-allow-remote-undo
17463 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
17464 (if (not (eq this-command last-command))
17465 (setq org-agenda-undo-has-started-in nil
17466 org-agenda-pending-undo-list org-agenda-undo-list))
17467 (if (not org-agenda-pending-undo-list)
17468 (error "No further undo information"))
17469 (let* ((entry (pop org-agenda-pending-undo-list))
17470 buf line cmd rembuf)
17471 (setq cmd (pop entry) line (pop entry))
17472 (setq rembuf (nth 2 entry))
17473 (org-with-remote-undo rembuf
17474 (while (bufferp (setq buf (pop entry)))
17475 (if (pop entry)
17476 (with-current-buffer buf
17477 (let ((last-undo-buffer buf)
17478 (inhibit-read-only t))
17479 (unless (memq buf org-agenda-undo-has-started-in)
17480 (push buf org-agenda-undo-has-started-in)
17481 (make-local-variable 'pending-undo-list)
17482 (undo-start))
17483 (while (and pending-undo-list
17484 (listp pending-undo-list)
17485 (not (car pending-undo-list)))
17486 (pop pending-undo-list))
17487 (undo-more 1))))))
17488 (goto-line line)
17489 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
17491 (defun org-verify-change-for-undo (l1 l2)
17492 "Verify that a real change occurred between the undo lists L1 and L2."
17493 (while (and l1 (listp l1) (null (car l1))) (pop l1))
17494 (while (and l2 (listp l2) (null (car l2))) (pop l2))
17495 (not (eq l1 l2)))
17497 ;;; Agenda dispatch
17499 (defvar org-agenda-restrict nil)
17500 (defvar org-agenda-restrict-begin (make-marker))
17501 (defvar org-agenda-restrict-end (make-marker))
17502 (defvar org-agenda-last-dispatch-buffer nil)
17504 ;;;###autoload
17505 (defun org-agenda (arg)
17506 "Dispatch agenda commands to collect entries to the agenda buffer.
17507 Prompts for a character to select a command. Any prefix arg will be passed
17508 on to the selected command. The default selections are:
17510 a Call `org-agenda-list' to display the agenda for current day or week.
17511 t Call `org-todo-list' to display the global todo list.
17512 T Call `org-todo-list' to display the global todo list, select only
17513 entries with a specific TODO keyword (the user gets a prompt).
17514 m Call `org-tags-view' to display headlines with tags matching
17515 a condition (the user is prompted for the condition).
17516 M Like `m', but select only TODO entries, no ordinary headlines.
17517 L Create a timeline for the current buffer.
17518 e Export views to associated files.
17520 More commands can be added by configuring the variable
17521 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
17522 searches can be pre-defined in this way.
17524 If the current buffer is in Org-mode and visiting a file, you can also
17525 first press `1' to indicate that the agenda should be temporarily (until the
17526 next use of \\[org-agenda]) restricted to the current file."
17527 (interactive "P")
17528 (catch 'exit
17529 (let* ((buf (current-buffer))
17530 (bfn (buffer-file-name (buffer-base-buffer)))
17531 (restrict-ok (and bfn (org-mode-p)))
17532 (custom org-agenda-custom-commands)
17533 c entry key type match lprops)
17534 ;; Turn off restriction
17535 (put 'org-agenda-files 'org-restrict nil)
17536 (setq org-agenda-restrict nil)
17537 (move-marker org-agenda-restrict-begin nil)
17538 (move-marker org-agenda-restrict-end nil)
17539 ;; Delete old local properties
17540 (put 'org-agenda-redo-command 'org-lprops nil)
17541 ;; Remember where this call originated
17542 (setq org-agenda-last-dispatch-buffer (current-buffer))
17543 (save-window-excursion
17544 (delete-other-windows)
17545 (org-switch-to-buffer-other-window " *Agenda Commands*")
17546 (erase-buffer)
17547 (insert (eval-when-compile
17548 (let ((header
17549 "Press key for an agenda command:
17550 -------------------------------- C Configure custom agenda commands
17551 a Agenda for current week or day e Export agenda views
17552 t List of all TODO entries T Entries with special TODO kwd
17553 m Match a TAGS query M Like m, but only TODO entries
17554 L Timeline for current buffer # List stuck projects (!=configure)
17555 / Multi-occur
17557 (start 0))
17558 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
17559 (setq start (match-end 0))
17560 (add-text-properties (match-beginning 2) (match-end 2)
17561 '(face bold) header))
17562 header)))
17563 (while (setq entry (pop custom))
17564 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
17565 (insert (format "\n%-4s%-14s: %s"
17566 (org-add-props (copy-sequence key)
17567 '(face bold))
17568 (cond
17569 ((stringp type) type)
17570 ((eq type 'agenda) "Agenda for current week or day")
17571 ((eq type 'alltodo) "List of all TODO entries")
17572 ((eq type 'stuck) "List of stuck projects")
17573 ((eq type 'todo) "TODO keyword")
17574 ((eq type 'tags) "Tags query")
17575 ((eq type 'tags-todo) "Tags (TODO)")
17576 ((eq type 'tags-tree) "Tags tree")
17577 ((eq type 'todo-tree) "TODO kwd tree")
17578 ((eq type 'occur-tree) "Occur tree")
17579 ((functionp type) (symbol-name type))
17580 (t "???"))
17581 (if (stringp match)
17582 (org-add-props match nil 'face 'org-warning)
17583 (format "set of %d commands" (length match))))))
17584 (if restrict-ok
17585 (insert "\n"
17586 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
17587 (goto-char (point-min))
17588 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
17589 (message "Press key for agenda command%s"
17590 (if restrict-ok ", or [1] or [0] to restrict" ""))
17591 (setq c (read-char-exclusive))
17592 (message "")
17593 (when (memq c '(?L ?1 ?0))
17594 (if restrict-ok
17595 (put 'org-agenda-files 'org-restrict (list bfn))
17596 (error "Cannot restrict agenda to current buffer"))
17597 (with-current-buffer " *Agenda Commands*"
17598 (goto-char (point-max))
17599 (delete-region (point-at-bol) (point))
17600 (goto-char (point-min)))
17601 (when (eq c ?0)
17602 (setq org-agenda-restrict t)
17603 (with-current-buffer buf
17604 (if (org-region-active-p)
17605 (progn
17606 (move-marker org-agenda-restrict-begin (region-beginning))
17607 (move-marker org-agenda-restrict-end (region-end)))
17608 (save-excursion
17609 (org-back-to-heading t)
17610 (move-marker org-agenda-restrict-begin (point))
17611 (move-marker org-agenda-restrict-end
17612 (progn (org-end-of-subtree t)))))))
17613 (unless (eq c ?L)
17614 (message "Press key for agenda command%s"
17615 (if restrict-ok " (restricted to current file)" ""))
17616 (setq c (read-char-exclusive)))
17617 (message "")))
17618 (require 'calendar) ; FIXME: can we avoid this for some commands?
17619 ;; For example the todo list should not need it (but does...)
17620 (cond
17621 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
17622 (if (symbolp (nth 1 entry))
17623 (progn
17624 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
17625 lprops (nth 3 entry))
17626 (put 'org-agenda-redo-command 'org-lprops lprops)
17627 (cond
17628 ((eq type 'agenda)
17629 (org-let lprops '(org-agenda-list current-prefix-arg)))
17630 ((eq type 'alltodo)
17631 (org-let lprops '(org-todo-list current-prefix-arg)))
17632 ((eq type 'stuck)
17633 (org-let lprops '(org-agenda-list-stuck-projects
17634 current-prefix-arg)))
17635 ((eq type 'tags)
17636 (org-let lprops '(org-tags-view current-prefix-arg match)))
17637 ((eq type 'tags-todo)
17638 (org-let lprops '(org-tags-view '(4) match)))
17639 ((eq type 'todo)
17640 (org-let lprops '(org-todo-list match)))
17641 ((eq type 'tags-tree)
17642 (org-check-for-org-mode)
17643 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
17644 ((eq type 'todo-tree)
17645 (org-check-for-org-mode)
17646 (org-let lprops
17647 '(org-occur (concat "^" outline-regexp "[ \t]*"
17648 (regexp-quote match) "\\>"))))
17649 ((eq type 'occur-tree)
17650 (org-check-for-org-mode)
17651 (org-let lprops '(org-occur match)))
17652 ((fboundp type)
17653 (org-let lprops '(funcall type match)))
17654 (t (error "Invalid custom agenda command type %s" type))))
17655 (org-run-agenda-series (nth 1 entry) (cddr entry))))
17656 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
17657 ((equal c ?a) (call-interactively 'org-agenda-list))
17658 ((equal c ?t) (call-interactively 'org-todo-list))
17659 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
17660 ((equal c ?m) (call-interactively 'org-tags-view))
17661 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
17662 ((equal c ?e) (call-interactively 'org-store-agenda-views))
17663 ((equal c ?L)
17664 (unless restrict-ok
17665 (error "This is not an Org-mode file"))
17666 (org-call-with-arg 'org-timeline arg))
17667 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
17668 ((equal c ?/) (call-interactively 'org-occur-in-agenda-files))
17669 ((equal c ?!) (customize-variable 'org-stuck-projects))
17670 (t (error "Invalid key"))))))
17672 (defun org-run-agenda-series (name series)
17673 (org-prepare-agenda name)
17674 (let* ((org-agenda-multi t)
17675 (redo (list 'org-run-agenda-series name (list 'quote series)))
17676 (cmds (car series))
17677 (gprops (nth 1 series))
17678 match ;; The byte compiler incorrectly complains about this. Keep it!
17679 cmd type lprops)
17680 (while (setq cmd (pop cmds))
17681 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
17682 (cond
17683 ((eq type 'agenda)
17684 (org-let2 gprops lprops
17685 '(call-interactively 'org-agenda-list)))
17686 ((eq type 'alltodo)
17687 (org-let2 gprops lprops
17688 '(call-interactively 'org-todo-list)))
17689 ((eq type 'stuck)
17690 (org-let2 gprops lprops
17691 '(call-interactively 'org-agenda-list-stuck-projects)))
17692 ((eq type 'tags)
17693 (org-let2 gprops lprops
17694 '(org-tags-view current-prefix-arg match)))
17695 ((eq type 'tags-todo)
17696 (org-let2 gprops lprops
17697 '(org-tags-view '(4) match)))
17698 ((eq type 'todo)
17699 (org-let2 gprops lprops
17700 '(org-todo-list match)))
17701 ((fboundp type)
17702 (org-let2 gprops lprops
17703 '(funcall type match)))
17704 (t (error "Invalid type in command series"))))
17705 (widen)
17706 (setq org-agenda-redo-command redo)
17707 (goto-char (point-min)))
17708 (org-finalize-agenda))
17710 ;;;###autoload
17711 (defmacro org-batch-agenda (cmd-key &rest parameters)
17712 "Run an agenda command in batch mode and send the result to STDOUT.
17713 If CMD-KEY is a string of length 1, it is used as a key in
17714 `org-agenda-custom-commands' and triggers this command. If it is a
17715 longer string is is used as a tags/todo match string.
17716 Paramters are alternating variable names and values that will be bound
17717 before running the agenda command."
17718 (let (pars)
17719 (while parameters
17720 (push (list (pop parameters) (if parameters (pop parameters))) pars))
17721 (if (> (length cmd-key) 1)
17722 (eval (list 'let (nreverse pars)
17723 (list 'org-tags-view nil cmd-key)))
17724 (flet ((read-char-exclusive () (string-to-char cmd-key)))
17725 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
17726 (set-buffer org-agenda-buffer-name)
17727 (princ (org-encode-for-stdout (buffer-string)))))
17729 (defun org-encode-for-stdout (string)
17730 (if (fboundp 'encode-coding-string)
17731 (encode-coding-string string buffer-file-coding-system)
17732 string))
17734 (defvar org-agenda-info nil)
17736 ;;;###autoload
17737 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
17738 "Run an agenda command in batch mode and send the result to STDOUT.
17739 If CMD-KEY is a string of length 1, it is used as a key in
17740 `org-agenda-custom-commands' and triggers this command. If it is a
17741 longer string is is used as a tags/todo match string.
17742 Paramters are alternating variable names and values that will be bound
17743 before running the agenda command.
17745 The output gives a line for each selected agenda item. Each
17746 item is a list of comma-separated values, like this:
17748 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
17750 category The category of the item
17751 head The headline, without TODO kwd, TAGS and PRIORITY
17752 type The type of the agenda entry, can be
17753 todo selected in TODO match
17754 tagsmatch selected in tags match
17755 diary imported from diary
17756 deadline a deadline on given date
17757 scheduled scheduled on given date
17758 timestamp entry has timestamp on given date
17759 closed entry was closed on given date
17760 upcoming-deadline warning about deadline
17761 past-scheduled forwarded scheduled item
17762 block entry has date block including g. date
17763 todo The todo keyword, if any
17764 tags All tags including inherited ones, separated by colons
17765 date The relevant date, like 2007-2-14
17766 time The time, like 15:00-16:50
17767 extra Sting with extra planning info
17768 priority-l The priority letter if any was given
17769 priority-n The computed numerical priority
17770 agenda-day The day in the agenda where this is listed"
17772 (let (pars)
17773 (while parameters
17774 (push (list (pop parameters) (if parameters (pop parameters))) pars))
17775 (push (list 'org-agenda-remove-tags t) pars)
17776 (if (> (length cmd-key) 1)
17777 (eval (list 'let (nreverse pars)
17778 (list 'org-tags-view nil cmd-key)))
17779 (flet ((read-char-exclusive () (string-to-char cmd-key)))
17780 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
17781 (set-buffer org-agenda-buffer-name)
17782 (let* ((lines (org-split-string (buffer-string) "\n"))
17783 line)
17784 (while (setq line (pop lines))
17785 (catch 'next
17786 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
17787 (setq org-agenda-info
17788 (org-fix-agenda-info (text-properties-at 0 line)))
17789 (princ
17790 (org-encode-for-stdout
17791 (mapconcat 'org-agenda-export-csv-mapper
17792 '(org-category txt type todo tags date time-of-day extra
17793 priority-letter priority agenda-day)
17794 ",")))
17795 (princ "\n"))))))
17797 (defun org-fix-agenda-info (props)
17798 "Make sure all properties on an agenda item have a canonical form,
17799 so the the export commands caneasily use it."
17800 (let (tmp re)
17801 (when (setq tmp (plist-get props 'tags))
17802 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
17803 (when (setq tmp (plist-get props 'date))
17804 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
17805 (let ((calendar-date-display-form '(year "-" month "-" day)))
17806 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
17808 (setq tmp (calendar-date-string tmp)))
17809 (setq props (plist-put props 'date tmp)))
17810 (when (setq tmp (plist-get props 'day))
17811 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
17812 (let ((calendar-date-display-form '(year "-" month "-" day)))
17813 (setq tmp (calendar-date-string tmp)))
17814 (setq props (plist-put props 'day tmp))
17815 (setq props (plist-put props 'agenda-day tmp)))
17816 (when (setq tmp (plist-get props 'txt))
17817 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
17818 (plist-put props 'priority-letter (match-string 1 tmp))
17819 (setq tmp (replace-match "" t t tmp)))
17820 (when (and (setq re (plist-get props 'org-todo-regexp))
17821 (setq re (concat "\\`\\.*" re " ?"))
17822 (string-match re tmp))
17823 (plist-put props 'todo (match-string 1 tmp))
17824 (setq tmp (replace-match "" t t tmp)))
17825 (plist-put props 'txt tmp)))
17826 props)
17828 (defun org-agenda-export-csv-mapper (prop)
17829 (let ((res (plist-get org-agenda-info prop)))
17830 (setq res
17831 (cond
17832 ((not res) "")
17833 ((stringp res) res)
17834 (t (prin1-to-string res))))
17835 (while (string-match "," res)
17836 (setq res (replace-match ";" t t res)))
17837 (org-trim res)))
17840 ;;;###autoload
17841 (defun org-store-agenda-views (&rest parameters)
17842 (interactive)
17843 (eval (list 'org-batch-store-agenda-views)))
17845 ;; FIXME, why is this a macro?????
17846 ;;;###autoload
17847 (defmacro org-batch-store-agenda-views (&rest parameters)
17848 "Run all custom agenda commands that have a file argument."
17849 (let ((cmds org-agenda-custom-commands)
17850 (pop-up-frames nil)
17851 (dir default-directory)
17852 pars cmd thiscmdkey files opts)
17853 (while parameters
17854 (push (list (pop parameters) (if parameters (pop parameters))) pars))
17855 (setq pars (reverse pars))
17856 (save-window-excursion
17857 (while cmds
17858 (setq cmd (pop cmds)
17859 thiscmdkey (car cmd)
17860 opts (nth 3 cmd)
17861 files (nth 4 cmd))
17862 (if (stringp files) (setq files (list files)))
17863 (when files
17864 (flet ((read-char-exclusive () (string-to-char thiscmdkey)))
17865 (eval (list 'let (append org-agenda-exporter-settings opts pars)
17866 '(org-agenda nil))))
17867 (set-buffer org-agenda-buffer-name)
17868 (while files
17869 (eval (list 'let (append org-agenda-exporter-settings opts pars)
17870 (list 'org-write-agenda
17871 (expand-file-name (pop files) dir) t))))
17872 (and (get-buffer org-agenda-buffer-name)
17873 (kill-buffer org-agenda-buffer-name)))))))
17875 (defun org-write-agenda (file &optional nosettings)
17876 "Write the current buffer (an agenda view) as a file.
17877 Depending on the extension of the file name, plain text (.txt),
17878 HTML (.html or .htm) or Postscript (.ps) is produced.
17879 If NOSETTINGS is given, do not scope the settings of
17880 `org-agenda-exporter-settings' into the export commands. This is used when
17881 the settings have already been scoped and we do not wish to overrule other,
17882 higher priority settings."
17883 (interactive "FWrite agenda to file: ")
17884 (if (not (file-writable-p file))
17885 (error "Cannot write agenda to file %s" file))
17886 (cond
17887 ((string-match "\\.html?\\'" file) (require 'htmlize))
17888 ((string-match "\\.ps\\'" file) (require 'ps-print)))
17889 (org-let (if nosettings nil org-agenda-exporter-settings)
17890 '(save-excursion
17891 (save-window-excursion
17892 (cond
17893 ((string-match "\\.html?\\'" file)
17894 (set-buffer (htmlize-buffer (current-buffer)))
17896 (when (and org-agenda-export-html-style
17897 (string-match "<style>" org-agenda-export-html-style))
17898 ;; replace <style> section with org-agenda-export-html-style
17899 (goto-char (point-min))
17900 (kill-region (- (search-forward "<style") 6)
17901 (search-forward "</style>"))
17902 (insert org-agenda-export-html-style))
17903 (write-file file)
17904 (kill-buffer (current-buffer))
17905 (message "HTML written to %s" file))
17906 ((string-match "\\.ps\\'" file)
17907 (ps-print-buffer-with-faces file)
17908 (message "Postscript written to %s" file))
17910 (let ((bs (buffer-string)))
17911 (find-file file)
17912 (insert bs)
17913 (save-buffer 0)
17914 (kill-buffer (current-buffer))
17915 (message "Plain text written to %s" file))))))
17916 (set-buffer org-agenda-buffer-name)))
17918 (defmacro org-no-read-only (&rest body)
17919 "Inhibit read-only for BODY."
17920 `(let ((inhibit-read-only t)) ,@body))
17922 (defun org-check-for-org-mode ()
17923 "Make sure current buffer is in org-mode. Error if not."
17924 (or (org-mode-p)
17925 (error "Cannot execute org-mode agenda command on buffer in %s."
17926 major-mode)))
17928 (defun org-fit-agenda-window ()
17929 "Fit the window to the buffer size."
17930 (and (memq org-agenda-window-setup '(reorganize-frame))
17931 (fboundp 'fit-window-to-buffer)
17932 (fit-window-to-buffer)))
17934 ;;; Agenda file list
17936 (defun org-agenda-files (&optional unrestricted)
17937 "Get the list of agenda files.
17938 Optional UNRESTRICTED means return the full list even if a restriction
17939 is currently in place."
17940 (let ((files
17941 (cond
17942 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17943 ((stringp org-agenda-files) (org-read-agenda-file-list))
17944 ((listp org-agenda-files) org-agenda-files)
17945 (t (error "Invalid value of `org-agenda-files'")))))
17946 (if org-agenda-skip-unavailable-files
17947 (delq nil
17948 (mapcar (function
17949 (lambda (file)
17950 (and (file-readable-p file) file)))
17951 files))
17952 files))) ; `org-check-agenda-file' will remove them from the list
17954 (defun org-edit-agenda-file-list ()
17955 "Edit the list of agenda files.
17956 Depending on setup, this either uses customize to edit the variable
17957 `org-agenda-files', or it visits the file that is holding the list. In the
17958 latter case, the buffer is set up in a way that saving it automatically kills
17959 the buffer and restores the previous window configuration."
17960 (interactive)
17961 (if (stringp org-agenda-files)
17962 (let ((cw (current-window-configuration)))
17963 (find-file org-agenda-files)
17964 (org-set-local 'org-window-configuration cw)
17965 (org-add-hook 'after-save-hook
17966 (lambda ()
17967 (set-window-configuration
17968 (prog1 org-window-configuration
17969 (kill-buffer (current-buffer))))
17970 (org-install-agenda-files-menu)
17971 (message "New agenda file list installed"))
17972 nil 'local)
17973 (message (substitute-command-keys
17974 "Edit list and finish with \\[save-buffer]")))
17975 (customize-variable 'org-agenda-files)))
17977 (defun org-store-new-agenda-file-list (list)
17978 "Set new value for the agenda file list and save it correcly."
17979 (if (stringp org-agenda-files)
17980 (let ((f org-agenda-files) b)
17981 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
17982 (with-temp-file f
17983 (insert (mapconcat 'identity list "\n") "\n")))
17984 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
17985 (setq org-agenda-files list)
17986 (customize-save-variable 'org-agenda-files org-agenda-files))))
17988 (defun org-read-agenda-file-list ()
17989 "Read the list of agenda files from a file."
17990 (when (stringp org-agenda-files)
17991 (with-temp-buffer
17992 (insert-file-contents org-agenda-files)
17993 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
17996 ;;;###autoload
17997 (defun org-cycle-agenda-files ()
17998 "Cycle through the files in `org-agenda-files'.
17999 If the current buffer visits an agenda file, find the next one in the list.
18000 If the current buffer does not, find the first agenda file."
18001 (interactive)
18002 (let* ((fs (org-agenda-files t))
18003 (files (append fs (list (car fs))))
18004 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18005 file)
18006 (unless files (error "No agenda files"))
18007 (catch 'exit
18008 (while (setq file (pop files))
18009 (if (equal (file-truename file) tcf)
18010 (when (car files)
18011 (find-file (car files))
18012 (throw 'exit t))))
18013 (find-file (car fs)))
18014 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
18016 (defun org-agenda-file-to-front (&optional to-end)
18017 "Move/add the current file to the top of the agenda file list.
18018 If the file is not present in the list, it is added to the front. If it is
18019 present, it is moved there. With optional argument TO-END, add/move to the
18020 end of the list."
18021 (interactive "P")
18022 (let ((org-agenda-skip-unavailable-files nil)
18023 (file-alist (mapcar (lambda (x)
18024 (cons (file-truename x) x))
18025 (org-agenda-files t)))
18026 (ctf (file-truename buffer-file-name))
18027 x had)
18028 (setq x (assoc ctf file-alist) had x)
18030 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18031 (if to-end
18032 (setq file-alist (append (delq x file-alist) (list x)))
18033 (setq file-alist (cons x (delq x file-alist))))
18034 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18035 (org-install-agenda-files-menu)
18036 (message "File %s to %s of agenda file list"
18037 (if had "moved" "added") (if to-end "end" "front"))))
18039 (defun org-remove-file (&optional file)
18040 "Remove current file from the list of files in variable `org-agenda-files'.
18041 These are the files which are being checked for agenda entries.
18042 Optional argument FILE means, use this file instead of the current."
18043 (interactive)
18044 (let* ((org-agenda-skip-unavailable-files nil)
18045 (file (or file buffer-file-name))
18046 (true-file (file-truename file))
18047 (afile (abbreviate-file-name file))
18048 (files (delq nil (mapcar
18049 (lambda (x)
18050 (if (equal true-file
18051 (file-truename x))
18052 nil x))
18053 (org-agenda-files t)))))
18054 (if (not (= (length files) (length (org-agenda-files t))))
18055 (progn
18056 (org-store-new-agenda-file-list files)
18057 (org-install-agenda-files-menu)
18058 (message "Removed file: %s" afile))
18059 (message "File was not in list: %s" afile))))
18061 (defun org-file-menu-entry (file)
18062 (vector file (list 'find-file file) t))
18064 (defun org-check-agenda-file (file)
18065 "Make sure FILE exists. If not, ask user what to do."
18066 (when (not (file-exists-p file))
18067 (message "non-existent file %s. [R]emove from list or [A]bort?"
18068 (abbreviate-file-name file))
18069 (let ((r (downcase (read-char-exclusive))))
18070 (cond
18071 ((equal r ?r)
18072 (org-remove-file file)
18073 (throw 'nextfile t))
18074 (t (error "Abort"))))))
18076 ;;; Agenda prepare and finalize
18078 (defvar org-agenda-multi nil) ; dynammically scoped
18079 (defvar org-agenda-buffer-name "*Org Agenda*")
18080 (defvar org-pre-agenda-window-conf nil)
18081 (defvar org-agenda-name nil)
18082 (defun org-prepare-agenda (&optional name)
18083 (setq org-todo-keywords-for-agenda nil)
18084 (setq org-done-keywords-for-agenda nil)
18085 (if org-agenda-multi
18086 (progn
18087 (setq buffer-read-only nil)
18088 (goto-char (point-max))
18089 (unless (or (bobp) org-agenda-compact-blocks)
18090 (insert "\n" (make-string (window-width) ?=) "\n"))
18091 (narrow-to-region (point) (point-max)))
18092 (org-agenda-maybe-reset-markers 'force)
18093 (org-prepare-agenda-buffers (org-agenda-files))
18094 (setq org-todo-keywords-for-agenda
18095 (org-uniquify org-todo-keywords-for-agenda))
18096 (setq org-done-keywords-for-agenda
18097 (org-uniquify org-done-keywords-for-agenda))
18098 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
18099 (awin (get-buffer-window abuf)))
18100 (cond
18101 ((equal (current-buffer) abuf) nil)
18102 (awin (select-window awin))
18103 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
18104 ((equal org-agenda-window-setup 'current-window)
18105 (switch-to-buffer abuf))
18106 ((equal org-agenda-window-setup 'other-window)
18107 (org-switch-to-buffer-other-window abuf))
18108 ((equal org-agenda-window-setup 'other-frame)
18109 (switch-to-buffer-other-frame abuf))
18110 ((equal org-agenda-window-setup 'reorganize-frame)
18111 (delete-other-windows)
18112 (org-switch-to-buffer-other-window abuf))))
18113 (setq buffer-read-only nil)
18114 (erase-buffer)
18115 (org-agenda-mode)
18116 (and name (not org-agenda-name)
18117 (org-set-local 'org-agenda-name name)))
18118 (setq buffer-read-only nil))
18120 (defun org-finalize-agenda ()
18121 "Finishing touch for the agenda buffer, called just before displaying it."
18122 (unless org-agenda-multi
18123 (save-excursion
18124 (let ((inhibit-read-only t))
18125 (goto-char (point-min))
18126 (while (org-activate-bracket-links (point-max))
18127 (add-text-properties (match-beginning 0) (match-end 0)
18128 '(face org-link)))
18129 (org-agenda-align-tags)
18130 (unless org-agenda-with-colors
18131 (remove-text-properties (point-min) (point-max) '(face nil))))
18132 (if (and (boundp 'org-overriding-columns-format)
18133 org-overriding-columns-format)
18134 (org-set-local 'org-overriding-columns-format
18135 org-overriding-columns-format))
18136 (if (and (boundp 'org-agenda-view-columns-initially)
18137 org-agenda-view-columns-initially)
18138 (org-agenda-columns))
18139 (when org-agenda-fontify-priorities
18140 (org-fontify-priorities))
18141 (run-hooks 'org-finalize-agenda-hook))))
18143 (defun org-fontify-priorities ()
18144 "Make highest priority lines bold, and lowest italic."
18145 (interactive)
18146 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
18147 (org-delete-overlay o)))
18148 (overlays-in (point-min) (point-max)))
18149 (save-excursion
18150 (let ((ovs (org-overlays-in (point-min) (point-max)))
18151 (inhibit-read-only t)
18152 b e p ov h l)
18153 (goto-char (point-min))
18154 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
18155 (setq h (or (get-char-property (point) 'org-highest-priority)
18156 org-highest-priority)
18157 l (or (get-char-property (point) 'org-lowest-priority)
18158 org-lowest-priority)
18159 p (string-to-char (match-string 1))
18160 b (match-beginning 0) e (line-end-position)
18161 ov (org-make-overlay b e))
18162 (org-overlay-put ov 'face (cond ((equal p l) 'italic)
18163 ((equal p h) 'bold)))
18164 (org-overlay-put ov 'org-type 'org-priority)))))
18166 (defun org-prepare-agenda-buffers (files)
18167 "Create buffers for all agenda files, protect archived trees and comments."
18168 (interactive)
18169 (let ((pa '(:org-archived t))
18170 (pc '(:org-comment t))
18171 (pall '(:org-archived t :org-comment t))
18172 (inhibit-read-only t)
18173 (rea (concat ":" org-archive-tag ":"))
18174 bmp file re)
18175 (save-excursion
18176 (save-restriction
18177 (while (setq file (pop files))
18178 (org-check-agenda-file file)
18179 (set-buffer (org-get-agenda-file-buffer file))
18180 (widen)
18181 (setq bmp (buffer-modified-p))
18182 (org-refresh-category-properties)
18183 (setq org-todo-keywords-for-agenda
18184 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18185 (setq org-done-keywords-for-agenda
18186 (append org-done-keywords-for-agenda org-done-keywords))
18187 (save-excursion
18188 (remove-text-properties (point-min) (point-max) pall)
18189 (when org-agenda-skip-archived-trees
18190 (goto-char (point-min))
18191 (while (re-search-forward rea nil t)
18192 (if (org-on-heading-p t)
18193 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18194 (goto-char (point-min))
18195 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
18196 (while (re-search-forward re nil t)
18197 (add-text-properties
18198 (match-beginning 0) (org-end-of-subtree t) pc)))
18199 (set-buffer-modified-p bmp))))))
18201 (defvar org-agenda-skip-function nil
18202 "Function to be called at each match during agenda construction.
18203 If this function returns nil, the current match should not be skipped.
18204 Otherwise, the function must return a position from where the search
18205 should be continued.
18206 This may also be a Lisp form, it will be evaluated.
18207 Never set this variable using `setq' or so, because then it will apply
18208 to all future agenda commands. Instead, bind it with `let' to scope
18209 it dynamically into the agenda-constructing command. A good way to set
18210 it is through options in org-agenda-custom-commands.")
18212 (defun org-agenda-skip ()
18213 "Throw to `:skip' in places that should be skipped.
18214 Also moves point to the end of the skipped region, so that search can
18215 continue from there."
18216 (let ((p (point-at-bol)) to fp)
18217 (and org-agenda-skip-archived-trees
18218 (get-text-property p :org-archived)
18219 (org-end-of-subtree t)
18220 (throw :skip t))
18221 (and (get-text-property p :org-comment)
18222 (org-end-of-subtree t)
18223 (throw :skip t))
18224 (if (equal (char-after p) ?#) (throw :skip t))
18225 (when (and (or (setq fp (functionp org-agenda-skip-function))
18226 (consp org-agenda-skip-function))
18227 (setq to (save-excursion
18228 (save-match-data
18229 (if fp
18230 (funcall org-agenda-skip-function)
18231 (eval org-agenda-skip-function))))))
18232 (goto-char to)
18233 (throw :skip t))))
18235 (defvar org-agenda-markers nil
18236 "List of all currently active markers created by `org-agenda'.")
18237 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
18238 "Creation time of the last agenda marker.")
18240 (defun org-agenda-new-marker (&optional pos)
18241 "Return a new agenda marker.
18242 Org-mode keeps a list of these markers and resets them when they are
18243 no longer in use."
18244 (let ((m (copy-marker (or pos (point)))))
18245 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
18246 (push m org-agenda-markers)
18249 (defun org-agenda-maybe-reset-markers (&optional force)
18250 "Reset markers created by `org-agenda'. But only if they are old enough."
18251 (if (or (and force (not org-agenda-multi))
18252 (> (- (time-to-seconds (current-time))
18253 org-agenda-last-marker-time)
18255 (while org-agenda-markers
18256 (move-marker (pop org-agenda-markers) nil))))
18258 (defvar org-agenda-new-buffers nil
18259 "Buffers created to visit agenda files.")
18261 (defun org-get-agenda-file-buffer (file)
18262 "Get a buffer visiting FILE. If the buffer needs to be created, add
18263 it to the list of buffers which might be released later."
18264 (let ((buf (org-find-base-buffer-visiting file)))
18265 (if buf
18266 buf ; just return it
18267 ;; Make a new buffer and remember it
18268 (setq buf (find-file-noselect file))
18269 (if buf (push buf org-agenda-new-buffers))
18270 buf)))
18272 (defun org-release-buffers (blist)
18273 "Release all buffers in list, asking the user for confirmation when needed.
18274 When a buffer is unmodified, it is just killed. When modified, it is saved
18275 \(if the user agrees) and then killed."
18276 (let (buf file)
18277 (while (setq buf (pop blist))
18278 (setq file (buffer-file-name buf))
18279 (when (and (buffer-modified-p buf)
18280 file
18281 (y-or-n-p (format "Save file %s? " file)))
18282 (with-current-buffer buf (save-buffer)))
18283 (kill-buffer buf))))
18285 (defun org-get-category (&optional pos)
18286 "Get the category applying to position POS."
18287 (get-text-property (or pos (point)) 'org-category))
18289 ;;; Agenda timeline
18291 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
18293 (defun org-timeline (&optional include-all)
18294 "Show a time-sorted view of the entries in the current org file.
18295 Only entries with a time stamp of today or later will be listed. With
18296 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
18297 under the current date.
18298 If the buffer contains an active region, only check the region for
18299 dates."
18300 (interactive "P")
18301 (require 'calendar)
18302 (org-compile-prefix-format 'timeline)
18303 (org-set-sorting-strategy 'timeline)
18304 (let* ((dopast t)
18305 (dotodo include-all)
18306 (doclosed org-agenda-show-log)
18307 (entry buffer-file-name)
18308 (date (calendar-current-date))
18309 (beg (if (org-region-active-p) (region-beginning) (point-min)))
18310 (end (if (org-region-active-p) (region-end) (point-max)))
18311 (day-numbers (org-get-all-dates beg end 'no-ranges
18312 t doclosed ; always include today
18313 org-timeline-show-empty-dates))
18314 (org-deadline-warning-days 0)
18315 (org-agenda-only-exact-dates t)
18316 (today (time-to-days (current-time)))
18317 (past t)
18318 args
18319 s e rtn d emptyp)
18320 (setq org-agenda-redo-command
18321 (list 'progn
18322 (list 'org-switch-to-buffer-other-window (current-buffer))
18323 (list 'org-timeline (list 'quote include-all))))
18324 (if (not dopast)
18325 ;; Remove past dates from the list of dates.
18326 (setq day-numbers (delq nil (mapcar (lambda(x)
18327 (if (>= x today) x nil))
18328 day-numbers))))
18329 (org-prepare-agenda (concat "Timeline "
18330 (file-name-nondirectory buffer-file-name)))
18331 (if doclosed (push :closed args))
18332 (push :timestamp args)
18333 (push :deadline args)
18334 (push :scheduled args)
18335 (push :sexp args)
18336 (if dotodo (push :todo args))
18337 (while (setq d (pop day-numbers))
18338 (if (and (listp d) (eq (car d) :omitted))
18339 (progn
18340 (setq s (point))
18341 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
18342 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
18343 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
18344 (if (and (>= d today)
18345 dopast
18346 past)
18347 (progn
18348 (setq past nil)
18349 (insert (make-string 79 ?-) "\n")))
18350 (setq date (calendar-gregorian-from-absolute d))
18351 (setq s (point))
18352 (setq rtn (and (not emptyp)
18353 (apply 'org-agenda-get-day-entries entry
18354 date args)))
18355 (if (or rtn (equal d today) org-timeline-show-empty-dates)
18356 (progn
18357 (insert
18358 (if (stringp org-agenda-format-date)
18359 (format-time-string org-agenda-format-date
18360 (org-time-from-absolute date))
18361 (funcall org-agenda-format-date date))
18362 "\n")
18363 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
18364 (put-text-property s (1- (point)) 'org-date-line t)
18365 (if (equal d today)
18366 (put-text-property s (1- (point)) 'org-today t))
18367 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
18368 (put-text-property s (1- (point)) 'day d)))))
18369 (goto-char (point-min))
18370 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
18371 (point-min)))
18372 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
18373 (org-finalize-agenda)
18374 (setq buffer-read-only t)))
18376 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
18377 "Return a list of all relevant day numbers from BEG to END buffer positions.
18378 If NO-RANGES is non-nil, include only the start and end dates of a range,
18379 not every single day in the range. If FORCE-TODAY is non-nil, make
18380 sure that TODAY is included in the list. If INACTIVE is non-nil, also
18381 inactive time stamps (those in square brackets) are included.
18382 When EMPTY is non-nil, also include days without any entries."
18383 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
18384 dates dates1 date day day1 day2 ts1 ts2)
18385 (if force-today
18386 (setq dates (list (time-to-days (current-time)))))
18387 (save-excursion
18388 (goto-char beg)
18389 (while (re-search-forward re end t)
18390 (setq day (time-to-days (org-time-string-to-time
18391 (substring (match-string 1) 0 10))))
18392 (or (memq day dates) (push day dates)))
18393 (unless no-ranges
18394 (goto-char beg)
18395 (while (re-search-forward org-tr-regexp end t)
18396 (setq ts1 (substring (match-string 1) 0 10)
18397 ts2 (substring (match-string 2) 0 10)
18398 day1 (time-to-days (org-time-string-to-time ts1))
18399 day2 (time-to-days (org-time-string-to-time ts2)))
18400 (while (< (setq day1 (1+ day1)) day2)
18401 (or (memq day1 dates) (push day1 dates)))))
18402 (setq dates (sort dates '<))
18403 (when empty
18404 (while (setq day (pop dates))
18405 (setq day2 (car dates))
18406 (push day dates1)
18407 (when (and day2 empty)
18408 (if (or (eq empty t)
18409 (and (numberp empty) (<= (- day2 day) empty)))
18410 (while (< (setq day (1+ day)) day2)
18411 (push (list day) dates1))
18412 (push (cons :omitted (- day2 day)) dates1))))
18413 (setq dates (nreverse dates1)))
18414 dates)))
18416 ;;; Agenda Daily/Weekly
18418 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
18419 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
18420 (defvar org-agenda-last-arguments nil
18421 "The arguments of the previous call to org-agenda")
18422 (defvar org-starting-day nil) ; local variable in the agenda buffer
18423 (defvar org-agenda-span nil) ; local variable in the agenda buffer
18424 (defvar org-include-all-loc nil) ; local variable
18425 (defvar org-agenda-remove-date nil) ; dynamically scoped
18427 ;;;###autoload
18428 (defun org-agenda-list (&optional include-all start-day ndays)
18429 "Produce a weekly view from all files in variable `org-agenda-files'.
18430 The view will be for the current week, but from the overview buffer you
18431 will be able to go to other weeks.
18432 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
18433 also be shown, under the current date.
18434 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
18435 on the days are also shown. See the variable `org-log-done' for how
18436 to turn on logging.
18437 START-DAY defaults to TODAY, or to the most recent match for the weekday
18438 given in `org-agenda-start-on-weekday'.
18439 NDAYS defaults to `org-agenda-ndays'."
18440 (interactive "P")
18441 (setq ndays (or ndays org-agenda-ndays)
18442 start-day (or start-day org-agenda-start-day))
18443 (if org-agenda-overriding-arguments
18444 (setq include-all (car org-agenda-overriding-arguments)
18445 start-day (nth 1 org-agenda-overriding-arguments)
18446 ndays (nth 2 org-agenda-overriding-arguments)))
18447 (if (stringp start-day)
18448 ;; Convert to an absolute day number
18449 (setq start-day (time-to-days (org-read-date nil t start-day))))
18450 (setq org-agenda-last-arguments (list include-all start-day ndays))
18451 (org-compile-prefix-format 'agenda)
18452 (org-set-sorting-strategy 'agenda)
18453 (require 'calendar)
18454 (let* ((org-agenda-start-on-weekday
18455 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
18456 org-agenda-start-on-weekday nil))
18457 (thefiles (org-agenda-files))
18458 (files thefiles)
18459 (today (time-to-days (current-time)))
18460 (sd (or start-day today))
18461 (start (if (or (null org-agenda-start-on-weekday)
18462 (< org-agenda-ndays 7))
18464 (let* ((nt (calendar-day-of-week
18465 (calendar-gregorian-from-absolute sd)))
18466 (n1 org-agenda-start-on-weekday)
18467 (d (- nt n1)))
18468 (- sd (+ (if (< d 0) 7 0) d)))))
18469 (day-numbers (list start))
18470 (day-cnt 0)
18471 (inhibit-redisplay (not debug-on-error))
18472 s e rtn rtnall file date d start-pos end-pos todayp nd)
18473 (setq org-agenda-redo-command
18474 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
18475 ;; Make the list of days
18476 (setq ndays (or ndays org-agenda-ndays)
18477 nd ndays)
18478 (while (> ndays 1)
18479 (push (1+ (car day-numbers)) day-numbers)
18480 (setq ndays (1- ndays)))
18481 (setq day-numbers (nreverse day-numbers))
18482 (org-prepare-agenda "Day/Week")
18483 (org-set-local 'org-starting-day (car day-numbers))
18484 (org-set-local 'org-include-all-loc include-all)
18485 (org-set-local 'org-agenda-span
18486 (org-agenda-ndays-to-span nd))
18487 (when (and (or include-all org-agenda-include-all-todo)
18488 (member today day-numbers))
18489 (setq files thefiles
18490 rtnall nil)
18491 (while (setq file (pop files))
18492 (catch 'nextfile
18493 (org-check-agenda-file file)
18494 (setq date (calendar-gregorian-from-absolute today)
18495 rtn (org-agenda-get-day-entries
18496 file date :todo))
18497 (setq rtnall (append rtnall rtn))))
18498 (when rtnall
18499 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
18500 (add-text-properties (point-min) (1- (point))
18501 (list 'face 'org-agenda-structure))
18502 (insert (org-finalize-agenda-entries rtnall) "\n")))
18503 (unless org-agenda-compact-blocks
18504 (setq s (point))
18505 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
18506 "-agenda:\n")
18507 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
18508 'org-date-line t)))
18509 (while (setq d (pop day-numbers))
18510 (setq date (calendar-gregorian-from-absolute d)
18511 s (point))
18512 (if (or (setq todayp (= d today))
18513 (and (not start-pos) (= d sd)))
18514 (setq start-pos (point))
18515 (if (and start-pos (not end-pos))
18516 (setq end-pos (point))))
18517 (setq files thefiles
18518 rtnall nil)
18519 (while (setq file (pop files))
18520 (catch 'nextfile
18521 (org-check-agenda-file file)
18522 (if org-agenda-show-log
18523 (setq rtn (org-agenda-get-day-entries
18524 file date
18525 :deadline :scheduled :timestamp :sexp :closed))
18526 (setq rtn (org-agenda-get-day-entries
18527 file date
18528 :deadline :scheduled :sexp :timestamp)))
18529 (setq rtnall (append rtnall rtn))))
18530 (if org-agenda-include-diary
18531 (progn
18532 (require 'diary-lib)
18533 (setq rtn (org-get-entries-from-diary date))
18534 (setq rtnall (append rtnall rtn))))
18535 (if (or rtnall org-agenda-show-all-dates)
18536 (progn
18537 (setq day-cnt (1+ day-cnt))
18538 (insert
18539 (if (stringp org-agenda-format-date)
18540 (format-time-string org-agenda-format-date
18541 (org-time-from-absolute date))
18542 (funcall org-agenda-format-date date))
18543 "\n")
18544 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
18545 (put-text-property s (1- (point)) 'org-date-line t)
18546 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
18547 (if todayp (put-text-property s (1- (point)) 'org-today t))
18548 (if rtnall (insert
18549 (org-finalize-agenda-entries
18550 (org-agenda-add-time-grid-maybe
18551 rtnall nd todayp))
18552 "\n"))
18553 (put-text-property s (1- (point)) 'day d)
18554 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
18555 (goto-char (point-min))
18556 (org-fit-agenda-window)
18557 (unless (and (pos-visible-in-window-p (point-min))
18558 (pos-visible-in-window-p (point-max)))
18559 (goto-char (1- (point-max)))
18560 (recenter -1)
18561 (if (not (pos-visible-in-window-p (or start-pos 1)))
18562 (progn
18563 (goto-char (or start-pos 1))
18564 (recenter 1))))
18565 (goto-char (or start-pos 1))
18566 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
18567 (org-finalize-agenda)
18568 (setq buffer-read-only t)
18569 (message "")))
18571 (defun org-agenda-ndays-to-span (n)
18572 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
18574 ;;; Agenda TODO list
18576 (defvar org-select-this-todo-keyword nil)
18577 (defvar org-last-arg nil)
18579 ;;;###autoload
18580 (defun org-todo-list (arg)
18581 "Show all TODO entries from all agenda file in a single list.
18582 The prefix arg can be used to select a specific TODO keyword and limit
18583 the list to these. When using \\[universal-argument], you will be prompted
18584 for a keyword. A numeric prefix directly selects the Nth keyword in
18585 `org-todo-keywords-1'."
18586 (interactive "P")
18587 (require 'calendar)
18588 (org-compile-prefix-format 'todo)
18589 (org-set-sorting-strategy 'todo)
18590 (org-prepare-agenda "TODO")
18591 (let* ((today (time-to-days (current-time)))
18592 (date (calendar-gregorian-from-absolute today))
18593 (kwds org-todo-keywords-for-agenda)
18594 (completion-ignore-case t)
18595 (org-select-this-todo-keyword
18596 (if (stringp arg) arg
18597 (and arg (integerp arg) (> arg 0)
18598 (nth (1- arg) kwds))))
18599 rtn rtnall files file pos)
18600 (when (equal arg '(4))
18601 (setq org-select-this-todo-keyword
18602 (completing-read "Keyword (or KWD1|K2D2|...): "
18603 (mapcar 'list kwds) nil nil)))
18604 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
18605 (org-set-local 'org-last-arg arg)
18606 (setq org-agenda-redo-command
18607 '(org-todo-list (or current-prefix-arg org-last-arg)))
18608 (setq files (org-agenda-files)
18609 rtnall nil)
18610 (while (setq file (pop files))
18611 (catch 'nextfile
18612 (org-check-agenda-file file)
18613 (setq rtn (org-agenda-get-day-entries file date :todo))
18614 (setq rtnall (append rtnall rtn))))
18615 (if org-agenda-overriding-header
18616 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
18617 nil 'face 'org-agenda-structure) "\n")
18618 (insert "Global list of TODO items of type: ")
18619 (add-text-properties (point-min) (1- (point))
18620 (list 'face 'org-agenda-structure))
18621 (setq pos (point))
18622 (insert (or org-select-this-todo-keyword "ALL") "\n")
18623 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
18624 (setq pos (point))
18625 (unless org-agenda-multi
18626 (insert "Available with `N r': (0)ALL")
18627 (let ((n 0) s)
18628 (mapc (lambda (x)
18629 (setq s (format "(%d)%s" (setq n (1+ n)) x))
18630 (if (> (+ (current-column) (string-width s) 1) (frame-width))
18631 (insert "\n "))
18632 (insert " " s))
18633 kwds))
18634 (insert "\n"))
18635 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
18636 (when rtnall
18637 (insert (org-finalize-agenda-entries rtnall) "\n"))
18638 (goto-char (point-min))
18639 (org-fit-agenda-window)
18640 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
18641 (org-finalize-agenda)
18642 (setq buffer-read-only t)))
18644 ;;; Agenda tags match
18646 ;;;###autoload
18647 (defun org-tags-view (&optional todo-only match)
18648 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
18649 The prefix arg TODO-ONLY limits the search to TODO entries."
18650 (interactive "P")
18651 (org-compile-prefix-format 'tags)
18652 (org-set-sorting-strategy 'tags)
18653 (let* ((org-tags-match-list-sublevels
18654 (if todo-only t org-tags-match-list-sublevels))
18655 (completion-ignore-case t)
18656 rtn rtnall files file pos matcher
18657 buffer)
18658 (setq matcher (org-make-tags-matcher match)
18659 match (car matcher) matcher (cdr matcher))
18660 (org-prepare-agenda (concat "TAGS " match))
18661 (setq org-agenda-redo-command
18662 (list 'org-tags-view (list 'quote todo-only)
18663 (list 'if 'current-prefix-arg nil match)))
18664 (setq files (org-agenda-files)
18665 rtnall nil)
18666 (while (setq file (pop files))
18667 (catch 'nextfile
18668 (org-check-agenda-file file)
18669 (setq buffer (if (file-exists-p file)
18670 (org-get-agenda-file-buffer file)
18671 (error "No such file %s" file)))
18672 (if (not buffer)
18673 ;; If file does not exist, merror message to agenda
18674 (setq rtn (list
18675 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
18676 rtnall (append rtnall rtn))
18677 (with-current-buffer buffer
18678 (unless (org-mode-p)
18679 (error "Agenda file %s is not in `org-mode'" file))
18680 (save-excursion
18681 (save-restriction
18682 (if org-agenda-restrict
18683 (narrow-to-region org-agenda-restrict-begin
18684 org-agenda-restrict-end)
18685 (widen))
18686 (setq rtn (org-scan-tags 'agenda matcher todo-only))
18687 (setq rtnall (append rtnall rtn))))))))
18688 (if org-agenda-overriding-header
18689 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
18690 nil 'face 'org-agenda-structure) "\n")
18691 (insert "Headlines with TAGS match: ")
18692 (add-text-properties (point-min) (1- (point))
18693 (list 'face 'org-agenda-structure))
18694 (setq pos (point))
18695 (insert match "\n")
18696 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
18697 (setq pos (point))
18698 (unless org-agenda-multi
18699 (insert "Press `C-u r' to search again with new search string\n"))
18700 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
18701 (when rtnall
18702 (insert (org-finalize-agenda-entries rtnall) "\n"))
18703 (goto-char (point-min))
18704 (org-fit-agenda-window)
18705 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
18706 (org-finalize-agenda)
18707 (setq buffer-read-only t)))
18709 ;;; Agenda Finding stuck projects
18711 (defvar org-agenda-skip-regexp nil
18712 "Regular expression used in skipping subtrees for the agenda.
18713 This is basically a temporary global variable that can be set and then
18714 used by user-defined selections using `org-agenda-skip-function'.")
18716 (defvar org-agenda-overriding-header nil
18717 "When this is set during todo and tags searches, will replace header.")
18719 (defun org-agenda-skip-subtree-when-regexp-matches ()
18720 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
18721 If yes, it returns the end position of this tree, causing agenda commands
18722 to skip this subtree. This is a function that can be put into
18723 `org-agenda-skip-function' for the duration of a command."
18724 (let ((end (save-excursion (org-end-of-subtree t)))
18725 skip)
18726 (save-excursion
18727 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
18728 (and skip end)))
18730 (defun org-agenda-skip-entry-if (&rest conditions)
18731 "Skip entry if any of CONDITIONS is true.
18732 See `org-agenda-skip-if for details."
18733 (org-agenda-skip-if nil conditions))
18734 (defun org-agenda-skip-subtree-if (&rest conditions)
18735 "Skip entry if any of CONDITIONS is true.
18736 See `org-agenda-skip-if for details."
18737 (org-agenda-skip-if t conditions))
18739 (defun org-agenda-skip-if (subtree conditions)
18740 "Checks current entity for CONDITIONS.
18741 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
18742 the entry, i.e. the text before the next heading is checked.
18744 CONDITIONS is a list of symbols, boolean OR is used to combine the results
18745 from different tests. Valid conditions are:
18747 scheduled Check if there is a scheduled cookie
18748 notscheduled Check if there is no scheduled cookie
18749 deadline Check if there is a deadline
18750 notdeadline Check if there is no deadline
18751 regexp Check if regexp matches
18752 notregexp Check if regexp does not match.
18754 The regexp is taken from the conditions list, it must com right after the
18755 `regexp' of `notregexp' element.
18757 If any of these conditions is met, this function returns the end point of
18758 the entity, causing the search to continue from there. This is a function
18759 that can be put into `org-agenda-skip-function' for the duration of a command."
18760 (let (beg end m r)
18761 (org-back-to-heading t)
18762 (setq beg (point)
18763 end (if subtree
18764 (progn (org-end-of-subtree t) (point))
18765 (progn (outline-next-heading) (1- (point)))))
18766 (goto-char beg)
18767 (and
18769 (and (memq 'scheduled conditions)
18770 (re-search-forward org-scheduled-time-regexp end t))
18771 (and (memq 'notscheduled conditions)
18772 (not (re-search-forward org-scheduled-time-regexp end t)))
18773 (and (memq 'deadline conditions)
18774 (re-search-forward org-deadline-time-regexp end t))
18775 (and (memq 'notdeadline conditions)
18776 (not (re-search-forward org-deadline-time-regexp end t)))
18777 (and (setq m (memq 'regexp conditions))
18778 (stringp (setq r (nth 1 m)))
18779 (re-search-forward (nth 1 m) end t))
18780 (and (setq m (memq 'notregexp conditions))
18781 (stringp (setq r (nth 1 m)))
18782 (not (re-search-forward (nth 1 m) end t))))
18783 end)))
18785 (defun org-agenda-list-stuck-projects (&rest ignore)
18786 "Create agenda view for projects that are stuck.
18787 Stuck projects are project that have no next actions. For the definitions
18788 of what a project is and how to check if it stuck, customize the variable
18789 `org-stuck-projects'.
18790 MATCH is being ignored."
18791 (interactive)
18792 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
18793 ;; FIXME: we could have used org-agenda-skip-if here.
18794 (org-agenda-overriding-header "List of stuck projects: ")
18795 (matcher (nth 0 org-stuck-projects))
18796 (todo (nth 1 org-stuck-projects))
18797 (todo-wds (if (member "*" todo)
18798 (progn
18799 (org-prepare-agenda-buffers (org-agenda-files))
18800 (org-delete-all
18801 org-done-keywords-for-agenda
18802 (copy-sequence org-todo-keywords-for-agenda)))
18803 todo))
18804 (todo-re (concat "^\\*+[ \t]+\\("
18805 (mapconcat 'identity todo-wds "\\|")
18806 "\\)\\>"))
18807 (tags (nth 2 org-stuck-projects))
18808 (tags-re (if (member "*" tags)
18809 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
18810 (concat "^\\*+ .*:\\("
18811 (mapconcat 'identity tags "\\|")
18812 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
18813 (gen-re (nth 3 org-stuck-projects))
18814 (re-list
18815 (delq nil
18816 (list
18817 (if todo todo-re)
18818 (if tags tags-re)
18819 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
18820 gen-re)))))
18821 (setq org-agenda-skip-regexp
18822 (if re-list
18823 (mapconcat 'identity re-list "\\|")
18824 (error "No information how to identify unstuck projects")))
18825 (org-tags-view nil matcher)
18826 (with-current-buffer org-agenda-buffer-name
18827 (setq org-agenda-redo-command
18828 '(org-agenda-list-stuck-projects
18829 (or current-prefix-arg org-last-arg))))))
18831 ;;; Diary integration
18833 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
18835 (defun org-get-entries-from-diary (date)
18836 "Get the (Emacs Calendar) diary entries for DATE."
18837 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
18838 (diary-display-hook '(fancy-diary-display))
18839 (pop-up-frames nil)
18840 (list-diary-entries-hook
18841 (cons 'org-diary-default-entry list-diary-entries-hook))
18842 (diary-file-name-prefix-function nil) ; turn this feature off
18843 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
18844 entries
18845 (org-disable-agenda-to-diary t))
18846 (save-excursion
18847 (save-window-excursion
18848 (funcall (if (fboundp 'diary-list-entries)
18849 'diary-list-entries 'list-diary-entries)
18850 date 1)))
18851 (if (not (get-buffer fancy-diary-buffer))
18852 (setq entries nil)
18853 (with-current-buffer fancy-diary-buffer
18854 (setq buffer-read-only nil)
18855 (if (zerop (buffer-size))
18856 ;; No entries
18857 (setq entries nil)
18858 ;; Omit the date and other unnecessary stuff
18859 (org-agenda-cleanup-fancy-diary)
18860 ;; Add prefix to each line and extend the text properties
18861 (if (zerop (buffer-size))
18862 (setq entries nil)
18863 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
18864 (set-buffer-modified-p nil)
18865 (kill-buffer fancy-diary-buffer)))
18866 (when entries
18867 (setq entries (org-split-string entries "\n"))
18868 (setq entries
18869 (mapcar
18870 (lambda (x)
18871 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
18872 ;; Extend the text properties to the beginning of the line
18873 (org-add-props x (text-properties-at (1- (length x)) x)
18874 'type "diary" 'date date))
18875 entries)))))
18877 (defun org-agenda-cleanup-fancy-diary ()
18878 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
18879 This gets rid of the date, the underline under the date, and
18880 the dummy entry installed by `org-mode' to ensure non-empty diary for each
18881 date. It also removes lines that contain only whitespace."
18882 (goto-char (point-min))
18883 (if (looking-at ".*?:[ \t]*")
18884 (progn
18885 (replace-match "")
18886 (re-search-forward "\n=+$" nil t)
18887 (replace-match "")
18888 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
18889 (re-search-forward "\n=+$" nil t)
18890 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
18891 (goto-char (point-min))
18892 (while (re-search-forward "^ +\n" nil t)
18893 (replace-match ""))
18894 (goto-char (point-min))
18895 (if (re-search-forward "^Org-mode dummy\n?" nil t)
18896 (replace-match "")))
18898 ;; Make sure entries from the diary have the right text properties.
18899 (eval-after-load "diary-lib"
18900 '(if (boundp 'diary-modify-entry-list-string-function)
18901 ;; We can rely on the hook, nothing to do
18903 ;; Hook not avaiable, must use advice to make this work
18904 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
18905 "Make the position visible."
18906 (if (and org-disable-agenda-to-diary ;; called from org-agenda
18907 (stringp string)
18908 buffer-file-name)
18909 (setq string (org-modify-diary-entry-string string))))))
18911 (defun org-modify-diary-entry-string (string)
18912 "Add text properties to string, allowing org-mode to act on it."
18913 (org-add-props string nil
18914 'mouse-face 'highlight
18915 'keymap org-agenda-keymap
18916 'help-echo (if buffer-file-name
18917 (format "mouse-2 or RET jump to diary file %s"
18918 (abbreviate-file-name buffer-file-name))
18920 'org-agenda-diary-link t
18921 'org-marker (org-agenda-new-marker (point-at-bol))))
18923 (defun org-diary-default-entry ()
18924 "Add a dummy entry to the diary.
18925 Needed to avoid empty dates which mess up holiday display."
18926 ;; Catch the error if dealing with the new add-to-diary-alist
18927 (when org-disable-agenda-to-diary
18928 (condition-case nil
18929 (add-to-diary-list original-date "Org-mode dummy" "")
18930 (error
18931 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
18933 ;;;###autoload
18934 (defun org-diary (&rest args)
18935 "Return diary information from org-files.
18936 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
18937 It accesses org files and extracts information from those files to be
18938 listed in the diary. The function accepts arguments specifying what
18939 items should be listed. The following arguments are allowed:
18941 :timestamp List the headlines of items containing a date stamp or
18942 date range matching the selected date. Deadlines will
18943 also be listed, on the expiration day.
18945 :sexp List entries resulting from diary-like sexps.
18947 :deadline List any deadlines past due, or due within
18948 `org-deadline-warning-days'. The listing occurs only
18949 in the diary for *today*, not at any other date. If
18950 an entry is marked DONE, it is no longer listed.
18952 :scheduled List all items which are scheduled for the given date.
18953 The diary for *today* also contains items which were
18954 scheduled earlier and are not yet marked DONE.
18956 :todo List all TODO items from the org-file. This may be a
18957 long list - so this is not turned on by default.
18958 Like deadlines, these entries only show up in the
18959 diary for *today*, not at any other date.
18961 The call in the diary file should look like this:
18963 &%%(org-diary) ~/path/to/some/orgfile.org
18965 Use a separate line for each org file to check. Or, if you omit the file name,
18966 all files listed in `org-agenda-files' will be checked automatically:
18968 &%%(org-diary)
18970 If you don't give any arguments (as in the example above), the default
18971 arguments (:deadline :scheduled :timestamp :sexp) are used.
18972 So the example above may also be written as
18974 &%%(org-diary :deadline :timestamp :sexp :scheduled)
18976 The function expects the lisp variables `entry' and `date' to be provided
18977 by the caller, because this is how the calendar works. Don't use this
18978 function from a program - use `org-agenda-get-day-entries' instead."
18979 (org-agenda-maybe-reset-markers)
18980 (org-compile-prefix-format 'agenda)
18981 (org-set-sorting-strategy 'agenda)
18982 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
18983 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
18984 (list entry)
18985 (org-agenda-files t)))
18986 file rtn results)
18987 (org-prepare-agenda-buffers files)
18988 ;; If this is called during org-agenda, don't return any entries to
18989 ;; the calendar. Org Agenda will list these entries itself.
18990 (if org-disable-agenda-to-diary (setq files nil))
18991 (while (setq file (pop files))
18992 (setq rtn (apply 'org-agenda-get-day-entries file date args))
18993 (setq results (append results rtn)))
18994 (if results
18995 (concat (org-finalize-agenda-entries results) "\n"))))
18997 ;;; Agenda entry finders
18999 (defun org-agenda-get-day-entries (file date &rest args)
19000 "Does the work for `org-diary' and `org-agenda'.
19001 FILE is the path to a file to be checked for entries. DATE is date like
19002 the one returned by `calendar-current-date'. ARGS are symbols indicating
19003 which kind of entries should be extracted. For details about these, see
19004 the documentation of `org-diary'."
19005 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
19006 (let* ((org-startup-folded nil)
19007 (org-startup-align-all-tables nil)
19008 (buffer (if (file-exists-p file)
19009 (org-get-agenda-file-buffer file)
19010 (error "No such file %s" file)))
19011 arg results rtn)
19012 (if (not buffer)
19013 ;; If file does not exist, make sure an error message ends up in diary
19014 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
19015 (with-current-buffer buffer
19016 (unless (org-mode-p)
19017 (error "Agenda file %s is not in `org-mode'" file))
19018 (let ((case-fold-search nil))
19019 (save-excursion
19020 (save-restriction
19021 (if org-agenda-restrict
19022 (narrow-to-region org-agenda-restrict-begin
19023 org-agenda-restrict-end)
19024 (widen))
19025 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
19026 (while (setq arg (pop args))
19027 (cond
19028 ((and (eq arg :todo)
19029 (equal date (calendar-current-date)))
19030 (setq rtn (org-agenda-get-todos))
19031 (setq results (append results rtn)))
19032 ((eq arg :timestamp)
19033 (setq rtn (org-agenda-get-blocks))
19034 (setq results (append results rtn))
19035 (setq rtn (org-agenda-get-timestamps))
19036 (setq results (append results rtn)))
19037 ((eq arg :sexp)
19038 (setq rtn (org-agenda-get-sexps))
19039 (setq results (append results rtn)))
19040 ((eq arg :scheduled)
19041 (setq rtn (org-agenda-get-scheduled))
19042 (setq results (append results rtn)))
19043 ((eq arg :closed)
19044 (setq rtn (org-agenda-get-closed))
19045 (setq results (append results rtn)))
19046 ((eq arg :deadline)
19047 (setq rtn (org-agenda-get-deadlines))
19048 (setq results (append results rtn))))))))
19049 results))))
19051 ;; FIXME: this works only if the cursor is *not* at the
19052 ;; beginning of the entry
19053 (defun org-entry-is-done-p ()
19054 "Is the current entry marked DONE?"
19055 (save-excursion
19056 (and (re-search-backward "[\r\n]\\*+ " nil t)
19057 (looking-at org-nl-done-regexp))))
19059 (defun org-at-date-range-p (&optional inactive-ok)
19060 "Is the cursor inside a date range?"
19061 (interactive)
19062 (save-excursion
19063 (catch 'exit
19064 (let ((pos (point)))
19065 (skip-chars-backward "^[<\r\n")
19066 (skip-chars-backward "<[")
19067 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
19068 (>= (match-end 0) pos)
19069 (throw 'exit t))
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 nil)))
19077 (defun org-agenda-get-todos ()
19078 "Return the TODO information for agenda display."
19079 (let* ((props (list 'face nil
19080 'done-face 'org-done
19081 'org-not-done-regexp org-not-done-regexp
19082 'org-todo-regexp org-todo-regexp
19083 'mouse-face 'highlight
19084 'keymap org-agenda-keymap
19085 'help-echo
19086 (format "mouse-2 or RET jump to org file %s"
19087 (abbreviate-file-name buffer-file-name))))
19088 ;; FIXME: get rid of the \n at some point but watch out
19089 (regexp (concat "^\\*+[ \t]+\\("
19090 (if org-select-this-todo-keyword
19091 (if (equal org-select-this-todo-keyword "*")
19092 org-todo-regexp
19093 (concat "\\<\\("
19094 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
19095 "\\)\\>"))
19096 org-not-done-regexp)
19097 "[^\n\r]*\\)"))
19098 marker priority category tags
19099 ee txt beg end)
19100 (goto-char (point-min))
19101 (while (re-search-forward regexp nil t)
19102 (catch :skip
19103 (save-match-data
19104 (beginning-of-line)
19105 (setq beg (point) end (progn (outline-next-heading) (point)))
19106 (when (or (and org-agenda-todo-ignore-scheduled (goto-char beg)
19107 (re-search-forward org-scheduled-time-regexp end t))
19108 (and org-agenda-todo-ignore-deadlines (goto-char beg)
19109 (re-search-forward org-deadline-time-regexp end t)
19110 (org-deadline-close (match-string 1))))
19111 (goto-char (1+ beg))
19112 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
19113 (throw :skip nil)))
19114 (goto-char beg)
19115 (org-agenda-skip)
19116 (goto-char (match-beginning 1))
19117 (setq marker (org-agenda-new-marker (match-beginning 0))
19118 category (org-get-category)
19119 tags (org-get-tags-at (point))
19120 txt (org-format-agenda-item "" (match-string 1) category tags)
19121 priority (1+ (org-get-priority txt)))
19122 (org-add-props txt props
19123 'org-marker marker 'org-hd-marker marker
19124 'priority priority 'org-category category
19125 'type "todo")
19126 (push txt ee)
19127 (if org-agenda-todo-list-sublevels
19128 (goto-char (match-end 1))
19129 (org-end-of-subtree 'invisible))))
19130 (nreverse ee)))
19132 (defconst org-agenda-no-heading-message
19133 "No heading for this item in buffer or region.")
19135 (defun org-agenda-get-timestamps ()
19136 "Return the date stamp information for agenda display."
19137 (let* ((props (list 'face nil
19138 'org-not-done-regexp org-not-done-regexp
19139 'org-todo-regexp org-todo-regexp
19140 'mouse-face 'highlight
19141 'keymap org-agenda-keymap
19142 'help-echo
19143 (format "mouse-2 or RET jump to org file %s"
19144 (abbreviate-file-name buffer-file-name))))
19145 (d1 (calendar-absolute-from-gregorian date))
19146 (remove-re
19147 (concat
19148 (regexp-quote
19149 (format-time-string
19150 "<%Y-%m-%d"
19151 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19152 ".*?>"))
19153 (regexp
19154 (concat
19155 (regexp-quote
19156 (substring
19157 (format-time-string
19158 (car org-time-stamp-formats)
19159 (apply 'encode-time ; DATE bound by calendar
19160 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
19161 0 11))
19162 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
19163 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
19164 marker hdmarker deadlinep scheduledp donep tmp priority category
19165 ee txt timestr tags b0 b3 e3)
19166 (goto-char (point-min))
19167 (while (re-search-forward regexp nil t)
19168 (setq b0 (match-beginning 0)
19169 b3 (match-beginning 3) e3 (match-end 3))
19170 (catch :skip
19171 (and (org-at-date-range-p) (throw :skip nil))
19172 (org-agenda-skip)
19173 (if (and (match-end 1)
19174 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
19175 (throw :skip nil))
19176 (if (and e3
19177 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
19178 (throw :skip nil))
19179 (setq marker (org-agenda-new-marker b0)
19180 category (org-get-category b0)
19181 tmp (buffer-substring (max (point-min)
19182 (- b0 org-ds-keyword-length))
19184 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
19185 deadlinep (string-match org-deadline-regexp tmp)
19186 scheduledp (string-match org-scheduled-regexp tmp)
19187 donep (org-entry-is-done-p))
19188 (if (or scheduledp deadlinep) (throw :skip t))
19189 (if (string-match ">" timestr)
19190 ;; substring should only run to end of time stamp
19191 (setq timestr (substring timestr 0 (match-end 0))))
19192 (save-excursion
19193 (if (re-search-backward "^\\*+ " nil t)
19194 (progn
19195 (goto-char (match-beginning 0))
19196 (setq hdmarker (org-agenda-new-marker)
19197 tags (org-get-tags-at))
19198 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
19199 (setq txt (org-format-agenda-item
19200 nil (match-string 1) category tags timestr nil
19201 remove-re)))
19202 (setq txt org-agenda-no-heading-message))
19203 (setq priority (org-get-priority txt))
19204 (org-add-props txt props
19205 'org-marker marker 'org-hd-marker hdmarker)
19206 (org-add-props txt nil 'priority priority
19207 'org-category category 'date date
19208 'type "timestamp")
19209 (push txt ee))
19210 (outline-next-heading)))
19211 (nreverse ee)))
19213 (defun org-agenda-get-sexps ()
19214 "Return the sexp information for agenda display."
19215 (require 'diary-lib)
19216 (let* ((props (list 'face nil
19217 'mouse-face 'highlight
19218 'keymap org-agenda-keymap
19219 'help-echo
19220 (format "mouse-2 or RET jump to org file %s"
19221 (abbreviate-file-name buffer-file-name))))
19222 (regexp "^&?%%(")
19223 marker category ee txt tags entry result beg b sexp sexp-entry)
19224 (goto-char (point-min))
19225 (while (re-search-forward regexp nil t)
19226 (catch :skip
19227 (org-agenda-skip)
19228 (setq beg (match-beginning 0))
19229 (goto-char (1- (match-end 0)))
19230 (setq b (point))
19231 (forward-sexp 1)
19232 (setq sexp (buffer-substring b (point)))
19233 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
19234 (org-trim (match-string 1))
19235 ""))
19236 (setq result (org-diary-sexp-entry sexp sexp-entry date))
19237 (when result
19238 (setq marker (org-agenda-new-marker beg)
19239 category (org-get-category beg))
19241 (if (string-match "\\S-" result)
19242 (setq txt result)
19243 (setq txt "SEXP entry returned empty string"))
19245 (setq txt (org-format-agenda-item
19246 "" txt category tags 'time))
19247 (org-add-props txt props 'org-marker marker)
19248 (org-add-props txt nil
19249 'org-category category 'date date
19250 'type "sexp")
19251 (push txt ee))))
19252 (nreverse ee)))
19254 (defun org-agenda-get-closed ()
19255 "Return the logged TODO entries for agenda display."
19256 (let* ((props (list 'mouse-face 'highlight
19257 'org-not-done-regexp org-not-done-regexp
19258 'org-todo-regexp org-todo-regexp
19259 'keymap org-agenda-keymap
19260 'help-echo
19261 (format "mouse-2 or RET jump to org file %s"
19262 (abbreviate-file-name buffer-file-name))))
19263 (regexp (concat
19264 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
19265 (regexp-quote
19266 (substring
19267 (format-time-string
19268 (car org-time-stamp-formats)
19269 (apply 'encode-time ; DATE bound by calendar
19270 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
19271 1 11))))
19272 marker hdmarker priority category tags closedp
19273 ee txt timestr)
19274 (goto-char (point-min))
19275 (while (re-search-forward regexp nil t)
19276 (catch :skip
19277 (org-agenda-skip)
19278 (setq marker (org-agenda-new-marker (match-beginning 0))
19279 closedp (equal (match-string 1) org-closed-string)
19280 category (org-get-category (match-beginning 0))
19281 timestr (buffer-substring (match-beginning 0) (point-at-eol))
19282 ;; donep (org-entry-is-done-p)
19284 (if (string-match "\\]" timestr)
19285 ;; substring should only run to end of time stamp
19286 (setq timestr (substring timestr 0 (match-end 0))))
19287 (save-excursion
19288 (if (re-search-backward "^\\*+ " nil t)
19289 (progn
19290 (goto-char (match-beginning 0))
19291 (setq hdmarker (org-agenda-new-marker)
19292 tags (org-get-tags-at))
19293 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
19294 (setq txt (org-format-agenda-item
19295 (if closedp "Closed: " "Clocked: ")
19296 (match-string 1) category tags timestr)))
19297 (setq txt org-agenda-no-heading-message))
19298 (setq priority 100000)
19299 (org-add-props txt props
19300 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
19301 'priority priority 'org-category category
19302 'type "closed" 'date date
19303 'undone-face 'org-warning 'done-face 'org-done)
19304 (push txt ee))
19305 (outline-next-heading)))
19306 (nreverse ee)))
19308 (defun org-agenda-get-deadlines ()
19309 "Return the deadline information for agenda display."
19310 (let* ((props (list 'mouse-face 'highlight
19311 'org-not-done-regexp org-not-done-regexp
19312 'org-todo-regexp org-todo-regexp
19313 'keymap org-agenda-keymap
19314 'help-echo
19315 (format "mouse-2 or RET jump to org file %s"
19316 (abbreviate-file-name buffer-file-name))))
19317 (regexp org-deadline-time-regexp)
19318 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
19319 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
19320 d2 diff dfrac wdays pos pos1 category tags
19321 ee txt head face s upcomingp donep timestr)
19322 (goto-char (point-min))
19323 (while (re-search-forward regexp nil t)
19324 (catch :skip
19325 (org-agenda-skip)
19326 (setq s (match-string 1)
19327 pos (1- (match-beginning 1))
19328 d2 (org-time-string-to-absolute (match-string 1) d1)
19329 diff (- d2 d1)
19330 wdays (org-get-wdays s)
19331 dfrac (/ (* 1.0 (- wdays diff)) wdays)
19332 upcomingp (and todayp (> diff 0)))
19333 ;; When to show a deadline in the calendar:
19334 ;; If the expiration is within wdays warning time.
19335 ;; Past-due deadlines are only shown on the current date
19336 (if (or (and (<= diff wdays)
19337 (and todayp (not org-agenda-only-exact-dates)))
19338 (= diff 0))
19339 (save-excursion
19340 (setq category (org-get-category))
19341 (if (re-search-backward "^\\*+[ \t]+" nil t)
19342 (progn
19343 (goto-char (match-end 0))
19344 (setq pos1 (match-beginning 0))
19345 (setq tags (org-get-tags-at pos1))
19346 (setq head (buffer-substring-no-properties
19347 (point)
19348 (progn (skip-chars-forward "^\r\n")
19349 (point))))
19350 (setq donep (string-match org-looking-at-done-regexp head))
19351 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
19352 (setq timestr
19353 (concat (substring s (match-beginning 1)) " "))
19354 (setq timestr 'time))
19355 (if (and donep
19356 (or org-agenda-skip-deadline-if-done
19357 (not (= diff 0))))
19358 (setq txt nil)
19359 (setq txt (org-format-agenda-item
19360 (if (= diff 0)
19361 (car org-agenda-deadline-leaders)
19362 (format (nth 1 org-agenda-deadline-leaders)
19363 diff))
19364 head category tags timestr))))
19365 (setq txt org-agenda-no-heading-message))
19366 (when txt
19367 (setq face (org-agenda-deadline-face dfrac))
19368 (org-add-props txt props
19369 'org-marker (org-agenda-new-marker pos)
19370 'org-hd-marker (org-agenda-new-marker pos1)
19371 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
19372 (org-get-priority txt))
19373 'org-category category
19374 'type (if upcomingp "upcoming-deadline" "deadline")
19375 'date (if upcomingp date d2)
19376 'face (if donep 'org-done face)
19377 'undone-face face 'done-face 'org-done)
19378 (push txt ee))))))
19379 (nreverse ee)))
19381 (defun org-agenda-deadline-face (fraction)
19382 "Return the face to displaying a deadline item.
19383 FRACTION is what fraction of the head-warning time has passed."
19384 (let ((faces org-agenda-deadline-faces) f)
19385 (catch 'exit
19386 (while (setq f (pop faces))
19387 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
19389 (defun org-agenda-get-scheduled ()
19390 "Return the scheduled information for agenda display."
19391 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
19392 'org-todo-regexp org-todo-regexp
19393 'done-face 'org-done
19394 'mouse-face 'highlight
19395 'keymap org-agenda-keymap
19396 'help-echo
19397 (format "mouse-2 or RET jump to org file %s"
19398 (abbreviate-file-name buffer-file-name))))
19399 (regexp org-scheduled-time-regexp)
19400 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
19401 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
19402 d2 diff pos pos1 category tags
19403 ee txt head pastschedp donep face timestr s)
19404 (goto-char (point-min))
19405 (while (re-search-forward regexp nil t)
19406 (catch :skip
19407 (org-agenda-skip)
19408 (setq s (match-string 1)
19409 pos (1- (match-beginning 1))
19410 d2 (org-time-string-to-absolute (match-string 1) d1)
19411 diff (- d2 d1))
19412 (setq pastschedp (and todayp (< diff 0)))
19413 ;; When to show a scheduled item in the calendar:
19414 ;; If it is on or past the date.
19415 (if (or (and (< diff 0)
19416 (and todayp (not org-agenda-only-exact-dates)))
19417 (= diff 0))
19418 (save-excursion
19419 (setq category (org-get-category))
19420 (if (re-search-backward "^\\*+[ \t]+" nil t)
19421 (progn
19422 (goto-char (match-end 0))
19423 (setq pos1 (match-beginning 0))
19424 (setq tags (org-get-tags-at))
19425 (setq head (buffer-substring-no-properties
19426 (point)
19427 (progn (skip-chars-forward "^\r\n") (point))))
19428 (setq donep (string-match org-looking-at-done-regexp head))
19429 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
19430 (setq timestr
19431 (concat (substring s (match-beginning 1)) " "))
19432 (setq timestr 'time))
19433 (if (and donep
19434 (or org-agenda-skip-scheduled-if-done
19435 (not (= diff 0))))
19436 (setq txt nil)
19437 (setq txt (org-format-agenda-item
19438 (if (= diff 0)
19439 (car org-agenda-scheduled-leaders)
19440 (format (nth 1 org-agenda-scheduled-leaders)
19441 (- 1 diff)))
19442 head category tags timestr))))
19443 (setq txt org-agenda-no-heading-message))
19444 (when txt
19445 (setq face (if pastschedp
19446 'org-scheduled-previously
19447 'org-scheduled-today))
19448 (org-add-props txt props
19449 'undone-face face
19450 'face (if donep 'org-done face)
19451 'org-marker (org-agenda-new-marker pos)
19452 'org-hd-marker (org-agenda-new-marker pos1)
19453 'type (if pastschedp "past-scheduled" "scheduled")
19454 'date (if pastschedp d2 date)
19455 'priority (+ 94 (- 5 diff) (org-get-priority txt))
19456 'org-category category)
19457 (push txt ee))))))
19458 (nreverse ee)))
19460 (defun org-agenda-get-blocks ()
19461 "Return the date-range information for agenda display."
19462 (let* ((props (list 'face nil
19463 'org-not-done-regexp org-not-done-regexp
19464 'org-todo-regexp org-todo-regexp
19465 'mouse-face 'highlight
19466 'keymap org-agenda-keymap
19467 'help-echo
19468 (format "mouse-2 or RET jump to org file %s"
19469 (abbreviate-file-name buffer-file-name))))
19470 (regexp org-tr-regexp)
19471 (d0 (calendar-absolute-from-gregorian date))
19472 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
19473 (goto-char (point-min))
19474 (while (re-search-forward regexp nil t)
19475 (catch :skip
19476 (org-agenda-skip)
19477 (setq pos (point))
19478 (setq timestr (match-string 0)
19479 s1 (match-string 1)
19480 s2 (match-string 2)
19481 d1 (time-to-days (org-time-string-to-time s1))
19482 d2 (time-to-days (org-time-string-to-time s2)))
19483 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
19484 ;; Only allow days between the limits, because the normal
19485 ;; date stamps will catch the limits.
19486 (save-excursion
19487 (setq marker (org-agenda-new-marker (point)))
19488 (setq category (org-get-category))
19489 (if (re-search-backward "^\\*+ " nil t)
19490 (progn
19491 (goto-char (match-beginning 0))
19492 (setq hdmarker (org-agenda-new-marker (point)))
19493 (setq tags (org-get-tags-at))
19494 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
19495 (setq txt (org-format-agenda-item
19496 (format (if (= d1 d2) "" "(%d/%d): ")
19497 (1+ (- d0 d1)) (1+ (- d2 d1)))
19498 (match-string 1) category tags
19499 (if (= d0 d1) timestr))))
19500 (setq txt org-agenda-no-heading-message))
19501 (org-add-props txt props
19502 'org-marker marker 'org-hd-marker hdmarker
19503 'type "block" 'date date
19504 'priority (org-get-priority txt) 'org-category category)
19505 (push txt ee)))
19506 (goto-char pos)))
19507 ;; Sort the entries by expiration date.
19508 (nreverse ee)))
19510 ;;; Agenda presentation and sorting
19512 (defconst org-plain-time-of-day-regexp
19513 (concat
19514 "\\(\\<[012]?[0-9]"
19515 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
19516 "\\(--?"
19517 "\\(\\<[012]?[0-9]"
19518 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
19519 "\\)?")
19520 "Regular expression to match a plain time or time range.
19521 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
19522 groups carry important information:
19523 0 the full match
19524 1 the first time, range or not
19525 8 the second time, if it is a range.")
19527 (defconst org-plain-time-extension-regexp
19528 (concat
19529 "\\(\\<[012]?[0-9]"
19530 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
19531 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
19532 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
19533 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
19534 groups carry important information:
19535 0 the full match
19536 7 hours of duration
19537 9 minutes of duration")
19539 (defconst org-stamp-time-of-day-regexp
19540 (concat
19541 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
19542 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
19543 "\\(--?"
19544 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
19545 "Regular expression to match a timestamp time or time range.
19546 After a match, the following groups carry important information:
19547 0 the full match
19548 1 date plus weekday, for backreferencing to make sure both times on same day
19549 2 the first time, range or not
19550 4 the second time, if it is a range.")
19552 (defvar org-prefix-has-time nil
19553 "A flag, set by `org-compile-prefix-format'.
19554 The flag is set if the currently compiled format contains a `%t'.")
19555 (defvar org-prefix-has-tag nil
19556 "A flag, set by `org-compile-prefix-format'.
19557 The flag is set if the currently compiled format contains a `%T'.")
19559 (defun org-format-agenda-item (extra txt &optional category tags dotime
19560 noprefix remove-re)
19561 "Format TXT to be inserted into the agenda buffer.
19562 In particular, it adds the prefix and corresponding text properties. EXTRA
19563 must be a string and replaces the `%s' specifier in the prefix format.
19564 CATEGORY (string, symbol or nil) may be used to overrule the default
19565 category taken from local variable or file name. It will replace the `%c'
19566 specifier in the format. DOTIME, when non-nil, indicates that a
19567 time-of-day should be extracted from TXT for sorting of this entry, and for
19568 the `%t' specifier in the format. When DOTIME is a string, this string is
19569 searched for a time before TXT is. NOPREFIX is a flag and indicates that
19570 only the correctly processes TXT should be returned - this is used by
19571 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
19572 Any match of REMOVE-RE will be removed from TXT."
19573 (save-match-data
19574 ;; Diary entries sometimes have extra whitespace at the beginning
19575 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
19576 (let* ((category (or category
19577 org-category
19578 (if buffer-file-name
19579 (file-name-sans-extension
19580 (file-name-nondirectory buffer-file-name))
19581 "")))
19582 (tag (if tags (nth (1- (length tags)) tags) ""))
19583 time ; time and tag are needed for the eval of the prefix format
19584 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
19585 (time-of-day (and dotime (org-get-time-of-day ts)))
19586 stamp plain s0 s1 s2 rtn srp)
19587 (when (and dotime time-of-day org-prefix-has-time)
19588 ;; Extract starting and ending time and move them to prefix
19589 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
19590 (setq plain (string-match org-plain-time-of-day-regexp ts)))
19591 (setq s0 (match-string 0 ts)
19592 srp (and stamp (match-end 3))
19593 s1 (match-string (if plain 1 2) ts)
19594 s2 (match-string (if plain 8 (if srp 4 6)) ts))
19596 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
19597 ;; them, we might want to remove them there to avoid duplication.
19598 ;; The user can turn this off with a variable.
19599 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
19600 (string-match (concat (regexp-quote s0) " *") txt)
19601 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
19602 (= (match-beginning 0) 0)
19604 (setq txt (replace-match "" nil nil txt))))
19605 ;; Normalize the time(s) to 24 hour
19606 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
19607 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
19609 (when (and s1 (not s2) org-agenda-default-appointment-duration
19610 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
19611 (let ((m (+ (string-to-number (match-string 2 s1))
19612 (* 60 (string-to-number (match-string 1 s1)))
19613 org-agenda-default-appointment-duration))
19615 (setq h (/ m 60) m (- m (* h 60)))
19616 (setq s2 (format "%02d:%02d" h m))))
19618 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
19619 txt)
19620 ;; Tags are in the string
19621 (if (or (eq org-agenda-remove-tags t)
19622 (and org-agenda-remove-tags
19623 org-prefix-has-tag))
19624 (setq txt (replace-match "" t t txt))
19625 (setq txt (replace-match
19626 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
19627 (match-string 2 txt))
19628 t t txt))))
19630 (when remove-re
19631 (while (string-match remove-re txt)
19632 (setq txt (replace-match "" t t txt))))
19634 ;; Create the final string
19635 (if noprefix
19636 (setq rtn txt)
19637 ;; Prepare the variables needed in the eval of the compiled format
19638 (setq time (cond (s2 (concat s1 "-" s2))
19639 (s1 (concat s1 "......"))
19640 (t ""))
19641 extra (or extra "")
19642 category (if (symbolp category) (symbol-name category) category))
19643 ;; Evaluate the compiled format
19644 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
19646 ;; And finally add the text properties
19647 (org-add-props rtn nil
19648 'org-category (downcase category) 'tags tags
19649 'org-highest-priority org-highest-priority
19650 'org-lowest-priority org-lowest-priority
19651 'prefix-length (- (length rtn) (length txt))
19652 'time-of-day time-of-day
19653 'txt txt
19654 'time time
19655 'extra extra
19656 'dotime dotime))))
19658 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
19659 (defvar org-agenda-sorting-strategy-selected nil)
19661 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
19662 (catch 'exit
19663 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
19664 ((and todayp (member 'today (car org-agenda-time-grid))))
19665 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
19666 ((member 'weekly (car org-agenda-time-grid)))
19667 (t (throw 'exit list)))
19668 (let* ((have (delq nil (mapcar
19669 (lambda (x) (get-text-property 1 'time-of-day x))
19670 list)))
19671 (string (nth 1 org-agenda-time-grid))
19672 (gridtimes (nth 2 org-agenda-time-grid))
19673 (req (car org-agenda-time-grid))
19674 (remove (member 'remove-match req))
19675 new time)
19676 (if (and (member 'require-timed req) (not have))
19677 ;; don't show empty grid
19678 (throw 'exit list))
19679 (while (setq time (pop gridtimes))
19680 (unless (and remove (member time have))
19681 (setq time (int-to-string time))
19682 (push (org-format-agenda-item
19683 nil string "" nil
19684 (concat (substring time 0 -2) ":" (substring time -2)))
19685 new)
19686 (put-text-property
19687 1 (length (car new)) 'face 'org-time-grid (car new))))
19688 (if (member 'time-up org-agenda-sorting-strategy-selected)
19689 (append new list)
19690 (append list new)))))
19692 (defun org-compile-prefix-format (key)
19693 "Compile the prefix format into a Lisp form that can be evaluated.
19694 The resulting form is returned and stored in the variable
19695 `org-prefix-format-compiled'."
19696 (setq org-prefix-has-time nil org-prefix-has-tag nil)
19697 (let ((s (cond
19698 ((stringp org-agenda-prefix-format)
19699 org-agenda-prefix-format)
19700 ((assq key org-agenda-prefix-format)
19701 (cdr (assq key org-agenda-prefix-format)))
19702 (t " %-12:c%?-12t% s")))
19703 (start 0)
19704 varform vars var e c f opt)
19705 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
19706 s start)
19707 (setq var (cdr (assoc (match-string 4 s)
19708 '(("c" . category) ("t" . time) ("s" . extra)
19709 ("T" . tag))))
19710 c (or (match-string 3 s) "")
19711 opt (match-beginning 1)
19712 start (1+ (match-beginning 0)))
19713 (if (equal var 'time) (setq org-prefix-has-time t))
19714 (if (equal var 'tag) (setq org-prefix-has-tag t))
19715 (setq f (concat "%" (match-string 2 s) "s"))
19716 (if opt
19717 (setq varform
19718 `(if (equal "" ,var)
19720 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
19721 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
19722 (setq s (replace-match "%s" t nil s))
19723 (push varform vars))
19724 (setq vars (nreverse vars))
19725 (setq org-prefix-format-compiled `(format ,s ,@vars))))
19727 (defun org-set-sorting-strategy (key)
19728 (if (symbolp (car org-agenda-sorting-strategy))
19729 ;; the old format
19730 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
19731 (setq org-agenda-sorting-strategy-selected
19732 (or (cdr (assq key org-agenda-sorting-strategy))
19733 (cdr (assq 'agenda org-agenda-sorting-strategy))
19734 '(time-up category-keep priority-down)))))
19736 (defun org-get-time-of-day (s &optional string mod24)
19737 "Check string S for a time of day.
19738 If found, return it as a military time number between 0 and 2400.
19739 If not found, return nil.
19740 The optional STRING argument forces conversion into a 5 character wide string
19741 HH:MM."
19742 (save-match-data
19743 (when
19744 (and (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
19745 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
19746 (not (equal (string-to-char (substring s (match-end 0))) ?\])))
19747 (let* ((h (string-to-number (match-string 1 s)))
19748 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
19749 (ampm (if (match-end 4) (downcase (match-string 4 s))))
19750 (am-p (equal ampm "am"))
19751 (h1 (cond ((not ampm) h)
19752 ((= h 12) (if am-p 0 12))
19753 (t (+ h (if am-p 0 12)))))
19754 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
19755 (mod h1 24) h1))
19756 (t0 (+ (* 100 h2) m))
19757 (t1 (concat (if (>= h1 24) "+" " ")
19758 (if (< t0 100) "0" "")
19759 (if (< t0 10) "0" "")
19760 (int-to-string t0))))
19761 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
19763 (defun org-finalize-agenda-entries (list &optional nosort)
19764 "Sort and concatenate the agenda items."
19765 (setq list (mapcar 'org-agenda-highlight-todo list))
19766 (if nosort
19767 list
19768 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
19770 (defun org-agenda-highlight-todo (x)
19771 (let (re pl)
19772 (if (eq x 'line)
19773 (save-excursion
19774 (beginning-of-line 1)
19775 (setq re (get-text-property (point) 'org-todo-regexp))
19776 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
19777 (and (looking-at (concat "[ \t]*\\.*" re))
19778 (add-text-properties (match-beginning 0) (match-end 0)
19779 (list 'face (org-get-todo-face 0)))))
19780 (setq re (concat (get-text-property 0 'org-todo-regexp x))
19781 pl (get-text-property 0 'prefix-length x))
19782 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
19783 (add-text-properties
19784 (or (match-end 1) (match-end 0)) (match-end 0)
19785 (list 'face (org-get-todo-face (match-string 2 x)))
19787 x)))
19789 (defsubst org-cmp-priority (a b)
19790 "Compare the priorities of string A and B."
19791 (let ((pa (or (get-text-property 1 'priority a) 0))
19792 (pb (or (get-text-property 1 'priority b) 0)))
19793 (cond ((> pa pb) +1)
19794 ((< pa pb) -1)
19795 (t nil))))
19797 (defsubst org-cmp-category (a b)
19798 "Compare the string values of categories of strings A and B."
19799 (let ((ca (or (get-text-property 1 'org-category a) ""))
19800 (cb (or (get-text-property 1 'org-category b) "")))
19801 (cond ((string-lessp ca cb) -1)
19802 ((string-lessp cb ca) +1)
19803 (t nil))))
19805 (defsubst org-cmp-tag (a b)
19806 "Compare the string values of categories of strings A and B."
19807 (let ((ta (car (last (get-text-property 1 'tags a))))
19808 (tb (car (last (get-text-property 1 'tags b)))))
19809 (cond ((not ta) +1)
19810 ((not tb) -1)
19811 ((string-lessp ta tb) -1)
19812 ((string-lessp tb ta) +1)
19813 (t nil))))
19815 (defsubst org-cmp-time (a b)
19816 "Compare the time-of-day values of strings A and B."
19817 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
19818 (ta (or (get-text-property 1 'time-of-day a) def))
19819 (tb (or (get-text-property 1 'time-of-day b) def)))
19820 (cond ((< ta tb) -1)
19821 ((< tb ta) +1)
19822 (t nil))))
19824 (defun org-entries-lessp (a b)
19825 "Predicate for sorting agenda entries."
19826 ;; The following variables will be used when the form is evaluated.
19827 ;; So even though the compiler complains, keep them.
19828 (let* ((time-up (org-cmp-time a b))
19829 (time-down (if time-up (- time-up) nil))
19830 (priority-up (org-cmp-priority a b))
19831 (priority-down (if priority-up (- priority-up) nil))
19832 (category-up (org-cmp-category a b))
19833 (category-down (if category-up (- category-up) nil))
19834 (category-keep (if category-up +1 nil))
19835 (tag-up (org-cmp-tag a b))
19836 (tag-down (if tag-up (- tag-up) nil)))
19837 (cdr (assoc
19838 (eval (cons 'or org-agenda-sorting-strategy-selected))
19839 '((-1 . t) (1 . nil) (nil . nil))))))
19841 ;;; Agenda commands
19843 (defun org-agenda-check-type (error &rest types)
19844 "Check if agenda buffer is of allowed type.
19845 If ERROR is non-nil, throw an error, otherwise just return nil."
19846 (if (memq org-agenda-type types)
19848 (if error
19849 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
19850 nil)))
19852 (defun org-agenda-quit ()
19853 "Exit agenda by removing the window or the buffer."
19854 (interactive)
19855 (let ((buf (current-buffer)))
19856 (if (not (one-window-p)) (delete-window))
19857 (kill-buffer buf)
19858 (org-agenda-maybe-reset-markers 'force)
19859 (org-columns-remove-overlays))
19860 ;; Maybe restore the pre-agenda window configuration.
19861 (and org-agenda-restore-windows-after-quit
19862 (not (eq org-agenda-window-setup 'other-frame))
19863 org-pre-agenda-window-conf
19864 (set-window-configuration org-pre-agenda-window-conf)))
19866 (defun org-agenda-exit ()
19867 "Exit agenda by removing the window or the buffer.
19868 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
19869 Org-mode buffers visited directly by the user will not be touched."
19870 (interactive)
19871 (org-release-buffers org-agenda-new-buffers)
19872 (setq org-agenda-new-buffers nil)
19873 (org-agenda-quit))
19875 (defun org-save-all-org-buffers ()
19876 "Save all Org-mode buffers without user confirmation."
19877 (interactive)
19878 (message "Saving all Org-mode buffers...")
19879 (save-some-buffers t 'org-mode-p)
19880 (message "Saving all Org-mode buffers... done"))
19882 (defun org-agenda-redo ()
19883 "Rebuild Agenda.
19884 When this is the global TODO list, a prefix argument will be interpreted."
19885 (interactive)
19886 (let* ((org-agenda-keep-modes t)
19887 (line (org-current-line))
19888 (window-line (- line (org-current-line (window-start))))
19889 (lprops (get 'org-agenda-redo-command 'org-lprops)))
19890 (message "Rebuilding agenda buffer...")
19891 (org-let lprops '(eval org-agenda-redo-command))
19892 (setq org-agenda-undo-list nil
19893 org-agenda-pending-undo-list nil)
19894 (message "Rebuilding agenda buffer...done")
19895 (goto-line line)
19896 (recenter window-line)))
19898 (defun org-agenda-goto-date (date)
19899 "Jump to DATE in agenda."
19900 (interactive (list (org-read-date)))
19901 (org-agenda-list nil date))
19903 (defun org-agenda-goto-today ()
19904 "Go to today."
19905 (interactive)
19906 (org-agenda-check-type t 'timeline 'agenda)
19907 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
19908 (cond
19909 (tdpos (goto-char tdpos))
19910 ((eq org-agenda-type 'agenda)
19911 (let* ((sd (time-to-days (current-time)))
19912 (comp (org-agenda-compute-time-span sd org-agenda-span))
19913 (org-agenda-overriding-arguments org-agenda-last-arguments))
19914 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
19915 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
19916 (org-agenda-redo)
19917 (org-agenda-find-same-or-today-or-agenda)))
19918 (t (error "Cannot find today")))))
19920 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
19921 (goto-char
19922 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
19923 (text-property-any (point-min) (point-max) 'org-today t)
19924 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
19925 (point-min))))
19927 (defun org-agenda-later (arg)
19928 "Go forward in time by thee current span.
19929 With prefix ARG, go forward that many times the current span."
19930 (interactive "p")
19931 (org-agenda-check-type t 'agenda)
19932 (let* ((span org-agenda-span)
19933 (sd org-starting-day)
19934 (greg (calendar-gregorian-from-absolute sd))
19935 (cnt (get-text-property (point) 'org-day-cnt))
19936 greg2 nd)
19937 (cond
19938 ((eq span 'day)
19939 (setq sd (+ arg sd) nd 1))
19940 ((eq span 'week)
19941 (setq sd (+ (* 7 arg) sd) nd 7))
19942 ((eq span 'month)
19943 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
19944 sd (calendar-absolute-from-gregorian greg2))
19945 (setcar greg2 (1+ (car greg2)))
19946 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
19947 ((eq span 'year)
19948 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
19949 sd (calendar-absolute-from-gregorian greg2))
19950 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
19951 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
19952 (let ((org-agenda-overriding-arguments
19953 (list (car org-agenda-last-arguments) sd nd t)))
19954 (org-agenda-redo)
19955 (org-agenda-find-same-or-today-or-agenda cnt))))
19957 (defun org-agenda-earlier (arg)
19958 "Go backward in time by the current span.
19959 With prefix ARG, go backward that many times the current span."
19960 (interactive "p")
19961 (org-agenda-later (- arg)))
19963 (defun org-agenda-day-view ()
19964 "Switch to daily view for agenda."
19965 (interactive)
19966 (setq org-agenda-ndays 1)
19967 (org-agenda-change-time-span 'day))
19968 (defun org-agenda-week-view ()
19969 "Switch to daily view for agenda."
19970 (interactive)
19971 (setq org-agenda-ndays 7)
19972 (org-agenda-change-time-span 'week))
19973 (defun org-agenda-month-view ()
19974 "Switch to daily view for agenda."
19975 (interactive)
19976 (org-agenda-change-time-span 'month))
19977 (defun org-agenda-year-view ()
19978 "Switch to daily view for agenda."
19979 (interactive)
19980 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
19981 (org-agenda-change-time-span 'year)
19982 (error "Abort")))
19984 (defun org-agenda-change-time-span (span)
19985 "Change the agenda view to SPAN.
19986 SPAN may be `day', `week', `month', `year'."
19987 (org-agenda-check-type t 'agenda)
19988 (if (equal org-agenda-span span)
19989 (error "Viewing span is already \"%s\"" span))
19990 (let* ((sd (or (get-text-property (point) 'day)
19991 org-starting-day))
19992 (computed (org-agenda-compute-time-span sd span))
19993 (org-agenda-overriding-arguments
19994 (list (car org-agenda-last-arguments)
19995 (car computed) (cdr computed) t)))
19996 (org-agenda-redo)
19997 (org-agenda-find-same-or-today-or-agenda))
19998 (org-agenda-set-mode-name)
19999 (message "Switched to %s view" span))
20001 (defun org-agenda-compute-time-span (sd span)
20002 "Compute starting date and number of days for agenda.
20003 SPAN may be `day', `week', `month', `year'. The return value
20004 is a cons cell with the starting date and the number of days,
20005 so that the date SD will be in that range."
20006 (let* ((greg (calendar-gregorian-from-absolute sd))
20008 (cond
20009 ((eq span 'day)
20010 (setq nd 1))
20011 ((eq span 'week)
20012 (let* ((nt (calendar-day-of-week
20013 (calendar-gregorian-from-absolute sd)))
20014 (d (if org-agenda-start-on-weekday
20015 (- nt org-agenda-start-on-weekday)
20016 0)))
20017 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
20018 (setq nd 7)))
20019 ((eq span 'month)
20020 (setq sd (calendar-absolute-from-gregorian
20021 (list (car greg) 1 (nth 2 greg)))
20022 nd (- (calendar-absolute-from-gregorian
20023 (list (1+ (car greg)) 1 (nth 2 greg)))
20024 sd)))
20025 ((eq span 'year)
20026 (setq sd (calendar-absolute-from-gregorian
20027 (list 1 1 (nth 2 greg)))
20028 nd (- (calendar-absolute-from-gregorian
20029 (list 1 1 (1+ (nth 2 greg))))
20030 sd))))
20031 (cons sd nd)))
20033 ;; FIXME: does not work if user makes date format that starts with a blank
20034 (defun org-agenda-next-date-line (&optional arg)
20035 "Jump to the next line indicating a date in agenda buffer."
20036 (interactive "p")
20037 (org-agenda-check-type t 'agenda 'timeline)
20038 (beginning-of-line 1)
20039 (if (looking-at "^\\S-") (forward-char 1))
20040 (if (not (re-search-forward "^\\S-" nil t arg))
20041 (progn
20042 (backward-char 1)
20043 (error "No next date after this line in this buffer")))
20044 (goto-char (match-beginning 0)))
20046 (defun org-agenda-previous-date-line (&optional arg)
20047 "Jump to the previous line indicating a date in agenda buffer."
20048 (interactive "p")
20049 (org-agenda-check-type t 'agenda 'timeline)
20050 (beginning-of-line 1)
20051 (if (not (re-search-backward "^\\S-" nil t arg))
20052 (error "No previous date before this line in this buffer")))
20054 ;; Initialize the highlight
20055 (defvar org-hl (org-make-overlay 1 1))
20056 (org-overlay-put org-hl 'face 'highlight)
20058 (defun org-highlight (begin end &optional buffer)
20059 "Highlight a region with overlay."
20060 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
20061 org-hl begin end (or buffer (current-buffer))))
20063 (defun org-unhighlight ()
20064 "Detach overlay INDEX."
20065 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
20067 ;; FIXME this is currently not used.
20068 (defun org-highlight-until-next-command (beg end &optional buffer)
20069 (org-highlight beg end buffer)
20070 (add-hook 'pre-command-hook 'org-unhighlight-once))
20071 (defun org-unhighlight-once ()
20072 (remove-hook 'pre-command-hook 'org-unhighlight-once)
20073 (org-unhighlight))
20075 (defun org-agenda-follow-mode ()
20076 "Toggle follow mode in an agenda buffer."
20077 (interactive)
20078 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
20079 (org-agenda-set-mode-name)
20080 (message "Follow mode is %s"
20081 (if org-agenda-follow-mode "on" "off")))
20083 (defun org-agenda-log-mode ()
20084 "Toggle log mode in an agenda buffer."
20085 (interactive)
20086 (org-agenda-check-type t 'agenda 'timeline)
20087 (setq org-agenda-show-log (not org-agenda-show-log))
20088 (org-agenda-set-mode-name)
20089 (org-agenda-redo)
20090 (message "Log mode is %s"
20091 (if org-agenda-show-log "on" "off")))
20093 (defun org-agenda-toggle-diary ()
20094 "Toggle diary inclusion in an agenda buffer."
20095 (interactive)
20096 (org-agenda-check-type t 'agenda)
20097 (setq org-agenda-include-diary (not org-agenda-include-diary))
20098 (org-agenda-redo)
20099 (org-agenda-set-mode-name)
20100 (message "Diary inclusion turned %s"
20101 (if org-agenda-include-diary "on" "off")))
20103 (defun org-agenda-toggle-time-grid ()
20104 "Toggle time grid in an agenda buffer."
20105 (interactive)
20106 (org-agenda-check-type t 'agenda)
20107 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
20108 (org-agenda-redo)
20109 (org-agenda-set-mode-name)
20110 (message "Time-grid turned %s"
20111 (if org-agenda-use-time-grid "on" "off")))
20113 (defun org-agenda-set-mode-name ()
20114 "Set the mode name to indicate all the small mode settings."
20115 (setq mode-name
20116 (concat "Org-Agenda"
20117 (if (equal org-agenda-ndays 1) " Day" "")
20118 (if (equal org-agenda-ndays 7) " Week" "")
20119 (if org-agenda-follow-mode " Follow" "")
20120 (if org-agenda-include-diary " Diary" "")
20121 (if org-agenda-use-time-grid " Grid" "")
20122 (if org-agenda-show-log " Log" "")))
20123 (force-mode-line-update))
20125 (defun org-agenda-post-command-hook ()
20126 (and (eolp) (not (bolp)) (backward-char 1))
20127 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20128 (if (and org-agenda-follow-mode
20129 (get-text-property (point) 'org-marker))
20130 (org-agenda-show)))
20132 (defun org-agenda-show-priority ()
20133 "Show the priority of the current item.
20134 This priority is composed of the main priority given with the [#A] cookies,
20135 and by additional input from the age of a schedules or deadline entry."
20136 (interactive)
20137 (let* ((pri (get-text-property (point-at-bol) 'priority)))
20138 (message "Priority is %d" (if pri pri -1000))))
20140 (defun org-agenda-show-tags ()
20141 "Show the tags applicable to the current item."
20142 (interactive)
20143 (let* ((tags (get-text-property (point-at-bol) 'tags)))
20144 (if tags
20145 (message "Tags are :%s:"
20146 (org-no-properties (mapconcat 'identity tags ":")))
20147 (message "No tags associated with this line"))))
20149 (defun org-agenda-goto (&optional highlight)
20150 "Go to the Org-mode file which contains the item at point."
20151 (interactive)
20152 (let* ((marker (or (get-text-property (point) 'org-marker)
20153 (org-agenda-error)))
20154 (buffer (marker-buffer marker))
20155 (pos (marker-position marker)))
20156 (switch-to-buffer-other-window buffer)
20157 (widen)
20158 (goto-char pos)
20159 (when (org-mode-p)
20160 (org-show-context 'agenda)
20161 (save-excursion
20162 (and (outline-next-heading)
20163 (org-flag-heading nil)))) ; show the next heading
20164 (run-hooks 'org-agenda-after-show-hook)
20165 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
20167 (defvar org-agenda-after-show-hook nil
20168 "Normal hook run after an item has been shown from the agenda.
20169 Point is in the buffer where the item originated.")
20171 (defun org-agenda-kill ()
20172 "Kill the entry or subtree belonging to the current agenda entry."
20173 (interactive)
20174 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
20175 (let* ((marker (or (get-text-property (point) 'org-marker)
20176 (org-agenda-error)))
20177 (buffer (marker-buffer marker))
20178 (pos (marker-position marker))
20179 (type (get-text-property (point) 'type))
20180 dbeg dend (n 0) conf)
20181 (org-with-remote-undo buffer
20182 (with-current-buffer buffer
20183 (save-excursion
20184 (goto-char pos)
20185 (if (and (org-mode-p) (not (member type '("sexp"))))
20186 (setq dbeg (progn (org-back-to-heading t) (point))
20187 dend (org-end-of-subtree t t))
20188 (setq dbeg (point-at-bol)
20189 dend (min (point-max) (1+ (point-at-eol)))))
20190 (goto-char dbeg)
20191 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
20192 (setq conf (or (eq t org-agenda-confirm-kill)
20193 (and (numberp org-agenda-confirm-kill)
20194 (> n org-agenda-confirm-kill))))
20195 (and conf
20196 (not (y-or-n-p
20197 (format "Delete entry with %d lines in buffer \"%s\"? "
20198 n (buffer-name buffer))))
20199 (error "Abort"))
20200 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
20201 (with-current-buffer buffer (delete-region dbeg dend))
20202 (message "Agenda item and source killed"))))
20204 (defun org-agenda-archive ()
20205 "Kill the entry or subtree belonging to the current agenda entry."
20206 (interactive)
20207 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
20208 (let* ((marker (or (get-text-property (point) 'org-marker)
20209 (org-agenda-error)))
20210 (buffer (marker-buffer marker))
20211 (pos (marker-position marker)))
20212 (org-with-remote-undo buffer
20213 (with-current-buffer buffer
20214 (if (org-mode-p)
20215 (save-excursion
20216 (goto-char pos)
20217 (org-remove-subtree-entries-from-agenda)
20218 (org-back-to-heading t)
20219 (org-archive-subtree))
20220 (error "Archiving works only in Org-mode files"))))))
20222 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
20223 "Remove all lines in the agenda that correspond to a given subtree.
20224 The subtree is the one in buffer BUF, starting at BEG and ending at END.
20225 If this information is not given, the function uses the tree at point."
20226 (let ((buf (or buf (current-buffer))) m p)
20227 (save-excursion
20228 (unless (and beg end)
20229 (org-back-to-heading t)
20230 (setq beg (point))
20231 (org-end-of-subtree t)
20232 (setq end (point)))
20233 (set-buffer (get-buffer org-agenda-buffer-name))
20234 (save-excursion
20235 (goto-char (point-max))
20236 (beginning-of-line 1)
20237 (while (not (bobp))
20238 (when (and (setq m (get-text-property (point) 'org-marker))
20239 (equal buf (marker-buffer m))
20240 (setq p (marker-position m))
20241 (>= p beg)
20242 (<= p end))
20243 (let ((inhibit-read-only t))
20244 (delete-region (point-at-bol) (1+ (point-at-eol)))))
20245 (beginning-of-line 0))))))
20247 (defun org-agenda-open-link ()
20248 "Follow the link in the current line, if any."
20249 (interactive)
20250 (let ((eol (point-at-eol)))
20251 (save-excursion
20252 (if (or (re-search-forward org-bracket-link-regexp eol t)
20253 (re-search-forward org-angle-link-re eol t)
20254 (re-search-forward org-plain-link-re eol t))
20255 (call-interactively 'org-open-at-point)
20256 (error "No link in current line")))))
20258 (defun org-agenda-switch-to (&optional delete-other-windows)
20259 "Go to the Org-mode file which contains the item at point."
20260 (interactive)
20261 (let* ((marker (or (get-text-property (point) 'org-marker)
20262 (org-agenda-error)))
20263 (buffer (marker-buffer marker))
20264 (pos (marker-position marker)))
20265 (switch-to-buffer buffer)
20266 (and delete-other-windows (delete-other-windows))
20267 (widen)
20268 (goto-char pos)
20269 (when (org-mode-p)
20270 (org-show-context 'agenda)
20271 (save-excursion
20272 (and (outline-next-heading)
20273 (org-flag-heading nil)))))) ; show the next heading
20275 (defun org-agenda-goto-mouse (ev)
20276 "Go to the Org-mode file which contains the item at the mouse click."
20277 (interactive "e")
20278 (mouse-set-point ev)
20279 (org-agenda-goto))
20281 (defun org-agenda-show ()
20282 "Display the Org-mode file which contains the item at point."
20283 (interactive)
20284 (let ((win (selected-window)))
20285 (org-agenda-goto t)
20286 (select-window win)))
20288 (defun org-agenda-recenter (arg)
20289 "Display the Org-mode file which contains the item at point and recenter."
20290 (interactive "P")
20291 (let ((win (selected-window)))
20292 (org-agenda-goto t)
20293 (recenter arg)
20294 (select-window win)))
20296 (defun org-agenda-show-mouse (ev)
20297 "Display the Org-mode file which contains the item at the mouse click."
20298 (interactive "e")
20299 (mouse-set-point ev)
20300 (org-agenda-show))
20302 (defun org-agenda-check-no-diary ()
20303 "Check if the entry is a diary link and abort if yes."
20304 (if (get-text-property (point) 'org-agenda-diary-link)
20305 (org-agenda-error)))
20307 (defun org-agenda-error ()
20308 (error "Command not allowed in this line"))
20310 (defun org-agenda-tree-to-indirect-buffer ()
20311 "Show the subtree corresponding to the current entry in an indirect buffer.
20312 This calls the command `org-tree-to-indirect-buffer' from the original
20313 Org-mode buffer.
20314 With numerical prefix arg ARG, go up to this level and then take that tree.
20315 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
20316 dedicated frame)."
20317 (interactive)
20318 (org-agenda-check-no-diary)
20319 (let* ((marker (or (get-text-property (point) 'org-marker)
20320 (org-agenda-error)))
20321 (buffer (marker-buffer marker))
20322 (pos (marker-position marker)))
20323 (with-current-buffer buffer
20324 (save-excursion
20325 (goto-char pos)
20326 (call-interactively 'org-tree-to-indirect-buffer)))))
20328 (defvar org-last-heading-marker (make-marker)
20329 "Marker pointing to the headline that last changed its TODO state
20330 by a remote command from the agenda.")
20332 (defun org-agenda-todo-nextset ()
20333 "Switch TODO entry to next sequence."
20334 (interactive)
20335 (org-agenda-todo 'nextset))
20337 (defun org-agenda-todo-previousset ()
20338 "Switch TODO entry to previous sequence."
20339 (interactive)
20340 (org-agenda-todo 'previousset))
20342 (defun org-agenda-todo (&optional arg)
20343 "Cycle TODO state of line at point, also in Org-mode file.
20344 This changes the line at point, all other lines in the agenda referring to
20345 the same tree node, and the headline of the tree node in the Org-mode file."
20346 (interactive "P")
20347 (org-agenda-check-no-diary)
20348 (let* ((col (current-column))
20349 (marker (or (get-text-property (point) 'org-marker)
20350 (org-agenda-error)))
20351 (buffer (marker-buffer marker))
20352 (pos (marker-position marker))
20353 (hdmarker (get-text-property (point) 'org-hd-marker))
20354 (inhibit-read-only t)
20355 newhead)
20356 (org-with-remote-undo buffer
20357 (with-current-buffer buffer
20358 (widen)
20359 (goto-char pos)
20360 (org-show-context 'agenda)
20361 (save-excursion
20362 (and (outline-next-heading)
20363 (org-flag-heading nil))) ; show the next heading
20364 (org-todo arg)
20365 (and (bolp) (forward-char 1))
20366 (setq newhead (org-get-heading))
20367 (save-excursion
20368 (org-back-to-heading)
20369 (move-marker org-last-heading-marker (point))))
20370 (beginning-of-line 1)
20371 (save-excursion
20372 (org-agenda-change-all-lines newhead hdmarker 'fixface))
20373 (move-to-column col))))
20375 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
20376 "Change all lines in the agenda buffer which match HDMARKER.
20377 The new content of the line will be NEWHEAD (as modified by
20378 `org-format-agenda-item'). HDMARKER is checked with
20379 `equal' against all `org-hd-marker' text properties in the file.
20380 If FIXFACE is non-nil, the face of each item is modified acording to
20381 the new TODO state."
20382 (let* ((inhibit-read-only t)
20383 props m pl undone-face done-face finish new dotime cat tags)
20384 (save-excursion
20385 (goto-char (point-max))
20386 (beginning-of-line 1)
20387 (while (not finish)
20388 (setq finish (bobp))
20389 (when (and (setq m (get-text-property (point) 'org-hd-marker))
20390 (equal m hdmarker))
20391 (setq props (text-properties-at (point))
20392 dotime (get-text-property (point) 'dotime)
20393 cat (get-text-property (point) 'org-category)
20394 tags (get-text-property (point) 'tags)
20395 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
20396 pl (get-text-property (point) 'prefix-length)
20397 undone-face (get-text-property (point) 'undone-face)
20398 done-face (get-text-property (point) 'done-face))
20399 (move-to-column pl)
20400 (cond
20401 ((equal new "")
20402 (beginning-of-line 1)
20403 (and (looking-at ".*\n?") (replace-match "")))
20404 ((looking-at ".*")
20405 (replace-match new t t)
20406 (beginning-of-line 1)
20407 (add-text-properties (point-at-bol) (point-at-eol) props)
20408 (when fixface
20409 (add-text-properties
20410 (point-at-bol) (point-at-eol)
20411 (list 'face
20412 (if org-last-todo-state-is-todo
20413 undone-face done-face))))
20414 (org-agenda-highlight-todo 'line)
20415 (beginning-of-line 1))
20416 (t (error "Line update did not work"))))
20417 (beginning-of-line 0)))
20418 (org-finalize-agenda)))
20420 (defun org-agenda-align-tags (&optional line)
20421 "Align all tags in agenda items to `org-agenda-tags-column'."
20422 (let ((inhibit-read-only t) l c)
20423 (save-excursion
20424 (goto-char (if line (point-at-bol) (point-min)))
20425 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
20426 (if line (point-at-eol) nil) t)
20427 (add-text-properties
20428 (match-beginning 2) (match-end 2)
20429 (list 'face (list 'org-tag (get-text-property
20430 (match-beginning 2) 'face))))
20431 (setq l (- (match-end 2) (match-beginning 2))
20432 c (if (< org-agenda-tags-column 0)
20433 (- (abs org-agenda-tags-column) l)
20434 org-agenda-tags-column))
20435 (delete-region (match-beginning 1) (match-end 1))
20436 (goto-char (match-beginning 1))
20437 (insert (org-add-props
20438 (make-string (max 1 (- c (current-column))) ?\ )
20439 (text-properties-at (point))))))))
20441 (defun org-agenda-priority-up ()
20442 "Increase the priority of line at point, also in Org-mode file."
20443 (interactive)
20444 (org-agenda-priority 'up))
20446 (defun org-agenda-priority-down ()
20447 "Decrease the priority of line at point, also in Org-mode file."
20448 (interactive)
20449 (org-agenda-priority 'down))
20451 (defun org-agenda-priority (&optional force-direction)
20452 "Set the priority of line at point, also in Org-mode file.
20453 This changes the line at point, all other lines in the agenda referring to
20454 the same tree node, and the headline of the tree node in the Org-mode file."
20455 (interactive)
20456 (org-agenda-check-no-diary)
20457 (let* ((marker (or (get-text-property (point) 'org-marker)
20458 (org-agenda-error)))
20459 (hdmarker (get-text-property (point) 'org-hd-marker))
20460 (buffer (marker-buffer hdmarker))
20461 (pos (marker-position hdmarker))
20462 (inhibit-read-only t)
20463 newhead)
20464 (org-with-remote-undo buffer
20465 (with-current-buffer buffer
20466 (widen)
20467 (goto-char pos)
20468 (org-show-context 'agenda)
20469 (save-excursion
20470 (and (outline-next-heading)
20471 (org-flag-heading nil))) ; show the next heading
20472 (funcall 'org-priority force-direction)
20473 (end-of-line 1)
20474 (setq newhead (org-get-heading)))
20475 (org-agenda-change-all-lines newhead hdmarker)
20476 (beginning-of-line 1))))
20478 (defun org-get-tags-at (&optional pos)
20479 "Get a list of all headline tags applicable at POS.
20480 POS defaults to point. If tags are inherited, the list contains
20481 the targets in the same sequence as the headlines appear, i.e.
20482 the tags of the current headline come last."
20483 (interactive)
20484 (let (tags lastpos)
20485 (save-excursion
20486 (save-restriction
20487 (widen)
20488 (goto-char (or pos (point)))
20489 (save-match-data
20490 (org-back-to-heading t)
20491 (condition-case nil
20492 (while (not (equal lastpos (point)))
20493 (setq lastpos (point))
20494 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
20495 (setq tags (append (org-split-string
20496 (org-match-string-no-properties 1) ":")
20497 tags)))
20498 (or org-use-tag-inheritance (error ""))
20499 (org-up-heading-all 1))
20500 (error nil))))
20501 tags)))
20503 ;; FIXME: should fix the tags property of the agenda line.
20504 (defun org-agenda-set-tags ()
20505 "Set tags for the current headline."
20506 (interactive)
20507 (org-agenda-check-no-diary)
20508 (if (and (org-region-active-p) (interactive-p))
20509 (call-interactively 'org-change-tag-in-region)
20510 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
20511 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
20512 (org-agenda-error)))
20513 (buffer (marker-buffer hdmarker))
20514 (pos (marker-position hdmarker))
20515 (inhibit-read-only t)
20516 newhead)
20517 (org-with-remote-undo buffer
20518 (with-current-buffer buffer
20519 (widen)
20520 (goto-char pos)
20521 (save-excursion
20522 (org-show-context 'agenda))
20523 (save-excursion
20524 (and (outline-next-heading)
20525 (org-flag-heading nil))) ; show the next heading
20526 (goto-char pos)
20527 (call-interactively 'org-set-tags)
20528 (end-of-line 1)
20529 (setq newhead (org-get-heading)))
20530 (org-agenda-change-all-lines newhead hdmarker)
20531 (beginning-of-line 1)))))
20533 (defun org-agenda-toggle-archive-tag ()
20534 "Toggle the archive tag for the current entry."
20535 (interactive)
20536 (org-agenda-check-no-diary)
20537 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
20538 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
20539 (org-agenda-error)))
20540 (buffer (marker-buffer hdmarker))
20541 (pos (marker-position hdmarker))
20542 (inhibit-read-only t)
20543 newhead)
20544 (org-with-remote-undo buffer
20545 (with-current-buffer buffer
20546 (widen)
20547 (goto-char pos)
20548 (org-show-context 'agenda)
20549 (save-excursion
20550 (and (outline-next-heading)
20551 (org-flag-heading nil))) ; show the next heading
20552 (call-interactively 'org-toggle-archive-tag)
20553 (end-of-line 1)
20554 (setq newhead (org-get-heading)))
20555 (org-agenda-change-all-lines newhead hdmarker)
20556 (beginning-of-line 1))))
20558 (defun org-agenda-date-later (arg &optional what)
20559 "Change the date of this item to one day later."
20560 (interactive "p")
20561 (org-agenda-check-type t 'agenda 'timeline)
20562 (org-agenda-check-no-diary)
20563 (let* ((marker (or (get-text-property (point) 'org-marker)
20564 (org-agenda-error)))
20565 (buffer (marker-buffer marker))
20566 (pos (marker-position marker)))
20567 (org-with-remote-undo buffer
20568 (with-current-buffer buffer
20569 (widen)
20570 (goto-char pos)
20571 (if (not (org-at-timestamp-p))
20572 (error "Cannot find time stamp"))
20573 (org-timestamp-change arg (or what 'day)))
20574 (org-agenda-show-new-time marker org-last-changed-timestamp))
20575 (message "Time stamp changed to %s" org-last-changed-timestamp)))
20577 (defun org-agenda-date-earlier (arg &optional what)
20578 "Change the date of this item to one day earlier."
20579 (interactive "p")
20580 (org-agenda-date-later (- arg) what))
20582 (defun org-agenda-show-new-time (marker stamp &optional prefix)
20583 "Show new date stamp via text properties."
20584 ;; We use text properties to make this undoable
20585 (let ((inhibit-read-only t))
20586 (setq stamp (concat " " prefix " => " stamp))
20587 (save-excursion
20588 (goto-char (point-max))
20589 (while (not (bobp))
20590 (when (equal marker (get-text-property (point) 'org-marker))
20591 (move-to-column (- (window-width) (length stamp)) t)
20592 (if (featurep 'xemacs)
20593 ;; Use `duplicable' property to trigger undo recording
20594 (let ((ex (make-extent nil nil))
20595 (gl (make-glyph stamp)))
20596 (set-glyph-face gl 'secondary-selection)
20597 (set-extent-properties
20598 ex (list 'invisible t 'end-glyph gl 'duplicable t))
20599 (insert-extent ex (1- (point)) (point-at-eol)))
20600 (add-text-properties
20601 (1- (point)) (point-at-eol)
20602 (list 'display (org-add-props stamp nil
20603 'face 'secondary-selection))))
20604 (beginning-of-line 1))
20605 (beginning-of-line 0)))))
20607 (defun org-agenda-date-prompt (arg)
20608 "Change the date of this item. Date is prompted for, with default today.
20609 The prefix ARG is passed to the `org-time-stamp' command and can therefore
20610 be used to request time specification in the time stamp."
20611 (interactive "P")
20612 (org-agenda-check-type t 'agenda 'timeline)
20613 (org-agenda-check-no-diary)
20614 (let* ((marker (or (get-text-property (point) 'org-marker)
20615 (org-agenda-error)))
20616 (buffer (marker-buffer marker))
20617 (pos (marker-position marker)))
20618 (org-with-remote-undo buffer
20619 (with-current-buffer buffer
20620 (widen)
20621 (goto-char pos)
20622 (if (not (org-at-timestamp-p))
20623 (error "Cannot find time stamp"))
20624 (org-time-stamp arg)
20625 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
20627 (defun org-agenda-schedule (arg)
20628 "Schedule the item at point."
20629 (interactive "P")
20630 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
20631 (org-agenda-check-no-diary)
20632 (let* ((marker (or (get-text-property (point) 'org-marker)
20633 (org-agenda-error)))
20634 (buffer (marker-buffer marker))
20635 (pos (marker-position marker))
20636 (org-insert-labeled-timestamps-at-point nil)
20638 (org-with-remote-undo buffer
20639 (with-current-buffer buffer
20640 (widen)
20641 (goto-char pos)
20642 (setq ts (org-schedule arg)))
20643 (org-agenda-show-new-time marker ts "S"))
20644 (message "Item scheduled for %s" ts)))
20646 (defun org-agenda-deadline (arg)
20647 "Schedule the item at point."
20648 (interactive "P")
20649 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
20650 (org-agenda-check-no-diary)
20651 (let* ((marker (or (get-text-property (point) 'org-marker)
20652 (org-agenda-error)))
20653 (buffer (marker-buffer marker))
20654 (pos (marker-position marker))
20655 (org-insert-labeled-timestamps-at-point nil)
20657 (org-with-remote-undo buffer
20658 (with-current-buffer buffer
20659 (widen)
20660 (goto-char pos)
20661 (setq ts (org-deadline arg)))
20662 (org-agenda-show-new-time marker ts "S"))
20663 (message "Deadline for this item set to %s" ts)))
20665 (defun org-get-heading (&optional no-tags)
20666 "Return the heading of the current entry, without the stars."
20667 (save-excursion
20668 (org-back-to-heading t)
20669 (if (looking-at
20670 (if no-tags
20671 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
20672 "\\*+[ \t]+\\([^\r\n]*\\)"))
20673 (match-string 1) "")))
20675 (defun org-agenda-clock-in (&optional arg)
20676 "Start the clock on the currently selected item."
20677 (interactive "P")
20678 (org-agenda-check-no-diary)
20679 (let* ((marker (or (get-text-property (point) 'org-marker)
20680 (org-agenda-error)))
20681 (pos (marker-position marker)))
20682 (org-with-remote-undo (marker-buffer marker)
20683 (with-current-buffer (marker-buffer marker)
20684 (widen)
20685 (goto-char pos)
20686 (org-clock-in)))))
20688 (defun org-agenda-clock-out (&optional arg)
20689 "Stop the currently running clock."
20690 (interactive "P")
20691 (unless (marker-buffer org-clock-marker)
20692 (error "No running clock"))
20693 (org-with-remote-undo (marker-buffer org-clock-marker)
20694 (org-clock-out)))
20696 (defun org-agenda-clock-cancel (&optional arg)
20697 "Cancel the currently running clock."
20698 (interactive "P")
20699 (unless (marker-buffer org-clock-marker)
20700 (error "No running clock"))
20701 (org-with-remote-undo (marker-buffer org-clock-marker)
20702 (org-clock-cancel)))
20704 (defun org-agenda-diary-entry ()
20705 "Make a diary entry, like the `i' command from the calendar.
20706 All the standard commands work: block, weekly etc."
20707 (interactive)
20708 (org-agenda-check-type t 'agenda 'timeline)
20709 (require 'diary-lib)
20710 (let* ((char (progn
20711 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
20712 (read-char-exclusive)))
20713 (cmd (cdr (assoc char
20714 '((?d . insert-diary-entry)
20715 (?w . insert-weekly-diary-entry)
20716 (?m . insert-monthly-diary-entry)
20717 (?y . insert-yearly-diary-entry)
20718 (?a . insert-anniversary-diary-entry)
20719 (?b . insert-block-diary-entry)
20720 (?c . insert-cyclic-diary-entry)))))
20721 (oldf (symbol-function 'calendar-cursor-to-date))
20722 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
20723 (point (point))
20724 (mark (or (mark t) (point))))
20725 (unless cmd
20726 (error "No command associated with <%c>" char))
20727 (unless (and (get-text-property point 'day)
20728 (or (not (equal ?b char))
20729 (get-text-property mark 'day)))
20730 (error "Don't know which date to use for diary entry"))
20731 ;; We implement this by hacking the `calendar-cursor-to-date' function
20732 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
20733 (let ((calendar-mark-ring
20734 (list (calendar-gregorian-from-absolute
20735 (or (get-text-property mark 'day)
20736 (get-text-property point 'day))))))
20737 (unwind-protect
20738 (progn
20739 (fset 'calendar-cursor-to-date
20740 (lambda (&optional error)
20741 (calendar-gregorian-from-absolute
20742 (get-text-property point 'day))))
20743 (call-interactively cmd))
20744 (fset 'calendar-cursor-to-date oldf)))))
20747 (defun org-agenda-execute-calendar-command (cmd)
20748 "Execute a calendar command from the agenda, with the date associated to
20749 the cursor position."
20750 (org-agenda-check-type t 'agenda 'timeline)
20751 (require 'diary-lib)
20752 (unless (get-text-property (point) 'day)
20753 (error "Don't know which date to use for calendar command"))
20754 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
20755 (point (point))
20756 (date (calendar-gregorian-from-absolute
20757 (get-text-property point 'day)))
20758 ;; the following 3 vars are needed in the calendar
20759 (displayed-day (extract-calendar-day date))
20760 (displayed-month (extract-calendar-month date))
20761 (displayed-year (extract-calendar-year date)))
20762 (unwind-protect
20763 (progn
20764 (fset 'calendar-cursor-to-date
20765 (lambda (&optional error)
20766 (calendar-gregorian-from-absolute
20767 (get-text-property point 'day))))
20768 (call-interactively cmd))
20769 (fset 'calendar-cursor-to-date oldf))))
20771 (defun org-agenda-phases-of-moon ()
20772 "Display the phases of the moon for the 3 months around the cursor date."
20773 (interactive)
20774 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
20776 (defun org-agenda-holidays ()
20777 "Display the holidays for the 3 months around the cursor date."
20778 (interactive)
20779 (org-agenda-execute-calendar-command 'list-calendar-holidays))
20781 (defun org-agenda-sunrise-sunset (arg)
20782 "Display sunrise and sunset for the cursor date.
20783 Latitude and longitude can be specified with the variables
20784 `calendar-latitude' and `calendar-longitude'. When called with prefix
20785 argument, latitude and longitude will be prompted for."
20786 (interactive "P")
20787 (let ((calendar-longitude (if arg nil calendar-longitude))
20788 (calendar-latitude (if arg nil calendar-latitude))
20789 (calendar-location-name
20790 (if arg "the given coordinates" calendar-location-name)))
20791 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
20793 (defun org-agenda-goto-calendar ()
20794 "Open the Emacs calendar with the date at the cursor."
20795 (interactive)
20796 (org-agenda-check-type t 'agenda 'timeline)
20797 (let* ((day (or (get-text-property (point) 'day)
20798 (error "Don't know which date to open in calendar")))
20799 (date (calendar-gregorian-from-absolute day))
20800 (calendar-move-hook nil)
20801 (view-calendar-holidays-initially nil)
20802 (view-diary-entries-initially nil))
20803 (calendar)
20804 (calendar-goto-date date)))
20806 (defun org-calendar-goto-agenda ()
20807 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
20808 This is a command that has to be installed in `calendar-mode-map'."
20809 (interactive)
20810 (org-agenda-list nil (calendar-absolute-from-gregorian
20811 (calendar-cursor-to-date))
20812 nil))
20814 (defun org-agenda-convert-date ()
20815 (interactive)
20816 (org-agenda-check-type t 'agenda 'timeline)
20817 (let ((day (get-text-property (point) 'day))
20818 date s)
20819 (unless day
20820 (error "Don't know which date to convert"))
20821 (setq date (calendar-gregorian-from-absolute day))
20822 (setq s (concat
20823 "Gregorian: " (calendar-date-string date) "\n"
20824 "ISO: " (calendar-iso-date-string date) "\n"
20825 "Day of Yr: " (calendar-day-of-year-string date) "\n"
20826 "Julian: " (calendar-julian-date-string date) "\n"
20827 "Astron. JD: " (calendar-astro-date-string date)
20828 " (Julian date number at noon UTC)\n"
20829 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
20830 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
20831 "French: " (calendar-french-date-string date) "\n"
20832 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
20833 "Mayan: " (calendar-mayan-date-string date) "\n"
20834 "Coptic: " (calendar-coptic-date-string date) "\n"
20835 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
20836 "Persian: " (calendar-persian-date-string date) "\n"
20837 "Chinese: " (calendar-chinese-date-string date) "\n"))
20838 (with-output-to-temp-buffer "*Dates*"
20839 (princ s))
20840 (if (fboundp 'fit-window-to-buffer)
20841 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
20844 ;;;; Embedded LaTeX
20846 (defvar org-cdlatex-mode-map (make-sparse-keymap)
20847 "Keymap for the minor `org-cdlatex-mode'.")
20849 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
20850 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
20851 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
20852 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
20853 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
20855 (defvar org-cdlatex-texmathp-advice-is-done nil
20856 "Flag remembering if we have applied the advice to texmathp already.")
20858 (define-minor-mode org-cdlatex-mode
20859 "Toggle the minor `org-cdlatex-mode'.
20860 This mode supports entering LaTeX environment and math in LaTeX fragments
20861 in Org-mode.
20862 \\{org-cdlatex-mode-map}"
20863 nil " OCDL" nil
20864 (when org-cdlatex-mode (require 'cdlatex))
20865 (unless org-cdlatex-texmathp-advice-is-done
20866 (setq org-cdlatex-texmathp-advice-is-done t)
20867 (defadvice texmathp (around org-math-always-on activate)
20868 "Always return t in org-mode buffers.
20869 This is because we want to insert math symbols without dollars even outside
20870 the LaTeX math segments. If Orgmode thinks that point is actually inside
20871 en embedded LaTeX fragement, let texmathp do its job.
20872 \\[org-cdlatex-mode-map]"
20873 (interactive)
20874 (let (p)
20875 (cond
20876 ((not (org-mode-p)) ad-do-it)
20877 ((eq this-command 'cdlatex-math-symbol)
20878 (setq ad-return-value t
20879 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
20881 (let ((p (org-inside-LaTeX-fragment-p)))
20882 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
20883 (setq ad-return-value t
20884 texmathp-why '("Org-mode embedded math" . 0))
20885 (if p ad-do-it)))))))))
20887 (defun turn-on-org-cdlatex ()
20888 "Unconditionally turn on `org-cdlatex-mode'."
20889 (org-cdlatex-mode 1))
20891 (defun org-inside-LaTeX-fragment-p ()
20892 "Test if point is inside a LaTeX fragment.
20893 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
20894 sequence appearing also before point.
20895 Even though the matchers for math are configurable, this function assumes
20896 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
20897 delimiters are skipped when they have been removed by customization.
20898 The return value is nil, or a cons cell with the delimiter and
20899 and the position of this delimiter.
20901 This function does a reasonably good job, but can locally be fooled by
20902 for example currency specifications. For example it will assume being in
20903 inline math after \"$22.34\". The LaTeX fragment formatter will only format
20904 fragments that are properly closed, but during editing, we have to live
20905 with the uncertainty caused by missing closing delimiters. This function
20906 looks only before point, not after."
20907 (catch 'exit
20908 (let ((pos (point))
20909 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
20910 (lim (progn
20911 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
20912 (point)))
20913 dd-on str (start 0) m re)
20914 (goto-char pos)
20915 (when dodollar
20916 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
20917 re (nth 1 (assoc "$" org-latex-regexps)))
20918 (while (string-match re str start)
20919 (cond
20920 ((= (match-end 0) (length str))
20921 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
20922 ((= (match-end 0) (- (length str) 5))
20923 (throw 'exit nil))
20924 (t (setq start (match-end 0))))))
20925 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
20926 (goto-char pos)
20927 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
20928 (and (match-beginning 2) (throw 'exit nil))
20929 ;; count $$
20930 (while (re-search-backward "\\$\\$" lim t)
20931 (setq dd-on (not dd-on)))
20932 (goto-char pos)
20933 (if dd-on (cons "$$" m))))))
20936 (defun org-try-cdlatex-tab ()
20937 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
20938 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
20939 - inside a LaTeX fragment, or
20940 - after the first word in a line, where an abbreviation expansion could
20941 insert a LaTeX environment."
20942 (when org-cdlatex-mode
20943 (cond
20944 ((save-excursion
20945 (skip-chars-backward "a-zA-Z0-9*")
20946 (skip-chars-backward " \t")
20947 (bolp))
20948 (cdlatex-tab) t)
20949 ((org-inside-LaTeX-fragment-p)
20950 (cdlatex-tab) t)
20951 (t nil))))
20953 (defun org-cdlatex-underscore-caret (&optional arg)
20954 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
20955 Revert to the normal definition outside of these fragments."
20956 (interactive "P")
20957 (if (org-inside-LaTeX-fragment-p)
20958 (call-interactively 'cdlatex-sub-superscript)
20959 (let (org-cdlatex-mode)
20960 (call-interactively (key-binding (vector last-input-event))))))
20962 (defun org-cdlatex-math-modify (&optional arg)
20963 "Execute `cdlatex-math-modify' in LaTeX fragments.
20964 Revert to the normal definition outside of these fragments."
20965 (interactive "P")
20966 (if (org-inside-LaTeX-fragment-p)
20967 (call-interactively 'cdlatex-math-modify)
20968 (let (org-cdlatex-mode)
20969 (call-interactively (key-binding (vector last-input-event))))))
20971 (defvar org-latex-fragment-image-overlays nil
20972 "List of overlays carrying the images of latex fragments.")
20973 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
20975 (defun org-remove-latex-fragment-image-overlays ()
20976 "Remove all overlays with LaTeX fragment images in current buffer."
20977 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
20978 (setq org-latex-fragment-image-overlays nil))
20980 (defun org-preview-latex-fragment (&optional subtree)
20981 "Preview the LaTeX fragment at point, or all locally or globally.
20982 If the cursor is in a LaTeX fragment, create the image and overlay
20983 it over the source code. If there is no fragment at point, display
20984 all fragments in the current text, from one headline to the next. With
20985 prefix SUBTREE, display all fragments in the current subtree. With a
20986 double prefix `C-u C-u', or when the cursor is before the first headline,
20987 display all fragments in the buffer.
20988 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
20989 (interactive "P")
20990 (org-remove-latex-fragment-image-overlays)
20991 (save-excursion
20992 (save-restriction
20993 (let (beg end at msg)
20994 (cond
20995 ((or (equal subtree '(16))
20996 (not (save-excursion
20997 (re-search-backward (concat "^" outline-regexp) nil t))))
20998 (setq beg (point-min) end (point-max)
20999 msg "Creating images for buffer...%s"))
21000 ((equal subtree '(4))
21001 (org-back-to-heading)
21002 (setq beg (point) end (org-end-of-subtree t)
21003 msg "Creating images for subtree...%s"))
21005 (if (setq at (org-inside-LaTeX-fragment-p))
21006 (goto-char (max (point-min) (- (cdr at) 2)))
21007 (org-back-to-heading))
21008 (setq beg (point) end (progn (outline-next-heading) (point))
21009 msg (if at "Creating image...%s"
21010 "Creating images for entry...%s"))))
21011 (message msg "")
21012 (narrow-to-region beg end)
21013 (goto-char beg)
21014 (org-format-latex
21015 (concat "ltxpng/" (file-name-sans-extension
21016 (file-name-nondirectory
21017 buffer-file-name)))
21018 default-directory 'overlays msg at 'forbuffer)
21019 (message msg "done. Use `C-c C-c' to remove images.")))))
21021 (defvar org-latex-regexps
21022 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
21023 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
21024 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
21025 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
21026 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
21027 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
21028 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
21029 "Regular expressions for matching embedded LaTeX.")
21031 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
21032 "Replace LaTeX fragments with links to an image, and produce images."
21033 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
21034 (let* ((prefixnodir (file-name-nondirectory prefix))
21035 (absprefix (expand-file-name prefix dir))
21036 (todir (file-name-directory absprefix))
21037 (opt org-format-latex-options)
21038 (matchers (plist-get opt :matchers))
21039 (re-list org-latex-regexps)
21040 (cnt 0) txt link beg end re e checkdir
21041 m n block linkfile movefile ov)
21042 ;; Check if there are old images files with this prefix, and remove them
21043 (when (file-directory-p todir)
21044 (mapc 'delete-file
21045 (directory-files
21046 todir 'full
21047 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
21048 ;; Check the different regular expressions
21049 (while (setq e (pop re-list))
21050 (setq m (car e) re (nth 1 e) n (nth 2 e)
21051 block (if (nth 3 e) "\n\n" ""))
21052 (when (member m matchers)
21053 (goto-char (point-min))
21054 (while (re-search-forward re nil t)
21055 (when (or (not at) (equal (cdr at) (match-beginning n)))
21056 (setq txt (match-string n)
21057 beg (match-beginning n) end (match-end n)
21058 cnt (1+ cnt)
21059 linkfile (format "%s_%04d.png" prefix cnt)
21060 movefile (format "%s_%04d.png" absprefix cnt)
21061 link (concat block "[[file:" linkfile "]]" block))
21062 (if msg (message msg cnt))
21063 (goto-char beg)
21064 (unless checkdir ; make sure the directory exists
21065 (setq checkdir t)
21066 (or (file-directory-p todir) (make-directory todir)))
21067 (org-create-formula-image
21068 txt movefile opt forbuffer)
21069 (if overlays
21070 (progn
21071 (setq ov (org-make-overlay beg end))
21072 (if (featurep 'xemacs)
21073 (progn
21074 (org-overlay-put ov 'invisible t)
21075 (org-overlay-put
21076 ov 'end-glyph
21077 (make-glyph (vector 'png :file movefile))))
21078 (org-overlay-put
21079 ov 'display
21080 (list 'image :type 'png :file movefile :ascent 'center)))
21081 (push ov org-latex-fragment-image-overlays)
21082 (goto-char end))
21083 (delete-region beg end)
21084 (insert link))))))))
21086 ;; This function borrows from Ganesh Swami's latex2png.el
21087 (defun org-create-formula-image (string tofile options buffer)
21088 (let* ((tmpdir (if (featurep 'xemacs)
21089 (temp-directory)
21090 temporary-file-directory))
21091 (texfilebase (make-temp-name
21092 (expand-file-name "orgtex" tmpdir)))
21093 (texfile (concat texfilebase ".tex"))
21094 (dvifile (concat texfilebase ".dvi"))
21095 (pngfile (concat texfilebase ".png"))
21096 (fnh (face-attribute 'default :height nil))
21097 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
21098 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
21099 (fg (or (plist-get options (if buffer :foreground :html-foreground))
21100 "Black"))
21101 (bg (or (plist-get options (if buffer :background :html-background))
21102 "Transparent")))
21103 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
21104 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
21105 (with-temp-file texfile
21106 (insert org-format-latex-header
21107 "\n\\begin{document}\n" string "\n\\end{document}\n"))
21108 (let ((dir default-directory))
21109 (condition-case nil
21110 (progn
21111 (cd tmpdir)
21112 (call-process "latex" nil nil nil texfile))
21113 (error nil))
21114 (cd dir))
21115 (if (not (file-exists-p dvifile))
21116 (progn (message "Failed to create dvi file from %s" texfile) nil)
21117 (call-process "dvipng" nil nil nil
21118 "-E" "-fg" fg "-bg" bg
21119 "-D" dpi
21120 ;;"-x" scale "-y" scale
21121 "-T" "tight"
21122 "-o" pngfile
21123 dvifile)
21124 (if (not (file-exists-p pngfile))
21125 (progn (message "Failed to create png file from %s" texfile) nil)
21126 ;; Use the requested file name and clean up
21127 (copy-file pngfile tofile 'replace)
21128 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
21129 (delete-file (concat texfilebase e)))
21130 pngfile))))
21132 (defun org-dvipng-color (attr)
21133 "Return an rgb color specification for dvipng."
21134 (apply 'format "rgb %s %s %s"
21135 (mapcar 'org-normalize-color
21136 (color-values (face-attribute 'default attr nil)))))
21138 (defun org-normalize-color (value)
21139 "Return string to be used as color value for an RGB component."
21140 (format "%g" (/ value 65535.0)))
21142 ;;;; Exporting
21144 ;;; Variables, constants, and parameter plists
21146 (defconst org-level-max 20)
21148 (defvar org-export-html-preamble nil
21149 "Preamble, to be inserted just after <body>. Set by publishing functions.")
21150 (defvar org-export-html-postamble nil
21151 "Preamble, to be inserted just before </body>. Set by publishing functions.")
21152 (defvar org-export-html-auto-preamble t
21153 "Should default preamble be inserted? Set by publishing functions.")
21154 (defvar org-export-html-auto-postamble t
21155 "Should default postamble be inserted? Set by publishing functions.")
21156 (defvar org-current-export-file nil) ; dynamically scoped parameter
21157 (defvar org-current-export-dir nil) ; dynamically scoped parameter
21160 (defconst org-export-plist-vars
21161 '((:language . org-export-default-language)
21162 (:customtime . org-display-custom-times)
21163 (:headline-levels . org-export-headline-levels)
21164 (:section-numbers . org-export-with-section-numbers)
21165 (:table-of-contents . org-export-with-toc)
21166 (:preserve-breaks . org-export-preserve-breaks)
21167 (:archived-trees . org-export-with-archived-trees)
21168 (:emphasize . org-export-with-emphasize)
21169 (:sub-superscript . org-export-with-sub-superscripts)
21170 (:footnotes . org-export-with-footnotes)
21171 (:property-drawer . org-export-with-property-drawer)
21172 (:tags . org-export-with-tags)
21173 (:TeX-macros . org-export-with-TeX-macros)
21174 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
21175 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
21176 (:fixed-width . org-export-with-fixed-width)
21177 (:timestamps . org-export-with-timestamps)
21178 (:author-info . org-export-author-info)
21179 (:time-stamp-file . org-export-time-stamp-file)
21180 (:tables . org-export-with-tables)
21181 (:table-auto-headline . org-export-highlight-first-table-line)
21182 (:style . org-export-html-style)
21183 (:agenda-style . org-agenda-export-html-style) ;; FIXME: Does this work????
21184 (:convert-org-links . org-export-html-link-org-files-as-html)
21185 (:inline-images . org-export-html-inline-images)
21186 (:html-extension . org-export-html-extension)
21187 (:expand-quoted-html . org-export-html-expand)
21188 (:timestamp . org-export-html-with-timestamp)
21189 (:publishing-directory . org-export-publishing-directory)
21190 (:preamble . org-export-html-preamble)
21191 (:postamble . org-export-html-postamble)
21192 (:auto-preamble . org-export-html-auto-preamble)
21193 (:auto-postamble . org-export-html-auto-postamble)
21194 (:author . user-full-name)
21195 (:email . user-mail-address)))
21197 (defun org-default-export-plist ()
21198 "Return the property list with default settings for the export variables."
21199 (let ((l org-export-plist-vars) rtn e)
21200 (while (setq e (pop l))
21201 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
21202 rtn))
21204 (defun org-infile-export-plist ()
21205 "Return the property list with file-local settings for export."
21206 (save-excursion
21207 (goto-char 0)
21208 (let ((re (org-make-options-regexp
21209 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
21210 p key val text options)
21211 (while (re-search-forward re nil t)
21212 (setq key (org-match-string-no-properties 1)
21213 val (org-match-string-no-properties 2))
21214 (cond
21215 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
21216 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
21217 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
21218 ((string-equal key "DATE") (setq p (plist-put p :date val)))
21219 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
21220 ((string-equal key "TEXT")
21221 (setq text (if text (concat text "\n" val) val)))
21222 ((string-equal key "OPTIONS") (setq options val))))
21223 (setq p (plist-put p :text text))
21224 (when options
21225 (let ((op '(("H" . :headline-levels)
21226 ("num" . :section-numbers)
21227 ("toc" . :table-of-contents)
21228 ("\\n" . :preserve-breaks)
21229 ("@" . :expand-quoted-html)
21230 (":" . :fixed-width)
21231 ("|" . :tables)
21232 ("^" . :sub-superscript)
21233 ("f" . :footnotes)
21234 ("p" . :property-drawer)
21235 ("tags" . :tags)
21236 ("*" . :emphasize)
21237 ("TeX" . :TeX-macros)
21238 ("LaTeX" . :LaTeX-fragments)
21239 ("skip" . :skip-before-1st-heading)
21240 ("author" . :author-info)
21241 ("timestamp" . :time-stamp-file)))
21243 (while (setq o (pop op))
21244 (if (string-match (concat (regexp-quote (car o))
21245 ":\\([^ \t\n\r;,.]*\\)")
21246 options)
21247 (setq p (plist-put p (cdr o)
21248 (car (read-from-string
21249 (match-string 1 options)))))))))
21250 p)))
21252 (defun org-export-directory (type plist)
21253 (let* ((val (plist-get plist :publishing-directory))
21254 (dir (if (listp val)
21255 (or (cdr (assoc type val)) ".")
21256 val)))
21257 dir))
21259 (defun org-skip-comments (lines)
21260 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
21261 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
21262 (re2 "^\\(\\*+\\)[ \t\n\r]")
21263 (case-fold-search nil)
21264 rtn line level)
21265 (while (setq line (pop lines))
21266 (cond
21267 ((and (string-match re1 line)
21268 (setq level (- (match-end 1) (match-beginning 1))))
21269 ;; Beginning of a COMMENT subtree. Skip it.
21270 (while (and (setq line (pop lines))
21271 (or (not (string-match re2 line))
21272 (> (- (match-end 1) (match-beginning 1)) level))))
21273 (setq lines (cons line lines)))
21274 ((string-match "^#" line)
21275 ;; an ordinary comment line
21277 ((and org-export-table-remove-special-lines
21278 (string-match "^[ \t]*|" line)
21279 (or (string-match "^[ \t]*| *[!_^] *|" line)
21280 (and (string-match "| *<[0-9]+> *|" line)
21281 (not (string-match "| *[^ <|]" line)))))
21282 ;; a special table line that should be removed
21284 (t (setq rtn (cons line rtn)))))
21285 (nreverse rtn)))
21287 (defun org-export (&optional arg)
21288 (interactive)
21289 (let ((help "[t] insert the export option template
21290 \[v] limit export to visible part of outline tree
21292 \[a] export as ASCII
21294 \[h] export as HTML
21295 \[H] export as HTML to temporary buffer
21296 \[R] export region as HTML
21297 \[b] export as HTML and browse immediately
21298 \[x] export as XOXO
21300 \[l] export as LaTeX
21301 \[L] export as LaTeX to temporary buffer
21303 \[i] export current file as iCalendar file
21304 \[I] export all agenda files as iCalendar files
21305 \[c] export agenda files into combined iCalendar file
21307 \[F] publish current file
21308 \[P] publish current project
21309 \[X] publish... (project will be prompted for)
21310 \[A] publish all projects")
21311 (cmds
21312 '((?t . org-insert-export-options-template)
21313 (?v . org-export-visible)
21314 (?a . org-export-as-ascii)
21315 (?h . org-export-as-html)
21316 (?b . org-export-as-html-and-open)
21317 (?H . org-export-as-html-to-buffer)
21318 (?R . org-export-region-as-html)
21319 (?x . org-export-as-xoxo)
21320 (?l . org-export-as-latex)
21321 (?L . org-export-as-latex-to-buffer)
21322 (?i . org-export-icalendar-this-file)
21323 (?I . org-export-icalendar-all-agenda-files)
21324 (?c . org-export-icalendar-combine-agenda-files)
21325 (?F . org-publish-current-file)
21326 (?P . org-publish-current-project)
21327 (?X . org-publish)
21328 (?A . org-publish-all)))
21329 r1 r2 ass)
21330 (save-window-excursion
21331 (delete-other-windows)
21332 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
21333 (princ help))
21334 (message "Select command: ")
21335 (setq r1 (read-char-exclusive)))
21336 (setq r2 (if (< r1 27) (+ r1 96) r1))
21337 (if (setq ass (assq r2 cmds))
21338 (call-interactively (cdr ass))
21339 (error "No command associated with key %c" r1))))
21341 (defconst org-html-entities
21342 '(("nbsp")
21343 ("iexcl")
21344 ("cent")
21345 ("pound")
21346 ("curren")
21347 ("yen")
21348 ("brvbar")
21349 ("vert" . "&#124;")
21350 ("sect")
21351 ("uml")
21352 ("copy")
21353 ("ordf")
21354 ("laquo")
21355 ("not")
21356 ("shy")
21357 ("reg")
21358 ("macr")
21359 ("deg")
21360 ("plusmn")
21361 ("sup2")
21362 ("sup3")
21363 ("acute")
21364 ("micro")
21365 ("para")
21366 ("middot")
21367 ("odot"."o")
21368 ("star"."*")
21369 ("cedil")
21370 ("sup1")
21371 ("ordm")
21372 ("raquo")
21373 ("frac14")
21374 ("frac12")
21375 ("frac34")
21376 ("iquest")
21377 ("Agrave")
21378 ("Aacute")
21379 ("Acirc")
21380 ("Atilde")
21381 ("Auml")
21382 ("Aring") ("AA"."&Aring;")
21383 ("AElig")
21384 ("Ccedil")
21385 ("Egrave")
21386 ("Eacute")
21387 ("Ecirc")
21388 ("Euml")
21389 ("Igrave")
21390 ("Iacute")
21391 ("Icirc")
21392 ("Iuml")
21393 ("ETH")
21394 ("Ntilde")
21395 ("Ograve")
21396 ("Oacute")
21397 ("Ocirc")
21398 ("Otilde")
21399 ("Ouml")
21400 ("times")
21401 ("Oslash")
21402 ("Ugrave")
21403 ("Uacute")
21404 ("Ucirc")
21405 ("Uuml")
21406 ("Yacute")
21407 ("THORN")
21408 ("szlig")
21409 ("agrave")
21410 ("aacute")
21411 ("acirc")
21412 ("atilde")
21413 ("auml")
21414 ("aring")
21415 ("aelig")
21416 ("ccedil")
21417 ("egrave")
21418 ("eacute")
21419 ("ecirc")
21420 ("euml")
21421 ("igrave")
21422 ("iacute")
21423 ("icirc")
21424 ("iuml")
21425 ("eth")
21426 ("ntilde")
21427 ("ograve")
21428 ("oacute")
21429 ("ocirc")
21430 ("otilde")
21431 ("ouml")
21432 ("divide")
21433 ("oslash")
21434 ("ugrave")
21435 ("uacute")
21436 ("ucirc")
21437 ("uuml")
21438 ("yacute")
21439 ("thorn")
21440 ("yuml")
21441 ("fnof")
21442 ("Alpha")
21443 ("Beta")
21444 ("Gamma")
21445 ("Delta")
21446 ("Epsilon")
21447 ("Zeta")
21448 ("Eta")
21449 ("Theta")
21450 ("Iota")
21451 ("Kappa")
21452 ("Lambda")
21453 ("Mu")
21454 ("Nu")
21455 ("Xi")
21456 ("Omicron")
21457 ("Pi")
21458 ("Rho")
21459 ("Sigma")
21460 ("Tau")
21461 ("Upsilon")
21462 ("Phi")
21463 ("Chi")
21464 ("Psi")
21465 ("Omega")
21466 ("alpha")
21467 ("beta")
21468 ("gamma")
21469 ("delta")
21470 ("epsilon")
21471 ("varepsilon"."&epsilon;")
21472 ("zeta")
21473 ("eta")
21474 ("theta")
21475 ("iota")
21476 ("kappa")
21477 ("lambda")
21478 ("mu")
21479 ("nu")
21480 ("xi")
21481 ("omicron")
21482 ("pi")
21483 ("rho")
21484 ("sigmaf") ("varsigma"."&sigmaf;")
21485 ("sigma")
21486 ("tau")
21487 ("upsilon")
21488 ("phi")
21489 ("chi")
21490 ("psi")
21491 ("omega")
21492 ("thetasym") ("vartheta"."&thetasym;")
21493 ("upsih")
21494 ("piv")
21495 ("bull") ("bullet"."&bull;")
21496 ("hellip") ("dots"."&hellip;")
21497 ("prime")
21498 ("Prime")
21499 ("oline")
21500 ("frasl")
21501 ("weierp")
21502 ("image")
21503 ("real")
21504 ("trade")
21505 ("alefsym")
21506 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
21507 ("uarr") ("uparrow"."&uarr;")
21508 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
21509 ("darr")("downarrow"."&darr;")
21510 ("harr") ("leftrightarrow"."&harr;")
21511 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
21512 ("lArr") ("Leftarrow"."&lArr;")
21513 ("uArr") ("Uparrow"."&uArr;")
21514 ("rArr") ("Rightarrow"."&rArr;")
21515 ("dArr") ("Downarrow"."&dArr;")
21516 ("hArr") ("Leftrightarrow"."&hArr;")
21517 ("forall")
21518 ("part") ("partial"."&part;")
21519 ("exist") ("exists"."&exist;")
21520 ("empty") ("emptyset"."&empty;")
21521 ("nabla")
21522 ("isin") ("in"."&isin;")
21523 ("notin")
21524 ("ni")
21525 ("prod")
21526 ("sum")
21527 ("minus")
21528 ("lowast") ("ast"."&lowast;")
21529 ("radic")
21530 ("prop") ("proptp"."&prop;")
21531 ("infin") ("infty"."&infin;")
21532 ("ang") ("angle"."&ang;")
21533 ("and") ("vee"."&and;")
21534 ("or") ("wedge"."&or;")
21535 ("cap")
21536 ("cup")
21537 ("int")
21538 ("there4")
21539 ("sim")
21540 ("cong") ("simeq"."&cong;")
21541 ("asymp")("approx"."&asymp;")
21542 ("ne") ("neq"."&ne;")
21543 ("equiv")
21544 ("le")
21545 ("ge")
21546 ("sub") ("subset"."&sub;")
21547 ("sup") ("supset"."&sup;")
21548 ("nsub")
21549 ("sube")
21550 ("supe")
21551 ("oplus")
21552 ("otimes")
21553 ("perp")
21554 ("sdot") ("cdot"."&sdot;")
21555 ("lceil")
21556 ("rceil")
21557 ("lfloor")
21558 ("rfloor")
21559 ("lang")
21560 ("rang")
21561 ("loz") ("Diamond"."&loz;")
21562 ("spades") ("spadesuit"."&spades;")
21563 ("clubs") ("clubsuit"."&clubs;")
21564 ("hearts") ("diamondsuit"."&hearts;")
21565 ("diams") ("diamondsuit"."&diams;")
21566 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
21567 ("quot")
21568 ("amp")
21569 ("lt")
21570 ("gt")
21571 ("OElig")
21572 ("oelig")
21573 ("Scaron")
21574 ("scaron")
21575 ("Yuml")
21576 ("circ")
21577 ("tilde")
21578 ("ensp")
21579 ("emsp")
21580 ("thinsp")
21581 ("zwnj")
21582 ("zwj")
21583 ("lrm")
21584 ("rlm")
21585 ("ndash")
21586 ("mdash")
21587 ("lsquo")
21588 ("rsquo")
21589 ("sbquo")
21590 ("ldquo")
21591 ("rdquo")
21592 ("bdquo")
21593 ("dagger")
21594 ("Dagger")
21595 ("permil")
21596 ("lsaquo")
21597 ("rsaquo")
21598 ("euro")
21600 ("arccos"."arccos")
21601 ("arcsin"."arcsin")
21602 ("arctan"."arctan")
21603 ("arg"."arg")
21604 ("cos"."cos")
21605 ("cosh"."cosh")
21606 ("cot"."cot")
21607 ("coth"."coth")
21608 ("csc"."csc")
21609 ("deg"."deg")
21610 ("det"."det")
21611 ("dim"."dim")
21612 ("exp"."exp")
21613 ("gcd"."gcd")
21614 ("hom"."hom")
21615 ("inf"."inf")
21616 ("ker"."ker")
21617 ("lg"."lg")
21618 ("lim"."lim")
21619 ("liminf"."liminf")
21620 ("limsup"."limsup")
21621 ("ln"."ln")
21622 ("log"."log")
21623 ("max"."max")
21624 ("min"."min")
21625 ("Pr"."Pr")
21626 ("sec"."sec")
21627 ("sin"."sin")
21628 ("sinh"."sinh")
21629 ("sup"."sup")
21630 ("tan"."tan")
21631 ("tanh"."tanh")
21633 "Entities for TeX->HTML translation.
21634 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
21635 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
21636 In that case, \"\\ent\" will be translated to \"&other;\".
21637 The list contains HTML entities for Latin-1, Greek and other symbols.
21638 It is supplemented by a number of commonly used TeX macros with appropriate
21639 translations. There is currently no way for users to extend this.")
21641 ;;; General functions for all backends
21643 (defun org-cleaned-string-for-export (string &rest parameters)
21644 "Cleanup a buffer STRING so that links can be created safely."
21645 (interactive)
21646 (let* ((re-radio (and org-target-link-regexp
21647 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
21648 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
21649 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
21650 (re-archive (concat ":" org-archive-tag ":"))
21651 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
21652 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
21653 (htmlp (plist-get parameters :for-html))
21654 (asciip (plist-get parameters :for-ascii))
21655 (latexp (plist-get parameters :for-LaTeX))
21656 (commentsp (plist-get parameters :comments))
21657 (archived-trees (plist-get parameters :archived-trees))
21658 (inhibit-read-only t)
21659 (outline-regexp "\\*+ ")
21660 a b xx
21661 rtn p)
21662 (with-current-buffer (get-buffer-create " org-mode-tmp")
21663 (erase-buffer)
21664 (insert string)
21665 ;; Remove license-to-kill stuff
21666 (while (setq p (text-property-any (point-min) (point-max)
21667 :org-license-to-kill t))
21668 (delete-region p (next-single-property-change p :org-license-to-kill)))
21670 (let ((org-inhibit-startup t)) (org-mode))
21671 (untabify (point-min) (point-max))
21673 ;; Get the correct stuff before the first headline
21674 (when (plist-get parameters :skip-before-1st-heading)
21675 (goto-char (point-min))
21676 (when (re-search-forward "^\\*+[ \t]" nil t)
21677 (delete-region (point-min) (match-beginning 0))
21678 (goto-char (point-min))
21679 (insert "\n")))
21680 (when (plist-get parameters :add-text)
21681 (goto-char (point-min))
21682 (insert (plist-get parameters :add-text) "\n"))
21684 ;; Get rid of archived trees
21685 (when (not (eq archived-trees t))
21686 (goto-char (point-min))
21687 (while (re-search-forward re-archive nil t)
21688 (if (not (org-on-heading-p t))
21689 (org-end-of-subtree t)
21690 (beginning-of-line 1)
21691 (setq a (if archived-trees
21692 (1+ (point-at-eol)) (point))
21693 b (org-end-of-subtree t))
21694 (if (> b a) (delete-region a b)))))
21696 ;; Get rid of property drawers
21697 (unless org-export-with-property-drawer
21698 (goto-char (point-min))
21699 (while (re-search-forward "^[ \t]*:PROPERTIES:[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n" nil t)
21700 (replace-match "")))
21702 ;; Find targets in comments and move them out of comments,
21703 ;; but mark them as targets that should be invisible
21704 (goto-char (point-min))
21705 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
21706 (replace-match "\\1(INVISIBLE)"))
21708 ;; Protect backend specific stuff, throw away the others.
21709 (goto-char (point-min))
21710 (let ((formatters
21711 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
21712 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
21713 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
21714 fmt)
21715 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
21716 (add-text-properties (match-beginning 0) (match-end 0)
21717 '(org-protected t)))
21718 (while formatters
21719 (setq fmt (pop formatters))
21720 (when (car fmt)
21721 (goto-char (point-min))
21722 (while (re-search-forward (concat "^#\\+" (cadr fmt)
21723 ":[ \t]*\\(.*\\)") nil t)
21724 (replace-match "\\1" t)
21725 (add-text-properties
21726 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
21727 '(org-protected t))))
21728 (goto-char (point-min))
21729 (while (re-search-forward
21730 (concat "^#\\+"
21731 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
21732 (cadddr fmt) "\\>.*\n?") nil t)
21733 (if (car fmt)
21734 (add-text-properties (match-beginning 1) (1+ (match-end 1))
21735 '(org-protected t))
21736 (delete-region (match-beginning 0) (match-end 0))))))
21738 ;; Protect quoted subtrees
21739 (goto-char (point-min))
21740 (while (re-search-forward re-quote nil t)
21741 (goto-char (match-beginning 0))
21742 (end-of-line 1)
21743 (add-text-properties (point) (org-end-of-subtree t)
21744 '(org-protected t)))
21746 ;; Remove subtrees that are commented
21747 (goto-char (point-min))
21748 (while (re-search-forward re-commented nil t)
21749 (goto-char (match-beginning 0))
21750 (delete-region (point) (org-end-of-subtree t)))
21752 ;; Remove special table lines
21753 (when org-export-table-remove-special-lines
21754 (goto-char (point-min))
21755 (while (re-search-forward "^[ \t]*|" nil t)
21756 (beginning-of-line 1)
21757 (if (or (looking-at "[ \t]*| *[!_^] *|")
21758 (and (looking-at ".*?| *<[0-9]+> *|")
21759 (not (looking-at ".*?| *[^ <|]"))))
21760 (delete-region (max (point-min) (1- (point-at-bol)))
21761 (point-at-eol))
21762 (end-of-line 1))))
21764 ;; Specific LaTeX stuff
21765 (when latexp
21766 (require 'org-export-latex nil)
21767 (org-export-latex-cleaned-string))
21769 ;; Specific HTML stuff
21770 (when htmlp
21771 ;; Convert LaTeX fragments to images
21772 (when (plist-get parameters :LaTeX-fragments)
21773 (org-format-latex
21774 (concat "ltxpng/" (file-name-sans-extension
21775 (file-name-nondirectory
21776 org-current-export-file)))
21777 org-current-export-dir nil "Creating LaTeX image %s"))
21778 (message "Exporting..."))
21780 ;; Remove or replace comments
21781 (goto-char (point-min))
21782 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
21783 (if commentsp
21784 (progn (add-text-properties
21785 (match-beginning 0) (match-end 0) '(org-protected t))
21786 (replace-match (format commentsp (match-string 1)) t t))
21787 (replace-match "")))
21789 ;; Find matches for radio targets and turn them into internal links
21790 (goto-char (point-min))
21791 (when re-radio
21792 (while (re-search-forward re-radio nil t)
21793 (org-if-unprotected
21794 (replace-match "\\1[[\\2]]"))))
21796 ;; Find all links that contain a newline and put them into a single line
21797 (goto-char (point-min))
21798 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
21799 (org-if-unprotected
21800 (replace-match "\\1 \\3")
21801 (goto-char (match-beginning 0))))
21804 ;; Normalize links: Convert angle and plain links into bracket links
21805 ;; Expand link abbreviations
21806 (goto-char (point-min))
21807 (while (re-search-forward re-plain-link nil t)
21808 (goto-char (1- (match-end 0)))
21809 (org-if-unprotected
21810 (let* ((s (concat (match-string 1) "[[" (match-string 2)
21811 ":" (match-string 3) "]]")))
21812 ;; added 'org-link face to links
21813 (put-text-property 0 (length s) 'face 'org-link s)
21814 (replace-match s t t))))
21815 (goto-char (point-min))
21816 (while (re-search-forward re-angle-link nil t)
21817 (goto-char (1- (match-end 0)))
21818 (org-if-unprotected
21819 (let* ((s (concat (match-string 1) "[[" (match-string 2)
21820 ":" (match-string 3) "]]")))
21821 (put-text-property 0 (length s) 'face 'org-link s)
21822 (replace-match s t t))))
21823 (goto-char (point-min))
21824 (while (re-search-forward org-bracket-link-regexp nil t)
21825 (org-if-unprotected
21826 (let* ((s (concat "[[" (setq xx (save-match-data
21827 (org-link-expand-abbrev (match-string 1))))
21829 (if (match-end 3)
21830 (match-string 2)
21831 (concat "[" xx "]"))
21832 "]")))
21833 (put-text-property 0 (length s) 'face 'org-link s)
21834 (replace-match s t t))))
21836 ;; Find multiline emphasis and put them into single line
21837 (when (plist-get parameters :emph-multiline)
21838 (goto-char (point-min))
21839 (while (re-search-forward org-emph-re nil t)
21840 (if (not (= (char-after (match-beginning 3))
21841 (char-after (match-beginning 4))))
21842 (org-if-unprotected
21843 (subst-char-in-region (match-beginning 0) (match-end 0)
21844 ?\n ?\ t)
21845 (goto-char (1- (match-end 0))))
21846 (goto-char (1+ (match-beginning 0))))))
21848 (setq rtn (buffer-string)))
21849 (kill-buffer " org-mode-tmp")
21850 rtn))
21852 (defun org-export-grab-title-from-buffer ()
21853 "Get a title for the current document, from looking at the buffer."
21854 (let ((inhibit-read-only t))
21855 (save-excursion
21856 (goto-char (point-min))
21857 (let ((end (save-excursion (outline-next-heading) (point))))
21858 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
21859 ;; Mark the line so that it will not be exported as normal text.
21860 (org-unmodified
21861 (add-text-properties (match-beginning 0) (match-end 0)
21862 (list :org-license-to-kill t)))
21863 ;; Return the title string
21864 (org-trim (match-string 0)))))))
21866 (defun org-export-get-title-from-subtree ()
21867 "Return subtree title and exclude it from export."
21868 (let (title (m (mark)))
21869 (save-excursion
21870 (goto-char (region-beginning))
21871 (when (and (org-at-heading-p)
21872 (>= (org-end-of-subtree t t) (region-end)))
21873 ;; This is a subtree, we take the title from the first heading
21874 (goto-char (region-beginning))
21875 (looking-at org-todo-line-regexp)
21876 (setq title (match-string 3))
21877 (org-unmodified
21878 (add-text-properties (point) (1+ (point-at-eol))
21879 (list :org-license-to-kill t)))))
21880 title))
21882 (defun org-solidify-link-text (s &optional alist)
21883 "Take link text and make a safe target out of it."
21884 (save-match-data
21885 (let* ((rtn
21886 (mapconcat
21887 'identity
21888 (org-split-string s "[ \t\r\n]+") "--"))
21889 (a (assoc rtn alist)))
21890 (or (cdr a) rtn))))
21892 (defun org-get-min-level (lines)
21893 "Get the minimum level in LINES."
21894 (let ((re "^\\(\\*+\\) ") l min)
21895 (catch 'exit
21896 (while (setq l (pop lines))
21897 (if (string-match re l)
21898 (throw 'exit (org-tr-level (length (match-string 1 l))))))
21899 1)))
21901 ;; Variable holding the vector with section numbers
21902 (defvar org-section-numbers (make-vector org-level-max 0))
21904 (defun org-init-section-numbers ()
21905 "Initialize the vector for the section numbers."
21906 (let* ((level -1)
21907 (numbers (nreverse (org-split-string "" "\\.")))
21908 (depth (1- (length org-section-numbers)))
21909 (i depth) number-string)
21910 (while (>= i 0)
21911 (if (> i level)
21912 (aset org-section-numbers i 0)
21913 (setq number-string (or (car numbers) "0"))
21914 (if (string-match "\\`[A-Z]\\'" number-string)
21915 (aset org-section-numbers i
21916 (- (string-to-char number-string) ?A -1))
21917 (aset org-section-numbers i (string-to-number number-string)))
21918 (pop numbers))
21919 (setq i (1- i)))))
21921 (defun org-section-number (&optional level)
21922 "Return a string with the current section number.
21923 When LEVEL is non-nil, increase section numbers on that level."
21924 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
21925 (when level
21926 (when (> level -1)
21927 (aset org-section-numbers
21928 level (1+ (aref org-section-numbers level))))
21929 (setq idx (1+ level))
21930 (while (<= idx depth)
21931 (if (not (= idx 1))
21932 (aset org-section-numbers idx 0))
21933 (setq idx (1+ idx))))
21934 (setq idx 0)
21935 (while (<= idx depth)
21936 (setq n (aref org-section-numbers idx))
21937 (setq string (concat string (if (not (string= string "")) "." "")
21938 (int-to-string n)))
21939 (setq idx (1+ idx)))
21940 (save-match-data
21941 (if (string-match "\\`\\([@0]\\.\\)+" string)
21942 (setq string (replace-match "" t nil string)))
21943 (if (string-match "\\(\\.0\\)+\\'" string)
21944 (setq string (replace-match "" t nil string))))
21945 string))
21947 ;;; ASCII export
21949 (defvar org-last-level nil) ; dynamically scoped variable
21950 (defvar org-min-level nil) ; dynamically scoped variable
21951 (defvar org-levels-open nil) ; dynamically scoped parameter
21952 (defvar org-ascii-current-indentation nil) ; For communication
21954 (defun org-export-as-ascii (arg)
21955 "Export the outline as a pretty ASCII file.
21956 If there is an active region, export only the region.
21957 The prefix ARG specifies how many levels of the outline should become
21958 underlined headlines. The default is 3."
21959 (interactive "P")
21960 (setq-default org-todo-line-regexp org-todo-line-regexp)
21961 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
21962 (org-infile-export-plist)))
21963 (region-p (org-region-active-p))
21964 (subtree-p
21965 (when region-p
21966 (save-excursion
21967 (goto-char (region-beginning))
21968 (and (org-at-heading-p)
21969 (>= (org-end-of-subtree t t) (region-end))))))
21970 (custom-times org-display-custom-times)
21971 (org-ascii-current-indentation '(0 . 0))
21972 (level 0) line txt
21973 (umax nil)
21974 (umax-toc nil)
21975 (case-fold-search nil)
21976 (filename (concat (file-name-as-directory
21977 (org-export-directory :ascii opt-plist))
21978 (file-name-sans-extension
21979 (or (and subtree-p
21980 (org-entry-get (region-beginning)
21981 "EXPORT_FILE_NAME" t))
21982 (file-name-nondirectory buffer-file-name)))
21983 ".txt"))
21984 (filename (if (equal (file-truename filename)
21985 (file-truename buffer-file-name))
21986 (concat filename ".txt")
21987 filename))
21988 (buffer (find-file-noselect filename))
21989 (org-levels-open (make-vector org-level-max nil))
21990 (odd org-odd-levels-only)
21991 (date (plist-get opt-plist :date))
21992 (author (plist-get opt-plist :author))
21993 (title (or (and subtree-p (org-export-get-title-from-subtree))
21994 (plist-get opt-plist :title)
21995 (and (not
21996 (plist-get opt-plist :skip-before-1st-heading))
21997 (org-export-grab-title-from-buffer))
21998 (file-name-sans-extension
21999 (file-name-nondirectory buffer-file-name))))
22000 (email (plist-get opt-plist :email))
22001 (language (plist-get opt-plist :language))
22002 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
22003 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
22004 (todo nil)
22005 (lang-words nil)
22006 (region
22007 (buffer-substring
22008 (if (org-region-active-p) (region-beginning) (point-min))
22009 (if (org-region-active-p) (region-end) (point-max))))
22010 (lines (org-split-string
22011 (org-cleaned-string-for-export
22012 region
22013 :for-ascii t
22014 :skip-before-1st-heading
22015 (plist-get opt-plist :skip-before-1st-heading)
22016 :archived-trees
22017 (plist-get opt-plist :archived-trees)
22018 :add-text (plist-get opt-plist :text))
22019 "\n"))
22020 thetoc have-headings first-heading-pos
22021 table-open table-buffer)
22023 (let ((inhibit-read-only t))
22024 (org-unmodified
22025 (remove-text-properties (point-min) (point-max)
22026 '(:org-license-to-kill t))))
22028 (setq org-min-level (org-get-min-level lines))
22029 (setq org-last-level org-min-level)
22030 (org-init-section-numbers)
22032 (find-file-noselect filename)
22034 (setq lang-words (or (assoc language org-export-language-setup)
22035 (assoc "en" org-export-language-setup)))
22036 (switch-to-buffer-other-window buffer)
22037 (erase-buffer)
22038 (fundamental-mode)
22039 ;; create local variables for all options, to make sure all called
22040 ;; functions get the correct information
22041 (mapcar (lambda (x)
22042 (set (make-local-variable (cdr x))
22043 (plist-get opt-plist (car x))))
22044 org-export-plist-vars)
22045 (org-set-local 'org-odd-levels-only odd)
22046 (setq umax (if arg (prefix-numeric-value arg)
22047 org-export-headline-levels))
22048 (setq umax-toc (if (integerp org-export-with-toc)
22049 (min org-export-with-toc umax)
22050 umax))
22052 ;; File header
22053 (if title (org-insert-centered title ?=))
22054 (insert "\n")
22055 (if (and (or author email)
22056 org-export-author-info)
22057 (insert (concat (nth 1 lang-words) ": " (or author "")
22058 (if email (concat " <" email ">") "")
22059 "\n")))
22061 (cond
22062 ((and date (string-match "%" date))
22063 (setq date (format-time-string date (current-time))))
22064 (date)
22065 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
22067 (if (and date org-export-time-stamp-file)
22068 (insert (concat (nth 2 lang-words) ": " date"\n")))
22070 (insert "\n\n")
22072 (if org-export-with-toc
22073 (progn
22074 (push (concat (nth 3 lang-words) "\n") thetoc)
22075 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
22076 (mapcar '(lambda (line)
22077 (if (string-match org-todo-line-regexp
22078 line)
22079 ;; This is a headline
22080 (progn
22081 (setq have-headings t)
22082 (setq level (- (match-end 1) (match-beginning 1))
22083 level (org-tr-level level)
22084 txt (match-string 3 line)
22085 todo
22086 (or (and org-export-mark-todo-in-toc
22087 (match-beginning 2)
22088 (not (member (match-string 2 line)
22089 org-done-keywords)))
22090 ; TODO, not DONE
22091 (and org-export-mark-todo-in-toc
22092 (= level umax-toc)
22093 (org-search-todo-below
22094 line lines level))))
22095 (setq txt (org-html-expand-for-ascii txt))
22097 (while (string-match org-bracket-link-regexp txt)
22098 (setq txt
22099 (replace-match
22100 (match-string (if (match-end 2) 3 1) txt)
22101 t t txt)))
22103 (if (and (memq org-export-with-tags '(not-in-toc nil))
22104 (string-match
22105 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
22106 txt))
22107 (setq txt (replace-match "" t t txt)))
22108 (if (string-match quote-re0 txt)
22109 (setq txt (replace-match "" t t txt)))
22111 (if org-export-with-section-numbers
22112 (setq txt (concat (org-section-number level)
22113 " " txt)))
22114 (if (<= level umax-toc)
22115 (progn
22116 (push
22117 (concat
22118 (make-string
22119 (* (max 0 (- level org-min-level)) 4) ?\ )
22120 (format (if todo "%s (*)\n" "%s\n") txt))
22121 thetoc)
22122 (setq org-last-level level))
22123 ))))
22124 lines)
22125 (setq thetoc (if have-headings (nreverse thetoc) nil))))
22127 (org-init-section-numbers)
22128 (while (setq line (pop lines))
22129 ;; Remove the quoted HTML tags.
22130 (setq line (org-html-expand-for-ascii line))
22131 ;; Remove targets
22132 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
22133 (setq line (replace-match "" t t line)))
22134 ;; Replace internal links
22135 (while (string-match org-bracket-link-regexp line)
22136 (setq line (replace-match
22137 (if (match-end 3) "[\\3]" "[\\1]")
22138 t nil line)))
22139 (when custom-times
22140 (setq line (org-translate-time line)))
22141 (cond
22142 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
22143 ;; a Headline
22144 (setq first-heading-pos (or first-heading-pos (point)))
22145 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
22146 txt (match-string 2 line))
22147 (org-ascii-level-start level txt umax lines))
22149 ((and org-export-with-tables
22150 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
22151 (if (not table-open)
22152 ;; New table starts
22153 (setq table-open t table-buffer nil))
22154 ;; Accumulate lines
22155 (setq table-buffer (cons line table-buffer))
22156 (when (or (not lines)
22157 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
22158 (car lines))))
22159 (setq table-open nil
22160 table-buffer (nreverse table-buffer))
22161 (insert (mapconcat
22162 (lambda (x)
22163 (org-fix-indentation x org-ascii-current-indentation))
22164 (org-format-table-ascii table-buffer)
22165 "\n") "\n")))
22167 (setq line (org-fix-indentation line org-ascii-current-indentation))
22168 (if (and org-export-with-fixed-width
22169 (string-match "^\\([ \t]*\\)\\(:\\)" line))
22170 (setq line (replace-match "\\1" nil nil line)))
22171 (insert line "\n"))))
22173 (normal-mode)
22175 ;; insert the table of contents
22176 (when thetoc
22177 (goto-char (point-min))
22178 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
22179 (progn
22180 (goto-char (match-beginning 0))
22181 (replace-match ""))
22182 (goto-char first-heading-pos))
22183 (mapc 'insert thetoc)
22184 (or (looking-at "[ \t]*\n[ \t]*\n")
22185 (insert "\n\n")))
22187 (save-buffer)
22188 ;; remove display and invisible chars
22189 (let (beg end)
22190 (goto-char (point-min))
22191 (while (setq beg (next-single-property-change (point) 'display))
22192 (setq end (next-single-property-change beg 'display))
22193 (delete-region beg end)
22194 (goto-char beg)
22195 (insert "=>"))
22196 (goto-char (point-min))
22197 (while (setq beg (next-single-property-change (point) 'org-cwidth))
22198 (setq end (next-single-property-change beg 'org-cwidth))
22199 (delete-region beg end)
22200 (goto-char beg)))
22201 (goto-char (point-min))))
22203 (defun org-search-todo-below (line lines level)
22204 "Search the subtree below LINE for any TODO entries."
22205 (let ((rest (cdr (memq line lines)))
22206 (re org-todo-line-regexp)
22207 line lv todo)
22208 (catch 'exit
22209 (while (setq line (pop rest))
22210 (if (string-match re line)
22211 (progn
22212 (setq lv (- (match-end 1) (match-beginning 1))
22213 todo (and (match-beginning 2)
22214 (not (member (match-string 2 line)
22215 org-done-keywords))))
22216 ; TODO, not DONE
22217 (if (<= lv level) (throw 'exit nil))
22218 (if todo (throw 'exit t))))))))
22220 (defun org-html-expand-for-ascii (line)
22221 "Handle quoted HTML for ASCII export."
22222 (if org-export-html-expand
22223 (while (string-match "@<[^<>\n]*>" line)
22224 ;; We just remove the tags for now.
22225 (setq line (replace-match "" nil nil line))))
22226 line)
22228 (defun org-insert-centered (s &optional underline)
22229 "Insert the string S centered and underline it with character UNDERLINE."
22230 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
22231 (insert (make-string ind ?\ ) s "\n")
22232 (if underline
22233 (insert (make-string ind ?\ )
22234 (make-string (string-width s) underline)
22235 "\n"))))
22237 (defun org-ascii-level-start (level title umax &optional lines)
22238 "Insert a new level in ASCII export."
22239 (let (char (n (- level umax 1)) (ind 0))
22240 (if (> level umax)
22241 (progn
22242 (insert (make-string (* 2 n) ?\ )
22243 (char-to-string (nth (% n (length org-export-ascii-bullets))
22244 org-export-ascii-bullets))
22245 " " title "\n")
22246 ;; find the indentation of the next non-empty line
22247 (catch 'stop
22248 (while lines
22249 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
22250 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
22251 (throw 'stop (setq ind (org-get-indentation (car lines)))))
22252 (pop lines)))
22253 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
22254 (if (or (not (equal (char-before) ?\n))
22255 (not (equal (char-before (1- (point))) ?\n)))
22256 (insert "\n"))
22257 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
22258 (unless org-export-with-tags
22259 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
22260 (setq title (replace-match "" t t title))))
22261 (if org-export-with-section-numbers
22262 (setq title (concat (org-section-number level) " " title)))
22263 (insert title "\n" (make-string (string-width title) char) "\n")
22264 (setq org-ascii-current-indentation '(0 . 0)))))
22266 (defun org-export-visible (type arg)
22267 "Create a copy of the visible part of the current buffer, and export it.
22268 The copy is created in a temporary buffer and removed after use.
22269 TYPE is the final key (as a string) that also select the export command in
22270 the `C-c C-e' export dispatcher.
22271 As a special case, if the you type SPC at the prompt, the temporary
22272 org-mode file will not be removed but presented to you so that you can
22273 continue to use it. The prefix arg ARG is passed through to the exporting
22274 command."
22275 (interactive
22276 (list (progn
22277 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
22278 (read-char-exclusive))
22279 current-prefix-arg))
22280 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
22281 (error "Invalid export key"))
22282 (let* ((binding (cdr (assoc type
22283 '((?a . org-export-as-ascii)
22284 (?\C-a . org-export-as-ascii)
22285 (?b . org-export-as-html-and-open)
22286 (?\C-b . org-export-as-html-and-open)
22287 (?h . org-export-as-html)
22288 (?H . org-export-as-html-to-buffer)
22289 (?R . org-export-region-as-html)
22290 (?x . org-export-as-xoxo)))))
22291 (keepp (equal type ?\ ))
22292 (file buffer-file-name)
22293 (buffer (get-buffer-create "*Org Export Visible*"))
22294 s e)
22295 ;; Need to hack the drawers here.
22296 (save-excursion
22297 (goto-char (point-min))
22298 (while (re-search-forward org-drawer-regexp nil t)
22299 (goto-char (match-beginning 1))
22300 (or (org-invisible-p) (org-flag-drawer nil))))
22301 (with-current-buffer buffer (erase-buffer))
22302 (save-excursion
22303 (setq s (goto-char (point-min)))
22304 (while (not (= (point) (point-max)))
22305 (goto-char (org-find-invisible))
22306 (append-to-buffer buffer s (point))
22307 (setq s (goto-char (org-find-visible))))
22308 (org-cycle-hide-drawers 'all)
22309 (goto-char (point-min))
22310 (unless keepp
22311 ;; Copy all comment lines to the end, to make sure #+ settings are
22312 ;; still available for the second export step. Kind of a hack, but
22313 ;; does do the trick.
22314 (if (looking-at "#[^\r\n]*")
22315 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
22316 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
22317 (append-to-buffer buffer (1+ (match-beginning 0))
22318 (min (point-max) (1+ (match-end 0))))))
22319 (set-buffer buffer)
22320 (let ((buffer-file-name file)
22321 (org-inhibit-startup t))
22322 (org-mode)
22323 (show-all)
22324 (unless keepp (funcall binding arg))))
22325 (if (not keepp)
22326 (kill-buffer buffer)
22327 (switch-to-buffer-other-window buffer)
22328 (goto-char (point-min)))))
22330 (defun org-find-visible ()
22331 (let ((s (point)))
22332 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
22333 (get-char-property s 'invisible)))
22335 (defun org-find-invisible ()
22336 (let ((s (point)))
22337 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
22338 (not (get-char-property s 'invisible))))
22341 ;;; HTML export
22343 (defun org-get-current-options ()
22344 "Return a string with current options as keyword options.
22345 Does include HTML export options as well as TODO and CATEGORY stuff."
22346 (format
22347 "#+TITLE: %s
22348 #+AUTHOR: %s
22349 #+EMAIL: %s
22350 #+LANGUAGE: %s
22351 #+TEXT: Some descriptive text to be emitted. Several lines OK.
22352 #+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
22353 #+CATEGORY: %s
22354 #+SEQ_TODO: %s
22355 #+TYP_TODO: %s
22356 #+PRIORITIES: %c %c %c
22357 #+STARTUP: %s %s %s %s %s
22358 #+TAGS: %s
22359 #+ARCHIVE: %s
22360 #+LINK: %s
22362 (buffer-name) (user-full-name) user-mail-address org-export-default-language
22363 org-export-headline-levels
22364 org-export-with-section-numbers
22365 org-export-with-toc
22366 org-export-preserve-breaks
22367 org-export-html-expand
22368 org-export-with-fixed-width
22369 org-export-with-tables
22370 org-export-with-sub-superscripts
22371 org-export-with-footnotes
22372 org-export-with-emphasize
22373 org-export-with-TeX-macros
22374 org-export-with-LaTeX-fragments
22375 org-export-skip-text-before-1st-heading
22376 org-export-with-property-drawer
22377 org-export-with-tags
22378 (file-name-nondirectory buffer-file-name)
22379 "TODO FEEDBACK VERIFY DONE"
22380 "Me Jason Marie DONE"
22381 org-highest-priority org-lowest-priority org-default-priority
22382 (cdr (assoc org-startup-folded
22383 '((nil . "showall") (t . "overview") (content . "content"))))
22384 (if org-odd-levels-only "odd" "oddeven")
22385 (if org-hide-leading-stars "hidestars" "showstars")
22386 (if org-startup-align-all-tables "align" "noalign")
22387 (cond ((eq t org-log-done) "logdone")
22388 ((not org-log-done) "nologging")
22389 ((listp org-log-done)
22390 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
22391 org-log-done " ")))
22392 (or (mapconcat (lambda (x)
22393 (cond
22394 ((equal '(:startgroup) x) "{")
22395 ((equal '(:endgroup) x) "}")
22396 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
22397 (t (car x))))
22398 (or org-tag-alist (org-get-buffer-tags)) " ") "")
22399 org-archive-location
22400 "org file:~/org/%s.org"
22403 (defun org-insert-export-options-template ()
22404 "Insert into the buffer a template with information for exporting."
22405 (interactive)
22406 (if (not (bolp)) (newline))
22407 (let ((s (org-get-current-options)))
22408 (and (string-match "#\\+CATEGORY" s)
22409 (setq s (substring s 0 (match-beginning 0))))
22410 (insert s)))
22412 (defun org-toggle-fixed-width-section (arg)
22413 "Toggle the fixed-width export.
22414 If there is no active region, the QUOTE keyword at the current headline is
22415 inserted or removed. When present, it causes the text between this headline
22416 and the next to be exported as fixed-width text, and unmodified.
22417 If there is an active region, this command adds or removes a colon as the
22418 first character of this line. If the first character of a line is a colon,
22419 this line is also exported in fixed-width font."
22420 (interactive "P")
22421 (let* ((cc 0)
22422 (regionp (org-region-active-p))
22423 (beg (if regionp (region-beginning) (point)))
22424 (end (if regionp (region-end)))
22425 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22426 (re "[ \t]*\\(:\\)")
22427 off)
22428 (if regionp
22429 (save-excursion
22430 (goto-char beg)
22431 (setq cc (current-column))
22432 (beginning-of-line 1)
22433 (setq off (looking-at re))
22434 (while (> nlines 0)
22435 (setq nlines (1- nlines))
22436 (beginning-of-line 1)
22437 (cond
22438 (arg
22439 (move-to-column cc t)
22440 (insert ":\n")
22441 (forward-line -1))
22442 ((and off (looking-at re))
22443 (replace-match "" t t nil 1))
22444 ((not off) (move-to-column cc t) (insert ":")))
22445 (forward-line 1)))
22446 (save-excursion
22447 (org-back-to-heading)
22448 (if (looking-at (concat outline-regexp
22449 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
22450 (replace-match "" t t nil 1)
22451 (if (looking-at outline-regexp)
22452 (progn
22453 (goto-char (match-end 0))
22454 (insert org-quote-string " "))))))))
22456 (defun org-export-as-html-and-open (arg)
22457 "Export the outline as HTML and immediately open it with a browser.
22458 If there is an active region, export only the region.
22459 The prefix ARG specifies how many levels of the outline should become
22460 headlines. The default is 3. Lower levels will become bulleted lists."
22461 (interactive "P")
22462 (org-export-as-html arg 'hidden)
22463 (org-open-file buffer-file-name))
22465 (defun org-export-as-html-batch ()
22466 "Call `org-export-as-html', may be used in batch processing as
22467 emacs --batch
22468 --load=$HOME/lib/emacs/org.el
22469 --eval \"(setq org-export-headline-levels 2)\"
22470 --visit=MyFile --funcall org-export-as-html-batch"
22471 (org-export-as-html org-export-headline-levels 'hidden))
22473 (defun org-export-as-html-to-buffer (arg)
22474 "Call `org-exort-as-html` with output to a temporary buffer.
22475 No file is created. The prefix ARG is passed through to `org-export-as-html'."
22476 (interactive "P")
22477 (org-export-as-html arg nil nil "*Org HTML Export*")
22478 (switch-to-buffer-other-window "*Org HTML Export*"))
22480 (defun org-replace-region-by-html (beg end)
22481 "Assume the current region has org-mode syntax, and convert it to HTML.
22482 This can be used in any buffer. For example, you could write an
22483 itemized list in org-mode syntax in an HTML buffer and then use this
22484 command to convert it."
22485 (interactive "r")
22486 (let (reg html buf pop-up-frames)
22487 (save-window-excursion
22488 (if (org-mode-p)
22489 (setq html (org-export-region-as-html
22490 beg end t 'string))
22491 (setq reg (buffer-substring beg end)
22492 buf (get-buffer-create "*Org tmp*"))
22493 (with-current-buffer buf
22494 (erase-buffer)
22495 (insert reg)
22496 (org-mode)
22497 (setq html (org-export-region-as-html
22498 (point-min) (point-max) t 'string)))
22499 (kill-buffer buf)))
22500 (delete-region beg end)
22501 (insert html)))
22503 (defun org-export-region-as-html (beg end &optional body-only buffer)
22504 "Convert region from BEG to END in org-mode buffer to HTML.
22505 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
22506 contents, and only produce the region of converted text, useful for
22507 cut-and-paste operations.
22508 If BUFFER is a buffer or a string, use/create that buffer as a target
22509 of the converted HTML. If BUFFER is the symbol `string', return the
22510 produced HTML as a string and leave not buffer behind. For example,
22511 a Lisp program could call this function in the following way:
22513 (setq html (org-export-region-as-html beg end t 'string))
22515 When called interactively, the output buffer is selected, and shown
22516 in a window. A non-interactive call will only retunr the buffer."
22517 (interactive "r\nP")
22518 (when (interactive-p)
22519 (setq buffer "*Org HTML Export*"))
22520 (let ((transient-mark-mode t) (zmacs-regions t)
22521 rtn)
22522 (goto-char end)
22523 (set-mark (point)) ;; to activate the region
22524 (goto-char beg)
22525 (setq rtn (org-export-as-html
22526 nil nil nil
22527 buffer body-only))
22528 (if (fboundp 'deactivate-mark) (deactivate-mark))
22529 (if (and (interactive-p) (bufferp rtn))
22530 (switch-to-buffer-other-window rtn)
22531 rtn)))
22533 (defun org-export-as-html (arg &optional hidden ext-plist
22534 to-buffer body-only)
22535 "Export the outline as a pretty HTML file.
22536 If there is an active region, export only the region. The prefix
22537 ARG specifies how many levels of the outline should become
22538 headlines. The default is 3. Lower levels will become bulleted
22539 lists. When HIDDEN is non-nil, don't display the HTML buffer.
22540 EXT-PLIST is a property list with external parameters overriding
22541 org-mode's default settings, but still inferior to file-local
22542 settings. When TO-BUFFER is non-nil, create a buffer with that
22543 name and export to that buffer. If TO-BUFFER is the symbol `string',
22544 don't leave any buffer behind but just return the resulting HTML as
22545 a string. When BODY-ONLY is set, don't produce the file header and footer,
22546 simply return the content of <body>...</body>, without even
22547 the body tags themselves."
22548 (interactive "P")
22550 ;; Make sure we have a file name when we need it.
22551 (when (and (not (or to-buffer body-only))
22552 (not buffer-file-name))
22553 (if (buffer-base-buffer)
22554 (org-set-local 'buffer-file-name
22555 (with-current-buffer (buffer-base-buffer)
22556 buffer-file-name))
22557 (error "Need a file name to be able to export.")))
22559 (message "Exporting...")
22560 (setq-default org-todo-line-regexp org-todo-line-regexp)
22561 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
22562 (setq-default org-done-keywords org-done-keywords)
22563 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
22564 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
22565 ext-plist
22566 (org-infile-export-plist)))
22568 (style (plist-get opt-plist :style))
22569 (link-validate (plist-get opt-plist :link-validation-function))
22570 valid thetoc have-headings first-heading-pos
22571 (odd org-odd-levels-only)
22572 (region-p (org-region-active-p))
22573 (subtree-p
22574 (when region-p
22575 (save-excursion
22576 (goto-char (region-beginning))
22577 (and (org-at-heading-p)
22578 (>= (org-end-of-subtree t t) (region-end))))))
22579 ;; The following two are dynamically scoped into other
22580 ;; routines below.
22581 (org-current-export-dir (org-export-directory :html opt-plist))
22582 (org-current-export-file buffer-file-name)
22583 (level 0) (line "") (origline "") txt todo
22584 (umax nil)
22585 (umax-toc nil)
22586 (filename (if to-buffer nil
22587 (concat (file-name-as-directory
22588 (org-export-directory :html opt-plist))
22589 (file-name-sans-extension
22590 (or (and subtree-p
22591 (org-entry-get (region-beginning)
22592 "EXPORT_FILE_NAME" t))
22593 (file-name-nondirectory buffer-file-name)))
22594 "." org-export-html-extension)))
22595 (current-dir (if buffer-file-name
22596 (file-name-directory buffer-file-name)
22597 default-directory))
22598 (buffer (if to-buffer
22599 (cond
22600 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
22601 (t (get-buffer-create to-buffer)))
22602 (find-file-noselect filename)))
22603 (org-levels-open (make-vector org-level-max nil))
22604 (date (plist-get opt-plist :date))
22605 (author (plist-get opt-plist :author))
22606 (title (or (and subtree-p (org-export-get-title-from-subtree))
22607 (plist-get opt-plist :title)
22608 (and (not
22609 (plist-get opt-plist :skip-before-1st-heading))
22610 (org-export-grab-title-from-buffer))
22611 (and buffer-file-name
22612 (file-name-sans-extension
22613 (file-name-nondirectory buffer-file-name)))
22614 "UNTITLED"))
22615 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
22616 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
22617 (inquote nil)
22618 (infixed nil)
22619 (in-local-list nil)
22620 (local-list-num nil)
22621 (local-list-indent nil)
22622 (llt org-plain-list-ordered-item-terminator)
22623 (email (plist-get opt-plist :email))
22624 (language (plist-get opt-plist :language))
22625 (lang-words nil)
22626 (target-alist nil) tg
22627 (head-count 0) cnt
22628 (start 0)
22629 (coding-system (and (boundp 'buffer-file-coding-system)
22630 buffer-file-coding-system))
22631 (coding-system-for-write (or org-export-html-coding-system
22632 coding-system))
22633 (save-buffer-coding-system (or org-export-html-coding-system
22634 coding-system))
22635 (charset (and coding-system-for-write
22636 (fboundp 'coding-system-get)
22637 (coding-system-get coding-system-for-write
22638 'mime-charset)))
22639 (region
22640 (buffer-substring
22641 (if region-p (region-beginning) (point-min))
22642 (if region-p (region-end) (point-max))))
22643 (lines
22644 (org-split-string
22645 (org-cleaned-string-for-export
22646 region
22647 :emph-multiline t
22648 :for-html t
22649 :skip-before-1st-heading
22650 (plist-get opt-plist :skip-before-1st-heading)
22651 :archived-trees
22652 (plist-get opt-plist :archived-trees)
22653 :add-text
22654 (plist-get opt-plist :text)
22655 :LaTeX-fragments
22656 (plist-get opt-plist :LaTeX-fragments))
22657 "[\r\n]"))
22658 table-open type
22659 table-buffer table-orig-buffer
22660 ind start-is-num starter didclose
22661 rpl path desc descp desc1 desc2 link
22664 (let ((inhibit-read-only t))
22665 (org-unmodified
22666 (remove-text-properties (point-min) (point-max)
22667 '(:org-license-to-kill t))))
22669 (message "Exporting...")
22671 (setq org-min-level (org-get-min-level lines))
22672 (setq org-last-level org-min-level)
22673 (org-init-section-numbers)
22675 (cond
22676 ((and date (string-match "%" date))
22677 (setq date (format-time-string date (current-time))))
22678 (date)
22679 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
22681 ;; Get the language-dependent settings
22682 (setq lang-words (or (assoc language org-export-language-setup)
22683 (assoc "en" org-export-language-setup)))
22685 ;; Switch to the output buffer
22686 (set-buffer buffer)
22687 (erase-buffer)
22688 (fundamental-mode)
22690 (and (fboundp 'set-buffer-file-coding-system)
22691 (set-buffer-file-coding-system coding-system-for-write))
22693 (let ((case-fold-search nil)
22694 (org-odd-levels-only odd))
22695 ;; create local variables for all options, to make sure all called
22696 ;; functions get the correct information
22697 (mapcar (lambda (x)
22698 (set (make-local-variable (cdr x))
22699 (plist-get opt-plist (car x))))
22700 org-export-plist-vars)
22701 (setq umax (if arg (prefix-numeric-value arg)
22702 org-export-headline-levels))
22703 (setq umax-toc (if (integerp org-export-with-toc)
22704 (min org-export-with-toc umax)
22705 umax))
22706 (unless body-only
22707 ;; File header
22708 (insert (format
22709 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
22710 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
22711 <html xmlns=\"http://www.w3.org/1999/xhtml\"
22712 lang=\"%s\" xml:lang=\"%s\">
22713 <head>
22714 <title>%s</title>
22715 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
22716 <meta name=\"generator\" content=\"Org-mode\"/>
22717 <meta name=\"generated\" content=\"%s\"/>
22718 <meta name=\"author\" content=\"%s\"/>
22720 </head><body>
22722 language language (org-html-expand title)
22723 (or charset "iso-8859-1") date author style))
22725 (insert (or (plist-get opt-plist :preamble) ""))
22727 (when (plist-get opt-plist :auto-preamble)
22728 (if title (insert (format org-export-html-title-format
22729 (org-html-expand title))))))
22731 (if (and org-export-with-toc (not body-only))
22732 (progn
22733 (push (format "<h%d>%s</h%d>\n"
22734 org-export-html-toplevel-hlevel
22735 (nth 3 lang-words)
22736 org-export-html-toplevel-hlevel)
22737 thetoc)
22738 (push "<ul>\n<li>" thetoc)
22739 (setq lines
22740 (mapcar '(lambda (line)
22741 (if (string-match org-todo-line-regexp line)
22742 ;; This is a headline
22743 (progn
22744 (setq have-headings t)
22745 (setq level (- (match-end 1) (match-beginning 1))
22746 level (org-tr-level level)
22747 txt (save-match-data
22748 (org-html-expand
22749 (org-export-cleanup-toc-line
22750 (match-string 3 line))))
22751 todo
22752 (or (and org-export-mark-todo-in-toc
22753 (match-beginning 2)
22754 (not (member (match-string 2 line)
22755 org-done-keywords)))
22756 ; TODO, not DONE
22757 (and org-export-mark-todo-in-toc
22758 (= level umax-toc)
22759 (org-search-todo-below
22760 line lines level))))
22761 (if (and (memq org-export-with-tags '(not-in-toc nil))
22762 (string-match
22763 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
22764 txt))
22765 (setq txt (replace-match "" t t txt)))
22766 (if (string-match quote-re0 txt)
22767 (setq txt (replace-match "" t t txt)))
22768 (if org-export-with-section-numbers
22769 (setq txt (concat (org-section-number level)
22770 " " txt)))
22771 (if (<= level (max umax umax-toc))
22772 (setq head-count (+ head-count 1)))
22773 (if (<= level umax-toc)
22774 (progn
22775 (if (> level org-last-level)
22776 (progn
22777 (setq cnt (- level org-last-level))
22778 (while (>= (setq cnt (1- cnt)) 0)
22779 (push "\n<ul>\n<li>" thetoc))
22780 (push "\n" thetoc)))
22781 (if (< level org-last-level)
22782 (progn
22783 (setq cnt (- org-last-level level))
22784 (while (>= (setq cnt (1- cnt)) 0)
22785 (push "</li>\n</ul>" thetoc))
22786 (push "\n" thetoc)))
22787 ;; Check for targets
22788 (while (string-match org-target-regexp line)
22789 (setq tg (match-string 1 line)
22790 line (replace-match
22791 (concat "@<span class=\"target\">" tg "@</span> ")
22792 t t line))
22793 (push (cons (org-solidify-link-text tg)
22794 (format "sec-%d" head-count))
22795 target-alist))
22796 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
22797 (setq txt (replace-match "" t t txt)))
22798 (push
22799 (format
22800 (if todo
22801 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
22802 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
22803 head-count txt) thetoc)
22805 (setq org-last-level level))
22807 line)
22808 lines))
22809 (while (> org-last-level (1- org-min-level))
22810 (setq org-last-level (1- org-last-level))
22811 (push "</li>\n</ul>\n" thetoc))
22812 (setq thetoc (if have-headings (nreverse thetoc) nil))))
22814 (setq head-count 0)
22815 (org-init-section-numbers)
22817 (while (setq line (pop lines) origline line)
22818 (catch 'nextline
22820 ;; end of quote section?
22821 (when (and inquote (string-match "^\\*+ " line))
22822 (insert "</pre>\n")
22823 (setq inquote nil))
22824 ;; inside a quote section?
22825 (when inquote
22826 (insert (org-html-protect line) "\n")
22827 (throw 'nextline nil))
22829 ;; verbatim lines
22830 (when (and org-export-with-fixed-width
22831 (string-match "^[ \t]*:\\(.*\\)" line))
22832 (when (not infixed)
22833 (setq infixed t)
22834 (insert "<pre>\n"))
22835 (insert (org-html-protect (match-string 1 line)) "\n")
22836 (when (and lines
22837 (not (string-match "^[ \t]*\\(:.*\\)"
22838 (car lines))))
22839 (setq infixed nil)
22840 (insert "</pre>\n"))
22841 (throw 'nextline nil))
22843 ;; Protected HTML
22844 (when (get-text-property 0 'org-protected line)
22845 (let (par)
22846 (when (re-search-backward
22847 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
22848 (setq par (match-string 1))
22849 (replace-match "\\2\n"))
22850 (insert line "\n")
22851 (while (and lines
22852 (get-text-property 0 'org-protected (car lines)))
22853 (insert (pop lines) "\n"))
22854 (and par (insert "<p>\n")))
22855 (throw 'nextline nil))
22857 ;; Horizontal line
22858 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
22859 (insert "\n<hr/>\n")
22860 (throw 'nextline nil))
22862 ;; make targets to anchors
22863 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
22864 (cond
22865 ((match-end 2)
22866 (setq line (replace-match
22867 (concat "@<a name=\""
22868 (org-solidify-link-text (match-string 1 line))
22869 "\">\\nbsp@</a>")
22870 t t line)))
22871 ((and org-export-with-toc (equal (string-to-char line) ?*))
22872 (setq line (replace-match
22873 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
22874 ; (concat "@<i>" (match-string 1 line) "@</i> ")
22875 t t line)))
22877 (setq line (replace-match
22878 (concat "@<a name=\""
22879 (org-solidify-link-text (match-string 1 line))
22880 "\" class=\"target\">" (match-string 1 line) "@</a> ")
22881 t t line)))))
22883 (setq line (org-html-handle-time-stamps line))
22885 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
22886 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
22887 ;; Also handle sub_superscripts and checkboxes
22888 (setq line (org-html-expand line))
22890 ;; Format the links
22891 (setq start 0)
22892 (while (string-match org-bracket-link-analytic-regexp line start)
22893 (setq start (match-beginning 0))
22894 (setq type (if (match-end 2) (match-string 2 line) "internal"))
22895 (setq path (match-string 3 line))
22896 (setq desc1 (if (match-end 5) (match-string 5 line))
22897 desc2 (if (match-end 2) (concat type ":" path) path)
22898 descp (and desc1 (not (equal desc1 desc2)))
22899 desc (or desc1 desc2))
22900 ;; Make an image out of the description if that is so wanted
22901 (when (and descp (org-file-image-p desc))
22902 (save-match-data
22903 (if (string-match "^file:" desc)
22904 (setq desc (substring desc (match-end 0)))))
22905 (setq desc (concat "<img src=\"" desc "\"/>")))
22906 ;; FIXME: do we need to unescape here somewhere?
22907 (cond
22908 ((equal type "internal")
22909 (setq rpl
22910 (concat
22911 "<a href=\"#"
22912 (org-solidify-link-text
22913 (save-match-data (org-link-unescape path)) target-alist)
22914 "\">" desc "</a>")))
22915 ((member type '("http" "https"))
22916 ;; standard URL, just check if we need to inline an image
22917 (if (and (or (eq t org-export-html-inline-images)
22918 (and org-export-html-inline-images (not descp)))
22919 (org-file-image-p path))
22920 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
22921 (setq link (concat type ":" path))
22922 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
22923 ((member type '("ftp" "mailto" "news"))
22924 ;; standard URL
22925 (setq link (concat type ":" path))
22926 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
22927 ((string= type "file")
22928 ;; FILE link
22929 (let* ((filename path)
22930 (abs-p (file-name-absolute-p filename))
22931 thefile file-is-image-p search)
22932 (save-match-data
22933 (if (string-match "::\\(.*\\)" filename)
22934 (setq search (match-string 1 filename)
22935 filename (replace-match "" t nil filename)))
22936 (setq valid
22937 (if (functionp link-validate)
22938 (funcall link-validate filename current-dir)
22940 (setq file-is-image-p (org-file-image-p filename))
22941 (setq thefile (if abs-p (expand-file-name filename) filename))
22942 (when (and org-export-html-link-org-files-as-html
22943 (string-match "\\.org$" thefile))
22944 (setq thefile (concat (substring thefile 0
22945 (match-beginning 0))
22946 "." org-export-html-extension))
22947 (if (and search
22948 ;; make sure this is can be used as target search
22949 (not (string-match "^[0-9]*$" search))
22950 (not (string-match "^\\*" search))
22951 (not (string-match "^/.*/$" search)))
22952 (setq thefile (concat thefile "#"
22953 (org-solidify-link-text
22954 (org-link-unescape search)))))
22955 (when (string-match "^file:" desc)
22956 (setq desc (replace-match "" t t desc))
22957 (if (string-match "\\.org$" desc)
22958 (setq desc (replace-match "" t t desc))))))
22959 (setq rpl (if (and file-is-image-p
22960 (or (eq t org-export-html-inline-images)
22961 (and org-export-html-inline-images
22962 (not descp))))
22963 (concat "<img src=\"" thefile "\"/>")
22964 (concat "<a href=\"" thefile "\">" desc "</a>")))
22965 (if (not valid) (setq rpl desc))))
22966 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
22967 (setq rpl (concat "<i>&lt;" type ":"
22968 (save-match-data (org-link-unescape path))
22969 "&gt;</i>"))))
22970 (setq line (replace-match rpl t t line)
22971 start (+ start (length rpl))))
22973 ;; TODO items
22974 (if (and (string-match org-todo-line-regexp line)
22975 (match-beginning 2))
22977 (setq line
22978 (concat (substring line 0 (match-beginning 2))
22979 "<span class=\""
22980 (if (member (match-string 2 line)
22981 org-done-keywords)
22982 "done" "todo")
22983 "\">" (match-string 2 line)
22984 "</span>" (substring line (match-end 2)))))
22986 ;; Does this contain a reference to a footnote?
22987 (when org-export-with-footnotes
22988 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line)
22989 (let ((n (match-string 2 line)))
22990 (setq line
22991 (replace-match
22992 (format
22993 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
22994 (match-string 1 line) n n n)
22995 t t line)))))
22997 (cond
22998 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
22999 ;; This is a headline
23000 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
23001 txt (match-string 2 line))
23002 (if (string-match quote-re0 txt)
23003 (setq txt (replace-match "" t t txt)))
23004 (if (<= level (max umax umax-toc))
23005 (setq head-count (+ head-count 1)))
23006 (when in-local-list
23007 ;; Close any local lists before inserting a new header line
23008 (while local-list-num
23009 (org-close-li)
23010 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
23011 (pop local-list-num))
23012 (setq local-list-indent nil
23013 in-local-list nil))
23014 (setq first-heading-pos (or first-heading-pos (point)))
23015 (org-html-level-start level txt umax
23016 (and org-export-with-toc (<= level umax))
23017 head-count)
23018 ;; QUOTES
23019 (when (string-match quote-re line)
23020 (insert "<pre>")
23021 (setq inquote t)))
23023 ((and org-export-with-tables
23024 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
23025 (if (not table-open)
23026 ;; New table starts
23027 (setq table-open t table-buffer nil table-orig-buffer nil))
23028 ;; Accumulate lines
23029 (setq table-buffer (cons line table-buffer)
23030 table-orig-buffer (cons origline table-orig-buffer))
23031 (when (or (not lines)
23032 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
23033 (car lines))))
23034 (setq table-open nil
23035 table-buffer (nreverse table-buffer)
23036 table-orig-buffer (nreverse table-orig-buffer))
23037 (org-close-par-maybe)
23038 (insert (org-format-table-html table-buffer table-orig-buffer))))
23040 ;; Normal lines
23041 (when (string-match
23042 (cond
23043 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23044 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23045 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23046 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
23047 line)
23048 (setq ind (org-get-string-indentation line)
23049 start-is-num (match-beginning 4)
23050 starter (if (match-beginning 2)
23051 (substring (match-string 2 line) 0 -1))
23052 line (substring line (match-beginning 5)))
23053 (unless (string-match "[^ \t]" line)
23054 ;; empty line. Pretend indentation is large.
23055 (setq ind (if org-empty-line-terminates-plain-lists
23057 (1+ (or (car local-list-indent) 1)))))
23058 (setq didclose nil)
23059 (while (and in-local-list
23060 (or (and (= ind (car local-list-indent))
23061 (not starter))
23062 (< ind (car local-list-indent))))
23063 (setq didclose t)
23064 (org-close-li)
23065 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
23066 (pop local-list-num) (pop local-list-indent)
23067 (setq in-local-list local-list-indent))
23068 (cond
23069 ((and starter
23070 (or (not in-local-list)
23071 (> ind (car local-list-indent))))
23072 ;; Start new (level of) list
23073 (org-close-par-maybe)
23074 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
23075 (push start-is-num local-list-num)
23076 (push ind local-list-indent)
23077 (setq in-local-list t))
23078 (starter
23079 ;; continue current list
23080 (org-close-li)
23081 (insert "<li>\n"))
23082 (didclose
23083 ;; we did close a list, normal text follows: need <p>
23084 (org-open-par)))
23085 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
23086 (setq line
23087 (replace-match
23088 (if (equal (match-string 1 line) "X")
23089 "<b>[X]</b>"
23090 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
23091 t t line))))
23093 ;; Empty lines start a new paragraph. If hand-formatted lists
23094 ;; are not fully interpreted, lines starting with "-", "+", "*"
23095 ;; also start a new paragraph.
23096 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
23098 ;; Is this the start of a footnote?
23099 (when org-export-with-footnotes
23100 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
23101 (org-close-par-maybe)
23102 (let ((n (match-string 1 line)))
23103 (setq line (replace-match
23104 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
23106 ;; Check if the line break needs to be conserved
23107 (cond
23108 ((string-match "\\\\\\\\[ \t]*$" line)
23109 (setq line (replace-match "<br/>" t t line)))
23110 (org-export-preserve-breaks
23111 (setq line (concat line "<br/>"))))
23113 (insert line "\n")))))
23115 ;; Properly close all local lists and other lists
23116 (when inquote (insert "</pre>\n"))
23117 (when in-local-list
23118 ;; Close any local lists before inserting a new header line
23119 (while local-list-num
23120 (org-close-li)
23121 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
23122 (pop local-list-num))
23123 (setq local-list-indent nil
23124 in-local-list nil))
23125 (org-html-level-start 1 nil umax
23126 (and org-export-with-toc (<= level umax))
23127 head-count)
23129 (unless body-only
23130 (when (plist-get opt-plist :auto-postamble)
23131 (when (and org-export-author-info author)
23132 (insert "<p class=\"author\"> "
23133 (nth 1 lang-words) ": " author "\n")
23134 (when email
23135 (insert "<a href=\"mailto:" email "\">&lt;"
23136 email "&gt;</a>\n"))
23137 (insert "</p>\n"))
23138 (when (and date org-export-time-stamp-file)
23139 (insert "<p class=\"date\"> "
23140 (nth 2 lang-words) ": "
23141 date "</p>\n")))
23143 (if org-export-html-with-timestamp
23144 (insert org-export-html-html-helper-timestamp))
23145 (insert (or (plist-get opt-plist :postamble) ""))
23146 (insert "</body>\n</html>\n"))
23148 (normal-mode)
23149 (if (eq major-mode default-major-mode) (html-mode))
23151 ;; insert the table of contents
23152 (goto-char (point-min))
23153 (when thetoc
23154 (if (or (re-search-forward
23155 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
23156 (re-search-forward
23157 "\\[TABLE-OF-CONTENTS\\]" nil t))
23158 (progn
23159 (goto-char (match-beginning 0))
23160 (replace-match ""))
23161 (goto-char first-heading-pos)
23162 (when (looking-at "\\s-*</p>")
23163 (goto-char (match-end 0))
23164 (insert "\n")))
23165 (mapc 'insert thetoc))
23166 ;; remove empty paragraphs and lists
23167 (goto-char (point-min))
23168 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
23169 (replace-match ""))
23170 (goto-char (point-min))
23171 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
23172 (replace-match ""))
23173 (or to-buffer (save-buffer))
23174 (goto-char (point-min))
23175 (message "Exporting... done")
23176 (if (eq to-buffer 'string)
23177 (prog1 (buffer-substring (point-min) (point-max))
23178 (kill-buffer (current-buffer)))
23179 (current-buffer)))))
23181 (defvar org-table-colgroup-info nil)
23182 (defun org-format-table-ascii (lines)
23183 "Format a table for ascii export."
23184 (if (stringp lines)
23185 (setq lines (org-split-string lines "\n")))
23186 (if (not (string-match "^[ \t]*|" (car lines)))
23187 ;; Table made by table.el - test for spanning
23188 lines
23190 ;; A normal org table
23191 ;; Get rid of hlines at beginning and end
23192 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
23193 (setq lines (nreverse lines))
23194 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
23195 (setq lines (nreverse lines))
23196 (when org-export-table-remove-special-lines
23197 ;; Check if the table has a marking column. If yes remove the
23198 ;; column and the special lines
23199 (setq lines (org-table-clean-before-export lines)))
23200 ;; Get rid of the vertical lines except for grouping
23201 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
23202 rtn line vl1 start)
23203 (while (setq line (pop lines))
23204 (if (string-match org-table-hline-regexp line)
23205 (and (string-match "|\\(.*\\)|" line)
23206 (setq line (replace-match " \\1" t nil line)))
23207 (setq start 0 vl1 vl)
23208 (while (string-match "|" line start)
23209 (setq start (match-end 0))
23210 (or (pop vl1) (setq line (replace-match " " t t line)))))
23211 (push line rtn))
23212 (nreverse rtn))))
23214 (defun org-colgroup-info-to-vline-list (info)
23215 (let (vl new last)
23216 (while info
23217 (setq last new new (pop info))
23218 (if (or (memq last '(:end :startend))
23219 (memq new '(:start :startend)))
23220 (push t vl)
23221 (push nil vl)))
23222 (setq vl (nreverse vl))
23223 (and vl (setcar vl nil))
23224 vl))
23226 (defun org-format-table-html (lines olines)
23227 "Find out which HTML converter to use and return the HTML code."
23228 (if (stringp lines)
23229 (setq lines (org-split-string lines "\n")))
23230 (if (string-match "^[ \t]*|" (car lines))
23231 ;; A normal org table
23232 (org-format-org-table-html lines)
23233 ;; Table made by table.el - test for spanning
23234 (let* ((hlines (delq nil (mapcar
23235 (lambda (x)
23236 (if (string-match "^[ \t]*\\+-" x) x
23237 nil))
23238 lines)))
23239 (first (car hlines))
23240 (ll (and (string-match "\\S-+" first)
23241 (match-string 0 first)))
23242 (re (concat "^[ \t]*" (regexp-quote ll)))
23243 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
23244 hlines))))
23245 (if (and (not spanning)
23246 (not org-export-prefer-native-exporter-for-tables))
23247 ;; We can use my own converter with HTML conversions
23248 (org-format-table-table-html lines)
23249 ;; Need to use the code generator in table.el, with the original text.
23250 (org-format-table-table-html-using-table-generate-source olines)))))
23252 (defun org-format-org-table-html (lines &optional splice)
23253 "Format a table into HTML."
23254 ;; Get rid of hlines at beginning and end
23255 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
23256 (setq lines (nreverse lines))
23257 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
23258 (setq lines (nreverse lines))
23259 (when org-export-table-remove-special-lines
23260 ;; Check if the table has a marking column. If yes remove the
23261 ;; column and the special lines
23262 (setq lines (org-table-clean-before-export lines)))
23264 (let ((head (and org-export-highlight-first-table-line
23265 (delq nil (mapcar
23266 (lambda (x) (string-match "^[ \t]*|-" x))
23267 (cdr lines)))))
23268 (nlines 0) fnum i
23269 tbopen line fields html gr colgropen)
23270 (if splice (setq head nil))
23271 (unless splice (push (if head "<thead>" "<tbody>") html))
23272 (setq tbopen t)
23273 (while (setq line (pop lines))
23274 (catch 'next-line
23275 (if (string-match "^[ \t]*|-" line)
23276 (progn
23277 (unless splice
23278 (push (if head "</thead>" "</tbody>") html)
23279 (if lines (push "<tbody>" html) (setq tbopen nil)))
23280 (setq head nil) ;; head ends here, first time around
23281 ;; ignore this line
23282 (throw 'next-line t)))
23283 ;; Break the line into fields
23284 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
23285 (unless fnum (setq fnum (make-vector (length fields) 0)))
23286 (setq nlines (1+ nlines) i -1)
23287 (push (concat "<tr>"
23288 (mapconcat
23289 (lambda (x)
23290 (setq i (1+ i))
23291 (if (and (< i nlines)
23292 (string-match org-table-number-regexp x))
23293 (incf (aref fnum i)))
23294 (if head
23295 (concat (car org-export-table-header-tags) x
23296 (cdr org-export-table-header-tags))
23297 (concat (car org-export-table-data-tags) x
23298 (cdr org-export-table-data-tags))))
23299 fields "")
23300 "</tr>")
23301 html)))
23302 (unless splice (if tbopen (push "</tbody>" html)))
23303 (unless splice (push "</table>\n" html))
23304 (setq html (nreverse html))
23305 (unless splice
23306 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
23307 (push (mapconcat
23308 (lambda (x)
23309 (setq gr (pop org-table-colgroup-info))
23310 (format "%s<COL align=\"%s\"></COL>%s"
23311 (if (memq gr '(:start :startend))
23312 (prog1
23313 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
23314 (setq colgropen t))
23316 (if (> (/ (float x) nlines) org-table-number-fraction)
23317 "right" "left")
23318 (if (memq gr '(:end :startend))
23319 (progn (setq colgropen nil) "</colgroup>")
23320 "")))
23321 fnum "")
23322 html)
23323 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
23324 (push org-export-html-table-tag html))
23325 (concat (mapconcat 'identity html "\n") "\n")))
23327 (defun org-table-clean-before-export (lines)
23328 "Check if the table has a marking column.
23329 If yes remove the column and the special lines."
23330 (setq org-table-colgroup-info nil)
23331 (if (memq nil
23332 (mapcar
23333 (lambda (x) (or (string-match "^[ \t]*|-" x)
23334 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
23335 lines))
23336 (progn
23337 (setq org-table-clean-did-remove-column nil)
23338 (delq nil
23339 (mapcar
23340 (lambda (x)
23341 (cond
23342 ((string-match "^[ \t]*| */ *|" x)
23343 (setq org-table-colgroup-info
23344 (mapcar (lambda (x)
23345 (cond ((member x '("<" "&lt;")) :start)
23346 ((member x '(">" "&gt;")) :end)
23347 ((member x '("<>" "&lt;&gt;")) :startend)
23348 (t nil)))
23349 (org-split-string x "[ \t]*|[ \t]*")))
23350 nil)
23351 (t x)))
23352 lines)))
23353 (setq org-table-clean-did-remove-column t)
23354 (delq nil
23355 (mapcar
23356 (lambda (x)
23357 (cond
23358 ((string-match "^[ \t]*| */ *|" x)
23359 (setq org-table-colgroup-info
23360 (mapcar (lambda (x)
23361 (cond ((member x '("<" "&lt;")) :start)
23362 ((member x '(">" "&gt;")) :end)
23363 ((member x '("<>" "&lt;&gt;")) :startend)
23364 (t nil)))
23365 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
23366 nil)
23367 ((string-match "^[ \t]*| *[!_^/] *|" x)
23368 nil) ; ignore this line
23369 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
23370 (string-match "^\\([ \t]*\\)|[^|]*|" x))
23371 ;; remove the first column
23372 (replace-match "\\1|" t nil x))
23373 (t (error "This should not happen"))))
23374 lines))))
23376 (defun org-format-table-table-html (lines)
23377 "Format a table generated by table.el into HTML.
23378 This conversion does *not* use `table-generate-source' from table.el.
23379 This has the advantage that Org-mode's HTML conversions can be used.
23380 But it has the disadvantage, that no cell- or row-spanning is allowed."
23381 (let (line field-buffer
23382 (head org-export-highlight-first-table-line)
23383 fields html empty)
23384 (setq html (concat org-export-html-table-tag "\n"))
23385 (while (setq line (pop lines))
23386 (setq empty "&nbsp;")
23387 (catch 'next-line
23388 (if (string-match "^[ \t]*\\+-" line)
23389 (progn
23390 (if field-buffer
23391 (progn
23392 (setq
23393 html
23394 (concat
23395 html
23396 "<tr>"
23397 (mapconcat
23398 (lambda (x)
23399 (if (equal x "") (setq x empty))
23400 (if head
23401 (concat (car org-export-table-header-tags) x
23402 (cdr org-export-table-header-tags))
23403 (concat (car org-export-table-data-tags) x
23404 (cdr org-export-table-data-tags))))
23405 field-buffer "\n")
23406 "</tr>\n"))
23407 (setq head nil)
23408 (setq field-buffer nil)))
23409 ;; Ignore this line
23410 (throw 'next-line t)))
23411 ;; Break the line into fields and store the fields
23412 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
23413 (if field-buffer
23414 (setq field-buffer (mapcar
23415 (lambda (x)
23416 (concat x "<br/>" (pop fields)))
23417 field-buffer))
23418 (setq field-buffer fields))))
23419 (setq html (concat html "</table>\n"))
23420 html))
23422 (defun org-format-table-table-html-using-table-generate-source (lines)
23423 "Format a table into html, using `table-generate-source' from table.el.
23424 This has the advantage that cell- or row-spanning is allowed.
23425 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
23426 (require 'table)
23427 (with-current-buffer (get-buffer-create " org-tmp1 ")
23428 (erase-buffer)
23429 (insert (mapconcat 'identity lines "\n"))
23430 (goto-char (point-min))
23431 (if (not (re-search-forward "|[^+]" nil t))
23432 (error "Error processing table"))
23433 (table-recognize-table)
23434 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
23435 (table-generate-source 'html " org-tmp2 ")
23436 (set-buffer " org-tmp2 ")
23437 (buffer-substring (point-min) (point-max))))
23439 (defun org-html-handle-time-stamps (s)
23440 "Format time stamps in string S, or remove them."
23441 (catch 'exit
23442 (let (r b)
23443 (while (string-match org-maybe-keyword-time-regexp s)
23444 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
23445 ;; never export CLOCK
23446 (throw 'exit ""))
23447 (or b (setq b (substring s 0 (match-beginning 0))))
23448 (if (not org-export-with-timestamps)
23449 (setq r (concat r (substring s 0 (match-beginning 0)))
23450 s (substring s (match-end 0)))
23451 (setq r (concat
23452 r (substring s 0 (match-beginning 0))
23453 (if (match-end 1)
23454 (format "@<span class=\"timestamp-kwd\">%s @</span>"
23455 (match-string 1 s)))
23456 (format " @<span class=\"timestamp\">%s@</span>"
23457 (substring
23458 (org-translate-time (match-string 3 s)) 1 -1)))
23459 s (substring s (match-end 0)))))
23460 ;; Line break if line started and ended with time stamp stuff
23461 (if (not r)
23463 (setq r (concat r s))
23464 (unless (string-match "\\S-" (concat b s))
23465 (setq r (concat r "@<br/>")))
23466 r))))
23468 (defun org-html-protect (s)
23469 ;; convert & to &amp;, < to &lt; and > to &gt;
23470 (let ((start 0))
23471 (while (string-match "&" s start)
23472 (setq s (replace-match "&amp;" t t s)
23473 start (1+ (match-beginning 0))))
23474 (while (string-match "<" s)
23475 (setq s (replace-match "&lt;" t t s)))
23476 (while (string-match ">" s)
23477 (setq s (replace-match "&gt;" t t s))))
23480 (defun org-export-cleanup-toc-line (s)
23481 "Remove tags and time staps from lines going into the toc."
23482 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
23483 (setq s (replace-match "" t t s)))
23484 (when org-export-remove-timestamps-from-toc
23485 (while (string-match org-maybe-keyword-time-regexp s)
23486 (setq s (replace-match "" t t s))))
23487 (while (string-match org-bracket-link-regexp s)
23488 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
23489 t t s)))
23492 (defun org-html-expand (string)
23493 "Prepare STRING for HTML export. Applies all active conversions.
23494 If there are links in the string, don't modify these."
23495 (let* (m s l res)
23496 (while (setq m (string-match org-bracket-link-regexp string))
23497 (setq s (substring string 0 m)
23498 l (match-string 0 string)
23499 string (substring string (match-end 0)))
23500 (push (org-html-do-expand s) res)
23501 (push l res))
23502 (push (org-html-do-expand string) res)
23503 (apply 'concat (nreverse res))))
23505 (defun org-html-do-expand (s)
23506 "Apply all active conversions to translate special ASCII to HTML."
23507 (setq s (org-html-protect s))
23508 (if org-export-html-expand
23509 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
23510 (setq s (replace-match "<\\1>" t nil s))))
23511 (if org-export-with-emphasize
23512 (setq s (org-export-html-convert-emphasize s)))
23513 (if org-export-with-sub-superscripts
23514 (setq s (org-export-html-convert-sub-super s)))
23515 (if org-export-with-TeX-macros
23516 (let ((start 0) wd ass)
23517 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
23518 (setq wd (match-string 1 s))
23519 (if (setq ass (assoc wd org-html-entities))
23520 (setq s (replace-match (or (cdr ass)
23521 (concat "&" (car ass) ";"))
23522 t t s))
23523 (setq start (+ start (length wd)))))))
23526 (defun org-create-multibrace-regexp (left right n)
23527 "Create a regular expression which will match a balanced sexp.
23528 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
23529 as single character strings.
23530 The regexp returned will match the entire expression including the
23531 delimiters. It will also define a single group which contains the
23532 match except for the outermost delimiters. The maximum depth of
23533 stacked delimiters is N. Escaping delimiters is not possible."
23534 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
23535 (or "\\|")
23536 (re nothing)
23537 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
23538 (while (> n 1)
23539 (setq n (1- n)
23540 re (concat re or next)
23541 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
23542 (concat left "\\(" re "\\)" right)))
23544 (defvar org-match-substring-regexp
23545 (concat
23546 "\\([^\\]\\)\\([_^]\\)\\("
23547 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
23548 "\\|"
23549 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
23550 "\\|"
23551 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
23552 "The regular expression matching a sub- or superscript.")
23554 ;(let ((s "a\\_b"))
23555 ; (and (string-match org-match-substring-regexp s)
23556 ; (conca t (match-string 1 s) ":::" (match-string 2 s))))
23558 (defun org-export-html-convert-sub-super (string)
23559 "Convert sub- and superscripts in STRING to HTML."
23560 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
23561 (while (string-match org-match-substring-regexp string s)
23562 (if (and requireb (match-end 8))
23563 (setq s (match-end 2))
23564 (setq s (match-end 1)
23565 key (if (string= (match-string 2 string) "_") "sub" "sup")
23566 c (or (match-string 8 string)
23567 (match-string 6 string)
23568 (match-string 5 string))
23569 string (replace-match
23570 (concat (match-string 1 string)
23571 "<" key ">" c "</" key ">")
23572 t t string))))
23573 (while (string-match "\\\\\\([_^]\\)" string)
23574 (setq string (replace-match (match-string 1 string) t t string)))
23575 string))
23577 (defun org-export-html-convert-emphasize (string)
23578 "Apply emphasis."
23579 (let ((s 0))
23580 (while (string-match org-emph-re string s)
23581 (if (not (equal
23582 (substring string (match-beginning 3) (1+ (match-beginning 3)))
23583 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
23584 (setq string (replace-match
23585 (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
23586 "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist))
23587 "\\5") t nil string))
23588 (setq s (1+ s))))
23589 string))
23591 (defvar org-par-open nil)
23592 (defun org-open-par ()
23593 "Insert <p>, but first close previous paragraph if any."
23594 (org-close-par-maybe)
23595 (insert "\n<p>")
23596 (setq org-par-open t))
23597 (defun org-close-par-maybe ()
23598 "Close paragraph if there is one open."
23599 (when org-par-open
23600 (insert "</p>")
23601 (setq org-par-open nil)))
23602 (defun org-close-li ()
23603 "Close <li> if necessary."
23604 (org-close-par-maybe)
23605 (insert "</li>\n"))
23607 (defvar body-only) ; dynamically scoped into this.
23608 (defun org-html-level-start (level title umax with-toc head-count)
23609 "Insert a new level in HTML export.
23610 When TITLE is nil, just close all open levels."
23611 (org-close-par-maybe)
23612 (let ((l (1+ (max level umax))))
23613 (while (<= l org-level-max)
23614 (if (aref org-levels-open (1- l))
23615 (progn
23616 (org-html-level-close l)
23617 (aset org-levels-open (1- l) nil)))
23618 (setq l (1+ l)))
23619 (when title
23620 ;; If title is nil, this means this function is called to close
23621 ;; all levels, so the rest is done only if title is given
23622 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
23623 (setq title (replace-match
23624 (if org-export-with-tags
23625 (save-match-data
23626 (concat
23627 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
23628 (mapconcat 'identity (org-split-string
23629 (match-string 1 title) ":")
23630 "&nbsp;")
23631 "</span>"))
23633 t t title)))
23634 (if (> level umax)
23635 (progn
23636 (if (aref org-levels-open (1- level))
23637 (progn
23638 (org-close-li)
23639 (insert "<li>" title "<br/>\n"))
23640 (aset org-levels-open (1- level) t)
23641 (org-close-par-maybe)
23642 (insert "<ul>\n<li>" title "<br/>\n")))
23643 (if (and org-export-with-section-numbers (not body-only))
23644 (setq title (concat (org-section-number level) " " title)))
23645 (setq level (+ level org-export-html-toplevel-hlevel -1))
23646 (if with-toc
23647 (insert (format "\n<h%d id=\"sec-%d\">%s</h%d>\n"
23648 level head-count title level))
23649 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
23650 (org-open-par)))))
23652 (defun org-html-level-close (&rest args)
23653 "Terminate one level in HTML export."
23654 (org-close-li)
23655 (insert "</ul>\n"))
23657 ;;; iCalendar export
23659 ;;;###autoload
23660 (defun org-export-icalendar-this-file ()
23661 "Export current file as an iCalendar file.
23662 The iCalendar file will be located in the same directory as the Org-mode
23663 file, but with extension `.ics'."
23664 (interactive)
23665 (org-export-icalendar nil buffer-file-name))
23667 ;;;###autoload
23668 (defun org-export-icalendar-all-agenda-files ()
23669 "Export all files in `org-agenda-files' to iCalendar .ics files.
23670 Each iCalendar file will be located in the same directory as the Org-mode
23671 file, but with extension `.ics'."
23672 (interactive)
23673 (apply 'org-export-icalendar nil (org-agenda-files t)))
23675 ;;;###autoload
23676 (defun org-export-icalendar-combine-agenda-files ()
23677 "Export all files in `org-agenda-files' to a single combined iCalendar file.
23678 The file is stored under the name `org-combined-agenda-icalendar-file'."
23679 (interactive)
23680 (apply 'org-export-icalendar t (org-agenda-files t)))
23682 (defun org-export-icalendar (combine &rest files)
23683 "Create iCalendar files for all elements of FILES.
23684 If COMBINE is non-nil, combine all calendar entries into a single large
23685 file and store it under the name `org-combined-agenda-icalendar-file'."
23686 (save-excursion
23687 (org-prepare-agenda-buffers files)
23688 (let* ((dir (org-export-directory
23689 :ical (list :publishing-directory
23690 org-export-publishing-directory)))
23691 file ical-file ical-buffer category started org-agenda-new-buffers)
23693 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
23694 (when combine
23695 (setq ical-file
23696 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
23697 org-combined-agenda-icalendar-file
23698 (expand-file-name org-combined-agenda-icalendar-file dir))
23699 ical-buffer (org-get-agenda-file-buffer ical-file))
23700 (set-buffer ical-buffer) (erase-buffer))
23701 (while (setq file (pop files))
23702 (catch 'nextfile
23703 (org-check-agenda-file file)
23704 (set-buffer (org-get-agenda-file-buffer file))
23705 (unless combine
23706 (setq ical-file (concat (file-name-as-directory dir)
23707 (file-name-sans-extension
23708 (file-name-nondirectory buffer-file-name))
23709 ".ics"))
23710 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
23711 (with-current-buffer ical-buffer (erase-buffer)))
23712 (setq category (or org-category
23713 (file-name-sans-extension
23714 (file-name-nondirectory buffer-file-name))))
23715 (if (symbolp category) (setq category (symbol-name category)))
23716 (let ((standard-output ical-buffer))
23717 (if combine
23718 (and (not started) (setq started t)
23719 (org-start-icalendar-file org-icalendar-combined-name))
23720 (org-start-icalendar-file category))
23721 (org-print-icalendar-entries combine)
23722 (when (or (and combine (not files)) (not combine))
23723 (org-finish-icalendar-file)
23724 (set-buffer ical-buffer)
23725 (save-buffer)
23726 (run-hooks 'org-after-save-iCalendar-file-hook)))))
23727 (org-release-buffers org-agenda-new-buffers))))
23729 (defvar org-after-save-iCalendar-file-hook nil
23730 "Hook run after an iCalendar file has been saved.
23731 The iCalendar buffer is still current when this hook is run.
23732 A good way to use this is to tell a desktop calenndar application to re-read
23733 the iCalendar file.")
23735 (defun org-print-icalendar-entries (&optional combine)
23736 "Print iCalendar entries for the current Org-mode file to `standard-output'.
23737 When COMBINE is non nil, add the category to each line."
23738 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
23739 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
23740 (dts (org-ical-ts-to-string
23741 (format-time-string (cdr org-time-stamp-formats) (current-time))
23742 "DTSTART"))
23743 hd ts ts2 state status (inc t) pos b sexp rrule
23744 scheduledp deadlinep tmp pri category entry location summary desc
23745 (sexp-buffer (get-buffer-create "*ical-tmp*")))
23746 (org-refresh-category-properties)
23747 (save-excursion
23748 (goto-char (point-min))
23749 (while (re-search-forward re1 nil t)
23750 (catch :skip
23751 (org-agenda-skip)
23752 (setq pos (match-beginning 0)
23753 ts (match-string 0)
23754 inc t
23755 hd (org-get-heading)
23756 summary (org-entry-get nil "SUMMARY")
23757 desc (or (org-entry-get nil "DESCRIPTION")
23758 (org-get-cleaned-entry org-icalendar-include-body))
23759 location (org-entry-get nil "LOCATION")
23760 category (org-get-category))
23761 (if (looking-at re2)
23762 (progn
23763 (goto-char (match-end 0))
23764 (setq ts2 (match-string 1) inc nil))
23765 (setq tmp (buffer-substring (max (point-min)
23766 (- pos org-ds-keyword-length))
23767 pos)
23768 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
23769 (progn
23770 (setq inc nil)
23771 (replace-match "\\1" t nil ts))
23773 deadlinep (string-match org-deadline-regexp tmp)
23774 scheduledp (string-match org-scheduled-regexp tmp)
23775 ;; donep (org-entry-is-done-p)
23777 (if (or (string-match org-tr-regexp hd)
23778 (string-match org-ts-regexp hd))
23779 (setq hd (replace-match "" t t hd)))
23780 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
23781 (setq rrule
23782 (concat "\nRRULE:FREQ="
23783 (cdr (assoc
23784 (match-string 2 ts)
23785 '(("d" . "DAILY")("w" . "WEEKLY")
23786 ("m" . "MONTHLY")("y" . "YEARLY"))))
23787 ";INTERVAL=" (match-string 1 ts)))
23788 (setq rrule ""))
23789 (setq summary (or summary hd))
23790 (if (string-match org-bracket-link-regexp summary)
23791 (setq summary
23792 (replace-match (if (match-end 3)
23793 (match-string 3 summary)
23794 (match-string 1 summary))
23795 t t summary)))
23796 (if deadlinep (setq summary (concat "DL: " summary)))
23797 (if scheduledp (setq summary (concat "S: " summary)))
23798 (if (string-match "\\`<%%" ts)
23799 (with-current-buffer sexp-buffer
23800 (insert (substring ts 1 -1) " " summary "\n"))
23801 (princ (format "BEGIN:VEVENT
23803 %s%s
23804 SUMMARY:%s%s%s
23805 CATEGORIES:%s
23806 END:VEVENT\n"
23807 (org-ical-ts-to-string ts "DTSTART")
23808 (org-ical-ts-to-string ts2 "DTEND" inc)
23809 rrule summary
23810 (if (and desc (string-match "\\S-" desc))
23811 (concat "\nDESCRIPTION: " desc) "")
23812 (if (and location (string-match "\\S-" location))
23813 (concat "\nLOCATION: " location) "")
23814 category)))))
23816 (when (and org-icalendar-include-sexps
23817 (condition-case nil (require 'icalendar) (error nil))
23818 (fboundp 'icalendar-export-region))
23819 ;; Get all the literal sexps
23820 (goto-char (point-min))
23821 (while (re-search-forward "^&?%%(" nil t)
23822 (catch :skip
23823 (org-agenda-skip)
23824 (setq b (match-beginning 0))
23825 (goto-char (1- (match-end 0)))
23826 (forward-sexp 1)
23827 (end-of-line 1)
23828 (setq sexp (buffer-substring b (point)))
23829 (with-current-buffer sexp-buffer
23830 (insert sexp "\n"))
23831 (princ (org-diary-to-ical-string sexp-buffer)))))
23833 (when org-icalendar-include-todo
23834 (goto-char (point-min))
23835 (while (re-search-forward org-todo-line-regexp nil t)
23836 (catch :skip
23837 (org-agenda-skip)
23838 (setq state (match-string 2))
23839 (setq status (if (member state org-done-keywords)
23840 "COMPLETED" "NEEDS-ACTION"))
23841 (when (and state
23842 (or (not (member state org-done-keywords))
23843 (eq org-icalendar-include-todo 'all))
23844 (not (member org-archive-tag (org-get-tags-at)))
23846 (setq hd (match-string 3)
23847 summary (org-entry-get nil "SUMMARY")
23848 desc (or (org-entry-get nil "DESCRIPTION")
23849 (org-get-cleaned-entry org-icalendar-include-body))
23850 location (org-entry-get nil "LOCATION"))
23851 (if (string-match org-bracket-link-regexp hd)
23852 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
23853 (match-string 1 hd))
23854 t t hd)))
23855 (if (string-match org-priority-regexp hd)
23856 (setq pri (string-to-char (match-string 2 hd))
23857 hd (concat (substring hd 0 (match-beginning 1))
23858 (substring hd (match-end 1))))
23859 (setq pri org-default-priority))
23860 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
23861 (- org-lowest-priority org-highest-priority))))))
23863 (princ (format "BEGIN:VTODO
23865 SUMMARY:%s%s%s
23866 CATEGORIES:%s
23867 SEQUENCE:1
23868 PRIORITY:%d
23869 STATUS:%s
23870 END:VTODO\n"
23872 (or summary hd)
23873 (if (and location (string-match "\\S-" location))
23874 (concat "\nLOCATION: " location) "")
23875 (if (and desc (string-match "\\S-" desc))
23876 (concat "\nDESCRIPTION: " desc) "")
23877 category pri status)))))))))
23879 (defun org-get-cleaned-entry (what)
23880 "Clean-up description string."
23881 (when what
23882 (save-excursion
23883 (org-back-to-heading t)
23884 (let ((s (buffer-substring (point-at-bol 2) (org-end-of-subtree t)))
23885 (re (concat org-drawer-regexp "[^\000]*?:END:.*\n?"))
23886 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
23887 (while (string-match re s) (setq s (replace-match "" t t s)))
23888 (while (string-match re2 s) (setq s (replace-match "" t t s)))
23889 (if (string-match "[ \t\r\n]+\\'" s) (setq s (replace-match "" t t s)))
23890 (while (string-match "[ \t]*\n[ \t]*" s)
23891 (setq s (replace-match "\\n" t t s)))
23892 (setq s (org-trim s))
23893 (if (and (numberp what)
23894 (> (length s) what))
23895 (substring s 0 what)
23896 s)))))
23898 (defun org-start-icalendar-file (name)
23899 "Start an iCalendar file by inserting the header."
23900 (let ((user user-full-name)
23901 (name (or name "unknown"))
23902 (timezone (cadr (current-time-zone))))
23903 (princ
23904 (format "BEGIN:VCALENDAR
23905 VERSION:2.0
23906 X-WR-CALNAME:%s
23907 PRODID:-//%s//Emacs with Org-mode//EN
23908 X-WR-TIMEZONE:%s
23909 CALSCALE:GREGORIAN\n" name user timezone))))
23911 (defun org-finish-icalendar-file ()
23912 "Finish an iCalendar file by inserting the END statement."
23913 (princ "END:VCALENDAR\n"))
23915 (defun org-ical-ts-to-string (s keyword &optional inc)
23916 "Take a time string S and convert it to iCalendar format.
23917 KEYWORD is added in front, to make a complete line like DTSTART....
23918 When INC is non-nil, increase the hour by two (if time string contains
23919 a time), or the day by one (if it does not contain a time)."
23920 (let ((t1 (org-parse-time-string s 'nodefault))
23921 t2 fmt have-time time)
23922 (if (and (car t1) (nth 1 t1) (nth 2 t1))
23923 (setq t2 t1 have-time t)
23924 (setq t2 (org-parse-time-string s)))
23925 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
23926 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
23927 (when inc
23928 (if have-time
23929 (if org-agenda-default-appointment-duration
23930 (setq mi (+ org-agenda-default-appointment-duration mi))
23931 (setq h (+ 2 h)))
23932 (setq d (1+ d))))
23933 (setq time (encode-time s mi h d m y)))
23934 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
23935 (concat keyword (format-time-string fmt time))))
23937 ;;; XOXO export
23939 (defun org-export-as-xoxo-insert-into (buffer &rest output)
23940 (with-current-buffer buffer
23941 (apply 'insert output)))
23942 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
23944 (defun org-export-as-xoxo (&optional buffer)
23945 "Export the org buffer as XOXO.
23946 The XOXO buffer is named *xoxo-<source buffer name>*"
23947 (interactive (list (current-buffer)))
23948 ;; A quickie abstraction
23950 ;; Output everything as XOXO
23951 (with-current-buffer (get-buffer buffer)
23952 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
23953 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23954 (org-infile-export-plist)))
23955 (filename (concat (file-name-as-directory
23956 (org-export-directory :xoxo opt-plist))
23957 (file-name-sans-extension
23958 (file-name-nondirectory buffer-file-name))
23959 ".html"))
23960 (out (find-file-noselect filename))
23961 (last-level 1)
23962 (hanging-li nil))
23963 ;; Check the output buffer is empty.
23964 (with-current-buffer out (erase-buffer))
23965 ;; Kick off the output
23966 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
23967 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
23968 (let* ((hd (match-string-no-properties 1))
23969 (level (length hd))
23970 (text (concat
23971 (match-string-no-properties 2)
23972 (save-excursion
23973 (goto-char (match-end 0))
23974 (let ((str ""))
23975 (catch 'loop
23976 (while 't
23977 (forward-line)
23978 (if (looking-at "^[ \t]\\(.*\\)")
23979 (setq str (concat str (match-string-no-properties 1)))
23980 (throw 'loop str)))))))))
23982 ;; Handle level rendering
23983 (cond
23984 ((> level last-level)
23985 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
23987 ((< level last-level)
23988 (dotimes (- (- last-level level) 1)
23989 (if hanging-li
23990 (org-export-as-xoxo-insert-into out "</li>\n"))
23991 (org-export-as-xoxo-insert-into out "</ol>\n"))
23992 (when hanging-li
23993 (org-export-as-xoxo-insert-into out "</li>\n")
23994 (setq hanging-li nil)))
23996 ((equal level last-level)
23997 (if hanging-li
23998 (org-export-as-xoxo-insert-into out "</li>\n")))
24001 (setq last-level level)
24003 ;; And output the new li
24004 (setq hanging-li 't)
24005 (if (equal ?+ (elt text 0))
24006 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
24007 (org-export-as-xoxo-insert-into out "<li>" text))))
24009 ;; Finally finish off the ol
24010 (dotimes (- last-level 1)
24011 (if hanging-li
24012 (org-export-as-xoxo-insert-into out "</li>\n"))
24013 (org-export-as-xoxo-insert-into out "</ol>\n"))
24015 ;; Finish the buffer off and clean it up.
24016 (switch-to-buffer-other-window out)
24017 (indent-region (point-min) (point-max) nil)
24018 (save-buffer)
24019 (goto-char (point-min))
24023 ;;;; Key bindings
24025 ;; Make `C-c C-x' a prefix key
24026 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
24028 ;; TAB key with modifiers
24029 (org-defkey org-mode-map "\C-i" 'org-cycle)
24030 (org-defkey org-mode-map [(tab)] 'org-cycle)
24031 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
24032 (org-defkey org-mode-map [(meta tab)] 'org-complete)
24033 (org-defkey org-mode-map "\M-\t" 'org-complete)
24034 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
24035 ;; The following line is necessary under Suse GNU/Linux
24036 (unless (featurep 'xemacs)
24037 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
24038 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
24039 (define-key org-mode-map (kbd "<backtab>") 'org-shifttab)
24041 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
24042 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
24043 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
24045 ;; Cursor keys with modifiers
24046 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
24047 (org-defkey org-mode-map [(meta right)] 'org-metaright)
24048 (org-defkey org-mode-map [(meta up)] 'org-metaup)
24049 (org-defkey org-mode-map [(meta down)] 'org-metadown)
24051 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
24052 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
24053 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
24054 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
24056 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
24057 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
24058 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
24059 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
24061 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
24062 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
24064 ;;; Extra keys for tty access.
24065 ;; We only set them when really needed because otherwise the
24066 ;; menus don't show the simple keys
24068 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
24069 (not window-system))
24070 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
24071 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
24072 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
24073 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
24074 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
24075 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
24076 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
24077 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
24078 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
24079 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
24080 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
24081 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
24082 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
24083 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
24084 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
24085 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
24086 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
24087 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
24088 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
24089 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
24090 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
24091 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
24093 ;; All the other keys
24095 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
24096 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
24097 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
24098 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
24099 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
24100 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
24101 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
24102 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
24103 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
24104 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
24105 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
24106 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
24107 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
24108 (org-defkey org-mode-map "\C-c\C-w" 'org-check-deadlines)
24109 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
24110 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
24111 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
24112 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
24113 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
24114 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
24115 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
24116 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
24117 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
24118 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
24119 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
24120 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
24121 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
24122 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
24123 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
24124 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
24125 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
24126 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
24127 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
24128 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
24129 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
24130 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
24131 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
24132 (org-defkey org-mode-map "\C-c^" 'org-sort)
24133 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
24134 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
24135 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
24136 (org-defkey org-mode-map "\C-m" 'org-return)
24137 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
24138 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
24139 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
24140 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
24141 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
24142 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
24143 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
24144 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
24145 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
24146 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
24147 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
24148 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
24149 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
24150 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
24151 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
24152 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
24154 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
24155 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
24156 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
24157 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
24159 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
24160 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
24161 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
24162 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
24163 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
24164 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
24165 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
24166 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
24167 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
24168 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
24169 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
24171 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
24173 (when (featurep 'xemacs)
24174 (org-defkey org-mode-map 'button3 'popup-mode-menu))
24176 (defsubst org-table-p () (org-at-table-p))
24178 (defun org-self-insert-command (N)
24179 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
24180 If the cursor is in a table looking at whitespace, the whitespace is
24181 overwritten, and the table is not marked as requiring realignment."
24182 (interactive "p")
24183 (if (and (org-table-p)
24184 (progn
24185 ;; check if we blank the field, and if that triggers align
24186 (and org-table-auto-blank-field
24187 (member last-command
24188 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
24189 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
24190 ;; got extra space, this field does not determine column width
24191 (let (org-table-may-need-update) (org-table-blank-field))
24192 ;; no extra space, this field may determine column width
24193 (org-table-blank-field)))
24195 (eq N 1)
24196 (looking-at "[^|\n]* |"))
24197 (let (org-table-may-need-update)
24198 (goto-char (1- (match-end 0)))
24199 (delete-backward-char 1)
24200 (goto-char (match-beginning 0))
24201 (self-insert-command N))
24202 (setq org-table-may-need-update t)
24203 (self-insert-command N)
24204 (org-fix-tags-on-the-fly)))
24206 (defun org-fix-tags-on-the-fly ()
24207 (when (and (equal (char-after (point-at-bol)) ?*)
24208 (org-on-heading-p))
24209 (org-align-tags-here org-tags-column)))
24211 (defun org-delete-backward-char (N)
24212 "Like `delete-backward-char', insert whitespace at field end in tables.
24213 When deleting backwards, in tables this function will insert whitespace in
24214 front of the next \"|\" separator, to keep the table aligned. The table will
24215 still be marked for re-alignment if the field did fill the entire column,
24216 because, in this case the deletion might narrow the column."
24217 (interactive "p")
24218 (if (and (org-table-p)
24219 (eq N 1)
24220 (string-match "|" (buffer-substring (point-at-bol) (point)))
24221 (looking-at ".*?|"))
24222 (let ((pos (point))
24223 (noalign (looking-at "[^|\n\r]* |"))
24224 (c org-table-may-need-update))
24225 (backward-delete-char N)
24226 (skip-chars-forward "^|")
24227 (insert " ")
24228 (goto-char (1- pos))
24229 ;; noalign: if there were two spaces at the end, this field
24230 ;; does not determine the width of the column.
24231 (if noalign (setq org-table-may-need-update c)))
24232 (backward-delete-char N)
24233 (org-fix-tags-on-the-fly)))
24235 (defun org-delete-char (N)
24236 "Like `delete-char', but insert whitespace at field end in tables.
24237 When deleting characters, in tables this function will insert whitespace in
24238 front of the next \"|\" separator, to keep the table aligned. The table will
24239 still be marked for re-alignment if the field did fill the entire column,
24240 because, in this case the deletion might narrow the column."
24241 (interactive "p")
24242 (if (and (org-table-p)
24243 (not (bolp))
24244 (not (= (char-after) ?|))
24245 (eq N 1))
24246 (if (looking-at ".*?|")
24247 (let ((pos (point))
24248 (noalign (looking-at "[^|\n\r]* |"))
24249 (c org-table-may-need-update))
24250 (replace-match (concat
24251 (substring (match-string 0) 1 -1)
24252 " |"))
24253 (goto-char pos)
24254 ;; noalign: if there were two spaces at the end, this field
24255 ;; does not determine the width of the column.
24256 (if noalign (setq org-table-may-need-update c)))
24257 (delete-char N))
24258 (delete-char N)
24259 (org-fix-tags-on-the-fly)))
24261 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
24262 (put 'org-self-insert-command 'delete-selection t)
24263 (put 'orgtbl-self-insert-command 'delete-selection t)
24264 (put 'org-delete-char 'delete-selection 'supersede)
24265 (put 'org-delete-backward-char 'delete-selection 'supersede)
24267 ;; Make `flyspell-mode' delay after some commands
24268 (put 'org-self-insert-command 'flyspell-delayed t)
24269 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
24270 (put 'org-delete-char 'flyspell-delayed t)
24271 (put 'org-delete-backward-char 'flyspell-delayed t)
24273 (eval-after-load "pabbrev"
24274 '(progn
24275 (add-to-list 'pabbrev-expand-after-command-list
24276 'orgtbl-self-insert-command t)
24277 (add-to-list 'pabbrev-expand-after-command-list
24278 'org-self-insert-command t)))
24280 ;; How to do this: Measure non-white length of current string
24281 ;; If equal to column width, we should realign.
24283 (defun org-remap (map &rest commands)
24284 "In MAP, remap the functions given in COMMANDS.
24285 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
24286 (let (new old)
24287 (while commands
24288 (setq old (pop commands) new (pop commands))
24289 (if (fboundp 'command-remapping)
24290 (org-defkey map (vector 'remap old) new)
24291 (substitute-key-definition old new map global-map)))))
24293 (when (eq org-enable-table-editor 'optimized)
24294 ;; If the user wants maximum table support, we need to hijack
24295 ;; some standard editing functions
24296 (org-remap org-mode-map
24297 'self-insert-command 'org-self-insert-command
24298 'delete-char 'org-delete-char
24299 'delete-backward-char 'org-delete-backward-char)
24300 (org-defkey org-mode-map "|" 'org-force-self-insert))
24302 (defun org-shiftcursor-error ()
24303 "Throw an error because Shift-Cursor command was applied in wrong context."
24304 (error "This command is active in special context like tables, headlines or timestamps"))
24306 (defun org-shifttab (&optional arg)
24307 "Global visibility cycling or move to previous table field.
24308 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
24309 on context.
24310 See the individual commands for more information."
24311 (interactive "P")
24312 (cond
24313 ((org-at-table-p) (call-interactively 'org-table-previous-field))
24314 (arg (message "Content view to level: ")
24315 (org-content (prefix-numeric-value arg))
24316 (setq org-cycle-global-status 'overview))
24317 (t (call-interactively 'org-global-cycle))))
24319 (defun org-shiftmetaleft ()
24320 "Promote subtree or delete table column.
24321 Calls `org-promote-subtree', `org-outdent-item',
24322 or `org-table-delete-column', depending on context.
24323 See the individual commands for more information."
24324 (interactive)
24325 (cond
24326 ((org-at-table-p) (call-interactively 'org-table-delete-column))
24327 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
24328 ((org-at-item-p) (call-interactively 'org-outdent-item))
24329 (t (org-shiftcursor-error))))
24331 (defun org-shiftmetaright ()
24332 "Demote subtree or insert table column.
24333 Calls `org-demote-subtree', `org-indent-item',
24334 or `org-table-insert-column', depending on context.
24335 See the individual commands for more information."
24336 (interactive)
24337 (cond
24338 ((org-at-table-p) (call-interactively 'org-table-insert-column))
24339 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
24340 ((org-at-item-p) (call-interactively 'org-indent-item))
24341 (t (org-shiftcursor-error))))
24343 (defun org-shiftmetaup (&optional arg)
24344 "Move subtree up or kill table row.
24345 Calls `org-move-subtree-up' or `org-table-kill-row' or
24346 `org-move-item-up' depending on context. See the individual commands
24347 for more information."
24348 (interactive "P")
24349 (cond
24350 ((org-at-table-p) (call-interactively 'org-table-kill-row))
24351 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
24352 ((org-at-item-p) (call-interactively 'org-move-item-up))
24353 (t (org-shiftcursor-error))))
24354 (defun org-shiftmetadown (&optional arg)
24355 "Move subtree down or insert table row.
24356 Calls `org-move-subtree-down' or `org-table-insert-row' or
24357 `org-move-item-down', depending on context. See the individual
24358 commands for more information."
24359 (interactive "P")
24360 (cond
24361 ((org-at-table-p) (call-interactively 'org-table-insert-row))
24362 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
24363 ((org-at-item-p) (call-interactively 'org-move-item-down))
24364 (t (org-shiftcursor-error))))
24366 (defun org-metaleft (&optional arg)
24367 "Promote heading or move table column to left.
24368 Calls `org-do-promote' or `org-table-move-column', depending on context.
24369 With no specific context, calls the Emacs default `backward-word'.
24370 See the individual commands for more information."
24371 (interactive "P")
24372 (cond
24373 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
24374 ((or (org-on-heading-p) (org-region-active-p))
24375 (call-interactively 'org-do-promote))
24376 ((org-at-item-p) (call-interactively 'org-outdent-item))
24377 (t (call-interactively 'backward-word))))
24379 (defun org-metaright (&optional arg)
24380 "Demote subtree or move table column to right.
24381 Calls `org-do-demote' or `org-table-move-column', depending on context.
24382 With no specific context, calls the Emacs default `forward-word'.
24383 See the individual commands for more information."
24384 (interactive "P")
24385 (cond
24386 ((org-at-table-p) (call-interactively 'org-table-move-column))
24387 ((or (org-on-heading-p) (org-region-active-p))
24388 (call-interactively 'org-do-demote))
24389 ((org-at-item-p) (call-interactively 'org-indent-item))
24390 (t (call-interactively 'forward-word))))
24392 (defun org-metaup (&optional arg)
24393 "Move subtree up or move table row up.
24394 Calls `org-move-subtree-up' or `org-table-move-row' or
24395 `org-move-item-up', depending on context. See the individual commands
24396 for more information."
24397 (interactive "P")
24398 (cond
24399 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
24400 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
24401 ((org-at-item-p) (call-interactively 'org-move-item-up))
24402 (t (org-shiftcursor-error))))
24404 (defun org-metadown (&optional arg)
24405 "Move subtree down or move table row down.
24406 Calls `org-move-subtree-down' or `org-table-move-row' or
24407 `org-move-item-down', depending on context. See the individual
24408 commands for more information."
24409 (interactive "P")
24410 (cond
24411 ((org-at-table-p) (call-interactively 'org-table-move-row))
24412 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
24413 ((org-at-item-p) (call-interactively 'org-move-item-down))
24414 (t (org-shiftcursor-error))))
24416 (defun org-shiftup (&optional arg)
24417 "Increase item in timestamp or increase priority of current headline.
24418 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
24419 depending on context. See the individual commands for more information."
24420 (interactive "P")
24421 (cond
24422 ((org-at-timestamp-p t)
24423 (call-interactively (if org-edit-timestamp-down-means-later
24424 'org-timestamp-down 'org-timestamp-up)))
24425 ((org-on-heading-p) (call-interactively 'org-priority-up))
24426 ((org-at-item-p) (call-interactively 'org-previous-item))
24427 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
24429 (defun org-shiftdown (&optional arg)
24430 "Decrease item in timestamp or decrease priority of current headline.
24431 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
24432 depending on context. See the individual commands for more information."
24433 (interactive "P")
24434 (cond
24435 ((org-at-timestamp-p t)
24436 (call-interactively (if org-edit-timestamp-down-means-later
24437 'org-timestamp-up 'org-timestamp-down)))
24438 ((org-on-heading-p) (call-interactively 'org-priority-down))
24439 (t (call-interactively 'org-next-item))))
24441 (defun org-shiftright ()
24442 "Next TODO keyword or timestamp one day later, depending on context."
24443 (interactive)
24444 (cond
24445 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
24446 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
24447 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
24448 (t (org-shiftcursor-error))))
24450 (defun org-shiftleft ()
24451 "Previous TODO keyword or timestamp one day earlier, depending on context."
24452 (interactive)
24453 (cond
24454 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
24455 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
24456 ((org-at-property-p)
24457 (call-interactively 'org-property-previous-allowed-value))
24458 (t (org-shiftcursor-error))))
24460 (defun org-shiftcontrolright ()
24461 "Switch to next TODO set."
24462 (interactive)
24463 (cond
24464 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
24465 (t (org-shiftcursor-error))))
24467 (defun org-shiftcontrolleft ()
24468 "Switch to previous TODO set."
24469 (interactive)
24470 (cond
24471 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
24472 (t (org-shiftcursor-error))))
24474 (defun org-ctrl-c-ret ()
24475 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
24476 (interactive)
24477 (cond
24478 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
24479 (t (call-interactively 'org-insert-heading))))
24481 (defun org-copy-special ()
24482 "Copy region in table or copy current subtree.
24483 Calls `org-table-copy' or `org-copy-subtree', depending on context.
24484 See the individual commands for more information."
24485 (interactive)
24486 (call-interactively
24487 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
24489 (defun org-cut-special ()
24490 "Cut region in table or cut current subtree.
24491 Calls `org-table-copy' or `org-cut-subtree', depending on context.
24492 See the individual commands for more information."
24493 (interactive)
24494 (call-interactively
24495 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
24497 (defun org-paste-special (arg)
24498 "Paste rectangular region into table, or past subtree relative to level.
24499 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
24500 See the individual commands for more information."
24501 (interactive "P")
24502 (if (org-at-table-p)
24503 (org-table-paste-rectangle)
24504 (org-paste-subtree arg)))
24506 (defun org-ctrl-c-ctrl-c (&optional arg)
24507 "Set tags in headline, or update according to changed information at point.
24509 This command does many different things, depending on context:
24511 - If the cursor is in a headline, prompt for tags and insert them
24512 into the current line, aligned to `org-tags-column'. When called
24513 with prefix arg, realign all tags in the current buffer.
24515 - If the cursor is in one of the special #+KEYWORD lines, this
24516 triggers scanning the buffer for these lines and updating the
24517 information.
24519 - If the cursor is inside a table, realign the table. This command
24520 works even if the automatic table editor has been turned off.
24522 - If the cursor is on a #+TBLFM line, re-apply the formulas to
24523 the entire table.
24525 - If the cursor is a the beginning of a dynamic block, update it.
24527 - If the cursor is inside a table created by the table.el package,
24528 activate that table.
24530 - If the current buffer is a remember buffer, close note and file it.
24531 with a prefix argument, file it without further interaction to the default
24532 location.
24534 - If the cursor is on a <<<target>>>, update radio targets and corresponding
24535 links in this buffer.
24537 - If the cursor is on a numbered item in a plain list, renumber the
24538 ordered list."
24539 (interactive "P")
24540 (let ((org-enable-table-editor t))
24541 (cond
24542 ((or org-clock-overlays
24543 org-occur-highlights
24544 org-latex-fragment-image-overlays)
24545 (org-remove-clock-overlays)
24546 (org-remove-occur-highlights)
24547 (org-remove-latex-fragment-image-overlays)
24548 (message "Temporary highlights/overlays removed from current buffer"))
24549 ((and (local-variable-p 'org-finish-function (current-buffer))
24550 (fboundp org-finish-function))
24551 (funcall org-finish-function))
24552 ((org-at-property-p)
24553 (call-interactively 'org-property-action))
24554 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
24555 ((org-on-heading-p) (call-interactively 'org-set-tags))
24556 ((org-at-table.el-p)
24557 (require 'table)
24558 (beginning-of-line 1)
24559 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
24560 (call-interactively 'table-recognize-table))
24561 ((org-at-table-p)
24562 (org-table-maybe-eval-formula)
24563 (if arg
24564 (call-interactively 'org-table-recalculate)
24565 (org-table-maybe-recalculate-line))
24566 (call-interactively 'org-table-align))
24567 ((org-at-item-checkbox-p)
24568 (call-interactively 'org-toggle-checkbox))
24569 ((org-at-item-p)
24570 (call-interactively 'org-maybe-renumber-ordered-list))
24571 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
24572 ;; Dynamic block
24573 (beginning-of-line 1)
24574 (org-update-dblock))
24575 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
24576 (cond
24577 ((equal (match-string 1) "TBLFM")
24578 ;; Recalculate the table before this line
24579 (save-excursion
24580 (beginning-of-line 1)
24581 (skip-chars-backward " \r\n\t")
24582 (if (org-at-table-p)
24583 (org-call-with-arg 'org-table-recalculate t))))
24585 (call-interactively 'org-mode-restart))))
24586 (t (error "C-c C-c can do nothing useful at this location.")))))
24588 (defun org-mode-restart ()
24589 "Restart Org-mode, to scan again for special lines.
24590 Also updates the keyword regular expressions."
24591 (interactive)
24592 (let ((org-inhibit-startup t)) (org-mode))
24593 (message "Org-mode restarted to refresh keyword and special line setup"))
24595 (defun org-kill-note-or-show-branches ()
24596 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
24597 (interactive)
24598 (if (not org-finish-function)
24599 (call-interactively 'show-branches)
24600 (let ((org-note-abort t))
24601 (funcall org-finish-function))))
24603 (defun org-return ()
24604 "Goto next table row or insert a newline.
24605 Calls `org-table-next-row' or `newline', depending on context.
24606 See the individual commands for more information."
24607 (interactive)
24608 (cond
24609 ((bobp) (newline))
24610 ((org-at-table-p)
24611 (org-table-justify-field-maybe)
24612 (call-interactively 'org-table-next-row))
24613 (t (newline))))
24615 (defun org-ctrl-c-minus ()
24616 "Insert separator line in table or modify bullet type in list.
24617 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
24618 depending on context."
24619 (interactive)
24620 (cond
24621 ((org-at-table-p)
24622 (call-interactively 'org-table-insert-hline))
24623 ((org-in-item-p)
24624 (call-interactively 'org-cycle-list-bullet))
24625 (t (error "`C-c -' does have no function here."))))
24627 (defun org-meta-return (&optional arg)
24628 "Insert a new heading or wrap a region in a table.
24629 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
24630 See the individual commands for more information."
24631 (interactive "P")
24632 (cond
24633 ((org-at-table-p)
24634 (call-interactively 'org-table-wrap-region))
24635 (t (call-interactively 'org-insert-heading))))
24637 ;;; Menu entries
24639 ;; Define the Org-mode menus
24640 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
24641 '("Tbl"
24642 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
24643 ["Next Field" org-cycle (org-at-table-p)]
24644 ["Previous Field" org-shifttab (org-at-table-p)]
24645 ["Next Row" org-return (org-at-table-p)]
24646 "--"
24647 ["Blank Field" org-table-blank-field (org-at-table-p)]
24648 ["Edit Field" org-table-edit-field (org-at-table-p)]
24649 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
24650 "--"
24651 ("Column"
24652 ["Move Column Left" org-metaleft (org-at-table-p)]
24653 ["Move Column Right" org-metaright (org-at-table-p)]
24654 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
24655 ["Insert Column" org-shiftmetaright (org-at-table-p)])
24656 ("Row"
24657 ["Move Row Up" org-metaup (org-at-table-p)]
24658 ["Move Row Down" org-metadown (org-at-table-p)]
24659 ["Delete Row" org-shiftmetaup (org-at-table-p)]
24660 ["Insert Row" org-shiftmetadown (org-at-table-p)]
24661 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
24662 "--"
24663 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
24664 ("Rectangle"
24665 ["Copy Rectangle" org-copy-special (org-at-table-p)]
24666 ["Cut Rectangle" org-cut-special (org-at-table-p)]
24667 ["Paste Rectangle" org-paste-special (org-at-table-p)]
24668 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
24669 "--"
24670 ("Calculate"
24671 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
24672 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
24673 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
24674 "--"
24675 ["Recalculate line" org-table-recalculate (org-at-table-p)]
24676 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
24677 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
24678 "--"
24679 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
24680 "--"
24681 ["Sum Column/Rectangle" org-table-sum
24682 (or (org-at-table-p) (org-region-active-p))]
24683 ["Which Column?" org-table-current-column (org-at-table-p)])
24684 ["Debug Formulas"
24685 org-table-toggle-formula-debugger
24686 :style toggle :selected org-table-formula-debug]
24687 ["Show Col/Row Numbers"
24688 org-table-toggle-coordinate-overlays
24689 :style toggle :selected org-table-overlay-coordinates]
24690 "--"
24691 ["Create" org-table-create (and (not (org-at-table-p))
24692 org-enable-table-editor)]
24693 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
24694 ["Import from File" org-table-import (not (org-at-table-p))]
24695 ["Export to File" org-table-export (org-at-table-p)]
24696 "--"
24697 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
24699 (easy-menu-define org-org-menu org-mode-map "Org menu"
24700 '("Org"
24701 ("Show/Hide"
24702 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
24703 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
24704 ["Sparse Tree" org-occur t]
24705 ["Reveal Context" org-reveal t]
24706 ["Show All" show-all t]
24707 "--"
24708 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
24709 "--"
24710 ["New Heading" org-insert-heading t]
24711 ("Navigate Headings"
24712 ["Up" outline-up-heading t]
24713 ["Next" outline-next-visible-heading t]
24714 ["Previous" outline-previous-visible-heading t]
24715 ["Next Same Level" outline-forward-same-level t]
24716 ["Previous Same Level" outline-backward-same-level t]
24717 "--"
24718 ["Jump" org-goto t])
24719 ("Edit Structure"
24720 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
24721 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
24722 "--"
24723 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
24724 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
24725 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
24726 "--"
24727 ["Promote Heading" org-metaleft (not (org-at-table-p))]
24728 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
24729 ["Demote Heading" org-metaright (not (org-at-table-p))]
24730 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
24731 "--"
24732 ["Sort Region/Children" org-sort (not (org-at-table-p))]
24733 "--"
24734 ["Convert to odd levels" org-convert-to-odd-levels t]
24735 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
24736 ("Editing"
24737 ["Emphasis..." org-emphasize t])
24738 ("Archive"
24739 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
24740 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
24741 ; :active t :keys "C-u C-c C-x C-a"]
24742 ["Sparse trees open ARCHIVE trees"
24743 (setq org-sparse-tree-open-archived-trees
24744 (not org-sparse-tree-open-archived-trees))
24745 :style toggle :selected org-sparse-tree-open-archived-trees]
24746 ["Cycling opens ARCHIVE trees"
24747 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
24748 :style toggle :selected org-cycle-open-archived-trees]
24749 ["Agenda includes ARCHIVE trees"
24750 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
24751 :style toggle :selected (not org-agenda-skip-archived-trees)]
24752 "--"
24753 ["Move Subtree to Archive" org-advertized-archive-subtree t]
24754 ; ["Check and Move Children" (org-archive-subtree '(4))
24755 ; :active t :keys "C-u C-c C-x C-s"]
24757 "--"
24758 ("TODO Lists"
24759 ["TODO/DONE/-" org-todo t]
24760 ("Select keyword"
24761 ["Next keyword" org-shiftright (org-on-heading-p)]
24762 ["Previous keyword" org-shiftleft (org-on-heading-p)]
24763 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
24764 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
24765 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
24766 ["Show TODO Tree" org-show-todo-tree t]
24767 ["Global TODO list" org-todo-list t]
24768 "--"
24769 ["Set Priority" org-priority t]
24770 ["Priority Up" org-shiftup t]
24771 ["Priority Down" org-shiftdown t])
24772 ("TAGS and Properties"
24773 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
24774 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
24775 "--"
24776 ["Set property" 'org-set-property t]
24777 ["Column view of properties" org-columns t])
24778 ("Dates and Scheduling"
24779 ["Timestamp" org-time-stamp t]
24780 ["Timestamp (inactive)" org-time-stamp-inactive t]
24781 ("Change Date"
24782 ["1 Day Later" org-shiftright t]
24783 ["1 Day Earlier" org-shiftleft t]
24784 ["1 ... Later" org-shiftup t]
24785 ["1 ... Earlier" org-shiftdown t])
24786 ["Compute Time Range" org-evaluate-time-range t]
24787 ["Schedule Item" org-schedule t]
24788 ["Deadline" org-deadline t]
24789 "--"
24790 ["Custom time format" org-toggle-time-stamp-overlays
24791 :style radio :selected org-display-custom-times]
24792 "--"
24793 ["Goto Calendar" org-goto-calendar t]
24794 ["Date from Calendar" org-date-from-calendar t])
24795 ("Logging work"
24796 ["Clock in" org-clock-in t]
24797 ["Clock out" org-clock-out t]
24798 ["Clock cancel" org-clock-cancel t]
24799 ["Goto running clock" org-clock-goto t]
24800 ["Display times" org-clock-display t]
24801 ["Create clock table" org-clock-report t]
24802 "--"
24803 ["Record DONE time"
24804 (progn (setq org-log-done (not org-log-done))
24805 (message "Switching to %s will %s record a timestamp"
24806 (car org-done-keywords)
24807 (if org-log-done "automatically" "not")))
24808 :style toggle :selected org-log-done])
24809 "--"
24810 ["Agenda Command..." org-agenda t]
24811 ("File List for Agenda")
24812 ("Special views current file"
24813 ["TODO Tree" org-show-todo-tree t]
24814 ["Check Deadlines" org-check-deadlines t]
24815 ["Timeline" org-timeline t]
24816 ["Tags Tree" org-tags-sparse-tree t])
24817 "--"
24818 ("Hyperlinks"
24819 ["Store Link (Global)" org-store-link t]
24820 ["Insert Link" org-insert-link t]
24821 ["Follow Link" org-open-at-point t]
24822 "--"
24823 ["Next link" org-next-link t]
24824 ["Previous link" org-previous-link t]
24825 "--"
24826 ["Descriptive Links"
24827 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
24828 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
24829 ["Literal Links"
24830 (progn
24831 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
24832 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
24833 "--"
24834 ["Export/Publish..." org-export t]
24835 ("LaTeX"
24836 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
24837 :selected org-cdlatex-mode]
24838 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
24839 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
24840 ["Modify math symbol" org-cdlatex-math-modify
24841 (org-inside-LaTeX-fragment-p)]
24842 ["Export LaTeX fragments as images"
24843 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
24844 :style toggle :selected org-export-with-LaTeX-fragments])
24845 "--"
24846 ("Documentation"
24847 ["Show Version" org-version t]
24848 ["Info Documentation" org-info t])
24849 ("Customize"
24850 ["Browse Org Group" org-customize t]
24851 "--"
24852 ["Expand This Menu" org-create-customize-menu
24853 (fboundp 'customize-menu-create)])
24854 "--"
24855 ["Refresh setup" org-mode-restart t]
24858 (defun org-info (&optional node)
24859 "Read documentation for Org-mode in the info system.
24860 With optional NODE, go directly to that node."
24861 (interactive)
24862 (require 'info)
24863 (Info-goto-node (format "(org)%s" (or node ""))))
24865 (defun org-install-agenda-files-menu ()
24866 (let ((bl (buffer-list)))
24867 (save-excursion
24868 (while bl
24869 (set-buffer (pop bl))
24870 (if (org-mode-p) (setq bl nil)))
24871 (when (org-mode-p)
24872 (easy-menu-change
24873 '("Org") "File List for Agenda"
24874 (append
24875 (list
24876 ["Edit File List" (org-edit-agenda-file-list) t]
24877 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
24878 ["Remove Current File from List" org-remove-file t]
24879 ["Cycle through agenda files" org-cycle-agenda-files t]
24880 ["Occur in all agenda files" org-occur-in-agenda-files t]
24881 "--")
24882 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
24884 ;;;; Documentation
24886 (defun org-customize ()
24887 "Call the customize function with org as argument."
24888 (interactive)
24889 (customize-browse 'org))
24891 (defun org-create-customize-menu ()
24892 "Create a full customization menu for Org-mode, insert it into the menu."
24893 (interactive)
24894 (if (fboundp 'customize-menu-create)
24895 (progn
24896 (easy-menu-change
24897 '("Org") "Customize"
24898 `(["Browse Org group" org-customize t]
24899 "--"
24900 ,(customize-menu-create 'org)
24901 ["Set" Custom-set t]
24902 ["Save" Custom-save t]
24903 ["Reset to Current" Custom-reset-current t]
24904 ["Reset to Saved" Custom-reset-saved t]
24905 ["Reset to Standard Settings" Custom-reset-standard t]))
24906 (message "\"Org\"-menu now contains full customization menu"))
24907 (error "Cannot expand menu (outdated version of cus-edit.el)")))
24909 ;;;; Miscellaneous stuff
24912 ;;; Generally useful functions
24914 (defun org-context ()
24915 "Return a list of contexts of the current cursor position.
24916 If several contexts apply, all are returned.
24917 Each context entry is a list with a symbol naming the context, and
24918 two positions indicating start and end of the context. Possible
24919 contexts are:
24921 :headline anywhere in a headline
24922 :headline-stars on the leading stars in a headline
24923 :todo-keyword on a TODO keyword (including DONE) in a headline
24924 :tags on the TAGS in a headline
24925 :priority on the priority cookie in a headline
24926 :item on the first line of a plain list item
24927 :item-bullet on the bullet/number of a plain list item
24928 :checkbox on the checkbox in a plain list item
24929 :table in an org-mode table
24930 :table-special on a special filed in a table
24931 :table-table in a table.el table
24932 :link on a hyperlink
24933 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
24934 :target on a <<target>>
24935 :radio-target on a <<<radio-target>>>
24936 :latex-fragment on a LaTeX fragment
24937 :latex-preview on a LaTeX fragment with overlayed preview image
24939 This function expects the position to be visible because it uses font-lock
24940 faces as a help to recognize the following contexts: :table-special, :link,
24941 and :keyword."
24942 (let* ((f (get-text-property (point) 'face))
24943 (faces (if (listp f) f (list f)))
24944 (p (point)) clist o)
24945 ;; First the large context
24946 (cond
24947 ((org-on-heading-p t)
24948 (push (list :headline (point-at-bol) (point-at-eol)) clist)
24949 (when (progn
24950 (beginning-of-line 1)
24951 (looking-at org-todo-line-tags-regexp))
24952 (push (org-point-in-group p 1 :headline-stars) clist)
24953 (push (org-point-in-group p 2 :todo-keyword) clist)
24954 (push (org-point-in-group p 4 :tags) clist))
24955 (goto-char p)
24956 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
24957 (if (looking-at "\\[#[A-Z0-9]\\]")
24958 (push (org-point-in-group p 0 :priority) clist)))
24960 ((org-at-item-p)
24961 (push (org-point-in-group p 2 :item-bullet) clist)
24962 (push (list :item (point-at-bol)
24963 (save-excursion (org-end-of-item) (point)))
24964 clist)
24965 (and (org-at-item-checkbox-p)
24966 (push (org-point-in-group p 0 :checkbox) clist)))
24968 ((org-at-table-p)
24969 (push (list :table (org-table-begin) (org-table-end)) clist)
24970 (if (memq 'org-formula faces)
24971 (push (list :table-special
24972 (previous-single-property-change p 'face)
24973 (next-single-property-change p 'face)) clist)))
24974 ((org-at-table-p 'any)
24975 (push (list :table-table) clist)))
24976 (goto-char p)
24978 ;; Now the small context
24979 (cond
24980 ((org-at-timestamp-p)
24981 (push (org-point-in-group p 0 :timestamp) clist))
24982 ((memq 'org-link faces)
24983 (push (list :link
24984 (previous-single-property-change p 'face)
24985 (next-single-property-change p 'face)) clist))
24986 ((memq 'org-special-keyword faces)
24987 (push (list :keyword
24988 (previous-single-property-change p 'face)
24989 (next-single-property-change p 'face)) clist))
24990 ((org-on-target-p)
24991 (push (org-point-in-group p 0 :target) clist)
24992 (goto-char (1- (match-beginning 0)))
24993 (if (looking-at org-radio-target-regexp)
24994 (push (org-point-in-group p 0 :radio-target) clist))
24995 (goto-char p))
24996 ((setq o (car (delq nil
24997 (mapcar
24998 (lambda (x)
24999 (if (memq x org-latex-fragment-image-overlays) x))
25000 (org-overlays-at (point))))))
25001 (push (list :latex-fragment
25002 (org-overlay-start o) (org-overlay-end o)) clist)
25003 (push (list :latex-preview
25004 (org-overlay-start o) (org-overlay-end o)) clist))
25005 ((org-inside-LaTeX-fragment-p)
25006 ;; FIXME: positions wrong.
25007 (push (list :latex-fragment (point) (point)) clist)))
25009 (setq clist (nreverse (delq nil clist)))
25010 clist))
25012 ;; FIXME: Compare with at-regexp-p Do we need both?
25013 (defun org-in-regexp (re &optional nlines visually)
25014 "Check if point is inside a match of regexp.
25015 Normally only the current line is checked, but you can include NLINES extra
25016 lines both before and after point into the search.
25017 If VISUALLY is set, require that the cursor is not after the match but
25018 really on, so that the block visually is on the match."
25019 (catch 'exit
25020 (let ((pos (point))
25021 (eol (point-at-eol (+ 1 (or nlines 0))))
25022 (inc (if visually 1 0)))
25023 (save-excursion
25024 (beginning-of-line (- 1 (or nlines 0)))
25025 (while (re-search-forward re eol t)
25026 (if (and (<= (match-beginning 0) pos)
25027 (>= (+ inc (match-end 0)) pos))
25028 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
25030 (defun org-at-regexp-p (regexp)
25031 "Is point inside a match of REGEXP in the current line?"
25032 (catch 'exit
25033 (save-excursion
25034 (let ((pos (point)) (end (point-at-eol)))
25035 (beginning-of-line 1)
25036 (while (re-search-forward regexp end t)
25037 (if (and (<= (match-beginning 0) pos)
25038 (>= (match-end 0) pos))
25039 (throw 'exit t)))
25040 nil))))
25042 (defun org-occur-in-agenda-files (regexp &optional nlines)
25043 "Call `multi-occur' with buffers for all agenda files."
25044 (interactive "sOrg-files matching: \np")
25045 (let* ((files (org-agenda-files))
25046 (tnames (mapcar 'file-truename files))
25047 (extra org-agenda-multi-occur-extra-files)
25049 (while (setq f (pop extra))
25050 (unless (member (file-truename f) tnames)
25051 (add-to-list 'files f 'append)
25052 (add-to-list 'tnames (file-truename f) 'append)))
25053 (multi-occur
25054 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
25055 regexp)))
25057 (defun org-uniquify (list)
25058 "Remove duplicate elements from LIST."
25059 (let (res)
25060 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
25061 res))
25063 (defun org-delete-all (elts list)
25064 "Remove all elements in ELTS from LIST."
25065 (while elts
25066 (setq list (delete (pop elts) list)))
25067 list)
25069 (defun org-point-in-group (point group &optional context)
25070 "Check if POINT is in match-group GROUP.
25071 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
25072 match. If the match group does ot exist or point is not inside it,
25073 return nil."
25074 (and (match-beginning group)
25075 (>= point (match-beginning group))
25076 (<= point (match-end group))
25077 (if context
25078 (list context (match-beginning group) (match-end group))
25079 t)))
25081 (defun org-switch-to-buffer-other-window (&rest args)
25082 "Switch to buffer in a second window on the current frame.
25083 In particular, do not allow pop-up frames."
25084 (let (pop-up-frames special-display-buffer-names special-display-regexps
25085 special-display-function)
25086 (apply 'switch-to-buffer-other-window args)))
25088 (defun org-combine-plists (&rest plists)
25089 "Create a single property list from all plists in PLISTS.
25090 The process starts by copying the first list, and then setting properties
25091 from the other lists. Settings in the last list are the most significant
25092 ones and overrule settings in the other lists."
25093 (let ((rtn (copy-sequence (pop plists)))
25094 p v ls)
25095 (while plists
25096 (setq ls (pop plists))
25097 (while ls
25098 (setq p (pop ls) v (pop ls))
25099 (setq rtn (plist-put rtn p v))))
25100 rtn))
25102 (defun org-move-line-down (arg)
25103 "Move the current line down. With prefix argument, move it past ARG lines."
25104 (interactive "p")
25105 (let ((col (current-column))
25106 beg end pos)
25107 (beginning-of-line 1) (setq beg (point))
25108 (beginning-of-line 2) (setq end (point))
25109 (beginning-of-line (+ 1 arg))
25110 (setq pos (move-marker (make-marker) (point)))
25111 (insert (delete-and-extract-region beg end))
25112 (goto-char pos)
25113 (move-to-column col)))
25115 (defun org-move-line-up (arg)
25116 "Move the current line up. With prefix argument, move it past ARG lines."
25117 (interactive "p")
25118 (let ((col (current-column))
25119 beg end pos)
25120 (beginning-of-line 1) (setq beg (point))
25121 (beginning-of-line 2) (setq end (point))
25122 (beginning-of-line (- arg))
25123 (setq pos (move-marker (make-marker) (point)))
25124 (insert (delete-and-extract-region beg end))
25125 (goto-char pos)
25126 (move-to-column col)))
25128 (defun org-replace-escapes (string table)
25129 "Replace %-escapes in STRING with values in TABLE.
25130 TABLE is an association list with keys like \"%a\" and string values.
25131 The sequences in STRING may contain normal field width and padding information,
25132 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
25133 so values can contain further %-escapes if they are define later in TABLE."
25134 (let ((case-fold-search nil)
25135 e re rpl)
25136 (while (setq e (pop table))
25137 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
25138 (while (string-match re string)
25139 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
25140 (cdr e)))
25141 (setq string (replace-match rpl t t string))))
25142 string))
25145 (defun org-sublist (list start end)
25146 "Return a section of LIST, from START to END.
25147 Counting starts at 1."
25148 (let (rtn (c start))
25149 (setq list (nthcdr (1- start) list))
25150 (while (and list (<= c end))
25151 (push (pop list) rtn)
25152 (setq c (1+ c)))
25153 (nreverse rtn)))
25155 (defun org-find-base-buffer-visiting (file)
25156 "Like `find-buffer-visiting' but alway return the base buffer and
25157 not an indirect buffer"
25158 (let ((buf (find-buffer-visiting file)))
25159 (if buf
25160 (or (buffer-base-buffer buf) buf)
25161 nil)))
25163 (defun org-image-file-name-regexp ()
25164 "Return regexp matching the file names of images."
25165 (if (fboundp 'image-file-name-regexp)
25166 (image-file-name-regexp)
25167 (let ((image-file-name-extensions
25168 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
25169 "xbm" "xpm" "pbm" "pgm" "ppm")))
25170 (concat "\\."
25171 (regexp-opt (nconc (mapcar 'upcase
25172 image-file-name-extensions)
25173 image-file-name-extensions)
25175 "\\'"))))
25177 (defun org-file-image-p (file)
25178 "Return non-nil if FILE is an image."
25179 (save-match-data
25180 (string-match (org-image-file-name-regexp) file)))
25182 ;;; Paragraph filling stuff.
25183 ;; We want this to be just right, so use the full arsenal.
25185 (defun org-indent-line-function ()
25186 "Indent line like previous, but further if previous was headline or item."
25187 (interactive)
25188 (let* ((pos (point))
25189 (itemp (org-at-item-p))
25190 column bpos bcol tpos tcol bullet btype bullet-type)
25191 ;; Find the previous relevant line
25192 (beginning-of-line 1)
25193 (cond
25194 ((looking-at "#") (setq column 0))
25195 ((looking-at "\\*+ ") (setq column 0))
25197 (beginning-of-line 0)
25198 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
25199 (beginning-of-line 0))
25200 (cond
25201 ((looking-at "\\*+[ \t]+")
25202 (goto-char (match-end 0))
25203 (setq column (current-column)))
25204 ((org-in-item-p)
25205 (org-beginning-of-item)
25206 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
25207 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
25208 (setq bpos (match-beginning 1) tpos (match-end 0)
25209 bcol (progn (goto-char bpos) (current-column))
25210 tcol (progn (goto-char tpos) (current-column))
25211 bullet (match-string 1)
25212 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
25213 (if (not itemp)
25214 (setq column tcol)
25215 (goto-char pos)
25216 (beginning-of-line 1)
25217 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
25218 (setq bullet (match-string 1)
25219 btype (if (string-match "[0-9]" bullet) "n" bullet))
25220 (setq column (if (equal btype bullet-type) bcol tcol))))
25221 (t (setq column (org-get-indentation))))))
25222 (goto-char pos)
25223 (if (<= (current-column) (current-indentation))
25224 (indent-line-to column)
25225 (save-excursion (indent-line-to column)))
25226 (setq column (current-column))
25227 (beginning-of-line 1)
25228 (if (looking-at
25229 "\\([ \t]+\\)\\(:[0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
25230 (replace-match (concat "\\1" (format org-property-format
25231 (match-string 2) (match-string 3)))
25232 t nil))
25233 (move-to-column column)))
25235 (defun org-set-autofill-regexps ()
25236 (interactive)
25237 ;; In the paragraph separator we include headlines, because filling
25238 ;; text in a line directly attached to a headline would otherwise
25239 ;; fill the headline as well.
25240 (org-set-local 'comment-start-skip "^#+[ \t]*")
25241 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
25242 ;; The paragraph starter includes hand-formatted lists.
25243 (org-set-local 'paragraph-start
25244 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
25245 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
25246 ;; But only if the user has not turned off tables or fixed-width regions
25247 (org-set-local
25248 'auto-fill-inhibit-regexp
25249 (concat "\\*+ \\|#\\+"
25250 "\\|[ \t]*" org-keyword-time-regexp
25251 (if (or org-enable-table-editor org-enable-fixed-width-editor)
25252 (concat
25253 "\\|[ \t]*["
25254 (if org-enable-table-editor "|" "")
25255 (if org-enable-fixed-width-editor ":" "")
25256 "]"))))
25257 ;; We use our own fill-paragraph function, to make sure that tables
25258 ;; and fixed-width regions are not wrapped. That function will pass
25259 ;; through to `fill-paragraph' when appropriate.
25260 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
25261 ; Adaptive filling: To get full control, first make sure that
25262 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
25263 (org-set-local 'adaptive-fill-regexp "\000")
25264 (org-set-local 'adaptive-fill-function
25265 'org-adaptive-fill-function))
25267 (defun org-fill-paragraph (&optional justify)
25268 "Re-align a table, pass through to fill-paragraph if no table."
25269 (let ((table-p (org-at-table-p))
25270 (table.el-p (org-at-table.el-p)))
25271 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
25272 (table.el-p t) ; skip table.el tables
25273 (table-p (org-table-align) t) ; align org-mode tables
25274 (t nil)))) ; call paragraph-fill
25276 ;; For reference, this is the default value of adaptive-fill-regexp
25277 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
25279 (defun org-adaptive-fill-function ()
25280 "Return a fill prefix for org-mode files.
25281 In particular, this makes sure hanging paragraphs for hand-formatted lists
25282 work correctly."
25283 (cond ((looking-at "#[ \t]+")
25284 (match-string 0))
25285 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
25286 (save-excursion
25287 (goto-char (match-end 0))
25288 (make-string (current-column) ?\ )))
25289 (t nil)))
25291 ;;;; Functions extending outline functionality
25293 (defun org-beginning-of-line (&optional arg)
25294 "Go to the beginning of the current line. If that is invisible, continue
25295 to a visible line beginning. This makes the function of C-a more intuitive.
25296 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
25297 first attempt, and only move to after the tags when the cursor is already
25298 beyond the end of the headline."
25299 (interactive "P")
25300 (let ((pos (point)))
25301 (beginning-of-line 1)
25302 (if (bobp)
25304 (backward-char 1)
25305 (if (org-invisible-p)
25306 (while (and (not (bobp)) (org-invisible-p))
25307 (backward-char 1)
25308 (beginning-of-line 1))
25309 (forward-char 1)))
25310 (when org-special-ctrl-a/e
25311 (cond
25312 ((and (looking-at org-todo-line-regexp)
25313 (= (char-after (match-end 1)) ?\ ))
25314 (goto-char
25315 (if (eq org-special-ctrl-a/e t)
25316 (cond ((> pos (match-beginning 3)) (match-beginning 3))
25317 ((= pos (point)) (match-beginning 3))
25318 (t (point)))
25319 (cond ((> pos (point)) (point))
25320 ((not (eq last-command this-command)) (point))
25321 (t (match-beginning 3))))))
25322 ((org-at-item-p)
25323 (goto-char
25324 (if (eq org-special-ctrl-a/e t)
25325 (cond ((> pos (match-end 4)) (match-end 4))
25326 ((= pos (point)) (match-end 4))
25327 (t (point)))
25328 (cond ((> pos (point)) (point))
25329 ((not (eq last-command this-command)) (point))
25330 (t (match-end 4))))))))))
25332 (defun org-end-of-line (&optional arg)
25333 "Go to the end of the line.
25334 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
25335 first attempt, and only move to after the tags when the cursor is already
25336 beyond the end of the headline."
25337 (interactive "P")
25338 (if (or (not org-special-ctrl-a/e)
25339 (not (org-on-heading-p)))
25340 (end-of-line arg)
25341 (let ((pos (point)))
25342 (beginning-of-line 1)
25343 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
25344 (if (eq org-special-ctrl-a/e t)
25345 (if (or (< pos (match-beginning 1))
25346 (= pos (match-end 0)))
25347 (goto-char (match-beginning 1))
25348 (goto-char (match-end 0)))
25349 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
25350 (goto-char (match-end 0))
25351 (goto-char (match-beginning 1))))
25352 (end-of-line arg)))))
25354 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
25355 (define-key org-mode-map "\C-e" 'org-end-of-line)
25357 (defun org-invisible-p ()
25358 "Check if point is at a character currently not visible."
25359 ;; Early versions of noutline don't have `outline-invisible-p'.
25360 (if (fboundp 'outline-invisible-p)
25361 (outline-invisible-p)
25362 (get-char-property (point) 'invisible)))
25364 (defun org-invisible-p2 ()
25365 "Check if point is at a character currently not visible."
25366 (save-excursion
25367 (if (and (eolp) (not (bobp))) (backward-char 1))
25368 ;; Early versions of noutline don't have `outline-invisible-p'.
25369 (if (fboundp 'outline-invisible-p)
25370 (outline-invisible-p)
25371 (get-char-property (point) 'invisible))))
25373 (defalias 'org-back-to-heading 'outline-back-to-heading)
25374 (defalias 'org-on-heading-p 'outline-on-heading-p)
25375 (defalias 'org-at-heading-p 'outline-on-heading-p)
25376 (defun org-at-heading-or-item-p ()
25377 (or (org-on-heading-p) (org-at-item-p)))
25379 (defun org-on-target-p ()
25380 (or (org-in-regexp org-radio-target-regexp)
25381 (org-in-regexp org-target-regexp)))
25383 (defun org-up-heading-all (arg)
25384 "Move to the heading line of which the present line is a subheading.
25385 This function considers both visible and invisible heading lines.
25386 With argument, move up ARG levels."
25387 (if (fboundp 'outline-up-heading-all)
25388 (outline-up-heading-all arg) ; emacs 21 version of outline.el
25389 (outline-up-heading arg t))) ; emacs 22 version of outline.el
25391 (defun org-up-heading-safe ()
25392 "Move to the heading line of which the present line is a subheading.
25393 This version will not throw an error. It will return the level of the
25394 headline found, or nil if no higher level is found."
25395 (let ((pos (point)) start-level level
25396 (re (concat "^" outline-regexp)))
25397 (catch 'exit
25398 (outline-back-to-heading t)
25399 (setq start-level (funcall outline-level))
25400 (if (equal start-level 1) (throw 'exit nil))
25401 (while (re-search-backward re nil t)
25402 (setq level (funcall outline-level))
25403 (if (< level start-level) (throw 'exit level)))
25404 nil)))
25406 (defun org-goto-sibling (&optional previous)
25407 "Goto the next sibling, even if it is invisible.
25408 When PREVIOUS is set, go to the previous sibling instead. Returns t
25409 when a sibling was found. When none is found, return nil and don't
25410 move point."
25411 (let ((fun (if previous 're-search-backward 're-search-forward))
25412 (pos (point))
25413 (re (concat "^" outline-regexp))
25414 level l)
25415 (when (condition-case nil (org-back-to-heading t) (error nil))
25416 (setq level (funcall outline-level))
25417 (catch 'exit
25418 (or previous (forward-char 1))
25419 (while (funcall fun re nil t)
25420 (setq l (funcall outline-level))
25421 (when (< l level) (goto-char pos) (throw 'exit nil))
25422 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
25423 (goto-char pos)
25424 nil))))
25426 (defun org-show-siblings ()
25427 "Show all siblings of the current headline."
25428 (save-excursion
25429 (while (org-goto-sibling) (org-flag-heading nil)))
25430 (save-excursion
25431 (while (org-goto-sibling 'previous)
25432 (org-flag-heading nil))))
25434 (defun org-show-hidden-entry ()
25435 "Show an entry where even the heading is hidden."
25436 (save-excursion
25437 (org-show-entry)))
25439 (defun org-flag-heading (flag &optional entry)
25440 "Flag the current heading. FLAG non-nil means make invisible.
25441 When ENTRY is non-nil, show the entire entry."
25442 (save-excursion
25443 (org-back-to-heading t)
25444 ;; Check if we should show the entire entry
25445 (if entry
25446 (progn
25447 (org-show-entry)
25448 (save-excursion
25449 (and (outline-next-heading)
25450 (org-flag-heading nil))))
25451 (outline-flag-region (max (point-min) (1- (point)))
25452 (save-excursion (outline-end-of-heading) (point))
25453 flag))))
25455 (defun org-end-of-subtree (&optional invisible-OK to-heading)
25456 ;; This is an exact copy of the original function, but it uses
25457 ;; `org-back-to-heading', to make it work also in invisible
25458 ;; trees. And is uses an invisible-OK argument.
25459 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
25460 (org-back-to-heading invisible-OK)
25461 (let ((first t)
25462 (level (funcall outline-level)))
25463 (while (and (not (eobp))
25464 (or first (> (funcall outline-level) level)))
25465 (setq first nil)
25466 (outline-next-heading))
25467 (unless to-heading
25468 (if (memq (preceding-char) '(?\n ?\^M))
25469 (progn
25470 ;; Go to end of line before heading
25471 (forward-char -1)
25472 (if (memq (preceding-char) '(?\n ?\^M))
25473 ;; leave blank line before heading
25474 (forward-char -1))))))
25475 (point))
25477 (defun org-show-subtree ()
25478 "Show everything after this heading at deeper levels."
25479 (outline-flag-region
25480 (point)
25481 (save-excursion
25482 (outline-end-of-subtree) (outline-next-heading) (point))
25483 nil))
25485 (defun org-show-entry ()
25486 "Show the body directly following this heading.
25487 Show the heading too, if it is currently invisible."
25488 (interactive)
25489 (save-excursion
25490 (condition-case nil
25491 (progn
25492 (org-back-to-heading t)
25493 (outline-flag-region
25494 (max (point-min) (1- (point)))
25495 (save-excursion
25496 (re-search-forward
25497 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
25498 (or (match-beginning 1) (point-max)))
25499 nil))
25500 (error nil))))
25502 (defun org-make-options-regexp (kwds)
25503 "Make a regular expression for keyword lines."
25504 (concat
25506 "#?[ \t]*\\+\\("
25507 (mapconcat 'regexp-quote kwds "\\|")
25508 "\\):[ \t]*"
25509 "\\(.+\\)"))
25511 ;; Make isearch reveal the necessary context
25512 (defun org-isearch-end ()
25513 "Reveal context after isearch exits."
25514 (when isearch-success ; only if search was successful
25515 (if (featurep 'xemacs)
25516 ;; Under XEmacs, the hook is run in the correct place,
25517 ;; we directly show the context.
25518 (org-show-context 'isearch)
25519 ;; In Emacs the hook runs *before* restoring the overlays.
25520 ;; So we have to use a one-time post-command-hook to do this.
25521 ;; (Emacs 22 has a special variable, see function `org-mode')
25522 (unless (and (boundp 'isearch-mode-end-hook-quit)
25523 isearch-mode-end-hook-quit)
25524 ;; Only when the isearch was not quitted.
25525 (org-add-hook 'post-command-hook 'org-isearch-post-command
25526 'append 'local)))))
25528 (defun org-isearch-post-command ()
25529 "Remove self from hook, and show context."
25530 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
25531 (org-show-context 'isearch))
25534 ;;;; Address problems with some other packages
25536 ;; Make flyspell not check words in links, to not mess up our keymap
25537 (defun org-mode-flyspell-verify ()
25538 "Don't let flyspell put overlays at active buttons."
25539 (not (get-text-property (point) 'keymap)))
25541 ;; Make `bookmark-jump' show the jump location if it was hidden.
25542 (eval-after-load "bookmark"
25543 '(if (boundp 'bookmark-after-jump-hook)
25544 ;; We can use the hook
25545 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25546 ;; Hook not available, use advice
25547 (defadvice bookmark-jump (after org-make-visible activate)
25548 "Make the position visible."
25549 (org-bookmark-jump-unhide))))
25551 (defun org-bookmark-jump-unhide ()
25552 "Unhide the current position, to show the bookmark location."
25553 (and (org-mode-p)
25554 (or (org-invisible-p)
25555 (save-excursion (goto-char (max (point-min) (1- (point))))
25556 (org-invisible-p)))
25557 (org-show-context 'bookmark-jump)))
25559 ;; Make session.el ignore our circular variable
25560 (eval-after-load "session"
25561 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25563 ;;;; Experimental code
25566 (defun org-closed-in-range ()
25567 "Sparse tree of items closed in a certain time range.
25568 Still experimental, may disappear in the furture."
25569 (interactive)
25570 ;; Get the time interval from the user.
25571 (let* ((time1 (time-to-seconds
25572 (org-read-date nil 'to-time nil "Starting date: ")))
25573 (time2 (time-to-seconds
25574 (org-read-date nil 'to-time nil "End date:")))
25575 ;; callback function
25576 (callback (lambda ()
25577 (let ((time
25578 (time-to-seconds
25579 (apply 'encode-time
25580 (org-parse-time-string
25581 (match-string 1))))))
25582 ;; check if time in interval
25583 (and (>= time time1) (<= time time2))))))
25584 ;; make tree, check each match with the callback
25585 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
25587 (defun org-fill-paragraph-experimental (&optional justify)
25588 "Re-align a table, pass through to fill-paragraph if no table."
25589 (let ((table-p (org-at-table-p))
25590 (table.el-p (org-at-table.el-p)))
25591 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
25592 (table.el-p t) ; skip table.el tables
25593 (table-p (org-table-align) t) ; align org-mode tables
25594 ((save-excursion
25595 (let ((pos (1+ (point-at-eol))))
25596 (backward-paragraph 1)
25597 (re-search-forward "\\\\\\\\[ \t]*$" pos t)))
25598 (save-excursion
25599 (save-restriction
25600 (narrow-to-region (1+ (match-end 0)) (point-max))
25601 (fill-paragraph nil)
25602 t)))
25603 (t nil)))) ; call paragraph-fill
25605 ;; FIXME: this needs a much better algorithm
25606 (defun org-assign-fast-keys (alist)
25607 "Assign fast keys to a keyword-key alist.
25608 Respect keys that are already there."
25609 (let (new e k c c1 c2 (char ?a))
25610 (while (setq e (pop alist))
25611 (cond
25612 ((equal e '(:startgroup)) (push e new))
25613 ((equal e '(:endgroup)) (push e new))
25615 (setq k (car e) c2 nil)
25616 (if (cdr e)
25617 (setq c (cdr e))
25618 ;; automatically assign a character.
25619 (setq c1 (string-to-char
25620 (downcase (substring
25621 k (if (= (string-to-char k) ?@) 1 0)))))
25622 (if (or (rassoc c1 new) (rassoc c1 alist))
25623 (while (or (rassoc char new) (rassoc char alist))
25624 (setq char (1+ char)))
25625 (setq c2 c1))
25626 (setq c (or c2 char)))
25627 (push (cons k c) new))))
25628 (nreverse new)))
25630 (defun org-parse-local-options (string var)
25631 "Parse STRING for startup setting relevant for variable VAR."
25632 (let ((rtn (symbol-value var))
25633 e opts)
25634 (save-match-data
25635 (if (or (not string) (not (string-match "\\S-" string)))
25637 (setq opts (delq nil (mapcar (lambda (x)
25638 (setq e (assoc x org-startup-options))
25639 (if (eq (nth 1 e) var) e nil))
25640 (org-split-string string "[ \t]+"))))
25641 (if (not opts)
25643 (setq rtn nil)
25644 (while (setq e (pop opts))
25645 (if (not (nth 3 e))
25646 (setq rtn (nth 2 e))
25647 (if (not (listp rtn)) (setq rtn nil))
25648 (push (nth 2 e) rtn)))
25649 rtn)))))
25651 ;; FIXME: what else would be useful?
25652 ;; - priority
25653 ;; - date
25655 (defun org-sparse-tree (&optional arg)
25656 "Create a sparse tree, prompt for the details.
25657 This command can create sparse trees. You first need to select the type
25658 of match used to create the tree:
25660 t Show entries with a specific TODO keyword.
25661 T Show entries selected by a tags match.
25662 p Enter a property name and its value (both with completion on existing
25663 names/values) and show entries with that property.
25664 r Show entries matching a regular expression"
25665 (interactive "P")
25666 (let (ans kwd value)
25667 (message "Sparse tree: [r]egexp [t]odo-kwd [T]ag [p]roperty")
25668 (setq ans (read-char-exclusive))
25669 (cond
25670 ((equal ans ?t)
25671 (org-show-todo-tree '(4)))
25672 ((equal ans ?T)
25673 (call-interactively 'org-tags-sparse-tree))
25674 ((member ans '(?p ?P))
25675 (setq kwd (completing-read "Property: "
25676 (mapcar 'list (org-buffer-property-keys))))
25677 (setq value (completing-read "Value: "
25678 (mapcar 'list (org-property-values kwd))))
25679 (unless (string-match "\\`{.*}\\'" value)
25680 (setq value (concat "\"" value "\"")))
25681 (org-tags-sparse-tree arg (concat kwd "=" value)))
25682 ((member ans '(?r ?R))
25683 (call-interactively 'org-occur))
25684 (t (error "No such sparse tree command \"%c\"" ans)))))
25687 ;;;; Finish up
25689 (provide 'org)
25691 (run-hooks 'org-load-hook)
25693 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
25694 ;;; org.el ends here