Release 5.16
[org-mode.git] / org.el
blobd9e5c8c266e9d52c19c48a461534169aa9c1d86e
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.16
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 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
81 (require 'easymenu)
83 ;;;; Customization variables
85 ;;; Version
87 (defconst org-version "5.16"
88 "The version number of the file org.el.")
89 (defun org-version ()
90 (interactive)
91 (message "Org-mode version %s" org-version))
93 ;;; Compatibility constants
94 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
95 (defconst org-format-transports-properties-p
96 (let ((x "a"))
97 (add-text-properties 0 1 '(test t) x)
98 (get-text-property 0 'test (format "%s" x)))
99 "Does format transport text properties?")
101 (defmacro org-unmodified (&rest body)
102 "Execute body without changing buffer-modified-p."
103 `(set-buffer-modified-p
104 (prog1 (buffer-modified-p) ,@body)))
106 (defmacro org-re (s)
107 "Replace posix classes in regular expression."
108 (if (featurep 'xemacs)
109 (let ((ss s))
110 (save-match-data
111 (while (string-match "\\[:alnum:\\]" ss)
112 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
113 (while (string-match "\\[:alpha:\\]" ss)
114 (setq ss (replace-match "a-zA-Z" t t ss)))
115 ss))
118 (defmacro org-preserve-lc (&rest body)
119 `(let ((_line (org-current-line))
120 (_col (current-column)))
121 (unwind-protect
122 (progn ,@body)
123 (goto-line _line)
124 (move-to-column _col))))
126 (defmacro org-without-partial-completion (&rest body)
127 `(let ((pc-mode (and (boundp 'partial-completion-mode)
128 partial-completion-mode)))
129 (unwind-protect
130 (progn
131 (if pc-mode (partial-completion-mode -1))
132 ,@body)
133 (if pc-mode (partial-completion-mode 1)))))
135 ;;; The custom variables
137 (defgroup org nil
138 "Outline-based notes management and organizer."
139 :tag "Org"
140 :group 'outlines
141 :group 'hypermedia
142 :group 'calendar)
144 ;; FIXME: Needs a separate group...
145 (defcustom org-completion-fallback-command 'hippie-expand
146 "The expansion command called by \\[org-complete] in normal context.
147 Normal means, no org-mode-specific context."
148 :group 'org
149 :type 'function)
151 (defgroup org-startup nil
152 "Options concerning startup of Org-mode."
153 :tag "Org Startup"
154 :group 'org)
156 (defcustom org-startup-folded t
157 "Non-nil means, entering Org-mode will switch to OVERVIEW.
158 This can also be configured on a per-file basis by adding one of
159 the following lines anywhere in the buffer:
161 #+STARTUP: fold
162 #+STARTUP: nofold
163 #+STARTUP: content"
164 :group 'org-startup
165 :type '(choice
166 (const :tag "nofold: show all" nil)
167 (const :tag "fold: overview" t)
168 (const :tag "content: all headlines" content)))
170 (defcustom org-startup-truncated t
171 "Non-nil means, entering Org-mode will set `truncate-lines'.
172 This is useful since some lines containing links can be very long and
173 uninteresting. Also tables look terrible when wrapped."
174 :group 'org-startup
175 :type 'boolean)
177 (defcustom org-startup-align-all-tables nil
178 "Non-nil means, align all tables when visiting a file.
179 This is useful when the column width in tables is forced with <N> cookies
180 in table fields. Such tables will look correct only after the first re-align.
181 This can also be configured on a per-file basis by adding one of
182 the following lines anywhere in the buffer:
183 #+STARTUP: align
184 #+STARTUP: noalign"
185 :group 'org-startup
186 :type 'boolean)
188 (defcustom org-insert-mode-line-in-empty-file nil
189 "Non-nil means insert the first line setting Org-mode in empty files.
190 When the function `org-mode' is called interactively in an empty file, this
191 normally means that the file name does not automatically trigger Org-mode.
192 To ensure that the file will always be in Org-mode in the future, a
193 line enforcing Org-mode will be inserted into the buffer, if this option
194 has been set."
195 :group 'org-startup
196 :type 'boolean)
198 (defcustom org-replace-disputed-keys nil
199 "Non-nil means use alternative key bindings for some keys.
200 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
201 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
202 If you want to use Org-mode together with one of these other modes,
203 or more generally if you would like to move some Org-mode commands to
204 other keys, set this variable and configure the keys with the variable
205 `org-disputed-keys'.
207 This option is only relevant at load-time of Org-mode, and must be set
208 *before* org.el is loaded. Changing it requires a restart of Emacs to
209 become effective."
210 :group 'org-startup
211 :type 'boolean)
213 (if (fboundp 'defvaralias)
214 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
216 (defcustom org-disputed-keys
217 '(([(shift up)] . [(meta p)])
218 ([(shift down)] . [(meta n)])
219 ([(shift left)] . [(meta -)])
220 ([(shift right)] . [(meta +)])
221 ([(control shift right)] . [(meta shift +)])
222 ([(control shift left)] . [(meta shift -)]))
223 "Keys for which Org-mode and other modes compete.
224 This is an alist, cars are the default keys, second element specifies
225 the alternative to use when `org-replace-disputed-keys' is t.
227 Keys can be specified in any syntax supported by `define-key'.
228 The value of this option takes effect only at Org-mode's startup,
229 therefore you'll have to restart Emacs to apply it after changing."
230 :group 'org-startup
231 :type 'alist)
233 (defun org-key (key)
234 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
235 Or return the original if not disputed."
236 (if org-replace-disputed-keys
237 (let* ((nkey (key-description key))
238 (x (org-find-if (lambda (x)
239 (equal (key-description (car x)) nkey))
240 org-disputed-keys)))
241 (if x (cdr x) key))
242 key))
244 (defun org-find-if (predicate seq)
245 (catch 'exit
246 (while seq
247 (if (funcall predicate (car seq))
248 (throw 'exit (car seq))
249 (pop seq)))))
251 (defun org-defkey (keymap key def)
252 "Define a key, possibly translated, as returned by `org-key'."
253 (define-key keymap (org-key key) def))
255 (defcustom org-ellipsis nil
256 "The ellipsis to use in the Org-mode outline.
257 When nil, just use the standard three dots. When a string, use that instead,
258 When a face, use the standart 3 dots, but with the specified face.
259 The change affects only Org-mode (which will then use its own display table).
260 Changing this requires executing `M-x org-mode' in a buffer to become
261 effective."
262 :group 'org-startup
263 :type '(choice (const :tag "Default" nil)
264 (face :tag "Face" :value org-warning)
265 (string :tag "String" :value "...#")))
267 (defvar org-display-table nil
268 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
270 (defgroup org-keywords nil
271 "Keywords in Org-mode."
272 :tag "Org Keywords"
273 :group 'org)
275 (defcustom org-deadline-string "DEADLINE:"
276 "String to mark deadline entries.
277 A deadline is this string, followed by a time stamp. Should be a word,
278 terminated by a colon. You can insert a schedule keyword and
279 a timestamp with \\[org-deadline].
280 Changes become only effective after restarting Emacs."
281 :group 'org-keywords
282 :type 'string)
284 (defcustom org-scheduled-string "SCHEDULED:"
285 "String to mark scheduled TODO entries.
286 A schedule is this string, followed by a time stamp. Should be a word,
287 terminated by a colon. You can insert a schedule keyword and
288 a timestamp with \\[org-schedule].
289 Changes become only effective after restarting Emacs."
290 :group 'org-keywords
291 :type 'string)
293 (defcustom org-closed-string "CLOSED:"
294 "String used as the prefix for timestamps logging closing a TODO entry."
295 :group 'org-keywords
296 :type 'string)
298 (defcustom org-clock-string "CLOCK:"
299 "String used as prefix for timestamps clocking work hours on an item."
300 :group 'org-keywords
301 :type 'string)
303 (defcustom org-comment-string "COMMENT"
304 "Entries starting with this keyword will never be exported.
305 An entry can be toggled between COMMENT and normal with
306 \\[org-toggle-comment].
307 Changes become only effective after restarting Emacs."
308 :group 'org-keywords
309 :type 'string)
311 (defcustom org-quote-string "QUOTE"
312 "Entries starting with this keyword will be exported in fixed-width font.
313 Quoting applies only to the text in the entry following the headline, and does
314 not extend beyond the next headline, even if that is lower level.
315 An entry can be toggled between QUOTE and normal with
316 \\[org-toggle-fixed-width-section]."
317 :group 'org-keywords
318 :type 'string)
320 (defconst org-repeat-re
321 (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
322 " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
323 "Regular expression for specifying repeated events.
324 After a match, group 1 contains the repeat expression.")
326 (defgroup org-structure nil
327 "Options concerning the general structure of Org-mode files."
328 :tag "Org Structure"
329 :group 'org)
331 (defgroup org-reveal-location nil
332 "Options about how to make context of a location visible."
333 :tag "Org Reveal Location"
334 :group 'org-structure)
336 (defcustom org-show-hierarchy-above '((default . t))
337 "Non-nil means, show full hierarchy when revealing a location.
338 Org-mode often shows locations in an org-mode file which might have
339 been invisible before. When this is set, the hierarchy of headings
340 above the exposed location is shown.
341 Turning this off for example for sparse trees makes them very compact.
342 Instead of t, this can also be an alist specifying this option for different
343 contexts. Valid contexts are
344 agenda when exposing an entry from the agenda
345 org-goto when using the command `org-goto' on key C-c C-j
346 occur-tree when using the command `org-occur' on key C-c /
347 tags-tree when constructing a sparse tree based on tags matches
348 link-search when exposing search matches associated with a link
349 mark-goto when exposing the jump goal of a mark
350 bookmark-jump when exposing a bookmark location
351 isearch when exiting from an incremental search
352 default default for all contexts not set explicitly"
353 :group 'org-reveal-location
354 :type '(choice
355 (const :tag "Always" t)
356 (const :tag "Never" nil)
357 (repeat :greedy t :tag "Individual contexts"
358 (cons
359 (choice :tag "Context"
360 (const agenda)
361 (const org-goto)
362 (const occur-tree)
363 (const tags-tree)
364 (const link-search)
365 (const mark-goto)
366 (const bookmark-jump)
367 (const isearch)
368 (const default))
369 (boolean)))))
371 (defcustom org-show-following-heading '((default . nil))
372 "Non-nil means, show following heading when revealing a location.
373 Org-mode often shows locations in an org-mode file which might have
374 been invisible before. When this is set, the heading following the
375 match is shown.
376 Turning this off for example for sparse trees makes them very compact,
377 but makes it harder to edit the location of the match. In such a case,
378 use the command \\[org-reveal] to show more context.
379 Instead of t, this can also be an alist specifying this option for different
380 contexts. See `org-show-hierarchy-above' for valid contexts."
381 :group 'org-reveal-location
382 :type '(choice
383 (const :tag "Always" t)
384 (const :tag "Never" nil)
385 (repeat :greedy t :tag "Individual contexts"
386 (cons
387 (choice :tag "Context"
388 (const agenda)
389 (const org-goto)
390 (const occur-tree)
391 (const tags-tree)
392 (const link-search)
393 (const mark-goto)
394 (const bookmark-jump)
395 (const isearch)
396 (const default))
397 (boolean)))))
399 (defcustom org-show-siblings '((default . nil) (isearch t))
400 "Non-nil means, show all sibling heading when revealing a location.
401 Org-mode often shows locations in an org-mode file which might have
402 been invisible before. When this is set, the sibling of the current entry
403 heading are all made visible. If `org-show-hierarchy-above' is t,
404 the same happens on each level of the hierarchy above the current entry.
406 By default this is on for the isearch context, off for all other contexts.
407 Turning this off for example for sparse trees makes them very compact,
408 but makes it harder to edit the location of the match. In such a case,
409 use the command \\[org-reveal] to show more context.
410 Instead of t, this can also be an alist specifying this option for different
411 contexts. See `org-show-hierarchy-above' for valid contexts."
412 :group 'org-reveal-location
413 :type '(choice
414 (const :tag "Always" t)
415 (const :tag "Never" nil)
416 (repeat :greedy t :tag "Individual contexts"
417 (cons
418 (choice :tag "Context"
419 (const agenda)
420 (const org-goto)
421 (const occur-tree)
422 (const tags-tree)
423 (const link-search)
424 (const mark-goto)
425 (const bookmark-jump)
426 (const isearch)
427 (const default))
428 (boolean)))))
430 (defcustom org-show-entry-below '((default . nil))
431 "Non-nil means, show the entry below a headline when revealing a location.
432 Org-mode often shows locations in an org-mode file which might have
433 been invisible before. When this is set, the text below the headline that is
434 exposed is also shown.
436 By default this is off for all contexts.
437 Instead of t, this can also be an alist specifying this option for different
438 contexts. See `org-show-hierarchy-above' for valid contexts."
439 :group 'org-reveal-location
440 :type '(choice
441 (const :tag "Always" t)
442 (const :tag "Never" nil)
443 (repeat :greedy t :tag "Individual contexts"
444 (cons
445 (choice :tag "Context"
446 (const agenda)
447 (const org-goto)
448 (const occur-tree)
449 (const tags-tree)
450 (const link-search)
451 (const mark-goto)
452 (const bookmark-jump)
453 (const isearch)
454 (const default))
455 (boolean)))))
457 (defgroup org-cycle nil
458 "Options concerning visibility cycling in Org-mode."
459 :tag "Org Cycle"
460 :group 'org-structure)
462 (defcustom org-drawers '("PROPERTIES" "CLOCK")
463 "Names of drawers. Drawers are not opened by cycling on the headline above.
464 Drawers only open with a TAB on the drawer line itself. A drawer looks like
465 this:
466 :DRAWERNAME:
467 .....
468 :END:
469 The drawer \"PROPERTIES\" is special for capturing properties through
470 the property API.
472 Drawers can be defined on the per-file basis with a line like:
474 #+DRAWERS: HIDDEN STATE PROPERTIES"
475 :group 'org-structure
476 :type '(repeat (string :tag "Drawer Name")))
478 (defcustom org-cycle-global-at-bob nil
479 "Cycle globally if cursor is at beginning of buffer and not at a headline.
480 This makes it possible to do global cycling without having to use S-TAB or
481 C-u TAB. For this special case to work, the first line of the buffer
482 must not be a headline - it may be empty ot some other text. When used in
483 this way, `org-cycle-hook' is disables temporarily, to make sure the
484 cursor stays at the beginning of the buffer.
485 When this option is nil, don't do anything special at the beginning
486 of the buffer."
487 :group 'org-cycle
488 :type 'boolean)
490 (defcustom org-cycle-emulate-tab t
491 "Where should `org-cycle' emulate TAB.
492 nil Never
493 white Only in completely white lines
494 whitestart Only at the beginning of lines, before the first non-white char.
495 t Everywhere except in headlines
496 exc-hl-bol Everywhere except at the start of a headline
497 If TAB is used in a place where it does not emulate TAB, the current subtree
498 visibility is cycled."
499 :group 'org-cycle
500 :type '(choice (const :tag "Never" nil)
501 (const :tag "Only in completely white lines" white)
502 (const :tag "Before first char in a line" whitestart)
503 (const :tag "Everywhere except in headlines" t)
504 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
507 (defcustom org-cycle-separator-lines 2
508 "Number of empty lines needed to keep an empty line between collapsed trees.
509 If you leave an empty line between the end of a subtree and the following
510 headline, this empty line is hidden when the subtree is folded.
511 Org-mode will leave (exactly) one empty line visible if the number of
512 empty lines is equal or larger to the number given in this variable.
513 So the default 2 means, at least 2 empty lines after the end of a subtree
514 are needed to produce free space between a collapsed subtree and the
515 following headline.
517 Special case: when 0, never leave empty lines in collapsed view."
518 :group 'org-cycle
519 :type 'integer)
521 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
522 org-cycle-hide-drawers
523 org-cycle-show-empty-lines
524 org-optimize-window-after-visibility-change)
525 "Hook that is run after `org-cycle' has changed the buffer visibility.
526 The function(s) in this hook must accept a single argument which indicates
527 the new state that was set by the most recent `org-cycle' command. The
528 argument is a symbol. After a global state change, it can have the values
529 `overview', `content', or `all'. After a local state change, it can have
530 the values `folded', `children', or `subtree'."
531 :group 'org-cycle
532 :type 'hook)
534 (defgroup org-edit-structure nil
535 "Options concerning structure editing in Org-mode."
536 :tag "Org Edit Structure"
537 :group 'org-structure)
539 (defcustom org-special-ctrl-a/e nil
540 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
541 When t, `C-a' will bring back the cursor to the beginning of the
542 headline text, i.e. after the stars and after a possible TODO keyword.
543 In an item, this will be the position after the bullet.
544 When the cursor is already at that position, another `C-a' will bring
545 it to the beginning of the line.
546 `C-e' will jump to the end of the headline, ignoring the presence of tags
547 in the headline. A second `C-e' will then jump to the true end of the
548 line, after any tags.
549 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
550 and only a directly following, identical keypress will bring the cursor
551 to the special positions."
552 :group 'org-edit-structure
553 :type '(choice
554 (const :tag "off" nil)
555 (const :tag "after bullet first" t)
556 (const :tag "border first" reversed)))
558 (if (fboundp 'defvaralias)
559 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
561 (defcustom org-odd-levels-only nil
562 "Non-nil means, skip even levels and only use odd levels for the outline.
563 This has the effect that two stars are being added/taken away in
564 promotion/demotion commands. It also influences how levels are
565 handled by the exporters.
566 Changing it requires restart of `font-lock-mode' to become effective
567 for fontification also in regions already fontified.
568 You may also set this on a per-file basis by adding one of the following
569 lines to the buffer:
571 #+STARTUP: odd
572 #+STARTUP: oddeven"
573 :group 'org-edit-structure
574 :group 'org-font-lock
575 :type 'boolean)
577 (defcustom org-adapt-indentation t
578 "Non-nil means, adapt indentation when promoting and demoting.
579 When this is set and the *entire* text in an entry is indented, the
580 indentation is increased by one space in a demotion command, and
581 decreased by one in a promotion command. If any line in the entry
582 body starts at column 0, indentation is not changed at all."
583 :group 'org-edit-structure
584 :type 'boolean)
586 (defcustom org-blank-before-new-entry '((heading . nil)
587 (plain-list-item . nil))
588 "Should `org-insert-heading' leave a blank line before new heading/item?
589 The value is an alist, with `heading' and `plain-list-item' as car,
590 and a boolean flag as cdr."
591 :group 'org-edit-structure
592 :type '(list
593 (cons (const heading) (boolean))
594 (cons (const plain-list-item) (boolean))))
596 (defcustom org-insert-heading-hook nil
597 "Hook being run after inserting a new heading."
598 :group 'org-edit-structure
599 :type 'hook)
601 (defcustom org-enable-fixed-width-editor t
602 "Non-nil means, lines starting with \":\" are treated as fixed-width.
603 This currently only means, they are never auto-wrapped.
604 When nil, such lines will be treated like ordinary lines.
605 See also the QUOTE keyword."
606 :group 'org-edit-structure
607 :type 'boolean)
609 (defgroup org-sparse-trees nil
610 "Options concerning sparse trees in Org-mode."
611 :tag "Org Sparse Trees"
612 :group 'org-structure)
614 (defcustom org-highlight-sparse-tree-matches t
615 "Non-nil means, highlight all matches that define a sparse tree.
616 The highlights will automatically disappear the next time the buffer is
617 changed by an edit command."
618 :group 'org-sparse-trees
619 :type 'boolean)
621 (defcustom org-remove-highlights-with-change t
622 "Non-nil means, any change to the buffer will remove temporary highlights.
623 Such highlights are created by `org-occur' and `org-clock-display'.
624 When nil, `C-c C-c needs to be used to get rid of the highlights.
625 The highlights created by `org-preview-latex-fragment' always need
626 `C-c C-c' to be removed."
627 :group 'org-sparse-trees
628 :group 'org-time
629 :type 'boolean)
632 (defcustom org-occur-hook '(org-first-headline-recenter)
633 "Hook that is run after `org-occur' has constructed a sparse tree.
634 This can be used to recenter the window to show as much of the structure
635 as possible."
636 :group 'org-sparse-trees
637 :type 'hook)
639 (defgroup org-plain-lists nil
640 "Options concerning plain lists in Org-mode."
641 :tag "Org Plain lists"
642 :group 'org-structure)
644 (defcustom org-cycle-include-plain-lists nil
645 "Non-nil means, include plain lists into visibility cycling.
646 This means that during cycling, plain list items will *temporarily* be
647 interpreted as outline headlines with a level given by 1000+i where i is the
648 indentation of the bullet. In all other operations, plain list items are
649 not seen as headlines. For example, you cannot assign a TODO keyword to
650 such an item."
651 :group 'org-plain-lists
652 :type 'boolean)
654 (defcustom org-plain-list-ordered-item-terminator t
655 "The character that makes a line with leading number an ordered list item.
656 Valid values are ?. and ?\). To get both terminators, use t. While
657 ?. may look nicer, it creates the danger that a line with leading
658 number may be incorrectly interpreted as an item. ?\) therefore is
659 the safe choice."
660 :group 'org-plain-lists
661 :type '(choice (const :tag "dot like in \"2.\"" ?.)
662 (const :tag "paren like in \"2)\"" ?\))
663 (const :tab "both" t)))
665 (defcustom org-auto-renumber-ordered-lists t
666 "Non-nil means, automatically renumber ordered plain lists.
667 Renumbering happens when the sequence have been changed with
668 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
669 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
670 :group 'org-plain-lists
671 :type 'boolean)
673 (defcustom org-provide-checkbox-statistics t
674 "Non-nil means, update checkbox statistics after insert and toggle.
675 When this is set, checkbox statistics is updated each time you either insert
676 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
677 with \\[org-ctrl-c-ctrl-c\\]."
678 :group 'org-plain-lists
679 :type 'boolean)
681 (defgroup org-archive nil
682 "Options concerning archiving in Org-mode."
683 :tag "Org Archive"
684 :group 'org-structure)
686 (defcustom org-archive-tag "ARCHIVE"
687 "The tag that marks a subtree as archived.
688 An archived subtree does not open during visibility cycling, and does
689 not contribute to the agenda listings.
690 After changing this, font-lock must be restarted in the relevant buffers to
691 get the proper fontification."
692 :group 'org-archive
693 :group 'org-keywords
694 :type 'string)
696 (defcustom org-agenda-skip-archived-trees t
697 "Non-nil means, the agenda will skip any items located in archived trees.
698 An archived tree is a tree marked with the tag ARCHIVE."
699 :group 'org-archive
700 :group 'org-agenda-skip
701 :type 'boolean)
703 (defcustom org-cycle-open-archived-trees nil
704 "Non-nil means, `org-cycle' will open archived trees.
705 An archived tree is a tree marked with the tag ARCHIVE.
706 When nil, archived trees will stay folded. You can still open them with
707 normal outline commands like `show-all', but not with the cycling commands."
708 :group 'org-archive
709 :group 'org-cycle
710 :type 'boolean)
712 (defcustom org-sparse-tree-open-archived-trees nil
713 "Non-nil means sparse tree construction shows matches in archived trees.
714 When nil, matches in these trees are highlighted, but the trees are kept in
715 collapsed state."
716 :group 'org-archive
717 :group 'org-sparse-trees
718 :type 'boolean)
720 (defcustom org-archive-location "%s_archive::"
721 "The location where subtrees should be archived.
722 This string consists of two parts, separated by a double-colon.
724 The first part is a file name - when omitted, archiving happens in the same
725 file. %s will be replaced by the current file name (without directory part).
726 Archiving to a different file is useful to keep archived entries from
727 contributing to the Org-mode Agenda.
729 The part after the double colon is a headline. The archived entries will be
730 filed under that headline. When omitted, the subtrees are simply filed away
731 at the end of the file, as top-level entries.
733 Here are a few examples:
734 \"%s_archive::\"
735 If the current file is Projects.org, archive in file
736 Projects.org_archive, as top-level trees. This is the default.
738 \"::* Archived Tasks\"
739 Archive in the current file, under the top-level headline
740 \"* Archived Tasks\".
742 \"~/org/archive.org::\"
743 Archive in file ~/org/archive.org (absolute path), as top-level trees.
745 \"basement::** Finished Tasks\"
746 Archive in file ./basement (relative path), as level 3 trees
747 below the level 2 heading \"** Finished Tasks\".
749 You may set this option on a per-file basis by adding to the buffer a
750 line like
752 #+ARCHIVE: basement::** Finished Tasks"
753 :group 'org-archive
754 :type 'string)
756 (defcustom org-archive-mark-done t
757 "Non-nil means, mark entries as DONE when they are moved to the archive file.
758 This can be a string to set the keyword to use. When t, Org-mode will
759 use the first keyword in its list that means done."
760 :group 'org-archive
761 :type '(choice
762 (const :tag "No" nil)
763 (const :tag "Yes" t)
764 (string :tag "Use this keyword")))
766 (defcustom org-archive-stamp-time t
767 "Non-nil means, add a time stamp to entries moved to an archive file.
768 This variable is obsolete and has no effect anymore, instead add ot remove
769 `time' from the variablle `org-archive-save-context-info'."
770 :group 'org-archive
771 :type 'boolean)
773 (defcustom org-archive-save-context-info '(time file category todo itags)
774 "Parts of context info that should be stored as properties when archiving.
775 When a subtree is moved to an archive file, it looses information given by
776 context, like inherited tags, the category, and possibly also the TODO
777 state (depending on the variable `org-archive-mark-done').
778 This variable can be a list of any of the following symbols:
780 time The time of archiving.
781 file The file where the entry originates.
782 itags The local tags, in the headline of the subtree.
783 ltags The tags the subtree inherits from further up the hierarchy.
784 todo The pre-archive TODO state.
785 category The category, taken from file name or #+CATEGORY lines.
787 For each symbol present in the list, a property will be created in
788 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
789 information."
790 :group 'org-archive
791 :type '(set :greedy t
792 (const :tag "Time" time)
793 (const :tag "File" file)
794 (const :tag "Category" category)
795 (const :tag "TODO state" todo)
796 (const :tag "TODO state" priority)
797 (const :tag "Inherited tags" itags)
798 (const :tag "Local tags" ltags)))
800 (defgroup org-imenu-and-speedbar nil
801 "Options concerning imenu and speedbar in Org-mode."
802 :tag "Org Imenu and Speedbar"
803 :group 'org-structure)
805 (defcustom org-imenu-depth 2
806 "The maximum level for Imenu access to Org-mode headlines.
807 This also applied for speedbar access."
808 :group 'org-imenu-and-speedbar
809 :type 'number)
811 (defgroup org-table nil
812 "Options concerning tables in Org-mode."
813 :tag "Org Table"
814 :group 'org)
816 (defcustom org-enable-table-editor 'optimized
817 "Non-nil means, lines starting with \"|\" are handled by the table editor.
818 When nil, such lines will be treated like ordinary lines.
820 When equal to the symbol `optimized', the table editor will be optimized to
821 do the following:
822 - Automatic overwrite mode in front of whitespace in table fields.
823 This makes the structure of the table stay in tact as long as the edited
824 field does not exceed the column width.
825 - Minimize the number of realigns. Normally, the table is aligned each time
826 TAB or RET are pressed to move to another field. With optimization this
827 happens only if changes to a field might have changed the column width.
828 Optimization requires replacing the functions `self-insert-command',
829 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
830 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
831 very good at guessing when a re-align will be necessary, but you can always
832 force one with \\[org-ctrl-c-ctrl-c].
834 If you would like to use the optimized version in Org-mode, but the
835 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
837 This variable can be used to turn on and off the table editor during a session,
838 but in order to toggle optimization, a restart is required.
840 See also the variable `org-table-auto-blank-field'."
841 :group 'org-table
842 :type '(choice
843 (const :tag "off" nil)
844 (const :tag "on" t)
845 (const :tag "on, optimized" optimized)))
847 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
848 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
849 In the optimized version, the table editor takes over all simple keys that
850 normally just insert a character. In tables, the characters are inserted
851 in a way to minimize disturbing the table structure (i.e. in overwrite mode
852 for empty fields). Outside tables, the correct binding of the keys is
853 restored.
855 The default for this option is t if the optimized version is also used in
856 Org-mode. See the variable `org-enable-table-editor' for details. Changing
857 this variable requires a restart of Emacs to become effective."
858 :group 'org-table
859 :type 'boolean)
861 (defcustom orgtbl-radio-table-templates
862 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
863 % END RECEIVE ORGTBL %n
864 \\begin{comment}
865 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
866 | | |
867 \\end{comment}\n")
868 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
869 @c END RECEIVE ORGTBL %n
870 @ignore
871 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
872 | | |
873 @end ignore\n")
874 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
875 <!-- END RECEIVE ORGTBL %n -->
876 <!--
877 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
878 | | |
879 -->\n"))
880 "Templates for radio tables in different major modes.
881 All occurrences of %n in a template will be replaced with the name of the
882 table, obtained by prompting the user."
883 :group 'org-table
884 :type '(repeat
885 (list (symbol :tag "Major mode")
886 (string :tag "Format"))))
888 (defgroup org-table-settings nil
889 "Settings for tables in Org-mode."
890 :tag "Org Table Settings"
891 :group 'org-table)
893 (defcustom org-table-default-size "5x2"
894 "The default size for newly created tables, Columns x Rows."
895 :group 'org-table-settings
896 :type 'string)
898 (defcustom org-table-number-regexp
899 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
900 "Regular expression for recognizing numbers in table columns.
901 If a table column contains mostly numbers, it will be aligned to the
902 right. If not, it will be aligned to the left.
904 The default value of this option is a regular expression which allows
905 anything which looks remotely like a number as used in scientific
906 context. For example, all of the following will be considered a
907 number:
908 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
910 Other options offered by the customize interface are more restrictive."
911 :group 'org-table-settings
912 :type '(choice
913 (const :tag "Positive Integers"
914 "^[0-9]+$")
915 (const :tag "Integers"
916 "^[-+]?[0-9]+$")
917 (const :tag "Floating Point Numbers"
918 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
919 (const :tag "Floating Point Number or Integer"
920 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
921 (const :tag "Exponential, Floating point, Integer"
922 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
923 (const :tag "Very General Number-Like, including hex"
924 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
925 (string :tag "Regexp:")))
927 (defcustom org-table-number-fraction 0.5
928 "Fraction of numbers in a column required to make the column align right.
929 In a column all non-white fields are considered. If at least this
930 fraction of fields is matched by `org-table-number-fraction',
931 alignment to the right border applies."
932 :group 'org-table-settings
933 :type 'number)
935 (defgroup org-table-editing nil
936 "Behavior of tables during editing in Org-mode."
937 :tag "Org Table Editing"
938 :group 'org-table)
940 (defcustom org-table-automatic-realign t
941 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
942 When nil, aligning is only done with \\[org-table-align], or after column
943 removal/insertion."
944 :group 'org-table-editing
945 :type 'boolean)
947 (defcustom org-table-auto-blank-field t
948 "Non-nil means, automatically blank table field when starting to type into it.
949 This only happens when typing immediately after a field motion
950 command (TAB, S-TAB or RET).
951 Only relevant when `org-enable-table-editor' is equal to `optimized'."
952 :group 'org-table-editing
953 :type 'boolean)
955 (defcustom org-table-tab-jumps-over-hlines t
956 "Non-nil means, tab in the last column of a table with jump over a hline.
957 If a horizontal separator line is following the current line,
958 `org-table-next-field' can either create a new row before that line, or jump
959 over the line. When this option is nil, a new line will be created before
960 this line."
961 :group 'org-table-editing
962 :type 'boolean)
964 (defcustom org-table-tab-recognizes-table.el t
965 "Non-nil means, TAB will automatically notice a table.el table.
966 When it sees such a table, it moves point into it and - if necessary -
967 calls `table-recognize-table'."
968 :group 'org-table-editing
969 :type 'boolean)
971 (defgroup org-table-calculation nil
972 "Options concerning tables in Org-mode."
973 :tag "Org Table Calculation"
974 :group 'org-table)
976 (defcustom org-table-use-standard-references t
977 "Should org-mode work with table refrences like B3 instead of @3$2?
978 Possible values are:
979 nil never use them
980 from accept as input, do not present for editing
981 t: accept as input and present for editing"
982 :group 'org-table-calculation
983 :type '(choice
984 (const :tag "Never, don't even check unser input for them" nil)
985 (const :tag "Always, both as user input, and when editing" t)
986 (const :tag "Convert user input, don't offer during editing" 'from)))
988 (defcustom org-table-copy-increment t
989 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
990 :group 'org-table-calculation
991 :type 'boolean)
993 (defcustom org-calc-default-modes
994 '(calc-internal-prec 12
995 calc-float-format (float 5)
996 calc-angle-mode deg
997 calc-prefer-frac nil
998 calc-symbolic-mode nil
999 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1000 calc-display-working-message t
1002 "List with Calc mode settings for use in calc-eval for table formulas.
1003 The list must contain alternating symbols (Calc modes variables and values).
1004 Don't remove any of the default settings, just change the values. Org-mode
1005 relies on the variables to be present in the list."
1006 :group 'org-table-calculation
1007 :type 'plist)
1009 (defcustom org-table-formula-evaluate-inline t
1010 "Non-nil means, TAB and RET evaluate a formula in current table field.
1011 If the current field starts with an equal sign, it is assumed to be a formula
1012 which should be evaluated as described in the manual and in the documentation
1013 string of the command `org-table-eval-formula'. This feature requires the
1014 Emacs calc package.
1015 When this variable is nil, formula calculation is only available through
1016 the command \\[org-table-eval-formula]."
1017 :group 'org-table-calculation
1018 :type 'boolean)
1020 (defcustom org-table-formula-use-constants t
1021 "Non-nil means, interpret constants in formulas in tables.
1022 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1023 by the value given in `org-table-formula-constants', or by a value obtained
1024 from the `constants.el' package."
1025 :group 'org-table-calculation
1026 :type 'boolean)
1028 (defcustom org-table-formula-constants nil
1029 "Alist with constant names and values, for use in table formulas.
1030 The car of each element is a name of a constant, without the `$' before it.
1031 The cdr is the value as a string. For example, if you'd like to use the
1032 speed of light in a formula, you would configure
1034 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1036 and then use it in an equation like `$1*$c'.
1038 Constants can also be defined on a per-file basis using a line like
1040 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1041 :group 'org-table-calculation
1042 :type '(repeat
1043 (cons (string :tag "name")
1044 (string :tag "value"))))
1046 (defvar org-table-formula-constants-local nil
1047 "Local version of `org-table-formula-constants'.")
1048 (make-variable-buffer-local 'org-table-formula-constants-local)
1050 (defcustom org-table-allow-automatic-line-recalculation t
1051 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1052 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1053 :group 'org-table-calculation
1054 :type 'boolean)
1056 (defgroup org-link nil
1057 "Options concerning links in Org-mode."
1058 :tag "Org Link"
1059 :group 'org)
1061 (defvar org-link-abbrev-alist-local nil
1062 "Buffer-local version of `org-link-abbrev-alist', which see.
1063 The value of this is taken from the #+LINK lines.")
1064 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1066 (defcustom org-link-abbrev-alist nil
1067 "Alist of link abbreviations.
1068 The car of each element is a string, to be replaced at the start of a link.
1069 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1070 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1072 [[linkkey:tag][description]]
1074 If REPLACE is a string, the tag will simply be appended to create the link.
1075 If the string contains \"%s\", the tag will be inserted there.
1077 REPLACE may also be a function that will be called with the tag as the
1078 only argument to create the link, which should be returned as a string.
1080 See the manual for examples."
1081 :group 'org-link
1082 :type 'alist)
1084 (defcustom org-descriptive-links t
1085 "Non-nil means, hide link part and only show description of bracket links.
1086 Bracket links are like [[link][descritpion]]. This variable sets the initial
1087 state in new org-mode buffers. The setting can then be toggled on a
1088 per-buffer basis from the Org->Hyperlinks menu."
1089 :group 'org-link
1090 :type 'boolean)
1092 (defcustom org-link-file-path-type 'adaptive
1093 "How the path name in file links should be stored.
1094 Valid values are:
1096 relative relative to the current directory, i.e. the directory of the file
1097 into which the link is being inserted.
1098 absolute absolute path, if possible with ~ for home directory.
1099 noabbrev absolute path, no abbreviation of home directory.
1100 adaptive Use relative path for files in the current directory and sub-
1101 directories of it. For other files, use an absolute path."
1102 :group 'org-link
1103 :type '(choice
1104 (const relative)
1105 (const absolute)
1106 (const noabbrev)
1107 (const adaptive)))
1109 (defcustom org-activate-links '(bracket angle plain radio tag date)
1110 "Types of links that should be activated in Org-mode files.
1111 This is a list of symbols, each leading to the activation of a certain link
1112 type. In principle, it does not hurt to turn on most link types - there may
1113 be a small gain when turning off unused link types. The types are:
1115 bracket The recommended [[link][description]] or [[link]] links with hiding.
1116 angular Links in angular brackes that may contain whitespace like
1117 <bbdb:Carsten Dominik>.
1118 plain Plain links in normal text, no whitespace, like http://google.com.
1119 radio Text that is matched by a radio target, see manual for details.
1120 tag Tag settings in a headline (link to tag search).
1121 date Time stamps (link to calendar).
1123 Changing this variable requires a restart of Emacs to become effective."
1124 :group 'org-link
1125 :type '(set (const :tag "Double bracket links (new style)" bracket)
1126 (const :tag "Angular bracket links (old style)" angular)
1127 (const :tag "plain text links" plain)
1128 (const :tag "Radio target matches" radio)
1129 (const :tag "Tags" tag)
1130 (const :tag "Tags" target)
1131 (const :tag "Timestamps" date)))
1133 (defgroup org-link-store nil
1134 "Options concerning storing links in Org-mode"
1135 :tag "Org Store Link"
1136 :group 'org-link)
1138 (defcustom org-email-link-description-format "Email %c: %.30s"
1139 "Format of the description part of a link to an email or usenet message.
1140 The following %-excapes will be replaced by corresponding information:
1142 %F full \"From\" field
1143 %f name, taken from \"From\" field, address if no name
1144 %T full \"To\" field
1145 %t first name in \"To\" field, address if no name
1146 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1147 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1148 %s subject
1149 %m message-id.
1151 You may use normal field width specification between the % and the letter.
1152 This is for example useful to limit the length of the subject.
1154 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1155 :group 'org-link-store
1156 :type 'string)
1158 (defcustom org-from-is-user-regexp
1159 (let (r1 r2)
1160 (when (and user-mail-address (not (string= user-mail-address "")))
1161 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1162 (when (and user-full-name (not (string= user-full-name "")))
1163 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1164 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1165 "Regexp mached against the \"From:\" header of an email or usenet message.
1166 It should match if the message is from the user him/herself."
1167 :group 'org-link-store
1168 :type 'regexp)
1170 (defcustom org-context-in-file-links t
1171 "Non-nil means, file links from `org-store-link' contain context.
1172 A search string will be added to the file name with :: as separator and
1173 used to find the context when the link is activated by the command
1174 `org-open-at-point'.
1175 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1176 negates this setting for the duration of the command."
1177 :group 'org-link-store
1178 :type 'boolean)
1180 (defcustom org-keep-stored-link-after-insertion nil
1181 "Non-nil means, keep link in list for entire session.
1183 The command `org-store-link' adds a link pointing to the current
1184 location to an internal list. These links accumulate during a session.
1185 The command `org-insert-link' can be used to insert links into any
1186 Org-mode file (offering completion for all stored links). When this
1187 option is nil, every link which has been inserted once using \\[org-insert-link]
1188 will be removed from the list, to make completing the unused links
1189 more efficient."
1190 :group 'org-link-store
1191 :type 'boolean)
1193 (defcustom org-usenet-links-prefer-google nil
1194 "Non-nil means, `org-store-link' will create web links to Google groups.
1195 When nil, Gnus will be used for such links.
1196 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1197 negates this setting for the duration of the command."
1198 :group 'org-link-store
1199 :type 'boolean)
1201 (defgroup org-link-follow nil
1202 "Options concerning following links in Org-mode"
1203 :tag "Org Follow Link"
1204 :group 'org-link)
1206 (defcustom org-tab-follows-link nil
1207 "Non-nil means, on links TAB will follow the link.
1208 Needs to be set before org.el is loaded."
1209 :group 'org-link-follow
1210 :type 'boolean)
1212 (defcustom org-return-follows-link nil
1213 "Non-nil means, on links RET will follow the link.
1214 Needs to be set before org.el is loaded."
1215 :group 'org-link-follow
1216 :type 'boolean)
1218 (defcustom org-mouse-1-follows-link t
1219 "Non-nil means, mouse-1 on a link will follow the link.
1220 A longer mouse click will still set point. Does not wortk on XEmacs.
1221 Needs to be set before org.el is loaded."
1222 :group 'org-link-follow
1223 :type 'boolean)
1225 (defcustom org-mark-ring-length 4
1226 "Number of different positions to be recorded in the ring
1227 Changing this requires a restart of Emacs to work correctly."
1228 :group 'org-link-follow
1229 :type 'interger)
1231 (defcustom org-link-frame-setup
1232 '((vm . vm-visit-folder-other-frame)
1233 (gnus . gnus-other-frame)
1234 (file . find-file-other-window))
1235 "Setup the frame configuration for following links.
1236 When following a link with Emacs, it may often be useful to display
1237 this link in another window or frame. This variable can be used to
1238 set this up for the different types of links.
1239 For VM, use any of
1240 `vm-visit-folder'
1241 `vm-visit-folder-other-frame'
1242 For Gnus, use any of
1243 `gnus'
1244 `gnus-other-frame'
1245 For FILE, use any of
1246 `find-file'
1247 `find-file-other-window'
1248 `find-file-other-frame'
1249 For the calendar, use the variable `calendar-setup'.
1250 For BBDB, it is currently only possible to display the matches in
1251 another window."
1252 :group 'org-link-follow
1253 :type '(list
1254 (cons (const vm)
1255 (choice
1256 (const vm-visit-folder)
1257 (const vm-visit-folder-other-window)
1258 (const vm-visit-folder-other-frame)))
1259 (cons (const gnus)
1260 (choice
1261 (const gnus)
1262 (const gnus-other-frame)))
1263 (cons (const file)
1264 (choice
1265 (const find-file)
1266 (const find-file-other-window)
1267 (const find-file-other-frame)))))
1269 (defcustom org-display-internal-link-with-indirect-buffer nil
1270 "Non-nil means, use indirect buffer to display infile links.
1271 Activating internal links (from one location in a file to another location
1272 in the same file) normally just jumps to the location. When the link is
1273 activated with a C-u prefix (or with mouse-3), the link is displayed in
1274 another window. When this option is set, the other window actually displays
1275 an indirect buffer clone of the current buffer, to avoid any visibility
1276 changes to the current buffer."
1277 :group 'org-link-follow
1278 :type 'boolean)
1280 (defcustom org-open-non-existing-files nil
1281 "Non-nil means, `org-open-file' will open non-existing files.
1282 When nil, an error will be generated."
1283 :group 'org-link-follow
1284 :type 'boolean)
1286 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1287 "Function and arguments to call for following mailto links.
1288 This is a list with the first element being a lisp function, and the
1289 remaining elements being arguments to the function. In string arguments,
1290 %a will be replaced by the address, and %s will be replaced by the subject
1291 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1292 :group 'org-link-follow
1293 :type '(choice
1294 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1295 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1296 (const :tag "message-mail" (message-mail "%a" "%s"))
1297 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1299 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1300 "Non-nil means, ask for confirmation before executing shell links.
1301 Shell links can be dangerous: just think about a link
1303 [[shell:rm -rf ~/*][Google Search]]
1305 This link would show up in your Org-mode document as \"Google Search\",
1306 but really it would remove your entire home directory.
1307 Therefore we advise against setting this variable to nil.
1308 Just change it to `y-or-n-p' of you want to confirm with a
1309 single keystroke rather than having to type \"yes\"."
1310 :group 'org-link-follow
1311 :type '(choice
1312 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1313 (const :tag "with y-or-n (faster)" y-or-n-p)
1314 (const :tag "no confirmation (dangerous)" nil)))
1316 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1317 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1318 Elisp links can be dangerous: just think about a link
1320 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1322 This link would show up in your Org-mode document as \"Google Search\",
1323 but really it would remove your entire home directory.
1324 Therefore we advise against setting this variable to nil.
1325 Just change it to `y-or-n-p' of you want to confirm with a
1326 single keystroke rather than having to type \"yes\"."
1327 :group 'org-link-follow
1328 :type '(choice
1329 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1330 (const :tag "with y-or-n (faster)" y-or-n-p)
1331 (const :tag "no confirmation (dangerous)" nil)))
1333 (defconst org-file-apps-defaults-gnu
1334 '((remote . emacs)
1335 (t . mailcap))
1336 "Default file applications on a UNIX or GNU/Linux system.
1337 See `org-file-apps'.")
1339 (defconst org-file-apps-defaults-macosx
1340 '((remote . emacs)
1341 (t . "open %s")
1342 ("ps" . "gv %s")
1343 ("ps.gz" . "gv %s")
1344 ("eps" . "gv %s")
1345 ("eps.gz" . "gv %s")
1346 ("dvi" . "xdvi %s")
1347 ("fig" . "xfig %s"))
1348 "Default file applications on a MacOS X system.
1349 The system \"open\" is known as a default, but we use X11 applications
1350 for some files for which the OS does not have a good default.
1351 See `org-file-apps'.")
1353 (defconst org-file-apps-defaults-windowsnt
1354 (list
1355 '(remote . emacs)
1356 (cons t
1357 (list (if (featurep 'xemacs)
1358 'mswindows-shell-execute
1359 'w32-shell-execute)
1360 "open" 'file)))
1361 "Default file applications on a Windows NT system.
1362 The system \"open\" is used for most files.
1363 See `org-file-apps'.")
1365 (defcustom org-file-apps
1367 ("txt" . emacs)
1368 ("tex" . emacs)
1369 ("ltx" . emacs)
1370 ("org" . emacs)
1371 ("el" . emacs)
1372 ("bib" . emacs)
1374 "External applications for opening `file:path' items in a document.
1375 Org-mode uses system defaults for different file types, but
1376 you can use this variable to set the application for a given file
1377 extension. The entries in this list are cons cells where the car identifies
1378 files and the cdr the corresponding command. Possible values for the
1379 file identifier are
1380 \"ext\" A string identifying an extension
1381 `directory' Matches a directory
1382 `remote' Matches a remote file, accessible through tramp or efs.
1383 Remote files most likely should be visited through Emacs
1384 because external applications cannot handle such paths.
1385 t Default for all remaining files
1387 Possible values for the command are:
1388 `emacs' The file will be visited by the current Emacs process.
1389 `default' Use the default application for this file type.
1390 string A command to be executed by a shell; %s will be replaced
1391 by the path to the file.
1392 sexp A Lisp form which will be evaluated. The file path will
1393 be available in the Lisp variable `file'.
1394 For more examples, see the system specific constants
1395 `org-file-apps-defaults-macosx'
1396 `org-file-apps-defaults-windowsnt'
1397 `org-file-apps-defaults-gnu'."
1398 :group 'org-link-follow
1399 :type '(repeat
1400 (cons (choice :value ""
1401 (string :tag "Extension")
1402 (const :tag "Default for unrecognized files" t)
1403 (const :tag "Remote file" remote)
1404 (const :tag "Links to a directory" directory))
1405 (choice :value ""
1406 (const :tag "Visit with Emacs" emacs)
1407 (const :tag "Use system default" default)
1408 (string :tag "Command")
1409 (sexp :tag "Lisp form")))))
1411 (defcustom org-mhe-search-all-folders nil
1412 "Non-nil means, that the search for the mh-message will be extended to
1413 all folders if the message cannot be found in the folder given in the link.
1414 Searching all folders is very efficient with one of the search engines
1415 supported by MH-E, but will be slow with pick."
1416 :group 'org-link-follow
1417 :type 'boolean)
1419 (defgroup org-remember nil
1420 "Options concerning interaction with remember.el."
1421 :tag "Org Remember"
1422 :group 'org)
1424 (defcustom org-directory "~/org"
1425 "Directory with org files.
1426 This directory will be used as default to prompt for org files.
1427 Used by the hooks for remember.el."
1428 :group 'org-remember
1429 :type 'directory)
1431 (defcustom org-default-notes-file "~/.notes"
1432 "Default target for storing notes.
1433 Used by the hooks for remember.el. This can be a string, or nil to mean
1434 the value of `remember-data-file'.
1435 You can set this on a per-template basis with the variable
1436 `org-remember-templates'."
1437 :group 'org-remember
1438 :type '(choice
1439 (const :tag "Default from remember-data-file" nil)
1440 file))
1442 (defcustom org-remember-store-without-prompt t
1443 "Non-nil means, `C-c C-c' stores remember note without further promts.
1444 In this case, you need `C-u C-c C-c' to get the prompts for
1445 note file and headline.
1446 When this variable is nil, `C-c C-c' give you the prompts, and
1447 `C-u C-c C-c' trigger the fasttrack."
1448 :group 'org-remember
1449 :type 'boolean)
1451 (defcustom org-remember-default-headline ""
1452 "The headline that should be the default location in the notes file.
1453 When filing remember notes, the cursor will start at that position.
1454 You can set this on a per-template basis with the variable
1455 `org-remember-templates'."
1456 :group 'org-remember
1457 :type 'string)
1459 (defcustom org-remember-templates nil
1460 "Templates for the creation of remember buffers.
1461 When nil, just let remember make the buffer.
1462 When not nil, this is a list of 5-element lists. In each entry, the first
1463 element is a the name of the template, It should be a single short word.
1464 The second element is a character, a unique key to select this template.
1465 The third element is the template. The forth element is optional and can
1466 specify a destination file for remember items created with this template.
1467 The default file is given by `org-default-notes-file'. An optional fifth
1468 element can specify the headline in that file that should be offered
1469 first when the user is asked to file the entry. The default headline is
1470 given in the variable `org-remember-default-headline'.
1472 The template specifies the structure of the remember buffer. It should have
1473 a first line starting with a star, to act as the org-mode headline.
1474 Furthermore, the following %-escapes will be replaced with content:
1476 %^{prompt} prompt the user for a string and replace this sequence with it.
1477 %t time stamp, date only
1478 %T time stamp with date and time
1479 %u, %U like the above, but inactive time stamps
1480 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1481 You may define a prompt like %^{Please specify birthday}t
1482 %n user name (taken from `user-full-name')
1483 %a annotation, normally the link created with org-store-link
1484 %i initial content, the region when remember is called with C-u.
1485 If %i is indented, the entire inserted text will be indented
1486 as well.
1488 %? After completing the template, position cursor here.
1490 Apart from these general escapes, you can access information specific to the
1491 link type that is created. For example, calling `remember' in emails or gnus
1492 will record the author and the subject of the message, which you can access
1493 with %:author and %:subject, respectively. Here is a complete list of what
1494 is recorded for each link type.
1496 Link type | Available information
1497 -------------------+------------------------------------------------------
1498 bbdb | %:type %:name %:company
1499 vm, wl, mh, rmail | %:type %:subject %:message-id
1500 | %:from %:fromname %:fromaddress
1501 | %:to %:toname %:toaddress
1502 | %:fromto (either \"to NAME\" or \"from NAME\")
1503 gnus | %:group, for messages also all email fields
1504 w3, w3m | %:type %:url
1505 info | %:type %:file %:node
1506 calendar | %:type %:date"
1507 :group 'org-remember
1508 :get (lambda (var) ; Make sure all entries have 5 elements
1509 (mapcar (lambda (x)
1510 (if (not (stringp (car x))) (setq x (cons "" x)))
1511 (cond ((= (length x) 4) (append x '("")))
1512 ((= (length x) 3) (append x '("" "")))
1513 (t x)))
1514 (default-value var)))
1515 :type '(repeat
1516 :tag "enabled"
1517 (list :value ("" ?a "\n" nil nil)
1518 (string :tag "Name")
1519 (character :tag "Selection Key")
1520 (string :tag "Template")
1521 (choice
1522 (file :tag "Destination file")
1523 (const :tag "Prompt for file" nil))
1524 (choice
1525 (string :tag "Destination headline")
1526 (const :tag "Selection interface for heading")))))
1528 (defcustom org-reverse-note-order nil
1529 "Non-nil means, store new notes at the beginning of a file or entry.
1530 When nil, new notes will be filed to the end of a file or entry.
1531 This can also be a list with cons cells of regular expressions that
1532 are matched against file names, and values."
1533 :group 'org-remember
1534 :type '(choice
1535 (const :tag "Reverse always" t)
1536 (const :tag "Reverse never" nil)
1537 (repeat :tag "By file name regexp"
1538 (cons regexp boolean))))
1540 (defcustom org-refile-targets '((nil . (:level . 1)))
1541 "Targets for refiling entries with \\[org-refile].
1542 This is list of cons cells. Each cell contains:
1543 - a specification of the files to be considered, either a list of files,
1544 or a symbol whose function or value fields will be used to retrieve
1545 a file name or a list of file names. Nil means, refile to a different
1546 heading in the current buffer.
1547 - A specification of how to find candidate refile targets. This may be
1548 any of
1549 - a cons cell (:tag . \"TAG\") to identify refile targes by a tag.
1550 This tag has to be present in all target headlines, inheritance will
1551 not be considered.
1552 - a cons cell (:todo . \"KEYWORD\" to identify refile targets by
1553 todo keyword.
1554 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1555 headlines that are refiling targets.
1556 - a cons cell (:level . N). Any headline of level N is considered a target."
1557 ;; FIXME: what if there are a var and func with same name???
1558 :group 'org
1559 :type '(repeat
1560 (cons
1561 (choice :value org-agenda-files
1562 (const :tag "All agenda files" org-agenda-files)
1563 (const :tag "Current buffer" nil)
1564 (function) (variable) (file))
1565 (choice :tag "Identify target headline by"
1566 (cons :tag "Specific tag" (const :tag) (string))
1567 (cons :tag "TODO keyword" (const :todo) (string))
1568 (cons :tag "Regular expression" (const :regexp) (regexp))
1569 (cons :tag "Level number" (const :level) (integer))))))
1571 (defgroup org-todo nil
1572 "Options concerning TODO items in Org-mode."
1573 :tag "Org TODO"
1574 :group 'org)
1576 (defgroup org-progress nil
1577 "Options concerning Progress logging in Org-mode."
1578 :tag "Org Progress"
1579 :group 'org-time)
1581 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1582 "List of TODO entry keyword sequences and their interpretation.
1583 \\<org-mode-map>This is a list of sequences.
1585 Each sequence starts with a symbol, either `sequence' or `type',
1586 indicating if the keywords should be interpreted as a sequence of
1587 action steps, or as different types of TODO items. The first
1588 keywords are states requiring action - these states will select a headline
1589 for inclusion into the global TODO list Org-mode produces. If one of
1590 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1591 signify that no further action is necessary. If \"|\" is not found,
1592 the last keyword is treated as the only DONE state of the sequence.
1594 The command \\[org-todo] cycles an entry through these states, and one
1595 additional state where no keyword is present. For details about this
1596 cycling, see the manual.
1598 TODO keywords and interpretation can also be set on a per-file basis with
1599 the special #+SEQ_TODO and #+TYP_TODO lines.
1601 For backward compatibility, this variable may also be just a list
1602 of keywords - in this case the interptetation (sequence or type) will be
1603 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1604 :group 'org-todo
1605 :group 'org-keywords
1606 :type '(choice
1607 (repeat :tag "Old syntax, just keywords"
1608 (string :tag "Keyword"))
1609 (repeat :tag "New syntax"
1610 (cons
1611 (choice
1612 :tag "Interpretation"
1613 (const :tag "Sequence (cycling hits every state)" sequence)
1614 (const :tag "Type (cycling directly to DONE)" type))
1615 (repeat
1616 (string :tag "Keyword"))))))
1618 (defvar org-todo-keywords-1 nil)
1619 (make-variable-buffer-local 'org-todo-keywords-1)
1620 (defvar org-todo-keywords-for-agenda nil)
1621 (defvar org-done-keywords-for-agenda nil)
1622 (defvar org-not-done-keywords nil)
1623 (make-variable-buffer-local 'org-not-done-keywords)
1624 (defvar org-done-keywords nil)
1625 (make-variable-buffer-local 'org-done-keywords)
1626 (defvar org-todo-heads nil)
1627 (make-variable-buffer-local 'org-todo-heads)
1628 (defvar org-todo-sets nil)
1629 (make-variable-buffer-local 'org-todo-sets)
1630 (defvar org-todo-log-states nil)
1631 (make-variable-buffer-local 'org-todo-log-states)
1632 (defvar org-todo-kwd-alist nil)
1633 (make-variable-buffer-local 'org-todo-kwd-alist)
1634 (defvar org-todo-key-alist nil)
1635 (make-variable-buffer-local 'org-todo-key-alist)
1636 (defvar org-todo-key-trigger nil)
1637 (make-variable-buffer-local 'org-todo-key-trigger)
1639 (defcustom org-todo-interpretation 'sequence
1640 "Controls how TODO keywords are interpreted.
1641 This variable is in principle obsolete and is only used for
1642 backward compatibility, if the interpretation of todo keywords is
1643 not given already in `org-todo-keywords'. See that variable for
1644 more information."
1645 :group 'org-todo
1646 :group 'org-keywords
1647 :type '(choice (const sequence)
1648 (const type)))
1650 (defcustom org-use-fast-todo-selection 'prefix
1651 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1652 This variable describes if and under what circumstances the cycling
1653 mechanism for TODO keywords will be replaced by a single-key, direct
1654 selection scheme.
1656 When nil, fast selection is never used.
1658 When the symbol `prefix', it will be used when `org-todo' is called with
1659 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1660 in an agenda buffer.
1662 When t, fast selection is used by default. In this case, the prefix
1663 argument forces cycling instead.
1665 In all cases, the special interface is only used if access keys have actually
1666 been assigned by the user, i.e. if keywords in the configuration are followed
1667 by a letter in parenthesis, like TODO(t)."
1668 :group 'org-todo
1669 :type '(choice
1670 (const :tag "Never" nil)
1671 (const :tag "By default" t)
1672 (const :tag "Only with C-u C-c C-t" prefix)))
1674 (defcustom org-after-todo-state-change-hook nil
1675 "Hook which is run after the state of a TODO item was changed.
1676 The new state (a string with a TODO keyword, or nil) is available in the
1677 Lisp variable `state'."
1678 :group 'org-todo
1679 :type 'hook)
1681 (defcustom org-log-done nil
1682 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1683 When the state of an entry is changed from nothing or a DONE state to
1684 a not-done TODO state, remove a previous closing date.
1686 This can also be a list of symbols indicating under which conditions
1687 the time stamp recording the action should be annotated with a short note.
1688 Valid members of this list are
1690 done Offer to record a note when marking entries done
1691 state Offer to record a note whenever changing the TODO state
1692 of an item. This is only relevant if TODO keywords are
1693 interpreted as sequence, see variable `org-todo-interpretation'.
1694 When `state' is set, this includes tracking `done'.
1695 clock-out Offer to record a note when clocking out of an item.
1697 A separate window will then pop up and allow you to type a note.
1698 After finishing with C-c C-c, the note will be added directly after the
1699 timestamp, as a plain list item. See also the variable
1700 `org-log-note-headings'.
1702 Logging can also be configured on a per-file basis by adding one of
1703 the following lines anywhere in the buffer:
1705 #+STARTUP: logdone
1706 #+STARTUP: nologging
1707 #+STARTUP: lognotedone
1708 #+STARTUP: lognotestate
1709 #+STARTUP: lognoteclock-out
1711 You can have local logging settings for a subtree by setting the LOGGING
1712 property to one or more of these keywords."
1713 :group 'org-todo
1714 :group 'org-progress
1715 :type '(choice
1716 (const :tag "off" nil)
1717 (const :tag "on" t)
1718 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1719 (const :tag "when item is marked DONE" done)
1720 (const :tag "when TODO state changes" state)
1721 (const :tag "when clocking out" clock-out))))
1723 (defcustom org-log-done-with-time t
1724 "Non-nil means, the CLOSED time stamp will contain date and time.
1725 When nil, only the date will be recorded."
1726 :group 'org-progress
1727 :type 'boolean)
1729 (defcustom org-log-note-headings
1730 '((done . "CLOSING NOTE %t")
1731 (state . "State %-12s %t")
1732 (clock-out . ""))
1733 "Headings for notes added when clocking out or closing TODO items.
1734 The value is an alist, with the car being a symbol indicating the note
1735 context, and the cdr is the heading to be used. The heading may also be the
1736 empty string.
1737 %t in the heading will be replaced by a time stamp.
1738 %s will be replaced by the new TODO state, in double quotes.
1739 %u will be replaced by the user name.
1740 %U will be replaced by the full user name."
1741 :group 'org-todo
1742 :group 'org-progress
1743 :type '(list :greedy t
1744 (cons (const :tag "Heading when closing an item" done) string)
1745 (cons (const :tag
1746 "Heading when changing todo state (todo sequence only)"
1747 state) string)
1748 (cons (const :tag "Heading when clocking out" clock-out) string)))
1750 (defcustom org-log-states-order-reversed t
1751 "Non-nil means, the latest state change note will be directly after heading.
1752 When nil, the notes will be orderer according to time."
1753 :group 'org-todo
1754 :group 'org-progress
1755 :type 'boolean)
1757 (defcustom org-log-repeat t
1758 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1759 When nil, no note will be taken.
1760 This option can also be set with on a per-file-basis with
1762 #+STARTUP: logrepeat
1763 #+STARTUP: nologrepeat
1765 You can have local logging settings for a subtree by setting the LOGGING
1766 property to one or more of these keywords."
1767 :group 'org-todo
1768 :group 'org-progress
1769 :type 'boolean)
1771 (defcustom org-clock-into-drawer 2
1772 "Should clocking info be wrapped into a drawer?
1773 When t, clocking info will always be inserted into a :CLOCK: drawer.
1774 If necessary, the drawer will be created.
1775 When nil, the drawer will not be created, but used when present.
1776 When an integer and the number of clocking entries in an item
1777 reaches or exceeds this number, a drawer will be created."
1778 :group 'org-todo
1779 :group 'org-progress
1780 :type '(choice
1781 (const :tag "Always" t)
1782 (const :tag "Only when drawer exists" nil)
1783 (integer :tag "When at least N clock entries")))
1785 (defcustom org-clock-out-when-done t
1786 "When t, the clock will be stopped when the relevant entry is marked DONE.
1787 Nil means, clock will keep running until stopped explicitly with
1788 `C-c C-x C-o', or until the clock is started in a different item."
1789 :group 'org-progress
1790 :type 'boolean)
1792 (defgroup org-priorities nil
1793 "Priorities in Org-mode."
1794 :tag "Org Priorities"
1795 :group 'org-todo)
1797 (defcustom org-highest-priority ?A
1798 "The highest priority of TODO items. A character like ?A, ?B etc.
1799 Must have a smaller ASCII number than `org-lowest-priority'."
1800 :group 'org-priorities
1801 :type 'character)
1803 (defcustom org-lowest-priority ?C
1804 "The lowest priority of TODO items. A character like ?A, ?B etc.
1805 Must have a larger ASCII number than `org-highest-priority'."
1806 :group 'org-priorities
1807 :type 'character)
1809 (defcustom org-default-priority ?B
1810 "The default priority of TODO items.
1811 This is the priority an item get if no explicit priority is given."
1812 :group 'org-priorities
1813 :type 'character)
1815 (defcustom org-priority-start-cycle-with-default t
1816 "Non-nil means, start with default priority when starting to cycle.
1817 When this is nil, the first step in the cycle will be (depending on the
1818 command used) one higher or lower that the default priority."
1819 :group 'org-priorities
1820 :type 'boolean)
1822 (defgroup org-time nil
1823 "Options concerning time stamps and deadlines in Org-mode."
1824 :tag "Org Time"
1825 :group 'org)
1827 (defcustom org-insert-labeled-timestamps-at-point nil
1828 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1829 When nil, these labeled time stamps are forces into the second line of an
1830 entry, just after the headline. When scheduling from the global TODO list,
1831 the time stamp will always be forced into the second line."
1832 :group 'org-time
1833 :type 'boolean)
1835 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1836 "Formats for `format-time-string' which are used for time stamps.
1837 It is not recommended to change this constant.")
1839 (defcustom org-time-stamp-rounding-minutes 0
1840 "Number of minutes to round time stamps to upon insertion.
1841 When zero, insert the time unmodified. Useful rounding numbers
1842 should be factors of 60, so for example 5, 10, 15.
1843 When this is not zero, you can still force an exact time-stamp by using
1844 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1845 :group 'org-time
1846 :type 'integer)
1848 (defcustom org-display-custom-times nil
1849 "Non-nil means, overlay custom formats over all time stamps.
1850 The formats are defined through the variable `org-time-stamp-custom-formats'.
1851 To turn this on on a per-file basis, insert anywhere in the file:
1852 #+STARTUP: customtime"
1853 :group 'org-time
1854 :set 'set-default
1855 :type 'sexp)
1856 (make-variable-buffer-local 'org-display-custom-times)
1858 (defcustom org-time-stamp-custom-formats
1859 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1860 "Custom formats for time stamps. See `format-time-string' for the syntax.
1861 These are overlayed over the default ISO format if the variable
1862 `org-display-custom-times' is set. Time like %H:%M should be at the
1863 end of the second format."
1864 :group 'org-time
1865 :type 'sexp)
1867 (defun org-time-stamp-format (&optional long inactive)
1868 "Get the right format for a time string."
1869 (let ((f (if long (cdr org-time-stamp-formats)
1870 (car org-time-stamp-formats))))
1871 (if inactive
1872 (concat "[" (substring f 1 -1) "]")
1873 f)))
1875 (defcustom org-read-date-prefer-future t
1876 "Non-nil means, assume future for incomplete date input from user.
1877 This affects the following situations:
1878 1. The user gives a day, but no month.
1879 For example, if today is the 15th, and you enter \"3\", Org-mode will
1880 read this as the third of *next* month. However, if you enter \"17\",
1881 it will be considered as *this* month.
1882 2. The user gives a month but not a year.
1883 For example, if it is april and you enter \"feb 2\", this will be read
1884 as feb 2, *next* year. \"May 5\", however, will be this year.
1886 When this option is nil, the current month and year will always be used
1887 as defaults."
1888 :group 'org-time
1889 :type 'boolean)
1891 (defcustom org-read-date-display-live t
1892 "Non-nil means, display current interpretation of date prompt live.
1893 This display will be in an overlay, in the minibuffer."
1894 :group 'org-time
1895 :type 'boolean)
1897 (defcustom org-read-date-popup-calendar t
1898 "Non-nil means, pop up a calendar when prompting for a date.
1899 In the calendar, the date can be selected with mouse-1. However, the
1900 minibuffer will also be active, and you can simply enter the date as well.
1901 When nil, only the minibuffer will be available."
1902 :group 'org-time
1903 :type 'boolean)
1904 (if (fboundp 'defvaralias)
1905 (defvaralias 'org-popup-calendar-for-date-prompt
1906 'org-read-date-popup-calendar))
1908 (defcustom org-extend-today-until 0
1909 "The hour when your day really ends.
1910 This has influence for the following applications:
1911 - When switching the agenda to \"today\". It it is still earlier than
1912 the time given here, the day recognized as TODAY is actually yesterday.
1913 - When a date is read from the user and it is still before the time given
1914 here, the current date and time will be assumed to be yesterday, 23:59.
1916 FIXME:
1917 IMPORTANT: This is still a very experimental feature, it may disappear
1918 again or it may be extended to mean more things."
1919 :group 'org-time
1920 :type 'number)
1922 (defcustom org-edit-timestamp-down-means-later nil
1923 "Non-nil means, S-down will increase the time in a time stamp.
1924 When nil, S-up will increase."
1925 :group 'org-time
1926 :type 'boolean)
1928 (defcustom org-calendar-follow-timestamp-change t
1929 "Non-nil means, make the calendar window follow timestamp changes.
1930 When a timestamp is modified and the calendar window is visible, it will be
1931 moved to the new date."
1932 :group 'org-time
1933 :type 'boolean)
1935 (defcustom org-clock-heading-function nil
1936 "When non-nil, should be a function to create `org-clock-heading'.
1937 This is the string shown in the mode line when a clock is running.
1938 The function is called with point at the beginning of the headline."
1939 :group 'org-time ; FIXME: Should we have a separate group????
1940 :type 'function)
1942 (defgroup org-tags nil
1943 "Options concerning tags in Org-mode."
1944 :tag "Org Tags"
1945 :group 'org)
1947 (defcustom org-tag-alist nil
1948 "List of tags allowed in Org-mode files.
1949 When this list is nil, Org-mode will base TAG input on what is already in the
1950 buffer.
1951 The value of this variable is an alist, the car of each entry must be a
1952 keyword as a string, the cdr may be a character that is used to select
1953 that tag through the fast-tag-selection interface.
1954 See the manual for details."
1955 :group 'org-tags
1956 :type '(repeat
1957 (choice
1958 (cons (string :tag "Tag name")
1959 (character :tag "Access char"))
1960 (const :tag "Start radio group" (:startgroup))
1961 (const :tag "End radio group" (:endgroup)))))
1963 (defcustom org-use-fast-tag-selection 'auto
1964 "Non-nil means, use fast tag selection scheme.
1965 This is a special interface to select and deselect tags with single keys.
1966 When nil, fast selection is never used.
1967 When the symbol `auto', fast selection is used if and only if selection
1968 characters for tags have been configured, either through the variable
1969 `org-tag-alist' or through a #+TAGS line in the buffer.
1970 When t, fast selection is always used and selection keys are assigned
1971 automatically if necessary."
1972 :group 'org-tags
1973 :type '(choice
1974 (const :tag "Always" t)
1975 (const :tag "Never" nil)
1976 (const :tag "When selection characters are configured" 'auto)))
1978 (defcustom org-fast-tag-selection-single-key nil
1979 "Non-nil means, fast tag selection exits after first change.
1980 When nil, you have to press RET to exit it.
1981 During fast tag selection, you can toggle this flag with `C-c'.
1982 This variable can also have the value `expert'. In this case, the window
1983 displaying the tags menu is not even shown, until you press C-c again."
1984 :group 'org-tags
1985 :type '(choice
1986 (const :tag "No" nil)
1987 (const :tag "Yes" t)
1988 (const :tag "Expert" expert)))
1990 (defvar org-fast-tag-selection-include-todo nil
1991 "Non-nil means, fast tags selection interface will also offer TODO states.
1992 This is an undocumented feature, you should not rely on it.")
1994 (defcustom org-tags-column -80
1995 "The column to which tags should be indented in a headline.
1996 If this number is positive, it specifies the column. If it is negative,
1997 it means that the tags should be flushright to that column. For example,
1998 -80 works well for a normal 80 character screen."
1999 :group 'org-tags
2000 :type 'integer)
2002 (defcustom org-auto-align-tags t
2003 "Non-nil means, realign tags after pro/demotion of TODO state change.
2004 These operations change the length of a headline and therefore shift
2005 the tags around. With this options turned on, after each such operation
2006 the tags are again aligned to `org-tags-column'."
2007 :group 'org-tags
2008 :type 'boolean)
2010 (defcustom org-use-tag-inheritance t
2011 "Non-nil means, tags in levels apply also for sublevels.
2012 When nil, only the tags directly given in a specific line apply there.
2013 If you turn off this option, you very likely want to turn on the
2014 companion option `org-tags-match-list-sublevels'."
2015 :group 'org-tags
2016 :type 'boolean)
2018 (defcustom org-tags-match-list-sublevels nil
2019 "Non-nil means list also sublevels of headlines matching tag search.
2020 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2021 the sublevels of a headline matching a tag search often also match
2022 the same search. Listing all of them can create very long lists.
2023 Setting this variable to nil causes subtrees of a match to be skipped.
2024 This option is off by default, because inheritance in on. If you turn
2025 inheritance off, you very likely want to turn this option on.
2027 As a special case, if the tag search is restricted to TODO items, the
2028 value of this variable is ignored and sublevels are always checked, to
2029 make sure all corresponding TODO items find their way into the list."
2030 :group 'org-tags
2031 :type 'boolean)
2033 (defvar org-tags-history nil
2034 "History of minibuffer reads for tags.")
2035 (defvar org-last-tags-completion-table nil
2036 "The last used completion table for tags.")
2037 (defvar org-after-tags-change-hook nil
2038 "Hook that is run after the tags in a line have changed.")
2040 (defgroup org-properties nil
2041 "Options concerning properties in Org-mode."
2042 :tag "Org Properties"
2043 :group 'org)
2045 (defcustom org-property-format "%-10s %s"
2046 "How property key/value pairs should be formatted by `indent-line'.
2047 When `indent-line' hits a property definition, it will format the line
2048 according to this format, mainly to make sure that the values are
2049 lined-up with respect to each other."
2050 :group 'org-properties
2051 :type 'string)
2053 (defcustom org-use-property-inheritance nil
2054 "Non-nil means, properties apply also for sublevels.
2055 This setting is only relevant during property searches, not when querying
2056 an entry with `org-entry-get'. To retrieve a property with inheritance,
2057 you need to call `org-entry-get' with the inheritance flag.
2058 Turning this on can cause significant overhead when doing a search, so
2059 this is turned off by default.
2060 When nil, only the properties directly given in the current entry count.
2061 The value may also be a list of properties that shouldhave inheritance.
2063 However, note that some special properties use inheritance under special
2064 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2065 and the properties ending in \"_ALL\" when they are used as descriptor
2066 for valid values of a property."
2067 :group 'org-properties
2068 :type '(choice
2069 (const :tag "Not" nil)
2070 (const :tag "Always" nil)
2071 (repeat :tag "Specific properties")))
2073 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2074 "The default column format, if no other format has been defined.
2075 This variable can be set on the per-file basis by inserting a line
2077 #+COLUMNS: %25ITEM ....."
2078 :group 'org-properties
2079 :type 'string)
2081 (defcustom org-global-properties nil
2082 "List of property/value pairs that can be inherited by any entry.
2083 You can set buffer-local values for this by adding lines like
2085 #+PROPERTY: NAME VALUE"
2086 :group 'org-properties
2087 :type '(repeat
2088 (cons (string :tag "Property")
2089 (string :tag "Value"))))
2091 (defvar org-local-properties nil
2092 "List of property/value pairs that can be inherited by any entry.
2093 Valid for the current buffer.
2094 This variable is populated from #+PROPERTY lines.")
2096 (defgroup org-agenda nil
2097 "Options concerning agenda views in Org-mode."
2098 :tag "Org Agenda"
2099 :group 'org)
2101 (defvar org-category nil
2102 "Variable used by org files to set a category for agenda display.
2103 Such files should use a file variable to set it, for example
2105 # -*- mode: org; org-category: \"ELisp\"
2107 or contain a special line
2109 #+CATEGORY: ELisp
2111 If the file does not specify a category, then file's base name
2112 is used instead.")
2113 (make-variable-buffer-local 'org-category)
2115 (defcustom org-agenda-files nil
2116 "The files to be used for agenda display.
2117 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2118 \\[org-remove-file]. You can also use customize to edit the list.
2120 If an entry is a directory, all files in that directory that are matched by
2121 `org-agenda-file-regexp' will be part of the file list.
2123 If the value of the variable is not a list but a single file name, then
2124 the list of agenda files is actually stored and maintained in that file, one
2125 agenda file per line."
2126 :group 'org-agenda
2127 :type '(choice
2128 (repeat :tag "List of files and directories" file)
2129 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2131 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2132 "Regular expression to match files for `org-agenda-files'.
2133 If any element in the list in that variable contains a directory instead
2134 of a normal file, all files in that directory that are matched by this
2135 regular expression will be included."
2136 :group 'org-agenda
2137 :type 'regexp)
2139 (defcustom org-agenda-skip-unavailable-files nil
2140 "t means to just skip non-reachable files in `org-agenda-files'.
2141 Nil means to remove them, after a query, from the list."
2142 :group 'org-agenda
2143 :type 'boolean)
2145 (defcustom org-agenda-multi-occur-extra-files nil
2146 "List of extra files to be searched by `org-occur-in-agenda-files'.
2147 The files in `org-agenda-files' are always searched."
2148 :group 'org-agenda
2149 :type '(repeat file))
2151 (defcustom org-agenda-confirm-kill 1
2152 "When set, remote killing from the agenda buffer needs confirmation.
2153 When t, a confirmation is always needed. When a number N, confirmation is
2154 only needed when the text to be killed contains more than N non-white lines."
2155 :group 'org-agenda
2156 :type '(choice
2157 (const :tag "Never" nil)
2158 (const :tag "Always" t)
2159 (number :tag "When more than N lines")))
2161 (defcustom org-calendar-to-agenda-key [?c]
2162 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2163 The command `org-calendar-goto-agenda' will be bound to this key. The
2164 default is the character `c' because then `c' can be used to switch back and
2165 forth between agenda and calendar."
2166 :group 'org-agenda
2167 :type 'sexp)
2169 (defcustom org-agenda-compact-blocks nil
2170 "Non-nil means, make the block agenda more compact.
2171 This is done by leaving out unnecessary lines."
2172 :group 'org-agenda
2173 :type nil)
2175 (defgroup org-agenda-export nil
2176 "Options concerning exporting agenda views in Org-mode."
2177 :tag "Org Agenda Export"
2178 :group 'org-agenda)
2180 (defcustom org-agenda-with-colors t
2181 "Non-nil means, use colors in agenda views."
2182 :group 'org-agenda-export
2183 :type 'boolean)
2185 (defcustom org-agenda-exporter-settings nil
2186 "Alist of variable/value pairs that should be active during agenda export.
2187 This is a good place to set uptions for ps-print and for htmlize."
2188 :group 'org-agenda-export
2189 :type '(repeat
2190 (list
2191 (variable)
2192 (sexp :tag "Value"))))
2194 (defcustom org-agenda-export-html-style ""
2195 "The style specification for exported HTML Agenda files.
2196 If this variable contains a string, it will replace the default <style>
2197 section as produced by `htmlize'.
2198 Since there are different ways of setting style information, this variable
2199 needs to contain the full HTML structure to provide a style, including the
2200 surrounding HTML tags. The style specifications should include definitions
2201 the fonts used by the agenda, here is an example:
2203 <style type=\"text/css\">
2204 p { font-weight: normal; color: gray; }
2205 .org-agenda-structure {
2206 font-size: 110%;
2207 color: #003399;
2208 font-weight: 600;
2210 .org-todo {
2211 color: #cc6666;Week-agenda:
2212 font-weight: bold;
2214 .org-done {
2215 color: #339933;
2217 .title { text-align: center; }
2218 .todo, .deadline { color: red; }
2219 .done { color: green; }
2220 </style>
2222 or, if you want to keep the style in a file,
2224 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2226 As the value of this option simply gets inserted into the HTML <head> header,
2227 you can \"misuse\" it to also add other text to the header. However,
2228 <style>...</style> is required, if not present the variable will be ignored."
2229 :group 'org-agenda-export
2230 :group 'org-export-html
2231 :type 'string)
2233 (defgroup org-agenda-custom-commands nil
2234 "Options concerning agenda views in Org-mode."
2235 :tag "Org Agenda Custom Commands"
2236 :group 'org-agenda)
2238 (defcustom org-agenda-custom-commands nil
2239 "Custom commands for the agenda.
2240 These commands will be offered on the splash screen displayed by the
2241 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2243 (key desc type match options files)
2245 key The key (one or more characters as a string) to be associated
2246 with the command.
2247 desc A description of the commend, when omitted or nil, a default
2248 description is built using MATCH.
2249 type The command type, any of the following symbols:
2250 todo Entries with a specific TODO keyword, in all agenda files.
2251 tags Tags match in all agenda files.
2252 tags-todo Tags match in all agenda files, TODO entries only.
2253 todo-tree Sparse tree of specific TODO keyword in *current* file.
2254 tags-tree Sparse tree with all tags matches in *current* file.
2255 occur-tree Occur sparse tree for *current* file.
2256 ... A user-defined function.
2257 match What to search for:
2258 - a single keyword for TODO keyword searches
2259 - a tags match expression for tags searches
2260 - a regular expression for occur searches
2261 options A list of option settings, similar to that in a let form, so like
2262 this: ((opt1 val1) (opt2 val2) ...)
2263 files A list of files file to write the produced agenda buffer to
2264 with the command `org-store-agenda-views'.
2265 If a file name ends in \".html\", an HTML version of the buffer
2266 is written out. If it ends in \".ps\", a postscript version is
2267 produced. Otherwide, only the plain text is written to the file.
2269 You can also define a set of commands, to create a composite agenda buffer.
2270 In this case, an entry looks like this:
2272 (key desc (cmd1 cmd2 ...) general-options file)
2274 where
2276 desc A description string to be displayed in the dispatcher menu.
2277 cmd An agenda command, similar to the above. However, tree commands
2278 are no allowed, but instead you can get agenda and global todo list.
2279 So valid commands for a set are:
2280 (agenda)
2281 (alltodo)
2282 (stuck)
2283 (todo \"match\" options files)
2284 (tags \"match\" options files)
2285 (tags-todo \"match\" options files)
2287 Each command can carry a list of options, and another set of options can be
2288 given for the whole set of commands. Individual command options take
2289 precedence over the general options.
2291 When using several characters as key to a command, the first characters
2292 are prefix commands. For the dispatcher to display useful information, you
2293 should provide a description for the prefix, like
2295 (setq org-agenda-custom-commands
2296 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2297 (\"hl\" tags \"+HOME+Lisa\")
2298 (\"hp\" tags \"+HOME+Peter\")
2299 (\"hk\" tags \"+HOME+Kim\")))"
2300 :group 'org-agenda-custom-commands
2301 :type '(repeat
2302 (choice :value ("a" "" tags "" nil)
2303 (list :tag "Single command"
2304 (string :tag "Access Key(s) ")
2305 (option (string :tag "Description"))
2306 (choice
2307 (const :tag "Agenda" agenda)
2308 (const :tag "TODO list" alltodo)
2309 (const :tag "Stuck projects" stuck)
2310 (const :tag "Tags search (all agenda files)" tags)
2311 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2312 (const :tag "TODO keyword search (all agenda files)" todo)
2313 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2314 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2315 (const :tag "Occur tree (current buffer)" occur-tree)
2316 (sexp :tag "Other, user-defined function"))
2317 (string :tag "Match")
2318 (repeat :tag "Local options"
2319 (list (variable :tag "Option") (sexp :tag "Value")))
2320 (option (repeat :tag "Export" (file :tag "Export to"))))
2321 (list :tag "Command series, all agenda files"
2322 (string :tag "Access Key(s)")
2323 (string :tag "Description ")
2324 (repeat
2325 (choice
2326 (const :tag "Agenda" (agenda))
2327 (const :tag "TODO list" (alltodo))
2328 (const :tag "Stuck projects" (stuck))
2329 (list :tag "Tags search"
2330 (const :format "" tags)
2331 (string :tag "Match")
2332 (repeat :tag "Local options"
2333 (list (variable :tag "Option")
2334 (sexp :tag "Value"))))
2336 (list :tag "Tags search, TODO entries only"
2337 (const :format "" tags-todo)
2338 (string :tag "Match")
2339 (repeat :tag "Local options"
2340 (list (variable :tag "Option")
2341 (sexp :tag "Value"))))
2343 (list :tag "TODO keyword search"
2344 (const :format "" todo)
2345 (string :tag "Match")
2346 (repeat :tag "Local options"
2347 (list (variable :tag "Option")
2348 (sexp :tag "Value"))))
2350 (list :tag "Other, user-defined function"
2351 (symbol :tag "function")
2352 (string :tag "Match")
2353 (repeat :tag "Local options"
2354 (list (variable :tag "Option")
2355 (sexp :tag "Value"))))))
2357 (repeat :tag "General options"
2358 (list (variable :tag "Option")
2359 (sexp :tag "Value")))
2360 (option (repeat :tag "Export" (file :tag "Export to"))))
2361 (cons :tag "Prefix key documentation"
2362 (string :tag "Access Key(s)")
2363 (string :tag "Description ")))))
2365 (defcustom org-stuck-projects
2366 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2367 "How to identify stuck projects.
2368 This is a list of four items:
2369 1. A tags/todo matcher string that is used to identify a project.
2370 The entire tree below a headline matched by this is considered one project.
2371 2. A list of TODO keywords identifying non-stuck projects.
2372 If the project subtree contains any headline with one of these todo
2373 keywords, the project is considered to be not stuck. If you specify
2374 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2375 3. A list of tags identifying non-stuck projects.
2376 If the project subtree contains any headline with one of these tags,
2377 the project is considered to be not stuck. If you specify \"*\" as
2378 a tag, any tag will mark the project unstuck.
2379 4. An arbitrary regular expression matching non-stuck projects.
2381 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2382 or `C-c a #' to produce the list."
2383 :group 'org-agenda-custom-commands
2384 :type '(list
2385 (string :tag "Tags/TODO match to identify a project")
2386 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2387 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2388 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2391 (defgroup org-agenda-skip nil
2392 "Options concerning skipping parts of agenda files."
2393 :tag "Org Agenda Skip"
2394 :group 'org-agenda)
2396 (defcustom org-agenda-todo-list-sublevels t
2397 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2398 When nil, the sublevels of a TODO entry are not checked, resulting in
2399 potentially much shorter TODO lists."
2400 :group 'org-agenda-skip
2401 :group 'org-todo
2402 :type 'boolean)
2404 (defcustom org-agenda-todo-ignore-with-date nil
2405 "Non-nil means, don't show entries with a date in the global todo list.
2406 You can use this if you prefer to mark mere appointments with a TODO keyword,
2407 but don't want them to show up in the TODO list.
2408 When this is set, it also covers deadlines and scheduled items, the settings
2409 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2410 will be ignored."
2411 :group 'org-agenda-skip
2412 :group 'org-todo
2413 :type 'boolean)
2415 (defcustom org-agenda-todo-ignore-scheduled nil
2416 "Non-nil means, don't show scheduled entries in the global todo list.
2417 The idea behind this is that by scheduling it, you have already taken care
2418 of this item.
2419 See also `org-agenda-todo-ignore-with-date'."
2420 :group 'org-agenda-skip
2421 :group 'org-todo
2422 :type 'boolean)
2424 (defcustom org-agenda-todo-ignore-deadlines nil
2425 "Non-nil means, don't show near deadline entries in the global todo list.
2426 Near means closer than `org-deadline-warning-days' days.
2427 The idea behind this is that such items will appear in the agenda anyway.
2428 See also `org-agenda-todo-ignore-with-date'."
2429 :group 'org-agenda-skip
2430 :group 'org-todo
2431 :type 'boolean)
2433 (defcustom org-agenda-skip-scheduled-if-done nil
2434 "Non-nil means don't show scheduled items in agenda when they are done.
2435 This is relevant for the daily/weekly agenda, not for the TODO list. And
2436 it applies only to the actual date of the scheduling. Warnings about
2437 an item with a past scheduling dates are always turned off when the item
2438 is DONE."
2439 :group 'org-agenda-skip
2440 :type 'boolean)
2442 (defcustom org-agenda-skip-deadline-if-done nil
2443 "Non-nil means don't show deadines when the corresponding item is done.
2444 When nil, the deadline is still shown and should give you a happy feeling.
2445 This is relevant for the daily/weekly agenda. And it applied only to the
2446 actualy date of the deadline. Warnings about approching and past-due
2447 deadlines are always turned off when the item is DONE."
2448 :group 'org-agenda-skip
2449 :type 'boolean)
2451 (defcustom org-agenda-skip-timestamp-if-done nil
2452 "Non-nil means don't don't select item by timestamp or -range if it is DONE."
2453 :group 'org-agenda-skip
2454 :type 'boolean)
2456 (defcustom org-timeline-show-empty-dates 3
2457 "Non-nil means, `org-timeline' also shows dates without an entry.
2458 When nil, only the days which actually have entries are shown.
2459 When t, all days between the first and the last date are shown.
2460 When an integer, show also empty dates, but if there is a gap of more than
2461 N days, just insert a special line indicating the size of the gap."
2462 :group 'org-agenda-skip
2463 :type '(choice
2464 (const :tag "None" nil)
2465 (const :tag "All" t)
2466 (number :tag "at most")))
2469 (defgroup org-agenda-startup nil
2470 "Options concerning initial settings in the Agenda in Org Mode."
2471 :tag "Org Agenda Startup"
2472 :group 'org-agenda)
2474 (defcustom org-finalize-agenda-hook nil
2475 "Hook run just before displaying an agenda buffer."
2476 :group 'org-agenda-startup
2477 :type 'hook)
2479 (defcustom org-agenda-mouse-1-follows-link nil
2480 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2481 A longer mouse click will still set point. Does not wortk on XEmacs.
2482 Needs to be set before org.el is loaded."
2483 :group 'org-agenda-startup
2484 :type 'boolean)
2486 (defcustom org-agenda-start-with-follow-mode nil
2487 "The initial value of follow-mode in a newly created agenda window."
2488 :group 'org-agenda-startup
2489 :type 'boolean)
2491 (defgroup org-agenda-windows nil
2492 "Options concerning the windows used by the Agenda in Org Mode."
2493 :tag "Org Agenda Windows"
2494 :group 'org-agenda)
2496 (defcustom org-agenda-window-setup 'reorganize-frame
2497 "How the agenda buffer should be displayed.
2498 Possible values for this option are:
2500 current-window Show agenda in the current window, keeping all other windows.
2501 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2502 other-window Use `switch-to-buffer-other-window' to display agenda.
2503 reorganize-frame Show only two windows on the current frame, the current
2504 window and the agenda.
2505 See also the variable `org-agenda-restore-windows-after-quit'."
2506 :group 'org-agenda-windows
2507 :type '(choice
2508 (const current-window)
2509 (const other-frame)
2510 (const other-window)
2511 (const reorganize-frame)))
2513 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2514 "The min and max height of the agenda window as a fraction of frame height.
2515 The value of the variable is a cons cell with two numbers between 0 and 1.
2516 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2517 :group 'org-agenda-windows
2518 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2520 (defcustom org-agenda-restore-windows-after-quit nil
2521 "Non-nil means, restore window configuration open exiting agenda.
2522 Before the window configuration is changed for displaying the agenda,
2523 the current status is recorded. When the agenda is exited with
2524 `q' or `x' and this option is set, the old state is restored. If
2525 `org-agenda-window-setup' is `other-frame', the value of this
2526 option will be ignored.."
2527 :group 'org-agenda-windows
2528 :type 'boolean)
2530 (defcustom org-indirect-buffer-display 'other-window
2531 "How should indirect tree buffers be displayed?
2532 This applies to indirect buffers created with the commands
2533 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2534 Valid values are:
2535 current-window Display in the current window
2536 other-window Just display in another window.
2537 dedicated-frame Create one new frame, and re-use it each time.
2538 new-frame Make a new frame each time. Note that in this case
2539 previously-made indirect buffers are kept, and you need to
2540 kill these buffers yourself."
2541 :group 'org-structure
2542 :group 'org-agenda-windows
2543 :type '(choice
2544 (const :tag "In current window" current-window)
2545 (const :tag "In current frame, other window" other-window)
2546 (const :tag "Each time a new frame" new-frame)
2547 (const :tag "One dedicated frame" dedicated-frame)))
2549 (defgroup org-agenda-daily/weekly nil
2550 "Options concerning the daily/weekly agenda."
2551 :tag "Org Agenda Daily/Weekly"
2552 :group 'org-agenda)
2554 (defcustom org-agenda-ndays 7
2555 "Number of days to include in overview display.
2556 Should be 1 or 7."
2557 :group 'org-agenda-daily/weekly
2558 :type 'number)
2560 (defcustom org-agenda-start-on-weekday 1
2561 "Non-nil means, start the overview always on the specified weekday.
2562 0 denotes Sunday, 1 denotes Monday etc.
2563 When nil, always start on the current day."
2564 :group 'org-agenda-daily/weekly
2565 :type '(choice (const :tag "Today" nil)
2566 (number :tag "Weekday No.")))
2568 (defcustom org-agenda-show-all-dates t
2569 "Non-nil means, `org-agenda' shows every day in the selected range.
2570 When nil, only the days which actually have entries are shown."
2571 :group 'org-agenda-daily/weekly
2572 :type 'boolean)
2574 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2575 "Format string for displaying dates in the agenda.
2576 Used by the daily/weekly agenda and by the timeline. This should be
2577 a format string understood by `format-time-string', or a function returning
2578 the formatted date as a string. The function must take a single argument,
2579 a calendar-style date list like (month day year)."
2580 :group 'org-agenda-daily/weekly
2581 :type '(choice
2582 (string :tag "Format string")
2583 (function :tag "Function")))
2585 (defun org-agenda-format-date-aligned (date)
2586 "Format a date string for display in the daily/weekly agenda, or timeline.
2587 This function makes sure that dates are aligned for easy reading."
2588 (format "%-9s %2d %s %4d"
2589 (calendar-day-name date)
2590 (extract-calendar-day date)
2591 (calendar-month-name (extract-calendar-month date))
2592 (extract-calendar-year date)))
2594 (defcustom org-agenda-include-diary nil
2595 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2596 :group 'org-agenda-daily/weekly
2597 :type 'boolean)
2599 (defcustom org-agenda-include-all-todo nil
2600 "Set means weekly/daily agenda will always contain all TODO entries.
2601 The TODO entries will be listed at the top of the agenda, before
2602 the entries for specific days."
2603 :group 'org-agenda-daily/weekly
2604 :type 'boolean)
2606 (defcustom org-agenda-repeating-timestamp-show-all t
2607 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2608 When nil, only one occurence is shown, either today or the
2609 nearest into the future."
2610 :group 'org-agenda-daily/weekly
2611 :type 'boolean)
2613 (defcustom org-deadline-warning-days 14
2614 "No. of days before expiration during which a deadline becomes active.
2615 This variable governs the display in sparse trees and in the agenda.
2616 When negative, it means use this number (the absolute value of it)
2617 even if a deadline has a different individual lead time specified."
2618 :group 'org-time
2619 :group 'org-agenda-daily/weekly
2620 :type 'number)
2622 (defcustom org-scheduled-past-days 10000
2623 "No. of days to continue listing scheduled items that are not marked DONE.
2624 When an item is scheduled on a date, it shows up in the agenda on this
2625 day and will be listed until it is marked done for the number of days
2626 given here."
2627 :group 'org-agenda-daily/weekly
2628 :type 'number)
2630 (defgroup org-agenda-time-grid nil
2631 "Options concerning the time grid in the Org-mode Agenda."
2632 :tag "Org Agenda Time Grid"
2633 :group 'org-agenda)
2635 (defcustom org-agenda-use-time-grid t
2636 "Non-nil means, show a time grid in the agenda schedule.
2637 A time grid is a set of lines for specific times (like every two hours between
2638 8:00 and 20:00). The items scheduled for a day at specific times are
2639 sorted in between these lines.
2640 For details about when the grid will be shown, and what it will look like, see
2641 the variable `org-agenda-time-grid'."
2642 :group 'org-agenda-time-grid
2643 :type 'boolean)
2645 (defcustom org-agenda-time-grid
2646 '((daily today require-timed)
2647 "----------------"
2648 (800 1000 1200 1400 1600 1800 2000))
2650 "The settings for time grid for agenda display.
2651 This is a list of three items. The first item is again a list. It contains
2652 symbols specifying conditions when the grid should be displayed:
2654 daily if the agenda shows a single day
2655 weekly if the agenda shows an entire week
2656 today show grid on current date, independent of daily/weekly display
2657 require-timed show grid only if at least one item has a time specification
2659 The second item is a string which will be places behing the grid time.
2661 The third item is a list of integers, indicating the times that should have
2662 a grid line."
2663 :group 'org-agenda-time-grid
2664 :type
2665 '(list
2666 (set :greedy t :tag "Grid Display Options"
2667 (const :tag "Show grid in single day agenda display" daily)
2668 (const :tag "Show grid in weekly agenda display" weekly)
2669 (const :tag "Always show grid for today" today)
2670 (const :tag "Show grid only if any timed entries are present"
2671 require-timed)
2672 (const :tag "Skip grid times already present in an entry"
2673 remove-match))
2674 (string :tag "Grid String")
2675 (repeat :tag "Grid Times" (integer :tag "Time"))))
2677 (defgroup org-agenda-sorting nil
2678 "Options concerning sorting in the Org-mode Agenda."
2679 :tag "Org Agenda Sorting"
2680 :group 'org-agenda)
2682 (let ((sorting-choice
2683 '(choice
2684 (const time-up) (const time-down)
2685 (const category-keep) (const category-up) (const category-down)
2686 (const tag-down) (const tag-up)
2687 (const priority-up) (const priority-down))))
2689 (defcustom org-agenda-sorting-strategy
2690 '((agenda time-up category-keep priority-down)
2691 (todo category-keep priority-down)
2692 (tags category-keep priority-down))
2693 "Sorting structure for the agenda items of a single day.
2694 This is a list of symbols which will be used in sequence to determine
2695 if an entry should be listed before another entry. The following
2696 symbols are recognized:
2698 time-up Put entries with time-of-day indications first, early first
2699 time-down Put entries with time-of-day indications first, late first
2700 category-keep Keep the default order of categories, corresponding to the
2701 sequence in `org-agenda-files'.
2702 category-up Sort alphabetically by category, A-Z.
2703 category-down Sort alphabetically by category, Z-A.
2704 tag-up Sort alphabetically by last tag, A-Z.
2705 tag-down Sort alphabetically by last tag, Z-A.
2706 priority-up Sort numerically by priority, high priority last.
2707 priority-down Sort numerically by priority, high priority first.
2709 The different possibilities will be tried in sequence, and testing stops
2710 if one comparison returns a \"not-equal\". For example, the default
2711 '(time-up category-keep priority-down)
2712 means: Pull out all entries having a specified time of day and sort them,
2713 in order to make a time schedule for the current day the first thing in the
2714 agenda listing for the day. Of the entries without a time indication, keep
2715 the grouped in categories, don't sort the categories, but keep them in
2716 the sequence given in `org-agenda-files'. Within each category sort by
2717 priority.
2719 Leaving out `category-keep' would mean that items will be sorted across
2720 categories by priority.
2722 Instead of a single list, this can also be a set of list for specific
2723 contents, with a context symbol in the car of the list, any of
2724 `agenda', `todo', `tags' for the corresponding agenda views."
2725 :group 'org-agenda-sorting
2726 :type `(choice
2727 (repeat :tag "General" ,sorting-choice)
2728 (list :tag "Individually"
2729 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2730 (repeat ,sorting-choice))
2731 (cons (const :tag "Strategy for TODO lists" todo)
2732 (repeat ,sorting-choice))
2733 (cons (const :tag "Strategy for Tags matches" tags)
2734 (repeat ,sorting-choice))))))
2736 (defcustom org-sort-agenda-notime-is-late t
2737 "Non-nil means, items without time are considered late.
2738 This is only relevant for sorting. When t, items which have no explicit
2739 time like 15:30 will be considered as 99:01, i.e. later than any items which
2740 do have a time. When nil, the default time is before 0:00. You can use this
2741 option to decide if the schedule for today should come before or after timeless
2742 agenda entries."
2743 :group 'org-agenda-sorting
2744 :type 'boolean)
2746 (defgroup org-agenda-line-format nil
2747 "Options concerning the entry prefix in the Org-mode agenda display."
2748 :tag "Org Agenda Line Format"
2749 :group 'org-agenda)
2751 (defcustom org-agenda-prefix-format
2752 '((agenda . " %-12:c%?-12t% s")
2753 (timeline . " % s")
2754 (todo . " %-12:c")
2755 (tags . " %-12:c"))
2756 "Format specifications for the prefix of items in the agenda views.
2757 An alist with four entries, for the different agenda types. The keys to the
2758 sublists are `agenda', `timeline', `todo', and `tags'. The values
2759 are format strings.
2760 This format works similar to a printf format, with the following meaning:
2762 %c the category of the item, \"Diary\" for entries from the diary, or
2763 as given by the CATEGORY keyword or derived from the file name.
2764 %T the *last* tag of the item. Last because inherited tags come
2765 first in the list.
2766 %t the time-of-day specification if one applies to the entry, in the
2767 format HH:MM
2768 %s Scheduling/Deadline information, a short string
2770 All specifiers work basically like the standard `%s' of printf, but may
2771 contain two additional characters: A question mark just after the `%' and
2772 a whitespace/punctuation character just before the final letter.
2774 If the first character after `%' is a question mark, the entire field
2775 will only be included if the corresponding value applies to the
2776 current entry. This is useful for fields which should have fixed
2777 width when present, but zero width when absent. For example,
2778 \"%?-12t\" will result in a 12 character time field if a time of the
2779 day is specified, but will completely disappear in entries which do
2780 not contain a time.
2782 If there is punctuation or whitespace character just before the final
2783 format letter, this character will be appended to the field value if
2784 the value is not empty. For example, the format \"%-12:c\" leads to
2785 \"Diary: \" if the category is \"Diary\". If the category were be
2786 empty, no additional colon would be interted.
2788 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2789 - Indent the line with two space characters
2790 - Give the category in a 12 chars wide field, padded with whitespace on
2791 the right (because of `-'). Append a colon if there is a category
2792 (because of `:').
2793 - If there is a time-of-day, put it into a 12 chars wide field. If no
2794 time, don't put in an empty field, just skip it (because of '?').
2795 - Finally, put the scheduling information and append a whitespace.
2797 As another example, if you don't want the time-of-day of entries in
2798 the prefix, you could use:
2800 (setq org-agenda-prefix-format \" %-11:c% s\")
2802 See also the variables `org-agenda-remove-times-when-in-prefix' and
2803 `org-agenda-remove-tags'."
2804 :type '(choice
2805 (string :tag "General format")
2806 (list :greedy t :tag "View dependent"
2807 (cons (const agenda) (string :tag "Format"))
2808 (cons (const timeline) (string :tag "Format"))
2809 (cons (const todo) (string :tag "Format"))
2810 (cons (const tags) (string :tag "Format"))))
2811 :group 'org-agenda-line-format)
2813 (defvar org-prefix-format-compiled nil
2814 "The compiled version of the most recently used prefix format.
2815 See the variable `org-agenda-prefix-format'.")
2817 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2818 "Text preceeding scheduled items in the agenda view.
2819 THis is a list with two strings. The first applies when the item is
2820 scheduled on the current day. The second applies when it has been scheduled
2821 previously, it may contain a %d to capture how many days ago the item was
2822 scheduled."
2823 :group 'org-agenda-line-format
2824 :type '(list
2825 (string :tag "Scheduled today ")
2826 (string :tag "Scheduled previously")))
2828 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2829 "Text preceeding deadline items in the agenda view.
2830 This is a list with two strings. The first applies when the item has its
2831 deadline on the current day. The second applies when it is in the past or
2832 in the future, it may contain %d to capture how many days away the deadline
2833 is (was)."
2834 :group 'org-agenda-line-format
2835 :type '(list
2836 (string :tag "Deadline today ")
2837 (string :tag "Deadline relative")))
2839 (defcustom org-agenda-remove-times-when-in-prefix t
2840 "Non-nil means, remove duplicate time specifications in agenda items.
2841 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2842 time-of-day specification in a headline or diary entry is extracted and
2843 placed into the prefix. If this option is non-nil, the original specification
2844 \(a timestamp or -range, or just a plain time(range) specification like
2845 11:30-4pm) will be removed for agenda display. This makes the agenda less
2846 cluttered.
2847 The option can be t or nil. It may also be the symbol `beg', indicating
2848 that the time should only be removed what it is located at the beginning of
2849 the headline/diary entry."
2850 :group 'org-agenda-line-format
2851 :type '(choice
2852 (const :tag "Always" t)
2853 (const :tag "Never" nil)
2854 (const :tag "When at beginning of entry" beg)))
2857 (defcustom org-agenda-default-appointment-duration nil
2858 "Default duration for appointments that only have a starting time.
2859 When nil, no duration is specified in such cases.
2860 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2861 :group 'org-agenda-line-format
2862 :type '(choice
2863 (integer :tag "Minutes")
2864 (const :tag "No default duration")))
2867 (defcustom org-agenda-remove-tags nil
2868 "Non-nil means, remove the tags from the headline copy in the agenda.
2869 When this is the symbol `prefix', only remove tags when
2870 `org-agenda-prefix-format' contains a `%T' specifier."
2871 :group 'org-agenda-line-format
2872 :type '(choice
2873 (const :tag "Always" t)
2874 (const :tag "Never" nil)
2875 (const :tag "When prefix format contains %T" prefix)))
2877 (if (fboundp 'defvaralias)
2878 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2879 'org-agenda-remove-tags))
2881 (defcustom org-agenda-tags-column -80
2882 "Shift tags in agenda items to this column.
2883 If this number is positive, it specifies the column. If it is negative,
2884 it means that the tags should be flushright to that column. For example,
2885 -80 works well for a normal 80 character screen."
2886 :group 'org-agenda-line-format
2887 :type 'integer)
2889 (if (fboundp 'defvaralias)
2890 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2892 (defcustom org-agenda-fontify-priorities t
2893 "Non-nil means, highlight low and high priorities in agenda.
2894 When t, the highest priority entries are bold, lowest priority italic.
2895 This may also be an association list of priority faces. The face may be
2896 a names face, or a list like `(:background \"Red\")'."
2897 :group 'org-agenda-line-format
2898 :type '(choice
2899 (const :tag "Never" nil)
2900 (const :tag "Defaults" t)
2901 (repeat :tag "Specify"
2902 (list (character :tag "Priority" :value ?A)
2903 (sexp :tag "face")))))
2905 (defgroup org-latex nil
2906 "Options for embedding LaTeX code into Org-mode"
2907 :tag "Org LaTeX"
2908 :group 'org)
2910 (defcustom org-format-latex-options
2911 '(:foreground default :background default :scale 1.0
2912 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2913 :matchers ("begin" "$" "$$" "\\(" "\\["))
2914 "Options for creating images from LaTeX fragments.
2915 This is a property list with the following properties:
2916 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2917 `default' means use the forground of the default face.
2918 :background the background color, or \"Transparent\".
2919 `default' means use the background of the default face.
2920 :scale a scaling factor for the size of the images
2921 :html-foreground, :html-background, :html-scale
2922 The same numbers for HTML export.
2923 :matchers a list indicating which matchers should be used to
2924 find LaTeX fragments. Valid members of this list are:
2925 \"begin\" find environments
2926 \"$\" find math expressions surrounded by $...$
2927 \"$$\" find math expressions surrounded by $$....$$
2928 \"\\(\" find math expressions surrounded by \\(...\\)
2929 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2930 :group 'org-latex
2931 :type 'plist)
2933 (defcustom org-format-latex-header "\\documentclass{article}
2934 \\usepackage{fullpage} % do not remove
2935 \\usepackage{amssymb}
2936 \\usepackage[usenames]{color}
2937 \\usepackage{amsmath}
2938 \\usepackage{latexsym}
2939 \\usepackage[mathscr]{eucal}
2940 \\pagestyle{empty} % do not remove"
2941 "The document header used for processing LaTeX fragments."
2942 :group 'org-latex
2943 :type 'string)
2945 (defgroup org-export nil
2946 "Options for exporting org-listings."
2947 :tag "Org Export"
2948 :group 'org)
2950 (defgroup org-export-general nil
2951 "General options for exporting Org-mode files."
2952 :tag "Org Export General"
2953 :group 'org-export)
2955 ;; FIXME
2956 (defvar org-export-publishing-directory nil)
2958 (defcustom org-export-with-special-strings t
2959 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
2960 When this option is turned on, these strings will be exported as:
2962 Org HTML LaTeX
2963 -----+----------+--------
2964 \\- &shy; \\-
2965 -- &ndash; --
2966 --- &mdash; ---
2967 ... &hellip; \ldots
2969 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
2970 :group 'org-export-translation
2971 :type 'boolean)
2973 (defcustom org-export-language-setup
2974 '(("en" "Author" "Date" "Table of Contents")
2975 ("cs" "Autor" "Datum" "Obsah")
2976 ("da" "Ophavsmand" "Dato" "Indhold")
2977 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2978 ("es" "Autor" "Fecha" "\xcdndice")
2979 ("fr" "Auteur" "Date" "Table des mati\xe8res")
2980 ("it" "Autore" "Data" "Indice")
2981 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2982 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2983 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2984 "Terms used in export text, translated to different languages.
2985 Use the variable `org-export-default-language' to set the language,
2986 or use the +OPTION lines for a per-file setting."
2987 :group 'org-export-general
2988 :type '(repeat
2989 (list
2990 (string :tag "HTML language tag")
2991 (string :tag "Author")
2992 (string :tag "Date")
2993 (string :tag "Table of Contents"))))
2995 (defcustom org-export-default-language "en"
2996 "The default language of HTML export, as a string.
2997 This should have an association in `org-export-language-setup'."
2998 :group 'org-export-general
2999 :type 'string)
3001 (defcustom org-export-skip-text-before-1st-heading t
3002 "Non-nil means, skip all text before the first headline when exporting.
3003 When nil, that text is exported as well."
3004 :group 'org-export-general
3005 :type 'boolean)
3007 (defcustom org-export-headline-levels 3
3008 "The last level which is still exported as a headline.
3009 Inferior levels will produce itemize lists when exported.
3010 Note that a numeric prefix argument to an exporter function overrides
3011 this setting.
3013 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3014 :group 'org-export-general
3015 :type 'number)
3017 (defcustom org-export-with-section-numbers t
3018 "Non-nil means, add section numbers to headlines when exporting.
3020 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3021 :group 'org-export-general
3022 :type 'boolean)
3024 (defcustom org-export-with-toc t
3025 "Non-nil means, create a table of contents in exported files.
3026 The TOC contains headlines with levels up to`org-export-headline-levels'.
3027 When an integer, include levels up to N in the toc, this may then be
3028 different from `org-export-headline-levels', but it will not be allowed
3029 to be larger than the number of headline levels.
3030 When nil, no table of contents is made.
3032 Headlines which contain any TODO items will be marked with \"(*)\" in
3033 ASCII export, and with red color in HTML output, if the option
3034 `org-export-mark-todo-in-toc' is set.
3036 In HTML output, the TOC will be clickable.
3038 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3039 or \"toc:3\"."
3040 :group 'org-export-general
3041 :type '(choice
3042 (const :tag "No Table of Contents" nil)
3043 (const :tag "Full Table of Contents" t)
3044 (integer :tag "TOC to level")))
3046 (defcustom org-export-mark-todo-in-toc nil
3047 "Non-nil means, mark TOC lines that contain any open TODO items."
3048 :group 'org-export-general
3049 :type 'boolean)
3051 (defcustom org-export-preserve-breaks nil
3052 "Non-nil means, preserve all line breaks when exporting.
3053 Normally, in HTML output paragraphs will be reformatted. In ASCII
3054 export, line breaks will always be preserved, regardless of this variable.
3056 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3057 :group 'org-export-general
3058 :type 'boolean)
3060 (defcustom org-export-with-archived-trees 'headline
3061 "Whether subtrees with the ARCHIVE tag should be exported.
3062 This can have three different values
3063 nil Do not export, pretend this tree is not present
3064 t Do export the entire tree
3065 headline Only export the headline, but skip the tree below it."
3066 :group 'org-export-general
3067 :group 'org-archive
3068 :type '(choice
3069 (const :tag "not at all" nil)
3070 (const :tag "headline only" 'headline)
3071 (const :tag "entirely" t)))
3073 (defcustom org-export-author-info t
3074 "Non-nil means, insert author name and email into the exported file.
3076 This option can also be set with the +OPTIONS line,
3077 e.g. \"author-info:nil\"."
3078 :group 'org-export-general
3079 :type 'boolean)
3081 (defcustom org-export-time-stamp-file t
3082 "Non-nil means, insert a time stamp into the exported file.
3083 The time stamp shows when the file was created.
3085 This option can also be set with the +OPTIONS line,
3086 e.g. \"timestamp:nil\"."
3087 :group 'org-export-general
3088 :type 'boolean)
3090 (defcustom org-export-with-timestamps t
3091 "If nil, do not export time stamps and associated keywords."
3092 :group 'org-export-general
3093 :type 'boolean)
3095 (defcustom org-export-remove-timestamps-from-toc t
3096 "If nil, remove timestamps from the table of contents entries."
3097 :group 'org-export-general
3098 :type 'boolean)
3100 (defcustom org-export-with-tags 'not-in-toc
3101 "If nil, do not export tags, just remove them from headlines.
3102 If this is the symbol `not-in-toc', tags will be removed from table of
3103 contents entries, but still be shown in the headlines of the document.
3105 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3106 :group 'org-export-general
3107 :type '(choice
3108 (const :tag "Off" nil)
3109 (const :tag "Not in TOC" not-in-toc)
3110 (const :tag "On" t)))
3112 (defcustom org-export-with-drawers nil
3113 "Non-nil means, export with drawers like the property drawer.
3114 When t, all drawers are exported. This may also be a list of
3115 drawer names to export."
3116 :group 'org-export-general
3117 :type '(choice
3118 (const :tag "All drawers" t)
3119 (const :tag "None" nil)
3120 (repeat :tag "Selected drawers"
3121 (string :tag "Drawer name"))))
3123 (defgroup org-export-translation nil
3124 "Options for translating special ascii sequences for the export backends."
3125 :tag "Org Export Translation"
3126 :group 'org-export)
3128 (defcustom org-export-with-emphasize t
3129 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3130 If the export target supports emphasizing text, the word will be
3131 typeset in bold, italic, or underlined, respectively. Works only for
3132 single words, but you can say: I *really* *mean* *this*.
3133 Not all export backends support this.
3135 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3136 :group 'org-export-translation
3137 :type 'boolean)
3139 (defcustom org-export-with-footnotes t
3140 "If nil, export [1] as a footnote marker.
3141 Lines starting with [1] will be formatted as footnotes.
3143 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3144 :group 'org-export-translation
3145 :type 'boolean)
3147 (defcustom org-export-with-sub-superscripts t
3148 "Non-nil means, interpret \"_\" and \"^\" for export.
3149 When this option is turned on, you can use TeX-like syntax for sub- and
3150 superscripts. Several characters after \"_\" or \"^\" will be
3151 considered as a single item - so grouping with {} is normally not
3152 needed. For example, the following things will be parsed as single
3153 sub- or superscripts.
3155 10^24 or 10^tau several digits will be considered 1 item.
3156 10^-12 or 10^-tau a leading sign with digits or a word
3157 x^2-y^3 will be read as x^2 - y^3, because items are
3158 terminated by almost any nonword/nondigit char.
3159 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3161 Still, ambiguity is possible - so when in doubt use {} to enclose the
3162 sub/superscript. If you set this variable to the symbol `{}',
3163 the braces are *required* in order to trigger interpretations as
3164 sub/superscript. This can be helpful in documents that need \"_\"
3165 frequently in plain text.
3167 Not all export backends support this, but HTML does.
3169 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3170 :group 'org-export-translation
3171 :type '(choice
3172 (const :tag "Always interpret" t)
3173 (const :tag "Only with braces" {})
3174 (const :tag "Never interpret" nil)))
3176 (defcustom org-export-with-special-strings t
3177 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3178 When this option is turned on, these strings will be exported as:
3180 \\- : &shy;
3181 -- : &ndash;
3182 --- : &mdash;
3184 Not all export backends support this, but HTML does.
3186 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3187 :group 'org-export-translation
3188 :type 'boolean)
3190 (defcustom org-export-with-TeX-macros t
3191 "Non-nil means, interpret simple TeX-like macros when exporting.
3192 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3193 No only real TeX macros will work here, but the standard HTML entities
3194 for math can be used as macro names as well. For a list of supported
3195 names in HTML export, see the constant `org-html-entities'.
3196 Not all export backends support this.
3198 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3199 :group 'org-export-translation
3200 :group 'org-export-latex
3201 :type 'boolean)
3203 (defcustom org-export-with-LaTeX-fragments nil
3204 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3205 When set, the exporter will find LaTeX environments if the \\begin line is
3206 the first non-white thing on a line. It will also find the math delimiters
3207 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3208 display math.
3210 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3211 :group 'org-export-translation
3212 :group 'org-export-latex
3213 :type 'boolean)
3215 (defcustom org-export-with-fixed-width t
3216 "Non-nil means, lines starting with \":\" will be in fixed width font.
3217 This can be used to have pre-formatted text, fragments of code etc. For
3218 example:
3219 : ;; Some Lisp examples
3220 : (while (defc cnt)
3221 : (ding))
3222 will be looking just like this in also HTML. See also the QUOTE keyword.
3223 Not all export backends support this.
3225 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3226 :group 'org-export-translation
3227 :type 'boolean)
3229 (defcustom org-match-sexp-depth 3
3230 "Number of stacked braces for sub/superscript matching.
3231 This has to be set before loading org.el to be effective."
3232 :group 'org-export-translation
3233 :type 'integer)
3235 (defgroup org-export-tables nil
3236 "Options for exporting tables in Org-mode."
3237 :tag "Org Export Tables"
3238 :group 'org-export)
3240 (defcustom org-export-with-tables t
3241 "If non-nil, lines starting with \"|\" define a table.
3242 For example:
3244 | Name | Address | Birthday |
3245 |-------------+----------+-----------|
3246 | Arthur Dent | England | 29.2.2100 |
3248 Not all export backends support this.
3250 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3251 :group 'org-export-tables
3252 :type 'boolean)
3254 (defcustom org-export-highlight-first-table-line t
3255 "Non-nil means, highlight the first table line.
3256 In HTML export, this means use <th> instead of <td>.
3257 In tables created with table.el, this applies to the first table line.
3258 In Org-mode tables, all lines before the first horizontal separator
3259 line will be formatted with <th> tags."
3260 :group 'org-export-tables
3261 :type 'boolean)
3263 (defcustom org-export-table-remove-special-lines t
3264 "Remove special lines and marking characters in calculating tables.
3265 This removes the special marking character column from tables that are set
3266 up for spreadsheet calculations. It also removes the entire lines
3267 marked with `!', `_', or `^'. The lines with `$' are kept, because
3268 the values of constants may be useful to have."
3269 :group 'org-export-tables
3270 :type 'boolean)
3272 (defcustom org-export-prefer-native-exporter-for-tables nil
3273 "Non-nil means, always export tables created with table.el natively.
3274 Natively means, use the HTML code generator in table.el.
3275 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3276 the table does not use row- or column-spanning). This has the
3277 advantage, that the automatic HTML conversions for math symbols and
3278 sub/superscripts can be applied. Org-mode's HTML generator is also
3279 much faster."
3280 :group 'org-export-tables
3281 :type 'boolean)
3283 (defgroup org-export-ascii nil
3284 "Options specific for ASCII export of Org-mode files."
3285 :tag "Org Export ASCII"
3286 :group 'org-export)
3288 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3289 "Characters for underlining headings in ASCII export.
3290 In the given sequence, these characters will be used for level 1, 2, ..."
3291 :group 'org-export-ascii
3292 :type '(repeat character))
3294 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3295 "Bullet characters for headlines converted to lists in ASCII export.
3296 The first character is is used for the first lest level generated in this
3297 way, and so on. If there are more levels than characters given here,
3298 the list will be repeated.
3299 Note that plain lists will keep the same bullets as the have in the
3300 Org-mode file."
3301 :group 'org-export-ascii
3302 :type '(repeat character))
3304 (defgroup org-export-xml nil
3305 "Options specific for XML export of Org-mode files."
3306 :tag "Org Export XML"
3307 :group 'org-export)
3309 (defgroup org-export-html nil
3310 "Options specific for HTML export of Org-mode files."
3311 :tag "Org Export HTML"
3312 :group 'org-export)
3314 (defcustom org-export-html-coding-system nil
3316 :group 'org-export-html
3317 :type 'coding-system)
3319 (defcustom org-export-html-extension "html"
3320 "The extension for exported HTML files."
3321 :group 'org-export-html
3322 :type 'string)
3324 (defcustom org-export-html-style
3325 "<style type=\"text/css\">
3326 html {
3327 font-family: Times, serif;
3328 font-size: 12pt;
3330 .title { text-align: center; }
3331 .todo { color: red; }
3332 .done { color: green; }
3333 .timestamp { color: grey }
3334 .timestamp-kwd { color: CadetBlue }
3335 .tag { background-color:lightblue; font-weight:normal }
3336 .target { background-color: lavender; }
3337 pre {
3338 border: 1pt solid #AEBDCC;
3339 background-color: #F3F5F7;
3340 padding: 5pt;
3341 font-family: courier, monospace;
3343 table { border-collapse: collapse; }
3344 td, th {
3345 vertical-align: top;
3346 <!--border: 1pt solid #ADB9CC;-->
3348 </style>"
3349 "The default style specification for exported HTML files.
3350 Since there are different ways of setting style information, this variable
3351 needs to contain the full HTML structure to provide a style, including the
3352 surrounding HTML tags. The style specifications should include definitions
3353 for new classes todo, done, title, and deadline. For example, legal values
3354 would be:
3356 <style type=\"text/css\">
3357 p { font-weight: normal; color: gray; }
3358 h1 { color: black; }
3359 .title { text-align: center; }
3360 .todo, .deadline { color: red; }
3361 .done { color: green; }
3362 </style>
3364 or, if you want to keep the style in a file,
3366 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3368 As the value of this option simply gets inserted into the HTML <head> header,
3369 you can \"misuse\" it to add arbitrary text to the header."
3370 :group 'org-export-html
3371 :type 'string)
3374 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3375 "Format for typesetting the document title in HTML export."
3376 :group 'org-export-html
3377 :type 'string)
3379 (defcustom org-export-html-toplevel-hlevel 2
3380 "The <H> level for level 1 headings in HTML export."
3381 :group 'org-export-html
3382 :type 'string)
3384 (defcustom org-export-html-link-org-files-as-html t
3385 "Non-nil means, make file links to `file.org' point to `file.html'.
3386 When org-mode is exporting an org-mode file to HTML, links to
3387 non-html files are directly put into a href tag in HTML.
3388 However, links to other Org-mode files (recognized by the
3389 extension `.org.) should become links to the corresponding html
3390 file, assuming that the linked org-mode file will also be
3391 converted to HTML.
3392 When nil, the links still point to the plain `.org' file."
3393 :group 'org-export-html
3394 :type 'boolean)
3396 (defcustom org-export-html-inline-images 'maybe
3397 "Non-nil means, inline images into exported HTML pages.
3398 This is done using an <img> tag. When nil, an anchor with href is used to
3399 link to the image. If this option is `maybe', then images in links with
3400 an empty description will be inlined, while images with a description will
3401 be linked only."
3402 :group 'org-export-html
3403 :type '(choice (const :tag "Never" nil)
3404 (const :tag "Always" t)
3405 (const :tag "When there is no description" maybe)))
3407 ;; FIXME: rename
3408 (defcustom org-export-html-expand t
3409 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3410 When nil, these tags will be exported as plain text and therefore
3411 not be interpreted by a browser.
3413 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3414 :group 'org-export-html
3415 :type 'boolean)
3417 (defcustom org-export-html-table-tag
3418 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3419 "The HTML tag that is used to start a table.
3420 This must be a <table> tag, but you may change the options like
3421 borders and spacing."
3422 :group 'org-export-html
3423 :type 'string)
3425 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3426 "The opening tag for table header fields.
3427 This is customizable so that alignment options can be specified."
3428 :group 'org-export-tables
3429 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3431 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3432 "The opening tag for table data fields.
3433 This is customizable so that alignment options can be specified."
3434 :group 'org-export-tables
3435 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3437 (defcustom org-export-html-with-timestamp nil
3438 "If non-nil, write `org-export-html-html-helper-timestamp'
3439 into the exported HTML text. Otherwise, the buffer will just be saved
3440 to a file."
3441 :group 'org-export-html
3442 :type 'boolean)
3444 (defcustom org-export-html-html-helper-timestamp
3445 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3446 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3447 :group 'org-export-html
3448 :type 'string)
3450 (defgroup org-export-icalendar nil
3451 "Options specific for iCalendar export of Org-mode files."
3452 :tag "Org Export iCalendar"
3453 :group 'org-export)
3455 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3456 "The file name for the iCalendar file covering all agenda files.
3457 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3458 The file name should be absolute, the file will be overwritten without warning."
3459 :group 'org-export-icalendar
3460 :type 'file)
3462 (defcustom org-icalendar-include-todo nil
3463 "Non-nil means, export to iCalendar files should also cover TODO items."
3464 :group 'org-export-icalendar
3465 :type '(choice
3466 (const :tag "None" nil)
3467 (const :tag "Unfinished" t)
3468 (const :tag "All" all)))
3470 (defcustom org-icalendar-include-sexps t
3471 "Non-nil means, export to iCalendar files should also cover sexp entries.
3472 These are entries like in the diary, but directly in an Org-mode file."
3473 :group 'org-export-icalendar
3474 :type 'boolean)
3476 (defcustom org-icalendar-include-body 100
3477 "Amount of text below headline to be included in iCalendar export.
3478 This is a number of characters that should maximally be included.
3479 Properties, scheduling and clocking lines will always be removed.
3480 The text will be inserted into the DESCRIPTION field."
3481 :group 'org-export-icalendar
3482 :type '(choice
3483 (const :tag "Nothing" nil)
3484 (const :tag "Everything" t)
3485 (integer :tag "Max characters")))
3487 (defcustom org-icalendar-combined-name "OrgMode"
3488 "Calendar name for the combined iCalendar representing all agenda files."
3489 :group 'org-export-icalendar
3490 :type 'string)
3492 (defgroup org-font-lock nil
3493 "Font-lock settings for highlighting in Org-mode."
3494 :tag "Org Font Lock"
3495 :group 'org)
3497 (defcustom org-level-color-stars-only nil
3498 "Non-nil means fontify only the stars in each headline.
3499 When nil, the entire headline is fontified.
3500 Changing it requires restart of `font-lock-mode' to become effective
3501 also in regions already fontified."
3502 :group 'org-font-lock
3503 :type 'boolean)
3505 (defcustom org-hide-leading-stars nil
3506 "Non-nil means, hide the first N-1 stars in a headline.
3507 This works by using the face `org-hide' for these stars. This
3508 face is white for a light background, and black for a dark
3509 background. You may have to customize the face `org-hide' to
3510 make this work.
3511 Changing it requires restart of `font-lock-mode' to become effective
3512 also in regions already fontified.
3513 You may also set this on a per-file basis by adding one of the following
3514 lines to the buffer:
3516 #+STARTUP: hidestars
3517 #+STARTUP: showstars"
3518 :group 'org-font-lock
3519 :type 'boolean)
3521 (defcustom org-fontify-done-headline nil
3522 "Non-nil means, change the face of a headline if it is marked DONE.
3523 Normally, only the TODO/DONE keyword indicates the state of a headline.
3524 When this is non-nil, the headline after the keyword is set to the
3525 `org-headline-done' as an additional indication."
3526 :group 'org-font-lock
3527 :type 'boolean)
3529 (defcustom org-fontify-emphasized-text t
3530 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3531 Changing this variable requires a restart of Emacs to take effect."
3532 :group 'org-font-lock
3533 :type 'boolean)
3535 (defcustom org-hide-emphasis-markers nil
3536 "Non-nil mean font-lock should hide the emphasis marker characters."
3537 :group 'org-font-lock
3538 :type 'boolean)
3540 (defvar org-emph-re nil
3541 "Regular expression for matching emphasis.")
3542 (defvar org-verbatim-re nil
3543 "Regular expression for matching verbatim text.")
3544 (defvar org-emphasis-regexp-components) ; defined just below
3545 (defvar org-emphasis-alist) ; defined just below
3546 (defun org-set-emph-re (var val)
3547 "Set variable and compute the emphasis regular expression."
3548 (set var val)
3549 (when (and (boundp 'org-emphasis-alist)
3550 (boundp 'org-emphasis-regexp-components)
3551 org-emphasis-alist org-emphasis-regexp-components)
3552 (let* ((e org-emphasis-regexp-components)
3553 (pre (car e))
3554 (post (nth 1 e))
3555 (border (nth 2 e))
3556 (body (nth 3 e))
3557 (nl (nth 4 e))
3558 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3559 (body1 (concat body "*?"))
3560 (markers (mapconcat 'car org-emphasis-alist ""))
3561 (vmarkers (mapconcat
3562 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3563 org-emphasis-alist "")))
3564 ;; make sure special characters appear at the right position in the class
3565 (if (string-match "\\^" markers)
3566 (setq markers (concat (replace-match "" t t markers) "^")))
3567 (if (string-match "-" markers)
3568 (setq markers (concat (replace-match "" t t markers) "-")))
3569 (if (string-match "\\^" vmarkers)
3570 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3571 (if (string-match "-" vmarkers)
3572 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3573 (if (> nl 0)
3574 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3575 (int-to-string nl) "\\}")))
3576 ;; Make the regexp
3577 (setq org-emph-re
3578 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3579 "\\("
3580 "\\([" markers "]\\)"
3581 "\\("
3582 "[^" border "]\\|"
3583 "[^" border (if (and nil stacked) markers) "]"
3584 body1
3585 "[^" border (if (and nil stacked) markers) "]"
3586 "\\)"
3587 "\\3\\)"
3588 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3589 (setq org-verbatim-re
3590 (concat "\\([" pre "]\\|^\\)"
3591 "\\("
3592 "\\([" vmarkers "]\\)"
3593 "\\("
3594 "[^" border "]\\|"
3595 "[^" border "]"
3596 body1
3597 "[^" border "]"
3598 "\\)"
3599 "\\3\\)"
3600 "\\([" post "]\\|$\\)")))))
3602 (defcustom org-emphasis-regexp-components
3603 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3604 "Components used to build the regular expression for emphasis.
3605 This is a list with 6 entries. Terminology: In an emphasis string
3606 like \" *strong word* \", we call the initial space PREMATCH, the final
3607 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3608 and \"trong wor\" is the body. The different components in this variable
3609 specify what is allowed/forbidden in each part:
3611 pre Chars allowed as prematch. Beginning of line will be allowed too.
3612 post Chars allowed as postmatch. End of line will be allowed too.
3613 border The chars *forbidden* as border characters.
3614 body-regexp A regexp like \".\" to match a body character. Don't use
3615 non-shy groups here, and don't allow newline here.
3616 newline The maximum number of newlines allowed in an emphasis exp.
3618 Use customize to modify this, or restart Emacs after changing it."
3619 :group 'org-font-lock
3620 :set 'org-set-emph-re
3621 :type '(list
3622 (sexp :tag "Allowed chars in pre ")
3623 (sexp :tag "Allowed chars in post ")
3624 (sexp :tag "Forbidden chars in border ")
3625 (sexp :tag "Regexp for body ")
3626 (integer :tag "number of newlines allowed")
3627 (option (boolean :tag "Stacking (DISABLED) "))))
3629 (defcustom org-emphasis-alist
3630 '(("*" bold "<b>" "</b>")
3631 ("/" italic "<i>" "</i>")
3632 ("_" underline "<u>" "</u>")
3633 ("=" org-code "<code>" "</code>" verbatim)
3634 ("~" org-verbatim "" "" verbatim)
3635 ("+" (:strike-through t) "<del>" "</del>")
3637 "Special syntax for emphasized text.
3638 Text starting and ending with a special character will be emphasized, for
3639 example *bold*, _underlined_ and /italic/. This variable sets the marker
3640 characters, the face to be used by font-lock for highlighting in Org-mode
3641 Emacs buffers, and the HTML tags to be used for this.
3642 Use customize to modify this, or restart Emacs after changing it."
3643 :group 'org-font-lock
3644 :set 'org-set-emph-re
3645 :type '(repeat
3646 (list
3647 (string :tag "Marker character")
3648 (choice
3649 (face :tag "Font-lock-face")
3650 (plist :tag "Face property list"))
3651 (string :tag "HTML start tag")
3652 (string :tag "HTML end tag")
3653 (option (const verbatim)))))
3655 ;;; The faces
3657 (defgroup org-faces nil
3658 "Faces in Org-mode."
3659 :tag "Org Faces"
3660 :group 'org-font-lock)
3662 (defun org-compatible-face (inherits specs)
3663 "Make a compatible face specification.
3664 If INHERITS is an existing face and if the Emacs version supports it,
3665 just inherit the face. If not, use SPECS to define the face.
3666 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3667 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3668 to the top of the list. The `min-colors' attribute will be removed from
3669 any other entries, and any resulting duplicates will be removed entirely."
3670 (cond
3671 ((and inherits (facep inherits)
3672 (not (featurep 'xemacs)) (> emacs-major-version 22))
3673 ;; In Emacs 23, we use inheritance where possible.
3674 ;; We only do this in Emacs 23, because only there the outline
3675 ;; faces have been changed to the original org-mode-level-faces.
3676 (list (list t :inherit inherits)))
3677 ((or (featurep 'xemacs) (< emacs-major-version 22))
3678 ;; These do not understand the `min-colors' attribute.
3679 (let (r e a)
3680 (while (setq e (pop specs))
3681 (cond
3682 ((memq (car e) '(t default)) (push e r))
3683 ((setq a (member '(min-colors 8) (car e)))
3684 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3685 (cdr e)))))
3686 ((setq a (assq 'min-colors (car e)))
3687 (setq e (cons (delq a (car e)) (cdr e)))
3688 (or (assoc (car e) r) (push e r)))
3689 (t (or (assoc (car e) r) (push e r)))))
3690 (nreverse r)))
3691 (t specs)))
3692 (put 'org-compatible-face 'lisp-indent-function 1)
3694 (defface org-hide
3695 '((((background light)) (:foreground "white"))
3696 (((background dark)) (:foreground "black")))
3697 "Face used to hide leading stars in headlines.
3698 The forground color of this face should be equal to the background
3699 color of the frame."
3700 :group 'org-faces)
3702 (defface org-level-1 ;; font-lock-function-name-face
3703 (org-compatible-face 'outline-1
3704 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3705 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3706 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3707 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3708 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3709 (t (:bold t))))
3710 "Face used for level 1 headlines."
3711 :group 'org-faces)
3713 (defface org-level-2 ;; font-lock-variable-name-face
3714 (org-compatible-face 'outline-2
3715 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3716 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3717 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3718 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3719 (t (:bold t))))
3720 "Face used for level 2 headlines."
3721 :group 'org-faces)
3723 (defface org-level-3 ;; font-lock-keyword-face
3724 (org-compatible-face 'outline-3
3725 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3726 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3727 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3728 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3729 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3730 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3731 (t (:bold t))))
3732 "Face used for level 3 headlines."
3733 :group 'org-faces)
3735 (defface org-level-4 ;; font-lock-comment-face
3736 (org-compatible-face 'outline-4
3737 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3738 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3739 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3740 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3741 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3742 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3743 (t (:bold t))))
3744 "Face used for level 4 headlines."
3745 :group 'org-faces)
3747 (defface org-level-5 ;; font-lock-type-face
3748 (org-compatible-face 'outline-5
3749 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3750 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3751 (((class color) (min-colors 8)) (:foreground "green"))))
3752 "Face used for level 5 headlines."
3753 :group 'org-faces)
3755 (defface org-level-6 ;; font-lock-constant-face
3756 (org-compatible-face 'outline-6
3757 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3758 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3759 (((class color) (min-colors 8)) (:foreground "magenta"))))
3760 "Face used for level 6 headlines."
3761 :group 'org-faces)
3763 (defface org-level-7 ;; font-lock-builtin-face
3764 (org-compatible-face 'outline-7
3765 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3766 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3767 (((class color) (min-colors 8)) (:foreground "blue"))))
3768 "Face used for level 7 headlines."
3769 :group 'org-faces)
3771 (defface org-level-8 ;; font-lock-string-face
3772 (org-compatible-face 'outline-8
3773 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3774 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3775 (((class color) (min-colors 8)) (:foreground "green"))))
3776 "Face used for level 8 headlines."
3777 :group 'org-faces)
3779 (defface org-special-keyword ;; font-lock-string-face
3780 (org-compatible-face nil
3781 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3782 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3783 (t (:italic t))))
3784 "Face used for special keywords."
3785 :group 'org-faces)
3787 (defface org-drawer ;; font-lock-function-name-face
3788 (org-compatible-face nil
3789 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3790 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3791 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3792 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3793 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3794 (t (:bold t))))
3795 "Face used for drawers."
3796 :group 'org-faces)
3798 (defface org-property-value nil
3799 "Face used for the value of a property."
3800 :group 'org-faces)
3802 (defface org-column
3803 (org-compatible-face nil
3804 '((((class color) (min-colors 16) (background light))
3805 (:background "grey90"))
3806 (((class color) (min-colors 16) (background dark))
3807 (:background "grey30"))
3808 (((class color) (min-colors 8))
3809 (:background "cyan" :foreground "black"))
3810 (t (:inverse-video t))))
3811 "Face for column display of entry properties."
3812 :group 'org-faces)
3814 (when (fboundp 'set-face-attribute)
3815 ;; Make sure that a fixed-width face is used when we have a column table.
3816 (set-face-attribute 'org-column nil
3817 :height (face-attribute 'default :height)
3818 :family (face-attribute 'default :family)))
3820 (defface org-warning
3821 (org-compatible-face 'font-lock-warning-face
3822 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3823 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3824 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3825 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3826 (t (:bold t))))
3827 "Face for deadlines and TODO keywords."
3828 :group 'org-faces)
3830 (defface org-archived ; similar to shadow
3831 (org-compatible-face 'shadow
3832 '((((class color grayscale) (min-colors 88) (background light))
3833 (:foreground "grey50"))
3834 (((class color grayscale) (min-colors 88) (background dark))
3835 (:foreground "grey70"))
3836 (((class color) (min-colors 8) (background light))
3837 (:foreground "green"))
3838 (((class color) (min-colors 8) (background dark))
3839 (:foreground "yellow"))))
3840 "Face for headline with the ARCHIVE tag."
3841 :group 'org-faces)
3843 (defface org-link
3844 '((((class color) (background light)) (:foreground "Purple" :underline t))
3845 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3846 (t (:underline t)))
3847 "Face for links."
3848 :group 'org-faces)
3850 (defface org-ellipsis
3851 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3852 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3853 (t (:strike-through t)))
3854 "Face for the ellipsis in folded text."
3855 :group 'org-faces)
3857 (defface org-target
3858 '((((class color) (background light)) (:underline t))
3859 (((class color) (background dark)) (:underline t))
3860 (t (:underline t)))
3861 "Face for links."
3862 :group 'org-faces)
3864 (defface org-date
3865 '((((class color) (background light)) (:foreground "Purple" :underline t))
3866 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3867 (t (:underline t)))
3868 "Face for links."
3869 :group 'org-faces)
3871 (defface org-sexp-date
3872 '((((class color) (background light)) (:foreground "Purple"))
3873 (((class color) (background dark)) (:foreground "Cyan"))
3874 (t (:underline t)))
3875 "Face for links."
3876 :group 'org-faces)
3878 (defface org-tag
3879 '((t (:bold t)))
3880 "Face for tags."
3881 :group 'org-faces)
3883 (defface org-todo ; font-lock-warning-face
3884 (org-compatible-face nil
3885 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3886 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3887 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3888 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3889 (t (:inverse-video t :bold t))))
3890 "Face for TODO keywords."
3891 :group 'org-faces)
3893 (defface org-done ;; font-lock-type-face
3894 (org-compatible-face nil
3895 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3896 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3897 (((class color) (min-colors 8)) (:foreground "green"))
3898 (t (:bold t))))
3899 "Face used for todo keywords that indicate DONE items."
3900 :group 'org-faces)
3902 (defface org-headline-done ;; font-lock-string-face
3903 (org-compatible-face nil
3904 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3905 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3906 (((class color) (min-colors 8) (background light)) (:bold nil))))
3907 "Face used to indicate that a headline is DONE.
3908 This face is only used if `org-fontify-done-headline' is set. If applies
3909 to the part of the headline after the DONE keyword."
3910 :group 'org-faces)
3912 (defcustom org-todo-keyword-faces nil
3913 "Faces for specific TODO keywords.
3914 This is a list of cons cells, with TODO keywords in the car
3915 and faces in the cdr. The face can be a symbol, or a property
3916 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3917 :group 'org-faces
3918 :group 'org-todo
3919 :type '(repeat
3920 (cons
3921 (string :tag "keyword")
3922 (sexp :tag "face"))))
3924 (defface org-table ;; font-lock-function-name-face
3925 (org-compatible-face nil
3926 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3927 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3928 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3929 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3930 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3931 (((class color) (min-colors 8) (background dark)))))
3932 "Face used for tables."
3933 :group 'org-faces)
3935 (defface org-formula
3936 (org-compatible-face nil
3937 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3938 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3939 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3940 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3941 (t (:bold t :italic t))))
3942 "Face for formulas."
3943 :group 'org-faces)
3945 (defface org-code
3946 (org-compatible-face nil
3947 '((((class color grayscale) (min-colors 88) (background light))
3948 (:foreground "grey50"))
3949 (((class color grayscale) (min-colors 88) (background dark))
3950 (:foreground "grey70"))
3951 (((class color) (min-colors 8) (background light))
3952 (:foreground "green"))
3953 (((class color) (min-colors 8) (background dark))
3954 (:foreground "yellow"))))
3955 "Face for fixed-with text like code snippets."
3956 :group 'org-faces
3957 :version "22.1")
3959 (defface org-verbatim
3960 (org-compatible-face nil
3961 '((((class color grayscale) (min-colors 88) (background light))
3962 (:foreground "grey50" :underline t))
3963 (((class color grayscale) (min-colors 88) (background dark))
3964 (:foreground "grey70" :underline t))
3965 (((class color) (min-colors 8) (background light))
3966 (:foreground "green" :underline t))
3967 (((class color) (min-colors 8) (background dark))
3968 (:foreground "yellow" :underline t))))
3969 "Face for fixed-with text like code snippets."
3970 :group 'org-faces
3971 :version "22.1")
3973 (defface org-agenda-structure ;; font-lock-function-name-face
3974 (org-compatible-face nil
3975 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3976 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3977 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3978 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3979 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3980 (t (:bold t))))
3981 "Face used in agenda for captions and dates."
3982 :group 'org-faces)
3984 (defface org-scheduled-today
3985 (org-compatible-face nil
3986 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3987 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3988 (((class color) (min-colors 8)) (:foreground "green"))
3989 (t (:bold t :italic t))))
3990 "Face for items scheduled for a certain day."
3991 :group 'org-faces)
3993 (defface org-scheduled-previously
3994 (org-compatible-face nil
3995 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3996 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3997 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3998 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3999 (t (:bold t))))
4000 "Face for items scheduled previously, and not yet done."
4001 :group 'org-faces)
4003 (defface org-upcoming-deadline
4004 (org-compatible-face nil
4005 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4006 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4007 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4008 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4009 (t (:bold t))))
4010 "Face for items scheduled previously, and not yet done."
4011 :group 'org-faces)
4013 (defcustom org-agenda-deadline-faces
4014 '((1.0 . org-warning)
4015 (0.5 . org-upcoming-deadline)
4016 (0.0 . default))
4017 "Faces for showing deadlines in the agenda.
4018 This is a list of cons cells. The cdr of each cess is a face to be used,
4019 and it can also just be a like like '(:foreground \"yellow\").
4020 Each car is a fraction of the head-warning time that must have passed for
4021 this the face in the cdr to be used for display. The numbers must be
4022 given in descending order. The head-warning time is normally taken
4023 from `org-deadline-warning-days', but can also be specified in the deadline
4024 timestamp itself, like this:
4026 DEADLINE: <2007-08-13 Mon -8d>
4028 You may use d for days, w for weeks, m for months and y for years. Months
4029 and years will only be treated in an approximate fashion (30.4 days for a
4030 month and 365.24 days for a year)."
4031 :group 'org-faces
4032 :group 'org-agenda-daily/weekly
4033 :type '(repeat
4034 (cons
4035 (number :tag "Fraction of head-warning time passed")
4036 (sexp :tag "Face"))))
4038 ;; FIXME: this is not good
4039 (defface org-agenda-restriction-lock
4040 (org-compatible-face nil
4041 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4042 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4043 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4044 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4045 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4046 (t (:inverse-video t))))
4047 "Face for showing the agenda restriction lock."
4048 :group 'org-faces)
4050 (defface org-time-grid ;; font-lock-variable-name-face
4051 (org-compatible-face nil
4052 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4053 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4054 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4055 "Face used for time grids."
4056 :group 'org-faces)
4058 (defconst org-level-faces
4059 '(org-level-1 org-level-2 org-level-3 org-level-4
4060 org-level-5 org-level-6 org-level-7 org-level-8
4063 (defcustom org-n-level-faces (length org-level-faces)
4064 "The number different faces to be used for headlines.
4065 Org-mode defines 8 different headline faces, so this can be at most 8.
4066 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4067 :type 'number
4068 :group 'org-faces)
4070 ;;; Variables for pre-computed regular expressions, all buffer local
4072 (defvar org-drawer-regexp nil
4073 "Matches first line of a hidden block.")
4074 (make-variable-buffer-local 'org-drawer-regexp)
4075 (defvar org-todo-regexp nil
4076 "Matches any of the TODO state keywords.")
4077 (make-variable-buffer-local 'org-todo-regexp)
4078 (defvar org-not-done-regexp nil
4079 "Matches any of the TODO state keywords except the last one.")
4080 (make-variable-buffer-local 'org-not-done-regexp)
4081 (defvar org-todo-line-regexp nil
4082 "Matches a headline and puts TODO state into group 2 if present.")
4083 (make-variable-buffer-local 'org-todo-line-regexp)
4084 (defvar org-complex-heading-regexp nil
4085 "Matches a headline and puts everything into groups:
4086 group 1: the stars
4087 group 2: The todo keyword, maybe
4088 group 3: Priority cookie
4089 group 4: True headline
4090 group 5: Tags")
4091 (make-variable-buffer-local 'org-complex-heading-regexp)
4092 (defvar org-todo-line-tags-regexp nil
4093 "Matches a headline and puts TODO state into group 2 if present.
4094 Also put tags into group 4 if tags are present.")
4095 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4096 (defvar org-nl-done-regexp nil
4097 "Matches newline followed by a headline with the DONE keyword.")
4098 (make-variable-buffer-local 'org-nl-done-regexp)
4099 (defvar org-looking-at-done-regexp nil
4100 "Matches the DONE keyword a point.")
4101 (make-variable-buffer-local 'org-looking-at-done-regexp)
4102 (defvar org-ds-keyword-length 12
4103 "Maximum length of the Deadline and SCHEDULED keywords.")
4104 (make-variable-buffer-local 'org-ds-keyword-length)
4105 (defvar org-deadline-regexp nil
4106 "Matches the DEADLINE keyword.")
4107 (make-variable-buffer-local 'org-deadline-regexp)
4108 (defvar org-deadline-time-regexp nil
4109 "Matches the DEADLINE keyword together with a time stamp.")
4110 (make-variable-buffer-local 'org-deadline-time-regexp)
4111 (defvar org-deadline-line-regexp nil
4112 "Matches the DEADLINE keyword and the rest of the line.")
4113 (make-variable-buffer-local 'org-deadline-line-regexp)
4114 (defvar org-scheduled-regexp nil
4115 "Matches the SCHEDULED keyword.")
4116 (make-variable-buffer-local 'org-scheduled-regexp)
4117 (defvar org-scheduled-time-regexp nil
4118 "Matches the SCHEDULED keyword together with a time stamp.")
4119 (make-variable-buffer-local 'org-scheduled-time-regexp)
4120 (defvar org-closed-time-regexp nil
4121 "Matches the CLOSED keyword together with a time stamp.")
4122 (make-variable-buffer-local 'org-closed-time-regexp)
4124 (defvar org-keyword-time-regexp nil
4125 "Matches any of the 4 keywords, together with the time stamp.")
4126 (make-variable-buffer-local 'org-keyword-time-regexp)
4127 (defvar org-keyword-time-not-clock-regexp nil
4128 "Matches any of the 3 keywords, together with the time stamp.")
4129 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4130 (defvar org-maybe-keyword-time-regexp nil
4131 "Matches a timestamp, possibly preceeded by a keyword.")
4132 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4133 (defvar org-planning-or-clock-line-re nil
4134 "Matches a line with planning or clock info.")
4135 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4137 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4138 rear-nonsticky t mouse-map t fontified t)
4139 "Properties to remove when a string without properties is wanted.")
4141 (defsubst org-match-string-no-properties (num &optional string)
4142 (if (featurep 'xemacs)
4143 (let ((s (match-string num string)))
4144 (remove-text-properties 0 (length s) org-rm-props s)
4146 (match-string-no-properties num string)))
4148 (defsubst org-no-properties (s)
4149 (if (fboundp 'set-text-properties)
4150 (set-text-properties 0 (length s) nil s)
4151 (remove-text-properties 0 (length s) org-rm-props s))
4154 (defsubst org-get-alist-option (option key)
4155 (cond ((eq key t) t)
4156 ((eq option t) t)
4157 ((assoc key option) (cdr (assoc key option)))
4158 (t (cdr (assq 'default option)))))
4160 (defsubst org-inhibit-invisibility ()
4161 "Modified `buffer-invisibility-spec' for Emacs 21.
4162 Some ops with invisible text do not work correctly on Emacs 21. For these
4163 we turn off invisibility temporarily. Use this in a `let' form."
4164 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4166 (defsubst org-set-local (var value)
4167 "Make VAR local in current buffer and set it to VALUE."
4168 (set (make-variable-buffer-local var) value))
4170 (defsubst org-mode-p ()
4171 "Check if the current buffer is in Org-mode."
4172 (eq major-mode 'org-mode))
4174 (defsubst org-last (list)
4175 "Return the last element of LIST."
4176 (car (last list)))
4178 (defun org-let (list &rest body)
4179 (eval (cons 'let (cons list body))))
4180 (put 'org-let 'lisp-indent-function 1)
4182 (defun org-let2 (list1 list2 &rest body)
4183 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4184 (put 'org-let2 'lisp-indent-function 2)
4185 (defconst org-startup-options
4186 '(("fold" org-startup-folded t)
4187 ("overview" org-startup-folded t)
4188 ("nofold" org-startup-folded nil)
4189 ("showall" org-startup-folded nil)
4190 ("content" org-startup-folded content)
4191 ("hidestars" org-hide-leading-stars t)
4192 ("showstars" org-hide-leading-stars nil)
4193 ("odd" org-odd-levels-only t)
4194 ("oddeven" org-odd-levels-only nil)
4195 ("align" org-startup-align-all-tables t)
4196 ("noalign" org-startup-align-all-tables nil)
4197 ("customtime" org-display-custom-times t)
4198 ("logging" org-log-done t)
4199 ("logdone" org-log-done t)
4200 ("nologging" org-log-done nil)
4201 ("lognotedone" org-log-done done push)
4202 ("lognotestate" org-log-done state push)
4203 ("lognoteclock-out" org-log-done clock-out push)
4204 ("logrepeat" org-log-repeat t)
4205 ("nologrepeat" org-log-repeat nil)
4206 ("constcgs" constants-unit-system cgs)
4207 ("constSI" constants-unit-system SI))
4208 "Variable associated with STARTUP options for org-mode.
4209 Each element is a list of three items: The startup options as written
4210 in the #+STARTUP line, the corresponding variable, and the value to
4211 set this variable to if the option is found. An optional forth element PUSH
4212 means to push this value onto the list in the variable.")
4214 (defun org-set-regexps-and-options ()
4215 "Precompute regular expressions for current buffer."
4216 (when (org-mode-p)
4217 (org-set-local 'org-todo-kwd-alist nil)
4218 (org-set-local 'org-todo-key-alist nil)
4219 (org-set-local 'org-todo-key-trigger nil)
4220 (org-set-local 'org-todo-keywords-1 nil)
4221 (org-set-local 'org-done-keywords nil)
4222 (org-set-local 'org-todo-heads nil)
4223 (org-set-local 'org-todo-sets nil)
4224 (org-set-local 'org-todo-log-states nil)
4225 (let ((re (org-make-options-regexp
4226 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4227 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4228 "CONSTANTS" "PROPERTY" "DRAWERS")))
4229 (splitre "[ \t]+")
4230 kwds kws0 kwsa key value cat arch tags const links hw dws
4231 tail sep kws1 prio props drawers
4232 ex log)
4233 (save-excursion
4234 (save-restriction
4235 (widen)
4236 (goto-char (point-min))
4237 (while (re-search-forward re nil t)
4238 (setq key (match-string 1) value (org-match-string-no-properties 2))
4239 (cond
4240 ((equal key "CATEGORY")
4241 (if (string-match "[ \t]+$" value)
4242 (setq value (replace-match "" t t value)))
4243 (setq cat value))
4244 ((member key '("SEQ_TODO" "TODO"))
4245 (push (cons 'sequence (org-split-string value splitre)) kwds))
4246 ((equal key "TYP_TODO")
4247 (push (cons 'type (org-split-string value splitre)) kwds))
4248 ((equal key "TAGS")
4249 (setq tags (append tags (org-split-string value splitre))))
4250 ((equal key "COLUMNS")
4251 (org-set-local 'org-columns-default-format value))
4252 ((equal key "LINK")
4253 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4254 (push (cons (match-string 1 value)
4255 (org-trim (match-string 2 value)))
4256 links)))
4257 ((equal key "PRIORITIES")
4258 (setq prio (org-split-string value " +")))
4259 ((equal key "PROPERTY")
4260 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4261 (push (cons (match-string 1 value) (match-string 2 value))
4262 props)))
4263 ((equal key "DRAWERS")
4264 (setq drawers (org-split-string value splitre)))
4265 ((equal key "CONSTANTS")
4266 (setq const (append const (org-split-string value splitre))))
4267 ((equal key "STARTUP")
4268 (let ((opts (org-split-string value splitre))
4269 l var val)
4270 (while (setq l (pop opts))
4271 (when (setq l (assoc l org-startup-options))
4272 (setq var (nth 1 l) val (nth 2 l))
4273 (if (not (nth 3 l))
4274 (set (make-local-variable var) val)
4275 (if (not (listp (symbol-value var)))
4276 (set (make-local-variable var) nil))
4277 (set (make-local-variable var) (symbol-value var))
4278 (add-to-list var val))))))
4279 ((equal key "ARCHIVE")
4280 (string-match " *$" value)
4281 (setq arch (replace-match "" t t value))
4282 (remove-text-properties 0 (length arch)
4283 '(face t fontified t) arch)))
4285 (when cat
4286 (org-set-local 'org-category (intern cat))
4287 (push (cons "CATEGORY" cat) props))
4288 (when prio
4289 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4290 (setq prio (mapcar 'string-to-char prio))
4291 (org-set-local 'org-highest-priority (nth 0 prio))
4292 (org-set-local 'org-lowest-priority (nth 1 prio))
4293 (org-set-local 'org-default-priority (nth 2 prio)))
4294 (and props (org-set-local 'org-local-properties (nreverse props)))
4295 (and drawers (org-set-local 'org-drawers drawers))
4296 (and arch (org-set-local 'org-archive-location arch))
4297 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4298 ;; Process the TODO keywords
4299 (unless kwds
4300 ;; Use the global values as if they had been given locally.
4301 (setq kwds (default-value 'org-todo-keywords))
4302 (if (stringp (car kwds))
4303 (setq kwds (list (cons org-todo-interpretation
4304 (default-value 'org-todo-keywords)))))
4305 (setq kwds (reverse kwds)))
4306 (setq kwds (nreverse kwds))
4307 (let (inter kws kw)
4308 (while (setq kws (pop kwds))
4309 (setq inter (pop kws) sep (member "|" kws)
4310 kws0 (delete "|" (copy-sequence kws))
4311 kwsa nil
4312 kws1 (mapcar
4313 (lambda (x)
4314 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4315 (progn
4316 (setq kw (match-string 1 x)
4317 ex (and (match-end 2) (match-string 2 x))
4318 log (and ex (string-match "@" ex))
4319 key (and ex (substring ex 0 1)))
4320 (if (equal key "@") (setq key nil))
4321 (push (cons kw (and key (string-to-char key))) kwsa)
4322 (and log (push kw org-todo-log-states))
4324 (error "Invalid TODO keyword %s" x)))
4325 kws0)
4326 kwsa (if kwsa (append '((:startgroup))
4327 (nreverse kwsa)
4328 '((:endgroup))))
4329 hw (car kws1)
4330 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4331 tail (list inter hw (car dws) (org-last dws)))
4332 (add-to-list 'org-todo-heads hw 'append)
4333 ;????????????????? (setq org-todo-heads (append org-todo-heads (list hw)))
4334 (add-to-list 'org-todo-heads hw 'append)
4335 (push kws1 org-todo-sets)
4336 (setq org-done-keywords (append org-done-keywords dws nil))
4337 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4338 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4339 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4340 (setq org-todo-sets (nreverse org-todo-sets)
4341 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4342 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4343 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4344 ;; Process the constants
4345 (when const
4346 (let (e cst)
4347 (while (setq e (pop const))
4348 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4349 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4350 (setq org-table-formula-constants-local cst)))
4352 ;; Process the tags.
4353 (when tags
4354 (let (e tgs)
4355 (while (setq e (pop tags))
4356 (cond
4357 ((equal e "{") (push '(:startgroup) tgs))
4358 ((equal e "}") (push '(:endgroup) tgs))
4359 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4360 (push (cons (match-string 1 e)
4361 (string-to-char (match-string 2 e)))
4362 tgs))
4363 (t (push (list e) tgs))))
4364 (org-set-local 'org-tag-alist nil)
4365 (while (setq e (pop tgs))
4366 (or (and (stringp (car e))
4367 (assoc (car e) org-tag-alist))
4368 (push e org-tag-alist))))))
4370 ;; Compute the regular expressions and other local variables
4371 (if (not org-done-keywords)
4372 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4373 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4374 (length org-scheduled-string)))
4375 org-drawer-regexp
4376 (concat "^[ \t]*:\\("
4377 (mapconcat 'regexp-quote org-drawers "\\|")
4378 "\\):[ \t]*$")
4379 org-not-done-keywords
4380 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4381 org-todo-regexp
4382 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4383 "\\|") "\\)\\>")
4384 org-not-done-regexp
4385 (concat "\\<\\("
4386 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4387 "\\)\\>")
4388 org-todo-line-regexp
4389 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4390 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4391 "\\)\\>\\)?[ \t]*\\(.*\\)")
4392 org-complex-heading-regexp
4393 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4394 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4395 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4396 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4397 org-nl-done-regexp
4398 (concat "\n\\*+[ \t]+"
4399 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4400 "\\)" "\\>")
4401 org-todo-line-tags-regexp
4402 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4403 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4404 (org-re
4405 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4406 org-looking-at-done-regexp
4407 (concat "^" "\\(?:"
4408 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4409 "\\>")
4410 org-deadline-regexp (concat "\\<" org-deadline-string)
4411 org-deadline-time-regexp
4412 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4413 org-deadline-line-regexp
4414 (concat "\\<\\(" org-deadline-string "\\).*")
4415 org-scheduled-regexp
4416 (concat "\\<" org-scheduled-string)
4417 org-scheduled-time-regexp
4418 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4419 org-closed-time-regexp
4420 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4421 org-keyword-time-regexp
4422 (concat "\\<\\(" org-scheduled-string
4423 "\\|" org-deadline-string
4424 "\\|" org-closed-string
4425 "\\|" org-clock-string "\\)"
4426 " *[[<]\\([^]>]+\\)[]>]")
4427 org-keyword-time-not-clock-regexp
4428 (concat "\\<\\(" org-scheduled-string
4429 "\\|" org-deadline-string
4430 "\\|" org-closed-string
4431 "\\)"
4432 " *[[<]\\([^]>]+\\)[]>]")
4433 org-maybe-keyword-time-regexp
4434 (concat "\\(\\<\\(" org-scheduled-string
4435 "\\|" org-deadline-string
4436 "\\|" org-closed-string
4437 "\\|" org-clock-string "\\)\\)?"
4438 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4439 org-planning-or-clock-line-re
4440 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4441 "\\|" org-deadline-string
4442 "\\|" org-closed-string "\\|" org-clock-string
4443 "\\)\\>\\)")
4445 (org-compute-latex-and-specials-regexp)
4446 (org-set-font-lock-defaults)))
4448 (defun org-remove-keyword-keys (list)
4449 (mapcar (lambda (x)
4450 (if (string-match "(..?)$" x)
4451 (substring x 0 (match-beginning 0))
4453 list))
4455 ;;; Some variables ujsed in various places
4457 (defvar org-window-configuration nil
4458 "Used in various places to store a window configuration.")
4459 (defvar org-finish-function nil
4460 "Function to be called when `C-c C-c' is used.
4461 This is for getting out of special buffers like remember.")
4463 ;;; Foreign variables, to inform the compiler
4465 ;; XEmacs only
4466 (defvar outline-mode-menu-heading)
4467 (defvar outline-mode-menu-show)
4468 (defvar outline-mode-menu-hide)
4469 (defvar zmacs-regions) ; XEmacs regions
4470 ;; Emacs only
4471 (defvar mark-active)
4473 ;; Packages that org-mode interacts with
4474 (defvar calc-embedded-close-formula)
4475 (defvar calc-embedded-open-formula)
4476 (defvar font-lock-unfontify-region-function)
4477 (defvar org-goto-start-pos)
4478 (defvar vm-message-pointer)
4479 (defvar vm-folder-directory)
4480 (defvar wl-summary-buffer-elmo-folder)
4481 (defvar wl-summary-buffer-folder-name)
4482 (defvar gnus-other-frame-object)
4483 (defvar gnus-group-name)
4484 (defvar gnus-article-current)
4485 (defvar w3m-current-url)
4486 (defvar w3m-current-title)
4487 (defvar mh-progs)
4488 (defvar mh-current-folder)
4489 (defvar mh-show-folder-buffer)
4490 (defvar mh-index-folder)
4491 (defvar mh-searcher)
4492 (defvar calendar-mode-map)
4493 (defvar Info-current-file)
4494 (defvar Info-current-node)
4495 (defvar texmathp-why)
4496 (defvar remember-save-after-remembering)
4497 (defvar remember-data-file)
4498 (defvar remember-register)
4499 (defvar remember-buffer)
4500 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
4501 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
4502 (defvar org-latex-regexps)
4503 (defvar constants-unit-system)
4505 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4507 ;; FIXME: Occasionally check by commenting these, to make sure
4508 ;; no other functions uses these, forgetting to let-bind them.
4509 (defvar entry)
4510 (defvar state)
4511 (defvar last-state)
4512 (defvar date)
4513 (defvar description)
4515 ;; Defined somewhere in this file, but used before definition.
4516 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4517 (defvar org-agenda-buffer-name)
4518 (defvar org-agenda-undo-list)
4519 (defvar org-agenda-pending-undo-list)
4520 (defvar org-agenda-overriding-header)
4521 (defvar orgtbl-mode)
4522 (defvar org-html-entities)
4523 (defvar org-struct-menu)
4524 (defvar org-org-menu)
4525 (defvar org-tbl-menu)
4526 (defvar org-agenda-keymap)
4528 ;;;; Emacs/XEmacs compatibility
4530 ;; Overlay compatibility functions
4531 (defun org-make-overlay (beg end &optional buffer)
4532 (if (featurep 'xemacs)
4533 (make-extent beg end buffer)
4534 (make-overlay beg end buffer)))
4535 (defun org-delete-overlay (ovl)
4536 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4537 (defun org-detach-overlay (ovl)
4538 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4539 (defun org-move-overlay (ovl beg end &optional buffer)
4540 (if (featurep 'xemacs)
4541 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4542 (move-overlay ovl beg end buffer)))
4543 (defun org-overlay-put (ovl prop value)
4544 (if (featurep 'xemacs)
4545 (set-extent-property ovl prop value)
4546 (overlay-put ovl prop value)))
4547 (defun org-overlay-display (ovl text &optional face evap)
4548 "Make overlay OVL display TEXT with face FACE."
4549 (if (featurep 'xemacs)
4550 (let ((gl (make-glyph text)))
4551 (and face (set-glyph-face gl face))
4552 (set-extent-property ovl 'invisible t)
4553 (set-extent-property ovl 'end-glyph gl))
4554 (overlay-put ovl 'display text)
4555 (if face (overlay-put ovl 'face face))
4556 (if evap (overlay-put ovl 'evaporate t))))
4557 (defun org-overlay-before-string (ovl text &optional face evap)
4558 "Make overlay OVL display TEXT with face FACE."
4559 (if (featurep 'xemacs)
4560 (let ((gl (make-glyph text)))
4561 (and face (set-glyph-face gl face))
4562 (set-extent-property ovl 'begin-glyph gl))
4563 (if face (org-add-props text nil 'face face))
4564 (overlay-put ovl 'before-string text)
4565 (if evap (overlay-put ovl 'evaporate t))))
4566 (defun org-overlay-get (ovl prop)
4567 (if (featurep 'xemacs)
4568 (extent-property ovl prop)
4569 (overlay-get ovl prop)))
4570 (defun org-overlays-at (pos)
4571 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4572 (defun org-overlays-in (&optional start end)
4573 (if (featurep 'xemacs)
4574 (extent-list nil start end)
4575 (overlays-in start end)))
4576 (defun org-overlay-start (o)
4577 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4578 (defun org-overlay-end (o)
4579 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4580 (defun org-find-overlays (prop &optional pos delete)
4581 "Find all overlays specifying PROP at POS or point.
4582 If DELETE is non-nil, delete all those overlays."
4583 (let ((overlays (org-overlays-at (or pos (point))))
4584 ov found)
4585 (while (setq ov (pop overlays))
4586 (if (org-overlay-get ov prop)
4587 (if delete (org-delete-overlay ov) (push ov found))))
4588 found))
4590 ;; Region compatibility
4592 (defun org-add-hook (hook function &optional append local)
4593 "Add-hook, compatible with both Emacsen."
4594 (if (and local (featurep 'xemacs))
4595 (add-local-hook hook function append)
4596 (add-hook hook function append local)))
4598 (defvar org-ignore-region nil
4599 "To temporarily disable the active region.")
4601 (defun org-region-active-p ()
4602 "Is `transient-mark-mode' on and the region active?
4603 Works on both Emacs and XEmacs."
4604 (if org-ignore-region
4606 (if (featurep 'xemacs)
4607 (and zmacs-regions (region-active-p))
4608 (and transient-mark-mode mark-active))))
4610 ;; Invisibility compatibility
4612 (defun org-add-to-invisibility-spec (arg)
4613 "Add elements to `buffer-invisibility-spec'.
4614 See documentation for `buffer-invisibility-spec' for the kind of elements
4615 that can be added."
4616 (cond
4617 ((fboundp 'add-to-invisibility-spec)
4618 (add-to-invisibility-spec arg))
4619 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4620 (setq buffer-invisibility-spec (list arg)))
4622 (setq buffer-invisibility-spec
4623 (cons arg buffer-invisibility-spec)))))
4625 (defun org-remove-from-invisibility-spec (arg)
4626 "Remove elements from `buffer-invisibility-spec'."
4627 (if (fboundp 'remove-from-invisibility-spec)
4628 (remove-from-invisibility-spec arg)
4629 (if (consp buffer-invisibility-spec)
4630 (setq buffer-invisibility-spec
4631 (delete arg buffer-invisibility-spec)))))
4633 (defun org-in-invisibility-spec-p (arg)
4634 "Is ARG a member of `buffer-invisibility-spec'?"
4635 (if (consp buffer-invisibility-spec)
4636 (member arg buffer-invisibility-spec)
4637 nil))
4639 ;;;; Define the Org-mode
4641 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4642 (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."))
4645 ;; We use a before-change function to check if a table might need
4646 ;; an update.
4647 (defvar org-table-may-need-update t
4648 "Indicates that a table might need an update.
4649 This variable is set by `org-before-change-function'.
4650 `org-table-align' sets it back to nil.")
4651 (defvar org-mode-map)
4652 (defvar org-mode-hook nil)
4653 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4654 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4655 (defvar org-table-buffer-is-an nil)
4656 (defconst org-outline-regexp "\\*+ ")
4658 ;;;###autoload
4659 (define-derived-mode org-mode outline-mode "Org"
4660 "Outline-based notes management and organizer, alias
4661 \"Carsten's outline-mode for keeping track of everything.\"
4663 Org-mode develops organizational tasks around a NOTES file which
4664 contains information about projects as plain text. Org-mode is
4665 implemented on top of outline-mode, which is ideal to keep the content
4666 of large files well structured. It supports ToDo items, deadlines and
4667 time stamps, which magically appear in the diary listing of the Emacs
4668 calendar. Tables are easily created with a built-in table editor.
4669 Plain text URL-like links connect to websites, emails (VM), Usenet
4670 messages (Gnus), BBDB entries, and any files related to the project.
4671 For printing and sharing of notes, an Org-mode file (or a part of it)
4672 can be exported as a structured ASCII or HTML file.
4674 The following commands are available:
4676 \\{org-mode-map}"
4678 ;; Get rid of Outline menus, they are not needed
4679 ;; Need to do this here because define-derived-mode sets up
4680 ;; the keymap so late. Still, it is a waste to call this each time
4681 ;; we switch another buffer into org-mode.
4682 (if (featurep 'xemacs)
4683 (when (boundp 'outline-mode-menu-heading)
4684 ;; Assume this is Greg's port, it used easymenu
4685 (easy-menu-remove outline-mode-menu-heading)
4686 (easy-menu-remove outline-mode-menu-show)
4687 (easy-menu-remove outline-mode-menu-hide))
4688 (define-key org-mode-map [menu-bar headings] 'undefined)
4689 (define-key org-mode-map [menu-bar hide] 'undefined)
4690 (define-key org-mode-map [menu-bar show] 'undefined))
4692 (easy-menu-add org-org-menu)
4693 (easy-menu-add org-tbl-menu)
4694 (org-install-agenda-files-menu)
4695 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4696 (org-add-to-invisibility-spec '(org-cwidth))
4697 (when (featurep 'xemacs)
4698 (org-set-local 'line-move-ignore-invisible t))
4699 (org-set-local 'outline-regexp org-outline-regexp)
4700 (org-set-local 'outline-level 'org-outline-level)
4701 (when (and org-ellipsis
4702 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4703 (fboundp 'make-glyph-code))
4704 (unless org-display-table
4705 (setq org-display-table (make-display-table)))
4706 (set-display-table-slot
4707 org-display-table 4
4708 (vconcat (mapcar
4709 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4710 org-ellipsis)))
4711 (if (stringp org-ellipsis) org-ellipsis "..."))))
4712 (setq buffer-display-table org-display-table))
4713 (org-set-regexps-and-options)
4714 ;; Calc embedded
4715 (org-set-local 'calc-embedded-open-mode "# ")
4716 (modify-syntax-entry ?# "<")
4717 (modify-syntax-entry ?@ "w")
4718 (if org-startup-truncated (setq truncate-lines t))
4719 (org-set-local 'font-lock-unfontify-region-function
4720 'org-unfontify-region)
4721 ;; Activate before-change-function
4722 (org-set-local 'org-table-may-need-update t)
4723 (org-add-hook 'before-change-functions 'org-before-change-function nil
4724 'local)
4725 ;; Check for running clock before killing a buffer
4726 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4727 ;; Paragraphs and auto-filling
4728 (org-set-autofill-regexps)
4729 (setq indent-line-function 'org-indent-line-function)
4730 (org-update-radio-target-regexp)
4732 ;; Comment characters
4733 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4734 (org-set-local 'comment-padding " ")
4736 ;; Imenu
4737 (org-set-local 'imenu-create-index-function
4738 'org-imenu-get-tree)
4740 ;; Make isearch reveal context
4741 (if (or (featurep 'xemacs)
4742 (not (boundp 'outline-isearch-open-invisible-function)))
4743 ;; Emacs 21 and XEmacs make use of the hook
4744 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4745 ;; Emacs 22 deals with this through a special variable
4746 (org-set-local 'outline-isearch-open-invisible-function
4747 (lambda (&rest ignore) (org-show-context 'isearch))))
4749 ;; If empty file that did not turn on org-mode automatically, make it to.
4750 (if (and org-insert-mode-line-in-empty-file
4751 (interactive-p)
4752 (= (point-min) (point-max)))
4753 (insert "# -*- mode: org -*-\n\n"))
4755 (unless org-inhibit-startup
4756 (when org-startup-align-all-tables
4757 (let ((bmp (buffer-modified-p)))
4758 (org-table-map-tables 'org-table-align)
4759 (set-buffer-modified-p bmp)))
4760 (org-cycle-hide-drawers 'all)
4761 (cond
4762 ((eq org-startup-folded t)
4763 (org-cycle '(4)))
4764 ((eq org-startup-folded 'content)
4765 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4766 (org-cycle '(4)) (org-cycle '(4)))))))
4768 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4770 (defsubst org-call-with-arg (command arg)
4771 "Call COMMAND interactively, but pretend prefix are was ARG."
4772 (let ((current-prefix-arg arg)) (call-interactively command)))
4774 (defsubst org-current-line (&optional pos)
4775 (save-excursion
4776 (and pos (goto-char pos))
4777 ;; works also in narrowed buffer, because we start at 1, not point-min
4778 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4780 (defun org-current-time ()
4781 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4782 (if (> org-time-stamp-rounding-minutes 0)
4783 (let ((r org-time-stamp-rounding-minutes)
4784 (time (decode-time)))
4785 (apply 'encode-time
4786 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4787 (nthcdr 2 time))))
4788 (current-time)))
4790 (defun org-add-props (string plist &rest props)
4791 "Add text properties to entire string, from beginning to end.
4792 PLIST may be a list of properties, PROPS are individual properties and values
4793 that will be added to PLIST. Returns the string that was modified."
4794 (add-text-properties
4795 0 (length string) (if props (append plist props) plist) string)
4796 string)
4797 (put 'org-add-props 'lisp-indent-function 2)
4800 ;;;; Font-Lock stuff, including the activators
4802 (defvar org-mouse-map (make-sparse-keymap))
4803 (org-defkey org-mouse-map
4804 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4805 (org-defkey org-mouse-map
4806 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4807 (when org-mouse-1-follows-link
4808 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4809 (when org-tab-follows-link
4810 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4811 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4812 (when org-return-follows-link
4813 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4814 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4816 (require 'font-lock)
4818 (defconst org-non-link-chars "]\t\n\r<>")
4819 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4820 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4821 (defvar org-link-re-with-space nil
4822 "Matches a link with spaces, optional angular brackets around it.")
4823 (defvar org-link-re-with-space2 nil
4824 "Matches a link with spaces, optional angular brackets around it.")
4825 (defvar org-angle-link-re nil
4826 "Matches link with angular brackets, spaces are allowed.")
4827 (defvar org-plain-link-re nil
4828 "Matches plain link, without spaces.")
4829 (defvar org-bracket-link-regexp nil
4830 "Matches a link in double brackets.")
4831 (defvar org-bracket-link-analytic-regexp nil
4832 "Regular expression used to analyze links.
4833 Here is what the match groups contain after a match:
4834 1: http:
4835 2: http
4836 3: path
4837 4: [desc]
4838 5: desc")
4839 (defvar org-any-link-re nil
4840 "Regular expression matching any link.")
4842 (defun org-make-link-regexps ()
4843 "Update the link regular expressions.
4844 This should be called after the variable `org-link-types' has changed."
4845 (setq org-link-re-with-space
4846 (concat
4847 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4848 "\\([^" org-non-link-chars " ]"
4849 "[^" org-non-link-chars "]*"
4850 "[^" org-non-link-chars " ]\\)>?")
4851 org-link-re-with-space2
4852 (concat
4853 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4854 "\\([^" org-non-link-chars " ]"
4855 "[^]\t\n\r]*"
4856 "[^" org-non-link-chars " ]\\)>?")
4857 org-angle-link-re
4858 (concat
4859 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4860 "\\([^" org-non-link-chars " ]"
4861 "[^" org-non-link-chars "]*"
4862 "\\)>")
4863 org-plain-link-re
4864 (concat
4865 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4866 "\\([^]\t\n\r<>,;() ]+\\)")
4867 org-bracket-link-regexp
4868 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4869 org-bracket-link-analytic-regexp
4870 (concat
4871 "\\[\\["
4872 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4873 "\\([^]]+\\)"
4874 "\\]"
4875 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4876 "\\]")
4877 org-any-link-re
4878 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4879 org-angle-link-re "\\)\\|\\("
4880 org-plain-link-re "\\)")))
4882 (org-make-link-regexps)
4884 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4885 "Regular expression for fast time stamp matching.")
4886 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4887 "Regular expression for fast time stamp matching.")
4888 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4889 "Regular expression matching time strings for analysis.
4890 This one does not require the space after the date.")
4891 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4892 "Regular expression matching time strings for analysis.")
4893 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4894 "Regular expression matching time stamps, with groups.")
4895 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4896 "Regular expression matching time stamps (also [..]), with groups.")
4897 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4898 "Regular expression matching a time stamp range.")
4899 (defconst org-tr-regexp-both
4900 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4901 "Regular expression matching a time stamp range.")
4902 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4903 org-ts-regexp "\\)?")
4904 "Regular expression matching a time stamp or time stamp range.")
4905 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4906 org-ts-regexp-both "\\)?")
4907 "Regular expression matching a time stamp or time stamp range.
4908 The time stamps may be either active or inactive.")
4910 (defvar org-emph-face nil)
4912 (defun org-do-emphasis-faces (limit)
4913 "Run through the buffer and add overlays to links."
4914 (let (rtn)
4915 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4916 (if (not (= (char-after (match-beginning 3))
4917 (char-after (match-beginning 4))))
4918 (progn
4919 (setq rtn t)
4920 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4921 'face
4922 (nth 1 (assoc (match-string 3)
4923 org-emphasis-alist)))
4924 (add-text-properties (match-beginning 2) (match-end 2)
4925 '(font-lock-multiline t))
4926 (when org-hide-emphasis-markers
4927 (add-text-properties (match-end 4) (match-beginning 5)
4928 '(invisible org-link))
4929 (add-text-properties (match-beginning 3) (match-end 3)
4930 '(invisible org-link)))))
4931 (backward-char 1))
4932 rtn))
4934 (defun org-emphasize (&optional char)
4935 "Insert or change an emphasis, i.e. a font like bold or italic.
4936 If there is an active region, change that region to a new emphasis.
4937 If there is no region, just insert the marker characters and position
4938 the cursor between them.
4939 CHAR should be either the marker character, or the first character of the
4940 HTML tag associated with that emphasis. If CHAR is a space, the means
4941 to remove the emphasis of the selected region.
4942 If char is not given (for example in an interactive call) it
4943 will be prompted for."
4944 (interactive)
4945 (let ((eal org-emphasis-alist) e det
4946 (erc org-emphasis-regexp-components)
4947 (prompt "")
4948 (string "") beg end move tag c s)
4949 (if (org-region-active-p)
4950 (setq beg (region-beginning) end (region-end)
4951 string (buffer-substring beg end))
4952 (setq move t))
4954 (while (setq e (pop eal))
4955 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4956 c (aref tag 0))
4957 (push (cons c (string-to-char (car e))) det)
4958 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4959 (substring tag 1)))))
4960 (unless char
4961 (message "%s" (concat "Emphasis marker or tag:" prompt))
4962 (setq char (read-char-exclusive)))
4963 (setq char (or (cdr (assoc char det)) char))
4964 (if (equal char ?\ )
4965 (setq s "" move nil)
4966 (unless (assoc (char-to-string char) org-emphasis-alist)
4967 (error "No such emphasis marker: \"%c\"" char))
4968 (setq s (char-to-string char)))
4969 (while (and (> (length string) 1)
4970 (equal (substring string 0 1) (substring string -1))
4971 (assoc (substring string 0 1) org-emphasis-alist))
4972 (setq string (substring string 1 -1)))
4973 (setq string (concat s string s))
4974 (if beg (delete-region beg end))
4975 (unless (or (bolp)
4976 (string-match (concat "[" (nth 0 erc) "\n]")
4977 (char-to-string (char-before (point)))))
4978 (insert " "))
4979 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4980 (char-to-string (char-after (point))))
4981 (insert " ") (backward-char 1))
4982 (insert string)
4983 (and move (backward-char 1))))
4985 (defconst org-nonsticky-props
4986 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4989 (defun org-activate-plain-links (limit)
4990 "Run through the buffer and add overlays to links."
4991 (catch 'exit
4992 (let (f)
4993 (while (re-search-forward org-plain-link-re limit t)
4994 (setq f (get-text-property (match-beginning 0) 'face))
4995 (if (or (eq f 'org-tag)
4996 (and (listp f) (memq 'org-tag f)))
4998 (add-text-properties (match-beginning 0) (match-end 0)
4999 (list 'mouse-face 'highlight
5000 'rear-nonsticky org-nonsticky-props
5001 'keymap org-mouse-map
5003 (throw 'exit t))))))
5005 (defun org-activate-code (limit)
5006 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5007 (unless (get-text-property (match-beginning 1) 'face)
5008 (remove-text-properties (match-beginning 0) (match-end 0)
5009 '(display t invisible t intangible t))
5010 t)))
5012 (defun org-activate-angle-links (limit)
5013 "Run through the buffer and add overlays to links."
5014 (if (re-search-forward org-angle-link-re limit t)
5015 (progn
5016 (add-text-properties (match-beginning 0) (match-end 0)
5017 (list 'mouse-face 'highlight
5018 'rear-nonsticky org-nonsticky-props
5019 'keymap org-mouse-map
5021 t)))
5023 (defmacro org-maybe-intangible (props)
5024 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5025 In emacs 21, invisible text is not avoided by the command loop, so the
5026 intangible property is needed to make sure point skips this text.
5027 In Emacs 22, this is not necessary. The intangible text property has
5028 led to problems with flyspell. These problems are fixed in flyspell.el,
5029 but we still avoid setting the property in Emacs 22 and later.
5030 We use a macro so that the test can happen at compilation time."
5031 (if (< emacs-major-version 22)
5032 `(append '(intangible t) ,props)
5033 props))
5035 (defun org-activate-bracket-links (limit)
5036 "Run through the buffer and add overlays to bracketed links."
5037 (if (re-search-forward org-bracket-link-regexp limit t)
5038 (let* ((help (concat "LINK: "
5039 (org-match-string-no-properties 1)))
5040 ;; FIXME: above we should remove the escapes.
5041 ;; but that requires another match, protecting match data,
5042 ;; a lot of overhead for font-lock.
5043 (ip (org-maybe-intangible
5044 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5045 'keymap org-mouse-map 'mouse-face 'highlight
5046 'font-lock-multiline t 'help-echo help)))
5047 (vp (list 'rear-nonsticky org-nonsticky-props
5048 'keymap org-mouse-map 'mouse-face 'highlight
5049 ' font-lock-multiline t 'help-echo help)))
5050 ;; We need to remove the invisible property here. Table narrowing
5051 ;; may have made some of this invisible.
5052 (remove-text-properties (match-beginning 0) (match-end 0)
5053 '(invisible nil))
5054 (if (match-end 3)
5055 (progn
5056 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5057 (add-text-properties (match-beginning 3) (match-end 3) vp)
5058 (add-text-properties (match-end 3) (match-end 0) ip))
5059 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5060 (add-text-properties (match-beginning 1) (match-end 1) vp)
5061 (add-text-properties (match-end 1) (match-end 0) ip))
5062 t)))
5064 (defun org-activate-dates (limit)
5065 "Run through the buffer and add overlays to dates."
5066 (if (re-search-forward org-tsr-regexp-both limit t)
5067 (progn
5068 (add-text-properties (match-beginning 0) (match-end 0)
5069 (list 'mouse-face 'highlight
5070 'rear-nonsticky org-nonsticky-props
5071 'keymap org-mouse-map))
5072 (when org-display-custom-times
5073 (if (match-end 3)
5074 (org-display-custom-time (match-beginning 3) (match-end 3)))
5075 (org-display-custom-time (match-beginning 1) (match-end 1)))
5076 t)))
5078 (defvar org-target-link-regexp nil
5079 "Regular expression matching radio targets in plain text.")
5080 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5081 "Regular expression matching a link target.")
5082 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5083 "Regular expression matching a radio target.")
5084 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5085 "Regular expression matching any target.")
5087 (defun org-activate-target-links (limit)
5088 "Run through the buffer and add overlays to target matches."
5089 (when org-target-link-regexp
5090 (let ((case-fold-search t))
5091 (if (re-search-forward org-target-link-regexp limit t)
5092 (progn
5093 (add-text-properties (match-beginning 0) (match-end 0)
5094 (list 'mouse-face 'highlight
5095 'rear-nonsticky org-nonsticky-props
5096 'keymap org-mouse-map
5097 'help-echo "Radio target link"
5098 'org-linked-text t))
5099 t)))))
5101 (defun org-update-radio-target-regexp ()
5102 "Find all radio targets in this file and update the regular expression."
5103 (interactive)
5104 (when (memq 'radio org-activate-links)
5105 (setq org-target-link-regexp
5106 (org-make-target-link-regexp (org-all-targets 'radio)))
5107 (org-restart-font-lock)))
5109 (defun org-hide-wide-columns (limit)
5110 (let (s e)
5111 (setq s (text-property-any (point) (or limit (point-max))
5112 'org-cwidth t))
5113 (when s
5114 (setq e (next-single-property-change s 'org-cwidth))
5115 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5116 (goto-char e)
5117 t)))
5119 (defun org-restart-font-lock ()
5120 "Restart font-lock-mode, to force refontification."
5121 (when (and (boundp 'font-lock-mode) font-lock-mode)
5122 (font-lock-mode -1)
5123 (font-lock-mode 1)))
5125 (defun org-all-targets (&optional radio)
5126 "Return a list of all targets in this file.
5127 With optional argument RADIO, only find radio targets."
5128 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5129 rtn)
5130 (save-excursion
5131 (goto-char (point-min))
5132 (while (re-search-forward re nil t)
5133 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5134 rtn)))
5136 (defun org-make-target-link-regexp (targets)
5137 "Make regular expression matching all strings in TARGETS.
5138 The regular expression finds the targets also if there is a line break
5139 between words."
5140 (and targets
5141 (concat
5142 "\\<\\("
5143 (mapconcat
5144 (lambda (x)
5145 (while (string-match " +" x)
5146 (setq x (replace-match "\\s-+" t t x)))
5148 targets
5149 "\\|")
5150 "\\)\\>")))
5152 (defun org-activate-tags (limit)
5153 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5154 (progn
5155 (add-text-properties (match-beginning 1) (match-end 1)
5156 (list 'mouse-face 'highlight
5157 'rear-nonsticky org-nonsticky-props
5158 'keymap org-mouse-map))
5159 t)))
5161 (defun org-outline-level ()
5162 (save-excursion
5163 (looking-at outline-regexp)
5164 (if (match-beginning 1)
5165 (+ (org-get-string-indentation (match-string 1)) 1000)
5166 (1- (- (match-end 0) (match-beginning 0))))))
5168 (defvar org-font-lock-keywords nil)
5170 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5171 "Regular expression matching a property line.")
5173 (defun org-set-font-lock-defaults ()
5174 (let* ((em org-fontify-emphasized-text)
5175 (lk org-activate-links)
5176 (org-font-lock-extra-keywords
5177 (list
5178 ;; Headlines
5179 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5180 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5181 ;; Table lines
5182 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5183 (1 'org-table t))
5184 ;; Table internals
5185 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5186 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5187 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5188 ;; Drawers
5189 (list org-drawer-regexp '(0 'org-special-keyword t))
5190 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5191 ;; Properties
5192 (list org-property-re
5193 '(1 'org-special-keyword t)
5194 '(3 'org-property-value t))
5195 (if org-format-transports-properties-p
5196 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5197 ;; Links
5198 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5199 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5200 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5201 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5202 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5203 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5204 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5205 '(org-hide-wide-columns (0 nil append))
5206 ;; TODO lines
5207 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5208 '(1 (org-get-todo-face 1) t))
5209 ;; DONE
5210 (if org-fontify-done-headline
5211 (list (concat "^[*]+ +\\<\\("
5212 (mapconcat 'regexp-quote org-done-keywords "\\|")
5213 "\\)\\(.*\\)")
5214 '(2 'org-headline-done t))
5215 nil)
5216 ;; Priorities
5217 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5218 ;; Special keywords
5219 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5220 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5221 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5222 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5223 ;; Emphasis
5224 (if em
5225 (if (featurep 'xemacs)
5226 '(org-do-emphasis-faces (0 nil append))
5227 '(org-do-emphasis-faces)))
5228 ;; Checkboxes
5229 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5230 2 'bold prepend)
5231 (if org-provide-checkbox-statistics
5232 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5233 (0 (org-get-checkbox-statistics-face) t)))
5234 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5235 '(1 'org-archived prepend))
5236 ;; Specials
5237 '(org-do-latex-and-special-faces)
5238 ;; Code
5239 '(org-activate-code (1 'org-code t))
5240 ;; COMMENT
5241 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5242 "\\|" org-quote-string "\\)\\>")
5243 '(1 'org-special-keyword t))
5244 '("^#.*" (0 'font-lock-comment-face t))
5246 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5247 ;; Now set the full font-lock-keywords
5248 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5249 (org-set-local 'font-lock-defaults
5250 '(org-font-lock-keywords t nil nil backward-paragraph))
5251 (kill-local-variable 'font-lock-keywords) nil))
5253 (defvar org-m nil)
5254 (defvar org-l nil)
5255 (defvar org-f nil)
5256 (defun org-get-level-face (n)
5257 "Get the right face for match N in font-lock matching of healdines."
5258 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5259 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5260 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5261 (cond
5262 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5263 ((eq n 2) org-f)
5264 (t (if org-level-color-stars-only nil org-f))))
5266 (defun org-get-todo-face (kwd)
5267 "Get the right face for a TODO keyword KWD.
5268 If KWD is a number, get the corresponding match group."
5269 (if (numberp kwd) (setq kwd (match-string kwd)))
5270 (or (cdr (assoc kwd org-todo-keyword-faces))
5271 (and (member kwd org-done-keywords) 'org-done)
5272 'org-todo))
5274 (defun org-unfontify-region (beg end &optional maybe_loudly)
5275 "Remove fontification and activation overlays from links."
5276 (font-lock-default-unfontify-region beg end)
5277 (let* ((buffer-undo-list t)
5278 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5279 (inhibit-modification-hooks t)
5280 deactivate-mark buffer-file-name buffer-file-truename)
5281 (remove-text-properties beg end
5282 '(mouse-face t keymap t org-linked-text t
5283 invisible t intangible t))))
5285 ;;;; Visibility cycling, including org-goto and indirect buffer
5287 ;;; Cycling
5289 (defvar org-cycle-global-status nil)
5290 (make-variable-buffer-local 'org-cycle-global-status)
5291 (defvar org-cycle-subtree-status nil)
5292 (make-variable-buffer-local 'org-cycle-subtree-status)
5294 ;;;###autoload
5295 (defun org-cycle (&optional arg)
5296 "Visibility cycling for Org-mode.
5298 - When this function is called with a prefix argument, rotate the entire
5299 buffer through 3 states (global cycling)
5300 1. OVERVIEW: Show only top-level headlines.
5301 2. CONTENTS: Show all headlines of all levels, but no body text.
5302 3. SHOW ALL: Show everything.
5304 - When point is at the beginning of a headline, rotate the subtree started
5305 by this line through 3 different states (local cycling)
5306 1. FOLDED: Only the main headline is shown.
5307 2. CHILDREN: The main headline and the direct children are shown.
5308 From this state, you can move to one of the children
5309 and zoom in further.
5310 3. SUBTREE: Show the entire subtree, including body text.
5312 - When there is a numeric prefix, go up to a heading with level ARG, do
5313 a `show-subtree' and return to the previous cursor position. If ARG
5314 is negative, go up that many levels.
5316 - When point is not at the beginning of a headline, execute
5317 `indent-relative', like TAB normally does. See the option
5318 `org-cycle-emulate-tab' for details.
5320 - Special case: if point is at the beginning of the buffer and there is
5321 no headline in line 1, this function will act as if called with prefix arg.
5322 But only if also the variable `org-cycle-global-at-bob' is t."
5323 (interactive "P")
5324 (let* ((outline-regexp
5325 (if (and (org-mode-p) org-cycle-include-plain-lists)
5326 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5327 outline-regexp))
5328 (bob-special (and org-cycle-global-at-bob (bobp)
5329 (not (looking-at outline-regexp))))
5330 (org-cycle-hook
5331 (if bob-special
5332 (delq 'org-optimize-window-after-visibility-change
5333 (copy-sequence org-cycle-hook))
5334 org-cycle-hook))
5335 (pos (point)))
5337 (if (or bob-special (equal arg '(4)))
5338 ;; special case: use global cycling
5339 (setq arg t))
5341 (cond
5343 ((org-at-table-p 'any)
5344 ;; Enter the table or move to the next field in the table
5345 (or (org-table-recognize-table.el)
5346 (progn
5347 (if arg (org-table-edit-field t)
5348 (org-table-justify-field-maybe)
5349 (call-interactively 'org-table-next-field)))))
5351 ((eq arg t) ;; Global cycling
5353 (cond
5354 ((and (eq last-command this-command)
5355 (eq org-cycle-global-status 'overview))
5356 ;; We just created the overview - now do table of contents
5357 ;; This can be slow in very large buffers, so indicate action
5358 (message "CONTENTS...")
5359 (org-content)
5360 (message "CONTENTS...done")
5361 (setq org-cycle-global-status 'contents)
5362 (run-hook-with-args 'org-cycle-hook 'contents))
5364 ((and (eq last-command this-command)
5365 (eq org-cycle-global-status 'contents))
5366 ;; We just showed the table of contents - now show everything
5367 (show-all)
5368 (message "SHOW ALL")
5369 (setq org-cycle-global-status 'all)
5370 (run-hook-with-args 'org-cycle-hook 'all))
5373 ;; Default action: go to overview
5374 (org-overview)
5375 (message "OVERVIEW")
5376 (setq org-cycle-global-status 'overview)
5377 (run-hook-with-args 'org-cycle-hook 'overview))))
5379 ((and org-drawers org-drawer-regexp
5380 (save-excursion
5381 (beginning-of-line 1)
5382 (looking-at org-drawer-regexp)))
5383 ;; Toggle block visibility
5384 (org-flag-drawer
5385 (not (get-char-property (match-end 0) 'invisible))))
5387 ((integerp arg)
5388 ;; Show-subtree, ARG levels up from here.
5389 (save-excursion
5390 (org-back-to-heading)
5391 (outline-up-heading (if (< arg 0) (- arg)
5392 (- (funcall outline-level) arg)))
5393 (org-show-subtree)))
5395 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5396 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5397 ;; At a heading: rotate between three different views
5398 (org-back-to-heading)
5399 (let ((goal-column 0) eoh eol eos)
5400 ;; First, some boundaries
5401 (save-excursion
5402 (org-back-to-heading)
5403 (save-excursion
5404 (beginning-of-line 2)
5405 (while (and (not (eobp)) ;; this is like `next-line'
5406 (get-char-property (1- (point)) 'invisible))
5407 (beginning-of-line 2)) (setq eol (point)))
5408 (outline-end-of-heading) (setq eoh (point))
5409 (org-end-of-subtree t)
5410 (unless (eobp)
5411 (skip-chars-forward " \t\n")
5412 (beginning-of-line 1) ; in case this is an item
5414 (setq eos (1- (point))))
5415 ;; Find out what to do next and set `this-command'
5416 (cond
5417 ((= eos eoh)
5418 ;; Nothing is hidden behind this heading
5419 (message "EMPTY ENTRY")
5420 (setq org-cycle-subtree-status nil)
5421 (save-excursion
5422 (goto-char eos)
5423 (outline-next-heading)
5424 (if (org-invisible-p) (org-flag-heading nil))))
5425 ((or (>= eol eos)
5426 (not (string-match "\\S-" (buffer-substring eol eos))))
5427 ;; Entire subtree is hidden in one line: open it
5428 (org-show-entry)
5429 (show-children)
5430 (message "CHILDREN")
5431 (save-excursion
5432 (goto-char eos)
5433 (outline-next-heading)
5434 (if (org-invisible-p) (org-flag-heading nil)))
5435 (setq org-cycle-subtree-status 'children)
5436 (run-hook-with-args 'org-cycle-hook 'children))
5437 ((and (eq last-command this-command)
5438 (eq org-cycle-subtree-status 'children))
5439 ;; We just showed the children, now show everything.
5440 (org-show-subtree)
5441 (message "SUBTREE")
5442 (setq org-cycle-subtree-status 'subtree)
5443 (run-hook-with-args 'org-cycle-hook 'subtree))
5445 ;; Default action: hide the subtree.
5446 (hide-subtree)
5447 (message "FOLDED")
5448 (setq org-cycle-subtree-status 'folded)
5449 (run-hook-with-args 'org-cycle-hook 'folded)))))
5451 ;; TAB emulation
5452 (buffer-read-only (org-back-to-heading))
5454 ((org-try-cdlatex-tab))
5456 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5457 (or (not (bolp))
5458 (not (looking-at outline-regexp))))
5459 (call-interactively (global-key-binding "\t")))
5461 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5462 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5463 (or (and (eq org-cycle-emulate-tab 'white)
5464 (= (match-end 0) (point-at-eol)))
5465 (and (eq org-cycle-emulate-tab 'whitestart)
5466 (>= (match-end 0) pos))))
5468 (eq org-cycle-emulate-tab t))
5469 ; (if (and (looking-at "[ \n\r\t]")
5470 ; (string-match "^[ \t]*$" (buffer-substring
5471 ; (point-at-bol) (point))))
5472 ; (progn
5473 ; (beginning-of-line 1)
5474 ; (and (looking-at "[ \t]+") (replace-match ""))))
5475 (call-interactively (global-key-binding "\t")))
5477 (t (save-excursion
5478 (org-back-to-heading)
5479 (org-cycle))))))
5481 ;;;###autoload
5482 (defun org-global-cycle (&optional arg)
5483 "Cycle the global visibility. For details see `org-cycle'."
5484 (interactive "P")
5485 (let ((org-cycle-include-plain-lists
5486 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5487 (if (integerp arg)
5488 (progn
5489 (show-all)
5490 (hide-sublevels arg)
5491 (setq org-cycle-global-status 'contents))
5492 (org-cycle '(4)))))
5494 (defun org-overview ()
5495 "Switch to overview mode, shoing only top-level headlines.
5496 Really, this shows all headlines with level equal or greater than the level
5497 of the first headline in the buffer. This is important, because if the
5498 first headline is not level one, then (hide-sublevels 1) gives confusing
5499 results."
5500 (interactive)
5501 (let ((level (save-excursion
5502 (goto-char (point-min))
5503 (if (re-search-forward (concat "^" outline-regexp) nil t)
5504 (progn
5505 (goto-char (match-beginning 0))
5506 (funcall outline-level))))))
5507 (and level (hide-sublevels level))))
5509 (defun org-content (&optional arg)
5510 "Show all headlines in the buffer, like a table of contents.
5511 With numerical argument N, show content up to level N."
5512 (interactive "P")
5513 (save-excursion
5514 ;; Visit all headings and show their offspring
5515 (and (integerp arg) (org-overview))
5516 (goto-char (point-max))
5517 (catch 'exit
5518 (while (and (progn (condition-case nil
5519 (outline-previous-visible-heading 1)
5520 (error (goto-char (point-min))))
5522 (looking-at outline-regexp))
5523 (if (integerp arg)
5524 (show-children (1- arg))
5525 (show-branches))
5526 (if (bobp) (throw 'exit nil))))))
5529 (defun org-optimize-window-after-visibility-change (state)
5530 "Adjust the window after a change in outline visibility.
5531 This function is the default value of the hook `org-cycle-hook'."
5532 (when (get-buffer-window (current-buffer))
5533 (cond
5534 ; ((eq state 'overview) (org-first-headline-recenter 1))
5535 ; ((eq state 'overview) (org-beginning-of-line))
5536 ((eq state 'content) nil)
5537 ((eq state 'all) nil)
5538 ((eq state 'folded) nil)
5539 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5540 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5543 (defun org-cycle-show-empty-lines (state)
5544 "Show empty lines above all visible headlines.
5545 The region to be covered depends on STATE when called through
5546 `org-cycle-hook'. Lisp program can use t for STATE to get the
5547 entire buffer covered. Note that an empty line is only shown if there
5548 are at least `org-cycle-separator-lines' empty lines before the headeline."
5549 (when (> org-cycle-separator-lines 0)
5550 (save-excursion
5551 (let* ((n org-cycle-separator-lines)
5552 (re (cond
5553 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5554 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5555 (t (let ((ns (number-to-string (- n 2))))
5556 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5557 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5558 beg end)
5559 (cond
5560 ((memq state '(overview contents t))
5561 (setq beg (point-min) end (point-max)))
5562 ((memq state '(children folded))
5563 (setq beg (point) end (progn (org-end-of-subtree t t)
5564 (beginning-of-line 2)
5565 (point)))))
5566 (when beg
5567 (goto-char beg)
5568 (while (re-search-forward re end t)
5569 (if (not (get-char-property (match-end 1) 'invisible))
5570 (outline-flag-region
5571 (match-beginning 1) (match-end 1) nil)))))))
5572 ;; Never hide empty lines at the end of the file.
5573 (save-excursion
5574 (goto-char (point-max))
5575 (outline-previous-heading)
5576 (outline-end-of-heading)
5577 (if (and (looking-at "[ \t\n]+")
5578 (= (match-end 0) (point-max)))
5579 (outline-flag-region (point) (match-end 0) nil))))
5581 (defun org-subtree-end-visible-p ()
5582 "Is the end of the current subtree visible?"
5583 (pos-visible-in-window-p
5584 (save-excursion (org-end-of-subtree t) (point))))
5586 (defun org-first-headline-recenter (&optional N)
5587 "Move cursor to the first headline and recenter the headline.
5588 Optional argument N means, put the headline into the Nth line of the window."
5589 (goto-char (point-min))
5590 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5591 (beginning-of-line)
5592 (recenter (prefix-numeric-value N))))
5594 ;;; Org-goto
5596 (defvar org-goto-window-configuration nil)
5597 (defvar org-goto-marker nil)
5598 (defvar org-goto-map
5599 (let ((map (make-sparse-keymap)))
5600 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5601 (while (setq cmd (pop cmds))
5602 (substitute-key-definition cmd cmd map global-map)))
5603 (suppress-keymap map)
5604 (org-defkey map "\C-m" 'org-goto-ret)
5605 (org-defkey map [(left)] 'org-goto-left)
5606 (org-defkey map [(right)] 'org-goto-right)
5607 (org-defkey map [(?q)] 'org-goto-quit)
5608 (org-defkey map [(control ?g)] 'org-goto-quit)
5609 (org-defkey map "\C-i" 'org-cycle)
5610 (org-defkey map [(tab)] 'org-cycle)
5611 (org-defkey map [(down)] 'outline-next-visible-heading)
5612 (org-defkey map [(up)] 'outline-previous-visible-heading)
5613 (org-defkey map "n" 'outline-next-visible-heading)
5614 (org-defkey map "p" 'outline-previous-visible-heading)
5615 (org-defkey map "f" 'outline-forward-same-level)
5616 (org-defkey map "b" 'outline-backward-same-level)
5617 (org-defkey map "u" 'outline-up-heading)
5618 (org-defkey map "/" 'org-occur)
5619 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5620 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5621 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5622 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5623 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5624 map))
5626 (defconst org-goto-help
5627 "Browse copy of buffer to find location or copy text.
5628 RET=jump to location [Q]uit and return to previous location
5629 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur"
5632 (defun org-goto ()
5633 "Look up a different location in the current file, keeping current visibility.
5635 When you want look-up or go to a different location in a document, the
5636 fastest way is often to fold the entire buffer and then dive into the tree.
5637 This method has the disadvantage, that the previous location will be folded,
5638 which may not be what you want.
5640 This command works around this by showing a copy of the current buffer
5641 in an indirect buffer, in overview mode. You can dive into the tree in
5642 that copy, use org-occur and incremental search to find a location.
5643 When pressing RET or `Q', the command returns to the original buffer in
5644 which the visibility is still unchanged. After RET is will also jump to
5645 the location selected in the indirect buffer and expose the
5646 the headline hierarchy above."
5647 (interactive)
5648 (let* ((org-goto-start-pos (point))
5649 (selected-point
5650 (car (org-get-location (current-buffer) org-goto-help))))
5651 (if selected-point
5652 (progn
5653 (org-mark-ring-push org-goto-start-pos)
5654 (goto-char selected-point)
5655 (if (or (org-invisible-p) (org-invisible-p2))
5656 (org-show-context 'org-goto)))
5657 (message "Quit"))))
5659 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5660 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5662 (defun org-get-location (buf help)
5663 "Let the user select a location in the Org-mode buffer BUF.
5664 This function uses a recursive edit. It returns the selected position
5665 or nil."
5666 (let (org-goto-selected-point org-goto-exit-command)
5667 (save-excursion
5668 (save-window-excursion
5669 (delete-other-windows)
5670 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5671 (switch-to-buffer
5672 (condition-case nil
5673 (make-indirect-buffer (current-buffer) "*org-goto*")
5674 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5675 (with-output-to-temp-buffer "*Help*"
5676 (princ help))
5677 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5678 (setq buffer-read-only nil)
5679 (let ((org-startup-truncated t)
5680 (org-startup-folded nil)
5681 (org-startup-align-all-tables nil))
5682 (org-mode)
5683 (org-overview))
5684 (setq buffer-read-only t)
5685 (if (and (boundp 'org-goto-start-pos)
5686 (integer-or-marker-p org-goto-start-pos))
5687 (let ((org-show-hierarchy-above t)
5688 (org-show-siblings t)
5689 (org-show-following-heading t))
5690 (goto-char org-goto-start-pos)
5691 (and (org-invisible-p) (org-show-context)))
5692 (goto-char (point-min)))
5693 (org-beginning-of-line)
5694 (message "Select location and press RET")
5695 ;; now we make sure that during selection, ony very few keys work
5696 ;; and that it is impossible to switch to another window.
5697 ; (let ((gm (current-global-map))
5698 ; (overriding-local-map org-goto-map))
5699 ; (unwind-protect
5700 ; (progn
5701 ; (use-global-map org-goto-map)
5702 ; (recursive-edit))
5703 ; (use-global-map gm)))
5704 (use-local-map org-goto-map)
5705 (recursive-edit)
5707 (kill-buffer "*org-goto*")
5708 (cons org-goto-selected-point org-goto-exit-command)))
5710 (defun org-goto-ret (&optional arg)
5711 "Finish `org-goto' by going to the new location."
5712 (interactive "P")
5713 (setq org-goto-selected-point (point)
5714 org-goto-exit-command 'return)
5715 (throw 'exit nil))
5717 (defun org-goto-left ()
5718 "Finish `org-goto' by going to the new location."
5719 (interactive)
5720 (if (org-on-heading-p)
5721 (progn
5722 (beginning-of-line 1)
5723 (setq org-goto-selected-point (point)
5724 org-goto-exit-command 'left)
5725 (throw 'exit nil))
5726 (error "Not on a heading")))
5728 (defun org-goto-right ()
5729 "Finish `org-goto' by going to the new location."
5730 (interactive)
5731 (if (org-on-heading-p)
5732 (progn
5733 (setq org-goto-selected-point (point)
5734 org-goto-exit-command 'right)
5735 (throw 'exit nil))
5736 (error "Not on a heading")))
5738 (defun org-goto-quit ()
5739 "Finish `org-goto' without cursor motion."
5740 (interactive)
5741 (setq org-goto-selected-point nil)
5742 (setq org-goto-exit-command 'quit)
5743 (throw 'exit nil))
5745 ;;; Indirect buffer display of subtrees
5747 (defvar org-indirect-dedicated-frame nil
5748 "This is the frame being used for indirect tree display.")
5749 (defvar org-last-indirect-buffer nil)
5751 (defun org-tree-to-indirect-buffer (&optional arg)
5752 "Create indirect buffer and narrow it to current subtree.
5753 With numerical prefix ARG, go up to this level and then take that tree.
5754 If ARG is negative, go up that many levels.
5755 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5756 indirect buffer previously made with this command, to avoid proliferation of
5757 indirect buffers. However, when you call the command with a `C-u' prefix, or
5758 when `org-indirect-buffer-display' is `new-frame', the last buffer
5759 is kept so that you can work with several indirect buffers at the same time.
5760 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5761 requests that a new frame be made for the new buffer, so that the dedicated
5762 frame is not changed."
5763 (interactive "P")
5764 (let ((cbuf (current-buffer))
5765 (cwin (selected-window))
5766 (pos (point))
5767 beg end level heading ibuf)
5768 (save-excursion
5769 (org-back-to-heading t)
5770 (when (numberp arg)
5771 (setq level (org-outline-level))
5772 (if (< arg 0) (setq arg (+ level arg)))
5773 (while (> (setq level (org-outline-level)) arg)
5774 (outline-up-heading 1 t)))
5775 (setq beg (point)
5776 heading (org-get-heading))
5777 (org-end-of-subtree t) (setq end (point)))
5778 (if (and (buffer-live-p org-last-indirect-buffer)
5779 (not (eq org-indirect-buffer-display 'new-frame))
5780 (not arg))
5781 (kill-buffer org-last-indirect-buffer))
5782 (setq ibuf (org-get-indirect-buffer cbuf)
5783 org-last-indirect-buffer ibuf)
5784 (cond
5785 ((or (eq org-indirect-buffer-display 'new-frame)
5786 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5787 (select-frame (make-frame))
5788 (delete-other-windows)
5789 (switch-to-buffer ibuf)
5790 (org-set-frame-title heading))
5791 ((eq org-indirect-buffer-display 'dedicated-frame)
5792 (raise-frame
5793 (select-frame (or (and org-indirect-dedicated-frame
5794 (frame-live-p org-indirect-dedicated-frame)
5795 org-indirect-dedicated-frame)
5796 (setq org-indirect-dedicated-frame (make-frame)))))
5797 (delete-other-windows)
5798 (switch-to-buffer ibuf)
5799 (org-set-frame-title (concat "Indirect: " heading)))
5800 ((eq org-indirect-buffer-display 'current-window)
5801 (switch-to-buffer ibuf))
5802 ((eq org-indirect-buffer-display 'other-window)
5803 (pop-to-buffer ibuf))
5804 (t (error "Invalid value.")))
5805 (if (featurep 'xemacs)
5806 (save-excursion (org-mode) (turn-on-font-lock)))
5807 (narrow-to-region beg end)
5808 (show-all)
5809 (goto-char pos)
5810 (and (window-live-p cwin) (select-window cwin))))
5812 (defun org-get-indirect-buffer (&optional buffer)
5813 (setq buffer (or buffer (current-buffer)))
5814 (let ((n 1) (base (buffer-name buffer)) bname)
5815 (while (buffer-live-p
5816 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5817 (setq n (1+ n)))
5818 (condition-case nil
5819 (make-indirect-buffer buffer bname 'clone)
5820 (error (make-indirect-buffer buffer bname)))))
5822 (defun org-set-frame-title (title)
5823 "Set the title of the current frame to the string TITLE."
5824 ;; FIXME: how to name a single frame in XEmacs???
5825 (unless (featurep 'xemacs)
5826 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5828 ;;;; Structure editing
5830 ;;; Inserting headlines
5832 (defun org-insert-heading (&optional force-heading)
5833 "Insert a new heading or item with same depth at point.
5834 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5835 If point is at the beginning of a headline, insert a sibling before the
5836 current headline. If point is in the middle of a headline, split the headline
5837 at that position and make the rest of the headline part of the sibling below
5838 the current headline."
5839 (interactive "P")
5840 (if (= (buffer-size) 0)
5841 (insert "\n* ")
5842 (when (or force-heading (not (org-insert-item)))
5843 (let* ((head (save-excursion
5844 (condition-case nil
5845 (progn
5846 (org-back-to-heading)
5847 (match-string 0))
5848 (error "*"))))
5849 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5850 pos)
5851 (cond
5852 ((and (org-on-heading-p) (bolp)
5853 (or (bobp)
5854 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5855 (open-line (if blank 2 1)))
5856 ((and (bolp)
5857 (or (bobp)
5858 (save-excursion
5859 (backward-char 1) (not (org-invisible-p)))))
5860 nil)
5861 (t (newline (if blank 2 1))))
5862 (insert head) (just-one-space)
5863 (setq pos (point))
5864 (end-of-line 1)
5865 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5866 (run-hooks 'org-insert-heading-hook)))))
5868 (defun org-insert-heading-after-current ()
5869 "Insert a new heading with same level as current, after current subtree."
5870 (interactive)
5871 (org-back-to-heading)
5872 (org-insert-heading)
5873 (org-move-subtree-down)
5874 (end-of-line 1))
5876 (defun org-insert-todo-heading (arg)
5877 "Insert a new heading with the same level and TODO state as current heading.
5878 If the heading has no TODO state, or if the state is DONE, use the first
5879 state (TODO by default). Also with prefix arg, force first state."
5880 (interactive "P")
5881 (when (not (org-insert-item 'checkbox))
5882 (org-insert-heading)
5883 (save-excursion
5884 (org-back-to-heading)
5885 (outline-previous-heading)
5886 (looking-at org-todo-line-regexp))
5887 (if (or arg
5888 (not (match-beginning 2))
5889 (member (match-string 2) org-done-keywords))
5890 (insert (car org-todo-keywords-1) " ")
5891 (insert (match-string 2) " "))))
5893 (defun org-insert-subheading (arg)
5894 "Insert a new subheading and demote it.
5895 Works for outline headings and for plain lists alike."
5896 (interactive "P")
5897 (org-insert-heading arg)
5898 (cond
5899 ((org-on-heading-p) (org-do-demote))
5900 ((org-at-item-p) (org-indent-item 1))))
5902 (defun org-insert-todo-subheading (arg)
5903 "Insert a new subheading with TODO keyword or checkbox and demote it.
5904 Works for outline headings and for plain lists alike."
5905 (interactive "P")
5906 (org-insert-todo-heading arg)
5907 (cond
5908 ((org-on-heading-p) (org-do-demote))
5909 ((org-at-item-p) (org-indent-item 1))))
5911 ;;; Promotion and Demotion
5913 (defun org-promote-subtree ()
5914 "Promote the entire subtree.
5915 See also `org-promote'."
5916 (interactive)
5917 (save-excursion
5918 (org-map-tree 'org-promote))
5919 (org-fix-position-after-promote))
5921 (defun org-demote-subtree ()
5922 "Demote the entire subtree. See `org-demote'.
5923 See also `org-promote'."
5924 (interactive)
5925 (save-excursion
5926 (org-map-tree 'org-demote))
5927 (org-fix-position-after-promote))
5930 (defun org-do-promote ()
5931 "Promote the current heading higher up the tree.
5932 If the region is active in `transient-mark-mode', promote all headings
5933 in the region."
5934 (interactive)
5935 (save-excursion
5936 (if (org-region-active-p)
5937 (org-map-region 'org-promote (region-beginning) (region-end))
5938 (org-promote)))
5939 (org-fix-position-after-promote))
5941 (defun org-do-demote ()
5942 "Demote the current heading lower down the tree.
5943 If the region is active in `transient-mark-mode', demote all headings
5944 in the region."
5945 (interactive)
5946 (save-excursion
5947 (if (org-region-active-p)
5948 (org-map-region 'org-demote (region-beginning) (region-end))
5949 (org-demote)))
5950 (org-fix-position-after-promote))
5952 (defun org-fix-position-after-promote ()
5953 "Make sure that after pro/demotion cursor position is right."
5954 (let ((pos (point)))
5955 (when (save-excursion
5956 (beginning-of-line 1)
5957 (looking-at org-todo-line-regexp)
5958 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5959 (cond ((eobp) (insert " "))
5960 ((eolp) (insert " "))
5961 ((equal (char-after) ?\ ) (forward-char 1))))))
5963 (defun org-reduced-level (l)
5964 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5966 (defun org-get-legal-level (level &optional change)
5967 "Rectify a level change under the influence of `org-odd-levels-only'
5968 LEVEL is a current level, CHANGE is by how much the level should be
5969 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5970 even level numbers will become the next higher odd number."
5971 (if org-odd-levels-only
5972 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5973 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5974 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5975 (max 1 (+ level change))))
5977 (defun org-promote ()
5978 "Promote the current heading higher up the tree.
5979 If the region is active in `transient-mark-mode', promote all headings
5980 in the region."
5981 (org-back-to-heading t)
5982 (let* ((level (save-match-data (funcall outline-level)))
5983 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
5984 (diff (abs (- level (length up-head) -1))))
5985 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5986 (replace-match up-head nil t)
5987 ;; Fixup tag positioning
5988 (and org-auto-align-tags (org-set-tags nil t))
5989 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5991 (defun org-demote ()
5992 "Demote the current heading lower down the tree.
5993 If the region is active in `transient-mark-mode', demote all headings
5994 in the region."
5995 (org-back-to-heading t)
5996 (let* ((level (save-match-data (funcall outline-level)))
5997 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
5998 (diff (abs (- level (length down-head) -1))))
5999 (replace-match down-head nil t)
6000 ;; Fixup tag positioning
6001 (and org-auto-align-tags (org-set-tags nil t))
6002 (if org-adapt-indentation (org-fixup-indentation diff))))
6004 (defun org-map-tree (fun)
6005 "Call FUN for every heading underneath the current one."
6006 (org-back-to-heading)
6007 (let ((level (funcall outline-level)))
6008 (save-excursion
6009 (funcall fun)
6010 (while (and (progn
6011 (outline-next-heading)
6012 (> (funcall outline-level) level))
6013 (not (eobp)))
6014 (funcall fun)))))
6016 (defun org-map-region (fun beg end)
6017 "Call FUN for every heading between BEG and END."
6018 (let ((org-ignore-region t))
6019 (save-excursion
6020 (setq end (copy-marker end))
6021 (goto-char beg)
6022 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6023 (< (point) end))
6024 (funcall fun))
6025 (while (and (progn
6026 (outline-next-heading)
6027 (< (point) end))
6028 (not (eobp)))
6029 (funcall fun)))))
6031 (defun org-fixup-indentation (diff)
6032 "Change the indentation in the current entry by DIFF
6033 However, if any line in the current entry has no indentation, or if it
6034 would end up with no indentation after the change, nothing at all is done."
6035 (save-excursion
6036 (let ((end (save-excursion (outline-next-heading)
6037 (point-marker)))
6038 (prohibit (if (> diff 0)
6039 "^\\S-"
6040 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6041 col)
6042 (unless (save-excursion (end-of-line 1)
6043 (re-search-forward prohibit end t))
6044 (while (and (< (point) end)
6045 (re-search-forward "^[ \t]+" end t))
6046 (goto-char (match-end 0))
6047 (setq col (current-column))
6048 (if (< diff 0) (replace-match ""))
6049 (indent-to (+ diff col))))
6050 (move-marker end nil))))
6052 (defun org-convert-to-odd-levels ()
6053 "Convert an org-mode file with all levels allowed to one with odd levels.
6054 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6055 level 5 etc."
6056 (interactive)
6057 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6058 (let ((org-odd-levels-only nil) n)
6059 (save-excursion
6060 (goto-char (point-min))
6061 (while (re-search-forward "^\\*\\*+ " nil t)
6062 (setq n (- (length (match-string 0)) 2))
6063 (while (>= (setq n (1- n)) 0)
6064 (org-demote))
6065 (end-of-line 1))))))
6068 (defun org-convert-to-oddeven-levels ()
6069 "Convert an org-mode file with only odd levels to one with odd and even levels.
6070 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6071 section with an even level, conversion would destroy the structure of the file. An error
6072 is signaled in this case."
6073 (interactive)
6074 (goto-char (point-min))
6075 ;; First check if there are no even levels
6076 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6077 (org-show-context t)
6078 (error "Not all levels are odd in this file. Conversion not possible."))
6079 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6080 (let ((org-odd-levels-only nil) n)
6081 (save-excursion
6082 (goto-char (point-min))
6083 (while (re-search-forward "^\\*\\*+ " nil t)
6084 (setq n (/ (1- (length (match-string 0))) 2))
6085 (while (>= (setq n (1- n)) 0)
6086 (org-promote))
6087 (end-of-line 1))))))
6089 (defun org-tr-level (n)
6090 "Make N odd if required."
6091 (if org-odd-levels-only (1+ (/ n 2)) n))
6093 ;;; Vertical tree motion, cutting and pasting of subtrees
6095 (defun org-move-subtree-up (&optional arg)
6096 "Move the current subtree up past ARG headlines of the same level."
6097 (interactive "p")
6098 (org-move-subtree-down (- (prefix-numeric-value arg))))
6100 (defun org-move-subtree-down (&optional arg)
6101 "Move the current subtree down past ARG headlines of the same level."
6102 (interactive "p")
6103 (setq arg (prefix-numeric-value arg))
6104 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6105 'outline-get-last-sibling))
6106 (ins-point (make-marker))
6107 (cnt (abs arg))
6108 beg end txt folded)
6109 ;; Select the tree
6110 (org-back-to-heading)
6111 (setq beg (point))
6112 (save-match-data
6113 (save-excursion (outline-end-of-heading)
6114 (setq folded (org-invisible-p)))
6115 (outline-end-of-subtree))
6116 (outline-next-heading)
6117 (setq end (point))
6118 ;; Find insertion point, with error handling
6119 (goto-char beg)
6120 (while (> cnt 0)
6121 (or (and (funcall movfunc) (looking-at outline-regexp))
6122 (progn (goto-char beg)
6123 (error "Cannot move past superior level or buffer limit")))
6124 (setq cnt (1- cnt)))
6125 (if (> arg 0)
6126 ;; Moving forward - still need to move over subtree
6127 (progn (outline-end-of-subtree)
6128 (outline-next-heading)
6129 (if (not (or (looking-at (concat "^" outline-regexp))
6130 (bolp)))
6131 (newline))))
6132 (move-marker ins-point (point))
6133 (setq txt (buffer-substring beg end))
6134 (delete-region beg end)
6135 (insert txt)
6136 (or (bolp) (insert "\n"))
6137 (goto-char ins-point)
6138 (if folded (hide-subtree))
6139 (move-marker ins-point nil)))
6141 (defvar org-subtree-clip ""
6142 "Clipboard for cut and paste of subtrees.
6143 This is actually only a copy of the kill, because we use the normal kill
6144 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6146 (defvar org-subtree-clip-folded nil
6147 "Was the last copied subtree folded?
6148 This is used to fold the tree back after pasting.")
6150 (defun org-cut-subtree (&optional n)
6151 "Cut the current subtree into the clipboard.
6152 With prefix arg N, cut this many sequential subtrees.
6153 This is a short-hand for marking the subtree and then cutting it."
6154 (interactive "p")
6155 (org-copy-subtree n 'cut))
6157 (defun org-copy-subtree (&optional n cut)
6158 "Cut the current subtree into the clipboard.
6159 With prefix arg N, cut this many sequential subtrees.
6160 This is a short-hand for marking the subtree and then copying it.
6161 If CUT is non-nil, actually cut the subtree."
6162 (interactive "p")
6163 (let (beg end folded)
6164 (if (interactive-p)
6165 (org-back-to-heading nil) ; take what looks like a subtree
6166 (org-back-to-heading t)) ; take what is really there
6167 (setq beg (point))
6168 (save-match-data
6169 (save-excursion (outline-end-of-heading)
6170 (setq folded (org-invisible-p)))
6171 (condition-case nil
6172 (outline-forward-same-level (1- n))
6173 (error nil))
6174 (org-end-of-subtree t t))
6175 (setq end (point))
6176 (goto-char beg)
6177 (when (> end beg)
6178 (setq org-subtree-clip-folded folded)
6179 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6180 (setq org-subtree-clip (current-kill 0))
6181 (message "%s: Subtree(s) with %d characters"
6182 (if cut "Cut" "Copied")
6183 (length org-subtree-clip)))))
6185 (defun org-paste-subtree (&optional level tree)
6186 "Paste the clipboard as a subtree, with modification of headline level.
6187 The entire subtree is promoted or demoted in order to match a new headline
6188 level. By default, the new level is derived from the visible headings
6189 before and after the insertion point, and taken to be the inferior headline
6190 level of the two. So if the previous visible heading is level 3 and the
6191 next is level 4 (or vice versa), level 4 will be used for insertion.
6192 This makes sure that the subtree remains an independent subtree and does
6193 not swallow low level entries.
6195 You can also force a different level, either by using a numeric prefix
6196 argument, or by inserting the heading marker by hand. For example, if the
6197 cursor is after \"*****\", then the tree will be shifted to level 5.
6199 If you want to insert the tree as is, just use \\[yank].
6201 If optional TREE is given, use this text instead of the kill ring."
6202 (interactive "P")
6203 (unless (org-kill-is-subtree-p tree)
6204 (error
6205 (substitute-command-keys
6206 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6207 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6208 (^re (concat "^\\(" outline-regexp "\\)"))
6209 (re (concat "\\(" outline-regexp "\\)"))
6210 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6212 (old-level (if (string-match ^re txt)
6213 (- (match-end 0) (match-beginning 0) 1)
6214 -1))
6215 (force-level (cond (level (prefix-numeric-value level))
6216 ((string-match
6217 ^re_ (buffer-substring (point-at-bol) (point)))
6218 (- (match-end 1) (match-beginning 1)))
6219 (t nil)))
6220 (previous-level (save-excursion
6221 (condition-case nil
6222 (progn
6223 (outline-previous-visible-heading 1)
6224 (if (looking-at re)
6225 (- (match-end 0) (match-beginning 0) 1)
6227 (error 1))))
6228 (next-level (save-excursion
6229 (condition-case nil
6230 (progn
6231 (or (looking-at outline-regexp)
6232 (outline-next-visible-heading 1))
6233 (if (looking-at re)
6234 (- (match-end 0) (match-beginning 0) 1)
6236 (error 1))))
6237 (new-level (or force-level (max previous-level next-level)))
6238 (shift (if (or (= old-level -1)
6239 (= new-level -1)
6240 (= old-level new-level))
6242 (- new-level old-level)))
6243 (delta (if (> shift 0) -1 1))
6244 (func (if (> shift 0) 'org-demote 'org-promote))
6245 (org-odd-levels-only nil)
6246 beg end)
6247 ;; Remove the forced level indicator
6248 (if force-level
6249 (delete-region (point-at-bol) (point)))
6250 ;; Paste
6251 (beginning-of-line 1)
6252 (setq beg (point))
6253 (insert txt)
6254 (unless (string-match "\n\\'" txt) (insert "\n"))
6255 (setq end (point))
6256 (goto-char beg)
6257 ;; Shift if necessary
6258 (unless (= shift 0)
6259 (save-restriction
6260 (narrow-to-region beg end)
6261 (while (not (= shift 0))
6262 (org-map-region func (point-min) (point-max))
6263 (setq shift (+ delta shift)))
6264 (goto-char (point-min))))
6265 (when (interactive-p)
6266 (message "Clipboard pasted as level %d subtree" new-level))
6267 (if (and kill-ring
6268 (eq org-subtree-clip (current-kill 0))
6269 org-subtree-clip-folded)
6270 ;; The tree was folded before it was killed/copied
6271 (hide-subtree))))
6273 (defun org-kill-is-subtree-p (&optional txt)
6274 "Check if the current kill is an outline subtree, or a set of trees.
6275 Returns nil if kill does not start with a headline, or if the first
6276 headline level is not the largest headline level in the tree.
6277 So this will actually accept several entries of equal levels as well,
6278 which is OK for `org-paste-subtree'.
6279 If optional TXT is given, check this string instead of the current kill."
6280 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6281 (start-level (and kill
6282 (string-match (concat "\\`" org-outline-regexp) kill)
6283 (- (match-end 0) (match-beginning 0) 1)))
6284 (re (concat "^" org-outline-regexp))
6285 (start 1))
6286 (if (not start-level)
6287 (progn
6288 nil) ;; does not even start with a heading
6289 (catch 'exit
6290 (while (setq start (string-match re kill (1+ start)))
6291 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6292 (throw 'exit nil)))
6293 t))))
6295 (defun org-narrow-to-subtree ()
6296 "Narrow buffer to the current subtree."
6297 (interactive)
6298 (save-excursion
6299 (narrow-to-region
6300 (progn (org-back-to-heading) (point))
6301 (progn (org-end-of-subtree t t) (point)))))
6304 ;;; Outline Sorting
6306 (defun org-sort (with-case)
6307 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6308 Optional argument WITH-CASE means sort case-sensitively."
6309 (interactive "P")
6310 (if (org-at-table-p)
6311 (org-call-with-arg 'org-table-sort-lines with-case)
6312 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6314 (defvar org-priority-regexp) ; defined later in the file
6316 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6317 "Sort entries on a certain level of an outline tree.
6318 If there is an active region, the entries in the region are sorted.
6319 Else, if the cursor is before the first entry, sort the top-level items.
6320 Else, the children of the entry at point are sorted.
6322 Sorting can be alphabetically, numerically, and by date/time as given by
6323 the first time stamp in the entry. The command prompts for the sorting
6324 type unless it has been given to the function through the SORTING-TYPE
6325 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6326 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6327 called with point at the beginning of the record. It must return either
6328 a string or a number that should serve as the sorting key for that record.
6330 Comparing entries ignores case by default. However, with an optional argument
6331 WITH-CASE, the sorting considers case as well."
6332 (interactive "P")
6333 (let ((case-func (if with-case 'identity 'downcase))
6334 start beg end stars re re2
6335 txt what tmp plain-list-p)
6336 ;; Find beginning and end of region to sort
6337 (cond
6338 ((org-region-active-p)
6339 ;; we will sort the region
6340 (setq end (region-end)
6341 what "region")
6342 (goto-char (region-beginning))
6343 (if (not (org-on-heading-p)) (outline-next-heading))
6344 (setq start (point)))
6345 ((org-at-item-p)
6346 ;; we will sort this plain list
6347 (org-beginning-of-item-list) (setq start (point))
6348 (org-end-of-item-list) (setq end (point))
6349 (goto-char start)
6350 (setq plain-list-p t
6351 what "plain list"))
6352 ((or (org-on-heading-p)
6353 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6354 ;; we will sort the children of the current headline
6355 (org-back-to-heading)
6356 (setq start (point) end (org-end-of-subtree) what "children")
6357 (goto-char start)
6358 (show-subtree)
6359 (outline-next-heading))
6361 ;; we will sort the top-level entries in this file
6362 (goto-char (point-min))
6363 (or (org-on-heading-p) (outline-next-heading))
6364 (setq start (point) end (point-max) what "top-level")
6365 (goto-char start)
6366 (show-all)))
6368 (setq beg (point))
6369 (if (>= beg end) (error "Nothing to sort"))
6371 (unless plain-list-p
6372 (looking-at "\\(\\*+\\)")
6373 (setq stars (match-string 1)
6374 re (concat "^" (regexp-quote stars) " +")
6375 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6376 txt (buffer-substring beg end))
6377 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6378 (if (and (not (equal stars "*")) (string-match re2 txt))
6379 (error "Region to sort contains a level above the first entry")))
6381 (unless sorting-type
6382 (message
6383 (if plain-list-p
6384 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6385 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6386 what)
6387 (setq sorting-type (read-char-exclusive))
6389 (and (= (downcase sorting-type) ?f)
6390 (setq getkey-func
6391 (completing-read "Sort using function: "
6392 obarray 'fboundp t nil nil))
6393 (setq getkey-func (intern getkey-func)))
6395 (and (= (downcase sorting-type) ?r)
6396 (setq property
6397 (completing-read "Property: "
6398 (mapcar 'list (org-buffer-property-keys t))
6399 nil t))))
6401 (message "Sorting entries...")
6403 (save-restriction
6404 (narrow-to-region start end)
6406 (let ((dcst (downcase sorting-type))
6407 (now (current-time)))
6408 (sort-subr
6409 (/= dcst sorting-type)
6410 ;; This function moves to the beginning character of the "record" to
6411 ;; be sorted.
6412 (if plain-list-p
6413 (lambda nil
6414 (if (org-at-item-p) t (goto-char (point-max))))
6415 (lambda nil
6416 (if (re-search-forward re nil t)
6417 (goto-char (match-beginning 0))
6418 (goto-char (point-max)))))
6419 ;; This function moves to the last character of the "record" being
6420 ;; sorted.
6421 (if plain-list-p
6422 'org-end-of-item
6423 (lambda nil
6424 (save-match-data
6425 (condition-case nil
6426 (outline-forward-same-level 1)
6427 (error
6428 (goto-char (point-max)))))))
6430 ;; This function returns the value that gets sorted against.
6431 (if plain-list-p
6432 (lambda nil
6433 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6434 (cond
6435 ((= dcst ?n)
6436 (string-to-number (buffer-substring (match-end 0)
6437 (point-at-eol))))
6438 ((= dcst ?a)
6439 (buffer-substring (match-end 0) (point-at-eol)))
6440 ((= dcst ?t)
6441 (if (re-search-forward org-ts-regexp
6442 (point-at-eol) t)
6443 (org-time-string-to-time (match-string 0))
6444 now))
6445 ((= dcst ?f)
6446 (if getkey-func
6447 (progn
6448 (setq tmp (funcall getkey-func))
6449 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6450 tmp)
6451 (error "Invalid key function `%s'" getkey-func)))
6452 (t (error "Invalid sorting type `%c'" sorting-type)))))
6453 (lambda nil
6454 (cond
6455 ((= dcst ?n)
6456 (if (looking-at outline-regexp)
6457 (string-to-number (buffer-substring (match-end 0)
6458 (point-at-eol)))
6459 nil))
6460 ((= dcst ?a)
6461 (funcall case-func (buffer-substring (point-at-bol)
6462 (point-at-eol))))
6463 ((= dcst ?t)
6464 (if (re-search-forward org-ts-regexp
6465 (save-excursion
6466 (forward-line 2)
6467 (point)) t)
6468 (org-time-string-to-time (match-string 0))
6469 now))
6470 ((= dcst ?p)
6471 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6472 (string-to-char (match-string 2))
6473 org-default-priority))
6474 ((= dcst ?r)
6475 (or (org-entry-get nil property) ""))
6476 ((= dcst ?f)
6477 (if getkey-func
6478 (progn
6479 (setq tmp (funcall getkey-func))
6480 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6481 tmp)
6482 (error "Invalid key function `%s'" getkey-func)))
6483 (t (error "Invalid sorting type `%c'" sorting-type)))))
6485 (cond
6486 ((= dcst ?a) 'string<)
6487 ((= dcst ?t) 'time-less-p)
6488 (t nil)))))
6489 (message "Sorting entries...done")))
6491 (defun org-do-sort (table what &optional with-case sorting-type)
6492 "Sort TABLE of WHAT according to SORTING-TYPE.
6493 The user will be prompted for the SORTING-TYPE if the call to this
6494 function does not specify it. WHAT is only for the prompt, to indicate
6495 what is being sorted. The sorting key will be extracted from
6496 the car of the elements of the table.
6497 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6498 (unless sorting-type
6499 (message
6500 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6501 what)
6502 (setq sorting-type (read-char-exclusive)))
6503 (let ((dcst (downcase sorting-type))
6504 extractfun comparefun)
6505 ;; Define the appropriate functions
6506 (cond
6507 ((= dcst ?n)
6508 (setq extractfun 'string-to-number
6509 comparefun (if (= dcst sorting-type) '< '>)))
6510 ((= dcst ?a)
6511 (setq extractfun (if with-case 'identity 'downcase)
6512 comparefun (if (= dcst sorting-type)
6513 'string<
6514 (lambda (a b) (and (not (string< a b))
6515 (not (string= a b)))))))
6516 ((= dcst ?t)
6517 (setq extractfun
6518 (lambda (x)
6519 (if (string-match org-ts-regexp x)
6520 (time-to-seconds
6521 (org-time-string-to-time (match-string 0 x)))
6523 comparefun (if (= dcst sorting-type) '< '>)))
6524 (t (error "Invalid sorting type `%c'" sorting-type)))
6526 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6527 table)
6528 (lambda (a b) (funcall comparefun (car a) (car b))))))
6530 ;;;; Plain list items, including checkboxes
6532 ;;; Plain list items
6534 (defun org-at-item-p ()
6535 "Is point in a line starting a hand-formatted item?"
6536 (let ((llt org-plain-list-ordered-item-terminator))
6537 (save-excursion
6538 (goto-char (point-at-bol))
6539 (looking-at
6540 (cond
6541 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6542 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6543 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6544 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6546 (defun org-in-item-p ()
6547 "It the cursor inside a plain list item.
6548 Does not have to be the first line."
6549 (save-excursion
6550 (condition-case nil
6551 (progn
6552 (org-beginning-of-item)
6553 (org-at-item-p)
6555 (error nil))))
6557 (defun org-insert-item (&optional checkbox)
6558 "Insert a new item at the current level.
6559 Return t when things worked, nil when we are not in an item."
6560 (when (save-excursion
6561 (condition-case nil
6562 (progn
6563 (org-beginning-of-item)
6564 (org-at-item-p)
6565 (if (org-invisible-p) (error "Invisible item"))
6567 (error nil)))
6568 (let* ((bul (match-string 0))
6569 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6570 (match-end 0)))
6571 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6572 pos)
6573 (cond
6574 ((and (org-at-item-p) (<= (point) eow))
6575 ;; before the bullet
6576 (beginning-of-line 1)
6577 (open-line (if blank 2 1)))
6578 ((<= (point) eow)
6579 (beginning-of-line 1))
6580 (t (newline (if blank 2 1))))
6581 (insert bul (if checkbox "[ ]" ""))
6582 (just-one-space)
6583 (setq pos (point))
6584 (end-of-line 1)
6585 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6586 (org-maybe-renumber-ordered-list)
6587 (and checkbox (org-update-checkbox-count-maybe))
6590 ;;; Checkboxes
6592 (defun org-at-item-checkbox-p ()
6593 "Is point at a line starting a plain-list item with a checklet?"
6594 (and (org-at-item-p)
6595 (save-excursion
6596 (goto-char (match-end 0))
6597 (skip-chars-forward " \t")
6598 (looking-at "\\[[- X]\\]"))))
6600 (defun org-toggle-checkbox (&optional arg)
6601 "Toggle the checkbox in the current line."
6602 (interactive "P")
6603 (catch 'exit
6604 (let (beg end status (firstnew 'unknown))
6605 (cond
6606 ((org-region-active-p)
6607 (setq beg (region-beginning) end (region-end)))
6608 ((org-on-heading-p)
6609 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6610 ((org-at-item-checkbox-p)
6611 (let ((pos (point)))
6612 (replace-match
6613 (cond (arg "[-]")
6614 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6615 (t "[ ]"))
6616 t t)
6617 (goto-char pos))
6618 (throw 'exit t))
6619 (t (error "Not at a checkbox or heading, and no active region")))
6620 (save-excursion
6621 (goto-char beg)
6622 (while (< (point) end)
6623 (when (org-at-item-checkbox-p)
6624 (setq status (equal (match-string 0) "[X]"))
6625 (when (eq firstnew 'unknown)
6626 (setq firstnew (not status)))
6627 (replace-match
6628 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6629 (beginning-of-line 2)))))
6630 (org-update-checkbox-count-maybe))
6632 (defun org-update-checkbox-count-maybe ()
6633 "Update checkbox statistics unless turned off by user."
6634 (when org-provide-checkbox-statistics
6635 (org-update-checkbox-count)))
6637 (defun org-update-checkbox-count (&optional all)
6638 "Update the checkbox statistics in the current section.
6639 This will find all statistic cookies like [57%] and [6/12] and update them
6640 with the current numbers. With optional prefix argument ALL, do this for
6641 the whole buffer."
6642 (interactive "P")
6643 (save-excursion
6644 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6645 (beg (condition-case nil
6646 (progn (outline-back-to-heading) (point))
6647 (error (point-min))))
6648 (end (move-marker (make-marker)
6649 (progn (outline-next-heading) (point))))
6650 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6651 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6652 b1 e1 f1 c-on c-off lim (cstat 0))
6653 (when all
6654 (goto-char (point-min))
6655 (outline-next-heading)
6656 (setq beg (point) end (point-max)))
6657 (goto-char beg)
6658 (while (re-search-forward re end t)
6659 (setq cstat (1+ cstat)
6660 b1 (match-beginning 0)
6661 e1 (match-end 0)
6662 f1 (match-beginning 1)
6663 lim (cond
6664 ((org-on-heading-p) (outline-next-heading) (point))
6665 ((org-at-item-p) (org-end-of-item) (point))
6666 (t nil))
6667 c-on 0 c-off 0)
6668 (goto-char e1)
6669 (when lim
6670 (while (re-search-forward re-box lim t)
6671 (if (member (match-string 2) '("[ ]" "[-]"))
6672 (setq c-off (1+ c-off))
6673 (setq c-on (1+ c-on))))
6674 ; (delete-region b1 e1)
6675 (goto-char b1)
6676 (insert (if f1
6677 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6678 (format "[%d/%d]" c-on (+ c-on c-off))))
6679 (and (looking-at "\\[.*?\\]")
6680 (replace-match ""))))
6681 (when (interactive-p)
6682 (message "Checkbox satistics updated %s (%d places)"
6683 (if all "in entire file" "in current outline entry") cstat)))))
6685 (defun org-get-checkbox-statistics-face ()
6686 "Select the face for checkbox statistics.
6687 The face will be `org-done' when all relevant boxes are checked. Otherwise
6688 it will be `org-todo'."
6689 (if (match-end 1)
6690 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6691 (if (and (> (match-end 2) (match-beginning 2))
6692 (equal (match-string 2) (match-string 3)))
6693 'org-done
6694 'org-todo)))
6696 (defun org-get-indentation (&optional line)
6697 "Get the indentation of the current line, interpreting tabs.
6698 When LINE is given, assume it represents a line and compute its indentation."
6699 (if line
6700 (if (string-match "^ *" (org-remove-tabs line))
6701 (match-end 0))
6702 (save-excursion
6703 (beginning-of-line 1)
6704 (skip-chars-forward " \t")
6705 (current-column))))
6707 (defun org-remove-tabs (s &optional width)
6708 "Replace tabulators in S with spaces.
6709 Assumes that s is a single line, starting in column 0."
6710 (setq width (or width tab-width))
6711 (while (string-match "\t" s)
6712 (setq s (replace-match
6713 (make-string
6714 (- (* width (/ (+ (match-beginning 0) width) width))
6715 (match-beginning 0)) ?\ )
6716 t t s)))
6719 (defun org-fix-indentation (line ind)
6720 "Fix indentation in LINE.
6721 IND is a cons cell with target and minimum indentation.
6722 If the current indenation in LINE is smaller than the minimum,
6723 leave it alone. If it is larger than ind, set it to the target."
6724 (let* ((l (org-remove-tabs line))
6725 (i (org-get-indentation l))
6726 (i1 (car ind)) (i2 (cdr ind)))
6727 (if (>= i i2) (setq l (substring line i2)))
6728 (if (> i1 0)
6729 (concat (make-string i1 ?\ ) l)
6730 l)))
6732 (defcustom org-empty-line-terminates-plain-lists nil
6733 "Non-nil means, an empty line ends all plain list levels.
6734 When nil, empty lines are part of the preceeding item."
6735 :group 'org-plain-lists
6736 :type 'boolean)
6738 (defun org-beginning-of-item ()
6739 "Go to the beginning of the current hand-formatted item.
6740 If the cursor is not in an item, throw an error."
6741 (interactive)
6742 (let ((pos (point))
6743 (limit (save-excursion
6744 (condition-case nil
6745 (progn
6746 (org-back-to-heading)
6747 (beginning-of-line 2) (point))
6748 (error (point-min)))))
6749 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6750 ind ind1)
6751 (if (org-at-item-p)
6752 (beginning-of-line 1)
6753 (beginning-of-line 1)
6754 (skip-chars-forward " \t")
6755 (setq ind (current-column))
6756 (if (catch 'exit
6757 (while t
6758 (beginning-of-line 0)
6759 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6761 (if (looking-at "[ \t]*$")
6762 (setq ind1 ind-empty)
6763 (skip-chars-forward " \t")
6764 (setq ind1 (current-column)))
6765 (if (< ind1 ind)
6766 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6768 (goto-char pos)
6769 (error "Not in an item")))))
6771 (defun org-end-of-item ()
6772 "Go to the end of the current hand-formatted item.
6773 If the cursor is not in an item, throw an error."
6774 (interactive)
6775 (let* ((pos (point))
6776 ind1
6777 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6778 (limit (save-excursion (outline-next-heading) (point)))
6779 (ind (save-excursion
6780 (org-beginning-of-item)
6781 (skip-chars-forward " \t")
6782 (current-column)))
6783 (end (catch 'exit
6784 (while t
6785 (beginning-of-line 2)
6786 (if (eobp) (throw 'exit (point)))
6787 (if (>= (point) limit) (throw 'exit (point-at-bol)))
6788 (if (looking-at "[ \t]*$")
6789 (setq ind1 ind-empty)
6790 (skip-chars-forward " \t")
6791 (setq ind1 (current-column)))
6792 (if (<= ind1 ind)
6793 (throw 'exit (point-at-bol)))))))
6794 (if end
6795 (goto-char end)
6796 (goto-char pos)
6797 (error "Not in an item"))))
6799 (defun org-next-item ()
6800 "Move to the beginning of the next item in the current plain list.
6801 Error if not at a plain list, or if this is the last item in the list."
6802 (interactive)
6803 (let (ind ind1 (pos (point)))
6804 (org-beginning-of-item)
6805 (setq ind (org-get-indentation))
6806 (org-end-of-item)
6807 (setq ind1 (org-get-indentation))
6808 (unless (and (org-at-item-p) (= ind ind1))
6809 (goto-char pos)
6810 (error "On last item"))))
6812 (defun org-previous-item ()
6813 "Move to the beginning of the previous item in the current plain list.
6814 Error if not at a plain list, or if this is the first item in the list."
6815 (interactive)
6816 (let (beg ind ind1 (pos (point)))
6817 (org-beginning-of-item)
6818 (setq beg (point))
6819 (setq ind (org-get-indentation))
6820 (goto-char beg)
6821 (catch 'exit
6822 (while t
6823 (beginning-of-line 0)
6824 (if (looking-at "[ \t]*$")
6826 (if (<= (setq ind1 (org-get-indentation)) ind)
6827 (throw 'exit t)))))
6828 (condition-case nil
6829 (if (or (not (org-at-item-p))
6830 (< ind1 (1- ind)))
6831 (error "")
6832 (org-beginning-of-item))
6833 (error (goto-char pos)
6834 (error "On first item")))))
6836 (defun org-move-item-down ()
6837 "Move the plain list item at point down, i.e. swap with following item.
6838 Subitems (items with larger indentation) are considered part of the item,
6839 so this really moves item trees."
6840 (interactive)
6841 (let (beg end ind ind1 (pos (point)) txt)
6842 (org-beginning-of-item)
6843 (setq beg (point))
6844 (setq ind (org-get-indentation))
6845 (org-end-of-item)
6846 (setq end (point))
6847 (setq ind1 (org-get-indentation))
6848 (if (and (org-at-item-p) (= ind ind1))
6849 (progn
6850 (org-end-of-item)
6851 (setq txt (buffer-substring beg end))
6852 (save-excursion
6853 (delete-region beg end))
6854 (setq pos (point))
6855 (insert txt)
6856 (goto-char pos)
6857 (org-maybe-renumber-ordered-list))
6858 (goto-char pos)
6859 (error "Cannot move this item further down"))))
6861 (defun org-move-item-up (arg)
6862 "Move the plain list item at point up, i.e. swap with previous item.
6863 Subitems (items with larger indentation) are considered part of the item,
6864 so this really moves item trees."
6865 (interactive "p")
6866 (let (beg end ind ind1 (pos (point)) txt)
6867 (org-beginning-of-item)
6868 (setq beg (point))
6869 (setq ind (org-get-indentation))
6870 (org-end-of-item)
6871 (setq end (point))
6872 (goto-char beg)
6873 (catch 'exit
6874 (while t
6875 (beginning-of-line 0)
6876 (if (looking-at "[ \t]*$")
6877 (if org-empty-line-terminates-plain-lists
6878 (progn
6879 (goto-char pos)
6880 (error "Cannot move this item further up"))
6881 nil)
6882 (if (<= (setq ind1 (org-get-indentation)) ind)
6883 (throw 'exit t)))))
6884 (condition-case nil
6885 (org-beginning-of-item)
6886 (error (goto-char beg)
6887 (error "Cannot move this item further up")))
6888 (setq ind1 (org-get-indentation))
6889 (if (and (org-at-item-p) (= ind ind1))
6890 (progn
6891 (setq txt (buffer-substring beg end))
6892 (save-excursion
6893 (delete-region beg end))
6894 (setq pos (point))
6895 (insert txt)
6896 (goto-char pos)
6897 (org-maybe-renumber-ordered-list))
6898 (goto-char pos)
6899 (error "Cannot move this item further up"))))
6901 (defun org-maybe-renumber-ordered-list ()
6902 "Renumber the ordered list at point if setup allows it.
6903 This tests the user option `org-auto-renumber-ordered-lists' before
6904 doing the renumbering."
6905 (interactive)
6906 (when (and org-auto-renumber-ordered-lists
6907 (org-at-item-p))
6908 (if (match-beginning 3)
6909 (org-renumber-ordered-list 1)
6910 (org-fix-bullet-type))))
6912 (defun org-maybe-renumber-ordered-list-safe ()
6913 (condition-case nil
6914 (save-excursion
6915 (org-maybe-renumber-ordered-list))
6916 (error nil)))
6918 (defun org-cycle-list-bullet (&optional which)
6919 "Cycle through the different itemize/enumerate bullets.
6920 This cycle the entire list level through the sequence:
6922 `-' -> `+' -> `*' -> `1.' -> `1)'
6924 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6925 0 meand `-', 1 means `+' etc."
6926 (interactive "P")
6927 (org-preserve-lc
6928 (org-beginning-of-item-list)
6929 (org-at-item-p)
6930 (beginning-of-line 1)
6931 (let ((current (match-string 0))
6932 (prevp (eq which 'previous))
6933 new)
6934 (setq new (cond
6935 ((and (numberp which)
6936 (nth (1- which) '("-" "+" "*" "1." "1)"))))
6937 ((string-match "-" current) (if prevp "1)" "+"))
6938 ((string-match "\\+" current)
6939 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
6940 ((string-match "\\*" current) (if prevp "+" "1."))
6941 ((string-match "\\." current) (if prevp "*" "1)"))
6942 ((string-match ")" current) (if prevp "1." "-"))
6943 (t (error "This should not happen"))))
6944 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6945 (org-fix-bullet-type)
6946 (org-maybe-renumber-ordered-list))))
6948 (defun org-get-string-indentation (s)
6949 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6950 (let ((n -1) (i 0) (w tab-width) c)
6951 (catch 'exit
6952 (while (< (setq n (1+ n)) (length s))
6953 (setq c (aref s n))
6954 (cond ((= c ?\ ) (setq i (1+ i)))
6955 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6956 (t (throw 'exit t)))))
6959 (defun org-renumber-ordered-list (arg)
6960 "Renumber an ordered plain list.
6961 Cursor needs to be in the first line of an item, the line that starts
6962 with something like \"1.\" or \"2)\"."
6963 (interactive "p")
6964 (unless (and (org-at-item-p)
6965 (match-beginning 3))
6966 (error "This is not an ordered list"))
6967 (let ((line (org-current-line))
6968 (col (current-column))
6969 (ind (org-get-string-indentation
6970 (buffer-substring (point-at-bol) (match-beginning 3))))
6971 ;; (term (substring (match-string 3) -1))
6972 ind1 (n (1- arg))
6973 fmt)
6974 ;; find where this list begins
6975 (org-beginning-of-item-list)
6976 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6977 (setq fmt (concat "%d" (match-string 1)))
6978 (beginning-of-line 0)
6979 ;; walk forward and replace these numbers
6980 (catch 'exit
6981 (while t
6982 (catch 'next
6983 (beginning-of-line 2)
6984 (if (eobp) (throw 'exit nil))
6985 (if (looking-at "[ \t]*$") (throw 'next nil))
6986 (skip-chars-forward " \t") (setq ind1 (current-column))
6987 (if (> ind1 ind) (throw 'next t))
6988 (if (< ind1 ind) (throw 'exit t))
6989 (if (not (org-at-item-p)) (throw 'exit nil))
6990 (delete-region (match-beginning 2) (match-end 2))
6991 (goto-char (match-beginning 2))
6992 (insert (format fmt (setq n (1+ n)))))))
6993 (goto-line line)
6994 (move-to-column col)))
6996 (defun org-fix-bullet-type ()
6997 "Make sure all items in this list have the same bullet as the firsst item."
6998 (interactive)
6999 (unless (org-at-item-p) (error "This is not a list"))
7000 (let ((line (org-current-line))
7001 (col (current-column))
7002 (ind (current-indentation))
7003 ind1 bullet)
7004 ;; find where this list begins
7005 (org-beginning-of-item-list)
7006 (beginning-of-line 1)
7007 ;; find out what the bullet type is
7008 (looking-at "[ \t]*\\(\\S-+\\)")
7009 (setq bullet (match-string 1))
7010 ;; walk forward and replace these numbers
7011 (beginning-of-line 0)
7012 (catch 'exit
7013 (while t
7014 (catch 'next
7015 (beginning-of-line 2)
7016 (if (eobp) (throw 'exit nil))
7017 (if (looking-at "[ \t]*$") (throw 'next nil))
7018 (skip-chars-forward " \t") (setq ind1 (current-column))
7019 (if (> ind1 ind) (throw 'next t))
7020 (if (< ind1 ind) (throw 'exit t))
7021 (if (not (org-at-item-p)) (throw 'exit nil))
7022 (skip-chars-forward " \t")
7023 (looking-at "\\S-+")
7024 (replace-match bullet))))
7025 (goto-line line)
7026 (move-to-column col)
7027 (if (string-match "[0-9]" bullet)
7028 (org-renumber-ordered-list 1))))
7030 (defun org-beginning-of-item-list ()
7031 "Go to the beginning of the current item list.
7032 I.e. to the first item in this list."
7033 (interactive)
7034 (org-beginning-of-item)
7035 (let ((pos (point-at-bol))
7036 (ind (org-get-indentation))
7037 ind1)
7038 ;; find where this list begins
7039 (catch 'exit
7040 (while t
7041 (catch 'next
7042 (beginning-of-line 0)
7043 (if (looking-at "[ \t]*$")
7044 (throw (if (bobp) 'exit 'next) t))
7045 (skip-chars-forward " \t") (setq ind1 (current-column))
7046 (if (or (< ind1 ind)
7047 (and (= ind1 ind)
7048 (not (org-at-item-p)))
7049 (bobp))
7050 (throw 'exit t)
7051 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7052 (goto-char pos)))
7055 (defun org-end-of-item-list ()
7056 "Go to the end of the current item list.
7057 I.e. to the text after the last item."
7058 (interactive)
7059 (org-beginning-of-item)
7060 (let ((pos (point-at-bol))
7061 (ind (org-get-indentation))
7062 ind1)
7063 ;; find where this list begins
7064 (catch 'exit
7065 (while t
7066 (catch 'next
7067 (beginning-of-line 2)
7068 (if (looking-at "[ \t]*$")
7069 (throw (if (eobp) 'exit 'next) t))
7070 (skip-chars-forward " \t") (setq ind1 (current-column))
7071 (if (or (< ind1 ind)
7072 (and (= ind1 ind)
7073 (not (org-at-item-p)))
7074 (eobp))
7075 (progn
7076 (setq pos (point-at-bol))
7077 (throw 'exit t))))))
7078 (goto-char pos)))
7081 (defvar org-last-indent-begin-marker (make-marker))
7082 (defvar org-last-indent-end-marker (make-marker))
7084 (defun org-outdent-item (arg)
7085 "Outdent a local list item."
7086 (interactive "p")
7087 (org-indent-item (- arg)))
7089 (defun org-indent-item (arg)
7090 "Indent a local list item."
7091 (interactive "p")
7092 (unless (org-at-item-p)
7093 (error "Not on an item"))
7094 (save-excursion
7095 (let (beg end ind ind1 tmp delta ind-down ind-up)
7096 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7097 (setq beg org-last-indent-begin-marker
7098 end org-last-indent-end-marker)
7099 (org-beginning-of-item)
7100 (setq beg (move-marker org-last-indent-begin-marker (point)))
7101 (org-end-of-item)
7102 (setq end (move-marker org-last-indent-end-marker (point))))
7103 (goto-char beg)
7104 (setq tmp (org-item-indent-positions)
7105 ind (car tmp)
7106 ind-down (nth 2 tmp)
7107 ind-up (nth 1 tmp)
7108 delta (if (> arg 0)
7109 (if ind-down (- ind-down ind) 2)
7110 (if ind-up (- ind-up ind) -2)))
7111 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7112 (while (< (point) end)
7113 (beginning-of-line 1)
7114 (skip-chars-forward " \t") (setq ind1 (current-column))
7115 (delete-region (point-at-bol) (point))
7116 (or (eolp) (indent-to-column (+ ind1 delta)))
7117 (beginning-of-line 2))))
7118 (org-fix-bullet-type)
7119 (org-maybe-renumber-ordered-list-safe)
7120 (save-excursion
7121 (beginning-of-line 0)
7122 (condition-case nil (org-beginning-of-item) (error nil))
7123 (org-maybe-renumber-ordered-list-safe)))
7125 (defun org-item-indent-positions ()
7126 "Return indentation for plain list items.
7127 This returns a list with three values: The current indentation, the
7128 parent indentation and the indentation a child should habe.
7129 Assumes cursor in item line."
7130 (let* ((bolpos (point-at-bol))
7131 (ind (org-get-indentation))
7132 ind-down ind-up pos)
7133 (save-excursion
7134 (org-beginning-of-item-list)
7135 (skip-chars-backward "\n\r \t")
7136 (when (org-in-item-p)
7137 (org-beginning-of-item)
7138 (setq ind-up (org-get-indentation))))
7139 (setq pos (point))
7140 (save-excursion
7141 (cond
7142 ((and (condition-case nil (progn (org-previous-item) t)
7143 (error nil))
7144 (or (forward-char 1) t)
7145 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7146 (setq ind-down (org-get-indentation)))
7147 ((and (goto-char pos)
7148 (org-at-item-p))
7149 (goto-char (match-end 0))
7150 (skip-chars-forward " \t")
7151 (setq ind-down (current-column)))))
7152 (list ind ind-up ind-down)))
7154 ;;; The orgstruct minor mode
7156 ;; Define a minor mode which can be used in other modes in order to
7157 ;; integrate the org-mode structure editing commands.
7159 ;; This is really a hack, because the org-mode structure commands use
7160 ;; keys which normally belong to the major mode. Here is how it
7161 ;; works: The minor mode defines all the keys necessary to operate the
7162 ;; structure commands, but wraps the commands into a function which
7163 ;; tests if the cursor is currently at a headline or a plain list
7164 ;; item. If that is the case, the structure command is used,
7165 ;; temporarily setting many Org-mode variables like regular
7166 ;; expressions for filling etc. However, when any of those keys is
7167 ;; used at a different location, function uses `key-binding' to look
7168 ;; up if the key has an associated command in another currently active
7169 ;; keymap (minor modes, major mode, global), and executes that
7170 ;; command. There might be problems if any of the keys is otherwise
7171 ;; used as a prefix key.
7173 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7174 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7175 ;; addresses this by checking explicitly for both bindings.
7177 (defvar orgstruct-mode-map (make-sparse-keymap)
7178 "Keymap for the minor `orgstruct-mode'.")
7180 (defvar org-local-vars nil
7181 "List of local variables, for use by `orgstruct-mode'")
7183 ;;;###autoload
7184 (define-minor-mode orgstruct-mode
7185 "Toggle the minor more `orgstruct-mode'.
7186 This mode is for using Org-mode structure commands in other modes.
7187 The following key behave as if Org-mode was active, if the cursor
7188 is on a headline, or on a plain list item (both in the definition
7189 of Org-mode).
7191 M-up Move entry/item up
7192 M-down Move entry/item down
7193 M-left Promote
7194 M-right Demote
7195 M-S-up Move entry/item up
7196 M-S-down Move entry/item down
7197 M-S-left Promote subtree
7198 M-S-right Demote subtree
7199 M-q Fill paragraph and items like in Org-mode
7200 C-c ^ Sort entries
7201 C-c - Cycle list bullet
7202 TAB Cycle item visibility
7203 M-RET Insert new heading/item
7204 S-M-RET Insert new TODO heading / Chekbox item
7205 C-c C-c Set tags / toggle checkbox"
7206 nil " OrgStruct" nil
7207 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7209 ;;;###autoload
7210 (defun turn-on-orgstruct ()
7211 "Unconditionally turn on `orgstruct-mode'."
7212 (orgstruct-mode 1))
7214 ;;;###autoload
7215 (defun turn-on-orgstruct++ ()
7216 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7217 In addition to setting orgstruct-mode, this also exports all indentation and
7218 autofilling variables from org-mode into the buffer. Note that turning
7219 off orgstruct-mode will *not* remove these additonal settings."
7220 (orgstruct-mode 1)
7221 (let (var val)
7222 (mapc
7223 (lambda (x)
7224 (when (string-match
7225 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7226 (symbol-name (car x)))
7227 (setq var (car x) val (nth 1 x))
7228 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7229 org-local-vars)))
7231 (defun orgstruct-error ()
7232 "Error when there is no default binding for a structure key."
7233 (interactive)
7234 (error "This key is has no function outside structure elements"))
7236 (defun orgstruct-setup ()
7237 "Setup orgstruct keymaps."
7238 (let ((nfunc 0)
7239 (bindings
7240 (list
7241 '([(meta up)] org-metaup)
7242 '([(meta down)] org-metadown)
7243 '([(meta left)] org-metaleft)
7244 '([(meta right)] org-metaright)
7245 '([(meta shift up)] org-shiftmetaup)
7246 '([(meta shift down)] org-shiftmetadown)
7247 '([(meta shift left)] org-shiftmetaleft)
7248 '([(meta shift right)] org-shiftmetaright)
7249 '([(shift up)] org-shiftup)
7250 '([(shift down)] org-shiftdown)
7251 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7252 '("\M-q" fill-paragraph)
7253 '("\C-c^" org-sort)
7254 '("\C-c-" org-cycle-list-bullet)))
7255 elt key fun cmd)
7256 (while (setq elt (pop bindings))
7257 (setq nfunc (1+ nfunc))
7258 (setq key (org-key (car elt))
7259 fun (nth 1 elt)
7260 cmd (orgstruct-make-binding fun nfunc key))
7261 (org-defkey orgstruct-mode-map key cmd))
7263 ;; Special treatment needed for TAB and RET
7264 (org-defkey orgstruct-mode-map [(tab)]
7265 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7266 (org-defkey orgstruct-mode-map "\C-i"
7267 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7269 (org-defkey orgstruct-mode-map "\M-\C-m"
7270 (orgstruct-make-binding 'org-insert-heading 105
7271 "\M-\C-m" [(meta return)]))
7272 (org-defkey orgstruct-mode-map [(meta return)]
7273 (orgstruct-make-binding 'org-insert-heading 106
7274 [(meta return)] "\M-\C-m"))
7276 (org-defkey orgstruct-mode-map [(shift meta return)]
7277 (orgstruct-make-binding 'org-insert-todo-heading 107
7278 [(meta return)] "\M-\C-m"))
7280 (unless org-local-vars
7281 (setq org-local-vars (org-get-local-variables)))
7285 (defun orgstruct-make-binding (fun n &rest keys)
7286 "Create a function for binding in the structure minor mode.
7287 FUN is the command to call inside a table. N is used to create a unique
7288 command name. KEYS are keys that should be checked in for a command
7289 to execute outside of tables."
7290 (eval
7291 (list 'defun
7292 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7293 '(arg)
7294 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7295 "Outside of structure, run the binding of `"
7296 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7297 "'.")
7298 '(interactive "p")
7299 (list 'if
7300 '(org-context-p 'headline 'item)
7301 (list 'org-run-like-in-org-mode (list 'quote fun))
7302 (list 'let '(orgstruct-mode)
7303 (list 'call-interactively
7304 (append '(or)
7305 (mapcar (lambda (k)
7306 (list 'key-binding k))
7307 keys)
7308 '('orgstruct-error))))))))
7310 (defun org-context-p (&rest contexts)
7311 "Check if local context is and of CONTEXTS.
7312 Possible values in the list of contexts are `table', `headline', and `item'."
7313 (let ((pos (point)))
7314 (goto-char (point-at-bol))
7315 (prog1 (or (and (memq 'table contexts)
7316 (looking-at "[ \t]*|"))
7317 (and (memq 'headline contexts)
7318 (looking-at "\\*+"))
7319 (and (memq 'item contexts)
7320 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7321 (goto-char pos))))
7323 (defun org-get-local-variables ()
7324 "Return a list of all local variables in an org-mode buffer."
7325 (let (varlist)
7326 (with-current-buffer (get-buffer-create "*Org tmp*")
7327 (erase-buffer)
7328 (org-mode)
7329 (setq varlist (buffer-local-variables)))
7330 (kill-buffer "*Org tmp*")
7331 (delq nil
7332 (mapcar
7333 (lambda (x)
7334 (setq x
7335 (if (symbolp x)
7336 (list x)
7337 (list (car x) (list 'quote (cdr x)))))
7338 (if (string-match
7339 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7340 (symbol-name (car x)))
7341 x nil))
7342 varlist))))
7344 ;;;###autoload
7345 (defun org-run-like-in-org-mode (cmd)
7346 (unless org-local-vars
7347 (setq org-local-vars (org-get-local-variables)))
7348 (eval (list 'let org-local-vars
7349 (list 'call-interactively (list 'quote cmd)))))
7351 ;;;; Archiving
7353 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7355 (defun org-archive-subtree (&optional find-done)
7356 "Move the current subtree to the archive.
7357 The archive can be a certain top-level heading in the current file, or in
7358 a different file. The tree will be moved to that location, the subtree
7359 heading be marked DONE, and the current time will be added.
7361 When called with prefix argument FIND-DONE, find whole trees without any
7362 open TODO items and archive them (after getting confirmation from the user).
7363 If the cursor is not at a headline when this comand is called, try all level
7364 1 trees. If the cursor is on a headline, only try the direct children of
7365 this heading."
7366 (interactive "P")
7367 (if find-done
7368 (org-archive-all-done)
7369 ;; Save all relevant TODO keyword-relatex variables
7371 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7372 (tr-org-todo-keywords-1 org-todo-keywords-1)
7373 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7374 (tr-org-done-keywords org-done-keywords)
7375 (tr-org-todo-regexp org-todo-regexp)
7376 (tr-org-todo-line-regexp org-todo-line-regexp)
7377 (tr-org-odd-levels-only org-odd-levels-only)
7378 (this-buffer (current-buffer))
7379 (org-archive-location org-archive-location)
7380 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7381 ;; start of variables that will be used for saving context
7382 ;; The compiler complains about them - keep them anyway!
7383 (file (abbreviate-file-name (buffer-file-name)))
7384 (time (format-time-string
7385 (substring (cdr org-time-stamp-formats) 1 -1)
7386 (current-time)))
7387 afile heading buffer level newfile-p
7388 category todo priority
7389 ;; start of variables that will be used for savind context
7390 ltags itags prop)
7392 ;; Try to find a local archive location
7393 (save-excursion
7394 (save-restriction
7395 (widen)
7396 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7397 (if (and prop (string-match "\\S-" prop))
7398 (setq org-archive-location prop)
7399 (if (or (re-search-backward re nil t)
7400 (re-search-forward re nil t))
7401 (setq org-archive-location (match-string 1))))))
7403 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7404 (progn
7405 (setq afile (format (match-string 1 org-archive-location)
7406 (file-name-nondirectory buffer-file-name))
7407 heading (match-string 2 org-archive-location)))
7408 (error "Invalid `org-archive-location'"))
7409 (if (> (length afile) 0)
7410 (setq newfile-p (not (file-exists-p afile))
7411 buffer (find-file-noselect afile))
7412 (setq buffer (current-buffer)))
7413 (unless buffer
7414 (error "Cannot access file \"%s\"" afile))
7415 (if (and (> (length heading) 0)
7416 (string-match "^\\*+" heading))
7417 (setq level (match-end 0))
7418 (setq heading nil level 0))
7419 (save-excursion
7420 (org-back-to-heading t)
7421 ;; Get context information that will be lost by moving the tree
7422 (org-refresh-category-properties)
7423 (setq category (org-get-category)
7424 todo (and (looking-at org-todo-line-regexp)
7425 (match-string 2))
7426 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7427 ltags (org-get-tags)
7428 itags (org-delete-all ltags (org-get-tags-at)))
7429 (setq ltags (mapconcat 'identity ltags " ")
7430 itags (mapconcat 'identity itags " "))
7431 ;; We first only copy, in case something goes wrong
7432 ;; we need to protect this-command, to avoid kill-region sets it,
7433 ;; which would lead to duplication of subtrees
7434 (let (this-command) (org-copy-subtree))
7435 (set-buffer buffer)
7436 ;; Enforce org-mode for the archive buffer
7437 (if (not (org-mode-p))
7438 ;; Force the mode for future visits.
7439 (let ((org-insert-mode-line-in-empty-file t)
7440 (org-inhibit-startup t))
7441 (call-interactively 'org-mode)))
7442 (when newfile-p
7443 (goto-char (point-max))
7444 (insert (format "\nArchived entries from file %s\n\n"
7445 (buffer-file-name this-buffer))))
7446 ;; Force the TODO keywords of the original buffer
7447 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7448 (org-todo-keywords-1 tr-org-todo-keywords-1)
7449 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7450 (org-done-keywords tr-org-done-keywords)
7451 (org-todo-regexp tr-org-todo-regexp)
7452 (org-todo-line-regexp tr-org-todo-line-regexp)
7453 (org-odd-levels-only
7454 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7455 org-odd-levels-only
7456 tr-org-odd-levels-only)))
7457 (goto-char (point-min))
7458 (if heading
7459 (progn
7460 (if (re-search-forward
7461 (concat "^" (regexp-quote heading)
7462 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7463 nil t)
7464 (goto-char (match-end 0))
7465 ;; Heading not found, just insert it at the end
7466 (goto-char (point-max))
7467 (or (bolp) (insert "\n"))
7468 (insert "\n" heading "\n")
7469 (end-of-line 0))
7470 ;; Make the subtree visible
7471 (show-subtree)
7472 (org-end-of-subtree t)
7473 (skip-chars-backward " \t\r\n")
7474 (and (looking-at "[ \t\r\n]*")
7475 (replace-match "\n\n")))
7476 ;; No specific heading, just go to end of file.
7477 (goto-char (point-max)) (insert "\n"))
7478 ;; Paste
7479 (org-paste-subtree (org-get-legal-level level 1))
7481 ;; Mark the entry as done
7482 (when (and org-archive-mark-done
7483 (looking-at org-todo-line-regexp)
7484 (or (not (match-end 2))
7485 (not (member (match-string 2) org-done-keywords))))
7486 (let (org-log-done)
7487 (org-todo
7488 (car (or (member org-archive-mark-done org-done-keywords)
7489 org-done-keywords)))))
7491 ;; Add the context info
7492 (when org-archive-save-context-info
7493 (let ((l org-archive-save-context-info) e n v)
7494 (while (setq e (pop l))
7495 (when (and (setq v (symbol-value e))
7496 (stringp v) (string-match "\\S-" v))
7497 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7498 (org-entry-put (point) n v)))))
7500 ;; Save the buffer, if it is not the same buffer.
7501 (if (not (eq this-buffer buffer)) (save-buffer))))
7502 ;; Here we are back in the original buffer. Everything seems to have
7503 ;; worked. So now cut the tree and finish up.
7504 (let (this-command) (org-cut-subtree))
7505 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7506 (message "Subtree archived %s"
7507 (if (eq this-buffer buffer)
7508 (concat "under heading: " heading)
7509 (concat "in file: " (abbreviate-file-name afile)))))))
7511 (defun org-refresh-category-properties ()
7512 "Refresh category text properties in teh buffer."
7513 (let ((def-cat (cond
7514 ((null org-category)
7515 (if buffer-file-name
7516 (file-name-sans-extension
7517 (file-name-nondirectory buffer-file-name))
7518 "???"))
7519 ((symbolp org-category) (symbol-name org-category))
7520 (t org-category)))
7521 beg end cat pos optionp)
7522 (org-unmodified
7523 (save-excursion
7524 (save-restriction
7525 (widen)
7526 (goto-char (point-min))
7527 (put-text-property (point) (point-max) 'org-category def-cat)
7528 (while (re-search-forward
7529 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7530 (setq pos (match-end 0)
7531 optionp (equal (char-after (match-beginning 0)) ?#)
7532 cat (org-trim (match-string 2)))
7533 (if optionp
7534 (setq beg (point-at-bol) end (point-max))
7535 (org-back-to-heading t)
7536 (setq beg (point) end (org-end-of-subtree t t)))
7537 (put-text-property beg end 'org-category cat)
7538 (goto-char pos)))))))
7540 (defun org-archive-all-done (&optional tag)
7541 "Archive sublevels of the current tree without open TODO items.
7542 If the cursor is not on a headline, try all level 1 trees. If
7543 it is on a headline, try all direct children.
7544 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7545 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7546 (rea (concat ".*:" org-archive-tag ":"))
7547 (begm (make-marker))
7548 (endm (make-marker))
7549 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7550 "Move subtree to archive (no open TODO items)? "))
7551 beg end (cntarch 0))
7552 (if (org-on-heading-p)
7553 (progn
7554 (setq re1 (concat "^" (regexp-quote
7555 (make-string
7556 (1+ (- (match-end 0) (match-beginning 0)))
7557 ?*))
7558 " "))
7559 (move-marker begm (point))
7560 (move-marker endm (org-end-of-subtree t)))
7561 (setq re1 "^* ")
7562 (move-marker begm (point-min))
7563 (move-marker endm (point-max)))
7564 (save-excursion
7565 (goto-char begm)
7566 (while (re-search-forward re1 endm t)
7567 (setq beg (match-beginning 0)
7568 end (save-excursion (org-end-of-subtree t) (point)))
7569 (goto-char beg)
7570 (if (re-search-forward re end t)
7571 (goto-char end)
7572 (goto-char beg)
7573 (if (and (or (not tag) (not (looking-at rea)))
7574 (y-or-n-p question))
7575 (progn
7576 (if tag
7577 (org-toggle-tag org-archive-tag 'on)
7578 (org-archive-subtree))
7579 (setq cntarch (1+ cntarch)))
7580 (goto-char end)))))
7581 (message "%d trees archived" cntarch)))
7583 (defun org-cycle-hide-drawers (state)
7584 "Re-hide all drawers after a visibility state change."
7585 (when (and (org-mode-p)
7586 (not (memq state '(overview folded))))
7587 (save-excursion
7588 (let* ((globalp (memq state '(contents all)))
7589 (beg (if globalp (point-min) (point)))
7590 (end (if globalp (point-max) (org-end-of-subtree t))))
7591 (goto-char beg)
7592 (while (re-search-forward org-drawer-regexp end t)
7593 (org-flag-drawer t))))))
7595 (defun org-flag-drawer (flag)
7596 (save-excursion
7597 (beginning-of-line 1)
7598 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7599 (let ((b (match-end 0)))
7600 (if (re-search-forward
7601 "^[ \t]*:END:"
7602 (save-excursion (outline-next-heading) (point)) t)
7603 (outline-flag-region b (point-at-eol) flag)
7604 (error ":END: line missing"))))))
7606 (defun org-cycle-hide-archived-subtrees (state)
7607 "Re-hide all archived subtrees after a visibility state change."
7608 (when (and (not org-cycle-open-archived-trees)
7609 (not (memq state '(overview folded))))
7610 (save-excursion
7611 (let* ((globalp (memq state '(contents all)))
7612 (beg (if globalp (point-min) (point)))
7613 (end (if globalp (point-max) (org-end-of-subtree t))))
7614 (org-hide-archived-subtrees beg end)
7615 (goto-char beg)
7616 (if (looking-at (concat ".*:" org-archive-tag ":"))
7617 (message (substitute-command-keys
7618 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7620 (defun org-force-cycle-archived ()
7621 "Cycle subtree even if it is archived."
7622 (interactive)
7623 (setq this-command 'org-cycle)
7624 (let ((org-cycle-open-archived-trees t))
7625 (call-interactively 'org-cycle)))
7627 (defun org-hide-archived-subtrees (beg end)
7628 "Re-hide all archived subtrees after a visibility state change."
7629 (save-excursion
7630 (let* ((re (concat ":" org-archive-tag ":")))
7631 (goto-char beg)
7632 (while (re-search-forward re end t)
7633 (and (org-on-heading-p) (hide-subtree))
7634 (org-end-of-subtree t)))))
7636 (defun org-toggle-tag (tag &optional onoff)
7637 "Toggle the tag TAG for the current line.
7638 If ONOFF is `on' or `off', don't toggle but set to this state."
7639 (unless (org-on-heading-p t) (error "Not on headling"))
7640 (let (res current)
7641 (save-excursion
7642 (beginning-of-line)
7643 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7644 (point-at-eol) t)
7645 (progn
7646 (setq current (match-string 1))
7647 (replace-match ""))
7648 (setq current ""))
7649 (setq current (nreverse (org-split-string current ":")))
7650 (cond
7651 ((eq onoff 'on)
7652 (setq res t)
7653 (or (member tag current) (push tag current)))
7654 ((eq onoff 'off)
7655 (or (not (member tag current)) (setq current (delete tag current))))
7656 (t (if (member tag current)
7657 (setq current (delete tag current))
7658 (setq res t)
7659 (push tag current))))
7660 (end-of-line 1)
7661 (if current
7662 (progn
7663 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
7664 (org-set-tags nil t))
7665 (delete-horizontal-space))
7666 (run-hooks 'org-after-tags-change-hook))
7667 res))
7669 (defun org-toggle-archive-tag (&optional arg)
7670 "Toggle the archive tag for the current headline.
7671 With prefix ARG, check all children of current headline and offer tagging
7672 the children that do not contain any open TODO items."
7673 (interactive "P")
7674 (if arg
7675 (org-archive-all-done 'tag)
7676 (let (set)
7677 (save-excursion
7678 (org-back-to-heading t)
7679 (setq set (org-toggle-tag org-archive-tag))
7680 (when set (hide-subtree)))
7681 (and set (beginning-of-line 1))
7682 (message "Subtree %s" (if set "archived" "unarchived")))))
7685 ;;;; Tables
7687 ;;; The table editor
7689 ;; Watch out: Here we are talking about two different kind of tables.
7690 ;; Most of the code is for the tables created with the Org-mode table editor.
7691 ;; Sometimes, we talk about tables created and edited with the table.el
7692 ;; Emacs package. We call the former org-type tables, and the latter
7693 ;; table.el-type tables.
7695 (defun org-before-change-function (beg end)
7696 "Every change indicates that a table might need an update."
7697 (setq org-table-may-need-update t))
7699 (defconst org-table-line-regexp "^[ \t]*|"
7700 "Detects an org-type table line.")
7701 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7702 "Detects an org-type table line.")
7703 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7704 "Detects a table line marked for automatic recalculation.")
7705 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7706 "Detects a table line marked for automatic recalculation.")
7707 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7708 "Detects a table line marked for automatic recalculation.")
7709 (defconst org-table-hline-regexp "^[ \t]*|-"
7710 "Detects an org-type table hline.")
7711 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7712 "Detects a table-type table hline.")
7713 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7714 "Detects an org-type or table-type table.")
7715 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7716 "Searching from within a table (any type) this finds the first line
7717 outside the table.")
7718 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7719 "Searching from within a table (any type) this finds the first line
7720 outside the table.")
7722 (defvar org-table-last-highlighted-reference nil)
7723 (defvar org-table-formula-history nil)
7725 (defvar org-table-column-names nil
7726 "Alist with column names, derived from the `!' line.")
7727 (defvar org-table-column-name-regexp nil
7728 "Regular expression matching the current column names.")
7729 (defvar org-table-local-parameters nil
7730 "Alist with parameter names, derived from the `$' line.")
7731 (defvar org-table-named-field-locations nil
7732 "Alist with locations of named fields.")
7734 (defvar org-table-current-line-types nil
7735 "Table row types, non-nil only for the duration of a comand.")
7736 (defvar org-table-current-begin-line nil
7737 "Table begin line, non-nil only for the duration of a comand.")
7738 (defvar org-table-current-begin-pos nil
7739 "Table begin position, non-nil only for the duration of a comand.")
7740 (defvar org-table-dlines nil
7741 "Vector of data line line numbers in the current table.")
7742 (defvar org-table-hlines nil
7743 "Vector of hline line numbers in the current table.")
7745 (defconst org-table-range-regexp
7746 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
7747 ;; 1 2 3 4 5
7748 "Regular expression for matching ranges in formulas.")
7750 (defconst org-table-range-regexp2
7751 (concat
7752 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
7753 "\\.\\."
7754 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
7755 "Match a range for reference display.")
7757 (defconst org-table-translate-regexp
7758 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
7759 "Match a reference that needs translation, for reference display.")
7761 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
7763 (defun org-table-create-with-table.el ()
7764 "Use the table.el package to insert a new table.
7765 If there is already a table at point, convert between Org-mode tables
7766 and table.el tables."
7767 (interactive)
7768 (require 'table)
7769 (cond
7770 ((org-at-table.el-p)
7771 (if (y-or-n-p "Convert table to Org-mode table? ")
7772 (org-table-convert)))
7773 ((org-at-table-p)
7774 (if (y-or-n-p "Convert table to table.el table? ")
7775 (org-table-convert)))
7776 (t (call-interactively 'table-insert))))
7778 (defun org-table-create-or-convert-from-region (arg)
7779 "Convert region to table, or create an empty table.
7780 If there is an active region, convert it to a table, using the function
7781 `org-table-convert-region'. See the documentation of that function
7782 to learn how the prefix argument is interpreted to determine the field
7783 separator.
7784 If there is no such region, create an empty table with `org-table-create'."
7785 (interactive "P")
7786 (if (org-region-active-p)
7787 (org-table-convert-region (region-beginning) (region-end) arg)
7788 (org-table-create arg)))
7790 (defun org-table-create (&optional size)
7791 "Query for a size and insert a table skeleton.
7792 SIZE is a string Columns x Rows like for example \"3x2\"."
7793 (interactive "P")
7794 (unless size
7795 (setq size (read-string
7796 (concat "Table size Columns x Rows [e.g. "
7797 org-table-default-size "]: ")
7798 "" nil org-table-default-size)))
7800 (let* ((pos (point))
7801 (indent (make-string (current-column) ?\ ))
7802 (split (org-split-string size " *x *"))
7803 (rows (string-to-number (nth 1 split)))
7804 (columns (string-to-number (car split)))
7805 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7806 "\n")))
7807 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7808 (point-at-bol) (point)))
7809 (beginning-of-line 1)
7810 (newline))
7811 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7812 (dotimes (i rows) (insert line))
7813 (goto-char pos)
7814 (if (> rows 1)
7815 ;; Insert a hline after the first row.
7816 (progn
7817 (end-of-line 1)
7818 (insert "\n|-")
7819 (goto-char pos)))
7820 (org-table-align)))
7822 (defun org-table-convert-region (beg0 end0 &optional separator)
7823 "Convert region to a table.
7824 The region goes from BEG0 to END0, but these borders will be moved
7825 slightly, to make sure a beginning of line in the first line is included.
7827 SEPARATOR specifies the field separator in the lines. It can have the
7828 following values:
7830 '(4) Use the comma as a field separator
7831 '(16) Use a TAB as field separator
7832 integer When a number, use that many spaces as field separator
7833 nil When nil, the command tries to be smart and figure out the
7834 separator in the following way:
7835 - when each line contains a TAB, assume TAB-separated material
7836 - when each line contains a comme, assume CSV material
7837 - else, assume one or more SPACE charcters as separator."
7838 (interactive "rP")
7839 (let* ((beg (min beg0 end0))
7840 (end (max beg0 end0))
7842 (goto-char beg)
7843 (beginning-of-line 1)
7844 (setq beg (move-marker (make-marker) (point)))
7845 (goto-char end)
7846 (if (bolp) (backward-char 1) (end-of-line 1))
7847 (setq end (move-marker (make-marker) (point)))
7848 ;; Get the right field separator
7849 (unless separator
7850 (goto-char beg)
7851 (setq separator
7852 (cond
7853 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
7854 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
7855 (t 1))))
7856 (setq re (cond
7857 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
7858 ((equal separator '(16)) "^\\|\t")
7859 ((integerp separator)
7860 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
7861 (t (error "This should not happen"))))
7862 (goto-char beg)
7863 (while (re-search-forward re end t)
7864 (replace-match "| " t t))
7865 (goto-char beg)
7866 (insert " ")
7867 (org-table-align)))
7869 (defun org-table-import (file arg)
7870 "Import FILE as a table.
7871 The file is assumed to be tab-separated. Such files can be produced by most
7872 spreadsheet and database applications. If no tabs (at least one per line)
7873 are found, lines will be split on whitespace into fields."
7874 (interactive "f\nP")
7875 (or (bolp) (newline))
7876 (let ((beg (point))
7877 (pm (point-max)))
7878 (insert-file-contents file)
7879 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7881 (defun org-table-export ()
7882 "Export table as a tab-separated file.
7883 Such a file can be imported into a spreadsheet program like Excel."
7884 (interactive)
7885 (let* ((beg (org-table-begin))
7886 (end (org-table-end))
7887 (table (buffer-substring beg end))
7888 (file (read-file-name "Export table to: "))
7889 buf)
7890 (unless (or (not (file-exists-p file))
7891 (y-or-n-p (format "Overwrite file %s? " file)))
7892 (error "Abort"))
7893 (with-current-buffer (find-file-noselect file)
7894 (setq buf (current-buffer))
7895 (erase-buffer)
7896 (fundamental-mode)
7897 (insert table)
7898 (goto-char (point-min))
7899 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7900 (replace-match "" t t)
7901 (end-of-line 1))
7902 (goto-char (point-min))
7903 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7904 (replace-match "" t t)
7905 (goto-char (min (1+ (point)) (point-max))))
7906 (goto-char (point-min))
7907 (while (re-search-forward "^-[-+]*$" nil t)
7908 (replace-match "")
7909 (if (looking-at "\n")
7910 (delete-char 1)))
7911 (goto-char (point-min))
7912 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7913 (replace-match "\t" t t))
7914 (save-buffer))
7915 (kill-buffer buf)))
7917 (defvar org-table-aligned-begin-marker (make-marker)
7918 "Marker at the beginning of the table last aligned.
7919 Used to check if cursor still is in that table, to minimize realignment.")
7920 (defvar org-table-aligned-end-marker (make-marker)
7921 "Marker at the end of the table last aligned.
7922 Used to check if cursor still is in that table, to minimize realignment.")
7923 (defvar org-table-last-alignment nil
7924 "List of flags for flushright alignment, from the last re-alignment.
7925 This is being used to correctly align a single field after TAB or RET.")
7926 (defvar org-table-last-column-widths nil
7927 "List of max width of fields in each column.
7928 This is being used to correctly align a single field after TAB or RET.")
7929 (defvar org-table-overlay-coordinates nil
7930 "Overlay coordinates after each align of a table.")
7931 (make-variable-buffer-local 'org-table-overlay-coordinates)
7933 (defvar org-last-recalc-line nil)
7934 (defconst org-narrow-column-arrow "=>"
7935 "Used as display property in narrowed table columns.")
7937 (defun org-table-align ()
7938 "Align the table at point by aligning all vertical bars."
7939 (interactive)
7940 (let* (
7941 ;; Limits of table
7942 (beg (org-table-begin))
7943 (end (org-table-end))
7944 ;; Current cursor position
7945 (linepos (org-current-line))
7946 (colpos (org-table-current-column))
7947 (winstart (window-start))
7948 (winstartline (org-current-line (min winstart (1- (point-max)))))
7949 lines (new "") lengths l typenums ty fields maxfields i
7950 column
7951 (indent "") cnt frac
7952 rfmt hfmt
7953 (spaces '(1 . 1))
7954 (sp1 (car spaces))
7955 (sp2 (cdr spaces))
7956 (rfmt1 (concat
7957 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7958 (hfmt1 (concat
7959 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7960 emptystrings links dates emph narrow fmax f1 len c e)
7961 (untabify beg end)
7962 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
7963 ;; Check if we have links or dates
7964 (goto-char beg)
7965 (setq links (re-search-forward org-bracket-link-regexp end t))
7966 (goto-char beg)
7967 (setq emph (and org-hide-emphasis-markers
7968 (re-search-forward org-emph-re end t)))
7969 (goto-char beg)
7970 (setq dates (and org-display-custom-times
7971 (re-search-forward org-ts-regexp-both end t)))
7972 ;; Make sure the link properties are right
7973 (when links (goto-char beg) (while (org-activate-bracket-links end)))
7974 ;; Make sure the date properties are right
7975 (when dates (goto-char beg) (while (org-activate-dates end)))
7976 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
7978 ;; Check if we are narrowing any columns
7979 (goto-char beg)
7980 (setq narrow (and org-format-transports-properties-p
7981 (re-search-forward "<[0-9]+>" end t)))
7982 ;; Get the rows
7983 (setq lines (org-split-string
7984 (buffer-substring beg end) "\n"))
7985 ;; Store the indentation of the first line
7986 (if (string-match "^ *" (car lines))
7987 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7988 ;; Mark the hlines by setting the corresponding element to nil
7989 ;; At the same time, we remove trailing space.
7990 (setq lines (mapcar (lambda (l)
7991 (if (string-match "^ *|-" l)
7993 (if (string-match "[ \t]+$" l)
7994 (substring l 0 (match-beginning 0))
7995 l)))
7996 lines))
7997 ;; Get the data fields by splitting the lines.
7998 (setq fields (mapcar
7999 (lambda (l)
8000 (org-split-string l " *| *"))
8001 (delq nil (copy-sequence lines))))
8002 ;; How many fields in the longest line?
8003 (condition-case nil
8004 (setq maxfields (apply 'max (mapcar 'length fields)))
8005 (error
8006 (kill-region beg end)
8007 (org-table-create org-table-default-size)
8008 (error "Empty table - created default table")))
8009 ;; A list of empty strings to fill any short rows on output
8010 (setq emptystrings (make-list maxfields ""))
8011 ;; Check for special formatting.
8012 (setq i -1)
8013 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8014 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8015 ;; Check if there is an explicit width specified
8016 (when narrow
8017 (setq c column fmax nil)
8018 (while c
8019 (setq e (pop c))
8020 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8021 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8022 ;; Find fields that are wider than fmax, and shorten them
8023 (when fmax
8024 (loop for xx in column do
8025 (when (and (stringp xx)
8026 (> (org-string-width xx) fmax))
8027 (org-add-props xx nil
8028 'help-echo
8029 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8030 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8031 (unless (> f1 1)
8032 (error "Cannot narrow field starting with wide link \"%s\""
8033 (match-string 0 xx)))
8034 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8035 (add-text-properties (- f1 2) f1
8036 (list 'display org-narrow-column-arrow)
8037 xx)))))
8038 ;; Get the maximum width for each column
8039 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8040 ;; Get the fraction of numbers, to decide about alignment of the column
8041 (setq cnt 0 frac 0.0)
8042 (loop for x in column do
8043 (if (equal x "")
8045 (setq frac ( / (+ (* frac cnt)
8046 (if (string-match org-table-number-regexp x) 1 0))
8047 (setq cnt (1+ cnt))))))
8048 (push (>= frac org-table-number-fraction) typenums))
8049 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8051 ;; Store the alignment of this table, for later editing of single fields
8052 (setq org-table-last-alignment typenums
8053 org-table-last-column-widths lengths)
8055 ;; With invisible characters, `format' does not get the field width right
8056 ;; So we need to make these fields wide by hand.
8057 (when (or links emph)
8058 (loop for i from 0 upto (1- maxfields) do
8059 (setq len (nth i lengths))
8060 (loop for j from 0 upto (1- (length fields)) do
8061 (setq c (nthcdr i (car (nthcdr j fields))))
8062 (if (and (stringp (car c))
8063 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8064 ; (string-match org-bracket-link-regexp (car c))
8065 (< (org-string-width (car c)) len))
8066 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8068 ;; Compute the formats needed for output of the table
8069 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8070 (while (setq l (pop lengths))
8071 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8072 (setq rfmt (concat rfmt (format rfmt1 ty l))
8073 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8074 (setq rfmt (concat rfmt "\n")
8075 hfmt (concat (substring hfmt 0 -1) "|\n"))
8077 (setq new (mapconcat
8078 (lambda (l)
8079 (if l (apply 'format rfmt
8080 (append (pop fields) emptystrings))
8081 hfmt))
8082 lines ""))
8083 ;; Replace the old one
8084 (delete-region beg end)
8085 (move-marker end nil)
8086 (move-marker org-table-aligned-begin-marker (point))
8087 (insert new)
8088 (move-marker org-table-aligned-end-marker (point))
8089 (when (and orgtbl-mode (not (org-mode-p)))
8090 (goto-char org-table-aligned-begin-marker)
8091 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8092 ;; Try to move to the old location
8093 (goto-line winstartline)
8094 (setq winstart (point-at-bol))
8095 (goto-line linepos)
8096 (set-window-start (selected-window) winstart 'noforce)
8097 (org-table-goto-column colpos)
8098 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8099 (setq org-table-may-need-update nil)
8102 (defun org-string-width (s)
8103 "Compute width of string, ignoring invisible characters.
8104 This ignores character with invisibility property `org-link', and also
8105 characters with property `org-cwidth', because these will become invisible
8106 upon the next fontification round."
8107 (let (b l)
8108 (when (or (eq t buffer-invisibility-spec)
8109 (assq 'org-link buffer-invisibility-spec))
8110 (while (setq b (text-property-any 0 (length s)
8111 'invisible 'org-link s))
8112 (setq s (concat (substring s 0 b)
8113 (substring s (or (next-single-property-change
8114 b 'invisible s) (length s)))))))
8115 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8116 (setq s (concat (substring s 0 b)
8117 (substring s (or (next-single-property-change
8118 b 'org-cwidth s) (length s))))))
8119 (setq l (string-width s) b -1)
8120 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8121 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8124 (defun org-table-begin (&optional table-type)
8125 "Find the beginning of the table and return its position.
8126 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8127 (save-excursion
8128 (if (not (re-search-backward
8129 (if table-type org-table-any-border-regexp
8130 org-table-border-regexp)
8131 nil t))
8132 (progn (goto-char (point-min)) (point))
8133 (goto-char (match-beginning 0))
8134 (beginning-of-line 2)
8135 (point))))
8137 (defun org-table-end (&optional table-type)
8138 "Find the end of the table and return its position.
8139 With argument TABLE-TYPE, go to the end of a table.el-type table."
8140 (save-excursion
8141 (if (not (re-search-forward
8142 (if table-type org-table-any-border-regexp
8143 org-table-border-regexp)
8144 nil t))
8145 (goto-char (point-max))
8146 (goto-char (match-beginning 0)))
8147 (point-marker)))
8149 (defun org-table-justify-field-maybe (&optional new)
8150 "Justify the current field, text to left, number to right.
8151 Optional argument NEW may specify text to replace the current field content."
8152 (cond
8153 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8154 ((org-at-table-hline-p))
8155 ((and (not new)
8156 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8157 (current-buffer)))
8158 (< (point) org-table-aligned-begin-marker)
8159 (>= (point) org-table-aligned-end-marker)))
8160 ;; This is not the same table, force a full re-align
8161 (setq org-table-may-need-update t))
8162 (t ;; realign the current field, based on previous full realign
8163 (let* ((pos (point)) s
8164 (col (org-table-current-column))
8165 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8166 l f n o e)
8167 (when (> col 0)
8168 (skip-chars-backward "^|\n")
8169 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8170 (progn
8171 (setq s (match-string 1)
8172 o (match-string 0)
8173 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8174 e (not (= (match-beginning 2) (match-end 2))))
8175 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8176 l (if e "|" (setq org-table-may-need-update t) ""))
8177 n (format f s))
8178 (if new
8179 (if (<= (length new) l) ;; FIXME: length -> str-width?
8180 (setq n (format f new))
8181 (setq n (concat new "|") org-table-may-need-update t)))
8182 (or (equal n o)
8183 (let (org-table-may-need-update)
8184 (replace-match n t t))))
8185 (setq org-table-may-need-update t))
8186 (goto-char pos))))))
8188 (defun org-table-next-field ()
8189 "Go to the next field in the current table, creating new lines as needed.
8190 Before doing so, re-align the table if necessary."
8191 (interactive)
8192 (org-table-maybe-eval-formula)
8193 (org-table-maybe-recalculate-line)
8194 (if (and org-table-automatic-realign
8195 org-table-may-need-update)
8196 (org-table-align))
8197 (let ((end (org-table-end)))
8198 (if (org-at-table-hline-p)
8199 (end-of-line 1))
8200 (condition-case nil
8201 (progn
8202 (re-search-forward "|" end)
8203 (if (looking-at "[ \t]*$")
8204 (re-search-forward "|" end))
8205 (if (and (looking-at "-")
8206 org-table-tab-jumps-over-hlines
8207 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8208 (goto-char (match-beginning 1)))
8209 (if (looking-at "-")
8210 (progn
8211 (beginning-of-line 0)
8212 (org-table-insert-row 'below))
8213 (if (looking-at " ") (forward-char 1))))
8214 (error
8215 (org-table-insert-row 'below)))))
8217 (defun org-table-previous-field ()
8218 "Go to the previous field in the table.
8219 Before doing so, re-align the table if necessary."
8220 (interactive)
8221 (org-table-justify-field-maybe)
8222 (org-table-maybe-recalculate-line)
8223 (if (and org-table-automatic-realign
8224 org-table-may-need-update)
8225 (org-table-align))
8226 (if (org-at-table-hline-p)
8227 (end-of-line 1))
8228 (re-search-backward "|" (org-table-begin))
8229 (re-search-backward "|" (org-table-begin))
8230 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8231 (re-search-backward "|" (org-table-begin)))
8232 (if (looking-at "| ?")
8233 (goto-char (match-end 0))))
8235 (defun org-table-next-row ()
8236 "Go to the next row (same column) in the current table.
8237 Before doing so, re-align the table if necessary."
8238 (interactive)
8239 (org-table-maybe-eval-formula)
8240 (org-table-maybe-recalculate-line)
8241 (if (or (looking-at "[ \t]*$")
8242 (save-excursion (skip-chars-backward " \t") (bolp)))
8243 (newline)
8244 (if (and org-table-automatic-realign
8245 org-table-may-need-update)
8246 (org-table-align))
8247 (let ((col (org-table-current-column)))
8248 (beginning-of-line 2)
8249 (if (or (not (org-at-table-p))
8250 (org-at-table-hline-p))
8251 (progn
8252 (beginning-of-line 0)
8253 (org-table-insert-row 'below)))
8254 (org-table-goto-column col)
8255 (skip-chars-backward "^|\n\r")
8256 (if (looking-at " ") (forward-char 1)))))
8258 (defun org-table-copy-down (n)
8259 "Copy a field down in the current column.
8260 If the field at the cursor is empty, copy into it the content of the nearest
8261 non-empty field above. With argument N, use the Nth non-empty field.
8262 If the current field is not empty, it is copied down to the next row, and
8263 the cursor is moved with it. Therefore, repeating this command causes the
8264 column to be filled row-by-row.
8265 If the variable `org-table-copy-increment' is non-nil and the field is an
8266 integer or a timestamp, it will be incremented while copying. In the case of
8267 a timestamp, if the cursor is on the year, change the year. If it is on the
8268 month or the day, change that. Point will stay on the current date field
8269 in order to easily repeat the interval."
8270 (interactive "p")
8271 (let* ((colpos (org-table-current-column))
8272 (col (current-column))
8273 (field (org-table-get-field))
8274 (non-empty (string-match "[^ \t]" field))
8275 (beg (org-table-begin))
8276 txt)
8277 (org-table-check-inside-data-field)
8278 (if non-empty
8279 (progn
8280 (setq txt (org-trim field))
8281 (org-table-next-row)
8282 (org-table-blank-field))
8283 (save-excursion
8284 (setq txt
8285 (catch 'exit
8286 (while (progn (beginning-of-line 1)
8287 (re-search-backward org-table-dataline-regexp
8288 beg t))
8289 (org-table-goto-column colpos t)
8290 (if (and (looking-at
8291 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8292 (= (setq n (1- n)) 0))
8293 (throw 'exit (match-string 1))))))))
8294 (if txt
8295 (progn
8296 (if (and org-table-copy-increment
8297 (string-match "^[0-9]+$" txt))
8298 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8299 (insert txt)
8300 (move-to-column col)
8301 (if (and org-table-copy-increment (org-at-timestamp-p t))
8302 (org-timestamp-up 1)
8303 (org-table-maybe-recalculate-line))
8304 (org-table-align)
8305 (move-to-column col))
8306 (error "No non-empty field found"))))
8308 (defun org-table-check-inside-data-field ()
8309 "Is point inside a table data field?
8310 I.e. not on a hline or before the first or after the last column?
8311 This actually throws an error, so it aborts the current command."
8312 (if (or (not (org-at-table-p))
8313 (= (org-table-current-column) 0)
8314 (org-at-table-hline-p)
8315 (looking-at "[ \t]*$"))
8316 (error "Not in table data field")))
8318 (defvar org-table-clip nil
8319 "Clipboard for table regions.")
8321 (defun org-table-blank-field ()
8322 "Blank the current table field or active region."
8323 (interactive)
8324 (org-table-check-inside-data-field)
8325 (if (and (interactive-p) (org-region-active-p))
8326 (let (org-table-clip)
8327 (org-table-cut-region (region-beginning) (region-end)))
8328 (skip-chars-backward "^|")
8329 (backward-char 1)
8330 (if (looking-at "|[^|\n]+")
8331 (let* ((pos (match-beginning 0))
8332 (match (match-string 0))
8333 (len (org-string-width match)))
8334 (replace-match (concat "|" (make-string (1- len) ?\ )))
8335 (goto-char (+ 2 pos))
8336 (substring match 1)))))
8338 (defun org-table-get-field (&optional n replace)
8339 "Return the value of the field in column N of current row.
8340 N defaults to current field.
8341 If REPLACE is a string, replace field with this value. The return value
8342 is always the old value."
8343 (and n (org-table-goto-column n))
8344 (skip-chars-backward "^|\n")
8345 (backward-char 1)
8346 (if (looking-at "|[^|\r\n]*")
8347 (let* ((pos (match-beginning 0))
8348 (val (buffer-substring (1+ pos) (match-end 0))))
8349 (if replace
8350 (replace-match (concat "|" replace) t t))
8351 (goto-char (min (point-at-eol) (+ 2 pos)))
8352 val)
8353 (forward-char 1) ""))
8355 (defun org-table-field-info (arg)
8356 "Show info about the current field, and highlight any reference at point."
8357 (interactive "P")
8358 (org-table-get-specials)
8359 (save-excursion
8360 (let* ((pos (point))
8361 (col (org-table-current-column))
8362 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8363 (name (car (rassoc (list (org-current-line) col)
8364 org-table-named-field-locations)))
8365 (eql (org-table-get-stored-formulas))
8366 (dline (org-table-current-dline))
8367 (ref (format "@%d$%d" dline col))
8368 (ref1 (org-table-convert-refs-to-an ref))
8369 (fequation (or (assoc name eql) (assoc ref eql)))
8370 (cequation (assoc (int-to-string col) eql))
8371 (eqn (or fequation cequation)))
8372 (goto-char pos)
8373 (condition-case nil
8374 (org-table-show-reference 'local)
8375 (error nil))
8376 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8377 dline col
8378 (if cname (concat " or $" cname) "")
8379 dline col ref1
8380 (if name (concat " or $" name) "")
8381 ;; FIXME: formula info not correct if special table line
8382 (if eqn
8383 (concat ", formula: "
8384 (org-table-formula-to-user
8385 (concat
8386 (if (string-match "^[$@]"(car eqn)) "" "$")
8387 (car eqn) "=" (cdr eqn))))
8388 "")))))
8390 (defun org-table-current-column ()
8391 "Find out which column we are in.
8392 When called interactively, column is also displayed in echo area."
8393 (interactive)
8394 (if (interactive-p) (org-table-check-inside-data-field))
8395 (save-excursion
8396 (let ((cnt 0) (pos (point)))
8397 (beginning-of-line 1)
8398 (while (search-forward "|" pos t)
8399 (setq cnt (1+ cnt)))
8400 (if (interactive-p) (message "This is table column %d" cnt))
8401 cnt)))
8403 (defun org-table-current-dline ()
8404 "Find out what table data line we are in.
8405 Only datalins count for this."
8406 (interactive)
8407 (if (interactive-p) (org-table-check-inside-data-field))
8408 (save-excursion
8409 (let ((cnt 0) (pos (point)))
8410 (goto-char (org-table-begin))
8411 (while (<= (point) pos)
8412 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8413 (beginning-of-line 2))
8414 (if (interactive-p) (message "This is table line %d" cnt))
8415 cnt)))
8417 (defun org-table-goto-column (n &optional on-delim force)
8418 "Move the cursor to the Nth column in the current table line.
8419 With optional argument ON-DELIM, stop with point before the left delimiter
8420 of the field.
8421 If there are less than N fields, just go to after the last delimiter.
8422 However, when FORCE is non-nil, create new columns if necessary."
8423 (interactive "p")
8424 (let ((pos (point-at-eol)))
8425 (beginning-of-line 1)
8426 (when (> n 0)
8427 (while (and (> (setq n (1- n)) -1)
8428 (or (search-forward "|" pos t)
8429 (and force
8430 (progn (end-of-line 1)
8431 (skip-chars-backward "^|")
8432 (insert " | "))))))
8433 ; (backward-char 2) t)))))
8434 (when (and force (not (looking-at ".*|")))
8435 (save-excursion (end-of-line 1) (insert " | ")))
8436 (if on-delim
8437 (backward-char 1)
8438 (if (looking-at " ") (forward-char 1))))))
8440 (defun org-at-table-p (&optional table-type)
8441 "Return t if the cursor is inside an org-type table.
8442 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8443 (if org-enable-table-editor
8444 (save-excursion
8445 (beginning-of-line 1)
8446 (looking-at (if table-type org-table-any-line-regexp
8447 org-table-line-regexp)))
8448 nil))
8450 (defun org-at-table.el-p ()
8451 "Return t if and only if we are at a table.el table."
8452 (and (org-at-table-p 'any)
8453 (save-excursion
8454 (goto-char (org-table-begin 'any))
8455 (looking-at org-table1-hline-regexp))))
8457 (defun org-table-recognize-table.el ()
8458 "If there is a table.el table nearby, recognize it and move into it."
8459 (if org-table-tab-recognizes-table.el
8460 (if (org-at-table.el-p)
8461 (progn
8462 (beginning-of-line 1)
8463 (if (looking-at org-table-dataline-regexp)
8465 (if (looking-at org-table1-hline-regexp)
8466 (progn
8467 (beginning-of-line 2)
8468 (if (looking-at org-table-any-border-regexp)
8469 (beginning-of-line -1)))))
8470 (if (re-search-forward "|" (org-table-end t) t)
8471 (progn
8472 (require 'table)
8473 (if (table--at-cell-p (point))
8475 (message "recognizing table.el table...")
8476 (table-recognize-table)
8477 (message "recognizing table.el table...done")))
8478 (error "This should not happen..."))
8480 nil)
8481 nil))
8483 (defun org-at-table-hline-p ()
8484 "Return t if the cursor is inside a hline in a table."
8485 (if org-enable-table-editor
8486 (save-excursion
8487 (beginning-of-line 1)
8488 (looking-at org-table-hline-regexp))
8489 nil))
8491 (defun org-table-insert-column ()
8492 "Insert a new column into the table."
8493 (interactive)
8494 (if (not (org-at-table-p))
8495 (error "Not at a table"))
8496 (org-table-find-dataline)
8497 (let* ((col (max 1 (org-table-current-column)))
8498 (beg (org-table-begin))
8499 (end (org-table-end))
8500 ;; Current cursor position
8501 (linepos (org-current-line))
8502 (colpos col))
8503 (goto-char beg)
8504 (while (< (point) end)
8505 (if (org-at-table-hline-p)
8507 (org-table-goto-column col t)
8508 (insert "| "))
8509 (beginning-of-line 2))
8510 (move-marker end nil)
8511 (goto-line linepos)
8512 (org-table-goto-column colpos)
8513 (org-table-align)
8514 (org-table-fix-formulas "$" nil (1- col) 1)))
8516 (defun org-table-find-dataline ()
8517 "Find a dataline in the current table, which is needed for column commands."
8518 (if (and (org-at-table-p)
8519 (not (org-at-table-hline-p)))
8521 (let ((col (current-column))
8522 (end (org-table-end)))
8523 (move-to-column col)
8524 (while (and (< (point) end)
8525 (or (not (= (current-column) col))
8526 (org-at-table-hline-p)))
8527 (beginning-of-line 2)
8528 (move-to-column col))
8529 (if (and (org-at-table-p)
8530 (not (org-at-table-hline-p)))
8532 (error
8533 "Please position cursor in a data line for column operations")))))
8535 (defun org-table-delete-column ()
8536 "Delete a column from the table."
8537 (interactive)
8538 (if (not (org-at-table-p))
8539 (error "Not at a table"))
8540 (org-table-find-dataline)
8541 (org-table-check-inside-data-field)
8542 (let* ((col (org-table-current-column))
8543 (beg (org-table-begin))
8544 (end (org-table-end))
8545 ;; Current cursor position
8546 (linepos (org-current-line))
8547 (colpos col))
8548 (goto-char beg)
8549 (while (< (point) end)
8550 (if (org-at-table-hline-p)
8552 (org-table-goto-column col t)
8553 (and (looking-at "|[^|\n]+|")
8554 (replace-match "|")))
8555 (beginning-of-line 2))
8556 (move-marker end nil)
8557 (goto-line linepos)
8558 (org-table-goto-column colpos)
8559 (org-table-align)
8560 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8561 col -1 col)))
8563 (defun org-table-move-column-right ()
8564 "Move column to the right."
8565 (interactive)
8566 (org-table-move-column nil))
8567 (defun org-table-move-column-left ()
8568 "Move column to the left."
8569 (interactive)
8570 (org-table-move-column 'left))
8572 (defun org-table-move-column (&optional left)
8573 "Move the current column to the right. With arg LEFT, move to the left."
8574 (interactive "P")
8575 (if (not (org-at-table-p))
8576 (error "Not at a table"))
8577 (org-table-find-dataline)
8578 (org-table-check-inside-data-field)
8579 (let* ((col (org-table-current-column))
8580 (col1 (if left (1- col) col))
8581 (beg (org-table-begin))
8582 (end (org-table-end))
8583 ;; Current cursor position
8584 (linepos (org-current-line))
8585 (colpos (if left (1- col) (1+ col))))
8586 (if (and left (= col 1))
8587 (error "Cannot move column further left"))
8588 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8589 (error "Cannot move column further right"))
8590 (goto-char beg)
8591 (while (< (point) end)
8592 (if (org-at-table-hline-p)
8594 (org-table-goto-column col1 t)
8595 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8596 (replace-match "|\\2|\\1|")))
8597 (beginning-of-line 2))
8598 (move-marker end nil)
8599 (goto-line linepos)
8600 (org-table-goto-column colpos)
8601 (org-table-align)
8602 (org-table-fix-formulas
8603 "$" (list (cons (number-to-string col) (number-to-string colpos))
8604 (cons (number-to-string colpos) (number-to-string col))))))
8606 (defun org-table-move-row-down ()
8607 "Move table row down."
8608 (interactive)
8609 (org-table-move-row nil))
8610 (defun org-table-move-row-up ()
8611 "Move table row up."
8612 (interactive)
8613 (org-table-move-row 'up))
8615 (defun org-table-move-row (&optional up)
8616 "Move the current table line down. With arg UP, move it up."
8617 (interactive "P")
8618 (let* ((col (current-column))
8619 (pos (point))
8620 (hline1p (save-excursion (beginning-of-line 1)
8621 (looking-at org-table-hline-regexp)))
8622 (dline1 (org-table-current-dline))
8623 (dline2 (+ dline1 (if up -1 1)))
8624 (tonew (if up 0 2))
8625 txt hline2p)
8626 (beginning-of-line tonew)
8627 (unless (org-at-table-p)
8628 (goto-char pos)
8629 (error "Cannot move row further"))
8630 (setq hline2p (looking-at org-table-hline-regexp))
8631 (goto-char pos)
8632 (beginning-of-line 1)
8633 (setq pos (point))
8634 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8635 (delete-region (point) (1+ (point-at-eol)))
8636 (beginning-of-line tonew)
8637 (insert txt)
8638 (beginning-of-line 0)
8639 (move-to-column col)
8640 (unless (or hline1p hline2p)
8641 (org-table-fix-formulas
8642 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8643 (cons (number-to-string dline2) (number-to-string dline1)))))))
8645 (defun org-table-insert-row (&optional arg)
8646 "Insert a new row above the current line into the table.
8647 With prefix ARG, insert below the current line."
8648 (interactive "P")
8649 (if (not (org-at-table-p))
8650 (error "Not at a table"))
8651 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8652 (new (org-table-clean-line line)))
8653 ;; Fix the first field if necessary
8654 (if (string-match "^[ \t]*| *[#$] *|" line)
8655 (setq new (replace-match (match-string 0 line) t t new)))
8656 (beginning-of-line (if arg 2 1))
8657 (let (org-table-may-need-update) (insert-before-markers new "\n"))
8658 (beginning-of-line 0)
8659 (re-search-forward "| ?" (point-at-eol) t)
8660 (and (or org-table-may-need-update org-table-overlay-coordinates)
8661 (org-table-align))
8662 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8664 (defun org-table-insert-hline (&optional above)
8665 "Insert a horizontal-line below the current line into the table.
8666 With prefix ABOVE, insert above the current line."
8667 (interactive "P")
8668 (if (not (org-at-table-p))
8669 (error "Not at a table"))
8670 (let ((line (org-table-clean-line
8671 (buffer-substring (point-at-bol) (point-at-eol))))
8672 (col (current-column)))
8673 (while (string-match "|\\( +\\)|" line)
8674 (setq line (replace-match
8675 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8676 ?-) "|") t t line)))
8677 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8678 (beginning-of-line (if above 1 2))
8679 (insert line "\n")
8680 (beginning-of-line (if above 1 -1))
8681 (move-to-column col)
8682 (and org-table-overlay-coordinates (org-table-align))))
8684 (defun org-table-hline-and-move (&optional same-column)
8685 "Insert a hline and move to the row below that line."
8686 (interactive "P")
8687 (let ((col (org-table-current-column)))
8688 (org-table-maybe-eval-formula)
8689 (org-table-maybe-recalculate-line)
8690 (org-table-insert-hline)
8691 (end-of-line 2)
8692 (if (looking-at "\n[ \t]*|-")
8693 (progn (insert "\n|") (org-table-align))
8694 (org-table-next-field))
8695 (if same-column (org-table-goto-column col))))
8697 (defun org-table-clean-line (s)
8698 "Convert a table line S into a string with only \"|\" and space.
8699 In particular, this does handle wide and invisible characters."
8700 (if (string-match "^[ \t]*|-" s)
8701 ;; It's a hline, just map the characters
8702 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
8703 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8704 (setq s (replace-match
8705 (concat "|" (make-string (org-string-width (match-string 1 s))
8706 ?\ ) "|")
8707 t t s)))
8710 (defun org-table-kill-row ()
8711 "Delete the current row or horizontal line from the table."
8712 (interactive)
8713 (if (not (org-at-table-p))
8714 (error "Not at a table"))
8715 (let ((col (current-column))
8716 (dline (org-table-current-dline)))
8717 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8718 (if (not (org-at-table-p)) (beginning-of-line 0))
8719 (move-to-column col)
8720 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
8721 dline -1 dline)))
8723 (defun org-table-sort-lines (with-case &optional sorting-type)
8724 "Sort table lines according to the column at point.
8726 The position of point indicates the column to be used for
8727 sorting, and the range of lines is the range between the nearest
8728 horizontal separator lines, or the entire table of no such lines
8729 exist. If point is before the first column, you will be prompted
8730 for the sorting column. If there is an active region, the mark
8731 specifies the first line and the sorting column, while point
8732 should be in the last line to be included into the sorting.
8734 The command then prompts for the sorting type which can be
8735 alphabetically, numerically, or by time (as given in a time stamp
8736 in the field). Sorting in reverse order is also possible.
8738 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
8740 If SORTING-TYPE is specified when this function is called from a Lisp
8741 program, no prompting will take place. SORTING-TYPE must be a character,
8742 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
8743 should be done in reverse order."
8744 (interactive "P")
8745 (let* ((thisline (org-current-line))
8746 (thiscol (org-table-current-column))
8747 beg end bcol ecol tend tbeg column lns pos)
8748 (when (equal thiscol 0)
8749 (if (interactive-p)
8750 (setq thiscol
8751 (string-to-number
8752 (read-string "Use column N for sorting: ")))
8753 (setq thiscol 1))
8754 (org-table-goto-column thiscol))
8755 (org-table-check-inside-data-field)
8756 (if (org-region-active-p)
8757 (progn
8758 (setq beg (region-beginning) end (region-end))
8759 (goto-char beg)
8760 (setq column (org-table-current-column)
8761 beg (point-at-bol))
8762 (goto-char end)
8763 (setq end (point-at-bol 2)))
8764 (setq column (org-table-current-column)
8765 pos (point)
8766 tbeg (org-table-begin)
8767 tend (org-table-end))
8768 (if (re-search-backward org-table-hline-regexp tbeg t)
8769 (setq beg (point-at-bol 2))
8770 (goto-char tbeg)
8771 (setq beg (point-at-bol 1)))
8772 (goto-char pos)
8773 (if (re-search-forward org-table-hline-regexp tend t)
8774 (setq end (point-at-bol 1))
8775 (goto-char tend)
8776 (setq end (point-at-bol))))
8777 (setq beg (move-marker (make-marker) beg)
8778 end (move-marker (make-marker) end))
8779 (untabify beg end)
8780 (goto-char beg)
8781 (org-table-goto-column column)
8782 (skip-chars-backward "^|")
8783 (setq bcol (current-column))
8784 (org-table-goto-column (1+ column))
8785 (skip-chars-backward "^|")
8786 (setq ecol (1- (current-column)))
8787 (org-table-goto-column column)
8788 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8789 (org-split-string (buffer-substring beg end) "\n")))
8790 (setq lns (org-do-sort lns "Table" with-case sorting-type))
8791 (delete-region beg end)
8792 (move-marker beg nil)
8793 (move-marker end nil)
8794 (insert (mapconcat 'cdr lns "\n") "\n")
8795 (goto-line thisline)
8796 (org-table-goto-column thiscol)
8797 (message "%d lines sorted, based on column %d" (length lns) column)))
8799 (defun org-table-cut-region (beg end)
8800 "Copy region in table to the clipboard and blank all relevant fields."
8801 (interactive "r")
8802 (org-table-copy-region beg end 'cut))
8804 (defun org-table-copy-region (beg end &optional cut)
8805 "Copy rectangular region in table to clipboard.
8806 A special clipboard is used which can only be accessed
8807 with `org-table-paste-rectangle'."
8808 (interactive "rP")
8809 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8810 region cols
8811 (rpl (if cut " " nil)))
8812 (goto-char beg)
8813 (org-table-check-inside-data-field)
8814 (setq l01 (org-current-line)
8815 c01 (org-table-current-column))
8816 (goto-char end)
8817 (org-table-check-inside-data-field)
8818 (setq l02 (org-current-line)
8819 c02 (org-table-current-column))
8820 (setq l1 (min l01 l02) l2 (max l01 l02)
8821 c1 (min c01 c02) c2 (max c01 c02))
8822 (catch 'exit
8823 (while t
8824 (catch 'nextline
8825 (if (> l1 l2) (throw 'exit t))
8826 (goto-line l1)
8827 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8828 (setq cols nil ic1 c1 ic2 c2)
8829 (while (< ic1 (1+ ic2))
8830 (push (org-table-get-field ic1 rpl) cols)
8831 (setq ic1 (1+ ic1)))
8832 (push (nreverse cols) region)
8833 (setq l1 (1+ l1)))))
8834 (setq org-table-clip (nreverse region))
8835 (if cut (org-table-align))
8836 org-table-clip))
8838 (defun org-table-paste-rectangle ()
8839 "Paste a rectangular region into a table.
8840 The upper right corner ends up in the current field. All involved fields
8841 will be overwritten. If the rectangle does not fit into the present table,
8842 the table is enlarged as needed. The process ignores horizontal separator
8843 lines."
8844 (interactive)
8845 (unless (and org-table-clip (listp org-table-clip))
8846 (error "First cut/copy a region to paste!"))
8847 (org-table-check-inside-data-field)
8848 (let* ((clip org-table-clip)
8849 (line (org-current-line))
8850 (col (org-table-current-column))
8851 (org-enable-table-editor t)
8852 (org-table-automatic-realign nil)
8853 c cols field)
8854 (while (setq cols (pop clip))
8855 (while (org-at-table-hline-p) (beginning-of-line 2))
8856 (if (not (org-at-table-p))
8857 (progn (end-of-line 0) (org-table-next-field)))
8858 (setq c col)
8859 (while (setq field (pop cols))
8860 (org-table-goto-column c nil 'force)
8861 (org-table-get-field nil field)
8862 (setq c (1+ c)))
8863 (beginning-of-line 2))
8864 (goto-line line)
8865 (org-table-goto-column col)
8866 (org-table-align)))
8868 (defun org-table-convert ()
8869 "Convert from `org-mode' table to table.el and back.
8870 Obviously, this only works within limits. When an Org-mode table is
8871 converted to table.el, all horizontal separator lines get lost, because
8872 table.el uses these as cell boundaries and has no notion of horizontal lines.
8873 A table.el table can be converted to an Org-mode table only if it does not
8874 do row or column spanning. Multiline cells will become multiple cells.
8875 Beware, Org-mode does not test if the table can be successfully converted - it
8876 blindly applies a recipe that works for simple tables."
8877 (interactive)
8878 (require 'table)
8879 (if (org-at-table.el-p)
8880 ;; convert to Org-mode table
8881 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8882 (end (move-marker (make-marker) (org-table-end t))))
8883 (table-unrecognize-region beg end)
8884 (goto-char beg)
8885 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8886 (replace-match ""))
8887 (goto-char beg))
8888 (if (org-at-table-p)
8889 ;; convert to table.el table
8890 (let ((beg (move-marker (make-marker) (org-table-begin)))
8891 (end (move-marker (make-marker) (org-table-end))))
8892 ;; first, get rid of all horizontal lines
8893 (goto-char beg)
8894 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8895 (replace-match ""))
8896 ;; insert a hline before first
8897 (goto-char beg)
8898 (org-table-insert-hline 'above)
8899 (beginning-of-line -1)
8900 ;; insert a hline after each line
8901 (while (progn (beginning-of-line 3) (< (point) end))
8902 (org-table-insert-hline))
8903 (goto-char beg)
8904 (setq end (move-marker end (org-table-end)))
8905 ;; replace "+" at beginning and ending of hlines
8906 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8907 (replace-match "\\1+-"))
8908 (goto-char beg)
8909 (while (re-search-forward "-|[ \t]*$" end t)
8910 (replace-match "-+"))
8911 (goto-char beg)))))
8913 (defun org-table-wrap-region (arg)
8914 "Wrap several fields in a column like a paragraph.
8915 This is useful if you'd like to spread the contents of a field over several
8916 lines, in order to keep the table compact.
8918 If there is an active region, and both point and mark are in the same column,
8919 the text in the column is wrapped to minimum width for the given number of
8920 lines. Generally, this makes the table more compact. A prefix ARG may be
8921 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8922 formats the selected text to two lines. If the region was longer than two
8923 lines, the remaining lines remain empty. A negative prefix argument reduces
8924 the current number of lines by that amount. The wrapped text is pasted back
8925 into the table. If you formatted it to more lines than it was before, fields
8926 further down in the table get overwritten - so you might need to make space in
8927 the table first.
8929 If there is no region, the current field is split at the cursor position and
8930 the text fragment to the right of the cursor is prepended to the field one
8931 line down.
8933 If there is no region, but you specify a prefix ARG, the current field gets
8934 blank, and the content is appended to the field above."
8935 (interactive "P")
8936 (org-table-check-inside-data-field)
8937 (if (org-region-active-p)
8938 ;; There is a region: fill as a paragraph
8939 (let* ((beg (region-beginning))
8940 (cline (save-excursion (goto-char beg) (org-current-line)))
8941 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
8942 nlines)
8943 (org-table-cut-region (region-beginning) (region-end))
8944 (if (> (length (car org-table-clip)) 1)
8945 (error "Region must be limited to single column"))
8946 (setq nlines (if arg
8947 (if (< arg 1)
8948 (+ (length org-table-clip) arg)
8949 arg)
8950 (length org-table-clip)))
8951 (setq org-table-clip
8952 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8953 nil nlines)))
8954 (goto-line cline)
8955 (org-table-goto-column ccol)
8956 (org-table-paste-rectangle))
8957 ;; No region, split the current field at point
8958 (if arg
8959 ;; combine with field above
8960 (let ((s (org-table-blank-field))
8961 (col (org-table-current-column)))
8962 (beginning-of-line 0)
8963 (while (org-at-table-hline-p) (beginning-of-line 0))
8964 (org-table-goto-column col)
8965 (skip-chars-forward "^|")
8966 (skip-chars-backward " ")
8967 (insert " " (org-trim s))
8968 (org-table-align))
8969 ;; split field
8970 (when (looking-at "\\([^|]+\\)+|")
8971 (let ((s (match-string 1)))
8972 (replace-match " |")
8973 (goto-char (match-beginning 0))
8974 (org-table-next-row)
8975 (insert (org-trim s) " ")
8976 (org-table-align))))))
8978 (defvar org-field-marker nil)
8980 (defun org-table-edit-field (arg)
8981 "Edit table field in a different window.
8982 This is mainly useful for fields that contain hidden parts.
8983 When called with a \\[universal-argument] prefix, just make the full field visible so that
8984 it can be edited in place."
8985 (interactive "P")
8986 (if arg
8987 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
8988 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
8989 (remove-text-properties b e '(org-cwidth t invisible t
8990 display t intangible t))
8991 (if (and (boundp 'font-lock-mode) font-lock-mode)
8992 (font-lock-fontify-block)))
8993 (let ((pos (move-marker (make-marker) (point)))
8994 (field (org-table-get-field))
8995 (cw (current-window-configuration))
8997 (org-switch-to-buffer-other-window "*Org tmp*")
8998 (erase-buffer)
8999 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9000 (let ((org-inhibit-startup t)) (org-mode))
9001 (goto-char (setq p (point-max)))
9002 (insert (org-trim field))
9003 (remove-text-properties p (point-max)
9004 '(invisible t org-cwidth t display t
9005 intangible t))
9006 (goto-char p)
9007 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9008 (org-set-local 'org-window-configuration cw)
9009 (org-set-local 'org-field-marker pos)
9010 (message "Edit and finish with C-c C-c"))))
9012 (defun org-table-finish-edit-field ()
9013 "Finish editing a table data field.
9014 Remove all newline characters, insert the result into the table, realign
9015 the table and kill the editing buffer."
9016 (let ((pos org-field-marker)
9017 (cw org-window-configuration)
9018 (cb (current-buffer))
9019 text)
9020 (goto-char (point-min))
9021 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9022 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9023 (replace-match " "))
9024 (setq text (org-trim (buffer-string)))
9025 (set-window-configuration cw)
9026 (kill-buffer cb)
9027 (select-window (get-buffer-window (marker-buffer pos)))
9028 (goto-char pos)
9029 (move-marker pos nil)
9030 (org-table-check-inside-data-field)
9031 (org-table-get-field nil text)
9032 (org-table-align)
9033 (message "New field value inserted")))
9035 (defun org-trim (s)
9036 "Remove whitespace at beginning and end of string."
9037 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9038 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9041 (defun org-wrap (string &optional width lines)
9042 "Wrap string to either a number of lines, or a width in characters.
9043 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9044 that costs. If there is a word longer than WIDTH, the text is actually
9045 wrapped to the length of that word.
9046 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9047 many lines, whatever width that takes.
9048 The return value is a list of lines, without newlines at the end."
9049 (let* ((words (org-split-string string "[ \t\n]+"))
9050 (maxword (apply 'max (mapcar 'org-string-width words)))
9051 w ll)
9052 (cond (width
9053 (org-do-wrap words (max maxword width)))
9054 (lines
9055 (setq w maxword)
9056 (setq ll (org-do-wrap words maxword))
9057 (if (<= (length ll) lines)
9059 (setq ll words)
9060 (while (> (length ll) lines)
9061 (setq w (1+ w))
9062 (setq ll (org-do-wrap words w)))
9063 ll))
9064 (t (error "Cannot wrap this")))))
9067 (defun org-do-wrap (words width)
9068 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9069 (let (lines line)
9070 (while words
9071 (setq line (pop words))
9072 (while (and words (< (+ (length line) (length (car words))) width))
9073 (setq line (concat line " " (pop words))))
9074 (setq lines (push line lines)))
9075 (nreverse lines)))
9077 (defun org-split-string (string &optional separators)
9078 "Splits STRING into substrings at SEPARATORS.
9079 No empty strings are returned if there are matches at the beginning
9080 and end of string."
9081 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9082 (start 0)
9083 notfirst
9084 (list nil))
9085 (while (and (string-match rexp string
9086 (if (and notfirst
9087 (= start (match-beginning 0))
9088 (< start (length string)))
9089 (1+ start) start))
9090 (< (match-beginning 0) (length string)))
9091 (setq notfirst t)
9092 (or (eq (match-beginning 0) 0)
9093 (and (eq (match-beginning 0) (match-end 0))
9094 (eq (match-beginning 0) start))
9095 (setq list
9096 (cons (substring string start (match-beginning 0))
9097 list)))
9098 (setq start (match-end 0)))
9099 (or (eq start (length string))
9100 (setq list
9101 (cons (substring string start)
9102 list)))
9103 (nreverse list)))
9105 (defun org-table-map-tables (function)
9106 "Apply FUNCTION to the start of all tables in the buffer."
9107 (save-excursion
9108 (save-restriction
9109 (widen)
9110 (goto-char (point-min))
9111 (while (re-search-forward org-table-any-line-regexp nil t)
9112 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9113 (beginning-of-line 1)
9114 (if (looking-at org-table-line-regexp)
9115 (save-excursion (funcall function)))
9116 (re-search-forward org-table-any-border-regexp nil 1))))
9117 (message "Mapping tables: done"))
9119 (defvar org-timecnt) ; dynamically scoped parameter
9121 (defun org-table-sum (&optional beg end nlast)
9122 "Sum numbers in region of current table column.
9123 The result will be displayed in the echo area, and will be available
9124 as kill to be inserted with \\[yank].
9126 If there is an active region, it is interpreted as a rectangle and all
9127 numbers in that rectangle will be summed. If there is no active
9128 region and point is located in a table column, sum all numbers in that
9129 column.
9131 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9132 numbers are assumed to be times as well (in decimal hours) and the
9133 numbers are added as such.
9135 If NLAST is a number, only the NLAST fields will actually be summed."
9136 (interactive)
9137 (save-excursion
9138 (let (col (org-timecnt 0) diff h m s org-table-clip)
9139 (cond
9140 ((and beg end)) ; beg and end given explicitly
9141 ((org-region-active-p)
9142 (setq beg (region-beginning) end (region-end)))
9144 (setq col (org-table-current-column))
9145 (goto-char (org-table-begin))
9146 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9147 (error "No table data"))
9148 (org-table-goto-column col)
9149 (setq beg (point))
9150 (goto-char (org-table-end))
9151 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9152 (error "No table data"))
9153 (org-table-goto-column col)
9154 (setq end (point))))
9155 (let* ((items (apply 'append (org-table-copy-region beg end)))
9156 (items1 (cond ((not nlast) items)
9157 ((>= nlast (length items)) items)
9158 (t (setq items (reverse items))
9159 (setcdr (nthcdr (1- nlast) items) nil)
9160 (nreverse items))))
9161 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9162 items1)))
9163 (res (apply '+ numbers))
9164 (sres (if (= org-timecnt 0)
9165 (format "%g" res)
9166 (setq diff (* 3600 res)
9167 h (floor (/ diff 3600)) diff (mod diff 3600)
9168 m (floor (/ diff 60)) diff (mod diff 60)
9169 s diff)
9170 (format "%d:%02d:%02d" h m s))))
9171 (kill-new sres)
9172 (if (interactive-p)
9173 (message "%s"
9174 (substitute-command-keys
9175 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9176 (length numbers) sres))))
9177 sres))))
9179 (defun org-table-get-number-for-summing (s)
9180 (let (n)
9181 (if (string-match "^ *|? *" s)
9182 (setq s (replace-match "" nil nil s)))
9183 (if (string-match " *|? *$" s)
9184 (setq s (replace-match "" nil nil s)))
9185 (setq n (string-to-number s))
9186 (cond
9187 ((and (string-match "0" s)
9188 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9189 ((string-match "\\`[ \t]+\\'" s) nil)
9190 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9191 (let ((h (string-to-number (or (match-string 1 s) "0")))
9192 (m (string-to-number (or (match-string 2 s) "0")))
9193 (s (string-to-number (or (match-string 4 s) "0"))))
9194 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9195 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9196 ((equal n 0) nil)
9197 (t n))))
9199 (defun org-table-current-field-formula (&optional key noerror)
9200 "Return the formula active for the current field.
9201 Assumes that specials are in place.
9202 If KEY is given, return the key to this formula.
9203 Otherwise return the formula preceeded with \"=\" or \":=\"."
9204 (let* ((name (car (rassoc (list (org-current-line)
9205 (org-table-current-column))
9206 org-table-named-field-locations)))
9207 (col (org-table-current-column))
9208 (scol (int-to-string col))
9209 (ref (format "@%d$%d" (org-table-current-dline) col))
9210 (stored-list (org-table-get-stored-formulas noerror))
9211 (ass (or (assoc name stored-list)
9212 (assoc ref stored-list)
9213 (assoc scol stored-list))))
9214 (if key
9215 (car ass)
9216 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9217 (cdr ass))))))
9219 (defun org-table-get-formula (&optional equation named)
9220 "Read a formula from the minibuffer, offer stored formula as default.
9221 When NAMED is non-nil, look for a named equation."
9222 (let* ((stored-list (org-table-get-stored-formulas))
9223 (name (car (rassoc (list (org-current-line)
9224 (org-table-current-column))
9225 org-table-named-field-locations)))
9226 (ref (format "@%d$%d" (org-table-current-dline)
9227 (org-table-current-column)))
9228 (refass (assoc ref stored-list))
9229 (scol (if named
9230 (if name name ref)
9231 (int-to-string (org-table-current-column))))
9232 (dummy (and (or name refass) (not named)
9233 (not (y-or-n-p "Replace field formula with column formula? " ))
9234 (error "Abort")))
9235 (name (or name ref))
9236 (org-table-may-need-update nil)
9237 (stored (cdr (assoc scol stored-list)))
9238 (eq (cond
9239 ((and stored equation (string-match "^ *=? *$" equation))
9240 stored)
9241 ((stringp equation)
9242 equation)
9243 (t (org-table-formula-from-user
9244 (read-string
9245 (org-table-formula-to-user
9246 (format "%s formula %s%s="
9247 (if named "Field" "Column")
9248 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9249 scol))
9250 (if stored (org-table-formula-to-user stored) "")
9251 'org-table-formula-history
9252 )))))
9253 mustsave)
9254 (when (not (string-match "\\S-" eq))
9255 ;; remove formula
9256 (setq stored-list (delq (assoc scol stored-list) stored-list))
9257 (org-table-store-formulas stored-list)
9258 (error "Formula removed"))
9259 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9260 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9261 (if (and name (not named))
9262 ;; We set the column equation, delete the named one.
9263 (setq stored-list (delq (assoc name stored-list) stored-list)
9264 mustsave t))
9265 (if stored
9266 (setcdr (assoc scol stored-list) eq)
9267 (setq stored-list (cons (cons scol eq) stored-list)))
9268 (if (or mustsave (not (equal stored eq)))
9269 (org-table-store-formulas stored-list))
9270 eq))
9272 (defun org-table-store-formulas (alist)
9273 "Store the list of formulas below the current table."
9274 (setq alist (sort alist 'org-table-formula-less-p))
9275 (save-excursion
9276 (goto-char (org-table-end))
9277 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9278 (progn
9279 ;; don't overwrite TBLFM, we might use text properties to store stuff
9280 (goto-char (match-beginning 2))
9281 (delete-region (match-beginning 2) (match-end 0)))
9282 (insert "#+TBLFM:"))
9283 (insert " "
9284 (mapconcat (lambda (x)
9285 (concat
9286 (if (equal (string-to-char (car x)) ?@) "" "$")
9287 (car x) "=" (cdr x)))
9288 alist "::")
9289 "\n")))
9291 (defsubst org-table-formula-make-cmp-string (a)
9292 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9293 (concat
9294 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9295 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9296 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9298 (defun org-table-formula-less-p (a b)
9299 "Compare two formulas for sorting."
9300 (let ((as (org-table-formula-make-cmp-string (car a)))
9301 (bs (org-table-formula-make-cmp-string (car b))))
9302 (and as bs (string< as bs))))
9304 (defun org-table-get-stored-formulas (&optional noerror)
9305 "Return an alist with the stored formulas directly after current table."
9306 (interactive)
9307 (let (scol eq eq-alist strings string seen)
9308 (save-excursion
9309 (goto-char (org-table-end))
9310 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9311 (setq strings (org-split-string (match-string 2) " *:: *"))
9312 (while (setq string (pop strings))
9313 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9314 (setq scol (if (match-end 2)
9315 (match-string 2 string)
9316 (match-string 1 string))
9317 eq (match-string 3 string)
9318 eq-alist (cons (cons scol eq) eq-alist))
9319 (if (member scol seen)
9320 (if noerror
9321 (progn
9322 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9323 (ding)
9324 (sit-for 2))
9325 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9326 (push scol seen))))))
9327 (nreverse eq-alist)))
9329 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9330 "Modify the equations after the table structure has been edited.
9331 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9332 For all numbers larger than LIMIT, shift them by DELTA."
9333 (save-excursion
9334 (goto-char (org-table-end))
9335 (when (looking-at "#\\+TBLFM:")
9336 (let ((re (concat key "\\([0-9]+\\)"))
9337 (re2
9338 (when remove
9339 (if (equal key "$")
9340 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9341 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9342 s n a)
9343 (when remove
9344 (while (re-search-forward re2 (point-at-eol) t)
9345 (replace-match "")))
9346 (while (re-search-forward re (point-at-eol) t)
9347 (setq s (match-string 1) n (string-to-number s))
9348 (cond
9349 ((setq a (assoc s replace))
9350 (replace-match (concat key (cdr a)) t t))
9351 ((and limit (> n limit))
9352 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9354 (defun org-table-get-specials ()
9355 "Get the column names and local parameters for this table."
9356 (save-excursion
9357 (let ((beg (org-table-begin)) (end (org-table-end))
9358 names name fields fields1 field cnt
9359 c v l line col types dlines hlines)
9360 (setq org-table-column-names nil
9361 org-table-local-parameters nil
9362 org-table-named-field-locations nil
9363 org-table-current-begin-line nil
9364 org-table-current-begin-pos nil
9365 org-table-current-line-types nil)
9366 (goto-char beg)
9367 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9368 (setq names (org-split-string (match-string 1) " *| *")
9369 cnt 1)
9370 (while (setq name (pop names))
9371 (setq cnt (1+ cnt))
9372 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9373 (push (cons name (int-to-string cnt)) org-table-column-names))))
9374 (setq org-table-column-names (nreverse org-table-column-names))
9375 (setq org-table-column-name-regexp
9376 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9377 (goto-char beg)
9378 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9379 (setq fields (org-split-string (match-string 1) " *| *"))
9380 (while (setq field (pop fields))
9381 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9382 (push (cons (match-string 1 field) (match-string 2 field))
9383 org-table-local-parameters))))
9384 (goto-char beg)
9385 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9386 (setq c (match-string 1)
9387 fields (org-split-string (match-string 2) " *| *"))
9388 (save-excursion
9389 (beginning-of-line (if (equal c "_") 2 0))
9390 (setq line (org-current-line) col 1)
9391 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9392 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9393 (while (and fields1 (setq field (pop fields)))
9394 (setq v (pop fields1) col (1+ col))
9395 (when (and (stringp field) (stringp v)
9396 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9397 (push (cons field v) org-table-local-parameters)
9398 (push (list field line col) org-table-named-field-locations))))
9399 ;; Analyse the line types
9400 (goto-char beg)
9401 (setq org-table-current-begin-line (org-current-line)
9402 org-table-current-begin-pos (point)
9403 l org-table-current-begin-line)
9404 (while (looking-at "[ \t]*|\\(-\\)?")
9405 (push (if (match-end 1) 'hline 'dline) types)
9406 (if (match-end 1) (push l hlines) (push l dlines))
9407 (beginning-of-line 2)
9408 (setq l (1+ l)))
9409 (setq org-table-current-line-types (apply 'vector (nreverse types))
9410 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9411 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9413 (defun org-table-maybe-eval-formula ()
9414 "Check if the current field starts with \"=\" or \":=\".
9415 If yes, store the formula and apply it."
9416 ;; We already know we are in a table. Get field will only return a formula
9417 ;; when appropriate. It might return a separator line, but no problem.
9418 (when org-table-formula-evaluate-inline
9419 (let* ((field (org-trim (or (org-table-get-field) "")))
9420 named eq)
9421 (when (string-match "^:?=\\(.*\\)" field)
9422 (setq named (equal (string-to-char field) ?:)
9423 eq (match-string 1 field))
9424 (if (or (fboundp 'calc-eval)
9425 (equal (substring eq 0 (min 2 (length eq))) "'("))
9426 (org-table-eval-formula (if named '(4) nil)
9427 (org-table-formula-from-user eq))
9428 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9430 (defvar org-recalc-commands nil
9431 "List of commands triggering the recalculation of a line.
9432 Will be filled automatically during use.")
9434 (defvar org-recalc-marks
9435 '((" " . "Unmarked: no special line, no automatic recalculation")
9436 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9437 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9438 ("!" . "Column name definition line. Reference in formula as $name.")
9439 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9440 ("_" . "Names for values in row below this one.")
9441 ("^" . "Names for values in row above this one.")))
9443 (defun org-table-rotate-recalc-marks (&optional newchar)
9444 "Rotate the recalculation mark in the first column.
9445 If in any row, the first field is not consistent with a mark,
9446 insert a new column for the markers.
9447 When there is an active region, change all the lines in the region,
9448 after prompting for the marking character.
9449 After each change, a message will be displayed indicating the meaning
9450 of the new mark."
9451 (interactive)
9452 (unless (org-at-table-p) (error "Not at a table"))
9453 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9454 (beg (org-table-begin))
9455 (end (org-table-end))
9456 (l (org-current-line))
9457 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9458 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9459 (have-col
9460 (save-excursion
9461 (goto-char beg)
9462 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9463 (col (org-table-current-column))
9464 (forcenew (car (assoc newchar org-recalc-marks)))
9465 epos new)
9466 (when l1
9467 (message "Change region to what mark? Type # * ! $ or SPC: ")
9468 (setq newchar (char-to-string (read-char-exclusive))
9469 forcenew (car (assoc newchar org-recalc-marks))))
9470 (if (and newchar (not forcenew))
9471 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9472 newchar))
9473 (if l1 (goto-line l1))
9474 (save-excursion
9475 (beginning-of-line 1)
9476 (unless (looking-at org-table-dataline-regexp)
9477 (error "Not at a table data line")))
9478 (unless have-col
9479 (org-table-goto-column 1)
9480 (org-table-insert-column)
9481 (org-table-goto-column (1+ col)))
9482 (setq epos (point-at-eol))
9483 (save-excursion
9484 (beginning-of-line 1)
9485 (org-table-get-field
9486 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9487 (concat " "
9488 (setq new (or forcenew
9489 (cadr (member (match-string 1) marks))))
9490 " ")
9491 " # ")))
9492 (if (and l1 l2)
9493 (progn
9494 (goto-line l1)
9495 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9496 (and (looking-at org-table-dataline-regexp)
9497 (org-table-get-field 1 (concat " " new " "))))
9498 (goto-line l1)))
9499 (if (not (= epos (point-at-eol))) (org-table-align))
9500 (goto-line l)
9501 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9503 (defun org-table-maybe-recalculate-line ()
9504 "Recompute the current line if marked for it, and if we haven't just done it."
9505 (interactive)
9506 (and org-table-allow-automatic-line-recalculation
9507 (not (and (memq last-command org-recalc-commands)
9508 (equal org-last-recalc-line (org-current-line))))
9509 (save-excursion (beginning-of-line 1)
9510 (looking-at org-table-auto-recalculate-regexp))
9511 (org-table-recalculate) t))
9513 (defvar org-table-formula-debug nil
9514 "Non-nil means, debug table formulas.
9515 When nil, simply write \"#ERROR\" in corrupted fields.")
9516 (make-variable-buffer-local 'org-table-formula-debug)
9518 (defvar modes)
9519 (defsubst org-set-calc-mode (var &optional value)
9520 (if (stringp var)
9521 (setq var (assoc var '(("D" calc-angle-mode deg)
9522 ("R" calc-angle-mode rad)
9523 ("F" calc-prefer-frac t)
9524 ("S" calc-symbolic-mode t)))
9525 value (nth 2 var) var (nth 1 var)))
9526 (if (memq var modes)
9527 (setcar (cdr (memq var modes)) value)
9528 (cons var (cons value modes)))
9529 modes)
9531 (defun org-table-eval-formula (&optional arg equation
9532 suppress-align suppress-const
9533 suppress-store suppress-analysis)
9534 "Replace the table field value at the cursor by the result of a calculation.
9536 This function makes use of Dave Gillespie's Calc package, in my view the
9537 most exciting program ever written for GNU Emacs. So you need to have Calc
9538 installed in order to use this function.
9540 In a table, this command replaces the value in the current field with the
9541 result of a formula. It also installs the formula as the \"current\" column
9542 formula, by storing it in a special line below the table. When called
9543 with a `C-u' prefix, the current field must ba a named field, and the
9544 formula is installed as valid in only this specific field.
9546 When called with two `C-u' prefixes, insert the active equation
9547 for the field back into the current field, so that it can be
9548 edited there. This is useful in order to use \\[org-table-show-reference]
9549 to check the referenced fields.
9551 When called, the command first prompts for a formula, which is read in
9552 the minibuffer. Previously entered formulas are available through the
9553 history list, and the last used formula is offered as a default.
9554 These stored formulas are adapted correctly when moving, inserting, or
9555 deleting columns with the corresponding commands.
9557 The formula can be any algebraic expression understood by the Calc package.
9558 For details, see the Org-mode manual.
9560 This function can also be called from Lisp programs and offers
9561 additional arguments: EQUATION can be the formula to apply. If this
9562 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9563 used to speed-up recursive calls by by-passing unnecessary aligns.
9564 SUPPRESS-CONST suppresses the interpretation of constants in the
9565 formula, assuming that this has been done already outside the function.
9566 SUPPRESS-STORE means the formula should not be stored, either because
9567 it is already stored, or because it is a modified equation that should
9568 not overwrite the stored one."
9569 (interactive "P")
9570 (org-table-check-inside-data-field)
9571 (or suppress-analysis (org-table-get-specials))
9572 (if (equal arg '(16))
9573 (let ((eq (org-table-current-field-formula)))
9574 (or eq (error "No equation active for current field"))
9575 (org-table-get-field nil eq)
9576 (org-table-align)
9577 (setq org-table-may-need-update t))
9578 (let* (fields
9579 (ndown (if (integerp arg) arg 1))
9580 (org-table-automatic-realign nil)
9581 (case-fold-search nil)
9582 (down (> ndown 1))
9583 (formula (if (and equation suppress-store)
9584 equation
9585 (org-table-get-formula equation (equal arg '(4)))))
9586 (n0 (org-table-current-column))
9587 (modes (copy-sequence org-calc-default-modes))
9588 (numbers nil) ; was a variable, now fixed default
9589 (keep-empty nil)
9590 n form form0 bw fmt x ev orig c lispp literal)
9591 ;; Parse the format string. Since we have a lot of modes, this is
9592 ;; a lot of work. However, I think calc still uses most of the time.
9593 (if (string-match ";" formula)
9594 (let ((tmp (org-split-string formula ";")))
9595 (setq formula (car tmp)
9596 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9597 (nth 1 tmp)))
9598 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9599 (setq c (string-to-char (match-string 1 fmt))
9600 n (string-to-number (match-string 2 fmt)))
9601 (if (= c ?p)
9602 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9603 (setq modes (org-set-calc-mode
9604 'calc-float-format
9605 (list (cdr (assoc c '((?n . float) (?f . fix)
9606 (?s . sci) (?e . eng))))
9607 n))))
9608 (setq fmt (replace-match "" t t fmt)))
9609 (if (string-match "[NT]" fmt)
9610 (setq numbers (equal (match-string 0 fmt) "N")
9611 fmt (replace-match "" t t fmt)))
9612 (if (string-match "L" fmt)
9613 (setq literal t
9614 fmt (replace-match "" t t fmt)))
9615 (if (string-match "E" fmt)
9616 (setq keep-empty t
9617 fmt (replace-match "" t t fmt)))
9618 (while (string-match "[DRFS]" fmt)
9619 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9620 (setq fmt (replace-match "" t t fmt)))
9621 (unless (string-match "\\S-" fmt)
9622 (setq fmt nil))))
9623 (if (and (not suppress-const) org-table-formula-use-constants)
9624 (setq formula (org-table-formula-substitute-names formula)))
9625 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9626 (while (> ndown 0)
9627 (setq fields (org-split-string
9628 (org-no-properties
9629 (buffer-substring (point-at-bol) (point-at-eol)))
9630 " *| *"))
9631 (if (eq numbers t)
9632 (setq fields (mapcar
9633 (lambda (x) (number-to-string (string-to-number x)))
9634 fields)))
9635 (setq ndown (1- ndown))
9636 (setq form (copy-sequence formula)
9637 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9638 (if (and lispp literal) (setq lispp 'literal))
9639 ;; Check for old vertical references
9640 (setq form (org-rewrite-old-row-references form))
9641 ;; Insert complex ranges
9642 (while (string-match org-table-range-regexp form)
9643 (setq form
9644 (replace-match
9645 (save-match-data
9646 (org-table-make-reference
9647 (org-table-get-range (match-string 0 form) nil n0)
9648 keep-empty numbers lispp))
9649 t t form)))
9650 ;; Insert simple ranges
9651 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
9652 (setq form
9653 (replace-match
9654 (save-match-data
9655 (org-table-make-reference
9656 (org-sublist
9657 fields (string-to-number (match-string 1 form))
9658 (string-to-number (match-string 2 form)))
9659 keep-empty numbers lispp))
9660 t t form)))
9661 (setq form0 form)
9662 ;; Insert the references to fields in same row
9663 (while (string-match "\\$\\([0-9]+\\)" form)
9664 (setq n (string-to-number (match-string 1 form))
9665 x (nth (1- (if (= n 0) n0 n)) fields))
9666 (unless x (error "Invalid field specifier \"%s\""
9667 (match-string 0 form)))
9668 (setq form (replace-match
9669 (save-match-data
9670 (org-table-make-reference x nil numbers lispp))
9671 t t form)))
9673 (if lispp
9674 (setq ev (condition-case nil
9675 (eval (eval (read form)))
9676 (error "#ERROR"))
9677 ev (if (numberp ev) (number-to-string ev) ev))
9678 (or (fboundp 'calc-eval)
9679 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
9680 (setq ev (calc-eval (cons form modes)
9681 (if numbers 'num))))
9683 (when org-table-formula-debug
9684 (with-output-to-temp-buffer "*Substitution History*"
9685 (princ (format "Substitution history of formula
9686 Orig: %s
9687 $xyz-> %s
9688 @r$c-> %s
9689 $1-> %s\n" orig formula form0 form))
9690 (if (listp ev)
9691 (princ (format " %s^\nError: %s"
9692 (make-string (car ev) ?\-) (nth 1 ev)))
9693 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9694 ev (or fmt "NONE")
9695 (if fmt (format fmt (string-to-number ev)) ev)))))
9696 (setq bw (get-buffer-window "*Substitution History*"))
9697 (shrink-window-if-larger-than-buffer bw)
9698 (unless (and (interactive-p) (not ndown))
9699 (unless (let (inhibit-redisplay)
9700 (y-or-n-p "Debugging Formula. Continue to next? "))
9701 (org-table-align)
9702 (error "Abort"))
9703 (delete-window bw)
9704 (message "")))
9705 (if (listp ev) (setq fmt nil ev "#ERROR"))
9706 (org-table-justify-field-maybe
9707 (if fmt (format fmt (string-to-number ev)) ev))
9708 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9709 (call-interactively 'org-return)
9710 (setq ndown 0)))
9711 (and down (org-table-maybe-recalculate-line))
9712 (or suppress-align (and org-table-may-need-update
9713 (org-table-align))))))
9715 (defun org-table-put-field-property (prop value)
9716 (save-excursion
9717 (put-text-property (progn (skip-chars-backward "^|") (point))
9718 (progn (skip-chars-forward "^|") (point))
9719 prop value)))
9721 (defun org-table-get-range (desc &optional tbeg col highlight)
9722 "Get a calc vector from a column, accorting to descriptor DESC.
9723 Optional arguments TBEG and COL can give the beginning of the table and
9724 the current column, to avoid unnecessary parsing.
9725 HIGHLIGHT means, just highlight the range."
9726 (if (not (equal (string-to-char desc) ?@))
9727 (setq desc (concat "@" desc)))
9728 (save-excursion
9729 (or tbeg (setq tbeg (org-table-begin)))
9730 (or col (setq col (org-table-current-column)))
9731 (let ((thisline (org-current-line))
9732 beg end c1 c2 r1 r2 rangep tmp)
9733 (unless (string-match org-table-range-regexp desc)
9734 (error "Invalid table range specifier `%s'" desc))
9735 (setq rangep (match-end 3)
9736 r1 (and (match-end 1) (match-string 1 desc))
9737 r2 (and (match-end 4) (match-string 4 desc))
9738 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
9739 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
9741 (and c1 (setq c1 (+ (string-to-number c1)
9742 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
9743 (and c2 (setq c2 (+ (string-to-number c2)
9744 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
9745 (if (equal r1 "") (setq r1 nil))
9746 (if (equal r2 "") (setq r2 nil))
9747 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
9748 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
9749 ; (setq r2 (or r2 r1) c2 (or c2 c1))
9750 (if (not r1) (setq r1 thisline))
9751 (if (not r2) (setq r2 thisline))
9752 (if (not c1) (setq c1 col))
9753 (if (not c2) (setq c2 col))
9754 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
9755 ;; just one field
9756 (progn
9757 (goto-line r1)
9758 (while (not (looking-at org-table-dataline-regexp))
9759 (beginning-of-line 2))
9760 (prog1 (org-trim (org-table-get-field c1))
9761 (if highlight (org-table-highlight-rectangle (point) (point)))))
9762 ;; A range, return a vector
9763 ;; First sort the numbers to get a regular ractangle
9764 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
9765 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
9766 (goto-line r1)
9767 (while (not (looking-at org-table-dataline-regexp))
9768 (beginning-of-line 2))
9769 (org-table-goto-column c1)
9770 (setq beg (point))
9771 (goto-line r2)
9772 (while (not (looking-at org-table-dataline-regexp))
9773 (beginning-of-line 0))
9774 (org-table-goto-column c2)
9775 (setq end (point))
9776 (if highlight
9777 (org-table-highlight-rectangle
9778 beg (progn (skip-chars-forward "^|\n") (point))))
9779 ;; return string representation of calc vector
9780 (mapcar 'org-trim
9781 (apply 'append (org-table-copy-region beg end)))))))
9783 (defun org-table-get-descriptor-line (desc &optional cline bline table)
9784 "Analyze descriptor DESC and retrieve the corresponding line number.
9785 The cursor is currently in line CLINE, the table begins in line BLINE,
9786 and TABLE is a vector with line types."
9787 (if (string-match "^[0-9]+$" desc)
9788 (aref org-table-dlines (string-to-number desc))
9789 (setq cline (or cline (org-current-line))
9790 bline (or bline org-table-current-begin-line)
9791 table (or table org-table-current-line-types))
9792 (if (or
9793 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
9794 ;; 1 2 3 4 5 6
9795 (and (not (match-end 3)) (not (match-end 6)))
9796 (and (match-end 3) (match-end 6) (not (match-end 5))))
9797 (error "invalid row descriptor `%s'" desc))
9798 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
9799 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
9800 (odir (and (match-end 5) (match-string 5 desc)))
9801 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
9802 (i (- cline bline))
9803 (rel (and (match-end 6)
9804 (or (and (match-end 1) (not (match-end 3)))
9805 (match-end 5)))))
9806 (if (and hn (not hdir))
9807 (progn
9808 (setq i 0 hdir "+")
9809 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
9810 (if (and (not hn) on (not odir))
9811 (error "should never happen");;(aref org-table-dlines on)
9812 (if (and hn (> hn 0))
9813 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
9814 (if on
9815 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
9816 (+ bline i)))))
9818 (defun org-find-row-type (table i type backwards relative n)
9819 (let ((l (length table)))
9820 (while (> n 0)
9821 (while (and (setq i (+ i (if backwards -1 1)))
9822 (>= i 0) (< i l)
9823 (not (eq (aref table i) type))
9824 (if (and relative (eq (aref table i) 'hline))
9825 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
9826 t)))
9827 (setq n (1- n)))
9828 (if (or (< i 0) (>= i l))
9829 (error "Row descriptior leads outside table")
9830 i)))
9832 (defun org-rewrite-old-row-references (s)
9833 (if (string-match "&[-+0-9I]" s)
9834 (error "Formula contains old &row reference, please rewrite using @-syntax")
9837 (defun org-table-make-reference (elements keep-empty numbers lispp)
9838 "Convert list ELEMENTS to something appropriate to insert into formula.
9839 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
9840 NUMBERS indicates that everything should be converted to numbers.
9841 LISPP means to return something appropriate for a Lisp list."
9842 (if (stringp elements) ; just a single val
9843 (if lispp
9844 (if (eq lispp 'literal)
9845 elements
9846 (prin1-to-string (if numbers (string-to-number elements) elements)))
9847 (if (equal elements "") (setq elements "0"))
9848 (if numbers (number-to-string (string-to-number elements)) elements))
9849 (unless keep-empty
9850 (setq elements
9851 (delq nil
9852 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
9853 elements))))
9854 (setq elements (or elements '("0")))
9855 (if lispp
9856 (mapconcat
9857 (lambda (x)
9858 (if (eq lispp 'literal)
9860 (prin1-to-string (if numbers (string-to-number x) x))))
9861 elements " ")
9862 (concat "[" (mapconcat
9863 (lambda (x)
9864 (if numbers (number-to-string (string-to-number x)) x))
9865 elements
9866 ",") "]"))))
9868 (defun org-table-recalculate (&optional all noalign)
9869 "Recalculate the current table line by applying all stored formulas.
9870 With prefix arg ALL, do this for all lines in the table."
9871 (interactive "P")
9872 (or (memq this-command org-recalc-commands)
9873 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9874 (unless (org-at-table-p) (error "Not at a table"))
9875 (if (equal all '(16))
9876 (org-table-iterate)
9877 (org-table-get-specials)
9878 (let* ((eqlist (sort (org-table-get-stored-formulas)
9879 (lambda (a b) (string< (car a) (car b)))))
9880 (inhibit-redisplay (not debug-on-error))
9881 (line-re org-table-dataline-regexp)
9882 (thisline (org-current-line))
9883 (thiscol (org-table-current-column))
9884 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
9885 ;; Insert constants in all formulas
9886 (setq eqlist
9887 (mapcar (lambda (x)
9888 (setcdr x (org-table-formula-substitute-names (cdr x)))
9890 eqlist))
9891 ;; Split the equation list
9892 (while (setq eq (pop eqlist))
9893 (if (<= (string-to-char (car eq)) ?9)
9894 (push eq eqlnum)
9895 (push eq eqlname)))
9896 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9897 (if all
9898 (progn
9899 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9900 (goto-char (setq beg (org-table-begin)))
9901 (if (re-search-forward org-table-calculate-mark-regexp end t)
9902 ;; This is a table with marked lines, compute selected lines
9903 (setq line-re org-table-recalculate-regexp)
9904 ;; Move forward to the first non-header line
9905 (if (and (re-search-forward org-table-dataline-regexp end t)
9906 (re-search-forward org-table-hline-regexp end t)
9907 (re-search-forward org-table-dataline-regexp end t))
9908 (setq beg (match-beginning 0))
9909 nil))) ;; just leave beg where it is
9910 (setq beg (point-at-bol)
9911 end (move-marker (make-marker) (1+ (point-at-eol)))))
9912 (goto-char beg)
9913 (and all (message "Re-applying formulas to full table..."))
9915 ;; First find the named fields, and mark them untouchanble
9916 (remove-text-properties beg end '(org-untouchable t))
9917 (while (setq eq (pop eqlname))
9918 (setq name (car eq)
9919 a (assoc name org-table-named-field-locations))
9920 (and (not a)
9921 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
9922 (setq a (list name
9923 (aref org-table-dlines
9924 (string-to-number (match-string 1 name)))
9925 (string-to-number (match-string 2 name)))))
9926 (when (and a (or all (equal (nth 1 a) thisline)))
9927 (message "Re-applying formula to field: %s" name)
9928 (goto-line (nth 1 a))
9929 (org-table-goto-column (nth 2 a))
9930 (push (append a (list (cdr eq))) eqlname1)
9931 (org-table-put-field-property :org-untouchable t)))
9933 ;; Now evauluate the column formulas, but skip fields covered by
9934 ;; field formulas
9935 (goto-char beg)
9936 (while (re-search-forward line-re end t)
9937 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
9938 ;; Unprotected line, recalculate
9939 (and all (message "Re-applying formulas to full table...(line %d)"
9940 (setq cnt (1+ cnt))))
9941 (setq org-last-recalc-line (org-current-line))
9942 (setq eql eqlnum)
9943 (while (setq entry (pop eql))
9944 (goto-line org-last-recalc-line)
9945 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9946 (unless (get-text-property (point) :org-untouchable)
9947 (org-table-eval-formula nil (cdr entry)
9948 'noalign 'nocst 'nostore 'noanalysis)))))
9950 ;; Now evaluate the field formulas
9951 (while (setq eq (pop eqlname1))
9952 (message "Re-applying formula to field: %s" (car eq))
9953 (goto-line (nth 1 eq))
9954 (org-table-goto-column (nth 2 eq))
9955 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
9956 'nostore 'noanalysis))
9958 (goto-line thisline)
9959 (org-table-goto-column thiscol)
9960 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
9961 (or noalign (and org-table-may-need-update (org-table-align))
9962 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9964 ;; back to initial position
9965 (message "Re-applying formulas...done")
9966 (goto-line thisline)
9967 (org-table-goto-column thiscol)
9968 (or noalign (and org-table-may-need-update (org-table-align))
9969 (and all (message "Re-applying formulas...done"))))))
9971 (defun org-table-iterate (&optional arg)
9972 "Recalculate the table until it does not change anymore."
9973 (interactive "P")
9974 (let ((imax (if arg (prefix-numeric-value arg) 10))
9975 (i 0)
9976 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
9977 thistbl)
9978 (catch 'exit
9979 (while (< i imax)
9980 (setq i (1+ i))
9981 (org-table-recalculate 'all)
9982 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
9983 (if (not (string= lasttbl thistbl))
9984 (setq lasttbl thistbl)
9985 (if (> i 1)
9986 (message "Convergence after %d iterations" i)
9987 (message "Table was already stable"))
9988 (throw 'exit t)))
9989 (error "No convergence after %d iterations" i))))
9991 (defun org-table-formula-substitute-names (f)
9992 "Replace $const with values in string F."
9993 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
9994 ;; First, check for column names
9995 (while (setq start (string-match org-table-column-name-regexp f start))
9996 (setq start (1+ start))
9997 (setq a (assoc (match-string 1 f) org-table-column-names))
9998 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9999 ;; Parameters and constants
10000 (setq start 0)
10001 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10002 (setq start (1+ start))
10003 (if (setq a (save-match-data
10004 (org-table-get-constant (match-string 1 f))))
10005 (setq f (replace-match
10006 (concat (if pp "(") a (if pp ")")) t t f))))
10007 (if org-table-formula-debug
10008 (put-text-property 0 (length f) :orig-formula f1 f))
10011 (defun org-table-get-constant (const)
10012 "Find the value for a parameter or constant in a formula.
10013 Parameters get priority."
10014 (or (cdr (assoc const org-table-local-parameters))
10015 (cdr (assoc const org-table-formula-constants-local))
10016 (cdr (assoc const org-table-formula-constants))
10017 (and (fboundp 'constants-get) (constants-get const))
10018 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10019 (org-entry-get nil (substring const 5) 'inherit))
10020 "#UNDEFINED_NAME"))
10022 (defvar org-table-fedit-map
10023 (let ((map (make-sparse-keymap)))
10024 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10025 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10026 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10027 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10028 (org-defkey map "\C-c?" 'org-table-show-reference)
10029 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10030 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10031 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10032 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10033 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10034 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10035 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10036 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10037 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10038 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10039 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10040 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10041 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10042 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10043 map))
10045 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10046 '("Edit-Formulas"
10047 ["Finish and Install" org-table-fedit-finish t]
10048 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10049 ["Abort" org-table-fedit-abort t]
10050 "--"
10051 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10052 ["Complete Lisp Symbol" lisp-complete-symbol t]
10053 "--"
10054 "Shift Reference at Point"
10055 ["Up" org-table-fedit-ref-up t]
10056 ["Down" org-table-fedit-ref-down t]
10057 ["Left" org-table-fedit-ref-left t]
10058 ["Right" org-table-fedit-ref-right t]
10060 "Change Test Row for Column Formulas"
10061 ["Up" org-table-fedit-line-up t]
10062 ["Down" org-table-fedit-line-down t]
10063 "--"
10064 ["Scroll Table Window" org-table-fedit-scroll t]
10065 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10066 ["Show Table Grid" org-table-fedit-toggle-coordinates
10067 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10068 org-table-overlay-coordinates)]
10069 "--"
10070 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10071 :style toggle :selected org-table-buffer-is-an]))
10073 (defvar org-pos)
10075 (defun org-table-edit-formulas ()
10076 "Edit the formulas of the current table in a separate buffer."
10077 (interactive)
10078 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10079 (beginning-of-line 0))
10080 (unless (org-at-table-p) (error "Not at a table"))
10081 (org-table-get-specials)
10082 (let ((key (org-table-current-field-formula 'key 'noerror))
10083 (eql (sort (org-table-get-stored-formulas 'noerror)
10084 'org-table-formula-less-p))
10085 (pos (move-marker (make-marker) (point)))
10086 (startline 1)
10087 (wc (current-window-configuration))
10088 (titles '((column . "# Column Formulas\n")
10089 (field . "# Field Formulas\n")
10090 (named . "# Named Field Formulas\n")))
10091 entry s type title)
10092 (org-switch-to-buffer-other-window "*Edit Formulas*")
10093 (erase-buffer)
10094 ;; Keep global-font-lock-mode from turning on font-lock-mode
10095 (let ((font-lock-global-modes '(not fundamental-mode)))
10096 (fundamental-mode))
10097 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10098 (org-set-local 'org-pos pos)
10099 (org-set-local 'org-window-configuration wc)
10100 (use-local-map org-table-fedit-map)
10101 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10102 (easy-menu-add org-table-fedit-menu)
10103 (setq startline (org-current-line))
10104 (while (setq entry (pop eql))
10105 (setq type (cond
10106 ((equal (string-to-char (car entry)) ?@) 'field)
10107 ((string-match "^[0-9]" (car entry)) 'column)
10108 (t 'named)))
10109 (when (setq title (assq type titles))
10110 (or (bobp) (insert "\n"))
10111 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10112 (setq titles (delq title titles)))
10113 (if (equal key (car entry)) (setq startline (org-current-line)))
10114 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10115 (car entry) " = " (cdr entry) "\n"))
10116 (remove-text-properties 0 (length s) '(face nil) s)
10117 (insert s))
10118 (if (eq org-table-use-standard-references t)
10119 (org-table-fedit-toggle-ref-type))
10120 (goto-line startline)
10121 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10123 (defun org-table-fedit-post-command ()
10124 (when (not (memq this-command '(lisp-complete-symbol)))
10125 (let ((win (selected-window)))
10126 (save-excursion
10127 (condition-case nil
10128 (org-table-show-reference)
10129 (error nil))
10130 (select-window win)))))
10132 (defun org-table-formula-to-user (s)
10133 "Convert a formula from internal to user representation."
10134 (if (eq org-table-use-standard-references t)
10135 (org-table-convert-refs-to-an s)
10138 (defun org-table-formula-from-user (s)
10139 "Convert a formula from user to internal representation."
10140 (if org-table-use-standard-references
10141 (org-table-convert-refs-to-rc s)
10144 (defun org-table-convert-refs-to-rc (s)
10145 "Convert spreadsheet references from AB7 to @7$28.
10146 Works for single references, but also for entire formulas and even the
10147 full TBLFM line."
10148 (let ((start 0))
10149 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10150 (cond
10151 ((match-end 3)
10152 ;; format match, just advance
10153 (setq start (match-end 0)))
10154 ((and (> (match-beginning 0) 0)
10155 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10156 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10157 ;; 3.e5 or something like this.
10158 (setq start (match-end 0)))
10160 (setq start (match-beginning 0)
10161 s (replace-match
10162 (if (equal (match-string 2 s) "&")
10163 (format "$%d" (org-letters-to-number (match-string 1 s)))
10164 (format "@%d$%d"
10165 (string-to-number (match-string 2 s))
10166 (org-letters-to-number (match-string 1 s))))
10167 t t s)))))
10170 (defun org-table-convert-refs-to-an (s)
10171 "Convert spreadsheet references from to @7$28 to AB7.
10172 Works for single references, but also for entire formulas and even the
10173 full TBLFM line."
10174 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10175 (setq s (replace-match
10176 (format "%s%d"
10177 (org-number-to-letters
10178 (string-to-number (match-string 2 s)))
10179 (string-to-number (match-string 1 s)))
10180 t t s)))
10181 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10182 (setq s (replace-match (concat "\\1"
10183 (org-number-to-letters
10184 (string-to-number (match-string 2 s))) "&")
10185 t nil s)))
10188 (defun org-letters-to-number (s)
10189 "Convert a base 26 number represented by letters into an integer.
10190 For example: AB -> 28."
10191 (let ((n 0))
10192 (setq s (upcase s))
10193 (while (> (length s) 0)
10194 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10195 s (substring s 1)))
10198 (defun org-number-to-letters (n)
10199 "Convert an integer into a base 26 number represented by letters.
10200 For example: 28 -> AB."
10201 (let ((s ""))
10202 (while (> n 0)
10203 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10204 n (/ (1- n) 26)))
10207 (defun org-table-fedit-convert-buffer (function)
10208 "Convert all references in this buffer, using FUNTION."
10209 (let ((line (org-current-line)))
10210 (goto-char (point-min))
10211 (while (not (eobp))
10212 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10213 (delete-region (point) (point-at-eol))
10214 (or (eobp) (forward-char 1)))
10215 (goto-line line)))
10217 (defun org-table-fedit-toggle-ref-type ()
10218 "Convert all references in the buffer from B3 to @3$2 and back."
10219 (interactive)
10220 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10221 (org-table-fedit-convert-buffer
10222 (if org-table-buffer-is-an
10223 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10224 (message "Reference type switched to %s"
10225 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10227 (defun org-table-fedit-ref-up ()
10228 "Shift the reference at point one row/hline up."
10229 (interactive)
10230 (org-table-fedit-shift-reference 'up))
10231 (defun org-table-fedit-ref-down ()
10232 "Shift the reference at point one row/hline down."
10233 (interactive)
10234 (org-table-fedit-shift-reference 'down))
10235 (defun org-table-fedit-ref-left ()
10236 "Shift the reference at point one field to the left."
10237 (interactive)
10238 (org-table-fedit-shift-reference 'left))
10239 (defun org-table-fedit-ref-right ()
10240 "Shift the reference at point one field to the right."
10241 (interactive)
10242 (org-table-fedit-shift-reference 'right))
10244 (defun org-table-fedit-shift-reference (dir)
10245 (cond
10246 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10247 (if (memq dir '(left right))
10248 (org-rematch-and-replace 1 (eq dir 'left))
10249 (error "Cannot shift reference in this direction")))
10250 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10251 ;; A B3-like reference
10252 (if (memq dir '(up down))
10253 (org-rematch-and-replace 2 (eq dir 'up))
10254 (org-rematch-and-replace 1 (eq dir 'left))))
10255 ((org-at-regexp-p
10256 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10257 ;; An internal reference
10258 (if (memq dir '(up down))
10259 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10260 (org-rematch-and-replace 5 (eq dir 'left))))))
10262 (defun org-rematch-and-replace (n &optional decr hline)
10263 "Re-match the group N, and replace it with the shifted refrence."
10264 (or (match-end n) (error "Cannot shift reference in this direction"))
10265 (goto-char (match-beginning n))
10266 (and (looking-at (regexp-quote (match-string n)))
10267 (replace-match (org-shift-refpart (match-string 0) decr hline)
10268 t t)))
10270 (defun org-shift-refpart (ref &optional decr hline)
10271 "Shift a refrence part REF.
10272 If DECR is set, decrease the references row/column, else increase.
10273 If HLINE is set, this may be a hline reference, it certainly is not
10274 a translation reference."
10275 (save-match-data
10276 (let* ((sign (string-match "^[-+]" ref)) n)
10278 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10279 (cond
10280 ((and hline (string-match "^I+" ref))
10281 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10282 (setq n (+ n (if decr -1 1)))
10283 (if (= n 0) (setq n (+ n (if decr -1 1))))
10284 (if sign
10285 (setq sign (if (< n 0) "-" "+") n (abs n))
10286 (setq n (max 1 n)))
10287 (concat sign (make-string n ?I)))
10289 ((string-match "^[0-9]+" ref)
10290 (setq n (string-to-number (concat sign ref)))
10291 (setq n (+ n (if decr -1 1)))
10292 (if sign
10293 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10294 (number-to-string (max 1 n))))
10296 ((string-match "^[a-zA-Z]+" ref)
10297 (org-number-to-letters
10298 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10300 (t (error "Cannot shift reference"))))))
10302 (defun org-table-fedit-toggle-coordinates ()
10303 "Toggle the display of coordinates in the refrenced table."
10304 (interactive)
10305 (let ((pos (marker-position org-pos)))
10306 (with-current-buffer (marker-buffer org-pos)
10307 (save-excursion
10308 (goto-char pos)
10309 (org-table-toggle-coordinate-overlays)))))
10311 (defun org-table-fedit-finish (&optional arg)
10312 "Parse the buffer for formula definitions and install them.
10313 With prefix ARG, apply the new formulas to the table."
10314 (interactive "P")
10315 (org-table-remove-rectangle-highlight)
10316 (if org-table-use-standard-references
10317 (progn
10318 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10319 (setq org-table-buffer-is-an nil)))
10320 (let ((pos org-pos) eql var form)
10321 (goto-char (point-min))
10322 (while (re-search-forward
10323 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10324 nil t)
10325 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10326 form (match-string 3))
10327 (setq form (org-trim form))
10328 (when (not (equal form ""))
10329 (while (string-match "[ \t]*\n[ \t]*" form)
10330 (setq form (replace-match " " t t form)))
10331 (when (assoc var eql)
10332 (error "Double formulas for %s" var))
10333 (push (cons var form) eql)))
10334 (setq org-pos nil)
10335 (set-window-configuration org-window-configuration)
10336 (select-window (get-buffer-window (marker-buffer pos)))
10337 (goto-char pos)
10338 (unless (org-at-table-p)
10339 (error "Lost table position - cannot install formulae"))
10340 (org-table-store-formulas eql)
10341 (move-marker pos nil)
10342 (kill-buffer "*Edit Formulas*")
10343 (if arg
10344 (org-table-recalculate 'all)
10345 (message "New formulas installed - press C-u C-c C-c to apply."))))
10347 (defun org-table-fedit-abort ()
10348 "Abort editing formulas, without installing the changes."
10349 (interactive)
10350 (org-table-remove-rectangle-highlight)
10351 (let ((pos org-pos))
10352 (set-window-configuration org-window-configuration)
10353 (select-window (get-buffer-window (marker-buffer pos)))
10354 (goto-char pos)
10355 (move-marker pos nil)
10356 (message "Formula editing aborted without installing changes")))
10358 (defun org-table-fedit-lisp-indent ()
10359 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10360 (interactive)
10361 (let ((pos (point)) beg end ind)
10362 (beginning-of-line 1)
10363 (cond
10364 ((looking-at "[ \t]")
10365 (goto-char pos)
10366 (call-interactively 'lisp-indent-line))
10367 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10368 ((not (fboundp 'pp-buffer))
10369 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10370 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10371 (goto-char (- (match-end 0) 2))
10372 (setq beg (point))
10373 (setq ind (make-string (current-column) ?\ ))
10374 (condition-case nil (forward-sexp 1)
10375 (error
10376 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10377 (setq end (point))
10378 (save-restriction
10379 (narrow-to-region beg end)
10380 (if (eq last-command this-command)
10381 (progn
10382 (goto-char (point-min))
10383 (setq this-command nil)
10384 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10385 (replace-match " ")))
10386 (pp-buffer)
10387 (untabify (point-min) (point-max))
10388 (goto-char (1+ (point-min)))
10389 (while (re-search-forward "^." nil t)
10390 (beginning-of-line 1)
10391 (insert ind))
10392 (goto-char (point-max))
10393 (backward-delete-char 1)))
10394 (goto-char beg))
10395 (t nil))))
10397 (defvar org-show-positions nil)
10399 (defun org-table-show-reference (&optional local)
10400 "Show the location/value of the $ expression at point."
10401 (interactive)
10402 (org-table-remove-rectangle-highlight)
10403 (catch 'exit
10404 (let ((pos (if local (point) org-pos))
10405 (face2 'highlight)
10406 (org-inhibit-highlight-removal t)
10407 (win (selected-window))
10408 (org-show-positions nil)
10409 var name e what match dest)
10410 (if local (org-table-get-specials))
10411 (setq what (cond
10412 ((or (org-at-regexp-p org-table-range-regexp2)
10413 (org-at-regexp-p org-table-translate-regexp)
10414 (org-at-regexp-p org-table-range-regexp))
10415 (setq match
10416 (save-match-data
10417 (org-table-convert-refs-to-rc (match-string 0))))
10418 'range)
10419 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10420 ((org-at-regexp-p "\\$[0-9]+") 'column)
10421 ((not local) nil)
10422 (t (error "No reference at point")))
10423 match (and what (or match (match-string 0))))
10424 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10425 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10426 'secondary-selection))
10427 (org-add-hook 'before-change-functions
10428 'org-table-remove-rectangle-highlight)
10429 (if (eq what 'name) (setq var (substring match 1)))
10430 (when (eq what 'range)
10431 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10432 (setq match (org-table-formula-substitute-names match)))
10433 (unless local
10434 (save-excursion
10435 (end-of-line 1)
10436 (re-search-backward "^\\S-" nil t)
10437 (beginning-of-line 1)
10438 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10439 (setq dest
10440 (save-match-data
10441 (org-table-convert-refs-to-rc (match-string 1))))
10442 (org-table-add-rectangle-overlay
10443 (match-beginning 1) (match-end 1) face2))))
10444 (if (and (markerp pos) (marker-buffer pos))
10445 (if (get-buffer-window (marker-buffer pos))
10446 (select-window (get-buffer-window (marker-buffer pos)))
10447 (org-switch-to-buffer-other-window (get-buffer-window
10448 (marker-buffer pos)))))
10449 (goto-char pos)
10450 (org-table-force-dataline)
10451 (when dest
10452 (setq name (substring dest 1))
10453 (cond
10454 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10455 (setq e (assoc name org-table-named-field-locations))
10456 (goto-line (nth 1 e))
10457 (org-table-goto-column (nth 2 e)))
10458 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10459 (let ((l (string-to-number (match-string 1 dest)))
10460 (c (string-to-number (match-string 2 dest))))
10461 (goto-line (aref org-table-dlines l))
10462 (org-table-goto-column c)))
10463 (t (org-table-goto-column (string-to-number name))))
10464 (move-marker pos (point))
10465 (org-table-highlight-rectangle nil nil face2))
10466 (cond
10467 ((equal dest match))
10468 ((not match))
10469 ((eq what 'range)
10470 (condition-case nil
10471 (save-excursion
10472 (org-table-get-range match nil nil 'highlight))
10473 (error nil)))
10474 ((setq e (assoc var org-table-named-field-locations))
10475 (goto-line (nth 1 e))
10476 (org-table-goto-column (nth 2 e))
10477 (org-table-highlight-rectangle (point) (point))
10478 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10479 ((setq e (assoc var org-table-column-names))
10480 (org-table-goto-column (string-to-number (cdr e)))
10481 (org-table-highlight-rectangle (point) (point))
10482 (goto-char (org-table-begin))
10483 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10484 (org-table-end) t)
10485 (progn
10486 (goto-char (match-beginning 1))
10487 (org-table-highlight-rectangle)
10488 (message "Named column (column %s)" (cdr e)))
10489 (error "Column name not found")))
10490 ((eq what 'column)
10491 ;; column number
10492 (org-table-goto-column (string-to-number (substring match 1)))
10493 (org-table-highlight-rectangle (point) (point))
10494 (message "Column %s" (substring match 1)))
10495 ((setq e (assoc var org-table-local-parameters))
10496 (goto-char (org-table-begin))
10497 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10498 (progn
10499 (goto-char (match-beginning 1))
10500 (org-table-highlight-rectangle)
10501 (message "Local parameter."))
10502 (error "Parameter not found")))
10504 (cond
10505 ((not var) (error "No reference at point"))
10506 ((setq e (assoc var org-table-formula-constants-local))
10507 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10508 var (cdr e)))
10509 ((setq e (assoc var org-table-formula-constants))
10510 (message "Constant: $%s=%s in `org-table-formula-constants'."
10511 var (cdr e)))
10512 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10513 (message "Constant: $%s=%s, from `constants.el'%s."
10514 var e (format " (%s units)" constants-unit-system)))
10515 (t (error "Undefined name $%s" var)))))
10516 (goto-char pos)
10517 (when (and org-show-positions
10518 (not (memq this-command '(org-table-fedit-scroll
10519 org-table-fedit-scroll-down))))
10520 (push pos org-show-positions)
10521 (push org-table-current-begin-pos org-show-positions)
10522 (let ((min (apply 'min org-show-positions))
10523 (max (apply 'max org-show-positions)))
10524 (goto-char min) (recenter 0)
10525 (goto-char max)
10526 (or (pos-visible-in-window-p max) (recenter -1))))
10527 (select-window win))))
10529 (defun org-table-force-dataline ()
10530 "Make sure the cursor is in a dataline in a table."
10531 (unless (save-excursion
10532 (beginning-of-line 1)
10533 (looking-at org-table-dataline-regexp))
10534 (let* ((re org-table-dataline-regexp)
10535 (p1 (save-excursion (re-search-forward re nil 'move)))
10536 (p2 (save-excursion (re-search-backward re nil 'move))))
10537 (cond ((and p1 p2)
10538 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10539 p1 p2)))
10540 ((or p1 p2) (goto-char (or p1 p2)))
10541 (t (error "No table dataline around here"))))))
10543 (defun org-table-fedit-line-up ()
10544 "Move cursor one line up in the window showing the table."
10545 (interactive)
10546 (org-table-fedit-move 'previous-line))
10548 (defun org-table-fedit-line-down ()
10549 "Move cursor one line down in the window showing the table."
10550 (interactive)
10551 (org-table-fedit-move 'next-line))
10553 (defun org-table-fedit-move (command)
10554 "Move the cursor in the window shoinw the table.
10555 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10556 (let ((org-table-allow-automatic-line-recalculation nil)
10557 (pos org-pos) (win (selected-window)) p)
10558 (select-window (get-buffer-window (marker-buffer org-pos)))
10559 (setq p (point))
10560 (call-interactively command)
10561 (while (and (org-at-table-p)
10562 (org-at-table-hline-p))
10563 (call-interactively command))
10564 (or (org-at-table-p) (goto-char p))
10565 (move-marker pos (point))
10566 (select-window win)))
10568 (defun org-table-fedit-scroll (N)
10569 (interactive "p")
10570 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10571 (scroll-other-window N)))
10573 (defun org-table-fedit-scroll-down (N)
10574 (interactive "p")
10575 (org-table-fedit-scroll (- N)))
10577 (defvar org-table-rectangle-overlays nil)
10579 (defun org-table-add-rectangle-overlay (beg end &optional face)
10580 "Add a new overlay."
10581 (let ((ov (org-make-overlay beg end)))
10582 (org-overlay-put ov 'face (or face 'secondary-selection))
10583 (push ov org-table-rectangle-overlays)))
10585 (defun org-table-highlight-rectangle (&optional beg end face)
10586 "Highlight rectangular region in a table."
10587 (setq beg (or beg (point)) end (or end (point)))
10588 (let ((b (min beg end))
10589 (e (max beg end))
10590 l1 c1 l2 c2 tmp)
10591 (and (boundp 'org-show-positions)
10592 (setq org-show-positions (cons b (cons e org-show-positions))))
10593 (goto-char (min beg end))
10594 (setq l1 (org-current-line)
10595 c1 (org-table-current-column))
10596 (goto-char (max beg end))
10597 (setq l2 (org-current-line)
10598 c2 (org-table-current-column))
10599 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10600 (goto-line l1)
10601 (beginning-of-line 1)
10602 (loop for line from l1 to l2 do
10603 (when (looking-at org-table-dataline-regexp)
10604 (org-table-goto-column c1)
10605 (skip-chars-backward "^|\n") (setq beg (point))
10606 (org-table-goto-column c2)
10607 (skip-chars-forward "^|\n") (setq end (point))
10608 (org-table-add-rectangle-overlay beg end face))
10609 (beginning-of-line 2))
10610 (goto-char b))
10611 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10613 (defun org-table-remove-rectangle-highlight (&rest ignore)
10614 "Remove the rectangle overlays."
10615 (unless org-inhibit-highlight-removal
10616 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10617 (mapc 'org-delete-overlay org-table-rectangle-overlays)
10618 (setq org-table-rectangle-overlays nil)))
10620 (defvar org-table-coordinate-overlays nil
10621 "Collects the cooordinate grid overlays, so that they can be removed.")
10622 (make-variable-buffer-local 'org-table-coordinate-overlays)
10624 (defun org-table-overlay-coordinates ()
10625 "Add overlays to the table at point, to show row/column coordinates."
10626 (interactive)
10627 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10628 (setq org-table-coordinate-overlays nil)
10629 (save-excursion
10630 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10631 (goto-char (org-table-begin))
10632 (while (org-at-table-p)
10633 (setq eol (point-at-eol))
10634 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10635 (push ov org-table-coordinate-overlays)
10636 (setq hline (looking-at org-table-hline-regexp))
10637 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10638 (format "%4d" (setq id (1+ id)))))
10639 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10640 (when hline
10641 (setq ic 0)
10642 (while (re-search-forward "[+|]\\(-+\\)" eol t)
10643 (setq beg (1+ (match-beginning 0))
10644 ic (1+ ic)
10645 s1 (concat "$" (int-to-string ic))
10646 s2 (org-number-to-letters ic)
10647 str (if (eq org-table-use-standard-references t) s2 s1))
10648 (setq ov (org-make-overlay beg (+ beg (length str))))
10649 (push ov org-table-coordinate-overlays)
10650 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10651 (beginning-of-line 2)))))
10653 (defun org-table-toggle-coordinate-overlays ()
10654 "Toggle the display of Row/Column numbers in tables."
10655 (interactive)
10656 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10657 (message "Row/Column number display turned %s"
10658 (if org-table-overlay-coordinates "on" "off"))
10659 (if (and (org-at-table-p) org-table-overlay-coordinates)
10660 (org-table-align))
10661 (unless org-table-overlay-coordinates
10662 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10663 (setq org-table-coordinate-overlays nil)))
10665 (defun org-table-toggle-formula-debugger ()
10666 "Toggle the formula debugger in tables."
10667 (interactive)
10668 (setq org-table-formula-debug (not org-table-formula-debug))
10669 (message "Formula debugging has been turned %s"
10670 (if org-table-formula-debug "on" "off")))
10672 ;;; The orgtbl minor mode
10674 ;; Define a minor mode which can be used in other modes in order to
10675 ;; integrate the org-mode table editor.
10677 ;; This is really a hack, because the org-mode table editor uses several
10678 ;; keys which normally belong to the major mode, for example the TAB and
10679 ;; RET keys. Here is how it works: The minor mode defines all the keys
10680 ;; necessary to operate the table editor, but wraps the commands into a
10681 ;; function which tests if the cursor is currently inside a table. If that
10682 ;; is the case, the table editor command is executed. However, when any of
10683 ;; those keys is used outside a table, the function uses `key-binding' to
10684 ;; look up if the key has an associated command in another currently active
10685 ;; keymap (minor modes, major mode, global), and executes that command.
10686 ;; There might be problems if any of the keys used by the table editor is
10687 ;; otherwise used as a prefix key.
10689 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10690 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10691 ;; addresses this by checking explicitly for both bindings.
10693 ;; The optimized version (see variable `orgtbl-optimized') takes over
10694 ;; all keys which are bound to `self-insert-command' in the *global map*.
10695 ;; Some modes bind other commands to simple characters, for example
10696 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10697 ;; active, this binding is ignored inside tables and replaced with a
10698 ;; modified self-insert.
10700 (defvar orgtbl-mode nil
10701 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10702 table editor in arbitrary modes.")
10703 (make-variable-buffer-local 'orgtbl-mode)
10705 (defvar orgtbl-mode-map (make-keymap)
10706 "Keymap for `orgtbl-mode'.")
10708 ;;;###autoload
10709 (defun turn-on-orgtbl ()
10710 "Unconditionally turn on `orgtbl-mode'."
10711 (orgtbl-mode 1))
10713 (defvar org-old-auto-fill-inhibit-regexp nil
10714 "Local variable used by `orgtbl-mode'")
10716 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
10717 "Matches a line belonging to an orgtbl.")
10719 (defconst orgtbl-extra-font-lock-keywords
10720 (list (list (concat "^" orgtbl-line-start-regexp ".*")
10721 0 (quote 'org-table) 'prepend))
10722 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
10724 ;;;###autoload
10725 (defun orgtbl-mode (&optional arg)
10726 "The `org-mode' table editor as a minor mode for use in other modes."
10727 (interactive)
10728 (if (org-mode-p)
10729 ;; Exit without error, in case some hook functions calls this
10730 ;; by accident in org-mode.
10731 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10732 (setq orgtbl-mode
10733 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10734 (if orgtbl-mode
10735 (progn
10736 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10737 ;; Make sure we are first in minor-mode-map-alist
10738 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10739 (and c (setq minor-mode-map-alist
10740 (cons c (delq c minor-mode-map-alist)))))
10741 (org-set-local (quote org-table-may-need-update) t)
10742 (org-add-hook 'before-change-functions 'org-before-change-function
10743 nil 'local)
10744 (org-set-local 'org-old-auto-fill-inhibit-regexp
10745 auto-fill-inhibit-regexp)
10746 (org-set-local 'auto-fill-inhibit-regexp
10747 (if auto-fill-inhibit-regexp
10748 (concat orgtbl-line-start-regexp "\\|"
10749 auto-fill-inhibit-regexp)
10750 orgtbl-line-start-regexp))
10751 (org-add-to-invisibility-spec '(org-cwidth))
10752 (when (fboundp 'font-lock-add-keywords)
10753 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
10754 (org-restart-font-lock))
10755 (easy-menu-add orgtbl-mode-menu)
10756 (run-hooks 'orgtbl-mode-hook))
10757 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10758 (org-cleanup-narrow-column-properties)
10759 (org-remove-from-invisibility-spec '(org-cwidth))
10760 (remove-hook 'before-change-functions 'org-before-change-function t)
10761 (when (fboundp 'font-lock-remove-keywords)
10762 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
10763 (org-restart-font-lock))
10764 (easy-menu-remove orgtbl-mode-menu)
10765 (force-mode-line-update 'all))))
10767 (defun org-cleanup-narrow-column-properties ()
10768 "Remove all properties related to narrow-column invisibility."
10769 (let ((s 1))
10770 (while (setq s (text-property-any s (point-max)
10771 'display org-narrow-column-arrow))
10772 (remove-text-properties s (1+ s) '(display t)))
10773 (setq s 1)
10774 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10775 (remove-text-properties s (1+ s) '(org-cwidth t)))
10776 (setq s 1)
10777 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10778 (remove-text-properties s (1+ s) '(invisible t)))))
10780 ;; Install it as a minor mode.
10781 (put 'orgtbl-mode :included t)
10782 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10783 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10785 (defun orgtbl-make-binding (fun n &rest keys)
10786 "Create a function for binding in the table minor mode.
10787 FUN is the command to call inside a table. N is used to create a unique
10788 command name. KEYS are keys that should be checked in for a command
10789 to execute outside of tables."
10790 (eval
10791 (list 'defun
10792 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10793 '(arg)
10794 (concat "In tables, run `" (symbol-name fun) "'.\n"
10795 "Outside of tables, run the binding of `"
10796 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10797 "'.")
10798 '(interactive "p")
10799 (list 'if
10800 '(org-at-table-p)
10801 (list 'call-interactively (list 'quote fun))
10802 (list 'let '(orgtbl-mode)
10803 (list 'call-interactively
10804 (append '(or)
10805 (mapcar (lambda (k)
10806 (list 'key-binding k))
10807 keys)
10808 '('orgtbl-error))))))))
10810 (defun orgtbl-error ()
10811 "Error when there is no default binding for a table key."
10812 (interactive)
10813 (error "This key is has no function outside tables"))
10815 (defun orgtbl-setup ()
10816 "Setup orgtbl keymaps."
10817 (let ((nfunc 0)
10818 (bindings
10819 (list
10820 '([(meta shift left)] org-table-delete-column)
10821 '([(meta left)] org-table-move-column-left)
10822 '([(meta right)] org-table-move-column-right)
10823 '([(meta shift right)] org-table-insert-column)
10824 '([(meta shift up)] org-table-kill-row)
10825 '([(meta shift down)] org-table-insert-row)
10826 '([(meta up)] org-table-move-row-up)
10827 '([(meta down)] org-table-move-row-down)
10828 '("\C-c\C-w" org-table-cut-region)
10829 '("\C-c\M-w" org-table-copy-region)
10830 '("\C-c\C-y" org-table-paste-rectangle)
10831 '("\C-c-" org-table-insert-hline)
10832 '("\C-c}" org-table-toggle-coordinate-overlays)
10833 '("\C-c{" org-table-toggle-formula-debugger)
10834 '("\C-m" org-table-next-row)
10835 '([(shift return)] org-table-copy-down)
10836 '("\C-c\C-q" org-table-wrap-region)
10837 '("\C-c?" org-table-field-info)
10838 '("\C-c " org-table-blank-field)
10839 '("\C-c+" org-table-sum)
10840 '("\C-c=" org-table-eval-formula)
10841 '("\C-c'" org-table-edit-formulas)
10842 '("\C-c`" org-table-edit-field)
10843 '("\C-c*" org-table-recalculate)
10844 '("\C-c|" org-table-create-or-convert-from-region)
10845 '("\C-c^" org-table-sort-lines)
10846 '([(control ?#)] org-table-rotate-recalc-marks)))
10847 elt key fun cmd)
10848 (while (setq elt (pop bindings))
10849 (setq nfunc (1+ nfunc))
10850 (setq key (org-key (car elt))
10851 fun (nth 1 elt)
10852 cmd (orgtbl-make-binding fun nfunc key))
10853 (org-defkey orgtbl-mode-map key cmd))
10855 ;; Special treatment needed for TAB and RET
10856 (org-defkey orgtbl-mode-map [(return)]
10857 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10858 (org-defkey orgtbl-mode-map "\C-m"
10859 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10861 (org-defkey orgtbl-mode-map [(tab)]
10862 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10863 (org-defkey orgtbl-mode-map "\C-i"
10864 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
10866 (org-defkey orgtbl-mode-map [(shift tab)]
10867 (orgtbl-make-binding 'org-table-previous-field 104
10868 [(shift tab)] [(tab)] "\C-i"))
10870 (org-defkey orgtbl-mode-map "\M-\C-m"
10871 (orgtbl-make-binding 'org-table-wrap-region 105
10872 "\M-\C-m" [(meta return)]))
10873 (org-defkey orgtbl-mode-map [(meta return)]
10874 (orgtbl-make-binding 'org-table-wrap-region 106
10875 [(meta return)] "\M-\C-m"))
10877 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
10878 (when orgtbl-optimized
10879 ;; If the user wants maximum table support, we need to hijack
10880 ;; some standard editing functions
10881 (org-remap orgtbl-mode-map
10882 'self-insert-command 'orgtbl-self-insert-command
10883 'delete-char 'org-delete-char
10884 'delete-backward-char 'org-delete-backward-char)
10885 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
10886 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10887 '("OrgTbl"
10888 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10889 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10890 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10891 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10892 "--"
10893 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10894 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10895 ["Copy Field from Above"
10896 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10897 "--"
10898 ("Column"
10899 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10900 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10901 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10902 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10903 ("Row"
10904 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10905 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10906 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10907 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10908 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10909 "--"
10910 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10911 ("Rectangle"
10912 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10913 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10914 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10915 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10916 "--"
10917 ("Radio tables"
10918 ["Insert table template" orgtbl-insert-radio-table
10919 (assq major-mode orgtbl-radio-table-templates)]
10920 ["Comment/uncomment table" orgtbl-toggle-comment t])
10921 "--"
10922 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10923 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10924 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10925 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10926 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10927 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
10928 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10929 ["Sum Column/Rectangle" org-table-sum
10930 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10931 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10932 ["Debug Formulas"
10933 org-table-toggle-formula-debugger :active (org-at-table-p)
10934 :keys "C-c {"
10935 :style toggle :selected org-table-formula-debug]
10936 ["Show Col/Row Numbers"
10937 org-table-toggle-coordinate-overlays :active (org-at-table-p)
10938 :keys "C-c }"
10939 :style toggle :selected org-table-overlay-coordinates]
10943 (defun orgtbl-ctrl-c-ctrl-c (arg)
10944 "If the cursor is inside a table, realign the table.
10945 It it is a table to be sent away to a receiver, do it.
10946 With prefix arg, also recompute table."
10947 (interactive "P")
10948 (let ((pos (point)) action)
10949 (save-excursion
10950 (beginning-of-line 1)
10951 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
10952 ((looking-at "[ \t]*|") pos)
10953 ((looking-at "#\\+TBLFM:") 'recalc))))
10954 (cond
10955 ((integerp action)
10956 (goto-char action)
10957 (org-table-maybe-eval-formula)
10958 (if arg
10959 (call-interactively 'org-table-recalculate)
10960 (org-table-maybe-recalculate-line))
10961 (call-interactively 'org-table-align)
10962 (orgtbl-send-table 'maybe))
10963 ((eq action 'recalc)
10964 (save-excursion
10965 (beginning-of-line 1)
10966 (skip-chars-backward " \r\n\t")
10967 (if (org-at-table-p)
10968 (org-call-with-arg 'org-table-recalculate t))))
10969 (t (let (orgtbl-mode)
10970 (call-interactively (key-binding "\C-c\C-c")))))))
10972 (defun orgtbl-tab (arg)
10973 "Justification and field motion for `orgtbl-mode'."
10974 (interactive "P")
10975 (if arg (org-table-edit-field t)
10976 (org-table-justify-field-maybe)
10977 (org-table-next-field)))
10979 (defun orgtbl-ret ()
10980 "Justification and field motion for `orgtbl-mode'."
10981 (interactive)
10982 (org-table-justify-field-maybe)
10983 (org-table-next-row))
10985 (defun orgtbl-self-insert-command (N)
10986 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10987 If the cursor is in a table looking at whitespace, the whitespace is
10988 overwritten, and the table is not marked as requiring realignment."
10989 (interactive "p")
10990 (if (and (org-at-table-p)
10992 (and org-table-auto-blank-field
10993 (member last-command
10994 '(orgtbl-hijacker-command-100
10995 orgtbl-hijacker-command-101
10996 orgtbl-hijacker-command-102
10997 orgtbl-hijacker-command-103
10998 orgtbl-hijacker-command-104
10999 orgtbl-hijacker-command-105))
11000 (org-table-blank-field))
11002 (eq N 1)
11003 (looking-at "[^|\n]* +|"))
11004 (let (org-table-may-need-update)
11005 (goto-char (1- (match-end 0)))
11006 (delete-backward-char 1)
11007 (goto-char (match-beginning 0))
11008 (self-insert-command N))
11009 (setq org-table-may-need-update t)
11010 (let (orgtbl-mode)
11011 (call-interactively (key-binding (vector last-input-event))))))
11013 (defun org-force-self-insert (N)
11014 "Needed to enforce self-insert under remapping."
11015 (interactive "p")
11016 (self-insert-command N))
11018 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11019 "Regula expression matching exponentials as produced by calc.")
11021 (defvar org-table-clean-did-remove-column nil)
11023 (defun orgtbl-export (table target)
11024 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11025 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11026 org-table-last-alignment org-table-last-column-widths
11027 maxcol column)
11028 (if (not (fboundp func))
11029 (error "Cannot export orgtbl table to %s" target))
11030 (setq lines (org-table-clean-before-export lines))
11031 (setq table
11032 (mapcar
11033 (lambda (x)
11034 (if (string-match org-table-hline-regexp x)
11035 'hline
11036 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11037 lines))
11038 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11039 table)))
11040 (loop for i from (1- maxcol) downto 0 do
11041 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11042 (setq column (delq nil column))
11043 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11044 (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))
11045 (funcall func table nil)))
11047 (defun orgtbl-send-table (&optional maybe)
11048 "Send a tranformed version of this table to the receiver position.
11049 With argument MAYBE, fail quietly if no transformation is defined for
11050 this table."
11051 (interactive)
11052 (catch 'exit
11053 (unless (org-at-table-p) (error "Not at a table"))
11054 ;; when non-interactive, we assume align has just happened.
11055 (when (interactive-p) (org-table-align))
11056 (save-excursion
11057 (goto-char (org-table-begin))
11058 (beginning-of-line 0)
11059 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11060 (if maybe
11061 (throw 'exit nil)
11062 (error "Don't know how to transform this table."))))
11063 (let* ((name (match-string 1))
11065 (transform (intern (match-string 2)))
11066 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11067 (skip (plist-get params :skip))
11068 (skipcols (plist-get params :skipcols))
11069 (txt (buffer-substring-no-properties
11070 (org-table-begin) (org-table-end)))
11071 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11072 (lines (org-table-clean-before-export lines))
11073 (i0 (if org-table-clean-did-remove-column 2 1))
11074 (table (mapcar
11075 (lambda (x)
11076 (if (string-match org-table-hline-regexp x)
11077 'hline
11078 (org-remove-by-index
11079 (org-split-string (org-trim x) "\\s-*|\\s-*")
11080 skipcols i0)))
11081 lines))
11082 (fun (if (= i0 2) 'cdr 'identity))
11083 (org-table-last-alignment
11084 (org-remove-by-index (funcall fun org-table-last-alignment)
11085 skipcols i0))
11086 (org-table-last-column-widths
11087 (org-remove-by-index (funcall fun org-table-last-column-widths)
11088 skipcols i0)))
11090 (unless (fboundp transform)
11091 (error "No such transformation function %s" transform))
11092 (setq txt (funcall transform table params))
11093 ;; Find the insertion place
11094 (save-excursion
11095 (goto-char (point-min))
11096 (unless (re-search-forward
11097 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11098 (error "Don't know where to insert translated table"))
11099 (goto-char (match-beginning 0))
11100 (beginning-of-line 2)
11101 (setq beg (point))
11102 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11103 (error "Cannot find end of insertion region"))
11104 (beginning-of-line 1)
11105 (delete-region beg (point))
11106 (goto-char beg)
11107 (insert txt "\n"))
11108 (message "Table converted and installed at receiver location"))))
11110 (defun org-remove-by-index (list indices &optional i0)
11111 "Remove the elements in LIST with indices in INDICES.
11112 First element has index 0, or I0 if given."
11113 (if (not indices)
11114 list
11115 (if (integerp indices) (setq indices (list indices)))
11116 (setq i0 (1- (or i0 0)))
11117 (delq :rm (mapcar (lambda (x)
11118 (setq i0 (1+ i0))
11119 (if (memq i0 indices) :rm x))
11120 list))))
11122 (defun orgtbl-toggle-comment ()
11123 "Comment or uncomment the orgtbl at point."
11124 (interactive)
11125 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11126 (re2 (concat "^" orgtbl-line-start-regexp))
11127 (commented (save-excursion (beginning-of-line 1)
11128 (cond ((looking-at re1) t)
11129 ((looking-at re2) nil)
11130 (t (error "Not at an org table")))))
11131 (re (if commented re1 re2))
11132 beg end)
11133 (save-excursion
11134 (beginning-of-line 1)
11135 (while (looking-at re) (beginning-of-line 0))
11136 (beginning-of-line 2)
11137 (setq beg (point))
11138 (while (looking-at re) (beginning-of-line 2))
11139 (setq end (point)))
11140 (comment-region beg end (if commented '(4) nil))))
11142 (defun orgtbl-insert-radio-table ()
11143 "Insert a radio table template appropriate for this major mode."
11144 (interactive)
11145 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11146 (txt (nth 1 e))
11147 name pos)
11148 (unless e (error "No radio table setup defined for %s" major-mode))
11149 (setq name (read-string "Table name: "))
11150 (while (string-match "%n" txt)
11151 (setq txt (replace-match name t t txt)))
11152 (or (bolp) (insert "\n"))
11153 (setq pos (point))
11154 (insert txt)
11155 (goto-char pos)))
11157 (defun org-get-param (params header i sym &optional hsym)
11158 "Get parameter value for symbol SYM.
11159 If this is a header line, actually get the value for the symbol with an
11160 additional \"h\" inserted after the colon.
11161 If the value is a protperty list, get the element for the current column.
11162 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11163 (let ((val (plist-get params sym)))
11164 (and hsym header (setq val (or (plist-get params hsym) val)))
11165 (if (consp val) (plist-get val i) val)))
11167 (defun orgtbl-to-generic (table params)
11168 "Convert the orgtbl-mode TABLE to some other format.
11169 This generic routine can be used for many standard cases.
11170 TABLE is a list, each entry either the symbol `hline' for a horizontal
11171 separator line, or a list of fields for that line.
11172 PARAMS is a property list of parameters that can influence the conversion.
11173 For the generic converter, some parameters are obligatory: You need to
11174 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11175 :splice, you must have :tstart and :tend.
11177 Valid parameters are
11179 :tstart String to start the table. Ignored when :splice is t.
11180 :tend String to end the table. Ignored when :splice is t.
11182 :splice When set to t, return only table body lines, don't wrap
11183 them into :tstart and :tend. Default is nil.
11185 :hline String to be inserted on horizontal separation lines.
11186 May be nil to ignore hlines.
11188 :lstart String to start a new table line.
11189 :lend String to end a table line
11190 :sep Separator between two fields
11191 :lfmt Format for entire line, with enough %s to capture all fields.
11192 If this is present, :lstart, :lend, and :sep are ignored.
11193 :fmt A format to be used to wrap the field, should contain
11194 %s for the original field value. For example, to wrap
11195 everything in dollars, you could use :fmt \"$%s$\".
11196 This may also be a property list with column numbers and
11197 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11199 :hlstart :hlend :hlsep :hlfmt :hfmt
11200 Same as above, specific for the header lines in the table.
11201 All lines before the first hline are treated as header.
11202 If any of these is not present, the data line value is used.
11204 :efmt Use this format to print numbers with exponentials.
11205 The format should have %s twice for inserting mantissa
11206 and exponent, for example \"%s\\\\times10^{%s}\". This
11207 may also be a property list with column numbers and
11208 formats. :fmt will still be applied after :efmt.
11210 In addition to this, the parameters :skip and :skipcols are always handled
11211 directly by `orgtbl-send-table'. See manual."
11212 (interactive)
11213 (let* ((p params)
11214 (splicep (plist-get p :splice))
11215 (hline (plist-get p :hline))
11216 rtn line i fm efm lfmt h)
11218 ;; Do we have a header?
11219 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11220 (setq h t))
11222 ;; Put header
11223 (unless splicep
11224 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11226 ;; Now loop over all lines
11227 (while (setq line (pop table))
11228 (if (eq line 'hline)
11229 ;; A horizontal separator line
11230 (progn (if hline (push hline rtn))
11231 (setq h nil)) ; no longer in header
11232 ;; A normal line. Convert the fields, push line onto the result list
11233 (setq i 0)
11234 (setq line
11235 (mapcar
11236 (lambda (f)
11237 (setq i (1+ i)
11238 fm (org-get-param p h i :fmt :hfmt)
11239 efm (org-get-param p h i :efmt))
11240 (if (and efm (string-match orgtbl-exp-regexp f))
11241 (setq f (format
11242 efm (match-string 1 f) (match-string 2 f))))
11243 (if fm (setq f (format fm f)))
11245 line))
11246 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11247 (push (apply 'format lfmt line) rtn)
11248 (push (concat
11249 (org-get-param p h i :lstart :hlstart)
11250 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11251 (org-get-param p h i :lend :hlend))
11252 rtn))))
11254 (unless splicep
11255 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11257 (mapconcat 'identity (nreverse rtn) "\n")))
11259 (defun orgtbl-to-latex (table params)
11260 "Convert the orgtbl-mode TABLE to LaTeX.
11261 TABLE is a list, each entry either the symbol `hline' for a horizontal
11262 separator line, or a list of fields for that line.
11263 PARAMS is a property list of parameters that can influence the conversion.
11264 Supports all parameters from `orgtbl-to-generic'. Most important for
11265 LaTeX are:
11267 :splice When set to t, return only table body lines, don't wrap
11268 them into a tabular environment. Default is nil.
11270 :fmt A format to be used to wrap the field, should contain %s for the
11271 original field value. For example, to wrap everything in dollars,
11272 use :fmt \"$%s$\". This may also be a property list with column
11273 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11275 :efmt Format for transforming numbers with exponentials. The format
11276 should have %s twice for inserting mantissa and exponent, for
11277 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11278 This may also be a property list with column numbers and formats.
11280 The general parameters :skip and :skipcols have already been applied when
11281 this function is called."
11282 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11283 org-table-last-alignment ""))
11284 (params2
11285 (list
11286 :tstart (concat "\\begin{tabular}{" alignment "}")
11287 :tend "\\end{tabular}"
11288 :lstart "" :lend " \\\\" :sep " & "
11289 :efmt "%s\\,(%s)" :hline "\\hline")))
11290 (orgtbl-to-generic table (org-combine-plists params2 params))))
11292 (defun orgtbl-to-html (table params)
11293 "Convert the orgtbl-mode TABLE to LaTeX.
11294 TABLE is a list, each entry either the symbol `hline' for a horizontal
11295 separator line, or a list of fields for that line.
11296 PARAMS is a property list of parameters that can influence the conversion.
11297 Currently this function recognizes the following parameters:
11299 :splice When set to t, return only table body lines, don't wrap
11300 them into a <table> environment. Default is nil.
11302 The general parameters :skip and :skipcols have already been applied when
11303 this function is called. The function does *not* use `orgtbl-to-generic',
11304 so you cannot specify parameters for it."
11305 (let* ((splicep (plist-get params :splice))
11306 html)
11307 ;; Just call the formatter we already have
11308 ;; We need to make text lines for it, so put the fields back together.
11309 (setq html (org-format-org-table-html
11310 (mapcar
11311 (lambda (x)
11312 (if (eq x 'hline)
11313 "|----+----|"
11314 (concat "| " (mapconcat 'identity x " | ") " |")))
11315 table)
11316 splicep))
11317 (if (string-match "\n+\\'" html)
11318 (setq html (replace-match "" t t html)))
11319 html))
11321 (defun orgtbl-to-texinfo (table params)
11322 "Convert the orgtbl-mode TABLE to TeXInfo.
11323 TABLE is a list, each entry either the symbol `hline' for a horizontal
11324 separator line, or a list of fields for that line.
11325 PARAMS is a property list of parameters that can influence the conversion.
11326 Supports all parameters from `orgtbl-to-generic'. Most important for
11327 TeXInfo are:
11329 :splice nil/t When set to t, return only table body lines, don't wrap
11330 them into a multitable environment. Default is nil.
11332 :fmt fmt A format to be used to wrap the field, should contain
11333 %s for the original field value. For example, to wrap
11334 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11335 This may also be a property list with column numbers and
11336 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11338 :cf \"f1 f2..\" The column fractions for the table. Bye default these
11339 are computed automatically from the width of the columns
11340 under org-mode.
11342 The general parameters :skip and :skipcols have already been applied when
11343 this function is called."
11344 (let* ((total (float (apply '+ org-table-last-column-widths)))
11345 (colfrac (or (plist-get params :cf)
11346 (mapconcat
11347 (lambda (x) (format "%.3f" (/ (float x) total)))
11348 org-table-last-column-widths " ")))
11349 (params2
11350 (list
11351 :tstart (concat "@multitable @columnfractions " colfrac)
11352 :tend "@end multitable"
11353 :lstart "@item " :lend "" :sep " @tab "
11354 :hlstart "@headitem ")))
11355 (orgtbl-to-generic table (org-combine-plists params2 params))))
11357 ;;;; Link Stuff
11359 ;;; Link abbreviations
11361 (defun org-link-expand-abbrev (link)
11362 "Apply replacements as defined in `org-link-abbrev-alist."
11363 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11364 (let* ((key (match-string 1 link))
11365 (as (or (assoc key org-link-abbrev-alist-local)
11366 (assoc key org-link-abbrev-alist)))
11367 (tag (and (match-end 2) (match-string 3 link)))
11368 rpl)
11369 (if (not as)
11370 link
11371 (setq rpl (cdr as))
11372 (cond
11373 ((symbolp rpl) (funcall rpl tag))
11374 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11375 (t (concat rpl tag)))))
11376 link))
11378 ;;; Storing and inserting links
11380 (defvar org-insert-link-history nil
11381 "Minibuffer history for links inserted with `org-insert-link'.")
11383 (defvar org-stored-links nil
11384 "Contains the links stored with `org-store-link'.")
11386 (defvar org-store-link-plist nil
11387 "Plist with info about the most recently link created with `org-store-link'.")
11389 (defvar org-link-protocols nil
11390 "Link protocols added to Org-mode using `org-add-link-type'.")
11392 (defvar org-store-link-functions nil
11393 "List of functions that are called to create and store a link.
11394 Each function will be called in turn until one returns a non-nil
11395 value. Each function should check if it is responsible for creating
11396 this link (for example by looking at the major mode).
11397 If not, it must exit and return nil.
11398 If yes, it should return a non-nil value after a calling
11399 `org-store-link-props' with a list of properties and values.
11400 Special properties are:
11402 :type The link prefix. like \"http\". This must be given.
11403 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11404 This is obligatory as well.
11405 :description Optional default description for the second pair
11406 of brackets in an Org-mode link. The user can still change
11407 this when inserting this link into an Org-mode buffer.
11409 In addition to these, any additional properties can be specified
11410 and then used in remember templates.")
11412 (defun org-add-link-type (type &optional follow publish)
11413 "Add TYPE to the list of `org-link-types'.
11414 Re-compute all regular expressions depending on `org-link-types'
11415 FOLLOW and PUBLISH are two functions. Both take the link path as
11416 an argument.
11417 FOLLOW should do whatever is necessary to follow the link, for example
11418 to find a file or display a mail message.
11420 PUBLISH takes the path and retuns the string that should be used when
11421 this document is published. FIMXE: This is actually not yet implemented."
11422 (add-to-list 'org-link-types type t)
11423 (org-make-link-regexps)
11424 (add-to-list 'org-link-protocols
11425 (list type follow publish)))
11427 (defun org-add-agenda-custom-command (entry)
11428 "Replace or add a command in `org-agenda-custom-commands'.
11429 This is mostly for hacking and trying a new command - once the command
11430 works you probably want to add it to `org-agenda-custom-commands' for good."
11431 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11432 (if ass
11433 (setcdr ass (cdr entry))
11434 (push entry org-agenda-custom-commands))))
11436 ;;;###autoload
11437 (defun org-store-link (arg)
11438 "\\<org-mode-map>Store an org-link to the current location.
11439 This link can later be inserted into an org-buffer with
11440 \\[org-insert-link].
11441 For some link types, a prefix arg is interpreted:
11442 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11443 For file links, arg negates `org-context-in-file-links'."
11444 (interactive "P")
11445 (setq org-store-link-plist nil) ; reset
11446 (let (link cpltxt desc description search txt)
11447 (cond
11449 ((run-hook-with-args-until-success 'org-store-link-functions)
11450 (setq link (plist-get org-store-link-plist :link)
11451 desc (or (plist-get org-store-link-plist :description) link)))
11453 ((eq major-mode 'bbdb-mode)
11454 (let ((name (bbdb-record-name (bbdb-current-record)))
11455 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11456 (setq cpltxt (concat "bbdb:" (or name company))
11457 link (org-make-link cpltxt))
11458 (org-store-link-props :type "bbdb" :name name :company company)))
11460 ((eq major-mode 'Info-mode)
11461 (setq link (org-make-link "info:"
11462 (file-name-nondirectory Info-current-file)
11463 ":" Info-current-node))
11464 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11465 ":" Info-current-node))
11466 (org-store-link-props :type "info" :file Info-current-file
11467 :node Info-current-node))
11469 ((eq major-mode 'calendar-mode)
11470 (let ((cd (calendar-cursor-to-date)))
11471 (setq link
11472 (format-time-string
11473 (car org-time-stamp-formats)
11474 (apply 'encode-time
11475 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11476 nil nil nil))))
11477 (org-store-link-props :type "calendar" :date cd)))
11479 ((or (eq major-mode 'vm-summary-mode)
11480 (eq major-mode 'vm-presentation-mode))
11481 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11482 (vm-follow-summary-cursor)
11483 (save-excursion
11484 (vm-select-folder-buffer)
11485 (let* ((message (car vm-message-pointer))
11486 (folder buffer-file-name)
11487 (subject (vm-su-subject message))
11488 (to (vm-get-header-contents message "To"))
11489 (from (vm-get-header-contents message "From"))
11490 (message-id (vm-su-message-id message)))
11491 (org-store-link-props :type "vm" :from from :to to :subject subject
11492 :message-id message-id)
11493 (setq message-id (org-remove-angle-brackets message-id))
11494 (setq folder (abbreviate-file-name folder))
11495 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11496 folder)
11497 (setq folder (replace-match "" t t folder)))
11498 (setq cpltxt (org-email-link-description))
11499 (setq link (org-make-link "vm:" folder "#" message-id)))))
11501 ((eq major-mode 'wl-summary-mode)
11502 (let* ((msgnum (wl-summary-message-number))
11503 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11504 msgnum 'message-id))
11505 (wl-message-entity
11506 (if (fboundp 'elmo-message-entity)
11507 (elmo-message-entity
11508 wl-summary-buffer-elmo-folder msgnum)
11509 (elmo-msgdb-overview-get-entity
11510 msgnum (wl-summary-buffer-msgdb))))
11511 (from (wl-summary-line-from))
11512 (to (elmo-message-entity-field wl-message-entity 'to))
11513 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11514 (wl-summary-line-subject))))
11515 (org-store-link-props :type "wl" :from from :to to
11516 :subject subject :message-id message-id)
11517 (setq message-id (org-remove-angle-brackets message-id))
11518 (setq cpltxt (org-email-link-description))
11519 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11520 "#" message-id))))
11522 ((or (equal major-mode 'mh-folder-mode)
11523 (equal major-mode 'mh-show-mode))
11524 (let ((from (org-mhe-get-header "From:"))
11525 (to (org-mhe-get-header "To:"))
11526 (message-id (org-mhe-get-header "Message-Id:"))
11527 (subject (org-mhe-get-header "Subject:")))
11528 (org-store-link-props :type "mh" :from from :to to
11529 :subject subject :message-id message-id)
11530 (setq cpltxt (org-email-link-description))
11531 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11532 (org-remove-angle-brackets message-id)))))
11534 ((eq major-mode 'rmail-mode)
11535 (save-excursion
11536 (save-restriction
11537 (rmail-narrow-to-non-pruned-header)
11538 (let ((folder buffer-file-name)
11539 (message-id (mail-fetch-field "message-id"))
11540 (from (mail-fetch-field "from"))
11541 (to (mail-fetch-field "to"))
11542 (subject (mail-fetch-field "subject")))
11543 (org-store-link-props
11544 :type "rmail" :from from :to to
11545 :subject subject :message-id message-id)
11546 (setq message-id (org-remove-angle-brackets message-id))
11547 (setq cpltxt (org-email-link-description))
11548 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11550 ((eq major-mode 'gnus-group-mode)
11551 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11552 (gnus-group-group-name)) ; version
11553 ((fboundp 'gnus-group-name)
11554 (gnus-group-name))
11555 (t "???"))))
11556 (unless group (error "Not on a group"))
11557 (org-store-link-props :type "gnus" :group group)
11558 (setq cpltxt (concat
11559 (if (org-xor arg org-usenet-links-prefer-google)
11560 "http://groups.google.com/groups?group="
11561 "gnus:")
11562 group)
11563 link (org-make-link cpltxt))))
11565 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11566 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11567 (let* ((group gnus-newsgroup-name)
11568 (article (gnus-summary-article-number))
11569 (header (gnus-summary-article-header article))
11570 (from (mail-header-from header))
11571 (message-id (mail-header-id header))
11572 (date (mail-header-date header))
11573 (subject (gnus-summary-subject-string)))
11574 (org-store-link-props :type "gnus" :from from :subject subject
11575 :message-id message-id :group group)
11576 (setq cpltxt (org-email-link-description))
11577 (if (org-xor arg org-usenet-links-prefer-google)
11578 (setq link
11579 (concat
11580 cpltxt "\n "
11581 (format "http://groups.google.com/groups?as_umsgid=%s"
11582 (org-fixup-message-id-for-http message-id))))
11583 (setq link (org-make-link "gnus:" group
11584 "#" (number-to-string article))))))
11586 ((eq major-mode 'w3-mode)
11587 (setq cpltxt (url-view-url t)
11588 link (org-make-link cpltxt))
11589 (org-store-link-props :type "w3" :url (url-view-url t)))
11591 ((eq major-mode 'w3m-mode)
11592 (setq cpltxt (or w3m-current-title w3m-current-url)
11593 link (org-make-link w3m-current-url))
11594 (org-store-link-props :type "w3m" :url (url-view-url t)))
11596 ((setq search (run-hook-with-args-until-success
11597 'org-create-file-search-functions))
11598 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11599 "::" search))
11600 (setq cpltxt (or description link)))
11602 ((eq major-mode 'image-mode)
11603 (setq cpltxt (concat "file:"
11604 (abbreviate-file-name buffer-file-name))
11605 link (org-make-link cpltxt))
11606 (org-store-link-props :type "image" :file buffer-file-name))
11608 ((eq major-mode 'dired-mode)
11609 ;; link to the file in the current line
11610 (setq cpltxt (concat "file:"
11611 (abbreviate-file-name
11612 (expand-file-name
11613 (dired-get-filename nil t))))
11614 link (org-make-link cpltxt)))
11616 ((and buffer-file-name (org-mode-p))
11617 ;; Just link to current headline
11618 (setq cpltxt (concat "file:"
11619 (abbreviate-file-name buffer-file-name)))
11620 ;; Add a context search string
11621 (when (org-xor org-context-in-file-links arg)
11622 ;; Check if we are on a target
11623 (if (org-in-regexp "<<\\(.*?\\)>>")
11624 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11625 (setq txt (cond
11626 ((org-on-heading-p) nil)
11627 ((org-region-active-p)
11628 (buffer-substring (region-beginning) (region-end)))
11629 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11630 (when (or (null txt) (string-match "\\S-" txt))
11631 (setq cpltxt
11632 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11633 desc "NONE"))))
11634 (if (string-match "::\\'" cpltxt)
11635 (setq cpltxt (substring cpltxt 0 -2)))
11636 (setq link (org-make-link cpltxt)))
11638 ((buffer-file-name (buffer-base-buffer))
11639 ;; Just link to this file here.
11640 (setq cpltxt (concat "file:"
11641 (abbreviate-file-name
11642 (buffer-file-name (buffer-base-buffer)))))
11643 ;; Add a context string
11644 (when (org-xor org-context-in-file-links arg)
11645 (setq txt (if (org-region-active-p)
11646 (buffer-substring (region-beginning) (region-end))
11647 (buffer-substring (point-at-bol) (point-at-eol))))
11648 ;; Only use search option if there is some text.
11649 (when (string-match "\\S-" txt)
11650 (setq cpltxt
11651 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11652 desc "NONE")))
11653 (setq link (org-make-link cpltxt)))
11655 ((interactive-p)
11656 (error "Cannot link to a buffer which is not visiting a file"))
11658 (t (setq link nil)))
11660 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11661 (setq link (or link cpltxt)
11662 desc (or desc cpltxt))
11663 (if (equal desc "NONE") (setq desc nil))
11665 (if (and (interactive-p) link)
11666 (progn
11667 (setq org-stored-links
11668 (cons (list link desc) org-stored-links))
11669 (message "Stored: %s" (or desc link)))
11670 (and link (org-make-link-string link desc)))))
11672 (defun org-store-link-props (&rest plist)
11673 "Store link properties, extract names and addresses."
11674 (let (x adr)
11675 (when (setq x (plist-get plist :from))
11676 (setq adr (mail-extract-address-components x))
11677 (plist-put plist :fromname (car adr))
11678 (plist-put plist :fromaddress (nth 1 adr)))
11679 (when (setq x (plist-get plist :to))
11680 (setq adr (mail-extract-address-components x))
11681 (plist-put plist :toname (car adr))
11682 (plist-put plist :toaddress (nth 1 adr))))
11683 (let ((from (plist-get plist :from))
11684 (to (plist-get plist :to)))
11685 (when (and from to org-from-is-user-regexp)
11686 (plist-put plist :fromto
11687 (if (string-match org-from-is-user-regexp from)
11688 (concat "to %t")
11689 (concat "from %f")))))
11690 (setq org-store-link-plist plist))
11692 (defun org-email-link-description (&optional fmt)
11693 "Return the description part of an email link.
11694 This takes information from `org-store-link-plist' and formats it
11695 according to FMT (default from `org-email-link-description-format')."
11696 (setq fmt (or fmt org-email-link-description-format))
11697 (let* ((p org-store-link-plist)
11698 (to (plist-get p :toaddress))
11699 (from (plist-get p :fromaddress))
11700 (table
11701 (list
11702 (cons "%c" (plist-get p :fromto))
11703 (cons "%F" (plist-get p :from))
11704 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
11705 (cons "%T" (plist-get p :to))
11706 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
11707 (cons "%s" (plist-get p :subject))
11708 (cons "%m" (plist-get p :message-id)))))
11709 (when (string-match "%c" fmt)
11710 ;; Check if the user wrote this message
11711 (if (and org-from-is-user-regexp from to
11712 (save-match-data (string-match org-from-is-user-regexp from)))
11713 (setq fmt (replace-match "to %t" t t fmt))
11714 (setq fmt (replace-match "from %f" t t fmt))))
11715 (org-replace-escapes fmt table)))
11717 (defun org-make-org-heading-search-string (&optional string heading)
11718 "Make search string for STRING or current headline."
11719 (interactive)
11720 (let ((s (or string (org-get-heading))))
11721 (unless (and string (not heading))
11722 ;; We are using a headline, clean up garbage in there.
11723 (if (string-match org-todo-regexp s)
11724 (setq s (replace-match "" t t s)))
11725 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
11726 (setq s (replace-match "" t t s)))
11727 (setq s (org-trim s))
11728 (if (string-match (concat "^\\(" org-quote-string "\\|"
11729 org-comment-string "\\)") s)
11730 (setq s (replace-match "" t t s)))
11731 (while (string-match org-ts-regexp s)
11732 (setq s (replace-match "" t t s))))
11733 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
11734 (setq s (replace-match " " t t s)))
11735 (or string (setq s (concat "*" s))) ; Add * for headlines
11736 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
11738 (defun org-make-link (&rest strings)
11739 "Concatenate STRINGS."
11740 (apply 'concat strings))
11742 (defun org-make-link-string (link &optional description)
11743 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11744 (unless (string-match "\\S-" link)
11745 (error "Empty link"))
11746 (when (stringp description)
11747 ;; Remove brackets from the description, they are fatal.
11748 (while (string-match "\\[\\|\\]" description)
11749 (setq description (replace-match "" t t description))))
11750 (when (equal (org-link-escape link) description)
11751 ;; No description needed, it is identical
11752 (setq description nil))
11753 (when (and (not description)
11754 (not (equal link (org-link-escape link))))
11755 (setq description link))
11756 (concat "[[" (org-link-escape link) "]"
11757 (if description (concat "[" description "]") "")
11758 "]"))
11760 (defconst org-link-escape-chars
11761 '((?\ . "%20")
11762 (?\[ . "%5B")
11763 (?\] . "%5d")
11764 (?\340 . "%E0") ; `a
11765 (?\342 . "%E2") ; ^a
11766 (?\347 . "%E7") ; ,c
11767 (?\350 . "%E8") ; `e
11768 (?\351 . "%E9") ; 'e
11769 (?\352 . "%EA") ; ^e
11770 (?\356 . "%EE") ; ^i
11771 (?\364 . "%F4") ; ^o
11772 (?\371 . "%F9") ; `u
11773 (?\373 . "%FB") ; ^u
11774 (?\; . "%3B")
11775 (?? . "%3F")
11776 (?= . "%3D")
11777 (?+ . "%2B")
11779 "Association list of escapes for some characters problematic in links.
11780 This is the list that is used for internal purposes.")
11782 (defconst org-link-escape-chars-browser
11783 '((?\ . "%20")) ; 32 for the SPC char
11785 "Association list of escapes for some characters problematic in links.
11786 This is the list that is used before handing over to the browser.")
11788 (defun org-link-escape (text &optional table)
11789 "Escape charaters in TEXT that are problematic for links."
11790 (setq table (or table org-link-escape-chars))
11791 (when text
11792 (let ((re (mapconcat (lambda (x) (regexp-quote
11793 (char-to-string (car x))))
11794 table "\\|")))
11795 (while (string-match re text)
11796 (setq text
11797 (replace-match
11798 (cdr (assoc (string-to-char (match-string 0 text))
11799 table))
11800 t t text)))
11801 text)))
11803 (defun org-link-unescape (text &optional table)
11804 "Reverse the action of `org-link-escape'."
11805 (setq table (or table org-link-escape-chars))
11806 (when text
11807 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
11808 table "\\|")))
11809 (while (string-match re text)
11810 (setq text
11811 (replace-match
11812 (char-to-string (car (rassoc (match-string 0 text) table)))
11813 t t text)))
11814 text)))
11816 (defun org-xor (a b)
11817 "Exclusive or."
11818 (if a (not b) b))
11820 (defun org-get-header (header)
11821 "Find a header field in the current buffer."
11822 (save-excursion
11823 (goto-char (point-min))
11824 (let ((case-fold-search t) s)
11825 (cond
11826 ((eq header 'from)
11827 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11828 (setq s (match-string 1)))
11829 (while (string-match "\"" s)
11830 (setq s (replace-match "" t t s)))
11831 (if (string-match "[<(].*" s)
11832 (setq s (replace-match "" t t s))))
11833 ((eq header 'message-id)
11834 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11835 (setq s (match-string 1))))
11836 ((eq header 'subject)
11837 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11838 (setq s (match-string 1)))))
11839 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11840 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11841 s)))
11844 (defun org-fixup-message-id-for-http (s)
11845 "Replace special characters in a message id, so it can be used in an http query."
11846 (while (string-match "<" s)
11847 (setq s (replace-match "%3C" t t s)))
11848 (while (string-match ">" s)
11849 (setq s (replace-match "%3E" t t s)))
11850 (while (string-match "@" s)
11851 (setq s (replace-match "%40" t t s)))
11854 ;;;###autoload
11855 (defun org-insert-link-global ()
11856 "Insert a link like Org-mode does.
11857 This command can be called in any mode to insert a link in Org-mode syntax."
11858 (interactive)
11859 (org-run-like-in-org-mode 'org-insert-link))
11861 (defun org-insert-link (&optional complete-file)
11862 "Insert a link. At the prompt, enter the link.
11864 Completion can be used to select a link previously stored with
11865 `org-store-link'. When the empty string is entered (i.e. if you just
11866 press RET at the prompt), the link defaults to the most recently
11867 stored link. As SPC triggers completion in the minibuffer, you need to
11868 use M-SPC or C-q SPC to force the insertion of a space character.
11870 You will also be prompted for a description, and if one is given, it will
11871 be displayed in the buffer instead of the link.
11873 If there is already a link at point, this command will allow you to edit link
11874 and description parts.
11876 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11877 selected using completion. The path to the file will be relative to
11878 the current directory if the file is in the current directory or a
11879 subdirectory. Otherwise, the link will be the absolute path as
11880 completed in the minibuffer (i.e. normally ~/path/to/file).
11882 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11883 is in the current directory or below.
11884 With three \\[universal-argument] prefixes, negate the meaning of
11885 `org-keep-stored-link-after-insertion'."
11886 (interactive "P")
11887 (let* ((wcf (current-window-configuration))
11888 (region (if (org-region-active-p)
11889 (buffer-substring (region-beginning) (region-end))))
11890 (remove (and region (list (region-beginning) (region-end))))
11891 (desc region)
11892 tmphist ; byte-compile incorrectly complains about this
11893 link entry file)
11894 (cond
11895 ((org-in-regexp org-bracket-link-regexp 1)
11896 ;; We do have a link at point, and we are going to edit it.
11897 (setq remove (list (match-beginning 0) (match-end 0)))
11898 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11899 (setq link (read-string "Link: "
11900 (org-link-unescape
11901 (org-match-string-no-properties 1)))))
11902 ((or (org-in-regexp org-angle-link-re)
11903 (org-in-regexp org-plain-link-re))
11904 ;; Convert to bracket link
11905 (setq remove (list (match-beginning 0) (match-end 0))
11906 link (read-string "Link: "
11907 (org-remove-angle-brackets (match-string 0)))))
11908 ((equal complete-file '(4))
11909 ;; Completing read for file names.
11910 (setq file (read-file-name "File: "))
11911 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11912 (pwd1 (file-name-as-directory (abbreviate-file-name
11913 (expand-file-name ".")))))
11914 (cond
11915 ((equal complete-file '(16))
11916 (setq link (org-make-link
11917 "file:"
11918 (abbreviate-file-name (expand-file-name file)))))
11919 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11920 (setq link (org-make-link "file:" (match-string 1 file))))
11921 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11922 (expand-file-name file))
11923 (setq link (org-make-link
11924 "file:" (match-string 1 (expand-file-name file)))))
11925 (t (setq link (org-make-link "file:" file))))))
11927 ;; Read link, with completion for stored links.
11928 (with-output-to-temp-buffer "*Org Links*"
11929 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
11930 (when org-stored-links
11931 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
11932 (princ (mapconcat
11933 (lambda (x)
11934 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
11935 (reverse org-stored-links) "\n"))))
11936 (let ((cw (selected-window)))
11937 (select-window (get-buffer-window "*Org Links*"))
11938 (shrink-window-if-larger-than-buffer)
11939 (setq truncate-lines t)
11940 (select-window cw))
11941 ;; Fake a link history, containing the stored links.
11942 (setq tmphist (append (mapcar 'car org-stored-links)
11943 org-insert-link-history))
11944 (unwind-protect
11945 (setq link (org-completing-read
11946 "Link: "
11947 (append
11948 (mapcar (lambda (x) (list (concat (car x) ":")))
11949 (append org-link-abbrev-alist-local org-link-abbrev-alist))
11950 (mapcar (lambda (x) (list (concat x ":")))
11951 org-link-types))
11952 nil nil nil
11953 'tmphist
11954 (or (car (car org-stored-links)))))
11955 (set-window-configuration wcf)
11956 (kill-buffer "*Org Links*"))
11957 (setq entry (assoc link org-stored-links))
11958 (or entry (push link org-insert-link-history))
11959 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11960 (not org-keep-stored-link-after-insertion))
11961 (setq org-stored-links (delq (assoc link org-stored-links)
11962 org-stored-links)))
11963 (setq desc (or desc (nth 1 entry)))))
11965 (if (string-match org-plain-link-re link)
11966 ;; URL-like link, normalize the use of angular brackets.
11967 (setq link (org-make-link (org-remove-angle-brackets link))))
11969 ;; Check if we are linking to the current file with a search option
11970 ;; If yes, simplify the link by using only the search option.
11971 (when (and buffer-file-name
11972 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11973 (let* ((path (match-string 1 link))
11974 (case-fold-search nil)
11975 (search (match-string 2 link)))
11976 (save-match-data
11977 (if (equal (file-truename buffer-file-name) (file-truename path))
11978 ;; We are linking to this same file, with a search option
11979 (setq link search)))))
11981 ;; Check if we can/should use a relative path. If yes, simplify the link
11982 (when (string-match "\\<file:\\(.*\\)" link)
11983 (let* ((path (match-string 1 link))
11984 (origpath path)
11985 (desc-is-link (equal link desc))
11986 (case-fold-search nil))
11987 (cond
11988 ((eq org-link-file-path-type 'absolute)
11989 (setq path (abbreviate-file-name (expand-file-name path))))
11990 ((eq org-link-file-path-type 'noabbrev)
11991 (setq path (expand-file-name path)))
11992 ((eq org-link-file-path-type 'relative)
11993 (setq path (file-relative-name path)))
11995 (save-match-data
11996 (if (string-match (concat "^" (regexp-quote
11997 (file-name-as-directory
11998 (expand-file-name "."))))
11999 (expand-file-name path))
12000 ;; We are linking a file with relative path name.
12001 (setq path (substring (expand-file-name path)
12002 (match-end 0)))))))
12003 (setq link (concat "file:" path))
12004 (if (equal desc origpath)
12005 (setq desc path))))
12007 (setq desc (read-string "Description: " desc))
12008 (unless (string-match "\\S-" desc) (setq desc nil))
12009 (if remove (apply 'delete-region remove))
12010 (insert (org-make-link-string link desc))))
12012 (defun org-completing-read (&rest args)
12013 (let ((minibuffer-local-completion-map
12014 (copy-keymap minibuffer-local-completion-map)))
12015 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12016 (apply 'completing-read args)))
12018 ;;; Opening/following a link
12019 (defvar org-link-search-failed nil)
12021 (defun org-next-link ()
12022 "Move forward to the next link.
12023 If the link is in hidden text, expose it."
12024 (interactive)
12025 (when (and org-link-search-failed (eq this-command last-command))
12026 (goto-char (point-min))
12027 (message "Link search wrapped back to beginning of buffer"))
12028 (setq org-link-search-failed nil)
12029 (let* ((pos (point))
12030 (ct (org-context))
12031 (a (assoc :link ct)))
12032 (if a (goto-char (nth 2 a)))
12033 (if (re-search-forward org-any-link-re nil t)
12034 (progn
12035 (goto-char (match-beginning 0))
12036 (if (org-invisible-p) (org-show-context)))
12037 (goto-char pos)
12038 (setq org-link-search-failed t)
12039 (error "No further link found"))))
12041 (defun org-previous-link ()
12042 "Move backward to the previous link.
12043 If the link is in hidden text, expose it."
12044 (interactive)
12045 (when (and org-link-search-failed (eq this-command last-command))
12046 (goto-char (point-max))
12047 (message "Link search wrapped back to end of buffer"))
12048 (setq org-link-search-failed nil)
12049 (let* ((pos (point))
12050 (ct (org-context))
12051 (a (assoc :link ct)))
12052 (if a (goto-char (nth 1 a)))
12053 (if (re-search-backward org-any-link-re nil t)
12054 (progn
12055 (goto-char (match-beginning 0))
12056 (if (org-invisible-p) (org-show-context)))
12057 (goto-char pos)
12058 (setq org-link-search-failed t)
12059 (error "No further link found"))))
12061 (defun org-find-file-at-mouse (ev)
12062 "Open file link or URL at mouse."
12063 (interactive "e")
12064 (mouse-set-point ev)
12065 (org-open-at-point 'in-emacs))
12067 (defun org-open-at-mouse (ev)
12068 "Open file link or URL at mouse."
12069 (interactive "e")
12070 (mouse-set-point ev)
12071 (org-open-at-point))
12073 (defvar org-window-config-before-follow-link nil
12074 "The window configuration before following a link.
12075 This is saved in case the need arises to restore it.")
12077 (defvar org-open-link-marker (make-marker)
12078 "Marker pointing to the location where `org-open-at-point; was called.")
12080 ;;;###autoload
12081 (defun org-open-at-point-global ()
12082 "Follow a link like Org-mode does.
12083 This command can be called in any mode to follow a link that has
12084 Org-mode syntax."
12085 (interactive)
12086 (org-run-like-in-org-mode 'org-open-at-point))
12088 (defun org-open-at-point (&optional in-emacs)
12089 "Open link at or after point.
12090 If there is no link at point, this function will search forward up to
12091 the end of the current subtree.
12092 Normally, files will be opened by an appropriate application. If the
12093 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12094 (interactive "P")
12095 (catch 'abort
12096 (move-marker org-open-link-marker (point))
12097 (setq org-window-config-before-follow-link (current-window-configuration))
12098 (org-remove-occur-highlights nil nil t)
12099 (if (org-at-timestamp-p t)
12100 (org-follow-timestamp-link)
12101 (let (type path link line search (pos (point)))
12102 (catch 'match
12103 (save-excursion
12104 (skip-chars-forward "^]\n\r")
12105 (when (org-in-regexp org-bracket-link-regexp)
12106 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12107 (while (string-match " *\n *" link)
12108 (setq link (replace-match " " t t link)))
12109 (setq link (org-link-expand-abbrev link))
12110 (if (string-match org-link-re-with-space2 link)
12111 (setq type (match-string 1 link) path (match-string 2 link))
12112 (setq type "thisfile" path link))
12113 (throw 'match t)))
12115 (when (get-text-property (point) 'org-linked-text)
12116 (setq type "thisfile"
12117 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12118 (1+ (point)) (point))
12119 path (buffer-substring
12120 (previous-single-property-change pos 'org-linked-text)
12121 (next-single-property-change pos 'org-linked-text)))
12122 (throw 'match t))
12124 (save-excursion
12125 (when (or (org-in-regexp org-angle-link-re)
12126 (org-in-regexp org-plain-link-re))
12127 (setq type (match-string 1) path (match-string 2))
12128 (throw 'match t)))
12129 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12130 (setq type "tree-match"
12131 path (match-string 1))
12132 (throw 'match t))
12133 (save-excursion
12134 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12135 (setq type "tags"
12136 path (match-string 1))
12137 (while (string-match ":" path)
12138 (setq path (replace-match "+" t t path)))
12139 (throw 'match t))))
12140 (unless path
12141 (error "No link found"))
12142 ;; Remove any trailing spaces in path
12143 (if (string-match " +\\'" path)
12144 (setq path (replace-match "" t t path)))
12146 (cond
12148 ((assoc type org-link-protocols)
12149 (funcall (nth 1 (assoc type org-link-protocols)) path))
12151 ((equal type "mailto")
12152 (let ((cmd (car org-link-mailto-program))
12153 (args (cdr org-link-mailto-program)) args1
12154 (address path) (subject "") a)
12155 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12156 (setq address (match-string 1 path)
12157 subject (org-link-escape (match-string 2 path))))
12158 (while args
12159 (cond
12160 ((not (stringp (car args))) (push (pop args) args1))
12161 (t (setq a (pop args))
12162 (if (string-match "%a" a)
12163 (setq a (replace-match address t t a)))
12164 (if (string-match "%s" a)
12165 (setq a (replace-match subject t t a)))
12166 (push a args1))))
12167 (apply cmd (nreverse args1))))
12169 ((member type '("http" "https" "ftp" "news"))
12170 (browse-url (concat type ":" (org-link-escape
12171 path org-link-escape-chars-browser))))
12173 ((string= type "tags")
12174 (org-tags-view in-emacs path))
12175 ((string= type "thisfile")
12176 (if in-emacs
12177 (switch-to-buffer-other-window
12178 (org-get-buffer-for-internal-link (current-buffer)))
12179 (org-mark-ring-push))
12180 (let ((cmd `(org-link-search
12181 ,path
12182 ,(cond ((equal in-emacs '(4)) 'occur)
12183 ((equal in-emacs '(16)) 'org-occur)
12184 (t nil))
12185 ,pos)))
12186 (condition-case nil (eval cmd)
12187 (error (progn (widen) (eval cmd))))))
12189 ((string= type "tree-match")
12190 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12192 ((string= type "file")
12193 (if (string-match "::\\([0-9]+\\)\\'" path)
12194 (setq line (string-to-number (match-string 1 path))
12195 path (substring path 0 (match-beginning 0)))
12196 (if (string-match "::\\(.+\\)\\'" path)
12197 (setq search (match-string 1 path)
12198 path (substring path 0 (match-beginning 0)))))
12199 (if (string-match "[*?{]" (file-name-nondirectory path))
12200 (dired path)
12201 (org-open-file path in-emacs line search)))
12203 ((string= type "news")
12204 (org-follow-gnus-link path))
12206 ((string= type "bbdb")
12207 (org-follow-bbdb-link path))
12209 ((string= type "info")
12210 (org-follow-info-link path))
12212 ((string= type "gnus")
12213 (let (group article)
12214 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12215 (error "Error in Gnus link"))
12216 (setq group (match-string 1 path)
12217 article (match-string 3 path))
12218 (org-follow-gnus-link group article)))
12220 ((string= type "vm")
12221 (let (folder article)
12222 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12223 (error "Error in VM link"))
12224 (setq folder (match-string 1 path)
12225 article (match-string 3 path))
12226 ;; in-emacs is the prefix arg, will be interpreted as read-only
12227 (org-follow-vm-link folder article in-emacs)))
12229 ((string= type "wl")
12230 (let (folder article)
12231 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12232 (error "Error in Wanderlust link"))
12233 (setq folder (match-string 1 path)
12234 article (match-string 3 path))
12235 (org-follow-wl-link folder article)))
12237 ((string= type "mhe")
12238 (let (folder article)
12239 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12240 (error "Error in MHE link"))
12241 (setq folder (match-string 1 path)
12242 article (match-string 3 path))
12243 (org-follow-mhe-link folder article)))
12245 ((string= type "rmail")
12246 (let (folder article)
12247 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12248 (error "Error in RMAIL link"))
12249 (setq folder (match-string 1 path)
12250 article (match-string 3 path))
12251 (org-follow-rmail-link folder article)))
12253 ((string= type "shell")
12254 (let ((cmd path))
12255 (if (or (not org-confirm-shell-link-function)
12256 (funcall org-confirm-shell-link-function
12257 (format "Execute \"%s\" in shell? "
12258 (org-add-props cmd nil
12259 'face 'org-warning))))
12260 (progn
12261 (message "Executing %s" cmd)
12262 (shell-command cmd))
12263 (error "Abort"))))
12265 ((string= type "elisp")
12266 (let ((cmd path))
12267 (if (or (not org-confirm-elisp-link-function)
12268 (funcall org-confirm-elisp-link-function
12269 (format "Execute \"%s\" as elisp? "
12270 (org-add-props cmd nil
12271 'face 'org-warning))))
12272 (message "%s => %s" cmd (eval (read cmd)))
12273 (error "Abort"))))
12276 (browse-url-at-point)))))
12277 (move-marker org-open-link-marker nil)))
12279 ;;; File search
12281 (defvar org-create-file-search-functions nil
12282 "List of functions to construct the right search string for a file link.
12283 These functions are called in turn with point at the location to
12284 which the link should point.
12286 A function in the hook should first test if it would like to
12287 handle this file type, for example by checking the major-mode or
12288 the file extension. If it decides not to handle this file, it
12289 should just return nil to give other functions a chance. If it
12290 does handle the file, it must return the search string to be used
12291 when following the link. The search string will be part of the
12292 file link, given after a double colon, and `org-open-at-point'
12293 will automatically search for it. If special measures must be
12294 taken to make the search successful, another function should be
12295 added to the companion hook `org-execute-file-search-functions',
12296 which see.
12298 A function in this hook may also use `setq' to set the variable
12299 `description' to provide a suggestion for the descriptive text to
12300 be used for this link when it gets inserted into an Org-mode
12301 buffer with \\[org-insert-link].")
12303 (defvar org-execute-file-search-functions nil
12304 "List of functions to execute a file search triggered by a link.
12306 Functions added to this hook must accept a single argument, the
12307 search string that was part of the file link, the part after the
12308 double colon. The function must first check if it would like to
12309 handle this search, for example by checking the major-mode or the
12310 file extension. If it decides not to handle this search, it
12311 should just return nil to give other functions a chance. If it
12312 does handle the search, it must return a non-nil value to keep
12313 other functions from trying.
12315 Each function can access the current prefix argument through the
12316 variable `current-prefix-argument'. Note that a single prefix is
12317 used to force opening a link in Emacs, so it may be good to only
12318 use a numeric or double prefix to guide the search function.
12320 In case this is needed, a function in this hook can also restore
12321 the window configuration before `org-open-at-point' was called using:
12323 (set-window-configuration org-window-config-before-follow-link)")
12325 (defun org-link-search (s &optional type avoid-pos)
12326 "Search for a link search option.
12327 If S is surrounded by forward slashes, it is interpreted as a
12328 regular expression. In org-mode files, this will create an `org-occur'
12329 sparse tree. In ordinary files, `occur' will be used to list matches.
12330 If the current buffer is in `dired-mode', grep will be used to search
12331 in all files. If AVOID-POS is given, ignore matches near that position."
12332 (let ((case-fold-search t)
12333 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12334 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12335 (append '(("") (" ") ("\t") ("\n"))
12336 org-emphasis-alist)
12337 "\\|") "\\)"))
12338 (pos (point))
12339 (pre "") (post "")
12340 words re0 re1 re2 re3 re4 re5 re2a reall)
12341 (cond
12342 ;; First check if there are any special
12343 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12344 ;; Now try the builtin stuff
12345 ((save-excursion
12346 (goto-char (point-min))
12347 (and
12348 (re-search-forward
12349 (concat "<<" (regexp-quote s0) ">>") nil t)
12350 (setq pos (match-beginning 0))))
12351 ;; There is an exact target for this
12352 (goto-char pos))
12353 ((string-match "^/\\(.*\\)/$" s)
12354 ;; A regular expression
12355 (cond
12356 ((org-mode-p)
12357 (org-occur (match-string 1 s)))
12358 ;;((eq major-mode 'dired-mode)
12359 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12360 (t (org-do-occur (match-string 1 s)))))
12362 ;; A normal search strings
12363 (when (equal (string-to-char s) ?*)
12364 ;; Anchor on headlines, post may include tags.
12365 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12366 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12367 s (substring s 1)))
12368 (remove-text-properties
12369 0 (length s)
12370 '(face nil mouse-face nil keymap nil fontified nil) s)
12371 ;; Make a series of regular expressions to find a match
12372 (setq words (org-split-string s "[ \n\r\t]+")
12373 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12374 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12375 "\\)" markers)
12376 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12377 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12378 re1 (concat pre re2 post)
12379 re3 (concat pre re4 post)
12380 re5 (concat pre ".*" re4)
12381 re2 (concat pre re2)
12382 re2a (concat pre re2a)
12383 re4 (concat pre re4)
12384 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12385 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12386 re5 "\\)"
12388 (cond
12389 ((eq type 'org-occur) (org-occur reall))
12390 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12391 (t (goto-char (point-min))
12392 (if (or (org-search-not-self 1 re0 nil t)
12393 (org-search-not-self 1 re1 nil t)
12394 (org-search-not-self 1 re2 nil t)
12395 (org-search-not-self 1 re2a nil t)
12396 (org-search-not-self 1 re3 nil t)
12397 (org-search-not-self 1 re4 nil t)
12398 (org-search-not-self 1 re5 nil t)
12400 (goto-char (match-beginning 1))
12401 (goto-char pos)
12402 (error "No match")))))
12404 ;; Normal string-search
12405 (goto-char (point-min))
12406 (if (search-forward s nil t)
12407 (goto-char (match-beginning 0))
12408 (error "No match"))))
12409 (and (org-mode-p) (org-show-context 'link-search))))
12411 (defun org-search-not-self (group &rest args)
12412 "Execute `re-search-forward', but only accept matches that do not
12413 enclose the position of `org-open-link-marker'."
12414 (let ((m org-open-link-marker))
12415 (catch 'exit
12416 (while (apply 're-search-forward args)
12417 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12418 (goto-char (match-end group))
12419 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12420 (> (match-beginning 0) (marker-position m))
12421 (< (match-end 0) (marker-position m)))
12422 (save-match-data
12423 (or (not (org-in-regexp
12424 org-bracket-link-analytic-regexp 1))
12425 (not (match-end 4)) ; no description
12426 (and (<= (match-beginning 4) (point))
12427 (>= (match-end 4) (point))))))
12428 (throw 'exit (point))))))))
12430 (defun org-get-buffer-for-internal-link (buffer)
12431 "Return a buffer to be used for displaying the link target of internal links."
12432 (cond
12433 ((not org-display-internal-link-with-indirect-buffer)
12434 buffer)
12435 ((string-match "(Clone)$" (buffer-name buffer))
12436 (message "Buffer is already a clone, not making another one")
12437 ;; we also do not modify visibility in this case
12438 buffer)
12439 (t ; make a new indirect buffer for displaying the link
12440 (let* ((bn (buffer-name buffer))
12441 (ibn (concat bn "(Clone)"))
12442 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12443 (with-current-buffer ib (org-overview))
12444 ib))))
12446 (defun org-do-occur (regexp &optional cleanup)
12447 "Call the Emacs command `occur'.
12448 If CLEANUP is non-nil, remove the printout of the regular expression
12449 in the *Occur* buffer. This is useful if the regex is long and not useful
12450 to read."
12451 (occur regexp)
12452 (when cleanup
12453 (let ((cwin (selected-window)) win beg end)
12454 (when (setq win (get-buffer-window "*Occur*"))
12455 (select-window win))
12456 (goto-char (point-min))
12457 (when (re-search-forward "match[a-z]+" nil t)
12458 (setq beg (match-end 0))
12459 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12460 (setq end (1- (match-beginning 0)))))
12461 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12462 (goto-char (point-min))
12463 (select-window cwin))))
12465 ;;; The mark ring for links jumps
12467 (defvar org-mark-ring nil
12468 "Mark ring for positions before jumps in Org-mode.")
12469 (defvar org-mark-ring-last-goto nil
12470 "Last position in the mark ring used to go back.")
12471 ;; Fill and close the ring
12472 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12473 (loop for i from 1 to org-mark-ring-length do
12474 (push (make-marker) org-mark-ring))
12475 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12476 org-mark-ring)
12478 (defun org-mark-ring-push (&optional pos buffer)
12479 "Put the current position or POS into the mark ring and rotate it."
12480 (interactive)
12481 (setq pos (or pos (point)))
12482 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12483 (move-marker (car org-mark-ring)
12484 (or pos (point))
12485 (or buffer (current-buffer)))
12486 (message
12487 (substitute-command-keys
12488 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12490 (defun org-mark-ring-goto (&optional n)
12491 "Jump to the previous position in the mark ring.
12492 With prefix arg N, jump back that many stored positions. When
12493 called several times in succession, walk through the entire ring.
12494 Org-mode commands jumping to a different position in the current file,
12495 or to another Org-mode file, automatically push the old position
12496 onto the ring."
12497 (interactive "p")
12498 (let (p m)
12499 (if (eq last-command this-command)
12500 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12501 (setq p org-mark-ring))
12502 (setq org-mark-ring-last-goto p)
12503 (setq m (car p))
12504 (switch-to-buffer (marker-buffer m))
12505 (goto-char m)
12506 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12508 (defun org-remove-angle-brackets (s)
12509 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12510 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12512 (defun org-add-angle-brackets (s)
12513 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12514 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12517 ;;; Following specific links
12519 (defun org-follow-timestamp-link ()
12520 (cond
12521 ((org-at-date-range-p t)
12522 (let ((org-agenda-start-on-weekday)
12523 (t1 (match-string 1))
12524 (t2 (match-string 2)))
12525 (setq t1 (time-to-days (org-time-string-to-time t1))
12526 t2 (time-to-days (org-time-string-to-time t2)))
12527 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12528 ((org-at-timestamp-p t)
12529 (org-agenda-list nil (time-to-days (org-time-string-to-time
12530 (substring (match-string 1) 0 10)))
12532 (t (error "This should not happen"))))
12535 (defun org-follow-bbdb-link (name)
12536 "Follow a BBDB link to NAME."
12537 (require 'bbdb)
12538 (let ((inhibit-redisplay (not debug-on-error))
12539 (bbdb-electric-p nil))
12540 (catch 'exit
12541 ;; Exact match on name
12542 (bbdb-name (concat "\\`" name "\\'") nil)
12543 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12544 ;; Exact match on name
12545 (bbdb-company (concat "\\`" name "\\'") nil)
12546 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12547 ;; Partial match on name
12548 (bbdb-name name nil)
12549 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12550 ;; Partial match on company
12551 (bbdb-company name nil)
12552 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12553 ;; General match including network address and notes
12554 (bbdb name nil)
12555 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12556 (delete-window (get-buffer-window "*BBDB*"))
12557 (error "No matching BBDB record")))))
12559 (defun org-follow-info-link (name)
12560 "Follow an info file & node link to NAME."
12561 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12562 (string-match "\\(.*\\)" name))
12563 (progn
12564 (require 'info)
12565 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12566 (Info-find-node (match-string 1 name) (match-string 2 name))
12567 (Info-find-node (match-string 1 name) "Top")))
12568 (message (concat "Could not open: " name))))
12570 (defun org-follow-gnus-link (&optional group article)
12571 "Follow a Gnus link to GROUP and ARTICLE."
12572 (require 'gnus)
12573 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12574 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12575 (cond ((and group article)
12576 (gnus-group-read-group 1 nil group)
12577 (gnus-summary-goto-article (string-to-number article) nil t))
12578 (group (gnus-group-jump-to-group group))))
12580 (defun org-follow-vm-link (&optional folder article readonly)
12581 "Follow a VM link to FOLDER and ARTICLE."
12582 (require 'vm)
12583 (setq article (org-add-angle-brackets article))
12584 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12585 ;; ange-ftp or efs or tramp access
12586 (let ((user (or (match-string 1 folder) (user-login-name)))
12587 (host (match-string 2 folder))
12588 (file (match-string 3 folder)))
12589 (cond
12590 ((featurep 'tramp)
12591 ;; use tramp to access the file
12592 (if (featurep 'xemacs)
12593 (setq folder (format "[%s@%s]%s" user host file))
12594 (setq folder (format "/%s@%s:%s" user host file))))
12596 ;; use ange-ftp or efs
12597 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12598 (setq folder (format "/%s@%s:%s" user host file))))))
12599 (when folder
12600 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12601 (sit-for 0.1)
12602 (when article
12603 (vm-select-folder-buffer)
12604 (widen)
12605 (let ((case-fold-search t))
12606 (goto-char (point-min))
12607 (if (not (re-search-forward
12608 (concat "^" "message-id: *" (regexp-quote article))))
12609 (error "Could not find the specified message in this folder"))
12610 (vm-isearch-update)
12611 (vm-isearch-narrow)
12612 (vm-beginning-of-message)
12613 (vm-summarize)))))
12615 (defun org-follow-wl-link (folder article)
12616 "Follow a Wanderlust link to FOLDER and ARTICLE."
12617 (if (and (string= folder "%")
12618 article
12619 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12620 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12621 ;; Thus, we recompose folder and article ids.
12622 (setq folder (format "%s#%s" folder (match-string 1 article))
12623 article (match-string 3 article)))
12624 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12625 (error "No such folder: %s" folder))
12626 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12627 (and article
12628 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12629 (wl-summary-redisplay)))
12631 (defun org-follow-rmail-link (folder article)
12632 "Follow an RMAIL link to FOLDER and ARTICLE."
12633 (setq article (org-add-angle-brackets article))
12634 (let (message-number)
12635 (save-excursion
12636 (save-window-excursion
12637 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12638 (setq message-number
12639 (save-restriction
12640 (widen)
12641 (goto-char (point-max))
12642 (if (re-search-backward
12643 (concat "^Message-ID:\\s-+" (regexp-quote
12644 (or article "")))
12645 nil t)
12646 (rmail-what-message))))))
12647 (if message-number
12648 (progn
12649 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12650 (rmail-show-message message-number)
12651 message-number)
12652 (error "Message not found"))))
12654 ;;; mh-e integration based on planner-mode
12655 (defun org-mhe-get-message-real-folder ()
12656 "Return the name of the current message real folder, so if you use
12657 sequences, it will now work."
12658 (save-excursion
12659 (let* ((folder
12660 (if (equal major-mode 'mh-folder-mode)
12661 mh-current-folder
12662 ;; Refer to the show buffer
12663 mh-show-folder-buffer))
12664 (end-index
12665 (if (boundp 'mh-index-folder)
12666 (min (length mh-index-folder) (length folder))))
12668 ;; a simple test on mh-index-data does not work, because
12669 ;; mh-index-data is always nil in a show buffer.
12670 (if (and (boundp 'mh-index-folder)
12671 (string= mh-index-folder (substring folder 0 end-index)))
12672 (if (equal major-mode 'mh-show-mode)
12673 (save-window-excursion
12674 (let (pop-up-frames)
12675 (when (buffer-live-p (get-buffer folder))
12676 (progn
12677 (pop-to-buffer folder)
12678 (org-mhe-get-message-folder-from-index)
12681 (org-mhe-get-message-folder-from-index)
12683 folder
12687 (defun org-mhe-get-message-folder-from-index ()
12688 "Returns the name of the message folder in a index folder buffer."
12689 (save-excursion
12690 (mh-index-previous-folder)
12691 (re-search-forward "^\\(+.*\\)$" nil t)
12692 (message (match-string 1))))
12694 (defun org-mhe-get-message-folder ()
12695 "Return the name of the current message folder. Be careful if you
12696 use sequences."
12697 (save-excursion
12698 (if (equal major-mode 'mh-folder-mode)
12699 mh-current-folder
12700 ;; Refer to the show buffer
12701 mh-show-folder-buffer)))
12703 (defun org-mhe-get-message-num ()
12704 "Return the number of the current message. Be careful if you
12705 use sequences."
12706 (save-excursion
12707 (if (equal major-mode 'mh-folder-mode)
12708 (mh-get-msg-num nil)
12709 ;; Refer to the show buffer
12710 (mh-show-buffer-message-number))))
12712 (defun org-mhe-get-header (header)
12713 "Return a header of the message in folder mode. This will create a
12714 show buffer for the corresponding message. If you have a more clever
12715 idea..."
12716 (let* ((folder (org-mhe-get-message-folder))
12717 (num (org-mhe-get-message-num))
12718 (buffer (get-buffer-create (concat "show-" folder)))
12719 (header-field))
12720 (with-current-buffer buffer
12721 (mh-display-msg num folder)
12722 (if (equal major-mode 'mh-folder-mode)
12723 (mh-header-display)
12724 (mh-show-header-display))
12725 (set-buffer buffer)
12726 (setq header-field (mh-get-header-field header))
12727 (if (equal major-mode 'mh-folder-mode)
12728 (mh-show)
12729 (mh-show-show))
12730 header-field)))
12732 (defun org-follow-mhe-link (folder article)
12733 "Follow an MHE link to FOLDER and ARTICLE.
12734 If ARTICLE is nil FOLDER is shown. If the configuration variable
12735 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
12736 ARTICLE is searched in all folders. Indexed searches (swish++,
12737 namazu, and others supported by MH-E) will always search in all
12738 folders."
12739 (require 'mh-e)
12740 (require 'mh-search)
12741 (require 'mh-utils)
12742 (mh-find-path)
12743 (if (not article)
12744 (mh-visit-folder (mh-normalize-folder-name folder))
12745 (setq article (org-add-angle-brackets article))
12746 (mh-search-choose)
12747 (if (equal mh-searcher 'pick)
12748 (progn
12749 (mh-search folder (list "--message-id" article))
12750 (when (and org-mhe-search-all-folders
12751 (not (org-mhe-get-message-real-folder)))
12752 (kill-this-buffer)
12753 (mh-search "+" (list "--message-id" article))))
12754 (mh-search "+" article))
12755 (if (org-mhe-get-message-real-folder)
12756 (mh-show-msg 1)
12757 (kill-this-buffer)
12758 (error "Message not found"))))
12760 ;;; BibTeX links
12762 ;; Use the custom search meachnism to construct and use search strings for
12763 ;; file links to BibTeX database entries.
12765 (defun org-create-file-search-in-bibtex ()
12766 "Create the search string and description for a BibTeX database entry."
12767 (when (eq major-mode 'bibtex-mode)
12768 ;; yes, we want to construct this search string.
12769 ;; Make a good description for this entry, using names, year and the title
12770 ;; Put it into the `description' variable which is dynamically scoped.
12771 (let ((bibtex-autokey-names 1)
12772 (bibtex-autokey-names-stretch 1)
12773 (bibtex-autokey-name-case-convert-function 'identity)
12774 (bibtex-autokey-name-separator " & ")
12775 (bibtex-autokey-additional-names " et al.")
12776 (bibtex-autokey-year-length 4)
12777 (bibtex-autokey-name-year-separator " ")
12778 (bibtex-autokey-titlewords 3)
12779 (bibtex-autokey-titleword-separator " ")
12780 (bibtex-autokey-titleword-case-convert-function 'identity)
12781 (bibtex-autokey-titleword-length 'infty)
12782 (bibtex-autokey-year-title-separator ": "))
12783 (setq description (bibtex-generate-autokey)))
12784 ;; Now parse the entry, get the key and return it.
12785 (save-excursion
12786 (bibtex-beginning-of-entry)
12787 (cdr (assoc "=key=" (bibtex-parse-entry))))))
12789 (defun org-execute-file-search-in-bibtex (s)
12790 "Find the link search string S as a key for a database entry."
12791 (when (eq major-mode 'bibtex-mode)
12792 ;; Yes, we want to do the search in this file.
12793 ;; We construct a regexp that searches for "@entrytype{" followed by the key
12794 (goto-char (point-min))
12795 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
12796 (regexp-quote s) "[ \t\n]*,") nil t)
12797 (goto-char (match-beginning 0)))
12798 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
12799 ;; Use double prefix to indicate that any web link should be browsed
12800 (let ((b (current-buffer)) (p (point)))
12801 ;; Restore the window configuration because we just use the web link
12802 (set-window-configuration org-window-config-before-follow-link)
12803 (save-excursion (set-buffer b) (goto-char p)
12804 (bibtex-url)))
12805 (recenter 0)) ; Move entry start to beginning of window
12806 ;; return t to indicate that the search is done.
12809 ;; Finally add the functions to the right hooks.
12810 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
12811 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
12813 ;; end of Bibtex link setup
12815 ;;; Following file links
12817 (defun org-open-file (path &optional in-emacs line search)
12818 "Open the file at PATH.
12819 First, this expands any special file name abbreviations. Then the
12820 configuration variable `org-file-apps' is checked if it contains an
12821 entry for this file type, and if yes, the corresponding command is launched.
12822 If no application is found, Emacs simply visits the file.
12823 With optional argument IN-EMACS, Emacs will visit the file.
12824 Optional LINE specifies a line to go to, optional SEARCH a string to
12825 search for. If LINE or SEARCH is given, the file will always be
12826 opened in Emacs.
12827 If the file does not exist, an error is thrown."
12828 (setq in-emacs (or in-emacs line search))
12829 (let* ((file (if (equal path "")
12830 buffer-file-name
12831 (substitute-in-file-name (expand-file-name path))))
12832 (apps (append org-file-apps (org-default-apps)))
12833 (remp (and (assq 'remote apps) (org-file-remote-p file)))
12834 (dirp (if remp nil (file-directory-p file)))
12835 (dfile (downcase file))
12836 (old-buffer (current-buffer))
12837 (old-pos (point))
12838 (old-mode major-mode)
12839 ext cmd)
12840 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
12841 (setq ext (match-string 1 dfile))
12842 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
12843 (setq ext (match-string 1 dfile))))
12844 (if in-emacs
12845 (setq cmd 'emacs)
12846 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
12847 (and dirp (cdr (assoc 'directory apps)))
12848 (cdr (assoc ext apps))
12849 (cdr (assoc t apps)))))
12850 (when (eq cmd 'mailcap)
12851 (require 'mailcap)
12852 (mailcap-parse-mailcaps)
12853 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
12854 (command (mailcap-mime-info mime-type)))
12855 (if (stringp command)
12856 (setq cmd command)
12857 (setq cmd 'emacs))))
12858 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
12859 (not (file-exists-p file))
12860 (not org-open-non-existing-files))
12861 (error "No such file: %s" file))
12862 (cond
12863 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
12864 ;; Remove quotes around the file name - we'll use shell-quote-argument.
12865 (if (string-match "['\"]%s['\"]" cmd)
12866 (setq cmd (replace-match "%s" t t cmd)))
12867 (setq cmd (format cmd (shell-quote-argument file)))
12868 (save-window-excursion
12869 (start-process-shell-command cmd nil cmd)))
12870 ((or (stringp cmd)
12871 (eq cmd 'emacs))
12872 (funcall (cdr (assq 'file org-link-frame-setup)) file)
12873 (widen)
12874 (if line (goto-line line)
12875 (if search (org-link-search search))))
12876 ((consp cmd)
12877 (eval cmd))
12878 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
12879 (and (org-mode-p) (eq old-mode 'org-mode)
12880 (or (not (equal old-buffer (current-buffer)))
12881 (not (equal old-pos (point))))
12882 (org-mark-ring-push old-pos old-buffer))))
12884 (defun org-default-apps ()
12885 "Return the default applications for this operating system."
12886 (cond
12887 ((eq system-type 'darwin)
12888 org-file-apps-defaults-macosx)
12889 ((eq system-type 'windows-nt)
12890 org-file-apps-defaults-windowsnt)
12891 (t org-file-apps-defaults-gnu)))
12893 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
12894 (defun org-file-remote-p (file)
12895 "Test whether FILE specifies a location on a remote system.
12896 Return non-nil if the location is indeed remote.
12898 For example, the filename \"/user@host:/foo\" specifies a location
12899 on the system \"/user@host:\"."
12900 (cond ((fboundp 'file-remote-p)
12901 (file-remote-p file))
12902 ((fboundp 'tramp-handle-file-remote-p)
12903 (tramp-handle-file-remote-p file))
12904 ((and (boundp 'ange-ftp-name-format)
12905 (string-match (car ange-ftp-name-format) file))
12907 (t nil)))
12910 ;;;; Hooks for remember.el, and refiling
12912 ;;;###autoload
12913 (defun org-remember-insinuate ()
12914 "Setup remember.el for use wiht Org-mode."
12915 (require 'remember)
12916 (setq remember-annotation-functions '(org-remember-annotation))
12917 (setq remember-handler-functions '(org-remember-handler))
12918 (add-hook 'remember-mode-hook 'org-remember-apply-template))
12920 ;;;###autoload
12921 (defun org-remember-annotation ()
12922 "Return a link to the current location as an annotation for remember.el.
12923 If you are using Org-mode files as target for data storage with
12924 remember.el, then the annotations should include a link compatible with the
12925 conventions in Org-mode. This function returns such a link."
12926 (org-store-link nil))
12928 (defconst org-remember-help
12929 "Select a destination location for the note.
12930 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
12931 RET on headline -> Store as sublevel entry to current headline
12932 RET at beg-of-buf -> Append to file as level 2 headline
12933 <left>/<right> -> before/after current headline, same headings level")
12935 (defvar org-remember-previous-location nil)
12936 (defvar org-force-remember-template-char) ;; dynamically scoped
12938 (defun org-select-remember-template (&optional use-char)
12939 (when org-remember-templates
12940 (let* ((templates (mapcar (lambda (x)
12941 (if (stringp (car x))
12942 (append (list (nth 1 x) (car x)) (cddr x))
12943 (append (list (car x) "") (cdr x))))
12944 org-remember-templates))
12945 (char (or use-char
12946 (cond
12947 ((= (length templates) 1)
12948 (caar templates))
12949 ((and (boundp 'org-force-remember-template-char)
12950 org-force-remember-template-char)
12951 (if (stringp org-force-remember-template-char)
12952 (string-to-char org-force-remember-template-char)
12953 org-force-remember-template-char))
12955 (message "Select template: %s"
12956 (mapconcat
12957 (lambda (x)
12958 (cond
12959 ((not (string-match "\\S-" (nth 1 x)))
12960 (format "[%c]" (car x)))
12961 ((equal (downcase (car x))
12962 (downcase (aref (nth 1 x) 0)))
12963 (format "[%c]%s" (car x)
12964 (substring (nth 1 x) 1)))
12965 (t (format "[%c]%s" (car x) (nth 1 x)))))
12966 templates " "))
12967 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
12968 (when (equal char0 ?\C-g)
12969 (jump-to-register remember-register)
12970 (kill-buffer remember-buffer))
12971 char0))))))
12972 (cddr (assoc char templates)))))
12974 ;;;###autoload
12975 (defun org-remember-apply-template (&optional use-char skip-interactive)
12976 "Initialize *remember* buffer with template, invoke `org-mode'.
12977 This function should be placed into `remember-mode-hook' and in fact requires
12978 to be run from that hook to function properly."
12979 (unless (fboundp 'remember-finalize)
12980 (defalias 'remember-finalize 'remember-buffer))
12981 (if org-remember-templates
12982 (let* ((entry (org-select-remember-template use-char))
12983 (tpl (car entry))
12984 (plist-p (if org-store-link-plist t nil))
12985 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
12986 (string-match "\\S-" (nth 1 entry)))
12987 (nth 1 entry)
12988 org-default-notes-file))
12989 (headline (nth 2 entry))
12990 (v-c (if (or (and (eq window-system 'x)
12991 (x-cut-buffer-or-selection-value))
12992 (bound-and-true-p x-last-selected-text)
12993 (bound-and-true-p x-last-selected-text-primary))
12994 x-last-selected-text-primary
12995 (if (> (length kill-ring) 0)
12996 (current-kill 0)
12997 nil)))
12998 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
12999 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13000 (v-u (concat "[" (substring v-t 1 -1) "]"))
13001 (v-U (concat "[" (substring v-T 1 -1) "]"))
13002 ;; `initial' and `annotation' are bound in `remember'
13003 (v-i (if (boundp 'initial) initial))
13004 (v-a (if (and (boundp 'annotation) annotation)
13005 (if (equal annotation "[[]]") "" annotation)
13006 ""))
13007 (v-A (if (and v-a
13008 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13009 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13010 v-a))
13011 (v-n user-full-name)
13012 (org-startup-folded nil)
13013 org-time-was-given org-end-time-was-given x prompt char time pos)
13014 (setq org-store-link-plist
13015 (append (list :annotation v-a :initial v-i)
13016 org-store-link-plist))
13017 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13018 (erase-buffer)
13019 (insert (substitute-command-keys
13020 (format
13021 "## Filing location: Select interactively, default, or last used:
13022 ## %s to select file and header location interactively.
13023 ## %s \"%s\" -> \"* %s\"
13024 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13025 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13026 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13027 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13028 (abbreviate-file-name (or file org-default-notes-file))
13029 (or headline "")
13030 (or (car org-remember-previous-location) "???")
13031 (or (cdr org-remember-previous-location) "???"))))
13032 (insert tpl) (goto-char (point-min))
13033 ;; Simple %-escapes
13034 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13035 (when (and initial (equal (match-string 0) "%i"))
13036 (save-match-data
13037 (let* ((lead (buffer-substring
13038 (point-at-bol) (match-beginning 0))))
13039 (setq v-i (mapconcat 'identity
13040 (org-split-string initial "\n")
13041 (concat "\n" lead))))))
13042 (replace-match
13043 (or (eval (intern (concat "v-" (match-string 1)))) "")
13044 t t))
13046 ;; %[] Insert contents of a file.
13047 (goto-char (point-min))
13048 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13049 (let ((start (match-beginning 0))
13050 (end (match-end 0))
13051 (filename (expand-file-name (match-string 1))))
13052 (goto-char start)
13053 (delete-region start end)
13054 (condition-case error
13055 (insert-file-contents filename)
13056 (error (insert (format "%%![Couldn't insert %s: %s]"
13057 filename error))))))
13058 ;; %() embedded elisp
13059 (goto-char (point-min))
13060 (while (re-search-forward "%\\((.+)\\)" nil t)
13061 (goto-char (match-beginning 0))
13062 (let ((template-start (point)))
13063 (forward-char 1)
13064 (let ((result
13065 (condition-case error
13066 (eval (read (current-buffer)))
13067 (error (format "%%![Error: %s]" error)))))
13068 (delete-region template-start (point))
13069 (insert result))))
13071 ;; From the property list
13072 (when plist-p
13073 (goto-char (point-min))
13074 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13075 (and (setq x (or (plist-get org-store-link-plist
13076 (intern (match-string 1))) ""))
13077 (replace-match x t t))))
13079 ;; Turn on org-mode in the remember buffer, set local variables
13080 (org-mode)
13081 (org-set-local 'org-finish-function 'remember-finalize)
13082 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13083 (org-set-local 'org-default-notes-file file))
13084 (if (and headline (stringp headline) (string-match "\\S-" headline))
13085 (org-set-local 'org-remember-default-headline headline))
13086 ;; Interactive template entries
13087 (goto-char (point-min))
13088 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
13089 (setq char (if (match-end 3) (match-string 3))
13090 prompt (if (match-end 2) (match-string 2)))
13091 (goto-char (match-beginning 0))
13092 (replace-match "")
13093 (cond
13094 ((member char '("G" "g"))
13095 (let* ((org-last-tags-completion-table
13096 (org-global-tags-completion-table
13097 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13098 (org-add-colon-after-tag-completion t)
13099 (ins (completing-read
13100 (if prompt (concat prompt ": ") "Tags: ")
13101 'org-tags-completion-function nil nil nil
13102 'org-tags-history)))
13103 (setq ins (mapconcat 'identity
13104 (org-split-string ins (org-re "[^[:alnum:]]+"))
13105 ":"))
13106 (when (string-match "\\S-" ins)
13107 (or (equal (char-before) ?:) (insert ":"))
13108 (insert ins)
13109 (or (equal (char-after) ?:) (insert ":")))))
13110 (char
13111 (setq org-time-was-given (equal (upcase char) char))
13112 (setq time (org-read-date (equal (upcase char) "U") t nil
13113 prompt))
13114 (org-insert-time-stamp time org-time-was-given
13115 (member char '("u" "U"))
13116 nil nil (list org-end-time-was-given)))
13118 (insert (read-string
13119 (if prompt (concat prompt ": ") "Enter string"))))))
13120 (goto-char (point-min))
13121 (if (re-search-forward "%\\?" nil t)
13122 (replace-match "")
13123 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13124 (org-mode)
13125 (org-set-local 'org-finish-function 'remember-finalize)))
13127 ;;;###autoload
13128 (defun org-remember (&optional goto org-force-remember-template-char)
13129 "Call `remember'. If this is already a remember buffer, re-apply template.
13130 If there is an active region, make sure remember uses it as initial content
13131 of the remember buffer.
13133 When called interactively with a `C-u' prefix argument GOTO, don't remember
13134 anything, just go to the file/headline where the selected templated usually
13135 stores its notes.
13137 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13138 associated with a template in `org-remember-tempates'."
13139 (interactive "P")
13140 (if (equal goto '(4))
13141 (org-go-to-remember-target)
13142 (if (eq org-finish-function 'remember-buffer)
13143 (progn
13144 (when (< (length org-remember-templates) 2)
13145 (error "No other template available"))
13146 (erase-buffer)
13147 (let ((annotation (plist-get org-store-link-plist :annotation))
13148 (initial (plist-get org-store-link-plist :initial)))
13149 (org-remember-apply-template))
13150 (message "Press C-c C-c to remember data"))
13151 (if (org-region-active-p)
13152 (remember (buffer-substring (point) (mark)))
13153 (call-interactively 'remember)))))
13155 (defun org-go-to-remember-target (&optional template-key)
13156 "Go to the target location of a remember template.
13157 The user is queried for the template."
13158 (interactive)
13159 (let* ((entry (org-select-remember-template template-key))
13160 (file (nth 1 entry))
13161 (heading (nth 2 entry))
13162 visiting)
13163 (unless (and file (stringp file) (string-match "\\S-" file))
13164 (setq file org-default-notes-file))
13165 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13166 (setq heading org-remember-default-headline))
13167 (setq visiting (org-find-base-buffer-visiting file))
13168 (if (not visiting) (find-file-noselect file))
13169 (switch-to-buffer (or visiting (get-file-buffer file)))
13170 (widen)
13171 (goto-char (point-min))
13172 (if (re-search-forward
13173 (concat "^\\*+[ \t]+" (regexp-quote heading)
13174 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13175 nil t)
13176 (goto-char (match-beginning 0))
13177 (error "Target headline not found: %s" heading))))
13179 (defvar org-note-abort nil) ; dynamically scoped
13181 ;;;###autoload
13182 (defun org-remember-handler ()
13183 "Store stuff from remember.el into an org file.
13184 First prompts for an org file. If the user just presses return, the value
13185 of `org-default-notes-file' is used.
13186 Then the command offers the headings tree of the selected file in order to
13187 file the text at a specific location.
13188 You can either immediately press RET to get the note appended to the
13189 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13190 find a better place. Then press RET or <left> or <right> in insert the note.
13192 Key Cursor position Note gets inserted
13193 -----------------------------------------------------------------------------
13194 RET buffer-start as level 1 heading at end of file
13195 RET on headline as sublevel of the heading at cursor
13196 RET no heading at cursor position, level taken from context.
13197 Or use prefix arg to specify level manually.
13198 <left> on headline as same level, before current heading
13199 <right> on headline as same level, after current heading
13201 So the fastest way to store the note is to press RET RET to append it to
13202 the default file. This way your current train of thought is not
13203 interrupted, in accordance with the principles of remember.el.
13204 You can also get the fast execution without prompting by using
13205 C-u C-c C-c to exit the remember buffer. See also the variable
13206 `org-remember-store-without-prompt'.
13208 Before being stored away, the function ensures that the text has a
13209 headline, i.e. a first line that starts with a \"*\". If not, a headline
13210 is constructed from the current date and some additional data.
13212 If the variable `org-adapt-indentation' is non-nil, the entire text is
13213 also indented so that it starts in the same column as the headline
13214 \(i.e. after the stars).
13216 See also the variable `org-reverse-note-order'."
13217 (goto-char (point-min))
13218 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13219 (replace-match ""))
13220 (goto-char (point-max))
13221 (catch 'quit
13222 (if org-note-abort (throw 'quit nil))
13223 (let* ((txt (buffer-substring (point-min) (point-max)))
13224 (fastp (org-xor (equal current-prefix-arg '(4))
13225 org-remember-store-without-prompt))
13226 (file (if fastp org-default-notes-file (org-get-org-file)))
13227 (heading org-remember-default-headline)
13228 (visiting (org-find-base-buffer-visiting file))
13229 (org-startup-folded nil)
13230 (org-startup-align-all-tables nil)
13231 (org-goto-start-pos 1)
13232 spos exitcmd level indent reversed)
13233 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13234 (setq file (car org-remember-previous-location)
13235 heading (cdr org-remember-previous-location)))
13236 (setq current-prefix-arg nil)
13237 ;; Modify text so that it becomes a nice subtree which can be inserted
13238 ;; into an org tree.
13239 (let* ((lines (split-string txt "\n"))
13240 first)
13241 (setq first (car lines) lines (cdr lines))
13242 (if (string-match "^\\*+ " first)
13243 ;; Is already a headline
13244 (setq indent nil)
13245 ;; We need to add a headline: Use time and first buffer line
13246 (setq lines (cons first lines)
13247 first (concat "* " (current-time-string)
13248 " (" (remember-buffer-desc) ")")
13249 indent " "))
13250 (if (and org-adapt-indentation indent)
13251 (setq lines (mapcar
13252 (lambda (x)
13253 (if (string-match "\\S-" x)
13254 (concat indent x) x))
13255 lines)))
13256 (setq txt (concat first "\n"
13257 (mapconcat 'identity lines "\n"))))
13258 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13259 (setq txt (replace-match "\n\n" t t txt))
13260 (if (string-match "[ \t\n]*\\'" txt)
13261 (setq txt (replace-match "\n" t t txt))))
13262 ;; Find the file
13263 (if (not visiting) (find-file-noselect file))
13264 (with-current-buffer (or visiting (get-file-buffer file))
13265 (unless (org-mode-p)
13266 (error "Target files for remember notes must be in Org-mode"))
13267 (save-excursion
13268 (save-restriction
13269 (widen)
13270 (and (goto-char (point-min))
13271 (not (re-search-forward "^\\* " nil t))
13272 (insert "\n* " (or heading "Notes") "\n"))
13273 (setq reversed (org-notes-order-reversed-p))
13275 ;; Find the default location
13276 (when (and heading (stringp heading) (string-match "\\S-" heading))
13277 (goto-char (point-min))
13278 (if (re-search-forward
13279 (concat "^\\*+[ \t]+" (regexp-quote heading)
13280 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13281 nil t)
13282 (setq org-goto-start-pos (match-beginning 0))
13283 (when fastp
13284 (goto-char (point-max))
13285 (unless (bolp) (newline))
13286 (insert "* " heading "\n")
13287 (setq org-goto-start-pos (point-at-bol 0)))))
13289 ;; Ask the User for a location
13290 (if fastp
13291 (setq spos org-goto-start-pos
13292 exitcmd 'return)
13293 (setq spos (org-get-location (current-buffer) org-remember-help)
13294 exitcmd (cdr spos)
13295 spos (car spos)))
13296 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13297 ; not handle this note
13298 (goto-char spos)
13299 (cond ((org-on-heading-p t)
13300 (org-back-to-heading t)
13301 (setq level (funcall outline-level))
13302 (cond
13303 ((eq exitcmd 'return)
13304 ;; sublevel of current
13305 (setq org-remember-previous-location
13306 (cons (abbreviate-file-name file)
13307 (org-get-heading 'notags)))
13308 (if reversed
13309 (outline-next-heading)
13310 (org-end-of-subtree)
13311 (if (not (bolp))
13312 (if (looking-at "[ \t]*\n")
13313 (beginning-of-line 2)
13314 (end-of-line 1)
13315 (insert "\n"))))
13316 (org-paste-subtree (org-get-legal-level level 1) txt))
13317 ((eq exitcmd 'left)
13318 ;; before current
13319 (org-paste-subtree level txt))
13320 ((eq exitcmd 'right)
13321 ;; after current
13322 (org-end-of-subtree t)
13323 (org-paste-subtree level txt))
13324 (t (error "This should not happen"))))
13326 ((and (bobp) (not reversed))
13327 ;; Put it at the end, one level below level 1
13328 (save-restriction
13329 (widen)
13330 (goto-char (point-max))
13331 (if (not (bolp)) (newline))
13332 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13334 ((and (bobp) reversed)
13335 ;; Put it at the start, as level 1
13336 (save-restriction
13337 (widen)
13338 (goto-char (point-min))
13339 (re-search-forward "^\\*+ " nil t)
13340 (beginning-of-line 1)
13341 (org-paste-subtree 1 txt)))
13343 ;; Put it right there, with automatic level determined by
13344 ;; org-paste-subtree or from prefix arg
13345 (org-paste-subtree
13346 (if (numberp current-prefix-arg) current-prefix-arg)
13347 txt)))
13348 (when remember-save-after-remembering
13349 (save-buffer)
13350 (if (not visiting) (kill-buffer (current-buffer)))))))))
13351 t) ;; return t to indicate that we took care of this note.
13353 (defun org-get-org-file ()
13354 "Read a filename, with default directory `org-directory'."
13355 (let ((default (or org-default-notes-file remember-data-file)))
13356 (read-file-name (format "File name [%s]: " default)
13357 (file-name-as-directory org-directory)
13358 default)))
13360 (defun org-notes-order-reversed-p ()
13361 "Check if the current file should receive notes in reversed order."
13362 (cond
13363 ((not org-reverse-note-order) nil)
13364 ((eq t org-reverse-note-order) t)
13365 ((not (listp org-reverse-note-order)) nil)
13366 (t (catch 'exit
13367 (let ((all org-reverse-note-order)
13368 entry)
13369 (while (setq entry (pop all))
13370 (if (string-match (car entry) buffer-file-name)
13371 (throw 'exit (cdr entry))))
13372 nil)))))
13374 ;;; Refiling
13376 (defvar org-refile-target-table nil
13377 "The list of refile targets, created by `org-refile'.")
13379 (defvar org-agenda-new-buffers nil
13380 "Buffers created to visit agenda files.")
13382 (defun org-get-refile-targets ()
13383 "Produce a table with refile targets."
13384 (let ((entries org-refile-targets)
13385 org-agenda-new-files targets txt re files f desc descre)
13386 (while (setq entry (pop entries))
13387 (setq files (car entry) desc (cdr entry))
13388 (cond
13389 ((null files) (setq files (list (current-buffer))))
13390 ((eq files 'org-agenda-files)
13391 (setq files (org-agenda-files 'unrestricted)))
13392 ((and (symbolp files) (fboundp files))
13393 (setq files (funcall files)))
13394 ((and (symbolp files) (boundp files))
13395 (setq files (symbol-value files))))
13396 (if (stringp files) (setq files (list files)))
13397 (cond
13398 ((eq (car desc) :tag)
13399 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13400 ((eq (car desc) :todo)
13401 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13402 ((eq (car desc) :regexp)
13403 (setq descre (cdr desc)))
13404 ((eq (car desc) :level)
13405 (setq descre (concat "^\\*\\{" (number-to-string
13406 (if org-odd-levels-only
13407 (1- (* 2 (cdr desc)))
13408 (cdr desc)))
13409 "\\}[ \t]")))
13410 (t (error "Bad refiling target description %s" desc)))
13411 (while (setq f (pop files))
13412 (save-excursion
13413 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13414 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13415 (save-excursion
13416 (save-restriction
13417 (widen)
13418 (goto-char (point-min))
13419 (while (re-search-forward descre nil t)
13420 (goto-char (point-at-bol))
13421 (when (looking-at org-complex-heading-regexp)
13422 (setq txt (match-string 4)
13423 re (concat "^" (regexp-quote
13424 (buffer-substring (match-beginning 1)
13425 (match-end 4)))))
13426 (if (match-end 5) (setq re (concat re "[ \t]+"
13427 (regexp-quote
13428 (match-string 5)))))
13429 (setq re (concat re "[ \t]*$"))
13430 (push (list txt f re (point)) targets))
13431 (goto-char (point-at-eol))))))))
13432 (org-release-buffers org-agenda-new-buffers)
13433 (nreverse targets)))
13435 (defun org-refile (&optional reversed-or-update)
13436 "Move the entry at point to another heading.
13437 The list of target headings is compiled using the information in
13438 `org-refile-targets', which see. This list is created upon first use, and
13439 you can update it by calling this command with a double prefix (`C-u C-u').
13441 At the target location, the entry is filed as a subitem of the target heading.
13442 Depending on `org-reverse-note-order', the new subitem will either be the
13443 first of the last subitem. A single C-u prefix will toggle the value of this
13444 variable for the duration of the command."
13445 (interactive "P")
13446 (if (equal reversed-or-update '(16))
13447 (progn
13448 (setq org-refile-target-table (org-get-refile-targets))
13449 (message "Refile targets updated (%d targets)"
13450 (length org-refile-target-table)))
13451 (when (or (not org-refile-target-table)
13452 (and (= (length org-refile-targets) 1)
13453 (not (caar org-refile-targets))))
13454 (setq org-refile-target-table (org-get-refile-targets)))
13455 (unless org-refile-target-table
13456 (error "No refile targets"))
13457 (let* ((cbuf (current-buffer))
13458 (filename (buffer-file-name (buffer-base-buffer cbuf)))
13459 (fname (and filename (file-truename filename)))
13460 (tbl (mapcar
13461 (lambda (x)
13462 (if (not (equal fname (file-truename (nth 1 x))))
13463 (cons (concat (car x) " (" (file-name-nondirectory
13464 (nth 1 x)) ")")
13465 (cdr x))
13467 org-refile-target-table))
13468 (completion-ignore-case t)
13469 pos it nbuf file re level reversed)
13470 (when (setq it (completing-read "Refile to: " tbl
13471 nil t nil 'org-refile-history))
13472 (setq it (assoc it tbl)
13473 file (nth 1 it)
13474 re (nth 2 it))
13475 (org-copy-special)
13476 (save-excursion
13477 (set-buffer (setq nbuf (or (find-buffer-visiting file)
13478 (find-file-noselect file))))
13479 (setq reversed (org-notes-order-reversed-p))
13480 (if (equal reversed-or-update '(16)) (setq reversed (not reversed)))
13481 (save-excursion
13482 (save-restriction
13483 (widen)
13484 (goto-char (point-min))
13485 (unless (re-search-forward re nil t)
13486 (error "Cannot find target location - try again with `C-u' prefix."))
13487 (goto-char (match-beginning 0))
13488 (looking-at outline-regexp)
13489 (setq level (org-get-legal-level (funcall outline-level) 1))
13490 (goto-char (or (save-excursion
13491 (if reversed
13492 (outline-next-heading)
13493 (outline-get-next-sibling)))
13494 (point-max)))
13495 (org-paste-subtree level))))
13496 (org-cut-special)
13497 (message "Entry refiled to \"%s\"" (car it))))))
13499 ;;;; Dynamic blocks
13501 (defun org-find-dblock (name)
13502 "Find the first dynamic block with name NAME in the buffer.
13503 If not found, stay at current position and return nil."
13504 (let (pos)
13505 (save-excursion
13506 (goto-char (point-min))
13507 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
13508 nil t)
13509 (match-beginning 0))))
13510 (if pos (goto-char pos))
13511 pos))
13513 (defconst org-dblock-start-re
13514 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
13515 "Matches the startline of a dynamic block, with parameters.")
13517 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
13518 "Matches the end of a dyhamic block.")
13520 (defun org-create-dblock (plist)
13521 "Create a dynamic block section, with parameters taken from PLIST.
13522 PLIST must containe a :name entry which is used as name of the block."
13523 (unless (bolp) (newline))
13524 (let ((name (plist-get plist :name)))
13525 (insert "#+BEGIN: " name)
13526 (while plist
13527 (if (eq (car plist) :name)
13528 (setq plist (cddr plist))
13529 (insert " " (prin1-to-string (pop plist)))))
13530 (insert "\n\n#+END:\n")
13531 (beginning-of-line -2)))
13533 (defun org-prepare-dblock ()
13534 "Prepare dynamic block for refresh.
13535 This empties the block, puts the cursor at the insert position and returns
13536 the property list including an extra property :name with the block name."
13537 (unless (looking-at org-dblock-start-re)
13538 (error "Not at a dynamic block"))
13539 (let* ((begdel (1+ (match-end 0)))
13540 (name (org-no-properties (match-string 1)))
13541 (params (append (list :name name)
13542 (read (concat "(" (match-string 3) ")")))))
13543 (unless (re-search-forward org-dblock-end-re nil t)
13544 (error "Dynamic block not terminated"))
13545 (delete-region begdel (match-beginning 0))
13546 (goto-char begdel)
13547 (open-line 1)
13548 params))
13550 (defun org-map-dblocks (&optional command)
13551 "Apply COMMAND to all dynamic blocks in the current buffer.
13552 If COMMAND is not given, use `org-update-dblock'."
13553 (let ((cmd (or command 'org-update-dblock))
13554 pos)
13555 (save-excursion
13556 (goto-char (point-min))
13557 (while (re-search-forward org-dblock-start-re nil t)
13558 (goto-char (setq pos (match-beginning 0)))
13559 (condition-case nil
13560 (funcall cmd)
13561 (error (message "Error during update of dynamic block")))
13562 (goto-char pos)
13563 (unless (re-search-forward org-dblock-end-re nil t)
13564 (error "Dynamic block not terminated"))))))
13566 (defun org-dblock-update (&optional arg)
13567 "User command for updating dynamic blocks.
13568 Update the dynamic block at point. With prefix ARG, update all dynamic
13569 blocks in the buffer."
13570 (interactive "P")
13571 (if arg
13572 (org-update-all-dblocks)
13573 (or (looking-at org-dblock-start-re)
13574 (org-beginning-of-dblock))
13575 (org-update-dblock)))
13577 (defun org-update-dblock ()
13578 "Update the dynamic block at point
13579 This means to empty the block, parse for parameters and then call
13580 the correct writing function."
13581 (save-window-excursion
13582 (let* ((pos (point))
13583 (line (org-current-line))
13584 (params (org-prepare-dblock))
13585 (name (plist-get params :name))
13586 (cmd (intern (concat "org-dblock-write:" name))))
13587 (message "Updating dynamic block `%s' at line %d..." name line)
13588 (funcall cmd params)
13589 (message "Updating dynamic block `%s' at line %d...done" name line)
13590 (goto-char pos))))
13592 (defun org-beginning-of-dblock ()
13593 "Find the beginning of the dynamic block at point.
13594 Error if there is no scuh block at point."
13595 (let ((pos (point))
13596 beg)
13597 (end-of-line 1)
13598 (if (and (re-search-backward org-dblock-start-re nil t)
13599 (setq beg (match-beginning 0))
13600 (re-search-forward org-dblock-end-re nil t)
13601 (> (match-end 0) pos))
13602 (goto-char beg)
13603 (goto-char pos)
13604 (error "Not in a dynamic block"))))
13606 (defun org-update-all-dblocks ()
13607 "Update all dynamic blocks in the buffer.
13608 This function can be used in a hook."
13609 (when (org-mode-p)
13610 (org-map-dblocks 'org-update-dblock)))
13613 ;;;; Completion
13615 (defconst org-additional-option-like-keywords
13616 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
13617 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
13618 "BEGIN_EXAMPLE" "END_EXAMPLE"))
13620 (defun org-complete (&optional arg)
13621 "Perform completion on word at point.
13622 At the beginning of a headline, this completes TODO keywords as given in
13623 `org-todo-keywords'.
13624 If the current word is preceded by a backslash, completes the TeX symbols
13625 that are supported for HTML support.
13626 If the current word is preceded by \"#+\", completes special words for
13627 setting file options.
13628 In the line after \"#+STARTUP:, complete valid keywords.\"
13629 At all other locations, this simply calls the value of
13630 `org-completion-fallback-command'."
13631 (interactive "P")
13632 (org-without-partial-completion
13633 (catch 'exit
13634 (let* ((end (point))
13635 (beg1 (save-excursion
13636 (skip-chars-backward (org-re "[:alnum:]_@"))
13637 (point)))
13638 (beg (save-excursion
13639 (skip-chars-backward "a-zA-Z0-9_:$")
13640 (point)))
13641 (confirm (lambda (x) (stringp (car x))))
13642 (searchhead (equal (char-before beg) ?*))
13643 (tag (and (equal (char-before beg1) ?:)
13644 (equal (char-after (point-at-bol)) ?*)))
13645 (prop (and (equal (char-before beg1) ?:)
13646 (not (equal (char-after (point-at-bol)) ?*))))
13647 (texp (equal (char-before beg) ?\\))
13648 (link (equal (char-before beg) ?\[))
13649 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
13650 beg)
13651 "#+"))
13652 (startup (string-match "^#\\+STARTUP:.*"
13653 (buffer-substring (point-at-bol) (point))))
13654 (completion-ignore-case opt)
13655 (type nil)
13656 (tbl nil)
13657 (table (cond
13658 (opt
13659 (setq type :opt)
13660 (append
13661 (mapcar
13662 (lambda (x)
13663 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
13664 (cons (match-string 2 x) (match-string 1 x)))
13665 (org-split-string (org-get-current-options) "\n"))
13666 (mapcar 'list org-additional-option-like-keywords)))
13667 (startup
13668 (setq type :startup)
13669 org-startup-options)
13670 (link (append org-link-abbrev-alist-local
13671 org-link-abbrev-alist))
13672 (texp
13673 (setq type :tex)
13674 org-html-entities)
13675 ((string-match "\\`\\*+[ \t]+\\'"
13676 (buffer-substring (point-at-bol) beg))
13677 (setq type :todo)
13678 (mapcar 'list org-todo-keywords-1))
13679 (searchhead
13680 (setq type :searchhead)
13681 (save-excursion
13682 (goto-char (point-min))
13683 (while (re-search-forward org-todo-line-regexp nil t)
13684 (push (list
13685 (org-make-org-heading-search-string
13686 (match-string 3) t))
13687 tbl)))
13688 tbl)
13689 (tag (setq type :tag beg beg1)
13690 (or org-tag-alist (org-get-buffer-tags)))
13691 (prop (setq type :prop beg beg1)
13692 (mapcar 'list (org-buffer-property-keys)))
13693 (t (progn
13694 (call-interactively org-completion-fallback-command)
13695 (throw 'exit nil)))))
13696 (pattern (buffer-substring-no-properties beg end))
13697 (completion (try-completion pattern table confirm)))
13698 (cond ((eq completion t)
13699 (if (not (assoc (upcase pattern) table))
13700 (message "Already complete")
13701 (if (equal type :opt)
13702 (insert (substring (cdr (assoc (upcase pattern) table))
13703 (length pattern)))
13704 (if (memq type '(:tag :prop)) (insert ":")))))
13705 ((null completion)
13706 (message "Can't find completion for \"%s\"" pattern)
13707 (ding))
13708 ((not (string= pattern completion))
13709 (delete-region beg end)
13710 (if (string-match " +$" completion)
13711 (setq completion (replace-match "" t t completion)))
13712 (insert completion)
13713 (if (get-buffer-window "*Completions*")
13714 (delete-window (get-buffer-window "*Completions*")))
13715 (if (assoc completion table)
13716 (if (eq type :todo) (insert " ")
13717 (if (memq type '(:tag :prop)) (insert ":"))))
13718 (if (and (equal type :opt) (assoc completion table))
13719 (message "%s" (substitute-command-keys
13720 "Press \\[org-complete] again to insert example settings"))))
13722 (message "Making completion list...")
13723 (let ((list (sort (all-completions pattern table confirm)
13724 'string<)))
13725 (with-output-to-temp-buffer "*Completions*"
13726 (condition-case nil
13727 ;; Protection needed for XEmacs and emacs 21
13728 (display-completion-list list pattern)
13729 (error (display-completion-list list)))))
13730 (message "Making completion list...%s" "done")))))))
13732 ;;;; TODO, DEADLINE, Comments
13734 (defun org-toggle-comment ()
13735 "Change the COMMENT state of an entry."
13736 (interactive)
13737 (save-excursion
13738 (org-back-to-heading)
13739 (let (case-fold-search)
13740 (if (looking-at (concat outline-regexp
13741 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
13742 (replace-match "" t t nil 1)
13743 (if (looking-at outline-regexp)
13744 (progn
13745 (goto-char (match-end 0))
13746 (insert org-comment-string " ")))))))
13748 (defvar org-last-todo-state-is-todo nil
13749 "This is non-nil when the last TODO state change led to a TODO state.
13750 If the last change removed the TODO tag or switched to DONE, then
13751 this is nil.")
13753 (defvar org-setting-tags nil) ; dynamically skiped
13755 ;; FIXME: better place
13756 (defun org-property-or-variable-value (var &optional inherit)
13757 "Check if there is a property fixing the value of VAR.
13758 If yes, return this value. If not, return the current value of the variable."
13759 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13760 (if (and prop (stringp prop) (string-match "\\S-" prop))
13761 (read prop)
13762 (symbol-value var))))
13764 (defun org-parse-local-options (string var)
13765 "Parse STRING for startup setting relevant for variable VAR."
13766 (let ((rtn (symbol-value var))
13767 e opts)
13768 (save-match-data
13769 (if (or (not string) (not (string-match "\\S-" string)))
13771 (setq opts (delq nil (mapcar (lambda (x)
13772 (setq e (assoc x org-startup-options))
13773 (if (eq (nth 1 e) var) e nil))
13774 (org-split-string string "[ \t]+"))))
13775 (if (not opts)
13777 (setq rtn nil)
13778 (while (setq e (pop opts))
13779 (if (not (nth 3 e))
13780 (setq rtn (nth 2 e))
13781 (if (not (listp rtn)) (setq rtn nil))
13782 (push (nth 2 e) rtn)))
13783 rtn)))))
13785 (defvar org-blocker-hook nil
13786 "Hook for functions that are allowed to block a state change.
13788 Each function gets as its single argument a property list, see
13789 `org-trigger-hook' for more information about this list.
13791 If any of the functions in this hook returns nil, the state change
13792 is blocked.")
13794 (defvar org-trigger-hook nil
13795 "Hook for functions that are triggered by a state change.
13797 Each function gets as its single argument a property list with at least
13798 the following elements:
13800 (:type type-of-change :position pos-at-entry-start
13801 :from old-state :to new-state)
13803 Depending on the type, more properties may be present.
13805 This mechanism is currently implemented for:
13807 TODO state changes
13808 ------------------
13809 :type todo-state-change
13810 :from previous state (keyword as a string), or nil
13811 :to new state (keyword as a string), or nil")
13814 (defun org-todo (&optional arg)
13815 "Change the TODO state of an item.
13816 The state of an item is given by a keyword at the start of the heading,
13817 like
13818 *** TODO Write paper
13819 *** DONE Call mom
13821 The different keywords are specified in the variable `org-todo-keywords'.
13822 By default the available states are \"TODO\" and \"DONE\".
13823 So for this example: when the item starts with TODO, it is changed to DONE.
13824 When it starts with DONE, the DONE is removed. And when neither TODO nor
13825 DONE are present, add TODO at the beginning of the heading.
13827 With C-u prefix arg, use completion to determine the new state.
13828 With numeric prefix arg, switch to that state.
13830 For calling through lisp, arg is also interpreted in the following way:
13831 'none -> empty state
13832 \"\"(empty string) -> switch to empty state
13833 'done -> switch to DONE
13834 'nextset -> switch to the next set of keywords
13835 'previousset -> switch to the previous set of keywords
13836 \"WAITING\" -> switch to the specified keyword, but only if it
13837 really is a member of `org-todo-keywords'."
13838 (interactive "P")
13839 (save-excursion
13840 (catch 'exit
13841 (org-back-to-heading)
13842 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
13843 (or (looking-at (concat " +" org-todo-regexp " *"))
13844 (looking-at " *"))
13845 (let* ((match-data (match-data))
13846 (startpos (point-at-bol))
13847 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
13848 (org-log-done (org-parse-local-options logging 'org-log-done))
13849 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
13850 (this (match-string 1))
13851 (hl-pos (match-beginning 0))
13852 (head (org-get-todo-sequence-head this))
13853 (ass (assoc head org-todo-kwd-alist))
13854 (interpret (nth 1 ass))
13855 (done-word (nth 3 ass))
13856 (final-done-word (nth 4 ass))
13857 (last-state (or this ""))
13858 (completion-ignore-case t)
13859 (member (member this org-todo-keywords-1))
13860 (tail (cdr member))
13861 (state (cond
13862 ((and org-todo-key-trigger
13863 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
13864 (and (not arg) org-use-fast-todo-selection
13865 (not (eq org-use-fast-todo-selection 'prefix)))))
13866 ;; Use fast selection
13867 (org-fast-todo-selection))
13868 ((and (equal arg '(4))
13869 (or (not org-use-fast-todo-selection)
13870 (not org-todo-key-trigger)))
13871 ;; Read a state with completion
13872 (completing-read "State: " (mapcar (lambda(x) (list x))
13873 org-todo-keywords-1)
13874 nil t))
13875 ((eq arg 'right)
13876 (if this
13877 (if tail (car tail) nil)
13878 (car org-todo-keywords-1)))
13879 ((eq arg 'left)
13880 (if (equal member org-todo-keywords-1)
13882 (if this
13883 (nth (- (length org-todo-keywords-1) (length tail) 2)
13884 org-todo-keywords-1)
13885 (org-last org-todo-keywords-1))))
13886 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
13887 (setq arg nil))) ; hack to fall back to cycling
13888 (arg
13889 ;; user or caller requests a specific state
13890 (cond
13891 ((equal arg "") nil)
13892 ((eq arg 'none) nil)
13893 ((eq arg 'done) (or done-word (car org-done-keywords)))
13894 ((eq arg 'nextset)
13895 (or (car (cdr (member head org-todo-heads)))
13896 (car org-todo-heads)))
13897 ((eq arg 'previousset)
13898 (let ((org-todo-heads (reverse org-todo-heads)))
13899 (or (car (cdr (member head org-todo-heads)))
13900 (car org-todo-heads))))
13901 ((car (member arg org-todo-keywords-1)))
13902 ((nth (1- (prefix-numeric-value arg))
13903 org-todo-keywords-1))))
13904 ((null member) (or head (car org-todo-keywords-1)))
13905 ((equal this final-done-word) nil) ;; -> make empty
13906 ((null tail) nil) ;; -> first entry
13907 ((eq interpret 'sequence)
13908 (car tail))
13909 ((memq interpret '(type priority))
13910 (if (eq this-command last-command)
13911 (car tail)
13912 (if (> (length tail) 0)
13913 (or done-word (car org-done-keywords))
13914 nil)))
13915 (t nil)))
13916 (next (if state (concat " " state " ") " "))
13917 (change-plist (list :type 'todo-state-change :from this :to state
13918 :position startpos))
13919 dostates)
13920 (when org-blocker-hook
13921 (unless (save-excursion
13922 (save-match-data
13923 (run-hook-with-args-until-failure
13924 'org-blocker-hook change-plist)))
13925 (if (interactive-p)
13926 (error "TODO state change from %s to %s blocked" this state)
13927 ;; fail silently
13928 (message "TODO state change from %s to %s blocked" this state)
13929 (throw 'exit nil))))
13930 (store-match-data match-data)
13931 (replace-match next t t)
13932 (unless (pos-visible-in-window-p hl-pos)
13933 (message "TODO state changed to %s" (org-trim next)))
13934 (unless head
13935 (setq head (org-get-todo-sequence-head state)
13936 ass (assoc head org-todo-kwd-alist)
13937 interpret (nth 1 ass)
13938 done-word (nth 3 ass)
13939 final-done-word (nth 4 ass)))
13940 (when (memq arg '(nextset previousset))
13941 (message "Keyword-Set %d/%d: %s"
13942 (- (length org-todo-sets) -1
13943 (length (memq (assoc state org-todo-sets) org-todo-sets)))
13944 (length org-todo-sets)
13945 (mapconcat 'identity (assoc state org-todo-sets) " ")))
13946 (setq org-last-todo-state-is-todo
13947 (not (member state org-done-keywords)))
13948 (when (and org-log-done (not (memq arg '(nextset previousset))))
13949 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
13950 (or (not org-todo-log-states)
13951 (member state org-todo-log-states))))
13953 (cond
13954 ((and state (member state org-not-done-keywords)
13955 (not (member this org-not-done-keywords)))
13956 ;; This is now a todo state and was not one before
13957 ;; Remove any CLOSED timestamp, and possibly log the state change
13958 (org-add-planning-info nil nil 'closed)
13959 (and dostates (org-add-log-maybe 'state state 'findpos)))
13960 ((and state dostates)
13961 ;; This is a non-nil state, and we need to log it
13962 (org-add-log-maybe 'state state 'findpos))
13963 ((and (member state org-done-keywords)
13964 (not (member this org-done-keywords)))
13965 ;; It is now done, and it was not done before
13966 (org-add-planning-info 'closed (org-current-time))
13967 (org-add-log-maybe 'done state 'findpos))))
13968 ;; Fixup tag positioning
13969 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
13970 (run-hooks 'org-after-todo-state-change-hook)
13971 (and (member state org-done-keywords) (org-auto-repeat-maybe))
13972 (if (and arg (not (member state org-done-keywords)))
13973 (setq head (org-get-todo-sequence-head state)))
13974 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
13975 ;; Fixup cursor location if close to the keyword
13976 (if (and (outline-on-heading-p)
13977 (not (bolp))
13978 (save-excursion (beginning-of-line 1)
13979 (looking-at org-todo-line-regexp))
13980 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
13981 (progn
13982 (goto-char (or (match-end 2) (match-end 1)))
13983 (just-one-space)))
13984 (when org-trigger-hook
13985 (save-excursion
13986 (run-hook-with-args 'org-trigger-hook change-plist)))))))
13988 (defun org-get-todo-sequence-head (kwd)
13989 "Return the head of the TODO sequence to which KWD belongs.
13990 If KWD is not set, check if there is a text property remembering the
13991 right sequence."
13992 (let (p)
13993 (cond
13994 ((not kwd)
13995 (or (get-text-property (point-at-bol) 'org-todo-head)
13996 (progn
13997 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13998 nil (point-at-eol)))
13999 (get-text-property p 'org-todo-head))))
14000 ((not (member kwd org-todo-keywords-1))
14001 (car org-todo-keywords-1))
14002 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14004 (defun org-fast-todo-selection ()
14005 "Fast TODO keyword selection with single keys.
14006 Returns the new TODO keyword, or nil if no state change should occur."
14007 (let* ((fulltable org-todo-key-alist)
14008 (done-keywords org-done-keywords) ;; needed for the faces.
14009 (maxlen (apply 'max (mapcar
14010 (lambda (x)
14011 (if (stringp (car x)) (string-width (car x)) 0))
14012 fulltable)))
14013 (expert nil)
14014 (fwidth (+ maxlen 3 1 3))
14015 (ncol (/ (- (window-width) 4) fwidth))
14016 tg cnt e c tbl
14017 groups ingroup)
14018 (save-window-excursion
14019 (if expert
14020 (set-buffer (get-buffer-create " *Org todo*"))
14021 ; (delete-other-windows)
14022 ; (split-window-vertically)
14023 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14024 (erase-buffer)
14025 (org-set-local 'org-done-keywords done-keywords)
14026 (setq tbl fulltable cnt 0)
14027 (while (setq e (pop tbl))
14028 (cond
14029 ((equal e '(:startgroup))
14030 (push '() groups) (setq ingroup t)
14031 (when (not (= cnt 0))
14032 (setq cnt 0)
14033 (insert "\n"))
14034 (insert "{ "))
14035 ((equal e '(:endgroup))
14036 (setq ingroup nil cnt 0)
14037 (insert "}\n"))
14039 (setq tg (car e) c (cdr e))
14040 (if ingroup (push tg (car groups)))
14041 (setq tg (org-add-props tg nil 'face
14042 (org-get-todo-face tg)))
14043 (if (and (= cnt 0) (not ingroup)) (insert " "))
14044 (insert "[" c "] " tg (make-string
14045 (- fwidth 4 (length tg)) ?\ ))
14046 (when (= (setq cnt (1+ cnt)) ncol)
14047 (insert "\n")
14048 (if ingroup (insert " "))
14049 (setq cnt 0)))))
14050 (insert "\n")
14051 (goto-char (point-min))
14052 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14053 (fit-window-to-buffer))
14054 (message "[a-z..]:Set [SPC]:clear")
14055 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14056 (cond
14057 ((or (= c ?\C-g)
14058 (and (= c ?q) (not (rassoc c fulltable))))
14059 (setq quit-flag t))
14060 ((= c ?\ ) nil)
14061 ((setq e (rassoc c fulltable) tg (car e))
14063 (t (setq quit-flag t))))))
14065 (defun org-get-repeat ()
14066 "Check if tere is a deadline/schedule with repeater in this entry."
14067 (save-match-data
14068 (save-excursion
14069 (org-back-to-heading t)
14070 (if (re-search-forward
14071 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14072 (match-string 1)))))
14074 (defvar org-last-changed-timestamp)
14075 (defvar org-log-post-message)
14076 (defun org-auto-repeat-maybe ()
14077 "Check if the current headline contains a repeated deadline/schedule.
14078 If yes, set TODO state back to what it was and change the base date
14079 of repeating deadline/scheduled time stamps to new date.
14080 This function should be run in the `org-after-todo-state-change-hook'."
14081 ;; last-state is dynamically scoped into this function
14082 (let* ((repeat (org-get-repeat))
14083 (aa (assoc last-state org-todo-kwd-alist))
14084 (interpret (nth 1 aa))
14085 (head (nth 2 aa))
14086 (done-word (nth 3 aa))
14087 (whata '(("d" . day) ("m" . month) ("y" . year)))
14088 (msg "Entry repeats: ")
14089 (org-log-done)
14090 re type n what ts)
14091 (when repeat
14092 (org-todo (if (eq interpret 'type) last-state head))
14093 (when (and org-log-repeat
14094 (not (memq 'org-add-log-note
14095 (default-value 'post-command-hook))))
14096 ;; Make sure a note is taken
14097 (let ((org-log-done '(done)))
14098 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
14099 'findpos)))
14100 (org-back-to-heading t)
14101 (org-add-planning-info nil nil 'closed)
14102 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14103 org-deadline-time-regexp "\\)"))
14104 (while (re-search-forward
14105 re (save-excursion (outline-next-heading) (point)) t)
14106 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
14107 ts (match-string (if (match-end 2) 2 4)))
14108 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14109 (setq n (string-to-number (match-string 1 ts))
14110 what (match-string 2 ts))
14111 (if (equal what "w") (setq n (* n 7) what "d"))
14112 (org-timestamp-change n (cdr (assoc what whata))))
14113 (setq msg (concat msg type org-last-changed-timestamp " ")))
14114 (setq org-log-post-message msg)
14115 (message msg))))
14117 (defun org-show-todo-tree (arg)
14118 "Make a compact tree which shows all headlines marked with TODO.
14119 The tree will show the lines where the regexp matches, and all higher
14120 headlines above the match.
14121 With \\[universal-argument] prefix, also show the DONE entries.
14122 With a numeric prefix N, construct a sparse tree for the Nth element
14123 of `org-todo-keywords-1'."
14124 (interactive "P")
14125 (let ((case-fold-search nil)
14126 (kwd-re
14127 (cond ((null arg) org-not-done-regexp)
14128 ((equal arg '(4))
14129 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14130 (mapcar 'list org-todo-keywords-1))))
14131 (concat "\\("
14132 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14133 "\\)\\>")))
14134 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14135 (regexp-quote (nth (1- (prefix-numeric-value arg))
14136 org-todo-keywords-1)))
14137 (t (error "Invalid prefix argument: %s" arg)))))
14138 (message "%d TODO entries found"
14139 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14141 (defun org-deadline (&optional remove)
14142 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14143 With argument REMOVE, remove any deadline from the item."
14144 (interactive "P")
14145 (if remove
14146 (progn
14147 (org-add-planning-info nil nil 'deadline)
14148 (message "Item no longer has a deadline."))
14149 (org-add-planning-info 'deadline nil 'closed)))
14151 (defun org-schedule (&optional remove)
14152 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14153 With argument REMOVE, remove any scheduling date from the item."
14154 (interactive "P")
14155 (if remove
14156 (progn
14157 (org-add-planning-info nil nil 'scheduled)
14158 (message "Item is no longer scheduled."))
14159 (org-add-planning-info 'scheduled nil 'closed)))
14161 (defun org-add-planning-info (what &optional time &rest remove)
14162 "Insert new timestamp with keyword in the line directly after the headline.
14163 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14164 If non is given, the user is prompted for a date.
14165 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14166 be removed."
14167 (interactive)
14168 (let (org-time-was-given org-end-time-was-given)
14169 (when what (setq time (or time (org-read-date nil 'to-time))))
14170 (when (and org-insert-labeled-timestamps-at-point
14171 (member what '(scheduled deadline)))
14172 (insert
14173 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14174 (org-insert-time-stamp time org-time-was-given
14175 nil nil nil (list org-end-time-was-given))
14176 (setq what nil))
14177 (save-excursion
14178 (save-restriction
14179 (let (col list elt ts buffer-invisibility-spec)
14180 (org-back-to-heading t)
14181 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14182 (goto-char (match-end 1))
14183 (setq col (current-column))
14184 (goto-char (match-end 0))
14185 (if (eobp) (insert "\n") (forward-char 1))
14186 (if (and (not (looking-at outline-regexp))
14187 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14188 "[^\r\n]*"))
14189 (not (equal (match-string 1) org-clock-string)))
14190 (narrow-to-region (match-beginning 0) (match-end 0))
14191 (insert-before-markers "\n")
14192 (backward-char 1)
14193 (narrow-to-region (point) (point))
14194 (indent-to-column col))
14195 ;; Check if we have to remove something.
14196 (setq list (cons what remove))
14197 (while list
14198 (setq elt (pop list))
14199 (goto-char (point-min))
14200 (when (or (and (eq elt 'scheduled)
14201 (re-search-forward org-scheduled-time-regexp nil t))
14202 (and (eq elt 'deadline)
14203 (re-search-forward org-deadline-time-regexp nil t))
14204 (and (eq elt 'closed)
14205 (re-search-forward org-closed-time-regexp nil t)))
14206 (replace-match "")
14207 (if (looking-at "--+<[^>]+>") (replace-match ""))
14208 (if (looking-at " +") (replace-match ""))))
14209 (goto-char (point-max))
14210 (when what
14211 (insert
14212 (if (not (equal (char-before) ?\ )) " " "")
14213 (cond ((eq what 'scheduled) org-scheduled-string)
14214 ((eq what 'deadline) org-deadline-string)
14215 ((eq what 'closed) org-closed-string))
14216 " ")
14217 (setq ts (org-insert-time-stamp
14218 time
14219 (or org-time-was-given
14220 (and (eq what 'closed) org-log-done-with-time))
14221 (eq what 'closed)
14222 nil nil (list org-end-time-was-given)))
14223 (end-of-line 1))
14224 (goto-char (point-min))
14225 (widen)
14226 (if (looking-at "[ \t]+\r?\n")
14227 (replace-match ""))
14228 ts)))))
14230 (defvar org-log-note-marker (make-marker))
14231 (defvar org-log-note-purpose nil)
14232 (defvar org-log-note-state nil)
14233 (defvar org-log-note-window-configuration nil)
14234 (defvar org-log-note-return-to (make-marker))
14235 (defvar org-log-post-message nil
14236 "Message to be displayed after a log note has been stored.
14237 The auto-repeater uses this.")
14239 (defun org-add-log-maybe (&optional purpose state findpos)
14240 "Set up the post command hook to take a note."
14241 (save-excursion
14242 (when (and (listp org-log-done)
14243 (memq purpose org-log-done))
14244 (when findpos
14245 (org-back-to-heading t)
14246 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14247 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14248 "[^\r\n]*\\)?"))
14249 (goto-char (match-end 0))
14250 (unless org-log-states-order-reversed
14251 (and (= (char-after) ?\n) (forward-char 1))
14252 (org-skip-over-state-notes)
14253 (skip-chars-backward " \t\n\r")))
14254 (move-marker org-log-note-marker (point))
14255 (setq org-log-note-purpose purpose)
14256 (setq org-log-note-state state)
14257 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14259 (defun org-skip-over-state-notes ()
14260 "Skip past the list of State notes in an entry."
14261 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14262 (while (looking-at "[ \t]*- State")
14263 (condition-case nil
14264 (org-next-item)
14265 (error (org-end-of-item)))))
14267 (defun org-add-log-note (&optional purpose)
14268 "Pop up a window for taking a note, and add this note later at point."
14269 (remove-hook 'post-command-hook 'org-add-log-note)
14270 (setq org-log-note-window-configuration (current-window-configuration))
14271 (delete-other-windows)
14272 (move-marker org-log-note-return-to (point))
14273 (switch-to-buffer (marker-buffer org-log-note-marker))
14274 (goto-char org-log-note-marker)
14275 (org-switch-to-buffer-other-window "*Org Note*")
14276 (erase-buffer)
14277 (let ((org-inhibit-startup t)) (org-mode))
14278 (insert (format "# Insert note for %s.
14279 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14280 (cond
14281 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14282 ((eq org-log-note-purpose 'done) "closed todo item")
14283 ((eq org-log-note-purpose 'state)
14284 (format "state change to \"%s\"" org-log-note-state))
14285 (t (error "This should not happen")))))
14286 (org-set-local 'org-finish-function 'org-store-log-note))
14288 (defun org-store-log-note ()
14289 "Finish taking a log note, and insert it to where it belongs."
14290 (let ((txt (buffer-string))
14291 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14292 lines ind)
14293 (kill-buffer (current-buffer))
14294 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14295 (setq txt (replace-match "" t t txt)))
14296 (if (string-match "\\s-+\\'" txt)
14297 (setq txt (replace-match "" t t txt)))
14298 (setq lines (org-split-string txt "\n"))
14299 (when (and note (string-match "\\S-" note))
14300 (setq note
14301 (org-replace-escapes
14302 note
14303 (list (cons "%u" (user-login-name))
14304 (cons "%U" user-full-name)
14305 (cons "%t" (format-time-string
14306 (org-time-stamp-format 'long 'inactive)
14307 (current-time)))
14308 (cons "%s" (if org-log-note-state
14309 (concat "\"" org-log-note-state "\"")
14310 "")))))
14311 (if lines (setq note (concat note " \\\\")))
14312 (push note lines))
14313 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14314 (when lines
14315 (save-excursion
14316 (set-buffer (marker-buffer org-log-note-marker))
14317 (save-excursion
14318 (goto-char org-log-note-marker)
14319 (move-marker org-log-note-marker nil)
14320 (end-of-line 1)
14321 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14322 (indent-relative nil)
14323 (insert "- " (pop lines))
14324 (org-indent-line-function)
14325 (beginning-of-line 1)
14326 (looking-at "[ \t]*")
14327 (setq ind (concat (match-string 0) " "))
14328 (end-of-line 1)
14329 (while lines (insert "\n" ind (pop lines)))))))
14330 (set-window-configuration org-log-note-window-configuration)
14331 (with-current-buffer (marker-buffer org-log-note-return-to)
14332 (goto-char org-log-note-return-to))
14333 (move-marker org-log-note-return-to nil)
14334 (and org-log-post-message (message org-log-post-message)))
14336 ;; FIXME: what else would be useful?
14337 ;; - priority
14338 ;; - date
14340 (defun org-sparse-tree (&optional arg)
14341 "Create a sparse tree, prompt for the details.
14342 This command can create sparse trees. You first need to select the type
14343 of match used to create the tree:
14345 t Show entries with a specific TODO keyword.
14346 T Show entries selected by a tags match.
14347 p Enter a property name and its value (both with completion on existing
14348 names/values) and show entries with that property.
14349 r Show entries matching a regular expression"
14350 (interactive "P")
14351 (let (ans kwd value)
14352 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines")
14353 (setq ans (read-char-exclusive))
14354 (cond
14355 ((equal ans ?d)
14356 (call-interactively 'org-check-deadlines))
14357 ((equal ans ?t)
14358 (org-show-todo-tree '(4)))
14359 ((equal ans ?T)
14360 (call-interactively 'org-tags-sparse-tree))
14361 ((member ans '(?p ?P))
14362 (setq kwd (completing-read "Property: "
14363 (mapcar 'list (org-buffer-property-keys))))
14364 (setq value (completing-read "Value: "
14365 (mapcar 'list (org-property-values kwd))))
14366 (unless (string-match "\\`{.*}\\'" value)
14367 (setq value (concat "\"" value "\"")))
14368 (org-tags-sparse-tree arg (concat kwd "=" value)))
14369 ((member ans '(?r ?R ?/))
14370 (call-interactively 'org-occur))
14371 (t (error "No such sparse tree command \"%c\"" ans)))))
14373 (defvar org-occur-highlights nil)
14374 (make-variable-buffer-local 'org-occur-highlights)
14376 (defun org-occur (regexp &optional keep-previous callback)
14377 "Make a compact tree which shows all matches of REGEXP.
14378 The tree will show the lines where the regexp matches, and all higher
14379 headlines above the match. It will also show the heading after the match,
14380 to make sure editing the matching entry is easy.
14381 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
14382 call to `org-occur' will be kept, to allow stacking of calls to this
14383 command.
14384 If CALLBACK is non-nil, it is a function which is called to confirm
14385 that the match should indeed be shown."
14386 (interactive "sRegexp: \nP")
14387 (or keep-previous (org-remove-occur-highlights nil nil t))
14388 (let ((cnt 0))
14389 (save-excursion
14390 (goto-char (point-min))
14391 (if (or (not keep-previous) ; do not want to keep
14392 (not org-occur-highlights)) ; no previous matches
14393 ;; hide everything
14394 (org-overview))
14395 (while (re-search-forward regexp nil t)
14396 (when (or (not callback)
14397 (save-match-data (funcall callback)))
14398 (setq cnt (1+ cnt))
14399 (when org-highlight-sparse-tree-matches
14400 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14401 (org-show-context 'occur-tree))))
14402 (when org-remove-highlights-with-change
14403 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
14404 nil 'local))
14405 (unless org-sparse-tree-open-archived-trees
14406 (org-hide-archived-subtrees (point-min) (point-max)))
14407 (run-hooks 'org-occur-hook)
14408 (if (interactive-p)
14409 (message "%d match(es) for regexp %s" cnt regexp))
14410 cnt))
14412 (defun org-show-context (&optional key)
14413 "Make sure point and context and visible.
14414 How much context is shown depends upon the variables
14415 `org-show-hierarchy-above', `org-show-following-heading'. and
14416 `org-show-siblings'."
14417 (let ((heading-p (org-on-heading-p t))
14418 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
14419 (following-p (org-get-alist-option org-show-following-heading key))
14420 (entry-p (org-get-alist-option org-show-entry-below key))
14421 (siblings-p (org-get-alist-option org-show-siblings key)))
14422 (catch 'exit
14423 ;; Show heading or entry text
14424 (if (and heading-p (not entry-p))
14425 (org-flag-heading nil) ; only show the heading
14426 (and (or entry-p (org-invisible-p) (org-invisible-p2))
14427 (org-show-hidden-entry))) ; show entire entry
14428 (when following-p
14429 ;; Show next sibling, or heading below text
14430 (save-excursion
14431 (and (if heading-p (org-goto-sibling) (outline-next-heading))
14432 (org-flag-heading nil))))
14433 (when siblings-p (org-show-siblings))
14434 (when hierarchy-p
14435 ;; show all higher headings, possibly with siblings
14436 (save-excursion
14437 (while (and (condition-case nil
14438 (progn (org-up-heading-all 1) t)
14439 (error nil))
14440 (not (bobp)))
14441 (org-flag-heading nil)
14442 (when siblings-p (org-show-siblings))))))))
14444 (defun org-reveal (&optional siblings)
14445 "Show current entry, hierarchy above it, and the following headline.
14446 This can be used to show a consistent set of context around locations
14447 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
14448 not t for the search context.
14450 With optional argument SIBLINGS, on each level of the hierarchy all
14451 siblings are shown. This repairs the tree structure to what it would
14452 look like when opened with hierarchical calls to `org-cycle'."
14453 (interactive "P")
14454 (let ((org-show-hierarchy-above t)
14455 (org-show-following-heading t)
14456 (org-show-siblings (if siblings t org-show-siblings)))
14457 (org-show-context nil)))
14459 (defun org-highlight-new-match (beg end)
14460 "Highlight from BEG to END and mark the highlight is an occur headline."
14461 (let ((ov (org-make-overlay beg end)))
14462 (org-overlay-put ov 'face 'secondary-selection)
14463 (push ov org-occur-highlights)))
14465 (defun org-remove-occur-highlights (&optional beg end noremove)
14466 "Remove the occur highlights from the buffer.
14467 BEG and END are ignored. If NOREMOVE is nil, remove this function
14468 from the `before-change-functions' in the current buffer."
14469 (interactive)
14470 (unless org-inhibit-highlight-removal
14471 (mapc 'org-delete-overlay org-occur-highlights)
14472 (setq org-occur-highlights nil)
14473 (unless noremove
14474 (remove-hook 'before-change-functions
14475 'org-remove-occur-highlights 'local))))
14477 ;;;; Priorities
14479 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14480 "Regular expression matching the priority indicator.")
14482 (defvar org-remove-priority-next-time nil)
14484 (defun org-priority-up ()
14485 "Increase the priority of the current item."
14486 (interactive)
14487 (org-priority 'up))
14489 (defun org-priority-down ()
14490 "Decrease the priority of the current item."
14491 (interactive)
14492 (org-priority 'down))
14494 (defun org-priority (&optional action)
14495 "Change the priority of an item by ARG.
14496 ACTION can be `set', `up', `down', or a character."
14497 (interactive)
14498 (setq action (or action 'set))
14499 (let (current new news have remove)
14500 (save-excursion
14501 (org-back-to-heading)
14502 (if (looking-at org-priority-regexp)
14503 (setq current (string-to-char (match-string 2))
14504 have t)
14505 (setq current org-default-priority))
14506 (cond
14507 ((or (eq action 'set) (integerp action))
14508 (if (integerp action)
14509 (setq new action)
14510 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
14511 (setq new (read-char-exclusive)))
14512 (if (and (= (upcase org-highest-priority) org-highest-priority)
14513 (= (upcase org-lowest-priority) org-lowest-priority))
14514 (setq new (upcase new)))
14515 (cond ((equal new ?\ ) (setq remove t))
14516 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14517 (error "Priority must be between `%c' and `%c'"
14518 org-highest-priority org-lowest-priority))))
14519 ((eq action 'up)
14520 (if (and (not have) (eq last-command this-command))
14521 (setq new org-lowest-priority)
14522 (setq new (if (and org-priority-start-cycle-with-default (not have))
14523 org-default-priority (1- current)))))
14524 ((eq action 'down)
14525 (if (and (not have) (eq last-command this-command))
14526 (setq new org-highest-priority)
14527 (setq new (if (and org-priority-start-cycle-with-default (not have))
14528 org-default-priority (1+ current)))))
14529 (t (error "Invalid action")))
14530 (if (or (< (upcase new) org-highest-priority)
14531 (> (upcase new) org-lowest-priority))
14532 (setq remove t))
14533 (setq news (format "%c" new))
14534 (if have
14535 (if remove
14536 (replace-match "" t t nil 1)
14537 (replace-match news t t nil 2))
14538 (if remove
14539 (error "No priority cookie found in line")
14540 (looking-at org-todo-line-regexp)
14541 (if (match-end 2)
14542 (progn
14543 (goto-char (match-end 2))
14544 (insert " [#" news "]"))
14545 (goto-char (match-beginning 3))
14546 (insert "[#" news "] ")))))
14547 (org-preserve-lc (org-set-tags nil 'align))
14548 (if remove
14549 (message "Priority removed")
14550 (message "Priority of current item set to %s" news))))
14553 (defun org-get-priority (s)
14554 "Find priority cookie and return priority."
14555 (save-match-data
14556 (if (not (string-match org-priority-regexp s))
14557 (* 1000 (- org-lowest-priority org-default-priority))
14558 (* 1000 (- org-lowest-priority
14559 (string-to-char (match-string 2 s)))))))
14561 ;;;; Tags
14563 (defun org-scan-tags (action matcher &optional todo-only)
14564 "Scan headline tags with inheritance and produce output ACTION.
14565 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
14566 evaluated, testing if a given set of tags qualifies a headline for
14567 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
14568 are included in the output."
14569 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
14570 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14571 (org-re
14572 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
14573 (props (list 'face nil
14574 'done-face 'org-done
14575 'undone-face nil
14576 'mouse-face 'highlight
14577 'org-not-done-regexp org-not-done-regexp
14578 'org-todo-regexp org-todo-regexp
14579 'keymap org-agenda-keymap
14580 'help-echo
14581 (format "mouse-2 or RET jump to org file %s"
14582 (abbreviate-file-name
14583 (or (buffer-file-name (buffer-base-buffer))
14584 (buffer-name (buffer-base-buffer)))))))
14585 (case-fold-search nil)
14586 lspos
14587 tags tags-list tags-alist (llast 0) rtn level category i txt
14588 todo marker entry priority)
14589 (save-excursion
14590 (goto-char (point-min))
14591 (when (eq action 'sparse-tree)
14592 (org-overview)
14593 (org-remove-occur-highlights))
14594 (while (re-search-forward re nil t)
14595 (catch :skip
14596 (setq todo (if (match-end 1) (match-string 2))
14597 tags (if (match-end 4) (match-string 4)))
14598 (goto-char (setq lspos (1+ (match-beginning 0))))
14599 (setq level (org-reduced-level (funcall outline-level))
14600 category (org-get-category))
14601 (setq i llast llast level)
14602 ;; remove tag lists from same and sublevels
14603 (while (>= i level)
14604 (when (setq entry (assoc i tags-alist))
14605 (setq tags-alist (delete entry tags-alist)))
14606 (setq i (1- i)))
14607 ;; add the nex tags
14608 (when tags
14609 (setq tags (mapcar 'downcase (org-split-string tags ":"))
14610 tags-alist
14611 (cons (cons level tags) tags-alist)))
14612 ;; compile tags for current headline
14613 (setq tags-list
14614 (if org-use-tag-inheritance
14615 (apply 'append (mapcar 'cdr tags-alist))
14616 tags))
14617 (when (and (or (not todo-only) (member todo org-not-done-keywords))
14618 (eval matcher)
14619 (or (not org-agenda-skip-archived-trees)
14620 (not (member org-archive-tag tags-list))))
14621 (and (eq action 'agenda) (org-agenda-skip))
14622 ;; list this headline
14624 (if (eq action 'sparse-tree)
14625 (progn
14626 (and org-highlight-sparse-tree-matches
14627 (org-get-heading) (match-end 0)
14628 (org-highlight-new-match
14629 (match-beginning 0) (match-beginning 1)))
14630 (org-show-context 'tags-tree))
14631 (setq txt (org-format-agenda-item
14633 (concat
14634 (if org-tags-match-list-sublevels
14635 (make-string (1- level) ?.) "")
14636 (org-get-heading))
14637 category tags-list)
14638 priority (org-get-priority txt))
14639 (goto-char lspos)
14640 (setq marker (org-agenda-new-marker))
14641 (org-add-props txt props
14642 'org-marker marker 'org-hd-marker marker 'org-category category
14643 'priority priority 'type "tagsmatch")
14644 (push txt rtn))
14645 ;; if we are to skip sublevels, jump to end of subtree
14646 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
14647 (when (and (eq action 'sparse-tree)
14648 (not org-sparse-tree-open-archived-trees))
14649 (org-hide-archived-subtrees (point-min) (point-max)))
14650 (nreverse rtn)))
14652 (defvar todo-only) ;; dynamically scoped
14654 (defun org-tags-sparse-tree (&optional todo-only match)
14655 "Create a sparse tree according to tags string MATCH.
14656 MATCH can contain positive and negative selection of tags, like
14657 \"+WORK+URGENT-WITHBOSS\".
14658 If optional argument TODO_ONLY is non-nil, only select lines that are
14659 also TODO lines."
14660 (interactive "P")
14661 (org-prepare-agenda-buffers (list (current-buffer)))
14662 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14664 (defvar org-cached-props nil)
14665 (defun org-cached-entry-get (pom property)
14666 (if (or (eq t org-use-property-inheritance)
14667 (member property org-use-property-inheritance))
14668 ;; Caching is not possible, check it directly
14669 (org-entry-get pom property 'inherit)
14670 ;; Get all properties, so that we can do complicated checks easily
14671 (cdr (assoc property (or org-cached-props
14672 (setq org-cached-props
14673 (org-entry-properties pom)))))))
14675 (defun org-global-tags-completion-table (&optional files)
14676 "Return the list of all tags in all agenda buffer/files."
14677 (save-excursion
14678 (org-uniquify
14679 (apply 'append
14680 (mapcar
14681 (lambda (file)
14682 (set-buffer (find-file-noselect file))
14683 (org-get-buffer-tags))
14684 (if (and files (car files))
14685 files
14686 (org-agenda-files)))))))
14688 (defun org-make-tags-matcher (match)
14689 "Create the TAGS//TODO matcher form for the selection string MATCH."
14690 ;; todo-only is scoped dynamically into this function, and the function
14691 ;; may change it it the matcher asksk for it.
14692 (unless match
14693 ;; Get a new match request, with completion
14694 (let ((org-last-tags-completion-table
14695 (org-global-tags-completion-table)))
14696 (setq match (completing-read
14697 "Match: " 'org-tags-completion-function nil nil nil
14698 'org-tags-history))))
14700 ;; Parse the string and create a lisp form
14701 (let ((match0 match)
14702 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
14703 minus tag mm
14704 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14705 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
14706 (if (string-match "/+" match)
14707 ;; match contains also a todo-matching request
14708 (progn
14709 (setq tagsmatch (substring match 0 (match-beginning 0))
14710 todomatch (substring match (match-end 0)))
14711 (if (string-match "^!" todomatch)
14712 (setq todo-only t todomatch (substring todomatch 1)))
14713 (if (string-match "^\\s-*$" todomatch)
14714 (setq todomatch nil)))
14715 ;; only matching tags
14716 (setq tagsmatch match todomatch nil))
14718 ;; Make the tags matcher
14719 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14720 (setq tagsmatcher t)
14721 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14722 (while (setq term (pop orterms))
14723 (while (and (equal (substring term -1) "\\") orterms)
14724 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14725 (while (string-match re term)
14726 (setq minus (and (match-end 1)
14727 (equal (match-string 1 term) "-"))
14728 tag (match-string 2 term)
14729 re-p (equal (string-to-char tag) ?{)
14730 level-p (match-end 3)
14731 prop-p (match-end 4)
14732 mm (cond
14733 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14734 (level-p `(= level ,(string-to-number
14735 (match-string 3 term))))
14736 (prop-p
14737 (setq pn (match-string 4 term)
14738 pv (match-string 5 term)
14739 cat-p (equal pn "CATEGORY")
14740 re-p (equal (string-to-char pv) ?{)
14741 pv (substring pv 1 -1))
14742 (if (equal pn "CATEGORY")
14743 (setq gv '(get-text-property (point) 'org-category))
14744 (setq gv `(org-cached-entry-get nil ,pn)))
14745 (if re-p
14746 `(string-match ,pv (or ,gv ""))
14747 `(equal ,pv ,gv)))
14748 (t `(member ,(downcase tag) tags-list)))
14749 mm (if minus (list 'not mm) mm)
14750 term (substring term (match-end 0)))
14751 (push mm tagsmatcher))
14752 (push (if (> (length tagsmatcher) 1)
14753 (cons 'and tagsmatcher)
14754 (car tagsmatcher))
14755 orlist)
14756 (setq tagsmatcher nil))
14757 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14758 (setq tagsmatcher
14759 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14761 ;; Make the todo matcher
14762 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14763 (setq todomatcher t)
14764 (setq orterms (org-split-string todomatch "|") orlist nil)
14765 (while (setq term (pop orterms))
14766 (while (string-match re term)
14767 (setq minus (and (match-end 1)
14768 (equal (match-string 1 term) "-"))
14769 kwd (match-string 2 term)
14770 re-p (equal (string-to-char kwd) ?{)
14771 term (substring term (match-end 0))
14772 mm (if re-p
14773 `(string-match ,(substring kwd 1 -1) todo)
14774 (list 'equal 'todo kwd))
14775 mm (if minus (list 'not mm) mm))
14776 (push mm todomatcher))
14777 (push (if (> (length todomatcher) 1)
14778 (cons 'and todomatcher)
14779 (car todomatcher))
14780 orlist)
14781 (setq todomatcher nil))
14782 (setq todomatcher (if (> (length orlist) 1)
14783 (cons 'or orlist) (car orlist))))
14785 ;; Return the string and lisp forms of the matcher
14786 (setq matcher (if todomatcher
14787 (list 'and tagsmatcher todomatcher)
14788 tagsmatcher))
14789 (cons match0 matcher)))
14791 (defun org-match-any-p (re list)
14792 "Does re match any element of list?"
14793 (setq list (mapcar (lambda (x) (string-match re x)) list))
14794 (delq nil list))
14796 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
14797 (defvar org-tags-overlay (org-make-overlay 1 1))
14798 (org-detach-overlay org-tags-overlay)
14800 (defun org-align-tags-here (to-col)
14801 ;; Assumes that this is a headline
14802 (let ((pos (point)) (col (current-column)) tags)
14803 (beginning-of-line 1)
14804 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14805 (< pos (match-beginning 2)))
14806 (progn
14807 (setq tags (match-string 2))
14808 (goto-char (match-beginning 1))
14809 (insert " ")
14810 (delete-region (point) (1+ (match-end 0)))
14811 (backward-char 1)
14812 (move-to-column
14813 (max (1+ (current-column))
14814 (1+ col)
14815 (if (> to-col 0)
14816 to-col
14817 (- (abs to-col) (length tags))))
14819 (insert tags)
14820 (move-to-column (min (current-column) col) t))
14821 (goto-char pos))))
14823 (defun org-set-tags (&optional arg just-align)
14824 "Set the tags for the current headline.
14825 With prefix ARG, realign all tags in headings in the current buffer."
14826 (interactive "P")
14827 (let* ((re (concat "^" outline-regexp))
14828 (current (org-get-tags-string))
14829 (col (current-column))
14830 (org-setting-tags t)
14831 table current-tags inherited-tags ; computed below when needed
14832 tags p0 c0 c1 rpl)
14833 (if arg
14834 (save-excursion
14835 (goto-char (point-min))
14836 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14837 (while (re-search-forward re nil t)
14838 (org-set-tags nil t)
14839 (end-of-line 1)))
14840 (message "All tags realigned to column %d" org-tags-column))
14841 (if just-align
14842 (setq tags current)
14843 ;; Get a new set of tags from the user
14844 (save-excursion
14845 (setq table (or org-tag-alist (org-get-buffer-tags))
14846 org-last-tags-completion-table table
14847 current-tags (org-split-string current ":")
14848 inherited-tags (nreverse
14849 (nthcdr (length current-tags)
14850 (nreverse (org-get-tags-at))))
14851 tags
14852 (if (or (eq t org-use-fast-tag-selection)
14853 (and org-use-fast-tag-selection
14854 (delq nil (mapcar 'cdr table))))
14855 (org-fast-tag-selection
14856 current-tags inherited-tags table
14857 (if org-fast-tag-selection-include-todo org-todo-key-alist))
14858 (let ((org-add-colon-after-tag-completion t))
14859 (org-trim
14860 (org-without-partial-completion
14861 (completing-read "Tags: " 'org-tags-completion-function
14862 nil nil current 'org-tags-history)))))))
14863 (while (string-match "[-+&]+" tags)
14864 ;; No boolean logic, just a list
14865 (setq tags (replace-match ":" t t tags))))
14867 (if (string-match "\\`[\t ]*\\'" tags)
14868 (setq tags "")
14869 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14870 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14872 ;; Insert new tags at the correct column
14873 (beginning-of-line 1)
14874 (cond
14875 ((and (equal current "") (equal tags "")))
14876 ((re-search-forward
14877 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14878 (point-at-eol) t)
14879 (if (equal tags "")
14880 (setq rpl "")
14881 (goto-char (match-beginning 0))
14882 (setq c0 (current-column) p0 (point)
14883 c1 (max (1+ c0) (if (> org-tags-column 0)
14884 org-tags-column
14885 (- (- org-tags-column) (length tags))))
14886 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14887 (replace-match rpl t t)
14888 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
14889 tags)
14890 (t (error "Tags alignment failed")))
14891 (move-to-column col)
14892 (unless just-align
14893 (run-hooks 'org-after-tags-change-hook)))))
14895 (defun org-change-tag-in-region (beg end tag off)
14896 "Add or remove TAG for each entry in the region.
14897 This works in the agenda, and also in an org-mode buffer."
14898 (interactive
14899 (list (region-beginning) (region-end)
14900 (let ((org-last-tags-completion-table
14901 (if (org-mode-p)
14902 (org-get-buffer-tags)
14903 (org-global-tags-completion-table))))
14904 (completing-read
14905 "Tag: " 'org-tags-completion-function nil nil nil
14906 'org-tags-history))
14907 (progn
14908 (message "[s]et or [r]emove? ")
14909 (equal (read-char-exclusive) ?r))))
14910 (if (fboundp 'deactivate-mark) (deactivate-mark))
14911 (let ((agendap (equal major-mode 'org-agenda-mode))
14912 l1 l2 m buf pos newhead (cnt 0))
14913 (goto-char end)
14914 (setq l2 (1- (org-current-line)))
14915 (goto-char beg)
14916 (setq l1 (org-current-line))
14917 (loop for l from l1 to l2 do
14918 (goto-line l)
14919 (setq m (get-text-property (point) 'org-hd-marker))
14920 (when (or (and (org-mode-p) (org-on-heading-p))
14921 (and agendap m))
14922 (setq buf (if agendap (marker-buffer m) (current-buffer))
14923 pos (if agendap m (point)))
14924 (with-current-buffer buf
14925 (save-excursion
14926 (save-restriction
14927 (goto-char pos)
14928 (setq cnt (1+ cnt))
14929 (org-toggle-tag tag (if off 'off 'on))
14930 (setq newhead (org-get-heading)))))
14931 (and agendap (org-agenda-change-all-lines newhead m))))
14932 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14934 (defun org-tags-completion-function (string predicate &optional flag)
14935 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14936 (confirm (lambda (x) (stringp (car x)))))
14937 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
14938 (setq s1 (match-string 1 string)
14939 s2 (match-string 2 string))
14940 (setq s1 "" s2 string))
14941 (cond
14942 ((eq flag nil)
14943 ;; try completion
14944 (setq rtn (try-completion s2 ctable confirm))
14945 (if (stringp rtn)
14946 (setq rtn
14947 (concat s1 s2 (substring rtn (length s2))
14948 (if (and org-add-colon-after-tag-completion
14949 (assoc rtn ctable))
14950 ":" ""))))
14951 rtn)
14952 ((eq flag t)
14953 ;; all-completions
14954 (all-completions s2 ctable confirm)
14956 ((eq flag 'lambda)
14957 ;; exact match?
14958 (assoc s2 ctable)))
14961 (defun org-fast-tag-insert (kwd tags face &optional end)
14962 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
14963 (insert (format "%-12s" (concat kwd ":"))
14964 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14965 (or end "")))
14967 (defun org-fast-tag-show-exit (flag)
14968 (save-excursion
14969 (goto-line 3)
14970 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14971 (replace-match ""))
14972 (when flag
14973 (end-of-line 1)
14974 (move-to-column (- (window-width) 19) t)
14975 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14977 (defun org-set-current-tags-overlay (current prefix)
14978 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14979 (if (featurep 'xemacs)
14980 (org-overlay-display org-tags-overlay (concat prefix s)
14981 'secondary-selection)
14982 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14983 (org-overlay-display org-tags-overlay (concat prefix s)))))
14985 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14986 "Fast tag selection with single keys.
14987 CURRENT is the current list of tags in the headline, INHERITED is the
14988 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14989 possibly with grouping information. TODO-TABLE is a similar table with
14990 TODO keywords, should these have keys assigned to them.
14991 If the keys are nil, a-z are automatically assigned.
14992 Returns the new tags string, or nil to not change the current settings."
14993 (let* ((fulltable (append table todo-table))
14994 (maxlen (apply 'max (mapcar
14995 (lambda (x)
14996 (if (stringp (car x)) (string-width (car x)) 0))
14997 fulltable)))
14998 (buf (current-buffer))
14999 (expert (eq org-fast-tag-selection-single-key 'expert))
15000 (buffer-tags nil)
15001 (fwidth (+ maxlen 3 1 3))
15002 (ncol (/ (- (window-width) 4) fwidth))
15003 (i-face 'org-done)
15004 (c-face 'org-todo)
15005 tg cnt e c char c1 c2 ntable tbl rtn
15006 ov-start ov-end ov-prefix
15007 (exit-after-next org-fast-tag-selection-single-key)
15008 (done-keywords org-done-keywords)
15009 groups ingroup)
15010 (save-excursion
15011 (beginning-of-line 1)
15012 (if (looking-at
15013 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15014 (setq ov-start (match-beginning 1)
15015 ov-end (match-end 1)
15016 ov-prefix "")
15017 (setq ov-start (1- (point-at-eol))
15018 ov-end (1+ ov-start))
15019 (skip-chars-forward "^\n\r")
15020 (setq ov-prefix
15021 (concat
15022 (buffer-substring (1- (point)) (point))
15023 (if (> (current-column) org-tags-column)
15025 (make-string (- org-tags-column (current-column)) ?\ ))))))
15026 (org-move-overlay org-tags-overlay ov-start ov-end)
15027 (save-window-excursion
15028 (if expert
15029 (set-buffer (get-buffer-create " *Org tags*"))
15030 (delete-other-windows)
15031 (split-window-vertically)
15032 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15033 (erase-buffer)
15034 (org-set-local 'org-done-keywords done-keywords)
15035 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15036 (org-fast-tag-insert "Current" current c-face "\n\n")
15037 (org-fast-tag-show-exit exit-after-next)
15038 (org-set-current-tags-overlay current ov-prefix)
15039 (setq tbl fulltable char ?a cnt 0)
15040 (while (setq e (pop tbl))
15041 (cond
15042 ((equal e '(:startgroup))
15043 (push '() groups) (setq ingroup t)
15044 (when (not (= cnt 0))
15045 (setq cnt 0)
15046 (insert "\n"))
15047 (insert "{ "))
15048 ((equal e '(:endgroup))
15049 (setq ingroup nil cnt 0)
15050 (insert "}\n"))
15052 (setq tg (car e) c2 nil)
15053 (if (cdr e)
15054 (setq c (cdr e))
15055 ;; automatically assign a character.
15056 (setq c1 (string-to-char
15057 (downcase (substring
15058 tg (if (= (string-to-char tg) ?@) 1 0)))))
15059 (if (or (rassoc c1 ntable) (rassoc c1 table))
15060 (while (or (rassoc char ntable) (rassoc char table))
15061 (setq char (1+ char)))
15062 (setq c2 c1))
15063 (setq c (or c2 char)))
15064 (if ingroup (push tg (car groups)))
15065 (setq tg (org-add-props tg nil 'face
15066 (cond
15067 ((not (assoc tg table))
15068 (org-get-todo-face tg))
15069 ((member tg current) c-face)
15070 ((member tg inherited) i-face)
15071 (t nil))))
15072 (if (and (= cnt 0) (not ingroup)) (insert " "))
15073 (insert "[" c "] " tg (make-string
15074 (- fwidth 4 (length tg)) ?\ ))
15075 (push (cons tg c) ntable)
15076 (when (= (setq cnt (1+ cnt)) ncol)
15077 (insert "\n")
15078 (if ingroup (insert " "))
15079 (setq cnt 0)))))
15080 (setq ntable (nreverse ntable))
15081 (insert "\n")
15082 (goto-char (point-min))
15083 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15084 (fit-window-to-buffer))
15085 (setq rtn
15086 (catch 'exit
15087 (while t
15088 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15089 (if groups " [!] no groups" " [!]groups")
15090 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15091 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15092 (cond
15093 ((= c ?\r) (throw 'exit t))
15094 ((= c ?!)
15095 (setq groups (not groups))
15096 (goto-char (point-min))
15097 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15098 ((= c ?\C-c)
15099 (if (not expert)
15100 (org-fast-tag-show-exit
15101 (setq exit-after-next (not exit-after-next)))
15102 (setq expert nil)
15103 (delete-other-windows)
15104 (split-window-vertically)
15105 (org-switch-to-buffer-other-window " *Org tags*")
15106 (and (fboundp 'fit-window-to-buffer)
15107 (fit-window-to-buffer))))
15108 ((or (= c ?\C-g)
15109 (and (= c ?q) (not (rassoc c ntable))))
15110 (org-detach-overlay org-tags-overlay)
15111 (setq quit-flag t))
15112 ((= c ?\ )
15113 (setq current nil)
15114 (if exit-after-next (setq exit-after-next 'now)))
15115 ((= c ?\t)
15116 (condition-case nil
15117 (setq tg (completing-read
15118 "Tag: "
15119 (or buffer-tags
15120 (with-current-buffer buf
15121 (org-get-buffer-tags)))))
15122 (quit (setq tg "")))
15123 (when (string-match "\\S-" tg)
15124 (add-to-list 'buffer-tags (list tg))
15125 (if (member tg current)
15126 (setq current (delete tg current))
15127 (push tg current)))
15128 (if exit-after-next (setq exit-after-next 'now)))
15129 ((setq e (rassoc c todo-table) tg (car e))
15130 (with-current-buffer buf
15131 (save-excursion (org-todo tg)))
15132 (if exit-after-next (setq exit-after-next 'now)))
15133 ((setq e (rassoc c ntable) tg (car e))
15134 (if (member tg current)
15135 (setq current (delete tg current))
15136 (loop for g in groups do
15137 (if (member tg g)
15138 (mapc (lambda (x)
15139 (setq current (delete x current)))
15140 g)))
15141 (push tg current))
15142 (if exit-after-next (setq exit-after-next 'now))))
15144 ;; Create a sorted list
15145 (setq current
15146 (sort current
15147 (lambda (a b)
15148 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15149 (if (eq exit-after-next 'now) (throw 'exit t))
15150 (goto-char (point-min))
15151 (beginning-of-line 2)
15152 (delete-region (point) (point-at-eol))
15153 (org-fast-tag-insert "Current" current c-face)
15154 (org-set-current-tags-overlay current ov-prefix)
15155 (while (re-search-forward
15156 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15157 (setq tg (match-string 1))
15158 (add-text-properties
15159 (match-beginning 1) (match-end 1)
15160 (list 'face
15161 (cond
15162 ((member tg current) c-face)
15163 ((member tg inherited) i-face)
15164 (t (get-text-property (match-beginning 1) 'face))))))
15165 (goto-char (point-min)))))
15166 (org-detach-overlay org-tags-overlay)
15167 (if rtn
15168 (mapconcat 'identity current ":")
15169 nil))))
15171 (defun org-get-tags-string ()
15172 "Get the TAGS string in the current headline."
15173 (unless (org-on-heading-p t)
15174 (error "Not on a heading"))
15175 (save-excursion
15176 (beginning-of-line 1)
15177 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15178 (org-match-string-no-properties 1)
15179 "")))
15181 (defun org-get-tags ()
15182 "Get the list of tags specified in the current headline."
15183 (org-split-string (org-get-tags-string) ":"))
15185 (defun org-get-buffer-tags ()
15186 "Get a table of all tags used in the buffer, for completion."
15187 (let (tags)
15188 (save-excursion
15189 (goto-char (point-min))
15190 (while (re-search-forward
15191 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15192 (when (equal (char-after (point-at-bol 0)) ?*)
15193 (mapc (lambda (x) (add-to-list 'tags x))
15194 (org-split-string (org-match-string-no-properties 1) ":")))))
15195 (mapcar 'list tags)))
15198 ;;;; Properties
15200 ;;; Setting and retrieving properties
15202 (defconst org-special-properties
15203 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15204 "TIMESTAMP" "TIMESTAMP_IA")
15205 "The special properties valid in Org-mode.
15207 These are properties that are not defined in the property drawer,
15208 but in some other way.")
15210 (defconst org-default-properties
15211 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15212 "LOCATION" "LOGGING" "COLUMNS")
15213 "Some properties that are used by Org-mode for various purposes.
15214 Being in this list makes sure that they are offered for completion.")
15216 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15217 "Regular expression matching the first line of a property drawer.")
15219 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15220 "Regular expression matching the first line of a property drawer.")
15222 (defun org-property-action ()
15223 "Do an action on properties."
15224 (interactive)
15225 (let (c)
15226 (org-at-property-p)
15227 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15228 (setq c (read-char-exclusive))
15229 (cond
15230 ((equal c ?s)
15231 (call-interactively 'org-set-property))
15232 ((equal c ?d)
15233 (call-interactively 'org-delete-property))
15234 ((equal c ?D)
15235 (call-interactively 'org-delete-property-globally))
15236 ((equal c ?c)
15237 (call-interactively 'org-compute-property-at-point))
15238 (t (error "No such property action %c" c)))))
15240 (defun org-at-property-p ()
15241 "Is the cursor in a property line?"
15242 ;; FIXME: Does not check if we are actually in the drawer.
15243 ;; FIXME: also returns true on any drawers.....
15244 ;; This is used by C-c C-c for property action.
15245 (save-excursion
15246 (beginning-of-line 1)
15247 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15249 (defmacro org-with-point-at (pom &rest body)
15250 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15251 (declare (indent 1) (debug t))
15252 `(save-excursion
15253 (if (markerp pom) (set-buffer (marker-buffer pom)))
15254 (save-excursion
15255 (goto-char (or pom (point)))
15256 ,@body)))
15258 (defun org-get-property-block (&optional beg end force)
15259 "Return the (beg . end) range of the body of the property drawer.
15260 BEG and END can be beginning and end of subtree, if not given
15261 they will be found.
15262 If the drawer does not exist and FORCE is non-nil, create the drawer."
15263 (catch 'exit
15264 (save-excursion
15265 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15266 (end (or end (progn (outline-next-heading) (point)))))
15267 (goto-char beg)
15268 (if (re-search-forward org-property-start-re end t)
15269 (setq beg (1+ (match-end 0)))
15270 (if force
15271 (save-excursion
15272 (org-insert-property-drawer)
15273 (setq end (progn (outline-next-heading) (point))))
15274 (throw 'exit nil))
15275 (goto-char beg)
15276 (if (re-search-forward org-property-start-re end t)
15277 (setq beg (1+ (match-end 0)))))
15278 (if (re-search-forward org-property-end-re end t)
15279 (setq end (match-beginning 0))
15280 (or force (throw 'exit nil))
15281 (goto-char beg)
15282 (setq end beg)
15283 (org-indent-line-function)
15284 (insert ":END:\n"))
15285 (cons beg end)))))
15287 (defun org-entry-properties (&optional pom which)
15288 "Get all properties of the entry at point-or-marker POM.
15289 This includes the TODO keyword, the tags, time strings for deadline,
15290 scheduled, and clocking, and any additional properties defined in the
15291 entry. The return value is an alist, keys may occur multiple times
15292 if the property key was used several times.
15293 POM may also be nil, in which case the current entry is used.
15294 If WHICH is nil or `all', get all properties. If WHICH is
15295 `special' or `standard', only get that subclass."
15296 (setq which (or which 'all))
15297 (org-with-point-at pom
15298 (let ((clockstr (substring org-clock-string 0 -1))
15299 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15300 beg end range props sum-props key value string)
15301 (save-excursion
15302 (when (condition-case nil (org-back-to-heading t) (error nil))
15303 (setq beg (point))
15304 (setq sum-props (get-text-property (point) 'org-summaries))
15305 (outline-next-heading)
15306 (setq end (point))
15307 (when (memq which '(all special))
15308 ;; Get the special properties, like TODO and tags
15309 (goto-char beg)
15310 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15311 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15312 (when (looking-at org-priority-regexp)
15313 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15314 (when (and (setq value (org-get-tags-string))
15315 (string-match "\\S-" value))
15316 (push (cons "TAGS" value) props))
15317 (when (setq value (org-get-tags-at))
15318 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15319 props))
15320 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15321 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15322 string (if (equal key clockstr)
15323 (org-no-properties
15324 (org-trim
15325 (buffer-substring
15326 (match-beginning 3) (goto-char (point-at-eol)))))
15327 (substring (org-match-string-no-properties 3) 1 -1)))
15328 (unless key
15329 (if (= (char-after (match-beginning 3)) ?\[)
15330 (setq key "TIMESTAMP_IA")
15331 (setq key "TIMESTAMP")))
15332 (when (or (equal key clockstr) (not (assoc key props)))
15333 (push (cons key string) props)))
15337 (when (memq which '(all standard))
15338 ;; Get the standard properties, like :PORP: ...
15339 (setq range (org-get-property-block beg end))
15340 (when range
15341 (goto-char (car range))
15342 (while (re-search-forward
15343 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15344 (cdr range) t)
15345 (setq key (org-match-string-no-properties 1)
15346 value (org-trim (or (org-match-string-no-properties 2) "")))
15347 (unless (member key excluded)
15348 (push (cons key (or value "")) props)))))
15349 (append sum-props (nreverse props)))))))
15351 (defun org-entry-get (pom property &optional inherit)
15352 "Get value of PROPERTY for entry at point-or-marker POM.
15353 If INHERIT is non-nil and the entry does not have the property,
15354 then also check higher levels of the hierarchy.
15355 If the property is present but empty, the return value is the empty string.
15356 If the property is not present at all, nil is returned."
15357 (org-with-point-at pom
15358 (if inherit
15359 (org-entry-get-with-inheritance property)
15360 (if (member property org-special-properties)
15361 ;; We need a special property. Use brute force, get all properties.
15362 (cdr (assoc property (org-entry-properties nil 'special)))
15363 (let ((range (org-get-property-block)))
15364 (if (and range
15365 (goto-char (car range))
15366 (re-search-forward
15367 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
15368 (cdr range) t))
15369 ;; Found the property, return it.
15370 (if (match-end 1)
15371 (org-match-string-no-properties 1)
15372 "")))))))
15374 (defun org-entry-delete (pom property)
15375 "Delete the property PROPERTY from entry at point-or-marker POM."
15376 (org-with-point-at pom
15377 (if (member property org-special-properties)
15378 nil ; cannot delete these properties.
15379 (let ((range (org-get-property-block)))
15380 (if (and range
15381 (goto-char (car range))
15382 (re-search-forward
15383 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
15384 (cdr range) t))
15385 (progn
15386 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15388 nil)))))
15390 ;; Multi-values properties are properties that contain multiple values
15391 ;; These values are assumed to be single words, separated by whitespace.
15392 (defun org-entry-add-to-multivalued-property (pom property value)
15393 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15394 (let* ((old (org-entry-get pom property))
15395 (values (and old (org-split-string old "[ \t]"))))
15396 (unless (member value values)
15397 (setq values (cons value values))
15398 (org-entry-put pom property
15399 (mapconcat 'identity values " ")))))
15401 (defun org-entry-remove-from-multivalued-property (pom property value)
15402 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15403 (let* ((old (org-entry-get pom property))
15404 (values (and old (org-split-string old "[ \t]"))))
15405 (when (member value values)
15406 (setq values (delete value values))
15407 (org-entry-put pom property
15408 (mapconcat 'identity values " ")))))
15410 (defun org-entry-member-in-multivalued-property (pom property value)
15411 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15412 (let* ((old (org-entry-get pom property))
15413 (values (and old (org-split-string old "[ \t]"))))
15414 (member value values)))
15416 (defvar org-entry-property-inherited-from (make-marker))
15418 (defun org-entry-get-with-inheritance (property)
15419 "Get entry property, and search higher levels if not present."
15420 (let (tmp)
15421 (save-excursion
15422 (save-restriction
15423 (widen)
15424 (catch 'ex
15425 (while t
15426 (when (setq tmp (org-entry-get nil property))
15427 (org-back-to-heading t)
15428 (move-marker org-entry-property-inherited-from (point))
15429 (throw 'ex tmp))
15430 (or (org-up-heading-safe) (throw 'ex nil)))))
15431 (or tmp (cdr (assoc property org-local-properties))
15432 (cdr (assoc property org-global-properties))))))
15434 (defun org-entry-put (pom property value)
15435 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15436 (org-with-point-at pom
15437 (org-back-to-heading t)
15438 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15439 range)
15440 (cond
15441 ((equal property "TODO")
15442 (when (and (stringp value) (string-match "\\S-" value)
15443 (not (member value org-todo-keywords-1)))
15444 (error "\"%s\" is not a valid TODO state" value))
15445 (if (or (not value)
15446 (not (string-match "\\S-" value)))
15447 (setq value 'none))
15448 (org-todo value)
15449 (org-set-tags nil 'align))
15450 ((equal property "PRIORITY")
15451 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15452 (string-to-char value) ?\ ))
15453 (org-set-tags nil 'align))
15454 ((equal property "SCHEDULED")
15455 (if (re-search-forward org-scheduled-time-regexp end t)
15456 (cond
15457 ((eq value 'earlier) (org-timestamp-change -1 'day))
15458 ((eq value 'later) (org-timestamp-change 1 'day))
15459 (t (call-interactively 'org-schedule)))
15460 (call-interactively 'org-schedule)))
15461 ((equal property "DEADLINE")
15462 (if (re-search-forward org-deadline-time-regexp end t)
15463 (cond
15464 ((eq value 'earlier) (org-timestamp-change -1 'day))
15465 ((eq value 'later) (org-timestamp-change 1 'day))
15466 (t (call-interactively 'org-deadline)))
15467 (call-interactively 'org-deadline)))
15468 ((member property org-special-properties)
15469 (error "The %s property can not yet be set with `org-entry-put'"
15470 property))
15471 (t ; a non-special property
15472 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15473 (setq range (org-get-property-block beg end 'force))
15474 (goto-char (car range))
15475 (if (re-search-forward
15476 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
15477 (progn
15478 (delete-region (match-beginning 1) (match-end 1))
15479 (goto-char (match-beginning 1)))
15480 (goto-char (cdr range))
15481 (insert "\n")
15482 (backward-char 1)
15483 (org-indent-line-function)
15484 (insert ":" property ":"))
15485 (and value (insert " " value))
15486 (org-indent-line-function)))))))
15488 (defun org-buffer-property-keys (&optional include-specials include-defaults)
15489 "Get all property keys in the current buffer.
15490 With INCLUDE-SPECIALS, also list the special properties that relect things
15491 like tags and TODO state.
15492 With INCLUDE-DEFAULTS, also include properties that has special meaning
15493 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
15494 (let (rtn range)
15495 (save-excursion
15496 (save-restriction
15497 (widen)
15498 (goto-char (point-min))
15499 (while (re-search-forward org-property-start-re nil t)
15500 (setq range (org-get-property-block))
15501 (goto-char (car range))
15502 (while (re-search-forward
15503 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
15504 (cdr range) t)
15505 (add-to-list 'rtn (org-match-string-no-properties 1)))
15506 (outline-next-heading))))
15508 (when include-specials
15509 (setq rtn (append org-special-properties rtn)))
15511 (when include-defaults
15512 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
15514 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15516 (defun org-property-values (key)
15517 "Return a list of all values of property KEY."
15518 (save-excursion
15519 (save-restriction
15520 (widen)
15521 (goto-char (point-min))
15522 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
15523 values)
15524 (while (re-search-forward re nil t)
15525 (add-to-list 'values (org-trim (match-string 1))))
15526 (delete "" values)))))
15528 (defun org-insert-property-drawer ()
15529 "Insert a property drawer into the current entry."
15530 (interactive)
15531 (org-back-to-heading t)
15532 (looking-at outline-regexp)
15533 (let ((indent (- (match-end 0)(match-beginning 0)))
15534 (beg (point))
15535 (re (concat "^[ \t]*" org-keyword-time-regexp))
15536 end hiddenp)
15537 (outline-next-heading)
15538 (setq end (point))
15539 (goto-char beg)
15540 (while (re-search-forward re end t))
15541 (setq hiddenp (org-invisible-p))
15542 (end-of-line 1)
15543 (and (equal (char-after) ?\n) (forward-char 1))
15544 (org-skip-over-state-notes)
15545 (skip-chars-backward " \t\n\r")
15546 (if (eq (char-before) ?*) (forward-char 1))
15547 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15548 (beginning-of-line 0)
15549 (indent-to-column indent)
15550 (beginning-of-line 2)
15551 (indent-to-column indent)
15552 (beginning-of-line 0)
15553 (if hiddenp
15554 (save-excursion
15555 (org-back-to-heading t)
15556 (hide-entry))
15557 (org-flag-drawer t))))
15559 (defun org-set-property (property value)
15560 "In the current entry, set PROPERTY to VALUE.
15561 When called interactively, this will prompt for a property name, offering
15562 completion on existing and default properties. And then it will prompt
15563 for a value, offering competion either on allowed values (via an inherited
15564 xxx_ALL property) or on existing values in other instances of this property
15565 in the current file."
15566 (interactive
15567 (let* ((prop (completing-read
15568 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
15569 (cur (org-entry-get nil prop))
15570 (allowed (org-property-get-allowed-values nil prop 'table))
15571 (existing (mapcar 'list (org-property-values prop)))
15572 (val (if allowed
15573 (completing-read "Value: " allowed nil 'req-match)
15574 (completing-read
15575 (concat "Value" (if (and cur (string-match "\\S-" cur))
15576 (concat "[" cur "]") "")
15577 ": ")
15578 existing nil nil "" nil cur))))
15579 (list prop (if (equal val "") cur val))))
15580 (unless (equal (org-entry-get nil property) value)
15581 (org-entry-put nil property value)))
15583 (defun org-delete-property (property)
15584 "In the current entry, delete PROPERTY."
15585 (interactive
15586 (let* ((prop (completing-read
15587 "Property: " (org-entry-properties nil 'standard))))
15588 (list prop)))
15589 (message (concat "Property " property
15590 (if (org-entry-delete nil property)
15591 " deleted"
15592 " was not present in the entry"))))
15594 (defun org-delete-property-globally (property)
15595 "Remove PROPERTY globally, from all entries."
15596 (interactive
15597 (let* ((prop (completing-read
15598 "Globally remove property: "
15599 (mapcar 'list (org-buffer-property-keys)))))
15600 (list prop)))
15601 (save-excursion
15602 (save-restriction
15603 (widen)
15604 (goto-char (point-min))
15605 (let ((cnt 0))
15606 (while (re-search-forward
15607 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
15608 nil t)
15609 (setq cnt (1+ cnt))
15610 (replace-match ""))
15611 (message "Property \"%s\" removed from %d entries" property cnt)))))
15613 (defvar org-columns-current-fmt-compiled) ; defined below
15615 (defun org-compute-property-at-point ()
15616 "Compute the property at point.
15617 This looks for an enclosing column format, extracts the operator and
15618 then applies it to the proerty in the column format's scope."
15619 (interactive)
15620 (unless (org-at-property-p)
15621 (error "Not at a property"))
15622 (let ((prop (org-match-string-no-properties 2)))
15623 (org-columns-get-format-and-top-level)
15624 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15625 (error "No operator defined for property %s" prop))
15626 (org-columns-compute prop)))
15628 (defun org-property-get-allowed-values (pom property &optional table)
15629 "Get allowed values for the property PROPERTY.
15630 When TABLE is non-nil, return an alist that can directly be used for
15631 completion."
15632 (let (vals)
15633 (cond
15634 ((equal property "TODO")
15635 (setq vals (org-with-point-at pom
15636 (append org-todo-keywords-1 '("")))))
15637 ((equal property "PRIORITY")
15638 (let ((n org-lowest-priority))
15639 (while (>= n org-highest-priority)
15640 (push (char-to-string n) vals)
15641 (setq n (1- n)))))
15642 ((member property org-special-properties))
15644 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15646 (when (and vals (string-match "\\S-" vals))
15647 (setq vals (car (read-from-string (concat "(" vals ")"))))
15648 (setq vals (mapcar (lambda (x)
15649 (cond ((stringp x) x)
15650 ((numberp x) (number-to-string x))
15651 ((symbolp x) (symbol-name x))
15652 (t "???")))
15653 vals)))))
15654 (if table (mapcar 'list vals) vals)))
15656 (defun org-property-previous-allowed-value (&optional previous)
15657 "Switch to the next allowed value for this property."
15658 (interactive)
15659 (org-property-next-allowed-value t))
15661 (defun org-property-next-allowed-value (&optional previous)
15662 "Switch to the next allowed value for this property."
15663 (interactive)
15664 (unless (org-at-property-p)
15665 (error "Not at a property"))
15666 (let* ((key (match-string 2))
15667 (value (match-string 3))
15668 (allowed (or (org-property-get-allowed-values (point) key)
15669 (and (member value '("[ ]" "[-]" "[X]"))
15670 '("[ ]" "[X]"))))
15671 nval)
15672 (unless allowed
15673 (error "Allowed values for this property have not been defined"))
15674 (if previous (setq allowed (reverse allowed)))
15675 (if (member value allowed)
15676 (setq nval (car (cdr (member value allowed)))))
15677 (setq nval (or nval (car allowed)))
15678 (if (equal nval value)
15679 (error "Only one allowed value for this property"))
15680 (org-at-property-p)
15681 (replace-match (concat " :" key ": " nval) t t)
15682 (org-indent-line-function)
15683 (beginning-of-line 1)
15684 (skip-chars-forward " \t")))
15686 (defun org-find-entry-with-id (ident)
15687 "Locate the entry that contains the ID property with exact value IDENT.
15688 IDENT can be a string, a symbol or a number, this function will search for
15689 the string representation of it.
15690 Return the position where this entry starts, or nil if there is no such entry."
15691 (let ((id (cond
15692 ((stringp ident) ident)
15693 ((symbol-name ident) (symbol-name ident))
15694 ((numberp ident) (number-to-string ident))
15695 (t (error "IDENT %s must be a string, symbol or number" ident))))
15696 (case-fold-search nil))
15697 (save-excursion
15698 (save-restriction
15699 (goto-char (point-min))
15700 (when (re-search-forward
15701 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15702 nil t)
15703 (org-back-to-heading)
15704 (point))))))
15706 ;;; Column View
15708 (defvar org-columns-overlays nil
15709 "Holds the list of current column overlays.")
15711 (defvar org-columns-current-fmt nil
15712 "Local variable, holds the currently active column format.")
15713 (defvar org-columns-current-fmt-compiled nil
15714 "Local variable, holds the currently active column format.
15715 This is the compiled version of the format.")
15716 (defvar org-columns-current-widths nil
15717 "Loval variable, holds the currently widths of fields.")
15718 (defvar org-columns-current-maxwidths nil
15719 "Loval variable, holds the currently active maximum column widths.")
15720 (defvar org-columns-begin-marker (make-marker)
15721 "Points to the position where last a column creation command was called.")
15722 (defvar org-columns-top-level-marker (make-marker)
15723 "Points to the position where current columns region starts.")
15725 (defvar org-columns-map (make-sparse-keymap)
15726 "The keymap valid in column display.")
15728 (defun org-columns-content ()
15729 "Switch to contents view while in columns view."
15730 (interactive)
15731 (org-overview)
15732 (org-content))
15734 (org-defkey org-columns-map "c" 'org-columns-content)
15735 (org-defkey org-columns-map "o" 'org-overview)
15736 (org-defkey org-columns-map "e" 'org-columns-edit-value)
15737 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
15738 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
15739 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
15740 (org-defkey org-columns-map "v" 'org-columns-show-value)
15741 (org-defkey org-columns-map "q" 'org-columns-quit)
15742 (org-defkey org-columns-map "r" 'org-columns-redo)
15743 (org-defkey org-columns-map [left] 'backward-char)
15744 (org-defkey org-columns-map "\M-b" 'backward-char)
15745 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
15746 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
15747 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
15748 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
15749 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
15750 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
15751 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
15752 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
15753 (org-defkey org-columns-map "<" 'org-columns-narrow)
15754 (org-defkey org-columns-map ">" 'org-columns-widen)
15755 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
15756 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
15757 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
15758 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
15760 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
15761 '("Column"
15762 ["Edit property" org-columns-edit-value t]
15763 ["Next allowed value" org-columns-next-allowed-value t]
15764 ["Previous allowed value" org-columns-previous-allowed-value t]
15765 ["Show full value" org-columns-show-value t]
15766 ["Edit allowed values" org-columns-edit-allowed t]
15767 "--"
15768 ["Edit column attributes" org-columns-edit-attributes t]
15769 ["Increase column width" org-columns-widen t]
15770 ["Decrease column width" org-columns-narrow t]
15771 "--"
15772 ["Move column right" org-columns-move-right t]
15773 ["Move column left" org-columns-move-left t]
15774 ["Add column" org-columns-new t]
15775 ["Delete column" org-columns-delete t]
15776 "--"
15777 ["CONTENTS" org-columns-content t]
15778 ["OVERVIEW" org-overview t]
15779 ["Refresh columns display" org-columns-redo t]
15780 "--"
15781 ["Open link" org-columns-open-link t]
15782 "--"
15783 ["Quit" org-columns-quit t]))
15785 (defun org-columns-new-overlay (beg end &optional string face)
15786 "Create a new column overlay and add it to the list."
15787 (let ((ov (org-make-overlay beg end)))
15788 (org-overlay-put ov 'face (or face 'secondary-selection))
15789 (org-overlay-display ov string face)
15790 (push ov org-columns-overlays)
15791 ov))
15793 (defun org-columns-display-here (&optional props)
15794 "Overlay the current line with column display."
15795 (interactive)
15796 (let* ((fmt org-columns-current-fmt-compiled)
15797 (beg (point-at-bol))
15798 (level-face (save-excursion
15799 (beginning-of-line 1)
15800 (and (looking-at "\\(\\**\\)\\(\\* \\)")
15801 (org-get-level-face 2))))
15802 (color (list :foreground
15803 (face-attribute (or level-face 'default) :foreground)))
15804 props pom property ass width f string ov column val modval)
15805 ;; Check if the entry is in another buffer.
15806 (unless props
15807 (if (eq major-mode 'org-agenda-mode)
15808 (setq pom (or (get-text-property (point) 'org-hd-marker)
15809 (get-text-property (point) 'org-marker))
15810 props (if pom (org-entry-properties pom) nil))
15811 (setq props (org-entry-properties nil))))
15812 ;; Walk the format
15813 (while (setq column (pop fmt))
15814 (setq property (car column)
15815 ass (if (equal property "ITEM")
15816 (cons "ITEM"
15817 (save-match-data
15818 (org-no-properties
15819 (org-remove-tabs
15820 (buffer-substring-no-properties
15821 (point-at-bol) (point-at-eol))))))
15822 (assoc property props))
15823 width (or (cdr (assoc property org-columns-current-maxwidths))
15824 (nth 2 column)
15825 (length property))
15826 f (format "%%-%d.%ds | " width width)
15827 val (or (cdr ass) "")
15828 modval (if (equal property "ITEM")
15829 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
15830 string (format f (or modval val)))
15831 ;; Create the overlay
15832 (org-unmodified
15833 (setq ov (org-columns-new-overlay
15834 beg (setq beg (1+ beg)) string
15835 (list color 'org-column)))
15836 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
15837 (org-overlay-put ov 'keymap org-columns-map)
15838 (org-overlay-put ov 'org-columns-key property)
15839 (org-overlay-put ov 'org-columns-value (cdr ass))
15840 (org-overlay-put ov 'org-columns-value-modified modval)
15841 (org-overlay-put ov 'org-columns-pom pom)
15842 (org-overlay-put ov 'org-columns-format f))
15843 (if (or (not (char-after beg))
15844 (equal (char-after beg) ?\n))
15845 (let ((inhibit-read-only t))
15846 (save-excursion
15847 (goto-char beg)
15848 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
15849 ;; Make the rest of the line disappear.
15850 (org-unmodified
15851 (setq ov (org-columns-new-overlay beg (point-at-eol)))
15852 (org-overlay-put ov 'invisible t)
15853 (org-overlay-put ov 'keymap org-columns-map)
15854 (org-overlay-put ov 'intangible t)
15855 (push ov org-columns-overlays)
15856 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
15857 (org-overlay-put ov 'keymap org-columns-map)
15858 (push ov org-columns-overlays)
15859 (let ((inhibit-read-only t))
15860 (put-text-property (max (point-min) (1- (point-at-bol)))
15861 (min (point-max) (1+ (point-at-eol)))
15862 'read-only "Type `e' to edit property")))))
15864 (defvar org-previous-header-line-format nil
15865 "The header line format before column view was turned on.")
15866 (defvar org-columns-inhibit-recalculation nil
15867 "Inhibit recomputing of columns on column view startup.")
15870 (defvar header-line-format)
15871 (defun org-columns-display-here-title ()
15872 "Overlay the newline before the current line with the table title."
15873 (interactive)
15874 (let ((fmt org-columns-current-fmt-compiled)
15875 string (title "")
15876 property width f column str widths)
15877 (while (setq column (pop fmt))
15878 (setq property (car column)
15879 str (or (nth 1 column) property)
15880 width (or (cdr (assoc property org-columns-current-maxwidths))
15881 (nth 2 column)
15882 (length str))
15883 widths (push width widths)
15884 f (format "%%-%d.%ds | " width width)
15885 string (format f str)
15886 title (concat title string)))
15887 (setq title (concat
15888 (org-add-props " " nil 'display '(space :align-to 0))
15889 (org-add-props title nil 'face '(:weight bold :underline t))))
15890 (org-set-local 'org-previous-header-line-format header-line-format)
15891 (org-set-local 'org-columns-current-widths (nreverse widths))
15892 (setq header-line-format title)))
15894 (defun org-columns-remove-overlays ()
15895 "Remove all currently active column overlays."
15896 (interactive)
15897 (when (marker-buffer org-columns-begin-marker)
15898 (with-current-buffer (marker-buffer org-columns-begin-marker)
15899 (when (local-variable-p 'org-previous-header-line-format)
15900 (setq header-line-format org-previous-header-line-format)
15901 (kill-local-variable 'org-previous-header-line-format))
15902 (move-marker org-columns-begin-marker nil)
15903 (move-marker org-columns-top-level-marker nil)
15904 (org-unmodified
15905 (mapc 'org-delete-overlay org-columns-overlays)
15906 (setq org-columns-overlays nil)
15907 (let ((inhibit-read-only t))
15908 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
15910 (defun org-columns-cleanup-item (item fmt)
15911 "Remove from ITEM what is a column in the format FMT."
15912 (if (not org-complex-heading-regexp)
15913 item
15914 (when (string-match org-complex-heading-regexp item)
15915 (concat
15916 (org-add-props (concat (match-string 1 item) " ") nil
15917 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
15918 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
15919 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
15920 " " (match-string 4 item)
15921 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
15923 (defun org-columns-show-value ()
15924 "Show the full value of the property."
15925 (interactive)
15926 (let ((value (get-char-property (point) 'org-columns-value)))
15927 (message "Value is: %s" (or value ""))))
15929 (defun org-columns-quit ()
15930 "Remove the column overlays and in this way exit column editing."
15931 (interactive)
15932 (org-unmodified
15933 (org-columns-remove-overlays)
15934 (let ((inhibit-read-only t))
15935 (remove-text-properties (point-min) (point-max) '(read-only t))))
15936 (when (eq major-mode 'org-agenda-mode)
15937 (message
15938 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
15940 (defun org-columns-check-computed ()
15941 "Check if this column value is computed.
15942 If yes, throw an error indicating that changing it does not make sense."
15943 (let ((val (get-char-property (point) 'org-columns-value)))
15944 (when (and (stringp val)
15945 (get-char-property 0 'org-computed val))
15946 (error "This value is computed from the entry's children"))))
15948 (defun org-columns-todo (&optional arg)
15949 "Change the TODO state during column view."
15950 (interactive "P")
15951 (org-columns-edit-value "TODO"))
15953 (defun org-columns-set-tags-or-toggle (&optional arg)
15954 "Toggle checkbox at point, or set tags for current headline."
15955 (interactive "P")
15956 (if (string-match "\\`\\[[ xX-]\\]\\'"
15957 (get-char-property (point) 'org-columns-value))
15958 (org-columns-next-allowed-value)
15959 (org-columns-edit-value "TAGS")))
15961 (defun org-columns-edit-value (&optional key)
15962 "Edit the value of the property at point in column view.
15963 Where possible, use the standard interface for changing this line."
15964 (interactive)
15965 (org-columns-check-computed)
15966 (let* ((external-key key)
15967 (col (current-column))
15968 (key (or key (get-char-property (point) 'org-columns-key)))
15969 (value (get-char-property (point) 'org-columns-value))
15970 (bol (point-at-bol)) (eol (point-at-eol))
15971 (pom (or (get-text-property bol 'org-hd-marker)
15972 (point))) ; keep despite of compiler waring
15973 (line-overlays
15974 (delq nil (mapcar (lambda (x)
15975 (and (eq (overlay-buffer x) (current-buffer))
15976 (>= (overlay-start x) bol)
15977 (<= (overlay-start x) eol)
15979 org-columns-overlays)))
15980 nval eval allowed)
15981 (cond
15982 ((equal key "ITEM")
15983 (setq eval '(org-with-point-at pom
15984 (org-edit-headline))))
15985 ((equal key "TODO")
15986 (setq eval '(org-with-point-at pom
15987 (let ((current-prefix-arg
15988 (if external-key current-prefix-arg '(4))))
15989 (call-interactively 'org-todo)))))
15990 ((equal key "PRIORITY")
15991 (setq eval '(org-with-point-at pom
15992 (call-interactively 'org-priority))))
15993 ((equal key "TAGS")
15994 (setq eval '(org-with-point-at pom
15995 (let ((org-fast-tag-selection-single-key
15996 (if (eq org-fast-tag-selection-single-key 'expert)
15997 t org-fast-tag-selection-single-key)))
15998 (call-interactively 'org-set-tags)))))
15999 ((equal key "DEADLINE")
16000 (setq eval '(org-with-point-at pom
16001 (call-interactively 'org-deadline))))
16002 ((equal key "SCHEDULED")
16003 (setq eval '(org-with-point-at pom
16004 (call-interactively 'org-schedule))))
16006 (setq allowed (org-property-get-allowed-values pom key 'table))
16007 (if allowed
16008 (setq nval (completing-read "Value: " allowed nil t))
16009 (setq nval (read-string "Edit: " value)))
16010 (setq nval (org-trim nval))
16011 (when (not (equal nval value))
16012 (setq eval '(org-entry-put pom key nval)))))
16013 (when eval
16014 (let ((inhibit-read-only t))
16015 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16016 (unwind-protect
16017 (progn
16018 (setq org-columns-overlays
16019 (org-delete-all line-overlays org-columns-overlays))
16020 (mapc 'org-delete-overlay line-overlays)
16021 (org-columns-eval eval))
16022 (org-columns-display-here))))
16023 (move-to-column col)
16024 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
16025 (org-columns-update key))))
16027 (defun org-edit-headline () ; FIXME: this is not columns specific
16028 "Edit the current headline, the part without TODO keyword, TAGS."
16029 (org-back-to-heading)
16030 (when (looking-at org-todo-line-regexp)
16031 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16032 (txt (match-string 3))
16033 (post "")
16034 txt2)
16035 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16036 (setq post (match-string 0 txt)
16037 txt (substring txt 0 (match-beginning 0))))
16038 (setq txt2 (read-string "Edit: " txt))
16039 (when (not (equal txt txt2))
16040 (beginning-of-line 1)
16041 (insert pre txt2 post)
16042 (delete-region (point) (point-at-eol))
16043 (org-set-tags nil t)))))
16045 (defun org-columns-edit-allowed ()
16046 "Edit the list of allowed values for the current property."
16047 (interactive)
16048 (let* ((key (get-char-property (point) 'org-columns-key))
16049 (key1 (concat key "_ALL"))
16050 (allowed (org-entry-get (point) key1 t))
16051 nval)
16052 ;; FIXME: Cover editing TODO, TAGS etc inbiffer settings.????
16053 (setq nval (read-string "Allowed: " allowed))
16054 (org-entry-put
16055 (cond ((marker-position org-entry-property-inherited-from)
16056 org-entry-property-inherited-from)
16057 ((marker-position org-columns-top-level-marker)
16058 org-columns-top-level-marker))
16059 key1 nval)))
16061 (defmacro org-no-warnings (&rest body)
16062 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16064 (defun org-columns-eval (form)
16065 (let (hidep)
16066 (save-excursion
16067 (beginning-of-line 1)
16068 ;; `next-line' is needed here, because it skips invisible line.
16069 ;; FIXME: RMS says this should be wrapped into `with-no-warnings'
16070 ;; but I don't know how to do this and keep the code XEmacs compatible.
16071 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16072 (setq hidep (org-on-heading-p 1)))
16073 (eval form)
16074 (and hidep (hide-entry))))
16076 (defun org-columns-previous-allowed-value ()
16077 "Switch to the previous allowed value for this column."
16078 (interactive)
16079 (org-columns-next-allowed-value t))
16081 (defun org-columns-next-allowed-value (&optional previous)
16082 "Switch to the next allowed value for this column."
16083 (interactive)
16084 (org-columns-check-computed)
16085 (let* ((col (current-column))
16086 (key (get-char-property (point) 'org-columns-key))
16087 (value (get-char-property (point) 'org-columns-value))
16088 (bol (point-at-bol)) (eol (point-at-eol))
16089 (pom (or (get-text-property bol 'org-hd-marker)
16090 (point))) ; keep despite of compiler waring
16091 (line-overlays
16092 (delq nil (mapcar (lambda (x)
16093 (and (eq (overlay-buffer x) (current-buffer))
16094 (>= (overlay-start x) bol)
16095 (<= (overlay-start x) eol)
16097 org-columns-overlays)))
16098 (allowed (or (org-property-get-allowed-values pom key)
16099 (and (equal
16100 (nth 4 (assoc key org-columns-current-fmt-compiled))
16101 'checkbox) '("[ ]" "[X]"))))
16102 nval)
16103 (when (equal key "ITEM")
16104 (error "Cannot edit item headline from here"))
16105 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16106 (error "Allowed values for this property have not been defined"))
16107 (if (member key '("SCHEDULED" "DEADLINE"))
16108 (setq nval (if previous 'earlier 'later))
16109 (if previous (setq allowed (reverse allowed)))
16110 (if (member value allowed)
16111 (setq nval (car (cdr (member value allowed)))))
16112 (setq nval (or nval (car allowed)))
16113 (if (equal nval value)
16114 (error "Only one allowed value for this property")))
16115 (let ((inhibit-read-only t))
16116 (remove-text-properties (1- bol) eol '(read-only t))
16117 (unwind-protect
16118 (progn
16119 (setq org-columns-overlays
16120 (org-delete-all line-overlays org-columns-overlays))
16121 (mapc 'org-delete-overlay line-overlays)
16122 (org-columns-eval '(org-entry-put pom key nval)))
16123 (org-columns-display-here)))
16124 (move-to-column col)
16125 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
16126 (org-columns-update key))))
16128 (defun org-verify-version (task)
16129 (cond
16130 ((eq task 'columns)
16131 (if (or (featurep 'xemacs)
16132 (< emacs-major-version 22))
16133 (error "Emacs 22 is required for the columns feature")))))
16135 (defun org-columns-open-link (&optional arg)
16136 (interactive "P")
16137 (let ((key (get-char-property (point) 'org-columns-key))
16138 (value (get-char-property (point) 'org-columns-value)))
16139 (org-open-link-from-string arg)))
16141 (defun org-open-link-from-string (s &optional arg)
16142 "Open a link in the string S, as if it was in Org-mode."
16143 (interactive)
16144 (with-temp-buffer
16145 (let ((org-inhibit-startup t))
16146 (org-mode)
16147 (insert s)
16148 (goto-char (point-min))
16149 (org-open-at-point arg))))
16151 (defun org-columns-get-format-and-top-level ()
16152 (let (fmt)
16153 (when (condition-case nil (org-back-to-heading) (error nil))
16154 (move-marker org-entry-property-inherited-from nil)
16155 (setq fmt (org-entry-get nil "COLUMNS" t)))
16156 (setq fmt (or fmt org-columns-default-format))
16157 (org-set-local 'org-columns-current-fmt fmt)
16158 (org-columns-compile-format fmt)
16159 (if (marker-position org-entry-property-inherited-from)
16160 (move-marker org-columns-top-level-marker
16161 org-entry-property-inherited-from)
16162 (move-marker org-columns-top-level-marker (point)))
16163 fmt))
16165 (defun org-columns ()
16166 "Turn on column view on an org-mode file."
16167 (interactive)
16168 (org-verify-version 'columns)
16169 (org-columns-remove-overlays)
16170 (move-marker org-columns-begin-marker (point))
16171 (let (beg end fmt cache maxwidths)
16172 (setq fmt (org-columns-get-format-and-top-level))
16173 (save-excursion
16174 (goto-char org-columns-top-level-marker)
16175 (setq beg (point))
16176 (unless org-columns-inhibit-recalculation
16177 (org-columns-compute-all))
16178 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16179 (point-max)))
16180 (goto-char beg)
16181 ;; Get and cache the properties
16182 (while (re-search-forward (concat "^" outline-regexp) end t)
16183 (push (cons (org-current-line) (org-entry-properties)) cache))
16184 (when cache
16185 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16186 (org-set-local 'org-columns-current-maxwidths maxwidths)
16187 (org-columns-display-here-title)
16188 (mapc (lambda (x)
16189 (goto-line (car x))
16190 (org-columns-display-here (cdr x)))
16191 cache)))))
16193 (defun org-columns-new (&optional prop title width op fmt)
16194 "Insert a new column, to the leeft o the current column."
16195 (interactive)
16196 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16197 cell)
16198 (setq prop (completing-read
16199 "Property: " (mapcar 'list (org-buffer-property-keys t))
16200 nil nil prop))
16201 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16202 (setq width (read-string "Column width: " (if width (number-to-string width))))
16203 (if (string-match "\\S-" width)
16204 (setq width (string-to-number width))
16205 (setq width nil))
16206 (setq fmt (completing-read "Summary [none]: "
16207 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16208 nil t))
16209 (if (string-match "\\S-" fmt)
16210 (setq fmt (intern fmt))
16211 (setq fmt nil))
16212 (if (eq fmt 'none) (setq fmt nil))
16213 (if editp
16214 (progn
16215 (setcar editp prop)
16216 (setcdr editp (list title width nil fmt)))
16217 (setq cell (nthcdr (1- (current-column))
16218 org-columns-current-fmt-compiled))
16219 (setcdr cell (cons (list prop title width nil fmt)
16220 (cdr cell))))
16221 (org-columns-store-format)
16222 (org-columns-redo)))
16224 (defun org-columns-delete ()
16225 "Delete the column at point from columns view."
16226 (interactive)
16227 (let* ((n (current-column))
16228 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16229 (when (y-or-n-p
16230 (format "Are you sure you want to remove column \"%s\"? " title))
16231 (setq org-columns-current-fmt-compiled
16232 (delq (nth n org-columns-current-fmt-compiled)
16233 org-columns-current-fmt-compiled))
16234 (org-columns-store-format)
16235 (org-columns-redo)
16236 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16237 (backward-char 1)))))
16239 (defun org-columns-edit-attributes ()
16240 "Edit the attributes of the current column."
16241 (interactive)
16242 (let* ((n (current-column))
16243 (info (nth n org-columns-current-fmt-compiled)))
16244 (apply 'org-columns-new info)))
16246 (defun org-columns-widen (arg)
16247 "Make the column wider by ARG characters."
16248 (interactive "p")
16249 (let* ((n (current-column))
16250 (entry (nth n org-columns-current-fmt-compiled))
16251 (width (or (nth 2 entry)
16252 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16253 (setq width (max 1 (+ width arg)))
16254 (setcar (nthcdr 2 entry) width)
16255 (org-columns-store-format)
16256 (org-columns-redo)))
16258 (defun org-columns-narrow (arg)
16259 "Make the column nrrower by ARG characters."
16260 (interactive "p")
16261 (org-columns-widen (- arg)))
16263 (defun org-columns-move-right ()
16264 "Swap this column with the one to the right."
16265 (interactive)
16266 (let* ((n (current-column))
16267 (cell (nthcdr n org-columns-current-fmt-compiled))
16269 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16270 (error "Cannot shift this column further to the right"))
16271 (setq e (car cell))
16272 (setcar cell (car (cdr cell)))
16273 (setcdr cell (cons e (cdr (cdr cell))))
16274 (org-columns-store-format)
16275 (org-columns-redo)
16276 (forward-char 1)))
16278 (defun org-columns-move-left ()
16279 "Swap this column with the one to the left."
16280 (interactive)
16281 (let* ((n (current-column)))
16282 (when (= n 0)
16283 (error "Cannot shift this column further to the left"))
16284 (backward-char 1)
16285 (org-columns-move-right)
16286 (backward-char 1)))
16288 (defun org-columns-store-format ()
16289 "Store the text version of the current columns format in appropriate place.
16290 This is either in the COLUMNS property of the node starting the current column
16291 display, or in the #+COLUMNS line of the current buffer."
16292 (let (fmt (cnt 0))
16293 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16294 (org-set-local 'org-columns-current-fmt fmt)
16295 (if (marker-position org-columns-top-level-marker)
16296 (save-excursion
16297 (goto-char org-columns-top-level-marker)
16298 (if (and (org-at-heading-p)
16299 (org-entry-get nil "COLUMNS"))
16300 (org-entry-put nil "COLUMNS" fmt)
16301 (goto-char (point-min))
16302 ;; Overwrite all #+COLUMNS lines....
16303 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16304 (setq cnt (1+ cnt))
16305 (replace-match (concat "#+COLUMNS: " fmt) t t))
16306 (unless (> cnt 0)
16307 (goto-char (point-min))
16308 (or (org-on-heading-p t) (outline-next-heading))
16309 (let ((inhibit-read-only t))
16310 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16311 (org-set-local 'org-columns-default-format fmt))))))
16313 (defvar org-overriding-columns-format nil
16314 "When set, overrides any other definition.")
16315 (defvar org-agenda-view-columns-initially nil
16316 "When set, switch to columns view immediately after creating the agenda.")
16318 (defun org-agenda-columns ()
16319 "Turn on column view in the agenda."
16320 (interactive)
16321 (org-verify-version 'columns)
16322 (org-columns-remove-overlays)
16323 (move-marker org-columns-begin-marker (point))
16324 (let (fmt cache maxwidths m)
16325 (cond
16326 ((and (local-variable-p 'org-overriding-columns-format)
16327 org-overriding-columns-format)
16328 (setq fmt org-overriding-columns-format))
16329 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16330 (setq fmt (org-entry-get m "COLUMNS" t)))
16331 ((and (boundp 'org-columns-current-fmt)
16332 (local-variable-p 'org-columns-current-fmt)
16333 org-columns-current-fmt)
16334 (setq fmt org-columns-current-fmt))
16335 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16336 (setq m (get-text-property m 'org-hd-marker))
16337 (setq fmt (org-entry-get m "COLUMNS" t))))
16338 (setq fmt (or fmt org-columns-default-format))
16339 (org-set-local 'org-columns-current-fmt fmt)
16340 (org-columns-compile-format fmt)
16341 (save-excursion
16342 ;; Get and cache the properties
16343 (goto-char (point-min))
16344 (while (not (eobp))
16345 (when (setq m (or (get-text-property (point) 'org-hd-marker)
16346 (get-text-property (point) 'org-marker)))
16347 (push (cons (org-current-line) (org-entry-properties m)) cache))
16348 (beginning-of-line 2))
16349 (when cache
16350 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16351 (org-set-local 'org-columns-current-maxwidths maxwidths)
16352 (org-columns-display-here-title)
16353 (mapc (lambda (x)
16354 (goto-line (car x))
16355 (org-columns-display-here (cdr x)))
16356 cache)))))
16358 (defun org-columns-get-autowidth-alist (s cache)
16359 "Derive the maximum column widths from the format and the cache."
16360 (let ((start 0) rtn)
16361 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
16362 (push (cons (match-string 1 s) 1) rtn)
16363 (setq start (match-end 0)))
16364 (mapc (lambda (x)
16365 (setcdr x (apply 'max
16366 (mapcar
16367 (lambda (y)
16368 (length (or (cdr (assoc (car x) (cdr y))) " ")))
16369 cache))))
16370 rtn)
16371 rtn))
16373 (defun org-columns-compute-all ()
16374 "Compute all columns that have operators defined."
16375 (org-unmodified
16376 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
16377 (let ((columns org-columns-current-fmt-compiled) col)
16378 (while (setq col (pop columns))
16379 (when (nth 3 col)
16380 (save-excursion
16381 (org-columns-compute (car col)))))))
16383 (defun org-columns-update (property)
16384 "Recompute PROPERTY, and update the columns display for it."
16385 (org-columns-compute property)
16386 (let (fmt val pos)
16387 (save-excursion
16388 (mapc (lambda (ov)
16389 (when (equal (org-overlay-get ov 'org-columns-key) property)
16390 (setq pos (org-overlay-start ov))
16391 (goto-char pos)
16392 (when (setq val (cdr (assoc property
16393 (get-text-property
16394 (point-at-bol) 'org-summaries))))
16395 (setq fmt (org-overlay-get ov 'org-columns-format))
16396 (org-overlay-put ov 'org-columns-value val)
16397 (org-overlay-put ov 'display (format fmt val)))))
16398 org-columns-overlays))))
16400 (defun org-columns-compute (property)
16401 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
16402 (interactive)
16403 (let* ((re (concat "^" outline-regexp))
16404 (lmax 30) ; Does anyone use deeper levels???
16405 (lsum (make-vector lmax 0))
16406 (lflag (make-vector lmax nil))
16407 (level 0)
16408 (ass (assoc property org-columns-current-fmt-compiled))
16409 (format (nth 4 ass))
16410 (printf (nth 5 ass))
16411 (beg org-columns-top-level-marker)
16412 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
16413 (save-excursion
16414 ;; Find the region to compute
16415 (goto-char beg)
16416 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
16417 (goto-char end)
16418 ;; Walk the tree from the back and do the computations
16419 (while (re-search-backward re beg t)
16420 (setq sumpos (match-beginning 0)
16421 last-level level
16422 level (org-outline-level)
16423 val (org-entry-get nil property)
16424 valflag (and val (string-match "\\S-" val)))
16425 (cond
16426 ((< level last-level)
16427 ;; put the sum of lower levels here as a property
16428 (setq sum (aref lsum last-level) ; current sum
16429 flag (aref lflag last-level) ; any valid entries from children?
16430 str (org-column-number-to-string sum format printf)
16431 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
16432 useval (if flag str1 (if valflag val ""))
16433 sum-alist (get-text-property sumpos 'org-summaries))
16434 (if (assoc property sum-alist)
16435 (setcdr (assoc property sum-alist) useval)
16436 (push (cons property useval) sum-alist)
16437 (org-unmodified
16438 (add-text-properties sumpos (1+ sumpos)
16439 (list 'org-summaries sum-alist))))
16440 (when val
16441 (org-entry-put nil property (if flag str val)))
16442 ;; add current to current level accumulator
16443 (when (or flag valflag)
16444 ;; FIXME: is this ok?????????
16445 (aset lsum level (+ (aref lsum level)
16446 (if flag sum (org-column-string-to-number
16447 (if flag str val) format))))
16448 (aset lflag level t))
16449 ;; clear accumulators for deeper levels
16450 (loop for l from (1+ level) to (1- lmax) do
16451 (aset lsum l 0)
16452 (aset lflag l nil)))
16453 ((>= level last-level)
16454 ;; add what we have here to the accumulator for this level
16455 (aset lsum level (+ (aref lsum level)
16456 (org-column-string-to-number (or val "0") format)))
16457 (and valflag (aset lflag level t)))
16458 (t (error "This should not happen")))))))
16460 (defun org-columns-redo ()
16461 "Construct the column display again."
16462 (interactive)
16463 (message "Recomputing columns...")
16464 (save-excursion
16465 (if (marker-position org-columns-begin-marker)
16466 (goto-char org-columns-begin-marker))
16467 (org-columns-remove-overlays)
16468 (if (org-mode-p)
16469 (call-interactively 'org-columns)
16470 (call-interactively 'org-agenda-columns)))
16471 (message "Recomputing columns...done"))
16473 (defun org-columns-not-in-agenda ()
16474 (if (eq major-mode 'org-agenda-mode)
16475 (error "This command is only allowed in Org-mode buffers")))
16478 (defun org-string-to-number (s)
16479 "Convert string to number, and interpret hh:mm:ss."
16480 (if (not (string-match ":" s))
16481 (string-to-number s)
16482 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16483 (while l
16484 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16485 sum)))
16487 (defun org-column-number-to-string (n fmt printf)
16488 "Convert a computed column number to a string value, according to FMT."
16489 (cond
16490 ((eq fmt 'add_times)
16491 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
16492 (format "%d:%02d" h m)))
16493 ((eq fmt 'checkbox)
16494 (cond ((= n (floor n)) "[X]")
16495 ((> n 1.) "[-]")
16496 (t "[ ]")))
16497 (printf (format printf n))
16498 ((eq fmt 'currency)
16499 (format "%.2f" n))
16500 (t (number-to-string n))))
16502 (defun org-column-string-to-number (s fmt)
16503 "Convert a column value to a number that can be used for column computing."
16504 (cond
16505 ((string-match ":" s)
16506 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16507 (while l
16508 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16509 sum))
16510 ((eq fmt 'checkbox)
16511 (if (equal s "[X]") 1. 0.000001))
16512 (t (string-to-number s))))
16514 (defun org-columns-uncompile-format (cfmt)
16515 "Turn the compiled columns format back into a string representation."
16516 (let ((rtn "") e s prop title op width fmt printf)
16517 (while (setq e (pop cfmt))
16518 (setq prop (car e)
16519 title (nth 1 e)
16520 width (nth 2 e)
16521 op (nth 3 e)
16522 fmt (nth 4 e)
16523 printf (nth 5 e))
16524 (cond
16525 ((eq fmt 'add_times) (setq op ":"))
16526 ((eq fmt 'checkbox) (setq op "X"))
16527 ((eq fmt 'add_numbers) (setq op "+"))
16528 ((eq fmt 'currency) (setq op "$")))
16529 (if (and op printf) (setq op (concat op ";" printf)))
16530 (if (equal title prop) (setq title nil))
16531 (setq s (concat "%" (if width (number-to-string width))
16532 prop
16533 (if title (concat "(" title ")"))
16534 (if op (concat "{" op "}"))))
16535 (setq rtn (concat rtn " " s)))
16536 (org-trim rtn)))
16538 (defun org-columns-compile-format (fmt)
16539 "Turn a column format string into an alist of specifications.
16540 The alist has one entry for each column in the format. The elements of
16541 that list are:
16542 property the property
16543 title the title field for the columns
16544 width the column width in characters, can be nil for automatic
16545 operator the operator if any
16546 format the output format for computed results, derived from operator
16547 printf a printf format for computed values"
16548 (let ((start 0) width prop title op f printf)
16549 (setq org-columns-current-fmt-compiled nil)
16550 (while (string-match
16551 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
16552 fmt start)
16553 (setq start (match-end 0)
16554 width (match-string 1 fmt)
16555 prop (match-string 2 fmt)
16556 title (or (match-string 3 fmt) prop)
16557 op (match-string 4 fmt)
16558 f nil
16559 printf nil)
16560 (if width (setq width (string-to-number width)))
16561 (when (and op (string-match ";" op))
16562 (setq printf (substring op (match-end 0))
16563 op (substring op 0 (match-beginning 0))))
16564 (cond
16565 ((equal op "+") (setq f 'add_numbers))
16566 ((equal op "$") (setq f 'currency))
16567 ((equal op ":") (setq f 'add_times))
16568 ((equal op "X") (setq f 'checkbox)))
16569 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
16570 (setq org-columns-current-fmt-compiled
16571 (nreverse org-columns-current-fmt-compiled))))
16574 ;;; Dynamic block for Column view
16576 (defun org-columns-capture-view ()
16577 "Get the column view of the current buffer and return it as a list.
16578 The list will contains the title row and all other rows. Each row is
16579 a list of fields."
16580 (save-excursion
16581 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
16582 (n (length title)) row tbl)
16583 (goto-char (point-min))
16584 (while (re-search-forward "^\\*+ " nil t)
16585 (when (get-char-property (match-beginning 0) 'org-columns-key)
16586 (setq row nil)
16587 (loop for i from 0 to (1- n) do
16588 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
16589 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
16591 row))
16592 (setq row (nreverse row))
16593 (push row tbl)))
16594 (append (list title 'hline) (nreverse tbl)))))
16596 (defun org-dblock-write:columnview (params)
16597 "Write the column view table.
16598 PARAMS is a property list of parameters:
16600 :width enforce same column widths with <N> specifiers.
16601 :id the :ID: property of the entry where the columns view
16602 should be built, as a string. When `local', call locally.
16603 When `global' call column view with the cursor at the beginning
16604 of the buffer (usually this means that the whole buffer switches
16605 to column view).
16606 :hlines When t, insert a hline before each item. When a number, insert
16607 a hline before each level <= that number.
16608 :vlines When t, make each column a colgroup to enforce vertical lines."
16609 (let ((pos (move-marker (make-marker) (point)))
16610 (hlines (plist-get params :hlines))
16611 (vlines (plist-get params :vlines))
16612 tbl id idpos nfields tmp)
16613 (save-excursion
16614 (save-restriction
16615 (when (setq id (plist-get params :id))
16616 (cond ((not id) nil)
16617 ((eq id 'global) (goto-char (point-min)))
16618 ((eq id 'local) nil)
16619 ((setq idpos (org-find-entry-with-id id))
16620 (goto-char idpos))
16621 (t (error "Cannot find entry with :ID: %s" id))))
16622 (org-columns)
16623 (setq tbl (org-columns-capture-view))
16624 (setq nfields (length (car tbl)))
16625 (org-columns-quit)))
16626 (goto-char pos)
16627 (move-marker pos nil)
16628 (when tbl
16629 (when (plist-get params :hlines)
16630 (setq tmp nil)
16631 (while tbl
16632 (if (eq (car tbl) 'hline)
16633 (push (pop tbl) tmp)
16634 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
16635 (if (and (not (eq (car tmp) 'hline))
16636 (or (eq hlines t)
16637 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
16638 (push 'hline tmp)))
16639 (push (pop tbl) tmp)))
16640 (setq tbl (nreverse tmp)))
16641 (when vlines
16642 (setq tbl (mapcar (lambda (x)
16643 (if (eq 'hline x) x (cons "" x)))
16644 tbl))
16645 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
16646 (setq pos (point))
16647 (insert (org-listtable-to-string tbl))
16648 (when (plist-get params :width)
16649 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
16650 org-columns-current-widths "|")))
16651 (goto-char pos)
16652 (org-table-align))))
16654 (defun org-listtable-to-string (tbl)
16655 "Convert a listtable TBL to a string that contains the Org-mode table.
16656 The table still need to be alligned. The resulting string has no leading
16657 and tailing newline characters."
16658 (mapconcat
16659 (lambda (x)
16660 (cond
16661 ((listp x)
16662 (concat "|" (mapconcat 'identity x "|") "|"))
16663 ((eq x 'hline) "|-|")
16664 (t (error "Garbage in listtable: %s" x))))
16665 tbl "\n"))
16667 (defun org-insert-columns-dblock ()
16668 "Create a dynamic block capturing a column view table."
16669 (interactive)
16670 (let ((defaults '(:name "columnview" :hlines 1))
16671 (id (completing-read
16672 "Capture columns (local, global, entry with :ID: property) [local]: "
16673 (append '(("global") ("local"))
16674 (mapcar 'list (org-property-values "ID"))))))
16675 (if (equal id "") (setq id 'local))
16676 (if (equal id "global") (setq id 'global))
16677 (setq defaults (append defaults (list :id id)))
16678 (org-create-dblock defaults)
16679 (org-update-dblock)))
16681 ;;;; Timestamps
16683 (defvar org-last-changed-timestamp nil)
16684 (defvar org-time-was-given) ; dynamically scoped parameter
16685 (defvar org-end-time-was-given) ; dynamically scoped parameter
16686 (defvar org-ts-what) ; dynamically scoped parameter
16688 (defun org-time-stamp (arg)
16689 "Prompt for a date/time and insert a time stamp.
16690 If the user specifies a time like HH:MM, or if this command is called
16691 with a prefix argument, the time stamp will contain date and time.
16692 Otherwise, only the date will be included. All parts of a date not
16693 specified by the user will be filled in from the current date/time.
16694 So if you press just return without typing anything, the time stamp
16695 will represent the current date/time. If there is already a timestamp
16696 at the cursor, it will be modified."
16697 (interactive "P")
16698 (let* ((ts nil)
16699 (default-time
16700 ;; Default time is either today, or, when entering a range,
16701 ;; the range start.
16702 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16703 (save-excursion
16704 (re-search-backward
16705 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16706 (- (point) 20) t)))
16707 (apply 'encode-time (org-parse-time-string (match-string 1)))
16708 (current-time)))
16709 (default-input (and ts (org-get-compact-tod ts)))
16710 org-time-was-given org-end-time-was-given time)
16711 (cond
16712 ((and (org-at-timestamp-p)
16713 (eq last-command 'org-time-stamp)
16714 (eq this-command 'org-time-stamp))
16715 (insert "--")
16716 (setq time (let ((this-command this-command))
16717 (org-read-date arg 'totime nil nil default-time default-input)))
16718 (org-insert-time-stamp time (or org-time-was-given arg)))
16719 ((org-at-timestamp-p)
16720 (setq time (let ((this-command this-command))
16721 (org-read-date arg 'totime nil nil default-time default-input)))
16722 (when (org-at-timestamp-p) ; just to get the match data
16723 (replace-match "")
16724 (setq org-last-changed-timestamp
16725 (org-insert-time-stamp
16726 time (or org-time-was-given arg)
16727 nil nil nil (list org-end-time-was-given))))
16728 (message "Timestamp updated"))
16730 (setq time (let ((this-command this-command))
16731 (org-read-date arg 'totime nil nil default-time default-input)))
16732 (org-insert-time-stamp time (or org-time-was-given arg)
16733 nil nil nil (list org-end-time-was-given))))))
16735 ;; FIXME: can we use this for something else????
16736 ;; like computing time differences?????
16737 (defun org-get-compact-tod (s)
16738 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16739 (let* ((t1 (match-string 1 s))
16740 (h1 (string-to-number (match-string 2 s)))
16741 (m1 (string-to-number (match-string 3 s)))
16742 (t2 (and (match-end 4) (match-string 5 s)))
16743 (h2 (and t2 (string-to-number (match-string 6 s))))
16744 (m2 (and t2 (string-to-number (match-string 7 s))))
16745 dh dm)
16746 (if (not t2)
16748 (setq dh (- h2 h1) dm (- m2 m1))
16749 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16750 (concat t1 "+" (number-to-string dh)
16751 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16753 (defun org-time-stamp-inactive (&optional arg)
16754 "Insert an inactive time stamp.
16755 An inactive time stamp is enclosed in square brackets instead of angle
16756 brackets. It is inactive in the sense that it does not trigger agenda entries,
16757 does not link to the calendar and cannot be changed with the S-cursor keys.
16758 So these are more for recording a certain time/date."
16759 (interactive "P")
16760 (let (org-time-was-given org-end-time-was-given time)
16761 (setq time (org-read-date arg 'totime))
16762 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
16763 nil nil (list org-end-time-was-given))))
16765 (defvar org-date-ovl (org-make-overlay 1 1))
16766 (org-overlay-put org-date-ovl 'face 'org-warning)
16767 (org-detach-overlay org-date-ovl)
16769 (defvar org-ans1) ; dynamically scoped parameter
16770 (defvar org-ans2) ; dynamically scoped parameter
16772 (defvar org-plain-time-of-day-regexp) ; defined below
16774 (defvar org-read-date-overlay nil)
16775 (defvar org-dcst nil) ; dynamically scoped
16777 (defun org-read-date (&optional with-time to-time from-string prompt
16778 default-time default-input)
16779 "Read a date, possibly a time, and make things smooth for the user.
16780 The prompt will suggest to enter an ISO date, but you can also enter anything
16781 which will at least partially be understood by `parse-time-string'.
16782 Unrecognized parts of the date will default to the current day, month, year,
16783 hour and minute. If this command is called to replace a timestamp at point,
16784 of to enter the second timestamp of a range, the default time is taken from the
16785 existing stamp. For example,
16786 3-2-5 --> 2003-02-05
16787 feb 15 --> currentyear-02-15
16788 sep 12 9 --> 2009-09-12
16789 12:45 --> today 12:45
16790 22 sept 0:34 --> currentyear-09-22 0:34
16791 12 --> currentyear-currentmonth-12
16792 Fri --> nearest Friday (today or later)
16793 etc.
16795 Furthermore you can specify a relative date by giving, as the *first* thing
16796 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
16797 change in days weeks, months, years.
16798 With a single plus or minus, the date is relative to today. With a double
16799 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16800 +4d --> four days from today
16801 +4 --> same as above
16802 +2w --> two weeks from today
16803 ++5 --> five days from default date
16805 The function understands only English month and weekday abbreviations,
16806 but this can be configured with the variables `parse-time-months' and
16807 `parse-time-weekdays'.
16809 While prompting, a calendar is popped up - you can also select the
16810 date with the mouse (button 1). The calendar shows a period of three
16811 months. To scroll it to other months, use the keys `>' and `<'.
16812 If you don't like the calendar, turn it off with
16813 \(setq org-read-date-popup-calendar nil)
16815 With optional argument TO-TIME, the date will immediately be converted
16816 to an internal time.
16817 With an optional argument WITH-TIME, the prompt will suggest to also
16818 insert a time. Note that when WITH-TIME is not set, you can still
16819 enter a time, and this function will inform the calling routine about
16820 this change. The calling routine may then choose to change the format
16821 used to insert the time stamp into the buffer to include the time.
16822 With optional argument FROM-STRING, read from this string instead from
16823 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16824 the time/date that is used for everything that is not specified by the
16825 user."
16826 (require 'parse-time)
16827 (let* ((org-time-stamp-rounding-minutes
16828 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
16829 (org-dcst org-display-custom-times)
16830 (ct (org-current-time))
16831 (def (or default-time ct))
16832 (defdecode (decode-time def))
16833 (dummy (progn
16834 (when (< (nth 2 defdecode) org-extend-today-until)
16835 (setcar (nthcdr 2 defdecode) -1)
16836 (setcar (nthcdr 1 defdecode) 59)
16837 (setq def (apply 'encode-time defdecode)
16838 defdecode (decode-time def)))))
16839 (calendar-move-hook nil)
16840 (view-diary-entries-initially nil)
16841 (view-calendar-holidays-initially nil)
16842 (timestr (format-time-string
16843 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
16844 (prompt (concat (if prompt (concat prompt " ") "")
16845 (format "Date+time [%s]: " timestr)))
16846 ans (org-ans0 "") org-ans1 org-ans2 final)
16848 (cond
16849 (from-string (setq ans from-string))
16850 (org-read-date-popup-calendar
16851 (save-excursion
16852 (save-window-excursion
16853 (calendar)
16854 (calendar-forward-day (- (time-to-days def)
16855 (calendar-absolute-from-gregorian
16856 (calendar-current-date))))
16857 (org-eval-in-calendar nil t)
16858 (let* ((old-map (current-local-map))
16859 (map (copy-keymap calendar-mode-map))
16860 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
16861 (org-defkey map (kbd "RET") 'org-calendar-select)
16862 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
16863 'org-calendar-select-mouse)
16864 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
16865 'org-calendar-select-mouse)
16866 (org-defkey minibuffer-local-map [(meta shift left)]
16867 (lambda () (interactive)
16868 (org-eval-in-calendar '(calendar-backward-month 1))))
16869 (org-defkey minibuffer-local-map [(meta shift right)]
16870 (lambda () (interactive)
16871 (org-eval-in-calendar '(calendar-forward-month 1))))
16872 (org-defkey minibuffer-local-map [(meta shift up)]
16873 (lambda () (interactive)
16874 (org-eval-in-calendar '(calendar-backward-year 1))))
16875 (org-defkey minibuffer-local-map [(meta shift down)]
16876 (lambda () (interactive)
16877 (org-eval-in-calendar '(calendar-forward-year 1))))
16878 (org-defkey minibuffer-local-map [(shift up)]
16879 (lambda () (interactive)
16880 (org-eval-in-calendar '(calendar-backward-week 1))))
16881 (org-defkey minibuffer-local-map [(shift down)]
16882 (lambda () (interactive)
16883 (org-eval-in-calendar '(calendar-forward-week 1))))
16884 (org-defkey minibuffer-local-map [(shift left)]
16885 (lambda () (interactive)
16886 (org-eval-in-calendar '(calendar-backward-day 1))))
16887 (org-defkey minibuffer-local-map [(shift right)]
16888 (lambda () (interactive)
16889 (org-eval-in-calendar '(calendar-forward-day 1))))
16890 (org-defkey minibuffer-local-map ">"
16891 (lambda () (interactive)
16892 (org-eval-in-calendar '(scroll-calendar-left 1))))
16893 (org-defkey minibuffer-local-map "<"
16894 (lambda () (interactive)
16895 (org-eval-in-calendar '(scroll-calendar-right 1))))
16896 (unwind-protect
16897 (progn
16898 (use-local-map map)
16899 (add-hook 'post-command-hook 'org-read-date-display)
16900 (setq org-ans0 (read-string prompt default-input nil nil))
16901 ;; org-ans0: from prompt
16902 ;; org-ans1: from mouse click
16903 ;; org-ans2: from calendar motion
16904 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16905 (remove-hook 'post-command-hook 'org-read-date-display)
16906 (use-local-map old-map)
16907 (when org-read-date-overlay
16908 (org-delete-overlay org-read-date-overlay)
16909 (setq org-read-date-overlay nil)))))))
16911 (t ; Naked prompt only
16912 (unwind-protect
16913 (setq ans (read-string prompt default-input nil timestr))
16914 (when org-read-date-overlay
16915 (org-delete-overlay org-read-date-overlay)
16916 (setq org-read-date-overlay nil)))))
16918 (setq final (org-read-date-analyze ans def defdecode))
16920 (if to-time
16921 (apply 'encode-time final)
16922 (if (and (boundp 'org-time-was-given) org-time-was-given)
16923 (format "%04d-%02d-%02d %02d:%02d"
16924 (nth 5 final) (nth 4 final) (nth 3 final)
16925 (nth 2 final) (nth 1 final))
16926 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16927 (defvar def)
16928 (defvar defdecode)
16929 (defvar with-time)
16930 (defun org-read-date-display ()
16931 "Display the currrent date prompt interpretation in the minibuffer."
16932 (when org-read-date-display-live
16933 (when org-read-date-overlay
16934 (org-delete-overlay org-read-date-overlay))
16935 (let ((p (point)))
16936 (end-of-line 1)
16937 (while (not (equal (buffer-substring
16938 (max (point-min) (- (point) 4)) (point))
16939 " "))
16940 (insert " "))
16941 (goto-char p))
16942 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16943 " " (or org-ans1 org-ans2)))
16944 (org-end-time-was-given nil)
16945 (f (org-read-date-analyze ans def defdecode))
16946 (fmts (if org-dcst
16947 org-time-stamp-custom-formats
16948 org-time-stamp-formats))
16949 (fmt (if (or with-time
16950 (and (boundp 'org-time-was-given) org-time-was-given))
16951 (cdr fmts)
16952 (car fmts)))
16953 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
16954 (when (and org-end-time-was-given
16955 (string-match org-plain-time-of-day-regexp txt))
16956 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16957 org-end-time-was-given
16958 (substring txt (match-end 0)))))
16959 (setq org-read-date-overlay
16960 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16961 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
16963 (defun org-read-date-analyze (ans def defdecode)
16964 "Analyze the combined answer of the date prompt."
16965 ;; FIXME: cleanup and comment
16966 (let (delta deltan deltaw deltadef year month day
16967 hour minute second wday pm h2 m2 tl wday1)
16969 (when (setq delta (org-read-date-get-relative ans (current-time) def))
16970 (setq ans (replace-match "" t t ans)
16971 deltan (car delta)
16972 deltaw (nth 1 delta)
16973 deltadef (nth 2 delta)))
16975 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
16976 (when (string-match
16977 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16978 (setq year (if (match-end 2)
16979 (string-to-number (match-string 2 ans))
16980 (string-to-number (format-time-string "%Y")))
16981 month (string-to-number (match-string 3 ans))
16982 day (string-to-number (match-string 4 ans)))
16983 (if (< year 100) (setq year (+ 2000 year)))
16984 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16985 t nil ans)))
16986 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16987 ;; If there is a time with am/pm, and *no* time without it, we convert
16988 ;; so that matching will be successful.
16989 (loop for i from 1 to 2 do ; twice, for end time as well
16990 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16991 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16992 (setq hour (string-to-number (match-string 1 ans))
16993 minute (if (match-end 3)
16994 (string-to-number (match-string 3 ans))
16996 pm (equal ?p
16997 (string-to-char (downcase (match-string 4 ans)))))
16998 (if (and (= hour 12) (not pm))
16999 (setq hour 0)
17000 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17001 (setq ans (replace-match (format "%02d:%02d" hour minute)
17002 t t ans))))
17004 ;; Check if a time range is given as a duration
17005 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17006 (setq hour (string-to-number (match-string 1 ans))
17007 h2 (+ hour (string-to-number (match-string 3 ans)))
17008 minute (string-to-number (match-string 2 ans))
17009 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17010 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17011 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17013 ;; Check if there is a time range
17014 (when (boundp 'org-end-time-was-given)
17015 (setq org-time-was-given nil)
17016 (when (and (string-match org-plain-time-of-day-regexp ans)
17017 (match-end 8))
17018 (setq org-end-time-was-given (match-string 8 ans))
17019 (setq ans (concat (substring ans 0 (match-beginning 7))
17020 (substring ans (match-end 7))))))
17022 (setq tl (parse-time-string ans)
17023 day (or (nth 3 tl) (nth 3 defdecode))
17024 month (or (nth 4 tl)
17025 (if (and org-read-date-prefer-future
17026 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17027 (1+ (nth 4 defdecode))
17028 (nth 4 defdecode)))
17029 year (or (nth 5 tl)
17030 (if (and org-read-date-prefer-future
17031 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17032 (1+ (nth 5 defdecode))
17033 (nth 5 defdecode)))
17034 hour (or (nth 2 tl) (nth 2 defdecode))
17035 minute (or (nth 1 tl) (nth 1 defdecode))
17036 second (or (nth 0 tl) 0)
17037 wday (nth 6 tl))
17038 (when deltan
17039 (unless deltadef
17040 (let ((now (decode-time (current-time))))
17041 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17042 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17043 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17044 ((equal deltaw "m") (setq month (+ month deltan)))
17045 ((equal deltaw "y") (setq year (+ year deltan)))))
17046 (when (and wday (not (nth 3 tl)))
17047 ;; Weekday was given, but no day, so pick that day in the week
17048 ;; on or after the derived date.
17049 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17050 (unless (equal wday wday1)
17051 (setq day (+ day (% (- wday wday1 -7) 7)))))
17052 (if (and (boundp 'org-time-was-given)
17053 (nth 2 tl))
17054 (setq org-time-was-given t))
17055 (if (< year 100) (setq year (+ 2000 year)))
17056 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17057 (list second minute hour day month year)))
17059 (defvar parse-time-weekdays)
17061 (defun org-read-date-get-relative (s today default)
17062 "Check string S for special relative date string.
17063 TODAY and DEFAULT are internal times, for today and for a default.
17064 Return shift list (N what def-flag)
17065 WHAT is \"d\", \"w\", \"m\", or \"y\" for day. week, month, year.
17066 N is the number if WHATs to shift
17067 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17068 the DEFAULT date rather than TODAY."
17069 (when (string-match
17070 (concat
17071 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17072 "\\([0-9]+\\)?"
17073 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17074 "\\([ \t]\\|$\\)") s)
17075 (let* ((dir (if (match-end 1)
17076 (string-to-char (substring (match-string 1 s) -1))
17077 ?+))
17078 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17079 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17080 (what (if (match-end 3) (match-string 3 s) "d"))
17081 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17082 (date (if rel default today))
17083 (wday (nth 6 (decode-time date)))
17084 delta)
17085 (if wday1
17086 (progn
17087 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17088 (if (= dir ?-) (setq delta (- delta 7)))
17089 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17090 (list delta "d" rel))
17091 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17093 (defun org-eval-in-calendar (form &optional keepdate)
17094 "Eval FORM in the calendar window and return to current window.
17095 Also, store the cursor date in variable org-ans2."
17096 (let ((sw (selected-window)))
17097 (select-window (get-buffer-window "*Calendar*"))
17098 (eval form)
17099 (when (and (not keepdate) (calendar-cursor-to-date))
17100 (let* ((date (calendar-cursor-to-date))
17101 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17102 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17103 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17104 (select-window sw)))
17106 ; ;; Update the prompt to show new default date
17107 ; (save-excursion
17108 ; (goto-char (point-min))
17109 ; (when (and org-ans2
17110 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17111 ; (get-text-property (match-end 0) 'field))
17112 ; (let ((inhibit-read-only t))
17113 ; (replace-match (concat "[" org-ans2 "]") t t)
17114 ; (add-text-properties (point-min) (1+ (match-end 0))
17115 ; (text-properties-at (1+ (point-min)))))))))
17117 (defun org-calendar-select ()
17118 "Return to `org-read-date' with the date currently selected.
17119 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17120 (interactive)
17121 (when (calendar-cursor-to-date)
17122 (let* ((date (calendar-cursor-to-date))
17123 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17124 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17125 (if (active-minibuffer-window) (exit-minibuffer))))
17127 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17128 "Insert a date stamp for the date given by the internal TIME.
17129 WITH-HM means, use the stamp format that includes the time of the day.
17130 INACTIVE means use square brackets instead of angular ones, so that the
17131 stamp will not contribute to the agenda.
17132 PRE and POST are optional strings to be inserted before and after the
17133 stamp.
17134 The command returns the inserted time stamp."
17135 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17136 stamp)
17137 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17138 (insert-before-markers (or pre ""))
17139 (insert-before-markers (setq stamp (format-time-string fmt time)))
17140 (when (listp extra)
17141 (setq extra (car extra))
17142 (if (and (stringp extra)
17143 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17144 (setq extra (format "-%02d:%02d"
17145 (string-to-number (match-string 1 extra))
17146 (string-to-number (match-string 2 extra))))
17147 (setq extra nil)))
17148 (when extra
17149 (backward-char 1)
17150 (insert-before-markers extra)
17151 (forward-char 1))
17152 (insert-before-markers (or post ""))
17153 stamp))
17155 (defun org-toggle-time-stamp-overlays ()
17156 "Toggle the use of custom time stamp formats."
17157 (interactive)
17158 (setq org-display-custom-times (not org-display-custom-times))
17159 (unless org-display-custom-times
17160 (let ((p (point-min)) (bmp (buffer-modified-p)))
17161 (while (setq p (next-single-property-change p 'display))
17162 (if (and (get-text-property p 'display)
17163 (eq (get-text-property p 'face) 'org-date))
17164 (remove-text-properties
17165 p (setq p (next-single-property-change p 'display))
17166 '(display t))))
17167 (set-buffer-modified-p bmp)))
17168 (if (featurep 'xemacs)
17169 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17170 (org-restart-font-lock)
17171 (setq org-table-may-need-update t)
17172 (if org-display-custom-times
17173 (message "Time stamps are overlayed with custom format")
17174 (message "Time stamp overlays removed")))
17176 (defun org-display-custom-time (beg end)
17177 "Overlay modified time stamp format over timestamp between BED and END."
17178 (let* ((ts (buffer-substring beg end))
17179 t1 w1 with-hm tf time str w2 (off 0))
17180 (save-match-data
17181 (setq t1 (org-parse-time-string ts t))
17182 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17183 (setq off (- (match-end 0) (match-beginning 0)))))
17184 (setq end (- end off))
17185 (setq w1 (- end beg)
17186 with-hm (and (nth 1 t1) (nth 2 t1))
17187 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17188 time (org-fix-decoded-time t1)
17189 str (org-add-props
17190 (format-time-string
17191 (substring tf 1 -1) (apply 'encode-time time))
17192 nil 'mouse-face 'highlight)
17193 w2 (length str))
17194 (if (not (= w2 w1))
17195 (add-text-properties (1+ beg) (+ 2 beg)
17196 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17197 (if (featurep 'xemacs)
17198 (progn
17199 (put-text-property beg end 'invisible t)
17200 (put-text-property beg end 'end-glyph (make-glyph str)))
17201 (put-text-property beg end 'display str))))
17203 (defun org-translate-time (string)
17204 "Translate all timestamps in STRING to custom format.
17205 But do this only if the variable `org-display-custom-times' is set."
17206 (when org-display-custom-times
17207 (save-match-data
17208 (let* ((start 0)
17209 (re org-ts-regexp-both)
17210 t1 with-hm inactive tf time str beg end)
17211 (while (setq start (string-match re string start))
17212 (setq beg (match-beginning 0)
17213 end (match-end 0)
17214 t1 (save-match-data
17215 (org-parse-time-string (substring string beg end) t))
17216 with-hm (and (nth 1 t1) (nth 2 t1))
17217 inactive (equal (substring string beg (1+ beg)) "[")
17218 tf (funcall (if with-hm 'cdr 'car)
17219 org-time-stamp-custom-formats)
17220 time (org-fix-decoded-time t1)
17221 str (format-time-string
17222 (concat
17223 (if inactive "[" "<") (substring tf 1 -1)
17224 (if inactive "]" ">"))
17225 (apply 'encode-time time))
17226 string (replace-match str t t string)
17227 start (+ start (length str)))))))
17228 string)
17230 (defun org-fix-decoded-time (time)
17231 "Set 0 instead of nil for the first 6 elements of time.
17232 Don't touch the rest."
17233 (let ((n 0))
17234 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17236 (defun org-days-to-time (timestamp-string)
17237 "Difference between TIMESTAMP-STRING and now in days."
17238 (- (time-to-days (org-time-string-to-time timestamp-string))
17239 (time-to-days (current-time))))
17241 (defun org-deadline-close (timestamp-string &optional ndays)
17242 "Is the time in TIMESTAMP-STRING close to the current date?"
17243 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17244 (and (< (org-days-to-time timestamp-string) ndays)
17245 (not (org-entry-is-done-p))))
17247 (defun org-get-wdays (ts)
17248 "Get the deadline lead time appropriate for timestring TS."
17249 (cond
17250 ((<= org-deadline-warning-days 0)
17251 ;; 0 or negative, enforce this value no matter what
17252 (- org-deadline-warning-days))
17253 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17254 ;; lead time is specified.
17255 (floor (* (string-to-number (match-string 1 ts))
17256 (cdr (assoc (match-string 2 ts)
17257 '(("d" . 1) ("w" . 7)
17258 ("m" . 30.4) ("y" . 365.25)))))))
17259 ;; go for the default.
17260 (t org-deadline-warning-days)))
17262 (defun org-calendar-select-mouse (ev)
17263 "Return to `org-read-date' with the date currently selected.
17264 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17265 (interactive "e")
17266 (mouse-set-point ev)
17267 (when (calendar-cursor-to-date)
17268 (let* ((date (calendar-cursor-to-date))
17269 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17270 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17271 (if (active-minibuffer-window) (exit-minibuffer))))
17273 (defun org-check-deadlines (ndays)
17274 "Check if there are any deadlines due or past due.
17275 A deadline is considered due if it happens within `org-deadline-warning-days'
17276 days from today's date. If the deadline appears in an entry marked DONE,
17277 it is not shown. The prefix arg NDAYS can be used to test that many
17278 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17279 (interactive "P")
17280 (let* ((org-warn-days
17281 (cond
17282 ((equal ndays '(4)) 100000)
17283 (ndays (prefix-numeric-value ndays))
17284 (t (abs org-deadline-warning-days))))
17285 (case-fold-search nil)
17286 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17287 (callback
17288 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17290 (message "%d deadlines past-due or due within %d days"
17291 (org-occur regexp nil callback)
17292 org-warn-days)))
17294 (defun org-evaluate-time-range (&optional to-buffer)
17295 "Evaluate a time range by computing the difference between start and end.
17296 Normally the result is just printed in the echo area, but with prefix arg
17297 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17298 If the time range is actually in a table, the result is inserted into the
17299 next column.
17300 For time difference computation, a year is assumed to be exactly 365
17301 days in order to avoid rounding problems."
17302 (interactive "P")
17304 (org-clock-update-time-maybe)
17305 (save-excursion
17306 (unless (org-at-date-range-p t)
17307 (goto-char (point-at-bol))
17308 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17309 (if (not (org-at-date-range-p t))
17310 (error "Not at a time-stamp range, and none found in current line")))
17311 (let* ((ts1 (match-string 1))
17312 (ts2 (match-string 2))
17313 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17314 (match-end (match-end 0))
17315 (time1 (org-time-string-to-time ts1))
17316 (time2 (org-time-string-to-time ts2))
17317 (t1 (time-to-seconds time1))
17318 (t2 (time-to-seconds time2))
17319 (diff (abs (- t2 t1)))
17320 (negative (< (- t2 t1) 0))
17321 ;; (ys (floor (* 365 24 60 60)))
17322 (ds (* 24 60 60))
17323 (hs (* 60 60))
17324 (fy "%dy %dd %02d:%02d")
17325 (fy1 "%dy %dd")
17326 (fd "%dd %02d:%02d")
17327 (fd1 "%dd")
17328 (fh "%02d:%02d")
17329 y d h m align)
17330 (if havetime
17331 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17333 d (floor (/ diff ds)) diff (mod diff ds)
17334 h (floor (/ diff hs)) diff (mod diff hs)
17335 m (floor (/ diff 60)))
17336 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17338 d (floor (+ (/ diff ds) 0.5))
17339 h 0 m 0))
17340 (if (not to-buffer)
17341 (message (org-make-tdiff-string y d h m))
17342 (if (org-at-table-p)
17343 (progn
17344 (goto-char match-end)
17345 (setq align t)
17346 (and (looking-at " *|") (goto-char (match-end 0))))
17347 (goto-char match-end))
17348 (if (looking-at
17349 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17350 (replace-match ""))
17351 (if negative (insert " -"))
17352 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17353 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17354 (insert " " (format fh h m))))
17355 (if align (org-table-align))
17356 (message "Time difference inserted")))))
17358 (defun org-make-tdiff-string (y d h m)
17359 (let ((fmt "")
17360 (l nil))
17361 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17362 l (push y l)))
17363 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17364 l (push d l)))
17365 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17366 l (push h l)))
17367 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17368 l (push m l)))
17369 (apply 'format fmt (nreverse l))))
17371 (defun org-time-string-to-time (s)
17372 (apply 'encode-time (org-parse-time-string s)))
17374 (defun org-time-string-to-absolute (s &optional daynr)
17375 "Convert a time stamp to an absolute day number.
17376 If there is a specifyer for a cyclic time stamp, get the closest date to
17377 DAYNR."
17378 (cond
17379 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17380 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17381 daynr
17382 (+ daynr 1000)))
17383 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
17384 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17385 (time-to-days (current-time))) (match-string 0 s)))
17386 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
17388 (defun org-time-from-absolute (d)
17389 "Return the time corresponding to date D.
17390 D may be an absolute day number, or a calendar-type list (month day year)."
17391 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17392 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17394 (defun org-calendar-holiday ()
17395 "List of holidays, for Diary display in Org-mode."
17396 (require 'holidays)
17397 (let ((hl (funcall
17398 (if (fboundp 'calendar-check-holidays)
17399 'calendar-check-holidays 'check-calendar-holidays) date)))
17400 (if hl (mapconcat 'identity hl "; "))))
17402 (defun org-diary-sexp-entry (sexp entry date)
17403 "Process a SEXP diary ENTRY for DATE."
17404 (require 'diary-lib)
17405 (let ((result (if calendar-debug-sexp
17406 (let ((stack-trace-on-error t))
17407 (eval (car (read-from-string sexp))))
17408 (condition-case nil
17409 (eval (car (read-from-string sexp)))
17410 (error
17411 (beep)
17412 (message "Bad sexp at line %d in %s: %s"
17413 (org-current-line)
17414 (buffer-file-name) sexp)
17415 (sleep-for 2))))))
17416 (cond ((stringp result) result)
17417 ((and (consp result)
17418 (stringp (cdr result))) (cdr result))
17419 (result entry)
17420 (t nil))))
17422 (defun org-diary-to-ical-string (frombuf)
17423 "Get iCalendar entries from diary entries in buffer FROMBUF.
17424 This uses the icalendar.el library."
17425 (let* ((tmpdir (if (featurep 'xemacs)
17426 (temp-directory)
17427 temporary-file-directory))
17428 (tmpfile (make-temp-name
17429 (expand-file-name "orgics" tmpdir)))
17430 buf rtn b e)
17431 (save-excursion
17432 (set-buffer frombuf)
17433 (icalendar-export-region (point-min) (point-max) tmpfile)
17434 (setq buf (find-buffer-visiting tmpfile))
17435 (set-buffer buf)
17436 (goto-char (point-min))
17437 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17438 (setq b (match-beginning 0)))
17439 (goto-char (point-max))
17440 (if (re-search-backward "^END:VEVENT" nil t)
17441 (setq e (match-end 0)))
17442 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17443 (kill-buffer buf)
17444 (kill-buffer frombuf)
17445 (delete-file tmpfile)
17446 rtn))
17448 (defun org-closest-date (start current change)
17449 "Find the date closest to CURRENT that is consistent with START and CHANGE."
17450 ;; Make the proper lists from the dates
17451 (catch 'exit
17452 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
17453 dn dw sday cday n1 n2
17454 d m y y1 y2 date1 date2 nmonths nm ny m2)
17456 (setq start (org-date-to-gregorian start)
17457 current (org-date-to-gregorian
17458 (if org-agenda-repeating-timestamp-show-all
17459 current
17460 (time-to-days (current-time))))
17461 sday (calendar-absolute-from-gregorian start)
17462 cday (calendar-absolute-from-gregorian current))
17464 (if (<= cday sday) (throw 'exit sday))
17466 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
17467 (setq dn (string-to-number (match-string 1 change))
17468 dw (cdr (assoc (match-string 2 change) a1)))
17469 (error "Invalid change specifyer: %s" change))
17470 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17471 (cond
17472 ((eq dw 'day)
17473 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17474 n2 (+ n1 dn)))
17475 ((eq dw 'year)
17476 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17477 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17478 (setq date1 (list m d y1)
17479 n1 (calendar-absolute-from-gregorian date1)
17480 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17481 n2 (calendar-absolute-from-gregorian date2)))
17482 ((eq dw 'month)
17483 ;; approx number of month between the tow dates
17484 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17485 ;; How often does dn fit in there?
17486 (setq d (nth 1 start) m (car start) y (nth 2 start)
17487 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17488 m (+ m nm)
17489 ny (floor (/ m 12))
17490 y (+ y ny)
17491 m (- m (* ny 12)))
17492 (while (> m 12) (setq m (- m 12) y (1+ y)))
17493 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17494 (setq m2 (+ m dn) y2 y)
17495 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17496 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17497 (while (< n2 cday)
17498 (setq n1 n2 m m2 y y2)
17499 (setq m2 (+ m dn) y2 y)
17500 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17501 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17503 (if org-agenda-repeating-timestamp-show-all
17504 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
17505 (if (= cday n1) n1 n2)))))
17507 (defun org-date-to-gregorian (date)
17508 "Turn any specification of DATE into a gregorian date for the calendar."
17509 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17510 ((and (listp date) (= (length date) 3)) date)
17511 ((stringp date)
17512 (setq date (org-parse-time-string date))
17513 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17514 ((listp date)
17515 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17517 (defun org-parse-time-string (s &optional nodefault)
17518 "Parse the standard Org-mode time string.
17519 This should be a lot faster than the normal `parse-time-string'.
17520 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17521 hour and minute fields will be nil if not given."
17522 (if (string-match org-ts-regexp0 s)
17523 (list 0
17524 (if (or (match-beginning 8) (not nodefault))
17525 (string-to-number (or (match-string 8 s) "0")))
17526 (if (or (match-beginning 7) (not nodefault))
17527 (string-to-number (or (match-string 7 s) "0")))
17528 (string-to-number (match-string 4 s))
17529 (string-to-number (match-string 3 s))
17530 (string-to-number (match-string 2 s))
17531 nil nil nil)
17532 (make-list 9 0)))
17534 (defun org-timestamp-up (&optional arg)
17535 "Increase the date item at the cursor by one.
17536 If the cursor is on the year, change the year. If it is on the month or
17537 the day, change that.
17538 With prefix ARG, change by that many units."
17539 (interactive "p")
17540 (org-timestamp-change (prefix-numeric-value arg)))
17542 (defun org-timestamp-down (&optional arg)
17543 "Decrease the date item at the cursor by one.
17544 If the cursor is on the year, change the year. If it is on the month or
17545 the day, change that.
17546 With prefix ARG, change by that many units."
17547 (interactive "p")
17548 (org-timestamp-change (- (prefix-numeric-value arg))))
17550 (defun org-timestamp-up-day (&optional arg)
17551 "Increase the date in the time stamp by one day.
17552 With prefix ARG, change that many days."
17553 (interactive "p")
17554 (if (and (not (org-at-timestamp-p t))
17555 (org-on-heading-p))
17556 (org-todo 'up)
17557 (org-timestamp-change (prefix-numeric-value arg) 'day)))
17559 (defun org-timestamp-down-day (&optional arg)
17560 "Decrease the date in the time stamp by one day.
17561 With prefix ARG, change that many days."
17562 (interactive "p")
17563 (if (and (not (org-at-timestamp-p t))
17564 (org-on-heading-p))
17565 (org-todo 'down)
17566 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
17568 (defsubst org-pos-in-match-range (pos n)
17569 (and (match-beginning n)
17570 (<= (match-beginning n) pos)
17571 (>= (match-end n) pos)))
17573 (defun org-at-timestamp-p (&optional inactive-ok)
17574 "Determine if the cursor is in or at a timestamp."
17575 (interactive)
17576 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17577 (pos (point))
17578 (ans (or (looking-at tsr)
17579 (save-excursion
17580 (skip-chars-backward "^[<\n\r\t")
17581 (if (> (point) (point-min)) (backward-char 1))
17582 (and (looking-at tsr)
17583 (> (- (match-end 0) pos) -1))))))
17584 (and ans
17585 (boundp 'org-ts-what)
17586 (setq org-ts-what
17587 (cond
17588 ((= pos (match-beginning 0)) 'bracket)
17589 ((= pos (1- (match-end 0))) 'bracket)
17590 ((org-pos-in-match-range pos 2) 'year)
17591 ((org-pos-in-match-range pos 3) 'month)
17592 ((org-pos-in-match-range pos 7) 'hour)
17593 ((org-pos-in-match-range pos 8) 'minute)
17594 ((or (org-pos-in-match-range pos 4)
17595 (org-pos-in-match-range pos 5)) 'day)
17596 ((and (> pos (or (match-end 8) (match-end 5)))
17597 (< pos (match-end 0)))
17598 (- pos (or (match-end 8) (match-end 5))))
17599 (t 'day))))
17600 ans))
17602 (defun org-toggle-timestamp-type ()
17604 (interactive)
17605 (when (org-at-timestamp-p t)
17606 (save-excursion
17607 (goto-char (match-beginning 0))
17608 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
17609 (goto-char (1- (match-end 0)))
17610 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
17611 (message "Timestamp is now %sactive"
17612 (if (equal (char-before) ?>) "in" ""))))
17614 (defun org-timestamp-change (n &optional what)
17615 "Change the date in the time stamp at point.
17616 The date will be changed by N times WHAT. WHAT can be `day', `month',
17617 `year', `minute', `second'. If WHAT is not given, the cursor position
17618 in the timestamp determines what will be changed."
17619 (let ((pos (point))
17620 with-hm inactive
17621 org-ts-what
17622 extra
17623 ts time time0)
17624 (if (not (org-at-timestamp-p t))
17625 (error "Not at a timestamp"))
17626 (if (and (not what) (eq org-ts-what 'bracket))
17627 (org-toggle-timestamp-type)
17628 (if (and (not what) (not (eq org-ts-what 'day))
17629 org-display-custom-times
17630 (get-text-property (point) 'display)
17631 (not (get-text-property (1- (point)) 'display)))
17632 (setq org-ts-what 'day))
17633 (setq org-ts-what (or what org-ts-what)
17634 inactive (= (char-after (match-beginning 0)) ?\[)
17635 ts (match-string 0))
17636 (replace-match "")
17637 (if (string-match
17638 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
17640 (setq extra (match-string 1 ts)))
17641 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17642 (setq with-hm t))
17643 (setq time0 (org-parse-time-string ts))
17644 (setq time
17645 (encode-time (or (car time0) 0)
17646 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17647 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17648 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17649 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17650 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17651 (nthcdr 6 time0)))
17652 (when (integerp org-ts-what)
17653 (setq extra (org-modify-ts-extra extra org-ts-what n)))
17654 (if (eq what 'calendar)
17655 (let ((cal-date (org-get-date-from-calendar)))
17656 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17657 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17658 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17659 (setcar time0 (or (car time0) 0))
17660 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17661 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17662 (setq time (apply 'encode-time time0))))
17663 (setq org-last-changed-timestamp
17664 (org-insert-time-stamp time with-hm inactive nil nil extra))
17665 (org-clock-update-time-maybe)
17666 (goto-char pos)
17667 ;; Try to recenter the calendar window, if any
17668 (if (and org-calendar-follow-timestamp-change
17669 (get-buffer-window "*Calendar*" t)
17670 (memq org-ts-what '(day month year)))
17671 (org-recenter-calendar (time-to-days time))))))
17673 ;; FIXME: does not yet work for lead times
17674 (defun org-modify-ts-extra (s pos n)
17675 "Change the different parts of the lead-time and repeat fields in timestamp."
17676 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17677 ng h m new)
17678 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17679 (cond
17680 ((or (org-pos-in-match-range pos 2)
17681 (org-pos-in-match-range pos 3))
17682 (setq m (string-to-number (match-string 3 s))
17683 h (string-to-number (match-string 2 s)))
17684 (if (org-pos-in-match-range pos 2)
17685 (setq h (+ h n))
17686 (setq m (+ m n)))
17687 (if (< m 0) (setq m (+ m 60) h (1- h)))
17688 (if (> m 59) (setq m (- m 60) h (1+ h)))
17689 (setq h (min 24 (max 0 h)))
17690 (setq ng 1 new (format "-%02d:%02d" h m)))
17691 ((org-pos-in-match-range pos 6)
17692 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17693 ((org-pos-in-match-range pos 5)
17694 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
17696 (when ng
17697 (setq s (concat
17698 (substring s 0 (match-beginning ng))
17700 (substring s (match-end ng))))))
17703 (defun org-recenter-calendar (date)
17704 "If the calendar is visible, recenter it to DATE."
17705 (let* ((win (selected-window))
17706 (cwin (get-buffer-window "*Calendar*" t))
17707 (calendar-move-hook nil))
17708 (when cwin
17709 (select-window cwin)
17710 (calendar-goto-date (if (listp date) date
17711 (calendar-gregorian-from-absolute date)))
17712 (select-window win))))
17714 (defun org-goto-calendar (&optional arg)
17715 "Go to the Emacs calendar at the current date.
17716 If there is a time stamp in the current line, go to that date.
17717 A prefix ARG can be used to force the current date."
17718 (interactive "P")
17719 (let ((tsr org-ts-regexp) diff
17720 (calendar-move-hook nil)
17721 (view-calendar-holidays-initially nil)
17722 (view-diary-entries-initially nil))
17723 (if (or (org-at-timestamp-p)
17724 (save-excursion
17725 (beginning-of-line 1)
17726 (looking-at (concat ".*" tsr))))
17727 (let ((d1 (time-to-days (current-time)))
17728 (d2 (time-to-days
17729 (org-time-string-to-time (match-string 1)))))
17730 (setq diff (- d2 d1))))
17731 (calendar)
17732 (calendar-goto-today)
17733 (if (and diff (not arg)) (calendar-forward-day diff))))
17735 (defun org-get-date-from-calendar ()
17736 "Return a list (month day year) of date at point in calendar."
17737 (with-current-buffer "*Calendar*"
17738 (save-match-data
17739 (calendar-cursor-to-date))))
17741 (defun org-date-from-calendar ()
17742 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17743 If there is already a time stamp at the cursor position, update it."
17744 (interactive)
17745 (if (org-at-timestamp-p t)
17746 (org-timestamp-change 0 'calendar)
17747 (let ((cal-date (org-get-date-from-calendar)))
17748 (org-insert-time-stamp
17749 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17751 ;; Make appt aware of appointments from the agenda
17752 ;;;###autoload
17753 (defun org-agenda-to-appt (&optional filter)
17754 "Activate appointments found in `org-agenda-files'.
17755 When prefixed, prompt for a regular expression and use it as a
17756 filter: only add entries if they match this regular expression.
17758 FILTER can be a string. In this case, use this string as a
17759 regular expression to filter results.
17761 FILTER can also be an alist, with the car of each cell being
17762 either 'headline or 'category. For example:
17764 '((headline \"IMPORTANT\")
17765 (category \"Work\"))
17767 will only add headlines containing IMPORTANT or headlines
17768 belonging to the category \"Work\"."
17769 (interactive "P")
17770 (require 'calendar)
17771 (if (equal filter '(4))
17772 (setq filter (read-from-minibuffer "Regexp filter: ")))
17773 (let* ((cnt 0) ; count added events
17774 (today (org-date-to-gregorian
17775 (time-to-days (current-time))))
17776 (files (org-agenda-files)) entries file)
17777 ;; Get all entries which may contain an appt
17778 (while (setq file (pop files))
17779 (setq entries
17780 (append entries
17781 (org-agenda-get-day-entries
17782 file today
17783 :timestamp :scheduled :deadline))))
17784 (setq entries (delq nil entries))
17785 ;; Map thru entries and find if they pass thru the filter
17786 (mapc
17787 (lambda(x)
17788 (let* ((evt (org-trim (get-text-property 1 'txt x)))
17789 (cat (get-text-property 1 'org-category x))
17790 (tod (get-text-property 1 'time-of-day x))
17791 (ok (or (null filter)
17792 (and (stringp filter) (string-match filter evt))
17793 (and (listp filter)
17794 (or (string-match
17795 (cadr (assoc 'category filter)) cat)
17796 (string-match
17797 (cadr (assoc 'headline filter)) evt))))))
17798 ;; FIXME Shall we remove text-properties for the appt text?
17799 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
17800 (when (and ok tod)
17801 (setq tod (number-to-string tod)
17802 tod (when (string-match
17803 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
17804 (concat (match-string 1 tod) ":"
17805 (match-string 2 tod))))
17806 (appt-add tod evt)
17807 (setq cnt (1+ cnt))))) entries)
17808 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
17810 ;;; The clock for measuring work time.
17812 (defvar org-mode-line-string "")
17813 (put 'org-mode-line-string 'risky-local-variable t)
17815 (defvar org-mode-line-timer nil)
17816 (defvar org-clock-heading "")
17817 (defvar org-clock-start-time "")
17819 (defun org-update-mode-line ()
17820 (let* ((delta (- (time-to-seconds (current-time))
17821 (time-to-seconds org-clock-start-time)))
17822 (h (floor delta 3600))
17823 (m (floor (- delta (* 3600 h)) 60)))
17824 (setq org-mode-line-string
17825 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
17826 'help-echo "Org-mode clock is running"))
17827 (force-mode-line-update)))
17829 (defvar org-clock-marker (make-marker)
17830 "Marker recording the last clock-in.")
17831 (defvar org-clock-mode-line-entry nil
17832 "Information for the modeline about the running clock.")
17834 (defun org-clock-in ()
17835 "Start the clock on the current item.
17836 If necessary, clock-out of the currently active clock."
17837 (interactive)
17838 (org-clock-out t)
17839 (let (ts)
17840 (save-excursion
17841 (org-back-to-heading t)
17842 (if (and org-clock-heading-function
17843 (functionp org-clock-heading-function))
17844 (setq org-clock-heading (funcall org-clock-heading-function))
17845 (if (looking-at org-complex-heading-regexp)
17846 (setq org-clock-heading (match-string 4))
17847 (setq org-clock-heading "???")))
17848 (setq org-clock-heading (propertize org-clock-heading 'face nil))
17849 (org-clock-find-position)
17851 (insert "\n") (backward-char 1)
17852 (indent-relative)
17853 (insert org-clock-string " ")
17854 (setq org-clock-start-time (current-time))
17855 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
17856 (move-marker org-clock-marker (point) (buffer-base-buffer))
17857 (or global-mode-string (setq global-mode-string '("")))
17858 (or (memq 'org-mode-line-string global-mode-string)
17859 (setq global-mode-string
17860 (append global-mode-string '(org-mode-line-string))))
17861 (org-update-mode-line)
17862 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
17863 (message "Clock started at %s" ts))))
17865 (defun org-clock-find-position ()
17866 "Find the location where the next clock line should be inserted."
17867 (org-back-to-heading t)
17868 (catch 'exit
17869 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
17870 (re (concat "^[ \t]*" org-clock-string))
17871 (cnt 0)
17872 first last)
17873 (goto-char beg)
17874 (when (eobp) (newline) (setq end (max (point) end)))
17875 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
17876 ;; we seem to have a CLOCK drawer, so go there.
17877 (beginning-of-line 2)
17878 (throw 'exit t))
17879 ;; Lets count the CLOCK lines
17880 (goto-char beg)
17881 (while (re-search-forward re end t)
17882 (setq first (or first (match-beginning 0))
17883 last (match-beginning 0)
17884 cnt (1+ cnt)))
17885 (when (and (integerp org-clock-into-drawer)
17886 (>= (1+ cnt) org-clock-into-drawer))
17887 ;; Wrap current entries into a new drawer
17888 (goto-char last)
17889 (beginning-of-line 2)
17890 (if (org-at-item-p) (org-end-of-item))
17891 (insert ":END:\n")
17892 (beginning-of-line 0)
17893 (org-indent-line-function)
17894 (goto-char first)
17895 (insert ":CLOCK:\n")
17896 (beginning-of-line 0)
17897 (org-indent-line-function)
17898 (org-flag-drawer t)
17899 (beginning-of-line 2)
17900 (throw 'exit nil))
17902 (goto-char beg)
17903 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
17904 (not (equal (match-string 1) org-clock-string)))
17905 ;; Planning info, skip to after it
17906 (beginning-of-line 2)
17907 (or (bolp) (newline)))
17908 (when (eq t org-clock-into-drawer)
17909 (insert ":CLOCK:\n:END:\n")
17910 (beginning-of-line -1)
17911 (org-indent-line-function)
17912 (org-flag-drawer t)
17913 (beginning-of-line 2)
17914 (org-indent-line-function)))))
17916 (defun org-clock-out (&optional fail-quietly)
17917 "Stop the currently running clock.
17918 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
17919 (interactive)
17920 (catch 'exit
17921 (if (not (marker-buffer org-clock-marker))
17922 (if fail-quietly (throw 'exit t) (error "No active clock")))
17923 (let (ts te s h m)
17924 (save-excursion
17925 (set-buffer (marker-buffer org-clock-marker))
17926 (goto-char org-clock-marker)
17927 (beginning-of-line 1)
17928 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
17929 (equal (match-string 1) org-clock-string))
17930 (setq ts (match-string 2))
17931 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
17932 (goto-char (match-end 0))
17933 (delete-region (point) (point-at-eol))
17934 (insert "--")
17935 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
17936 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
17937 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
17938 h (floor (/ s 3600))
17939 s (- s (* 3600 h))
17940 m (floor (/ s 60))
17941 s (- s (* 60 s)))
17942 (insert " => " (format "%2d:%02d" h m))
17943 (move-marker org-clock-marker nil)
17944 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
17945 (org-log-done (org-parse-local-options logging 'org-log-done))
17946 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
17947 (org-add-log-maybe 'clock-out))
17948 (when org-mode-line-timer
17949 (cancel-timer org-mode-line-timer)
17950 (setq org-mode-line-timer nil))
17951 (setq global-mode-string
17952 (delq 'org-mode-line-string global-mode-string))
17953 (force-mode-line-update)
17954 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
17956 (defun org-clock-cancel ()
17957 "Cancel the running clock be removing the start timestamp."
17958 (interactive)
17959 (if (not (marker-buffer org-clock-marker))
17960 (error "No active clock"))
17961 (save-excursion
17962 (set-buffer (marker-buffer org-clock-marker))
17963 (goto-char org-clock-marker)
17964 (delete-region (1- (point-at-bol)) (point-at-eol)))
17965 (setq global-mode-string
17966 (delq 'org-mode-line-string global-mode-string))
17967 (force-mode-line-update)
17968 (message "Clock canceled"))
17970 (defun org-clock-goto (&optional delete-windows)
17971 "Go to the currently clocked-in entry."
17972 (interactive "P")
17973 (if (not (marker-buffer org-clock-marker))
17974 (error "No active clock"))
17975 (switch-to-buffer-other-window
17976 (marker-buffer org-clock-marker))
17977 (if delete-windows (delete-other-windows))
17978 (goto-char org-clock-marker)
17979 (org-show-entry)
17980 (org-back-to-heading)
17981 (recenter))
17983 (defvar org-clock-file-total-minutes nil
17984 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
17985 (make-variable-buffer-local 'org-clock-file-total-minutes)
17987 (defun org-clock-sum (&optional tstart tend)
17988 "Sum the times for each subtree.
17989 Puts the resulting times in minutes as a text property on each headline."
17990 (interactive)
17991 (let* ((bmp (buffer-modified-p))
17992 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
17993 org-clock-string
17994 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
17995 (lmax 30)
17996 (ltimes (make-vector lmax 0))
17997 (t1 0)
17998 (level 0)
17999 ts te dt
18000 time)
18001 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18002 (save-excursion
18003 (goto-char (point-max))
18004 (while (re-search-backward re nil t)
18005 (cond
18006 ((match-end 2)
18007 ;; Two time stamps
18008 (setq ts (match-string 2)
18009 te (match-string 3)
18010 ts (time-to-seconds
18011 (apply 'encode-time (org-parse-time-string ts)))
18012 te (time-to-seconds
18013 (apply 'encode-time (org-parse-time-string te)))
18014 ts (if tstart (max ts tstart) ts)
18015 te (if tend (min te tend) te)
18016 dt (- te ts)
18017 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18018 ((match-end 4)
18019 ;; A naket time
18020 (setq t1 (+ t1 (string-to-number (match-string 5))
18021 (* 60 (string-to-number (match-string 4))))))
18022 (t ;; A headline
18023 (setq level (- (match-end 1) (match-beginning 1)))
18024 (when (or (> t1 0) (> (aref ltimes level) 0))
18025 (loop for l from 0 to level do
18026 (aset ltimes l (+ (aref ltimes l) t1)))
18027 (setq t1 0 time (aref ltimes level))
18028 (loop for l from level to (1- lmax) do
18029 (aset ltimes l 0))
18030 (goto-char (match-beginning 0))
18031 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18032 (setq org-clock-file-total-minutes (aref ltimes 0)))
18033 (set-buffer-modified-p bmp)))
18035 (defun org-clock-display (&optional total-only)
18036 "Show subtree times in the entire buffer.
18037 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18038 in the echo area."
18039 (interactive)
18040 (org-remove-clock-overlays)
18041 (let (time h m p)
18042 (org-clock-sum)
18043 (unless total-only
18044 (save-excursion
18045 (goto-char (point-min))
18046 (while (or (and (equal (setq p (point)) (point-min))
18047 (get-text-property p :org-clock-minutes))
18048 (setq p (next-single-property-change
18049 (point) :org-clock-minutes)))
18050 (goto-char p)
18051 (when (setq time (get-text-property p :org-clock-minutes))
18052 (org-put-clock-overlay time (funcall outline-level))))
18053 (setq h (/ org-clock-file-total-minutes 60)
18054 m (- org-clock-file-total-minutes (* 60 h)))
18055 ;; Arrange to remove the overlays upon next change.
18056 (when org-remove-highlights-with-change
18057 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18058 nil 'local))))
18059 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18061 (defvar org-clock-overlays nil)
18062 (make-variable-buffer-local 'org-clock-overlays)
18064 (defun org-put-clock-overlay (time &optional level)
18065 "Put an overlays on the current line, displaying TIME.
18066 If LEVEL is given, prefix time with a corresponding number of stars.
18067 This creates a new overlay and stores it in `org-clock-overlays', so that it
18068 will be easy to remove."
18069 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18070 (l (if level (org-get-legal-level level 0) 0))
18071 (off 0)
18072 ov tx)
18073 (move-to-column c)
18074 (unless (eolp) (skip-chars-backward "^ \t"))
18075 (skip-chars-backward " \t")
18076 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18077 tx (concat (buffer-substring (1- (point)) (point))
18078 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18079 (org-add-props (format "%s %2d:%02d%s"
18080 (make-string l ?*) h m
18081 (make-string (- 10 l) ?\ ))
18082 '(face secondary-selection))
18083 ""))
18084 (if (not (featurep 'xemacs))
18085 (org-overlay-put ov 'display tx)
18086 (org-overlay-put ov 'invisible t)
18087 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18088 (push ov org-clock-overlays)))
18090 (defun org-remove-clock-overlays (&optional beg end noremove)
18091 "Remove the occur highlights from the buffer.
18092 BEG and END are ignored. If NOREMOVE is nil, remove this function
18093 from the `before-change-functions' in the current buffer."
18094 (interactive)
18095 (unless org-inhibit-highlight-removal
18096 (mapc 'org-delete-overlay org-clock-overlays)
18097 (setq org-clock-overlays nil)
18098 (unless noremove
18099 (remove-hook 'before-change-functions
18100 'org-remove-clock-overlays 'local))))
18102 (defun org-clock-out-if-current ()
18103 "Clock out if the current entry contains the running clock.
18104 This is used to stop the clock after a TODO entry is marked DONE,
18105 and is only done if the variable `org-clock-out-when-done' is not nil."
18106 (when (and org-clock-out-when-done
18107 (member state org-done-keywords)
18108 (equal (marker-buffer org-clock-marker) (current-buffer))
18109 (< (point) org-clock-marker)
18110 (> (save-excursion (outline-next-heading) (point))
18111 org-clock-marker))
18112 ;; Clock out, but don't accept a logging message for this.
18113 (let ((org-log-done (if (and (listp org-log-done)
18114 (member 'clock-out org-log-done))
18115 '(done)
18116 org-log-done)))
18117 (org-clock-out))))
18119 (add-hook 'org-after-todo-state-change-hook
18120 'org-clock-out-if-current)
18122 (defun org-check-running-clock ()
18123 "Check if the current buffer contains the running clock.
18124 If yes, offer to stop it and to save the buffer with the changes."
18125 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18126 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18127 (buffer-name))))
18128 (org-clock-out)
18129 (when (y-or-n-p "Save changed buffer?")
18130 (save-buffer))))
18132 (defun org-clock-report (&optional arg)
18133 "Create a table containing a report about clocked time.
18134 If the cursor is inside an existing clocktable block, then the table
18135 will be updated. If not, a new clocktable will be inserted.
18136 When called with a prefix argument, move to the first clock table in the
18137 buffer and update it."
18138 (interactive "P")
18139 (org-remove-clock-overlays)
18140 (when arg (org-find-dblock "clocktable"))
18141 (if (org-in-clocktable-p)
18142 (goto-char (org-in-clocktable-p))
18143 (org-create-dblock (list :name "clocktable"
18144 :maxlevel 2 :scope 'file)))
18145 (org-update-dblock))
18147 (defun org-in-clocktable-p ()
18148 "Check if the cursor is in a clocktable."
18149 (let ((pos (point)) start)
18150 (save-excursion
18151 (end-of-line 1)
18152 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18153 (setq start (match-beginning 0))
18154 (re-search-forward "^#\\+END:.*" nil t)
18155 (>= (match-end 0) pos)
18156 start))))
18158 (defun org-clock-update-time-maybe ()
18159 "If this is a CLOCK line, update it and return t.
18160 Otherwise, return nil."
18161 (interactive)
18162 (save-excursion
18163 (beginning-of-line 1)
18164 (skip-chars-forward " \t")
18165 (when (looking-at org-clock-string)
18166 (let ((re (concat "[ \t]*" org-clock-string
18167 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18168 "\\([ \t]*=>.*\\)?"))
18169 ts te h m s)
18170 (if (not (looking-at re))
18172 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18173 (end-of-line 1)
18174 (setq ts (match-string 1)
18175 te (match-string 2))
18176 (setq s (- (time-to-seconds
18177 (apply 'encode-time (org-parse-time-string te)))
18178 (time-to-seconds
18179 (apply 'encode-time (org-parse-time-string ts))))
18180 h (floor (/ s 3600))
18181 s (- s (* 3600 h))
18182 m (floor (/ s 60))
18183 s (- s (* 60 s)))
18184 (insert " => " (format "%2d:%02d" h m))
18185 t)))))
18187 (defun org-clock-special-range (key &optional time as-strings)
18188 "Return two times bordering a special time range.
18189 Key is a symbol specifying the range and can be one of `today', `yesterday',
18190 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18191 A week starts Monday 0:00 and ends Sunday 24:00.
18192 The range is determined relative to TIME. TIME defaults to the current time.
18193 The return value is a cons cell with two internal times like the ones
18194 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18195 the returned times will be formatted strings."
18196 (let* ((tm (decode-time (or time (current-time))))
18197 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18198 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18199 (dow (nth 6 tm))
18200 s1 m1 h1 d1 month1 y1 diff ts te fm)
18201 (cond
18202 ((eq key 'today)
18203 (setq h 0 m 0 h1 24 m1 0))
18204 ((eq key 'yesterday)
18205 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18206 ((eq key 'thisweek)
18207 (setq diff (if (= dow 0) 6 (1- dow))
18208 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18209 ((eq key 'lastweek)
18210 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18211 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18212 ((eq key 'thismonth)
18213 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18214 ((eq key 'lastmonth)
18215 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18216 ((eq key 'thisyear)
18217 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18218 ((eq key 'lastyear)
18219 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18220 (t (error "No such time block %s" key)))
18221 (setq ts (encode-time s m h d month y)
18222 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18223 (or d1 d) (or month1 month) (or y1 y)))
18224 (setq fm (cdr org-time-stamp-formats))
18225 (if as-strings
18226 (cons (format-time-string fm ts) (format-time-string fm te))
18227 (cons ts te))))
18229 (defun org-dblock-write:clocktable (params)
18230 "Write the standard clocktable."
18231 (let ((hlchars '((1 . "*") (2 . "/")))
18232 (emph nil)
18233 (ins (make-marker))
18234 (total-time nil)
18235 ipos time h m p level hlc hdl maxlevel
18236 ts te cc block beg end pos scope tbl tostring multifile)
18237 (setq scope (plist-get params :scope)
18238 tostring (plist-get params :tostring)
18239 multifile (plist-get params :multifile)
18240 maxlevel (or (plist-get params :maxlevel) 3)
18241 emph (plist-get params :emphasize)
18242 ts (plist-get params :tstart)
18243 te (plist-get params :tend)
18244 block (plist-get params :block))
18245 (when block
18246 (setq cc (org-clock-special-range block nil t)
18247 ts (car cc) te (cdr cc)))
18248 (if ts (setq ts (time-to-seconds
18249 (apply 'encode-time (org-parse-time-string ts)))))
18250 (if te (setq te (time-to-seconds
18251 (apply 'encode-time (org-parse-time-string te)))))
18252 (move-marker ins (point))
18253 (setq ipos (point))
18255 ;; Get the right scope
18256 (setq pos (point))
18257 (save-restriction
18258 (cond
18259 ((not scope))
18260 ((eq scope 'file) (widen))
18261 ((eq scope 'subtree) (org-narrow-to-subtree))
18262 ((eq scope 'tree)
18263 (while (org-up-heading-safe))
18264 (org-narrow-to-subtree))
18265 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18266 (symbol-name scope)))
18267 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18268 (catch 'exit
18269 (while (org-up-heading-safe)
18270 (looking-at outline-regexp)
18271 (if (<= (org-reduced-level (funcall outline-level)) level)
18272 (throw 'exit nil))))
18273 (org-narrow-to-subtree))
18274 ((or (listp scope) (eq scope 'agenda))
18275 (let* ((files (if (listp scope) scope (org-agenda-files)))
18276 (scope 'agenda)
18277 (p1 (copy-sequence params))
18278 file)
18279 (plist-put p1 :tostring t)
18280 (plist-put p1 :multifile t)
18281 (plist-put p1 :scope 'file)
18282 (org-prepare-agenda-buffers files)
18283 (while (setq file (pop files))
18284 (with-current-buffer (find-buffer-visiting file)
18285 (push (org-clocktable-add-file
18286 file (org-dblock-write:clocktable p1)) tbl)
18287 (setq total-time (+ (or total-time 0)
18288 org-clock-file-total-minutes)))))))
18289 (goto-char pos)
18291 (unless (eq scope 'agenda)
18292 (org-clock-sum ts te)
18293 (goto-char (point-min))
18294 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18295 (goto-char p)
18296 (when (setq time (get-text-property p :org-clock-minutes))
18297 (save-excursion
18298 (beginning-of-line 1)
18299 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18300 (setq level (org-reduced-level
18301 (- (match-end 1) (match-beginning 1))))
18302 (<= level maxlevel))
18303 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
18304 hdl (match-string 2)
18305 h (/ time 60)
18306 m (- time (* 60 h)))
18307 (if (and (not multifile) (= level 1)) (push "|-" tbl))
18308 (push (concat
18309 "| " (int-to-string level) "|" hlc hdl hlc " |"
18310 (make-string (1- level) ?|)
18311 hlc (format "%d:%02d" h m) hlc
18312 " |") tbl))))))
18313 (setq tbl (nreverse tbl))
18314 (if tostring
18315 (if tbl (mapconcat 'identity tbl "\n") nil)
18316 (goto-char ins)
18317 (insert-before-markers
18318 "Clock summary at ["
18319 (substring
18320 (format-time-string (cdr org-time-stamp-formats))
18321 1 -1)
18322 "]."
18323 (if block
18324 (format " Considered range is /%s/." block)
18326 "\n\n"
18327 (if (eq scope 'agenda) "|File" "")
18328 "|L|Headline|Time|\n")
18329 (setq total-time (or total-time org-clock-file-total-minutes)
18330 h (/ total-time 60)
18331 m (- total-time (* 60 h)))
18332 (insert-before-markers
18333 "|-\n|"
18334 (if (eq scope 'agenda) "|" "")
18336 "*Total time*| "
18337 (format "*%d:%02d*" h m)
18338 "|\n|-\n")
18339 (setq tbl (delq nil tbl))
18340 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
18341 (equal (substring (car tbl) 0 2) "|-"))
18342 (pop tbl))
18343 (insert-before-markers (mapconcat
18344 'identity (delq nil tbl)
18345 (if (eq scope 'agenda) "\n|-\n" "\n")))
18346 (backward-delete-char 1)
18347 (goto-char ipos)
18348 (skip-chars-forward "^|")
18349 (org-table-align)))))
18351 (defun org-clocktable-add-file (file table)
18352 (if table
18353 (let ((lines (org-split-string table "\n"))
18354 (ff (file-name-nondirectory file)))
18355 (mapconcat 'identity
18356 (mapcar (lambda (x)
18357 (if (string-match org-table-dataline-regexp x)
18358 (concat "|" ff x)
18360 lines)
18361 "\n"))))
18363 ;; FIXME: I don't think anybody uses this, ask David
18364 (defun org-collect-clock-time-entries ()
18365 "Return an internal list with clocking information.
18366 This list has one entry for each CLOCK interval.
18367 FIXME: describe the elements."
18368 (interactive)
18369 (let ((re (concat "^[ \t]*" org-clock-string
18370 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
18371 rtn beg end next cont level title total closedp leafp
18372 clockpos titlepos h m donep)
18373 (save-excursion
18374 (org-clock-sum)
18375 (goto-char (point-min))
18376 (while (re-search-forward re nil t)
18377 (setq clockpos (match-beginning 0)
18378 beg (match-string 1) end (match-string 2)
18379 cont (match-end 0))
18380 (setq beg (apply 'encode-time (org-parse-time-string beg))
18381 end (apply 'encode-time (org-parse-time-string end)))
18382 (org-back-to-heading t)
18383 (setq donep (org-entry-is-done-p))
18384 (setq titlepos (point)
18385 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
18386 h (/ total 60) m (- total (* 60 h))
18387 total (cons h m))
18388 (looking-at "\\(\\*+\\) +\\(.*\\)")
18389 (setq level (- (match-end 1) (match-beginning 1))
18390 title (org-match-string-no-properties 2))
18391 (save-excursion (outline-next-heading) (setq next (point)))
18392 (setq closedp (re-search-forward org-closed-time-regexp next t))
18393 (goto-char next)
18394 (setq leafp (and (looking-at "^\\*+ ")
18395 (<= (- (match-end 0) (point)) level)))
18396 (push (list beg end clockpos closedp donep
18397 total title titlepos level leafp)
18398 rtn)
18399 (goto-char cont)))
18400 (nreverse rtn)))
18402 ;;;; Agenda, and Diary Integration
18404 ;;; Define the Org-agenda-mode
18406 (defvar org-agenda-mode-map (make-sparse-keymap)
18407 "Keymap for `org-agenda-mode'.")
18409 (defvar org-agenda-menu) ; defined later in this file.
18410 (defvar org-agenda-follow-mode nil)
18411 (defvar org-agenda-show-log nil)
18412 (defvar org-agenda-redo-command nil)
18413 (defvar org-agenda-mode-hook nil)
18414 (defvar org-agenda-type nil)
18415 (defvar org-agenda-force-single-file nil)
18417 (defun org-agenda-mode ()
18418 "Mode for time-sorted view on action items in Org-mode files.
18420 The following commands are available:
18422 \\{org-agenda-mode-map}"
18423 (interactive)
18424 (kill-all-local-variables)
18425 (setq org-agenda-undo-list nil
18426 org-agenda-pending-undo-list nil)
18427 (setq major-mode 'org-agenda-mode)
18428 ;; Keep global-font-lock-mode from turning on font-lock-mode
18429 (org-set-local 'font-lock-global-modes (list 'not major-mode))
18430 (setq mode-name "Org-Agenda")
18431 (use-local-map org-agenda-mode-map)
18432 (easy-menu-add org-agenda-menu)
18433 (if org-startup-truncated (setq truncate-lines t))
18434 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
18435 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
18436 ;; Make sure properties are removed when copying text
18437 (when (boundp 'buffer-substring-filters)
18438 (org-set-local 'buffer-substring-filters
18439 (cons (lambda (x)
18440 (set-text-properties 0 (length x) nil x) x)
18441 buffer-substring-filters)))
18442 (unless org-agenda-keep-modes
18443 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
18444 org-agenda-show-log nil))
18445 (easy-menu-change
18446 '("Agenda") "Agenda Files"
18447 (append
18448 (list
18449 (vector
18450 (if (get 'org-agenda-files 'org-restrict)
18451 "Restricted to single file"
18452 "Edit File List")
18453 '(org-edit-agenda-file-list)
18454 (not (get 'org-agenda-files 'org-restrict)))
18455 "--")
18456 (mapcar 'org-file-menu-entry (org-agenda-files))))
18457 (org-agenda-set-mode-name)
18458 (apply
18459 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
18460 (list 'org-agenda-mode-hook)))
18462 (substitute-key-definition 'undo 'org-agenda-undo
18463 org-agenda-mode-map global-map)
18464 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
18465 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
18466 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
18467 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
18468 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
18469 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
18470 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
18471 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
18472 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
18473 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
18474 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
18475 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
18476 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
18477 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
18478 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
18479 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
18480 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
18481 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
18482 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
18483 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
18484 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
18485 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
18486 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
18487 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
18488 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
18489 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
18490 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
18491 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
18492 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
18494 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
18495 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
18496 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
18497 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
18498 (while l (org-defkey org-agenda-mode-map
18499 (int-to-string (pop l)) 'digit-argument)))
18501 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
18502 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
18503 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
18504 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
18505 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
18506 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
18507 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
18508 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
18509 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
18510 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
18511 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
18512 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
18513 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
18514 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
18515 (org-defkey org-agenda-mode-map "n" 'next-line)
18516 (org-defkey org-agenda-mode-map "p" 'previous-line)
18517 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
18518 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
18519 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
18520 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
18521 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
18522 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
18523 (eval-after-load "calendar"
18524 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
18525 'org-calendar-goto-agenda))
18526 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
18527 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
18528 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
18529 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
18530 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
18531 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
18532 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
18533 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
18534 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
18535 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
18536 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
18537 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18538 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
18539 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
18540 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
18541 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
18542 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
18543 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
18544 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
18545 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
18546 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
18547 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
18549 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
18550 "Local keymap for agenda entries from Org-mode.")
18552 (org-defkey org-agenda-keymap
18553 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
18554 (org-defkey org-agenda-keymap
18555 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
18556 (when org-agenda-mouse-1-follows-link
18557 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
18558 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
18559 '("Agenda"
18560 ("Agenda Files")
18561 "--"
18562 ["Show" org-agenda-show t]
18563 ["Go To (other window)" org-agenda-goto t]
18564 ["Go To (this window)" org-agenda-switch-to t]
18565 ["Follow Mode" org-agenda-follow-mode
18566 :style toggle :selected org-agenda-follow-mode :active t]
18567 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
18568 "--"
18569 ["Cycle TODO" org-agenda-todo t]
18570 ["Archive subtree" org-agenda-archive t]
18571 ["Delete subtree" org-agenda-kill t]
18572 "--"
18573 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
18574 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
18575 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
18576 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
18577 "--"
18578 ("Tags and Properties"
18579 ["Show all Tags" org-agenda-show-tags t]
18580 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
18581 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
18582 "--"
18583 ["Column View" org-columns t])
18584 ("Date/Schedule"
18585 ["Schedule" org-agenda-schedule t]
18586 ["Set Deadline" org-agenda-deadline t]
18587 "--"
18588 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
18589 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
18590 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
18591 ("Clock"
18592 ["Clock in" org-agenda-clock-in t]
18593 ["Clock out" org-agenda-clock-out t]
18594 ["Clock cancel" org-agenda-clock-cancel t]
18595 ["Goto running clock" org-clock-goto t])
18596 ("Priority"
18597 ["Set Priority" org-agenda-priority t]
18598 ["Increase Priority" org-agenda-priority-up t]
18599 ["Decrease Priority" org-agenda-priority-down t]
18600 ["Show Priority" org-agenda-show-priority t])
18601 ("Calendar/Diary"
18602 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
18603 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
18604 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
18605 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
18606 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
18607 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
18608 "--"
18609 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
18610 "--"
18611 ("View"
18612 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
18613 :style radio :selected (equal org-agenda-ndays 1)]
18614 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
18615 :style radio :selected (equal org-agenda-ndays 7)]
18616 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
18617 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
18618 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
18619 :style radio :selected (member org-agenda-ndays '(365 366))]
18620 "--"
18621 ["Show Logbook entries" org-agenda-log-mode
18622 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
18623 ["Include Diary" org-agenda-toggle-diary
18624 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
18625 ["Use Time Grid" org-agenda-toggle-time-grid
18626 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
18627 ["Write view to file" org-write-agenda t]
18628 ["Rebuild buffer" org-agenda-redo t]
18629 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
18630 "--"
18631 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
18632 "--"
18633 ["Quit" org-agenda-quit t]
18634 ["Exit and Release Buffers" org-agenda-exit t]
18637 ;;; Agenda undo
18639 (defvar org-agenda-allow-remote-undo t
18640 "Non-nil means, allow remote undo from the agenda buffer.")
18641 (defvar org-agenda-undo-list nil
18642 "List of undoable operations in the agenda since last refresh.")
18643 (defvar org-agenda-undo-has-started-in nil
18644 "Buffers that have already seen `undo-start' in the current undo sequence.")
18645 (defvar org-agenda-pending-undo-list nil
18646 "In a series of undo commands, this is the list of remaning undo items.")
18648 (defmacro org-if-unprotected (&rest body)
18649 "Execute BODY if there is no `org-protected' text property at point."
18650 (declare (debug t))
18651 `(unless (get-text-property (point) 'org-protected)
18652 ,@body))
18654 (defmacro org-with-remote-undo (_buffer &rest _body)
18655 "Execute BODY while recording undo information in two buffers."
18656 (declare (indent 1) (debug t))
18657 `(let ((_cline (org-current-line))
18658 (_cmd this-command)
18659 (_buf1 (current-buffer))
18660 (_buf2 ,_buffer)
18661 (_undo1 buffer-undo-list)
18662 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
18663 _c1 _c2)
18664 ,@_body
18665 (when org-agenda-allow-remote-undo
18666 (setq _c1 (org-verify-change-for-undo
18667 _undo1 (with-current-buffer _buf1 buffer-undo-list))
18668 _c2 (org-verify-change-for-undo
18669 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
18670 (when (or _c1 _c2)
18671 ;; make sure there are undo boundaries
18672 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
18673 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
18674 ;; remember which buffer to undo
18675 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
18676 org-agenda-undo-list)))))
18678 (defun org-agenda-undo ()
18679 "Undo a remote editing step in the agenda.
18680 This undoes changes both in the agenda buffer and in the remote buffer
18681 that have been changed along."
18682 (interactive)
18683 (or org-agenda-allow-remote-undo
18684 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
18685 (if (not (eq this-command last-command))
18686 (setq org-agenda-undo-has-started-in nil
18687 org-agenda-pending-undo-list org-agenda-undo-list))
18688 (if (not org-agenda-pending-undo-list)
18689 (error "No further undo information"))
18690 (let* ((entry (pop org-agenda-pending-undo-list))
18691 buf line cmd rembuf)
18692 (setq cmd (pop entry) line (pop entry))
18693 (setq rembuf (nth 2 entry))
18694 (org-with-remote-undo rembuf
18695 (while (bufferp (setq buf (pop entry)))
18696 (if (pop entry)
18697 (with-current-buffer buf
18698 (let ((last-undo-buffer buf)
18699 (inhibit-read-only t))
18700 (unless (memq buf org-agenda-undo-has-started-in)
18701 (push buf org-agenda-undo-has-started-in)
18702 (make-local-variable 'pending-undo-list)
18703 (undo-start))
18704 (while (and pending-undo-list
18705 (listp pending-undo-list)
18706 (not (car pending-undo-list)))
18707 (pop pending-undo-list))
18708 (undo-more 1))))))
18709 (goto-line line)
18710 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
18712 (defun org-verify-change-for-undo (l1 l2)
18713 "Verify that a real change occurred between the undo lists L1 and L2."
18714 (while (and l1 (listp l1) (null (car l1))) (pop l1))
18715 (while (and l2 (listp l2) (null (car l2))) (pop l2))
18716 (not (eq l1 l2)))
18718 ;;; Agenda dispatch
18720 (defvar org-agenda-restrict nil)
18721 (defvar org-agenda-restrict-begin (make-marker))
18722 (defvar org-agenda-restrict-end (make-marker))
18723 (defvar org-agenda-last-dispatch-buffer nil)
18724 (defvar org-agenda-overriding-restriction nil)
18726 ;;;###autoload
18727 (defun org-agenda (arg &optional keys restriction)
18728 "Dispatch agenda commands to collect entries to the agenda buffer.
18729 Prompts for a command to execute. Any prefix arg will be passed
18730 on to the selected command. The default selections are:
18732 a Call `org-agenda-list' to display the agenda for current day or week.
18733 t Call `org-todo-list' to display the global todo list.
18734 T Call `org-todo-list' to display the global todo list, select only
18735 entries with a specific TODO keyword (the user gets a prompt).
18736 m Call `org-tags-view' to display headlines with tags matching
18737 a condition (the user is prompted for the condition).
18738 M Like `m', but select only TODO entries, no ordinary headlines.
18739 L Create a timeline for the current buffer.
18740 e Export views to associated files.
18742 More commands can be added by configuring the variable
18743 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
18744 searches can be pre-defined in this way.
18746 If the current buffer is in Org-mode and visiting a file, you can also
18747 first press `<' once to indicate that the agenda should be temporarily
18748 \(until the next use of \\[org-agenda]) restricted to the current file.
18749 Pressing `<' twice means to restrict to the current subtree or region
18750 \(if active)."
18751 (interactive "P")
18752 (catch 'exit
18753 (let* ((prefix-descriptions nil)
18754 (org-agenda-custom-commands
18755 ;; normalize different versions
18756 (delq nil
18757 (mapcar
18758 (lambda (x)
18759 (cond ((stringp (cdr x))
18760 (push x prefix-descriptions)
18761 nil)
18762 ((stringp (nth 1 x)) x)
18763 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
18764 (t (cons (car x) (cons "" (cdr x))))))
18765 org-agenda-custom-commands)))
18766 (buf (current-buffer))
18767 (bfn (buffer-file-name (buffer-base-buffer)))
18768 entry key type match lprops ans)
18769 ;; Turn off restriction unless there is an overriding one
18770 (unless org-agenda-overriding-restriction
18771 (put 'org-agenda-files 'org-restrict nil)
18772 (setq org-agenda-restrict nil)
18773 (move-marker org-agenda-restrict-begin nil)
18774 (move-marker org-agenda-restrict-end nil))
18775 ;; Delete old local properties
18776 (put 'org-agenda-redo-command 'org-lprops nil)
18777 ;; Remember where this call originated
18778 (setq org-agenda-last-dispatch-buffer (current-buffer))
18779 (unless keys
18780 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
18781 keys (car ans)
18782 restriction (cdr ans)))
18783 ;; Estabish the restriction, if any
18784 (when (and (not org-agenda-overriding-restriction) restriction)
18785 (put 'org-agenda-files 'org-restrict (list bfn))
18786 (cond
18787 ((eq restriction 'region)
18788 (setq org-agenda-restrict t)
18789 (move-marker org-agenda-restrict-begin (region-beginning))
18790 (move-marker org-agenda-restrict-end (region-end)))
18791 ((eq restriction 'subtree)
18792 (save-excursion
18793 (setq org-agenda-restrict t)
18794 (org-back-to-heading t)
18795 (move-marker org-agenda-restrict-begin (point))
18796 (move-marker org-agenda-restrict-end
18797 (progn (org-end-of-subtree t)))))))
18799 (require 'calendar) ; FIXME: can we avoid this for some commands?
18800 ;; For example the todo list should not need it (but does...)
18801 (cond
18802 ((setq entry (assoc keys org-agenda-custom-commands))
18803 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
18804 (progn
18805 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
18806 (put 'org-agenda-redo-command 'org-lprops lprops)
18807 (cond
18808 ((eq type 'agenda)
18809 (org-let lprops '(org-agenda-list current-prefix-arg)))
18810 ((eq type 'alltodo)
18811 (org-let lprops '(org-todo-list current-prefix-arg)))
18812 ((eq type 'stuck)
18813 (org-let lprops '(org-agenda-list-stuck-projects
18814 current-prefix-arg)))
18815 ((eq type 'tags)
18816 (org-let lprops '(org-tags-view current-prefix-arg match)))
18817 ((eq type 'tags-todo)
18818 (org-let lprops '(org-tags-view '(4) match)))
18819 ((eq type 'todo)
18820 (org-let lprops '(org-todo-list match)))
18821 ((eq type 'tags-tree)
18822 (org-check-for-org-mode)
18823 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
18824 ((eq type 'todo-tree)
18825 (org-check-for-org-mode)
18826 (org-let lprops
18827 '(org-occur (concat "^" outline-regexp "[ \t]*"
18828 (regexp-quote match) "\\>"))))
18829 ((eq type 'occur-tree)
18830 (org-check-for-org-mode)
18831 (org-let lprops '(org-occur match)))
18832 ((functionp type)
18833 (org-let lprops '(funcall type match)))
18834 ((fboundp type)
18835 (org-let lprops '(funcall type match)))
18836 (t (error "Invalid custom agenda command type %s" type))))
18837 (org-run-agenda-series (nth 1 entry) (cddr entry))))
18838 ((equal keys "C") (customize-variable 'org-agenda-custom-commands))
18839 ((equal keys "a") (call-interactively 'org-agenda-list))
18840 ((equal keys "t") (call-interactively 'org-todo-list))
18841 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
18842 ((equal keys "m") (call-interactively 'org-tags-view))
18843 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
18844 ((equal keys "e") (call-interactively 'org-store-agenda-views))
18845 ((equal keys "L")
18846 (unless (org-mode-p)
18847 (error "This is not an Org-mode file"))
18848 (unless restriction
18849 (put 'org-agenda-files 'org-restrict (list bfn))
18850 (org-call-with-arg 'org-timeline arg)))
18851 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
18852 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
18853 ((equal keys "!") (customize-variable 'org-stuck-projects))
18854 (t (error "Invalid agenda key"))))))
18856 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
18857 "The user interface for selecting an agenda command."
18858 (catch 'exit
18859 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
18860 (restrict-ok (and bfn (org-mode-p)))
18861 (region-p (org-region-active-p))
18862 (custom org-agenda-custom-commands)
18863 (selstring "")
18864 restriction second-time
18865 c entry key type match prefixes rmheader header-end custom1 desc)
18866 (save-window-excursion
18867 (delete-other-windows)
18868 (org-switch-to-buffer-other-window " *Agenda Commands*")
18869 (erase-buffer)
18870 (insert (eval-when-compile
18871 (let ((header
18873 Press key for an agenda command: < Buffer,subtree/region restriction
18874 -------------------------------- > Remove restriction
18875 a Agenda for current week or day e Export agenda views
18876 t List of all TODO entries T Entries with special TODO kwd
18877 m Match a TAGS query M Like m, but only TODO entries
18878 L Timeline for current buffer # List stuck projects (!=configure)
18879 / Multi-occur C Configure custom agenda commands
18881 (start 0))
18882 (while (string-match
18883 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
18884 header start)
18885 (setq start (match-end 0))
18886 (add-text-properties (match-beginning 2) (match-end 2)
18887 '(face bold) header))
18888 header)))
18889 (setq header-end (move-marker (make-marker) (point)))
18890 (while t
18891 (setq custom1 custom)
18892 (when (eq rmheader t)
18893 (goto-line 1)
18894 (re-search-forward ":" nil t)
18895 (delete-region (match-end 0) (point-at-eol))
18896 (forward-char 1)
18897 (looking-at "-+")
18898 (delete-region (match-end 0) (point-at-eol))
18899 (move-marker header-end (match-end 0)))
18900 (goto-char header-end)
18901 (delete-region (point) (point-max))
18902 (while (setq entry (pop custom1))
18903 (setq key (car entry) desc (nth 1 entry)
18904 type (nth 2 entry) match (nth 3 entry))
18905 (if (> (length key) 1)
18906 (add-to-list 'prefixes (string-to-char key))
18907 (insert
18908 (format
18909 "\n%-4s%-14s: %s"
18910 (org-add-props (copy-sequence key)
18911 '(face bold))
18912 (cond
18913 ((string-match "\\S-" desc) desc)
18914 ((eq type 'agenda) "Agenda for current week or day")
18915 ((eq type 'alltodo) "List of all TODO entries")
18916 ((eq type 'stuck) "List of stuck projects")
18917 ((eq type 'todo) "TODO keyword")
18918 ((eq type 'tags) "Tags query")
18919 ((eq type 'tags-todo) "Tags (TODO)")
18920 ((eq type 'tags-tree) "Tags tree")
18921 ((eq type 'todo-tree) "TODO kwd tree")
18922 ((eq type 'occur-tree) "Occur tree")
18923 ((functionp type) (if (symbolp type)
18924 (symbol-name type)
18925 "Lambda expression"))
18926 (t "???"))
18927 (cond
18928 ((stringp match)
18929 (org-add-props match nil 'face 'org-warning))
18930 (match
18931 (format "set of %d commands" (length match)))
18932 (t ""))))))
18933 (when prefixes
18934 (mapc (lambda (x)
18935 (insert
18936 (format "\n%s %s"
18937 (org-add-props (char-to-string x)
18938 nil 'face 'bold)
18939 (or (cdr (assoc (concat selstring (char-to-string x))
18940 prefix-descriptions))
18941 "Prefix key"))))
18942 prefixes))
18943 (goto-char (point-min))
18944 (when (fboundp 'fit-window-to-buffer)
18945 (if second-time
18946 (if (not (pos-visible-in-window-p (point-max)))
18947 (fit-window-to-buffer))
18948 (setq second-time t)
18949 (fit-window-to-buffer)))
18950 (message "Press key for agenda command%s:"
18951 (if (or restrict-ok org-agenda-overriding-restriction)
18952 (if org-agenda-overriding-restriction
18953 " (restriction lock active)"
18954 (if restriction
18955 (format " (restricted to %s)" restriction)
18956 " (unrestricted)"))
18957 ""))
18958 (setq c (read-char-exclusive))
18959 (message "")
18960 (cond
18961 ((assoc (char-to-string c) custom)
18962 (setq selstring (concat selstring (char-to-string c)))
18963 (throw 'exit (cons selstring restriction)))
18964 ((memq c prefixes)
18965 (setq selstring (concat selstring (char-to-string c))
18966 prefixes nil
18967 rmheader (or rmheader t)
18968 custom (delq nil (mapcar
18969 (lambda (x)
18970 (if (or (= (length (car x)) 1)
18971 (/= (string-to-char (car x)) c))
18973 (cons (substring (car x) 1) (cdr x))))
18974 custom))))
18975 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
18976 (message "Restriction is only possible in Org-mode buffers")
18977 (ding) (sit-for 1))
18978 ((eq c ?1)
18979 (org-agenda-remove-restriction-lock 'noupdate)
18980 (setq restriction 'buffer))
18981 ((eq c ?0)
18982 (org-agenda-remove-restriction-lock 'noupdate)
18983 (setq restriction (if region-p 'region 'subtree)))
18984 ((eq c ?<)
18985 (org-agenda-remove-restriction-lock 'noupdate)
18986 (setq restriction
18987 (cond
18988 ((eq restriction 'buffer)
18989 (if region-p 'region 'subtree))
18990 ((memq restriction '(subtree region))
18991 nil)
18992 (t 'buffer))))
18993 ((eq c ?>)
18994 (org-agenda-remove-restriction-lock 'noupdate)
18995 (setq restriction nil))
18996 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?/)))
18997 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
18998 ((equal c ?q) (error "Abort"))
18999 (t (error "Invalid key %c" c))))))))
19001 (defun org-run-agenda-series (name series)
19002 (org-prepare-agenda name)
19003 (let* ((org-agenda-multi t)
19004 (redo (list 'org-run-agenda-series name (list 'quote series)))
19005 (cmds (car series))
19006 (gprops (nth 1 series))
19007 match ;; The byte compiler incorrectly complains about this. Keep it!
19008 cmd type lprops)
19009 (while (setq cmd (pop cmds))
19010 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19011 (cond
19012 ((eq type 'agenda)
19013 (org-let2 gprops lprops
19014 '(call-interactively 'org-agenda-list)))
19015 ((eq type 'alltodo)
19016 (org-let2 gprops lprops
19017 '(call-interactively 'org-todo-list)))
19018 ((eq type 'stuck)
19019 (org-let2 gprops lprops
19020 '(call-interactively 'org-agenda-list-stuck-projects)))
19021 ((eq type 'tags)
19022 (org-let2 gprops lprops
19023 '(org-tags-view current-prefix-arg match)))
19024 ((eq type 'tags-todo)
19025 (org-let2 gprops lprops
19026 '(org-tags-view '(4) match)))
19027 ((eq type 'todo)
19028 (org-let2 gprops lprops
19029 '(org-todo-list match)))
19030 ((fboundp type)
19031 (org-let2 gprops lprops
19032 '(funcall type match)))
19033 (t (error "Invalid type in command series"))))
19034 (widen)
19035 (setq org-agenda-redo-command redo)
19036 (goto-char (point-min)))
19037 (org-finalize-agenda))
19039 ;;;###autoload
19040 (defmacro org-batch-agenda (cmd-key &rest parameters)
19041 "Run an agenda command in batch mode and send the result to STDOUT.
19042 If CMD-KEY is a string of length 1, it is used as a key in
19043 `org-agenda-custom-commands' and triggers this command. If it is a
19044 longer string is is used as a tags/todo match string.
19045 Paramters are alternating variable names and values that will be bound
19046 before running the agenda command."
19047 (let (pars)
19048 (while parameters
19049 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19050 (if (> (length cmd-key) 2)
19051 (eval (list 'let (nreverse pars)
19052 (list 'org-tags-view nil cmd-key)))
19053 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19054 (set-buffer org-agenda-buffer-name)
19055 (princ (org-encode-for-stdout (buffer-string)))))
19057 (defun org-encode-for-stdout (string)
19058 (if (fboundp 'encode-coding-string)
19059 (encode-coding-string string buffer-file-coding-system)
19060 string))
19062 (defvar org-agenda-info nil)
19064 ;;;###autoload
19065 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19066 "Run an agenda command in batch mode and send the result to STDOUT.
19067 If CMD-KEY is a string of length 1, it is used as a key in
19068 `org-agenda-custom-commands' and triggers this command. If it is a
19069 longer string is is used as a tags/todo match string.
19070 Paramters are alternating variable names and values that will be bound
19071 before running the agenda command.
19073 The output gives a line for each selected agenda item. Each
19074 item is a list of comma-separated values, like this:
19076 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19078 category The category of the item
19079 head The headline, without TODO kwd, TAGS and PRIORITY
19080 type The type of the agenda entry, can be
19081 todo selected in TODO match
19082 tagsmatch selected in tags match
19083 diary imported from diary
19084 deadline a deadline on given date
19085 scheduled scheduled on given date
19086 timestamp entry has timestamp on given date
19087 closed entry was closed on given date
19088 upcoming-deadline warning about deadline
19089 past-scheduled forwarded scheduled item
19090 block entry has date block including g. date
19091 todo The todo keyword, if any
19092 tags All tags including inherited ones, separated by colons
19093 date The relevant date, like 2007-2-14
19094 time The time, like 15:00-16:50
19095 extra Sting with extra planning info
19096 priority-l The priority letter if any was given
19097 priority-n The computed numerical priority
19098 agenda-day The day in the agenda where this is listed"
19100 (let (pars)
19101 (while parameters
19102 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19103 (push (list 'org-agenda-remove-tags t) pars)
19104 (if (> (length cmd-key) 2)
19105 (eval (list 'let (nreverse pars)
19106 (list 'org-tags-view nil cmd-key)))
19107 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19108 (set-buffer org-agenda-buffer-name)
19109 (let* ((lines (org-split-string (buffer-string) "\n"))
19110 line)
19111 (while (setq line (pop lines))
19112 (catch 'next
19113 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19114 (setq org-agenda-info
19115 (org-fix-agenda-info (text-properties-at 0 line)))
19116 (princ
19117 (org-encode-for-stdout
19118 (mapconcat 'org-agenda-export-csv-mapper
19119 '(org-category txt type todo tags date time-of-day extra
19120 priority-letter priority agenda-day)
19121 ",")))
19122 (princ "\n"))))))
19124 (defun org-fix-agenda-info (props)
19125 "Make sure all properties on an agenda item have a canonical form,
19126 so the the export commands caneasily use it."
19127 (let (tmp re)
19128 (when (setq tmp (plist-get props 'tags))
19129 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19130 (when (setq tmp (plist-get props 'date))
19131 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19132 (let ((calendar-date-display-form '(year "-" month "-" day)))
19133 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19135 (setq tmp (calendar-date-string tmp)))
19136 (setq props (plist-put props 'date tmp)))
19137 (when (setq tmp (plist-get props 'day))
19138 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19139 (let ((calendar-date-display-form '(year "-" month "-" day)))
19140 (setq tmp (calendar-date-string tmp)))
19141 (setq props (plist-put props 'day tmp))
19142 (setq props (plist-put props 'agenda-day tmp)))
19143 (when (setq tmp (plist-get props 'txt))
19144 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19145 (plist-put props 'priority-letter (match-string 1 tmp))
19146 (setq tmp (replace-match "" t t tmp)))
19147 (when (and (setq re (plist-get props 'org-todo-regexp))
19148 (setq re (concat "\\`\\.*" re " ?"))
19149 (string-match re tmp))
19150 (plist-put props 'todo (match-string 1 tmp))
19151 (setq tmp (replace-match "" t t tmp)))
19152 (plist-put props 'txt tmp)))
19153 props)
19155 (defun org-agenda-export-csv-mapper (prop)
19156 (let ((res (plist-get org-agenda-info prop)))
19157 (setq res
19158 (cond
19159 ((not res) "")
19160 ((stringp res) res)
19161 (t (prin1-to-string res))))
19162 (while (string-match "," res)
19163 (setq res (replace-match ";" t t res)))
19164 (org-trim res)))
19167 ;;;###autoload
19168 (defun org-store-agenda-views (&rest parameters)
19169 (interactive)
19170 (eval (list 'org-batch-store-agenda-views)))
19172 ;; FIXME, why is this a macro?????
19173 ;;;###autoload
19174 (defmacro org-batch-store-agenda-views (&rest parameters)
19175 "Run all custom agenda commands that have a file argument."
19176 (let ((cmds org-agenda-custom-commands)
19177 (pop-up-frames nil)
19178 (dir default-directory)
19179 pars cmd thiscmdkey files opts)
19180 (while parameters
19181 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19182 (setq pars (reverse pars))
19183 (save-window-excursion
19184 (while cmds
19185 (setq cmd (pop cmds)
19186 thiscmdkey (car cmd)
19187 opts (nth 3 cmd)
19188 files (nth 4 cmd))
19189 (if (stringp files) (setq files (list files)))
19190 (when files
19191 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19192 (list 'org-agenda nil thiscmdkey)))
19193 (set-buffer org-agenda-buffer-name)
19194 (while files
19195 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19196 (list 'org-write-agenda
19197 (expand-file-name (pop files) dir) t))))
19198 (and (get-buffer org-agenda-buffer-name)
19199 (kill-buffer org-agenda-buffer-name)))))))
19201 (defun org-write-agenda (file &optional nosettings)
19202 "Write the current buffer (an agenda view) as a file.
19203 Depending on the extension of the file name, plain text (.txt),
19204 HTML (.html or .htm) or Postscript (.ps) is produced.
19205 If NOSETTINGS is given, do not scope the settings of
19206 `org-agenda-exporter-settings' into the export commands. This is used when
19207 the settings have already been scoped and we do not wish to overrule other,
19208 higher priority settings."
19209 (interactive "FWrite agenda to file: ")
19210 (if (not (file-writable-p file))
19211 (error "Cannot write agenda to file %s" file))
19212 (cond
19213 ((string-match "\\.html?\\'" file) (require 'htmlize))
19214 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19215 (org-let (if nosettings nil org-agenda-exporter-settings)
19216 '(save-excursion
19217 (save-window-excursion
19218 (cond
19219 ((string-match "\\.html?\\'" file)
19220 (set-buffer (htmlize-buffer (current-buffer)))
19222 (when (and org-agenda-export-html-style
19223 (string-match "<style>" org-agenda-export-html-style))
19224 ;; replace <style> section with org-agenda-export-html-style
19225 (goto-char (point-min))
19226 (kill-region (- (search-forward "<style") 6)
19227 (search-forward "</style>"))
19228 (insert org-agenda-export-html-style))
19229 (write-file file)
19230 (kill-buffer (current-buffer))
19231 (message "HTML written to %s" file))
19232 ((string-match "\\.ps\\'" file)
19233 (ps-print-buffer-with-faces file)
19234 (message "Postscript written to %s" file))
19236 (let ((bs (buffer-string)))
19237 (find-file file)
19238 (insert bs)
19239 (save-buffer 0)
19240 (kill-buffer (current-buffer))
19241 (message "Plain text written to %s" file))))))
19242 (set-buffer org-agenda-buffer-name)))
19244 (defmacro org-no-read-only (&rest body)
19245 "Inhibit read-only for BODY."
19246 `(let ((inhibit-read-only t)) ,@body))
19248 (defun org-check-for-org-mode ()
19249 "Make sure current buffer is in org-mode. Error if not."
19250 (or (org-mode-p)
19251 (error "Cannot execute org-mode agenda command on buffer in %s."
19252 major-mode)))
19254 (defun org-fit-agenda-window ()
19255 "Fit the window to the buffer size."
19256 (and (memq org-agenda-window-setup '(reorganize-frame))
19257 (fboundp 'fit-window-to-buffer)
19258 (fit-window-to-buffer
19260 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
19261 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
19263 ;;; Agenda file list
19265 (defun org-agenda-files (&optional unrestricted)
19266 "Get the list of agenda files.
19267 Optional UNRESTRICTED means return the full list even if a restriction
19268 is currently in place."
19269 (let ((files
19270 (cond
19271 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
19272 ((stringp org-agenda-files) (org-read-agenda-file-list))
19273 ((listp org-agenda-files) org-agenda-files)
19274 (t (error "Invalid value of `org-agenda-files'")))))
19275 (setq files (apply 'append
19276 (mapcar (lambda (f)
19277 (if (file-directory-p f)
19278 (directory-files f t "\\.org\\'")
19279 (list f)))
19280 files)))
19281 (if org-agenda-skip-unavailable-files
19282 (delq nil
19283 (mapcar (function
19284 (lambda (file)
19285 (and (file-readable-p file) file)))
19286 files))
19287 files))) ; `org-check-agenda-file' will remove them from the list
19289 (defun org-edit-agenda-file-list ()
19290 "Edit the list of agenda files.
19291 Depending on setup, this either uses customize to edit the variable
19292 `org-agenda-files', or it visits the file that is holding the list. In the
19293 latter case, the buffer is set up in a way that saving it automatically kills
19294 the buffer and restores the previous window configuration."
19295 (interactive)
19296 (if (stringp org-agenda-files)
19297 (let ((cw (current-window-configuration)))
19298 (find-file org-agenda-files)
19299 (org-set-local 'org-window-configuration cw)
19300 (org-add-hook 'after-save-hook
19301 (lambda ()
19302 (set-window-configuration
19303 (prog1 org-window-configuration
19304 (kill-buffer (current-buffer))))
19305 (org-install-agenda-files-menu)
19306 (message "New agenda file list installed"))
19307 nil 'local)
19308 (message (substitute-command-keys
19309 "Edit list and finish with \\[save-buffer]")))
19310 (customize-variable 'org-agenda-files)))
19312 (defun org-store-new-agenda-file-list (list)
19313 "Set new value for the agenda file list and save it correcly."
19314 (if (stringp org-agenda-files)
19315 (let ((f org-agenda-files) b)
19316 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
19317 (with-temp-file f
19318 (insert (mapconcat 'identity list "\n") "\n")))
19319 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
19320 (setq org-agenda-files list)
19321 (customize-save-variable 'org-agenda-files org-agenda-files))))
19323 (defun org-read-agenda-file-list ()
19324 "Read the list of agenda files from a file."
19325 (when (stringp org-agenda-files)
19326 (with-temp-buffer
19327 (insert-file-contents org-agenda-files)
19328 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
19331 ;;;###autoload
19332 (defun org-cycle-agenda-files ()
19333 "Cycle through the files in `org-agenda-files'.
19334 If the current buffer visits an agenda file, find the next one in the list.
19335 If the current buffer does not, find the first agenda file."
19336 (interactive)
19337 (let* ((fs (org-agenda-files t))
19338 (files (append fs (list (car fs))))
19339 (tcf (if buffer-file-name (file-truename buffer-file-name)))
19340 file)
19341 (unless files (error "No agenda files"))
19342 (catch 'exit
19343 (while (setq file (pop files))
19344 (if (equal (file-truename file) tcf)
19345 (when (car files)
19346 (find-file (car files))
19347 (throw 'exit t))))
19348 (find-file (car fs)))
19349 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
19351 (defun org-agenda-file-to-front (&optional to-end)
19352 "Move/add the current file to the top of the agenda file list.
19353 If the file is not present in the list, it is added to the front. If it is
19354 present, it is moved there. With optional argument TO-END, add/move to the
19355 end of the list."
19356 (interactive "P")
19357 (let ((org-agenda-skip-unavailable-files nil)
19358 (file-alist (mapcar (lambda (x)
19359 (cons (file-truename x) x))
19360 (org-agenda-files t)))
19361 (ctf (file-truename buffer-file-name))
19362 x had)
19363 (setq x (assoc ctf file-alist) had x)
19365 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
19366 (if to-end
19367 (setq file-alist (append (delq x file-alist) (list x)))
19368 (setq file-alist (cons x (delq x file-alist))))
19369 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
19370 (org-install-agenda-files-menu)
19371 (message "File %s to %s of agenda file list"
19372 (if had "moved" "added") (if to-end "end" "front"))))
19374 (defun org-remove-file (&optional file)
19375 "Remove current file from the list of files in variable `org-agenda-files'.
19376 These are the files which are being checked for agenda entries.
19377 Optional argument FILE means, use this file instead of the current."
19378 (interactive)
19379 (let* ((org-agenda-skip-unavailable-files nil)
19380 (file (or file buffer-file-name))
19381 (true-file (file-truename file))
19382 (afile (abbreviate-file-name file))
19383 (files (delq nil (mapcar
19384 (lambda (x)
19385 (if (equal true-file
19386 (file-truename x))
19387 nil x))
19388 (org-agenda-files t)))))
19389 (if (not (= (length files) (length (org-agenda-files t))))
19390 (progn
19391 (org-store-new-agenda-file-list files)
19392 (org-install-agenda-files-menu)
19393 (message "Removed file: %s" afile))
19394 (message "File was not in list: %s" afile))))
19396 (defun org-file-menu-entry (file)
19397 (vector file (list 'find-file file) t))
19399 (defun org-check-agenda-file (file)
19400 "Make sure FILE exists. If not, ask user what to do."
19401 (when (not (file-exists-p file))
19402 (message "non-existent file %s. [R]emove from list or [A]bort?"
19403 (abbreviate-file-name file))
19404 (let ((r (downcase (read-char-exclusive))))
19405 (cond
19406 ((equal r ?r)
19407 (org-remove-file file)
19408 (throw 'nextfile t))
19409 (t (error "Abort"))))))
19411 ;;; Agenda prepare and finalize
19413 (defvar org-agenda-multi nil) ; dynammically scoped
19414 (defvar org-agenda-buffer-name "*Org Agenda*")
19415 (defvar org-pre-agenda-window-conf nil)
19416 (defvar org-agenda-name nil)
19417 (defun org-prepare-agenda (&optional name)
19418 (setq org-todo-keywords-for-agenda nil)
19419 (setq org-done-keywords-for-agenda nil)
19420 (if org-agenda-multi
19421 (progn
19422 (setq buffer-read-only nil)
19423 (goto-char (point-max))
19424 (unless (or (bobp) org-agenda-compact-blocks)
19425 (insert "\n" (make-string (window-width) ?=) "\n"))
19426 (narrow-to-region (point) (point-max)))
19427 (org-agenda-maybe-reset-markers 'force)
19428 (org-prepare-agenda-buffers (org-agenda-files))
19429 (setq org-todo-keywords-for-agenda
19430 (org-uniquify org-todo-keywords-for-agenda))
19431 (setq org-done-keywords-for-agenda
19432 (org-uniquify org-done-keywords-for-agenda))
19433 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
19434 (awin (get-buffer-window abuf)))
19435 (cond
19436 ((equal (current-buffer) abuf) nil)
19437 (awin (select-window awin))
19438 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
19439 ((equal org-agenda-window-setup 'current-window)
19440 (switch-to-buffer abuf))
19441 ((equal org-agenda-window-setup 'other-window)
19442 (org-switch-to-buffer-other-window abuf))
19443 ((equal org-agenda-window-setup 'other-frame)
19444 (switch-to-buffer-other-frame abuf))
19445 ((equal org-agenda-window-setup 'reorganize-frame)
19446 (delete-other-windows)
19447 (org-switch-to-buffer-other-window abuf))))
19448 (setq buffer-read-only nil)
19449 (erase-buffer)
19450 (org-agenda-mode)
19451 (and name (not org-agenda-name)
19452 (org-set-local 'org-agenda-name name)))
19453 (setq buffer-read-only nil))
19455 (defun org-finalize-agenda ()
19456 "Finishing touch for the agenda buffer, called just before displaying it."
19457 (unless org-agenda-multi
19458 (save-excursion
19459 (let ((inhibit-read-only t))
19460 (goto-char (point-min))
19461 (while (org-activate-bracket-links (point-max))
19462 (add-text-properties (match-beginning 0) (match-end 0)
19463 '(face org-link)))
19464 (org-agenda-align-tags)
19465 (unless org-agenda-with-colors
19466 (remove-text-properties (point-min) (point-max) '(face nil))))
19467 (if (and (boundp 'org-overriding-columns-format)
19468 org-overriding-columns-format)
19469 (org-set-local 'org-overriding-columns-format
19470 org-overriding-columns-format))
19471 (if (and (boundp 'org-agenda-view-columns-initially)
19472 org-agenda-view-columns-initially)
19473 (org-agenda-columns))
19474 (when org-agenda-fontify-priorities
19475 (org-fontify-priorities))
19476 (run-hooks 'org-finalize-agenda-hook))))
19478 (defun org-fontify-priorities ()
19479 "Make highest priority lines bold, and lowest italic."
19480 (interactive)
19481 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
19482 (org-delete-overlay o)))
19483 (org-overlays-in (point-min) (point-max)))
19484 (save-excursion
19485 (let ((inhibit-read-only t)
19486 b e p ov h l)
19487 (goto-char (point-min))
19488 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
19489 (setq h (or (get-char-property (point) 'org-highest-priority)
19490 org-highest-priority)
19491 l (or (get-char-property (point) 'org-lowest-priority)
19492 org-lowest-priority)
19493 p (string-to-char (match-string 1))
19494 b (match-beginning 0) e (point-at-eol)
19495 ov (org-make-overlay b e))
19496 (org-overlay-put
19497 ov 'face
19498 (cond ((listp org-agenda-fontify-priorities)
19499 (cdr (assoc p org-agenda-fontify-priorities)))
19500 ((equal p l) 'italic)
19501 ((equal p h) 'bold)))
19502 (org-overlay-put ov 'org-type 'org-priority)))))
19504 (defun org-prepare-agenda-buffers (files)
19505 "Create buffers for all agenda files, protect archived trees and comments."
19506 (interactive)
19507 (let ((pa '(:org-archived t))
19508 (pc '(:org-comment t))
19509 (pall '(:org-archived t :org-comment t))
19510 (inhibit-read-only t)
19511 (rea (concat ":" org-archive-tag ":"))
19512 bmp file re)
19513 (save-excursion
19514 (save-restriction
19515 (while (setq file (pop files))
19516 (if (bufferp file)
19517 (set-buffer file)
19518 (org-check-agenda-file file)
19519 (set-buffer (org-get-agenda-file-buffer file)))
19520 (widen)
19521 (setq bmp (buffer-modified-p))
19522 (org-refresh-category-properties)
19523 (setq org-todo-keywords-for-agenda
19524 (append org-todo-keywords-for-agenda org-todo-keywords-1))
19525 (setq org-done-keywords-for-agenda
19526 (append org-done-keywords-for-agenda org-done-keywords))
19527 (save-excursion
19528 (remove-text-properties (point-min) (point-max) pall)
19529 (when org-agenda-skip-archived-trees
19530 (goto-char (point-min))
19531 (while (re-search-forward rea nil t)
19532 (if (org-on-heading-p t)
19533 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
19534 (goto-char (point-min))
19535 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
19536 (while (re-search-forward re nil t)
19537 (add-text-properties
19538 (match-beginning 0) (org-end-of-subtree t) pc)))
19539 (set-buffer-modified-p bmp))))))
19541 (defvar org-agenda-skip-function nil
19542 "Function to be called at each match during agenda construction.
19543 If this function returns nil, the current match should not be skipped.
19544 Otherwise, the function must return a position from where the search
19545 should be continued.
19546 This may also be a Lisp form, it will be evaluated.
19547 Never set this variable using `setq' or so, because then it will apply
19548 to all future agenda commands. Instead, bind it with `let' to scope
19549 it dynamically into the agenda-constructing command. A good way to set
19550 it is through options in org-agenda-custom-commands.")
19552 (defun org-agenda-skip ()
19553 "Throw to `:skip' in places that should be skipped.
19554 Also moves point to the end of the skipped region, so that search can
19555 continue from there."
19556 (let ((p (point-at-bol)) to fp)
19557 (and org-agenda-skip-archived-trees
19558 (get-text-property p :org-archived)
19559 (org-end-of-subtree t)
19560 (throw :skip t))
19561 (and (get-text-property p :org-comment)
19562 (org-end-of-subtree t)
19563 (throw :skip t))
19564 (if (equal (char-after p) ?#) (throw :skip t))
19565 (when (and (or (setq fp (functionp org-agenda-skip-function))
19566 (consp org-agenda-skip-function))
19567 (setq to (save-excursion
19568 (save-match-data
19569 (if fp
19570 (funcall org-agenda-skip-function)
19571 (eval org-agenda-skip-function))))))
19572 (goto-char to)
19573 (throw :skip t))))
19575 (defvar org-agenda-markers nil
19576 "List of all currently active markers created by `org-agenda'.")
19577 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
19578 "Creation time of the last agenda marker.")
19580 (defun org-agenda-new-marker (&optional pos)
19581 "Return a new agenda marker.
19582 Org-mode keeps a list of these markers and resets them when they are
19583 no longer in use."
19584 (let ((m (copy-marker (or pos (point)))))
19585 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
19586 (push m org-agenda-markers)
19589 (defun org-agenda-maybe-reset-markers (&optional force)
19590 "Reset markers created by `org-agenda'. But only if they are old enough."
19591 (if (or (and force (not org-agenda-multi))
19592 (> (- (time-to-seconds (current-time))
19593 org-agenda-last-marker-time)
19595 (while org-agenda-markers
19596 (move-marker (pop org-agenda-markers) nil))))
19598 (defun org-get-agenda-file-buffer (file)
19599 "Get a buffer visiting FILE. If the buffer needs to be created, add
19600 it to the list of buffers which might be released later."
19601 (let ((buf (org-find-base-buffer-visiting file)))
19602 (if buf
19603 buf ; just return it
19604 ;; Make a new buffer and remember it
19605 (setq buf (find-file-noselect file))
19606 (if buf (push buf org-agenda-new-buffers))
19607 buf)))
19609 (defun org-release-buffers (blist)
19610 "Release all buffers in list, asking the user for confirmation when needed.
19611 When a buffer is unmodified, it is just killed. When modified, it is saved
19612 \(if the user agrees) and then killed."
19613 (let (buf file)
19614 (while (setq buf (pop blist))
19615 (setq file (buffer-file-name buf))
19616 (when (and (buffer-modified-p buf)
19617 file
19618 (y-or-n-p (format "Save file %s? " file)))
19619 (with-current-buffer buf (save-buffer)))
19620 (kill-buffer buf))))
19622 (defun org-get-category (&optional pos)
19623 "Get the category applying to position POS."
19624 (get-text-property (or pos (point)) 'org-category))
19626 ;;; Agenda timeline
19628 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
19630 (defun org-timeline (&optional include-all)
19631 "Show a time-sorted view of the entries in the current org file.
19632 Only entries with a time stamp of today or later will be listed. With
19633 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
19634 under the current date.
19635 If the buffer contains an active region, only check the region for
19636 dates."
19637 (interactive "P")
19638 (require 'calendar)
19639 (org-compile-prefix-format 'timeline)
19640 (org-set-sorting-strategy 'timeline)
19641 (let* ((dopast t)
19642 (dotodo include-all)
19643 (doclosed org-agenda-show-log)
19644 (entry buffer-file-name)
19645 (date (calendar-current-date))
19646 (beg (if (org-region-active-p) (region-beginning) (point-min)))
19647 (end (if (org-region-active-p) (region-end) (point-max)))
19648 (day-numbers (org-get-all-dates beg end 'no-ranges
19649 t doclosed ; always include today
19650 org-timeline-show-empty-dates))
19651 (org-deadline-warning-days 0)
19652 (org-agenda-only-exact-dates t)
19653 (today (time-to-days (current-time)))
19654 (past t)
19655 args
19656 s e rtn d emptyp)
19657 (setq org-agenda-redo-command
19658 (list 'progn
19659 (list 'org-switch-to-buffer-other-window (current-buffer))
19660 (list 'org-timeline (list 'quote include-all))))
19661 (if (not dopast)
19662 ;; Remove past dates from the list of dates.
19663 (setq day-numbers (delq nil (mapcar (lambda(x)
19664 (if (>= x today) x nil))
19665 day-numbers))))
19666 (org-prepare-agenda (concat "Timeline "
19667 (file-name-nondirectory buffer-file-name)))
19668 (if doclosed (push :closed args))
19669 (push :timestamp args)
19670 (push :deadline args)
19671 (push :scheduled args)
19672 (push :sexp args)
19673 (if dotodo (push :todo args))
19674 (while (setq d (pop day-numbers))
19675 (if (and (listp d) (eq (car d) :omitted))
19676 (progn
19677 (setq s (point))
19678 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
19679 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
19680 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
19681 (if (and (>= d today)
19682 dopast
19683 past)
19684 (progn
19685 (setq past nil)
19686 (insert (make-string 79 ?-) "\n")))
19687 (setq date (calendar-gregorian-from-absolute d))
19688 (setq s (point))
19689 (setq rtn (and (not emptyp)
19690 (apply 'org-agenda-get-day-entries entry
19691 date args)))
19692 (if (or rtn (equal d today) org-timeline-show-empty-dates)
19693 (progn
19694 (insert
19695 (if (stringp org-agenda-format-date)
19696 (format-time-string org-agenda-format-date
19697 (org-time-from-absolute date))
19698 (funcall org-agenda-format-date date))
19699 "\n")
19700 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19701 (put-text-property s (1- (point)) 'org-date-line t)
19702 (if (equal d today)
19703 (put-text-property s (1- (point)) 'org-today t))
19704 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
19705 (put-text-property s (1- (point)) 'day d)))))
19706 (goto-char (point-min))
19707 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
19708 (point-min)))
19709 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
19710 (org-finalize-agenda)
19711 (setq buffer-read-only t)))
19713 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
19714 "Return a list of all relevant day numbers from BEG to END buffer positions.
19715 If NO-RANGES is non-nil, include only the start and end dates of a range,
19716 not every single day in the range. If FORCE-TODAY is non-nil, make
19717 sure that TODAY is included in the list. If INACTIVE is non-nil, also
19718 inactive time stamps (those in square brackets) are included.
19719 When EMPTY is non-nil, also include days without any entries."
19720 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
19721 dates dates1 date day day1 day2 ts1 ts2)
19722 (if force-today
19723 (setq dates (list (time-to-days (current-time)))))
19724 (save-excursion
19725 (goto-char beg)
19726 (while (re-search-forward re end t)
19727 (setq day (time-to-days (org-time-string-to-time
19728 (substring (match-string 1) 0 10))))
19729 (or (memq day dates) (push day dates)))
19730 (unless no-ranges
19731 (goto-char beg)
19732 (while (re-search-forward org-tr-regexp end t)
19733 (setq ts1 (substring (match-string 1) 0 10)
19734 ts2 (substring (match-string 2) 0 10)
19735 day1 (time-to-days (org-time-string-to-time ts1))
19736 day2 (time-to-days (org-time-string-to-time ts2)))
19737 (while (< (setq day1 (1+ day1)) day2)
19738 (or (memq day1 dates) (push day1 dates)))))
19739 (setq dates (sort dates '<))
19740 (when empty
19741 (while (setq day (pop dates))
19742 (setq day2 (car dates))
19743 (push day dates1)
19744 (when (and day2 empty)
19745 (if (or (eq empty t)
19746 (and (numberp empty) (<= (- day2 day) empty)))
19747 (while (< (setq day (1+ day)) day2)
19748 (push (list day) dates1))
19749 (push (cons :omitted (- day2 day)) dates1))))
19750 (setq dates (nreverse dates1)))
19751 dates)))
19753 ;;; Agenda Daily/Weekly
19755 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
19756 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
19757 (defvar org-agenda-last-arguments nil
19758 "The arguments of the previous call to org-agenda")
19759 (defvar org-starting-day nil) ; local variable in the agenda buffer
19760 (defvar org-agenda-span nil) ; local variable in the agenda buffer
19761 (defvar org-include-all-loc nil) ; local variable
19762 (defvar org-agenda-remove-date nil) ; dynamically scoped
19764 ;;;###autoload
19765 (defun org-agenda-list (&optional include-all start-day ndays)
19766 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
19767 The view will be for the current day or week, but from the overview buffer
19768 you will be able to go to other days/weeks.
19770 With one \\[universal-argument] prefix argument INCLUDE-ALL,
19771 all unfinished TODO items will also be shown, before the agenda.
19772 This feature is considered obsolete, please use the TODO list or a block
19773 agenda instead.
19775 With a numeric prefix argument in an interactive call, the agenda will
19776 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
19777 the number of days. NDAYS defaults to `org-agenda-ndays'.
19779 START-DAY defaults to TODAY, or to the most recent match for the weekday
19780 given in `org-agenda-start-on-weekday'."
19781 (interactive "P")
19782 (if (and (integerp include-all) (> include-all 0))
19783 (setq ndays include-all include-all nil))
19784 (setq ndays (or ndays org-agenda-ndays)
19785 start-day (or start-day org-agenda-start-day))
19786 (if org-agenda-overriding-arguments
19787 (setq include-all (car org-agenda-overriding-arguments)
19788 start-day (nth 1 org-agenda-overriding-arguments)
19789 ndays (nth 2 org-agenda-overriding-arguments)))
19790 (if (stringp start-day)
19791 ;; Convert to an absolute day number
19792 (setq start-day (time-to-days (org-read-date nil t start-day))))
19793 (setq org-agenda-last-arguments (list include-all start-day ndays))
19794 (org-compile-prefix-format 'agenda)
19795 (org-set-sorting-strategy 'agenda)
19796 (require 'calendar)
19797 (let* ((org-agenda-start-on-weekday
19798 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
19799 org-agenda-start-on-weekday nil))
19800 (thefiles (org-agenda-files))
19801 (files thefiles)
19802 (today (time-to-days
19803 (time-subtract (current-time)
19804 (list 0 (* 3600 org-extend-today-until) 0))))
19805 (sd (or start-day today))
19806 (start (if (or (null org-agenda-start-on-weekday)
19807 (< org-agenda-ndays 7))
19809 (let* ((nt (calendar-day-of-week
19810 (calendar-gregorian-from-absolute sd)))
19811 (n1 org-agenda-start-on-weekday)
19812 (d (- nt n1)))
19813 (- sd (+ (if (< d 0) 7 0) d)))))
19814 (day-numbers (list start))
19815 (day-cnt 0)
19816 (inhibit-redisplay (not debug-on-error))
19817 s e rtn rtnall file date d start-pos end-pos todayp nd)
19818 (setq org-agenda-redo-command
19819 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
19820 ;; Make the list of days
19821 (setq ndays (or ndays org-agenda-ndays)
19822 nd ndays)
19823 (while (> ndays 1)
19824 (push (1+ (car day-numbers)) day-numbers)
19825 (setq ndays (1- ndays)))
19826 (setq day-numbers (nreverse day-numbers))
19827 (org-prepare-agenda "Day/Week")
19828 (org-set-local 'org-starting-day (car day-numbers))
19829 (org-set-local 'org-include-all-loc include-all)
19830 (org-set-local 'org-agenda-span
19831 (org-agenda-ndays-to-span nd))
19832 (when (and (or include-all org-agenda-include-all-todo)
19833 (member today day-numbers))
19834 (setq files thefiles
19835 rtnall nil)
19836 (while (setq file (pop files))
19837 (catch 'nextfile
19838 (org-check-agenda-file file)
19839 (setq date (calendar-gregorian-from-absolute today)
19840 rtn (org-agenda-get-day-entries
19841 file date :todo))
19842 (setq rtnall (append rtnall rtn))))
19843 (when rtnall
19844 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
19845 (add-text-properties (point-min) (1- (point))
19846 (list 'face 'org-agenda-structure))
19847 (insert (org-finalize-agenda-entries rtnall) "\n")))
19848 (unless org-agenda-compact-blocks
19849 (setq s (point))
19850 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
19851 "-agenda:\n")
19852 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
19853 'org-date-line t)))
19854 (while (setq d (pop day-numbers))
19855 (setq date (calendar-gregorian-from-absolute d)
19856 s (point))
19857 (if (or (setq todayp (= d today))
19858 (and (not start-pos) (= d sd)))
19859 (setq start-pos (point))
19860 (if (and start-pos (not end-pos))
19861 (setq end-pos (point))))
19862 (setq files thefiles
19863 rtnall nil)
19864 (while (setq file (pop files))
19865 (catch 'nextfile
19866 (org-check-agenda-file file)
19867 (if org-agenda-show-log
19868 (setq rtn (org-agenda-get-day-entries
19869 file date
19870 :deadline :scheduled :timestamp :sexp :closed))
19871 (setq rtn (org-agenda-get-day-entries
19872 file date
19873 :deadline :scheduled :sexp :timestamp)))
19874 (setq rtnall (append rtnall rtn))))
19875 (if org-agenda-include-diary
19876 (progn
19877 (require 'diary-lib)
19878 (setq rtn (org-get-entries-from-diary date))
19879 (setq rtnall (append rtnall rtn))))
19880 (if (or rtnall org-agenda-show-all-dates)
19881 (progn
19882 (setq day-cnt (1+ day-cnt))
19883 (insert
19884 (if (stringp org-agenda-format-date)
19885 (format-time-string org-agenda-format-date
19886 (org-time-from-absolute date))
19887 (funcall org-agenda-format-date date))
19888 "\n")
19889 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19890 (put-text-property s (1- (point)) 'org-date-line t)
19891 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
19892 (if todayp (put-text-property s (1- (point)) 'org-today t))
19893 (if rtnall (insert
19894 (org-finalize-agenda-entries
19895 (org-agenda-add-time-grid-maybe
19896 rtnall nd todayp))
19897 "\n"))
19898 (put-text-property s (1- (point)) 'day d)
19899 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
19900 (goto-char (point-min))
19901 (org-fit-agenda-window)
19902 (unless (and (pos-visible-in-window-p (point-min))
19903 (pos-visible-in-window-p (point-max)))
19904 (goto-char (1- (point-max)))
19905 (recenter -1)
19906 (if (not (pos-visible-in-window-p (or start-pos 1)))
19907 (progn
19908 (goto-char (or start-pos 1))
19909 (recenter 1))))
19910 (goto-char (or start-pos 1))
19911 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
19912 (org-finalize-agenda)
19913 (setq buffer-read-only t)
19914 (message "")))
19916 (defun org-agenda-ndays-to-span (n)
19917 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
19919 ;;; Agenda TODO list
19921 (defvar org-select-this-todo-keyword nil)
19922 (defvar org-last-arg nil)
19924 ;;;###autoload
19925 (defun org-todo-list (arg)
19926 "Show all TODO entries from all agenda file in a single list.
19927 The prefix arg can be used to select a specific TODO keyword and limit
19928 the list to these. When using \\[universal-argument], you will be prompted
19929 for a keyword. A numeric prefix directly selects the Nth keyword in
19930 `org-todo-keywords-1'."
19931 (interactive "P")
19932 (require 'calendar)
19933 (org-compile-prefix-format 'todo)
19934 (org-set-sorting-strategy 'todo)
19935 (org-prepare-agenda "TODO")
19936 (let* ((today (time-to-days (current-time)))
19937 (date (calendar-gregorian-from-absolute today))
19938 (kwds org-todo-keywords-for-agenda)
19939 (completion-ignore-case t)
19940 (org-select-this-todo-keyword
19941 (if (stringp arg) arg
19942 (and arg (integerp arg) (> arg 0)
19943 (nth (1- arg) kwds))))
19944 rtn rtnall files file pos)
19945 (when (equal arg '(4))
19946 (setq org-select-this-todo-keyword
19947 (completing-read "Keyword (or KWD1|K2D2|...): "
19948 (mapcar 'list kwds) nil nil)))
19949 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
19950 (org-set-local 'org-last-arg arg)
19951 (setq org-agenda-redo-command
19952 '(org-todo-list (or current-prefix-arg org-last-arg)))
19953 (setq files (org-agenda-files)
19954 rtnall nil)
19955 (while (setq file (pop files))
19956 (catch 'nextfile
19957 (org-check-agenda-file file)
19958 (setq rtn (org-agenda-get-day-entries file date :todo))
19959 (setq rtnall (append rtnall rtn))))
19960 (if org-agenda-overriding-header
19961 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
19962 nil 'face 'org-agenda-structure) "\n")
19963 (insert "Global list of TODO items of type: ")
19964 (add-text-properties (point-min) (1- (point))
19965 (list 'face 'org-agenda-structure))
19966 (setq pos (point))
19967 (insert (or org-select-this-todo-keyword "ALL") "\n")
19968 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
19969 (setq pos (point))
19970 (unless org-agenda-multi
19971 (insert "Available with `N r': (0)ALL")
19972 (let ((n 0) s)
19973 (mapc (lambda (x)
19974 (setq s (format "(%d)%s" (setq n (1+ n)) x))
19975 (if (> (+ (current-column) (string-width s) 1) (frame-width))
19976 (insert "\n "))
19977 (insert " " s))
19978 kwds))
19979 (insert "\n"))
19980 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
19981 (when rtnall
19982 (insert (org-finalize-agenda-entries rtnall) "\n"))
19983 (goto-char (point-min))
19984 (org-fit-agenda-window)
19985 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
19986 (org-finalize-agenda)
19987 (setq buffer-read-only t)))
19989 ;;; Agenda tags match
19991 ;;;###autoload
19992 (defun org-tags-view (&optional todo-only match)
19993 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
19994 The prefix arg TODO-ONLY limits the search to TODO entries."
19995 (interactive "P")
19996 (org-compile-prefix-format 'tags)
19997 (org-set-sorting-strategy 'tags)
19998 (let* ((org-tags-match-list-sublevels
19999 (if todo-only t org-tags-match-list-sublevels))
20000 (completion-ignore-case t)
20001 rtn rtnall files file pos matcher
20002 buffer)
20003 (setq matcher (org-make-tags-matcher match)
20004 match (car matcher) matcher (cdr matcher))
20005 (org-prepare-agenda (concat "TAGS " match))
20006 (setq org-agenda-redo-command
20007 (list 'org-tags-view (list 'quote todo-only)
20008 (list 'if 'current-prefix-arg nil match)))
20009 (setq files (org-agenda-files)
20010 rtnall nil)
20011 (while (setq file (pop files))
20012 (catch 'nextfile
20013 (org-check-agenda-file file)
20014 (setq buffer (if (file-exists-p file)
20015 (org-get-agenda-file-buffer file)
20016 (error "No such file %s" file)))
20017 (if (not buffer)
20018 ;; If file does not exist, merror message to agenda
20019 (setq rtn (list
20020 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20021 rtnall (append rtnall rtn))
20022 (with-current-buffer buffer
20023 (unless (org-mode-p)
20024 (error "Agenda file %s is not in `org-mode'" file))
20025 (save-excursion
20026 (save-restriction
20027 (if org-agenda-restrict
20028 (narrow-to-region org-agenda-restrict-begin
20029 org-agenda-restrict-end)
20030 (widen))
20031 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20032 (setq rtnall (append rtnall rtn))))))))
20033 (if org-agenda-overriding-header
20034 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20035 nil 'face 'org-agenda-structure) "\n")
20036 (insert "Headlines with TAGS match: ")
20037 (add-text-properties (point-min) (1- (point))
20038 (list 'face 'org-agenda-structure))
20039 (setq pos (point))
20040 (insert match "\n")
20041 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20042 (setq pos (point))
20043 (unless org-agenda-multi
20044 (insert "Press `C-u r' to search again with new search string\n"))
20045 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20046 (when rtnall
20047 (insert (org-finalize-agenda-entries rtnall) "\n"))
20048 (goto-char (point-min))
20049 (org-fit-agenda-window)
20050 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20051 (org-finalize-agenda)
20052 (setq buffer-read-only t)))
20054 ;;; Agenda Finding stuck projects
20056 (defvar org-agenda-skip-regexp nil
20057 "Regular expression used in skipping subtrees for the agenda.
20058 This is basically a temporary global variable that can be set and then
20059 used by user-defined selections using `org-agenda-skip-function'.")
20061 (defvar org-agenda-overriding-header nil
20062 "When this is set during todo and tags searches, will replace header.")
20064 (defun org-agenda-skip-subtree-when-regexp-matches ()
20065 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20066 If yes, it returns the end position of this tree, causing agenda commands
20067 to skip this subtree. This is a function that can be put into
20068 `org-agenda-skip-function' for the duration of a command."
20069 (let ((end (save-excursion (org-end-of-subtree t)))
20070 skip)
20071 (save-excursion
20072 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20073 (and skip end)))
20075 (defun org-agenda-skip-entry-if (&rest conditions)
20076 "Skip entry if any of CONDITIONS is true.
20077 See `org-agenda-skip-if for details."
20078 (org-agenda-skip-if nil conditions))
20080 (defun org-agenda-skip-subtree-if (&rest conditions)
20081 "Skip entry if any of CONDITIONS is true.
20082 See `org-agenda-skip-if for details."
20083 (org-agenda-skip-if t conditions))
20085 (defun org-agenda-skip-if (subtree conditions)
20086 "Checks current entity for CONDITIONS.
20087 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20088 the entry, i.e. the text before the next heading is checked.
20090 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20091 from different tests. Valid conditions are:
20093 scheduled Check if there is a scheduled cookie
20094 notscheduled Check if there is no scheduled cookie
20095 deadline Check if there is a deadline
20096 notdeadline Check if there is no deadline
20097 regexp Check if regexp matches
20098 notregexp Check if regexp does not match.
20100 The regexp is taken from the conditions list, it must com right after the
20101 `regexp' of `notregexp' element.
20103 If any of these conditions is met, this function returns the end point of
20104 the entity, causing the search to continue from there. This is a function
20105 that can be put into `org-agenda-skip-function' for the duration of a command."
20106 (let (beg end m)
20107 (org-back-to-heading t)
20108 (setq beg (point)
20109 end (if subtree
20110 (progn (org-end-of-subtree t) (point))
20111 (progn (outline-next-heading) (1- (point)))))
20112 (goto-char beg)
20113 (and
20115 (and (memq 'scheduled conditions)
20116 (re-search-forward org-scheduled-time-regexp end t))
20117 (and (memq 'notscheduled conditions)
20118 (not (re-search-forward org-scheduled-time-regexp end t)))
20119 (and (memq 'deadline conditions)
20120 (re-search-forward org-deadline-time-regexp end t))
20121 (and (memq 'notdeadline conditions)
20122 (not (re-search-forward org-deadline-time-regexp end t)))
20123 (and (setq m (memq 'regexp conditions))
20124 (stringp (nth 1 m))
20125 (re-search-forward (nth 1 m) end t))
20126 (and (setq m (memq 'notregexp conditions))
20127 (stringp (nth 1 m))
20128 (not (re-search-forward (nth 1 m) end t))))
20129 end)))
20131 ;;;###autoload
20132 (defun org-agenda-list-stuck-projects (&rest ignore)
20133 "Create agenda view for projects that are stuck.
20134 Stuck projects are project that have no next actions. For the definitions
20135 of what a project is and how to check if it stuck, customize the variable
20136 `org-stuck-projects'.
20137 MATCH is being ignored."
20138 (interactive)
20139 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20140 ;; FIXME: we could have used org-agenda-skip-if here.
20141 (org-agenda-overriding-header "List of stuck projects: ")
20142 (matcher (nth 0 org-stuck-projects))
20143 (todo (nth 1 org-stuck-projects))
20144 (todo-wds (if (member "*" todo)
20145 (progn
20146 (org-prepare-agenda-buffers (org-agenda-files))
20147 (org-delete-all
20148 org-done-keywords-for-agenda
20149 (copy-sequence org-todo-keywords-for-agenda)))
20150 todo))
20151 (todo-re (concat "^\\*+[ \t]+\\("
20152 (mapconcat 'identity todo-wds "\\|")
20153 "\\)\\>"))
20154 (tags (nth 2 org-stuck-projects))
20155 (tags-re (if (member "*" tags)
20156 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20157 (concat "^\\*+ .*:\\("
20158 (mapconcat 'identity tags "\\|")
20159 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20160 (gen-re (nth 3 org-stuck-projects))
20161 (re-list
20162 (delq nil
20163 (list
20164 (if todo todo-re)
20165 (if tags tags-re)
20166 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20167 gen-re)))))
20168 (setq org-agenda-skip-regexp
20169 (if re-list
20170 (mapconcat 'identity re-list "\\|")
20171 (error "No information how to identify unstuck projects")))
20172 (org-tags-view nil matcher)
20173 (with-current-buffer org-agenda-buffer-name
20174 (setq org-agenda-redo-command
20175 '(org-agenda-list-stuck-projects
20176 (or current-prefix-arg org-last-arg))))))
20178 ;;; Diary integration
20180 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20182 (defun org-get-entries-from-diary (date)
20183 "Get the (Emacs Calendar) diary entries for DATE."
20184 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20185 (diary-display-hook '(fancy-diary-display))
20186 (pop-up-frames nil)
20187 (list-diary-entries-hook
20188 (cons 'org-diary-default-entry list-diary-entries-hook))
20189 (diary-file-name-prefix-function nil) ; turn this feature off
20190 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20191 entries
20192 (org-disable-agenda-to-diary t))
20193 (save-excursion
20194 (save-window-excursion
20195 (funcall (if (fboundp 'diary-list-entries)
20196 'diary-list-entries 'list-diary-entries)
20197 date 1)))
20198 (if (not (get-buffer fancy-diary-buffer))
20199 (setq entries nil)
20200 (with-current-buffer fancy-diary-buffer
20201 (setq buffer-read-only nil)
20202 (if (zerop (buffer-size))
20203 ;; No entries
20204 (setq entries nil)
20205 ;; Omit the date and other unnecessary stuff
20206 (org-agenda-cleanup-fancy-diary)
20207 ;; Add prefix to each line and extend the text properties
20208 (if (zerop (buffer-size))
20209 (setq entries nil)
20210 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20211 (set-buffer-modified-p nil)
20212 (kill-buffer fancy-diary-buffer)))
20213 (when entries
20214 (setq entries (org-split-string entries "\n"))
20215 (setq entries
20216 (mapcar
20217 (lambda (x)
20218 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20219 ;; Extend the text properties to the beginning of the line
20220 (org-add-props x (text-properties-at (1- (length x)) x)
20221 'type "diary" 'date date))
20222 entries)))))
20224 (defun org-agenda-cleanup-fancy-diary ()
20225 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20226 This gets rid of the date, the underline under the date, and
20227 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20228 date. It also removes lines that contain only whitespace."
20229 (goto-char (point-min))
20230 (if (looking-at ".*?:[ \t]*")
20231 (progn
20232 (replace-match "")
20233 (re-search-forward "\n=+$" nil t)
20234 (replace-match "")
20235 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20236 (re-search-forward "\n=+$" nil t)
20237 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20238 (goto-char (point-min))
20239 (while (re-search-forward "^ +\n" nil t)
20240 (replace-match ""))
20241 (goto-char (point-min))
20242 (if (re-search-forward "^Org-mode dummy\n?" nil t)
20243 (replace-match "")))
20245 ;; Make sure entries from the diary have the right text properties.
20246 (eval-after-load "diary-lib"
20247 '(if (boundp 'diary-modify-entry-list-string-function)
20248 ;; We can rely on the hook, nothing to do
20250 ;; Hook not avaiable, must use advice to make this work
20251 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
20252 "Make the position visible."
20253 (if (and org-disable-agenda-to-diary ;; called from org-agenda
20254 (stringp string)
20255 buffer-file-name)
20256 (setq string (org-modify-diary-entry-string string))))))
20258 (defun org-modify-diary-entry-string (string)
20259 "Add text properties to string, allowing org-mode to act on it."
20260 (org-add-props string nil
20261 'mouse-face 'highlight
20262 'keymap org-agenda-keymap
20263 'help-echo (if buffer-file-name
20264 (format "mouse-2 or RET jump to diary file %s"
20265 (abbreviate-file-name buffer-file-name))
20267 'org-agenda-diary-link t
20268 'org-marker (org-agenda-new-marker (point-at-bol))))
20270 (defun org-diary-default-entry ()
20271 "Add a dummy entry to the diary.
20272 Needed to avoid empty dates which mess up holiday display."
20273 ;; Catch the error if dealing with the new add-to-diary-alist
20274 (when org-disable-agenda-to-diary
20275 (condition-case nil
20276 (add-to-diary-list original-date "Org-mode dummy" "")
20277 (error
20278 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
20280 ;;;###autoload
20281 (defun org-diary (&rest args)
20282 "Return diary information from org-files.
20283 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
20284 It accesses org files and extracts information from those files to be
20285 listed in the diary. The function accepts arguments specifying what
20286 items should be listed. The following arguments are allowed:
20288 :timestamp List the headlines of items containing a date stamp or
20289 date range matching the selected date. Deadlines will
20290 also be listed, on the expiration day.
20292 :sexp List entries resulting from diary-like sexps.
20294 :deadline List any deadlines past due, or due within
20295 `org-deadline-warning-days'. The listing occurs only
20296 in the diary for *today*, not at any other date. If
20297 an entry is marked DONE, it is no longer listed.
20299 :scheduled List all items which are scheduled for the given date.
20300 The diary for *today* also contains items which were
20301 scheduled earlier and are not yet marked DONE.
20303 :todo List all TODO items from the org-file. This may be a
20304 long list - so this is not turned on by default.
20305 Like deadlines, these entries only show up in the
20306 diary for *today*, not at any other date.
20308 The call in the diary file should look like this:
20310 &%%(org-diary) ~/path/to/some/orgfile.org
20312 Use a separate line for each org file to check. Or, if you omit the file name,
20313 all files listed in `org-agenda-files' will be checked automatically:
20315 &%%(org-diary)
20317 If you don't give any arguments (as in the example above), the default
20318 arguments (:deadline :scheduled :timestamp :sexp) are used.
20319 So the example above may also be written as
20321 &%%(org-diary :deadline :timestamp :sexp :scheduled)
20323 The function expects the lisp variables `entry' and `date' to be provided
20324 by the caller, because this is how the calendar works. Don't use this
20325 function from a program - use `org-agenda-get-day-entries' instead."
20326 (org-agenda-maybe-reset-markers)
20327 (org-compile-prefix-format 'agenda)
20328 (org-set-sorting-strategy 'agenda)
20329 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20330 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
20331 (list entry)
20332 (org-agenda-files t)))
20333 file rtn results)
20334 (org-prepare-agenda-buffers files)
20335 ;; If this is called during org-agenda, don't return any entries to
20336 ;; the calendar. Org Agenda will list these entries itself.
20337 (if org-disable-agenda-to-diary (setq files nil))
20338 (while (setq file (pop files))
20339 (setq rtn (apply 'org-agenda-get-day-entries file date args))
20340 (setq results (append results rtn)))
20341 (if results
20342 (concat (org-finalize-agenda-entries results) "\n"))))
20344 ;;; Agenda entry finders
20346 (defun org-agenda-get-day-entries (file date &rest args)
20347 "Does the work for `org-diary' and `org-agenda'.
20348 FILE is the path to a file to be checked for entries. DATE is date like
20349 the one returned by `calendar-current-date'. ARGS are symbols indicating
20350 which kind of entries should be extracted. For details about these, see
20351 the documentation of `org-diary'."
20352 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20353 (let* ((org-startup-folded nil)
20354 (org-startup-align-all-tables nil)
20355 (buffer (if (file-exists-p file)
20356 (org-get-agenda-file-buffer file)
20357 (error "No such file %s" file)))
20358 arg results rtn)
20359 (if (not buffer)
20360 ;; If file does not exist, make sure an error message ends up in diary
20361 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20362 (with-current-buffer buffer
20363 (unless (org-mode-p)
20364 (error "Agenda file %s is not in `org-mode'" file))
20365 (let ((case-fold-search nil))
20366 (save-excursion
20367 (save-restriction
20368 (if org-agenda-restrict
20369 (narrow-to-region org-agenda-restrict-begin
20370 org-agenda-restrict-end)
20371 (widen))
20372 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
20373 (while (setq arg (pop args))
20374 (cond
20375 ((and (eq arg :todo)
20376 (equal date (calendar-current-date)))
20377 (setq rtn (org-agenda-get-todos))
20378 (setq results (append results rtn)))
20379 ((eq arg :timestamp)
20380 (setq rtn (org-agenda-get-blocks))
20381 (setq results (append results rtn))
20382 (setq rtn (org-agenda-get-timestamps))
20383 (setq results (append results rtn)))
20384 ((eq arg :sexp)
20385 (setq rtn (org-agenda-get-sexps))
20386 (setq results (append results rtn)))
20387 ((eq arg :scheduled)
20388 (setq rtn (org-agenda-get-scheduled))
20389 (setq results (append results rtn)))
20390 ((eq arg :closed)
20391 (setq rtn (org-agenda-get-closed))
20392 (setq results (append results rtn)))
20393 ((eq arg :deadline)
20394 (setq rtn (org-agenda-get-deadlines))
20395 (setq results (append results rtn))))))))
20396 results))))
20398 ;; FIXME: this works only if the cursor is *not* at the
20399 ;; beginning of the entry
20400 ;(defun org-entry-is-done-p ()
20401 ; "Is the current entry marked DONE?"
20402 ; (save-excursion
20403 ; (and (re-search-backward "[\r\n]\\*+ " nil t)
20404 ; (looking-at org-nl-done-regexp))))
20406 (defun org-entry-is-todo-p ()
20407 (member (org-get-todo-state) org-not-done-keywords))
20409 (defun org-entry-is-done-p ()
20410 (member (org-get-todo-state) org-done-keywords))
20412 (defun org-get-todo-state ()
20413 (save-excursion
20414 (org-back-to-heading t)
20415 (and (looking-at org-todo-line-regexp)
20416 (match-end 2)
20417 (match-string 2))))
20419 (defun org-at-date-range-p (&optional inactive-ok)
20420 "Is the cursor inside a date range?"
20421 (interactive)
20422 (save-excursion
20423 (catch 'exit
20424 (let ((pos (point)))
20425 (skip-chars-backward "^[<\r\n")
20426 (skip-chars-backward "<[")
20427 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20428 (>= (match-end 0) pos)
20429 (throw 'exit t))
20430 (skip-chars-backward "^<[\r\n")
20431 (skip-chars-backward "<[")
20432 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20433 (>= (match-end 0) pos)
20434 (throw 'exit t)))
20435 nil)))
20437 (defun org-agenda-get-todos ()
20438 "Return the TODO information for agenda display."
20439 (let* ((props (list 'face nil
20440 'done-face 'org-done
20441 'org-not-done-regexp org-not-done-regexp
20442 'org-todo-regexp org-todo-regexp
20443 'mouse-face 'highlight
20444 'keymap org-agenda-keymap
20445 'help-echo
20446 (format "mouse-2 or RET jump to org file %s"
20447 (abbreviate-file-name buffer-file-name))))
20448 ;; FIXME: get rid of the \n at some point but watch out
20449 (regexp (concat "^\\*+[ \t]+\\("
20450 (if org-select-this-todo-keyword
20451 (if (equal org-select-this-todo-keyword "*")
20452 org-todo-regexp
20453 (concat "\\<\\("
20454 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
20455 "\\)\\>"))
20456 org-not-done-regexp)
20457 "[^\n\r]*\\)"))
20458 marker priority category tags
20459 ee txt beg end)
20460 (goto-char (point-min))
20461 (while (re-search-forward regexp nil t)
20462 (catch :skip
20463 (save-match-data
20464 (beginning-of-line)
20465 (setq beg (point) end (progn (outline-next-heading) (point)))
20466 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
20467 (re-search-forward org-ts-regexp end t))
20468 (and org-agenda-todo-ignore-scheduled (goto-char beg)
20469 (re-search-forward org-scheduled-time-regexp end t))
20470 (and org-agenda-todo-ignore-deadlines (goto-char beg)
20471 (re-search-forward org-deadline-time-regexp end t)
20472 (org-deadline-close (match-string 1))))
20473 (goto-char (1+ beg))
20474 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
20475 (throw :skip nil)))
20476 (goto-char beg)
20477 (org-agenda-skip)
20478 (goto-char (match-beginning 1))
20479 (setq marker (org-agenda-new-marker (match-beginning 0))
20480 category (org-get-category)
20481 tags (org-get-tags-at (point))
20482 txt (org-format-agenda-item "" (match-string 1) category tags)
20483 priority (1+ (org-get-priority txt)))
20484 (org-add-props txt props
20485 'org-marker marker 'org-hd-marker marker
20486 'priority priority 'org-category category
20487 'type "todo")
20488 (push txt ee)
20489 (if org-agenda-todo-list-sublevels
20490 (goto-char (match-end 1))
20491 (org-end-of-subtree 'invisible))))
20492 (nreverse ee)))
20494 (defconst org-agenda-no-heading-message
20495 "No heading for this item in buffer or region.")
20497 (defun org-agenda-get-timestamps ()
20498 "Return the date stamp information for agenda display."
20499 (let* ((props (list 'face nil
20500 'org-not-done-regexp org-not-done-regexp
20501 'org-todo-regexp org-todo-regexp
20502 'mouse-face 'highlight
20503 'keymap org-agenda-keymap
20504 'help-echo
20505 (format "mouse-2 or RET jump to org file %s"
20506 (abbreviate-file-name buffer-file-name))))
20507 (d1 (calendar-absolute-from-gregorian date))
20508 (remove-re
20509 (concat
20510 (regexp-quote
20511 (format-time-string
20512 "<%Y-%m-%d"
20513 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20514 ".*?>"))
20515 (regexp
20516 (concat
20517 (regexp-quote
20518 (substring
20519 (format-time-string
20520 (car org-time-stamp-formats)
20521 (apply 'encode-time ; DATE bound by calendar
20522 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20523 0 11))
20524 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
20525 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
20526 marker hdmarker deadlinep scheduledp donep tmp priority category
20527 ee txt timestr tags b0 b3 e3 head)
20528 (goto-char (point-min))
20529 (while (re-search-forward regexp nil t)
20530 (setq b0 (match-beginning 0)
20531 b3 (match-beginning 3) e3 (match-end 3))
20532 (catch :skip
20533 (and (org-at-date-range-p) (throw :skip nil))
20534 (org-agenda-skip)
20535 (if (and (match-end 1)
20536 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
20537 (throw :skip nil))
20538 (if (and e3
20539 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
20540 (throw :skip nil))
20541 (setq marker (org-agenda-new-marker b0)
20542 category (org-get-category b0)
20543 tmp (buffer-substring (max (point-min)
20544 (- b0 org-ds-keyword-length))
20546 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
20547 deadlinep (string-match org-deadline-regexp tmp)
20548 scheduledp (string-match org-scheduled-regexp tmp)
20549 donep (org-entry-is-done-p))
20550 (if (or scheduledp deadlinep) (throw :skip t))
20551 (if (string-match ">" timestr)
20552 ;; substring should only run to end of time stamp
20553 (setq timestr (substring timestr 0 (match-end 0))))
20554 (save-excursion
20555 (if (re-search-backward "^\\*+ " nil t)
20556 (progn
20557 (goto-char (match-beginning 0))
20558 (setq hdmarker (org-agenda-new-marker)
20559 tags (org-get-tags-at))
20560 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20561 (setq head (match-string 1))
20562 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
20563 (setq txt (org-format-agenda-item
20564 nil head category tags timestr nil
20565 remove-re)))
20566 (setq txt org-agenda-no-heading-message))
20567 (setq priority (org-get-priority txt))
20568 (org-add-props txt props
20569 'org-marker marker 'org-hd-marker hdmarker)
20570 (org-add-props txt nil 'priority priority
20571 'org-category category 'date date
20572 'type "timestamp")
20573 (push txt ee))
20574 (outline-next-heading)))
20575 (nreverse ee)))
20577 (defun org-agenda-get-sexps ()
20578 "Return the sexp information for agenda display."
20579 (require 'diary-lib)
20580 (let* ((props (list 'face nil
20581 'mouse-face 'highlight
20582 'keymap org-agenda-keymap
20583 'help-echo
20584 (format "mouse-2 or RET jump to org file %s"
20585 (abbreviate-file-name buffer-file-name))))
20586 (regexp "^&?%%(")
20587 marker category ee txt tags entry result beg b sexp sexp-entry)
20588 (goto-char (point-min))
20589 (while (re-search-forward regexp nil t)
20590 (catch :skip
20591 (org-agenda-skip)
20592 (setq beg (match-beginning 0))
20593 (goto-char (1- (match-end 0)))
20594 (setq b (point))
20595 (forward-sexp 1)
20596 (setq sexp (buffer-substring b (point)))
20597 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
20598 (org-trim (match-string 1))
20599 ""))
20600 (setq result (org-diary-sexp-entry sexp sexp-entry date))
20601 (when result
20602 (setq marker (org-agenda-new-marker beg)
20603 category (org-get-category beg))
20605 (if (string-match "\\S-" result)
20606 (setq txt result)
20607 (setq txt "SEXP entry returned empty string"))
20609 (setq txt (org-format-agenda-item
20610 "" txt category tags 'time))
20611 (org-add-props txt props 'org-marker marker)
20612 (org-add-props txt nil
20613 'org-category category 'date date
20614 'type "sexp")
20615 (push txt ee))))
20616 (nreverse ee)))
20618 (defun org-agenda-get-closed ()
20619 "Return the logged TODO entries for agenda display."
20620 (let* ((props (list 'mouse-face 'highlight
20621 'org-not-done-regexp org-not-done-regexp
20622 'org-todo-regexp org-todo-regexp
20623 'keymap org-agenda-keymap
20624 'help-echo
20625 (format "mouse-2 or RET jump to org file %s"
20626 (abbreviate-file-name buffer-file-name))))
20627 (regexp (concat
20628 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
20629 (regexp-quote
20630 (substring
20631 (format-time-string
20632 (car org-time-stamp-formats)
20633 (apply 'encode-time ; DATE bound by calendar
20634 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20635 1 11))))
20636 marker hdmarker priority category tags closedp
20637 ee txt timestr)
20638 (goto-char (point-min))
20639 (while (re-search-forward regexp nil t)
20640 (catch :skip
20641 (org-agenda-skip)
20642 (setq marker (org-agenda-new-marker (match-beginning 0))
20643 closedp (equal (match-string 1) org-closed-string)
20644 category (org-get-category (match-beginning 0))
20645 timestr (buffer-substring (match-beginning 0) (point-at-eol))
20646 ;; donep (org-entry-is-done-p)
20648 (if (string-match "\\]" timestr)
20649 ;; substring should only run to end of time stamp
20650 (setq timestr (substring timestr 0 (match-end 0))))
20651 (save-excursion
20652 (if (re-search-backward "^\\*+ " nil t)
20653 (progn
20654 (goto-char (match-beginning 0))
20655 (setq hdmarker (org-agenda-new-marker)
20656 tags (org-get-tags-at))
20657 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20658 (setq txt (org-format-agenda-item
20659 (if closedp "Closed: " "Clocked: ")
20660 (match-string 1) category tags timestr)))
20661 (setq txt org-agenda-no-heading-message))
20662 (setq priority 100000)
20663 (org-add-props txt props
20664 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
20665 'priority priority 'org-category category
20666 'type "closed" 'date date
20667 'undone-face 'org-warning 'done-face 'org-done)
20668 (push txt ee))
20669 (outline-next-heading)))
20670 (nreverse ee)))
20672 (defun org-agenda-get-deadlines ()
20673 "Return the deadline information for agenda display."
20674 (let* ((props (list 'mouse-face 'highlight
20675 'org-not-done-regexp org-not-done-regexp
20676 'org-todo-regexp org-todo-regexp
20677 'keymap org-agenda-keymap
20678 'help-echo
20679 (format "mouse-2 or RET jump to org file %s"
20680 (abbreviate-file-name buffer-file-name))))
20681 (regexp org-deadline-time-regexp)
20682 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20683 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20684 d2 diff dfrac wdays pos pos1 category tags
20685 ee txt head face s upcomingp donep timestr)
20686 (goto-char (point-min))
20687 (while (re-search-forward regexp nil t)
20688 (catch :skip
20689 (org-agenda-skip)
20690 (setq s (match-string 1)
20691 pos (1- (match-beginning 1))
20692 d2 (org-time-string-to-absolute (match-string 1) d1)
20693 diff (- d2 d1)
20694 wdays (org-get-wdays s)
20695 dfrac (/ (* 1.0 (- wdays diff)) wdays)
20696 upcomingp (and todayp (> diff 0)))
20697 ;; When to show a deadline in the calendar:
20698 ;; If the expiration is within wdays warning time.
20699 ;; Past-due deadlines are only shown on the current date
20700 (if (or (and (<= diff wdays)
20701 (and todayp (not org-agenda-only-exact-dates)))
20702 (= diff 0))
20703 (save-excursion
20704 (setq category (org-get-category))
20705 (if (re-search-backward "^\\*+[ \t]+" nil t)
20706 (progn
20707 (goto-char (match-end 0))
20708 (setq pos1 (match-beginning 0))
20709 (setq tags (org-get-tags-at pos1))
20710 (setq head (buffer-substring-no-properties
20711 (point)
20712 (progn (skip-chars-forward "^\r\n")
20713 (point))))
20714 (setq donep (string-match org-looking-at-done-regexp head))
20715 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20716 (setq timestr
20717 (concat (substring s (match-beginning 1)) " "))
20718 (setq timestr 'time))
20719 (if (and donep
20720 (or org-agenda-skip-deadline-if-done
20721 (not (= diff 0))))
20722 (setq txt nil)
20723 (setq txt (org-format-agenda-item
20724 (if (= diff 0)
20725 (car org-agenda-deadline-leaders)
20726 (format (nth 1 org-agenda-deadline-leaders)
20727 diff))
20728 head category tags timestr))))
20729 (setq txt org-agenda-no-heading-message))
20730 (when txt
20731 (setq face (org-agenda-deadline-face dfrac))
20732 (org-add-props txt props
20733 'org-marker (org-agenda-new-marker pos)
20734 'org-hd-marker (org-agenda-new-marker pos1)
20735 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
20736 (org-get-priority txt))
20737 'org-category category
20738 'type (if upcomingp "upcoming-deadline" "deadline")
20739 'date (if upcomingp date d2)
20740 'face (if donep 'org-done face)
20741 'undone-face face 'done-face 'org-done)
20742 (push txt ee))))))
20743 (nreverse ee)))
20745 (defun org-agenda-deadline-face (fraction)
20746 "Return the face to displaying a deadline item.
20747 FRACTION is what fraction of the head-warning time has passed."
20748 (let ((faces org-agenda-deadline-faces) f)
20749 (catch 'exit
20750 (while (setq f (pop faces))
20751 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
20753 (defun org-agenda-get-scheduled ()
20754 "Return the scheduled information for agenda display."
20755 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
20756 'org-todo-regexp org-todo-regexp
20757 'done-face 'org-done
20758 'mouse-face 'highlight
20759 'keymap org-agenda-keymap
20760 'help-echo
20761 (format "mouse-2 or RET jump to org file %s"
20762 (abbreviate-file-name buffer-file-name))))
20763 (regexp org-scheduled-time-regexp)
20764 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20765 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20766 d2 diff pos pos1 category tags
20767 ee txt head pastschedp donep face timestr s)
20768 (goto-char (point-min))
20769 (while (re-search-forward regexp nil t)
20770 (catch :skip
20771 (org-agenda-skip)
20772 (setq s (match-string 1)
20773 pos (1- (match-beginning 1))
20774 d2 (org-time-string-to-absolute (match-string 1) d1)
20775 diff (- d2 d1))
20776 (setq pastschedp (and todayp (< diff 0)))
20777 ;; When to show a scheduled item in the calendar:
20778 ;; If it is on or past the date.
20779 (if (or (and (< diff 0)
20780 (and todayp (not org-agenda-only-exact-dates)))
20781 (= diff 0))
20782 (save-excursion
20783 (setq category (org-get-category))
20784 (if (re-search-backward "^\\*+[ \t]+" nil t)
20785 (progn
20786 (goto-char (match-end 0))
20787 (setq pos1 (match-beginning 0))
20788 (setq tags (org-get-tags-at))
20789 (setq head (buffer-substring-no-properties
20790 (point)
20791 (progn (skip-chars-forward "^\r\n") (point))))
20792 (setq donep (string-match org-looking-at-done-regexp head))
20793 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20794 (setq timestr
20795 (concat (substring s (match-beginning 1)) " "))
20796 (setq timestr 'time))
20797 (if (and donep
20798 (or org-agenda-skip-scheduled-if-done
20799 (not (= diff 0))))
20800 (setq txt nil)
20801 (setq txt (org-format-agenda-item
20802 (if (= diff 0)
20803 (car org-agenda-scheduled-leaders)
20804 (format (nth 1 org-agenda-scheduled-leaders)
20805 (- 1 diff)))
20806 head category tags timestr))))
20807 (setq txt org-agenda-no-heading-message))
20808 (when txt
20809 (setq face (if pastschedp
20810 'org-scheduled-previously
20811 'org-scheduled-today))
20812 (org-add-props txt props
20813 'undone-face face
20814 'face (if donep 'org-done face)
20815 'org-marker (org-agenda-new-marker pos)
20816 'org-hd-marker (org-agenda-new-marker pos1)
20817 'type (if pastschedp "past-scheduled" "scheduled")
20818 'date (if pastschedp d2 date)
20819 'priority (+ 94 (- 5 diff) (org-get-priority txt))
20820 'org-category category)
20821 (push txt ee))))))
20822 (nreverse ee)))
20824 (defun org-agenda-get-blocks ()
20825 "Return the date-range information for agenda display."
20826 (let* ((props (list 'face nil
20827 'org-not-done-regexp org-not-done-regexp
20828 'org-todo-regexp org-todo-regexp
20829 'mouse-face 'highlight
20830 'keymap org-agenda-keymap
20831 'help-echo
20832 (format "mouse-2 or RET jump to org file %s"
20833 (abbreviate-file-name buffer-file-name))))
20834 (regexp org-tr-regexp)
20835 (d0 (calendar-absolute-from-gregorian date))
20836 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
20837 donep head)
20838 (goto-char (point-min))
20839 (while (re-search-forward regexp nil t)
20840 (catch :skip
20841 (org-agenda-skip)
20842 (setq pos (point))
20843 (setq timestr (match-string 0)
20844 s1 (match-string 1)
20845 s2 (match-string 2)
20846 d1 (time-to-days (org-time-string-to-time s1))
20847 d2 (time-to-days (org-time-string-to-time s2)))
20848 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
20849 ;; Only allow days between the limits, because the normal
20850 ;; date stamps will catch the limits.
20851 (save-excursion
20852 (setq marker (org-agenda-new-marker (point)))
20853 (setq category (org-get-category))
20854 (if (re-search-backward "^\\*+ " nil t)
20855 (progn
20856 (goto-char (match-beginning 0))
20857 (setq hdmarker (org-agenda-new-marker (point)))
20858 (setq tags (org-get-tags-at))
20859 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20860 (setq head (match-string 1))
20861 (and org-agenda-skip-timestamp-if-done
20862 (org-entry-is-done-p)
20863 (throw :skip t))
20864 (setq txt (org-format-agenda-item
20865 (format (if (= d1 d2) "" "(%d/%d): ")
20866 (1+ (- d0 d1)) (1+ (- d2 d1)))
20867 head category tags
20868 (if (= d0 d1) timestr))))
20869 (setq txt org-agenda-no-heading-message))
20870 (org-add-props txt props
20871 'org-marker marker 'org-hd-marker hdmarker
20872 'type "block" 'date date
20873 'priority (org-get-priority txt) 'org-category category)
20874 (push txt ee)))
20875 (goto-char pos)))
20876 ;; Sort the entries by expiration date.
20877 (nreverse ee)))
20879 ;;; Agenda presentation and sorting
20881 (defconst org-plain-time-of-day-regexp
20882 (concat
20883 "\\(\\<[012]?[0-9]"
20884 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20885 "\\(--?"
20886 "\\(\\<[012]?[0-9]"
20887 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20888 "\\)?")
20889 "Regular expression to match a plain time or time range.
20890 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20891 groups carry important information:
20892 0 the full match
20893 1 the first time, range or not
20894 8 the second time, if it is a range.")
20896 (defconst org-plain-time-extension-regexp
20897 (concat
20898 "\\(\\<[012]?[0-9]"
20899 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20900 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
20901 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
20902 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20903 groups carry important information:
20904 0 the full match
20905 7 hours of duration
20906 9 minutes of duration")
20908 (defconst org-stamp-time-of-day-regexp
20909 (concat
20910 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
20911 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
20912 "\\(--?"
20913 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
20914 "Regular expression to match a timestamp time or time range.
20915 After a match, the following groups carry important information:
20916 0 the full match
20917 1 date plus weekday, for backreferencing to make sure both times on same day
20918 2 the first time, range or not
20919 4 the second time, if it is a range.")
20921 (defvar org-prefix-has-time nil
20922 "A flag, set by `org-compile-prefix-format'.
20923 The flag is set if the currently compiled format contains a `%t'.")
20924 (defvar org-prefix-has-tag nil
20925 "A flag, set by `org-compile-prefix-format'.
20926 The flag is set if the currently compiled format contains a `%T'.")
20928 (defun org-format-agenda-item (extra txt &optional category tags dotime
20929 noprefix remove-re)
20930 "Format TXT to be inserted into the agenda buffer.
20931 In particular, it adds the prefix and corresponding text properties. EXTRA
20932 must be a string and replaces the `%s' specifier in the prefix format.
20933 CATEGORY (string, symbol or nil) may be used to overrule the default
20934 category taken from local variable or file name. It will replace the `%c'
20935 specifier in the format. DOTIME, when non-nil, indicates that a
20936 time-of-day should be extracted from TXT for sorting of this entry, and for
20937 the `%t' specifier in the format. When DOTIME is a string, this string is
20938 searched for a time before TXT is. NOPREFIX is a flag and indicates that
20939 only the correctly processes TXT should be returned - this is used by
20940 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
20941 Any match of REMOVE-RE will be removed from TXT."
20942 (save-match-data
20943 ;; Diary entries sometimes have extra whitespace at the beginning
20944 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
20945 (let* ((category (or category
20946 org-category
20947 (if buffer-file-name
20948 (file-name-sans-extension
20949 (file-name-nondirectory buffer-file-name))
20950 "")))
20951 (tag (if tags (nth (1- (length tags)) tags) ""))
20952 time ; time and tag are needed for the eval of the prefix format
20953 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
20954 (time-of-day (and dotime (org-get-time-of-day ts)))
20955 stamp plain s0 s1 s2 rtn srp)
20956 (when (and dotime time-of-day org-prefix-has-time)
20957 ;; Extract starting and ending time and move them to prefix
20958 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
20959 (setq plain (string-match org-plain-time-of-day-regexp ts)))
20960 (setq s0 (match-string 0 ts)
20961 srp (and stamp (match-end 3))
20962 s1 (match-string (if plain 1 2) ts)
20963 s2 (match-string (if plain 8 (if srp 4 6)) ts))
20965 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
20966 ;; them, we might want to remove them there to avoid duplication.
20967 ;; The user can turn this off with a variable.
20968 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
20969 (string-match (concat (regexp-quote s0) " *") txt)
20970 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
20971 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
20972 (= (match-beginning 0) 0)
20974 (setq txt (replace-match "" nil nil txt))))
20975 ;; Normalize the time(s) to 24 hour
20976 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
20977 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
20979 (when (and s1 (not s2) org-agenda-default-appointment-duration
20980 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
20981 (let ((m (+ (string-to-number (match-string 2 s1))
20982 (* 60 (string-to-number (match-string 1 s1)))
20983 org-agenda-default-appointment-duration))
20985 (setq h (/ m 60) m (- m (* h 60)))
20986 (setq s2 (format "%02d:%02d" h m))))
20988 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
20989 txt)
20990 ;; Tags are in the string
20991 (if (or (eq org-agenda-remove-tags t)
20992 (and org-agenda-remove-tags
20993 org-prefix-has-tag))
20994 (setq txt (replace-match "" t t txt))
20995 (setq txt (replace-match
20996 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
20997 (match-string 2 txt))
20998 t t txt))))
21000 (when remove-re
21001 (while (string-match remove-re txt)
21002 (setq txt (replace-match "" t t txt))))
21004 ;; Create the final string
21005 (if noprefix
21006 (setq rtn txt)
21007 ;; Prepare the variables needed in the eval of the compiled format
21008 (setq time (cond (s2 (concat s1 "-" s2))
21009 (s1 (concat s1 "......"))
21010 (t ""))
21011 extra (or extra "")
21012 category (if (symbolp category) (symbol-name category) category))
21013 ;; Evaluate the compiled format
21014 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21016 ;; And finally add the text properties
21017 (org-add-props rtn nil
21018 'org-category (downcase category) 'tags tags
21019 'org-highest-priority org-highest-priority
21020 'org-lowest-priority org-lowest-priority
21021 'prefix-length (- (length rtn) (length txt))
21022 'time-of-day time-of-day
21023 'txt txt
21024 'time time
21025 'extra extra
21026 'dotime dotime))))
21028 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
21029 (defvar org-agenda-sorting-strategy-selected nil)
21031 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21032 (catch 'exit
21033 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21034 ((and todayp (member 'today (car org-agenda-time-grid))))
21035 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21036 ((member 'weekly (car org-agenda-time-grid)))
21037 (t (throw 'exit list)))
21038 (let* ((have (delq nil (mapcar
21039 (lambda (x) (get-text-property 1 'time-of-day x))
21040 list)))
21041 (string (nth 1 org-agenda-time-grid))
21042 (gridtimes (nth 2 org-agenda-time-grid))
21043 (req (car org-agenda-time-grid))
21044 (remove (member 'remove-match req))
21045 new time)
21046 (if (and (member 'require-timed req) (not have))
21047 ;; don't show empty grid
21048 (throw 'exit list))
21049 (while (setq time (pop gridtimes))
21050 (unless (and remove (member time have))
21051 (setq time (int-to-string time))
21052 (push (org-format-agenda-item
21053 nil string "" nil
21054 (concat (substring time 0 -2) ":" (substring time -2)))
21055 new)
21056 (put-text-property
21057 1 (length (car new)) 'face 'org-time-grid (car new))))
21058 (if (member 'time-up org-agenda-sorting-strategy-selected)
21059 (append new list)
21060 (append list new)))))
21062 (defun org-compile-prefix-format (key)
21063 "Compile the prefix format into a Lisp form that can be evaluated.
21064 The resulting form is returned and stored in the variable
21065 `org-prefix-format-compiled'."
21066 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21067 (let ((s (cond
21068 ((stringp org-agenda-prefix-format)
21069 org-agenda-prefix-format)
21070 ((assq key org-agenda-prefix-format)
21071 (cdr (assq key org-agenda-prefix-format)))
21072 (t " %-12:c%?-12t% s")))
21073 (start 0)
21074 varform vars var e c f opt)
21075 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21076 s start)
21077 (setq var (cdr (assoc (match-string 4 s)
21078 '(("c" . category) ("t" . time) ("s" . extra)
21079 ("T" . tag))))
21080 c (or (match-string 3 s) "")
21081 opt (match-beginning 1)
21082 start (1+ (match-beginning 0)))
21083 (if (equal var 'time) (setq org-prefix-has-time t))
21084 (if (equal var 'tag) (setq org-prefix-has-tag t))
21085 (setq f (concat "%" (match-string 2 s) "s"))
21086 (if opt
21087 (setq varform
21088 `(if (equal "" ,var)
21090 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21091 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21092 (setq s (replace-match "%s" t nil s))
21093 (push varform vars))
21094 (setq vars (nreverse vars))
21095 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21097 (defun org-set-sorting-strategy (key)
21098 (if (symbolp (car org-agenda-sorting-strategy))
21099 ;; the old format
21100 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21101 (setq org-agenda-sorting-strategy-selected
21102 (or (cdr (assq key org-agenda-sorting-strategy))
21103 (cdr (assq 'agenda org-agenda-sorting-strategy))
21104 '(time-up category-keep priority-down)))))
21106 (defun org-get-time-of-day (s &optional string mod24)
21107 "Check string S for a time of day.
21108 If found, return it as a military time number between 0 and 2400.
21109 If not found, return nil.
21110 The optional STRING argument forces conversion into a 5 character wide string
21111 HH:MM."
21112 (save-match-data
21113 (when
21114 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21115 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21116 (let* ((h (string-to-number (match-string 1 s)))
21117 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21118 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21119 (am-p (equal ampm "am"))
21120 (h1 (cond ((not ampm) h)
21121 ((= h 12) (if am-p 0 12))
21122 (t (+ h (if am-p 0 12)))))
21123 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21124 (mod h1 24) h1))
21125 (t0 (+ (* 100 h2) m))
21126 (t1 (concat (if (>= h1 24) "+" " ")
21127 (if (< t0 100) "0" "")
21128 (if (< t0 10) "0" "")
21129 (int-to-string t0))))
21130 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21132 (defun org-finalize-agenda-entries (list &optional nosort)
21133 "Sort and concatenate the agenda items."
21134 (setq list (mapcar 'org-agenda-highlight-todo list))
21135 (if nosort
21136 list
21137 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21139 (defun org-agenda-highlight-todo (x)
21140 (let (re pl)
21141 (if (eq x 'line)
21142 (save-excursion
21143 (beginning-of-line 1)
21144 (setq re (get-text-property (point) 'org-todo-regexp))
21145 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21146 (and (looking-at (concat "[ \t]*\\.*" re))
21147 (add-text-properties (match-beginning 0) (match-end 0)
21148 (list 'face (org-get-todo-face 0)))))
21149 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21150 pl (get-text-property 0 'prefix-length x))
21151 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
21152 (add-text-properties
21153 (or (match-end 1) (match-end 0)) (match-end 0)
21154 (list 'face (org-get-todo-face (match-string 2 x)))
21156 x)))
21158 (defsubst org-cmp-priority (a b)
21159 "Compare the priorities of string A and B."
21160 (let ((pa (or (get-text-property 1 'priority a) 0))
21161 (pb (or (get-text-property 1 'priority b) 0)))
21162 (cond ((> pa pb) +1)
21163 ((< pa pb) -1)
21164 (t nil))))
21166 (defsubst org-cmp-category (a b)
21167 "Compare the string values of categories of strings A and B."
21168 (let ((ca (or (get-text-property 1 'org-category a) ""))
21169 (cb (or (get-text-property 1 'org-category b) "")))
21170 (cond ((string-lessp ca cb) -1)
21171 ((string-lessp cb ca) +1)
21172 (t nil))))
21174 (defsubst org-cmp-tag (a b)
21175 "Compare the string values of categories of strings A and B."
21176 (let ((ta (car (last (get-text-property 1 'tags a))))
21177 (tb (car (last (get-text-property 1 'tags b)))))
21178 (cond ((not ta) +1)
21179 ((not tb) -1)
21180 ((string-lessp ta tb) -1)
21181 ((string-lessp tb ta) +1)
21182 (t nil))))
21184 (defsubst org-cmp-time (a b)
21185 "Compare the time-of-day values of strings A and B."
21186 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21187 (ta (or (get-text-property 1 'time-of-day a) def))
21188 (tb (or (get-text-property 1 'time-of-day b) def)))
21189 (cond ((< ta tb) -1)
21190 ((< tb ta) +1)
21191 (t nil))))
21193 (defun org-entries-lessp (a b)
21194 "Predicate for sorting agenda entries."
21195 ;; The following variables will be used when the form is evaluated.
21196 ;; So even though the compiler complains, keep them.
21197 (let* ((time-up (org-cmp-time a b))
21198 (time-down (if time-up (- time-up) nil))
21199 (priority-up (org-cmp-priority a b))
21200 (priority-down (if priority-up (- priority-up) nil))
21201 (category-up (org-cmp-category a b))
21202 (category-down (if category-up (- category-up) nil))
21203 (category-keep (if category-up +1 nil))
21204 (tag-up (org-cmp-tag a b))
21205 (tag-down (if tag-up (- tag-up) nil)))
21206 (cdr (assoc
21207 (eval (cons 'or org-agenda-sorting-strategy-selected))
21208 '((-1 . t) (1 . nil) (nil . nil))))))
21210 ;;; Agenda restriction lock
21212 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
21213 "Overlay to mark the headline to which arenda commands are restricted.")
21214 (org-overlay-put org-agenda-restriction-lock-overlay
21215 'face 'org-agenda-restriction-lock)
21216 (org-overlay-put org-agenda-restriction-lock-overlay
21217 'help-echo "Agendas are currently limited to this subtree.")
21218 (org-detach-overlay org-agenda-restriction-lock-overlay)
21219 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
21220 "Overlay marking the agenda restriction line in speedbar.")
21221 (org-overlay-put org-speedbar-restriction-lock-overlay
21222 'face 'org-agenda-restriction-lock)
21223 (org-overlay-put org-speedbar-restriction-lock-overlay
21224 'help-echo "Agendas are currently limited to this item.")
21225 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21227 (defun org-agenda-set-restriction-lock (&optional type)
21228 "Set restriction lock for agenda, to current subtree or file.
21229 Restriction will be the file if TYPE is `file', or if type is the
21230 universal prefix '(4), or if the cursor is before the first headline
21231 in the file. Otherwise, restriction will be to the current subtree."
21232 (interactive "P")
21233 (and (equal type '(4)) (setq type 'file))
21234 (setq type (cond
21235 (type type)
21236 ((org-at-heading-p) 'subtree)
21237 ((condition-case nil (org-back-to-heading t) (error nil))
21238 'subtree)
21239 (t 'file)))
21240 (if (eq type 'subtree)
21241 (progn
21242 (setq org-agenda-restrict t)
21243 (setq org-agenda-overriding-restriction 'subtree)
21244 (put 'org-agenda-files 'org-restrict
21245 (list (buffer-file-name (buffer-base-buffer))))
21246 (org-back-to-heading t)
21247 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
21248 (move-marker org-agenda-restrict-begin (point))
21249 (move-marker org-agenda-restrict-end
21250 (save-excursion (org-end-of-subtree t)))
21251 (message "Locking agenda restriction to subtree"))
21252 (put 'org-agenda-files 'org-restrict
21253 (list (buffer-file-name (buffer-base-buffer))))
21254 (setq org-agenda-restrict nil)
21255 (setq org-agenda-overriding-restriction 'file)
21256 (move-marker org-agenda-restrict-begin nil)
21257 (move-marker org-agenda-restrict-end nil)
21258 (message "Locking agenda restriction to file"))
21259 (setq current-prefix-arg nil)
21260 (org-agenda-maybe-redo))
21262 (defun org-agenda-remove-restriction-lock (&optional noupdate)
21263 "Remove the agenda restriction lock."
21264 (interactive "P")
21265 (org-detach-overlay org-agenda-restriction-lock-overlay)
21266 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21267 (setq org-agenda-overriding-restriction nil)
21268 (setq org-agenda-restrict nil)
21269 (put 'org-agenda-files 'org-restrict nil)
21270 (move-marker org-agenda-restrict-begin nil)
21271 (move-marker org-agenda-restrict-end nil)
21272 (setq current-prefix-arg nil)
21273 (message "Agenda restriction lock removed")
21274 (or noupdate (org-agenda-maybe-redo)))
21276 (defun org-agenda-maybe-redo ()
21277 "If there is any window showing the agenda view, update it."
21278 (let ((w (get-buffer-window org-agenda-buffer-name t))
21279 (w0 (selected-window)))
21280 (when w
21281 (select-window w)
21282 (org-agenda-redo)
21283 (select-window w0)
21284 (if org-agenda-overriding-restriction
21285 (message "Agenda view shifted to new %s restriction"
21286 org-agenda-overriding-restriction)
21287 (message "Agenda restriction lock removed")))))
21289 ;;; Agenda commands
21291 (defun org-agenda-check-type (error &rest types)
21292 "Check if agenda buffer is of allowed type.
21293 If ERROR is non-nil, throw an error, otherwise just return nil."
21294 (if (memq org-agenda-type types)
21296 (if error
21297 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
21298 nil)))
21300 (defun org-agenda-quit ()
21301 "Exit agenda by removing the window or the buffer."
21302 (interactive)
21303 (let ((buf (current-buffer)))
21304 (if (not (one-window-p)) (delete-window))
21305 (kill-buffer buf)
21306 (org-agenda-maybe-reset-markers 'force)
21307 (org-columns-remove-overlays))
21308 ;; Maybe restore the pre-agenda window configuration.
21309 (and org-agenda-restore-windows-after-quit
21310 (not (eq org-agenda-window-setup 'other-frame))
21311 org-pre-agenda-window-conf
21312 (set-window-configuration org-pre-agenda-window-conf)))
21314 (defun org-agenda-exit ()
21315 "Exit agenda by removing the window or the buffer.
21316 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
21317 Org-mode buffers visited directly by the user will not be touched."
21318 (interactive)
21319 (org-release-buffers org-agenda-new-buffers)
21320 (setq org-agenda-new-buffers nil)
21321 (org-agenda-quit))
21323 (defun org-agenda-execute (arg)
21324 "Execute another agenda command, keeping same window.\\<global-map>
21325 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
21326 (interactive "P")
21327 (let ((org-agenda-window-setup 'current-window))
21328 (org-agenda arg)))
21330 (defun org-save-all-org-buffers ()
21331 "Save all Org-mode buffers without user confirmation."
21332 (interactive)
21333 (message "Saving all Org-mode buffers...")
21334 (save-some-buffers t 'org-mode-p)
21335 (message "Saving all Org-mode buffers... done"))
21337 (defun org-agenda-redo ()
21338 "Rebuild Agenda.
21339 When this is the global TODO list, a prefix argument will be interpreted."
21340 (interactive)
21341 (let* ((org-agenda-keep-modes t)
21342 (line (org-current-line))
21343 (window-line (- line (org-current-line (window-start))))
21344 (lprops (get 'org-agenda-redo-command 'org-lprops)))
21345 (message "Rebuilding agenda buffer...")
21346 (org-let lprops '(eval org-agenda-redo-command))
21347 (setq org-agenda-undo-list nil
21348 org-agenda-pending-undo-list nil)
21349 (message "Rebuilding agenda buffer...done")
21350 (goto-line line)
21351 (recenter window-line)))
21353 (defun org-agenda-goto-date (date)
21354 "Jump to DATE in agenda."
21355 (interactive (list (org-read-date)))
21356 (org-agenda-list nil date))
21358 (defun org-agenda-goto-today ()
21359 "Go to today."
21360 (interactive)
21361 (org-agenda-check-type t 'timeline 'agenda)
21362 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
21363 (cond
21364 (tdpos (goto-char tdpos))
21365 ((eq org-agenda-type 'agenda)
21366 (let* ((sd (time-to-days
21367 (time-subtract (current-time)
21368 (list 0 (* 3600 org-extend-today-until) 0))))
21369 (comp (org-agenda-compute-time-span sd org-agenda-span))
21370 (org-agenda-overriding-arguments org-agenda-last-arguments))
21371 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
21372 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
21373 (org-agenda-redo)
21374 (org-agenda-find-same-or-today-or-agenda)))
21375 (t (error "Cannot find today")))))
21377 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
21378 (goto-char
21379 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
21380 (text-property-any (point-min) (point-max) 'org-today t)
21381 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
21382 (point-min))))
21384 (defun org-agenda-later (arg)
21385 "Go forward in time by thee current span.
21386 With prefix ARG, go forward that many times the current span."
21387 (interactive "p")
21388 (org-agenda-check-type t 'agenda)
21389 (let* ((span org-agenda-span)
21390 (sd org-starting-day)
21391 (greg (calendar-gregorian-from-absolute sd))
21392 (cnt (get-text-property (point) 'org-day-cnt))
21393 greg2 nd)
21394 (cond
21395 ((eq span 'day)
21396 (setq sd (+ arg sd) nd 1))
21397 ((eq span 'week)
21398 (setq sd (+ (* 7 arg) sd) nd 7))
21399 ((eq span 'month)
21400 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
21401 sd (calendar-absolute-from-gregorian greg2))
21402 (setcar greg2 (1+ (car greg2)))
21403 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
21404 ((eq span 'year)
21405 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
21406 sd (calendar-absolute-from-gregorian greg2))
21407 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
21408 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
21409 (let ((org-agenda-overriding-arguments
21410 (list (car org-agenda-last-arguments) sd nd t)))
21411 (org-agenda-redo)
21412 (org-agenda-find-same-or-today-or-agenda cnt))))
21414 (defun org-agenda-earlier (arg)
21415 "Go backward in time by the current span.
21416 With prefix ARG, go backward that many times the current span."
21417 (interactive "p")
21418 (org-agenda-later (- arg)))
21420 (defun org-agenda-day-view ()
21421 "Switch to daily view for agenda."
21422 (interactive)
21423 (setq org-agenda-ndays 1)
21424 (org-agenda-change-time-span 'day))
21425 (defun org-agenda-week-view ()
21426 "Switch to daily view for agenda."
21427 (interactive)
21428 (setq org-agenda-ndays 7)
21429 (org-agenda-change-time-span 'week))
21430 (defun org-agenda-month-view ()
21431 "Switch to daily view for agenda."
21432 (interactive)
21433 (org-agenda-change-time-span 'month))
21434 (defun org-agenda-year-view ()
21435 "Switch to daily view for agenda."
21436 (interactive)
21437 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
21438 (org-agenda-change-time-span 'year)
21439 (error "Abort")))
21441 (defun org-agenda-change-time-span (span)
21442 "Change the agenda view to SPAN.
21443 SPAN may be `day', `week', `month', `year'."
21444 (org-agenda-check-type t 'agenda)
21445 (if (equal org-agenda-span span)
21446 (error "Viewing span is already \"%s\"" span))
21447 (let* ((sd (or (get-text-property (point) 'day)
21448 org-starting-day))
21449 (computed (org-agenda-compute-time-span sd span))
21450 (org-agenda-overriding-arguments
21451 (list (car org-agenda-last-arguments)
21452 (car computed) (cdr computed) t)))
21453 (org-agenda-redo)
21454 (org-agenda-find-same-or-today-or-agenda))
21455 (org-agenda-set-mode-name)
21456 (message "Switched to %s view" span))
21458 (defun org-agenda-compute-time-span (sd span)
21459 "Compute starting date and number of days for agenda.
21460 SPAN may be `day', `week', `month', `year'. The return value
21461 is a cons cell with the starting date and the number of days,
21462 so that the date SD will be in that range."
21463 (let* ((greg (calendar-gregorian-from-absolute sd))
21465 (cond
21466 ((eq span 'day)
21467 (setq nd 1))
21468 ((eq span 'week)
21469 (let* ((nt (calendar-day-of-week
21470 (calendar-gregorian-from-absolute sd)))
21471 (d (if org-agenda-start-on-weekday
21472 (- nt org-agenda-start-on-weekday)
21473 0)))
21474 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
21475 (setq nd 7)))
21476 ((eq span 'month)
21477 (setq sd (calendar-absolute-from-gregorian
21478 (list (car greg) 1 (nth 2 greg)))
21479 nd (- (calendar-absolute-from-gregorian
21480 (list (1+ (car greg)) 1 (nth 2 greg)))
21481 sd)))
21482 ((eq span 'year)
21483 (setq sd (calendar-absolute-from-gregorian
21484 (list 1 1 (nth 2 greg)))
21485 nd (- (calendar-absolute-from-gregorian
21486 (list 1 1 (1+ (nth 2 greg))))
21487 sd))))
21488 (cons sd nd)))
21490 ;; FIXME: does not work if user makes date format that starts with a blank
21491 (defun org-agenda-next-date-line (&optional arg)
21492 "Jump to the next line indicating a date in agenda buffer."
21493 (interactive "p")
21494 (org-agenda-check-type t 'agenda 'timeline)
21495 (beginning-of-line 1)
21496 (if (looking-at "^\\S-") (forward-char 1))
21497 (if (not (re-search-forward "^\\S-" nil t arg))
21498 (progn
21499 (backward-char 1)
21500 (error "No next date after this line in this buffer")))
21501 (goto-char (match-beginning 0)))
21503 (defun org-agenda-previous-date-line (&optional arg)
21504 "Jump to the previous line indicating a date in agenda buffer."
21505 (interactive "p")
21506 (org-agenda-check-type t 'agenda 'timeline)
21507 (beginning-of-line 1)
21508 (if (not (re-search-backward "^\\S-" nil t arg))
21509 (error "No previous date before this line in this buffer")))
21511 ;; Initialize the highlight
21512 (defvar org-hl (org-make-overlay 1 1))
21513 (org-overlay-put org-hl 'face 'highlight)
21515 (defun org-highlight (begin end &optional buffer)
21516 "Highlight a region with overlay."
21517 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
21518 org-hl begin end (or buffer (current-buffer))))
21520 (defun org-unhighlight ()
21521 "Detach overlay INDEX."
21522 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
21524 ;; FIXME this is currently not used.
21525 (defun org-highlight-until-next-command (beg end &optional buffer)
21526 (org-highlight beg end buffer)
21527 (add-hook 'pre-command-hook 'org-unhighlight-once))
21528 (defun org-unhighlight-once ()
21529 (remove-hook 'pre-command-hook 'org-unhighlight-once)
21530 (org-unhighlight))
21532 (defun org-agenda-follow-mode ()
21533 "Toggle follow mode in an agenda buffer."
21534 (interactive)
21535 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
21536 (org-agenda-set-mode-name)
21537 (message "Follow mode is %s"
21538 (if org-agenda-follow-mode "on" "off")))
21540 (defun org-agenda-log-mode ()
21541 "Toggle log mode in an agenda buffer."
21542 (interactive)
21543 (org-agenda-check-type t 'agenda 'timeline)
21544 (setq org-agenda-show-log (not org-agenda-show-log))
21545 (org-agenda-set-mode-name)
21546 (org-agenda-redo)
21547 (message "Log mode is %s"
21548 (if org-agenda-show-log "on" "off")))
21550 (defun org-agenda-toggle-diary ()
21551 "Toggle diary inclusion in an agenda buffer."
21552 (interactive)
21553 (org-agenda-check-type t 'agenda)
21554 (setq org-agenda-include-diary (not org-agenda-include-diary))
21555 (org-agenda-redo)
21556 (org-agenda-set-mode-name)
21557 (message "Diary inclusion turned %s"
21558 (if org-agenda-include-diary "on" "off")))
21560 (defun org-agenda-toggle-time-grid ()
21561 "Toggle time grid in an agenda buffer."
21562 (interactive)
21563 (org-agenda-check-type t 'agenda)
21564 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
21565 (org-agenda-redo)
21566 (org-agenda-set-mode-name)
21567 (message "Time-grid turned %s"
21568 (if org-agenda-use-time-grid "on" "off")))
21570 (defun org-agenda-set-mode-name ()
21571 "Set the mode name to indicate all the small mode settings."
21572 (setq mode-name
21573 (concat "Org-Agenda"
21574 (if (equal org-agenda-ndays 1) " Day" "")
21575 (if (equal org-agenda-ndays 7) " Week" "")
21576 (if org-agenda-follow-mode " Follow" "")
21577 (if org-agenda-include-diary " Diary" "")
21578 (if org-agenda-use-time-grid " Grid" "")
21579 (if org-agenda-show-log " Log" "")))
21580 (force-mode-line-update))
21582 (defun org-agenda-post-command-hook ()
21583 (and (eolp) (not (bolp)) (backward-char 1))
21584 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
21585 (if (and org-agenda-follow-mode
21586 (get-text-property (point) 'org-marker))
21587 (org-agenda-show)))
21589 (defun org-agenda-show-priority ()
21590 "Show the priority of the current item.
21591 This priority is composed of the main priority given with the [#A] cookies,
21592 and by additional input from the age of a schedules or deadline entry."
21593 (interactive)
21594 (let* ((pri (get-text-property (point-at-bol) 'priority)))
21595 (message "Priority is %d" (if pri pri -1000))))
21597 (defun org-agenda-show-tags ()
21598 "Show the tags applicable to the current item."
21599 (interactive)
21600 (let* ((tags (get-text-property (point-at-bol) 'tags)))
21601 (if tags
21602 (message "Tags are :%s:"
21603 (org-no-properties (mapconcat 'identity tags ":")))
21604 (message "No tags associated with this line"))))
21606 (defun org-agenda-goto (&optional highlight)
21607 "Go to the Org-mode file which contains the item at point."
21608 (interactive)
21609 (let* ((marker (or (get-text-property (point) 'org-marker)
21610 (org-agenda-error)))
21611 (buffer (marker-buffer marker))
21612 (pos (marker-position marker)))
21613 (switch-to-buffer-other-window buffer)
21614 (widen)
21615 (goto-char pos)
21616 (when (org-mode-p)
21617 (org-show-context 'agenda)
21618 (save-excursion
21619 (and (outline-next-heading)
21620 (org-flag-heading nil)))) ; show the next heading
21621 (run-hooks 'org-agenda-after-show-hook)
21622 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
21624 (defvar org-agenda-after-show-hook nil
21625 "Normal hook run after an item has been shown from the agenda.
21626 Point is in the buffer where the item originated.")
21628 (defun org-agenda-kill ()
21629 "Kill the entry or subtree belonging to the current agenda entry."
21630 (interactive)
21631 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
21632 (let* ((marker (or (get-text-property (point) 'org-marker)
21633 (org-agenda-error)))
21634 (buffer (marker-buffer marker))
21635 (pos (marker-position marker))
21636 (type (get-text-property (point) 'type))
21637 dbeg dend (n 0) conf)
21638 (org-with-remote-undo buffer
21639 (with-current-buffer buffer
21640 (save-excursion
21641 (goto-char pos)
21642 (if (and (org-mode-p) (not (member type '("sexp"))))
21643 (setq dbeg (progn (org-back-to-heading t) (point))
21644 dend (org-end-of-subtree t t))
21645 (setq dbeg (point-at-bol)
21646 dend (min (point-max) (1+ (point-at-eol)))))
21647 (goto-char dbeg)
21648 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
21649 (setq conf (or (eq t org-agenda-confirm-kill)
21650 (and (numberp org-agenda-confirm-kill)
21651 (> n org-agenda-confirm-kill))))
21652 (and conf
21653 (not (y-or-n-p
21654 (format "Delete entry with %d lines in buffer \"%s\"? "
21655 n (buffer-name buffer))))
21656 (error "Abort"))
21657 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
21658 (with-current-buffer buffer (delete-region dbeg dend))
21659 (message "Agenda item and source killed"))))
21661 (defun org-agenda-archive ()
21662 "Kill the entry or subtree belonging to the current agenda entry."
21663 (interactive)
21664 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
21665 (let* ((marker (or (get-text-property (point) 'org-marker)
21666 (org-agenda-error)))
21667 (buffer (marker-buffer marker))
21668 (pos (marker-position marker)))
21669 (org-with-remote-undo buffer
21670 (with-current-buffer buffer
21671 (if (org-mode-p)
21672 (save-excursion
21673 (goto-char pos)
21674 (org-remove-subtree-entries-from-agenda)
21675 (org-back-to-heading t)
21676 (org-archive-subtree))
21677 (error "Archiving works only in Org-mode files"))))))
21679 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
21680 "Remove all lines in the agenda that correspond to a given subtree.
21681 The subtree is the one in buffer BUF, starting at BEG and ending at END.
21682 If this information is not given, the function uses the tree at point."
21683 (let ((buf (or buf (current-buffer))) m p)
21684 (save-excursion
21685 (unless (and beg end)
21686 (org-back-to-heading t)
21687 (setq beg (point))
21688 (org-end-of-subtree t)
21689 (setq end (point)))
21690 (set-buffer (get-buffer org-agenda-buffer-name))
21691 (save-excursion
21692 (goto-char (point-max))
21693 (beginning-of-line 1)
21694 (while (not (bobp))
21695 (when (and (setq m (get-text-property (point) 'org-marker))
21696 (equal buf (marker-buffer m))
21697 (setq p (marker-position m))
21698 (>= p beg)
21699 (<= p end))
21700 (let ((inhibit-read-only t))
21701 (delete-region (point-at-bol) (1+ (point-at-eol)))))
21702 (beginning-of-line 0))))))
21704 (defun org-agenda-open-link ()
21705 "Follow the link in the current line, if any."
21706 (interactive)
21707 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
21708 (save-excursion
21709 (save-restriction
21710 (narrow-to-region (point-at-bol) (point-at-eol))
21711 (org-open-at-point))))
21713 (defun org-agenda-copy-local-variable (var)
21714 "Get a variable from a referenced buffer and install it here."
21715 (let ((m (get-text-property (point) 'org-marker)))
21716 (when (and m (buffer-live-p (marker-buffer m)))
21717 (org-set-local var (with-current-buffer (marker-buffer m)
21718 (symbol-value var))))))
21720 (defun org-agenda-switch-to (&optional delete-other-windows)
21721 "Go to the Org-mode file which contains the item at point."
21722 (interactive)
21723 (let* ((marker (or (get-text-property (point) 'org-marker)
21724 (org-agenda-error)))
21725 (buffer (marker-buffer marker))
21726 (pos (marker-position marker)))
21727 (switch-to-buffer buffer)
21728 (and delete-other-windows (delete-other-windows))
21729 (widen)
21730 (goto-char pos)
21731 (when (org-mode-p)
21732 (org-show-context 'agenda)
21733 (save-excursion
21734 (and (outline-next-heading)
21735 (org-flag-heading nil)))))) ; show the next heading
21737 (defun org-agenda-goto-mouse (ev)
21738 "Go to the Org-mode file which contains the item at the mouse click."
21739 (interactive "e")
21740 (mouse-set-point ev)
21741 (org-agenda-goto))
21743 (defun org-agenda-show ()
21744 "Display the Org-mode file which contains the item at point."
21745 (interactive)
21746 (let ((win (selected-window)))
21747 (org-agenda-goto t)
21748 (select-window win)))
21750 (defun org-agenda-recenter (arg)
21751 "Display the Org-mode file which contains the item at point and recenter."
21752 (interactive "P")
21753 (let ((win (selected-window)))
21754 (org-agenda-goto t)
21755 (recenter arg)
21756 (select-window win)))
21758 (defun org-agenda-show-mouse (ev)
21759 "Display the Org-mode file which contains the item at the mouse click."
21760 (interactive "e")
21761 (mouse-set-point ev)
21762 (org-agenda-show))
21764 (defun org-agenda-check-no-diary ()
21765 "Check if the entry is a diary link and abort if yes."
21766 (if (get-text-property (point) 'org-agenda-diary-link)
21767 (org-agenda-error)))
21769 (defun org-agenda-error ()
21770 (error "Command not allowed in this line"))
21772 (defun org-agenda-tree-to-indirect-buffer ()
21773 "Show the subtree corresponding to the current entry in an indirect buffer.
21774 This calls the command `org-tree-to-indirect-buffer' from the original
21775 Org-mode buffer.
21776 With numerical prefix arg ARG, go up to this level and then take that tree.
21777 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
21778 dedicated frame)."
21779 (interactive)
21780 (org-agenda-check-no-diary)
21781 (let* ((marker (or (get-text-property (point) 'org-marker)
21782 (org-agenda-error)))
21783 (buffer (marker-buffer marker))
21784 (pos (marker-position marker)))
21785 (with-current-buffer buffer
21786 (save-excursion
21787 (goto-char pos)
21788 (call-interactively 'org-tree-to-indirect-buffer)))))
21790 (defvar org-last-heading-marker (make-marker)
21791 "Marker pointing to the headline that last changed its TODO state
21792 by a remote command from the agenda.")
21794 (defun org-agenda-todo-nextset ()
21795 "Switch TODO entry to next sequence."
21796 (interactive)
21797 (org-agenda-todo 'nextset))
21799 (defun org-agenda-todo-previousset ()
21800 "Switch TODO entry to previous sequence."
21801 (interactive)
21802 (org-agenda-todo 'previousset))
21804 (defun org-agenda-todo (&optional arg)
21805 "Cycle TODO state of line at point, also in Org-mode file.
21806 This changes the line at point, all other lines in the agenda referring to
21807 the same tree node, and the headline of the tree node in the Org-mode file."
21808 (interactive "P")
21809 (org-agenda-check-no-diary)
21810 (let* ((col (current-column))
21811 (marker (or (get-text-property (point) 'org-marker)
21812 (org-agenda-error)))
21813 (buffer (marker-buffer marker))
21814 (pos (marker-position marker))
21815 (hdmarker (get-text-property (point) 'org-hd-marker))
21816 (inhibit-read-only t)
21817 newhead)
21818 (org-with-remote-undo buffer
21819 (with-current-buffer buffer
21820 (widen)
21821 (goto-char pos)
21822 (org-show-context 'agenda)
21823 (save-excursion
21824 (and (outline-next-heading)
21825 (org-flag-heading nil))) ; show the next heading
21826 (org-todo arg)
21827 (and (bolp) (forward-char 1))
21828 (setq newhead (org-get-heading))
21829 (save-excursion
21830 (org-back-to-heading)
21831 (move-marker org-last-heading-marker (point))))
21832 (beginning-of-line 1)
21833 (save-excursion
21834 (org-agenda-change-all-lines newhead hdmarker 'fixface))
21835 (move-to-column col))))
21837 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
21838 "Change all lines in the agenda buffer which match HDMARKER.
21839 The new content of the line will be NEWHEAD (as modified by
21840 `org-format-agenda-item'). HDMARKER is checked with
21841 `equal' against all `org-hd-marker' text properties in the file.
21842 If FIXFACE is non-nil, the face of each item is modified acording to
21843 the new TODO state."
21844 (let* ((inhibit-read-only t)
21845 props m pl undone-face done-face finish new dotime cat tags)
21846 (save-excursion
21847 (goto-char (point-max))
21848 (beginning-of-line 1)
21849 (while (not finish)
21850 (setq finish (bobp))
21851 (when (and (setq m (get-text-property (point) 'org-hd-marker))
21852 (equal m hdmarker))
21853 (setq props (text-properties-at (point))
21854 dotime (get-text-property (point) 'dotime)
21855 cat (get-text-property (point) 'org-category)
21856 tags (get-text-property (point) 'tags)
21857 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
21858 pl (get-text-property (point) 'prefix-length)
21859 undone-face (get-text-property (point) 'undone-face)
21860 done-face (get-text-property (point) 'done-face))
21861 (move-to-column pl)
21862 (cond
21863 ((equal new "")
21864 (beginning-of-line 1)
21865 (and (looking-at ".*\n?") (replace-match "")))
21866 ((looking-at ".*")
21867 (replace-match new t t)
21868 (beginning-of-line 1)
21869 (add-text-properties (point-at-bol) (point-at-eol) props)
21870 (when fixface
21871 (add-text-properties
21872 (point-at-bol) (point-at-eol)
21873 (list 'face
21874 (if org-last-todo-state-is-todo
21875 undone-face done-face))))
21876 (org-agenda-highlight-todo 'line)
21877 (beginning-of-line 1))
21878 (t (error "Line update did not work"))))
21879 (beginning-of-line 0)))
21880 (org-finalize-agenda)))
21882 (defun org-agenda-align-tags (&optional line)
21883 "Align all tags in agenda items to `org-agenda-tags-column'."
21884 (let ((inhibit-read-only t) l c)
21885 (save-excursion
21886 (goto-char (if line (point-at-bol) (point-min)))
21887 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21888 (if line (point-at-eol) nil) t)
21889 (add-text-properties
21890 (match-beginning 2) (match-end 2)
21891 (list 'face (list 'org-tag (get-text-property
21892 (match-beginning 2) 'face))))
21893 (setq l (- (match-end 2) (match-beginning 2))
21894 c (if (< org-agenda-tags-column 0)
21895 (- (abs org-agenda-tags-column) l)
21896 org-agenda-tags-column))
21897 (delete-region (match-beginning 1) (match-end 1))
21898 (goto-char (match-beginning 1))
21899 (insert (org-add-props
21900 (make-string (max 1 (- c (current-column))) ?\ )
21901 (text-properties-at (point))))))))
21903 (defun org-agenda-priority-up ()
21904 "Increase the priority of line at point, also in Org-mode file."
21905 (interactive)
21906 (org-agenda-priority 'up))
21908 (defun org-agenda-priority-down ()
21909 "Decrease the priority of line at point, also in Org-mode file."
21910 (interactive)
21911 (org-agenda-priority 'down))
21913 (defun org-agenda-priority (&optional force-direction)
21914 "Set the priority of line at point, also in Org-mode file.
21915 This changes the line at point, all other lines in the agenda referring to
21916 the same tree node, and the headline of the tree node in the Org-mode file."
21917 (interactive)
21918 (org-agenda-check-no-diary)
21919 (let* ((marker (or (get-text-property (point) 'org-marker)
21920 (org-agenda-error)))
21921 (hdmarker (get-text-property (point) 'org-hd-marker))
21922 (buffer (marker-buffer hdmarker))
21923 (pos (marker-position hdmarker))
21924 (inhibit-read-only t)
21925 newhead)
21926 (org-with-remote-undo buffer
21927 (with-current-buffer buffer
21928 (widen)
21929 (goto-char pos)
21930 (org-show-context 'agenda)
21931 (save-excursion
21932 (and (outline-next-heading)
21933 (org-flag-heading nil))) ; show the next heading
21934 (funcall 'org-priority force-direction)
21935 (end-of-line 1)
21936 (setq newhead (org-get-heading)))
21937 (org-agenda-change-all-lines newhead hdmarker)
21938 (beginning-of-line 1))))
21940 (defun org-get-tags-at (&optional pos)
21941 "Get a list of all headline tags applicable at POS.
21942 POS defaults to point. If tags are inherited, the list contains
21943 the targets in the same sequence as the headlines appear, i.e.
21944 the tags of the current headline come last."
21945 (interactive)
21946 (let (tags lastpos)
21947 (save-excursion
21948 (save-restriction
21949 (widen)
21950 (goto-char (or pos (point)))
21951 (save-match-data
21952 (org-back-to-heading t)
21953 (condition-case nil
21954 (while (not (equal lastpos (point)))
21955 (setq lastpos (point))
21956 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
21957 (setq tags (append (org-split-string
21958 (org-match-string-no-properties 1) ":")
21959 tags)))
21960 (or org-use-tag-inheritance (error ""))
21961 (org-up-heading-all 1))
21962 (error nil))))
21963 tags)))
21965 ;; FIXME: should fix the tags property of the agenda line.
21966 (defun org-agenda-set-tags ()
21967 "Set tags for the current headline."
21968 (interactive)
21969 (org-agenda-check-no-diary)
21970 (if (and (org-region-active-p) (interactive-p))
21971 (call-interactively 'org-change-tag-in-region)
21972 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
21973 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
21974 (org-agenda-error)))
21975 (buffer (marker-buffer hdmarker))
21976 (pos (marker-position hdmarker))
21977 (inhibit-read-only t)
21978 newhead)
21979 (org-with-remote-undo buffer
21980 (with-current-buffer buffer
21981 (widen)
21982 (goto-char pos)
21983 (save-excursion
21984 (org-show-context 'agenda))
21985 (save-excursion
21986 (and (outline-next-heading)
21987 (org-flag-heading nil))) ; show the next heading
21988 (goto-char pos)
21989 (call-interactively 'org-set-tags)
21990 (end-of-line 1)
21991 (setq newhead (org-get-heading)))
21992 (org-agenda-change-all-lines newhead hdmarker)
21993 (beginning-of-line 1)))))
21995 (defun org-agenda-toggle-archive-tag ()
21996 "Toggle the archive tag for the current entry."
21997 (interactive)
21998 (org-agenda-check-no-diary)
21999 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22000 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22001 (org-agenda-error)))
22002 (buffer (marker-buffer hdmarker))
22003 (pos (marker-position hdmarker))
22004 (inhibit-read-only t)
22005 newhead)
22006 (org-with-remote-undo buffer
22007 (with-current-buffer buffer
22008 (widen)
22009 (goto-char pos)
22010 (org-show-context 'agenda)
22011 (save-excursion
22012 (and (outline-next-heading)
22013 (org-flag-heading nil))) ; show the next heading
22014 (call-interactively 'org-toggle-archive-tag)
22015 (end-of-line 1)
22016 (setq newhead (org-get-heading)))
22017 (org-agenda-change-all-lines newhead hdmarker)
22018 (beginning-of-line 1))))
22020 (defun org-agenda-date-later (arg &optional what)
22021 "Change the date of this item to one day later."
22022 (interactive "p")
22023 (org-agenda-check-type t 'agenda 'timeline)
22024 (org-agenda-check-no-diary)
22025 (let* ((marker (or (get-text-property (point) 'org-marker)
22026 (org-agenda-error)))
22027 (buffer (marker-buffer marker))
22028 (pos (marker-position marker)))
22029 (org-with-remote-undo buffer
22030 (with-current-buffer buffer
22031 (widen)
22032 (goto-char pos)
22033 (if (not (org-at-timestamp-p))
22034 (error "Cannot find time stamp"))
22035 (org-timestamp-change arg (or what 'day)))
22036 (org-agenda-show-new-time marker org-last-changed-timestamp))
22037 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22039 (defun org-agenda-date-earlier (arg &optional what)
22040 "Change the date of this item to one day earlier."
22041 (interactive "p")
22042 (org-agenda-date-later (- arg) what))
22044 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22045 "Show new date stamp via text properties."
22046 ;; We use text properties to make this undoable
22047 (let ((inhibit-read-only t))
22048 (setq stamp (concat " " prefix " => " stamp))
22049 (save-excursion
22050 (goto-char (point-max))
22051 (while (not (bobp))
22052 (when (equal marker (get-text-property (point) 'org-marker))
22053 (move-to-column (- (window-width) (length stamp)) t)
22054 (if (featurep 'xemacs)
22055 ;; Use `duplicable' property to trigger undo recording
22056 (let ((ex (make-extent nil nil))
22057 (gl (make-glyph stamp)))
22058 (set-glyph-face gl 'secondary-selection)
22059 (set-extent-properties
22060 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22061 (insert-extent ex (1- (point)) (point-at-eol)))
22062 (add-text-properties
22063 (1- (point)) (point-at-eol)
22064 (list 'display (org-add-props stamp nil
22065 'face 'secondary-selection))))
22066 (beginning-of-line 1))
22067 (beginning-of-line 0)))))
22069 (defun org-agenda-date-prompt (arg)
22070 "Change the date of this item. Date is prompted for, with default today.
22071 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22072 be used to request time specification in the time stamp."
22073 (interactive "P")
22074 (org-agenda-check-type t 'agenda 'timeline)
22075 (org-agenda-check-no-diary)
22076 (let* ((marker (or (get-text-property (point) 'org-marker)
22077 (org-agenda-error)))
22078 (buffer (marker-buffer marker))
22079 (pos (marker-position marker)))
22080 (org-with-remote-undo buffer
22081 (with-current-buffer buffer
22082 (widen)
22083 (goto-char pos)
22084 (if (not (org-at-timestamp-p))
22085 (error "Cannot find time stamp"))
22086 (org-time-stamp arg)
22087 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22089 (defun org-agenda-schedule (arg)
22090 "Schedule the item at point."
22091 (interactive "P")
22092 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22093 (org-agenda-check-no-diary)
22094 (let* ((marker (or (get-text-property (point) 'org-marker)
22095 (org-agenda-error)))
22096 (buffer (marker-buffer marker))
22097 (pos (marker-position marker))
22098 (org-insert-labeled-timestamps-at-point nil)
22100 (org-with-remote-undo buffer
22101 (with-current-buffer buffer
22102 (widen)
22103 (goto-char pos)
22104 (setq ts (org-schedule arg)))
22105 (org-agenda-show-new-time marker ts "S"))
22106 (message "Item scheduled for %s" ts)))
22108 (defun org-agenda-deadline (arg)
22109 "Schedule the item at point."
22110 (interactive "P")
22111 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22112 (org-agenda-check-no-diary)
22113 (let* ((marker (or (get-text-property (point) 'org-marker)
22114 (org-agenda-error)))
22115 (buffer (marker-buffer marker))
22116 (pos (marker-position marker))
22117 (org-insert-labeled-timestamps-at-point nil)
22119 (org-with-remote-undo buffer
22120 (with-current-buffer buffer
22121 (widen)
22122 (goto-char pos)
22123 (setq ts (org-deadline arg)))
22124 (org-agenda-show-new-time marker ts "S"))
22125 (message "Deadline for this item set to %s" ts)))
22127 (defun org-get-heading (&optional no-tags)
22128 "Return the heading of the current entry, without the stars."
22129 (save-excursion
22130 (org-back-to-heading t)
22131 (if (looking-at
22132 (if no-tags
22133 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22134 "\\*+[ \t]+\\([^\r\n]*\\)"))
22135 (match-string 1) "")))
22137 (defun org-agenda-clock-in (&optional arg)
22138 "Start the clock on the currently selected item."
22139 (interactive "P")
22140 (org-agenda-check-no-diary)
22141 (let* ((marker (or (get-text-property (point) 'org-marker)
22142 (org-agenda-error)))
22143 (pos (marker-position marker)))
22144 (org-with-remote-undo (marker-buffer marker)
22145 (with-current-buffer (marker-buffer marker)
22146 (widen)
22147 (goto-char pos)
22148 (org-clock-in)))))
22150 (defun org-agenda-clock-out (&optional arg)
22151 "Stop the currently running clock."
22152 (interactive "P")
22153 (unless (marker-buffer org-clock-marker)
22154 (error "No running clock"))
22155 (org-with-remote-undo (marker-buffer org-clock-marker)
22156 (org-clock-out)))
22158 (defun org-agenda-clock-cancel (&optional arg)
22159 "Cancel the currently running clock."
22160 (interactive "P")
22161 (unless (marker-buffer org-clock-marker)
22162 (error "No running clock"))
22163 (org-with-remote-undo (marker-buffer org-clock-marker)
22164 (org-clock-cancel)))
22166 (defun org-agenda-diary-entry ()
22167 "Make a diary entry, like the `i' command from the calendar.
22168 All the standard commands work: block, weekly etc."
22169 (interactive)
22170 (org-agenda-check-type t 'agenda 'timeline)
22171 (require 'diary-lib)
22172 (let* ((char (progn
22173 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
22174 (read-char-exclusive)))
22175 (cmd (cdr (assoc char
22176 '((?d . insert-diary-entry)
22177 (?w . insert-weekly-diary-entry)
22178 (?m . insert-monthly-diary-entry)
22179 (?y . insert-yearly-diary-entry)
22180 (?a . insert-anniversary-diary-entry)
22181 (?b . insert-block-diary-entry)
22182 (?c . insert-cyclic-diary-entry)))))
22183 (oldf (symbol-function 'calendar-cursor-to-date))
22184 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
22185 (point (point))
22186 (mark (or (mark t) (point))))
22187 (unless cmd
22188 (error "No command associated with <%c>" char))
22189 (unless (and (get-text-property point 'day)
22190 (or (not (equal ?b char))
22191 (get-text-property mark 'day)))
22192 (error "Don't know which date to use for diary entry"))
22193 ;; We implement this by hacking the `calendar-cursor-to-date' function
22194 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
22195 (let ((calendar-mark-ring
22196 (list (calendar-gregorian-from-absolute
22197 (or (get-text-property mark 'day)
22198 (get-text-property point 'day))))))
22199 (unwind-protect
22200 (progn
22201 (fset 'calendar-cursor-to-date
22202 (lambda (&optional error)
22203 (calendar-gregorian-from-absolute
22204 (get-text-property point 'day))))
22205 (call-interactively cmd))
22206 (fset 'calendar-cursor-to-date oldf)))))
22209 (defun org-agenda-execute-calendar-command (cmd)
22210 "Execute a calendar command from the agenda, with the date associated to
22211 the cursor position."
22212 (org-agenda-check-type t 'agenda 'timeline)
22213 (require 'diary-lib)
22214 (unless (get-text-property (point) 'day)
22215 (error "Don't know which date to use for calendar command"))
22216 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
22217 (point (point))
22218 (date (calendar-gregorian-from-absolute
22219 (get-text-property point 'day)))
22220 ;; the following 3 vars are needed in the calendar
22221 (displayed-day (extract-calendar-day date))
22222 (displayed-month (extract-calendar-month date))
22223 (displayed-year (extract-calendar-year date)))
22224 (unwind-protect
22225 (progn
22226 (fset 'calendar-cursor-to-date
22227 (lambda (&optional error)
22228 (calendar-gregorian-from-absolute
22229 (get-text-property point 'day))))
22230 (call-interactively cmd))
22231 (fset 'calendar-cursor-to-date oldf))))
22233 (defun org-agenda-phases-of-moon ()
22234 "Display the phases of the moon for the 3 months around the cursor date."
22235 (interactive)
22236 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
22238 (defun org-agenda-holidays ()
22239 "Display the holidays for the 3 months around the cursor date."
22240 (interactive)
22241 (org-agenda-execute-calendar-command 'list-calendar-holidays))
22243 (defun org-agenda-sunrise-sunset (arg)
22244 "Display sunrise and sunset for the cursor date.
22245 Latitude and longitude can be specified with the variables
22246 `calendar-latitude' and `calendar-longitude'. When called with prefix
22247 argument, latitude and longitude will be prompted for."
22248 (interactive "P")
22249 (let ((calendar-longitude (if arg nil calendar-longitude))
22250 (calendar-latitude (if arg nil calendar-latitude))
22251 (calendar-location-name
22252 (if arg "the given coordinates" calendar-location-name)))
22253 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
22255 (defun org-agenda-goto-calendar ()
22256 "Open the Emacs calendar with the date at the cursor."
22257 (interactive)
22258 (org-agenda-check-type t 'agenda 'timeline)
22259 (let* ((day (or (get-text-property (point) 'day)
22260 (error "Don't know which date to open in calendar")))
22261 (date (calendar-gregorian-from-absolute day))
22262 (calendar-move-hook nil)
22263 (view-calendar-holidays-initially nil)
22264 (view-diary-entries-initially nil))
22265 (calendar)
22266 (calendar-goto-date date)))
22268 (defun org-calendar-goto-agenda ()
22269 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
22270 This is a command that has to be installed in `calendar-mode-map'."
22271 (interactive)
22272 (org-agenda-list nil (calendar-absolute-from-gregorian
22273 (calendar-cursor-to-date))
22274 nil))
22276 (defun org-agenda-convert-date ()
22277 (interactive)
22278 (org-agenda-check-type t 'agenda 'timeline)
22279 (let ((day (get-text-property (point) 'day))
22280 date s)
22281 (unless day
22282 (error "Don't know which date to convert"))
22283 (setq date (calendar-gregorian-from-absolute day))
22284 (setq s (concat
22285 "Gregorian: " (calendar-date-string date) "\n"
22286 "ISO: " (calendar-iso-date-string date) "\n"
22287 "Day of Yr: " (calendar-day-of-year-string date) "\n"
22288 "Julian: " (calendar-julian-date-string date) "\n"
22289 "Astron. JD: " (calendar-astro-date-string date)
22290 " (Julian date number at noon UTC)\n"
22291 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
22292 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
22293 "French: " (calendar-french-date-string date) "\n"
22294 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
22295 "Mayan: " (calendar-mayan-date-string date) "\n"
22296 "Coptic: " (calendar-coptic-date-string date) "\n"
22297 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
22298 "Persian: " (calendar-persian-date-string date) "\n"
22299 "Chinese: " (calendar-chinese-date-string date) "\n"))
22300 (with-output-to-temp-buffer "*Dates*"
22301 (princ s))
22302 (if (fboundp 'fit-window-to-buffer)
22303 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
22306 ;;;; Embedded LaTeX
22308 (defvar org-cdlatex-mode-map (make-sparse-keymap)
22309 "Keymap for the minor `org-cdlatex-mode'.")
22311 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
22312 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
22313 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
22314 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
22315 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
22317 (defvar org-cdlatex-texmathp-advice-is-done nil
22318 "Flag remembering if we have applied the advice to texmathp already.")
22320 (define-minor-mode org-cdlatex-mode
22321 "Toggle the minor `org-cdlatex-mode'.
22322 This mode supports entering LaTeX environment and math in LaTeX fragments
22323 in Org-mode.
22324 \\{org-cdlatex-mode-map}"
22325 nil " OCDL" nil
22326 (when org-cdlatex-mode (require 'cdlatex))
22327 (unless org-cdlatex-texmathp-advice-is-done
22328 (setq org-cdlatex-texmathp-advice-is-done t)
22329 (defadvice texmathp (around org-math-always-on activate)
22330 "Always return t in org-mode buffers.
22331 This is because we want to insert math symbols without dollars even outside
22332 the LaTeX math segments. If Orgmode thinks that point is actually inside
22333 en embedded LaTeX fragement, let texmathp do its job.
22334 \\[org-cdlatex-mode-map]"
22335 (interactive)
22336 (let (p)
22337 (cond
22338 ((not (org-mode-p)) ad-do-it)
22339 ((eq this-command 'cdlatex-math-symbol)
22340 (setq ad-return-value t
22341 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
22343 (let ((p (org-inside-LaTeX-fragment-p)))
22344 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
22345 (setq ad-return-value t
22346 texmathp-why '("Org-mode embedded math" . 0))
22347 (if p ad-do-it)))))))))
22349 (defun turn-on-org-cdlatex ()
22350 "Unconditionally turn on `org-cdlatex-mode'."
22351 (org-cdlatex-mode 1))
22353 (defun org-inside-LaTeX-fragment-p ()
22354 "Test if point is inside a LaTeX fragment.
22355 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
22356 sequence appearing also before point.
22357 Even though the matchers for math are configurable, this function assumes
22358 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
22359 delimiters are skipped when they have been removed by customization.
22360 The return value is nil, or a cons cell with the delimiter and
22361 and the position of this delimiter.
22363 This function does a reasonably good job, but can locally be fooled by
22364 for example currency specifications. For example it will assume being in
22365 inline math after \"$22.34\". The LaTeX fragment formatter will only format
22366 fragments that are properly closed, but during editing, we have to live
22367 with the uncertainty caused by missing closing delimiters. This function
22368 looks only before point, not after."
22369 (catch 'exit
22370 (let ((pos (point))
22371 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
22372 (lim (progn
22373 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
22374 (point)))
22375 dd-on str (start 0) m re)
22376 (goto-char pos)
22377 (when dodollar
22378 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
22379 re (nth 1 (assoc "$" org-latex-regexps)))
22380 (while (string-match re str start)
22381 (cond
22382 ((= (match-end 0) (length str))
22383 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
22384 ((= (match-end 0) (- (length str) 5))
22385 (throw 'exit nil))
22386 (t (setq start (match-end 0))))))
22387 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
22388 (goto-char pos)
22389 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
22390 (and (match-beginning 2) (throw 'exit nil))
22391 ;; count $$
22392 (while (re-search-backward "\\$\\$" lim t)
22393 (setq dd-on (not dd-on)))
22394 (goto-char pos)
22395 (if dd-on (cons "$$" m))))))
22398 (defun org-try-cdlatex-tab ()
22399 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
22400 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
22401 - inside a LaTeX fragment, or
22402 - after the first word in a line, where an abbreviation expansion could
22403 insert a LaTeX environment."
22404 (when org-cdlatex-mode
22405 (cond
22406 ((save-excursion
22407 (skip-chars-backward "a-zA-Z0-9*")
22408 (skip-chars-backward " \t")
22409 (bolp))
22410 (cdlatex-tab) t)
22411 ((org-inside-LaTeX-fragment-p)
22412 (cdlatex-tab) t)
22413 (t nil))))
22415 (defun org-cdlatex-underscore-caret (&optional arg)
22416 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
22417 Revert to the normal definition outside of these fragments."
22418 (interactive "P")
22419 (if (org-inside-LaTeX-fragment-p)
22420 (call-interactively 'cdlatex-sub-superscript)
22421 (let (org-cdlatex-mode)
22422 (call-interactively (key-binding (vector last-input-event))))))
22424 (defun org-cdlatex-math-modify (&optional arg)
22425 "Execute `cdlatex-math-modify' in LaTeX fragments.
22426 Revert to the normal definition outside of these fragments."
22427 (interactive "P")
22428 (if (org-inside-LaTeX-fragment-p)
22429 (call-interactively 'cdlatex-math-modify)
22430 (let (org-cdlatex-mode)
22431 (call-interactively (key-binding (vector last-input-event))))))
22433 (defvar org-latex-fragment-image-overlays nil
22434 "List of overlays carrying the images of latex fragments.")
22435 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
22437 (defun org-remove-latex-fragment-image-overlays ()
22438 "Remove all overlays with LaTeX fragment images in current buffer."
22439 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
22440 (setq org-latex-fragment-image-overlays nil))
22442 (defun org-preview-latex-fragment (&optional subtree)
22443 "Preview the LaTeX fragment at point, or all locally or globally.
22444 If the cursor is in a LaTeX fragment, create the image and overlay
22445 it over the source code. If there is no fragment at point, display
22446 all fragments in the current text, from one headline to the next. With
22447 prefix SUBTREE, display all fragments in the current subtree. With a
22448 double prefix `C-u C-u', or when the cursor is before the first headline,
22449 display all fragments in the buffer.
22450 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
22451 (interactive "P")
22452 (org-remove-latex-fragment-image-overlays)
22453 (save-excursion
22454 (save-restriction
22455 (let (beg end at msg)
22456 (cond
22457 ((or (equal subtree '(16))
22458 (not (save-excursion
22459 (re-search-backward (concat "^" outline-regexp) nil t))))
22460 (setq beg (point-min) end (point-max)
22461 msg "Creating images for buffer...%s"))
22462 ((equal subtree '(4))
22463 (org-back-to-heading)
22464 (setq beg (point) end (org-end-of-subtree t)
22465 msg "Creating images for subtree...%s"))
22467 (if (setq at (org-inside-LaTeX-fragment-p))
22468 (goto-char (max (point-min) (- (cdr at) 2)))
22469 (org-back-to-heading))
22470 (setq beg (point) end (progn (outline-next-heading) (point))
22471 msg (if at "Creating image...%s"
22472 "Creating images for entry...%s"))))
22473 (message msg "")
22474 (narrow-to-region beg end)
22475 (goto-char beg)
22476 (org-format-latex
22477 (concat "ltxpng/" (file-name-sans-extension
22478 (file-name-nondirectory
22479 buffer-file-name)))
22480 default-directory 'overlays msg at 'forbuffer)
22481 (message msg "done. Use `C-c C-c' to remove images.")))))
22483 (defvar org-latex-regexps
22484 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
22485 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
22486 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
22487 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
22488 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
22489 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
22490 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
22491 "Regular expressions for matching embedded LaTeX.")
22493 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
22494 "Replace LaTeX fragments with links to an image, and produce images."
22495 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
22496 (let* ((prefixnodir (file-name-nondirectory prefix))
22497 (absprefix (expand-file-name prefix dir))
22498 (todir (file-name-directory absprefix))
22499 (opt org-format-latex-options)
22500 (matchers (plist-get opt :matchers))
22501 (re-list org-latex-regexps)
22502 (cnt 0) txt link beg end re e checkdir
22503 m n block linkfile movefile ov)
22504 ;; Check if there are old images files with this prefix, and remove them
22505 (when (file-directory-p todir)
22506 (mapc 'delete-file
22507 (directory-files
22508 todir 'full
22509 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
22510 ;; Check the different regular expressions
22511 (while (setq e (pop re-list))
22512 (setq m (car e) re (nth 1 e) n (nth 2 e)
22513 block (if (nth 3 e) "\n\n" ""))
22514 (when (member m matchers)
22515 (goto-char (point-min))
22516 (while (re-search-forward re nil t)
22517 (when (or (not at) (equal (cdr at) (match-beginning n)))
22518 (setq txt (match-string n)
22519 beg (match-beginning n) end (match-end n)
22520 cnt (1+ cnt)
22521 linkfile (format "%s_%04d.png" prefix cnt)
22522 movefile (format "%s_%04d.png" absprefix cnt)
22523 link (concat block "[[file:" linkfile "]]" block))
22524 (if msg (message msg cnt))
22525 (goto-char beg)
22526 (unless checkdir ; make sure the directory exists
22527 (setq checkdir t)
22528 (or (file-directory-p todir) (make-directory todir)))
22529 (org-create-formula-image
22530 txt movefile opt forbuffer)
22531 (if overlays
22532 (progn
22533 (setq ov (org-make-overlay beg end))
22534 (if (featurep 'xemacs)
22535 (progn
22536 (org-overlay-put ov 'invisible t)
22537 (org-overlay-put
22538 ov 'end-glyph
22539 (make-glyph (vector 'png :file movefile))))
22540 (org-overlay-put
22541 ov 'display
22542 (list 'image :type 'png :file movefile :ascent 'center)))
22543 (push ov org-latex-fragment-image-overlays)
22544 (goto-char end))
22545 (delete-region beg end)
22546 (insert link))))))))
22548 ;; This function borrows from Ganesh Swami's latex2png.el
22549 (defun org-create-formula-image (string tofile options buffer)
22550 (let* ((tmpdir (if (featurep 'xemacs)
22551 (temp-directory)
22552 temporary-file-directory))
22553 (texfilebase (make-temp-name
22554 (expand-file-name "orgtex" tmpdir)))
22555 (texfile (concat texfilebase ".tex"))
22556 (dvifile (concat texfilebase ".dvi"))
22557 (pngfile (concat texfilebase ".png"))
22558 (fnh (face-attribute 'default :height nil))
22559 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
22560 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
22561 (fg (or (plist-get options (if buffer :foreground :html-foreground))
22562 "Black"))
22563 (bg (or (plist-get options (if buffer :background :html-background))
22564 "Transparent")))
22565 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
22566 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
22567 (with-temp-file texfile
22568 (insert org-format-latex-header
22569 "\n\\begin{document}\n" string "\n\\end{document}\n"))
22570 (let ((dir default-directory))
22571 (condition-case nil
22572 (progn
22573 (cd tmpdir)
22574 (call-process "latex" nil nil nil texfile))
22575 (error nil))
22576 (cd dir))
22577 (if (not (file-exists-p dvifile))
22578 (progn (message "Failed to create dvi file from %s" texfile) nil)
22579 (call-process "dvipng" nil nil nil
22580 "-E" "-fg" fg "-bg" bg
22581 "-D" dpi
22582 ;;"-x" scale "-y" scale
22583 "-T" "tight"
22584 "-o" pngfile
22585 dvifile)
22586 (if (not (file-exists-p pngfile))
22587 (progn (message "Failed to create png file from %s" texfile) nil)
22588 ;; Use the requested file name and clean up
22589 (copy-file pngfile tofile 'replace)
22590 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
22591 (delete-file (concat texfilebase e)))
22592 pngfile))))
22594 (defun org-dvipng-color (attr)
22595 "Return an rgb color specification for dvipng."
22596 (apply 'format "rgb %s %s %s"
22597 (mapcar 'org-normalize-color
22598 (color-values (face-attribute 'default attr nil)))))
22600 (defun org-normalize-color (value)
22601 "Return string to be used as color value for an RGB component."
22602 (format "%g" (/ value 65535.0)))
22604 ;;;; Exporting
22606 ;;; Variables, constants, and parameter plists
22608 (defconst org-level-max 20)
22610 (defvar org-export-html-preamble nil
22611 "Preamble, to be inserted just after <body>. Set by publishing functions.")
22612 (defvar org-export-html-postamble nil
22613 "Preamble, to be inserted just before </body>. Set by publishing functions.")
22614 (defvar org-export-html-auto-preamble t
22615 "Should default preamble be inserted? Set by publishing functions.")
22616 (defvar org-export-html-auto-postamble t
22617 "Should default postamble be inserted? Set by publishing functions.")
22618 (defvar org-current-export-file nil) ; dynamically scoped parameter
22619 (defvar org-current-export-dir nil) ; dynamically scoped parameter
22622 (defconst org-export-plist-vars
22623 '((:language . org-export-default-language)
22624 (:customtime . org-display-custom-times)
22625 (:headline-levels . org-export-headline-levels)
22626 (:section-numbers . org-export-with-section-numbers)
22627 (:table-of-contents . org-export-with-toc)
22628 (:preserve-breaks . org-export-preserve-breaks)
22629 (:archived-trees . org-export-with-archived-trees)
22630 (:emphasize . org-export-with-emphasize)
22631 (:sub-superscript . org-export-with-sub-superscripts)
22632 (:special-strings . org-export-with-special-strings)
22633 (:footnotes . org-export-with-footnotes)
22634 (:drawers . org-export-with-drawers)
22635 (:tags . org-export-with-tags)
22636 (:TeX-macros . org-export-with-TeX-macros)
22637 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
22638 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
22639 (:fixed-width . org-export-with-fixed-width)
22640 (:timestamps . org-export-with-timestamps)
22641 (:author-info . org-export-author-info)
22642 (:time-stamp-file . org-export-time-stamp-file)
22643 (:tables . org-export-with-tables)
22644 (:table-auto-headline . org-export-highlight-first-table-line)
22645 (:style . org-export-html-style)
22646 (:agenda-style . org-agenda-export-html-style) ;; FIXME: Does this work????
22647 (:convert-org-links . org-export-html-link-org-files-as-html)
22648 (:inline-images . org-export-html-inline-images)
22649 (:html-extension . org-export-html-extension)
22650 (:html-table-tag . org-export-html-table-tag)
22651 (:expand-quoted-html . org-export-html-expand)
22652 (:timestamp . org-export-html-with-timestamp)
22653 (:publishing-directory . org-export-publishing-directory)
22654 (:preamble . org-export-html-preamble)
22655 (:postamble . org-export-html-postamble)
22656 (:auto-preamble . org-export-html-auto-preamble)
22657 (:auto-postamble . org-export-html-auto-postamble)
22658 (:author . user-full-name)
22659 (:email . user-mail-address)))
22661 (defun org-default-export-plist ()
22662 "Return the property list with default settings for the export variables."
22663 (let ((l org-export-plist-vars) rtn e)
22664 (while (setq e (pop l))
22665 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
22666 rtn))
22668 (defun org-infile-export-plist ()
22669 "Return the property list with file-local settings for export."
22670 (save-excursion
22671 (goto-char 0)
22672 (let ((re (org-make-options-regexp
22673 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
22674 p key val text options)
22675 (while (re-search-forward re nil t)
22676 (setq key (org-match-string-no-properties 1)
22677 val (org-match-string-no-properties 2))
22678 (cond
22679 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
22680 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
22681 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
22682 ((string-equal key "DATE") (setq p (plist-put p :date val)))
22683 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
22684 ((string-equal key "TEXT")
22685 (setq text (if text (concat text "\n" val) val)))
22686 ((string-equal key "OPTIONS") (setq options val))))
22687 (setq p (plist-put p :text text))
22688 (when options
22689 (let ((op '(("H" . :headline-levels)
22690 ("num" . :section-numbers)
22691 ("toc" . :table-of-contents)
22692 ("\\n" . :preserve-breaks)
22693 ("@" . :expand-quoted-html)
22694 (":" . :fixed-width)
22695 ("|" . :tables)
22696 ("^" . :sub-superscript)
22697 ("-" . :special-strings)
22698 ("f" . :footnotes)
22699 ("d" . :drawers)
22700 ("tags" . :tags)
22701 ("*" . :emphasize)
22702 ("TeX" . :TeX-macros)
22703 ("LaTeX" . :LaTeX-fragments)
22704 ("skip" . :skip-before-1st-heading)
22705 ("author" . :author-info)
22706 ("timestamp" . :time-stamp-file)))
22708 (while (setq o (pop op))
22709 (if (string-match (concat (regexp-quote (car o))
22710 ":\\([^ \t\n\r;,.]*\\)")
22711 options)
22712 (setq p (plist-put p (cdr o)
22713 (car (read-from-string
22714 (match-string 1 options)))))))))
22715 p)))
22717 (defun org-export-directory (type plist)
22718 (let* ((val (plist-get plist :publishing-directory))
22719 (dir (if (listp val)
22720 (or (cdr (assoc type val)) ".")
22721 val)))
22722 dir))
22724 (defun org-skip-comments (lines)
22725 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
22726 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
22727 (re2 "^\\(\\*+\\)[ \t\n\r]")
22728 (case-fold-search nil)
22729 rtn line level)
22730 (while (setq line (pop lines))
22731 (cond
22732 ((and (string-match re1 line)
22733 (setq level (- (match-end 1) (match-beginning 1))))
22734 ;; Beginning of a COMMENT subtree. Skip it.
22735 (while (and (setq line (pop lines))
22736 (or (not (string-match re2 line))
22737 (> (- (match-end 1) (match-beginning 1)) level))))
22738 (setq lines (cons line lines)))
22739 ((string-match "^#" line)
22740 ;; an ordinary comment line
22742 ((and org-export-table-remove-special-lines
22743 (string-match "^[ \t]*|" line)
22744 (or (string-match "^[ \t]*| *[!_^] *|" line)
22745 (and (string-match "| *<[0-9]+> *|" line)
22746 (not (string-match "| *[^ <|]" line)))))
22747 ;; a special table line that should be removed
22749 (t (setq rtn (cons line rtn)))))
22750 (nreverse rtn)))
22752 (defun org-export (&optional arg)
22753 (interactive)
22754 (let ((help "[t] insert the export option template
22755 \[v] limit export to visible part of outline tree
22757 \[a] export as ASCII
22759 \[h] export as HTML
22760 \[H] export as HTML to temporary buffer
22761 \[R] export region as HTML
22762 \[b] export as HTML and browse immediately
22763 \[x] export as XOXO
22765 \[l] export as LaTeX
22766 \[L] export as LaTeX to temporary buffer
22768 \[i] export current file as iCalendar file
22769 \[I] export all agenda files as iCalendar files
22770 \[c] export agenda files into combined iCalendar file
22772 \[F] publish current file
22773 \[P] publish current project
22774 \[X] publish... (project will be prompted for)
22775 \[A] publish all projects")
22776 (cmds
22777 '((?t . org-insert-export-options-template)
22778 (?v . org-export-visible)
22779 (?a . org-export-as-ascii)
22780 (?h . org-export-as-html)
22781 (?b . org-export-as-html-and-open)
22782 (?H . org-export-as-html-to-buffer)
22783 (?R . org-export-region-as-html)
22784 (?x . org-export-as-xoxo)
22785 (?l . org-export-as-latex)
22786 (?L . org-export-as-latex-to-buffer)
22787 (?i . org-export-icalendar-this-file)
22788 (?I . org-export-icalendar-all-agenda-files)
22789 (?c . org-export-icalendar-combine-agenda-files)
22790 (?F . org-publish-current-file)
22791 (?P . org-publish-current-project)
22792 (?X . org-publish)
22793 (?A . org-publish-all)))
22794 r1 r2 ass)
22795 (save-window-excursion
22796 (delete-other-windows)
22797 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
22798 (princ help))
22799 (message "Select command: ")
22800 (setq r1 (read-char-exclusive)))
22801 (setq r2 (if (< r1 27) (+ r1 96) r1))
22802 (if (setq ass (assq r2 cmds))
22803 (call-interactively (cdr ass))
22804 (error "No command associated with key %c" r1))))
22806 (defconst org-html-entities
22807 '(("nbsp")
22808 ("iexcl")
22809 ("cent")
22810 ("pound")
22811 ("curren")
22812 ("yen")
22813 ("brvbar")
22814 ("vert" . "&#124;")
22815 ("sect")
22816 ("uml")
22817 ("copy")
22818 ("ordf")
22819 ("laquo")
22820 ("not")
22821 ("shy")
22822 ("reg")
22823 ("macr")
22824 ("deg")
22825 ("plusmn")
22826 ("sup2")
22827 ("sup3")
22828 ("acute")
22829 ("micro")
22830 ("para")
22831 ("middot")
22832 ("odot"."o")
22833 ("star"."*")
22834 ("cedil")
22835 ("sup1")
22836 ("ordm")
22837 ("raquo")
22838 ("frac14")
22839 ("frac12")
22840 ("frac34")
22841 ("iquest")
22842 ("Agrave")
22843 ("Aacute")
22844 ("Acirc")
22845 ("Atilde")
22846 ("Auml")
22847 ("Aring") ("AA"."&Aring;")
22848 ("AElig")
22849 ("Ccedil")
22850 ("Egrave")
22851 ("Eacute")
22852 ("Ecirc")
22853 ("Euml")
22854 ("Igrave")
22855 ("Iacute")
22856 ("Icirc")
22857 ("Iuml")
22858 ("ETH")
22859 ("Ntilde")
22860 ("Ograve")
22861 ("Oacute")
22862 ("Ocirc")
22863 ("Otilde")
22864 ("Ouml")
22865 ("times")
22866 ("Oslash")
22867 ("Ugrave")
22868 ("Uacute")
22869 ("Ucirc")
22870 ("Uuml")
22871 ("Yacute")
22872 ("THORN")
22873 ("szlig")
22874 ("agrave")
22875 ("aacute")
22876 ("acirc")
22877 ("atilde")
22878 ("auml")
22879 ("aring")
22880 ("aelig")
22881 ("ccedil")
22882 ("egrave")
22883 ("eacute")
22884 ("ecirc")
22885 ("euml")
22886 ("igrave")
22887 ("iacute")
22888 ("icirc")
22889 ("iuml")
22890 ("eth")
22891 ("ntilde")
22892 ("ograve")
22893 ("oacute")
22894 ("ocirc")
22895 ("otilde")
22896 ("ouml")
22897 ("divide")
22898 ("oslash")
22899 ("ugrave")
22900 ("uacute")
22901 ("ucirc")
22902 ("uuml")
22903 ("yacute")
22904 ("thorn")
22905 ("yuml")
22906 ("fnof")
22907 ("Alpha")
22908 ("Beta")
22909 ("Gamma")
22910 ("Delta")
22911 ("Epsilon")
22912 ("Zeta")
22913 ("Eta")
22914 ("Theta")
22915 ("Iota")
22916 ("Kappa")
22917 ("Lambda")
22918 ("Mu")
22919 ("Nu")
22920 ("Xi")
22921 ("Omicron")
22922 ("Pi")
22923 ("Rho")
22924 ("Sigma")
22925 ("Tau")
22926 ("Upsilon")
22927 ("Phi")
22928 ("Chi")
22929 ("Psi")
22930 ("Omega")
22931 ("alpha")
22932 ("beta")
22933 ("gamma")
22934 ("delta")
22935 ("epsilon")
22936 ("varepsilon"."&epsilon;")
22937 ("zeta")
22938 ("eta")
22939 ("theta")
22940 ("iota")
22941 ("kappa")
22942 ("lambda")
22943 ("mu")
22944 ("nu")
22945 ("xi")
22946 ("omicron")
22947 ("pi")
22948 ("rho")
22949 ("sigmaf") ("varsigma"."&sigmaf;")
22950 ("sigma")
22951 ("tau")
22952 ("upsilon")
22953 ("phi")
22954 ("chi")
22955 ("psi")
22956 ("omega")
22957 ("thetasym") ("vartheta"."&thetasym;")
22958 ("upsih")
22959 ("piv")
22960 ("bull") ("bullet"."&bull;")
22961 ("hellip") ("dots"."&hellip;")
22962 ("prime")
22963 ("Prime")
22964 ("oline")
22965 ("frasl")
22966 ("weierp")
22967 ("image")
22968 ("real")
22969 ("trade")
22970 ("alefsym")
22971 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
22972 ("uarr") ("uparrow"."&uarr;")
22973 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
22974 ("darr")("downarrow"."&darr;")
22975 ("harr") ("leftrightarrow"."&harr;")
22976 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
22977 ("lArr") ("Leftarrow"."&lArr;")
22978 ("uArr") ("Uparrow"."&uArr;")
22979 ("rArr") ("Rightarrow"."&rArr;")
22980 ("dArr") ("Downarrow"."&dArr;")
22981 ("hArr") ("Leftrightarrow"."&hArr;")
22982 ("forall")
22983 ("part") ("partial"."&part;")
22984 ("exist") ("exists"."&exist;")
22985 ("empty") ("emptyset"."&empty;")
22986 ("nabla")
22987 ("isin") ("in"."&isin;")
22988 ("notin")
22989 ("ni")
22990 ("prod")
22991 ("sum")
22992 ("minus")
22993 ("lowast") ("ast"."&lowast;")
22994 ("radic")
22995 ("prop") ("proptp"."&prop;")
22996 ("infin") ("infty"."&infin;")
22997 ("ang") ("angle"."&ang;")
22998 ("and") ("wedge"."&and;")
22999 ("or") ("vee"."&or;")
23000 ("cap")
23001 ("cup")
23002 ("int")
23003 ("there4")
23004 ("sim")
23005 ("cong") ("simeq"."&cong;")
23006 ("asymp")("approx"."&asymp;")
23007 ("ne") ("neq"."&ne;")
23008 ("equiv")
23009 ("le")
23010 ("ge")
23011 ("sub") ("subset"."&sub;")
23012 ("sup") ("supset"."&sup;")
23013 ("nsub")
23014 ("sube")
23015 ("supe")
23016 ("oplus")
23017 ("otimes")
23018 ("perp")
23019 ("sdot") ("cdot"."&sdot;")
23020 ("lceil")
23021 ("rceil")
23022 ("lfloor")
23023 ("rfloor")
23024 ("lang")
23025 ("rang")
23026 ("loz") ("Diamond"."&loz;")
23027 ("spades") ("spadesuit"."&spades;")
23028 ("clubs") ("clubsuit"."&clubs;")
23029 ("hearts") ("diamondsuit"."&hearts;")
23030 ("diams") ("diamondsuit"."&diams;")
23031 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23032 ("quot")
23033 ("amp")
23034 ("lt")
23035 ("gt")
23036 ("OElig")
23037 ("oelig")
23038 ("Scaron")
23039 ("scaron")
23040 ("Yuml")
23041 ("circ")
23042 ("tilde")
23043 ("ensp")
23044 ("emsp")
23045 ("thinsp")
23046 ("zwnj")
23047 ("zwj")
23048 ("lrm")
23049 ("rlm")
23050 ("ndash")
23051 ("mdash")
23052 ("lsquo")
23053 ("rsquo")
23054 ("sbquo")
23055 ("ldquo")
23056 ("rdquo")
23057 ("bdquo")
23058 ("dagger")
23059 ("Dagger")
23060 ("permil")
23061 ("lsaquo")
23062 ("rsaquo")
23063 ("euro")
23065 ("arccos"."arccos")
23066 ("arcsin"."arcsin")
23067 ("arctan"."arctan")
23068 ("arg"."arg")
23069 ("cos"."cos")
23070 ("cosh"."cosh")
23071 ("cot"."cot")
23072 ("coth"."coth")
23073 ("csc"."csc")
23074 ("deg"."deg")
23075 ("det"."det")
23076 ("dim"."dim")
23077 ("exp"."exp")
23078 ("gcd"."gcd")
23079 ("hom"."hom")
23080 ("inf"."inf")
23081 ("ker"."ker")
23082 ("lg"."lg")
23083 ("lim"."lim")
23084 ("liminf"."liminf")
23085 ("limsup"."limsup")
23086 ("ln"."ln")
23087 ("log"."log")
23088 ("max"."max")
23089 ("min"."min")
23090 ("Pr"."Pr")
23091 ("sec"."sec")
23092 ("sin"."sin")
23093 ("sinh"."sinh")
23094 ("sup"."sup")
23095 ("tan"."tan")
23096 ("tanh"."tanh")
23098 "Entities for TeX->HTML translation.
23099 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23100 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23101 In that case, \"\\ent\" will be translated to \"&other;\".
23102 The list contains HTML entities for Latin-1, Greek and other symbols.
23103 It is supplemented by a number of commonly used TeX macros with appropriate
23104 translations. There is currently no way for users to extend this.")
23106 ;;; General functions for all backends
23108 (defun org-cleaned-string-for-export (string &rest parameters)
23109 "Cleanup a buffer STRING so that links can be created safely."
23110 (interactive)
23111 (let* ((re-radio (and org-target-link-regexp
23112 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23113 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23114 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23115 (re-archive (concat ":" org-archive-tag ":"))
23116 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23117 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23118 (htmlp (plist-get parameters :for-html))
23119 (asciip (plist-get parameters :for-ascii))
23120 (latexp (plist-get parameters :for-LaTeX))
23121 (commentsp (plist-get parameters :comments))
23122 (archived-trees (plist-get parameters :archived-trees))
23123 (inhibit-read-only t)
23124 (drawers org-drawers)
23125 (exp-drawers (plist-get parameters :drawers))
23126 (outline-regexp "\\*+ ")
23127 a b xx
23128 rtn p)
23129 (with-current-buffer (get-buffer-create " org-mode-tmp")
23130 (erase-buffer)
23131 (insert string)
23132 ;; Remove license-to-kill stuff
23133 (while (setq p (text-property-any (point-min) (point-max)
23134 :org-license-to-kill t))
23135 (delete-region p (next-single-property-change p :org-license-to-kill)))
23137 (let ((org-inhibit-startup t)) (org-mode))
23138 (untabify (point-min) (point-max))
23140 ;; Get the correct stuff before the first headline
23141 (when (plist-get parameters :skip-before-1st-heading)
23142 (goto-char (point-min))
23143 (when (re-search-forward "^\\*+[ \t]" nil t)
23144 (delete-region (point-min) (match-beginning 0))
23145 (goto-char (point-min))
23146 (insert "\n")))
23147 (when (plist-get parameters :add-text)
23148 (goto-char (point-min))
23149 (insert (plist-get parameters :add-text) "\n"))
23151 ;; Get rid of archived trees
23152 (when (not (eq archived-trees t))
23153 (goto-char (point-min))
23154 (while (re-search-forward re-archive nil t)
23155 (if (not (org-on-heading-p t))
23156 (org-end-of-subtree t)
23157 (beginning-of-line 1)
23158 (setq a (if archived-trees
23159 (1+ (point-at-eol)) (point))
23160 b (org-end-of-subtree t))
23161 (if (> b a) (delete-region a b)))))
23163 ;; Get rid of drawers
23164 (unless (eq t exp-drawers)
23165 (goto-char (point-min))
23166 (let ((re (concat "^[ \t]*:\\("
23167 (mapconcat
23168 'identity
23169 (org-delete-all exp-drawers
23170 (copy-sequence drawers))
23171 "\\|")
23172 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23173 (while (re-search-forward re nil t)
23174 (replace-match ""))))
23176 ;; Find targets in comments and move them out of comments,
23177 ;; but mark them as targets that should be invisible
23178 (goto-char (point-min))
23179 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
23180 (replace-match "\\1(INVISIBLE)"))
23182 ;; Protect backend specific stuff, throw away the others.
23183 (let ((formatters
23184 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
23185 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
23186 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
23187 fmt)
23188 (goto-char (point-min))
23189 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
23190 (goto-char (match-end 0))
23191 (while (not (looking-at "#\\+END_EXAMPLE"))
23192 (insert ": ")
23193 (beginning-of-line 2)))
23194 (goto-char (point-min))
23195 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
23196 (add-text-properties (match-beginning 0) (match-end 0)
23197 '(org-protected t)))
23198 (while formatters
23199 (setq fmt (pop formatters))
23200 (when (car fmt)
23201 (goto-char (point-min))
23202 (while (re-search-forward (concat "^#\\+" (cadr fmt)
23203 ":[ \t]*\\(.*\\)") nil t)
23204 (replace-match "\\1" t)
23205 (add-text-properties
23206 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
23207 '(org-protected t))))
23208 (goto-char (point-min))
23209 (while (re-search-forward
23210 (concat "^#\\+"
23211 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
23212 (cadddr fmt) "\\>.*\n?") nil t)
23213 (if (car fmt)
23214 (add-text-properties (match-beginning 1) (1+ (match-end 1))
23215 '(org-protected t))
23216 (delete-region (match-beginning 0) (match-end 0))))))
23218 ;; Protect quoted subtrees
23219 (goto-char (point-min))
23220 (while (re-search-forward re-quote nil t)
23221 (goto-char (match-beginning 0))
23222 (end-of-line 1)
23223 (add-text-properties (point) (org-end-of-subtree t)
23224 '(org-protected t)))
23226 ;; Protect verbatim elements
23227 (goto-char (point-min))
23228 (while (re-search-forward org-verbatim-re nil t)
23229 (add-text-properties (match-beginning 4) (match-end 4)
23230 '(org-protected t))
23231 (goto-char (1+ (match-end 4))))
23233 ;; Remove subtrees that are commented
23234 (goto-char (point-min))
23235 (while (re-search-forward re-commented nil t)
23236 (goto-char (match-beginning 0))
23237 (delete-region (point) (org-end-of-subtree t)))
23239 ;; Remove special table lines
23240 (when org-export-table-remove-special-lines
23241 (goto-char (point-min))
23242 (while (re-search-forward "^[ \t]*|" nil t)
23243 (beginning-of-line 1)
23244 (if (or (looking-at "[ \t]*| *[!_^] *|")
23245 (and (looking-at ".*?| *<[0-9]+> *|")
23246 (not (looking-at ".*?| *[^ <|]"))))
23247 (delete-region (max (point-min) (1- (point-at-bol)))
23248 (point-at-eol))
23249 (end-of-line 1))))
23251 ;; Specific LaTeX stuff
23252 (when latexp
23253 (require 'org-export-latex nil)
23254 (org-export-latex-cleaned-string))
23256 (when asciip
23257 (org-export-ascii-clean-string))
23259 ;; Specific HTML stuff
23260 (when htmlp
23261 ;; Convert LaTeX fragments to images
23262 (when (plist-get parameters :LaTeX-fragments)
23263 (org-format-latex
23264 (concat "ltxpng/" (file-name-sans-extension
23265 (file-name-nondirectory
23266 org-current-export-file)))
23267 org-current-export-dir nil "Creating LaTeX image %s"))
23268 (message "Exporting..."))
23270 ;; Remove or replace comments
23271 (goto-char (point-min))
23272 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
23273 (if commentsp
23274 (progn (add-text-properties
23275 (match-beginning 0) (match-end 0) '(org-protected t))
23276 (replace-match (format commentsp (match-string 1)) t t))
23277 (replace-match "")))
23279 ;; Find matches for radio targets and turn them into internal links
23280 (goto-char (point-min))
23281 (when re-radio
23282 (while (re-search-forward re-radio nil t)
23283 (org-if-unprotected
23284 (replace-match "\\1[[\\2]]"))))
23286 ;; Find all links that contain a newline and put them into a single line
23287 (goto-char (point-min))
23288 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
23289 (org-if-unprotected
23290 (replace-match "\\1 \\3")
23291 (goto-char (match-beginning 0))))
23294 ;; Normalize links: Convert angle and plain links into bracket links
23295 ;; Expand link abbreviations
23296 (goto-char (point-min))
23297 (while (re-search-forward re-plain-link nil t)
23298 (goto-char (1- (match-end 0)))
23299 (org-if-unprotected
23300 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23301 ":" (match-string 3) "]]")))
23302 ;; added 'org-link face to links
23303 (put-text-property 0 (length s) 'face 'org-link s)
23304 (replace-match s t t))))
23305 (goto-char (point-min))
23306 (while (re-search-forward re-angle-link nil t)
23307 (goto-char (1- (match-end 0)))
23308 (org-if-unprotected
23309 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23310 ":" (match-string 3) "]]")))
23311 (put-text-property 0 (length s) 'face 'org-link s)
23312 (replace-match s t t))))
23313 (goto-char (point-min))
23314 (while (re-search-forward org-bracket-link-regexp nil t)
23315 (org-if-unprotected
23316 (let* ((s (concat "[[" (setq xx (save-match-data
23317 (org-link-expand-abbrev (match-string 1))))
23319 (if (match-end 3)
23320 (match-string 2)
23321 (concat "[" xx "]"))
23322 "]")))
23323 (put-text-property 0 (length s) 'face 'org-link s)
23324 (replace-match s t t))))
23326 ;; Find multiline emphasis and put them into single line
23327 (when (plist-get parameters :emph-multiline)
23328 (goto-char (point-min))
23329 (while (re-search-forward org-emph-re nil t)
23330 (if (not (= (char-after (match-beginning 3))
23331 (char-after (match-beginning 4))))
23332 (org-if-unprotected
23333 (subst-char-in-region (match-beginning 0) (match-end 0)
23334 ?\n ?\ t)
23335 (goto-char (1- (match-end 0))))
23336 (goto-char (1+ (match-beginning 0))))))
23338 (setq rtn (buffer-string)))
23339 (kill-buffer " org-mode-tmp")
23340 rtn))
23342 (defun org-export-grab-title-from-buffer ()
23343 "Get a title for the current document, from looking at the buffer."
23344 (let ((inhibit-read-only t))
23345 (save-excursion
23346 (goto-char (point-min))
23347 (let ((end (save-excursion (outline-next-heading) (point))))
23348 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
23349 ;; Mark the line so that it will not be exported as normal text.
23350 (org-unmodified
23351 (add-text-properties (match-beginning 0) (match-end 0)
23352 (list :org-license-to-kill t)))
23353 ;; Return the title string
23354 (org-trim (match-string 0)))))))
23356 (defun org-export-get-title-from-subtree ()
23357 "Return subtree title and exclude it from export."
23358 (let (title (m (mark)))
23359 (save-excursion
23360 (goto-char (region-beginning))
23361 (when (and (org-at-heading-p)
23362 (>= (org-end-of-subtree t t) (region-end)))
23363 ;; This is a subtree, we take the title from the first heading
23364 (goto-char (region-beginning))
23365 (looking-at org-todo-line-regexp)
23366 (setq title (match-string 3))
23367 (org-unmodified
23368 (add-text-properties (point) (1+ (point-at-eol))
23369 (list :org-license-to-kill t)))))
23370 title))
23372 (defun org-solidify-link-text (s &optional alist)
23373 "Take link text and make a safe target out of it."
23374 (save-match-data
23375 (let* ((rtn
23376 (mapconcat
23377 'identity
23378 (org-split-string s "[ \t\r\n]+") "--"))
23379 (a (assoc rtn alist)))
23380 (or (cdr a) rtn))))
23382 (defun org-get-min-level (lines)
23383 "Get the minimum level in LINES."
23384 (let ((re "^\\(\\*+\\) ") l min)
23385 (catch 'exit
23386 (while (setq l (pop lines))
23387 (if (string-match re l)
23388 (throw 'exit (org-tr-level (length (match-string 1 l))))))
23389 1)))
23391 ;; Variable holding the vector with section numbers
23392 (defvar org-section-numbers (make-vector org-level-max 0))
23394 (defun org-init-section-numbers ()
23395 "Initialize the vector for the section numbers."
23396 (let* ((level -1)
23397 (numbers (nreverse (org-split-string "" "\\.")))
23398 (depth (1- (length org-section-numbers)))
23399 (i depth) number-string)
23400 (while (>= i 0)
23401 (if (> i level)
23402 (aset org-section-numbers i 0)
23403 (setq number-string (or (car numbers) "0"))
23404 (if (string-match "\\`[A-Z]\\'" number-string)
23405 (aset org-section-numbers i
23406 (- (string-to-char number-string) ?A -1))
23407 (aset org-section-numbers i (string-to-number number-string)))
23408 (pop numbers))
23409 (setq i (1- i)))))
23411 (defun org-section-number (&optional level)
23412 "Return a string with the current section number.
23413 When LEVEL is non-nil, increase section numbers on that level."
23414 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
23415 (when level
23416 (when (> level -1)
23417 (aset org-section-numbers
23418 level (1+ (aref org-section-numbers level))))
23419 (setq idx (1+ level))
23420 (while (<= idx depth)
23421 (if (not (= idx 1))
23422 (aset org-section-numbers idx 0))
23423 (setq idx (1+ idx))))
23424 (setq idx 0)
23425 (while (<= idx depth)
23426 (setq n (aref org-section-numbers idx))
23427 (setq string (concat string (if (not (string= string "")) "." "")
23428 (int-to-string n)))
23429 (setq idx (1+ idx)))
23430 (save-match-data
23431 (if (string-match "\\`\\([@0]\\.\\)+" string)
23432 (setq string (replace-match "" t nil string)))
23433 (if (string-match "\\(\\.0\\)+\\'" string)
23434 (setq string (replace-match "" t nil string))))
23435 string))
23437 ;;; ASCII export
23439 (defvar org-last-level nil) ; dynamically scoped variable
23440 (defvar org-min-level nil) ; dynamically scoped variable
23441 (defvar org-levels-open nil) ; dynamically scoped parameter
23442 (defvar org-ascii-current-indentation nil) ; For communication
23444 (defun org-export-as-ascii (arg)
23445 "Export the outline as a pretty ASCII file.
23446 If there is an active region, export only the region.
23447 The prefix ARG specifies how many levels of the outline should become
23448 underlined headlines. The default is 3."
23449 (interactive "P")
23450 (setq-default org-todo-line-regexp org-todo-line-regexp)
23451 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23452 (org-infile-export-plist)))
23453 (region-p (org-region-active-p))
23454 (subtree-p
23455 (when region-p
23456 (save-excursion
23457 (goto-char (region-beginning))
23458 (and (org-at-heading-p)
23459 (>= (org-end-of-subtree t t) (region-end))))))
23460 (custom-times org-display-custom-times)
23461 (org-ascii-current-indentation '(0 . 0))
23462 (level 0) line txt
23463 (umax nil)
23464 (umax-toc nil)
23465 (case-fold-search nil)
23466 (filename (concat (file-name-as-directory
23467 (org-export-directory :ascii opt-plist))
23468 (file-name-sans-extension
23469 (or (and subtree-p
23470 (org-entry-get (region-beginning)
23471 "EXPORT_FILE_NAME" t))
23472 (file-name-nondirectory buffer-file-name)))
23473 ".txt"))
23474 (filename (if (equal (file-truename filename)
23475 (file-truename buffer-file-name))
23476 (concat filename ".txt")
23477 filename))
23478 (buffer (find-file-noselect filename))
23479 (org-levels-open (make-vector org-level-max nil))
23480 (odd org-odd-levels-only)
23481 (date (plist-get opt-plist :date))
23482 (author (plist-get opt-plist :author))
23483 (title (or (and subtree-p (org-export-get-title-from-subtree))
23484 (plist-get opt-plist :title)
23485 (and (not
23486 (plist-get opt-plist :skip-before-1st-heading))
23487 (org-export-grab-title-from-buffer))
23488 (file-name-sans-extension
23489 (file-name-nondirectory buffer-file-name))))
23490 (email (plist-get opt-plist :email))
23491 (language (plist-get opt-plist :language))
23492 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
23493 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
23494 (todo nil)
23495 (lang-words nil)
23496 (region
23497 (buffer-substring
23498 (if (org-region-active-p) (region-beginning) (point-min))
23499 (if (org-region-active-p) (region-end) (point-max))))
23500 (lines (org-split-string
23501 (org-cleaned-string-for-export
23502 region
23503 :for-ascii t
23504 :skip-before-1st-heading
23505 (plist-get opt-plist :skip-before-1st-heading)
23506 :drawers (plist-get opt-plist :drawers)
23507 :verbatim-multiline t
23508 :archived-trees
23509 (plist-get opt-plist :archived-trees)
23510 :add-text (plist-get opt-plist :text))
23511 "\n"))
23512 thetoc have-headings first-heading-pos
23513 table-open table-buffer)
23515 (let ((inhibit-read-only t))
23516 (org-unmodified
23517 (remove-text-properties (point-min) (point-max)
23518 '(:org-license-to-kill t))))
23520 (setq org-min-level (org-get-min-level lines))
23521 (setq org-last-level org-min-level)
23522 (org-init-section-numbers)
23524 (find-file-noselect filename)
23526 (setq lang-words (or (assoc language org-export-language-setup)
23527 (assoc "en" org-export-language-setup)))
23528 (switch-to-buffer-other-window buffer)
23529 (erase-buffer)
23530 (fundamental-mode)
23531 ;; create local variables for all options, to make sure all called
23532 ;; functions get the correct information
23533 (mapc (lambda (x)
23534 (set (make-local-variable (cdr x))
23535 (plist-get opt-plist (car x))))
23536 org-export-plist-vars)
23537 (org-set-local 'org-odd-levels-only odd)
23538 (setq umax (if arg (prefix-numeric-value arg)
23539 org-export-headline-levels))
23540 (setq umax-toc (if (integerp org-export-with-toc)
23541 (min org-export-with-toc umax)
23542 umax))
23544 ;; File header
23545 (if title (org-insert-centered title ?=))
23546 (insert "\n")
23547 (if (and (or author email)
23548 org-export-author-info)
23549 (insert (concat (nth 1 lang-words) ": " (or author "")
23550 (if email (concat " <" email ">") "")
23551 "\n")))
23553 (cond
23554 ((and date (string-match "%" date))
23555 (setq date (format-time-string date (current-time))))
23556 (date)
23557 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
23559 (if (and date org-export-time-stamp-file)
23560 (insert (concat (nth 2 lang-words) ": " date"\n")))
23562 (insert "\n\n")
23564 (if org-export-with-toc
23565 (progn
23566 (push (concat (nth 3 lang-words) "\n") thetoc)
23567 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
23568 (mapc '(lambda (line)
23569 (if (string-match org-todo-line-regexp
23570 line)
23571 ;; This is a headline
23572 (progn
23573 (setq have-headings t)
23574 (setq level (- (match-end 1) (match-beginning 1))
23575 level (org-tr-level level)
23576 txt (match-string 3 line)
23577 todo
23578 (or (and org-export-mark-todo-in-toc
23579 (match-beginning 2)
23580 (not (member (match-string 2 line)
23581 org-done-keywords)))
23582 ; TODO, not DONE
23583 (and org-export-mark-todo-in-toc
23584 (= level umax-toc)
23585 (org-search-todo-below
23586 line lines level))))
23587 (setq txt (org-html-expand-for-ascii txt))
23589 (while (string-match org-bracket-link-regexp txt)
23590 (setq txt
23591 (replace-match
23592 (match-string (if (match-end 2) 3 1) txt)
23593 t t txt)))
23595 (if (and (memq org-export-with-tags '(not-in-toc nil))
23596 (string-match
23597 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
23598 txt))
23599 (setq txt (replace-match "" t t txt)))
23600 (if (string-match quote-re0 txt)
23601 (setq txt (replace-match "" t t txt)))
23603 (if org-export-with-section-numbers
23604 (setq txt (concat (org-section-number level)
23605 " " txt)))
23606 (if (<= level umax-toc)
23607 (progn
23608 (push
23609 (concat
23610 (make-string
23611 (* (max 0 (- level org-min-level)) 4) ?\ )
23612 (format (if todo "%s (*)\n" "%s\n") txt))
23613 thetoc)
23614 (setq org-last-level level))
23615 ))))
23616 lines)
23617 (setq thetoc (if have-headings (nreverse thetoc) nil))))
23619 (org-init-section-numbers)
23620 (while (setq line (pop lines))
23621 ;; Remove the quoted HTML tags.
23622 (setq line (org-html-expand-for-ascii line))
23623 ;; Remove targets
23624 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
23625 (setq line (replace-match "" t t line)))
23626 ;; Replace internal links
23627 (while (string-match org-bracket-link-regexp line)
23628 (setq line (replace-match
23629 (if (match-end 3) "[\\3]" "[\\1]")
23630 t nil line)))
23631 (when custom-times
23632 (setq line (org-translate-time line)))
23633 (cond
23634 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
23635 ;; a Headline
23636 (setq first-heading-pos (or first-heading-pos (point)))
23637 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
23638 txt (match-string 2 line))
23639 (org-ascii-level-start level txt umax lines))
23641 ((and org-export-with-tables
23642 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
23643 (if (not table-open)
23644 ;; New table starts
23645 (setq table-open t table-buffer nil))
23646 ;; Accumulate lines
23647 (setq table-buffer (cons line table-buffer))
23648 (when (or (not lines)
23649 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
23650 (car lines))))
23651 (setq table-open nil
23652 table-buffer (nreverse table-buffer))
23653 (insert (mapconcat
23654 (lambda (x)
23655 (org-fix-indentation x org-ascii-current-indentation))
23656 (org-format-table-ascii table-buffer)
23657 "\n") "\n")))
23659 (setq line (org-fix-indentation line org-ascii-current-indentation))
23660 (if (and org-export-with-fixed-width
23661 (string-match "^\\([ \t]*\\)\\(:\\)" line))
23662 (setq line (replace-match "\\1" nil nil line)))
23663 (insert line "\n"))))
23665 (normal-mode)
23667 ;; insert the table of contents
23668 (when thetoc
23669 (goto-char (point-min))
23670 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
23671 (progn
23672 (goto-char (match-beginning 0))
23673 (replace-match ""))
23674 (goto-char first-heading-pos))
23675 (mapc 'insert thetoc)
23676 (or (looking-at "[ \t]*\n[ \t]*\n")
23677 (insert "\n\n")))
23679 ;; Convert whitespace place holders
23680 (goto-char (point-min))
23681 (let (beg end)
23682 (while (setq beg (next-single-property-change (point) 'org-whitespace))
23683 (setq end (next-single-property-change beg 'org-whitespace))
23684 (goto-char beg)
23685 (delete-region beg end)
23686 (insert (make-string (- end beg) ?\ ))))
23688 (save-buffer)
23689 ;; remove display and invisible chars
23690 (let (beg end)
23691 (goto-char (point-min))
23692 (while (setq beg (next-single-property-change (point) 'display))
23693 (setq end (next-single-property-change beg 'display))
23694 (delete-region beg end)
23695 (goto-char beg)
23696 (insert "=>"))
23697 (goto-char (point-min))
23698 (while (setq beg (next-single-property-change (point) 'org-cwidth))
23699 (setq end (next-single-property-change beg 'org-cwidth))
23700 (delete-region beg end)
23701 (goto-char beg)))
23702 (goto-char (point-min))))
23704 (defun org-export-ascii-clean-string ()
23705 "Do extra work for ASCII export"
23706 (goto-char (point-min))
23707 (while (re-search-forward org-verbatim-re nil t)
23708 (goto-char (match-end 2))
23709 (backward-delete-char 1) (insert "'")
23710 (goto-char (match-beginning 2))
23711 (delete-char 1) (insert "`")
23712 (goto-char (match-end 2))))
23714 (defun org-search-todo-below (line lines level)
23715 "Search the subtree below LINE for any TODO entries."
23716 (let ((rest (cdr (memq line lines)))
23717 (re org-todo-line-regexp)
23718 line lv todo)
23719 (catch 'exit
23720 (while (setq line (pop rest))
23721 (if (string-match re line)
23722 (progn
23723 (setq lv (- (match-end 1) (match-beginning 1))
23724 todo (and (match-beginning 2)
23725 (not (member (match-string 2 line)
23726 org-done-keywords))))
23727 ; TODO, not DONE
23728 (if (<= lv level) (throw 'exit nil))
23729 (if todo (throw 'exit t))))))))
23731 (defun org-html-expand-for-ascii (line)
23732 "Handle quoted HTML for ASCII export."
23733 (if org-export-html-expand
23734 (while (string-match "@<[^<>\n]*>" line)
23735 ;; We just remove the tags for now.
23736 (setq line (replace-match "" nil nil line))))
23737 line)
23739 (defun org-insert-centered (s &optional underline)
23740 "Insert the string S centered and underline it with character UNDERLINE."
23741 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
23742 (insert (make-string ind ?\ ) s "\n")
23743 (if underline
23744 (insert (make-string ind ?\ )
23745 (make-string (string-width s) underline)
23746 "\n"))))
23748 (defun org-ascii-level-start (level title umax &optional lines)
23749 "Insert a new level in ASCII export."
23750 (let (char (n (- level umax 1)) (ind 0))
23751 (if (> level umax)
23752 (progn
23753 (insert (make-string (* 2 n) ?\ )
23754 (char-to-string (nth (% n (length org-export-ascii-bullets))
23755 org-export-ascii-bullets))
23756 " " title "\n")
23757 ;; find the indentation of the next non-empty line
23758 (catch 'stop
23759 (while lines
23760 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
23761 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
23762 (throw 'stop (setq ind (org-get-indentation (car lines)))))
23763 (pop lines)))
23764 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
23765 (if (or (not (equal (char-before) ?\n))
23766 (not (equal (char-before (1- (point))) ?\n)))
23767 (insert "\n"))
23768 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
23769 (unless org-export-with-tags
23770 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
23771 (setq title (replace-match "" t t title))))
23772 (if org-export-with-section-numbers
23773 (setq title (concat (org-section-number level) " " title)))
23774 (insert title "\n" (make-string (string-width title) char) "\n")
23775 (setq org-ascii-current-indentation '(0 . 0)))))
23777 (defun org-export-visible (type arg)
23778 "Create a copy of the visible part of the current buffer, and export it.
23779 The copy is created in a temporary buffer and removed after use.
23780 TYPE is the final key (as a string) that also select the export command in
23781 the `C-c C-e' export dispatcher.
23782 As a special case, if the you type SPC at the prompt, the temporary
23783 org-mode file will not be removed but presented to you so that you can
23784 continue to use it. The prefix arg ARG is passed through to the exporting
23785 command."
23786 (interactive
23787 (list (progn
23788 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
23789 (read-char-exclusive))
23790 current-prefix-arg))
23791 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
23792 (error "Invalid export key"))
23793 (let* ((binding (cdr (assoc type
23794 '((?a . org-export-as-ascii)
23795 (?\C-a . org-export-as-ascii)
23796 (?b . org-export-as-html-and-open)
23797 (?\C-b . org-export-as-html-and-open)
23798 (?h . org-export-as-html)
23799 (?H . org-export-as-html-to-buffer)
23800 (?R . org-export-region-as-html)
23801 (?x . org-export-as-xoxo)))))
23802 (keepp (equal type ?\ ))
23803 (file buffer-file-name)
23804 (buffer (get-buffer-create "*Org Export Visible*"))
23805 s e)
23806 ;; Need to hack the drawers here.
23807 (save-excursion
23808 (goto-char (point-min))
23809 (while (re-search-forward org-drawer-regexp nil t)
23810 (goto-char (match-beginning 1))
23811 (or (org-invisible-p) (org-flag-drawer nil))))
23812 (with-current-buffer buffer (erase-buffer))
23813 (save-excursion
23814 (setq s (goto-char (point-min)))
23815 (while (not (= (point) (point-max)))
23816 (goto-char (org-find-invisible))
23817 (append-to-buffer buffer s (point))
23818 (setq s (goto-char (org-find-visible))))
23819 (org-cycle-hide-drawers 'all)
23820 (goto-char (point-min))
23821 (unless keepp
23822 ;; Copy all comment lines to the end, to make sure #+ settings are
23823 ;; still available for the second export step. Kind of a hack, but
23824 ;; does do the trick.
23825 (if (looking-at "#[^\r\n]*")
23826 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
23827 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
23828 (append-to-buffer buffer (1+ (match-beginning 0))
23829 (min (point-max) (1+ (match-end 0))))))
23830 (set-buffer buffer)
23831 (let ((buffer-file-name file)
23832 (org-inhibit-startup t))
23833 (org-mode)
23834 (show-all)
23835 (unless keepp (funcall binding arg))))
23836 (if (not keepp)
23837 (kill-buffer buffer)
23838 (switch-to-buffer-other-window buffer)
23839 (goto-char (point-min)))))
23841 (defun org-find-visible ()
23842 (let ((s (point)))
23843 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23844 (get-char-property s 'invisible)))
23846 (defun org-find-invisible ()
23847 (let ((s (point)))
23848 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23849 (not (get-char-property s 'invisible))))
23852 ;;; HTML export
23854 (defun org-get-current-options ()
23855 "Return a string with current options as keyword options.
23856 Does include HTML export options as well as TODO and CATEGORY stuff."
23857 (format
23858 "#+TITLE: %s
23859 #+AUTHOR: %s
23860 #+EMAIL: %s
23861 #+LANGUAGE: %s
23862 #+TEXT: Some descriptive text to be emitted. Several lines OK.
23863 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s -:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s d:%s tags:%s
23864 #+CATEGORY: %s
23865 #+SEQ_TODO: %s
23866 #+TYP_TODO: %s
23867 #+PRIORITIES: %c %c %c
23868 #+DRAWERS: %s
23869 #+STARTUP: %s %s %s %s %s
23870 #+TAGS: %s
23871 #+ARCHIVE: %s
23872 #+LINK: %s
23874 (buffer-name) (user-full-name) user-mail-address org-export-default-language
23875 org-export-headline-levels
23876 org-export-with-section-numbers
23877 org-export-with-toc
23878 org-export-preserve-breaks
23879 org-export-html-expand
23880 org-export-with-fixed-width
23881 org-export-with-tables
23882 org-export-with-sub-superscripts
23883 org-export-with-special-strings
23884 org-export-with-footnotes
23885 org-export-with-emphasize
23886 org-export-with-TeX-macros
23887 org-export-with-LaTeX-fragments
23888 org-export-skip-text-before-1st-heading
23889 org-export-with-drawers
23890 org-export-with-tags
23891 (file-name-nondirectory buffer-file-name)
23892 "TODO FEEDBACK VERIFY DONE"
23893 "Me Jason Marie DONE"
23894 org-highest-priority org-lowest-priority org-default-priority
23895 (mapconcat 'identity org-drawers " ")
23896 (cdr (assoc org-startup-folded
23897 '((nil . "showall") (t . "overview") (content . "content"))))
23898 (if org-odd-levels-only "odd" "oddeven")
23899 (if org-hide-leading-stars "hidestars" "showstars")
23900 (if org-startup-align-all-tables "align" "noalign")
23901 (cond ((eq t org-log-done) "logdone")
23902 ((not org-log-done) "nologging")
23903 ((listp org-log-done)
23904 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
23905 org-log-done " ")))
23906 (or (mapconcat (lambda (x)
23907 (cond
23908 ((equal '(:startgroup) x) "{")
23909 ((equal '(:endgroup) x) "}")
23910 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
23911 (t (car x))))
23912 (or org-tag-alist (org-get-buffer-tags)) " ") "")
23913 org-archive-location
23914 "org file:~/org/%s.org"
23917 (defun org-insert-export-options-template ()
23918 "Insert into the buffer a template with information for exporting."
23919 (interactive)
23920 (if (not (bolp)) (newline))
23921 (let ((s (org-get-current-options)))
23922 (and (string-match "#\\+CATEGORY" s)
23923 (setq s (substring s 0 (match-beginning 0))))
23924 (insert s)))
23926 (defun org-toggle-fixed-width-section (arg)
23927 "Toggle the fixed-width export.
23928 If there is no active region, the QUOTE keyword at the current headline is
23929 inserted or removed. When present, it causes the text between this headline
23930 and the next to be exported as fixed-width text, and unmodified.
23931 If there is an active region, this command adds or removes a colon as the
23932 first character of this line. If the first character of a line is a colon,
23933 this line is also exported in fixed-width font."
23934 (interactive "P")
23935 (let* ((cc 0)
23936 (regionp (org-region-active-p))
23937 (beg (if regionp (region-beginning) (point)))
23938 (end (if regionp (region-end)))
23939 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
23940 (case-fold-search nil)
23941 (re "[ \t]*\\(:\\)")
23942 off)
23943 (if regionp
23944 (save-excursion
23945 (goto-char beg)
23946 (setq cc (current-column))
23947 (beginning-of-line 1)
23948 (setq off (looking-at re))
23949 (while (> nlines 0)
23950 (setq nlines (1- nlines))
23951 (beginning-of-line 1)
23952 (cond
23953 (arg
23954 (move-to-column cc t)
23955 (insert ":\n")
23956 (forward-line -1))
23957 ((and off (looking-at re))
23958 (replace-match "" t t nil 1))
23959 ((not off) (move-to-column cc t) (insert ":")))
23960 (forward-line 1)))
23961 (save-excursion
23962 (org-back-to-heading)
23963 (if (looking-at (concat outline-regexp
23964 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
23965 (replace-match "" t t nil 1)
23966 (if (looking-at outline-regexp)
23967 (progn
23968 (goto-char (match-end 0))
23969 (insert org-quote-string " "))))))))
23971 (defun org-export-as-html-and-open (arg)
23972 "Export the outline as HTML and immediately open it with a browser.
23973 If there is an active region, export only the region.
23974 The prefix ARG specifies how many levels of the outline should become
23975 headlines. The default is 3. Lower levels will become bulleted lists."
23976 (interactive "P")
23977 (org-export-as-html arg 'hidden)
23978 (org-open-file buffer-file-name))
23980 (defun org-export-as-html-batch ()
23981 "Call `org-export-as-html', may be used in batch processing as
23982 emacs --batch
23983 --load=$HOME/lib/emacs/org.el
23984 --eval \"(setq org-export-headline-levels 2)\"
23985 --visit=MyFile --funcall org-export-as-html-batch"
23986 (org-export-as-html org-export-headline-levels 'hidden))
23988 (defun org-export-as-html-to-buffer (arg)
23989 "Call `org-exort-as-html` with output to a temporary buffer.
23990 No file is created. The prefix ARG is passed through to `org-export-as-html'."
23991 (interactive "P")
23992 (org-export-as-html arg nil nil "*Org HTML Export*")
23993 (switch-to-buffer-other-window "*Org HTML Export*"))
23995 (defun org-replace-region-by-html (beg end)
23996 "Assume the current region has org-mode syntax, and convert it to HTML.
23997 This can be used in any buffer. For example, you could write an
23998 itemized list in org-mode syntax in an HTML buffer and then use this
23999 command to convert it."
24000 (interactive "r")
24001 (let (reg html buf pop-up-frames)
24002 (save-window-excursion
24003 (if (org-mode-p)
24004 (setq html (org-export-region-as-html
24005 beg end t 'string))
24006 (setq reg (buffer-substring beg end)
24007 buf (get-buffer-create "*Org tmp*"))
24008 (with-current-buffer buf
24009 (erase-buffer)
24010 (insert reg)
24011 (org-mode)
24012 (setq html (org-export-region-as-html
24013 (point-min) (point-max) t 'string)))
24014 (kill-buffer buf)))
24015 (delete-region beg end)
24016 (insert html)))
24018 (defun org-export-region-as-html (beg end &optional body-only buffer)
24019 "Convert region from BEG to END in org-mode buffer to HTML.
24020 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24021 contents, and only produce the region of converted text, useful for
24022 cut-and-paste operations.
24023 If BUFFER is a buffer or a string, use/create that buffer as a target
24024 of the converted HTML. If BUFFER is the symbol `string', return the
24025 produced HTML as a string and leave not buffer behind. For example,
24026 a Lisp program could call this function in the following way:
24028 (setq html (org-export-region-as-html beg end t 'string))
24030 When called interactively, the output buffer is selected, and shown
24031 in a window. A non-interactive call will only retunr the buffer."
24032 (interactive "r\nP")
24033 (when (interactive-p)
24034 (setq buffer "*Org HTML Export*"))
24035 (let ((transient-mark-mode t) (zmacs-regions t)
24036 rtn)
24037 (goto-char end)
24038 (set-mark (point)) ;; to activate the region
24039 (goto-char beg)
24040 (setq rtn (org-export-as-html
24041 nil nil nil
24042 buffer body-only))
24043 (if (fboundp 'deactivate-mark) (deactivate-mark))
24044 (if (and (interactive-p) (bufferp rtn))
24045 (switch-to-buffer-other-window rtn)
24046 rtn)))
24048 (defvar html-table-tag nil) ; dynamically scoped into this.
24049 (defun org-export-as-html (arg &optional hidden ext-plist
24050 to-buffer body-only)
24051 "Export the outline as a pretty HTML file.
24052 If there is an active region, export only the region. The prefix
24053 ARG specifies how many levels of the outline should become
24054 headlines. The default is 3. Lower levels will become bulleted
24055 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24056 EXT-PLIST is a property list with external parameters overriding
24057 org-mode's default settings, but still inferior to file-local
24058 settings. When TO-BUFFER is non-nil, create a buffer with that
24059 name and export to that buffer. If TO-BUFFER is the symbol `string',
24060 don't leave any buffer behind but just return the resulting HTML as
24061 a string. When BODY-ONLY is set, don't produce the file header and footer,
24062 simply return the content of <body>...</body>, without even
24063 the body tags themselves."
24064 (interactive "P")
24066 ;; Make sure we have a file name when we need it.
24067 (when (and (not (or to-buffer body-only))
24068 (not buffer-file-name))
24069 (if (buffer-base-buffer)
24070 (org-set-local 'buffer-file-name
24071 (with-current-buffer (buffer-base-buffer)
24072 buffer-file-name))
24073 (error "Need a file name to be able to export.")))
24075 (message "Exporting...")
24076 (setq-default org-todo-line-regexp org-todo-line-regexp)
24077 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24078 (setq-default org-done-keywords org-done-keywords)
24079 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24080 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24081 ext-plist
24082 (org-infile-export-plist)))
24084 (style (plist-get opt-plist :style))
24085 (link-validate (plist-get opt-plist :link-validation-function))
24086 valid thetoc have-headings first-heading-pos
24087 (odd org-odd-levels-only)
24088 (region-p (org-region-active-p))
24089 (subtree-p
24090 (when region-p
24091 (save-excursion
24092 (goto-char (region-beginning))
24093 (and (org-at-heading-p)
24094 (>= (org-end-of-subtree t t) (region-end))))))
24095 ;; The following two are dynamically scoped into other
24096 ;; routines below.
24097 (org-current-export-dir (org-export-directory :html opt-plist))
24098 (org-current-export-file buffer-file-name)
24099 (level 0) (line "") (origline "") txt todo
24100 (umax nil)
24101 (umax-toc nil)
24102 (filename (if to-buffer nil
24103 (concat (file-name-as-directory
24104 (org-export-directory :html opt-plist))
24105 (file-name-sans-extension
24106 (or (and subtree-p
24107 (org-entry-get (region-beginning)
24108 "EXPORT_FILE_NAME" t))
24109 (file-name-nondirectory buffer-file-name)))
24110 "." org-export-html-extension)))
24111 (current-dir (if buffer-file-name
24112 (file-name-directory buffer-file-name)
24113 default-directory))
24114 (buffer (if to-buffer
24115 (cond
24116 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24117 (t (get-buffer-create to-buffer)))
24118 (find-file-noselect filename)))
24119 (org-levels-open (make-vector org-level-max nil))
24120 (date (plist-get opt-plist :date))
24121 (author (plist-get opt-plist :author))
24122 (title (or (and subtree-p (org-export-get-title-from-subtree))
24123 (plist-get opt-plist :title)
24124 (and (not
24125 (plist-get opt-plist :skip-before-1st-heading))
24126 (org-export-grab-title-from-buffer))
24127 (and buffer-file-name
24128 (file-name-sans-extension
24129 (file-name-nondirectory buffer-file-name)))
24130 "UNTITLED"))
24131 (html-table-tag (plist-get opt-plist :html-table-tag))
24132 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24133 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24134 (inquote nil)
24135 (infixed nil)
24136 (in-local-list nil)
24137 (local-list-num nil)
24138 (local-list-indent nil)
24139 (llt org-plain-list-ordered-item-terminator)
24140 (email (plist-get opt-plist :email))
24141 (language (plist-get opt-plist :language))
24142 (lang-words nil)
24143 (target-alist nil) tg
24144 (head-count 0) cnt
24145 (start 0)
24146 (coding-system (and (boundp 'buffer-file-coding-system)
24147 buffer-file-coding-system))
24148 (coding-system-for-write (or org-export-html-coding-system
24149 coding-system))
24150 (save-buffer-coding-system (or org-export-html-coding-system
24151 coding-system))
24152 (charset (and coding-system-for-write
24153 (fboundp 'coding-system-get)
24154 (coding-system-get coding-system-for-write
24155 'mime-charset)))
24156 (region
24157 (buffer-substring
24158 (if region-p (region-beginning) (point-min))
24159 (if region-p (region-end) (point-max))))
24160 (lines
24161 (org-split-string
24162 (org-cleaned-string-for-export
24163 region
24164 :emph-multiline t
24165 :for-html t
24166 :skip-before-1st-heading
24167 (plist-get opt-plist :skip-before-1st-heading)
24168 :drawers (plist-get opt-plist :drawers)
24169 :archived-trees
24170 (plist-get opt-plist :archived-trees)
24171 :add-text
24172 (plist-get opt-plist :text)
24173 :LaTeX-fragments
24174 (plist-get opt-plist :LaTeX-fragments))
24175 "[\r\n]"))
24176 table-open type
24177 table-buffer table-orig-buffer
24178 ind start-is-num starter didclose
24179 rpl path desc descp desc1 desc2 link
24182 (let ((inhibit-read-only t))
24183 (org-unmodified
24184 (remove-text-properties (point-min) (point-max)
24185 '(:org-license-to-kill t))))
24187 (message "Exporting...")
24189 (setq org-min-level (org-get-min-level lines))
24190 (setq org-last-level org-min-level)
24191 (org-init-section-numbers)
24193 (cond
24194 ((and date (string-match "%" date))
24195 (setq date (format-time-string date (current-time))))
24196 (date)
24197 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24199 ;; Get the language-dependent settings
24200 (setq lang-words (or (assoc language org-export-language-setup)
24201 (assoc "en" org-export-language-setup)))
24203 ;; Switch to the output buffer
24204 (set-buffer buffer)
24205 (erase-buffer)
24206 (fundamental-mode)
24208 (and (fboundp 'set-buffer-file-coding-system)
24209 (set-buffer-file-coding-system coding-system-for-write))
24211 (let ((case-fold-search nil)
24212 (org-odd-levels-only odd))
24213 ;; create local variables for all options, to make sure all called
24214 ;; functions get the correct information
24215 (mapc (lambda (x)
24216 (set (make-local-variable (cdr x))
24217 (plist-get opt-plist (car x))))
24218 org-export-plist-vars)
24219 (setq umax (if arg (prefix-numeric-value arg)
24220 org-export-headline-levels))
24221 (setq umax-toc (if (integerp org-export-with-toc)
24222 (min org-export-with-toc umax)
24223 umax))
24224 (unless body-only
24225 ;; File header
24226 (insert (format
24227 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
24228 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
24229 <html xmlns=\"http://www.w3.org/1999/xhtml\"
24230 lang=\"%s\" xml:lang=\"%s\">
24231 <head>
24232 <title>%s</title>
24233 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
24234 <meta name=\"generator\" content=\"Org-mode\"/>
24235 <meta name=\"generated\" content=\"%s\"/>
24236 <meta name=\"author\" content=\"%s\"/>
24238 </head><body>
24240 language language (org-html-expand title)
24241 (or charset "iso-8859-1") date author style))
24243 (insert (or (plist-get opt-plist :preamble) ""))
24245 (when (plist-get opt-plist :auto-preamble)
24246 (if title (insert (format org-export-html-title-format
24247 (org-html-expand title))))))
24249 (if (and org-export-with-toc (not body-only))
24250 (progn
24251 (push (format "<h%d>%s</h%d>\n"
24252 org-export-html-toplevel-hlevel
24253 (nth 3 lang-words)
24254 org-export-html-toplevel-hlevel)
24255 thetoc)
24256 (push "<ul>\n<li>" thetoc)
24257 (setq lines
24258 (mapcar '(lambda (line)
24259 (if (string-match org-todo-line-regexp line)
24260 ;; This is a headline
24261 (progn
24262 (setq have-headings t)
24263 (setq level (- (match-end 1) (match-beginning 1))
24264 level (org-tr-level level)
24265 txt (save-match-data
24266 (org-html-expand
24267 (org-export-cleanup-toc-line
24268 (match-string 3 line))))
24269 todo
24270 (or (and org-export-mark-todo-in-toc
24271 (match-beginning 2)
24272 (not (member (match-string 2 line)
24273 org-done-keywords)))
24274 ; TODO, not DONE
24275 (and org-export-mark-todo-in-toc
24276 (= level umax-toc)
24277 (org-search-todo-below
24278 line lines level))))
24279 (if (string-match
24280 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
24281 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
24282 (if (string-match quote-re0 txt)
24283 (setq txt (replace-match "" t t txt)))
24284 (if org-export-with-section-numbers
24285 (setq txt (concat (org-section-number level)
24286 " " txt)))
24287 (if (<= level (max umax umax-toc))
24288 (setq head-count (+ head-count 1)))
24289 (if (<= level umax-toc)
24290 (progn
24291 (if (> level org-last-level)
24292 (progn
24293 (setq cnt (- level org-last-level))
24294 (while (>= (setq cnt (1- cnt)) 0)
24295 (push "\n<ul>\n<li>" thetoc))
24296 (push "\n" thetoc)))
24297 (if (< level org-last-level)
24298 (progn
24299 (setq cnt (- org-last-level level))
24300 (while (>= (setq cnt (1- cnt)) 0)
24301 (push "</li>\n</ul>" thetoc))
24302 (push "\n" thetoc)))
24303 ;; Check for targets
24304 (while (string-match org-target-regexp line)
24305 (setq tg (match-string 1 line)
24306 line (replace-match
24307 (concat "@<span class=\"target\">" tg "@</span> ")
24308 t t line))
24309 (push (cons (org-solidify-link-text tg)
24310 (format "sec-%d" head-count))
24311 target-alist))
24312 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
24313 (setq txt (replace-match "" t t txt)))
24314 (push
24315 (format
24316 (if todo
24317 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
24318 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
24319 head-count txt) thetoc)
24321 (setq org-last-level level))
24323 line)
24324 lines))
24325 (while (> org-last-level (1- org-min-level))
24326 (setq org-last-level (1- org-last-level))
24327 (push "</li>\n</ul>\n" thetoc))
24328 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24330 (setq head-count 0)
24331 (org-init-section-numbers)
24333 (while (setq line (pop lines) origline line)
24334 (catch 'nextline
24336 ;; end of quote section?
24337 (when (and inquote (string-match "^\\*+ " line))
24338 (insert "</pre>\n")
24339 (setq inquote nil))
24340 ;; inside a quote section?
24341 (when inquote
24342 (insert (org-html-protect line) "\n")
24343 (throw 'nextline nil))
24345 ;; verbatim lines
24346 (when (and org-export-with-fixed-width
24347 (string-match "^[ \t]*:\\(.*\\)" line))
24348 (when (not infixed)
24349 (setq infixed t)
24350 (insert "<pre>\n"))
24351 (insert (org-html-protect (match-string 1 line)) "\n")
24352 (when (and lines
24353 (not (string-match "^[ \t]*\\(:.*\\)"
24354 (car lines))))
24355 (setq infixed nil)
24356 (insert "</pre>\n"))
24357 (throw 'nextline nil))
24359 ;; Protected HTML
24360 (when (get-text-property 0 'org-protected line)
24361 (let (par)
24362 (when (re-search-backward
24363 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
24364 (setq par (match-string 1))
24365 (replace-match "\\2\n"))
24366 (insert line "\n")
24367 (while (and lines
24368 (get-text-property 0 'org-protected (car lines)))
24369 (insert (pop lines) "\n"))
24370 (and par (insert "<p>\n")))
24371 (throw 'nextline nil))
24373 ;; Horizontal line
24374 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
24375 (insert "\n<hr/>\n")
24376 (throw 'nextline nil))
24378 ;; make targets to anchors
24379 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
24380 (cond
24381 ((match-end 2)
24382 (setq line (replace-match
24383 (concat "@<a name=\""
24384 (org-solidify-link-text (match-string 1 line))
24385 "\">\\nbsp@</a>")
24386 t t line)))
24387 ((and org-export-with-toc (equal (string-to-char line) ?*))
24388 (setq line (replace-match
24389 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
24390 ; (concat "@<i>" (match-string 1 line) "@</i> ")
24391 t t line)))
24393 (setq line (replace-match
24394 (concat "@<a name=\""
24395 (org-solidify-link-text (match-string 1 line))
24396 "\" class=\"target\">" (match-string 1 line) "@</a> ")
24397 t t line)))))
24399 (setq line (org-html-handle-time-stamps line))
24401 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
24402 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
24403 ;; Also handle sub_superscripts and checkboxes
24404 (or (string-match org-table-hline-regexp line)
24405 (setq line (org-html-expand line)))
24407 ;; Format the links
24408 (setq start 0)
24409 (while (string-match org-bracket-link-analytic-regexp line start)
24410 (setq start (match-beginning 0))
24411 (setq type (if (match-end 2) (match-string 2 line) "internal"))
24412 (setq path (match-string 3 line))
24413 (setq desc1 (if (match-end 5) (match-string 5 line))
24414 desc2 (if (match-end 2) (concat type ":" path) path)
24415 descp (and desc1 (not (equal desc1 desc2)))
24416 desc (or desc1 desc2))
24417 ;; Make an image out of the description if that is so wanted
24418 (when (and descp (org-file-image-p desc))
24419 (save-match-data
24420 (if (string-match "^file:" desc)
24421 (setq desc (substring desc (match-end 0)))))
24422 (setq desc (concat "<img src=\"" desc "\"/>")))
24423 ;; FIXME: do we need to unescape here somewhere?
24424 (cond
24425 ((equal type "internal")
24426 (setq rpl
24427 (concat
24428 "<a href=\"#"
24429 (org-solidify-link-text
24430 (save-match-data (org-link-unescape path)) target-alist)
24431 "\">" desc "</a>")))
24432 ((member type '("http" "https"))
24433 ;; standard URL, just check if we need to inline an image
24434 (if (and (or (eq t org-export-html-inline-images)
24435 (and org-export-html-inline-images (not descp)))
24436 (org-file-image-p path))
24437 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
24438 (setq link (concat type ":" path))
24439 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
24440 ((member type '("ftp" "mailto" "news"))
24441 ;; standard URL
24442 (setq link (concat type ":" path))
24443 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
24444 ((string= type "file")
24445 ;; FILE link
24446 (let* ((filename path)
24447 (abs-p (file-name-absolute-p filename))
24448 thefile file-is-image-p search)
24449 (save-match-data
24450 (if (string-match "::\\(.*\\)" filename)
24451 (setq search (match-string 1 filename)
24452 filename (replace-match "" t nil filename)))
24453 (setq valid
24454 (if (functionp link-validate)
24455 (funcall link-validate filename current-dir)
24457 (setq file-is-image-p (org-file-image-p filename))
24458 (setq thefile (if abs-p (expand-file-name filename) filename))
24459 (when (and org-export-html-link-org-files-as-html
24460 (string-match "\\.org$" thefile))
24461 (setq thefile (concat (substring thefile 0
24462 (match-beginning 0))
24463 "." org-export-html-extension))
24464 (if (and search
24465 ;; make sure this is can be used as target search
24466 (not (string-match "^[0-9]*$" search))
24467 (not (string-match "^\\*" search))
24468 (not (string-match "^/.*/$" search)))
24469 (setq thefile (concat thefile "#"
24470 (org-solidify-link-text
24471 (org-link-unescape search)))))
24472 (when (string-match "^file:" desc)
24473 (setq desc (replace-match "" t t desc))
24474 (if (string-match "\\.org$" desc)
24475 (setq desc (replace-match "" t t desc))))))
24476 (setq rpl (if (and file-is-image-p
24477 (or (eq t org-export-html-inline-images)
24478 (and org-export-html-inline-images
24479 (not descp))))
24480 (concat "<img src=\"" thefile "\"/>")
24481 (concat "<a href=\"" thefile "\">" desc "</a>")))
24482 (if (not valid) (setq rpl desc))))
24483 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
24484 (setq rpl (concat "<i>&lt;" type ":"
24485 (save-match-data (org-link-unescape path))
24486 "&gt;</i>"))))
24487 (setq line (replace-match rpl t t line)
24488 start (+ start (length rpl))))
24490 ;; TODO items
24491 (if (and (string-match org-todo-line-regexp line)
24492 (match-beginning 2))
24494 (setq line
24495 (concat (substring line 0 (match-beginning 2))
24496 "<span class=\""
24497 (if (member (match-string 2 line)
24498 org-done-keywords)
24499 "done" "todo")
24500 "\">" (match-string 2 line)
24501 "</span>" (substring line (match-end 2)))))
24503 ;; Does this contain a reference to a footnote?
24504 (when org-export-with-footnotes
24505 (setq start 0)
24506 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
24507 (if (get-text-property (match-beginning 2) 'org-protected line)
24508 (setq start (match-end 2))
24509 (let ((n (match-string 2 line)))
24510 (setq line
24511 (replace-match
24512 (format
24513 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
24514 (match-string 1 line) n n n)
24515 t t line))))))
24517 (cond
24518 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24519 ;; This is a headline
24520 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24521 txt (match-string 2 line))
24522 (if (string-match quote-re0 txt)
24523 (setq txt (replace-match "" t t txt)))
24524 (if (<= level (max umax umax-toc))
24525 (setq head-count (+ head-count 1)))
24526 (when in-local-list
24527 ;; Close any local lists before inserting a new header line
24528 (while local-list-num
24529 (org-close-li)
24530 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
24531 (pop local-list-num))
24532 (setq local-list-indent nil
24533 in-local-list nil))
24534 (setq first-heading-pos (or first-heading-pos (point)))
24535 (org-html-level-start level txt umax
24536 (and org-export-with-toc (<= level umax))
24537 head-count)
24538 ;; QUOTES
24539 (when (string-match quote-re line)
24540 (insert "<pre>")
24541 (setq inquote t)))
24543 ((and org-export-with-tables
24544 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24545 (if (not table-open)
24546 ;; New table starts
24547 (setq table-open t table-buffer nil table-orig-buffer nil))
24548 ;; Accumulate lines
24549 (setq table-buffer (cons line table-buffer)
24550 table-orig-buffer (cons origline table-orig-buffer))
24551 (when (or (not lines)
24552 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24553 (car lines))))
24554 (setq table-open nil
24555 table-buffer (nreverse table-buffer)
24556 table-orig-buffer (nreverse table-orig-buffer))
24557 (org-close-par-maybe)
24558 (insert (org-format-table-html table-buffer table-orig-buffer))))
24560 ;; Normal lines
24561 (when (string-match
24562 (cond
24563 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24564 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24565 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24566 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
24567 line)
24568 (setq ind (org-get-string-indentation line)
24569 start-is-num (match-beginning 4)
24570 starter (if (match-beginning 2)
24571 (substring (match-string 2 line) 0 -1))
24572 line (substring line (match-beginning 5)))
24573 (unless (string-match "[^ \t]" line)
24574 ;; empty line. Pretend indentation is large.
24575 (setq ind (if org-empty-line-terminates-plain-lists
24577 (1+ (or (car local-list-indent) 1)))))
24578 (setq didclose nil)
24579 (while (and in-local-list
24580 (or (and (= ind (car local-list-indent))
24581 (not starter))
24582 (< ind (car local-list-indent))))
24583 (setq didclose t)
24584 (org-close-li)
24585 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
24586 (pop local-list-num) (pop local-list-indent)
24587 (setq in-local-list local-list-indent))
24588 (cond
24589 ((and starter
24590 (or (not in-local-list)
24591 (> ind (car local-list-indent))))
24592 ;; Start new (level of) list
24593 (org-close-par-maybe)
24594 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
24595 (push start-is-num local-list-num)
24596 (push ind local-list-indent)
24597 (setq in-local-list t))
24598 (starter
24599 ;; continue current list
24600 (org-close-li)
24601 (insert "<li>\n"))
24602 (didclose
24603 ;; we did close a list, normal text follows: need <p>
24604 (org-open-par)))
24605 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
24606 (setq line
24607 (replace-match
24608 (if (equal (match-string 1 line) "X")
24609 "<b>[X]</b>"
24610 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
24611 t t line))))
24613 ;; Empty lines start a new paragraph. If hand-formatted lists
24614 ;; are not fully interpreted, lines starting with "-", "+", "*"
24615 ;; also start a new paragraph.
24616 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
24618 ;; Is this the start of a footnote?
24619 (when org-export-with-footnotes
24620 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
24621 (org-close-par-maybe)
24622 (let ((n (match-string 1 line)))
24623 (setq line (replace-match
24624 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
24626 ;; Check if the line break needs to be conserved
24627 (cond
24628 ((string-match "\\\\\\\\[ \t]*$" line)
24629 (setq line (replace-match "<br/>" t t line)))
24630 (org-export-preserve-breaks
24631 (setq line (concat line "<br/>"))))
24633 (insert line "\n")))))
24635 ;; Properly close all local lists and other lists
24636 (when inquote (insert "</pre>\n"))
24637 (when in-local-list
24638 ;; Close any local lists before inserting a new header line
24639 (while local-list-num
24640 (org-close-li)
24641 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
24642 (pop local-list-num))
24643 (setq local-list-indent nil
24644 in-local-list nil))
24645 (org-html-level-start 1 nil umax
24646 (and org-export-with-toc (<= level umax))
24647 head-count)
24649 (unless body-only
24650 (when (plist-get opt-plist :auto-postamble)
24651 (insert "<div id=\"postamble\">")
24652 (when (and org-export-author-info author)
24653 (insert "<p class=\"author\"> "
24654 (nth 1 lang-words) ": " author "\n")
24655 (when email
24656 (if (listp (split-string email ",+ *"))
24657 (mapc (lambda(e)
24658 (insert "<a href=\"mailto:" e "\">&lt;"
24659 e "&gt;</a>\n"))
24660 (split-string email ",+ *"))
24661 (insert "<a href=\"mailto:" email "\">&lt;"
24662 email "&gt;</a>\n")))
24663 (insert "</p>\n"))
24664 (when (and date org-export-time-stamp-file)
24665 (insert "<p class=\"date\"> "
24666 (nth 2 lang-words) ": "
24667 date "</p>\n"))
24668 (insert "</div>"))
24670 (if org-export-html-with-timestamp
24671 (insert org-export-html-html-helper-timestamp))
24672 (insert (or (plist-get opt-plist :postamble) ""))
24673 (insert "</body>\n</html>\n"))
24675 (normal-mode)
24676 (if (eq major-mode default-major-mode) (html-mode))
24678 ;; insert the table of contents
24679 (goto-char (point-min))
24680 (when thetoc
24681 (if (or (re-search-forward
24682 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
24683 (re-search-forward
24684 "\\[TABLE-OF-CONTENTS\\]" nil t))
24685 (progn
24686 (goto-char (match-beginning 0))
24687 (replace-match ""))
24688 (goto-char first-heading-pos)
24689 (when (looking-at "\\s-*</p>")
24690 (goto-char (match-end 0))
24691 (insert "\n")))
24692 (insert "<div id=\"table-of-contents\">\n")
24693 (mapc 'insert thetoc)
24694 (insert "</div>\n"))
24695 ;; remove empty paragraphs and lists
24696 (goto-char (point-min))
24697 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
24698 (replace-match ""))
24699 (goto-char (point-min))
24700 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
24701 (replace-match ""))
24702 ;; Convert whitespace place holders
24703 (goto-char (point-min))
24704 (let (beg end n)
24705 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24706 (setq n (get-text-property beg 'org-whitespace)
24707 end (next-single-property-change beg 'org-whitespace))
24708 (goto-char beg)
24709 (delete-region beg end)
24710 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
24711 (make-string n ?x)))))
24713 (or to-buffer (save-buffer))
24714 (goto-char (point-min))
24715 (message "Exporting... done")
24716 (if (eq to-buffer 'string)
24717 (prog1 (buffer-substring (point-min) (point-max))
24718 (kill-buffer (current-buffer)))
24719 (current-buffer)))))
24721 (defvar org-table-colgroup-info nil)
24722 (defun org-format-table-ascii (lines)
24723 "Format a table for ascii export."
24724 (if (stringp lines)
24725 (setq lines (org-split-string lines "\n")))
24726 (if (not (string-match "^[ \t]*|" (car lines)))
24727 ;; Table made by table.el - test for spanning
24728 lines
24730 ;; A normal org table
24731 ;; Get rid of hlines at beginning and end
24732 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24733 (setq lines (nreverse lines))
24734 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24735 (setq lines (nreverse lines))
24736 (when org-export-table-remove-special-lines
24737 ;; Check if the table has a marking column. If yes remove the
24738 ;; column and the special lines
24739 (setq lines (org-table-clean-before-export lines)))
24740 ;; Get rid of the vertical lines except for grouping
24741 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
24742 rtn line vl1 start)
24743 (while (setq line (pop lines))
24744 (if (string-match org-table-hline-regexp line)
24745 (and (string-match "|\\(.*\\)|" line)
24746 (setq line (replace-match " \\1" t nil line)))
24747 (setq start 0 vl1 vl)
24748 (while (string-match "|" line start)
24749 (setq start (match-end 0))
24750 (or (pop vl1) (setq line (replace-match " " t t line)))))
24751 (push line rtn))
24752 (nreverse rtn))))
24754 (defun org-colgroup-info-to-vline-list (info)
24755 (let (vl new last)
24756 (while info
24757 (setq last new new (pop info))
24758 (if (or (memq last '(:end :startend))
24759 (memq new '(:start :startend)))
24760 (push t vl)
24761 (push nil vl)))
24762 (setq vl (nreverse vl))
24763 (and vl (setcar vl nil))
24764 vl))
24766 (defun org-format-table-html (lines olines)
24767 "Find out which HTML converter to use and return the HTML code."
24768 (if (stringp lines)
24769 (setq lines (org-split-string lines "\n")))
24770 (if (string-match "^[ \t]*|" (car lines))
24771 ;; A normal org table
24772 (org-format-org-table-html lines)
24773 ;; Table made by table.el - test for spanning
24774 (let* ((hlines (delq nil (mapcar
24775 (lambda (x)
24776 (if (string-match "^[ \t]*\\+-" x) x
24777 nil))
24778 lines)))
24779 (first (car hlines))
24780 (ll (and (string-match "\\S-+" first)
24781 (match-string 0 first)))
24782 (re (concat "^[ \t]*" (regexp-quote ll)))
24783 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
24784 hlines))))
24785 (if (and (not spanning)
24786 (not org-export-prefer-native-exporter-for-tables))
24787 ;; We can use my own converter with HTML conversions
24788 (org-format-table-table-html lines)
24789 ;; Need to use the code generator in table.el, with the original text.
24790 (org-format-table-table-html-using-table-generate-source olines)))))
24792 (defun org-format-org-table-html (lines &optional splice)
24793 "Format a table into HTML."
24794 ;; Get rid of hlines at beginning and end
24795 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24796 (setq lines (nreverse lines))
24797 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24798 (setq lines (nreverse lines))
24799 (when org-export-table-remove-special-lines
24800 ;; Check if the table has a marking column. If yes remove the
24801 ;; column and the special lines
24802 (setq lines (org-table-clean-before-export lines)))
24804 (let ((head (and org-export-highlight-first-table-line
24805 (delq nil (mapcar
24806 (lambda (x) (string-match "^[ \t]*|-" x))
24807 (cdr lines)))))
24808 (nlines 0) fnum i
24809 tbopen line fields html gr colgropen)
24810 (if splice (setq head nil))
24811 (unless splice (push (if head "<thead>" "<tbody>") html))
24812 (setq tbopen t)
24813 (while (setq line (pop lines))
24814 (catch 'next-line
24815 (if (string-match "^[ \t]*|-" line)
24816 (progn
24817 (unless splice
24818 (push (if head "</thead>" "</tbody>") html)
24819 (if lines (push "<tbody>" html) (setq tbopen nil)))
24820 (setq head nil) ;; head ends here, first time around
24821 ;; ignore this line
24822 (throw 'next-line t)))
24823 ;; Break the line into fields
24824 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
24825 (unless fnum (setq fnum (make-vector (length fields) 0)))
24826 (setq nlines (1+ nlines) i -1)
24827 (push (concat "<tr>"
24828 (mapconcat
24829 (lambda (x)
24830 (setq i (1+ i))
24831 (if (and (< i nlines)
24832 (string-match org-table-number-regexp x))
24833 (incf (aref fnum i)))
24834 (if head
24835 (concat (car org-export-table-header-tags) x
24836 (cdr org-export-table-header-tags))
24837 (concat (car org-export-table-data-tags) x
24838 (cdr org-export-table-data-tags))))
24839 fields "")
24840 "</tr>")
24841 html)))
24842 (unless splice (if tbopen (push "</tbody>" html)))
24843 (unless splice (push "</table>\n" html))
24844 (setq html (nreverse html))
24845 (unless splice
24846 ;; Put in col tags with the alignment (unfortuntely often ignored...)
24847 (push (mapconcat
24848 (lambda (x)
24849 (setq gr (pop org-table-colgroup-info))
24850 (format "%s<col align=\"%s\"></col>%s"
24851 (if (memq gr '(:start :startend))
24852 (prog1
24853 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
24854 (setq colgropen t))
24856 (if (> (/ (float x) nlines) org-table-number-fraction)
24857 "right" "left")
24858 (if (memq gr '(:end :startend))
24859 (progn (setq colgropen nil) "</colgroup>")
24860 "")))
24861 fnum "")
24862 html)
24863 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
24864 (push html-table-tag html))
24865 (concat (mapconcat 'identity html "\n") "\n")))
24867 (defun org-table-clean-before-export (lines)
24868 "Check if the table has a marking column.
24869 If yes remove the column and the special lines."
24870 (setq org-table-colgroup-info nil)
24871 (if (memq nil
24872 (mapcar
24873 (lambda (x) (or (string-match "^[ \t]*|-" x)
24874 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
24875 lines))
24876 (progn
24877 (setq org-table-clean-did-remove-column nil)
24878 (delq nil
24879 (mapcar
24880 (lambda (x)
24881 (cond
24882 ((string-match "^[ \t]*| */ *|" x)
24883 (setq org-table-colgroup-info
24884 (mapcar (lambda (x)
24885 (cond ((member x '("<" "&lt;")) :start)
24886 ((member x '(">" "&gt;")) :end)
24887 ((member x '("<>" "&lt;&gt;")) :startend)
24888 (t nil)))
24889 (org-split-string x "[ \t]*|[ \t]*")))
24890 nil)
24891 (t x)))
24892 lines)))
24893 (setq org-table-clean-did-remove-column t)
24894 (delq nil
24895 (mapcar
24896 (lambda (x)
24897 (cond
24898 ((string-match "^[ \t]*| */ *|" x)
24899 (setq org-table-colgroup-info
24900 (mapcar (lambda (x)
24901 (cond ((member x '("<" "&lt;")) :start)
24902 ((member x '(">" "&gt;")) :end)
24903 ((member x '("<>" "&lt;&gt;")) :startend)
24904 (t nil)))
24905 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
24906 nil)
24907 ((string-match "^[ \t]*| *[!_^/] *|" x)
24908 nil) ; ignore this line
24909 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
24910 (string-match "^\\([ \t]*\\)|[^|]*|" x))
24911 ;; remove the first column
24912 (replace-match "\\1|" t nil x))))
24913 lines))))
24915 (defun org-format-table-table-html (lines)
24916 "Format a table generated by table.el into HTML.
24917 This conversion does *not* use `table-generate-source' from table.el.
24918 This has the advantage that Org-mode's HTML conversions can be used.
24919 But it has the disadvantage, that no cell- or row-spanning is allowed."
24920 (let (line field-buffer
24921 (head org-export-highlight-first-table-line)
24922 fields html empty)
24923 (setq html (concat html-table-tag "\n"))
24924 (while (setq line (pop lines))
24925 (setq empty "&nbsp;")
24926 (catch 'next-line
24927 (if (string-match "^[ \t]*\\+-" line)
24928 (progn
24929 (if field-buffer
24930 (progn
24931 (setq
24932 html
24933 (concat
24934 html
24935 "<tr>"
24936 (mapconcat
24937 (lambda (x)
24938 (if (equal x "") (setq x empty))
24939 (if head
24940 (concat (car org-export-table-header-tags) x
24941 (cdr org-export-table-header-tags))
24942 (concat (car org-export-table-data-tags) x
24943 (cdr org-export-table-data-tags))))
24944 field-buffer "\n")
24945 "</tr>\n"))
24946 (setq head nil)
24947 (setq field-buffer nil)))
24948 ;; Ignore this line
24949 (throw 'next-line t)))
24950 ;; Break the line into fields and store the fields
24951 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
24952 (if field-buffer
24953 (setq field-buffer (mapcar
24954 (lambda (x)
24955 (concat x "<br/>" (pop fields)))
24956 field-buffer))
24957 (setq field-buffer fields))))
24958 (setq html (concat html "</table>\n"))
24959 html))
24961 (defun org-format-table-table-html-using-table-generate-source (lines)
24962 "Format a table into html, using `table-generate-source' from table.el.
24963 This has the advantage that cell- or row-spanning is allowed.
24964 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
24965 (require 'table)
24966 (with-current-buffer (get-buffer-create " org-tmp1 ")
24967 (erase-buffer)
24968 (insert (mapconcat 'identity lines "\n"))
24969 (goto-char (point-min))
24970 (if (not (re-search-forward "|[^+]" nil t))
24971 (error "Error processing table"))
24972 (table-recognize-table)
24973 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
24974 (table-generate-source 'html " org-tmp2 ")
24975 (set-buffer " org-tmp2 ")
24976 (buffer-substring (point-min) (point-max))))
24978 (defun org-html-handle-time-stamps (s)
24979 "Format time stamps in string S, or remove them."
24980 (catch 'exit
24981 (let (r b)
24982 (while (string-match org-maybe-keyword-time-regexp s)
24983 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
24984 ;; never export CLOCK
24985 (throw 'exit ""))
24986 (or b (setq b (substring s 0 (match-beginning 0))))
24987 (if (not org-export-with-timestamps)
24988 (setq r (concat r (substring s 0 (match-beginning 0)))
24989 s (substring s (match-end 0)))
24990 (setq r (concat
24991 r (substring s 0 (match-beginning 0))
24992 (if (match-end 1)
24993 (format "@<span class=\"timestamp-kwd\">%s @</span>"
24994 (match-string 1 s)))
24995 (format " @<span class=\"timestamp\">%s@</span>"
24996 (substring
24997 (org-translate-time (match-string 3 s)) 1 -1)))
24998 s (substring s (match-end 0)))))
24999 ;; Line break if line started and ended with time stamp stuff
25000 (if (not r)
25002 (setq r (concat r s))
25003 (unless (string-match "\\S-" (concat b s))
25004 (setq r (concat r "@<br/>")))
25005 r))))
25007 (defun org-html-protect (s)
25008 ;; convert & to &amp;, < to &lt; and > to &gt;
25009 (let ((start 0))
25010 (while (string-match "&" s start)
25011 (setq s (replace-match "&amp;" t t s)
25012 start (1+ (match-beginning 0))))
25013 (while (string-match "<" s)
25014 (setq s (replace-match "&lt;" t t s)))
25015 (while (string-match ">" s)
25016 (setq s (replace-match "&gt;" t t s))))
25019 (defun org-export-cleanup-toc-line (s)
25020 "Remove tags and time staps from lines going into the toc."
25021 (when (memq org-export-with-tags '(not-in-toc nil))
25022 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25023 (setq s (replace-match "" t t s))))
25024 (when org-export-remove-timestamps-from-toc
25025 (while (string-match org-maybe-keyword-time-regexp s)
25026 (setq s (replace-match "" t t s))))
25027 (while (string-match org-bracket-link-regexp s)
25028 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25029 t t s)))
25032 (defun org-html-expand (string)
25033 "Prepare STRING for HTML export. Applies all active conversions.
25034 If there are links in the string, don't modify these."
25035 (let* ((re (concat org-bracket-link-regexp "\\|"
25036 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25037 m s l res)
25038 (while (setq m (string-match re string))
25039 (setq s (substring string 0 m)
25040 l (match-string 0 string)
25041 string (substring string (match-end 0)))
25042 (push (org-html-do-expand s) res)
25043 (push l res))
25044 (push (org-html-do-expand string) res)
25045 (apply 'concat (nreverse res))))
25047 (defun org-html-do-expand (s)
25048 "Apply all active conversions to translate special ASCII to HTML."
25049 (setq s (org-html-protect s))
25050 (if org-export-html-expand
25051 (let ((start 0))
25052 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25053 (setq s (replace-match "<\\1>" t nil s)))))
25054 (if org-export-with-emphasize
25055 (setq s (org-export-html-convert-emphasize s)))
25056 (if org-export-with-special-strings
25057 (setq s (org-export-html-convert-special-strings s)))
25058 (if org-export-with-sub-superscripts
25059 (setq s (org-export-html-convert-sub-super s)))
25060 (if org-export-with-TeX-macros
25061 (let ((start 0) wd ass)
25062 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25063 (if (get-text-property (match-beginning 0) 'org-protected s)
25064 (setq start (match-end 0))
25065 (setq wd (match-string 1 s))
25066 (if (setq ass (assoc wd org-html-entities))
25067 (setq s (replace-match (or (cdr ass)
25068 (concat "&" (car ass) ";"))
25069 t t s))
25070 (setq start (+ start (length wd))))))))
25073 (defun org-create-multibrace-regexp (left right n)
25074 "Create a regular expression which will match a balanced sexp.
25075 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25076 as single character strings.
25077 The regexp returned will match the entire expression including the
25078 delimiters. It will also define a single group which contains the
25079 match except for the outermost delimiters. The maximum depth of
25080 stacked delimiters is N. Escaping delimiters is not possible."
25081 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25082 (or "\\|")
25083 (re nothing)
25084 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25085 (while (> n 1)
25086 (setq n (1- n)
25087 re (concat re or next)
25088 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25089 (concat left "\\(" re "\\)" right)))
25091 (defvar org-match-substring-regexp
25092 (concat
25093 "\\([^\\]\\)\\([_^]\\)\\("
25094 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25095 "\\|"
25096 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25097 "\\|"
25098 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25099 "The regular expression matching a sub- or superscript.")
25101 (defvar org-match-substring-with-braces-regexp
25102 (concat
25103 "\\([^\\]\\)\\([_^]\\)\\("
25104 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25105 "\\)")
25106 "The regular expression matching a sub- or superscript, forcing braces.")
25108 (defconst org-export-html-special-string-regexps
25109 '(("\\\\-" . "&shy;")
25110 ("---\\([^-]\\)" . "&mdash;\\1")
25111 ("--\\([^-]\\)" . "&ndash;\\1")
25112 ("\\.\\.\\." . "&hellip;"))
25113 "Regular expressions for special string conversion.")
25115 (defun org-export-html-convert-special-strings (string)
25116 "Convert special characters in STRING to HTML."
25117 (let ((all org-export-html-special-string-regexps)
25118 e a re rpl start)
25119 (while (setq a (pop all))
25120 (setq re (car a) rpl (cdr a) start 0)
25121 (while (string-match re string start)
25122 (if (get-text-property (match-beginning 0) 'org-protected string)
25123 (setq start (match-end 0))
25124 (setq string (replace-match rpl t nil string)))))
25125 string))
25127 (defun org-export-html-convert-sub-super (string)
25128 "Convert sub- and superscripts in STRING to HTML."
25129 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25130 (while (string-match org-match-substring-regexp string s)
25131 (cond
25132 ((and requireb (match-end 8)) (setq s (match-end 2)))
25133 ((get-text-property (match-beginning 2) 'org-protected string)
25134 (setq s (match-end 2)))
25136 (setq s (match-end 1)
25137 key (if (string= (match-string 2 string) "_") "sub" "sup")
25138 c (or (match-string 8 string)
25139 (match-string 6 string)
25140 (match-string 5 string))
25141 string (replace-match
25142 (concat (match-string 1 string)
25143 "<" key ">" c "</" key ">")
25144 t t string)))))
25145 (while (string-match "\\\\\\([_^]\\)" string)
25146 (setq string (replace-match (match-string 1 string) t t string)))
25147 string))
25149 (defun org-export-html-convert-emphasize (string)
25150 "Apply emphasis."
25151 (let ((s 0) rpl)
25152 (while (string-match org-emph-re string s)
25153 (if (not (equal
25154 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25155 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25156 (setq s (match-beginning 0)
25158 (concat
25159 (match-string 1 string)
25160 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25161 (match-string 4 string)
25162 (nth 3 (assoc (match-string 3 string)
25163 org-emphasis-alist))
25164 (match-string 5 string))
25165 string (replace-match rpl t t string)
25166 s (+ s (- (length rpl) 2)))
25167 (setq s (1+ s))))
25168 string))
25170 (defvar org-par-open nil)
25171 (defun org-open-par ()
25172 "Insert <p>, but first close previous paragraph if any."
25173 (org-close-par-maybe)
25174 (insert "\n<p>")
25175 (setq org-par-open t))
25176 (defun org-close-par-maybe ()
25177 "Close paragraph if there is one open."
25178 (when org-par-open
25179 (insert "</p>")
25180 (setq org-par-open nil)))
25181 (defun org-close-li ()
25182 "Close <li> if necessary."
25183 (org-close-par-maybe)
25184 (insert "</li>\n"))
25186 (defvar body-only) ; dynamically scoped into this.
25187 (defun org-html-level-start (level title umax with-toc head-count)
25188 "Insert a new level in HTML export.
25189 When TITLE is nil, just close all open levels."
25190 (org-close-par-maybe)
25191 (let ((l org-level-max))
25192 (while (>= l level)
25193 (if (aref org-levels-open (1- l))
25194 (progn
25195 (org-html-level-close l umax)
25196 (aset org-levels-open (1- l) nil)))
25197 (setq l (1- l)))
25198 (when title
25199 ;; If title is nil, this means this function is called to close
25200 ;; all levels, so the rest is done only if title is given
25201 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25202 (setq title (replace-match
25203 (if org-export-with-tags
25204 (save-match-data
25205 (concat
25206 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
25207 (mapconcat 'identity (org-split-string
25208 (match-string 1 title) ":")
25209 "&nbsp;")
25210 "</span>"))
25212 t t title)))
25213 (if (> level umax)
25214 (progn
25215 (if (aref org-levels-open (1- level))
25216 (progn
25217 (org-close-li)
25218 (insert "<li>" title "<br/>\n"))
25219 (aset org-levels-open (1- level) t)
25220 (org-close-par-maybe)
25221 (insert "<ul>\n<li>" title "<br/>\n")))
25222 (aset org-levels-open (1- level) t)
25223 (if (and org-export-with-section-numbers (not body-only))
25224 (setq title (concat (org-section-number level) " " title)))
25225 (setq level (+ level org-export-html-toplevel-hlevel -1))
25226 (if with-toc
25227 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
25228 level level head-count title level))
25229 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
25230 (org-open-par)))))
25232 (defun org-html-level-close (level max-outline-level)
25233 "Terminate one level in HTML export."
25234 (if (<= level max-outline-level)
25235 (insert "</div>\n")
25236 (org-close-li)
25237 (insert "</ul>\n")))
25239 ;;; iCalendar export
25241 ;;;###autoload
25242 (defun org-export-icalendar-this-file ()
25243 "Export current file as an iCalendar file.
25244 The iCalendar file will be located in the same directory as the Org-mode
25245 file, but with extension `.ics'."
25246 (interactive)
25247 (org-export-icalendar nil buffer-file-name))
25249 ;;;###autoload
25250 (defun org-export-icalendar-all-agenda-files ()
25251 "Export all files in `org-agenda-files' to iCalendar .ics files.
25252 Each iCalendar file will be located in the same directory as the Org-mode
25253 file, but with extension `.ics'."
25254 (interactive)
25255 (apply 'org-export-icalendar nil (org-agenda-files t)))
25257 ;;;###autoload
25258 (defun org-export-icalendar-combine-agenda-files ()
25259 "Export all files in `org-agenda-files' to a single combined iCalendar file.
25260 The file is stored under the name `org-combined-agenda-icalendar-file'."
25261 (interactive)
25262 (apply 'org-export-icalendar t (org-agenda-files t)))
25264 (defun org-export-icalendar (combine &rest files)
25265 "Create iCalendar files for all elements of FILES.
25266 If COMBINE is non-nil, combine all calendar entries into a single large
25267 file and store it under the name `org-combined-agenda-icalendar-file'."
25268 (save-excursion
25269 (org-prepare-agenda-buffers files)
25270 (let* ((dir (org-export-directory
25271 :ical (list :publishing-directory
25272 org-export-publishing-directory)))
25273 file ical-file ical-buffer category started org-agenda-new-buffers)
25275 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
25276 (when combine
25277 (setq ical-file
25278 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
25279 org-combined-agenda-icalendar-file
25280 (expand-file-name org-combined-agenda-icalendar-file dir))
25281 ical-buffer (org-get-agenda-file-buffer ical-file))
25282 (set-buffer ical-buffer) (erase-buffer))
25283 (while (setq file (pop files))
25284 (catch 'nextfile
25285 (org-check-agenda-file file)
25286 (set-buffer (org-get-agenda-file-buffer file))
25287 (unless combine
25288 (setq ical-file (concat (file-name-as-directory dir)
25289 (file-name-sans-extension
25290 (file-name-nondirectory buffer-file-name))
25291 ".ics"))
25292 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
25293 (with-current-buffer ical-buffer (erase-buffer)))
25294 (setq category (or org-category
25295 (file-name-sans-extension
25296 (file-name-nondirectory buffer-file-name))))
25297 (if (symbolp category) (setq category (symbol-name category)))
25298 (let ((standard-output ical-buffer))
25299 (if combine
25300 (and (not started) (setq started t)
25301 (org-start-icalendar-file org-icalendar-combined-name))
25302 (org-start-icalendar-file category))
25303 (org-print-icalendar-entries combine)
25304 (when (or (and combine (not files)) (not combine))
25305 (org-finish-icalendar-file)
25306 (set-buffer ical-buffer)
25307 (save-buffer)
25308 (run-hooks 'org-after-save-iCalendar-file-hook)))))
25309 (org-release-buffers org-agenda-new-buffers))))
25311 (defvar org-after-save-iCalendar-file-hook nil
25312 "Hook run after an iCalendar file has been saved.
25313 The iCalendar buffer is still current when this hook is run.
25314 A good way to use this is to tell a desktop calenndar application to re-read
25315 the iCalendar file.")
25317 (defun org-print-icalendar-entries (&optional combine)
25318 "Print iCalendar entries for the current Org-mode file to `standard-output'.
25319 When COMBINE is non nil, add the category to each line."
25320 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
25321 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
25322 (dts (org-ical-ts-to-string
25323 (format-time-string (cdr org-time-stamp-formats) (current-time))
25324 "DTSTART"))
25325 hd ts ts2 state status (inc t) pos b sexp rrule
25326 scheduledp deadlinep tmp pri category entry location summary desc
25327 (sexp-buffer (get-buffer-create "*ical-tmp*")))
25328 (org-refresh-category-properties)
25329 (save-excursion
25330 (goto-char (point-min))
25331 (while (re-search-forward re1 nil t)
25332 (catch :skip
25333 (org-agenda-skip)
25334 (setq pos (match-beginning 0)
25335 ts (match-string 0)
25336 inc t
25337 hd (org-get-heading)
25338 summary (org-icalendar-cleanup-string
25339 (org-entry-get nil "SUMMARY"))
25340 desc (org-icalendar-cleanup-string
25341 (or (org-entry-get nil "DESCRIPTION")
25342 (and org-icalendar-include-body (org-get-entry)))
25343 t org-icalendar-include-body)
25344 location (org-icalendar-cleanup-string
25345 (org-entry-get nil "LOCATION"))
25346 category (org-get-category))
25347 (if (looking-at re2)
25348 (progn
25349 (goto-char (match-end 0))
25350 (setq ts2 (match-string 1) inc nil))
25351 (setq tmp (buffer-substring (max (point-min)
25352 (- pos org-ds-keyword-length))
25353 pos)
25354 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
25355 (progn
25356 (setq inc nil)
25357 (replace-match "\\1" t nil ts))
25359 deadlinep (string-match org-deadline-regexp tmp)
25360 scheduledp (string-match org-scheduled-regexp tmp)
25361 ;; donep (org-entry-is-done-p)
25363 (if (or (string-match org-tr-regexp hd)
25364 (string-match org-ts-regexp hd))
25365 (setq hd (replace-match "" t t hd)))
25366 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
25367 (setq rrule
25368 (concat "\nRRULE:FREQ="
25369 (cdr (assoc
25370 (match-string 2 ts)
25371 '(("d" . "DAILY")("w" . "WEEKLY")
25372 ("m" . "MONTHLY")("y" . "YEARLY"))))
25373 ";INTERVAL=" (match-string 1 ts)))
25374 (setq rrule ""))
25375 (setq summary (or summary hd))
25376 (if (string-match org-bracket-link-regexp summary)
25377 (setq summary
25378 (replace-match (if (match-end 3)
25379 (match-string 3 summary)
25380 (match-string 1 summary))
25381 t t summary)))
25382 (if deadlinep (setq summary (concat "DL: " summary)))
25383 (if scheduledp (setq summary (concat "S: " summary)))
25384 (if (string-match "\\`<%%" ts)
25385 (with-current-buffer sexp-buffer
25386 (insert (substring ts 1 -1) " " summary "\n"))
25387 (princ (format "BEGIN:VEVENT
25389 %s%s
25390 SUMMARY:%s%s%s
25391 CATEGORIES:%s
25392 END:VEVENT\n"
25393 (org-ical-ts-to-string ts "DTSTART")
25394 (org-ical-ts-to-string ts2 "DTEND" inc)
25395 rrule summary
25396 (if (and desc (string-match "\\S-" desc))
25397 (concat "\nDESCRIPTION: " desc) "")
25398 (if (and location (string-match "\\S-" location))
25399 (concat "\nLOCATION: " location) "")
25400 category)))))
25402 (when (and org-icalendar-include-sexps
25403 (condition-case nil (require 'icalendar) (error nil))
25404 (fboundp 'icalendar-export-region))
25405 ;; Get all the literal sexps
25406 (goto-char (point-min))
25407 (while (re-search-forward "^&?%%(" nil t)
25408 (catch :skip
25409 (org-agenda-skip)
25410 (setq b (match-beginning 0))
25411 (goto-char (1- (match-end 0)))
25412 (forward-sexp 1)
25413 (end-of-line 1)
25414 (setq sexp (buffer-substring b (point)))
25415 (with-current-buffer sexp-buffer
25416 (insert sexp "\n"))
25417 (princ (org-diary-to-ical-string sexp-buffer)))))
25419 (when org-icalendar-include-todo
25420 (goto-char (point-min))
25421 (while (re-search-forward org-todo-line-regexp nil t)
25422 (catch :skip
25423 (org-agenda-skip)
25424 (setq state (match-string 2))
25425 (setq status (if (member state org-done-keywords)
25426 "COMPLETED" "NEEDS-ACTION"))
25427 (when (and state
25428 (or (not (member state org-done-keywords))
25429 (eq org-icalendar-include-todo 'all))
25430 (not (member org-archive-tag (org-get-tags-at)))
25432 (setq hd (match-string 3)
25433 summary (org-icalendar-cleanup-string
25434 (org-entry-get nil "SUMMARY"))
25435 desc (org-icalendar-cleanup-string
25436 (or (org-entry-get nil "DESCRIPTION")
25437 (and org-icalendar-include-body (org-get-entry)))
25438 t org-icalendar-include-body)
25439 location (org-icalendar-cleanup-string
25440 (org-entry-get nil "LOCATION")))
25441 (if (string-match org-bracket-link-regexp hd)
25442 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
25443 (match-string 1 hd))
25444 t t hd)))
25445 (if (string-match org-priority-regexp hd)
25446 (setq pri (string-to-char (match-string 2 hd))
25447 hd (concat (substring hd 0 (match-beginning 1))
25448 (substring hd (match-end 1))))
25449 (setq pri org-default-priority))
25450 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
25451 (- org-lowest-priority org-highest-priority))))))
25453 (princ (format "BEGIN:VTODO
25455 SUMMARY:%s%s%s
25456 CATEGORIES:%s
25457 SEQUENCE:1
25458 PRIORITY:%d
25459 STATUS:%s
25460 END:VTODO\n"
25462 (or summary hd)
25463 (if (and location (string-match "\\S-" location))
25464 (concat "\nLOCATION: " location) "")
25465 (if (and desc (string-match "\\S-" desc))
25466 (concat "\nDESCRIPTION: " desc) "")
25467 category pri status)))))))))
25469 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
25470 "Take out stuff and quote what needs to be quoted.
25471 When IS-BODY is non-nil, assume that this is the body of an item, clean up
25472 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
25473 characters."
25474 (if (not s)
25476 (when is-body
25477 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
25478 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
25479 (while (string-match re s) (setq s (replace-match "" t t s)))
25480 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
25481 (let ((start 0))
25482 (while (string-match "\\([,;\\]\\)" s start)
25483 (setq start (+ (match-beginning 0) 2)
25484 s (replace-match "\\\\\\1" nil nil s))))
25485 (when is-body
25486 (while (string-match "[ \t]*\n[ \t]*" s)
25487 (setq s (replace-match "\\n" t t s))))
25488 (setq s (org-trim s))
25489 (if is-body
25490 (if maxlength
25491 (if (and (numberp maxlength)
25492 (> (length s) maxlength))
25493 (setq s (substring s 0 maxlength)))))
25496 (defun org-get-entry ()
25497 "Clean-up description string."
25498 (save-excursion
25499 (org-back-to-heading t)
25500 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
25502 (defun org-start-icalendar-file (name)
25503 "Start an iCalendar file by inserting the header."
25504 (let ((user user-full-name)
25505 (name (or name "unknown"))
25506 (timezone (cadr (current-time-zone))))
25507 (princ
25508 (format "BEGIN:VCALENDAR
25509 VERSION:2.0
25510 X-WR-CALNAME:%s
25511 PRODID:-//%s//Emacs with Org-mode//EN
25512 X-WR-TIMEZONE:%s
25513 CALSCALE:GREGORIAN\n" name user timezone))))
25515 (defun org-finish-icalendar-file ()
25516 "Finish an iCalendar file by inserting the END statement."
25517 (princ "END:VCALENDAR\n"))
25519 (defun org-ical-ts-to-string (s keyword &optional inc)
25520 "Take a time string S and convert it to iCalendar format.
25521 KEYWORD is added in front, to make a complete line like DTSTART....
25522 When INC is non-nil, increase the hour by two (if time string contains
25523 a time), or the day by one (if it does not contain a time)."
25524 (let ((t1 (org-parse-time-string s 'nodefault))
25525 t2 fmt have-time time)
25526 (if (and (car t1) (nth 1 t1) (nth 2 t1))
25527 (setq t2 t1 have-time t)
25528 (setq t2 (org-parse-time-string s)))
25529 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
25530 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
25531 (when inc
25532 (if have-time
25533 (if org-agenda-default-appointment-duration
25534 (setq mi (+ org-agenda-default-appointment-duration mi))
25535 (setq h (+ 2 h)))
25536 (setq d (1+ d))))
25537 (setq time (encode-time s mi h d m y)))
25538 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
25539 (concat keyword (format-time-string fmt time))))
25541 ;;; XOXO export
25543 (defun org-export-as-xoxo-insert-into (buffer &rest output)
25544 (with-current-buffer buffer
25545 (apply 'insert output)))
25546 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
25548 (defun org-export-as-xoxo (&optional buffer)
25549 "Export the org buffer as XOXO.
25550 The XOXO buffer is named *xoxo-<source buffer name>*"
25551 (interactive (list (current-buffer)))
25552 ;; A quickie abstraction
25554 ;; Output everything as XOXO
25555 (with-current-buffer (get-buffer buffer)
25556 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
25557 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25558 (org-infile-export-plist)))
25559 (filename (concat (file-name-as-directory
25560 (org-export-directory :xoxo opt-plist))
25561 (file-name-sans-extension
25562 (file-name-nondirectory buffer-file-name))
25563 ".html"))
25564 (out (find-file-noselect filename))
25565 (last-level 1)
25566 (hanging-li nil))
25567 ;; Check the output buffer is empty.
25568 (with-current-buffer out (erase-buffer))
25569 ;; Kick off the output
25570 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
25571 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
25572 (let* ((hd (match-string-no-properties 1))
25573 (level (length hd))
25574 (text (concat
25575 (match-string-no-properties 2)
25576 (save-excursion
25577 (goto-char (match-end 0))
25578 (let ((str ""))
25579 (catch 'loop
25580 (while 't
25581 (forward-line)
25582 (if (looking-at "^[ \t]\\(.*\\)")
25583 (setq str (concat str (match-string-no-properties 1)))
25584 (throw 'loop str)))))))))
25586 ;; Handle level rendering
25587 (cond
25588 ((> level last-level)
25589 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
25591 ((< level last-level)
25592 (dotimes (- (- last-level level) 1)
25593 (if hanging-li
25594 (org-export-as-xoxo-insert-into out "</li>\n"))
25595 (org-export-as-xoxo-insert-into out "</ol>\n"))
25596 (when hanging-li
25597 (org-export-as-xoxo-insert-into out "</li>\n")
25598 (setq hanging-li nil)))
25600 ((equal level last-level)
25601 (if hanging-li
25602 (org-export-as-xoxo-insert-into out "</li>\n")))
25605 (setq last-level level)
25607 ;; And output the new li
25608 (setq hanging-li 't)
25609 (if (equal ?+ (elt text 0))
25610 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
25611 (org-export-as-xoxo-insert-into out "<li>" text))))
25613 ;; Finally finish off the ol
25614 (dotimes (- last-level 1)
25615 (if hanging-li
25616 (org-export-as-xoxo-insert-into out "</li>\n"))
25617 (org-export-as-xoxo-insert-into out "</ol>\n"))
25619 ;; Finish the buffer off and clean it up.
25620 (switch-to-buffer-other-window out)
25621 (indent-region (point-min) (point-max) nil)
25622 (save-buffer)
25623 (goto-char (point-min))
25627 ;;;; Key bindings
25629 ;; Make `C-c C-x' a prefix key
25630 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
25632 ;; TAB key with modifiers
25633 (org-defkey org-mode-map "\C-i" 'org-cycle)
25634 (org-defkey org-mode-map [(tab)] 'org-cycle)
25635 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
25636 (org-defkey org-mode-map [(meta tab)] 'org-complete)
25637 (org-defkey org-mode-map "\M-\t" 'org-complete)
25638 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
25639 ;; The following line is necessary under Suse GNU/Linux
25640 (unless (featurep 'xemacs)
25641 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
25642 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
25643 (define-key org-mode-map [backtab] 'org-shifttab)
25645 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
25646 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
25647 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
25649 ;; Cursor keys with modifiers
25650 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
25651 (org-defkey org-mode-map [(meta right)] 'org-metaright)
25652 (org-defkey org-mode-map [(meta up)] 'org-metaup)
25653 (org-defkey org-mode-map [(meta down)] 'org-metadown)
25655 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
25656 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
25657 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
25658 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
25660 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
25661 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
25662 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
25663 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
25665 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
25666 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
25668 ;;; Extra keys for tty access.
25669 ;; We only set them when really needed because otherwise the
25670 ;; menus don't show the simple keys
25672 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
25673 (not window-system))
25674 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
25675 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
25676 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
25677 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
25678 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
25679 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
25680 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
25681 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
25682 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
25683 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
25684 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
25685 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
25686 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
25687 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
25688 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
25689 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
25690 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
25691 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
25692 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
25693 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
25694 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
25695 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
25697 ;; All the other keys
25699 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
25700 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
25701 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
25702 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
25703 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
25704 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
25705 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
25706 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
25707 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
25708 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
25709 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
25710 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
25711 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
25712 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
25713 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
25714 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
25715 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
25716 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
25717 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
25718 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
25719 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
25720 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
25721 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
25722 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
25723 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
25724 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
25725 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
25726 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
25727 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
25728 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
25729 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
25730 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
25731 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
25732 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
25733 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
25734 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
25735 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
25736 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25737 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
25738 (org-defkey org-mode-map "\C-c^" 'org-sort)
25739 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
25740 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
25741 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
25742 (org-defkey org-mode-map "\C-m" 'org-return)
25743 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
25744 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
25745 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
25746 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
25747 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
25748 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
25749 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
25750 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
25751 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
25752 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
25753 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
25754 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
25755 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
25756 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
25757 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
25758 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
25760 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
25761 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
25762 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
25763 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
25765 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
25766 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
25767 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
25768 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
25769 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
25770 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
25771 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
25772 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
25773 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
25774 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
25775 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
25776 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
25778 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
25780 (when (featurep 'xemacs)
25781 (org-defkey org-mode-map 'button3 'popup-mode-menu))
25783 (defsubst org-table-p () (org-at-table-p))
25785 (defun org-self-insert-command (N)
25786 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
25787 If the cursor is in a table looking at whitespace, the whitespace is
25788 overwritten, and the table is not marked as requiring realignment."
25789 (interactive "p")
25790 (if (and (org-table-p)
25791 (progn
25792 ;; check if we blank the field, and if that triggers align
25793 (and org-table-auto-blank-field
25794 (member last-command
25795 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
25796 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
25797 ;; got extra space, this field does not determine column width
25798 (let (org-table-may-need-update) (org-table-blank-field))
25799 ;; no extra space, this field may determine column width
25800 (org-table-blank-field)))
25802 (eq N 1)
25803 (looking-at "[^|\n]* |"))
25804 (let (org-table-may-need-update)
25805 (goto-char (1- (match-end 0)))
25806 (delete-backward-char 1)
25807 (goto-char (match-beginning 0))
25808 (self-insert-command N))
25809 (setq org-table-may-need-update t)
25810 (self-insert-command N)
25811 (org-fix-tags-on-the-fly)))
25813 (defun org-fix-tags-on-the-fly ()
25814 (when (and (equal (char-after (point-at-bol)) ?*)
25815 (org-on-heading-p))
25816 (org-align-tags-here org-tags-column)))
25818 (defun org-delete-backward-char (N)
25819 "Like `delete-backward-char', insert whitespace at field end in tables.
25820 When deleting backwards, in tables this function will insert whitespace in
25821 front of the next \"|\" separator, to keep the table aligned. The table will
25822 still be marked for re-alignment if the field did fill the entire column,
25823 because, in this case the deletion might narrow the column."
25824 (interactive "p")
25825 (if (and (org-table-p)
25826 (eq N 1)
25827 (string-match "|" (buffer-substring (point-at-bol) (point)))
25828 (looking-at ".*?|"))
25829 (let ((pos (point))
25830 (noalign (looking-at "[^|\n\r]* |"))
25831 (c org-table-may-need-update))
25832 (backward-delete-char N)
25833 (skip-chars-forward "^|")
25834 (insert " ")
25835 (goto-char (1- pos))
25836 ;; noalign: if there were two spaces at the end, this field
25837 ;; does not determine the width of the column.
25838 (if noalign (setq org-table-may-need-update c)))
25839 (backward-delete-char N)
25840 (org-fix-tags-on-the-fly)))
25842 (defun org-delete-char (N)
25843 "Like `delete-char', but insert whitespace at field end in tables.
25844 When deleting characters, in tables this function will insert whitespace in
25845 front of the next \"|\" separator, to keep the table aligned. The table will
25846 still be marked for re-alignment if the field did fill the entire column,
25847 because, in this case the deletion might narrow the column."
25848 (interactive "p")
25849 (if (and (org-table-p)
25850 (not (bolp))
25851 (not (= (char-after) ?|))
25852 (eq N 1))
25853 (if (looking-at ".*?|")
25854 (let ((pos (point))
25855 (noalign (looking-at "[^|\n\r]* |"))
25856 (c org-table-may-need-update))
25857 (replace-match (concat
25858 (substring (match-string 0) 1 -1)
25859 " |"))
25860 (goto-char pos)
25861 ;; noalign: if there were two spaces at the end, this field
25862 ;; does not determine the width of the column.
25863 (if noalign (setq org-table-may-need-update c)))
25864 (delete-char N))
25865 (delete-char N)
25866 (org-fix-tags-on-the-fly)))
25868 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
25869 (put 'org-self-insert-command 'delete-selection t)
25870 (put 'orgtbl-self-insert-command 'delete-selection t)
25871 (put 'org-delete-char 'delete-selection 'supersede)
25872 (put 'org-delete-backward-char 'delete-selection 'supersede)
25874 ;; Make `flyspell-mode' delay after some commands
25875 (put 'org-self-insert-command 'flyspell-delayed t)
25876 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
25877 (put 'org-delete-char 'flyspell-delayed t)
25878 (put 'org-delete-backward-char 'flyspell-delayed t)
25880 ;; Make pabbrev-mode expand after org-mode commands
25881 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
25882 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
25884 ;; How to do this: Measure non-white length of current string
25885 ;; If equal to column width, we should realign.
25887 (defun org-remap (map &rest commands)
25888 "In MAP, remap the functions given in COMMANDS.
25889 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
25890 (let (new old)
25891 (while commands
25892 (setq old (pop commands) new (pop commands))
25893 (if (fboundp 'command-remapping)
25894 (org-defkey map (vector 'remap old) new)
25895 (substitute-key-definition old new map global-map)))))
25897 (when (eq org-enable-table-editor 'optimized)
25898 ;; If the user wants maximum table support, we need to hijack
25899 ;; some standard editing functions
25900 (org-remap org-mode-map
25901 'self-insert-command 'org-self-insert-command
25902 'delete-char 'org-delete-char
25903 'delete-backward-char 'org-delete-backward-char)
25904 (org-defkey org-mode-map "|" 'org-force-self-insert))
25906 (defun org-shiftcursor-error ()
25907 "Throw an error because Shift-Cursor command was applied in wrong context."
25908 (error "This command is active in special context like tables, headlines or timestamps"))
25910 (defun org-shifttab (&optional arg)
25911 "Global visibility cycling or move to previous table field.
25912 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
25913 on context.
25914 See the individual commands for more information."
25915 (interactive "P")
25916 (cond
25917 ((org-at-table-p) (call-interactively 'org-table-previous-field))
25918 (arg (message "Content view to level: ")
25919 (org-content (prefix-numeric-value arg))
25920 (setq org-cycle-global-status 'overview))
25921 (t (call-interactively 'org-global-cycle))))
25923 (defun org-shiftmetaleft ()
25924 "Promote subtree or delete table column.
25925 Calls `org-promote-subtree', `org-outdent-item',
25926 or `org-table-delete-column', depending on context.
25927 See the individual commands for more information."
25928 (interactive)
25929 (cond
25930 ((org-at-table-p) (call-interactively 'org-table-delete-column))
25931 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
25932 ((org-at-item-p) (call-interactively 'org-outdent-item))
25933 (t (org-shiftcursor-error))))
25935 (defun org-shiftmetaright ()
25936 "Demote subtree or insert table column.
25937 Calls `org-demote-subtree', `org-indent-item',
25938 or `org-table-insert-column', depending on context.
25939 See the individual commands for more information."
25940 (interactive)
25941 (cond
25942 ((org-at-table-p) (call-interactively 'org-table-insert-column))
25943 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
25944 ((org-at-item-p) (call-interactively 'org-indent-item))
25945 (t (org-shiftcursor-error))))
25947 (defun org-shiftmetaup (&optional arg)
25948 "Move subtree up or kill table row.
25949 Calls `org-move-subtree-up' or `org-table-kill-row' or
25950 `org-move-item-up' depending on context. See the individual commands
25951 for more information."
25952 (interactive "P")
25953 (cond
25954 ((org-at-table-p) (call-interactively 'org-table-kill-row))
25955 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
25956 ((org-at-item-p) (call-interactively 'org-move-item-up))
25957 (t (org-shiftcursor-error))))
25958 (defun org-shiftmetadown (&optional arg)
25959 "Move subtree down or insert table row.
25960 Calls `org-move-subtree-down' or `org-table-insert-row' or
25961 `org-move-item-down', depending on context. See the individual
25962 commands for more information."
25963 (interactive "P")
25964 (cond
25965 ((org-at-table-p) (call-interactively 'org-table-insert-row))
25966 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
25967 ((org-at-item-p) (call-interactively 'org-move-item-down))
25968 (t (org-shiftcursor-error))))
25970 (defun org-metaleft (&optional arg)
25971 "Promote heading or move table column to left.
25972 Calls `org-do-promote' or `org-table-move-column', depending on context.
25973 With no specific context, calls the Emacs default `backward-word'.
25974 See the individual commands for more information."
25975 (interactive "P")
25976 (cond
25977 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
25978 ((or (org-on-heading-p) (org-region-active-p))
25979 (call-interactively 'org-do-promote))
25980 ((org-at-item-p) (call-interactively 'org-outdent-item))
25981 (t (call-interactively 'backward-word))))
25983 (defun org-metaright (&optional arg)
25984 "Demote subtree or move table column to right.
25985 Calls `org-do-demote' or `org-table-move-column', depending on context.
25986 With no specific context, calls the Emacs default `forward-word'.
25987 See the individual commands for more information."
25988 (interactive "P")
25989 (cond
25990 ((org-at-table-p) (call-interactively 'org-table-move-column))
25991 ((or (org-on-heading-p) (org-region-active-p))
25992 (call-interactively 'org-do-demote))
25993 ((org-at-item-p) (call-interactively 'org-indent-item))
25994 (t (call-interactively 'forward-word))))
25996 (defun org-metaup (&optional arg)
25997 "Move subtree up or move table row up.
25998 Calls `org-move-subtree-up' or `org-table-move-row' or
25999 `org-move-item-up', depending on context. See the individual commands
26000 for more information."
26001 (interactive "P")
26002 (cond
26003 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26004 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26005 ((org-at-item-p) (call-interactively 'org-move-item-up))
26006 (t (transpose-lines 1) (beginning-of-line -1))))
26008 (defun org-metadown (&optional arg)
26009 "Move subtree down or move table row down.
26010 Calls `org-move-subtree-down' or `org-table-move-row' or
26011 `org-move-item-down', depending on context. See the individual
26012 commands for more information."
26013 (interactive "P")
26014 (cond
26015 ((org-at-table-p) (call-interactively 'org-table-move-row))
26016 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26017 ((org-at-item-p) (call-interactively 'org-move-item-down))
26018 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26020 (defun org-shiftup (&optional arg)
26021 "Increase item in timestamp or increase priority of current headline.
26022 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26023 depending on context. See the individual commands for more information."
26024 (interactive "P")
26025 (cond
26026 ((org-at-timestamp-p t)
26027 (call-interactively (if org-edit-timestamp-down-means-later
26028 'org-timestamp-down 'org-timestamp-up)))
26029 ((org-on-heading-p) (call-interactively 'org-priority-up))
26030 ((org-at-item-p) (call-interactively 'org-previous-item))
26031 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26033 (defun org-shiftdown (&optional arg)
26034 "Decrease item in timestamp or decrease priority of current headline.
26035 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26036 depending on context. See the individual commands for more information."
26037 (interactive "P")
26038 (cond
26039 ((org-at-timestamp-p t)
26040 (call-interactively (if org-edit-timestamp-down-means-later
26041 'org-timestamp-up 'org-timestamp-down)))
26042 ((org-on-heading-p) (call-interactively 'org-priority-down))
26043 (t (call-interactively 'org-next-item))))
26045 (defun org-shiftright ()
26046 "Next TODO keyword or timestamp one day later, depending on context."
26047 (interactive)
26048 (cond
26049 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26050 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26051 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26052 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26053 (t (org-shiftcursor-error))))
26055 (defun org-shiftleft ()
26056 "Previous TODO keyword or timestamp one day earlier, depending on context."
26057 (interactive)
26058 (cond
26059 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26060 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26061 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26062 ((org-at-property-p)
26063 (call-interactively 'org-property-previous-allowed-value))
26064 (t (org-shiftcursor-error))))
26066 (defun org-shiftcontrolright ()
26067 "Switch to next TODO set."
26068 (interactive)
26069 (cond
26070 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26071 (t (org-shiftcursor-error))))
26073 (defun org-shiftcontrolleft ()
26074 "Switch to previous TODO set."
26075 (interactive)
26076 (cond
26077 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26078 (t (org-shiftcursor-error))))
26080 (defun org-ctrl-c-ret ()
26081 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26082 (interactive)
26083 (cond
26084 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26085 (t (call-interactively 'org-insert-heading))))
26087 (defun org-copy-special ()
26088 "Copy region in table or copy current subtree.
26089 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26090 See the individual commands for more information."
26091 (interactive)
26092 (call-interactively
26093 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26095 (defun org-cut-special ()
26096 "Cut region in table or cut current subtree.
26097 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26098 See the individual commands for more information."
26099 (interactive)
26100 (call-interactively
26101 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26103 (defun org-paste-special (arg)
26104 "Paste rectangular region into table, or past subtree relative to level.
26105 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26106 See the individual commands for more information."
26107 (interactive "P")
26108 (if (org-at-table-p)
26109 (org-table-paste-rectangle)
26110 (org-paste-subtree arg)))
26112 (defun org-ctrl-c-ctrl-c (&optional arg)
26113 "Set tags in headline, or update according to changed information at point.
26115 This command does many different things, depending on context:
26117 - If the cursor is in a headline, prompt for tags and insert them
26118 into the current line, aligned to `org-tags-column'. When called
26119 with prefix arg, realign all tags in the current buffer.
26121 - If the cursor is in one of the special #+KEYWORD lines, this
26122 triggers scanning the buffer for these lines and updating the
26123 information.
26125 - If the cursor is inside a table, realign the table. This command
26126 works even if the automatic table editor has been turned off.
26128 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26129 the entire table.
26131 - If the cursor is a the beginning of a dynamic block, update it.
26133 - If the cursor is inside a table created by the table.el package,
26134 activate that table.
26136 - If the current buffer is a remember buffer, close note and file it.
26137 with a prefix argument, file it without further interaction to the default
26138 location.
26140 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26141 links in this buffer.
26143 - If the cursor is on a numbered item in a plain list, renumber the
26144 ordered list.
26146 - If the cursor is on a checkbox, toggle it."
26147 (interactive "P")
26148 (let ((org-enable-table-editor t))
26149 (cond
26150 ((or org-clock-overlays
26151 org-occur-highlights
26152 org-latex-fragment-image-overlays)
26153 (org-remove-clock-overlays)
26154 (org-remove-occur-highlights)
26155 (org-remove-latex-fragment-image-overlays)
26156 (message "Temporary highlights/overlays removed from current buffer"))
26157 ((and (local-variable-p 'org-finish-function (current-buffer))
26158 (fboundp org-finish-function))
26159 (funcall org-finish-function))
26160 ((org-at-property-p)
26161 (call-interactively 'org-property-action))
26162 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
26163 ((org-on-heading-p) (call-interactively 'org-set-tags))
26164 ((org-at-table.el-p)
26165 (require 'table)
26166 (beginning-of-line 1)
26167 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
26168 (call-interactively 'table-recognize-table))
26169 ((org-at-table-p)
26170 (org-table-maybe-eval-formula)
26171 (if arg
26172 (call-interactively 'org-table-recalculate)
26173 (org-table-maybe-recalculate-line))
26174 (call-interactively 'org-table-align))
26175 ((org-at-item-checkbox-p)
26176 (call-interactively 'org-toggle-checkbox))
26177 ((org-at-item-p)
26178 (call-interactively 'org-maybe-renumber-ordered-list))
26179 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
26180 ;; Dynamic block
26181 (beginning-of-line 1)
26182 (org-update-dblock))
26183 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
26184 (cond
26185 ((equal (match-string 1) "TBLFM")
26186 ;; Recalculate the table before this line
26187 (save-excursion
26188 (beginning-of-line 1)
26189 (skip-chars-backward " \r\n\t")
26190 (if (org-at-table-p)
26191 (org-call-with-arg 'org-table-recalculate t))))
26193 (call-interactively 'org-mode-restart))))
26194 (t (error "C-c C-c can do nothing useful at this location.")))))
26196 (defun org-mode-restart ()
26197 "Restart Org-mode, to scan again for special lines.
26198 Also updates the keyword regular expressions."
26199 (interactive)
26200 (let ((org-inhibit-startup t)) (org-mode))
26201 (message "Org-mode restarted to refresh keyword and special line setup"))
26203 (defun org-kill-note-or-show-branches ()
26204 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
26205 (interactive)
26206 (if (not org-finish-function)
26207 (call-interactively 'show-branches)
26208 (let ((org-note-abort t))
26209 (funcall org-finish-function))))
26211 (defun org-return ()
26212 "Goto next table row or insert a newline.
26213 Calls `org-table-next-row' or `newline', depending on context.
26214 See the individual commands for more information."
26215 (interactive)
26216 (cond
26217 ((bobp) (newline))
26218 ((org-at-table-p)
26219 (org-table-justify-field-maybe)
26220 (call-interactively 'org-table-next-row))
26221 (t (newline))))
26224 (defun org-ctrl-c-minus ()
26225 "Insert separator line in table or modify bullet type in list.
26226 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
26227 depending on context."
26228 (interactive)
26229 (cond
26230 ((org-at-table-p)
26231 (call-interactively 'org-table-insert-hline))
26232 ((org-on-heading-p)
26233 ;; Convert to item
26234 (save-excursion
26235 (beginning-of-line 1)
26236 (if (looking-at "\\*+ ")
26237 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
26238 ((org-in-item-p)
26239 (call-interactively 'org-cycle-list-bullet))
26240 (t (error "`C-c -' does have no function here."))))
26242 (defun org-meta-return (&optional arg)
26243 "Insert a new heading or wrap a region in a table.
26244 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
26245 See the individual commands for more information."
26246 (interactive "P")
26247 (cond
26248 ((org-at-table-p)
26249 (call-interactively 'org-table-wrap-region))
26250 (t (call-interactively 'org-insert-heading))))
26252 ;;; Menu entries
26254 ;; Define the Org-mode menus
26255 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
26256 '("Tbl"
26257 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
26258 ["Next Field" org-cycle (org-at-table-p)]
26259 ["Previous Field" org-shifttab (org-at-table-p)]
26260 ["Next Row" org-return (org-at-table-p)]
26261 "--"
26262 ["Blank Field" org-table-blank-field (org-at-table-p)]
26263 ["Edit Field" org-table-edit-field (org-at-table-p)]
26264 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
26265 "--"
26266 ("Column"
26267 ["Move Column Left" org-metaleft (org-at-table-p)]
26268 ["Move Column Right" org-metaright (org-at-table-p)]
26269 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
26270 ["Insert Column" org-shiftmetaright (org-at-table-p)])
26271 ("Row"
26272 ["Move Row Up" org-metaup (org-at-table-p)]
26273 ["Move Row Down" org-metadown (org-at-table-p)]
26274 ["Delete Row" org-shiftmetaup (org-at-table-p)]
26275 ["Insert Row" org-shiftmetadown (org-at-table-p)]
26276 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
26277 "--"
26278 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
26279 ("Rectangle"
26280 ["Copy Rectangle" org-copy-special (org-at-table-p)]
26281 ["Cut Rectangle" org-cut-special (org-at-table-p)]
26282 ["Paste Rectangle" org-paste-special (org-at-table-p)]
26283 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
26284 "--"
26285 ("Calculate"
26286 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
26287 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
26288 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
26289 "--"
26290 ["Recalculate line" org-table-recalculate (org-at-table-p)]
26291 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
26292 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
26293 "--"
26294 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
26295 "--"
26296 ["Sum Column/Rectangle" org-table-sum
26297 (or (org-at-table-p) (org-region-active-p))]
26298 ["Which Column?" org-table-current-column (org-at-table-p)])
26299 ["Debug Formulas"
26300 org-table-toggle-formula-debugger
26301 :style toggle :selected org-table-formula-debug]
26302 ["Show Col/Row Numbers"
26303 org-table-toggle-coordinate-overlays
26304 :style toggle :selected org-table-overlay-coordinates]
26305 "--"
26306 ["Create" org-table-create (and (not (org-at-table-p))
26307 org-enable-table-editor)]
26308 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
26309 ["Import from File" org-table-import (not (org-at-table-p))]
26310 ["Export to File" org-table-export (org-at-table-p)]
26311 "--"
26312 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
26314 (easy-menu-define org-org-menu org-mode-map "Org menu"
26315 '("Org"
26316 ("Show/Hide"
26317 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
26318 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
26319 ["Sparse Tree" org-occur t]
26320 ["Reveal Context" org-reveal t]
26321 ["Show All" show-all t]
26322 "--"
26323 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
26324 "--"
26325 ["New Heading" org-insert-heading t]
26326 ("Navigate Headings"
26327 ["Up" outline-up-heading t]
26328 ["Next" outline-next-visible-heading t]
26329 ["Previous" outline-previous-visible-heading t]
26330 ["Next Same Level" outline-forward-same-level t]
26331 ["Previous Same Level" outline-backward-same-level t]
26332 "--"
26333 ["Jump" org-goto t])
26334 ("Edit Structure"
26335 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
26336 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
26337 "--"
26338 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
26339 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
26340 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
26341 "--"
26342 ["Promote Heading" org-metaleft (not (org-at-table-p))]
26343 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
26344 ["Demote Heading" org-metaright (not (org-at-table-p))]
26345 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
26346 "--"
26347 ["Sort Region/Children" org-sort (not (org-at-table-p))]
26348 "--"
26349 ["Convert to odd levels" org-convert-to-odd-levels t]
26350 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
26351 ("Editing"
26352 ["Emphasis..." org-emphasize t])
26353 ("Archive"
26354 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
26355 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
26356 ; :active t :keys "C-u C-c C-x C-a"]
26357 ["Sparse trees open ARCHIVE trees"
26358 (setq org-sparse-tree-open-archived-trees
26359 (not org-sparse-tree-open-archived-trees))
26360 :style toggle :selected org-sparse-tree-open-archived-trees]
26361 ["Cycling opens ARCHIVE trees"
26362 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
26363 :style toggle :selected org-cycle-open-archived-trees]
26364 ["Agenda includes ARCHIVE trees"
26365 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
26366 :style toggle :selected (not org-agenda-skip-archived-trees)]
26367 "--"
26368 ["Move Subtree to Archive" org-advertized-archive-subtree t]
26369 ; ["Check and Move Children" (org-archive-subtree '(4))
26370 ; :active t :keys "C-u C-c C-x C-s"]
26372 "--"
26373 ("TODO Lists"
26374 ["TODO/DONE/-" org-todo t]
26375 ("Select keyword"
26376 ["Next keyword" org-shiftright (org-on-heading-p)]
26377 ["Previous keyword" org-shiftleft (org-on-heading-p)]
26378 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
26379 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
26380 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
26381 ["Show TODO Tree" org-show-todo-tree t]
26382 ["Global TODO list" org-todo-list t]
26383 "--"
26384 ["Set Priority" org-priority t]
26385 ["Priority Up" org-shiftup t]
26386 ["Priority Down" org-shiftdown t])
26387 ("TAGS and Properties"
26388 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
26389 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
26390 "--"
26391 ["Set property" 'org-set-property t]
26392 ["Column view of properties" org-columns t]
26393 ["Insert Column View DBlock" org-insert-columns-dblock t])
26394 ("Dates and Scheduling"
26395 ["Timestamp" org-time-stamp t]
26396 ["Timestamp (inactive)" org-time-stamp-inactive t]
26397 ("Change Date"
26398 ["1 Day Later" org-shiftright t]
26399 ["1 Day Earlier" org-shiftleft t]
26400 ["1 ... Later" org-shiftup t]
26401 ["1 ... Earlier" org-shiftdown t])
26402 ["Compute Time Range" org-evaluate-time-range t]
26403 ["Schedule Item" org-schedule t]
26404 ["Deadline" org-deadline t]
26405 "--"
26406 ["Custom time format" org-toggle-time-stamp-overlays
26407 :style radio :selected org-display-custom-times]
26408 "--"
26409 ["Goto Calendar" org-goto-calendar t]
26410 ["Date from Calendar" org-date-from-calendar t])
26411 ("Logging work"
26412 ["Clock in" org-clock-in t]
26413 ["Clock out" org-clock-out t]
26414 ["Clock cancel" org-clock-cancel t]
26415 ["Goto running clock" org-clock-goto t]
26416 ["Display times" org-clock-display t]
26417 ["Create clock table" org-clock-report t]
26418 "--"
26419 ["Record DONE time"
26420 (progn (setq org-log-done (not org-log-done))
26421 (message "Switching to %s will %s record a timestamp"
26422 (car org-done-keywords)
26423 (if org-log-done "automatically" "not")))
26424 :style toggle :selected org-log-done])
26425 "--"
26426 ["Agenda Command..." org-agenda t]
26427 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
26428 ("File List for Agenda")
26429 ("Special views current file"
26430 ["TODO Tree" org-show-todo-tree t]
26431 ["Check Deadlines" org-check-deadlines t]
26432 ["Timeline" org-timeline t]
26433 ["Tags Tree" org-tags-sparse-tree t])
26434 "--"
26435 ("Hyperlinks"
26436 ["Store Link (Global)" org-store-link t]
26437 ["Insert Link" org-insert-link t]
26438 ["Follow Link" org-open-at-point t]
26439 "--"
26440 ["Next link" org-next-link t]
26441 ["Previous link" org-previous-link t]
26442 "--"
26443 ["Descriptive Links"
26444 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
26445 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
26446 ["Literal Links"
26447 (progn
26448 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
26449 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
26450 "--"
26451 ["Export/Publish..." org-export t]
26452 ("LaTeX"
26453 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
26454 :selected org-cdlatex-mode]
26455 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
26456 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
26457 ["Modify math symbol" org-cdlatex-math-modify
26458 (org-inside-LaTeX-fragment-p)]
26459 ["Export LaTeX fragments as images"
26460 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
26461 :style toggle :selected org-export-with-LaTeX-fragments])
26462 "--"
26463 ("Documentation"
26464 ["Show Version" org-version t]
26465 ["Info Documentation" org-info t])
26466 ("Customize"
26467 ["Browse Org Group" org-customize t]
26468 "--"
26469 ["Expand This Menu" org-create-customize-menu
26470 (fboundp 'customize-menu-create)])
26471 "--"
26472 ["Refresh setup" org-mode-restart t]
26475 (defun org-info (&optional node)
26476 "Read documentation for Org-mode in the info system.
26477 With optional NODE, go directly to that node."
26478 (interactive)
26479 (require 'info)
26480 (Info-goto-node (format "(org)%s" (or node ""))))
26482 (defun org-install-agenda-files-menu ()
26483 (let ((bl (buffer-list)))
26484 (save-excursion
26485 (while bl
26486 (set-buffer (pop bl))
26487 (if (org-mode-p) (setq bl nil)))
26488 (when (org-mode-p)
26489 (easy-menu-change
26490 '("Org") "File List for Agenda"
26491 (append
26492 (list
26493 ["Edit File List" (org-edit-agenda-file-list) t]
26494 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
26495 ["Remove Current File from List" org-remove-file t]
26496 ["Cycle through agenda files" org-cycle-agenda-files t]
26497 ["Occur in all agenda files" org-occur-in-agenda-files t]
26498 "--")
26499 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
26501 ;;;; Documentation
26503 (defun org-customize ()
26504 "Call the customize function with org as argument."
26505 (interactive)
26506 (customize-browse 'org))
26508 (defun org-create-customize-menu ()
26509 "Create a full customization menu for Org-mode, insert it into the menu."
26510 (interactive)
26511 (if (fboundp 'customize-menu-create)
26512 (progn
26513 (easy-menu-change
26514 '("Org") "Customize"
26515 `(["Browse Org group" org-customize t]
26516 "--"
26517 ,(customize-menu-create 'org)
26518 ["Set" Custom-set t]
26519 ["Save" Custom-save t]
26520 ["Reset to Current" Custom-reset-current t]
26521 ["Reset to Saved" Custom-reset-saved t]
26522 ["Reset to Standard Settings" Custom-reset-standard t]))
26523 (message "\"Org\"-menu now contains full customization menu"))
26524 (error "Cannot expand menu (outdated version of cus-edit.el)")))
26526 ;;;; Miscellaneous stuff
26529 ;;; Generally useful functions
26531 (defun org-context ()
26532 "Return a list of contexts of the current cursor position.
26533 If several contexts apply, all are returned.
26534 Each context entry is a list with a symbol naming the context, and
26535 two positions indicating start and end of the context. Possible
26536 contexts are:
26538 :headline anywhere in a headline
26539 :headline-stars on the leading stars in a headline
26540 :todo-keyword on a TODO keyword (including DONE) in a headline
26541 :tags on the TAGS in a headline
26542 :priority on the priority cookie in a headline
26543 :item on the first line of a plain list item
26544 :item-bullet on the bullet/number of a plain list item
26545 :checkbox on the checkbox in a plain list item
26546 :table in an org-mode table
26547 :table-special on a special filed in a table
26548 :table-table in a table.el table
26549 :link on a hyperlink
26550 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
26551 :target on a <<target>>
26552 :radio-target on a <<<radio-target>>>
26553 :latex-fragment on a LaTeX fragment
26554 :latex-preview on a LaTeX fragment with overlayed preview image
26556 This function expects the position to be visible because it uses font-lock
26557 faces as a help to recognize the following contexts: :table-special, :link,
26558 and :keyword."
26559 (let* ((f (get-text-property (point) 'face))
26560 (faces (if (listp f) f (list f)))
26561 (p (point)) clist o)
26562 ;; First the large context
26563 (cond
26564 ((org-on-heading-p t)
26565 (push (list :headline (point-at-bol) (point-at-eol)) clist)
26566 (when (progn
26567 (beginning-of-line 1)
26568 (looking-at org-todo-line-tags-regexp))
26569 (push (org-point-in-group p 1 :headline-stars) clist)
26570 (push (org-point-in-group p 2 :todo-keyword) clist)
26571 (push (org-point-in-group p 4 :tags) clist))
26572 (goto-char p)
26573 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
26574 (if (looking-at "\\[#[A-Z0-9]\\]")
26575 (push (org-point-in-group p 0 :priority) clist)))
26577 ((org-at-item-p)
26578 (push (org-point-in-group p 2 :item-bullet) clist)
26579 (push (list :item (point-at-bol)
26580 (save-excursion (org-end-of-item) (point)))
26581 clist)
26582 (and (org-at-item-checkbox-p)
26583 (push (org-point-in-group p 0 :checkbox) clist)))
26585 ((org-at-table-p)
26586 (push (list :table (org-table-begin) (org-table-end)) clist)
26587 (if (memq 'org-formula faces)
26588 (push (list :table-special
26589 (previous-single-property-change p 'face)
26590 (next-single-property-change p 'face)) clist)))
26591 ((org-at-table-p 'any)
26592 (push (list :table-table) clist)))
26593 (goto-char p)
26595 ;; Now the small context
26596 (cond
26597 ((org-at-timestamp-p)
26598 (push (org-point-in-group p 0 :timestamp) clist))
26599 ((memq 'org-link faces)
26600 (push (list :link
26601 (previous-single-property-change p 'face)
26602 (next-single-property-change p 'face)) clist))
26603 ((memq 'org-special-keyword faces)
26604 (push (list :keyword
26605 (previous-single-property-change p 'face)
26606 (next-single-property-change p 'face)) clist))
26607 ((org-on-target-p)
26608 (push (org-point-in-group p 0 :target) clist)
26609 (goto-char (1- (match-beginning 0)))
26610 (if (looking-at org-radio-target-regexp)
26611 (push (org-point-in-group p 0 :radio-target) clist))
26612 (goto-char p))
26613 ((setq o (car (delq nil
26614 (mapcar
26615 (lambda (x)
26616 (if (memq x org-latex-fragment-image-overlays) x))
26617 (org-overlays-at (point))))))
26618 (push (list :latex-fragment
26619 (org-overlay-start o) (org-overlay-end o)) clist)
26620 (push (list :latex-preview
26621 (org-overlay-start o) (org-overlay-end o)) clist))
26622 ((org-inside-LaTeX-fragment-p)
26623 ;; FIXME: positions wrong.
26624 (push (list :latex-fragment (point) (point)) clist)))
26626 (setq clist (nreverse (delq nil clist)))
26627 clist))
26629 ;; FIXME: Compare with at-regexp-p Do we need both?
26630 (defun org-in-regexp (re &optional nlines visually)
26631 "Check if point is inside a match of regexp.
26632 Normally only the current line is checked, but you can include NLINES extra
26633 lines both before and after point into the search.
26634 If VISUALLY is set, require that the cursor is not after the match but
26635 really on, so that the block visually is on the match."
26636 (catch 'exit
26637 (let ((pos (point))
26638 (eol (point-at-eol (+ 1 (or nlines 0))))
26639 (inc (if visually 1 0)))
26640 (save-excursion
26641 (beginning-of-line (- 1 (or nlines 0)))
26642 (while (re-search-forward re eol t)
26643 (if (and (<= (match-beginning 0) pos)
26644 (>= (+ inc (match-end 0)) pos))
26645 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
26647 (defun org-at-regexp-p (regexp)
26648 "Is point inside a match of REGEXP in the current line?"
26649 (catch 'exit
26650 (save-excursion
26651 (let ((pos (point)) (end (point-at-eol)))
26652 (beginning-of-line 1)
26653 (while (re-search-forward regexp end t)
26654 (if (and (<= (match-beginning 0) pos)
26655 (>= (match-end 0) pos))
26656 (throw 'exit t)))
26657 nil))))
26659 (defun org-occur-in-agenda-files (regexp &optional nlines)
26660 "Call `multi-occur' with buffers for all agenda files."
26661 (interactive "sOrg-files matching: \np")
26662 (let* ((files (org-agenda-files))
26663 (tnames (mapcar 'file-truename files))
26664 (extra org-agenda-multi-occur-extra-files)
26666 (while (setq f (pop extra))
26667 (unless (member (file-truename f) tnames)
26668 (add-to-list 'files f 'append)
26669 (add-to-list 'tnames (file-truename f) 'append)))
26670 (multi-occur
26671 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
26672 regexp)))
26674 (defun org-uniquify (list)
26675 "Remove duplicate elements from LIST."
26676 (let (res)
26677 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
26678 res))
26680 (defun org-delete-all (elts list)
26681 "Remove all elements in ELTS from LIST."
26682 (while elts
26683 (setq list (delete (pop elts) list)))
26684 list)
26686 (defun org-point-in-group (point group &optional context)
26687 "Check if POINT is in match-group GROUP.
26688 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
26689 match. If the match group does ot exist or point is not inside it,
26690 return nil."
26691 (and (match-beginning group)
26692 (>= point (match-beginning group))
26693 (<= point (match-end group))
26694 (if context
26695 (list context (match-beginning group) (match-end group))
26696 t)))
26698 (defun org-switch-to-buffer-other-window (&rest args)
26699 "Switch to buffer in a second window on the current frame.
26700 In particular, do not allow pop-up frames."
26701 (let (pop-up-frames special-display-buffer-names special-display-regexps
26702 special-display-function)
26703 (apply 'switch-to-buffer-other-window args)))
26705 (defun org-combine-plists (&rest plists)
26706 "Create a single property list from all plists in PLISTS.
26707 The process starts by copying the first list, and then setting properties
26708 from the other lists. Settings in the last list are the most significant
26709 ones and overrule settings in the other lists."
26710 (let ((rtn (copy-sequence (pop plists)))
26711 p v ls)
26712 (while plists
26713 (setq ls (pop plists))
26714 (while ls
26715 (setq p (pop ls) v (pop ls))
26716 (setq rtn (plist-put rtn p v))))
26717 rtn))
26719 (defun org-move-line-down (arg)
26720 "Move the current line down. With prefix argument, move it past ARG lines."
26721 (interactive "p")
26722 (let ((col (current-column))
26723 beg end pos)
26724 (beginning-of-line 1) (setq beg (point))
26725 (beginning-of-line 2) (setq end (point))
26726 (beginning-of-line (+ 1 arg))
26727 (setq pos (move-marker (make-marker) (point)))
26728 (insert (delete-and-extract-region beg end))
26729 (goto-char pos)
26730 (move-to-column col)))
26732 (defun org-move-line-up (arg)
26733 "Move the current line up. With prefix argument, move it past ARG lines."
26734 (interactive "p")
26735 (let ((col (current-column))
26736 beg end pos)
26737 (beginning-of-line 1) (setq beg (point))
26738 (beginning-of-line 2) (setq end (point))
26739 (beginning-of-line (- arg))
26740 (setq pos (move-marker (make-marker) (point)))
26741 (insert (delete-and-extract-region beg end))
26742 (goto-char pos)
26743 (move-to-column col)))
26745 (defun org-replace-escapes (string table)
26746 "Replace %-escapes in STRING with values in TABLE.
26747 TABLE is an association list with keys like \"%a\" and string values.
26748 The sequences in STRING may contain normal field width and padding information,
26749 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
26750 so values can contain further %-escapes if they are define later in TABLE."
26751 (let ((case-fold-search nil)
26752 e re rpl)
26753 (while (setq e (pop table))
26754 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
26755 (while (string-match re string)
26756 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
26757 (cdr e)))
26758 (setq string (replace-match rpl t t string))))
26759 string))
26762 (defun org-sublist (list start end)
26763 "Return a section of LIST, from START to END.
26764 Counting starts at 1."
26765 (let (rtn (c start))
26766 (setq list (nthcdr (1- start) list))
26767 (while (and list (<= c end))
26768 (push (pop list) rtn)
26769 (setq c (1+ c)))
26770 (nreverse rtn)))
26772 (defun org-find-base-buffer-visiting (file)
26773 "Like `find-buffer-visiting' but alway return the base buffer and
26774 not an indirect buffer"
26775 (let ((buf (find-buffer-visiting file)))
26776 (if buf
26777 (or (buffer-base-buffer buf) buf)
26778 nil)))
26780 (defun org-image-file-name-regexp ()
26781 "Return regexp matching the file names of images."
26782 (if (fboundp 'image-file-name-regexp)
26783 (image-file-name-regexp)
26784 (let ((image-file-name-extensions
26785 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
26786 "xbm" "xpm" "pbm" "pgm" "ppm")))
26787 (concat "\\."
26788 (regexp-opt (nconc (mapcar 'upcase
26789 image-file-name-extensions)
26790 image-file-name-extensions)
26792 "\\'"))))
26794 (defun org-file-image-p (file)
26795 "Return non-nil if FILE is an image."
26796 (save-match-data
26797 (string-match (org-image-file-name-regexp) file)))
26799 ;;; Paragraph filling stuff.
26800 ;; We want this to be just right, so use the full arsenal.
26802 (defun org-indent-line-function ()
26803 "Indent line like previous, but further if previous was headline or item."
26804 (interactive)
26805 (let* ((pos (point))
26806 (itemp (org-at-item-p))
26807 column bpos bcol tpos tcol bullet btype bullet-type)
26808 ;; Find the previous relevant line
26809 (beginning-of-line 1)
26810 (cond
26811 ((looking-at "#") (setq column 0))
26812 ((looking-at "\\*+ ") (setq column 0))
26814 (beginning-of-line 0)
26815 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
26816 (beginning-of-line 0))
26817 (cond
26818 ((looking-at "\\*+[ \t]+")
26819 (goto-char (match-end 0))
26820 (setq column (current-column)))
26821 ((org-in-item-p)
26822 (org-beginning-of-item)
26823 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
26824 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
26825 (setq bpos (match-beginning 1) tpos (match-end 0)
26826 bcol (progn (goto-char bpos) (current-column))
26827 tcol (progn (goto-char tpos) (current-column))
26828 bullet (match-string 1)
26829 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
26830 (if (not itemp)
26831 (setq column tcol)
26832 (goto-char pos)
26833 (beginning-of-line 1)
26834 (if (looking-at "\\S-")
26835 (progn
26836 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
26837 (setq bullet (match-string 1)
26838 btype (if (string-match "[0-9]" bullet) "n" bullet))
26839 (setq column (if (equal btype bullet-type) bcol tcol)))
26840 (setq column (org-get-indentation)))))
26841 (t (setq column (org-get-indentation))))))
26842 (goto-char pos)
26843 (if (<= (current-column) (current-indentation))
26844 (indent-line-to column)
26845 (save-excursion (indent-line-to column)))
26846 (setq column (current-column))
26847 (beginning-of-line 1)
26848 (if (looking-at
26849 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
26850 (replace-match (concat "\\1" (format org-property-format
26851 (match-string 2) (match-string 3)))
26852 t nil))
26853 (move-to-column column)))
26855 (defun org-set-autofill-regexps ()
26856 (interactive)
26857 ;; In the paragraph separator we include headlines, because filling
26858 ;; text in a line directly attached to a headline would otherwise
26859 ;; fill the headline as well.
26860 (org-set-local 'comment-start-skip "^#+[ \t]*")
26861 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
26862 ;; The paragraph starter includes hand-formatted lists.
26863 (org-set-local 'paragraph-start
26864 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
26865 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
26866 ;; But only if the user has not turned off tables or fixed-width regions
26867 (org-set-local
26868 'auto-fill-inhibit-regexp
26869 (concat "\\*+ \\|#\\+"
26870 "\\|[ \t]*" org-keyword-time-regexp
26871 (if (or org-enable-table-editor org-enable-fixed-width-editor)
26872 (concat
26873 "\\|[ \t]*["
26874 (if org-enable-table-editor "|" "")
26875 (if org-enable-fixed-width-editor ":" "")
26876 "]"))))
26877 ;; We use our own fill-paragraph function, to make sure that tables
26878 ;; and fixed-width regions are not wrapped. That function will pass
26879 ;; through to `fill-paragraph' when appropriate.
26880 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
26881 ; Adaptive filling: To get full control, first make sure that
26882 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
26883 (org-set-local 'adaptive-fill-regexp "\000")
26884 (org-set-local 'adaptive-fill-function
26885 'org-adaptive-fill-function))
26887 (defun org-fill-paragraph (&optional justify)
26888 "Re-align a table, pass through to fill-paragraph if no table."
26889 (let ((table-p (org-at-table-p))
26890 (table.el-p (org-at-table.el-p)))
26891 (cond ((and (equal (char-after (point-at-bol)) ?*)
26892 (save-excursion (goto-char (point-at-bol))
26893 (looking-at outline-regexp)))
26894 t) ; skip headlines
26895 (table.el-p t) ; skip table.el tables
26896 (table-p (org-table-align) t) ; align org-mode tables
26897 (t nil)))) ; call paragraph-fill
26899 ;; For reference, this is the default value of adaptive-fill-regexp
26900 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
26902 (defun org-adaptive-fill-function ()
26903 "Return a fill prefix for org-mode files.
26904 In particular, this makes sure hanging paragraphs for hand-formatted lists
26905 work correctly."
26906 (cond ((looking-at "#[ \t]+")
26907 (match-string 0))
26908 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
26909 (save-excursion
26910 (goto-char (match-end 0))
26911 (make-string (current-column) ?\ )))
26912 (t nil)))
26914 ;;;; Functions extending outline functionality
26916 (defun org-beginning-of-line (&optional arg)
26917 "Go to the beginning of the current line. If that is invisible, continue
26918 to a visible line beginning. This makes the function of C-a more intuitive.
26919 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
26920 first attempt, and only move to after the tags when the cursor is already
26921 beyond the end of the headline."
26922 (interactive "P")
26923 (let ((pos (point)))
26924 (beginning-of-line 1)
26925 (if (bobp)
26927 (backward-char 1)
26928 (if (org-invisible-p)
26929 (while (and (not (bobp)) (org-invisible-p))
26930 (backward-char 1)
26931 (beginning-of-line 1))
26932 (forward-char 1)))
26933 (when org-special-ctrl-a/e
26934 (cond
26935 ((and (looking-at org-todo-line-regexp)
26936 (= (char-after (match-end 1)) ?\ ))
26937 (goto-char
26938 (if (eq org-special-ctrl-a/e t)
26939 (cond ((> pos (match-beginning 3)) (match-beginning 3))
26940 ((= pos (point)) (match-beginning 3))
26941 (t (point)))
26942 (cond ((> pos (point)) (point))
26943 ((not (eq last-command this-command)) (point))
26944 (t (match-beginning 3))))))
26945 ((org-at-item-p)
26946 (goto-char
26947 (if (eq org-special-ctrl-a/e t)
26948 (cond ((> pos (match-end 4)) (match-end 4))
26949 ((= pos (point)) (match-end 4))
26950 (t (point)))
26951 (cond ((> pos (point)) (point))
26952 ((not (eq last-command this-command)) (point))
26953 (t (match-end 4))))))))))
26955 (defun org-end-of-line (&optional arg)
26956 "Go to the end of the line.
26957 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
26958 first attempt, and only move to after the tags when the cursor is already
26959 beyond the end of the headline."
26960 (interactive "P")
26961 (if (or (not org-special-ctrl-a/e)
26962 (not (org-on-heading-p)))
26963 (end-of-line arg)
26964 (let ((pos (point)))
26965 (beginning-of-line 1)
26966 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
26967 (if (eq org-special-ctrl-a/e t)
26968 (if (or (< pos (match-beginning 1))
26969 (= pos (match-end 0)))
26970 (goto-char (match-beginning 1))
26971 (goto-char (match-end 0)))
26972 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
26973 (goto-char (match-end 0))
26974 (goto-char (match-beginning 1))))
26975 (end-of-line arg)))))
26977 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
26978 (define-key org-mode-map "\C-e" 'org-end-of-line)
26980 (defun org-invisible-p ()
26981 "Check if point is at a character currently not visible."
26982 ;; Early versions of noutline don't have `outline-invisible-p'.
26983 (if (fboundp 'outline-invisible-p)
26984 (outline-invisible-p)
26985 (get-char-property (point) 'invisible)))
26987 (defun org-invisible-p2 ()
26988 "Check if point is at a character currently not visible."
26989 (save-excursion
26990 (if (and (eolp) (not (bobp))) (backward-char 1))
26991 ;; Early versions of noutline don't have `outline-invisible-p'.
26992 (if (fboundp 'outline-invisible-p)
26993 (outline-invisible-p)
26994 (get-char-property (point) 'invisible))))
26996 (defalias 'org-back-to-heading 'outline-back-to-heading)
26997 (defalias 'org-on-heading-p 'outline-on-heading-p)
26998 (defalias 'org-at-heading-p 'outline-on-heading-p)
26999 (defun org-at-heading-or-item-p ()
27000 (or (org-on-heading-p) (org-at-item-p)))
27002 (defun org-on-target-p ()
27003 (or (org-in-regexp org-radio-target-regexp)
27004 (org-in-regexp org-target-regexp)))
27006 (defun org-up-heading-all (arg)
27007 "Move to the heading line of which the present line is a subheading.
27008 This function considers both visible and invisible heading lines.
27009 With argument, move up ARG levels."
27010 (if (fboundp 'outline-up-heading-all)
27011 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27012 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27014 (defun org-up-heading-safe ()
27015 "Move to the heading line of which the present line is a subheading.
27016 This version will not throw an error. It will return the level of the
27017 headline found, or nil if no higher level is found."
27018 (let ((pos (point)) start-level level
27019 (re (concat "^" outline-regexp)))
27020 (catch 'exit
27021 (outline-back-to-heading t)
27022 (setq start-level (funcall outline-level))
27023 (if (equal start-level 1) (throw 'exit nil))
27024 (while (re-search-backward re nil t)
27025 (setq level (funcall outline-level))
27026 (if (< level start-level) (throw 'exit level)))
27027 nil)))
27029 (defun org-goto-sibling (&optional previous)
27030 "Goto the next sibling, even if it is invisible.
27031 When PREVIOUS is set, go to the previous sibling instead. Returns t
27032 when a sibling was found. When none is found, return nil and don't
27033 move point."
27034 (let ((fun (if previous 're-search-backward 're-search-forward))
27035 (pos (point))
27036 (re (concat "^" outline-regexp))
27037 level l)
27038 (when (condition-case nil (org-back-to-heading t) (error nil))
27039 (setq level (funcall outline-level))
27040 (catch 'exit
27041 (or previous (forward-char 1))
27042 (while (funcall fun re nil t)
27043 (setq l (funcall outline-level))
27044 (when (< l level) (goto-char pos) (throw 'exit nil))
27045 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27046 (goto-char pos)
27047 nil))))
27049 (defun org-show-siblings ()
27050 "Show all siblings of the current headline."
27051 (save-excursion
27052 (while (org-goto-sibling) (org-flag-heading nil)))
27053 (save-excursion
27054 (while (org-goto-sibling 'previous)
27055 (org-flag-heading nil))))
27057 (defun org-show-hidden-entry ()
27058 "Show an entry where even the heading is hidden."
27059 (save-excursion
27060 (org-show-entry)))
27062 (defun org-flag-heading (flag &optional entry)
27063 "Flag the current heading. FLAG non-nil means make invisible.
27064 When ENTRY is non-nil, show the entire entry."
27065 (save-excursion
27066 (org-back-to-heading t)
27067 ;; Check if we should show the entire entry
27068 (if entry
27069 (progn
27070 (org-show-entry)
27071 (save-excursion
27072 (and (outline-next-heading)
27073 (org-flag-heading nil))))
27074 (outline-flag-region (max (point-min) (1- (point)))
27075 (save-excursion (outline-end-of-heading) (point))
27076 flag))))
27078 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27079 ;; This is an exact copy of the original function, but it uses
27080 ;; `org-back-to-heading', to make it work also in invisible
27081 ;; trees. And is uses an invisible-OK argument.
27082 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
27083 (org-back-to-heading invisible-OK)
27084 (let ((first t)
27085 (level (funcall outline-level)))
27086 (while (and (not (eobp))
27087 (or first (> (funcall outline-level) level)))
27088 (setq first nil)
27089 (outline-next-heading))
27090 (unless to-heading
27091 (if (memq (preceding-char) '(?\n ?\^M))
27092 (progn
27093 ;; Go to end of line before heading
27094 (forward-char -1)
27095 (if (memq (preceding-char) '(?\n ?\^M))
27096 ;; leave blank line before heading
27097 (forward-char -1))))))
27098 (point))
27100 (defun org-show-subtree ()
27101 "Show everything after this heading at deeper levels."
27102 (outline-flag-region
27103 (point)
27104 (save-excursion
27105 (outline-end-of-subtree) (outline-next-heading) (point))
27106 nil))
27108 (defun org-show-entry ()
27109 "Show the body directly following this heading.
27110 Show the heading too, if it is currently invisible."
27111 (interactive)
27112 (save-excursion
27113 (condition-case nil
27114 (progn
27115 (org-back-to-heading t)
27116 (outline-flag-region
27117 (max (point-min) (1- (point)))
27118 (save-excursion
27119 (re-search-forward
27120 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
27121 (or (match-beginning 1) (point-max)))
27122 nil))
27123 (error nil))))
27125 (defun org-make-options-regexp (kwds)
27126 "Make a regular expression for keyword lines."
27127 (concat
27129 "#?[ \t]*\\+\\("
27130 (mapconcat 'regexp-quote kwds "\\|")
27131 "\\):[ \t]*"
27132 "\\(.+\\)"))
27134 ;; Make isearch reveal the necessary context
27135 (defun org-isearch-end ()
27136 "Reveal context after isearch exits."
27137 (when isearch-success ; only if search was successful
27138 (if (featurep 'xemacs)
27139 ;; Under XEmacs, the hook is run in the correct place,
27140 ;; we directly show the context.
27141 (org-show-context 'isearch)
27142 ;; In Emacs the hook runs *before* restoring the overlays.
27143 ;; So we have to use a one-time post-command-hook to do this.
27144 ;; (Emacs 22 has a special variable, see function `org-mode')
27145 (unless (and (boundp 'isearch-mode-end-hook-quit)
27146 isearch-mode-end-hook-quit)
27147 ;; Only when the isearch was not quitted.
27148 (org-add-hook 'post-command-hook 'org-isearch-post-command
27149 'append 'local)))))
27151 (defun org-isearch-post-command ()
27152 "Remove self from hook, and show context."
27153 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
27154 (org-show-context 'isearch))
27157 ;;;; Integration with and fixes for other packages
27159 ;;; Imenu support
27161 (defvar org-imenu-markers nil
27162 "All markers currently used by Imenu.")
27163 (make-variable-buffer-local 'org-imenu-markers)
27165 (defun org-imenu-new-marker (&optional pos)
27166 "Return a new marker for use by Imenu, and remember the marker."
27167 (let ((m (make-marker)))
27168 (move-marker m (or pos (point)))
27169 (push m org-imenu-markers)
27172 (defun org-imenu-get-tree ()
27173 "Produce the index for Imenu."
27174 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
27175 (setq org-imenu-markers nil)
27176 (let* ((n org-imenu-depth)
27177 (re (concat "^" outline-regexp))
27178 (subs (make-vector (1+ n) nil))
27179 (last-level 0)
27180 m tree level head)
27181 (save-excursion
27182 (save-restriction
27183 (widen)
27184 (goto-char (point-max))
27185 (while (re-search-backward re nil t)
27186 (setq level (org-reduced-level (funcall outline-level)))
27187 (when (<= level n)
27188 (looking-at org-complex-heading-regexp)
27189 (setq head (org-match-string-no-properties 4)
27190 m (org-imenu-new-marker))
27191 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
27192 (if (>= level last-level)
27193 (push (cons head m) (aref subs level))
27194 (push (cons head (aref subs (1+ level))) (aref subs level))
27195 (loop for i from (1+ level) to n do (aset subs i nil)))
27196 (setq last-level level)))))
27197 (aref subs 1)))
27199 (eval-after-load "imenu"
27200 '(progn
27201 (add-hook 'imenu-after-jump-hook
27202 (lambda () (org-show-context 'org-goto)))))
27204 ;; Speedbar support
27206 (defun org-speedbar-set-agenda-restriction ()
27207 "Restrict future agenda commands to the location at point in speedbar.
27208 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
27209 (interactive)
27210 (let (p m tp np dir txt w)
27211 (cond
27212 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27213 'org-imenu t))
27214 (setq m (get-text-property p 'org-imenu-marker))
27215 (save-excursion
27216 (save-restriction
27217 (set-buffer (marker-buffer m))
27218 (goto-char m)
27219 (org-agenda-set-restriction-lock 'subtree))))
27220 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27221 'speedbar-function 'speedbar-find-file))
27222 (setq tp (previous-single-property-change
27223 (1+ p) 'speedbar-function)
27224 np (next-single-property-change
27225 tp 'speedbar-function)
27226 dir (speedbar-line-directory)
27227 txt (buffer-substring-no-properties (or tp (point-min))
27228 (or np (point-max))))
27229 (save-excursion
27230 (save-restriction
27231 (set-buffer (find-file-noselect
27232 (let ((default-directory dir))
27233 (expand-file-name txt))))
27234 (unless (org-mode-p)
27235 (error "Cannot restrict to non-Org-mode file"))
27236 (org-agenda-set-restriction-lock 'file))))
27237 (t (error "Don't know how to restrict Org-mode's agenda")))
27238 (org-move-overlay org-speedbar-restriction-lock-overlay
27239 (point-at-bol) (point-at-eol))
27240 (setq current-prefix-arg nil)
27241 (org-agenda-maybe-redo)))
27243 (eval-after-load "speedbar"
27244 '(progn
27245 (speedbar-add-supported-extension ".org")
27246 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
27247 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
27248 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
27249 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)))
27251 ;;; Fixes and Hacks
27253 ;; Make flyspell not check words in links, to not mess up our keymap
27254 (defun org-mode-flyspell-verify ()
27255 "Don't let flyspell put overlays at active buttons."
27256 (not (get-text-property (point) 'keymap)))
27258 ;; Make `bookmark-jump' show the jump location if it was hidden.
27259 (eval-after-load "bookmark"
27260 '(if (boundp 'bookmark-after-jump-hook)
27261 ;; We can use the hook
27262 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
27263 ;; Hook not available, use advice
27264 (defadvice bookmark-jump (after org-make-visible activate)
27265 "Make the position visible."
27266 (org-bookmark-jump-unhide))))
27268 (defun org-bookmark-jump-unhide ()
27269 "Unhide the current position, to show the bookmark location."
27270 (and (org-mode-p)
27271 (or (org-invisible-p)
27272 (save-excursion (goto-char (max (point-min) (1- (point))))
27273 (org-invisible-p)))
27274 (org-show-context 'bookmark-jump)))
27276 ;; Fix a bug in htmlize where there are text properties (face nil)
27277 (eval-after-load "htmlize"
27278 '(progn
27279 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
27280 "Make sure there are no nil faces"
27281 (setq ad-return-value (delq nil ad-return-value)))))
27283 ;; Make session.el ignore our circular variable
27284 (eval-after-load "session"
27285 '(add-to-list 'session-globals-exclude 'org-mark-ring))
27287 ;;;; Experimental code
27289 (defun org-closed-in-range ()
27290 "Sparse tree of items closed in a certain time range.
27291 Still experimental, may disappear in the future."
27292 (interactive)
27293 ;; Get the time interval from the user.
27294 (let* ((time1 (time-to-seconds
27295 (org-read-date nil 'to-time nil "Starting date: ")))
27296 (time2 (time-to-seconds
27297 (org-read-date nil 'to-time nil "End date:")))
27298 ;; callback function
27299 (callback (lambda ()
27300 (let ((time
27301 (time-to-seconds
27302 (apply 'encode-time
27303 (org-parse-time-string
27304 (match-string 1))))))
27305 ;; check if time in interval
27306 (and (>= time time1) (<= time time2))))))
27307 ;; make tree, check each match with the callback
27308 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
27310 ;; FIXME: this needs a much better algorithm
27311 (defun org-assign-fast-keys (alist)
27312 "Assign fast keys to a keyword-key alist.
27313 Respect keys that are already there."
27314 (let (new e k c c1 c2 (char ?a))
27315 (while (setq e (pop alist))
27316 (cond
27317 ((equal e '(:startgroup)) (push e new))
27318 ((equal e '(:endgroup)) (push e new))
27320 (setq k (car e) c2 nil)
27321 (if (cdr e)
27322 (setq c (cdr e))
27323 ;; automatically assign a character.
27324 (setq c1 (string-to-char
27325 (downcase (substring
27326 k (if (= (string-to-char k) ?@) 1 0)))))
27327 (if (or (rassoc c1 new) (rassoc c1 alist))
27328 (while (or (rassoc char new) (rassoc char alist))
27329 (setq char (1+ char)))
27330 (setq c2 c1))
27331 (setq c (or c2 char)))
27332 (push (cons k c) new))))
27333 (nreverse new)))
27336 (defcustom org-highlight-latex-fragments-and-specials nil
27337 "Non-nil means, fontify what is treated specially by the exporters."
27338 :group 'org-font-lock
27339 :type 'boolean)
27341 (defvar org-latex-and-specials-regexp nil
27342 "Regular expression for highlighting export special stuff.")
27344 (defun org-compute-latex-and-specials-regexp ()
27345 "Compute regular expression for stuff treated specially by exporters."
27346 (if (not org-highlight-latex-fragments-and-specials)
27347 (org-set-local 'org-latex-and-specials-regexp nil)
27348 (let*
27349 ((matchers (plist-get org-format-latex-options :matchers))
27350 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
27351 org-latex-regexps)))
27352 (options (org-combine-plists (org-default-export-plist)
27353 (org-infile-export-plist)))
27354 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
27355 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
27356 (org-export-with-TeX-macros (plist-get options :TeX-macros))
27357 (org-export-html-expand (plist-get options :expand-quoted-html))
27358 (org-export-with-special-strings (plist-get options :special-strings))
27359 (re-sub
27360 (cond
27361 ((equal org-export-with-sub-superscripts '{})
27362 (list org-match-substring-with-braces-regexp))
27363 (org-export-with-sub-superscripts
27364 (list org-match-substring-regexp))
27365 (t nil)))
27366 (re-latex
27367 (if org-export-with-LaTeX-fragments
27368 (mapcar (lambda (x) (nth 1 x)) latexs)))
27369 (re-macros
27370 (if org-export-with-TeX-macros
27371 (list (concat "\\\\"
27372 (regexp-opt
27373 (append (mapcar 'car org-html-entities)
27374 (if (boundp 'org-latex-entities)
27375 org-latex-entities nil))
27376 'words))) ; FIXME
27378 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
27379 (re-special (if org-export-with-special-strings
27380 (mapcar (lambda (x) (car x))
27381 org-export-html-special-string-regexps)))
27382 (re-rest
27383 (delq nil
27384 (list
27385 (if org-export-html-expand "@<[^>\n]+>")
27386 ))))
27387 (org-set-local
27388 'org-latex-and-specials-regexp
27389 (mapconcat 'identity (append re-latex re-sub re-macros re-special re-rest) "\\|")))))
27391 (defface org-latex-and-export-specials
27392 (let ((font (cond ((assq :inherit custom-face-attributes)
27393 '(:inherit underline))
27394 (t '(:underline t)))))
27395 `((((class grayscale) (background light))
27396 (:foreground "DimGray" ,@font))
27397 (((class grayscale) (background dark))
27398 (:foreground "LightGray" ,@font))
27399 (((class color) (background light))
27400 (:foreground "SaddleBrown"))
27401 (((class color) (background dark))
27402 (:foreground "burlywood"))
27403 (t (,@font))))
27404 "Face used to highlight math latex and other special exporter stuff."
27405 :group 'org-faces)
27407 (defun org-do-latex-and-special-faces (limit)
27408 "Run through the buffer and add overlays to links."
27409 (when org-latex-and-specials-regexp
27410 (let (rtn d)
27411 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
27412 limit t))
27413 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0)) 'face))
27414 '(org-code org-verbatim underline)))
27415 (progn
27416 (setq rtn t
27417 d (cond ((member (char-after (1+ (match-beginning 0))) '(?_ ?^)) 1)
27418 (t 0)))
27419 (font-lock-prepend-text-property
27420 (+ d (match-beginning 0)) (match-end 0)
27421 'face 'org-latex-and-export-specials)
27422 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
27423 '(font-lock-multiline t)))))
27424 rtn)))
27427 (defun org-find-first-timestamp (keyword inactive end)
27428 "Return location of first timestamp matching KEYWORD and INACTIVE.
27429 KEYWORD may be any of the timestamp keywords, or nil.
27430 INACTIVE means it should be an inactive timestamp.
27431 If there is no such time stamp, return nil."
27432 (catch 'exit
27433 (let (key ia)
27434 (setq inactive (and inactive t))
27435 (while (re-search-forward org-maybe-keyword-time-regexp end t)
27436 (setq key (and (match-end 1) (substring (match-string 1) 0 -1)
27437 (equal (char-after (match-beginning 3)) ?\[)))
27438 (when (and (equal keyword key)
27439 (equal inactive ia))
27440 (throw 'exit (match-beginning 3)))))))
27443 ;;;; Finish up
27445 (provide 'org)
27447 (run-hooks 'org-load-hook)
27449 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
27450 ;;; org.el ends here