Intermediate state, I am just trying comiting now.
[org-mode.git] / EXPERIMENTAL / interactive-query / org.el
blob0d2f0a5980d1302f7c11571ca36d8d873465a63d
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, 2008 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.18a
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.17a"
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-bound-and-true-p (var)
102 "Return the value of symbol VAR if it is bound, else nil."
103 `(and (boundp (quote ,var)) ,var))
105 (defmacro org-unmodified (&rest body)
106 "Execute body without changing buffer-modified-p."
107 `(set-buffer-modified-p
108 (prog1 (buffer-modified-p) ,@body)))
110 (defmacro org-re (s)
111 "Replace posix classes in regular expression."
112 (if (featurep 'xemacs)
113 (let ((ss s))
114 (save-match-data
115 (while (string-match "\\[:alnum:\\]" ss)
116 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
117 (while (string-match "\\[:alpha:\\]" ss)
118 (setq ss (replace-match "a-zA-Z" t t ss)))
119 ss))
122 (defmacro org-preserve-lc (&rest body)
123 `(let ((_line (org-current-line))
124 (_col (current-column)))
125 (unwind-protect
126 (progn ,@body)
127 (goto-line _line)
128 (move-to-column _col))))
130 (defmacro org-without-partial-completion (&rest body)
131 `(let ((pc-mode (and (boundp 'partial-completion-mode)
132 partial-completion-mode)))
133 (unwind-protect
134 (progn
135 (if pc-mode (partial-completion-mode -1))
136 ,@body)
137 (if pc-mode (partial-completion-mode 1)))))
139 ;;; The custom variables
141 (defgroup org nil
142 "Outline-based notes management and organizer."
143 :tag "Org"
144 :group 'outlines
145 :group 'hypermedia
146 :group 'calendar)
148 ;; FIXME: Needs a separate group...
149 (defcustom org-completion-fallback-command 'hippie-expand
150 "The expansion command called by \\[org-complete] in normal context.
151 Normal means, no org-mode-specific context."
152 :group 'org
153 :type 'function)
155 (defgroup org-startup nil
156 "Options concerning startup of Org-mode."
157 :tag "Org Startup"
158 :group 'org)
160 (defcustom org-startup-folded t
161 "Non-nil means, entering Org-mode will switch to OVERVIEW.
162 This can also be configured on a per-file basis by adding one of
163 the following lines anywhere in the buffer:
165 #+STARTUP: fold
166 #+STARTUP: nofold
167 #+STARTUP: content"
168 :group 'org-startup
169 :type '(choice
170 (const :tag "nofold: show all" nil)
171 (const :tag "fold: overview" t)
172 (const :tag "content: all headlines" content)))
174 (defcustom org-startup-truncated t
175 "Non-nil means, entering Org-mode will set `truncate-lines'.
176 This is useful since some lines containing links can be very long and
177 uninteresting. Also tables look terrible when wrapped."
178 :group 'org-startup
179 :type 'boolean)
181 (defcustom org-startup-align-all-tables nil
182 "Non-nil means, align all tables when visiting a file.
183 This is useful when the column width in tables is forced with <N> cookies
184 in table fields. Such tables will look correct only after the first re-align.
185 This can also be configured on a per-file basis by adding one of
186 the following lines anywhere in the buffer:
187 #+STARTUP: align
188 #+STARTUP: noalign"
189 :group 'org-startup
190 :type 'boolean)
192 (defcustom org-insert-mode-line-in-empty-file nil
193 "Non-nil means insert the first line setting Org-mode in empty files.
194 When the function `org-mode' is called interactively in an empty file, this
195 normally means that the file name does not automatically trigger Org-mode.
196 To ensure that the file will always be in Org-mode in the future, a
197 line enforcing Org-mode will be inserted into the buffer, if this option
198 has been set."
199 :group 'org-startup
200 :type 'boolean)
202 (defcustom org-replace-disputed-keys nil
203 "Non-nil means use alternative key bindings for some keys.
204 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
205 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
206 If you want to use Org-mode together with one of these other modes,
207 or more generally if you would like to move some Org-mode commands to
208 other keys, set this variable and configure the keys with the variable
209 `org-disputed-keys'.
211 This option is only relevant at load-time of Org-mode, and must be set
212 *before* org.el is loaded. Changing it requires a restart of Emacs to
213 become effective."
214 :group 'org-startup
215 :type 'boolean)
217 (if (fboundp 'defvaralias)
218 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
220 (defcustom org-disputed-keys
221 '(([(shift up)] . [(meta p)])
222 ([(shift down)] . [(meta n)])
223 ([(shift left)] . [(meta -)])
224 ([(shift right)] . [(meta +)])
225 ([(control shift right)] . [(meta shift +)])
226 ([(control shift left)] . [(meta shift -)]))
227 "Keys for which Org-mode and other modes compete.
228 This is an alist, cars are the default keys, second element specifies
229 the alternative to use when `org-replace-disputed-keys' is t.
231 Keys can be specified in any syntax supported by `define-key'.
232 The value of this option takes effect only at Org-mode's startup,
233 therefore you'll have to restart Emacs to apply it after changing."
234 :group 'org-startup
235 :type 'alist)
237 (defun org-key (key)
238 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
239 Or return the original if not disputed."
240 (if org-replace-disputed-keys
241 (let* ((nkey (key-description key))
242 (x (org-find-if (lambda (x)
243 (equal (key-description (car x)) nkey))
244 org-disputed-keys)))
245 (if x (cdr x) key))
246 key))
248 (defun org-find-if (predicate seq)
249 (catch 'exit
250 (while seq
251 (if (funcall predicate (car seq))
252 (throw 'exit (car seq))
253 (pop seq)))))
255 (defun org-defkey (keymap key def)
256 "Define a key, possibly translated, as returned by `org-key'."
257 (define-key keymap (org-key key) def))
259 (defcustom org-ellipsis nil
260 "The ellipsis to use in the Org-mode outline.
261 When nil, just use the standard three dots. When a string, use that instead,
262 When a face, use the standart 3 dots, but with the specified face.
263 The change affects only Org-mode (which will then use its own display table).
264 Changing this requires executing `M-x org-mode' in a buffer to become
265 effective."
266 :group 'org-startup
267 :type '(choice (const :tag "Default" nil)
268 (face :tag "Face" :value org-warning)
269 (string :tag "String" :value "...#")))
271 (defvar org-display-table nil
272 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
274 (defgroup org-keywords nil
275 "Keywords in Org-mode."
276 :tag "Org Keywords"
277 :group 'org)
279 (defcustom org-deadline-string "DEADLINE:"
280 "String to mark deadline entries.
281 A deadline is this string, followed by a time stamp. Should be a word,
282 terminated by a colon. You can insert a schedule keyword and
283 a timestamp with \\[org-deadline].
284 Changes become only effective after restarting Emacs."
285 :group 'org-keywords
286 :type 'string)
288 (defcustom org-scheduled-string "SCHEDULED:"
289 "String to mark scheduled TODO entries.
290 A schedule is this string, followed by a time stamp. Should be a word,
291 terminated by a colon. You can insert a schedule keyword and
292 a timestamp with \\[org-schedule].
293 Changes become only effective after restarting Emacs."
294 :group 'org-keywords
295 :type 'string)
297 (defcustom org-closed-string "CLOSED:"
298 "String used as the prefix for timestamps logging closing a TODO entry."
299 :group 'org-keywords
300 :type 'string)
302 (defcustom org-clock-string "CLOCK:"
303 "String used as prefix for timestamps clocking work hours on an item."
304 :group 'org-keywords
305 :type 'string)
307 (defcustom org-comment-string "COMMENT"
308 "Entries starting with this keyword will never be exported.
309 An entry can be toggled between COMMENT and normal with
310 \\[org-toggle-comment].
311 Changes become only effective after restarting Emacs."
312 :group 'org-keywords
313 :type 'string)
315 (defcustom org-quote-string "QUOTE"
316 "Entries starting with this keyword will be exported in fixed-width font.
317 Quoting applies only to the text in the entry following the headline, and does
318 not extend beyond the next headline, even if that is lower level.
319 An entry can be toggled between QUOTE and normal with
320 \\[org-toggle-fixed-width-section]."
321 :group 'org-keywords
322 :type 'string)
324 (defconst org-repeat-re
325 (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
326 " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
327 "Regular expression for specifying repeated events.
328 After a match, group 1 contains the repeat expression.")
330 (defgroup org-structure nil
331 "Options concerning the general structure of Org-mode files."
332 :tag "Org Structure"
333 :group 'org)
335 (defgroup org-reveal-location nil
336 "Options about how to make context of a location visible."
337 :tag "Org Reveal Location"
338 :group 'org-structure)
340 (defconst org-context-choice
341 '(choice
342 (const :tag "Always" t)
343 (const :tag "Never" nil)
344 (repeat :greedy t :tag "Individual contexts"
345 (cons
346 (choice :tag "Context"
347 (const agenda)
348 (const org-goto)
349 (const occur-tree)
350 (const tags-tree)
351 (const link-search)
352 (const mark-goto)
353 (const bookmark-jump)
354 (const isearch)
355 (const default))
356 (boolean))))
357 "Contexts for the reveal options.")
359 (defcustom org-show-hierarchy-above '((default . t))
360 "Non-nil means, show full hierarchy when revealing a location.
361 Org-mode often shows locations in an org-mode file which might have
362 been invisible before. When this is set, the hierarchy of headings
363 above the exposed location is shown.
364 Turning this off for example for sparse trees makes them very compact.
365 Instead of t, this can also be an alist specifying this option for different
366 contexts. Valid contexts are
367 agenda when exposing an entry from the agenda
368 org-goto when using the command `org-goto' on key C-c C-j
369 occur-tree when using the command `org-occur' on key C-c /
370 tags-tree when constructing a sparse tree based on tags matches
371 link-search when exposing search matches associated with a link
372 mark-goto when exposing the jump goal of a mark
373 bookmark-jump when exposing a bookmark location
374 isearch when exiting from an incremental search
375 default default for all contexts not set explicitly"
376 :group 'org-reveal-location
377 :type org-context-choice)
379 (defcustom org-show-following-heading '((default . nil))
380 "Non-nil means, show following heading when revealing a location.
381 Org-mode often shows locations in an org-mode file which might have
382 been invisible before. When this is set, the heading following the
383 match is shown.
384 Turning this off for example for sparse trees makes them very compact,
385 but makes it harder to edit the location of the match. In such a case,
386 use the command \\[org-reveal] to show more context.
387 Instead of t, this can also be an alist specifying this option for different
388 contexts. See `org-show-hierarchy-above' for valid contexts."
389 :group 'org-reveal-location
390 :type org-context-choice)
392 (defcustom org-show-siblings '((default . nil) (isearch t))
393 "Non-nil means, show all sibling heading when revealing a location.
394 Org-mode often shows locations in an org-mode file which might have
395 been invisible before. When this is set, the sibling of the current entry
396 heading are all made visible. If `org-show-hierarchy-above' is t,
397 the same happens on each level of the hierarchy above the current entry.
399 By default this is on for the isearch context, off for all other contexts.
400 Turning this off for example for sparse trees makes them very compact,
401 but makes it harder to edit the location of the match. In such a case,
402 use the command \\[org-reveal] to show more context.
403 Instead of t, this can also be an alist specifying this option for different
404 contexts. See `org-show-hierarchy-above' for valid contexts."
405 :group 'org-reveal-location
406 :type org-context-choice)
408 (defcustom org-show-entry-below '((default . nil))
409 "Non-nil means, show the entry below a headline when revealing a location.
410 Org-mode often shows locations in an org-mode file which might have
411 been invisible before. When this is set, the text below the headline that is
412 exposed is also shown.
414 By default this is off for all contexts.
415 Instead of t, this can also be an alist specifying this option for different
416 contexts. See `org-show-hierarchy-above' for valid contexts."
417 :group 'org-reveal-location
418 :type org-context-choice)
420 (defgroup org-cycle nil
421 "Options concerning visibility cycling in Org-mode."
422 :tag "Org Cycle"
423 :group 'org-structure)
425 (defcustom org-drawers '("PROPERTIES" "CLOCK")
426 "Names of drawers. Drawers are not opened by cycling on the headline above.
427 Drawers only open with a TAB on the drawer line itself. A drawer looks like
428 this:
429 :DRAWERNAME:
430 .....
431 :END:
432 The drawer \"PROPERTIES\" is special for capturing properties through
433 the property API.
435 Drawers can be defined on the per-file basis with a line like:
437 #+DRAWERS: HIDDEN STATE PROPERTIES"
438 :group 'org-structure
439 :type '(repeat (string :tag "Drawer Name")))
441 (defcustom org-cycle-global-at-bob nil
442 "Cycle globally if cursor is at beginning of buffer and not at a headline.
443 This makes it possible to do global cycling without having to use S-TAB or
444 C-u TAB. For this special case to work, the first line of the buffer
445 must not be a headline - it may be empty ot some other text. When used in
446 this way, `org-cycle-hook' is disables temporarily, to make sure the
447 cursor stays at the beginning of the buffer.
448 When this option is nil, don't do anything special at the beginning
449 of the buffer."
450 :group 'org-cycle
451 :type 'boolean)
453 (defcustom org-cycle-emulate-tab t
454 "Where should `org-cycle' emulate TAB.
455 nil Never
456 white Only in completely white lines
457 whitestart Only at the beginning of lines, before the first non-white char.
458 t Everywhere except in headlines
459 exc-hl-bol Everywhere except at the start of a headline
460 If TAB is used in a place where it does not emulate TAB, the current subtree
461 visibility is cycled."
462 :group 'org-cycle
463 :type '(choice (const :tag "Never" nil)
464 (const :tag "Only in completely white lines" white)
465 (const :tag "Before first char in a line" whitestart)
466 (const :tag "Everywhere except in headlines" t)
467 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
470 (defcustom org-cycle-separator-lines 2
471 "Number of empty lines needed to keep an empty line between collapsed trees.
472 If you leave an empty line between the end of a subtree and the following
473 headline, this empty line is hidden when the subtree is folded.
474 Org-mode will leave (exactly) one empty line visible if the number of
475 empty lines is equal or larger to the number given in this variable.
476 So the default 2 means, at least 2 empty lines after the end of a subtree
477 are needed to produce free space between a collapsed subtree and the
478 following headline.
480 Special case: when 0, never leave empty lines in collapsed view."
481 :group 'org-cycle
482 :type 'integer)
484 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
485 org-cycle-hide-drawers
486 org-cycle-show-empty-lines
487 org-optimize-window-after-visibility-change)
488 "Hook that is run after `org-cycle' has changed the buffer visibility.
489 The function(s) in this hook must accept a single argument which indicates
490 the new state that was set by the most recent `org-cycle' command. The
491 argument is a symbol. After a global state change, it can have the values
492 `overview', `content', or `all'. After a local state change, it can have
493 the values `folded', `children', or `subtree'."
494 :group 'org-cycle
495 :type 'hook)
497 (defgroup org-edit-structure nil
498 "Options concerning structure editing in Org-mode."
499 :tag "Org Edit Structure"
500 :group 'org-structure)
502 (defcustom org-special-ctrl-a/e nil
503 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
504 When t, `C-a' will bring back the cursor to the beginning of the
505 headline text, i.e. after the stars and after a possible TODO keyword.
506 In an item, this will be the position after the bullet.
507 When the cursor is already at that position, another `C-a' will bring
508 it to the beginning of the line.
509 `C-e' will jump to the end of the headline, ignoring the presence of tags
510 in the headline. A second `C-e' will then jump to the true end of the
511 line, after any tags.
512 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
513 and only a directly following, identical keypress will bring the cursor
514 to the special positions."
515 :group 'org-edit-structure
516 :type '(choice
517 (const :tag "off" nil)
518 (const :tag "after bullet first" t)
519 (const :tag "border first" reversed)))
521 (if (fboundp 'defvaralias)
522 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
524 (defcustom org-odd-levels-only nil
525 "Non-nil means, skip even levels and only use odd levels for the outline.
526 This has the effect that two stars are being added/taken away in
527 promotion/demotion commands. It also influences how levels are
528 handled by the exporters.
529 Changing it requires restart of `font-lock-mode' to become effective
530 for fontification also in regions already fontified.
531 You may also set this on a per-file basis by adding one of the following
532 lines to the buffer:
534 #+STARTUP: odd
535 #+STARTUP: oddeven"
536 :group 'org-edit-structure
537 :group 'org-font-lock
538 :type 'boolean)
540 (defcustom org-adapt-indentation t
541 "Non-nil means, adapt indentation when promoting and demoting.
542 When this is set and the *entire* text in an entry is indented, the
543 indentation is increased by one space in a demotion command, and
544 decreased by one in a promotion command. If any line in the entry
545 body starts at column 0, indentation is not changed at all."
546 :group 'org-edit-structure
547 :type 'boolean)
549 (defcustom org-blank-before-new-entry '((heading . nil)
550 (plain-list-item . nil))
551 "Should `org-insert-heading' leave a blank line before new heading/item?
552 The value is an alist, with `heading' and `plain-list-item' as car,
553 and a boolean flag as cdr."
554 :group 'org-edit-structure
555 :type '(list
556 (cons (const heading) (boolean))
557 (cons (const plain-list-item) (boolean))))
559 (defcustom org-insert-heading-hook nil
560 "Hook being run after inserting a new heading."
561 :group 'org-edit-structure
562 :type 'hook)
564 (defcustom org-enable-fixed-width-editor t
565 "Non-nil means, lines starting with \":\" are treated as fixed-width.
566 This currently only means, they are never auto-wrapped.
567 When nil, such lines will be treated like ordinary lines.
568 See also the QUOTE keyword."
569 :group 'org-edit-structure
570 :type 'boolean)
572 (defgroup org-sparse-trees nil
573 "Options concerning sparse trees in Org-mode."
574 :tag "Org Sparse Trees"
575 :group 'org-structure)
577 (defcustom org-highlight-sparse-tree-matches t
578 "Non-nil means, highlight all matches that define a sparse tree.
579 The highlights will automatically disappear the next time the buffer is
580 changed by an edit command."
581 :group 'org-sparse-trees
582 :type 'boolean)
584 (defcustom org-remove-highlights-with-change t
585 "Non-nil means, any change to the buffer will remove temporary highlights.
586 Such highlights are created by `org-occur' and `org-clock-display'.
587 When nil, `C-c C-c needs to be used to get rid of the highlights.
588 The highlights created by `org-preview-latex-fragment' always need
589 `C-c C-c' to be removed."
590 :group 'org-sparse-trees
591 :group 'org-time
592 :type 'boolean)
595 (defcustom org-occur-hook '(org-first-headline-recenter)
596 "Hook that is run after `org-occur' has constructed a sparse tree.
597 This can be used to recenter the window to show as much of the structure
598 as possible."
599 :group 'org-sparse-trees
600 :type 'hook)
602 (defgroup org-plain-lists nil
603 "Options concerning plain lists in Org-mode."
604 :tag "Org Plain lists"
605 :group 'org-structure)
607 (defcustom org-cycle-include-plain-lists nil
608 "Non-nil means, include plain lists into visibility cycling.
609 This means that during cycling, plain list items will *temporarily* be
610 interpreted as outline headlines with a level given by 1000+i where i is the
611 indentation of the bullet. In all other operations, plain list items are
612 not seen as headlines. For example, you cannot assign a TODO keyword to
613 such an item."
614 :group 'org-plain-lists
615 :type 'boolean)
617 (defcustom org-plain-list-ordered-item-terminator t
618 "The character that makes a line with leading number an ordered list item.
619 Valid values are ?. and ?\). To get both terminators, use t. While
620 ?. may look nicer, it creates the danger that a line with leading
621 number may be incorrectly interpreted as an item. ?\) therefore is
622 the safe choice."
623 :group 'org-plain-lists
624 :type '(choice (const :tag "dot like in \"2.\"" ?.)
625 (const :tag "paren like in \"2)\"" ?\))
626 (const :tab "both" t)))
628 (defcustom org-auto-renumber-ordered-lists t
629 "Non-nil means, automatically renumber ordered plain lists.
630 Renumbering happens when the sequence have been changed with
631 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
632 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
633 :group 'org-plain-lists
634 :type 'boolean)
636 (defcustom org-provide-checkbox-statistics t
637 "Non-nil means, update checkbox statistics after insert and toggle.
638 When this is set, checkbox statistics is updated each time you either insert
639 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
640 with \\[org-ctrl-c-ctrl-c\\]."
641 :group 'org-plain-lists
642 :type 'boolean)
644 (defgroup org-archive nil
645 "Options concerning archiving in Org-mode."
646 :tag "Org Archive"
647 :group 'org-structure)
649 (defcustom org-archive-tag "ARCHIVE"
650 "The tag that marks a subtree as archived.
651 An archived subtree does not open during visibility cycling, and does
652 not contribute to the agenda listings.
653 After changing this, font-lock must be restarted in the relevant buffers to
654 get the proper fontification."
655 :group 'org-archive
656 :group 'org-keywords
657 :type 'string)
659 (defcustom org-agenda-skip-archived-trees t
660 "Non-nil means, the agenda will skip any items located in archived trees.
661 An archived tree is a tree marked with the tag ARCHIVE."
662 :group 'org-archive
663 :group 'org-agenda-skip
664 :type 'boolean)
666 (defcustom org-cycle-open-archived-trees nil
667 "Non-nil means, `org-cycle' will open archived trees.
668 An archived tree is a tree marked with the tag ARCHIVE.
669 When nil, archived trees will stay folded. You can still open them with
670 normal outline commands like `show-all', but not with the cycling commands."
671 :group 'org-archive
672 :group 'org-cycle
673 :type 'boolean)
675 (defcustom org-sparse-tree-open-archived-trees nil
676 "Non-nil means sparse tree construction shows matches in archived trees.
677 When nil, matches in these trees are highlighted, but the trees are kept in
678 collapsed state."
679 :group 'org-archive
680 :group 'org-sparse-trees
681 :type 'boolean)
683 (defcustom org-archive-location "%s_archive::"
684 "The location where subtrees should be archived.
685 This string consists of two parts, separated by a double-colon.
687 The first part is a file name - when omitted, archiving happens in the same
688 file. %s will be replaced by the current file name (without directory part).
689 Archiving to a different file is useful to keep archived entries from
690 contributing to the Org-mode Agenda.
692 The part after the double colon is a headline. The archived entries will be
693 filed under that headline. When omitted, the subtrees are simply filed away
694 at the end of the file, as top-level entries.
696 Here are a few examples:
697 \"%s_archive::\"
698 If the current file is Projects.org, archive in file
699 Projects.org_archive, as top-level trees. This is the default.
701 \"::* Archived Tasks\"
702 Archive in the current file, under the top-level headline
703 \"* Archived Tasks\".
705 \"~/org/archive.org::\"
706 Archive in file ~/org/archive.org (absolute path), as top-level trees.
708 \"basement::** Finished Tasks\"
709 Archive in file ./basement (relative path), as level 3 trees
710 below the level 2 heading \"** Finished Tasks\".
712 You may set this option on a per-file basis by adding to the buffer a
713 line like
715 #+ARCHIVE: basement::** Finished Tasks"
716 :group 'org-archive
717 :type 'string)
719 (defcustom org-archive-mark-done t
720 "Non-nil means, mark entries as DONE when they are moved to the archive file.
721 This can be a string to set the keyword to use. When t, Org-mode will
722 use the first keyword in its list that means done."
723 :group 'org-archive
724 :type '(choice
725 (const :tag "No" nil)
726 (const :tag "Yes" t)
727 (string :tag "Use this keyword")))
729 (defcustom org-archive-stamp-time t
730 "Non-nil means, add a time stamp to entries moved to an archive file.
731 This variable is obsolete and has no effect anymore, instead add ot remove
732 `time' from the variablle `org-archive-save-context-info'."
733 :group 'org-archive
734 :type 'boolean)
736 (defcustom org-archive-save-context-info '(time file category todo itags)
737 "Parts of context info that should be stored as properties when archiving.
738 When a subtree is moved to an archive file, it looses information given by
739 context, like inherited tags, the category, and possibly also the TODO
740 state (depending on the variable `org-archive-mark-done').
741 This variable can be a list of any of the following symbols:
743 time The time of archiving.
744 file The file where the entry originates.
745 itags The local tags, in the headline of the subtree.
746 ltags The tags the subtree inherits from further up the hierarchy.
747 todo The pre-archive TODO state.
748 category The category, taken from file name or #+CATEGORY lines.
750 For each symbol present in the list, a property will be created in
751 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
752 information."
753 :group 'org-archive
754 :type '(set :greedy t
755 (const :tag "Time" time)
756 (const :tag "File" file)
757 (const :tag "Category" category)
758 (const :tag "TODO state" todo)
759 (const :tag "TODO state" priority)
760 (const :tag "Inherited tags" itags)
761 (const :tag "Local tags" ltags)))
763 (defgroup org-imenu-and-speedbar nil
764 "Options concerning imenu and speedbar in Org-mode."
765 :tag "Org Imenu and Speedbar"
766 :group 'org-structure)
768 (defcustom org-imenu-depth 2
769 "The maximum level for Imenu access to Org-mode headlines.
770 This also applied for speedbar access."
771 :group 'org-imenu-and-speedbar
772 :type 'number)
774 (defgroup org-table nil
775 "Options concerning tables in Org-mode."
776 :tag "Org Table"
777 :group 'org)
779 (defcustom org-enable-table-editor 'optimized
780 "Non-nil means, lines starting with \"|\" are handled by the table editor.
781 When nil, such lines will be treated like ordinary lines.
783 When equal to the symbol `optimized', the table editor will be optimized to
784 do the following:
785 - Automatic overwrite mode in front of whitespace in table fields.
786 This makes the structure of the table stay in tact as long as the edited
787 field does not exceed the column width.
788 - Minimize the number of realigns. Normally, the table is aligned each time
789 TAB or RET are pressed to move to another field. With optimization this
790 happens only if changes to a field might have changed the column width.
791 Optimization requires replacing the functions `self-insert-command',
792 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
793 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
794 very good at guessing when a re-align will be necessary, but you can always
795 force one with \\[org-ctrl-c-ctrl-c].
797 If you would like to use the optimized version in Org-mode, but the
798 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
800 This variable can be used to turn on and off the table editor during a session,
801 but in order to toggle optimization, a restart is required.
803 See also the variable `org-table-auto-blank-field'."
804 :group 'org-table
805 :type '(choice
806 (const :tag "off" nil)
807 (const :tag "on" t)
808 (const :tag "on, optimized" optimized)))
810 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
811 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
812 In the optimized version, the table editor takes over all simple keys that
813 normally just insert a character. In tables, the characters are inserted
814 in a way to minimize disturbing the table structure (i.e. in overwrite mode
815 for empty fields). Outside tables, the correct binding of the keys is
816 restored.
818 The default for this option is t if the optimized version is also used in
819 Org-mode. See the variable `org-enable-table-editor' for details. Changing
820 this variable requires a restart of Emacs to become effective."
821 :group 'org-table
822 :type 'boolean)
824 (defcustom orgtbl-radio-table-templates
825 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
826 % END RECEIVE ORGTBL %n
827 \\begin{comment}
828 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
829 | | |
830 \\end{comment}\n")
831 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
832 @c END RECEIVE ORGTBL %n
833 @ignore
834 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
835 | | |
836 @end ignore\n")
837 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
838 <!-- END RECEIVE ORGTBL %n -->
839 <!--
840 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
841 | | |
842 -->\n"))
843 "Templates for radio tables in different major modes.
844 All occurrences of %n in a template will be replaced with the name of the
845 table, obtained by prompting the user."
846 :group 'org-table
847 :type '(repeat
848 (list (symbol :tag "Major mode")
849 (string :tag "Format"))))
851 (defgroup org-table-settings nil
852 "Settings for tables in Org-mode."
853 :tag "Org Table Settings"
854 :group 'org-table)
856 (defcustom org-table-default-size "5x2"
857 "The default size for newly created tables, Columns x Rows."
858 :group 'org-table-settings
859 :type 'string)
861 (defcustom org-table-number-regexp
862 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
863 "Regular expression for recognizing numbers in table columns.
864 If a table column contains mostly numbers, it will be aligned to the
865 right. If not, it will be aligned to the left.
867 The default value of this option is a regular expression which allows
868 anything which looks remotely like a number as used in scientific
869 context. For example, all of the following will be considered a
870 number:
871 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
873 Other options offered by the customize interface are more restrictive."
874 :group 'org-table-settings
875 :type '(choice
876 (const :tag "Positive Integers"
877 "^[0-9]+$")
878 (const :tag "Integers"
879 "^[-+]?[0-9]+$")
880 (const :tag "Floating Point Numbers"
881 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
882 (const :tag "Floating Point Number or Integer"
883 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
884 (const :tag "Exponential, Floating point, Integer"
885 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
886 (const :tag "Very General Number-Like, including hex"
887 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
888 (string :tag "Regexp:")))
890 (defcustom org-table-number-fraction 0.5
891 "Fraction of numbers in a column required to make the column align right.
892 In a column all non-white fields are considered. If at least this
893 fraction of fields is matched by `org-table-number-fraction',
894 alignment to the right border applies."
895 :group 'org-table-settings
896 :type 'number)
898 (defgroup org-table-editing nil
899 "Behavior of tables during editing in Org-mode."
900 :tag "Org Table Editing"
901 :group 'org-table)
903 (defcustom org-table-automatic-realign t
904 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
905 When nil, aligning is only done with \\[org-table-align], or after column
906 removal/insertion."
907 :group 'org-table-editing
908 :type 'boolean)
910 (defcustom org-table-auto-blank-field t
911 "Non-nil means, automatically blank table field when starting to type into it.
912 This only happens when typing immediately after a field motion
913 command (TAB, S-TAB or RET).
914 Only relevant when `org-enable-table-editor' is equal to `optimized'."
915 :group 'org-table-editing
916 :type 'boolean)
918 (defcustom org-table-tab-jumps-over-hlines t
919 "Non-nil means, tab in the last column of a table with jump over a hline.
920 If a horizontal separator line is following the current line,
921 `org-table-next-field' can either create a new row before that line, or jump
922 over the line. When this option is nil, a new line will be created before
923 this line."
924 :group 'org-table-editing
925 :type 'boolean)
927 (defcustom org-table-tab-recognizes-table.el t
928 "Non-nil means, TAB will automatically notice a table.el table.
929 When it sees such a table, it moves point into it and - if necessary -
930 calls `table-recognize-table'."
931 :group 'org-table-editing
932 :type 'boolean)
934 (defgroup org-table-calculation nil
935 "Options concerning tables in Org-mode."
936 :tag "Org Table Calculation"
937 :group 'org-table)
939 (defcustom org-table-use-standard-references t
940 "Should org-mode work with table refrences like B3 instead of @3$2?
941 Possible values are:
942 nil never use them
943 from accept as input, do not present for editing
944 t: accept as input and present for editing"
945 :group 'org-table-calculation
946 :type '(choice
947 (const :tag "Never, don't even check unser input for them" nil)
948 (const :tag "Always, both as user input, and when editing" t)
949 (const :tag "Convert user input, don't offer during editing" 'from)))
951 (defcustom org-table-copy-increment t
952 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
953 :group 'org-table-calculation
954 :type 'boolean)
956 (defcustom org-calc-default-modes
957 '(calc-internal-prec 12
958 calc-float-format (float 5)
959 calc-angle-mode deg
960 calc-prefer-frac nil
961 calc-symbolic-mode nil
962 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
963 calc-display-working-message t
965 "List with Calc mode settings for use in calc-eval for table formulas.
966 The list must contain alternating symbols (Calc modes variables and values).
967 Don't remove any of the default settings, just change the values. Org-mode
968 relies on the variables to be present in the list."
969 :group 'org-table-calculation
970 :type 'plist)
972 (defcustom org-table-formula-evaluate-inline t
973 "Non-nil means, TAB and RET evaluate a formula in current table field.
974 If the current field starts with an equal sign, it is assumed to be a formula
975 which should be evaluated as described in the manual and in the documentation
976 string of the command `org-table-eval-formula'. This feature requires the
977 Emacs calc package.
978 When this variable is nil, formula calculation is only available through
979 the command \\[org-table-eval-formula]."
980 :group 'org-table-calculation
981 :type 'boolean)
983 (defcustom org-table-formula-use-constants t
984 "Non-nil means, interpret constants in formulas in tables.
985 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
986 by the value given in `org-table-formula-constants', or by a value obtained
987 from the `constants.el' package."
988 :group 'org-table-calculation
989 :type 'boolean)
991 (defcustom org-table-formula-constants nil
992 "Alist with constant names and values, for use in table formulas.
993 The car of each element is a name of a constant, without the `$' before it.
994 The cdr is the value as a string. For example, if you'd like to use the
995 speed of light in a formula, you would configure
997 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
999 and then use it in an equation like `$1*$c'.
1001 Constants can also be defined on a per-file basis using a line like
1003 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1004 :group 'org-table-calculation
1005 :type '(repeat
1006 (cons (string :tag "name")
1007 (string :tag "value"))))
1009 (defvar org-table-formula-constants-local nil
1010 "Local version of `org-table-formula-constants'.")
1011 (make-variable-buffer-local 'org-table-formula-constants-local)
1013 (defcustom org-table-allow-automatic-line-recalculation t
1014 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1015 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1016 :group 'org-table-calculation
1017 :type 'boolean)
1019 (defgroup org-link nil
1020 "Options concerning links in Org-mode."
1021 :tag "Org Link"
1022 :group 'org)
1024 (defvar org-link-abbrev-alist-local nil
1025 "Buffer-local version of `org-link-abbrev-alist', which see.
1026 The value of this is taken from the #+LINK lines.")
1027 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1029 (defcustom org-link-abbrev-alist nil
1030 "Alist of link abbreviations.
1031 The car of each element is a string, to be replaced at the start of a link.
1032 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1033 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1035 [[linkkey:tag][description]]
1037 If REPLACE is a string, the tag will simply be appended to create the link.
1038 If the string contains \"%s\", the tag will be inserted there.
1040 REPLACE may also be a function that will be called with the tag as the
1041 only argument to create the link, which should be returned as a string.
1043 See the manual for examples."
1044 :group 'org-link
1045 :type 'alist)
1047 (defcustom org-descriptive-links t
1048 "Non-nil means, hide link part and only show description of bracket links.
1049 Bracket links are like [[link][descritpion]]. This variable sets the initial
1050 state in new org-mode buffers. The setting can then be toggled on a
1051 per-buffer basis from the Org->Hyperlinks menu."
1052 :group 'org-link
1053 :type 'boolean)
1055 (defcustom org-link-file-path-type 'adaptive
1056 "How the path name in file links should be stored.
1057 Valid values are:
1059 relative relative to the current directory, i.e. the directory of the file
1060 into which the link is being inserted.
1061 absolute absolute path, if possible with ~ for home directory.
1062 noabbrev absolute path, no abbreviation of home directory.
1063 adaptive Use relative path for files in the current directory and sub-
1064 directories of it. For other files, use an absolute path."
1065 :group 'org-link
1066 :type '(choice
1067 (const relative)
1068 (const absolute)
1069 (const noabbrev)
1070 (const adaptive)))
1072 (defcustom org-activate-links '(bracket angle plain radio tag date)
1073 "Types of links that should be activated in Org-mode files.
1074 This is a list of symbols, each leading to the activation of a certain link
1075 type. In principle, it does not hurt to turn on most link types - there may
1076 be a small gain when turning off unused link types. The types are:
1078 bracket The recommended [[link][description]] or [[link]] links with hiding.
1079 angular Links in angular brackes that may contain whitespace like
1080 <bbdb:Carsten Dominik>.
1081 plain Plain links in normal text, no whitespace, like http://google.com.
1082 radio Text that is matched by a radio target, see manual for details.
1083 tag Tag settings in a headline (link to tag search).
1084 date Time stamps (link to calendar).
1086 Changing this variable requires a restart of Emacs to become effective."
1087 :group 'org-link
1088 :type '(set (const :tag "Double bracket links (new style)" bracket)
1089 (const :tag "Angular bracket links (old style)" angular)
1090 (const :tag "plain text links" plain)
1091 (const :tag "Radio target matches" radio)
1092 (const :tag "Tags" tag)
1093 (const :tag "Tags" target)
1094 (const :tag "Timestamps" date)))
1096 (defgroup org-link-store nil
1097 "Options concerning storing links in Org-mode"
1098 :tag "Org Store Link"
1099 :group 'org-link)
1101 (defcustom org-email-link-description-format "Email %c: %.30s"
1102 "Format of the description part of a link to an email or usenet message.
1103 The following %-excapes will be replaced by corresponding information:
1105 %F full \"From\" field
1106 %f name, taken from \"From\" field, address if no name
1107 %T full \"To\" field
1108 %t first name in \"To\" field, address if no name
1109 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1110 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1111 %s subject
1112 %m message-id.
1114 You may use normal field width specification between the % and the letter.
1115 This is for example useful to limit the length of the subject.
1117 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1118 :group 'org-link-store
1119 :type 'string)
1121 (defcustom org-from-is-user-regexp
1122 (let (r1 r2)
1123 (when (and user-mail-address (not (string= user-mail-address "")))
1124 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1125 (when (and user-full-name (not (string= user-full-name "")))
1126 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1127 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1128 "Regexp mached against the \"From:\" header of an email or usenet message.
1129 It should match if the message is from the user him/herself."
1130 :group 'org-link-store
1131 :type 'regexp)
1133 (defcustom org-context-in-file-links t
1134 "Non-nil means, file links from `org-store-link' contain context.
1135 A search string will be added to the file name with :: as separator and
1136 used to find the context when the link is activated by the command
1137 `org-open-at-point'.
1138 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1139 negates this setting for the duration of the command."
1140 :group 'org-link-store
1141 :type 'boolean)
1143 (defcustom org-keep-stored-link-after-insertion nil
1144 "Non-nil means, keep link in list for entire session.
1146 The command `org-store-link' adds a link pointing to the current
1147 location to an internal list. These links accumulate during a session.
1148 The command `org-insert-link' can be used to insert links into any
1149 Org-mode file (offering completion for all stored links). When this
1150 option is nil, every link which has been inserted once using \\[org-insert-link]
1151 will be removed from the list, to make completing the unused links
1152 more efficient."
1153 :group 'org-link-store
1154 :type 'boolean)
1156 (defcustom org-usenet-links-prefer-google nil
1157 "Non-nil means, `org-store-link' will create web links to Google groups.
1158 When nil, Gnus will be used for such links.
1159 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1160 negates this setting for the duration of the command."
1161 :group 'org-link-store
1162 :type 'boolean)
1164 (defgroup org-link-follow nil
1165 "Options concerning following links in Org-mode"
1166 :tag "Org Follow Link"
1167 :group 'org-link)
1169 (defcustom org-tab-follows-link nil
1170 "Non-nil means, on links TAB will follow the link.
1171 Needs to be set before org.el is loaded."
1172 :group 'org-link-follow
1173 :type 'boolean)
1175 (defcustom org-return-follows-link nil
1176 "Non-nil means, on links RET will follow the link.
1177 Needs to be set before org.el is loaded."
1178 :group 'org-link-follow
1179 :type 'boolean)
1181 (defcustom org-mouse-1-follows-link t
1182 "Non-nil means, mouse-1 on a link will follow the link.
1183 A longer mouse click will still set point. Does not wortk on XEmacs.
1184 Needs to be set before org.el is loaded."
1185 :group 'org-link-follow
1186 :type 'boolean)
1188 (defcustom org-mark-ring-length 4
1189 "Number of different positions to be recorded in the ring
1190 Changing this requires a restart of Emacs to work correctly."
1191 :group 'org-link-follow
1192 :type 'interger)
1194 (defcustom org-link-frame-setup
1195 '((vm . vm-visit-folder-other-frame)
1196 (gnus . gnus-other-frame)
1197 (file . find-file-other-window))
1198 "Setup the frame configuration for following links.
1199 When following a link with Emacs, it may often be useful to display
1200 this link in another window or frame. This variable can be used to
1201 set this up for the different types of links.
1202 For VM, use any of
1203 `vm-visit-folder'
1204 `vm-visit-folder-other-frame'
1205 For Gnus, use any of
1206 `gnus'
1207 `gnus-other-frame'
1208 For FILE, use any of
1209 `find-file'
1210 `find-file-other-window'
1211 `find-file-other-frame'
1212 For the calendar, use the variable `calendar-setup'.
1213 For BBDB, it is currently only possible to display the matches in
1214 another window."
1215 :group 'org-link-follow
1216 :type '(list
1217 (cons (const vm)
1218 (choice
1219 (const vm-visit-folder)
1220 (const vm-visit-folder-other-window)
1221 (const vm-visit-folder-other-frame)))
1222 (cons (const gnus)
1223 (choice
1224 (const gnus)
1225 (const gnus-other-frame)))
1226 (cons (const file)
1227 (choice
1228 (const find-file)
1229 (const find-file-other-window)
1230 (const find-file-other-frame)))))
1232 (defcustom org-display-internal-link-with-indirect-buffer nil
1233 "Non-nil means, use indirect buffer to display infile links.
1234 Activating internal links (from one location in a file to another location
1235 in the same file) normally just jumps to the location. When the link is
1236 activated with a C-u prefix (or with mouse-3), the link is displayed in
1237 another window. When this option is set, the other window actually displays
1238 an indirect buffer clone of the current buffer, to avoid any visibility
1239 changes to the current buffer."
1240 :group 'org-link-follow
1241 :type 'boolean)
1243 (defcustom org-open-non-existing-files nil
1244 "Non-nil means, `org-open-file' will open non-existing files.
1245 When nil, an error will be generated."
1246 :group 'org-link-follow
1247 :type 'boolean)
1249 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1250 "Function and arguments to call for following mailto links.
1251 This is a list with the first element being a lisp function, and the
1252 remaining elements being arguments to the function. In string arguments,
1253 %a will be replaced by the address, and %s will be replaced by the subject
1254 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1255 :group 'org-link-follow
1256 :type '(choice
1257 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1258 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1259 (const :tag "message-mail" (message-mail "%a" "%s"))
1260 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1262 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1263 "Non-nil means, ask for confirmation before executing shell links.
1264 Shell links can be dangerous: just think about a link
1266 [[shell:rm -rf ~/*][Google Search]]
1268 This link would show up in your Org-mode document as \"Google Search\",
1269 but really it would remove your entire home directory.
1270 Therefore we advise against setting this variable to nil.
1271 Just change it to `y-or-n-p' of you want to confirm with a
1272 single keystroke rather than having to type \"yes\"."
1273 :group 'org-link-follow
1274 :type '(choice
1275 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1276 (const :tag "with y-or-n (faster)" y-or-n-p)
1277 (const :tag "no confirmation (dangerous)" nil)))
1279 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1280 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1281 Elisp links can be dangerous: just think about a link
1283 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1285 This link would show up in your Org-mode document as \"Google Search\",
1286 but really it would remove your entire home directory.
1287 Therefore we advise against setting this variable to nil.
1288 Just change it to `y-or-n-p' of you want to confirm with a
1289 single keystroke rather than having to type \"yes\"."
1290 :group 'org-link-follow
1291 :type '(choice
1292 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1293 (const :tag "with y-or-n (faster)" y-or-n-p)
1294 (const :tag "no confirmation (dangerous)" nil)))
1296 (defconst org-file-apps-defaults-gnu
1297 '((remote . emacs)
1298 (t . mailcap))
1299 "Default file applications on a UNIX or GNU/Linux system.
1300 See `org-file-apps'.")
1302 (defconst org-file-apps-defaults-macosx
1303 '((remote . emacs)
1304 (t . "open %s")
1305 ("ps" . "gv %s")
1306 ("ps.gz" . "gv %s")
1307 ("eps" . "gv %s")
1308 ("eps.gz" . "gv %s")
1309 ("dvi" . "xdvi %s")
1310 ("fig" . "xfig %s"))
1311 "Default file applications on a MacOS X system.
1312 The system \"open\" is known as a default, but we use X11 applications
1313 for some files for which the OS does not have a good default.
1314 See `org-file-apps'.")
1316 (defconst org-file-apps-defaults-windowsnt
1317 (list
1318 '(remote . emacs)
1319 (cons t
1320 (list (if (featurep 'xemacs)
1321 'mswindows-shell-execute
1322 'w32-shell-execute)
1323 "open" 'file)))
1324 "Default file applications on a Windows NT system.
1325 The system \"open\" is used for most files.
1326 See `org-file-apps'.")
1328 (defcustom org-file-apps
1330 ("txt" . emacs)
1331 ("tex" . emacs)
1332 ("ltx" . emacs)
1333 ("org" . emacs)
1334 ("el" . emacs)
1335 ("bib" . emacs)
1337 "External applications for opening `file:path' items in a document.
1338 Org-mode uses system defaults for different file types, but
1339 you can use this variable to set the application for a given file
1340 extension. The entries in this list are cons cells where the car identifies
1341 files and the cdr the corresponding command. Possible values for the
1342 file identifier are
1343 \"ext\" A string identifying an extension
1344 `directory' Matches a directory
1345 `remote' Matches a remote file, accessible through tramp or efs.
1346 Remote files most likely should be visited through Emacs
1347 because external applications cannot handle such paths.
1348 t Default for all remaining files
1350 Possible values for the command are:
1351 `emacs' The file will be visited by the current Emacs process.
1352 `default' Use the default application for this file type.
1353 string A command to be executed by a shell; %s will be replaced
1354 by the path to the file.
1355 sexp A Lisp form which will be evaluated. The file path will
1356 be available in the Lisp variable `file'.
1357 For more examples, see the system specific constants
1358 `org-file-apps-defaults-macosx'
1359 `org-file-apps-defaults-windowsnt'
1360 `org-file-apps-defaults-gnu'."
1361 :group 'org-link-follow
1362 :type '(repeat
1363 (cons (choice :value ""
1364 (string :tag "Extension")
1365 (const :tag "Default for unrecognized files" t)
1366 (const :tag "Remote file" remote)
1367 (const :tag "Links to a directory" directory))
1368 (choice :value ""
1369 (const :tag "Visit with Emacs" emacs)
1370 (const :tag "Use system default" default)
1371 (string :tag "Command")
1372 (sexp :tag "Lisp form")))))
1374 (defcustom org-mhe-search-all-folders nil
1375 "Non-nil means, that the search for the mh-message will be extended to
1376 all folders if the message cannot be found in the folder given in the link.
1377 Searching all folders is very efficient with one of the search engines
1378 supported by MH-E, but will be slow with pick."
1379 :group 'org-link-follow
1380 :type 'boolean)
1382 (defgroup org-remember nil
1383 "Options concerning interaction with remember.el."
1384 :tag "Org Remember"
1385 :group 'org)
1387 (defcustom org-directory "~/org"
1388 "Directory with org files.
1389 This directory will be used as default to prompt for org files.
1390 Used by the hooks for remember.el."
1391 :group 'org-remember
1392 :type 'directory)
1394 (defcustom org-default-notes-file "~/.notes"
1395 "Default target for storing notes.
1396 Used by the hooks for remember.el. This can be a string, or nil to mean
1397 the value of `remember-data-file'.
1398 You can set this on a per-template basis with the variable
1399 `org-remember-templates'."
1400 :group 'org-remember
1401 :type '(choice
1402 (const :tag "Default from remember-data-file" nil)
1403 file))
1405 (defcustom org-remember-store-without-prompt t
1406 "Non-nil means, `C-c C-c' stores remember note without further promts.
1407 In this case, you need `C-u C-c C-c' to get the prompts for
1408 note file and headline.
1409 When this variable is nil, `C-c C-c' give you the prompts, and
1410 `C-u C-c C-c' trigger the fasttrack."
1411 :group 'org-remember
1412 :type 'boolean)
1414 (defcustom org-remember-default-headline ""
1415 "The headline that should be the default location in the notes file.
1416 When filing remember notes, the cursor will start at that position.
1417 You can set this on a per-template basis with the variable
1418 `org-remember-templates'."
1419 :group 'org-remember
1420 :type 'string)
1422 (defcustom org-remember-templates nil
1423 "Templates for the creation of remember buffers.
1424 When nil, just let remember make the buffer.
1425 When not nil, this is a list of 5-element lists. In each entry, the first
1426 element is a the name of the template, It should be a single short word.
1427 The second element is a character, a unique key to select this template.
1428 The third element is the template. The forth element is optional and can
1429 specify a destination file for remember items created with this template.
1430 The default file is given by `org-default-notes-file'. An optional fifth
1431 element can specify the headline in that file that should be offered
1432 first when the user is asked to file the entry. The default headline is
1433 given in the variable `org-remember-default-headline'.
1435 The template specifies the structure of the remember buffer. It should have
1436 a first line starting with a star, to act as the org-mode headline.
1437 Furthermore, the following %-escapes will be replaced with content:
1439 %^{prompt} Prompt the user for a string and replace this sequence with it.
1440 A default value and a completion table ca be specified like this:
1441 %^{prompt|default|completion2|completion3|...}
1442 %t time stamp, date only
1443 %T time stamp with date and time
1444 %u, %U like the above, but inactive time stamps
1445 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1446 You may define a prompt like %^{Please specify birthday}t
1447 %n user name (taken from `user-full-name')
1448 %a annotation, normally the link created with org-store-link
1449 %i initial content, the region when remember is called with C-u.
1450 If %i is indented, the entire inserted text will be indented
1451 as well.
1452 %c content of the clipboard, or current kill ring head
1453 %^g prompt for tags, with completion on tags in target file
1454 %^G prompt for tags, with completion all tags in all agenda files
1455 %:keyword specific information for certain link types, see below
1456 %[pathname] insert the contents of the file given by `pathname'
1457 %(sexp) evaluate elisp `(sexp)' and replace with the result
1458 %! Store this note immediately after filling the template
1460 %? After completing the template, position cursor here.
1462 Apart from these general escapes, you can access information specific to the
1463 link type that is created. For example, calling `remember' in emails or gnus
1464 will record the author and the subject of the message, which you can access
1465 with %:author and %:subject, respectively. Here is a complete list of what
1466 is recorded for each link type.
1468 Link type | Available information
1469 -------------------+------------------------------------------------------
1470 bbdb | %:type %:name %:company
1471 vm, wl, mh, rmail | %:type %:subject %:message-id
1472 | %:from %:fromname %:fromaddress
1473 | %:to %:toname %:toaddress
1474 | %:fromto (either \"to NAME\" or \"from NAME\")
1475 gnus | %:group, for messages also all email fields
1476 w3, w3m | %:type %:url
1477 info | %:type %:file %:node
1478 calendar | %:type %:date"
1479 :group 'org-remember
1480 :get (lambda (var) ; Make sure all entries have 5 elements
1481 (mapcar (lambda (x)
1482 (if (not (stringp (car x))) (setq x (cons "" x)))
1483 (cond ((= (length x) 4) (append x '("")))
1484 ((= (length x) 3) (append x '("" "")))
1485 (t x)))
1486 (default-value var)))
1487 :type '(repeat
1488 :tag "enabled"
1489 (list :value ("" ?a "\n" nil nil)
1490 (string :tag "Name")
1491 (character :tag "Selection Key")
1492 (string :tag "Template")
1493 (choice
1494 (file :tag "Destination file")
1495 (const :tag "Prompt for file" nil))
1496 (choice
1497 (string :tag "Destination headline")
1498 (const :tag "Selection interface for heading")))))
1500 (defcustom org-reverse-note-order nil
1501 "Non-nil means, store new notes at the beginning of a file or entry.
1502 When nil, new notes will be filed to the end of a file or entry.
1503 This can also be a list with cons cells of regular expressions that
1504 are matched against file names, and values."
1505 :group 'org-remember
1506 :type '(choice
1507 (const :tag "Reverse always" t)
1508 (const :tag "Reverse never" nil)
1509 (repeat :tag "By file name regexp"
1510 (cons regexp boolean))))
1512 (defcustom org-refile-targets '((nil . (:level . 1)))
1513 "Targets for refiling entries with \\[org-refile].
1514 This is list of cons cells. Each cell contains:
1515 - a specification of the files to be considered, either a list of files,
1516 or a symbol whose function or value fields will be used to retrieve
1517 a file name or a list of file names. Nil means, refile to a different
1518 heading in the current buffer.
1519 - A specification of how to find candidate refile targets. This may be
1520 any of
1521 - a cons cell (:tag . \"TAG\") to identify refile targes by a tag.
1522 This tag has to be present in all target headlines, inheritance will
1523 not be considered.
1524 - a cons cell (:todo . \"KEYWORD\" to identify refile targets by
1525 todo keyword.
1526 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1527 headlines that are refiling targets.
1528 - a cons cell (:level . N). Any headline of level N is considered a target.
1529 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1530 ;; FIXME: what if there are a var and func with same name???
1531 :group 'org-remember
1532 :type '(repeat
1533 (cons
1534 (choice :value org-agenda-files
1535 (const :tag "All agenda files" org-agenda-files)
1536 (const :tag "Current buffer" nil)
1537 (function) (variable) (file))
1538 (choice :tag "Identify target headline by"
1539 (cons :tag "Specific tag" (const :tag) (string))
1540 (cons :tag "TODO keyword" (const :todo) (string))
1541 (cons :tag "Regular expression" (const :regexp) (regexp))
1542 (cons :tag "Level number" (const :level) (integer))
1543 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1545 (defcustom org-refile-use-outline-path nil
1546 "Non-nil means, provide refile targets as paths.
1547 So a level 3 headline will be available as level1/level2/level3.
1548 When the value is `file', also include the file name (without directory)
1549 into the path. When `full-file-path', include the full file path."
1550 :group 'org-remember
1551 :type '(choice
1552 (const :tag "Not" nil)
1553 (const :tag "Yes" t)
1554 (const :tag "Start with file name" file)
1555 (const :tag "Start with full file path" full-file-path)))
1557 (defgroup org-todo nil
1558 "Options concerning TODO items in Org-mode."
1559 :tag "Org TODO"
1560 :group 'org)
1562 (defgroup org-progress nil
1563 "Options concerning Progress logging in Org-mode."
1564 :tag "Org Progress"
1565 :group 'org-time)
1567 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1568 "List of TODO entry keyword sequences and their interpretation.
1569 \\<org-mode-map>This is a list of sequences.
1571 Each sequence starts with a symbol, either `sequence' or `type',
1572 indicating if the keywords should be interpreted as a sequence of
1573 action steps, or as different types of TODO items. The first
1574 keywords are states requiring action - these states will select a headline
1575 for inclusion into the global TODO list Org-mode produces. If one of
1576 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1577 signify that no further action is necessary. If \"|\" is not found,
1578 the last keyword is treated as the only DONE state of the sequence.
1580 The command \\[org-todo] cycles an entry through these states, and one
1581 additional state where no keyword is present. For details about this
1582 cycling, see the manual.
1584 TODO keywords and interpretation can also be set on a per-file basis with
1585 the special #+SEQ_TODO and #+TYP_TODO lines.
1587 For backward compatibility, this variable may also be just a list
1588 of keywords - in this case the interptetation (sequence or type) will be
1589 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1590 :group 'org-todo
1591 :group 'org-keywords
1592 :type '(choice
1593 (repeat :tag "Old syntax, just keywords"
1594 (string :tag "Keyword"))
1595 (repeat :tag "New syntax"
1596 (cons
1597 (choice
1598 :tag "Interpretation"
1599 (const :tag "Sequence (cycling hits every state)" sequence)
1600 (const :tag "Type (cycling directly to DONE)" type))
1601 (repeat
1602 (string :tag "Keyword"))))))
1604 (defvar org-todo-keywords-1 nil)
1605 (make-variable-buffer-local 'org-todo-keywords-1)
1606 (defvar org-todo-keywords-for-agenda nil)
1607 (defvar org-done-keywords-for-agenda nil)
1608 (defvar org-not-done-keywords nil)
1609 (make-variable-buffer-local 'org-not-done-keywords)
1610 (defvar org-done-keywords nil)
1611 (make-variable-buffer-local 'org-done-keywords)
1612 (defvar org-todo-heads nil)
1613 (make-variable-buffer-local 'org-todo-heads)
1614 (defvar org-todo-sets nil)
1615 (make-variable-buffer-local 'org-todo-sets)
1616 (defvar org-todo-log-states nil)
1617 (make-variable-buffer-local 'org-todo-log-states)
1618 (defvar org-todo-kwd-alist nil)
1619 (make-variable-buffer-local 'org-todo-kwd-alist)
1620 (defvar org-todo-key-alist nil)
1621 (make-variable-buffer-local 'org-todo-key-alist)
1622 (defvar org-todo-key-trigger nil)
1623 (make-variable-buffer-local 'org-todo-key-trigger)
1625 (defcustom org-todo-interpretation 'sequence
1626 "Controls how TODO keywords are interpreted.
1627 This variable is in principle obsolete and is only used for
1628 backward compatibility, if the interpretation of todo keywords is
1629 not given already in `org-todo-keywords'. See that variable for
1630 more information."
1631 :group 'org-todo
1632 :group 'org-keywords
1633 :type '(choice (const sequence)
1634 (const type)))
1636 (defcustom org-use-fast-todo-selection 'prefix
1637 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1638 This variable describes if and under what circumstances the cycling
1639 mechanism for TODO keywords will be replaced by a single-key, direct
1640 selection scheme.
1642 When nil, fast selection is never used.
1644 When the symbol `prefix', it will be used when `org-todo' is called with
1645 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1646 in an agenda buffer.
1648 When t, fast selection is used by default. In this case, the prefix
1649 argument forces cycling instead.
1651 In all cases, the special interface is only used if access keys have actually
1652 been assigned by the user, i.e. if keywords in the configuration are followed
1653 by a letter in parenthesis, like TODO(t)."
1654 :group 'org-todo
1655 :type '(choice
1656 (const :tag "Never" nil)
1657 (const :tag "By default" t)
1658 (const :tag "Only with C-u C-c C-t" prefix)))
1660 (defcustom org-after-todo-state-change-hook nil
1661 "Hook which is run after the state of a TODO item was changed.
1662 The new state (a string with a TODO keyword, or nil) is available in the
1663 Lisp variable `state'."
1664 :group 'org-todo
1665 :type 'hook)
1667 (defcustom org-log-done nil
1668 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1669 When the state of an entry is changed from nothing or a DONE state to
1670 a not-done TODO state, remove a previous closing date.
1672 This can also be a list of symbols indicating under which conditions
1673 the time stamp recording the action should be annotated with a short note.
1674 Valid members of this list are
1676 done Offer to record a note when marking entries done
1677 state Offer to record a note whenever changing the TODO state
1678 of an item. This is only relevant if TODO keywords are
1679 interpreted as sequence, see variable `org-todo-interpretation'.
1680 When `state' is set, this includes tracking `done'.
1681 clock-out Offer to record a note when clocking out of an item.
1683 A separate window will then pop up and allow you to type a note.
1684 After finishing with C-c C-c, the note will be added directly after the
1685 timestamp, as a plain list item. See also the variable
1686 `org-log-note-headings'.
1688 Logging can also be configured on a per-file basis by adding one of
1689 the following lines anywhere in the buffer:
1691 #+STARTUP: logdone
1692 #+STARTUP: nologging
1693 #+STARTUP: lognotedone
1694 #+STARTUP: lognotestate
1695 #+STARTUP: lognoteclock-out
1697 You can have local logging settings for a subtree by setting the LOGGING
1698 property to one or more of these keywords."
1699 :group 'org-todo
1700 :group 'org-progress
1701 :type '(choice
1702 (const :tag "off" nil)
1703 (const :tag "on" t)
1704 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1705 (const :tag "when item is marked DONE" done)
1706 (const :tag "when TODO state changes" state)
1707 (const :tag "when clocking out" clock-out))))
1709 (defcustom org-log-done-with-time t
1710 "Non-nil means, the CLOSED time stamp will contain date and time.
1711 When nil, only the date will be recorded."
1712 :group 'org-progress
1713 :type 'boolean)
1715 (defcustom org-log-note-headings
1716 '((done . "CLOSING NOTE %t")
1717 (state . "State %-12s %t")
1718 (clock-out . ""))
1719 "Headings for notes added when clocking out or closing TODO items.
1720 The value is an alist, with the car being a symbol indicating the note
1721 context, and the cdr is the heading to be used. The heading may also be the
1722 empty string.
1723 %t in the heading will be replaced by a time stamp.
1724 %s will be replaced by the new TODO state, in double quotes.
1725 %u will be replaced by the user name.
1726 %U will be replaced by the full user name."
1727 :group 'org-todo
1728 :group 'org-progress
1729 :type '(list :greedy t
1730 (cons (const :tag "Heading when closing an item" done) string)
1731 (cons (const :tag
1732 "Heading when changing todo state (todo sequence only)"
1733 state) string)
1734 (cons (const :tag "Heading when clocking out" clock-out) string)))
1736 (defcustom org-log-states-order-reversed t
1737 "Non-nil means, the latest state change note will be directly after heading.
1738 When nil, the notes will be orderer according to time."
1739 :group 'org-todo
1740 :group 'org-progress
1741 :type 'boolean)
1743 (defcustom org-log-repeat t
1744 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1745 When nil, no note will be taken.
1746 This option can also be set with on a per-file-basis with
1748 #+STARTUP: logrepeat
1749 #+STARTUP: nologrepeat
1751 You can have local logging settings for a subtree by setting the LOGGING
1752 property to one or more of these keywords."
1753 :group 'org-todo
1754 :group 'org-progress
1755 :type 'boolean)
1757 (defcustom org-clock-into-drawer 2
1758 "Should clocking info be wrapped into a drawer?
1759 When t, clocking info will always be inserted into a :CLOCK: drawer.
1760 If necessary, the drawer will be created.
1761 When nil, the drawer will not be created, but used when present.
1762 When an integer and the number of clocking entries in an item
1763 reaches or exceeds this number, a drawer will be created."
1764 :group 'org-todo
1765 :group 'org-progress
1766 :type '(choice
1767 (const :tag "Always" t)
1768 (const :tag "Only when drawer exists" nil)
1769 (integer :tag "When at least N clock entries")))
1771 (defcustom org-clock-out-when-done t
1772 "When t, the clock will be stopped when the relevant entry is marked DONE.
1773 Nil means, clock will keep running until stopped explicitly with
1774 `C-c C-x C-o', or until the clock is started in a different item."
1775 :group 'org-progress
1776 :type 'boolean)
1778 (defcustom org-clock-in-switch-to-state nil
1779 "Set task to a special todo state while clocking it.
1780 The value should be the state to which the entry should be switched."
1781 :group 'org-progress
1782 :group 'org-todo
1783 :type '(choice
1784 (const :tag "Don't force a state" nil)
1785 (string :tag "State")))
1787 (defgroup org-priorities nil
1788 "Priorities in Org-mode."
1789 :tag "Org Priorities"
1790 :group 'org-todo)
1792 (defcustom org-highest-priority ?A
1793 "The highest priority of TODO items. A character like ?A, ?B etc.
1794 Must have a smaller ASCII number than `org-lowest-priority'."
1795 :group 'org-priorities
1796 :type 'character)
1798 (defcustom org-lowest-priority ?C
1799 "The lowest priority of TODO items. A character like ?A, ?B etc.
1800 Must have a larger ASCII number than `org-highest-priority'."
1801 :group 'org-priorities
1802 :type 'character)
1804 (defcustom org-default-priority ?B
1805 "The default priority of TODO items.
1806 This is the priority an item get if no explicit priority is given."
1807 :group 'org-priorities
1808 :type 'character)
1810 (defcustom org-priority-start-cycle-with-default t
1811 "Non-nil means, start with default priority when starting to cycle.
1812 When this is nil, the first step in the cycle will be (depending on the
1813 command used) one higher or lower that the default priority."
1814 :group 'org-priorities
1815 :type 'boolean)
1817 (defgroup org-time nil
1818 "Options concerning time stamps and deadlines in Org-mode."
1819 :tag "Org Time"
1820 :group 'org)
1822 (defcustom org-insert-labeled-timestamps-at-point nil
1823 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1824 When nil, these labeled time stamps are forces into the second line of an
1825 entry, just after the headline. When scheduling from the global TODO list,
1826 the time stamp will always be forced into the second line."
1827 :group 'org-time
1828 :type 'boolean)
1830 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1831 "Formats for `format-time-string' which are used for time stamps.
1832 It is not recommended to change this constant.")
1834 (defcustom org-time-stamp-rounding-minutes 0
1835 "Number of minutes to round time stamps to upon insertion.
1836 When zero, insert the time unmodified. Useful rounding numbers
1837 should be factors of 60, so for example 5, 10, 15.
1838 When this is not zero, you can still force an exact time-stamp by using
1839 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1840 :group 'org-time
1841 :type 'integer)
1843 (defcustom org-display-custom-times nil
1844 "Non-nil means, overlay custom formats over all time stamps.
1845 The formats are defined through the variable `org-time-stamp-custom-formats'.
1846 To turn this on on a per-file basis, insert anywhere in the file:
1847 #+STARTUP: customtime"
1848 :group 'org-time
1849 :set 'set-default
1850 :type 'sexp)
1851 (make-variable-buffer-local 'org-display-custom-times)
1853 (defcustom org-time-stamp-custom-formats
1854 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1855 "Custom formats for time stamps. See `format-time-string' for the syntax.
1856 These are overlayed over the default ISO format if the variable
1857 `org-display-custom-times' is set. Time like %H:%M should be at the
1858 end of the second format."
1859 :group 'org-time
1860 :type 'sexp)
1862 (defun org-time-stamp-format (&optional long inactive)
1863 "Get the right format for a time string."
1864 (let ((f (if long (cdr org-time-stamp-formats)
1865 (car org-time-stamp-formats))))
1866 (if inactive
1867 (concat "[" (substring f 1 -1) "]")
1868 f)))
1870 (defcustom org-read-date-prefer-future t
1871 "Non-nil means, assume future for incomplete date input from user.
1872 This affects the following situations:
1873 1. The user gives a day, but no month.
1874 For example, if today is the 15th, and you enter \"3\", Org-mode will
1875 read this as the third of *next* month. However, if you enter \"17\",
1876 it will be considered as *this* month.
1877 2. The user gives a month but not a year.
1878 For example, if it is april and you enter \"feb 2\", this will be read
1879 as feb 2, *next* year. \"May 5\", however, will be this year.
1881 When this option is nil, the current month and year will always be used
1882 as defaults."
1883 :group 'org-time
1884 :type 'boolean)
1886 (defcustom org-read-date-display-live t
1887 "Non-nil means, display current interpretation of date prompt live.
1888 This display will be in an overlay, in the minibuffer."
1889 :group 'org-time
1890 :type 'boolean)
1892 (defcustom org-read-date-popup-calendar t
1893 "Non-nil means, pop up a calendar when prompting for a date.
1894 In the calendar, the date can be selected with mouse-1. However, the
1895 minibuffer will also be active, and you can simply enter the date as well.
1896 When nil, only the minibuffer will be available."
1897 :group 'org-time
1898 :type 'boolean)
1899 (if (fboundp 'defvaralias)
1900 (defvaralias 'org-popup-calendar-for-date-prompt
1901 'org-read-date-popup-calendar))
1903 (defcustom org-extend-today-until 0
1904 "The hour when your day really ends.
1905 This has influence for the following applications:
1906 - When switching the agenda to \"today\". It it is still earlier than
1907 the time given here, the day recognized as TODAY is actually yesterday.
1908 - When a date is read from the user and it is still before the time given
1909 here, the current date and time will be assumed to be yesterday, 23:59.
1911 FIXME:
1912 IMPORTANT: This is still a very experimental feature, it may disappear
1913 again or it may be extended to mean more things."
1914 :group 'org-time
1915 :type 'number)
1917 (defcustom org-edit-timestamp-down-means-later nil
1918 "Non-nil means, S-down will increase the time in a time stamp.
1919 When nil, S-up will increase."
1920 :group 'org-time
1921 :type 'boolean)
1923 (defcustom org-calendar-follow-timestamp-change t
1924 "Non-nil means, make the calendar window follow timestamp changes.
1925 When a timestamp is modified and the calendar window is visible, it will be
1926 moved to the new date."
1927 :group 'org-time
1928 :type 'boolean)
1930 (defcustom org-clock-heading-function nil
1931 "When non-nil, should be a function to create `org-clock-heading'.
1932 This is the string shown in the mode line when a clock is running.
1933 The function is called with point at the beginning of the headline."
1934 :group 'org-time ; FIXME: Should we have a separate group????
1935 :type 'function)
1937 (defgroup org-tags nil
1938 "Options concerning tags in Org-mode."
1939 :tag "Org Tags"
1940 :group 'org)
1942 (defcustom org-tag-alist nil
1943 "List of tags allowed in Org-mode files.
1944 When this list is nil, Org-mode will base TAG input on what is already in the
1945 buffer.
1946 The value of this variable is an alist, the car of each entry must be a
1947 keyword as a string, the cdr may be a character that is used to select
1948 that tag through the fast-tag-selection interface.
1949 See the manual for details."
1950 :group 'org-tags
1951 :type '(repeat
1952 (choice
1953 (cons (string :tag "Tag name")
1954 (character :tag "Access char"))
1955 (const :tag "Start radio group" (:startgroup))
1956 (const :tag "End radio group" (:endgroup)))))
1958 (defcustom org-use-fast-tag-selection 'auto
1959 "Non-nil means, use fast tag selection scheme.
1960 This is a special interface to select and deselect tags with single keys.
1961 When nil, fast selection is never used.
1962 When the symbol `auto', fast selection is used if and only if selection
1963 characters for tags have been configured, either through the variable
1964 `org-tag-alist' or through a #+TAGS line in the buffer.
1965 When t, fast selection is always used and selection keys are assigned
1966 automatically if necessary."
1967 :group 'org-tags
1968 :type '(choice
1969 (const :tag "Always" t)
1970 (const :tag "Never" nil)
1971 (const :tag "When selection characters are configured" 'auto)))
1973 (defcustom org-fast-tag-selection-single-key nil
1974 "Non-nil means, fast tag selection exits after first change.
1975 When nil, you have to press RET to exit it.
1976 During fast tag selection, you can toggle this flag with `C-c'.
1977 This variable can also have the value `expert'. In this case, the window
1978 displaying the tags menu is not even shown, until you press C-c again."
1979 :group 'org-tags
1980 :type '(choice
1981 (const :tag "No" nil)
1982 (const :tag "Yes" t)
1983 (const :tag "Expert" expert)))
1985 (defvar org-fast-tag-selection-include-todo nil
1986 "Non-nil means, fast tags selection interface will also offer TODO states.
1987 This is an undocumented feature, you should not rely on it.")
1989 (defcustom org-tags-column -80
1990 "The column to which tags should be indented in a headline.
1991 If this number is positive, it specifies the column. If it is negative,
1992 it means that the tags should be flushright to that column. For example,
1993 -80 works well for a normal 80 character screen."
1994 :group 'org-tags
1995 :type 'integer)
1997 (defcustom org-auto-align-tags t
1998 "Non-nil means, realign tags after pro/demotion of TODO state change.
1999 These operations change the length of a headline and therefore shift
2000 the tags around. With this options turned on, after each such operation
2001 the tags are again aligned to `org-tags-column'."
2002 :group 'org-tags
2003 :type 'boolean)
2005 (defcustom org-use-tag-inheritance t
2006 "Non-nil means, tags in levels apply also for sublevels.
2007 When nil, only the tags directly given in a specific line apply there.
2008 If you turn off this option, you very likely want to turn on the
2009 companion option `org-tags-match-list-sublevels'."
2010 :group 'org-tags
2011 :type 'boolean)
2013 (defcustom org-tags-match-list-sublevels nil
2014 "Non-nil means list also sublevels of headlines matching tag search.
2015 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2016 the sublevels of a headline matching a tag search often also match
2017 the same search. Listing all of them can create very long lists.
2018 Setting this variable to nil causes subtrees of a match to be skipped.
2019 This option is off by default, because inheritance in on. If you turn
2020 inheritance off, you very likely want to turn this option on.
2022 As a special case, if the tag search is restricted to TODO items, the
2023 value of this variable is ignored and sublevels are always checked, to
2024 make sure all corresponding TODO items find their way into the list."
2025 :group 'org-tags
2026 :type 'boolean)
2028 (defvar org-tags-history nil
2029 "History of minibuffer reads for tags.")
2030 (defvar org-last-tags-completion-table nil
2031 "The last used completion table for tags.")
2032 (defvar org-after-tags-change-hook nil
2033 "Hook that is run after the tags in a line have changed.")
2035 (defgroup org-properties nil
2036 "Options concerning properties in Org-mode."
2037 :tag "Org Properties"
2038 :group 'org)
2040 (defcustom org-property-format "%-10s %s"
2041 "How property key/value pairs should be formatted by `indent-line'.
2042 When `indent-line' hits a property definition, it will format the line
2043 according to this format, mainly to make sure that the values are
2044 lined-up with respect to each other."
2045 :group 'org-properties
2046 :type 'string)
2048 (defcustom org-use-property-inheritance nil
2049 "Non-nil means, properties apply also for sublevels.
2050 This setting is only relevant during property searches, not when querying
2051 an entry with `org-entry-get'. To retrieve a property with inheritance,
2052 you need to call `org-entry-get' with the inheritance flag.
2053 Turning this on can cause significant overhead when doing a search, so
2054 this is turned off by default.
2055 When nil, only the properties directly given in the current entry count.
2056 The value may also be a list of properties that shouldhave inheritance.
2058 However, note that some special properties use inheritance under special
2059 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2060 and the properties ending in \"_ALL\" when they are used as descriptor
2061 for valid values of a property."
2062 :group 'org-properties
2063 :type '(choice
2064 (const :tag "Not" nil)
2065 (const :tag "Always" nil)
2066 (repeat :tag "Specific properties" (string :tag "Property"))))
2068 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2069 "The default column format, if no other format has been defined.
2070 This variable can be set on the per-file basis by inserting a line
2072 #+COLUMNS: %25ITEM ....."
2073 :group 'org-properties
2074 :type 'string)
2076 (defcustom org-global-properties nil
2077 "List of property/value pairs that can be inherited by any entry.
2078 You can set buffer-local values for this by adding lines like
2080 #+PROPERTY: NAME VALUE"
2081 :group 'org-properties
2082 :type '(repeat
2083 (cons (string :tag "Property")
2084 (string :tag "Value"))))
2086 (defvar org-local-properties nil
2087 "List of property/value pairs that can be inherited by any entry.
2088 Valid for the current buffer.
2089 This variable is populated from #+PROPERTY lines.")
2091 (defgroup org-agenda nil
2092 "Options concerning agenda views in Org-mode."
2093 :tag "Org Agenda"
2094 :group 'org)
2096 (defvar org-category nil
2097 "Variable used by org files to set a category for agenda display.
2098 Such files should use a file variable to set it, for example
2100 # -*- mode: org; org-category: \"ELisp\"
2102 or contain a special line
2104 #+CATEGORY: ELisp
2106 If the file does not specify a category, then file's base name
2107 is used instead.")
2108 (make-variable-buffer-local 'org-category)
2110 (defcustom org-agenda-files nil
2111 "The files to be used for agenda display.
2112 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2113 \\[org-remove-file]. You can also use customize to edit the list.
2115 If an entry is a directory, all files in that directory that are matched by
2116 `org-agenda-file-regexp' will be part of the file list.
2118 If the value of the variable is not a list but a single file name, then
2119 the list of agenda files is actually stored and maintained in that file, one
2120 agenda file per line."
2121 :group 'org-agenda
2122 :type '(choice
2123 (repeat :tag "List of files and directories" file)
2124 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2126 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2127 "Regular expression to match files for `org-agenda-files'.
2128 If any element in the list in that variable contains a directory instead
2129 of a normal file, all files in that directory that are matched by this
2130 regular expression will be included."
2131 :group 'org-agenda
2132 :type 'regexp)
2134 (defcustom org-agenda-skip-unavailable-files nil
2135 "t means to just skip non-reachable files in `org-agenda-files'.
2136 Nil means to remove them, after a query, from the list."
2137 :group 'org-agenda
2138 :type 'boolean)
2140 (defcustom org-agenda-multi-occur-extra-files nil
2141 "List of extra files to be searched by `org-occur-in-agenda-files'.
2142 The files in `org-agenda-files' are always searched."
2143 :group 'org-agenda
2144 :type '(repeat file))
2146 (defcustom org-agenda-confirm-kill 1
2147 "When set, remote killing from the agenda buffer needs confirmation.
2148 When t, a confirmation is always needed. When a number N, confirmation is
2149 only needed when the text to be killed contains more than N non-white lines."
2150 :group 'org-agenda
2151 :type '(choice
2152 (const :tag "Never" nil)
2153 (const :tag "Always" t)
2154 (number :tag "When more than N lines")))
2156 (defcustom org-calendar-to-agenda-key [?c]
2157 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2158 The command `org-calendar-goto-agenda' will be bound to this key. The
2159 default is the character `c' because then `c' can be used to switch back and
2160 forth between agenda and calendar."
2161 :group 'org-agenda
2162 :type 'sexp)
2164 (defcustom org-agenda-compact-blocks nil
2165 "Non-nil means, make the block agenda more compact.
2166 This is done by leaving out unnecessary lines."
2167 :group 'org-agenda
2168 :type nil)
2170 (defgroup org-agenda-export nil
2171 "Options concerning exporting agenda views in Org-mode."
2172 :tag "Org Agenda Export"
2173 :group 'org-agenda)
2175 (defcustom org-agenda-with-colors t
2176 "Non-nil means, use colors in agenda views."
2177 :group 'org-agenda-export
2178 :type 'boolean)
2180 (defcustom org-agenda-exporter-settings nil
2181 "Alist of variable/value pairs that should be active during agenda export.
2182 This is a good place to set uptions for ps-print and for htmlize."
2183 :group 'org-agenda-export
2184 :type '(repeat
2185 (list
2186 (variable)
2187 (sexp :tag "Value"))))
2189 (defcustom org-agenda-export-html-style ""
2190 "The style specification for exported HTML Agenda files.
2191 If this variable contains a string, it will replace the default <style>
2192 section as produced by `htmlize'.
2193 Since there are different ways of setting style information, this variable
2194 needs to contain the full HTML structure to provide a style, including the
2195 surrounding HTML tags. The style specifications should include definitions
2196 the fonts used by the agenda, here is an example:
2198 <style type=\"text/css\">
2199 p { font-weight: normal; color: gray; }
2200 .org-agenda-structure {
2201 font-size: 110%;
2202 color: #003399;
2203 font-weight: 600;
2205 .org-todo {
2206 color: #cc6666;Week-agenda:
2207 font-weight: bold;
2209 .org-done {
2210 color: #339933;
2212 .title { text-align: center; }
2213 .todo, .deadline { color: red; }
2214 .done { color: green; }
2215 </style>
2217 or, if you want to keep the style in a file,
2219 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2221 As the value of this option simply gets inserted into the HTML <head> header,
2222 you can \"misuse\" it to also add other text to the header. However,
2223 <style>...</style> is required, if not present the variable will be ignored."
2224 :group 'org-agenda-export
2225 :group 'org-export-html
2226 :type 'string)
2228 (defgroup org-agenda-custom-commands nil
2229 "Options concerning agenda views in Org-mode."
2230 :tag "Org Agenda Custom Commands"
2231 :group 'org-agenda)
2233 (defcustom org-agenda-custom-commands nil
2234 "Custom commands for the agenda.
2235 These commands will be offered on the splash screen displayed by the
2236 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2238 (key desc type match options files)
2240 key The key (one or more characters as a string) to be associated
2241 with the command.
2242 desc A description of the commend, when omitted or nil, a default
2243 description is built using MATCH.
2244 type The command type, any of the following symbols:
2245 todo Entries with a specific TODO keyword, in all agenda files.
2246 tags Tags match in all agenda files.
2247 tags-todo Tags match in all agenda files, TODO entries only.
2248 todo-tree Sparse tree of specific TODO keyword in *current* file.
2249 tags-tree Sparse tree with all tags matches in *current* file.
2250 occur-tree Occur sparse tree for *current* file.
2251 ... A user-defined function.
2252 match What to search for:
2253 - a single keyword for TODO keyword searches
2254 - a tags match expression for tags searches
2255 - a regular expression for occur searches
2256 options A list of option settings, similar to that in a let form, so like
2257 this: ((opt1 val1) (opt2 val2) ...)
2258 files A list of files file to write the produced agenda buffer to
2259 with the command `org-store-agenda-views'.
2260 If a file name ends in \".html\", an HTML version of the buffer
2261 is written out. If it ends in \".ps\", a postscript version is
2262 produced. Otherwide, only the plain text is written to the file.
2264 You can also define a set of commands, to create a composite agenda buffer.
2265 In this case, an entry looks like this:
2267 (key desc (cmd1 cmd2 ...) general-options file)
2269 where
2271 desc A description string to be displayed in the dispatcher menu.
2272 cmd An agenda command, similar to the above. However, tree commands
2273 are no allowed, but instead you can get agenda and global todo list.
2274 So valid commands for a set are:
2275 (agenda)
2276 (alltodo)
2277 (stuck)
2278 (todo \"match\" options files)
2279 (tags \"match\" options files)
2280 (tags-todo \"match\" options files)
2282 Each command can carry a list of options, and another set of options can be
2283 given for the whole set of commands. Individual command options take
2284 precedence over the general options.
2286 When using several characters as key to a command, the first characters
2287 are prefix commands. For the dispatcher to display useful information, you
2288 should provide a description for the prefix, like
2290 (setq org-agenda-custom-commands
2291 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2292 (\"hl\" tags \"+HOME+Lisa\")
2293 (\"hp\" tags \"+HOME+Peter\")
2294 (\"hk\" tags \"+HOME+Kim\")))"
2295 :group 'org-agenda-custom-commands
2296 :type '(repeat
2297 (choice :value ("a" "" tags "" nil)
2298 (list :tag "Single command"
2299 (string :tag "Access Key(s) ")
2300 (option (string :tag "Description"))
2301 (choice
2302 (const :tag "Agenda" agenda)
2303 (const :tag "TODO list" alltodo)
2304 (const :tag "Stuck projects" stuck)
2305 (const :tag "Tags search (all agenda files)" tags)
2306 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2307 (const :tag "TODO keyword search (all agenda files)" todo)
2308 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2309 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2310 (const :tag "Occur tree (current buffer)" occur-tree)
2311 (sexp :tag "Other, user-defined function"))
2312 (string :tag "Match")
2313 (repeat :tag "Local options"
2314 (list (variable :tag "Option") (sexp :tag "Value")))
2315 (option (repeat :tag "Export" (file :tag "Export to"))))
2316 (list :tag "Command series, all agenda files"
2317 (string :tag "Access Key(s)")
2318 (string :tag "Description ")
2319 (repeat
2320 (choice
2321 (const :tag "Agenda" (agenda))
2322 (const :tag "TODO list" (alltodo))
2323 (const :tag "Stuck projects" (stuck))
2324 (list :tag "Tags search"
2325 (const :format "" tags)
2326 (string :tag "Match")
2327 (repeat :tag "Local options"
2328 (list (variable :tag "Option")
2329 (sexp :tag "Value"))))
2331 (list :tag "Tags search, TODO entries only"
2332 (const :format "" tags-todo)
2333 (string :tag "Match")
2334 (repeat :tag "Local options"
2335 (list (variable :tag "Option")
2336 (sexp :tag "Value"))))
2338 (list :tag "TODO keyword search"
2339 (const :format "" todo)
2340 (string :tag "Match")
2341 (repeat :tag "Local options"
2342 (list (variable :tag "Option")
2343 (sexp :tag "Value"))))
2345 (list :tag "Other, user-defined function"
2346 (symbol :tag "function")
2347 (string :tag "Match")
2348 (repeat :tag "Local options"
2349 (list (variable :tag "Option")
2350 (sexp :tag "Value"))))))
2352 (repeat :tag "General options"
2353 (list (variable :tag "Option")
2354 (sexp :tag "Value")))
2355 (option (repeat :tag "Export" (file :tag "Export to"))))
2356 (cons :tag "Prefix key documentation"
2357 (string :tag "Access Key(s)")
2358 (string :tag "Description ")))))
2360 (defcustom org-stuck-projects
2361 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2362 "How to identify stuck projects.
2363 This is a list of four items:
2364 1. A tags/todo matcher string that is used to identify a project.
2365 The entire tree below a headline matched by this is considered one project.
2366 2. A list of TODO keywords identifying non-stuck projects.
2367 If the project subtree contains any headline with one of these todo
2368 keywords, the project is considered to be not stuck. If you specify
2369 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2370 3. A list of tags identifying non-stuck projects.
2371 If the project subtree contains any headline with one of these tags,
2372 the project is considered to be not stuck. If you specify \"*\" as
2373 a tag, any tag will mark the project unstuck.
2374 4. An arbitrary regular expression matching non-stuck projects.
2376 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2377 or `C-c a #' to produce the list."
2378 :group 'org-agenda-custom-commands
2379 :type '(list
2380 (string :tag "Tags/TODO match to identify a project")
2381 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2382 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2383 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2386 (defgroup org-agenda-skip nil
2387 "Options concerning skipping parts of agenda files."
2388 :tag "Org Agenda Skip"
2389 :group 'org-agenda)
2391 (defcustom org-agenda-todo-list-sublevels t
2392 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2393 When nil, the sublevels of a TODO entry are not checked, resulting in
2394 potentially much shorter TODO lists."
2395 :group 'org-agenda-skip
2396 :group 'org-todo
2397 :type 'boolean)
2399 (defcustom org-agenda-todo-ignore-with-date nil
2400 "Non-nil means, don't show entries with a date in the global todo list.
2401 You can use this if you prefer to mark mere appointments with a TODO keyword,
2402 but don't want them to show up in the TODO list.
2403 When this is set, it also covers deadlines and scheduled items, the settings
2404 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2405 will be ignored."
2406 :group 'org-agenda-skip
2407 :group 'org-todo
2408 :type 'boolean)
2410 (defcustom org-agenda-todo-ignore-scheduled nil
2411 "Non-nil means, don't show scheduled entries in the global todo list.
2412 The idea behind this is that by scheduling it, you have already taken care
2413 of this item.
2414 See also `org-agenda-todo-ignore-with-date'."
2415 :group 'org-agenda-skip
2416 :group 'org-todo
2417 :type 'boolean)
2419 (defcustom org-agenda-todo-ignore-deadlines nil
2420 "Non-nil means, don't show near deadline entries in the global todo list.
2421 Near means closer than `org-deadline-warning-days' days.
2422 The idea behind this is that such items will appear in the agenda anyway.
2423 See also `org-agenda-todo-ignore-with-date'."
2424 :group 'org-agenda-skip
2425 :group 'org-todo
2426 :type 'boolean)
2428 (defcustom org-agenda-skip-scheduled-if-done nil
2429 "Non-nil means don't show scheduled items in agenda when they are done.
2430 This is relevant for the daily/weekly agenda, not for the TODO list. And
2431 it applies only to the actual date of the scheduling. Warnings about
2432 an item with a past scheduling dates are always turned off when the item
2433 is DONE."
2434 :group 'org-agenda-skip
2435 :type 'boolean)
2437 (defcustom org-agenda-skip-deadline-if-done nil
2438 "Non-nil means don't show deadines when the corresponding item is done.
2439 When nil, the deadline is still shown and should give you a happy feeling.
2440 This is relevant for the daily/weekly agenda. And it applied only to the
2441 actualy date of the deadline. Warnings about approching and past-due
2442 deadlines are always turned off when the item is DONE."
2443 :group 'org-agenda-skip
2444 :type 'boolean)
2446 (defcustom org-agenda-skip-timestamp-if-done nil
2447 "Non-nil means don't don't select item by timestamp or -range if it is DONE."
2448 :group 'org-agenda-skip
2449 :type 'boolean)
2451 (defcustom org-timeline-show-empty-dates 3
2452 "Non-nil means, `org-timeline' also shows dates without an entry.
2453 When nil, only the days which actually have entries are shown.
2454 When t, all days between the first and the last date are shown.
2455 When an integer, show also empty dates, but if there is a gap of more than
2456 N days, just insert a special line indicating the size of the gap."
2457 :group 'org-agenda-skip
2458 :type '(choice
2459 (const :tag "None" nil)
2460 (const :tag "All" t)
2461 (number :tag "at most")))
2464 (defgroup org-agenda-startup nil
2465 "Options concerning initial settings in the Agenda in Org Mode."
2466 :tag "Org Agenda Startup"
2467 :group 'org-agenda)
2469 (defcustom org-finalize-agenda-hook nil
2470 "Hook run just before displaying an agenda buffer."
2471 :group 'org-agenda-startup
2472 :type 'hook)
2474 (defcustom org-agenda-mouse-1-follows-link nil
2475 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2476 A longer mouse click will still set point. Does not wortk on XEmacs.
2477 Needs to be set before org.el is loaded."
2478 :group 'org-agenda-startup
2479 :type 'boolean)
2481 (defcustom org-agenda-start-with-follow-mode nil
2482 "The initial value of follow-mode in a newly created agenda window."
2483 :group 'org-agenda-startup
2484 :type 'boolean)
2486 (defgroup org-agenda-windows nil
2487 "Options concerning the windows used by the Agenda in Org Mode."
2488 :tag "Org Agenda Windows"
2489 :group 'org-agenda)
2491 (defcustom org-agenda-window-setup 'reorganize-frame
2492 "How the agenda buffer should be displayed.
2493 Possible values for this option are:
2495 current-window Show agenda in the current window, keeping all other windows.
2496 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2497 other-window Use `switch-to-buffer-other-window' to display agenda.
2498 reorganize-frame Show only two windows on the current frame, the current
2499 window and the agenda.
2500 See also the variable `org-agenda-restore-windows-after-quit'."
2501 :group 'org-agenda-windows
2502 :type '(choice
2503 (const current-window)
2504 (const other-frame)
2505 (const other-window)
2506 (const reorganize-frame)))
2508 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2509 "The min and max height of the agenda window as a fraction of frame height.
2510 The value of the variable is a cons cell with two numbers between 0 and 1.
2511 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2512 :group 'org-agenda-windows
2513 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2515 (defcustom org-agenda-restore-windows-after-quit nil
2516 "Non-nil means, restore window configuration open exiting agenda.
2517 Before the window configuration is changed for displaying the agenda,
2518 the current status is recorded. When the agenda is exited with
2519 `q' or `x' and this option is set, the old state is restored. If
2520 `org-agenda-window-setup' is `other-frame', the value of this
2521 option will be ignored.."
2522 :group 'org-agenda-windows
2523 :type 'boolean)
2525 (defcustom org-indirect-buffer-display 'other-window
2526 "How should indirect tree buffers be displayed?
2527 This applies to indirect buffers created with the commands
2528 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2529 Valid values are:
2530 current-window Display in the current window
2531 other-window Just display in another window.
2532 dedicated-frame Create one new frame, and re-use it each time.
2533 new-frame Make a new frame each time. Note that in this case
2534 previously-made indirect buffers are kept, and you need to
2535 kill these buffers yourself."
2536 :group 'org-structure
2537 :group 'org-agenda-windows
2538 :type '(choice
2539 (const :tag "In current window" current-window)
2540 (const :tag "In current frame, other window" other-window)
2541 (const :tag "Each time a new frame" new-frame)
2542 (const :tag "One dedicated frame" dedicated-frame)))
2544 (defgroup org-agenda-daily/weekly nil
2545 "Options concerning the daily/weekly agenda."
2546 :tag "Org Agenda Daily/Weekly"
2547 :group 'org-agenda)
2549 (defcustom org-agenda-ndays 7
2550 "Number of days to include in overview display.
2551 Should be 1 or 7."
2552 :group 'org-agenda-daily/weekly
2553 :type 'number)
2555 (defcustom org-agenda-start-on-weekday 1
2556 "Non-nil means, start the overview always on the specified weekday.
2557 0 denotes Sunday, 1 denotes Monday etc.
2558 When nil, always start on the current day."
2559 :group 'org-agenda-daily/weekly
2560 :type '(choice (const :tag "Today" nil)
2561 (number :tag "Weekday No.")))
2563 (defcustom org-agenda-show-all-dates t
2564 "Non-nil means, `org-agenda' shows every day in the selected range.
2565 When nil, only the days which actually have entries are shown."
2566 :group 'org-agenda-daily/weekly
2567 :type 'boolean)
2569 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2570 "Format string for displaying dates in the agenda.
2571 Used by the daily/weekly agenda and by the timeline. This should be
2572 a format string understood by `format-time-string', or a function returning
2573 the formatted date as a string. The function must take a single argument,
2574 a calendar-style date list like (month day year)."
2575 :group 'org-agenda-daily/weekly
2576 :type '(choice
2577 (string :tag "Format string")
2578 (function :tag "Function")))
2580 (defun org-agenda-format-date-aligned (date)
2581 "Format a date string for display in the daily/weekly agenda, or timeline.
2582 This function makes sure that dates are aligned for easy reading."
2583 (format "%-9s %2d %s %4d"
2584 (calendar-day-name date)
2585 (extract-calendar-day date)
2586 (calendar-month-name (extract-calendar-month date))
2587 (extract-calendar-year date)))
2589 (defcustom org-agenda-include-diary nil
2590 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2591 :group 'org-agenda-daily/weekly
2592 :type 'boolean)
2594 (defcustom org-agenda-include-all-todo nil
2595 "Set means weekly/daily agenda will always contain all TODO entries.
2596 The TODO entries will be listed at the top of the agenda, before
2597 the entries for specific days."
2598 :group 'org-agenda-daily/weekly
2599 :type 'boolean)
2601 (defcustom org-agenda-repeating-timestamp-show-all t
2602 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2603 When nil, only one occurence is shown, either today or the
2604 nearest into the future."
2605 :group 'org-agenda-daily/weekly
2606 :type 'boolean)
2608 (defcustom org-deadline-warning-days 14
2609 "No. of days before expiration during which a deadline becomes active.
2610 This variable governs the display in sparse trees and in the agenda.
2611 When negative, it means use this number (the absolute value of it)
2612 even if a deadline has a different individual lead time specified."
2613 :group 'org-time
2614 :group 'org-agenda-daily/weekly
2615 :type 'number)
2617 (defcustom org-scheduled-past-days 10000
2618 "No. of days to continue listing scheduled items that are not marked DONE.
2619 When an item is scheduled on a date, it shows up in the agenda on this
2620 day and will be listed until it is marked done for the number of days
2621 given here."
2622 :group 'org-agenda-daily/weekly
2623 :type 'number)
2625 (defgroup org-agenda-time-grid nil
2626 "Options concerning the time grid in the Org-mode Agenda."
2627 :tag "Org Agenda Time Grid"
2628 :group 'org-agenda)
2630 (defcustom org-agenda-use-time-grid t
2631 "Non-nil means, show a time grid in the agenda schedule.
2632 A time grid is a set of lines for specific times (like every two hours between
2633 8:00 and 20:00). The items scheduled for a day at specific times are
2634 sorted in between these lines.
2635 For details about when the grid will be shown, and what it will look like, see
2636 the variable `org-agenda-time-grid'."
2637 :group 'org-agenda-time-grid
2638 :type 'boolean)
2640 (defcustom org-agenda-time-grid
2641 '((daily today require-timed)
2642 "----------------"
2643 (800 1000 1200 1400 1600 1800 2000))
2645 "The settings for time grid for agenda display.
2646 This is a list of three items. The first item is again a list. It contains
2647 symbols specifying conditions when the grid should be displayed:
2649 daily if the agenda shows a single day
2650 weekly if the agenda shows an entire week
2651 today show grid on current date, independent of daily/weekly display
2652 require-timed show grid only if at least one item has a time specification
2654 The second item is a string which will be places behing the grid time.
2656 The third item is a list of integers, indicating the times that should have
2657 a grid line."
2658 :group 'org-agenda-time-grid
2659 :type
2660 '(list
2661 (set :greedy t :tag "Grid Display Options"
2662 (const :tag "Show grid in single day agenda display" daily)
2663 (const :tag "Show grid in weekly agenda display" weekly)
2664 (const :tag "Always show grid for today" today)
2665 (const :tag "Show grid only if any timed entries are present"
2666 require-timed)
2667 (const :tag "Skip grid times already present in an entry"
2668 remove-match))
2669 (string :tag "Grid String")
2670 (repeat :tag "Grid Times" (integer :tag "Time"))))
2672 (defgroup org-agenda-sorting nil
2673 "Options concerning sorting in the Org-mode Agenda."
2674 :tag "Org Agenda Sorting"
2675 :group 'org-agenda)
2677 (defconst org-sorting-choice
2678 '(choice
2679 (const time-up) (const time-down)
2680 (const category-keep) (const category-up) (const category-down)
2681 (const tag-down) (const tag-up)
2682 (const priority-up) (const priority-down))
2683 "Sorting choices.")
2685 (defcustom org-agenda-sorting-strategy
2686 '((agenda time-up category-keep priority-down)
2687 (todo category-keep priority-down)
2688 (tags category-keep priority-down))
2689 "Sorting structure for the agenda items of a single day.
2690 This is a list of symbols which will be used in sequence to determine
2691 if an entry should be listed before another entry. The following
2692 symbols are recognized:
2694 time-up Put entries with time-of-day indications first, early first
2695 time-down Put entries with time-of-day indications first, late first
2696 category-keep Keep the default order of categories, corresponding to the
2697 sequence in `org-agenda-files'.
2698 category-up Sort alphabetically by category, A-Z.
2699 category-down Sort alphabetically by category, Z-A.
2700 tag-up Sort alphabetically by last tag, A-Z.
2701 tag-down Sort alphabetically by last tag, Z-A.
2702 priority-up Sort numerically by priority, high priority last.
2703 priority-down Sort numerically by priority, high priority first.
2705 The different possibilities will be tried in sequence, and testing stops
2706 if one comparison returns a \"not-equal\". For example, the default
2707 '(time-up category-keep priority-down)
2708 means: Pull out all entries having a specified time of day and sort them,
2709 in order to make a time schedule for the current day the first thing in the
2710 agenda listing for the day. Of the entries without a time indication, keep
2711 the grouped in categories, don't sort the categories, but keep them in
2712 the sequence given in `org-agenda-files'. Within each category sort by
2713 priority.
2715 Leaving out `category-keep' would mean that items will be sorted across
2716 categories by priority.
2718 Instead of a single list, this can also be a set of list for specific
2719 contents, with a context symbol in the car of the list, any of
2720 `agenda', `todo', `tags' for the corresponding agenda views."
2721 :group 'org-agenda-sorting
2722 :type `(choice
2723 (repeat :tag "General" ,org-sorting-choice)
2724 (list :tag "Individually"
2725 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2726 (repeat ,org-sorting-choice))
2727 (cons (const :tag "Strategy for TODO lists" todo)
2728 (repeat ,org-sorting-choice))
2729 (cons (const :tag "Strategy for Tags matches" tags)
2730 (repeat ,org-sorting-choice)))))
2732 (defcustom org-sort-agenda-notime-is-late t
2733 "Non-nil means, items without time are considered late.
2734 This is only relevant for sorting. When t, items which have no explicit
2735 time like 15:30 will be considered as 99:01, i.e. later than any items which
2736 do have a time. When nil, the default time is before 0:00. You can use this
2737 option to decide if the schedule for today should come before or after timeless
2738 agenda entries."
2739 :group 'org-agenda-sorting
2740 :type 'boolean)
2742 (defgroup org-agenda-line-format nil
2743 "Options concerning the entry prefix in the Org-mode agenda display."
2744 :tag "Org Agenda Line Format"
2745 :group 'org-agenda)
2747 (defcustom org-agenda-prefix-format
2748 '((agenda . " %-12:c%?-12t% s")
2749 (timeline . " % s")
2750 (todo . " %-12:c")
2751 (tags . " %-12:c"))
2752 "Format specifications for the prefix of items in the agenda views.
2753 An alist with four entries, for the different agenda types. The keys to the
2754 sublists are `agenda', `timeline', `todo', and `tags'. The values
2755 are format strings.
2756 This format works similar to a printf format, with the following meaning:
2758 %c the category of the item, \"Diary\" for entries from the diary, or
2759 as given by the CATEGORY keyword or derived from the file name.
2760 %T the *last* tag of the item. Last because inherited tags come
2761 first in the list.
2762 %t the time-of-day specification if one applies to the entry, in the
2763 format HH:MM
2764 %s Scheduling/Deadline information, a short string
2766 All specifiers work basically like the standard `%s' of printf, but may
2767 contain two additional characters: A question mark just after the `%' and
2768 a whitespace/punctuation character just before the final letter.
2770 If the first character after `%' is a question mark, the entire field
2771 will only be included if the corresponding value applies to the
2772 current entry. This is useful for fields which should have fixed
2773 width when present, but zero width when absent. For example,
2774 \"%?-12t\" will result in a 12 character time field if a time of the
2775 day is specified, but will completely disappear in entries which do
2776 not contain a time.
2778 If there is punctuation or whitespace character just before the final
2779 format letter, this character will be appended to the field value if
2780 the value is not empty. For example, the format \"%-12:c\" leads to
2781 \"Diary: \" if the category is \"Diary\". If the category were be
2782 empty, no additional colon would be interted.
2784 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2785 - Indent the line with two space characters
2786 - Give the category in a 12 chars wide field, padded with whitespace on
2787 the right (because of `-'). Append a colon if there is a category
2788 (because of `:').
2789 - If there is a time-of-day, put it into a 12 chars wide field. If no
2790 time, don't put in an empty field, just skip it (because of '?').
2791 - Finally, put the scheduling information and append a whitespace.
2793 As another example, if you don't want the time-of-day of entries in
2794 the prefix, you could use:
2796 (setq org-agenda-prefix-format \" %-11:c% s\")
2798 See also the variables `org-agenda-remove-times-when-in-prefix' and
2799 `org-agenda-remove-tags'."
2800 :type '(choice
2801 (string :tag "General format")
2802 (list :greedy t :tag "View dependent"
2803 (cons (const agenda) (string :tag "Format"))
2804 (cons (const timeline) (string :tag "Format"))
2805 (cons (const todo) (string :tag "Format"))
2806 (cons (const tags) (string :tag "Format"))))
2807 :group 'org-agenda-line-format)
2809 (defvar org-prefix-format-compiled nil
2810 "The compiled version of the most recently used prefix format.
2811 See the variable `org-agenda-prefix-format'.")
2813 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2814 "Text preceeding scheduled items in the agenda view.
2815 THis is a list with two strings. The first applies when the item is
2816 scheduled on the current day. The second applies when it has been scheduled
2817 previously, it may contain a %d to capture how many days ago the item was
2818 scheduled."
2819 :group 'org-agenda-line-format
2820 :type '(list
2821 (string :tag "Scheduled today ")
2822 (string :tag "Scheduled previously")))
2824 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2825 "Text preceeding deadline items in the agenda view.
2826 This is a list with two strings. The first applies when the item has its
2827 deadline on the current day. The second applies when it is in the past or
2828 in the future, it may contain %d to capture how many days away the deadline
2829 is (was)."
2830 :group 'org-agenda-line-format
2831 :type '(list
2832 (string :tag "Deadline today ")
2833 (string :tag "Deadline relative")))
2835 (defcustom org-agenda-remove-times-when-in-prefix t
2836 "Non-nil means, remove duplicate time specifications in agenda items.
2837 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2838 time-of-day specification in a headline or diary entry is extracted and
2839 placed into the prefix. If this option is non-nil, the original specification
2840 \(a timestamp or -range, or just a plain time(range) specification like
2841 11:30-4pm) will be removed for agenda display. This makes the agenda less
2842 cluttered.
2843 The option can be t or nil. It may also be the symbol `beg', indicating
2844 that the time should only be removed what it is located at the beginning of
2845 the headline/diary entry."
2846 :group 'org-agenda-line-format
2847 :type '(choice
2848 (const :tag "Always" t)
2849 (const :tag "Never" nil)
2850 (const :tag "When at beginning of entry" beg)))
2853 (defcustom org-agenda-default-appointment-duration nil
2854 "Default duration for appointments that only have a starting time.
2855 When nil, no duration is specified in such cases.
2856 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2857 :group 'org-agenda-line-format
2858 :type '(choice
2859 (integer :tag "Minutes")
2860 (const :tag "No default duration")))
2863 (defcustom org-agenda-remove-tags nil
2864 "Non-nil means, remove the tags from the headline copy in the agenda.
2865 When this is the symbol `prefix', only remove tags when
2866 `org-agenda-prefix-format' contains a `%T' specifier."
2867 :group 'org-agenda-line-format
2868 :type '(choice
2869 (const :tag "Always" t)
2870 (const :tag "Never" nil)
2871 (const :tag "When prefix format contains %T" prefix)))
2873 (if (fboundp 'defvaralias)
2874 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2875 'org-agenda-remove-tags))
2877 (defcustom org-agenda-tags-column -80
2878 "Shift tags in agenda items to this column.
2879 If this number is positive, it specifies the column. If it is negative,
2880 it means that the tags should be flushright to that column. For example,
2881 -80 works well for a normal 80 character screen."
2882 :group 'org-agenda-line-format
2883 :type 'integer)
2885 (if (fboundp 'defvaralias)
2886 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2888 (defcustom org-agenda-fontify-priorities t
2889 "Non-nil means, highlight low and high priorities in agenda.
2890 When t, the highest priority entries are bold, lowest priority italic.
2891 This may also be an association list of priority faces. The face may be
2892 a names face, or a list like `(:background \"Red\")'."
2893 :group 'org-agenda-line-format
2894 :type '(choice
2895 (const :tag "Never" nil)
2896 (const :tag "Defaults" t)
2897 (repeat :tag "Specify"
2898 (list (character :tag "Priority" :value ?A)
2899 (sexp :tag "face")))))
2901 (defgroup org-latex nil
2902 "Options for embedding LaTeX code into Org-mode"
2903 :tag "Org LaTeX"
2904 :group 'org)
2906 (defcustom org-format-latex-options
2907 '(:foreground default :background default :scale 1.0
2908 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2909 :matchers ("begin" "$" "$$" "\\(" "\\["))
2910 "Options for creating images from LaTeX fragments.
2911 This is a property list with the following properties:
2912 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2913 `default' means use the forground of the default face.
2914 :background the background color, or \"Transparent\".
2915 `default' means use the background of the default face.
2916 :scale a scaling factor for the size of the images
2917 :html-foreground, :html-background, :html-scale
2918 The same numbers for HTML export.
2919 :matchers a list indicating which matchers should be used to
2920 find LaTeX fragments. Valid members of this list are:
2921 \"begin\" find environments
2922 \"$\" find math expressions surrounded by $...$
2923 \"$$\" find math expressions surrounded by $$....$$
2924 \"\\(\" find math expressions surrounded by \\(...\\)
2925 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2926 :group 'org-latex
2927 :type 'plist)
2929 (defcustom org-format-latex-header "\\documentclass{article}
2930 \\usepackage{fullpage} % do not remove
2931 \\usepackage{amssymb}
2932 \\usepackage[usenames]{color}
2933 \\usepackage{amsmath}
2934 \\usepackage{latexsym}
2935 \\usepackage[mathscr]{eucal}
2936 \\pagestyle{empty} % do not remove"
2937 "The document header used for processing LaTeX fragments."
2938 :group 'org-latex
2939 :type 'string)
2941 (defgroup org-export nil
2942 "Options for exporting org-listings."
2943 :tag "Org Export"
2944 :group 'org)
2946 (defgroup org-export-general nil
2947 "General options for exporting Org-mode files."
2948 :tag "Org Export General"
2949 :group 'org-export)
2951 ;; FIXME
2952 (defvar org-export-publishing-directory nil)
2954 (defcustom org-export-with-special-strings t
2955 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
2956 When this option is turned on, these strings will be exported as:
2958 Org HTML LaTeX
2959 -----+----------+--------
2960 \\- &shy; \\-
2961 -- &ndash; --
2962 --- &mdash; ---
2963 ... &hellip; \ldots
2965 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
2966 :group 'org-export-translation
2967 :type 'boolean)
2969 (defcustom org-export-language-setup
2970 '(("en" "Author" "Date" "Table of Contents")
2971 ("cs" "Autor" "Datum" "Obsah")
2972 ("da" "Ophavsmand" "Dato" "Indhold")
2973 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2974 ("es" "Autor" "Fecha" "\xcdndice")
2975 ("fr" "Auteur" "Date" "Table des mati\xe8res")
2976 ("it" "Autore" "Data" "Indice")
2977 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2978 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2979 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2980 "Terms used in export text, translated to different languages.
2981 Use the variable `org-export-default-language' to set the language,
2982 or use the +OPTION lines for a per-file setting."
2983 :group 'org-export-general
2984 :type '(repeat
2985 (list
2986 (string :tag "HTML language tag")
2987 (string :tag "Author")
2988 (string :tag "Date")
2989 (string :tag "Table of Contents"))))
2991 (defcustom org-export-default-language "en"
2992 "The default language of HTML export, as a string.
2993 This should have an association in `org-export-language-setup'."
2994 :group 'org-export-general
2995 :type 'string)
2997 (defcustom org-export-skip-text-before-1st-heading t
2998 "Non-nil means, skip all text before the first headline when exporting.
2999 When nil, that text is exported as well."
3000 :group 'org-export-general
3001 :type 'boolean)
3003 (defcustom org-export-headline-levels 3
3004 "The last level which is still exported as a headline.
3005 Inferior levels will produce itemize lists when exported.
3006 Note that a numeric prefix argument to an exporter function overrides
3007 this setting.
3009 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3010 :group 'org-export-general
3011 :type 'number)
3013 (defcustom org-export-with-section-numbers t
3014 "Non-nil means, add section numbers to headlines when exporting.
3016 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3017 :group 'org-export-general
3018 :type 'boolean)
3020 (defcustom org-export-with-toc t
3021 "Non-nil means, create a table of contents in exported files.
3022 The TOC contains headlines with levels up to`org-export-headline-levels'.
3023 When an integer, include levels up to N in the toc, this may then be
3024 different from `org-export-headline-levels', but it will not be allowed
3025 to be larger than the number of headline levels.
3026 When nil, no table of contents is made.
3028 Headlines which contain any TODO items will be marked with \"(*)\" in
3029 ASCII export, and with red color in HTML output, if the option
3030 `org-export-mark-todo-in-toc' is set.
3032 In HTML output, the TOC will be clickable.
3034 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3035 or \"toc:3\"."
3036 :group 'org-export-general
3037 :type '(choice
3038 (const :tag "No Table of Contents" nil)
3039 (const :tag "Full Table of Contents" t)
3040 (integer :tag "TOC to level")))
3042 (defcustom org-export-mark-todo-in-toc nil
3043 "Non-nil means, mark TOC lines that contain any open TODO items."
3044 :group 'org-export-general
3045 :type 'boolean)
3047 (defcustom org-export-preserve-breaks nil
3048 "Non-nil means, preserve all line breaks when exporting.
3049 Normally, in HTML output paragraphs will be reformatted. In ASCII
3050 export, line breaks will always be preserved, regardless of this variable.
3052 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3053 :group 'org-export-general
3054 :type 'boolean)
3056 (defcustom org-export-with-archived-trees 'headline
3057 "Whether subtrees with the ARCHIVE tag should be exported.
3058 This can have three different values
3059 nil Do not export, pretend this tree is not present
3060 t Do export the entire tree
3061 headline Only export the headline, but skip the tree below it."
3062 :group 'org-export-general
3063 :group 'org-archive
3064 :type '(choice
3065 (const :tag "not at all" nil)
3066 (const :tag "headline only" 'headline)
3067 (const :tag "entirely" t)))
3069 (defcustom org-export-author-info t
3070 "Non-nil means, insert author name and email into the exported file.
3072 This option can also be set with the +OPTIONS line,
3073 e.g. \"author-info:nil\"."
3074 :group 'org-export-general
3075 :type 'boolean)
3077 (defcustom org-export-time-stamp-file t
3078 "Non-nil means, insert a time stamp into the exported file.
3079 The time stamp shows when the file was created.
3081 This option can also be set with the +OPTIONS line,
3082 e.g. \"timestamp:nil\"."
3083 :group 'org-export-general
3084 :type 'boolean)
3086 (defcustom org-export-with-timestamps t
3087 "If nil, do not export time stamps and associated keywords."
3088 :group 'org-export-general
3089 :type 'boolean)
3091 (defcustom org-export-remove-timestamps-from-toc t
3092 "If nil, remove timestamps from the table of contents entries."
3093 :group 'org-export-general
3094 :type 'boolean)
3096 (defcustom org-export-with-tags 'not-in-toc
3097 "If nil, do not export tags, just remove them from headlines.
3098 If this is the symbol `not-in-toc', tags will be removed from table of
3099 contents entries, but still be shown in the headlines of the document.
3101 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3102 :group 'org-export-general
3103 :type '(choice
3104 (const :tag "Off" nil)
3105 (const :tag "Not in TOC" not-in-toc)
3106 (const :tag "On" t)))
3108 (defcustom org-export-with-drawers nil
3109 "Non-nil means, export with drawers like the property drawer.
3110 When t, all drawers are exported. This may also be a list of
3111 drawer names to export."
3112 :group 'org-export-general
3113 :type '(choice
3114 (const :tag "All drawers" t)
3115 (const :tag "None" nil)
3116 (repeat :tag "Selected drawers"
3117 (string :tag "Drawer name"))))
3119 (defgroup org-export-translation nil
3120 "Options for translating special ascii sequences for the export backends."
3121 :tag "Org Export Translation"
3122 :group 'org-export)
3124 (defcustom org-export-with-emphasize t
3125 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3126 If the export target supports emphasizing text, the word will be
3127 typeset in bold, italic, or underlined, respectively. Works only for
3128 single words, but you can say: I *really* *mean* *this*.
3129 Not all export backends support this.
3131 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3132 :group 'org-export-translation
3133 :type 'boolean)
3135 (defcustom org-export-with-footnotes t
3136 "If nil, export [1] as a footnote marker.
3137 Lines starting with [1] will be formatted as footnotes.
3139 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3140 :group 'org-export-translation
3141 :type 'boolean)
3143 (defcustom org-export-with-sub-superscripts t
3144 "Non-nil means, interpret \"_\" and \"^\" for export.
3145 When this option is turned on, you can use TeX-like syntax for sub- and
3146 superscripts. Several characters after \"_\" or \"^\" will be
3147 considered as a single item - so grouping with {} is normally not
3148 needed. For example, the following things will be parsed as single
3149 sub- or superscripts.
3151 10^24 or 10^tau several digits will be considered 1 item.
3152 10^-12 or 10^-tau a leading sign with digits or a word
3153 x^2-y^3 will be read as x^2 - y^3, because items are
3154 terminated by almost any nonword/nondigit char.
3155 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3157 Still, ambiguity is possible - so when in doubt use {} to enclose the
3158 sub/superscript. If you set this variable to the symbol `{}',
3159 the braces are *required* in order to trigger interpretations as
3160 sub/superscript. This can be helpful in documents that need \"_\"
3161 frequently in plain text.
3163 Not all export backends support this, but HTML does.
3165 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3166 :group 'org-export-translation
3167 :type '(choice
3168 (const :tag "Always interpret" t)
3169 (const :tag "Only with braces" {})
3170 (const :tag "Never interpret" nil)))
3172 (defcustom org-export-with-special-strings t
3173 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3174 When this option is turned on, these strings will be exported as:
3176 \\- : &shy;
3177 -- : &ndash;
3178 --- : &mdash;
3180 Not all export backends support this, but HTML does.
3182 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3183 :group 'org-export-translation
3184 :type 'boolean)
3186 (defcustom org-export-with-TeX-macros t
3187 "Non-nil means, interpret simple TeX-like macros when exporting.
3188 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3189 No only real TeX macros will work here, but the standard HTML entities
3190 for math can be used as macro names as well. For a list of supported
3191 names in HTML export, see the constant `org-html-entities'.
3192 Not all export backends support this.
3194 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3195 :group 'org-export-translation
3196 :group 'org-export-latex
3197 :type 'boolean)
3199 (defcustom org-export-with-LaTeX-fragments nil
3200 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3201 When set, the exporter will find LaTeX environments if the \\begin line is
3202 the first non-white thing on a line. It will also find the math delimiters
3203 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3204 display math.
3206 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3207 :group 'org-export-translation
3208 :group 'org-export-latex
3209 :type 'boolean)
3211 (defcustom org-export-with-fixed-width t
3212 "Non-nil means, lines starting with \":\" will be in fixed width font.
3213 This can be used to have pre-formatted text, fragments of code etc. For
3214 example:
3215 : ;; Some Lisp examples
3216 : (while (defc cnt)
3217 : (ding))
3218 will be looking just like this in also HTML. See also the QUOTE keyword.
3219 Not all export backends support this.
3221 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3222 :group 'org-export-translation
3223 :type 'boolean)
3225 (defcustom org-match-sexp-depth 3
3226 "Number of stacked braces for sub/superscript matching.
3227 This has to be set before loading org.el to be effective."
3228 :group 'org-export-translation
3229 :type 'integer)
3231 (defgroup org-export-tables nil
3232 "Options for exporting tables in Org-mode."
3233 :tag "Org Export Tables"
3234 :group 'org-export)
3236 (defcustom org-export-with-tables t
3237 "If non-nil, lines starting with \"|\" define a table.
3238 For example:
3240 | Name | Address | Birthday |
3241 |-------------+----------+-----------|
3242 | Arthur Dent | England | 29.2.2100 |
3244 Not all export backends support this.
3246 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3247 :group 'org-export-tables
3248 :type 'boolean)
3250 (defcustom org-export-highlight-first-table-line t
3251 "Non-nil means, highlight the first table line.
3252 In HTML export, this means use <th> instead of <td>.
3253 In tables created with table.el, this applies to the first table line.
3254 In Org-mode tables, all lines before the first horizontal separator
3255 line will be formatted with <th> tags."
3256 :group 'org-export-tables
3257 :type 'boolean)
3259 (defcustom org-export-table-remove-special-lines t
3260 "Remove special lines and marking characters in calculating tables.
3261 This removes the special marking character column from tables that are set
3262 up for spreadsheet calculations. It also removes the entire lines
3263 marked with `!', `_', or `^'. The lines with `$' are kept, because
3264 the values of constants may be useful to have."
3265 :group 'org-export-tables
3266 :type 'boolean)
3268 (defcustom org-export-prefer-native-exporter-for-tables nil
3269 "Non-nil means, always export tables created with table.el natively.
3270 Natively means, use the HTML code generator in table.el.
3271 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3272 the table does not use row- or column-spanning). This has the
3273 advantage, that the automatic HTML conversions for math symbols and
3274 sub/superscripts can be applied. Org-mode's HTML generator is also
3275 much faster."
3276 :group 'org-export-tables
3277 :type 'boolean)
3279 (defgroup org-export-ascii nil
3280 "Options specific for ASCII export of Org-mode files."
3281 :tag "Org Export ASCII"
3282 :group 'org-export)
3284 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3285 "Characters for underlining headings in ASCII export.
3286 In the given sequence, these characters will be used for level 1, 2, ..."
3287 :group 'org-export-ascii
3288 :type '(repeat character))
3290 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3291 "Bullet characters for headlines converted to lists in ASCII export.
3292 The first character is is used for the first lest level generated in this
3293 way, and so on. If there are more levels than characters given here,
3294 the list will be repeated.
3295 Note that plain lists will keep the same bullets as the have in the
3296 Org-mode file."
3297 :group 'org-export-ascii
3298 :type '(repeat character))
3300 (defgroup org-export-xml nil
3301 "Options specific for XML export of Org-mode files."
3302 :tag "Org Export XML"
3303 :group 'org-export)
3305 (defgroup org-export-html nil
3306 "Options specific for HTML export of Org-mode files."
3307 :tag "Org Export HTML"
3308 :group 'org-export)
3310 (defcustom org-export-html-coding-system nil
3312 :group 'org-export-html
3313 :type 'coding-system)
3315 (defcustom org-export-html-extension "html"
3316 "The extension for exported HTML files."
3317 :group 'org-export-html
3318 :type 'string)
3320 (defcustom org-export-html-style
3321 "<style type=\"text/css\">
3322 html {
3323 font-family: Times, serif;
3324 font-size: 12pt;
3326 .title { text-align: center; }
3327 .todo { color: red; }
3328 .done { color: green; }
3329 .timestamp { color: grey }
3330 .timestamp-kwd { color: CadetBlue }
3331 .tag { background-color:lightblue; font-weight:normal }
3332 .target { background-color: lavender; }
3333 pre {
3334 border: 1pt solid #AEBDCC;
3335 background-color: #F3F5F7;
3336 padding: 5pt;
3337 font-family: courier, monospace;
3339 table { border-collapse: collapse; }
3340 td, th {
3341 vertical-align: top;
3342 <!--border: 1pt solid #ADB9CC;-->
3344 </style>"
3345 "The default style specification for exported HTML files.
3346 Since there are different ways of setting style information, this variable
3347 needs to contain the full HTML structure to provide a style, including the
3348 surrounding HTML tags. The style specifications should include definitions
3349 for new classes todo, done, title, and deadline. For example, legal values
3350 would be:
3352 <style type=\"text/css\">
3353 p { font-weight: normal; color: gray; }
3354 h1 { color: black; }
3355 .title { text-align: center; }
3356 .todo, .deadline { color: red; }
3357 .done { color: green; }
3358 </style>
3360 or, if you want to keep the style in a file,
3362 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3364 As the value of this option simply gets inserted into the HTML <head> header,
3365 you can \"misuse\" it to add arbitrary text to the header."
3366 :group 'org-export-html
3367 :type 'string)
3370 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3371 "Format for typesetting the document title in HTML export."
3372 :group 'org-export-html
3373 :type 'string)
3375 (defcustom org-export-html-toplevel-hlevel 2
3376 "The <H> level for level 1 headings in HTML export."
3377 :group 'org-export-html
3378 :type 'string)
3380 (defcustom org-export-html-link-org-files-as-html t
3381 "Non-nil means, make file links to `file.org' point to `file.html'.
3382 When org-mode is exporting an org-mode file to HTML, links to
3383 non-html files are directly put into a href tag in HTML.
3384 However, links to other Org-mode files (recognized by the
3385 extension `.org.) should become links to the corresponding html
3386 file, assuming that the linked org-mode file will also be
3387 converted to HTML.
3388 When nil, the links still point to the plain `.org' file."
3389 :group 'org-export-html
3390 :type 'boolean)
3392 (defcustom org-export-html-inline-images 'maybe
3393 "Non-nil means, inline images into exported HTML pages.
3394 This is done using an <img> tag. When nil, an anchor with href is used to
3395 link to the image. If this option is `maybe', then images in links with
3396 an empty description will be inlined, while images with a description will
3397 be linked only."
3398 :group 'org-export-html
3399 :type '(choice (const :tag "Never" nil)
3400 (const :tag "Always" t)
3401 (const :tag "When there is no description" maybe)))
3403 ;; FIXME: rename
3404 (defcustom org-export-html-expand t
3405 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3406 When nil, these tags will be exported as plain text and therefore
3407 not be interpreted by a browser.
3409 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3410 :group 'org-export-html
3411 :type 'boolean)
3413 (defcustom org-export-html-table-tag
3414 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3415 "The HTML tag that is used to start a table.
3416 This must be a <table> tag, but you may change the options like
3417 borders and spacing."
3418 :group 'org-export-html
3419 :type 'string)
3421 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3422 "The opening tag for table header fields.
3423 This is customizable so that alignment options can be specified."
3424 :group 'org-export-tables
3425 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3427 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3428 "The opening tag for table data fields.
3429 This is customizable so that alignment options can be specified."
3430 :group 'org-export-tables
3431 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3433 (defcustom org-export-html-with-timestamp nil
3434 "If non-nil, write `org-export-html-html-helper-timestamp'
3435 into the exported HTML text. Otherwise, the buffer will just be saved
3436 to a file."
3437 :group 'org-export-html
3438 :type 'boolean)
3440 (defcustom org-export-html-html-helper-timestamp
3441 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3442 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3443 :group 'org-export-html
3444 :type 'string)
3446 (defgroup org-export-icalendar nil
3447 "Options specific for iCalendar export of Org-mode files."
3448 :tag "Org Export iCalendar"
3449 :group 'org-export)
3451 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3452 "The file name for the iCalendar file covering all agenda files.
3453 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3454 The file name should be absolute, the file will be overwritten without warning."
3455 :group 'org-export-icalendar
3456 :type 'file)
3458 (defcustom org-icalendar-include-todo nil
3459 "Non-nil means, export to iCalendar files should also cover TODO items."
3460 :group 'org-export-icalendar
3461 :type '(choice
3462 (const :tag "None" nil)
3463 (const :tag "Unfinished" t)
3464 (const :tag "All" all)))
3466 (defcustom org-icalendar-include-sexps t
3467 "Non-nil means, export to iCalendar files should also cover sexp entries.
3468 These are entries like in the diary, but directly in an Org-mode file."
3469 :group 'org-export-icalendar
3470 :type 'boolean)
3472 (defcustom org-icalendar-include-body 100
3473 "Amount of text below headline to be included in iCalendar export.
3474 This is a number of characters that should maximally be included.
3475 Properties, scheduling and clocking lines will always be removed.
3476 The text will be inserted into the DESCRIPTION field."
3477 :group 'org-export-icalendar
3478 :type '(choice
3479 (const :tag "Nothing" nil)
3480 (const :tag "Everything" t)
3481 (integer :tag "Max characters")))
3483 (defcustom org-icalendar-combined-name "OrgMode"
3484 "Calendar name for the combined iCalendar representing all agenda files."
3485 :group 'org-export-icalendar
3486 :type 'string)
3488 (defgroup org-font-lock nil
3489 "Font-lock settings for highlighting in Org-mode."
3490 :tag "Org Font Lock"
3491 :group 'org)
3493 (defcustom org-level-color-stars-only nil
3494 "Non-nil means fontify only the stars in each headline.
3495 When nil, the entire headline is fontified.
3496 Changing it requires restart of `font-lock-mode' to become effective
3497 also in regions already fontified."
3498 :group 'org-font-lock
3499 :type 'boolean)
3501 (defcustom org-hide-leading-stars nil
3502 "Non-nil means, hide the first N-1 stars in a headline.
3503 This works by using the face `org-hide' for these stars. This
3504 face is white for a light background, and black for a dark
3505 background. You may have to customize the face `org-hide' to
3506 make this work.
3507 Changing it requires restart of `font-lock-mode' to become effective
3508 also in regions already fontified.
3509 You may also set this on a per-file basis by adding one of the following
3510 lines to the buffer:
3512 #+STARTUP: hidestars
3513 #+STARTUP: showstars"
3514 :group 'org-font-lock
3515 :type 'boolean)
3517 (defcustom org-fontify-done-headline nil
3518 "Non-nil means, change the face of a headline if it is marked DONE.
3519 Normally, only the TODO/DONE keyword indicates the state of a headline.
3520 When this is non-nil, the headline after the keyword is set to the
3521 `org-headline-done' as an additional indication."
3522 :group 'org-font-lock
3523 :type 'boolean)
3525 (defcustom org-fontify-emphasized-text t
3526 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3527 Changing this variable requires a restart of Emacs to take effect."
3528 :group 'org-font-lock
3529 :type 'boolean)
3531 (defcustom org-highlight-latex-fragments-and-specials nil
3532 "Non-nil means, fontify what is treated specially by the exporters."
3533 :group 'org-font-lock
3534 :type 'boolean)
3536 (defcustom org-hide-emphasis-markers nil
3537 "Non-nil mean font-lock should hide the emphasis marker characters."
3538 :group 'org-font-lock
3539 :type 'boolean)
3541 (defvar org-emph-re nil
3542 "Regular expression for matching emphasis.")
3543 (defvar org-verbatim-re nil
3544 "Regular expression for matching verbatim text.")
3545 (defvar org-emphasis-regexp-components) ; defined just below
3546 (defvar org-emphasis-alist) ; defined just below
3547 (defun org-set-emph-re (var val)
3548 "Set variable and compute the emphasis regular expression."
3549 (set var val)
3550 (when (and (boundp 'org-emphasis-alist)
3551 (boundp 'org-emphasis-regexp-components)
3552 org-emphasis-alist org-emphasis-regexp-components)
3553 (let* ((e org-emphasis-regexp-components)
3554 (pre (car e))
3555 (post (nth 1 e))
3556 (border (nth 2 e))
3557 (body (nth 3 e))
3558 (nl (nth 4 e))
3559 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3560 (body1 (concat body "*?"))
3561 (markers (mapconcat 'car org-emphasis-alist ""))
3562 (vmarkers (mapconcat
3563 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3564 org-emphasis-alist "")))
3565 ;; make sure special characters appear at the right position in the class
3566 (if (string-match "\\^" markers)
3567 (setq markers (concat (replace-match "" t t markers) "^")))
3568 (if (string-match "-" markers)
3569 (setq markers (concat (replace-match "" t t markers) "-")))
3570 (if (string-match "\\^" vmarkers)
3571 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3572 (if (string-match "-" vmarkers)
3573 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3574 (if (> nl 0)
3575 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3576 (int-to-string nl) "\\}")))
3577 ;; Make the regexp
3578 (setq org-emph-re
3579 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3580 "\\("
3581 "\\([" markers "]\\)"
3582 "\\("
3583 "[^" border "]\\|"
3584 "[^" border (if (and nil stacked) markers) "]"
3585 body1
3586 "[^" border (if (and nil stacked) markers) "]"
3587 "\\)"
3588 "\\3\\)"
3589 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3590 (setq org-verbatim-re
3591 (concat "\\([" pre "]\\|^\\)"
3592 "\\("
3593 "\\([" vmarkers "]\\)"
3594 "\\("
3595 "[^" border "]\\|"
3596 "[^" border "]"
3597 body1
3598 "[^" border "]"
3599 "\\)"
3600 "\\3\\)"
3601 "\\([" post "]\\|$\\)")))))
3603 (defcustom org-emphasis-regexp-components
3604 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3605 "Components used to build the regular expression for emphasis.
3606 This is a list with 6 entries. Terminology: In an emphasis string
3607 like \" *strong word* \", we call the initial space PREMATCH, the final
3608 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3609 and \"trong wor\" is the body. The different components in this variable
3610 specify what is allowed/forbidden in each part:
3612 pre Chars allowed as prematch. Beginning of line will be allowed too.
3613 post Chars allowed as postmatch. End of line will be allowed too.
3614 border The chars *forbidden* as border characters.
3615 body-regexp A regexp like \".\" to match a body character. Don't use
3616 non-shy groups here, and don't allow newline here.
3617 newline The maximum number of newlines allowed in an emphasis exp.
3619 Use customize to modify this, or restart Emacs after changing it."
3620 :group 'org-font-lock
3621 :set 'org-set-emph-re
3622 :type '(list
3623 (sexp :tag "Allowed chars in pre ")
3624 (sexp :tag "Allowed chars in post ")
3625 (sexp :tag "Forbidden chars in border ")
3626 (sexp :tag "Regexp for body ")
3627 (integer :tag "number of newlines allowed")
3628 (option (boolean :tag "Stacking (DISABLED) "))))
3630 (defcustom org-emphasis-alist
3631 '(("*" bold "<b>" "</b>")
3632 ("/" italic "<i>" "</i>")
3633 ("_" underline "<u>" "</u>")
3634 ("=" org-code "<code>" "</code>" verbatim)
3635 ("~" org-verbatim "" "" verbatim)
3636 ("+" (:strike-through t) "<del>" "</del>")
3638 "Special syntax for emphasized text.
3639 Text starting and ending with a special character will be emphasized, for
3640 example *bold*, _underlined_ and /italic/. This variable sets the marker
3641 characters, the face to be used by font-lock for highlighting in Org-mode
3642 Emacs buffers, and the HTML tags to be used for this.
3643 Use customize to modify this, or restart Emacs after changing it."
3644 :group 'org-font-lock
3645 :set 'org-set-emph-re
3646 :type '(repeat
3647 (list
3648 (string :tag "Marker character")
3649 (choice
3650 (face :tag "Font-lock-face")
3651 (plist :tag "Face property list"))
3652 (string :tag "HTML start tag")
3653 (string :tag "HTML end tag")
3654 (option (const verbatim)))))
3656 ;;; The faces
3658 (defgroup org-faces nil
3659 "Faces in Org-mode."
3660 :tag "Org Faces"
3661 :group 'org-font-lock)
3663 (defun org-compatible-face (inherits specs)
3664 "Make a compatible face specification.
3665 If INHERITS is an existing face and if the Emacs version supports it,
3666 just inherit the face. If not, use SPECS to define the face.
3667 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3668 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3669 to the top of the list. The `min-colors' attribute will be removed from
3670 any other entries, and any resulting duplicates will be removed entirely."
3671 (cond
3672 ((and inherits (facep inherits)
3673 (not (featurep 'xemacs)) (> emacs-major-version 22))
3674 ;; In Emacs 23, we use inheritance where possible.
3675 ;; We only do this in Emacs 23, because only there the outline
3676 ;; faces have been changed to the original org-mode-level-faces.
3677 (list (list t :inherit inherits)))
3678 ((or (featurep 'xemacs) (< emacs-major-version 22))
3679 ;; These do not understand the `min-colors' attribute.
3680 (let (r e a)
3681 (while (setq e (pop specs))
3682 (cond
3683 ((memq (car e) '(t default)) (push e r))
3684 ((setq a (member '(min-colors 8) (car e)))
3685 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3686 (cdr e)))))
3687 ((setq a (assq 'min-colors (car e)))
3688 (setq e (cons (delq a (car e)) (cdr e)))
3689 (or (assoc (car e) r) (push e r)))
3690 (t (or (assoc (car e) r) (push e r)))))
3691 (nreverse r)))
3692 (t specs)))
3693 (put 'org-compatible-face 'lisp-indent-function 1)
3695 (defface org-hide
3696 '((((background light)) (:foreground "white"))
3697 (((background dark)) (:foreground "black")))
3698 "Face used to hide leading stars in headlines.
3699 The forground color of this face should be equal to the background
3700 color of the frame."
3701 :group 'org-faces)
3703 (defface org-level-1 ;; font-lock-function-name-face
3704 (org-compatible-face 'outline-1
3705 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3706 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3707 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3708 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3709 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3710 (t (:bold t))))
3711 "Face used for level 1 headlines."
3712 :group 'org-faces)
3714 (defface org-level-2 ;; font-lock-variable-name-face
3715 (org-compatible-face 'outline-2
3716 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3717 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3718 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3719 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3720 (t (:bold t))))
3721 "Face used for level 2 headlines."
3722 :group 'org-faces)
3724 (defface org-level-3 ;; font-lock-keyword-face
3725 (org-compatible-face 'outline-3
3726 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3727 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3728 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3729 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3730 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3731 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3732 (t (:bold t))))
3733 "Face used for level 3 headlines."
3734 :group 'org-faces)
3736 (defface org-level-4 ;; font-lock-comment-face
3737 (org-compatible-face 'outline-4
3738 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3739 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3740 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3741 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3742 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3743 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3744 (t (:bold t))))
3745 "Face used for level 4 headlines."
3746 :group 'org-faces)
3748 (defface org-level-5 ;; font-lock-type-face
3749 (org-compatible-face 'outline-5
3750 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3751 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3752 (((class color) (min-colors 8)) (:foreground "green"))))
3753 "Face used for level 5 headlines."
3754 :group 'org-faces)
3756 (defface org-level-6 ;; font-lock-constant-face
3757 (org-compatible-face 'outline-6
3758 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3759 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3760 (((class color) (min-colors 8)) (:foreground "magenta"))))
3761 "Face used for level 6 headlines."
3762 :group 'org-faces)
3764 (defface org-level-7 ;; font-lock-builtin-face
3765 (org-compatible-face 'outline-7
3766 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3767 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3768 (((class color) (min-colors 8)) (:foreground "blue"))))
3769 "Face used for level 7 headlines."
3770 :group 'org-faces)
3772 (defface org-level-8 ;; font-lock-string-face
3773 (org-compatible-face 'outline-8
3774 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3775 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3776 (((class color) (min-colors 8)) (:foreground "green"))))
3777 "Face used for level 8 headlines."
3778 :group 'org-faces)
3780 (defface org-special-keyword ;; font-lock-string-face
3781 (org-compatible-face nil
3782 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3783 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3784 (t (:italic t))))
3785 "Face used for special keywords."
3786 :group 'org-faces)
3788 (defface org-drawer ;; font-lock-function-name-face
3789 (org-compatible-face nil
3790 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3791 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3792 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3793 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3794 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3795 (t (:bold t))))
3796 "Face used for drawers."
3797 :group 'org-faces)
3799 (defface org-property-value nil
3800 "Face used for the value of a property."
3801 :group 'org-faces)
3803 (defface org-column
3804 (org-compatible-face nil
3805 '((((class color) (min-colors 16) (background light))
3806 (:background "grey90"))
3807 (((class color) (min-colors 16) (background dark))
3808 (:background "grey30"))
3809 (((class color) (min-colors 8))
3810 (:background "cyan" :foreground "black"))
3811 (t (:inverse-video t))))
3812 "Face for column display of entry properties."
3813 :group 'org-faces)
3815 (when (fboundp 'set-face-attribute)
3816 ;; Make sure that a fixed-width face is used when we have a column table.
3817 (set-face-attribute 'org-column nil
3818 :height (face-attribute 'default :height)
3819 :family (face-attribute 'default :family)))
3821 (defface org-warning
3822 (org-compatible-face 'font-lock-warning-face
3823 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3824 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3825 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3826 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3827 (t (:bold t))))
3828 "Face for deadlines and TODO keywords."
3829 :group 'org-faces)
3831 (defface org-archived ; similar to shadow
3832 (org-compatible-face 'shadow
3833 '((((class color grayscale) (min-colors 88) (background light))
3834 (:foreground "grey50"))
3835 (((class color grayscale) (min-colors 88) (background dark))
3836 (:foreground "grey70"))
3837 (((class color) (min-colors 8) (background light))
3838 (:foreground "green"))
3839 (((class color) (min-colors 8) (background dark))
3840 (:foreground "yellow"))))
3841 "Face for headline with the ARCHIVE tag."
3842 :group 'org-faces)
3844 (defface org-link
3845 '((((class color) (background light)) (:foreground "Purple" :underline t))
3846 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3847 (t (:underline t)))
3848 "Face for links."
3849 :group 'org-faces)
3851 (defface org-ellipsis
3852 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3853 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3854 (t (:strike-through t)))
3855 "Face for the ellipsis in folded text."
3856 :group 'org-faces)
3858 (defface org-target
3859 '((((class color) (background light)) (:underline t))
3860 (((class color) (background dark)) (:underline t))
3861 (t (:underline t)))
3862 "Face for links."
3863 :group 'org-faces)
3865 (defface org-date
3866 '((((class color) (background light)) (:foreground "Purple" :underline t))
3867 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3868 (t (:underline t)))
3869 "Face for links."
3870 :group 'org-faces)
3872 (defface org-sexp-date
3873 '((((class color) (background light)) (:foreground "Purple"))
3874 (((class color) (background dark)) (:foreground "Cyan"))
3875 (t (:underline t)))
3876 "Face for links."
3877 :group 'org-faces)
3879 (defface org-tag
3880 '((t (:bold t)))
3881 "Face for tags."
3882 :group 'org-faces)
3884 (defface org-todo ; font-lock-warning-face
3885 (org-compatible-face nil
3886 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3887 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3888 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3889 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3890 (t (:inverse-video t :bold t))))
3891 "Face for TODO keywords."
3892 :group 'org-faces)
3894 (defface org-done ;; font-lock-type-face
3895 (org-compatible-face nil
3896 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3897 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3898 (((class color) (min-colors 8)) (:foreground "green"))
3899 (t (:bold t))))
3900 "Face used for todo keywords that indicate DONE items."
3901 :group 'org-faces)
3903 (defface org-headline-done ;; font-lock-string-face
3904 (org-compatible-face nil
3905 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3906 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3907 (((class color) (min-colors 8) (background light)) (:bold nil))))
3908 "Face used to indicate that a headline is DONE.
3909 This face is only used if `org-fontify-done-headline' is set. If applies
3910 to the part of the headline after the DONE keyword."
3911 :group 'org-faces)
3913 (defcustom org-todo-keyword-faces nil
3914 "Faces for specific TODO keywords.
3915 This is a list of cons cells, with TODO keywords in the car
3916 and faces in the cdr. The face can be a symbol, or a property
3917 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3918 :group 'org-faces
3919 :group 'org-todo
3920 :type '(repeat
3921 (cons
3922 (string :tag "keyword")
3923 (sexp :tag "face"))))
3925 (defface org-table ;; font-lock-function-name-face
3926 (org-compatible-face nil
3927 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3928 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3929 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3930 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3931 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3932 (((class color) (min-colors 8) (background dark)))))
3933 "Face used for tables."
3934 :group 'org-faces)
3936 (defface org-formula
3937 (org-compatible-face nil
3938 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3939 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3940 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3941 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3942 (t (:bold t :italic t))))
3943 "Face for formulas."
3944 :group 'org-faces)
3946 (defface org-code
3947 (org-compatible-face nil
3948 '((((class color grayscale) (min-colors 88) (background light))
3949 (:foreground "grey50"))
3950 (((class color grayscale) (min-colors 88) (background dark))
3951 (:foreground "grey70"))
3952 (((class color) (min-colors 8) (background light))
3953 (:foreground "green"))
3954 (((class color) (min-colors 8) (background dark))
3955 (:foreground "yellow"))))
3956 "Face for fixed-with text like code snippets."
3957 :group 'org-faces
3958 :version "22.1")
3960 (defface org-verbatim
3961 (org-compatible-face nil
3962 '((((class color grayscale) (min-colors 88) (background light))
3963 (:foreground "grey50" :underline t))
3964 (((class color grayscale) (min-colors 88) (background dark))
3965 (:foreground "grey70" :underline t))
3966 (((class color) (min-colors 8) (background light))
3967 (:foreground "green" :underline t))
3968 (((class color) (min-colors 8) (background dark))
3969 (:foreground "yellow" :underline t))))
3970 "Face for fixed-with text like code snippets."
3971 :group 'org-faces
3972 :version "22.1")
3974 (defface org-agenda-structure ;; font-lock-function-name-face
3975 (org-compatible-face nil
3976 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3977 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3978 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3979 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3980 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3981 (t (:bold t))))
3982 "Face used in agenda for captions and dates."
3983 :group 'org-faces)
3985 (defface org-scheduled-today
3986 (org-compatible-face nil
3987 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3988 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3989 (((class color) (min-colors 8)) (:foreground "green"))
3990 (t (:bold t :italic t))))
3991 "Face for items scheduled for a certain day."
3992 :group 'org-faces)
3994 (defface org-scheduled-previously
3995 (org-compatible-face nil
3996 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3997 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3998 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3999 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4000 (t (:bold t))))
4001 "Face for items scheduled previously, and not yet done."
4002 :group 'org-faces)
4004 (defface org-upcoming-deadline
4005 (org-compatible-face nil
4006 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4007 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4008 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4009 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4010 (t (:bold t))))
4011 "Face for items scheduled previously, and not yet done."
4012 :group 'org-faces)
4014 (defcustom org-agenda-deadline-faces
4015 '((1.0 . org-warning)
4016 (0.5 . org-upcoming-deadline)
4017 (0.0 . default))
4018 "Faces for showing deadlines in the agenda.
4019 This is a list of cons cells. The cdr of each cess is a face to be used,
4020 and it can also just be a like like '(:foreground \"yellow\").
4021 Each car is a fraction of the head-warning time that must have passed for
4022 this the face in the cdr to be used for display. The numbers must be
4023 given in descending order. The head-warning time is normally taken
4024 from `org-deadline-warning-days', but can also be specified in the deadline
4025 timestamp itself, like this:
4027 DEADLINE: <2007-08-13 Mon -8d>
4029 You may use d for days, w for weeks, m for months and y for years. Months
4030 and years will only be treated in an approximate fashion (30.4 days for a
4031 month and 365.24 days for a year)."
4032 :group 'org-faces
4033 :group 'org-agenda-daily/weekly
4034 :type '(repeat
4035 (cons
4036 (number :tag "Fraction of head-warning time passed")
4037 (sexp :tag "Face"))))
4039 ;; FIXME: this is not a good face yet.
4040 (defface org-agenda-restriction-lock
4041 (org-compatible-face nil
4042 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4043 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4044 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4045 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4046 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4047 (t (:inverse-video t))))
4048 "Face for showing the agenda restriction lock."
4049 :group 'org-faces)
4051 (defface org-time-grid ;; font-lock-variable-name-face
4052 (org-compatible-face nil
4053 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4054 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4055 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4056 "Face used for time grids."
4057 :group 'org-faces)
4059 (defconst org-level-faces
4060 '(org-level-1 org-level-2 org-level-3 org-level-4
4061 org-level-5 org-level-6 org-level-7 org-level-8
4064 (defcustom org-n-level-faces (length org-level-faces)
4065 "The number different faces to be used for headlines.
4066 Org-mode defines 8 different headline faces, so this can be at most 8.
4067 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4068 :type 'number
4069 :group 'org-faces)
4071 ;;; Functions and variables from ther packages
4072 ;; Declared here to avoid compiler warnings
4074 (eval-and-compile
4075 (unless (fboundp 'declare-function)
4076 (defmacro declare-function (fn file &optional arglist fileonly))))
4078 ;; XEmacs only
4079 (defvar outline-mode-menu-heading)
4080 (defvar outline-mode-menu-show)
4081 (defvar outline-mode-menu-hide)
4082 (defvar zmacs-regions) ; XEmacs regions
4084 ;; Emacs only
4085 (defvar mark-active)
4087 ;; Various packages
4088 ;; FIXME: get the argument lists for the UNKNOWN stuff
4089 (declare-function add-to-diary-list "diary-lib"
4090 (date string specifier &optional marker globcolor literal))
4091 (declare-function table--at-cell-p "table" (position &optional object at-column))
4092 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4093 (declare-function Info-goto-node "info" (nodename &optional fork))
4094 (declare-function bbdb "ext:bbdb-com" (string elidep))
4095 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4096 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4097 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4098 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4099 (declare-function bbdb-record-name "ext:bbdb" (record))
4100 (declare-function bibtex-beginning-of-entry "bibtex" ())
4101 (declare-function bibtex-generate-autokey "bibtex" ())
4102 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4103 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4104 (defvar calc-embedded-close-formula)
4105 (defvar calc-embedded-open-formula)
4106 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4107 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4108 (declare-function calendar-check-holidays "holidays" (date))
4109 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4110 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4111 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4112 (declare-function calendar-forward-day "cal-move" (arg))
4113 (declare-function calendar-french-date-string "cal-french" (&optional date))
4114 (declare-function calendar-goto-date "cal-move" (date))
4115 (declare-function calendar-goto-today "cal-move" ())
4116 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4117 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4118 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4119 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4120 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4121 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4122 (defvar calendar-mode-map)
4123 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4124 (declare-function cdlatex-tab "ext:cdlatex" ())
4125 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4126 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4127 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4128 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4129 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4130 (defvar font-lock-unfontify-region-function)
4131 (declare-function gnus-article-show-summary "gnus-art" ())
4132 (declare-function gnus-summary-last-subject "gnus-sum" ())
4133 (defvar gnus-other-frame-object)
4134 (defvar gnus-group-name)
4135 (defvar gnus-article-current)
4136 (defvar Info-current-file)
4137 (defvar Info-current-node)
4138 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4139 (declare-function mh-find-path "mh-utils" ())
4140 (declare-function mh-get-header-field "mh-utils" (field))
4141 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4142 (declare-function mh-header-display "mh-show" ())
4143 (declare-function mh-index-previous-folder "mh-search" ())
4144 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4145 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4146 (declare-function mh-search-choose "mh-search" (&optional searcher))
4147 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4148 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4149 (declare-function mh-show-header-display "mh-show" t t)
4150 (declare-function mh-show-msg "mh-show" (msg))
4151 (declare-function mh-show-show "mh-show" t t)
4152 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4153 (defvar mh-progs)
4154 (defvar mh-current-folder)
4155 (defvar mh-show-folder-buffer)
4156 (defvar mh-index-folder)
4157 (defvar mh-searcher)
4158 (declare-function org-export-latex-cleaned-string "org-export-latex" (&optional commentsp))
4159 (declare-function parse-time-string "parse-time" (string))
4160 (declare-function remember "remember" (&optional initial))
4161 (declare-function remember-buffer-desc "remember" ())
4162 (defvar remember-save-after-remembering)
4163 (defvar remember-data-file)
4164 (defvar remember-register)
4165 (defvar remember-buffer)
4166 (defvar remember-handler-functions)
4167 (defvar remember-annotation-functions)
4168 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4169 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4170 (declare-function rmail-what-message "rmail" ())
4171 (defvar texmathp-why)
4172 (declare-function vm-beginning-of-message "ext:vm-page" ())
4173 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4174 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4175 (declare-function vm-isearch-narrow "ext:vm-search" ())
4176 (declare-function vm-isearch-update "ext:vm-search" ())
4177 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4178 (declare-function vm-su-message-id "ext:vm-summary" (m))
4179 (declare-function vm-su-subject "ext:vm-summary" (m))
4180 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4181 (defvar vm-message-pointer)
4182 (defvar vm-folder-directory)
4183 (defvar w3m-current-url)
4184 (defvar w3m-current-title)
4185 ;; backward compatibility to old version of wl
4186 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4187 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4188 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4189 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4190 (declare-function wl-summary-line-from "ext:wl-summary" ())
4191 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4192 (declare-function wl-summary-message-number "ext:wl-summary" ())
4193 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4194 (defvar wl-summary-buffer-elmo-folder)
4195 (defvar wl-summary-buffer-folder-name)
4196 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4198 (defvar org-latex-regexps)
4199 (defvar constants-unit-system)
4201 ;;; Variables for pre-computed regular expressions, all buffer local
4203 (defvar org-drawer-regexp nil
4204 "Matches first line of a hidden block.")
4205 (make-variable-buffer-local 'org-drawer-regexp)
4206 (defvar org-todo-regexp nil
4207 "Matches any of the TODO state keywords.")
4208 (make-variable-buffer-local 'org-todo-regexp)
4209 (defvar org-not-done-regexp nil
4210 "Matches any of the TODO state keywords except the last one.")
4211 (make-variable-buffer-local 'org-not-done-regexp)
4212 (defvar org-todo-line-regexp nil
4213 "Matches a headline and puts TODO state into group 2 if present.")
4214 (make-variable-buffer-local 'org-todo-line-regexp)
4215 (defvar org-complex-heading-regexp nil
4216 "Matches a headline and puts everything into groups:
4217 group 1: the stars
4218 group 2: The todo keyword, maybe
4219 group 3: Priority cookie
4220 group 4: True headline
4221 group 5: Tags")
4222 (make-variable-buffer-local 'org-complex-heading-regexp)
4223 (defvar org-todo-line-tags-regexp nil
4224 "Matches a headline and puts TODO state into group 2 if present.
4225 Also put tags into group 4 if tags are present.")
4226 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4227 (defvar org-nl-done-regexp nil
4228 "Matches newline followed by a headline with the DONE keyword.")
4229 (make-variable-buffer-local 'org-nl-done-regexp)
4230 (defvar org-looking-at-done-regexp nil
4231 "Matches the DONE keyword a point.")
4232 (make-variable-buffer-local 'org-looking-at-done-regexp)
4233 (defvar org-ds-keyword-length 12
4234 "Maximum length of the Deadline and SCHEDULED keywords.")
4235 (make-variable-buffer-local 'org-ds-keyword-length)
4236 (defvar org-deadline-regexp nil
4237 "Matches the DEADLINE keyword.")
4238 (make-variable-buffer-local 'org-deadline-regexp)
4239 (defvar org-deadline-time-regexp nil
4240 "Matches the DEADLINE keyword together with a time stamp.")
4241 (make-variable-buffer-local 'org-deadline-time-regexp)
4242 (defvar org-deadline-line-regexp nil
4243 "Matches the DEADLINE keyword and the rest of the line.")
4244 (make-variable-buffer-local 'org-deadline-line-regexp)
4245 (defvar org-scheduled-regexp nil
4246 "Matches the SCHEDULED keyword.")
4247 (make-variable-buffer-local 'org-scheduled-regexp)
4248 (defvar org-scheduled-time-regexp nil
4249 "Matches the SCHEDULED keyword together with a time stamp.")
4250 (make-variable-buffer-local 'org-scheduled-time-regexp)
4251 (defvar org-closed-time-regexp nil
4252 "Matches the CLOSED keyword together with a time stamp.")
4253 (make-variable-buffer-local 'org-closed-time-regexp)
4255 (defvar org-keyword-time-regexp nil
4256 "Matches any of the 4 keywords, together with the time stamp.")
4257 (make-variable-buffer-local 'org-keyword-time-regexp)
4258 (defvar org-keyword-time-not-clock-regexp nil
4259 "Matches any of the 3 keywords, together with the time stamp.")
4260 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4261 (defvar org-maybe-keyword-time-regexp nil
4262 "Matches a timestamp, possibly preceeded by a keyword.")
4263 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4264 (defvar org-planning-or-clock-line-re nil
4265 "Matches a line with planning or clock info.")
4266 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4268 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4269 rear-nonsticky t mouse-map t fontified t)
4270 "Properties to remove when a string without properties is wanted.")
4272 (defsubst org-match-string-no-properties (num &optional string)
4273 (if (featurep 'xemacs)
4274 (let ((s (match-string num string)))
4275 (remove-text-properties 0 (length s) org-rm-props s)
4277 (match-string-no-properties num string)))
4279 (defsubst org-no-properties (s)
4280 (if (fboundp 'set-text-properties)
4281 (set-text-properties 0 (length s) nil s)
4282 (remove-text-properties 0 (length s) org-rm-props s))
4285 (defsubst org-get-alist-option (option key)
4286 (cond ((eq key t) t)
4287 ((eq option t) t)
4288 ((assoc key option) (cdr (assoc key option)))
4289 (t (cdr (assq 'default option)))))
4291 (defsubst org-inhibit-invisibility ()
4292 "Modified `buffer-invisibility-spec' for Emacs 21.
4293 Some ops with invisible text do not work correctly on Emacs 21. For these
4294 we turn off invisibility temporarily. Use this in a `let' form."
4295 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4297 (defsubst org-set-local (var value)
4298 "Make VAR local in current buffer and set it to VALUE."
4299 (set (make-variable-buffer-local var) value))
4301 (defsubst org-mode-p ()
4302 "Check if the current buffer is in Org-mode."
4303 (eq major-mode 'org-mode))
4305 (defsubst org-last (list)
4306 "Return the last element of LIST."
4307 (car (last list)))
4309 (defun org-let (list &rest body)
4310 (eval (cons 'let (cons list body))))
4311 (put 'org-let 'lisp-indent-function 1)
4313 (defun org-let2 (list1 list2 &rest body)
4314 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4315 (put 'org-let2 'lisp-indent-function 2)
4316 (defconst org-startup-options
4317 '(("fold" org-startup-folded t)
4318 ("overview" org-startup-folded t)
4319 ("nofold" org-startup-folded nil)
4320 ("showall" org-startup-folded nil)
4321 ("content" org-startup-folded content)
4322 ("hidestars" org-hide-leading-stars t)
4323 ("showstars" org-hide-leading-stars nil)
4324 ("odd" org-odd-levels-only t)
4325 ("oddeven" org-odd-levels-only nil)
4326 ("align" org-startup-align-all-tables t)
4327 ("noalign" org-startup-align-all-tables nil)
4328 ("customtime" org-display-custom-times t)
4329 ("logging" org-log-done t)
4330 ("logdone" org-log-done t)
4331 ("nologging" org-log-done nil)
4332 ("lognotedone" org-log-done done push)
4333 ("lognotestate" org-log-done state push)
4334 ("lognoteclock-out" org-log-done clock-out push)
4335 ("logrepeat" org-log-repeat t)
4336 ("nologrepeat" org-log-repeat nil)
4337 ("constcgs" constants-unit-system cgs)
4338 ("constSI" constants-unit-system SI))
4339 "Variable associated with STARTUP options for org-mode.
4340 Each element is a list of three items: The startup options as written
4341 in the #+STARTUP line, the corresponding variable, and the value to
4342 set this variable to if the option is found. An optional forth element PUSH
4343 means to push this value onto the list in the variable.")
4345 (defun org-set-regexps-and-options ()
4346 "Precompute regular expressions for current buffer."
4347 (when (org-mode-p)
4348 (org-set-local 'org-todo-kwd-alist nil)
4349 (org-set-local 'org-todo-key-alist nil)
4350 (org-set-local 'org-todo-key-trigger nil)
4351 (org-set-local 'org-todo-keywords-1 nil)
4352 (org-set-local 'org-done-keywords nil)
4353 (org-set-local 'org-todo-heads nil)
4354 (org-set-local 'org-todo-sets nil)
4355 (org-set-local 'org-todo-log-states nil)
4356 (let ((re (org-make-options-regexp
4357 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4358 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4359 "CONSTANTS" "PROPERTY" "DRAWERS")))
4360 (splitre "[ \t]+")
4361 kwds kws0 kwsa key value cat arch tags const links hw dws
4362 tail sep kws1 prio props drawers
4363 ex log)
4364 (save-excursion
4365 (save-restriction
4366 (widen)
4367 (goto-char (point-min))
4368 (while (re-search-forward re nil t)
4369 (setq key (match-string 1) value (org-match-string-no-properties 2))
4370 (cond
4371 ((equal key "CATEGORY")
4372 (if (string-match "[ \t]+$" value)
4373 (setq value (replace-match "" t t value)))
4374 (setq cat value))
4375 ((member key '("SEQ_TODO" "TODO"))
4376 (push (cons 'sequence (org-split-string value splitre)) kwds))
4377 ((equal key "TYP_TODO")
4378 (push (cons 'type (org-split-string value splitre)) kwds))
4379 ((equal key "TAGS")
4380 (setq tags (append tags (org-split-string value splitre))))
4381 ((equal key "COLUMNS")
4382 (org-set-local 'org-columns-default-format value))
4383 ((equal key "LINK")
4384 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4385 (push (cons (match-string 1 value)
4386 (org-trim (match-string 2 value)))
4387 links)))
4388 ((equal key "PRIORITIES")
4389 (setq prio (org-split-string value " +")))
4390 ((equal key "PROPERTY")
4391 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4392 (push (cons (match-string 1 value) (match-string 2 value))
4393 props)))
4394 ((equal key "DRAWERS")
4395 (setq drawers (org-split-string value splitre)))
4396 ((equal key "CONSTANTS")
4397 (setq const (append const (org-split-string value splitre))))
4398 ((equal key "STARTUP")
4399 (let ((opts (org-split-string value splitre))
4400 l var val)
4401 (while (setq l (pop opts))
4402 (when (setq l (assoc l org-startup-options))
4403 (setq var (nth 1 l) val (nth 2 l))
4404 (if (not (nth 3 l))
4405 (set (make-local-variable var) val)
4406 (if (not (listp (symbol-value var)))
4407 (set (make-local-variable var) nil))
4408 (set (make-local-variable var) (symbol-value var))
4409 (add-to-list var val))))))
4410 ((equal key "ARCHIVE")
4411 (string-match " *$" value)
4412 (setq arch (replace-match "" t t value))
4413 (remove-text-properties 0 (length arch)
4414 '(face t fontified t) arch)))
4416 (when cat
4417 (org-set-local 'org-category (intern cat))
4418 (push (cons "CATEGORY" cat) props))
4419 (when prio
4420 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4421 (setq prio (mapcar 'string-to-char prio))
4422 (org-set-local 'org-highest-priority (nth 0 prio))
4423 (org-set-local 'org-lowest-priority (nth 1 prio))
4424 (org-set-local 'org-default-priority (nth 2 prio)))
4425 (and props (org-set-local 'org-local-properties (nreverse props)))
4426 (and drawers (org-set-local 'org-drawers drawers))
4427 (and arch (org-set-local 'org-archive-location arch))
4428 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4429 ;; Process the TODO keywords
4430 (unless kwds
4431 ;; Use the global values as if they had been given locally.
4432 (setq kwds (default-value 'org-todo-keywords))
4433 (if (stringp (car kwds))
4434 (setq kwds (list (cons org-todo-interpretation
4435 (default-value 'org-todo-keywords)))))
4436 (setq kwds (reverse kwds)))
4437 (setq kwds (nreverse kwds))
4438 (let (inter kws kw)
4439 (while (setq kws (pop kwds))
4440 (setq inter (pop kws) sep (member "|" kws)
4441 kws0 (delete "|" (copy-sequence kws))
4442 kwsa nil
4443 kws1 (mapcar
4444 (lambda (x)
4445 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4446 (progn
4447 (setq kw (match-string 1 x)
4448 ex (and (match-end 2) (match-string 2 x))
4449 log (and ex (string-match "@" ex))
4450 key (and ex (substring ex 0 1)))
4451 (if (equal key "@") (setq key nil))
4452 (push (cons kw (and key (string-to-char key))) kwsa)
4453 (and log (push kw org-todo-log-states))
4455 (error "Invalid TODO keyword %s" x)))
4456 kws0)
4457 kwsa (if kwsa (append '((:startgroup))
4458 (nreverse kwsa)
4459 '((:endgroup))))
4460 hw (car kws1)
4461 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4462 tail (list inter hw (car dws) (org-last dws)))
4463 (add-to-list 'org-todo-heads hw 'append)
4464 (push kws1 org-todo-sets)
4465 (setq org-done-keywords (append org-done-keywords dws nil))
4466 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4467 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4468 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4469 (setq org-todo-sets (nreverse org-todo-sets)
4470 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4471 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4472 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4473 ;; Process the constants
4474 (when const
4475 (let (e cst)
4476 (while (setq e (pop const))
4477 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4478 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4479 (setq org-table-formula-constants-local cst)))
4481 ;; Process the tags.
4482 (when tags
4483 (let (e tgs)
4484 (while (setq e (pop tags))
4485 (cond
4486 ((equal e "{") (push '(:startgroup) tgs))
4487 ((equal e "}") (push '(:endgroup) tgs))
4488 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4489 (push (cons (match-string 1 e)
4490 (string-to-char (match-string 2 e)))
4491 tgs))
4492 (t (push (list e) tgs))))
4493 (org-set-local 'org-tag-alist nil)
4494 (while (setq e (pop tgs))
4495 (or (and (stringp (car e))
4496 (assoc (car e) org-tag-alist))
4497 (push e org-tag-alist))))))
4499 ;; Compute the regular expressions and other local variables
4500 (if (not org-done-keywords)
4501 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4502 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4503 (length org-scheduled-string)))
4504 org-drawer-regexp
4505 (concat "^[ \t]*:\\("
4506 (mapconcat 'regexp-quote org-drawers "\\|")
4507 "\\):[ \t]*$")
4508 org-not-done-keywords
4509 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4510 org-todo-regexp
4511 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4512 "\\|") "\\)\\>")
4513 org-not-done-regexp
4514 (concat "\\<\\("
4515 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4516 "\\)\\>")
4517 org-todo-line-regexp
4518 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4519 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4520 "\\)\\>\\)?[ \t]*\\(.*\\)")
4521 org-complex-heading-regexp
4522 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4523 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4524 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4525 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4526 org-nl-done-regexp
4527 (concat "\n\\*+[ \t]+"
4528 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4529 "\\)" "\\>")
4530 org-todo-line-tags-regexp
4531 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4532 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4533 (org-re
4534 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4535 org-looking-at-done-regexp
4536 (concat "^" "\\(?:"
4537 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4538 "\\>")
4539 org-deadline-regexp (concat "\\<" org-deadline-string)
4540 org-deadline-time-regexp
4541 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4542 org-deadline-line-regexp
4543 (concat "\\<\\(" org-deadline-string "\\).*")
4544 org-scheduled-regexp
4545 (concat "\\<" org-scheduled-string)
4546 org-scheduled-time-regexp
4547 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4548 org-closed-time-regexp
4549 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4550 org-keyword-time-regexp
4551 (concat "\\<\\(" org-scheduled-string
4552 "\\|" org-deadline-string
4553 "\\|" org-closed-string
4554 "\\|" org-clock-string "\\)"
4555 " *[[<]\\([^]>]+\\)[]>]")
4556 org-keyword-time-not-clock-regexp
4557 (concat "\\<\\(" org-scheduled-string
4558 "\\|" org-deadline-string
4559 "\\|" org-closed-string
4560 "\\)"
4561 " *[[<]\\([^]>]+\\)[]>]")
4562 org-maybe-keyword-time-regexp
4563 (concat "\\(\\<\\(" org-scheduled-string
4564 "\\|" org-deadline-string
4565 "\\|" org-closed-string
4566 "\\|" org-clock-string "\\)\\)?"
4567 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4568 org-planning-or-clock-line-re
4569 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4570 "\\|" org-deadline-string
4571 "\\|" org-closed-string "\\|" org-clock-string
4572 "\\)\\>\\)")
4574 (org-compute-latex-and-specials-regexp)
4575 (org-set-font-lock-defaults)))
4577 (defun org-remove-keyword-keys (list)
4578 (mapcar (lambda (x)
4579 (if (string-match "(..?)$" x)
4580 (substring x 0 (match-beginning 0))
4582 list))
4584 ;; FIXME: this could be done much better, using second characters etc.
4585 (defun org-assign-fast-keys (alist)
4586 "Assign fast keys to a keyword-key alist.
4587 Respect keys that are already there."
4588 (let (new e k c c1 c2 (char ?a))
4589 (while (setq e (pop alist))
4590 (cond
4591 ((equal e '(:startgroup)) (push e new))
4592 ((equal e '(:endgroup)) (push e new))
4594 (setq k (car e) c2 nil)
4595 (if (cdr e)
4596 (setq c (cdr e))
4597 ;; automatically assign a character.
4598 (setq c1 (string-to-char
4599 (downcase (substring
4600 k (if (= (string-to-char k) ?@) 1 0)))))
4601 (if (or (rassoc c1 new) (rassoc c1 alist))
4602 (while (or (rassoc char new) (rassoc char alist))
4603 (setq char (1+ char)))
4604 (setq c2 c1))
4605 (setq c (or c2 char)))
4606 (push (cons k c) new))))
4607 (nreverse new)))
4609 ;;; Some variables ujsed in various places
4611 (defvar org-window-configuration nil
4612 "Used in various places to store a window configuration.")
4613 (defvar org-finish-function nil
4614 "Function to be called when `C-c C-c' is used.
4615 This is for getting out of special buffers like remember.")
4618 ;; FIXME: Occasionally check by commenting these, to make sure
4619 ;; no other functions uses these, forgetting to let-bind them.
4620 (defvar entry)
4621 (defvar state)
4622 (defvar last-state)
4623 (defvar date)
4624 (defvar description)
4626 ;; Defined somewhere in this file, but used before definition.
4627 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4628 (defvar org-agenda-buffer-name)
4629 (defvar org-agenda-undo-list)
4630 (defvar org-agenda-pending-undo-list)
4631 (defvar org-agenda-overriding-header)
4632 (defvar orgtbl-mode)
4633 (defvar org-html-entities)
4634 (defvar org-struct-menu)
4635 (defvar org-org-menu)
4636 (defvar org-tbl-menu)
4637 (defvar org-agenda-keymap)
4639 ;;;; Emacs/XEmacs compatibility
4641 ;; Overlay compatibility functions
4642 (defun org-make-overlay (beg end &optional buffer)
4643 (if (featurep 'xemacs)
4644 (make-extent beg end buffer)
4645 (make-overlay beg end buffer)))
4646 (defun org-delete-overlay (ovl)
4647 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4648 (defun org-detach-overlay (ovl)
4649 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4650 (defun org-move-overlay (ovl beg end &optional buffer)
4651 (if (featurep 'xemacs)
4652 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4653 (move-overlay ovl beg end buffer)))
4654 (defun org-overlay-put (ovl prop value)
4655 (if (featurep 'xemacs)
4656 (set-extent-property ovl prop value)
4657 (overlay-put ovl prop value)))
4658 (defun org-overlay-display (ovl text &optional face evap)
4659 "Make overlay OVL display TEXT with face FACE."
4660 (if (featurep 'xemacs)
4661 (let ((gl (make-glyph text)))
4662 (and face (set-glyph-face gl face))
4663 (set-extent-property ovl 'invisible t)
4664 (set-extent-property ovl 'end-glyph gl))
4665 (overlay-put ovl 'display text)
4666 (if face (overlay-put ovl 'face face))
4667 (if evap (overlay-put ovl 'evaporate t))))
4668 (defun org-overlay-before-string (ovl text &optional face evap)
4669 "Make overlay OVL display TEXT with face FACE."
4670 (if (featurep 'xemacs)
4671 (let ((gl (make-glyph text)))
4672 (and face (set-glyph-face gl face))
4673 (set-extent-property ovl 'begin-glyph gl))
4674 (if face (org-add-props text nil 'face face))
4675 (overlay-put ovl 'before-string text)
4676 (if evap (overlay-put ovl 'evaporate t))))
4677 (defun org-overlay-get (ovl prop)
4678 (if (featurep 'xemacs)
4679 (extent-property ovl prop)
4680 (overlay-get ovl prop)))
4681 (defun org-overlays-at (pos)
4682 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4683 (defun org-overlays-in (&optional start end)
4684 (if (featurep 'xemacs)
4685 (extent-list nil start end)
4686 (overlays-in start end)))
4687 (defun org-overlay-start (o)
4688 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4689 (defun org-overlay-end (o)
4690 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4691 (defun org-find-overlays (prop &optional pos delete)
4692 "Find all overlays specifying PROP at POS or point.
4693 If DELETE is non-nil, delete all those overlays."
4694 (let ((overlays (org-overlays-at (or pos (point))))
4695 ov found)
4696 (while (setq ov (pop overlays))
4697 (if (org-overlay-get ov prop)
4698 (if delete (org-delete-overlay ov) (push ov found))))
4699 found))
4701 ;; Region compatibility
4703 (defun org-add-hook (hook function &optional append local)
4704 "Add-hook, compatible with both Emacsen."
4705 (if (and local (featurep 'xemacs))
4706 (add-local-hook hook function append)
4707 (add-hook hook function append local)))
4709 (defvar org-ignore-region nil
4710 "To temporarily disable the active region.")
4712 (defun org-region-active-p ()
4713 "Is `transient-mark-mode' on and the region active?
4714 Works on both Emacs and XEmacs."
4715 (if org-ignore-region
4717 (if (featurep 'xemacs)
4718 (and zmacs-regions (region-active-p))
4719 (if (fboundp 'use-region-p)
4720 (use-region-p)
4721 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4723 ;; Invisibility compatibility
4725 (defun org-add-to-invisibility-spec (arg)
4726 "Add elements to `buffer-invisibility-spec'.
4727 See documentation for `buffer-invisibility-spec' for the kind of elements
4728 that can be added."
4729 (cond
4730 ((fboundp 'add-to-invisibility-spec)
4731 (add-to-invisibility-spec arg))
4732 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4733 (setq buffer-invisibility-spec (list arg)))
4735 (setq buffer-invisibility-spec
4736 (cons arg buffer-invisibility-spec)))))
4738 (defun org-remove-from-invisibility-spec (arg)
4739 "Remove elements from `buffer-invisibility-spec'."
4740 (if (fboundp 'remove-from-invisibility-spec)
4741 (remove-from-invisibility-spec arg)
4742 (if (consp buffer-invisibility-spec)
4743 (setq buffer-invisibility-spec
4744 (delete arg buffer-invisibility-spec)))))
4746 (defun org-in-invisibility-spec-p (arg)
4747 "Is ARG a member of `buffer-invisibility-spec'?"
4748 (if (consp buffer-invisibility-spec)
4749 (member arg buffer-invisibility-spec)
4750 nil))
4752 ;;;; Define the Org-mode
4754 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4755 (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."))
4758 ;; We use a before-change function to check if a table might need
4759 ;; an update.
4760 (defvar org-table-may-need-update t
4761 "Indicates that a table might need an update.
4762 This variable is set by `org-before-change-function'.
4763 `org-table-align' sets it back to nil.")
4764 (defvar org-mode-map)
4765 (defvar org-mode-hook nil)
4766 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4767 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4768 (defvar org-table-buffer-is-an nil)
4769 (defconst org-outline-regexp "\\*+ ")
4771 ;;;###autoload
4772 (define-derived-mode org-mode outline-mode "Org"
4773 "Outline-based notes management and organizer, alias
4774 \"Carsten's outline-mode for keeping track of everything.\"
4776 Org-mode develops organizational tasks around a NOTES file which
4777 contains information about projects as plain text. Org-mode is
4778 implemented on top of outline-mode, which is ideal to keep the content
4779 of large files well structured. It supports ToDo items, deadlines and
4780 time stamps, which magically appear in the diary listing of the Emacs
4781 calendar. Tables are easily created with a built-in table editor.
4782 Plain text URL-like links connect to websites, emails (VM), Usenet
4783 messages (Gnus), BBDB entries, and any files related to the project.
4784 For printing and sharing of notes, an Org-mode file (or a part of it)
4785 can be exported as a structured ASCII or HTML file.
4787 The following commands are available:
4789 \\{org-mode-map}"
4791 ;; Get rid of Outline menus, they are not needed
4792 ;; Need to do this here because define-derived-mode sets up
4793 ;; the keymap so late. Still, it is a waste to call this each time
4794 ;; we switch another buffer into org-mode.
4795 (if (featurep 'xemacs)
4796 (when (boundp 'outline-mode-menu-heading)
4797 ;; Assume this is Greg's port, it used easymenu
4798 (easy-menu-remove outline-mode-menu-heading)
4799 (easy-menu-remove outline-mode-menu-show)
4800 (easy-menu-remove outline-mode-menu-hide))
4801 (define-key org-mode-map [menu-bar headings] 'undefined)
4802 (define-key org-mode-map [menu-bar hide] 'undefined)
4803 (define-key org-mode-map [menu-bar show] 'undefined))
4805 (easy-menu-add org-org-menu)
4806 (easy-menu-add org-tbl-menu)
4807 (org-install-agenda-files-menu)
4808 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4809 (org-add-to-invisibility-spec '(org-cwidth))
4810 (when (featurep 'xemacs)
4811 (org-set-local 'line-move-ignore-invisible t))
4812 (org-set-local 'outline-regexp org-outline-regexp)
4813 (org-set-local 'outline-level 'org-outline-level)
4814 (when (and org-ellipsis
4815 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4816 (fboundp 'make-glyph-code))
4817 (unless org-display-table
4818 (setq org-display-table (make-display-table)))
4819 (set-display-table-slot
4820 org-display-table 4
4821 (vconcat (mapcar
4822 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4823 org-ellipsis)))
4824 (if (stringp org-ellipsis) org-ellipsis "..."))))
4825 (setq buffer-display-table org-display-table))
4826 (org-set-regexps-and-options)
4827 ;; Calc embedded
4828 (org-set-local 'calc-embedded-open-mode "# ")
4829 (modify-syntax-entry ?# "<")
4830 (modify-syntax-entry ?@ "w")
4831 (if org-startup-truncated (setq truncate-lines t))
4832 (org-set-local 'font-lock-unfontify-region-function
4833 'org-unfontify-region)
4834 ;; Activate before-change-function
4835 (org-set-local 'org-table-may-need-update t)
4836 (org-add-hook 'before-change-functions 'org-before-change-function nil
4837 'local)
4838 ;; Check for running clock before killing a buffer
4839 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4840 ;; Paragraphs and auto-filling
4841 (org-set-autofill-regexps)
4842 (setq indent-line-function 'org-indent-line-function)
4843 (org-update-radio-target-regexp)
4845 ;; Comment characters
4846 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4847 (org-set-local 'comment-padding " ")
4849 ;; Imenu
4850 (org-set-local 'imenu-create-index-function
4851 'org-imenu-get-tree)
4853 ;; Make isearch reveal context
4854 (if (or (featurep 'xemacs)
4855 (not (boundp 'outline-isearch-open-invisible-function)))
4856 ;; Emacs 21 and XEmacs make use of the hook
4857 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4858 ;; Emacs 22 deals with this through a special variable
4859 (org-set-local 'outline-isearch-open-invisible-function
4860 (lambda (&rest ignore) (org-show-context 'isearch))))
4862 ;; If empty file that did not turn on org-mode automatically, make it to.
4863 (if (and org-insert-mode-line-in-empty-file
4864 (interactive-p)
4865 (= (point-min) (point-max)))
4866 (insert "# -*- mode: org -*-\n\n"))
4868 (unless org-inhibit-startup
4869 (when org-startup-align-all-tables
4870 (let ((bmp (buffer-modified-p)))
4871 (org-table-map-tables 'org-table-align)
4872 (set-buffer-modified-p bmp)))
4873 (org-cycle-hide-drawers 'all)
4874 (cond
4875 ((eq org-startup-folded t)
4876 (org-cycle '(4)))
4877 ((eq org-startup-folded 'content)
4878 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4879 (org-cycle '(4)) (org-cycle '(4)))))))
4881 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4883 (defsubst org-call-with-arg (command arg)
4884 "Call COMMAND interactively, but pretend prefix are was ARG."
4885 (let ((current-prefix-arg arg)) (call-interactively command)))
4887 (defsubst org-current-line (&optional pos)
4888 (save-excursion
4889 (and pos (goto-char pos))
4890 ;; works also in narrowed buffer, because we start at 1, not point-min
4891 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4893 (defun org-current-time ()
4894 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4895 (if (> org-time-stamp-rounding-minutes 0)
4896 (let ((r org-time-stamp-rounding-minutes)
4897 (time (decode-time)))
4898 (apply 'encode-time
4899 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4900 (nthcdr 2 time))))
4901 (current-time)))
4903 (defun org-add-props (string plist &rest props)
4904 "Add text properties to entire string, from beginning to end.
4905 PLIST may be a list of properties, PROPS are individual properties and values
4906 that will be added to PLIST. Returns the string that was modified."
4907 (add-text-properties
4908 0 (length string) (if props (append plist props) plist) string)
4909 string)
4910 (put 'org-add-props 'lisp-indent-function 2)
4913 ;;;; Font-Lock stuff, including the activators
4915 (defvar org-mouse-map (make-sparse-keymap))
4916 (org-defkey org-mouse-map
4917 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4918 (org-defkey org-mouse-map
4919 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4920 (when org-mouse-1-follows-link
4921 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4922 (when org-tab-follows-link
4923 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4924 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4925 (when org-return-follows-link
4926 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4927 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4929 (require 'font-lock)
4931 (defconst org-non-link-chars "]\t\n\r<>")
4932 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4933 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4934 (defvar org-link-re-with-space nil
4935 "Matches a link with spaces, optional angular brackets around it.")
4936 (defvar org-link-re-with-space2 nil
4937 "Matches a link with spaces, optional angular brackets around it.")
4938 (defvar org-angle-link-re nil
4939 "Matches link with angular brackets, spaces are allowed.")
4940 (defvar org-plain-link-re nil
4941 "Matches plain link, without spaces.")
4942 (defvar org-bracket-link-regexp nil
4943 "Matches a link in double brackets.")
4944 (defvar org-bracket-link-analytic-regexp nil
4945 "Regular expression used to analyze links.
4946 Here is what the match groups contain after a match:
4947 1: http:
4948 2: http
4949 3: path
4950 4: [desc]
4951 5: desc")
4952 (defvar org-any-link-re nil
4953 "Regular expression matching any link.")
4955 (defun org-make-link-regexps ()
4956 "Update the link regular expressions.
4957 This should be called after the variable `org-link-types' has changed."
4958 (setq org-link-re-with-space
4959 (concat
4960 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4961 "\\([^" org-non-link-chars " ]"
4962 "[^" org-non-link-chars "]*"
4963 "[^" org-non-link-chars " ]\\)>?")
4964 org-link-re-with-space2
4965 (concat
4966 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4967 "\\([^" org-non-link-chars " ]"
4968 "[^]\t\n\r]*"
4969 "[^" org-non-link-chars " ]\\)>?")
4970 org-angle-link-re
4971 (concat
4972 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4973 "\\([^" org-non-link-chars " ]"
4974 "[^" org-non-link-chars "]*"
4975 "\\)>")
4976 org-plain-link-re
4977 (concat
4978 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4979 "\\([^]\t\n\r<>,;() ]+\\)")
4980 org-bracket-link-regexp
4981 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4982 org-bracket-link-analytic-regexp
4983 (concat
4984 "\\[\\["
4985 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4986 "\\([^]]+\\)"
4987 "\\]"
4988 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4989 "\\]")
4990 org-any-link-re
4991 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4992 org-angle-link-re "\\)\\|\\("
4993 org-plain-link-re "\\)")))
4995 (org-make-link-regexps)
4997 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4998 "Regular expression for fast time stamp matching.")
4999 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5000 "Regular expression for fast time stamp matching.")
5001 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5002 "Regular expression matching time strings for analysis.
5003 This one does not require the space after the date.")
5004 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5005 "Regular expression matching time strings for analysis.")
5006 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5007 "Regular expression matching time stamps, with groups.")
5008 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5009 "Regular expression matching time stamps (also [..]), with groups.")
5010 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5011 "Regular expression matching a time stamp range.")
5012 (defconst org-tr-regexp-both
5013 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5014 "Regular expression matching a time stamp range.")
5015 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5016 org-ts-regexp "\\)?")
5017 "Regular expression matching a time stamp or time stamp range.")
5018 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5019 org-ts-regexp-both "\\)?")
5020 "Regular expression matching a time stamp or time stamp range.
5021 The time stamps may be either active or inactive.")
5023 (defvar org-emph-face nil)
5025 (defun org-do-emphasis-faces (limit)
5026 "Run through the buffer and add overlays to links."
5027 (let (rtn)
5028 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5029 (if (not (= (char-after (match-beginning 3))
5030 (char-after (match-beginning 4))))
5031 (progn
5032 (setq rtn t)
5033 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5034 'face
5035 (nth 1 (assoc (match-string 3)
5036 org-emphasis-alist)))
5037 (add-text-properties (match-beginning 2) (match-end 2)
5038 '(font-lock-multiline t))
5039 (when org-hide-emphasis-markers
5040 (add-text-properties (match-end 4) (match-beginning 5)
5041 '(invisible org-link))
5042 (add-text-properties (match-beginning 3) (match-end 3)
5043 '(invisible org-link)))))
5044 (backward-char 1))
5045 rtn))
5047 (defun org-emphasize (&optional char)
5048 "Insert or change an emphasis, i.e. a font like bold or italic.
5049 If there is an active region, change that region to a new emphasis.
5050 If there is no region, just insert the marker characters and position
5051 the cursor between them.
5052 CHAR should be either the marker character, or the first character of the
5053 HTML tag associated with that emphasis. If CHAR is a space, the means
5054 to remove the emphasis of the selected region.
5055 If char is not given (for example in an interactive call) it
5056 will be prompted for."
5057 (interactive)
5058 (let ((eal org-emphasis-alist) e det
5059 (erc org-emphasis-regexp-components)
5060 (prompt "")
5061 (string "") beg end move tag c s)
5062 (if (org-region-active-p)
5063 (setq beg (region-beginning) end (region-end)
5064 string (buffer-substring beg end))
5065 (setq move t))
5067 (while (setq e (pop eal))
5068 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5069 c (aref tag 0))
5070 (push (cons c (string-to-char (car e))) det)
5071 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5072 (substring tag 1)))))
5073 (unless char
5074 (message "%s" (concat "Emphasis marker or tag:" prompt))
5075 (setq char (read-char-exclusive)))
5076 (setq char (or (cdr (assoc char det)) char))
5077 (if (equal char ?\ )
5078 (setq s "" move nil)
5079 (unless (assoc (char-to-string char) org-emphasis-alist)
5080 (error "No such emphasis marker: \"%c\"" char))
5081 (setq s (char-to-string char)))
5082 (while (and (> (length string) 1)
5083 (equal (substring string 0 1) (substring string -1))
5084 (assoc (substring string 0 1) org-emphasis-alist))
5085 (setq string (substring string 1 -1)))
5086 (setq string (concat s string s))
5087 (if beg (delete-region beg end))
5088 (unless (or (bolp)
5089 (string-match (concat "[" (nth 0 erc) "\n]")
5090 (char-to-string (char-before (point)))))
5091 (insert " "))
5092 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5093 (char-to-string (char-after (point))))
5094 (insert " ") (backward-char 1))
5095 (insert string)
5096 (and move (backward-char 1))))
5098 (defconst org-nonsticky-props
5099 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5102 (defun org-activate-plain-links (limit)
5103 "Run through the buffer and add overlays to links."
5104 (catch 'exit
5105 (let (f)
5106 (while (re-search-forward org-plain-link-re limit t)
5107 (setq f (get-text-property (match-beginning 0) 'face))
5108 (if (or (eq f 'org-tag)
5109 (and (listp f) (memq 'org-tag f)))
5111 (add-text-properties (match-beginning 0) (match-end 0)
5112 (list 'mouse-face 'highlight
5113 'rear-nonsticky org-nonsticky-props
5114 'keymap org-mouse-map
5116 (throw 'exit t))))))
5118 (defun org-activate-code (limit)
5119 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5120 (unless (get-text-property (match-beginning 1) 'face)
5121 (remove-text-properties (match-beginning 0) (match-end 0)
5122 '(display t invisible t intangible t))
5123 t)))
5125 (defun org-activate-angle-links (limit)
5126 "Run through the buffer and add overlays to links."
5127 (if (re-search-forward org-angle-link-re limit t)
5128 (progn
5129 (add-text-properties (match-beginning 0) (match-end 0)
5130 (list 'mouse-face 'highlight
5131 'rear-nonsticky org-nonsticky-props
5132 'keymap org-mouse-map
5134 t)))
5136 (defmacro org-maybe-intangible (props)
5137 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5138 In emacs 21, invisible text is not avoided by the command loop, so the
5139 intangible property is needed to make sure point skips this text.
5140 In Emacs 22, this is not necessary. The intangible text property has
5141 led to problems with flyspell. These problems are fixed in flyspell.el,
5142 but we still avoid setting the property in Emacs 22 and later.
5143 We use a macro so that the test can happen at compilation time."
5144 (if (< emacs-major-version 22)
5145 `(append '(intangible t) ,props)
5146 props))
5148 (defun org-activate-bracket-links (limit)
5149 "Run through the buffer and add overlays to bracketed links."
5150 (if (re-search-forward org-bracket-link-regexp limit t)
5151 (let* ((help (concat "LINK: "
5152 (org-match-string-no-properties 1)))
5153 ;; FIXME: above we should remove the escapes.
5154 ;; but that requires another match, protecting match data,
5155 ;; a lot of overhead for font-lock.
5156 (ip (org-maybe-intangible
5157 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5158 'keymap org-mouse-map 'mouse-face 'highlight
5159 'font-lock-multiline t 'help-echo help)))
5160 (vp (list 'rear-nonsticky org-nonsticky-props
5161 'keymap org-mouse-map 'mouse-face 'highlight
5162 ' font-lock-multiline t 'help-echo help)))
5163 ;; We need to remove the invisible property here. Table narrowing
5164 ;; may have made some of this invisible.
5165 (remove-text-properties (match-beginning 0) (match-end 0)
5166 '(invisible nil))
5167 (if (match-end 3)
5168 (progn
5169 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5170 (add-text-properties (match-beginning 3) (match-end 3) vp)
5171 (add-text-properties (match-end 3) (match-end 0) ip))
5172 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5173 (add-text-properties (match-beginning 1) (match-end 1) vp)
5174 (add-text-properties (match-end 1) (match-end 0) ip))
5175 t)))
5177 (defun org-activate-dates (limit)
5178 "Run through the buffer and add overlays to dates."
5179 (if (re-search-forward org-tsr-regexp-both limit t)
5180 (progn
5181 (add-text-properties (match-beginning 0) (match-end 0)
5182 (list 'mouse-face 'highlight
5183 'rear-nonsticky org-nonsticky-props
5184 'keymap org-mouse-map))
5185 (when org-display-custom-times
5186 (if (match-end 3)
5187 (org-display-custom-time (match-beginning 3) (match-end 3)))
5188 (org-display-custom-time (match-beginning 1) (match-end 1)))
5189 t)))
5191 (defvar org-target-link-regexp nil
5192 "Regular expression matching radio targets in plain text.")
5193 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5194 "Regular expression matching a link target.")
5195 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5196 "Regular expression matching a radio target.")
5197 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5198 "Regular expression matching any target.")
5200 (defun org-activate-target-links (limit)
5201 "Run through the buffer and add overlays to target matches."
5202 (when org-target-link-regexp
5203 (let ((case-fold-search t))
5204 (if (re-search-forward org-target-link-regexp limit t)
5205 (progn
5206 (add-text-properties (match-beginning 0) (match-end 0)
5207 (list 'mouse-face 'highlight
5208 'rear-nonsticky org-nonsticky-props
5209 'keymap org-mouse-map
5210 'help-echo "Radio target link"
5211 'org-linked-text t))
5212 t)))))
5214 (defun org-update-radio-target-regexp ()
5215 "Find all radio targets in this file and update the regular expression."
5216 (interactive)
5217 (when (memq 'radio org-activate-links)
5218 (setq org-target-link-regexp
5219 (org-make-target-link-regexp (org-all-targets 'radio)))
5220 (org-restart-font-lock)))
5222 (defun org-hide-wide-columns (limit)
5223 (let (s e)
5224 (setq s (text-property-any (point) (or limit (point-max))
5225 'org-cwidth t))
5226 (when s
5227 (setq e (next-single-property-change s 'org-cwidth))
5228 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5229 (goto-char e)
5230 t)))
5232 (defvar org-latex-and-specials-regexp nil
5233 "Regular expression for highlighting export special stuff.")
5234 (defvar org-match-substring-regexp)
5235 (defvar org-match-substring-with-braces-regexp)
5236 (defvar org-export-html-special-string-regexps)
5238 (defun org-compute-latex-and-specials-regexp ()
5239 "Compute regular expression for stuff treated specially by exporters."
5240 (if (not org-highlight-latex-fragments-and-specials)
5241 (org-set-local 'org-latex-and-specials-regexp nil)
5242 (let*
5243 ((matchers (plist-get org-format-latex-options :matchers))
5244 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5245 org-latex-regexps)))
5246 (options (org-combine-plists (org-default-export-plist)
5247 (org-infile-export-plist)))
5248 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5249 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5250 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5251 (org-export-html-expand (plist-get options :expand-quoted-html))
5252 (org-export-with-special-strings (plist-get options :special-strings))
5253 (re-sub
5254 (cond
5255 ((equal org-export-with-sub-superscripts '{})
5256 (list org-match-substring-with-braces-regexp))
5257 (org-export-with-sub-superscripts
5258 (list org-match-substring-regexp))
5259 (t nil)))
5260 (re-latex
5261 (if org-export-with-LaTeX-fragments
5262 (mapcar (lambda (x) (nth 1 x)) latexs)))
5263 (re-macros
5264 (if org-export-with-TeX-macros
5265 (list (concat "\\\\"
5266 (regexp-opt
5267 (append (mapcar 'car org-html-entities)
5268 (if (boundp 'org-latex-entities)
5269 org-latex-entities nil))
5270 'words))) ; FIXME
5272 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5273 (re-special (if org-export-with-special-strings
5274 (mapcar (lambda (x) (car x))
5275 org-export-html-special-string-regexps)))
5276 (re-rest
5277 (delq nil
5278 (list
5279 (if org-export-html-expand "@<[^>\n]+>")
5280 ))))
5281 (org-set-local
5282 'org-latex-and-specials-regexp
5283 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5284 re-rest) "\\|")))))
5286 (defface org-latex-and-export-specials
5287 (let ((font (cond ((assq :inherit custom-face-attributes)
5288 '(:inherit underline))
5289 (t '(:underline t)))))
5290 `((((class grayscale) (background light))
5291 (:foreground "DimGray" ,@font))
5292 (((class grayscale) (background dark))
5293 (:foreground "LightGray" ,@font))
5294 (((class color) (background light))
5295 (:foreground "SaddleBrown"))
5296 (((class color) (background dark))
5297 (:foreground "burlywood"))
5298 (t (,@font))))
5299 "Face used to highlight math latex and other special exporter stuff."
5300 :group 'org-faces)
5302 (defun org-do-latex-and-special-faces (limit)
5303 "Run through the buffer and add overlays to links."
5304 (when org-latex-and-specials-regexp
5305 (let (rtn d)
5306 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5307 limit t))
5308 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5309 'face))
5310 '(org-code org-verbatim underline)))
5311 (progn
5312 (setq rtn t
5313 d (cond ((member (char-after (1+ (match-beginning 0)))
5314 '(?_ ?^)) 1)
5315 (t 0)))
5316 (font-lock-prepend-text-property
5317 (+ d (match-beginning 0)) (match-end 0)
5318 'face 'org-latex-and-export-specials)
5319 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5320 '(font-lock-multiline t)))))
5321 rtn)))
5323 (defun org-restart-font-lock ()
5324 "Restart font-lock-mode, to force refontification."
5325 (when (and (boundp 'font-lock-mode) font-lock-mode)
5326 (font-lock-mode -1)
5327 (font-lock-mode 1)))
5329 (defun org-all-targets (&optional radio)
5330 "Return a list of all targets in this file.
5331 With optional argument RADIO, only find radio targets."
5332 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5333 rtn)
5334 (save-excursion
5335 (goto-char (point-min))
5336 (while (re-search-forward re nil t)
5337 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5338 rtn)))
5340 (defun org-make-target-link-regexp (targets)
5341 "Make regular expression matching all strings in TARGETS.
5342 The regular expression finds the targets also if there is a line break
5343 between words."
5344 (and targets
5345 (concat
5346 "\\<\\("
5347 (mapconcat
5348 (lambda (x)
5349 (while (string-match " +" x)
5350 (setq x (replace-match "\\s-+" t t x)))
5352 targets
5353 "\\|")
5354 "\\)\\>")))
5356 (defun org-activate-tags (limit)
5357 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5358 (progn
5359 (add-text-properties (match-beginning 1) (match-end 1)
5360 (list 'mouse-face 'highlight
5361 'rear-nonsticky org-nonsticky-props
5362 'keymap org-mouse-map))
5363 t)))
5365 (defun org-outline-level ()
5366 (save-excursion
5367 (looking-at outline-regexp)
5368 (if (match-beginning 1)
5369 (+ (org-get-string-indentation (match-string 1)) 1000)
5370 (1- (- (match-end 0) (match-beginning 0))))))
5372 (defvar org-font-lock-keywords nil)
5374 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5375 "Regular expression matching a property line.")
5377 (defun org-set-font-lock-defaults ()
5378 (let* ((em org-fontify-emphasized-text)
5379 (lk org-activate-links)
5380 (org-font-lock-extra-keywords
5381 (list
5382 ;; Headlines
5383 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5384 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5385 ;; Table lines
5386 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5387 (1 'org-table t))
5388 ;; Table internals
5389 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5390 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5391 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5392 ;; Drawers
5393 (list org-drawer-regexp '(0 'org-special-keyword t))
5394 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5395 ;; Properties
5396 (list org-property-re
5397 '(1 'org-special-keyword t)
5398 '(3 'org-property-value t))
5399 (if org-format-transports-properties-p
5400 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5401 ;; Links
5402 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5403 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5404 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5405 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5406 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5407 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5408 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5409 '(org-hide-wide-columns (0 nil append))
5410 ;; TODO lines
5411 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5412 '(1 (org-get-todo-face 1) t))
5413 ;; DONE
5414 (if org-fontify-done-headline
5415 (list (concat "^[*]+ +\\<\\("
5416 (mapconcat 'regexp-quote org-done-keywords "\\|")
5417 "\\)\\(.*\\)")
5418 '(2 'org-headline-done t))
5419 nil)
5420 ;; Priorities
5421 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5422 ;; Special keywords
5423 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5424 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5425 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5426 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5427 ;; Emphasis
5428 (if em
5429 (if (featurep 'xemacs)
5430 '(org-do-emphasis-faces (0 nil append))
5431 '(org-do-emphasis-faces)))
5432 ;; Checkboxes
5433 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5434 2 'bold prepend)
5435 (if org-provide-checkbox-statistics
5436 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5437 (0 (org-get-checkbox-statistics-face) t)))
5438 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5439 '(1 'org-archived prepend))
5440 ;; Specials
5441 '(org-do-latex-and-special-faces)
5442 ;; Code
5443 '(org-activate-code (1 'org-code t))
5444 ;; COMMENT
5445 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5446 "\\|" org-quote-string "\\)\\>")
5447 '(1 'org-special-keyword t))
5448 '("^#.*" (0 'font-lock-comment-face t))
5450 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5451 ;; Now set the full font-lock-keywords
5452 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5453 (org-set-local 'font-lock-defaults
5454 '(org-font-lock-keywords t nil nil backward-paragraph))
5455 (kill-local-variable 'font-lock-keywords) nil))
5457 (defvar org-m nil)
5458 (defvar org-l nil)
5459 (defvar org-f nil)
5460 (defun org-get-level-face (n)
5461 "Get the right face for match N in font-lock matching of healdines."
5462 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5463 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5464 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5465 (cond
5466 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5467 ((eq n 2) org-f)
5468 (t (if org-level-color-stars-only nil org-f))))
5470 (defun org-get-todo-face (kwd)
5471 "Get the right face for a TODO keyword KWD.
5472 If KWD is a number, get the corresponding match group."
5473 (if (numberp kwd) (setq kwd (match-string kwd)))
5474 (or (cdr (assoc kwd org-todo-keyword-faces))
5475 (and (member kwd org-done-keywords) 'org-done)
5476 'org-todo))
5478 (defun org-unfontify-region (beg end &optional maybe_loudly)
5479 "Remove fontification and activation overlays from links."
5480 (font-lock-default-unfontify-region beg end)
5481 (let* ((buffer-undo-list t)
5482 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5483 (inhibit-modification-hooks t)
5484 deactivate-mark buffer-file-name buffer-file-truename)
5485 (remove-text-properties beg end
5486 '(mouse-face t keymap t org-linked-text t
5487 invisible t intangible t))))
5489 ;;;; Visibility cycling, including org-goto and indirect buffer
5491 ;;; Cycling
5493 (defvar org-cycle-global-status nil)
5494 (make-variable-buffer-local 'org-cycle-global-status)
5495 (defvar org-cycle-subtree-status nil)
5496 (make-variable-buffer-local 'org-cycle-subtree-status)
5498 ;;;###autoload
5499 (defun org-cycle (&optional arg)
5500 "Visibility cycling for Org-mode.
5502 - When this function is called with a prefix argument, rotate the entire
5503 buffer through 3 states (global cycling)
5504 1. OVERVIEW: Show only top-level headlines.
5505 2. CONTENTS: Show all headlines of all levels, but no body text.
5506 3. SHOW ALL: Show everything.
5508 - When point is at the beginning of a headline, rotate the subtree started
5509 by this line through 3 different states (local cycling)
5510 1. FOLDED: Only the main headline is shown.
5511 2. CHILDREN: The main headline and the direct children are shown.
5512 From this state, you can move to one of the children
5513 and zoom in further.
5514 3. SUBTREE: Show the entire subtree, including body text.
5516 - When there is a numeric prefix, go up to a heading with level ARG, do
5517 a `show-subtree' and return to the previous cursor position. If ARG
5518 is negative, go up that many levels.
5520 - When point is not at the beginning of a headline, execute
5521 `indent-relative', like TAB normally does. See the option
5522 `org-cycle-emulate-tab' for details.
5524 - Special case: if point is at the beginning of the buffer and there is
5525 no headline in line 1, this function will act as if called with prefix arg.
5526 But only if also the variable `org-cycle-global-at-bob' is t."
5527 (interactive "P")
5528 (let* ((outline-regexp
5529 (if (and (org-mode-p) org-cycle-include-plain-lists)
5530 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5531 outline-regexp))
5532 (bob-special (and org-cycle-global-at-bob (bobp)
5533 (not (looking-at outline-regexp))))
5534 (org-cycle-hook
5535 (if bob-special
5536 (delq 'org-optimize-window-after-visibility-change
5537 (copy-sequence org-cycle-hook))
5538 org-cycle-hook))
5539 (pos (point)))
5541 (if (or bob-special (equal arg '(4)))
5542 ;; special case: use global cycling
5543 (setq arg t))
5545 (cond
5547 ((org-at-table-p 'any)
5548 ;; Enter the table or move to the next field in the table
5549 (or (org-table-recognize-table.el)
5550 (progn
5551 (if arg (org-table-edit-field t)
5552 (org-table-justify-field-maybe)
5553 (call-interactively 'org-table-next-field)))))
5555 ((eq arg t) ;; Global cycling
5557 (cond
5558 ((and (eq last-command this-command)
5559 (eq org-cycle-global-status 'overview))
5560 ;; We just created the overview - now do table of contents
5561 ;; This can be slow in very large buffers, so indicate action
5562 (message "CONTENTS...")
5563 (org-content)
5564 (message "CONTENTS...done")
5565 (setq org-cycle-global-status 'contents)
5566 (run-hook-with-args 'org-cycle-hook 'contents))
5568 ((and (eq last-command this-command)
5569 (eq org-cycle-global-status 'contents))
5570 ;; We just showed the table of contents - now show everything
5571 (show-all)
5572 (message "SHOW ALL")
5573 (setq org-cycle-global-status 'all)
5574 (run-hook-with-args 'org-cycle-hook 'all))
5577 ;; Default action: go to overview
5578 (org-overview)
5579 (message "OVERVIEW")
5580 (setq org-cycle-global-status 'overview)
5581 (run-hook-with-args 'org-cycle-hook 'overview))))
5583 ((and org-drawers org-drawer-regexp
5584 (save-excursion
5585 (beginning-of-line 1)
5586 (looking-at org-drawer-regexp)))
5587 ;; Toggle block visibility
5588 (org-flag-drawer
5589 (not (get-char-property (match-end 0) 'invisible))))
5591 ((integerp arg)
5592 ;; Show-subtree, ARG levels up from here.
5593 (save-excursion
5594 (org-back-to-heading)
5595 (outline-up-heading (if (< arg 0) (- arg)
5596 (- (funcall outline-level) arg)))
5597 (org-show-subtree)))
5599 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5600 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5601 ;; At a heading: rotate between three different views
5602 (org-back-to-heading)
5603 (let ((goal-column 0) eoh eol eos)
5604 ;; First, some boundaries
5605 (save-excursion
5606 (org-back-to-heading)
5607 (save-excursion
5608 (beginning-of-line 2)
5609 (while (and (not (eobp)) ;; this is like `next-line'
5610 (get-char-property (1- (point)) 'invisible))
5611 (beginning-of-line 2)) (setq eol (point)))
5612 (outline-end-of-heading) (setq eoh (point))
5613 (org-end-of-subtree t)
5614 (unless (eobp)
5615 (skip-chars-forward " \t\n")
5616 (beginning-of-line 1) ; in case this is an item
5618 (setq eos (1- (point))))
5619 ;; Find out what to do next and set `this-command'
5620 (cond
5621 ((= eos eoh)
5622 ;; Nothing is hidden behind this heading
5623 (message "EMPTY ENTRY")
5624 (setq org-cycle-subtree-status nil)
5625 (save-excursion
5626 (goto-char eos)
5627 (outline-next-heading)
5628 (if (org-invisible-p) (org-flag-heading nil))))
5629 ((or (>= eol eos)
5630 (not (string-match "\\S-" (buffer-substring eol eos))))
5631 ;; Entire subtree is hidden in one line: open it
5632 (org-show-entry)
5633 (show-children)
5634 (message "CHILDREN")
5635 (save-excursion
5636 (goto-char eos)
5637 (outline-next-heading)
5638 (if (org-invisible-p) (org-flag-heading nil)))
5639 (setq org-cycle-subtree-status 'children)
5640 (run-hook-with-args 'org-cycle-hook 'children))
5641 ((and (eq last-command this-command)
5642 (eq org-cycle-subtree-status 'children))
5643 ;; We just showed the children, now show everything.
5644 (org-show-subtree)
5645 (message "SUBTREE")
5646 (setq org-cycle-subtree-status 'subtree)
5647 (run-hook-with-args 'org-cycle-hook 'subtree))
5649 ;; Default action: hide the subtree.
5650 (hide-subtree)
5651 (message "FOLDED")
5652 (setq org-cycle-subtree-status 'folded)
5653 (run-hook-with-args 'org-cycle-hook 'folded)))))
5655 ;; TAB emulation
5656 (buffer-read-only (org-back-to-heading))
5658 ((org-try-cdlatex-tab))
5660 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5661 (or (not (bolp))
5662 (not (looking-at outline-regexp))))
5663 (call-interactively (global-key-binding "\t")))
5665 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5666 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5667 (or (and (eq org-cycle-emulate-tab 'white)
5668 (= (match-end 0) (point-at-eol)))
5669 (and (eq org-cycle-emulate-tab 'whitestart)
5670 (>= (match-end 0) pos))))
5672 (eq org-cycle-emulate-tab t))
5673 ; (if (and (looking-at "[ \n\r\t]")
5674 ; (string-match "^[ \t]*$" (buffer-substring
5675 ; (point-at-bol) (point))))
5676 ; (progn
5677 ; (beginning-of-line 1)
5678 ; (and (looking-at "[ \t]+") (replace-match ""))))
5679 (call-interactively (global-key-binding "\t")))
5681 (t (save-excursion
5682 (org-back-to-heading)
5683 (org-cycle))))))
5685 ;;;###autoload
5686 (defun org-global-cycle (&optional arg)
5687 "Cycle the global visibility. For details see `org-cycle'."
5688 (interactive "P")
5689 (let ((org-cycle-include-plain-lists
5690 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5691 (if (integerp arg)
5692 (progn
5693 (show-all)
5694 (hide-sublevels arg)
5695 (setq org-cycle-global-status 'contents))
5696 (org-cycle '(4)))))
5698 (defun org-overview ()
5699 "Switch to overview mode, shoing only top-level headlines.
5700 Really, this shows all headlines with level equal or greater than the level
5701 of the first headline in the buffer. This is important, because if the
5702 first headline is not level one, then (hide-sublevels 1) gives confusing
5703 results."
5704 (interactive)
5705 (let ((level (save-excursion
5706 (goto-char (point-min))
5707 (if (re-search-forward (concat "^" outline-regexp) nil t)
5708 (progn
5709 (goto-char (match-beginning 0))
5710 (funcall outline-level))))))
5711 (and level (hide-sublevels level))))
5713 (defun org-content (&optional arg)
5714 "Show all headlines in the buffer, like a table of contents.
5715 With numerical argument N, show content up to level N."
5716 (interactive "P")
5717 (save-excursion
5718 ;; Visit all headings and show their offspring
5719 (and (integerp arg) (org-overview))
5720 (goto-char (point-max))
5721 (catch 'exit
5722 (while (and (progn (condition-case nil
5723 (outline-previous-visible-heading 1)
5724 (error (goto-char (point-min))))
5726 (looking-at outline-regexp))
5727 (if (integerp arg)
5728 (show-children (1- arg))
5729 (show-branches))
5730 (if (bobp) (throw 'exit nil))))))
5733 (defun org-optimize-window-after-visibility-change (state)
5734 "Adjust the window after a change in outline visibility.
5735 This function is the default value of the hook `org-cycle-hook'."
5736 (when (get-buffer-window (current-buffer))
5737 (cond
5738 ; ((eq state 'overview) (org-first-headline-recenter 1))
5739 ; ((eq state 'overview) (org-beginning-of-line))
5740 ((eq state 'content) nil)
5741 ((eq state 'all) nil)
5742 ((eq state 'folded) nil)
5743 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5744 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5746 (defun org-compact-display-after-subtree-move ()
5747 (let (beg end)
5748 (save-excursion
5749 (if (org-up-heading-safe)
5750 (progn
5751 (hide-subtree)
5752 (show-entry)
5753 (show-children)
5754 (org-cycle-show-empty-lines 'children)
5755 (org-cycle-hide-drawers 'children))
5756 (org-overview)))))
5758 (defun org-cycle-show-empty-lines (state)
5759 "Show empty lines above all visible headlines.
5760 The region to be covered depends on STATE when called through
5761 `org-cycle-hook'. Lisp program can use t for STATE to get the
5762 entire buffer covered. Note that an empty line is only shown if there
5763 are at least `org-cycle-separator-lines' empty lines before the headeline."
5764 (when (> org-cycle-separator-lines 0)
5765 (save-excursion
5766 (let* ((n org-cycle-separator-lines)
5767 (re (cond
5768 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5769 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5770 (t (let ((ns (number-to-string (- n 2))))
5771 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5772 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5773 beg end)
5774 (cond
5775 ((memq state '(overview contents t))
5776 (setq beg (point-min) end (point-max)))
5777 ((memq state '(children folded))
5778 (setq beg (point) end (progn (org-end-of-subtree t t)
5779 (beginning-of-line 2)
5780 (point)))))
5781 (when beg
5782 (goto-char beg)
5783 (while (re-search-forward re end t)
5784 (if (not (get-char-property (match-end 1) 'invisible))
5785 (outline-flag-region
5786 (match-beginning 1) (match-end 1) nil)))))))
5787 ;; Never hide empty lines at the end of the file.
5788 (save-excursion
5789 (goto-char (point-max))
5790 (outline-previous-heading)
5791 (outline-end-of-heading)
5792 (if (and (looking-at "[ \t\n]+")
5793 (= (match-end 0) (point-max)))
5794 (outline-flag-region (point) (match-end 0) nil))))
5796 (defun org-subtree-end-visible-p ()
5797 "Is the end of the current subtree visible?"
5798 (pos-visible-in-window-p
5799 (save-excursion (org-end-of-subtree t) (point))))
5801 (defun org-first-headline-recenter (&optional N)
5802 "Move cursor to the first headline and recenter the headline.
5803 Optional argument N means, put the headline into the Nth line of the window."
5804 (goto-char (point-min))
5805 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5806 (beginning-of-line)
5807 (recenter (prefix-numeric-value N))))
5809 ;;; Org-goto
5811 (defvar org-goto-window-configuration nil)
5812 (defvar org-goto-marker nil)
5813 (defvar org-goto-map
5814 (let ((map (make-sparse-keymap)))
5815 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5816 (while (setq cmd (pop cmds))
5817 (substitute-key-definition cmd cmd map global-map)))
5818 (suppress-keymap map)
5819 (org-defkey map "\C-m" 'org-goto-ret)
5820 (org-defkey map [(left)] 'org-goto-left)
5821 (org-defkey map [(right)] 'org-goto-right)
5822 (org-defkey map [(?q)] 'org-goto-quit)
5823 (org-defkey map [(control ?g)] 'org-goto-quit)
5824 (org-defkey map "\C-i" 'org-cycle)
5825 (org-defkey map [(tab)] 'org-cycle)
5826 (org-defkey map [(down)] 'outline-next-visible-heading)
5827 (org-defkey map [(up)] 'outline-previous-visible-heading)
5828 (org-defkey map "n" 'outline-next-visible-heading)
5829 (org-defkey map "p" 'outline-previous-visible-heading)
5830 (org-defkey map "f" 'outline-forward-same-level)
5831 (org-defkey map "b" 'outline-backward-same-level)
5832 (org-defkey map "u" 'outline-up-heading)
5833 (org-defkey map "/" 'org-occur)
5834 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5835 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5836 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5837 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5838 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5839 map))
5841 (defconst org-goto-help
5842 "Browse copy of buffer to find location or copy text.
5843 RET=jump to location [Q]uit and return to previous location
5844 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur"
5847 (defvar org-goto-start-pos) ; dynamically scoped parameter
5849 (defun org-goto ()
5850 "Look up a different location in the current file, keeping current visibility.
5852 When you want look-up or go to a different location in a document, the
5853 fastest way is often to fold the entire buffer and then dive into the tree.
5854 This method has the disadvantage, that the previous location will be folded,
5855 which may not be what you want.
5857 This command works around this by showing a copy of the current buffer
5858 in an indirect buffer, in overview mode. You can dive into the tree in
5859 that copy, use org-occur and incremental search to find a location.
5860 When pressing RET or `Q', the command returns to the original buffer in
5861 which the visibility is still unchanged. After RET is will also jump to
5862 the location selected in the indirect buffer and expose the
5863 the headline hierarchy above."
5864 (interactive)
5865 (let* ((org-goto-start-pos (point))
5866 (selected-point
5867 (car (org-get-location (current-buffer) org-goto-help))))
5868 (if selected-point
5869 (progn
5870 (org-mark-ring-push org-goto-start-pos)
5871 (goto-char selected-point)
5872 (if (or (org-invisible-p) (org-invisible-p2))
5873 (org-show-context 'org-goto)))
5874 (message "Quit"))))
5876 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5877 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5879 (defun org-get-location (buf help)
5880 "Let the user select a location in the Org-mode buffer BUF.
5881 This function uses a recursive edit. It returns the selected position
5882 or nil."
5883 (let (org-goto-selected-point org-goto-exit-command)
5884 (save-excursion
5885 (save-window-excursion
5886 (delete-other-windows)
5887 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5888 (switch-to-buffer
5889 (condition-case nil
5890 (make-indirect-buffer (current-buffer) "*org-goto*")
5891 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5892 (with-output-to-temp-buffer "*Help*"
5893 (princ help))
5894 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5895 (setq buffer-read-only nil)
5896 (let ((org-startup-truncated t)
5897 (org-startup-folded nil)
5898 (org-startup-align-all-tables nil))
5899 (org-mode)
5900 (org-overview))
5901 (setq buffer-read-only t)
5902 (if (and (boundp 'org-goto-start-pos)
5903 (integer-or-marker-p org-goto-start-pos))
5904 (let ((org-show-hierarchy-above t)
5905 (org-show-siblings t)
5906 (org-show-following-heading t))
5907 (goto-char org-goto-start-pos)
5908 (and (org-invisible-p) (org-show-context)))
5909 (goto-char (point-min)))
5910 (org-beginning-of-line)
5911 (message "Select location and press RET")
5912 ;; now we make sure that during selection, ony very few keys work
5913 ;; and that it is impossible to switch to another window.
5914 ; (let ((gm (current-global-map))
5915 ; (overriding-local-map org-goto-map))
5916 ; (unwind-protect
5917 ; (progn
5918 ; (use-global-map org-goto-map)
5919 ; (recursive-edit))
5920 ; (use-global-map gm)))
5921 (use-local-map org-goto-map)
5922 (recursive-edit)
5924 (kill-buffer "*org-goto*")
5925 (cons org-goto-selected-point org-goto-exit-command)))
5927 (defun org-goto-ret (&optional arg)
5928 "Finish `org-goto' by going to the new location."
5929 (interactive "P")
5930 (setq org-goto-selected-point (point)
5931 org-goto-exit-command 'return)
5932 (throw 'exit nil))
5934 (defun org-goto-left ()
5935 "Finish `org-goto' by going to the new location."
5936 (interactive)
5937 (if (org-on-heading-p)
5938 (progn
5939 (beginning-of-line 1)
5940 (setq org-goto-selected-point (point)
5941 org-goto-exit-command 'left)
5942 (throw 'exit nil))
5943 (error "Not on a heading")))
5945 (defun org-goto-right ()
5946 "Finish `org-goto' by going to the new location."
5947 (interactive)
5948 (if (org-on-heading-p)
5949 (progn
5950 (setq org-goto-selected-point (point)
5951 org-goto-exit-command 'right)
5952 (throw 'exit nil))
5953 (error "Not on a heading")))
5955 (defun org-goto-quit ()
5956 "Finish `org-goto' without cursor motion."
5957 (interactive)
5958 (setq org-goto-selected-point nil)
5959 (setq org-goto-exit-command 'quit)
5960 (throw 'exit nil))
5962 ;;; Indirect buffer display of subtrees
5964 (defvar org-indirect-dedicated-frame nil
5965 "This is the frame being used for indirect tree display.")
5966 (defvar org-last-indirect-buffer nil)
5968 (defun org-tree-to-indirect-buffer (&optional arg)
5969 "Create indirect buffer and narrow it to current subtree.
5970 With numerical prefix ARG, go up to this level and then take that tree.
5971 If ARG is negative, go up that many levels.
5972 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5973 indirect buffer previously made with this command, to avoid proliferation of
5974 indirect buffers. However, when you call the command with a `C-u' prefix, or
5975 when `org-indirect-buffer-display' is `new-frame', the last buffer
5976 is kept so that you can work with several indirect buffers at the same time.
5977 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5978 requests that a new frame be made for the new buffer, so that the dedicated
5979 frame is not changed."
5980 (interactive "P")
5981 (let ((cbuf (current-buffer))
5982 (cwin (selected-window))
5983 (pos (point))
5984 beg end level heading ibuf)
5985 (save-excursion
5986 (org-back-to-heading t)
5987 (when (numberp arg)
5988 (setq level (org-outline-level))
5989 (if (< arg 0) (setq arg (+ level arg)))
5990 (while (> (setq level (org-outline-level)) arg)
5991 (outline-up-heading 1 t)))
5992 (setq beg (point)
5993 heading (org-get-heading))
5994 (org-end-of-subtree t) (setq end (point)))
5995 (if (and (buffer-live-p org-last-indirect-buffer)
5996 (not (eq org-indirect-buffer-display 'new-frame))
5997 (not arg))
5998 (kill-buffer org-last-indirect-buffer))
5999 (setq ibuf (org-get-indirect-buffer cbuf)
6000 org-last-indirect-buffer ibuf)
6001 (cond
6002 ((or (eq org-indirect-buffer-display 'new-frame)
6003 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6004 (select-frame (make-frame))
6005 (delete-other-windows)
6006 (switch-to-buffer ibuf)
6007 (org-set-frame-title heading))
6008 ((eq org-indirect-buffer-display 'dedicated-frame)
6009 (raise-frame
6010 (select-frame (or (and org-indirect-dedicated-frame
6011 (frame-live-p org-indirect-dedicated-frame)
6012 org-indirect-dedicated-frame)
6013 (setq org-indirect-dedicated-frame (make-frame)))))
6014 (delete-other-windows)
6015 (switch-to-buffer ibuf)
6016 (org-set-frame-title (concat "Indirect: " heading)))
6017 ((eq org-indirect-buffer-display 'current-window)
6018 (switch-to-buffer ibuf))
6019 ((eq org-indirect-buffer-display 'other-window)
6020 (pop-to-buffer ibuf))
6021 (t (error "Invalid value.")))
6022 (if (featurep 'xemacs)
6023 (save-excursion (org-mode) (turn-on-font-lock)))
6024 (narrow-to-region beg end)
6025 (show-all)
6026 (goto-char pos)
6027 (and (window-live-p cwin) (select-window cwin))))
6029 (defun org-get-indirect-buffer (&optional buffer)
6030 (setq buffer (or buffer (current-buffer)))
6031 (let ((n 1) (base (buffer-name buffer)) bname)
6032 (while (buffer-live-p
6033 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6034 (setq n (1+ n)))
6035 (condition-case nil
6036 (make-indirect-buffer buffer bname 'clone)
6037 (error (make-indirect-buffer buffer bname)))))
6039 (defun org-set-frame-title (title)
6040 "Set the title of the current frame to the string TITLE."
6041 ;; FIXME: how to name a single frame in XEmacs???
6042 (unless (featurep 'xemacs)
6043 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6045 ;;;; Structure editing
6047 ;;; Inserting headlines
6049 (defun org-insert-heading (&optional force-heading)
6050 "Insert a new heading or item with same depth at point.
6051 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6052 If point is at the beginning of a headline, insert a sibling before the
6053 current headline. If point is in the middle of a headline, split the headline
6054 at that position and make the rest of the headline part of the sibling below
6055 the current headline."
6056 (interactive "P")
6057 (if (= (buffer-size) 0)
6058 (insert "\n* ")
6059 (when (or force-heading (not (org-insert-item)))
6060 (let* ((head (save-excursion
6061 (condition-case nil
6062 (progn
6063 (org-back-to-heading)
6064 (match-string 0))
6065 (error "*"))))
6066 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6067 pos)
6068 (cond
6069 ((and (org-on-heading-p) (bolp)
6070 (or (bobp)
6071 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6072 (open-line (if blank 2 1)))
6073 ((and (bolp)
6074 (or (bobp)
6075 (save-excursion
6076 (backward-char 1) (not (org-invisible-p)))))
6077 nil)
6078 (t (newline (if blank 2 1))))
6079 (insert head) (just-one-space)
6080 (setq pos (point))
6081 (end-of-line 1)
6082 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6083 (run-hooks 'org-insert-heading-hook)))))
6085 (defun org-insert-heading-after-current ()
6086 "Insert a new heading with same level as current, after current subtree."
6087 (interactive)
6088 (org-back-to-heading)
6089 (org-insert-heading)
6090 (org-move-subtree-down)
6091 (end-of-line 1))
6093 (defun org-insert-todo-heading (arg)
6094 "Insert a new heading with the same level and TODO state as current heading.
6095 If the heading has no TODO state, or if the state is DONE, use the first
6096 state (TODO by default). Also with prefix arg, force first state."
6097 (interactive "P")
6098 (when (not (org-insert-item 'checkbox))
6099 (org-insert-heading)
6100 (save-excursion
6101 (org-back-to-heading)
6102 (outline-previous-heading)
6103 (looking-at org-todo-line-regexp))
6104 (if (or arg
6105 (not (match-beginning 2))
6106 (member (match-string 2) org-done-keywords))
6107 (insert (car org-todo-keywords-1) " ")
6108 (insert (match-string 2) " "))))
6110 (defun org-insert-subheading (arg)
6111 "Insert a new subheading and demote it.
6112 Works for outline headings and for plain lists alike."
6113 (interactive "P")
6114 (org-insert-heading arg)
6115 (cond
6116 ((org-on-heading-p) (org-do-demote))
6117 ((org-at-item-p) (org-indent-item 1))))
6119 (defun org-insert-todo-subheading (arg)
6120 "Insert a new subheading with TODO keyword or checkbox and demote it.
6121 Works for outline headings and for plain lists alike."
6122 (interactive "P")
6123 (org-insert-todo-heading arg)
6124 (cond
6125 ((org-on-heading-p) (org-do-demote))
6126 ((org-at-item-p) (org-indent-item 1))))
6128 ;;; Promotion and Demotion
6130 (defun org-promote-subtree ()
6131 "Promote the entire subtree.
6132 See also `org-promote'."
6133 (interactive)
6134 (save-excursion
6135 (org-map-tree 'org-promote))
6136 (org-fix-position-after-promote))
6138 (defun org-demote-subtree ()
6139 "Demote the entire subtree. See `org-demote'.
6140 See also `org-promote'."
6141 (interactive)
6142 (save-excursion
6143 (org-map-tree 'org-demote))
6144 (org-fix-position-after-promote))
6147 (defun org-do-promote ()
6148 "Promote the current heading higher up the tree.
6149 If the region is active in `transient-mark-mode', promote all headings
6150 in the region."
6151 (interactive)
6152 (save-excursion
6153 (if (org-region-active-p)
6154 (org-map-region 'org-promote (region-beginning) (region-end))
6155 (org-promote)))
6156 (org-fix-position-after-promote))
6158 (defun org-do-demote ()
6159 "Demote the current heading lower down the tree.
6160 If the region is active in `transient-mark-mode', demote all headings
6161 in the region."
6162 (interactive)
6163 (save-excursion
6164 (if (org-region-active-p)
6165 (org-map-region 'org-demote (region-beginning) (region-end))
6166 (org-demote)))
6167 (org-fix-position-after-promote))
6169 (defun org-fix-position-after-promote ()
6170 "Make sure that after pro/demotion cursor position is right."
6171 (let ((pos (point)))
6172 (when (save-excursion
6173 (beginning-of-line 1)
6174 (looking-at org-todo-line-regexp)
6175 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6176 (cond ((eobp) (insert " "))
6177 ((eolp) (insert " "))
6178 ((equal (char-after) ?\ ) (forward-char 1))))))
6180 (defun org-reduced-level (l)
6181 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6183 (defun org-get-legal-level (level &optional change)
6184 "Rectify a level change under the influence of `org-odd-levels-only'
6185 LEVEL is a current level, CHANGE is by how much the level should be
6186 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6187 even level numbers will become the next higher odd number."
6188 (if org-odd-levels-only
6189 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6190 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6191 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6192 (max 1 (+ level change))))
6194 (defun org-promote ()
6195 "Promote the current heading higher up the tree.
6196 If the region is active in `transient-mark-mode', promote all headings
6197 in the region."
6198 (org-back-to-heading t)
6199 (let* ((level (save-match-data (funcall outline-level)))
6200 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6201 (diff (abs (- level (length up-head) -1))))
6202 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6203 (replace-match up-head nil t)
6204 ;; Fixup tag positioning
6205 (and org-auto-align-tags (org-set-tags nil t))
6206 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6208 (defun org-demote ()
6209 "Demote the current heading lower down the tree.
6210 If the region is active in `transient-mark-mode', demote all headings
6211 in the region."
6212 (org-back-to-heading t)
6213 (let* ((level (save-match-data (funcall outline-level)))
6214 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6215 (diff (abs (- level (length down-head) -1))))
6216 (replace-match down-head nil t)
6217 ;; Fixup tag positioning
6218 (and org-auto-align-tags (org-set-tags nil t))
6219 (if org-adapt-indentation (org-fixup-indentation diff))))
6221 (defun org-map-tree (fun)
6222 "Call FUN for every heading underneath the current one."
6223 (org-back-to-heading)
6224 (let ((level (funcall outline-level)))
6225 (save-excursion
6226 (funcall fun)
6227 (while (and (progn
6228 (outline-next-heading)
6229 (> (funcall outline-level) level))
6230 (not (eobp)))
6231 (funcall fun)))))
6233 (defun org-map-region (fun beg end)
6234 "Call FUN for every heading between BEG and END."
6235 (let ((org-ignore-region t))
6236 (save-excursion
6237 (setq end (copy-marker end))
6238 (goto-char beg)
6239 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6240 (< (point) end))
6241 (funcall fun))
6242 (while (and (progn
6243 (outline-next-heading)
6244 (< (point) end))
6245 (not (eobp)))
6246 (funcall fun)))))
6248 (defun org-fixup-indentation (diff)
6249 "Change the indentation in the current entry by DIFF
6250 However, if any line in the current entry has no indentation, or if it
6251 would end up with no indentation after the change, nothing at all is done."
6252 (save-excursion
6253 (let ((end (save-excursion (outline-next-heading)
6254 (point-marker)))
6255 (prohibit (if (> diff 0)
6256 "^\\S-"
6257 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6258 col)
6259 (unless (save-excursion (end-of-line 1)
6260 (re-search-forward prohibit end t))
6261 (while (and (< (point) end)
6262 (re-search-forward "^[ \t]+" end t))
6263 (goto-char (match-end 0))
6264 (setq col (current-column))
6265 (if (< diff 0) (replace-match ""))
6266 (indent-to (+ diff col))))
6267 (move-marker end nil))))
6269 (defun org-convert-to-odd-levels ()
6270 "Convert an org-mode file with all levels allowed to one with odd levels.
6271 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6272 level 5 etc."
6273 (interactive)
6274 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6275 (let ((org-odd-levels-only nil) n)
6276 (save-excursion
6277 (goto-char (point-min))
6278 (while (re-search-forward "^\\*\\*+ " nil t)
6279 (setq n (- (length (match-string 0)) 2))
6280 (while (>= (setq n (1- n)) 0)
6281 (org-demote))
6282 (end-of-line 1))))))
6285 (defun org-convert-to-oddeven-levels ()
6286 "Convert an org-mode file with only odd levels to one with odd and even levels.
6287 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6288 section with an even level, conversion would destroy the structure of the file. An error
6289 is signaled in this case."
6290 (interactive)
6291 (goto-char (point-min))
6292 ;; First check if there are no even levels
6293 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6294 (org-show-context t)
6295 (error "Not all levels are odd in this file. Conversion not possible."))
6296 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6297 (let ((org-odd-levels-only nil) n)
6298 (save-excursion
6299 (goto-char (point-min))
6300 (while (re-search-forward "^\\*\\*+ " nil t)
6301 (setq n (/ (1- (length (match-string 0))) 2))
6302 (while (>= (setq n (1- n)) 0)
6303 (org-promote))
6304 (end-of-line 1))))))
6306 (defun org-tr-level (n)
6307 "Make N odd if required."
6308 (if org-odd-levels-only (1+ (/ n 2)) n))
6310 ;;; Vertical tree motion, cutting and pasting of subtrees
6312 (defun org-move-subtree-up (&optional arg)
6313 "Move the current subtree up past ARG headlines of the same level."
6314 (interactive "p")
6315 (org-move-subtree-down (- (prefix-numeric-value arg))))
6317 (defun org-move-subtree-down (&optional arg)
6318 "Move the current subtree down past ARG headlines of the same level."
6319 (interactive "p")
6320 (setq arg (prefix-numeric-value arg))
6321 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6322 'outline-get-last-sibling))
6323 (ins-point (make-marker))
6324 (cnt (abs arg))
6325 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6326 ;; Select the tree
6327 (org-back-to-heading)
6328 (setq beg0 (point))
6329 (save-excursion
6330 (setq ne-beg (org-back-over-empty-lines))
6331 (setq beg (point)))
6332 (save-match-data
6333 (save-excursion (outline-end-of-heading)
6334 (setq folded (org-invisible-p)))
6335 (outline-end-of-subtree))
6336 (outline-next-heading)
6337 (setq ne-end (org-back-over-empty-lines))
6338 (setq end (point))
6339 (goto-char beg0)
6340 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6341 ;; include less whitespace
6342 (save-excursion
6343 (goto-char beg)
6344 (forward-line (- ne-beg ne-end))
6345 (setq beg (point))))
6346 ;; Find insertion point, with error handling
6347 (while (> cnt 0)
6348 (or (and (funcall movfunc) (looking-at outline-regexp))
6349 (progn (goto-char beg0)
6350 (error "Cannot move past superior level or buffer limit")))
6351 (setq cnt (1- cnt)))
6352 (if (> arg 0)
6353 ;; Moving forward - still need to move over subtree
6354 (progn (org-end-of-subtree t t)
6355 (save-excursion
6356 (org-back-over-empty-lines)
6357 (or (bolp) (newline)))))
6358 (setq ne-ins (org-back-over-empty-lines))
6359 (move-marker ins-point (point))
6360 (setq txt (buffer-substring beg end))
6361 (delete-region beg end)
6362 (outline-flag-region (1- beg) beg nil)
6363 (outline-flag-region (1- (point)) (point) nil)
6364 (insert txt)
6365 (or (bolp) (insert "\n"))
6366 (setq ins-end (point))
6367 (goto-char ins-point)
6368 (org-skip-whitespace)
6369 (when (and (< arg 0)
6370 (org-first-sibling-p)
6371 (> ne-ins ne-beg))
6372 ;; Move whitespace back to beginning
6373 (save-excursion
6374 (goto-char ins-end)
6375 (let ((kill-whole-line t))
6376 (kill-line (- ne-ins ne-beg)) (point)))
6377 (insert (make-string (- ne-ins ne-beg) ?\n)))
6378 (move-marker ins-point nil)
6379 (org-compact-display-after-subtree-move)
6380 (unless folded
6381 (org-show-entry)
6382 (show-children)
6383 (org-cycle-hide-drawers 'children))))
6385 (defvar org-subtree-clip ""
6386 "Clipboard for cut and paste of subtrees.
6387 This is actually only a copy of the kill, because we use the normal kill
6388 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6390 (defvar org-subtree-clip-folded nil
6391 "Was the last copied subtree folded?
6392 This is used to fold the tree back after pasting.")
6394 (defun org-cut-subtree (&optional n)
6395 "Cut the current subtree into the clipboard.
6396 With prefix arg N, cut this many sequential subtrees.
6397 This is a short-hand for marking the subtree and then cutting it."
6398 (interactive "p")
6399 (org-copy-subtree n 'cut))
6401 (defun org-copy-subtree (&optional n cut)
6402 "Cut the current subtree into the clipboard.
6403 With prefix arg N, cut this many sequential subtrees.
6404 This is a short-hand for marking the subtree and then copying it.
6405 If CUT is non-nil, actually cut the subtree."
6406 (interactive "p")
6407 (let (beg end folded (beg0 (point)))
6408 (if (interactive-p)
6409 (org-back-to-heading nil) ; take what looks like a subtree
6410 (org-back-to-heading t)) ; take what is really there
6411 (org-back-over-empty-lines)
6412 (setq beg (point))
6413 (skip-chars-forward " \t\r\n")
6414 (save-match-data
6415 (save-excursion (outline-end-of-heading)
6416 (setq folded (org-invisible-p)))
6417 (condition-case nil
6418 (outline-forward-same-level (1- n))
6419 (error nil))
6420 (org-end-of-subtree t t))
6421 (org-back-over-empty-lines)
6422 (setq end (point))
6423 (goto-char beg0)
6424 (when (> end beg)
6425 (setq org-subtree-clip-folded folded)
6426 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6427 (setq org-subtree-clip (current-kill 0))
6428 (message "%s: Subtree(s) with %d characters"
6429 (if cut "Cut" "Copied")
6430 (length org-subtree-clip)))))
6432 (defun org-paste-subtree (&optional level tree)
6433 "Paste the clipboard as a subtree, with modification of headline level.
6434 The entire subtree is promoted or demoted in order to match a new headline
6435 level. By default, the new level is derived from the visible headings
6436 before and after the insertion point, and taken to be the inferior headline
6437 level of the two. So if the previous visible heading is level 3 and the
6438 next is level 4 (or vice versa), level 4 will be used for insertion.
6439 This makes sure that the subtree remains an independent subtree and does
6440 not swallow low level entries.
6442 You can also force a different level, either by using a numeric prefix
6443 argument, or by inserting the heading marker by hand. For example, if the
6444 cursor is after \"*****\", then the tree will be shifted to level 5.
6446 If you want to insert the tree as is, just use \\[yank].
6448 If optional TREE is given, use this text instead of the kill ring."
6449 (interactive "P")
6450 (unless (org-kill-is-subtree-p tree)
6451 (error "%s"
6452 (substitute-command-keys
6453 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6454 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6455 (^re (concat "^\\(" outline-regexp "\\)"))
6456 (re (concat "\\(" outline-regexp "\\)"))
6457 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6459 (old-level (if (string-match ^re txt)
6460 (- (match-end 0) (match-beginning 0) 1)
6461 -1))
6462 (force-level (cond (level (prefix-numeric-value level))
6463 ((string-match
6464 ^re_ (buffer-substring (point-at-bol) (point)))
6465 (- (match-end 1) (match-beginning 1)))
6466 (t nil)))
6467 (previous-level (save-excursion
6468 (condition-case nil
6469 (progn
6470 (outline-previous-visible-heading 1)
6471 (if (looking-at re)
6472 (- (match-end 0) (match-beginning 0) 1)
6474 (error 1))))
6475 (next-level (save-excursion
6476 (condition-case nil
6477 (progn
6478 (or (looking-at outline-regexp)
6479 (outline-next-visible-heading 1))
6480 (if (looking-at re)
6481 (- (match-end 0) (match-beginning 0) 1)
6483 (error 1))))
6484 (new-level (or force-level (max previous-level next-level)))
6485 (shift (if (or (= old-level -1)
6486 (= new-level -1)
6487 (= old-level new-level))
6489 (- new-level old-level)))
6490 (delta (if (> shift 0) -1 1))
6491 (func (if (> shift 0) 'org-demote 'org-promote))
6492 (org-odd-levels-only nil)
6493 beg end)
6494 ;; Remove the forced level indicator
6495 (if force-level
6496 (delete-region (point-at-bol) (point)))
6497 ;; Paste
6498 (beginning-of-line 1)
6499 (org-back-over-empty-lines) ;; FIXME: correct fix????
6500 (setq beg (point))
6501 (insert-before-markers txt) ;; FIXME: correct fix????
6502 (unless (string-match "\n\\'" txt) (insert "\n"))
6503 (setq end (point))
6504 (goto-char beg)
6505 (skip-chars-forward " \t\n\r")
6506 (setq beg (point))
6507 ;; Shift if necessary
6508 (unless (= shift 0)
6509 (save-restriction
6510 (narrow-to-region beg end)
6511 (while (not (= shift 0))
6512 (org-map-region func (point-min) (point-max))
6513 (setq shift (+ delta shift)))
6514 (goto-char (point-min))))
6515 (when (interactive-p)
6516 (message "Clipboard pasted as level %d subtree" new-level))
6517 (if (and kill-ring
6518 (eq org-subtree-clip (current-kill 0))
6519 org-subtree-clip-folded)
6520 ;; The tree was folded before it was killed/copied
6521 (hide-subtree))))
6523 (defun org-kill-is-subtree-p (&optional txt)
6524 "Check if the current kill is an outline subtree, or a set of trees.
6525 Returns nil if kill does not start with a headline, or if the first
6526 headline level is not the largest headline level in the tree.
6527 So this will actually accept several entries of equal levels as well,
6528 which is OK for `org-paste-subtree'.
6529 If optional TXT is given, check this string instead of the current kill."
6530 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6531 (start-level (and kill
6532 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6533 org-outline-regexp "\\)")
6534 kill)
6535 (- (match-end 2) (match-beginning 2) 1)))
6536 (re (concat "^" org-outline-regexp))
6537 (start (1+ (match-beginning 2))))
6538 (if (not start-level)
6539 (progn
6540 nil) ;; does not even start with a heading
6541 (catch 'exit
6542 (while (setq start (string-match re kill (1+ start)))
6543 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6544 (throw 'exit nil)))
6545 t))))
6547 (defun org-narrow-to-subtree ()
6548 "Narrow buffer to the current subtree."
6549 (interactive)
6550 (save-excursion
6551 (narrow-to-region
6552 (progn (org-back-to-heading) (point))
6553 (progn (org-end-of-subtree t t) (point)))))
6556 ;;; Outline Sorting
6558 (defun org-sort (with-case)
6559 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6560 Optional argument WITH-CASE means sort case-sensitively."
6561 (interactive "P")
6562 (if (org-at-table-p)
6563 (org-call-with-arg 'org-table-sort-lines with-case)
6564 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6566 (defvar org-priority-regexp) ; defined later in the file
6568 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6569 "Sort entries on a certain level of an outline tree.
6570 If there is an active region, the entries in the region are sorted.
6571 Else, if the cursor is before the first entry, sort the top-level items.
6572 Else, the children of the entry at point are sorted.
6574 Sorting can be alphabetically, numerically, and by date/time as given by
6575 the first time stamp in the entry. The command prompts for the sorting
6576 type unless it has been given to the function through the SORTING-TYPE
6577 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6578 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6579 called with point at the beginning of the record. It must return either
6580 a string or a number that should serve as the sorting key for that record.
6582 Comparing entries ignores case by default. However, with an optional argument
6583 WITH-CASE, the sorting considers case as well."
6584 (interactive "P")
6585 (let ((case-func (if with-case 'identity 'downcase))
6586 start beg end stars re re2
6587 txt what tmp plain-list-p)
6588 ;; Find beginning and end of region to sort
6589 (cond
6590 ((org-region-active-p)
6591 ;; we will sort the region
6592 (setq end (region-end)
6593 what "region")
6594 (goto-char (region-beginning))
6595 (if (not (org-on-heading-p)) (outline-next-heading))
6596 (setq start (point)))
6597 ((org-at-item-p)
6598 ;; we will sort this plain list
6599 (org-beginning-of-item-list) (setq start (point))
6600 (org-end-of-item-list) (setq end (point))
6601 (goto-char start)
6602 (setq plain-list-p t
6603 what "plain list"))
6604 ((or (org-on-heading-p)
6605 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6606 ;; we will sort the children of the current headline
6607 (org-back-to-heading)
6608 (setq start (point)
6609 end (progn (org-end-of-subtree t t)
6610 (org-back-over-empty-lines)
6611 (point))
6612 what "children")
6613 (goto-char start)
6614 (show-subtree)
6615 (outline-next-heading))
6617 ;; we will sort the top-level entries in this file
6618 (goto-char (point-min))
6619 (or (org-on-heading-p) (outline-next-heading))
6620 (setq start (point) end (point-max) what "top-level")
6621 (goto-char start)
6622 (show-all)))
6624 (setq beg (point))
6625 (if (>= beg end) (error "Nothing to sort"))
6627 (unless plain-list-p
6628 (looking-at "\\(\\*+\\)")
6629 (setq stars (match-string 1)
6630 re (concat "^" (regexp-quote stars) " +")
6631 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6632 txt (buffer-substring beg end))
6633 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6634 (if (and (not (equal stars "*")) (string-match re2 txt))
6635 (error "Region to sort contains a level above the first entry")))
6637 (unless sorting-type
6638 (message
6639 (if plain-list-p
6640 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6641 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6642 what)
6643 (setq sorting-type (read-char-exclusive))
6645 (and (= (downcase sorting-type) ?f)
6646 (setq getkey-func
6647 (completing-read "Sort using function: "
6648 obarray 'fboundp t nil nil))
6649 (setq getkey-func (intern getkey-func)))
6651 (and (= (downcase sorting-type) ?r)
6652 (setq property
6653 (completing-read "Property: "
6654 (mapcar 'list (org-buffer-property-keys t))
6655 nil t))))
6657 (message "Sorting entries...")
6659 (save-restriction
6660 (narrow-to-region start end)
6662 (let ((dcst (downcase sorting-type))
6663 (now (current-time)))
6664 (sort-subr
6665 (/= dcst sorting-type)
6666 ;; This function moves to the beginning character of the "record" to
6667 ;; be sorted.
6668 (if plain-list-p
6669 (lambda nil
6670 (if (org-at-item-p) t (goto-char (point-max))))
6671 (lambda nil
6672 (if (re-search-forward re nil t)
6673 (goto-char (match-beginning 0))
6674 (goto-char (point-max)))))
6675 ;; This function moves to the last character of the "record" being
6676 ;; sorted.
6677 (if plain-list-p
6678 'org-end-of-item
6679 (lambda nil
6680 (save-match-data
6681 (condition-case nil
6682 (outline-forward-same-level 1)
6683 (error
6684 (goto-char (point-max)))))))
6686 ;; This function returns the value that gets sorted against.
6687 (if plain-list-p
6688 (lambda nil
6689 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6690 (cond
6691 ((= dcst ?n)
6692 (string-to-number (buffer-substring (match-end 0)
6693 (point-at-eol))))
6694 ((= dcst ?a)
6695 (buffer-substring (match-end 0) (point-at-eol)))
6696 ((= dcst ?t)
6697 (if (re-search-forward org-ts-regexp
6698 (point-at-eol) t)
6699 (org-time-string-to-time (match-string 0))
6700 now))
6701 ((= dcst ?f)
6702 (if getkey-func
6703 (progn
6704 (setq tmp (funcall getkey-func))
6705 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6706 tmp)
6707 (error "Invalid key function `%s'" getkey-func)))
6708 (t (error "Invalid sorting type `%c'" sorting-type)))))
6709 (lambda nil
6710 (cond
6711 ((= dcst ?n)
6712 (if (looking-at outline-regexp)
6713 (string-to-number (buffer-substring (match-end 0)
6714 (point-at-eol)))
6715 nil))
6716 ((= dcst ?a)
6717 (funcall case-func (buffer-substring (point-at-bol)
6718 (point-at-eol))))
6719 ((= dcst ?t)
6720 (if (re-search-forward org-ts-regexp
6721 (save-excursion
6722 (forward-line 2)
6723 (point)) t)
6724 (org-time-string-to-time (match-string 0))
6725 now))
6726 ((= dcst ?p)
6727 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6728 (string-to-char (match-string 2))
6729 org-default-priority))
6730 ((= dcst ?r)
6731 (or (org-entry-get nil property) ""))
6732 ((= dcst ?f)
6733 (if getkey-func
6734 (progn
6735 (setq tmp (funcall getkey-func))
6736 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6737 tmp)
6738 (error "Invalid key function `%s'" getkey-func)))
6739 (t (error "Invalid sorting type `%c'" sorting-type)))))
6741 (cond
6742 ((= dcst ?a) 'string<)
6743 ((= dcst ?t) 'time-less-p)
6744 (t nil)))))
6745 (message "Sorting entries...done")))
6747 (defun org-do-sort (table what &optional with-case sorting-type)
6748 "Sort TABLE of WHAT according to SORTING-TYPE.
6749 The user will be prompted for the SORTING-TYPE if the call to this
6750 function does not specify it. WHAT is only for the prompt, to indicate
6751 what is being sorted. The sorting key will be extracted from
6752 the car of the elements of the table.
6753 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6754 (unless sorting-type
6755 (message
6756 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6757 what)
6758 (setq sorting-type (read-char-exclusive)))
6759 (let ((dcst (downcase sorting-type))
6760 extractfun comparefun)
6761 ;; Define the appropriate functions
6762 (cond
6763 ((= dcst ?n)
6764 (setq extractfun 'string-to-number
6765 comparefun (if (= dcst sorting-type) '< '>)))
6766 ((= dcst ?a)
6767 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6768 (lambda(x) (downcase (org-sort-remove-invisible x))))
6769 comparefun (if (= dcst sorting-type)
6770 'string<
6771 (lambda (a b) (and (not (string< a b))
6772 (not (string= a b)))))))
6773 ((= dcst ?t)
6774 (setq extractfun
6775 (lambda (x)
6776 (if (string-match org-ts-regexp x)
6777 (time-to-seconds
6778 (org-time-string-to-time (match-string 0 x)))
6780 comparefun (if (= dcst sorting-type) '< '>)))
6781 (t (error "Invalid sorting type `%c'" sorting-type)))
6783 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6784 table)
6785 (lambda (a b) (funcall comparefun (car a) (car b))))))
6787 ;;;; Plain list items, including checkboxes
6789 ;;; Plain list items
6791 (defun org-at-item-p ()
6792 "Is point in a line starting a hand-formatted item?"
6793 (let ((llt org-plain-list-ordered-item-terminator))
6794 (save-excursion
6795 (goto-char (point-at-bol))
6796 (looking-at
6797 (cond
6798 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6799 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6800 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6801 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6803 (defun org-in-item-p ()
6804 "It the cursor inside a plain list item.
6805 Does not have to be the first line."
6806 (save-excursion
6807 (condition-case nil
6808 (progn
6809 (org-beginning-of-item)
6810 (org-at-item-p)
6812 (error nil))))
6814 (defun org-insert-item (&optional checkbox)
6815 "Insert a new item at the current level.
6816 Return t when things worked, nil when we are not in an item."
6817 (when (save-excursion
6818 (condition-case nil
6819 (progn
6820 (org-beginning-of-item)
6821 (org-at-item-p)
6822 (if (org-invisible-p) (error "Invisible item"))
6824 (error nil)))
6825 (let* ((bul (match-string 0))
6826 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6827 (match-end 0)))
6828 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6829 pos)
6830 (cond
6831 ((and (org-at-item-p) (<= (point) eow))
6832 ;; before the bullet
6833 (beginning-of-line 1)
6834 (open-line (if blank 2 1)))
6835 ((<= (point) eow)
6836 (beginning-of-line 1))
6837 (t (newline (if blank 2 1))))
6838 (insert bul (if checkbox "[ ]" ""))
6839 (just-one-space)
6840 (setq pos (point))
6841 (end-of-line 1)
6842 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6843 (org-maybe-renumber-ordered-list)
6844 (and checkbox (org-update-checkbox-count-maybe))
6847 ;;; Checkboxes
6849 (defun org-at-item-checkbox-p ()
6850 "Is point at a line starting a plain-list item with a checklet?"
6851 (and (org-at-item-p)
6852 (save-excursion
6853 (goto-char (match-end 0))
6854 (skip-chars-forward " \t")
6855 (looking-at "\\[[- X]\\]"))))
6857 (defun org-toggle-checkbox (&optional arg)
6858 "Toggle the checkbox in the current line."
6859 (interactive "P")
6860 (catch 'exit
6861 (let (beg end status (firstnew 'unknown))
6862 (cond
6863 ((org-region-active-p)
6864 (setq beg (region-beginning) end (region-end)))
6865 ((org-on-heading-p)
6866 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6867 ((org-at-item-checkbox-p)
6868 (let ((pos (point)))
6869 (replace-match
6870 (cond (arg "[-]")
6871 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6872 (t "[ ]"))
6873 t t)
6874 (goto-char pos))
6875 (throw 'exit t))
6876 (t (error "Not at a checkbox or heading, and no active region")))
6877 (save-excursion
6878 (goto-char beg)
6879 (while (< (point) end)
6880 (when (org-at-item-checkbox-p)
6881 (setq status (equal (match-string 0) "[X]"))
6882 (when (eq firstnew 'unknown)
6883 (setq firstnew (not status)))
6884 (replace-match
6885 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6886 (beginning-of-line 2)))))
6887 (org-update-checkbox-count-maybe))
6889 (defun org-update-checkbox-count-maybe ()
6890 "Update checkbox statistics unless turned off by user."
6891 (when org-provide-checkbox-statistics
6892 (org-update-checkbox-count)))
6894 (defun org-update-checkbox-count (&optional all)
6895 "Update the checkbox statistics in the current section.
6896 This will find all statistic cookies like [57%] and [6/12] and update them
6897 with the current numbers. With optional prefix argument ALL, do this for
6898 the whole buffer."
6899 (interactive "P")
6900 (save-excursion
6901 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6902 (beg (condition-case nil
6903 (progn (outline-back-to-heading) (point))
6904 (error (point-min))))
6905 (end (move-marker (make-marker)
6906 (progn (outline-next-heading) (point))))
6907 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6908 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6909 b1 e1 f1 c-on c-off lim (cstat 0))
6910 (when all
6911 (goto-char (point-min))
6912 (outline-next-heading)
6913 (setq beg (point) end (point-max)))
6914 (goto-char beg)
6915 (while (re-search-forward re end t)
6916 (setq cstat (1+ cstat)
6917 b1 (match-beginning 0)
6918 e1 (match-end 0)
6919 f1 (match-beginning 1)
6920 lim (cond
6921 ((org-on-heading-p) (outline-next-heading) (point))
6922 ((org-at-item-p) (org-end-of-item) (point))
6923 (t nil))
6924 c-on 0 c-off 0)
6925 (goto-char e1)
6926 (when lim
6927 (while (re-search-forward re-box lim t)
6928 (if (member (match-string 2) '("[ ]" "[-]"))
6929 (setq c-off (1+ c-off))
6930 (setq c-on (1+ c-on))))
6931 ; (delete-region b1 e1)
6932 (goto-char b1)
6933 (insert (if f1
6934 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6935 (format "[%d/%d]" c-on (+ c-on c-off))))
6936 (and (looking-at "\\[.*?\\]")
6937 (replace-match ""))))
6938 (when (interactive-p)
6939 (message "Checkbox satistics updated %s (%d places)"
6940 (if all "in entire file" "in current outline entry") cstat)))))
6942 (defun org-get-checkbox-statistics-face ()
6943 "Select the face for checkbox statistics.
6944 The face will be `org-done' when all relevant boxes are checked. Otherwise
6945 it will be `org-todo'."
6946 (if (match-end 1)
6947 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6948 (if (and (> (match-end 2) (match-beginning 2))
6949 (equal (match-string 2) (match-string 3)))
6950 'org-done
6951 'org-todo)))
6953 (defun org-get-indentation (&optional line)
6954 "Get the indentation of the current line, interpreting tabs.
6955 When LINE is given, assume it represents a line and compute its indentation."
6956 (if line
6957 (if (string-match "^ *" (org-remove-tabs line))
6958 (match-end 0))
6959 (save-excursion
6960 (beginning-of-line 1)
6961 (skip-chars-forward " \t")
6962 (current-column))))
6964 (defun org-remove-tabs (s &optional width)
6965 "Replace tabulators in S with spaces.
6966 Assumes that s is a single line, starting in column 0."
6967 (setq width (or width tab-width))
6968 (while (string-match "\t" s)
6969 (setq s (replace-match
6970 (make-string
6971 (- (* width (/ (+ (match-beginning 0) width) width))
6972 (match-beginning 0)) ?\ )
6973 t t s)))
6976 (defun org-fix-indentation (line ind)
6977 "Fix indentation in LINE.
6978 IND is a cons cell with target and minimum indentation.
6979 If the current indenation in LINE is smaller than the minimum,
6980 leave it alone. If it is larger than ind, set it to the target."
6981 (let* ((l (org-remove-tabs line))
6982 (i (org-get-indentation l))
6983 (i1 (car ind)) (i2 (cdr ind)))
6984 (if (>= i i2) (setq l (substring line i2)))
6985 (if (> i1 0)
6986 (concat (make-string i1 ?\ ) l)
6987 l)))
6989 (defcustom org-empty-line-terminates-plain-lists nil
6990 "Non-nil means, an empty line ends all plain list levels.
6991 When nil, empty lines are part of the preceeding item."
6992 :group 'org-plain-lists
6993 :type 'boolean)
6995 (defun org-beginning-of-item ()
6996 "Go to the beginning of the current hand-formatted item.
6997 If the cursor is not in an item, throw an error."
6998 (interactive)
6999 (let ((pos (point))
7000 (limit (save-excursion
7001 (condition-case nil
7002 (progn
7003 (org-back-to-heading)
7004 (beginning-of-line 2) (point))
7005 (error (point-min)))))
7006 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7007 ind ind1)
7008 (if (org-at-item-p)
7009 (beginning-of-line 1)
7010 (beginning-of-line 1)
7011 (skip-chars-forward " \t")
7012 (setq ind (current-column))
7013 (if (catch 'exit
7014 (while t
7015 (beginning-of-line 0)
7016 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7018 (if (looking-at "[ \t]*$")
7019 (setq ind1 ind-empty)
7020 (skip-chars-forward " \t")
7021 (setq ind1 (current-column)))
7022 (if (< ind1 ind)
7023 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7025 (goto-char pos)
7026 (error "Not in an item")))))
7028 (defun org-end-of-item ()
7029 "Go to the end of the current hand-formatted item.
7030 If the cursor is not in an item, throw an error."
7031 (interactive)
7032 (let* ((pos (point))
7033 ind1
7034 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7035 (limit (save-excursion (outline-next-heading) (point)))
7036 (ind (save-excursion
7037 (org-beginning-of-item)
7038 (skip-chars-forward " \t")
7039 (current-column)))
7040 (end (catch 'exit
7041 (while t
7042 (beginning-of-line 2)
7043 (if (eobp) (throw 'exit (point)))
7044 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7045 (if (looking-at "[ \t]*$")
7046 (setq ind1 ind-empty)
7047 (skip-chars-forward " \t")
7048 (setq ind1 (current-column)))
7049 (if (<= ind1 ind)
7050 (throw 'exit (point-at-bol)))))))
7051 (if end
7052 (goto-char end)
7053 (goto-char pos)
7054 (error "Not in an item"))))
7056 (defun org-next-item ()
7057 "Move to the beginning of the next item in the current plain list.
7058 Error if not at a plain list, or if this is the last item in the list."
7059 (interactive)
7060 (let (ind ind1 (pos (point)))
7061 (org-beginning-of-item)
7062 (setq ind (org-get-indentation))
7063 (org-end-of-item)
7064 (setq ind1 (org-get-indentation))
7065 (unless (and (org-at-item-p) (= ind ind1))
7066 (goto-char pos)
7067 (error "On last item"))))
7069 (defun org-previous-item ()
7070 "Move to the beginning of the previous item in the current plain list.
7071 Error if not at a plain list, or if this is the first item in the list."
7072 (interactive)
7073 (let (beg ind ind1 (pos (point)))
7074 (org-beginning-of-item)
7075 (setq beg (point))
7076 (setq ind (org-get-indentation))
7077 (goto-char beg)
7078 (catch 'exit
7079 (while t
7080 (beginning-of-line 0)
7081 (if (looking-at "[ \t]*$")
7083 (if (<= (setq ind1 (org-get-indentation)) ind)
7084 (throw 'exit t)))))
7085 (condition-case nil
7086 (if (or (not (org-at-item-p))
7087 (< ind1 (1- ind)))
7088 (error "")
7089 (org-beginning-of-item))
7090 (error (goto-char pos)
7091 (error "On first item")))))
7093 (defun org-first-list-item-p ()
7094 "Is this heading the item in a plain list?"
7095 (unless (org-at-item-p)
7096 (error "Not at a plain list item"))
7097 (org-beginning-of-item)
7098 (= (point) (save-excursion (org-beginning-of-item-list))))
7100 (defun org-move-item-down ()
7101 "Move the plain list item at point down, i.e. swap with following item.
7102 Subitems (items with larger indentation) are considered part of the item,
7103 so this really moves item trees."
7104 (interactive)
7105 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7106 (org-beginning-of-item)
7107 (setq beg0 (point))
7108 (save-excursion
7109 (setq ne-beg (org-back-over-empty-lines))
7110 (setq beg (point)))
7111 (goto-char beg0)
7112 (setq ind (org-get-indentation))
7113 (org-end-of-item)
7114 (setq end0 (point))
7115 (setq ind1 (org-get-indentation))
7116 (setq ne-end (org-back-over-empty-lines))
7117 (setq end (point))
7118 (goto-char beg0)
7119 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7120 ;; include less whitespace
7121 (save-excursion
7122 (goto-char beg)
7123 (forward-line (- ne-beg ne-end))
7124 (setq beg (point))))
7125 (goto-char end0)
7126 (if (and (org-at-item-p) (= ind ind1))
7127 (progn
7128 (org-end-of-item)
7129 (org-back-over-empty-lines)
7130 (setq txt (buffer-substring beg end))
7131 (save-excursion
7132 (delete-region beg end))
7133 (setq pos (point))
7134 (insert txt)
7135 (goto-char pos) (org-skip-whitespace)
7136 (org-maybe-renumber-ordered-list))
7137 (goto-char pos)
7138 (error "Cannot move this item further down"))))
7140 (defun org-move-item-up (arg)
7141 "Move the plain list item at point up, i.e. swap with previous item.
7142 Subitems (items with larger indentation) are considered part of the item,
7143 so this really moves item trees."
7144 (interactive "p")
7145 (let (beg beg0 end end0 ind ind1 (pos (point)) txt
7146 ne-beg ne-end ne-ins ins-end)
7147 (org-beginning-of-item)
7148 (setq beg0 (point))
7149 (setq ind (org-get-indentation))
7150 (save-excursion
7151 (setq ne-beg (org-back-over-empty-lines))
7152 (setq beg (point)))
7153 (goto-char beg0)
7154 (org-end-of-item)
7155 (setq ne-end (org-back-over-empty-lines))
7156 (setq end (point))
7157 (goto-char beg0)
7158 (catch 'exit
7159 (while t
7160 (beginning-of-line 0)
7161 (if (looking-at "[ \t]*$")
7162 (if org-empty-line-terminates-plain-lists
7163 (progn
7164 (goto-char pos)
7165 (error "Cannot move this item further up"))
7166 nil)
7167 (if (<= (setq ind1 (org-get-indentation)) ind)
7168 (throw 'exit t)))))
7169 (condition-case nil
7170 (org-beginning-of-item)
7171 (error (goto-char beg)
7172 (error "Cannot move this item further up")))
7173 (setq ind1 (org-get-indentation))
7174 (if (and (org-at-item-p) (= ind ind1))
7175 (progn
7176 (setq ne-ins (org-back-over-empty-lines))
7177 (setq txt (buffer-substring beg end))
7178 (save-excursion
7179 (delete-region beg end))
7180 (setq pos (point))
7181 (insert txt)
7182 (setq ins-end (point))
7183 (goto-char pos) (org-skip-whitespace)
7185 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7186 ;; Move whitespace back to beginning
7187 (save-excursion
7188 (goto-char ins-end)
7189 (let ((kill-whole-line t))
7190 (kill-line (- ne-ins ne-beg)) (point)))
7191 (insert (make-string (- ne-ins ne-beg) ?\n)))
7193 (org-maybe-renumber-ordered-list))
7194 (goto-char pos)
7195 (error "Cannot move this item further up"))))
7197 (defun org-maybe-renumber-ordered-list ()
7198 "Renumber the ordered list at point if setup allows it.
7199 This tests the user option `org-auto-renumber-ordered-lists' before
7200 doing the renumbering."
7201 (interactive)
7202 (when (and org-auto-renumber-ordered-lists
7203 (org-at-item-p))
7204 (if (match-beginning 3)
7205 (org-renumber-ordered-list 1)
7206 (org-fix-bullet-type))))
7208 (defun org-maybe-renumber-ordered-list-safe ()
7209 (condition-case nil
7210 (save-excursion
7211 (org-maybe-renumber-ordered-list))
7212 (error nil)))
7214 (defun org-cycle-list-bullet (&optional which)
7215 "Cycle through the different itemize/enumerate bullets.
7216 This cycle the entire list level through the sequence:
7218 `-' -> `+' -> `*' -> `1.' -> `1)'
7220 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7221 0 meand `-', 1 means `+' etc."
7222 (interactive "P")
7223 (org-preserve-lc
7224 (org-beginning-of-item-list)
7225 (org-at-item-p)
7226 (beginning-of-line 1)
7227 (let ((current (match-string 0))
7228 (prevp (eq which 'previous))
7229 new)
7230 (setq new (cond
7231 ((and (numberp which)
7232 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7233 ((string-match "-" current) (if prevp "1)" "+"))
7234 ((string-match "\\+" current)
7235 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7236 ((string-match "\\*" current) (if prevp "+" "1."))
7237 ((string-match "\\." current) (if prevp "*" "1)"))
7238 ((string-match ")" current) (if prevp "1." "-"))
7239 (t (error "This should not happen"))))
7240 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7241 (org-fix-bullet-type)
7242 (org-maybe-renumber-ordered-list))))
7244 (defun org-get-string-indentation (s)
7245 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7246 (let ((n -1) (i 0) (w tab-width) c)
7247 (catch 'exit
7248 (while (< (setq n (1+ n)) (length s))
7249 (setq c (aref s n))
7250 (cond ((= c ?\ ) (setq i (1+ i)))
7251 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7252 (t (throw 'exit t)))))
7255 (defun org-renumber-ordered-list (arg)
7256 "Renumber an ordered plain list.
7257 Cursor needs to be in the first line of an item, the line that starts
7258 with something like \"1.\" or \"2)\"."
7259 (interactive "p")
7260 (unless (and (org-at-item-p)
7261 (match-beginning 3))
7262 (error "This is not an ordered list"))
7263 (let ((line (org-current-line))
7264 (col (current-column))
7265 (ind (org-get-string-indentation
7266 (buffer-substring (point-at-bol) (match-beginning 3))))
7267 ;; (term (substring (match-string 3) -1))
7268 ind1 (n (1- arg))
7269 fmt)
7270 ;; find where this list begins
7271 (org-beginning-of-item-list)
7272 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7273 (setq fmt (concat "%d" (match-string 1)))
7274 (beginning-of-line 0)
7275 ;; walk forward and replace these numbers
7276 (catch 'exit
7277 (while t
7278 (catch 'next
7279 (beginning-of-line 2)
7280 (if (eobp) (throw 'exit nil))
7281 (if (looking-at "[ \t]*$") (throw 'next nil))
7282 (skip-chars-forward " \t") (setq ind1 (current-column))
7283 (if (> ind1 ind) (throw 'next t))
7284 (if (< ind1 ind) (throw 'exit t))
7285 (if (not (org-at-item-p)) (throw 'exit nil))
7286 (delete-region (match-beginning 2) (match-end 2))
7287 (goto-char (match-beginning 2))
7288 (insert (format fmt (setq n (1+ n)))))))
7289 (goto-line line)
7290 (move-to-column col)))
7292 (defun org-fix-bullet-type ()
7293 "Make sure all items in this list have the same bullet as the firsst item."
7294 (interactive)
7295 (unless (org-at-item-p) (error "This is not a list"))
7296 (let ((line (org-current-line))
7297 (col (current-column))
7298 (ind (current-indentation))
7299 ind1 bullet)
7300 ;; find where this list begins
7301 (org-beginning-of-item-list)
7302 (beginning-of-line 1)
7303 ;; find out what the bullet type is
7304 (looking-at "[ \t]*\\(\\S-+\\)")
7305 (setq bullet (match-string 1))
7306 ;; walk forward and replace these numbers
7307 (beginning-of-line 0)
7308 (catch 'exit
7309 (while t
7310 (catch 'next
7311 (beginning-of-line 2)
7312 (if (eobp) (throw 'exit nil))
7313 (if (looking-at "[ \t]*$") (throw 'next nil))
7314 (skip-chars-forward " \t") (setq ind1 (current-column))
7315 (if (> ind1 ind) (throw 'next t))
7316 (if (< ind1 ind) (throw 'exit t))
7317 (if (not (org-at-item-p)) (throw 'exit nil))
7318 (skip-chars-forward " \t")
7319 (looking-at "\\S-+")
7320 (replace-match bullet))))
7321 (goto-line line)
7322 (move-to-column col)
7323 (if (string-match "[0-9]" bullet)
7324 (org-renumber-ordered-list 1))))
7326 (defun org-beginning-of-item-list ()
7327 "Go to the beginning of the current item list.
7328 I.e. to the first item in this list."
7329 (interactive)
7330 (org-beginning-of-item)
7331 (let ((pos (point-at-bol))
7332 (ind (org-get-indentation))
7333 ind1)
7334 ;; find where this list begins
7335 (catch 'exit
7336 (while t
7337 (catch 'next
7338 (beginning-of-line 0)
7339 (if (looking-at "[ \t]*$")
7340 (throw (if (bobp) 'exit 'next) t))
7341 (skip-chars-forward " \t") (setq ind1 (current-column))
7342 (if (or (< ind1 ind)
7343 (and (= ind1 ind)
7344 (not (org-at-item-p)))
7345 (bobp))
7346 (throw 'exit t)
7347 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7348 (goto-char pos)))
7351 (defun org-end-of-item-list ()
7352 "Go to the end of the current item list.
7353 I.e. to the text after the last item."
7354 (interactive)
7355 (org-beginning-of-item)
7356 (let ((pos (point-at-bol))
7357 (ind (org-get-indentation))
7358 ind1)
7359 ;; find where this list begins
7360 (catch 'exit
7361 (while t
7362 (catch 'next
7363 (beginning-of-line 2)
7364 (if (looking-at "[ \t]*$")
7365 (throw (if (eobp) 'exit 'next) t))
7366 (skip-chars-forward " \t") (setq ind1 (current-column))
7367 (if (or (< ind1 ind)
7368 (and (= ind1 ind)
7369 (not (org-at-item-p)))
7370 (eobp))
7371 (progn
7372 (setq pos (point-at-bol))
7373 (throw 'exit t))))))
7374 (goto-char pos)))
7377 (defvar org-last-indent-begin-marker (make-marker))
7378 (defvar org-last-indent-end-marker (make-marker))
7380 (defun org-outdent-item (arg)
7381 "Outdent a local list item."
7382 (interactive "p")
7383 (org-indent-item (- arg)))
7385 (defun org-indent-item (arg)
7386 "Indent a local list item."
7387 (interactive "p")
7388 (unless (org-at-item-p)
7389 (error "Not on an item"))
7390 (save-excursion
7391 (let (beg end ind ind1 tmp delta ind-down ind-up)
7392 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7393 (setq beg org-last-indent-begin-marker
7394 end org-last-indent-end-marker)
7395 (org-beginning-of-item)
7396 (setq beg (move-marker org-last-indent-begin-marker (point)))
7397 (org-end-of-item)
7398 (setq end (move-marker org-last-indent-end-marker (point))))
7399 (goto-char beg)
7400 (setq tmp (org-item-indent-positions)
7401 ind (car tmp)
7402 ind-down (nth 2 tmp)
7403 ind-up (nth 1 tmp)
7404 delta (if (> arg 0)
7405 (if ind-down (- ind-down ind) 2)
7406 (if ind-up (- ind-up ind) -2)))
7407 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7408 (while (< (point) end)
7409 (beginning-of-line 1)
7410 (skip-chars-forward " \t") (setq ind1 (current-column))
7411 (delete-region (point-at-bol) (point))
7412 (or (eolp) (indent-to-column (+ ind1 delta)))
7413 (beginning-of-line 2))))
7414 (org-fix-bullet-type)
7415 (org-maybe-renumber-ordered-list-safe)
7416 (save-excursion
7417 (beginning-of-line 0)
7418 (condition-case nil (org-beginning-of-item) (error nil))
7419 (org-maybe-renumber-ordered-list-safe)))
7421 (defun org-item-indent-positions ()
7422 "Return indentation for plain list items.
7423 This returns a list with three values: The current indentation, the
7424 parent indentation and the indentation a child should habe.
7425 Assumes cursor in item line."
7426 (let* ((bolpos (point-at-bol))
7427 (ind (org-get-indentation))
7428 ind-down ind-up pos)
7429 (save-excursion
7430 (org-beginning-of-item-list)
7431 (skip-chars-backward "\n\r \t")
7432 (when (org-in-item-p)
7433 (org-beginning-of-item)
7434 (setq ind-up (org-get-indentation))))
7435 (setq pos (point))
7436 (save-excursion
7437 (cond
7438 ((and (condition-case nil (progn (org-previous-item) t)
7439 (error nil))
7440 (or (forward-char 1) t)
7441 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7442 (setq ind-down (org-get-indentation)))
7443 ((and (goto-char pos)
7444 (org-at-item-p))
7445 (goto-char (match-end 0))
7446 (skip-chars-forward " \t")
7447 (setq ind-down (current-column)))))
7448 (list ind ind-up ind-down)))
7450 ;;; The orgstruct minor mode
7452 ;; Define a minor mode which can be used in other modes in order to
7453 ;; integrate the org-mode structure editing commands.
7455 ;; This is really a hack, because the org-mode structure commands use
7456 ;; keys which normally belong to the major mode. Here is how it
7457 ;; works: The minor mode defines all the keys necessary to operate the
7458 ;; structure commands, but wraps the commands into a function which
7459 ;; tests if the cursor is currently at a headline or a plain list
7460 ;; item. If that is the case, the structure command is used,
7461 ;; temporarily setting many Org-mode variables like regular
7462 ;; expressions for filling etc. However, when any of those keys is
7463 ;; used at a different location, function uses `key-binding' to look
7464 ;; up if the key has an associated command in another currently active
7465 ;; keymap (minor modes, major mode, global), and executes that
7466 ;; command. There might be problems if any of the keys is otherwise
7467 ;; used as a prefix key.
7469 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7470 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7471 ;; addresses this by checking explicitly for both bindings.
7473 (defvar orgstruct-mode-map (make-sparse-keymap)
7474 "Keymap for the minor `orgstruct-mode'.")
7476 (defvar org-local-vars nil
7477 "List of local variables, for use by `orgstruct-mode'")
7479 ;;;###autoload
7480 (define-minor-mode orgstruct-mode
7481 "Toggle the minor more `orgstruct-mode'.
7482 This mode is for using Org-mode structure commands in other modes.
7483 The following key behave as if Org-mode was active, if the cursor
7484 is on a headline, or on a plain list item (both in the definition
7485 of Org-mode).
7487 M-up Move entry/item up
7488 M-down Move entry/item down
7489 M-left Promote
7490 M-right Demote
7491 M-S-up Move entry/item up
7492 M-S-down Move entry/item down
7493 M-S-left Promote subtree
7494 M-S-right Demote subtree
7495 M-q Fill paragraph and items like in Org-mode
7496 C-c ^ Sort entries
7497 C-c - Cycle list bullet
7498 TAB Cycle item visibility
7499 M-RET Insert new heading/item
7500 S-M-RET Insert new TODO heading / Chekbox item
7501 C-c C-c Set tags / toggle checkbox"
7502 nil " OrgStruct" nil
7503 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7505 ;;;###autoload
7506 (defun turn-on-orgstruct ()
7507 "Unconditionally turn on `orgstruct-mode'."
7508 (orgstruct-mode 1))
7510 ;;;###autoload
7511 (defun turn-on-orgstruct++ ()
7512 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7513 In addition to setting orgstruct-mode, this also exports all indentation and
7514 autofilling variables from org-mode into the buffer. Note that turning
7515 off orgstruct-mode will *not* remove these additonal settings."
7516 (orgstruct-mode 1)
7517 (let (var val)
7518 (mapc
7519 (lambda (x)
7520 (when (string-match
7521 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7522 (symbol-name (car x)))
7523 (setq var (car x) val (nth 1 x))
7524 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7525 org-local-vars)))
7527 (defun orgstruct-error ()
7528 "Error when there is no default binding for a structure key."
7529 (interactive)
7530 (error "This key has no function outside structure elements"))
7532 (defun orgstruct-setup ()
7533 "Setup orgstruct keymaps."
7534 (let ((nfunc 0)
7535 (bindings
7536 (list
7537 '([(meta up)] org-metaup)
7538 '([(meta down)] org-metadown)
7539 '([(meta left)] org-metaleft)
7540 '([(meta right)] org-metaright)
7541 '([(meta shift up)] org-shiftmetaup)
7542 '([(meta shift down)] org-shiftmetadown)
7543 '([(meta shift left)] org-shiftmetaleft)
7544 '([(meta shift right)] org-shiftmetaright)
7545 '([(shift up)] org-shiftup)
7546 '([(shift down)] org-shiftdown)
7547 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7548 '("\M-q" fill-paragraph)
7549 '("\C-c^" org-sort)
7550 '("\C-c-" org-cycle-list-bullet)))
7551 elt key fun cmd)
7552 (while (setq elt (pop bindings))
7553 (setq nfunc (1+ nfunc))
7554 (setq key (org-key (car elt))
7555 fun (nth 1 elt)
7556 cmd (orgstruct-make-binding fun nfunc key))
7557 (org-defkey orgstruct-mode-map key cmd))
7559 ;; Special treatment needed for TAB and RET
7560 (org-defkey orgstruct-mode-map [(tab)]
7561 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7562 (org-defkey orgstruct-mode-map "\C-i"
7563 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7565 (org-defkey orgstruct-mode-map "\M-\C-m"
7566 (orgstruct-make-binding 'org-insert-heading 105
7567 "\M-\C-m" [(meta return)]))
7568 (org-defkey orgstruct-mode-map [(meta return)]
7569 (orgstruct-make-binding 'org-insert-heading 106
7570 [(meta return)] "\M-\C-m"))
7572 (org-defkey orgstruct-mode-map [(shift meta return)]
7573 (orgstruct-make-binding 'org-insert-todo-heading 107
7574 [(meta return)] "\M-\C-m"))
7576 (unless org-local-vars
7577 (setq org-local-vars (org-get-local-variables)))
7581 (defun orgstruct-make-binding (fun n &rest keys)
7582 "Create a function for binding in the structure minor mode.
7583 FUN is the command to call inside a table. N is used to create a unique
7584 command name. KEYS are keys that should be checked in for a command
7585 to execute outside of tables."
7586 (eval
7587 (list 'defun
7588 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7589 '(arg)
7590 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7591 "Outside of structure, run the binding of `"
7592 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7593 "'.")
7594 '(interactive "p")
7595 (list 'if
7596 '(org-context-p 'headline 'item)
7597 (list 'org-run-like-in-org-mode (list 'quote fun))
7598 (list 'let '(orgstruct-mode)
7599 (list 'call-interactively
7600 (append '(or)
7601 (mapcar (lambda (k)
7602 (list 'key-binding k))
7603 keys)
7604 '('orgstruct-error))))))))
7606 (defun org-context-p (&rest contexts)
7607 "Check if local context is and of CONTEXTS.
7608 Possible values in the list of contexts are `table', `headline', and `item'."
7609 (let ((pos (point)))
7610 (goto-char (point-at-bol))
7611 (prog1 (or (and (memq 'table contexts)
7612 (looking-at "[ \t]*|"))
7613 (and (memq 'headline contexts)
7614 (looking-at "\\*+"))
7615 (and (memq 'item contexts)
7616 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7617 (goto-char pos))))
7619 (defun org-get-local-variables ()
7620 "Return a list of all local variables in an org-mode buffer."
7621 (let (varlist)
7622 (with-current-buffer (get-buffer-create "*Org tmp*")
7623 (erase-buffer)
7624 (org-mode)
7625 (setq varlist (buffer-local-variables)))
7626 (kill-buffer "*Org tmp*")
7627 (delq nil
7628 (mapcar
7629 (lambda (x)
7630 (setq x
7631 (if (symbolp x)
7632 (list x)
7633 (list (car x) (list 'quote (cdr x)))))
7634 (if (string-match
7635 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7636 (symbol-name (car x)))
7637 x nil))
7638 varlist))))
7640 ;;;###autoload
7641 (defun org-run-like-in-org-mode (cmd)
7642 (unless org-local-vars
7643 (setq org-local-vars (org-get-local-variables)))
7644 (eval (list 'let org-local-vars
7645 (list 'call-interactively (list 'quote cmd)))))
7647 ;;;; Archiving
7649 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7651 (defun org-archive-subtree (&optional find-done)
7652 "Move the current subtree to the archive.
7653 The archive can be a certain top-level heading in the current file, or in
7654 a different file. The tree will be moved to that location, the subtree
7655 heading be marked DONE, and the current time will be added.
7657 When called with prefix argument FIND-DONE, find whole trees without any
7658 open TODO items and archive them (after getting confirmation from the user).
7659 If the cursor is not at a headline when this comand is called, try all level
7660 1 trees. If the cursor is on a headline, only try the direct children of
7661 this heading."
7662 (interactive "P")
7663 (if find-done
7664 (org-archive-all-done)
7665 ;; Save all relevant TODO keyword-relatex variables
7667 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7668 (tr-org-todo-keywords-1 org-todo-keywords-1)
7669 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7670 (tr-org-done-keywords org-done-keywords)
7671 (tr-org-todo-regexp org-todo-regexp)
7672 (tr-org-todo-line-regexp org-todo-line-regexp)
7673 (tr-org-odd-levels-only org-odd-levels-only)
7674 (this-buffer (current-buffer))
7675 (org-archive-location org-archive-location)
7676 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7677 ;; start of variables that will be used for saving context
7678 ;; The compiler complains about them - keep them anyway!
7679 (file (abbreviate-file-name (buffer-file-name)))
7680 (time (format-time-string
7681 (substring (cdr org-time-stamp-formats) 1 -1)
7682 (current-time)))
7683 afile heading buffer level newfile-p
7684 category todo priority
7685 ;; start of variables that will be used for savind context
7686 ltags itags prop)
7688 ;; Try to find a local archive location
7689 (save-excursion
7690 (save-restriction
7691 (widen)
7692 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7693 (if (and prop (string-match "\\S-" prop))
7694 (setq org-archive-location prop)
7695 (if (or (re-search-backward re nil t)
7696 (re-search-forward re nil t))
7697 (setq org-archive-location (match-string 1))))))
7699 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7700 (progn
7701 (setq afile (format (match-string 1 org-archive-location)
7702 (file-name-nondirectory buffer-file-name))
7703 heading (match-string 2 org-archive-location)))
7704 (error "Invalid `org-archive-location'"))
7705 (if (> (length afile) 0)
7706 (setq newfile-p (not (file-exists-p afile))
7707 buffer (find-file-noselect afile))
7708 (setq buffer (current-buffer)))
7709 (unless buffer
7710 (error "Cannot access file \"%s\"" afile))
7711 (if (and (> (length heading) 0)
7712 (string-match "^\\*+" heading))
7713 (setq level (match-end 0))
7714 (setq heading nil level 0))
7715 (save-excursion
7716 (org-back-to-heading t)
7717 ;; Get context information that will be lost by moving the tree
7718 (org-refresh-category-properties)
7719 (setq category (org-get-category)
7720 todo (and (looking-at org-todo-line-regexp)
7721 (match-string 2))
7722 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7723 ltags (org-get-tags)
7724 itags (org-delete-all ltags (org-get-tags-at)))
7725 (setq ltags (mapconcat 'identity ltags " ")
7726 itags (mapconcat 'identity itags " "))
7727 ;; We first only copy, in case something goes wrong
7728 ;; we need to protect this-command, to avoid kill-region sets it,
7729 ;; which would lead to duplication of subtrees
7730 (let (this-command) (org-copy-subtree))
7731 (set-buffer buffer)
7732 ;; Enforce org-mode for the archive buffer
7733 (if (not (org-mode-p))
7734 ;; Force the mode for future visits.
7735 (let ((org-insert-mode-line-in-empty-file t)
7736 (org-inhibit-startup t))
7737 (call-interactively 'org-mode)))
7738 (when newfile-p
7739 (goto-char (point-max))
7740 (insert (format "\nArchived entries from file %s\n\n"
7741 (buffer-file-name this-buffer))))
7742 ;; Force the TODO keywords of the original buffer
7743 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7744 (org-todo-keywords-1 tr-org-todo-keywords-1)
7745 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7746 (org-done-keywords tr-org-done-keywords)
7747 (org-todo-regexp tr-org-todo-regexp)
7748 (org-todo-line-regexp tr-org-todo-line-regexp)
7749 (org-odd-levels-only
7750 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7751 org-odd-levels-only
7752 tr-org-odd-levels-only)))
7753 (goto-char (point-min))
7754 (if heading
7755 (progn
7756 (if (re-search-forward
7757 (concat "^" (regexp-quote heading)
7758 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7759 nil t)
7760 (goto-char (match-end 0))
7761 ;; Heading not found, just insert it at the end
7762 (goto-char (point-max))
7763 (or (bolp) (insert "\n"))
7764 (insert "\n" heading "\n")
7765 (end-of-line 0))
7766 ;; Make the subtree visible
7767 (show-subtree)
7768 (org-end-of-subtree t)
7769 (skip-chars-backward " \t\r\n")
7770 (and (looking-at "[ \t\r\n]*")
7771 (replace-match "\n\n")))
7772 ;; No specific heading, just go to end of file.
7773 (goto-char (point-max)) (insert "\n"))
7774 ;; Paste
7775 (org-paste-subtree (org-get-legal-level level 1))
7777 ;; Mark the entry as done
7778 (when (and org-archive-mark-done
7779 (looking-at org-todo-line-regexp)
7780 (or (not (match-end 2))
7781 (not (member (match-string 2) org-done-keywords))))
7782 (let (org-log-done)
7783 (org-todo
7784 (car (or (member org-archive-mark-done org-done-keywords)
7785 org-done-keywords)))))
7787 ;; Add the context info
7788 (when org-archive-save-context-info
7789 (let ((l org-archive-save-context-info) e n v)
7790 (while (setq e (pop l))
7791 (when (and (setq v (symbol-value e))
7792 (stringp v) (string-match "\\S-" v))
7793 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7794 (org-entry-put (point) n v)))))
7796 ;; Save the buffer, if it is not the same buffer.
7797 (if (not (eq this-buffer buffer)) (save-buffer))))
7798 ;; Here we are back in the original buffer. Everything seems to have
7799 ;; worked. So now cut the tree and finish up.
7800 (let (this-command) (org-cut-subtree))
7801 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7802 (message "Subtree archived %s"
7803 (if (eq this-buffer buffer)
7804 (concat "under heading: " heading)
7805 (concat "in file: " (abbreviate-file-name afile)))))))
7807 (defun org-refresh-category-properties ()
7808 "Refresh category text properties in teh buffer."
7809 (let ((def-cat (cond
7810 ((null org-category)
7811 (if buffer-file-name
7812 (file-name-sans-extension
7813 (file-name-nondirectory buffer-file-name))
7814 "???"))
7815 ((symbolp org-category) (symbol-name org-category))
7816 (t org-category)))
7817 beg end cat pos optionp)
7818 (org-unmodified
7819 (save-excursion
7820 (save-restriction
7821 (widen)
7822 (goto-char (point-min))
7823 (put-text-property (point) (point-max) 'org-category def-cat)
7824 (while (re-search-forward
7825 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7826 (setq pos (match-end 0)
7827 optionp (equal (char-after (match-beginning 0)) ?#)
7828 cat (org-trim (match-string 2)))
7829 (if optionp
7830 (setq beg (point-at-bol) end (point-max))
7831 (org-back-to-heading t)
7832 (setq beg (point) end (org-end-of-subtree t t)))
7833 (put-text-property beg end 'org-category cat)
7834 (goto-char pos)))))))
7836 (defun org-archive-all-done (&optional tag)
7837 "Archive sublevels of the current tree without open TODO items.
7838 If the cursor is not on a headline, try all level 1 trees. If
7839 it is on a headline, try all direct children.
7840 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7841 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7842 (rea (concat ".*:" org-archive-tag ":"))
7843 (begm (make-marker))
7844 (endm (make-marker))
7845 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7846 "Move subtree to archive (no open TODO items)? "))
7847 beg end (cntarch 0))
7848 (if (org-on-heading-p)
7849 (progn
7850 (setq re1 (concat "^" (regexp-quote
7851 (make-string
7852 (1+ (- (match-end 0) (match-beginning 0)))
7853 ?*))
7854 " "))
7855 (move-marker begm (point))
7856 (move-marker endm (org-end-of-subtree t)))
7857 (setq re1 "^* ")
7858 (move-marker begm (point-min))
7859 (move-marker endm (point-max)))
7860 (save-excursion
7861 (goto-char begm)
7862 (while (re-search-forward re1 endm t)
7863 (setq beg (match-beginning 0)
7864 end (save-excursion (org-end-of-subtree t) (point)))
7865 (goto-char beg)
7866 (if (re-search-forward re end t)
7867 (goto-char end)
7868 (goto-char beg)
7869 (if (and (or (not tag) (not (looking-at rea)))
7870 (y-or-n-p question))
7871 (progn
7872 (if tag
7873 (org-toggle-tag org-archive-tag 'on)
7874 (org-archive-subtree))
7875 (setq cntarch (1+ cntarch)))
7876 (goto-char end)))))
7877 (message "%d trees archived" cntarch)))
7879 (defun org-cycle-hide-drawers (state)
7880 "Re-hide all drawers after a visibility state change."
7881 (when (and (org-mode-p)
7882 (not (memq state '(overview folded))))
7883 (save-excursion
7884 (let* ((globalp (memq state '(contents all)))
7885 (beg (if globalp (point-min) (point)))
7886 (end (if globalp (point-max) (org-end-of-subtree t))))
7887 (goto-char beg)
7888 (while (re-search-forward org-drawer-regexp end t)
7889 (org-flag-drawer t))))))
7891 (defun org-flag-drawer (flag)
7892 (save-excursion
7893 (beginning-of-line 1)
7894 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7895 (let ((b (match-end 0)))
7896 (if (re-search-forward
7897 "^[ \t]*:END:"
7898 (save-excursion (outline-next-heading) (point)) t)
7899 (outline-flag-region b (point-at-eol) flag)
7900 (error ":END: line missing"))))))
7902 (defun org-cycle-hide-archived-subtrees (state)
7903 "Re-hide all archived subtrees after a visibility state change."
7904 (when (and (not org-cycle-open-archived-trees)
7905 (not (memq state '(overview folded))))
7906 (save-excursion
7907 (let* ((globalp (memq state '(contents all)))
7908 (beg (if globalp (point-min) (point)))
7909 (end (if globalp (point-max) (org-end-of-subtree t))))
7910 (org-hide-archived-subtrees beg end)
7911 (goto-char beg)
7912 (if (looking-at (concat ".*:" org-archive-tag ":"))
7913 (message "%s" (substitute-command-keys
7914 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7916 (defun org-force-cycle-archived ()
7917 "Cycle subtree even if it is archived."
7918 (interactive)
7919 (setq this-command 'org-cycle)
7920 (let ((org-cycle-open-archived-trees t))
7921 (call-interactively 'org-cycle)))
7923 (defun org-hide-archived-subtrees (beg end)
7924 "Re-hide all archived subtrees after a visibility state change."
7925 (save-excursion
7926 (let* ((re (concat ":" org-archive-tag ":")))
7927 (goto-char beg)
7928 (while (re-search-forward re end t)
7929 (and (org-on-heading-p) (hide-subtree))
7930 (org-end-of-subtree t)))))
7932 (defun org-toggle-tag (tag &optional onoff)
7933 "Toggle the tag TAG for the current line.
7934 If ONOFF is `on' or `off', don't toggle but set to this state."
7935 (unless (org-on-heading-p t) (error "Not on headling"))
7936 (let (res current)
7937 (save-excursion
7938 (beginning-of-line)
7939 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7940 (point-at-eol) t)
7941 (progn
7942 (setq current (match-string 1))
7943 (replace-match ""))
7944 (setq current ""))
7945 (setq current (nreverse (org-split-string current ":")))
7946 (cond
7947 ((eq onoff 'on)
7948 (setq res t)
7949 (or (member tag current) (push tag current)))
7950 ((eq onoff 'off)
7951 (or (not (member tag current)) (setq current (delete tag current))))
7952 (t (if (member tag current)
7953 (setq current (delete tag current))
7954 (setq res t)
7955 (push tag current))))
7956 (end-of-line 1)
7957 (if current
7958 (progn
7959 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
7960 (org-set-tags nil t))
7961 (delete-horizontal-space))
7962 (run-hooks 'org-after-tags-change-hook))
7963 res))
7965 (defun org-toggle-archive-tag (&optional arg)
7966 "Toggle the archive tag for the current headline.
7967 With prefix ARG, check all children of current headline and offer tagging
7968 the children that do not contain any open TODO items."
7969 (interactive "P")
7970 (if arg
7971 (org-archive-all-done 'tag)
7972 (let (set)
7973 (save-excursion
7974 (org-back-to-heading t)
7975 (setq set (org-toggle-tag org-archive-tag))
7976 (when set (hide-subtree)))
7977 (and set (beginning-of-line 1))
7978 (message "Subtree %s" (if set "archived" "unarchived")))))
7981 ;;;; Tables
7983 ;;; The table editor
7985 ;; Watch out: Here we are talking about two different kind of tables.
7986 ;; Most of the code is for the tables created with the Org-mode table editor.
7987 ;; Sometimes, we talk about tables created and edited with the table.el
7988 ;; Emacs package. We call the former org-type tables, and the latter
7989 ;; table.el-type tables.
7991 (defun org-before-change-function (beg end)
7992 "Every change indicates that a table might need an update."
7993 (setq org-table-may-need-update t))
7995 (defconst org-table-line-regexp "^[ \t]*|"
7996 "Detects an org-type table line.")
7997 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7998 "Detects an org-type table line.")
7999 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8000 "Detects a table line marked for automatic recalculation.")
8001 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8002 "Detects a table line marked for automatic recalculation.")
8003 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8004 "Detects a table line marked for automatic recalculation.")
8005 (defconst org-table-hline-regexp "^[ \t]*|-"
8006 "Detects an org-type table hline.")
8007 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8008 "Detects a table-type table hline.")
8009 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8010 "Detects an org-type or table-type table.")
8011 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8012 "Searching from within a table (any type) this finds the first line
8013 outside the table.")
8014 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8015 "Searching from within a table (any type) this finds the first line
8016 outside the table.")
8018 (defvar org-table-last-highlighted-reference nil)
8019 (defvar org-table-formula-history nil)
8021 (defvar org-table-column-names nil
8022 "Alist with column names, derived from the `!' line.")
8023 (defvar org-table-column-name-regexp nil
8024 "Regular expression matching the current column names.")
8025 (defvar org-table-local-parameters nil
8026 "Alist with parameter names, derived from the `$' line.")
8027 (defvar org-table-named-field-locations nil
8028 "Alist with locations of named fields.")
8030 (defvar org-table-current-line-types nil
8031 "Table row types, non-nil only for the duration of a comand.")
8032 (defvar org-table-current-begin-line nil
8033 "Table begin line, non-nil only for the duration of a comand.")
8034 (defvar org-table-current-begin-pos nil
8035 "Table begin position, non-nil only for the duration of a comand.")
8036 (defvar org-table-dlines nil
8037 "Vector of data line line numbers in the current table.")
8038 (defvar org-table-hlines nil
8039 "Vector of hline line numbers in the current table.")
8041 (defconst org-table-range-regexp
8042 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8043 ;; 1 2 3 4 5
8044 "Regular expression for matching ranges in formulas.")
8046 (defconst org-table-range-regexp2
8047 (concat
8048 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8049 "\\.\\."
8050 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8051 "Match a range for reference display.")
8053 (defconst org-table-translate-regexp
8054 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8055 "Match a reference that needs translation, for reference display.")
8057 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8059 (defun org-table-create-with-table.el ()
8060 "Use the table.el package to insert a new table.
8061 If there is already a table at point, convert between Org-mode tables
8062 and table.el tables."
8063 (interactive)
8064 (require 'table)
8065 (cond
8066 ((org-at-table.el-p)
8067 (if (y-or-n-p "Convert table to Org-mode table? ")
8068 (org-table-convert)))
8069 ((org-at-table-p)
8070 (if (y-or-n-p "Convert table to table.el table? ")
8071 (org-table-convert)))
8072 (t (call-interactively 'table-insert))))
8074 (defun org-table-create-or-convert-from-region (arg)
8075 "Convert region to table, or create an empty table.
8076 If there is an active region, convert it to a table, using the function
8077 `org-table-convert-region'. See the documentation of that function
8078 to learn how the prefix argument is interpreted to determine the field
8079 separator.
8080 If there is no such region, create an empty table with `org-table-create'."
8081 (interactive "P")
8082 (if (org-region-active-p)
8083 (org-table-convert-region (region-beginning) (region-end) arg)
8084 (org-table-create arg)))
8086 (defun org-table-create (&optional size)
8087 "Query for a size and insert a table skeleton.
8088 SIZE is a string Columns x Rows like for example \"3x2\"."
8089 (interactive "P")
8090 (unless size
8091 (setq size (read-string
8092 (concat "Table size Columns x Rows [e.g. "
8093 org-table-default-size "]: ")
8094 "" nil org-table-default-size)))
8096 (let* ((pos (point))
8097 (indent (make-string (current-column) ?\ ))
8098 (split (org-split-string size " *x *"))
8099 (rows (string-to-number (nth 1 split)))
8100 (columns (string-to-number (car split)))
8101 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8102 "\n")))
8103 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8104 (point-at-bol) (point)))
8105 (beginning-of-line 1)
8106 (newline))
8107 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8108 (dotimes (i rows) (insert line))
8109 (goto-char pos)
8110 (if (> rows 1)
8111 ;; Insert a hline after the first row.
8112 (progn
8113 (end-of-line 1)
8114 (insert "\n|-")
8115 (goto-char pos)))
8116 (org-table-align)))
8118 (defun org-table-convert-region (beg0 end0 &optional separator)
8119 "Convert region to a table.
8120 The region goes from BEG0 to END0, but these borders will be moved
8121 slightly, to make sure a beginning of line in the first line is included.
8123 SEPARATOR specifies the field separator in the lines. It can have the
8124 following values:
8126 '(4) Use the comma as a field separator
8127 '(16) Use a TAB as field separator
8128 integer When a number, use that many spaces as field separator
8129 nil When nil, the command tries to be smart and figure out the
8130 separator in the following way:
8131 - when each line contains a TAB, assume TAB-separated material
8132 - when each line contains a comme, assume CSV material
8133 - else, assume one or more SPACE charcters as separator."
8134 (interactive "rP")
8135 (let* ((beg (min beg0 end0))
8136 (end (max beg0 end0))
8138 (goto-char beg)
8139 (beginning-of-line 1)
8140 (setq beg (move-marker (make-marker) (point)))
8141 (goto-char end)
8142 (if (bolp) (backward-char 1) (end-of-line 1))
8143 (setq end (move-marker (make-marker) (point)))
8144 ;; Get the right field separator
8145 (unless separator
8146 (goto-char beg)
8147 (setq separator
8148 (cond
8149 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8150 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8151 (t 1))))
8152 (setq re (cond
8153 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8154 ((equal separator '(16)) "^\\|\t")
8155 ((integerp separator)
8156 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8157 (t (error "This should not happen"))))
8158 (goto-char beg)
8159 (while (re-search-forward re end t)
8160 (replace-match "| " t t))
8161 (goto-char beg)
8162 (insert " ")
8163 (org-table-align)))
8165 (defun org-table-import (file arg)
8166 "Import FILE as a table.
8167 The file is assumed to be tab-separated. Such files can be produced by most
8168 spreadsheet and database applications. If no tabs (at least one per line)
8169 are found, lines will be split on whitespace into fields."
8170 (interactive "f\nP")
8171 (or (bolp) (newline))
8172 (let ((beg (point))
8173 (pm (point-max)))
8174 (insert-file-contents file)
8175 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8177 (defun org-table-export ()
8178 "Export table as a tab-separated file.
8179 Such a file can be imported into a spreadsheet program like Excel."
8180 (interactive)
8181 (let* ((beg (org-table-begin))
8182 (end (org-table-end))
8183 (table (buffer-substring beg end))
8184 (file (read-file-name "Export table to: "))
8185 buf)
8186 (unless (or (not (file-exists-p file))
8187 (y-or-n-p (format "Overwrite file %s? " file)))
8188 (error "Abort"))
8189 (with-current-buffer (find-file-noselect file)
8190 (setq buf (current-buffer))
8191 (erase-buffer)
8192 (fundamental-mode)
8193 (insert table)
8194 (goto-char (point-min))
8195 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8196 (replace-match "" t t)
8197 (end-of-line 1))
8198 (goto-char (point-min))
8199 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8200 (replace-match "" t t)
8201 (goto-char (min (1+ (point)) (point-max))))
8202 (goto-char (point-min))
8203 (while (re-search-forward "^-[-+]*$" nil t)
8204 (replace-match "")
8205 (if (looking-at "\n")
8206 (delete-char 1)))
8207 (goto-char (point-min))
8208 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8209 (replace-match "\t" t t))
8210 (save-buffer))
8211 (kill-buffer buf)))
8213 (defvar org-table-aligned-begin-marker (make-marker)
8214 "Marker at the beginning of the table last aligned.
8215 Used to check if cursor still is in that table, to minimize realignment.")
8216 (defvar org-table-aligned-end-marker (make-marker)
8217 "Marker at the end of the table last aligned.
8218 Used to check if cursor still is in that table, to minimize realignment.")
8219 (defvar org-table-last-alignment nil
8220 "List of flags for flushright alignment, from the last re-alignment.
8221 This is being used to correctly align a single field after TAB or RET.")
8222 (defvar org-table-last-column-widths nil
8223 "List of max width of fields in each column.
8224 This is being used to correctly align a single field after TAB or RET.")
8225 (defvar org-table-overlay-coordinates nil
8226 "Overlay coordinates after each align of a table.")
8227 (make-variable-buffer-local 'org-table-overlay-coordinates)
8229 (defvar org-last-recalc-line nil)
8230 (defconst org-narrow-column-arrow "=>"
8231 "Used as display property in narrowed table columns.")
8233 (defun org-table-align ()
8234 "Align the table at point by aligning all vertical bars."
8235 (interactive)
8236 (let* (
8237 ;; Limits of table
8238 (beg (org-table-begin))
8239 (end (org-table-end))
8240 ;; Current cursor position
8241 (linepos (org-current-line))
8242 (colpos (org-table-current-column))
8243 (winstart (window-start))
8244 (winstartline (org-current-line (min winstart (1- (point-max)))))
8245 lines (new "") lengths l typenums ty fields maxfields i
8246 column
8247 (indent "") cnt frac
8248 rfmt hfmt
8249 (spaces '(1 . 1))
8250 (sp1 (car spaces))
8251 (sp2 (cdr spaces))
8252 (rfmt1 (concat
8253 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8254 (hfmt1 (concat
8255 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8256 emptystrings links dates emph narrow fmax f1 len c e)
8257 (untabify beg end)
8258 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8259 ;; Check if we have links or dates
8260 (goto-char beg)
8261 (setq links (re-search-forward org-bracket-link-regexp end t))
8262 (goto-char beg)
8263 (setq emph (and org-hide-emphasis-markers
8264 (re-search-forward org-emph-re end t)))
8265 (goto-char beg)
8266 (setq dates (and org-display-custom-times
8267 (re-search-forward org-ts-regexp-both end t)))
8268 ;; Make sure the link properties are right
8269 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8270 ;; Make sure the date properties are right
8271 (when dates (goto-char beg) (while (org-activate-dates end)))
8272 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8274 ;; Check if we are narrowing any columns
8275 (goto-char beg)
8276 (setq narrow (and org-format-transports-properties-p
8277 (re-search-forward "<[0-9]+>" end t)))
8278 ;; Get the rows
8279 (setq lines (org-split-string
8280 (buffer-substring beg end) "\n"))
8281 ;; Store the indentation of the first line
8282 (if (string-match "^ *" (car lines))
8283 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8284 ;; Mark the hlines by setting the corresponding element to nil
8285 ;; At the same time, we remove trailing space.
8286 (setq lines (mapcar (lambda (l)
8287 (if (string-match "^ *|-" l)
8289 (if (string-match "[ \t]+$" l)
8290 (substring l 0 (match-beginning 0))
8291 l)))
8292 lines))
8293 ;; Get the data fields by splitting the lines.
8294 (setq fields (mapcar
8295 (lambda (l)
8296 (org-split-string l " *| *"))
8297 (delq nil (copy-sequence lines))))
8298 ;; How many fields in the longest line?
8299 (condition-case nil
8300 (setq maxfields (apply 'max (mapcar 'length fields)))
8301 (error
8302 (kill-region beg end)
8303 (org-table-create org-table-default-size)
8304 (error "Empty table - created default table")))
8305 ;; A list of empty strings to fill any short rows on output
8306 (setq emptystrings (make-list maxfields ""))
8307 ;; Check for special formatting.
8308 (setq i -1)
8309 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8310 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8311 ;; Check if there is an explicit width specified
8312 (when narrow
8313 (setq c column fmax nil)
8314 (while c
8315 (setq e (pop c))
8316 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8317 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8318 ;; Find fields that are wider than fmax, and shorten them
8319 (when fmax
8320 (loop for xx in column do
8321 (when (and (stringp xx)
8322 (> (org-string-width xx) fmax))
8323 (org-add-props xx nil
8324 'help-echo
8325 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8326 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8327 (unless (> f1 1)
8328 (error "Cannot narrow field starting with wide link \"%s\""
8329 (match-string 0 xx)))
8330 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8331 (add-text-properties (- f1 2) f1
8332 (list 'display org-narrow-column-arrow)
8333 xx)))))
8334 ;; Get the maximum width for each column
8335 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8336 ;; Get the fraction of numbers, to decide about alignment of the column
8337 (setq cnt 0 frac 0.0)
8338 (loop for x in column do
8339 (if (equal x "")
8341 (setq frac ( / (+ (* frac cnt)
8342 (if (string-match org-table-number-regexp x) 1 0))
8343 (setq cnt (1+ cnt))))))
8344 (push (>= frac org-table-number-fraction) typenums))
8345 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8347 ;; Store the alignment of this table, for later editing of single fields
8348 (setq org-table-last-alignment typenums
8349 org-table-last-column-widths lengths)
8351 ;; With invisible characters, `format' does not get the field width right
8352 ;; So we need to make these fields wide by hand.
8353 (when (or links emph)
8354 (loop for i from 0 upto (1- maxfields) do
8355 (setq len (nth i lengths))
8356 (loop for j from 0 upto (1- (length fields)) do
8357 (setq c (nthcdr i (car (nthcdr j fields))))
8358 (if (and (stringp (car c))
8359 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8360 ; (string-match org-bracket-link-regexp (car c))
8361 (< (org-string-width (car c)) len))
8362 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8364 ;; Compute the formats needed for output of the table
8365 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8366 (while (setq l (pop lengths))
8367 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8368 (setq rfmt (concat rfmt (format rfmt1 ty l))
8369 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8370 (setq rfmt (concat rfmt "\n")
8371 hfmt (concat (substring hfmt 0 -1) "|\n"))
8373 (setq new (mapconcat
8374 (lambda (l)
8375 (if l (apply 'format rfmt
8376 (append (pop fields) emptystrings))
8377 hfmt))
8378 lines ""))
8379 ;; Replace the old one
8380 (delete-region beg end)
8381 (move-marker end nil)
8382 (move-marker org-table-aligned-begin-marker (point))
8383 (insert new)
8384 (move-marker org-table-aligned-end-marker (point))
8385 (when (and orgtbl-mode (not (org-mode-p)))
8386 (goto-char org-table-aligned-begin-marker)
8387 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8388 ;; Try to move to the old location
8389 (goto-line winstartline)
8390 (setq winstart (point-at-bol))
8391 (goto-line linepos)
8392 (set-window-start (selected-window) winstart 'noforce)
8393 (org-table-goto-column colpos)
8394 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8395 (setq org-table-may-need-update nil)
8398 (defun org-string-width (s)
8399 "Compute width of string, ignoring invisible characters.
8400 This ignores character with invisibility property `org-link', and also
8401 characters with property `org-cwidth', because these will become invisible
8402 upon the next fontification round."
8403 (let (b l)
8404 (when (or (eq t buffer-invisibility-spec)
8405 (assq 'org-link buffer-invisibility-spec))
8406 (while (setq b (text-property-any 0 (length s)
8407 'invisible 'org-link s))
8408 (setq s (concat (substring s 0 b)
8409 (substring s (or (next-single-property-change
8410 b 'invisible s) (length s)))))))
8411 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8412 (setq s (concat (substring s 0 b)
8413 (substring s (or (next-single-property-change
8414 b 'org-cwidth s) (length s))))))
8415 (setq l (string-width s) b -1)
8416 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8417 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8420 (defun org-table-begin (&optional table-type)
8421 "Find the beginning of the table and return its position.
8422 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8423 (save-excursion
8424 (if (not (re-search-backward
8425 (if table-type org-table-any-border-regexp
8426 org-table-border-regexp)
8427 nil t))
8428 (progn (goto-char (point-min)) (point))
8429 (goto-char (match-beginning 0))
8430 (beginning-of-line 2)
8431 (point))))
8433 (defun org-table-end (&optional table-type)
8434 "Find the end of the table and return its position.
8435 With argument TABLE-TYPE, go to the end of a table.el-type table."
8436 (save-excursion
8437 (if (not (re-search-forward
8438 (if table-type org-table-any-border-regexp
8439 org-table-border-regexp)
8440 nil t))
8441 (goto-char (point-max))
8442 (goto-char (match-beginning 0)))
8443 (point-marker)))
8445 (defun org-table-justify-field-maybe (&optional new)
8446 "Justify the current field, text to left, number to right.
8447 Optional argument NEW may specify text to replace the current field content."
8448 (cond
8449 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8450 ((org-at-table-hline-p))
8451 ((and (not new)
8452 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8453 (current-buffer)))
8454 (< (point) org-table-aligned-begin-marker)
8455 (>= (point) org-table-aligned-end-marker)))
8456 ;; This is not the same table, force a full re-align
8457 (setq org-table-may-need-update t))
8458 (t ;; realign the current field, based on previous full realign
8459 (let* ((pos (point)) s
8460 (col (org-table-current-column))
8461 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8462 l f n o e)
8463 (when (> col 0)
8464 (skip-chars-backward "^|\n")
8465 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8466 (progn
8467 (setq s (match-string 1)
8468 o (match-string 0)
8469 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8470 e (not (= (match-beginning 2) (match-end 2))))
8471 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8472 l (if e "|" (setq org-table-may-need-update t) ""))
8473 n (format f s))
8474 (if new
8475 (if (<= (length new) l) ;; FIXME: length -> str-width?
8476 (setq n (format f new))
8477 (setq n (concat new "|") org-table-may-need-update t)))
8478 (or (equal n o)
8479 (let (org-table-may-need-update)
8480 (replace-match n t t))))
8481 (setq org-table-may-need-update t))
8482 (goto-char pos))))))
8484 (defun org-table-next-field ()
8485 "Go to the next field in the current table, creating new lines as needed.
8486 Before doing so, re-align the table if necessary."
8487 (interactive)
8488 (org-table-maybe-eval-formula)
8489 (org-table-maybe-recalculate-line)
8490 (if (and org-table-automatic-realign
8491 org-table-may-need-update)
8492 (org-table-align))
8493 (let ((end (org-table-end)))
8494 (if (org-at-table-hline-p)
8495 (end-of-line 1))
8496 (condition-case nil
8497 (progn
8498 (re-search-forward "|" end)
8499 (if (looking-at "[ \t]*$")
8500 (re-search-forward "|" end))
8501 (if (and (looking-at "-")
8502 org-table-tab-jumps-over-hlines
8503 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8504 (goto-char (match-beginning 1)))
8505 (if (looking-at "-")
8506 (progn
8507 (beginning-of-line 0)
8508 (org-table-insert-row 'below))
8509 (if (looking-at " ") (forward-char 1))))
8510 (error
8511 (org-table-insert-row 'below)))))
8513 (defun org-table-previous-field ()
8514 "Go to the previous field in the table.
8515 Before doing so, re-align the table if necessary."
8516 (interactive)
8517 (org-table-justify-field-maybe)
8518 (org-table-maybe-recalculate-line)
8519 (if (and org-table-automatic-realign
8520 org-table-may-need-update)
8521 (org-table-align))
8522 (if (org-at-table-hline-p)
8523 (end-of-line 1))
8524 (re-search-backward "|" (org-table-begin))
8525 (re-search-backward "|" (org-table-begin))
8526 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8527 (re-search-backward "|" (org-table-begin)))
8528 (if (looking-at "| ?")
8529 (goto-char (match-end 0))))
8531 (defun org-table-next-row ()
8532 "Go to the next row (same column) in the current table.
8533 Before doing so, re-align the table if necessary."
8534 (interactive)
8535 (org-table-maybe-eval-formula)
8536 (org-table-maybe-recalculate-line)
8537 (if (or (looking-at "[ \t]*$")
8538 (save-excursion (skip-chars-backward " \t") (bolp)))
8539 (newline)
8540 (if (and org-table-automatic-realign
8541 org-table-may-need-update)
8542 (org-table-align))
8543 (let ((col (org-table-current-column)))
8544 (beginning-of-line 2)
8545 (if (or (not (org-at-table-p))
8546 (org-at-table-hline-p))
8547 (progn
8548 (beginning-of-line 0)
8549 (org-table-insert-row 'below)))
8550 (org-table-goto-column col)
8551 (skip-chars-backward "^|\n\r")
8552 (if (looking-at " ") (forward-char 1)))))
8554 (defun org-table-copy-down (n)
8555 "Copy a field down in the current column.
8556 If the field at the cursor is empty, copy into it the content of the nearest
8557 non-empty field above. With argument N, use the Nth non-empty field.
8558 If the current field is not empty, it is copied down to the next row, and
8559 the cursor is moved with it. Therefore, repeating this command causes the
8560 column to be filled row-by-row.
8561 If the variable `org-table-copy-increment' is non-nil and the field is an
8562 integer or a timestamp, it will be incremented while copying. In the case of
8563 a timestamp, if the cursor is on the year, change the year. If it is on the
8564 month or the day, change that. Point will stay on the current date field
8565 in order to easily repeat the interval."
8566 (interactive "p")
8567 (let* ((colpos (org-table-current-column))
8568 (col (current-column))
8569 (field (org-table-get-field))
8570 (non-empty (string-match "[^ \t]" field))
8571 (beg (org-table-begin))
8572 txt)
8573 (org-table-check-inside-data-field)
8574 (if non-empty
8575 (progn
8576 (setq txt (org-trim field))
8577 (org-table-next-row)
8578 (org-table-blank-field))
8579 (save-excursion
8580 (setq txt
8581 (catch 'exit
8582 (while (progn (beginning-of-line 1)
8583 (re-search-backward org-table-dataline-regexp
8584 beg t))
8585 (org-table-goto-column colpos t)
8586 (if (and (looking-at
8587 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8588 (= (setq n (1- n)) 0))
8589 (throw 'exit (match-string 1))))))))
8590 (if txt
8591 (progn
8592 (if (and org-table-copy-increment
8593 (string-match "^[0-9]+$" txt))
8594 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8595 (insert txt)
8596 (move-to-column col)
8597 (if (and org-table-copy-increment (org-at-timestamp-p t))
8598 (org-timestamp-up 1)
8599 (org-table-maybe-recalculate-line))
8600 (org-table-align)
8601 (move-to-column col))
8602 (error "No non-empty field found"))))
8604 (defun org-table-check-inside-data-field ()
8605 "Is point inside a table data field?
8606 I.e. not on a hline or before the first or after the last column?
8607 This actually throws an error, so it aborts the current command."
8608 (if (or (not (org-at-table-p))
8609 (= (org-table-current-column) 0)
8610 (org-at-table-hline-p)
8611 (looking-at "[ \t]*$"))
8612 (error "Not in table data field")))
8614 (defvar org-table-clip nil
8615 "Clipboard for table regions.")
8617 (defun org-table-blank-field ()
8618 "Blank the current table field or active region."
8619 (interactive)
8620 (org-table-check-inside-data-field)
8621 (if (and (interactive-p) (org-region-active-p))
8622 (let (org-table-clip)
8623 (org-table-cut-region (region-beginning) (region-end)))
8624 (skip-chars-backward "^|")
8625 (backward-char 1)
8626 (if (looking-at "|[^|\n]+")
8627 (let* ((pos (match-beginning 0))
8628 (match (match-string 0))
8629 (len (org-string-width match)))
8630 (replace-match (concat "|" (make-string (1- len) ?\ )))
8631 (goto-char (+ 2 pos))
8632 (substring match 1)))))
8634 (defun org-table-get-field (&optional n replace)
8635 "Return the value of the field in column N of current row.
8636 N defaults to current field.
8637 If REPLACE is a string, replace field with this value. The return value
8638 is always the old value."
8639 (and n (org-table-goto-column n))
8640 (skip-chars-backward "^|\n")
8641 (backward-char 1)
8642 (if (looking-at "|[^|\r\n]*")
8643 (let* ((pos (match-beginning 0))
8644 (val (buffer-substring (1+ pos) (match-end 0))))
8645 (if replace
8646 (replace-match (concat "|" replace) t t))
8647 (goto-char (min (point-at-eol) (+ 2 pos)))
8648 val)
8649 (forward-char 1) ""))
8651 (defun org-table-field-info (arg)
8652 "Show info about the current field, and highlight any reference at point."
8653 (interactive "P")
8654 (org-table-get-specials)
8655 (save-excursion
8656 (let* ((pos (point))
8657 (col (org-table-current-column))
8658 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8659 (name (car (rassoc (list (org-current-line) col)
8660 org-table-named-field-locations)))
8661 (eql (org-table-get-stored-formulas))
8662 (dline (org-table-current-dline))
8663 (ref (format "@%d$%d" dline col))
8664 (ref1 (org-table-convert-refs-to-an ref))
8665 (fequation (or (assoc name eql) (assoc ref eql)))
8666 (cequation (assoc (int-to-string col) eql))
8667 (eqn (or fequation cequation)))
8668 (goto-char pos)
8669 (condition-case nil
8670 (org-table-show-reference 'local)
8671 (error nil))
8672 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8673 dline col
8674 (if cname (concat " or $" cname) "")
8675 dline col ref1
8676 (if name (concat " or $" name) "")
8677 ;; FIXME: formula info not correct if special table line
8678 (if eqn
8679 (concat ", formula: "
8680 (org-table-formula-to-user
8681 (concat
8682 (if (string-match "^[$@]"(car eqn)) "" "$")
8683 (car eqn) "=" (cdr eqn))))
8684 "")))))
8686 (defun org-table-current-column ()
8687 "Find out which column we are in.
8688 When called interactively, column is also displayed in echo area."
8689 (interactive)
8690 (if (interactive-p) (org-table-check-inside-data-field))
8691 (save-excursion
8692 (let ((cnt 0) (pos (point)))
8693 (beginning-of-line 1)
8694 (while (search-forward "|" pos t)
8695 (setq cnt (1+ cnt)))
8696 (if (interactive-p) (message "This is table column %d" cnt))
8697 cnt)))
8699 (defun org-table-current-dline ()
8700 "Find out what table data line we are in.
8701 Only datalins count for this."
8702 (interactive)
8703 (if (interactive-p) (org-table-check-inside-data-field))
8704 (save-excursion
8705 (let ((cnt 0) (pos (point)))
8706 (goto-char (org-table-begin))
8707 (while (<= (point) pos)
8708 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8709 (beginning-of-line 2))
8710 (if (interactive-p) (message "This is table line %d" cnt))
8711 cnt)))
8713 (defun org-table-goto-column (n &optional on-delim force)
8714 "Move the cursor to the Nth column in the current table line.
8715 With optional argument ON-DELIM, stop with point before the left delimiter
8716 of the field.
8717 If there are less than N fields, just go to after the last delimiter.
8718 However, when FORCE is non-nil, create new columns if necessary."
8719 (interactive "p")
8720 (let ((pos (point-at-eol)))
8721 (beginning-of-line 1)
8722 (when (> n 0)
8723 (while (and (> (setq n (1- n)) -1)
8724 (or (search-forward "|" pos t)
8725 (and force
8726 (progn (end-of-line 1)
8727 (skip-chars-backward "^|")
8728 (insert " | "))))))
8729 ; (backward-char 2) t)))))
8730 (when (and force (not (looking-at ".*|")))
8731 (save-excursion (end-of-line 1) (insert " | ")))
8732 (if on-delim
8733 (backward-char 1)
8734 (if (looking-at " ") (forward-char 1))))))
8736 (defun org-at-table-p (&optional table-type)
8737 "Return t if the cursor is inside an org-type table.
8738 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8739 (if org-enable-table-editor
8740 (save-excursion
8741 (beginning-of-line 1)
8742 (looking-at (if table-type org-table-any-line-regexp
8743 org-table-line-regexp)))
8744 nil))
8746 (defun org-at-table.el-p ()
8747 "Return t if and only if we are at a table.el table."
8748 (and (org-at-table-p 'any)
8749 (save-excursion
8750 (goto-char (org-table-begin 'any))
8751 (looking-at org-table1-hline-regexp))))
8753 (defun org-table-recognize-table.el ()
8754 "If there is a table.el table nearby, recognize it and move into it."
8755 (if org-table-tab-recognizes-table.el
8756 (if (org-at-table.el-p)
8757 (progn
8758 (beginning-of-line 1)
8759 (if (looking-at org-table-dataline-regexp)
8761 (if (looking-at org-table1-hline-regexp)
8762 (progn
8763 (beginning-of-line 2)
8764 (if (looking-at org-table-any-border-regexp)
8765 (beginning-of-line -1)))))
8766 (if (re-search-forward "|" (org-table-end t) t)
8767 (progn
8768 (require 'table)
8769 (if (table--at-cell-p (point))
8771 (message "recognizing table.el table...")
8772 (table-recognize-table)
8773 (message "recognizing table.el table...done")))
8774 (error "This should not happen..."))
8776 nil)
8777 nil))
8779 (defun org-at-table-hline-p ()
8780 "Return t if the cursor is inside a hline in a table."
8781 (if org-enable-table-editor
8782 (save-excursion
8783 (beginning-of-line 1)
8784 (looking-at org-table-hline-regexp))
8785 nil))
8787 (defun org-table-insert-column ()
8788 "Insert a new column into the table."
8789 (interactive)
8790 (if (not (org-at-table-p))
8791 (error "Not at a table"))
8792 (org-table-find-dataline)
8793 (let* ((col (max 1 (org-table-current-column)))
8794 (beg (org-table-begin))
8795 (end (org-table-end))
8796 ;; Current cursor position
8797 (linepos (org-current-line))
8798 (colpos col))
8799 (goto-char beg)
8800 (while (< (point) end)
8801 (if (org-at-table-hline-p)
8803 (org-table-goto-column col t)
8804 (insert "| "))
8805 (beginning-of-line 2))
8806 (move-marker end nil)
8807 (goto-line linepos)
8808 (org-table-goto-column colpos)
8809 (org-table-align)
8810 (org-table-fix-formulas "$" nil (1- col) 1)))
8812 (defun org-table-find-dataline ()
8813 "Find a dataline in the current table, which is needed for column commands."
8814 (if (and (org-at-table-p)
8815 (not (org-at-table-hline-p)))
8817 (let ((col (current-column))
8818 (end (org-table-end)))
8819 (move-to-column col)
8820 (while (and (< (point) end)
8821 (or (not (= (current-column) col))
8822 (org-at-table-hline-p)))
8823 (beginning-of-line 2)
8824 (move-to-column col))
8825 (if (and (org-at-table-p)
8826 (not (org-at-table-hline-p)))
8828 (error
8829 "Please position cursor in a data line for column operations")))))
8831 (defun org-table-delete-column ()
8832 "Delete a column from the table."
8833 (interactive)
8834 (if (not (org-at-table-p))
8835 (error "Not at a table"))
8836 (org-table-find-dataline)
8837 (org-table-check-inside-data-field)
8838 (let* ((col (org-table-current-column))
8839 (beg (org-table-begin))
8840 (end (org-table-end))
8841 ;; Current cursor position
8842 (linepos (org-current-line))
8843 (colpos col))
8844 (goto-char beg)
8845 (while (< (point) end)
8846 (if (org-at-table-hline-p)
8848 (org-table-goto-column col t)
8849 (and (looking-at "|[^|\n]+|")
8850 (replace-match "|")))
8851 (beginning-of-line 2))
8852 (move-marker end nil)
8853 (goto-line linepos)
8854 (org-table-goto-column colpos)
8855 (org-table-align)
8856 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8857 col -1 col)))
8859 (defun org-table-move-column-right ()
8860 "Move column to the right."
8861 (interactive)
8862 (org-table-move-column nil))
8863 (defun org-table-move-column-left ()
8864 "Move column to the left."
8865 (interactive)
8866 (org-table-move-column 'left))
8868 (defun org-table-move-column (&optional left)
8869 "Move the current column to the right. With arg LEFT, move to the left."
8870 (interactive "P")
8871 (if (not (org-at-table-p))
8872 (error "Not at a table"))
8873 (org-table-find-dataline)
8874 (org-table-check-inside-data-field)
8875 (let* ((col (org-table-current-column))
8876 (col1 (if left (1- col) col))
8877 (beg (org-table-begin))
8878 (end (org-table-end))
8879 ;; Current cursor position
8880 (linepos (org-current-line))
8881 (colpos (if left (1- col) (1+ col))))
8882 (if (and left (= col 1))
8883 (error "Cannot move column further left"))
8884 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8885 (error "Cannot move column further right"))
8886 (goto-char beg)
8887 (while (< (point) end)
8888 (if (org-at-table-hline-p)
8890 (org-table-goto-column col1 t)
8891 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8892 (replace-match "|\\2|\\1|")))
8893 (beginning-of-line 2))
8894 (move-marker end nil)
8895 (goto-line linepos)
8896 (org-table-goto-column colpos)
8897 (org-table-align)
8898 (org-table-fix-formulas
8899 "$" (list (cons (number-to-string col) (number-to-string colpos))
8900 (cons (number-to-string colpos) (number-to-string col))))))
8902 (defun org-table-move-row-down ()
8903 "Move table row down."
8904 (interactive)
8905 (org-table-move-row nil))
8906 (defun org-table-move-row-up ()
8907 "Move table row up."
8908 (interactive)
8909 (org-table-move-row 'up))
8911 (defun org-table-move-row (&optional up)
8912 "Move the current table line down. With arg UP, move it up."
8913 (interactive "P")
8914 (let* ((col (current-column))
8915 (pos (point))
8916 (hline1p (save-excursion (beginning-of-line 1)
8917 (looking-at org-table-hline-regexp)))
8918 (dline1 (org-table-current-dline))
8919 (dline2 (+ dline1 (if up -1 1)))
8920 (tonew (if up 0 2))
8921 txt hline2p)
8922 (beginning-of-line tonew)
8923 (unless (org-at-table-p)
8924 (goto-char pos)
8925 (error "Cannot move row further"))
8926 (setq hline2p (looking-at org-table-hline-regexp))
8927 (goto-char pos)
8928 (beginning-of-line 1)
8929 (setq pos (point))
8930 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8931 (delete-region (point) (1+ (point-at-eol)))
8932 (beginning-of-line tonew)
8933 (insert txt)
8934 (beginning-of-line 0)
8935 (move-to-column col)
8936 (unless (or hline1p hline2p)
8937 (org-table-fix-formulas
8938 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8939 (cons (number-to-string dline2) (number-to-string dline1)))))))
8941 (defun org-table-insert-row (&optional arg)
8942 "Insert a new row above the current line into the table.
8943 With prefix ARG, insert below the current line."
8944 (interactive "P")
8945 (if (not (org-at-table-p))
8946 (error "Not at a table"))
8947 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8948 (new (org-table-clean-line line)))
8949 ;; Fix the first field if necessary
8950 (if (string-match "^[ \t]*| *[#$] *|" line)
8951 (setq new (replace-match (match-string 0 line) t t new)))
8952 (beginning-of-line (if arg 2 1))
8953 (let (org-table-may-need-update) (insert-before-markers new "\n"))
8954 (beginning-of-line 0)
8955 (re-search-forward "| ?" (point-at-eol) t)
8956 (and (or org-table-may-need-update org-table-overlay-coordinates)
8957 (org-table-align))
8958 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8960 (defun org-table-insert-hline (&optional above)
8961 "Insert a horizontal-line below the current line into the table.
8962 With prefix ABOVE, insert above the current line."
8963 (interactive "P")
8964 (if (not (org-at-table-p))
8965 (error "Not at a table"))
8966 (let ((line (org-table-clean-line
8967 (buffer-substring (point-at-bol) (point-at-eol))))
8968 (col (current-column)))
8969 (while (string-match "|\\( +\\)|" line)
8970 (setq line (replace-match
8971 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8972 ?-) "|") t t line)))
8973 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8974 (beginning-of-line (if above 1 2))
8975 (insert line "\n")
8976 (beginning-of-line (if above 1 -1))
8977 (move-to-column col)
8978 (and org-table-overlay-coordinates (org-table-align))))
8980 (defun org-table-hline-and-move (&optional same-column)
8981 "Insert a hline and move to the row below that line."
8982 (interactive "P")
8983 (let ((col (org-table-current-column)))
8984 (org-table-maybe-eval-formula)
8985 (org-table-maybe-recalculate-line)
8986 (org-table-insert-hline)
8987 (end-of-line 2)
8988 (if (looking-at "\n[ \t]*|-")
8989 (progn (insert "\n|") (org-table-align))
8990 (org-table-next-field))
8991 (if same-column (org-table-goto-column col))))
8993 (defun org-table-clean-line (s)
8994 "Convert a table line S into a string with only \"|\" and space.
8995 In particular, this does handle wide and invisible characters."
8996 (if (string-match "^[ \t]*|-" s)
8997 ;; It's a hline, just map the characters
8998 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
8999 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9000 (setq s (replace-match
9001 (concat "|" (make-string (org-string-width (match-string 1 s))
9002 ?\ ) "|")
9003 t t s)))
9006 (defun org-table-kill-row ()
9007 "Delete the current row or horizontal line from the table."
9008 (interactive)
9009 (if (not (org-at-table-p))
9010 (error "Not at a table"))
9011 (let ((col (current-column))
9012 (dline (org-table-current-dline)))
9013 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9014 (if (not (org-at-table-p)) (beginning-of-line 0))
9015 (move-to-column col)
9016 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9017 dline -1 dline)))
9019 (defun org-table-sort-lines (with-case &optional sorting-type)
9020 "Sort table lines according to the column at point.
9022 The position of point indicates the column to be used for
9023 sorting, and the range of lines is the range between the nearest
9024 horizontal separator lines, or the entire table of no such lines
9025 exist. If point is before the first column, you will be prompted
9026 for the sorting column. If there is an active region, the mark
9027 specifies the first line and the sorting column, while point
9028 should be in the last line to be included into the sorting.
9030 The command then prompts for the sorting type which can be
9031 alphabetically, numerically, or by time (as given in a time stamp
9032 in the field). Sorting in reverse order is also possible.
9034 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9036 If SORTING-TYPE is specified when this function is called from a Lisp
9037 program, no prompting will take place. SORTING-TYPE must be a character,
9038 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9039 should be done in reverse order."
9040 (interactive "P")
9041 (let* ((thisline (org-current-line))
9042 (thiscol (org-table-current-column))
9043 beg end bcol ecol tend tbeg column lns pos)
9044 (when (equal thiscol 0)
9045 (if (interactive-p)
9046 (setq thiscol
9047 (string-to-number
9048 (read-string "Use column N for sorting: ")))
9049 (setq thiscol 1))
9050 (org-table-goto-column thiscol))
9051 (org-table-check-inside-data-field)
9052 (if (org-region-active-p)
9053 (progn
9054 (setq beg (region-beginning) end (region-end))
9055 (goto-char beg)
9056 (setq column (org-table-current-column)
9057 beg (point-at-bol))
9058 (goto-char end)
9059 (setq end (point-at-bol 2)))
9060 (setq column (org-table-current-column)
9061 pos (point)
9062 tbeg (org-table-begin)
9063 tend (org-table-end))
9064 (if (re-search-backward org-table-hline-regexp tbeg t)
9065 (setq beg (point-at-bol 2))
9066 (goto-char tbeg)
9067 (setq beg (point-at-bol 1)))
9068 (goto-char pos)
9069 (if (re-search-forward org-table-hline-regexp tend t)
9070 (setq end (point-at-bol 1))
9071 (goto-char tend)
9072 (setq end (point-at-bol))))
9073 (setq beg (move-marker (make-marker) beg)
9074 end (move-marker (make-marker) end))
9075 (untabify beg end)
9076 (goto-char beg)
9077 (org-table-goto-column column)
9078 (skip-chars-backward "^|")
9079 (setq bcol (current-column))
9080 (org-table-goto-column (1+ column))
9081 (skip-chars-backward "^|")
9082 (setq ecol (1- (current-column)))
9083 (org-table-goto-column column)
9084 (setq lns (mapcar (lambda(x) (cons
9085 (org-sort-remove-invisible
9086 (nth (1- column)
9087 (org-split-string x "[ \t]*|[ \t]*")))
9089 (org-split-string (buffer-substring beg end) "\n")))
9090 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9091 (delete-region beg end)
9092 (move-marker beg nil)
9093 (move-marker end nil)
9094 (insert (mapconcat 'cdr lns "\n") "\n")
9095 (goto-line thisline)
9096 (org-table-goto-column thiscol)
9097 (message "%d lines sorted, based on column %d" (length lns) column)))
9099 ;; FIXME: maybe we will not need this? Table sorting is broken....
9100 (defun org-sort-remove-invisible (s)
9101 (remove-text-properties 0 (length s) org-rm-props s)
9102 (while (string-match org-bracket-link-regexp s)
9103 (setq s (replace-match (if (match-end 2)
9104 (match-string 3 s)
9105 (match-string 1 s)) t t s)))
9108 (defun org-table-cut-region (beg end)
9109 "Copy region in table to the clipboard and blank all relevant fields."
9110 (interactive "r")
9111 (org-table-copy-region beg end 'cut))
9113 (defun org-table-copy-region (beg end &optional cut)
9114 "Copy rectangular region in table to clipboard.
9115 A special clipboard is used which can only be accessed
9116 with `org-table-paste-rectangle'."
9117 (interactive "rP")
9118 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9119 region cols
9120 (rpl (if cut " " nil)))
9121 (goto-char beg)
9122 (org-table-check-inside-data-field)
9123 (setq l01 (org-current-line)
9124 c01 (org-table-current-column))
9125 (goto-char end)
9126 (org-table-check-inside-data-field)
9127 (setq l02 (org-current-line)
9128 c02 (org-table-current-column))
9129 (setq l1 (min l01 l02) l2 (max l01 l02)
9130 c1 (min c01 c02) c2 (max c01 c02))
9131 (catch 'exit
9132 (while t
9133 (catch 'nextline
9134 (if (> l1 l2) (throw 'exit t))
9135 (goto-line l1)
9136 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9137 (setq cols nil ic1 c1 ic2 c2)
9138 (while (< ic1 (1+ ic2))
9139 (push (org-table-get-field ic1 rpl) cols)
9140 (setq ic1 (1+ ic1)))
9141 (push (nreverse cols) region)
9142 (setq l1 (1+ l1)))))
9143 (setq org-table-clip (nreverse region))
9144 (if cut (org-table-align))
9145 org-table-clip))
9147 (defun org-table-paste-rectangle ()
9148 "Paste a rectangular region into a table.
9149 The upper right corner ends up in the current field. All involved fields
9150 will be overwritten. If the rectangle does not fit into the present table,
9151 the table is enlarged as needed. The process ignores horizontal separator
9152 lines."
9153 (interactive)
9154 (unless (and org-table-clip (listp org-table-clip))
9155 (error "First cut/copy a region to paste!"))
9156 (org-table-check-inside-data-field)
9157 (let* ((clip org-table-clip)
9158 (line (org-current-line))
9159 (col (org-table-current-column))
9160 (org-enable-table-editor t)
9161 (org-table-automatic-realign nil)
9162 c cols field)
9163 (while (setq cols (pop clip))
9164 (while (org-at-table-hline-p) (beginning-of-line 2))
9165 (if (not (org-at-table-p))
9166 (progn (end-of-line 0) (org-table-next-field)))
9167 (setq c col)
9168 (while (setq field (pop cols))
9169 (org-table-goto-column c nil 'force)
9170 (org-table-get-field nil field)
9171 (setq c (1+ c)))
9172 (beginning-of-line 2))
9173 (goto-line line)
9174 (org-table-goto-column col)
9175 (org-table-align)))
9177 (defun org-table-convert ()
9178 "Convert from `org-mode' table to table.el and back.
9179 Obviously, this only works within limits. When an Org-mode table is
9180 converted to table.el, all horizontal separator lines get lost, because
9181 table.el uses these as cell boundaries and has no notion of horizontal lines.
9182 A table.el table can be converted to an Org-mode table only if it does not
9183 do row or column spanning. Multiline cells will become multiple cells.
9184 Beware, Org-mode does not test if the table can be successfully converted - it
9185 blindly applies a recipe that works for simple tables."
9186 (interactive)
9187 (require 'table)
9188 (if (org-at-table.el-p)
9189 ;; convert to Org-mode table
9190 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9191 (end (move-marker (make-marker) (org-table-end t))))
9192 (table-unrecognize-region beg end)
9193 (goto-char beg)
9194 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9195 (replace-match ""))
9196 (goto-char beg))
9197 (if (org-at-table-p)
9198 ;; convert to table.el table
9199 (let ((beg (move-marker (make-marker) (org-table-begin)))
9200 (end (move-marker (make-marker) (org-table-end))))
9201 ;; first, get rid of all horizontal lines
9202 (goto-char beg)
9203 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9204 (replace-match ""))
9205 ;; insert a hline before first
9206 (goto-char beg)
9207 (org-table-insert-hline 'above)
9208 (beginning-of-line -1)
9209 ;; insert a hline after each line
9210 (while (progn (beginning-of-line 3) (< (point) end))
9211 (org-table-insert-hline))
9212 (goto-char beg)
9213 (setq end (move-marker end (org-table-end)))
9214 ;; replace "+" at beginning and ending of hlines
9215 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9216 (replace-match "\\1+-"))
9217 (goto-char beg)
9218 (while (re-search-forward "-|[ \t]*$" end t)
9219 (replace-match "-+"))
9220 (goto-char beg)))))
9222 (defun org-table-wrap-region (arg)
9223 "Wrap several fields in a column like a paragraph.
9224 This is useful if you'd like to spread the contents of a field over several
9225 lines, in order to keep the table compact.
9227 If there is an active region, and both point and mark are in the same column,
9228 the text in the column is wrapped to minimum width for the given number of
9229 lines. Generally, this makes the table more compact. A prefix ARG may be
9230 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9231 formats the selected text to two lines. If the region was longer than two
9232 lines, the remaining lines remain empty. A negative prefix argument reduces
9233 the current number of lines by that amount. The wrapped text is pasted back
9234 into the table. If you formatted it to more lines than it was before, fields
9235 further down in the table get overwritten - so you might need to make space in
9236 the table first.
9238 If there is no region, the current field is split at the cursor position and
9239 the text fragment to the right of the cursor is prepended to the field one
9240 line down.
9242 If there is no region, but you specify a prefix ARG, the current field gets
9243 blank, and the content is appended to the field above."
9244 (interactive "P")
9245 (org-table-check-inside-data-field)
9246 (if (org-region-active-p)
9247 ;; There is a region: fill as a paragraph
9248 (let* ((beg (region-beginning))
9249 (cline (save-excursion (goto-char beg) (org-current-line)))
9250 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9251 nlines)
9252 (org-table-cut-region (region-beginning) (region-end))
9253 (if (> (length (car org-table-clip)) 1)
9254 (error "Region must be limited to single column"))
9255 (setq nlines (if arg
9256 (if (< arg 1)
9257 (+ (length org-table-clip) arg)
9258 arg)
9259 (length org-table-clip)))
9260 (setq org-table-clip
9261 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9262 nil nlines)))
9263 (goto-line cline)
9264 (org-table-goto-column ccol)
9265 (org-table-paste-rectangle))
9266 ;; No region, split the current field at point
9267 (if arg
9268 ;; combine with field above
9269 (let ((s (org-table-blank-field))
9270 (col (org-table-current-column)))
9271 (beginning-of-line 0)
9272 (while (org-at-table-hline-p) (beginning-of-line 0))
9273 (org-table-goto-column col)
9274 (skip-chars-forward "^|")
9275 (skip-chars-backward " ")
9276 (insert " " (org-trim s))
9277 (org-table-align))
9278 ;; split field
9279 (when (looking-at "\\([^|]+\\)+|")
9280 (let ((s (match-string 1)))
9281 (replace-match " |")
9282 (goto-char (match-beginning 0))
9283 (org-table-next-row)
9284 (insert (org-trim s) " ")
9285 (org-table-align))))))
9287 (defvar org-field-marker nil)
9289 (defun org-table-edit-field (arg)
9290 "Edit table field in a different window.
9291 This is mainly useful for fields that contain hidden parts.
9292 When called with a \\[universal-argument] prefix, just make the full field visible so that
9293 it can be edited in place."
9294 (interactive "P")
9295 (if arg
9296 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9297 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9298 (remove-text-properties b e '(org-cwidth t invisible t
9299 display t intangible t))
9300 (if (and (boundp 'font-lock-mode) font-lock-mode)
9301 (font-lock-fontify-block)))
9302 (let ((pos (move-marker (make-marker) (point)))
9303 (field (org-table-get-field))
9304 (cw (current-window-configuration))
9306 (org-switch-to-buffer-other-window "*Org tmp*")
9307 (erase-buffer)
9308 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9309 (let ((org-inhibit-startup t)) (org-mode))
9310 (goto-char (setq p (point-max)))
9311 (insert (org-trim field))
9312 (remove-text-properties p (point-max)
9313 '(invisible t org-cwidth t display t
9314 intangible t))
9315 (goto-char p)
9316 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9317 (org-set-local 'org-window-configuration cw)
9318 (org-set-local 'org-field-marker pos)
9319 (message "Edit and finish with C-c C-c"))))
9321 (defun org-table-finish-edit-field ()
9322 "Finish editing a table data field.
9323 Remove all newline characters, insert the result into the table, realign
9324 the table and kill the editing buffer."
9325 (let ((pos org-field-marker)
9326 (cw org-window-configuration)
9327 (cb (current-buffer))
9328 text)
9329 (goto-char (point-min))
9330 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9331 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9332 (replace-match " "))
9333 (setq text (org-trim (buffer-string)))
9334 (set-window-configuration cw)
9335 (kill-buffer cb)
9336 (select-window (get-buffer-window (marker-buffer pos)))
9337 (goto-char pos)
9338 (move-marker pos nil)
9339 (org-table-check-inside-data-field)
9340 (org-table-get-field nil text)
9341 (org-table-align)
9342 (message "New field value inserted")))
9344 (defun org-trim (s)
9345 "Remove whitespace at beginning and end of string."
9346 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9347 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9350 (defun org-wrap (string &optional width lines)
9351 "Wrap string to either a number of lines, or a width in characters.
9352 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9353 that costs. If there is a word longer than WIDTH, the text is actually
9354 wrapped to the length of that word.
9355 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9356 many lines, whatever width that takes.
9357 The return value is a list of lines, without newlines at the end."
9358 (let* ((words (org-split-string string "[ \t\n]+"))
9359 (maxword (apply 'max (mapcar 'org-string-width words)))
9360 w ll)
9361 (cond (width
9362 (org-do-wrap words (max maxword width)))
9363 (lines
9364 (setq w maxword)
9365 (setq ll (org-do-wrap words maxword))
9366 (if (<= (length ll) lines)
9368 (setq ll words)
9369 (while (> (length ll) lines)
9370 (setq w (1+ w))
9371 (setq ll (org-do-wrap words w)))
9372 ll))
9373 (t (error "Cannot wrap this")))))
9376 (defun org-do-wrap (words width)
9377 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9378 (let (lines line)
9379 (while words
9380 (setq line (pop words))
9381 (while (and words (< (+ (length line) (length (car words))) width))
9382 (setq line (concat line " " (pop words))))
9383 (setq lines (push line lines)))
9384 (nreverse lines)))
9386 (defun org-split-string (string &optional separators)
9387 "Splits STRING into substrings at SEPARATORS.
9388 No empty strings are returned if there are matches at the beginning
9389 and end of string."
9390 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9391 (start 0)
9392 notfirst
9393 (list nil))
9394 (while (and (string-match rexp string
9395 (if (and notfirst
9396 (= start (match-beginning 0))
9397 (< start (length string)))
9398 (1+ start) start))
9399 (< (match-beginning 0) (length string)))
9400 (setq notfirst t)
9401 (or (eq (match-beginning 0) 0)
9402 (and (eq (match-beginning 0) (match-end 0))
9403 (eq (match-beginning 0) start))
9404 (setq list
9405 (cons (substring string start (match-beginning 0))
9406 list)))
9407 (setq start (match-end 0)))
9408 (or (eq start (length string))
9409 (setq list
9410 (cons (substring string start)
9411 list)))
9412 (nreverse list)))
9414 (defun org-table-map-tables (function)
9415 "Apply FUNCTION to the start of all tables in the buffer."
9416 (save-excursion
9417 (save-restriction
9418 (widen)
9419 (goto-char (point-min))
9420 (while (re-search-forward org-table-any-line-regexp nil t)
9421 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9422 (beginning-of-line 1)
9423 (if (looking-at org-table-line-regexp)
9424 (save-excursion (funcall function)))
9425 (re-search-forward org-table-any-border-regexp nil 1))))
9426 (message "Mapping tables: done"))
9428 (defvar org-timecnt) ; dynamically scoped parameter
9430 (defun org-table-sum (&optional beg end nlast)
9431 "Sum numbers in region of current table column.
9432 The result will be displayed in the echo area, and will be available
9433 as kill to be inserted with \\[yank].
9435 If there is an active region, it is interpreted as a rectangle and all
9436 numbers in that rectangle will be summed. If there is no active
9437 region and point is located in a table column, sum all numbers in that
9438 column.
9440 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9441 numbers are assumed to be times as well (in decimal hours) and the
9442 numbers are added as such.
9444 If NLAST is a number, only the NLAST fields will actually be summed."
9445 (interactive)
9446 (save-excursion
9447 (let (col (org-timecnt 0) diff h m s org-table-clip)
9448 (cond
9449 ((and beg end)) ; beg and end given explicitly
9450 ((org-region-active-p)
9451 (setq beg (region-beginning) end (region-end)))
9453 (setq col (org-table-current-column))
9454 (goto-char (org-table-begin))
9455 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9456 (error "No table data"))
9457 (org-table-goto-column col)
9458 (setq beg (point))
9459 (goto-char (org-table-end))
9460 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9461 (error "No table data"))
9462 (org-table-goto-column col)
9463 (setq end (point))))
9464 (let* ((items (apply 'append (org-table-copy-region beg end)))
9465 (items1 (cond ((not nlast) items)
9466 ((>= nlast (length items)) items)
9467 (t (setq items (reverse items))
9468 (setcdr (nthcdr (1- nlast) items) nil)
9469 (nreverse items))))
9470 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9471 items1)))
9472 (res (apply '+ numbers))
9473 (sres (if (= org-timecnt 0)
9474 (format "%g" res)
9475 (setq diff (* 3600 res)
9476 h (floor (/ diff 3600)) diff (mod diff 3600)
9477 m (floor (/ diff 60)) diff (mod diff 60)
9478 s diff)
9479 (format "%d:%02d:%02d" h m s))))
9480 (kill-new sres)
9481 (if (interactive-p)
9482 (message "%s"
9483 (substitute-command-keys
9484 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9485 (length numbers) sres))))
9486 sres))))
9488 (defun org-table-get-number-for-summing (s)
9489 (let (n)
9490 (if (string-match "^ *|? *" s)
9491 (setq s (replace-match "" nil nil s)))
9492 (if (string-match " *|? *$" s)
9493 (setq s (replace-match "" nil nil s)))
9494 (setq n (string-to-number s))
9495 (cond
9496 ((and (string-match "0" s)
9497 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9498 ((string-match "\\`[ \t]+\\'" s) nil)
9499 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9500 (let ((h (string-to-number (or (match-string 1 s) "0")))
9501 (m (string-to-number (or (match-string 2 s) "0")))
9502 (s (string-to-number (or (match-string 4 s) "0"))))
9503 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9504 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9505 ((equal n 0) nil)
9506 (t n))))
9508 (defun org-table-current-field-formula (&optional key noerror)
9509 "Return the formula active for the current field.
9510 Assumes that specials are in place.
9511 If KEY is given, return the key to this formula.
9512 Otherwise return the formula preceeded with \"=\" or \":=\"."
9513 (let* ((name (car (rassoc (list (org-current-line)
9514 (org-table-current-column))
9515 org-table-named-field-locations)))
9516 (col (org-table-current-column))
9517 (scol (int-to-string col))
9518 (ref (format "@%d$%d" (org-table-current-dline) col))
9519 (stored-list (org-table-get-stored-formulas noerror))
9520 (ass (or (assoc name stored-list)
9521 (assoc ref stored-list)
9522 (assoc scol stored-list))))
9523 (if key
9524 (car ass)
9525 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9526 (cdr ass))))))
9528 (defun org-table-get-formula (&optional equation named)
9529 "Read a formula from the minibuffer, offer stored formula as default.
9530 When NAMED is non-nil, look for a named equation."
9531 (let* ((stored-list (org-table-get-stored-formulas))
9532 (name (car (rassoc (list (org-current-line)
9533 (org-table-current-column))
9534 org-table-named-field-locations)))
9535 (ref (format "@%d$%d" (org-table-current-dline)
9536 (org-table-current-column)))
9537 (refass (assoc ref stored-list))
9538 (scol (if named
9539 (if name name ref)
9540 (int-to-string (org-table-current-column))))
9541 (dummy (and (or name refass) (not named)
9542 (not (y-or-n-p "Replace field formula with column formula? " ))
9543 (error "Abort")))
9544 (name (or name ref))
9545 (org-table-may-need-update nil)
9546 (stored (cdr (assoc scol stored-list)))
9547 (eq (cond
9548 ((and stored equation (string-match "^ *=? *$" equation))
9549 stored)
9550 ((stringp equation)
9551 equation)
9552 (t (org-table-formula-from-user
9553 (read-string
9554 (org-table-formula-to-user
9555 (format "%s formula %s%s="
9556 (if named "Field" "Column")
9557 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9558 scol))
9559 (if stored (org-table-formula-to-user stored) "")
9560 'org-table-formula-history
9561 )))))
9562 mustsave)
9563 (when (not (string-match "\\S-" eq))
9564 ;; remove formula
9565 (setq stored-list (delq (assoc scol stored-list) stored-list))
9566 (org-table-store-formulas stored-list)
9567 (error "Formula removed"))
9568 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9569 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9570 (if (and name (not named))
9571 ;; We set the column equation, delete the named one.
9572 (setq stored-list (delq (assoc name stored-list) stored-list)
9573 mustsave t))
9574 (if stored
9575 (setcdr (assoc scol stored-list) eq)
9576 (setq stored-list (cons (cons scol eq) stored-list)))
9577 (if (or mustsave (not (equal stored eq)))
9578 (org-table-store-formulas stored-list))
9579 eq))
9581 (defun org-table-store-formulas (alist)
9582 "Store the list of formulas below the current table."
9583 (setq alist (sort alist 'org-table-formula-less-p))
9584 (save-excursion
9585 (goto-char (org-table-end))
9586 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9587 (progn
9588 ;; don't overwrite TBLFM, we might use text properties to store stuff
9589 (goto-char (match-beginning 2))
9590 (delete-region (match-beginning 2) (match-end 0)))
9591 (insert "#+TBLFM:"))
9592 (insert " "
9593 (mapconcat (lambda (x)
9594 (concat
9595 (if (equal (string-to-char (car x)) ?@) "" "$")
9596 (car x) "=" (cdr x)))
9597 alist "::")
9598 "\n")))
9600 (defsubst org-table-formula-make-cmp-string (a)
9601 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9602 (concat
9603 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9604 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9605 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9607 (defun org-table-formula-less-p (a b)
9608 "Compare two formulas for sorting."
9609 (let ((as (org-table-formula-make-cmp-string (car a)))
9610 (bs (org-table-formula-make-cmp-string (car b))))
9611 (and as bs (string< as bs))))
9613 (defun org-table-get-stored-formulas (&optional noerror)
9614 "Return an alist with the stored formulas directly after current table."
9615 (interactive)
9616 (let (scol eq eq-alist strings string seen)
9617 (save-excursion
9618 (goto-char (org-table-end))
9619 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9620 (setq strings (org-split-string (match-string 2) " *:: *"))
9621 (while (setq string (pop strings))
9622 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9623 (setq scol (if (match-end 2)
9624 (match-string 2 string)
9625 (match-string 1 string))
9626 eq (match-string 3 string)
9627 eq-alist (cons (cons scol eq) eq-alist))
9628 (if (member scol seen)
9629 (if noerror
9630 (progn
9631 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9632 (ding)
9633 (sit-for 2))
9634 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9635 (push scol seen))))))
9636 (nreverse eq-alist)))
9638 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9639 "Modify the equations after the table structure has been edited.
9640 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9641 For all numbers larger than LIMIT, shift them by DELTA."
9642 (save-excursion
9643 (goto-char (org-table-end))
9644 (when (looking-at "#\\+TBLFM:")
9645 (let ((re (concat key "\\([0-9]+\\)"))
9646 (re2
9647 (when remove
9648 (if (equal key "$")
9649 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9650 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9651 s n a)
9652 (when remove
9653 (while (re-search-forward re2 (point-at-eol) t)
9654 (replace-match "")))
9655 (while (re-search-forward re (point-at-eol) t)
9656 (setq s (match-string 1) n (string-to-number s))
9657 (cond
9658 ((setq a (assoc s replace))
9659 (replace-match (concat key (cdr a)) t t))
9660 ((and limit (> n limit))
9661 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9663 (defun org-table-get-specials ()
9664 "Get the column names and local parameters for this table."
9665 (save-excursion
9666 (let ((beg (org-table-begin)) (end (org-table-end))
9667 names name fields fields1 field cnt
9668 c v l line col types dlines hlines)
9669 (setq org-table-column-names nil
9670 org-table-local-parameters nil
9671 org-table-named-field-locations nil
9672 org-table-current-begin-line nil
9673 org-table-current-begin-pos nil
9674 org-table-current-line-types nil)
9675 (goto-char beg)
9676 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9677 (setq names (org-split-string (match-string 1) " *| *")
9678 cnt 1)
9679 (while (setq name (pop names))
9680 (setq cnt (1+ cnt))
9681 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9682 (push (cons name (int-to-string cnt)) org-table-column-names))))
9683 (setq org-table-column-names (nreverse org-table-column-names))
9684 (setq org-table-column-name-regexp
9685 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9686 (goto-char beg)
9687 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9688 (setq fields (org-split-string (match-string 1) " *| *"))
9689 (while (setq field (pop fields))
9690 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9691 (push (cons (match-string 1 field) (match-string 2 field))
9692 org-table-local-parameters))))
9693 (goto-char beg)
9694 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9695 (setq c (match-string 1)
9696 fields (org-split-string (match-string 2) " *| *"))
9697 (save-excursion
9698 (beginning-of-line (if (equal c "_") 2 0))
9699 (setq line (org-current-line) col 1)
9700 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9701 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9702 (while (and fields1 (setq field (pop fields)))
9703 (setq v (pop fields1) col (1+ col))
9704 (when (and (stringp field) (stringp v)
9705 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9706 (push (cons field v) org-table-local-parameters)
9707 (push (list field line col) org-table-named-field-locations))))
9708 ;; Analyse the line types
9709 (goto-char beg)
9710 (setq org-table-current-begin-line (org-current-line)
9711 org-table-current-begin-pos (point)
9712 l org-table-current-begin-line)
9713 (while (looking-at "[ \t]*|\\(-\\)?")
9714 (push (if (match-end 1) 'hline 'dline) types)
9715 (if (match-end 1) (push l hlines) (push l dlines))
9716 (beginning-of-line 2)
9717 (setq l (1+ l)))
9718 (setq org-table-current-line-types (apply 'vector (nreverse types))
9719 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9720 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9722 (defun org-table-maybe-eval-formula ()
9723 "Check if the current field starts with \"=\" or \":=\".
9724 If yes, store the formula and apply it."
9725 ;; We already know we are in a table. Get field will only return a formula
9726 ;; when appropriate. It might return a separator line, but no problem.
9727 (when org-table-formula-evaluate-inline
9728 (let* ((field (org-trim (or (org-table-get-field) "")))
9729 named eq)
9730 (when (string-match "^:?=\\(.*\\)" field)
9731 (setq named (equal (string-to-char field) ?:)
9732 eq (match-string 1 field))
9733 (if (or (fboundp 'calc-eval)
9734 (equal (substring eq 0 (min 2 (length eq))) "'("))
9735 (org-table-eval-formula (if named '(4) nil)
9736 (org-table-formula-from-user eq))
9737 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9739 (defvar org-recalc-commands nil
9740 "List of commands triggering the recalculation of a line.
9741 Will be filled automatically during use.")
9743 (defvar org-recalc-marks
9744 '((" " . "Unmarked: no special line, no automatic recalculation")
9745 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9746 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9747 ("!" . "Column name definition line. Reference in formula as $name.")
9748 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9749 ("_" . "Names for values in row below this one.")
9750 ("^" . "Names for values in row above this one.")))
9752 (defun org-table-rotate-recalc-marks (&optional newchar)
9753 "Rotate the recalculation mark in the first column.
9754 If in any row, the first field is not consistent with a mark,
9755 insert a new column for the markers.
9756 When there is an active region, change all the lines in the region,
9757 after prompting for the marking character.
9758 After each change, a message will be displayed indicating the meaning
9759 of the new mark."
9760 (interactive)
9761 (unless (org-at-table-p) (error "Not at a table"))
9762 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9763 (beg (org-table-begin))
9764 (end (org-table-end))
9765 (l (org-current-line))
9766 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9767 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9768 (have-col
9769 (save-excursion
9770 (goto-char beg)
9771 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9772 (col (org-table-current-column))
9773 (forcenew (car (assoc newchar org-recalc-marks)))
9774 epos new)
9775 (when l1
9776 (message "Change region to what mark? Type # * ! $ or SPC: ")
9777 (setq newchar (char-to-string (read-char-exclusive))
9778 forcenew (car (assoc newchar org-recalc-marks))))
9779 (if (and newchar (not forcenew))
9780 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9781 newchar))
9782 (if l1 (goto-line l1))
9783 (save-excursion
9784 (beginning-of-line 1)
9785 (unless (looking-at org-table-dataline-regexp)
9786 (error "Not at a table data line")))
9787 (unless have-col
9788 (org-table-goto-column 1)
9789 (org-table-insert-column)
9790 (org-table-goto-column (1+ col)))
9791 (setq epos (point-at-eol))
9792 (save-excursion
9793 (beginning-of-line 1)
9794 (org-table-get-field
9795 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9796 (concat " "
9797 (setq new (or forcenew
9798 (cadr (member (match-string 1) marks))))
9799 " ")
9800 " # ")))
9801 (if (and l1 l2)
9802 (progn
9803 (goto-line l1)
9804 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9805 (and (looking-at org-table-dataline-regexp)
9806 (org-table-get-field 1 (concat " " new " "))))
9807 (goto-line l1)))
9808 (if (not (= epos (point-at-eol))) (org-table-align))
9809 (goto-line l)
9810 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
9812 (defun org-table-maybe-recalculate-line ()
9813 "Recompute the current line if marked for it, and if we haven't just done it."
9814 (interactive)
9815 (and org-table-allow-automatic-line-recalculation
9816 (not (and (memq last-command org-recalc-commands)
9817 (equal org-last-recalc-line (org-current-line))))
9818 (save-excursion (beginning-of-line 1)
9819 (looking-at org-table-auto-recalculate-regexp))
9820 (org-table-recalculate) t))
9822 (defvar org-table-formula-debug nil
9823 "Non-nil means, debug table formulas.
9824 When nil, simply write \"#ERROR\" in corrupted fields.")
9825 (make-variable-buffer-local 'org-table-formula-debug)
9827 (defvar modes)
9828 (defsubst org-set-calc-mode (var &optional value)
9829 (if (stringp var)
9830 (setq var (assoc var '(("D" calc-angle-mode deg)
9831 ("R" calc-angle-mode rad)
9832 ("F" calc-prefer-frac t)
9833 ("S" calc-symbolic-mode t)))
9834 value (nth 2 var) var (nth 1 var)))
9835 (if (memq var modes)
9836 (setcar (cdr (memq var modes)) value)
9837 (cons var (cons value modes)))
9838 modes)
9840 (defun org-table-eval-formula (&optional arg equation
9841 suppress-align suppress-const
9842 suppress-store suppress-analysis)
9843 "Replace the table field value at the cursor by the result of a calculation.
9845 This function makes use of Dave Gillespie's Calc package, in my view the
9846 most exciting program ever written for GNU Emacs. So you need to have Calc
9847 installed in order to use this function.
9849 In a table, this command replaces the value in the current field with the
9850 result of a formula. It also installs the formula as the \"current\" column
9851 formula, by storing it in a special line below the table. When called
9852 with a `C-u' prefix, the current field must ba a named field, and the
9853 formula is installed as valid in only this specific field.
9855 When called with two `C-u' prefixes, insert the active equation
9856 for the field back into the current field, so that it can be
9857 edited there. This is useful in order to use \\[org-table-show-reference]
9858 to check the referenced fields.
9860 When called, the command first prompts for a formula, which is read in
9861 the minibuffer. Previously entered formulas are available through the
9862 history list, and the last used formula is offered as a default.
9863 These stored formulas are adapted correctly when moving, inserting, or
9864 deleting columns with the corresponding commands.
9866 The formula can be any algebraic expression understood by the Calc package.
9867 For details, see the Org-mode manual.
9869 This function can also be called from Lisp programs and offers
9870 additional arguments: EQUATION can be the formula to apply. If this
9871 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9872 used to speed-up recursive calls by by-passing unnecessary aligns.
9873 SUPPRESS-CONST suppresses the interpretation of constants in the
9874 formula, assuming that this has been done already outside the function.
9875 SUPPRESS-STORE means the formula should not be stored, either because
9876 it is already stored, or because it is a modified equation that should
9877 not overwrite the stored one."
9878 (interactive "P")
9879 (org-table-check-inside-data-field)
9880 (or suppress-analysis (org-table-get-specials))
9881 (if (equal arg '(16))
9882 (let ((eq (org-table-current-field-formula)))
9883 (or eq (error "No equation active for current field"))
9884 (org-table-get-field nil eq)
9885 (org-table-align)
9886 (setq org-table-may-need-update t))
9887 (let* (fields
9888 (ndown (if (integerp arg) arg 1))
9889 (org-table-automatic-realign nil)
9890 (case-fold-search nil)
9891 (down (> ndown 1))
9892 (formula (if (and equation suppress-store)
9893 equation
9894 (org-table-get-formula equation (equal arg '(4)))))
9895 (n0 (org-table-current-column))
9896 (modes (copy-sequence org-calc-default-modes))
9897 (numbers nil) ; was a variable, now fixed default
9898 (keep-empty nil)
9899 n form form0 bw fmt x ev orig c lispp literal)
9900 ;; Parse the format string. Since we have a lot of modes, this is
9901 ;; a lot of work. However, I think calc still uses most of the time.
9902 (if (string-match ";" formula)
9903 (let ((tmp (org-split-string formula ";")))
9904 (setq formula (car tmp)
9905 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9906 (nth 1 tmp)))
9907 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9908 (setq c (string-to-char (match-string 1 fmt))
9909 n (string-to-number (match-string 2 fmt)))
9910 (if (= c ?p)
9911 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9912 (setq modes (org-set-calc-mode
9913 'calc-float-format
9914 (list (cdr (assoc c '((?n . float) (?f . fix)
9915 (?s . sci) (?e . eng))))
9916 n))))
9917 (setq fmt (replace-match "" t t fmt)))
9918 (if (string-match "[NT]" fmt)
9919 (setq numbers (equal (match-string 0 fmt) "N")
9920 fmt (replace-match "" t t fmt)))
9921 (if (string-match "L" fmt)
9922 (setq literal t
9923 fmt (replace-match "" t t fmt)))
9924 (if (string-match "E" fmt)
9925 (setq keep-empty t
9926 fmt (replace-match "" t t fmt)))
9927 (while (string-match "[DRFS]" fmt)
9928 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9929 (setq fmt (replace-match "" t t fmt)))
9930 (unless (string-match "\\S-" fmt)
9931 (setq fmt nil))))
9932 (if (and (not suppress-const) org-table-formula-use-constants)
9933 (setq formula (org-table-formula-substitute-names formula)))
9934 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9935 (while (> ndown 0)
9936 (setq fields (org-split-string
9937 (org-no-properties
9938 (buffer-substring (point-at-bol) (point-at-eol)))
9939 " *| *"))
9940 (if (eq numbers t)
9941 (setq fields (mapcar
9942 (lambda (x) (number-to-string (string-to-number x)))
9943 fields)))
9944 (setq ndown (1- ndown))
9945 (setq form (copy-sequence formula)
9946 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9947 (if (and lispp literal) (setq lispp 'literal))
9948 ;; Check for old vertical references
9949 (setq form (org-rewrite-old-row-references form))
9950 ;; Insert complex ranges
9951 (while (string-match org-table-range-regexp form)
9952 (setq form
9953 (replace-match
9954 (save-match-data
9955 (org-table-make-reference
9956 (org-table-get-range (match-string 0 form) nil n0)
9957 keep-empty numbers lispp))
9958 t t form)))
9959 ;; Insert simple ranges
9960 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
9961 (setq form
9962 (replace-match
9963 (save-match-data
9964 (org-table-make-reference
9965 (org-sublist
9966 fields (string-to-number (match-string 1 form))
9967 (string-to-number (match-string 2 form)))
9968 keep-empty numbers lispp))
9969 t t form)))
9970 (setq form0 form)
9971 ;; Insert the references to fields in same row
9972 (while (string-match "\\$\\([0-9]+\\)" form)
9973 (setq n (string-to-number (match-string 1 form))
9974 x (nth (1- (if (= n 0) n0 n)) fields))
9975 (unless x (error "Invalid field specifier \"%s\""
9976 (match-string 0 form)))
9977 (setq form (replace-match
9978 (save-match-data
9979 (org-table-make-reference x nil numbers lispp))
9980 t t form)))
9982 (if lispp
9983 (setq ev (condition-case nil
9984 (eval (eval (read form)))
9985 (error "#ERROR"))
9986 ev (if (numberp ev) (number-to-string ev) ev))
9987 (or (fboundp 'calc-eval)
9988 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
9989 (setq ev (calc-eval (cons form modes)
9990 (if numbers 'num))))
9992 (when org-table-formula-debug
9993 (with-output-to-temp-buffer "*Substitution History*"
9994 (princ (format "Substitution history of formula
9995 Orig: %s
9996 $xyz-> %s
9997 @r$c-> %s
9998 $1-> %s\n" orig formula form0 form))
9999 (if (listp ev)
10000 (princ (format " %s^\nError: %s"
10001 (make-string (car ev) ?\-) (nth 1 ev)))
10002 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10003 ev (or fmt "NONE")
10004 (if fmt (format fmt (string-to-number ev)) ev)))))
10005 (setq bw (get-buffer-window "*Substitution History*"))
10006 (shrink-window-if-larger-than-buffer bw)
10007 (unless (and (interactive-p) (not ndown))
10008 (unless (let (inhibit-redisplay)
10009 (y-or-n-p "Debugging Formula. Continue to next? "))
10010 (org-table-align)
10011 (error "Abort"))
10012 (delete-window bw)
10013 (message "")))
10014 (if (listp ev) (setq fmt nil ev "#ERROR"))
10015 (org-table-justify-field-maybe
10016 (if fmt (format fmt (string-to-number ev)) ev))
10017 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10018 (call-interactively 'org-return)
10019 (setq ndown 0)))
10020 (and down (org-table-maybe-recalculate-line))
10021 (or suppress-align (and org-table-may-need-update
10022 (org-table-align))))))
10024 (defun org-table-put-field-property (prop value)
10025 (save-excursion
10026 (put-text-property (progn (skip-chars-backward "^|") (point))
10027 (progn (skip-chars-forward "^|") (point))
10028 prop value)))
10030 (defun org-table-get-range (desc &optional tbeg col highlight)
10031 "Get a calc vector from a column, accorting to descriptor DESC.
10032 Optional arguments TBEG and COL can give the beginning of the table and
10033 the current column, to avoid unnecessary parsing.
10034 HIGHLIGHT means, just highlight the range."
10035 (if (not (equal (string-to-char desc) ?@))
10036 (setq desc (concat "@" desc)))
10037 (save-excursion
10038 (or tbeg (setq tbeg (org-table-begin)))
10039 (or col (setq col (org-table-current-column)))
10040 (let ((thisline (org-current-line))
10041 beg end c1 c2 r1 r2 rangep tmp)
10042 (unless (string-match org-table-range-regexp desc)
10043 (error "Invalid table range specifier `%s'" desc))
10044 (setq rangep (match-end 3)
10045 r1 (and (match-end 1) (match-string 1 desc))
10046 r2 (and (match-end 4) (match-string 4 desc))
10047 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10048 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10050 (and c1 (setq c1 (+ (string-to-number c1)
10051 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10052 (and c2 (setq c2 (+ (string-to-number c2)
10053 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10054 (if (equal r1 "") (setq r1 nil))
10055 (if (equal r2 "") (setq r2 nil))
10056 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10057 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10058 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10059 (if (not r1) (setq r1 thisline))
10060 (if (not r2) (setq r2 thisline))
10061 (if (not c1) (setq c1 col))
10062 (if (not c2) (setq c2 col))
10063 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10064 ;; just one field
10065 (progn
10066 (goto-line r1)
10067 (while (not (looking-at org-table-dataline-regexp))
10068 (beginning-of-line 2))
10069 (prog1 (org-trim (org-table-get-field c1))
10070 (if highlight (org-table-highlight-rectangle (point) (point)))))
10071 ;; A range, return a vector
10072 ;; First sort the numbers to get a regular ractangle
10073 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10074 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10075 (goto-line r1)
10076 (while (not (looking-at org-table-dataline-regexp))
10077 (beginning-of-line 2))
10078 (org-table-goto-column c1)
10079 (setq beg (point))
10080 (goto-line r2)
10081 (while (not (looking-at org-table-dataline-regexp))
10082 (beginning-of-line 0))
10083 (org-table-goto-column c2)
10084 (setq end (point))
10085 (if highlight
10086 (org-table-highlight-rectangle
10087 beg (progn (skip-chars-forward "^|\n") (point))))
10088 ;; return string representation of calc vector
10089 (mapcar 'org-trim
10090 (apply 'append (org-table-copy-region beg end)))))))
10092 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10093 "Analyze descriptor DESC and retrieve the corresponding line number.
10094 The cursor is currently in line CLINE, the table begins in line BLINE,
10095 and TABLE is a vector with line types."
10096 (if (string-match "^[0-9]+$" desc)
10097 (aref org-table-dlines (string-to-number desc))
10098 (setq cline (or cline (org-current-line))
10099 bline (or bline org-table-current-begin-line)
10100 table (or table org-table-current-line-types))
10101 (if (or
10102 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10103 ;; 1 2 3 4 5 6
10104 (and (not (match-end 3)) (not (match-end 6)))
10105 (and (match-end 3) (match-end 6) (not (match-end 5))))
10106 (error "invalid row descriptor `%s'" desc))
10107 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10108 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10109 (odir (and (match-end 5) (match-string 5 desc)))
10110 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10111 (i (- cline bline))
10112 (rel (and (match-end 6)
10113 (or (and (match-end 1) (not (match-end 3)))
10114 (match-end 5)))))
10115 (if (and hn (not hdir))
10116 (progn
10117 (setq i 0 hdir "+")
10118 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10119 (if (and (not hn) on (not odir))
10120 (error "should never happen");;(aref org-table-dlines on)
10121 (if (and hn (> hn 0))
10122 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10123 (if on
10124 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10125 (+ bline i)))))
10127 (defun org-find-row-type (table i type backwards relative n)
10128 (let ((l (length table)))
10129 (while (> n 0)
10130 (while (and (setq i (+ i (if backwards -1 1)))
10131 (>= i 0) (< i l)
10132 (not (eq (aref table i) type))
10133 (if (and relative (eq (aref table i) 'hline))
10134 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10135 t)))
10136 (setq n (1- n)))
10137 (if (or (< i 0) (>= i l))
10138 (error "Row descriptior leads outside table")
10139 i)))
10141 (defun org-rewrite-old-row-references (s)
10142 (if (string-match "&[-+0-9I]" s)
10143 (error "Formula contains old &row reference, please rewrite using @-syntax")
10146 (defun org-table-make-reference (elements keep-empty numbers lispp)
10147 "Convert list ELEMENTS to something appropriate to insert into formula.
10148 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10149 NUMBERS indicates that everything should be converted to numbers.
10150 LISPP means to return something appropriate for a Lisp list."
10151 (if (stringp elements) ; just a single val
10152 (if lispp
10153 (if (eq lispp 'literal)
10154 elements
10155 (prin1-to-string (if numbers (string-to-number elements) elements)))
10156 (if (equal elements "") (setq elements "0"))
10157 (if numbers (number-to-string (string-to-number elements)) elements))
10158 (unless keep-empty
10159 (setq elements
10160 (delq nil
10161 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10162 elements))))
10163 (setq elements (or elements '("0")))
10164 (if lispp
10165 (mapconcat
10166 (lambda (x)
10167 (if (eq lispp 'literal)
10169 (prin1-to-string (if numbers (string-to-number x) x))))
10170 elements " ")
10171 (concat "[" (mapconcat
10172 (lambda (x)
10173 (if numbers (number-to-string (string-to-number x)) x))
10174 elements
10175 ",") "]"))))
10177 (defun org-table-recalculate (&optional all noalign)
10178 "Recalculate the current table line by applying all stored formulas.
10179 With prefix arg ALL, do this for all lines in the table."
10180 (interactive "P")
10181 (or (memq this-command org-recalc-commands)
10182 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10183 (unless (org-at-table-p) (error "Not at a table"))
10184 (if (equal all '(16))
10185 (org-table-iterate)
10186 (org-table-get-specials)
10187 (let* ((eqlist (sort (org-table-get-stored-formulas)
10188 (lambda (a b) (string< (car a) (car b)))))
10189 (inhibit-redisplay (not debug-on-error))
10190 (line-re org-table-dataline-regexp)
10191 (thisline (org-current-line))
10192 (thiscol (org-table-current-column))
10193 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10194 ;; Insert constants in all formulas
10195 (setq eqlist
10196 (mapcar (lambda (x)
10197 (setcdr x (org-table-formula-substitute-names (cdr x)))
10199 eqlist))
10200 ;; Split the equation list
10201 (while (setq eq (pop eqlist))
10202 (if (<= (string-to-char (car eq)) ?9)
10203 (push eq eqlnum)
10204 (push eq eqlname)))
10205 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10206 (if all
10207 (progn
10208 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10209 (goto-char (setq beg (org-table-begin)))
10210 (if (re-search-forward org-table-calculate-mark-regexp end t)
10211 ;; This is a table with marked lines, compute selected lines
10212 (setq line-re org-table-recalculate-regexp)
10213 ;; Move forward to the first non-header line
10214 (if (and (re-search-forward org-table-dataline-regexp end t)
10215 (re-search-forward org-table-hline-regexp end t)
10216 (re-search-forward org-table-dataline-regexp end t))
10217 (setq beg (match-beginning 0))
10218 nil))) ;; just leave beg where it is
10219 (setq beg (point-at-bol)
10220 end (move-marker (make-marker) (1+ (point-at-eol)))))
10221 (goto-char beg)
10222 (and all (message "Re-applying formulas to full table..."))
10224 ;; First find the named fields, and mark them untouchanble
10225 (remove-text-properties beg end '(org-untouchable t))
10226 (while (setq eq (pop eqlname))
10227 (setq name (car eq)
10228 a (assoc name org-table-named-field-locations))
10229 (and (not a)
10230 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10231 (setq a (list name
10232 (aref org-table-dlines
10233 (string-to-number (match-string 1 name)))
10234 (string-to-number (match-string 2 name)))))
10235 (when (and a (or all (equal (nth 1 a) thisline)))
10236 (message "Re-applying formula to field: %s" name)
10237 (goto-line (nth 1 a))
10238 (org-table-goto-column (nth 2 a))
10239 (push (append a (list (cdr eq))) eqlname1)
10240 (org-table-put-field-property :org-untouchable t)))
10242 ;; Now evauluate the column formulas, but skip fields covered by
10243 ;; field formulas
10244 (goto-char beg)
10245 (while (re-search-forward line-re end t)
10246 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10247 ;; Unprotected line, recalculate
10248 (and all (message "Re-applying formulas to full table...(line %d)"
10249 (setq cnt (1+ cnt))))
10250 (setq org-last-recalc-line (org-current-line))
10251 (setq eql eqlnum)
10252 (while (setq entry (pop eql))
10253 (goto-line org-last-recalc-line)
10254 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10255 (unless (get-text-property (point) :org-untouchable)
10256 (org-table-eval-formula nil (cdr entry)
10257 'noalign 'nocst 'nostore 'noanalysis)))))
10259 ;; Now evaluate the field formulas
10260 (while (setq eq (pop eqlname1))
10261 (message "Re-applying formula to field: %s" (car eq))
10262 (goto-line (nth 1 eq))
10263 (org-table-goto-column (nth 2 eq))
10264 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10265 'nostore 'noanalysis))
10267 (goto-line thisline)
10268 (org-table-goto-column thiscol)
10269 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10270 (or noalign (and org-table-may-need-update (org-table-align))
10271 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10273 ;; back to initial position
10274 (message "Re-applying formulas...done")
10275 (goto-line thisline)
10276 (org-table-goto-column thiscol)
10277 (or noalign (and org-table-may-need-update (org-table-align))
10278 (and all (message "Re-applying formulas...done"))))))
10280 (defun org-table-iterate (&optional arg)
10281 "Recalculate the table until it does not change anymore."
10282 (interactive "P")
10283 (let ((imax (if arg (prefix-numeric-value arg) 10))
10284 (i 0)
10285 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10286 thistbl)
10287 (catch 'exit
10288 (while (< i imax)
10289 (setq i (1+ i))
10290 (org-table-recalculate 'all)
10291 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10292 (if (not (string= lasttbl thistbl))
10293 (setq lasttbl thistbl)
10294 (if (> i 1)
10295 (message "Convergence after %d iterations" i)
10296 (message "Table was already stable"))
10297 (throw 'exit t)))
10298 (error "No convergence after %d iterations" i))))
10300 (defun org-table-formula-substitute-names (f)
10301 "Replace $const with values in string F."
10302 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10303 ;; First, check for column names
10304 (while (setq start (string-match org-table-column-name-regexp f start))
10305 (setq start (1+ start))
10306 (setq a (assoc (match-string 1 f) org-table-column-names))
10307 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10308 ;; Parameters and constants
10309 (setq start 0)
10310 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10311 (setq start (1+ start))
10312 (if (setq a (save-match-data
10313 (org-table-get-constant (match-string 1 f))))
10314 (setq f (replace-match
10315 (concat (if pp "(") a (if pp ")")) t t f))))
10316 (if org-table-formula-debug
10317 (put-text-property 0 (length f) :orig-formula f1 f))
10320 (defun org-table-get-constant (const)
10321 "Find the value for a parameter or constant in a formula.
10322 Parameters get priority."
10323 (or (cdr (assoc const org-table-local-parameters))
10324 (cdr (assoc const org-table-formula-constants-local))
10325 (cdr (assoc const org-table-formula-constants))
10326 (and (fboundp 'constants-get) (constants-get const))
10327 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10328 (org-entry-get nil (substring const 5) 'inherit))
10329 "#UNDEFINED_NAME"))
10331 (defvar org-table-fedit-map
10332 (let ((map (make-sparse-keymap)))
10333 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10334 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10335 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10336 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10337 (org-defkey map "\C-c?" 'org-table-show-reference)
10338 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10339 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10340 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10341 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10342 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10343 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10344 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10345 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10346 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10347 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10348 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10349 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10350 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10351 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10352 map))
10354 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10355 '("Edit-Formulas"
10356 ["Finish and Install" org-table-fedit-finish t]
10357 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10358 ["Abort" org-table-fedit-abort t]
10359 "--"
10360 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10361 ["Complete Lisp Symbol" lisp-complete-symbol t]
10362 "--"
10363 "Shift Reference at Point"
10364 ["Up" org-table-fedit-ref-up t]
10365 ["Down" org-table-fedit-ref-down t]
10366 ["Left" org-table-fedit-ref-left t]
10367 ["Right" org-table-fedit-ref-right t]
10369 "Change Test Row for Column Formulas"
10370 ["Up" org-table-fedit-line-up t]
10371 ["Down" org-table-fedit-line-down t]
10372 "--"
10373 ["Scroll Table Window" org-table-fedit-scroll t]
10374 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10375 ["Show Table Grid" org-table-fedit-toggle-coordinates
10376 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10377 org-table-overlay-coordinates)]
10378 "--"
10379 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10380 :style toggle :selected org-table-buffer-is-an]))
10382 (defvar org-pos)
10384 (defun org-table-edit-formulas ()
10385 "Edit the formulas of the current table in a separate buffer."
10386 (interactive)
10387 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10388 (beginning-of-line 0))
10389 (unless (org-at-table-p) (error "Not at a table"))
10390 (org-table-get-specials)
10391 (let ((key (org-table-current-field-formula 'key 'noerror))
10392 (eql (sort (org-table-get-stored-formulas 'noerror)
10393 'org-table-formula-less-p))
10394 (pos (move-marker (make-marker) (point)))
10395 (startline 1)
10396 (wc (current-window-configuration))
10397 (titles '((column . "# Column Formulas\n")
10398 (field . "# Field Formulas\n")
10399 (named . "# Named Field Formulas\n")))
10400 entry s type title)
10401 (org-switch-to-buffer-other-window "*Edit Formulas*")
10402 (erase-buffer)
10403 ;; Keep global-font-lock-mode from turning on font-lock-mode
10404 (let ((font-lock-global-modes '(not fundamental-mode)))
10405 (fundamental-mode))
10406 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10407 (org-set-local 'org-pos pos)
10408 (org-set-local 'org-window-configuration wc)
10409 (use-local-map org-table-fedit-map)
10410 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10411 (easy-menu-add org-table-fedit-menu)
10412 (setq startline (org-current-line))
10413 (while (setq entry (pop eql))
10414 (setq type (cond
10415 ((equal (string-to-char (car entry)) ?@) 'field)
10416 ((string-match "^[0-9]" (car entry)) 'column)
10417 (t 'named)))
10418 (when (setq title (assq type titles))
10419 (or (bobp) (insert "\n"))
10420 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10421 (setq titles (delq title titles)))
10422 (if (equal key (car entry)) (setq startline (org-current-line)))
10423 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10424 (car entry) " = " (cdr entry) "\n"))
10425 (remove-text-properties 0 (length s) '(face nil) s)
10426 (insert s))
10427 (if (eq org-table-use-standard-references t)
10428 (org-table-fedit-toggle-ref-type))
10429 (goto-line startline)
10430 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10432 (defun org-table-fedit-post-command ()
10433 (when (not (memq this-command '(lisp-complete-symbol)))
10434 (let ((win (selected-window)))
10435 (save-excursion
10436 (condition-case nil
10437 (org-table-show-reference)
10438 (error nil))
10439 (select-window win)))))
10441 (defun org-table-formula-to-user (s)
10442 "Convert a formula from internal to user representation."
10443 (if (eq org-table-use-standard-references t)
10444 (org-table-convert-refs-to-an s)
10447 (defun org-table-formula-from-user (s)
10448 "Convert a formula from user to internal representation."
10449 (if org-table-use-standard-references
10450 (org-table-convert-refs-to-rc s)
10453 (defun org-table-convert-refs-to-rc (s)
10454 "Convert spreadsheet references from AB7 to @7$28.
10455 Works for single references, but also for entire formulas and even the
10456 full TBLFM line."
10457 (let ((start 0))
10458 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10459 (cond
10460 ((match-end 3)
10461 ;; format match, just advance
10462 (setq start (match-end 0)))
10463 ((and (> (match-beginning 0) 0)
10464 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10465 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10466 ;; 3.e5 or something like this.
10467 (setq start (match-end 0)))
10469 (setq start (match-beginning 0)
10470 s (replace-match
10471 (if (equal (match-string 2 s) "&")
10472 (format "$%d" (org-letters-to-number (match-string 1 s)))
10473 (format "@%d$%d"
10474 (string-to-number (match-string 2 s))
10475 (org-letters-to-number (match-string 1 s))))
10476 t t s)))))
10479 (defun org-table-convert-refs-to-an (s)
10480 "Convert spreadsheet references from to @7$28 to AB7.
10481 Works for single references, but also for entire formulas and even the
10482 full TBLFM line."
10483 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10484 (setq s (replace-match
10485 (format "%s%d"
10486 (org-number-to-letters
10487 (string-to-number (match-string 2 s)))
10488 (string-to-number (match-string 1 s)))
10489 t t s)))
10490 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10491 (setq s (replace-match (concat "\\1"
10492 (org-number-to-letters
10493 (string-to-number (match-string 2 s))) "&")
10494 t nil s)))
10497 (defun org-letters-to-number (s)
10498 "Convert a base 26 number represented by letters into an integer.
10499 For example: AB -> 28."
10500 (let ((n 0))
10501 (setq s (upcase s))
10502 (while (> (length s) 0)
10503 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10504 s (substring s 1)))
10507 (defun org-number-to-letters (n)
10508 "Convert an integer into a base 26 number represented by letters.
10509 For example: 28 -> AB."
10510 (let ((s ""))
10511 (while (> n 0)
10512 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10513 n (/ (1- n) 26)))
10516 (defun org-table-fedit-convert-buffer (function)
10517 "Convert all references in this buffer, using FUNTION."
10518 (let ((line (org-current-line)))
10519 (goto-char (point-min))
10520 (while (not (eobp))
10521 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10522 (delete-region (point) (point-at-eol))
10523 (or (eobp) (forward-char 1)))
10524 (goto-line line)))
10526 (defun org-table-fedit-toggle-ref-type ()
10527 "Convert all references in the buffer from B3 to @3$2 and back."
10528 (interactive)
10529 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10530 (org-table-fedit-convert-buffer
10531 (if org-table-buffer-is-an
10532 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10533 (message "Reference type switched to %s"
10534 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10536 (defun org-table-fedit-ref-up ()
10537 "Shift the reference at point one row/hline up."
10538 (interactive)
10539 (org-table-fedit-shift-reference 'up))
10540 (defun org-table-fedit-ref-down ()
10541 "Shift the reference at point one row/hline down."
10542 (interactive)
10543 (org-table-fedit-shift-reference 'down))
10544 (defun org-table-fedit-ref-left ()
10545 "Shift the reference at point one field to the left."
10546 (interactive)
10547 (org-table-fedit-shift-reference 'left))
10548 (defun org-table-fedit-ref-right ()
10549 "Shift the reference at point one field to the right."
10550 (interactive)
10551 (org-table-fedit-shift-reference 'right))
10553 (defun org-table-fedit-shift-reference (dir)
10554 (cond
10555 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10556 (if (memq dir '(left right))
10557 (org-rematch-and-replace 1 (eq dir 'left))
10558 (error "Cannot shift reference in this direction")))
10559 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10560 ;; A B3-like reference
10561 (if (memq dir '(up down))
10562 (org-rematch-and-replace 2 (eq dir 'up))
10563 (org-rematch-and-replace 1 (eq dir 'left))))
10564 ((org-at-regexp-p
10565 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10566 ;; An internal reference
10567 (if (memq dir '(up down))
10568 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10569 (org-rematch-and-replace 5 (eq dir 'left))))))
10571 (defun org-rematch-and-replace (n &optional decr hline)
10572 "Re-match the group N, and replace it with the shifted refrence."
10573 (or (match-end n) (error "Cannot shift reference in this direction"))
10574 (goto-char (match-beginning n))
10575 (and (looking-at (regexp-quote (match-string n)))
10576 (replace-match (org-shift-refpart (match-string 0) decr hline)
10577 t t)))
10579 (defun org-shift-refpart (ref &optional decr hline)
10580 "Shift a refrence part REF.
10581 If DECR is set, decrease the references row/column, else increase.
10582 If HLINE is set, this may be a hline reference, it certainly is not
10583 a translation reference."
10584 (save-match-data
10585 (let* ((sign (string-match "^[-+]" ref)) n)
10587 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10588 (cond
10589 ((and hline (string-match "^I+" ref))
10590 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10591 (setq n (+ n (if decr -1 1)))
10592 (if (= n 0) (setq n (+ n (if decr -1 1))))
10593 (if sign
10594 (setq sign (if (< n 0) "-" "+") n (abs n))
10595 (setq n (max 1 n)))
10596 (concat sign (make-string n ?I)))
10598 ((string-match "^[0-9]+" ref)
10599 (setq n (string-to-number (concat sign ref)))
10600 (setq n (+ n (if decr -1 1)))
10601 (if sign
10602 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10603 (number-to-string (max 1 n))))
10605 ((string-match "^[a-zA-Z]+" ref)
10606 (org-number-to-letters
10607 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10609 (t (error "Cannot shift reference"))))))
10611 (defun org-table-fedit-toggle-coordinates ()
10612 "Toggle the display of coordinates in the refrenced table."
10613 (interactive)
10614 (let ((pos (marker-position org-pos)))
10615 (with-current-buffer (marker-buffer org-pos)
10616 (save-excursion
10617 (goto-char pos)
10618 (org-table-toggle-coordinate-overlays)))))
10620 (defun org-table-fedit-finish (&optional arg)
10621 "Parse the buffer for formula definitions and install them.
10622 With prefix ARG, apply the new formulas to the table."
10623 (interactive "P")
10624 (org-table-remove-rectangle-highlight)
10625 (if org-table-use-standard-references
10626 (progn
10627 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10628 (setq org-table-buffer-is-an nil)))
10629 (let ((pos org-pos) eql var form)
10630 (goto-char (point-min))
10631 (while (re-search-forward
10632 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10633 nil t)
10634 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10635 form (match-string 3))
10636 (setq form (org-trim form))
10637 (when (not (equal form ""))
10638 (while (string-match "[ \t]*\n[ \t]*" form)
10639 (setq form (replace-match " " t t form)))
10640 (when (assoc var eql)
10641 (error "Double formulas for %s" var))
10642 (push (cons var form) eql)))
10643 (setq org-pos nil)
10644 (set-window-configuration org-window-configuration)
10645 (select-window (get-buffer-window (marker-buffer pos)))
10646 (goto-char pos)
10647 (unless (org-at-table-p)
10648 (error "Lost table position - cannot install formulae"))
10649 (org-table-store-formulas eql)
10650 (move-marker pos nil)
10651 (kill-buffer "*Edit Formulas*")
10652 (if arg
10653 (org-table-recalculate 'all)
10654 (message "New formulas installed - press C-u C-c C-c to apply."))))
10656 (defun org-table-fedit-abort ()
10657 "Abort editing formulas, without installing the changes."
10658 (interactive)
10659 (org-table-remove-rectangle-highlight)
10660 (let ((pos org-pos))
10661 (set-window-configuration org-window-configuration)
10662 (select-window (get-buffer-window (marker-buffer pos)))
10663 (goto-char pos)
10664 (move-marker pos nil)
10665 (message "Formula editing aborted without installing changes")))
10667 (defun org-table-fedit-lisp-indent ()
10668 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10669 (interactive)
10670 (let ((pos (point)) beg end ind)
10671 (beginning-of-line 1)
10672 (cond
10673 ((looking-at "[ \t]")
10674 (goto-char pos)
10675 (call-interactively 'lisp-indent-line))
10676 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10677 ((not (fboundp 'pp-buffer))
10678 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10679 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10680 (goto-char (- (match-end 0) 2))
10681 (setq beg (point))
10682 (setq ind (make-string (current-column) ?\ ))
10683 (condition-case nil (forward-sexp 1)
10684 (error
10685 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10686 (setq end (point))
10687 (save-restriction
10688 (narrow-to-region beg end)
10689 (if (eq last-command this-command)
10690 (progn
10691 (goto-char (point-min))
10692 (setq this-command nil)
10693 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10694 (replace-match " ")))
10695 (pp-buffer)
10696 (untabify (point-min) (point-max))
10697 (goto-char (1+ (point-min)))
10698 (while (re-search-forward "^." nil t)
10699 (beginning-of-line 1)
10700 (insert ind))
10701 (goto-char (point-max))
10702 (backward-delete-char 1)))
10703 (goto-char beg))
10704 (t nil))))
10706 (defvar org-show-positions nil)
10708 (defun org-table-show-reference (&optional local)
10709 "Show the location/value of the $ expression at point."
10710 (interactive)
10711 (org-table-remove-rectangle-highlight)
10712 (catch 'exit
10713 (let ((pos (if local (point) org-pos))
10714 (face2 'highlight)
10715 (org-inhibit-highlight-removal t)
10716 (win (selected-window))
10717 (org-show-positions nil)
10718 var name e what match dest)
10719 (if local (org-table-get-specials))
10720 (setq what (cond
10721 ((or (org-at-regexp-p org-table-range-regexp2)
10722 (org-at-regexp-p org-table-translate-regexp)
10723 (org-at-regexp-p org-table-range-regexp))
10724 (setq match
10725 (save-match-data
10726 (org-table-convert-refs-to-rc (match-string 0))))
10727 'range)
10728 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10729 ((org-at-regexp-p "\\$[0-9]+") 'column)
10730 ((not local) nil)
10731 (t (error "No reference at point")))
10732 match (and what (or match (match-string 0))))
10733 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10734 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10735 'secondary-selection))
10736 (org-add-hook 'before-change-functions
10737 'org-table-remove-rectangle-highlight)
10738 (if (eq what 'name) (setq var (substring match 1)))
10739 (when (eq what 'range)
10740 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10741 (setq match (org-table-formula-substitute-names match)))
10742 (unless local
10743 (save-excursion
10744 (end-of-line 1)
10745 (re-search-backward "^\\S-" nil t)
10746 (beginning-of-line 1)
10747 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10748 (setq dest
10749 (save-match-data
10750 (org-table-convert-refs-to-rc (match-string 1))))
10751 (org-table-add-rectangle-overlay
10752 (match-beginning 1) (match-end 1) face2))))
10753 (if (and (markerp pos) (marker-buffer pos))
10754 (if (get-buffer-window (marker-buffer pos))
10755 (select-window (get-buffer-window (marker-buffer pos)))
10756 (org-switch-to-buffer-other-window (get-buffer-window
10757 (marker-buffer pos)))))
10758 (goto-char pos)
10759 (org-table-force-dataline)
10760 (when dest
10761 (setq name (substring dest 1))
10762 (cond
10763 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10764 (setq e (assoc name org-table-named-field-locations))
10765 (goto-line (nth 1 e))
10766 (org-table-goto-column (nth 2 e)))
10767 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10768 (let ((l (string-to-number (match-string 1 dest)))
10769 (c (string-to-number (match-string 2 dest))))
10770 (goto-line (aref org-table-dlines l))
10771 (org-table-goto-column c)))
10772 (t (org-table-goto-column (string-to-number name))))
10773 (move-marker pos (point))
10774 (org-table-highlight-rectangle nil nil face2))
10775 (cond
10776 ((equal dest match))
10777 ((not match))
10778 ((eq what 'range)
10779 (condition-case nil
10780 (save-excursion
10781 (org-table-get-range match nil nil 'highlight))
10782 (error nil)))
10783 ((setq e (assoc var org-table-named-field-locations))
10784 (goto-line (nth 1 e))
10785 (org-table-goto-column (nth 2 e))
10786 (org-table-highlight-rectangle (point) (point))
10787 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10788 ((setq e (assoc var org-table-column-names))
10789 (org-table-goto-column (string-to-number (cdr e)))
10790 (org-table-highlight-rectangle (point) (point))
10791 (goto-char (org-table-begin))
10792 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10793 (org-table-end) t)
10794 (progn
10795 (goto-char (match-beginning 1))
10796 (org-table-highlight-rectangle)
10797 (message "Named column (column %s)" (cdr e)))
10798 (error "Column name not found")))
10799 ((eq what 'column)
10800 ;; column number
10801 (org-table-goto-column (string-to-number (substring match 1)))
10802 (org-table-highlight-rectangle (point) (point))
10803 (message "Column %s" (substring match 1)))
10804 ((setq e (assoc var org-table-local-parameters))
10805 (goto-char (org-table-begin))
10806 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10807 (progn
10808 (goto-char (match-beginning 1))
10809 (org-table-highlight-rectangle)
10810 (message "Local parameter."))
10811 (error "Parameter not found")))
10813 (cond
10814 ((not var) (error "No reference at point"))
10815 ((setq e (assoc var org-table-formula-constants-local))
10816 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10817 var (cdr e)))
10818 ((setq e (assoc var org-table-formula-constants))
10819 (message "Constant: $%s=%s in `org-table-formula-constants'."
10820 var (cdr e)))
10821 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10822 (message "Constant: $%s=%s, from `constants.el'%s."
10823 var e (format " (%s units)" constants-unit-system)))
10824 (t (error "Undefined name $%s" var)))))
10825 (goto-char pos)
10826 (when (and org-show-positions
10827 (not (memq this-command '(org-table-fedit-scroll
10828 org-table-fedit-scroll-down))))
10829 (push pos org-show-positions)
10830 (push org-table-current-begin-pos org-show-positions)
10831 (let ((min (apply 'min org-show-positions))
10832 (max (apply 'max org-show-positions)))
10833 (goto-char min) (recenter 0)
10834 (goto-char max)
10835 (or (pos-visible-in-window-p max) (recenter -1))))
10836 (select-window win))))
10838 (defun org-table-force-dataline ()
10839 "Make sure the cursor is in a dataline in a table."
10840 (unless (save-excursion
10841 (beginning-of-line 1)
10842 (looking-at org-table-dataline-regexp))
10843 (let* ((re org-table-dataline-regexp)
10844 (p1 (save-excursion (re-search-forward re nil 'move)))
10845 (p2 (save-excursion (re-search-backward re nil 'move))))
10846 (cond ((and p1 p2)
10847 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10848 p1 p2)))
10849 ((or p1 p2) (goto-char (or p1 p2)))
10850 (t (error "No table dataline around here"))))))
10852 (defun org-table-fedit-line-up ()
10853 "Move cursor one line up in the window showing the table."
10854 (interactive)
10855 (org-table-fedit-move 'previous-line))
10857 (defun org-table-fedit-line-down ()
10858 "Move cursor one line down in the window showing the table."
10859 (interactive)
10860 (org-table-fedit-move 'next-line))
10862 (defun org-table-fedit-move (command)
10863 "Move the cursor in the window shoinw the table.
10864 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10865 (let ((org-table-allow-automatic-line-recalculation nil)
10866 (pos org-pos) (win (selected-window)) p)
10867 (select-window (get-buffer-window (marker-buffer org-pos)))
10868 (setq p (point))
10869 (call-interactively command)
10870 (while (and (org-at-table-p)
10871 (org-at-table-hline-p))
10872 (call-interactively command))
10873 (or (org-at-table-p) (goto-char p))
10874 (move-marker pos (point))
10875 (select-window win)))
10877 (defun org-table-fedit-scroll (N)
10878 (interactive "p")
10879 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10880 (scroll-other-window N)))
10882 (defun org-table-fedit-scroll-down (N)
10883 (interactive "p")
10884 (org-table-fedit-scroll (- N)))
10886 (defvar org-table-rectangle-overlays nil)
10888 (defun org-table-add-rectangle-overlay (beg end &optional face)
10889 "Add a new overlay."
10890 (let ((ov (org-make-overlay beg end)))
10891 (org-overlay-put ov 'face (or face 'secondary-selection))
10892 (push ov org-table-rectangle-overlays)))
10894 (defun org-table-highlight-rectangle (&optional beg end face)
10895 "Highlight rectangular region in a table."
10896 (setq beg (or beg (point)) end (or end (point)))
10897 (let ((b (min beg end))
10898 (e (max beg end))
10899 l1 c1 l2 c2 tmp)
10900 (and (boundp 'org-show-positions)
10901 (setq org-show-positions (cons b (cons e org-show-positions))))
10902 (goto-char (min beg end))
10903 (setq l1 (org-current-line)
10904 c1 (org-table-current-column))
10905 (goto-char (max beg end))
10906 (setq l2 (org-current-line)
10907 c2 (org-table-current-column))
10908 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10909 (goto-line l1)
10910 (beginning-of-line 1)
10911 (loop for line from l1 to l2 do
10912 (when (looking-at org-table-dataline-regexp)
10913 (org-table-goto-column c1)
10914 (skip-chars-backward "^|\n") (setq beg (point))
10915 (org-table-goto-column c2)
10916 (skip-chars-forward "^|\n") (setq end (point))
10917 (org-table-add-rectangle-overlay beg end face))
10918 (beginning-of-line 2))
10919 (goto-char b))
10920 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10922 (defun org-table-remove-rectangle-highlight (&rest ignore)
10923 "Remove the rectangle overlays."
10924 (unless org-inhibit-highlight-removal
10925 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10926 (mapc 'org-delete-overlay org-table-rectangle-overlays)
10927 (setq org-table-rectangle-overlays nil)))
10929 (defvar org-table-coordinate-overlays nil
10930 "Collects the cooordinate grid overlays, so that they can be removed.")
10931 (make-variable-buffer-local 'org-table-coordinate-overlays)
10933 (defun org-table-overlay-coordinates ()
10934 "Add overlays to the table at point, to show row/column coordinates."
10935 (interactive)
10936 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10937 (setq org-table-coordinate-overlays nil)
10938 (save-excursion
10939 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10940 (goto-char (org-table-begin))
10941 (while (org-at-table-p)
10942 (setq eol (point-at-eol))
10943 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10944 (push ov org-table-coordinate-overlays)
10945 (setq hline (looking-at org-table-hline-regexp))
10946 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10947 (format "%4d" (setq id (1+ id)))))
10948 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10949 (when hline
10950 (setq ic 0)
10951 (while (re-search-forward "[+|]\\(-+\\)" eol t)
10952 (setq beg (1+ (match-beginning 0))
10953 ic (1+ ic)
10954 s1 (concat "$" (int-to-string ic))
10955 s2 (org-number-to-letters ic)
10956 str (if (eq org-table-use-standard-references t) s2 s1))
10957 (setq ov (org-make-overlay beg (+ beg (length str))))
10958 (push ov org-table-coordinate-overlays)
10959 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10960 (beginning-of-line 2)))))
10962 (defun org-table-toggle-coordinate-overlays ()
10963 "Toggle the display of Row/Column numbers in tables."
10964 (interactive)
10965 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10966 (message "Row/Column number display turned %s"
10967 (if org-table-overlay-coordinates "on" "off"))
10968 (if (and (org-at-table-p) org-table-overlay-coordinates)
10969 (org-table-align))
10970 (unless org-table-overlay-coordinates
10971 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10972 (setq org-table-coordinate-overlays nil)))
10974 (defun org-table-toggle-formula-debugger ()
10975 "Toggle the formula debugger in tables."
10976 (interactive)
10977 (setq org-table-formula-debug (not org-table-formula-debug))
10978 (message "Formula debugging has been turned %s"
10979 (if org-table-formula-debug "on" "off")))
10981 ;;; The orgtbl minor mode
10983 ;; Define a minor mode which can be used in other modes in order to
10984 ;; integrate the org-mode table editor.
10986 ;; This is really a hack, because the org-mode table editor uses several
10987 ;; keys which normally belong to the major mode, for example the TAB and
10988 ;; RET keys. Here is how it works: The minor mode defines all the keys
10989 ;; necessary to operate the table editor, but wraps the commands into a
10990 ;; function which tests if the cursor is currently inside a table. If that
10991 ;; is the case, the table editor command is executed. However, when any of
10992 ;; those keys is used outside a table, the function uses `key-binding' to
10993 ;; look up if the key has an associated command in another currently active
10994 ;; keymap (minor modes, major mode, global), and executes that command.
10995 ;; There might be problems if any of the keys used by the table editor is
10996 ;; otherwise used as a prefix key.
10998 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10999 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11000 ;; addresses this by checking explicitly for both bindings.
11002 ;; The optimized version (see variable `orgtbl-optimized') takes over
11003 ;; all keys which are bound to `self-insert-command' in the *global map*.
11004 ;; Some modes bind other commands to simple characters, for example
11005 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11006 ;; active, this binding is ignored inside tables and replaced with a
11007 ;; modified self-insert.
11009 (defvar orgtbl-mode nil
11010 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11011 table editor in arbitrary modes.")
11012 (make-variable-buffer-local 'orgtbl-mode)
11014 (defvar orgtbl-mode-map (make-keymap)
11015 "Keymap for `orgtbl-mode'.")
11017 ;;;###autoload
11018 (defun turn-on-orgtbl ()
11019 "Unconditionally turn on `orgtbl-mode'."
11020 (orgtbl-mode 1))
11022 (defvar org-old-auto-fill-inhibit-regexp nil
11023 "Local variable used by `orgtbl-mode'")
11025 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11026 "Matches a line belonging to an orgtbl.")
11028 (defconst orgtbl-extra-font-lock-keywords
11029 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11030 0 (quote 'org-table) 'prepend))
11031 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11033 ;;;###autoload
11034 (defun orgtbl-mode (&optional arg)
11035 "The `org-mode' table editor as a minor mode for use in other modes."
11036 (interactive)
11037 (if (org-mode-p)
11038 ;; Exit without error, in case some hook functions calls this
11039 ;; by accident in org-mode.
11040 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11041 (setq orgtbl-mode
11042 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11043 (if orgtbl-mode
11044 (progn
11045 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11046 ;; Make sure we are first in minor-mode-map-alist
11047 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11048 (and c (setq minor-mode-map-alist
11049 (cons c (delq c minor-mode-map-alist)))))
11050 (org-set-local (quote org-table-may-need-update) t)
11051 (org-add-hook 'before-change-functions 'org-before-change-function
11052 nil 'local)
11053 (org-set-local 'org-old-auto-fill-inhibit-regexp
11054 auto-fill-inhibit-regexp)
11055 (org-set-local 'auto-fill-inhibit-regexp
11056 (if auto-fill-inhibit-regexp
11057 (concat orgtbl-line-start-regexp "\\|"
11058 auto-fill-inhibit-regexp)
11059 orgtbl-line-start-regexp))
11060 (org-add-to-invisibility-spec '(org-cwidth))
11061 (when (fboundp 'font-lock-add-keywords)
11062 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11063 (org-restart-font-lock))
11064 (easy-menu-add orgtbl-mode-menu)
11065 (run-hooks 'orgtbl-mode-hook))
11066 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11067 (org-cleanup-narrow-column-properties)
11068 (org-remove-from-invisibility-spec '(org-cwidth))
11069 (remove-hook 'before-change-functions 'org-before-change-function t)
11070 (when (fboundp 'font-lock-remove-keywords)
11071 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11072 (org-restart-font-lock))
11073 (easy-menu-remove orgtbl-mode-menu)
11074 (force-mode-line-update 'all))))
11076 (defun org-cleanup-narrow-column-properties ()
11077 "Remove all properties related to narrow-column invisibility."
11078 (let ((s 1))
11079 (while (setq s (text-property-any s (point-max)
11080 'display org-narrow-column-arrow))
11081 (remove-text-properties s (1+ s) '(display t)))
11082 (setq s 1)
11083 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11084 (remove-text-properties s (1+ s) '(org-cwidth t)))
11085 (setq s 1)
11086 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11087 (remove-text-properties s (1+ s) '(invisible t)))))
11089 ;; Install it as a minor mode.
11090 (put 'orgtbl-mode :included t)
11091 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11092 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11094 (defun orgtbl-make-binding (fun n &rest keys)
11095 "Create a function for binding in the table minor mode.
11096 FUN is the command to call inside a table. N is used to create a unique
11097 command name. KEYS are keys that should be checked in for a command
11098 to execute outside of tables."
11099 (eval
11100 (list 'defun
11101 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11102 '(arg)
11103 (concat "In tables, run `" (symbol-name fun) "'.\n"
11104 "Outside of tables, run the binding of `"
11105 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11106 "'.")
11107 '(interactive "p")
11108 (list 'if
11109 '(org-at-table-p)
11110 (list 'call-interactively (list 'quote fun))
11111 (list 'let '(orgtbl-mode)
11112 (list 'call-interactively
11113 (append '(or)
11114 (mapcar (lambda (k)
11115 (list 'key-binding k))
11116 keys)
11117 '('orgtbl-error))))))))
11119 (defun orgtbl-error ()
11120 "Error when there is no default binding for a table key."
11121 (interactive)
11122 (error "This key has no function outside tables"))
11124 (defun orgtbl-setup ()
11125 "Setup orgtbl keymaps."
11126 (let ((nfunc 0)
11127 (bindings
11128 (list
11129 '([(meta shift left)] org-table-delete-column)
11130 '([(meta left)] org-table-move-column-left)
11131 '([(meta right)] org-table-move-column-right)
11132 '([(meta shift right)] org-table-insert-column)
11133 '([(meta shift up)] org-table-kill-row)
11134 '([(meta shift down)] org-table-insert-row)
11135 '([(meta up)] org-table-move-row-up)
11136 '([(meta down)] org-table-move-row-down)
11137 '("\C-c\C-w" org-table-cut-region)
11138 '("\C-c\M-w" org-table-copy-region)
11139 '("\C-c\C-y" org-table-paste-rectangle)
11140 '("\C-c-" org-table-insert-hline)
11141 '("\C-c}" org-table-toggle-coordinate-overlays)
11142 '("\C-c{" org-table-toggle-formula-debugger)
11143 '("\C-m" org-table-next-row)
11144 '([(shift return)] org-table-copy-down)
11145 '("\C-c\C-q" org-table-wrap-region)
11146 '("\C-c?" org-table-field-info)
11147 '("\C-c " org-table-blank-field)
11148 '("\C-c+" org-table-sum)
11149 '("\C-c=" org-table-eval-formula)
11150 '("\C-c'" org-table-edit-formulas)
11151 '("\C-c`" org-table-edit-field)
11152 '("\C-c*" org-table-recalculate)
11153 '("\C-c|" org-table-create-or-convert-from-region)
11154 '("\C-c^" org-table-sort-lines)
11155 '([(control ?#)] org-table-rotate-recalc-marks)))
11156 elt key fun cmd)
11157 (while (setq elt (pop bindings))
11158 (setq nfunc (1+ nfunc))
11159 (setq key (org-key (car elt))
11160 fun (nth 1 elt)
11161 cmd (orgtbl-make-binding fun nfunc key))
11162 (org-defkey orgtbl-mode-map key cmd))
11164 ;; Special treatment needed for TAB and RET
11165 (org-defkey orgtbl-mode-map [(return)]
11166 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11167 (org-defkey orgtbl-mode-map "\C-m"
11168 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11170 (org-defkey orgtbl-mode-map [(tab)]
11171 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11172 (org-defkey orgtbl-mode-map "\C-i"
11173 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11175 (org-defkey orgtbl-mode-map [(shift tab)]
11176 (orgtbl-make-binding 'org-table-previous-field 104
11177 [(shift tab)] [(tab)] "\C-i"))
11179 (org-defkey orgtbl-mode-map "\M-\C-m"
11180 (orgtbl-make-binding 'org-table-wrap-region 105
11181 "\M-\C-m" [(meta return)]))
11182 (org-defkey orgtbl-mode-map [(meta return)]
11183 (orgtbl-make-binding 'org-table-wrap-region 106
11184 [(meta return)] "\M-\C-m"))
11186 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11187 (when orgtbl-optimized
11188 ;; If the user wants maximum table support, we need to hijack
11189 ;; some standard editing functions
11190 (org-remap orgtbl-mode-map
11191 'self-insert-command 'orgtbl-self-insert-command
11192 'delete-char 'org-delete-char
11193 'delete-backward-char 'org-delete-backward-char)
11194 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11195 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11196 '("OrgTbl"
11197 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11198 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11199 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11200 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11201 "--"
11202 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11203 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11204 ["Copy Field from Above"
11205 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11206 "--"
11207 ("Column"
11208 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11209 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11210 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11211 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11212 ("Row"
11213 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11214 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11215 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11216 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11217 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11218 "--"
11219 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11220 ("Rectangle"
11221 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11222 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11223 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11224 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11225 "--"
11226 ("Radio tables"
11227 ["Insert table template" orgtbl-insert-radio-table
11228 (assq major-mode orgtbl-radio-table-templates)]
11229 ["Comment/uncomment table" orgtbl-toggle-comment t])
11230 "--"
11231 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11232 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11233 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11234 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11235 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11236 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11237 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11238 ["Sum Column/Rectangle" org-table-sum
11239 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11240 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11241 ["Debug Formulas"
11242 org-table-toggle-formula-debugger :active (org-at-table-p)
11243 :keys "C-c {"
11244 :style toggle :selected org-table-formula-debug]
11245 ["Show Col/Row Numbers"
11246 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11247 :keys "C-c }"
11248 :style toggle :selected org-table-overlay-coordinates]
11252 (defun orgtbl-ctrl-c-ctrl-c (arg)
11253 "If the cursor is inside a table, realign the table.
11254 It it is a table to be sent away to a receiver, do it.
11255 With prefix arg, also recompute table."
11256 (interactive "P")
11257 (let ((pos (point)) action)
11258 (save-excursion
11259 (beginning-of-line 1)
11260 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11261 ((looking-at "[ \t]*|") pos)
11262 ((looking-at "#\\+TBLFM:") 'recalc))))
11263 (cond
11264 ((integerp action)
11265 (goto-char action)
11266 (org-table-maybe-eval-formula)
11267 (if arg
11268 (call-interactively 'org-table-recalculate)
11269 (org-table-maybe-recalculate-line))
11270 (call-interactively 'org-table-align)
11271 (orgtbl-send-table 'maybe))
11272 ((eq action 'recalc)
11273 (save-excursion
11274 (beginning-of-line 1)
11275 (skip-chars-backward " \r\n\t")
11276 (if (org-at-table-p)
11277 (org-call-with-arg 'org-table-recalculate t))))
11278 (t (let (orgtbl-mode)
11279 (call-interactively (key-binding "\C-c\C-c")))))))
11281 (defun orgtbl-tab (arg)
11282 "Justification and field motion for `orgtbl-mode'."
11283 (interactive "P")
11284 (if arg (org-table-edit-field t)
11285 (org-table-justify-field-maybe)
11286 (org-table-next-field)))
11288 (defun orgtbl-ret ()
11289 "Justification and field motion for `orgtbl-mode'."
11290 (interactive)
11291 (org-table-justify-field-maybe)
11292 (org-table-next-row))
11294 (defun orgtbl-self-insert-command (N)
11295 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11296 If the cursor is in a table looking at whitespace, the whitespace is
11297 overwritten, and the table is not marked as requiring realignment."
11298 (interactive "p")
11299 (if (and (org-at-table-p)
11301 (and org-table-auto-blank-field
11302 (member last-command
11303 '(orgtbl-hijacker-command-100
11304 orgtbl-hijacker-command-101
11305 orgtbl-hijacker-command-102
11306 orgtbl-hijacker-command-103
11307 orgtbl-hijacker-command-104
11308 orgtbl-hijacker-command-105))
11309 (org-table-blank-field))
11311 (eq N 1)
11312 (looking-at "[^|\n]* +|"))
11313 (let (org-table-may-need-update)
11314 (goto-char (1- (match-end 0)))
11315 (delete-backward-char 1)
11316 (goto-char (match-beginning 0))
11317 (self-insert-command N))
11318 (setq org-table-may-need-update t)
11319 (let (orgtbl-mode)
11320 (call-interactively (key-binding (vector last-input-event))))))
11322 (defun org-force-self-insert (N)
11323 "Needed to enforce self-insert under remapping."
11324 (interactive "p")
11325 (self-insert-command N))
11327 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11328 "Regula expression matching exponentials as produced by calc.")
11330 (defvar org-table-clean-did-remove-column nil)
11332 (defun orgtbl-export (table target)
11333 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11334 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11335 org-table-last-alignment org-table-last-column-widths
11336 maxcol column)
11337 (if (not (fboundp func))
11338 (error "Cannot export orgtbl table to %s" target))
11339 (setq lines (org-table-clean-before-export lines))
11340 (setq table
11341 (mapcar
11342 (lambda (x)
11343 (if (string-match org-table-hline-regexp x)
11344 'hline
11345 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11346 lines))
11347 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11348 table)))
11349 (loop for i from (1- maxcol) downto 0 do
11350 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11351 (setq column (delq nil column))
11352 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11353 (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))
11354 (funcall func table nil)))
11356 (defun orgtbl-send-table (&optional maybe)
11357 "Send a tranformed version of this table to the receiver position.
11358 With argument MAYBE, fail quietly if no transformation is defined for
11359 this table."
11360 (interactive)
11361 (catch 'exit
11362 (unless (org-at-table-p) (error "Not at a table"))
11363 ;; when non-interactive, we assume align has just happened.
11364 (when (interactive-p) (org-table-align))
11365 (save-excursion
11366 (goto-char (org-table-begin))
11367 (beginning-of-line 0)
11368 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11369 (if maybe
11370 (throw 'exit nil)
11371 (error "Don't know how to transform this table."))))
11372 (let* ((name (match-string 1))
11374 (transform (intern (match-string 2)))
11375 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11376 (skip (plist-get params :skip))
11377 (skipcols (plist-get params :skipcols))
11378 (txt (buffer-substring-no-properties
11379 (org-table-begin) (org-table-end)))
11380 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11381 (lines (org-table-clean-before-export lines))
11382 (i0 (if org-table-clean-did-remove-column 2 1))
11383 (table (mapcar
11384 (lambda (x)
11385 (if (string-match org-table-hline-regexp x)
11386 'hline
11387 (org-remove-by-index
11388 (org-split-string (org-trim x) "\\s-*|\\s-*")
11389 skipcols i0)))
11390 lines))
11391 (fun (if (= i0 2) 'cdr 'identity))
11392 (org-table-last-alignment
11393 (org-remove-by-index (funcall fun org-table-last-alignment)
11394 skipcols i0))
11395 (org-table-last-column-widths
11396 (org-remove-by-index (funcall fun org-table-last-column-widths)
11397 skipcols i0)))
11399 (unless (fboundp transform)
11400 (error "No such transformation function %s" transform))
11401 (setq txt (funcall transform table params))
11402 ;; Find the insertion place
11403 (save-excursion
11404 (goto-char (point-min))
11405 (unless (re-search-forward
11406 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11407 (error "Don't know where to insert translated table"))
11408 (goto-char (match-beginning 0))
11409 (beginning-of-line 2)
11410 (setq beg (point))
11411 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11412 (error "Cannot find end of insertion region"))
11413 (beginning-of-line 1)
11414 (delete-region beg (point))
11415 (goto-char beg)
11416 (insert txt "\n"))
11417 (message "Table converted and installed at receiver location"))))
11419 (defun org-remove-by-index (list indices &optional i0)
11420 "Remove the elements in LIST with indices in INDICES.
11421 First element has index 0, or I0 if given."
11422 (if (not indices)
11423 list
11424 (if (integerp indices) (setq indices (list indices)))
11425 (setq i0 (1- (or i0 0)))
11426 (delq :rm (mapcar (lambda (x)
11427 (setq i0 (1+ i0))
11428 (if (memq i0 indices) :rm x))
11429 list))))
11431 (defun orgtbl-toggle-comment ()
11432 "Comment or uncomment the orgtbl at point."
11433 (interactive)
11434 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11435 (re2 (concat "^" orgtbl-line-start-regexp))
11436 (commented (save-excursion (beginning-of-line 1)
11437 (cond ((looking-at re1) t)
11438 ((looking-at re2) nil)
11439 (t (error "Not at an org table")))))
11440 (re (if commented re1 re2))
11441 beg end)
11442 (save-excursion
11443 (beginning-of-line 1)
11444 (while (looking-at re) (beginning-of-line 0))
11445 (beginning-of-line 2)
11446 (setq beg (point))
11447 (while (looking-at re) (beginning-of-line 2))
11448 (setq end (point)))
11449 (comment-region beg end (if commented '(4) nil))))
11451 (defun orgtbl-insert-radio-table ()
11452 "Insert a radio table template appropriate for this major mode."
11453 (interactive)
11454 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11455 (txt (nth 1 e))
11456 name pos)
11457 (unless e (error "No radio table setup defined for %s" major-mode))
11458 (setq name (read-string "Table name: "))
11459 (while (string-match "%n" txt)
11460 (setq txt (replace-match name t t txt)))
11461 (or (bolp) (insert "\n"))
11462 (setq pos (point))
11463 (insert txt)
11464 (goto-char pos)))
11466 (defun org-get-param (params header i sym &optional hsym)
11467 "Get parameter value for symbol SYM.
11468 If this is a header line, actually get the value for the symbol with an
11469 additional \"h\" inserted after the colon.
11470 If the value is a protperty list, get the element for the current column.
11471 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11472 (let ((val (plist-get params sym)))
11473 (and hsym header (setq val (or (plist-get params hsym) val)))
11474 (if (consp val) (plist-get val i) val)))
11476 (defun orgtbl-to-generic (table params)
11477 "Convert the orgtbl-mode TABLE to some other format.
11478 This generic routine can be used for many standard cases.
11479 TABLE is a list, each entry either the symbol `hline' for a horizontal
11480 separator line, or a list of fields for that line.
11481 PARAMS is a property list of parameters that can influence the conversion.
11482 For the generic converter, some parameters are obligatory: You need to
11483 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11484 :splice, you must have :tstart and :tend.
11486 Valid parameters are
11488 :tstart String to start the table. Ignored when :splice is t.
11489 :tend String to end the table. Ignored when :splice is t.
11491 :splice When set to t, return only table body lines, don't wrap
11492 them into :tstart and :tend. Default is nil.
11494 :hline String to be inserted on horizontal separation lines.
11495 May be nil to ignore hlines.
11497 :lstart String to start a new table line.
11498 :lend String to end a table line
11499 :sep Separator between two fields
11500 :lfmt Format for entire line, with enough %s to capture all fields.
11501 If this is present, :lstart, :lend, and :sep are ignored.
11502 :fmt A format to be used to wrap the field, should contain
11503 %s for the original field value. For example, to wrap
11504 everything in dollars, you could use :fmt \"$%s$\".
11505 This may also be a property list with column numbers and
11506 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11508 :hlstart :hlend :hlsep :hlfmt :hfmt
11509 Same as above, specific for the header lines in the table.
11510 All lines before the first hline are treated as header.
11511 If any of these is not present, the data line value is used.
11513 :efmt Use this format to print numbers with exponentials.
11514 The format should have %s twice for inserting mantissa
11515 and exponent, for example \"%s\\\\times10^{%s}\". This
11516 may also be a property list with column numbers and
11517 formats. :fmt will still be applied after :efmt.
11519 In addition to this, the parameters :skip and :skipcols are always handled
11520 directly by `orgtbl-send-table'. See manual."
11521 (interactive)
11522 (let* ((p params)
11523 (splicep (plist-get p :splice))
11524 (hline (plist-get p :hline))
11525 rtn line i fm efm lfmt h)
11527 ;; Do we have a header?
11528 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11529 (setq h t))
11531 ;; Put header
11532 (unless splicep
11533 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11535 ;; Now loop over all lines
11536 (while (setq line (pop table))
11537 (if (eq line 'hline)
11538 ;; A horizontal separator line
11539 (progn (if hline (push hline rtn))
11540 (setq h nil)) ; no longer in header
11541 ;; A normal line. Convert the fields, push line onto the result list
11542 (setq i 0)
11543 (setq line
11544 (mapcar
11545 (lambda (f)
11546 (setq i (1+ i)
11547 fm (org-get-param p h i :fmt :hfmt)
11548 efm (org-get-param p h i :efmt))
11549 (if (and efm (string-match orgtbl-exp-regexp f))
11550 (setq f (format
11551 efm (match-string 1 f) (match-string 2 f))))
11552 (if fm (setq f (format fm f)))
11554 line))
11555 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11556 (push (apply 'format lfmt line) rtn)
11557 (push (concat
11558 (org-get-param p h i :lstart :hlstart)
11559 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11560 (org-get-param p h i :lend :hlend))
11561 rtn))))
11563 (unless splicep
11564 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11566 (mapconcat 'identity (nreverse rtn) "\n")))
11568 (defun orgtbl-to-latex (table params)
11569 "Convert the orgtbl-mode TABLE to LaTeX.
11570 TABLE is a list, each entry either the symbol `hline' for a horizontal
11571 separator line, or a list of fields for that line.
11572 PARAMS is a property list of parameters that can influence the conversion.
11573 Supports all parameters from `orgtbl-to-generic'. Most important for
11574 LaTeX are:
11576 :splice When set to t, return only table body lines, don't wrap
11577 them into a tabular environment. Default is nil.
11579 :fmt A format to be used to wrap the field, should contain %s for the
11580 original field value. For example, to wrap everything in dollars,
11581 use :fmt \"$%s$\". This may also be a property list with column
11582 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11584 :efmt Format for transforming numbers with exponentials. The format
11585 should have %s twice for inserting mantissa and exponent, for
11586 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11587 This may also be a property list with column numbers and formats.
11589 The general parameters :skip and :skipcols have already been applied when
11590 this function is called."
11591 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11592 org-table-last-alignment ""))
11593 (params2
11594 (list
11595 :tstart (concat "\\begin{tabular}{" alignment "}")
11596 :tend "\\end{tabular}"
11597 :lstart "" :lend " \\\\" :sep " & "
11598 :efmt "%s\\,(%s)" :hline "\\hline")))
11599 (orgtbl-to-generic table (org-combine-plists params2 params))))
11601 (defun orgtbl-to-html (table params)
11602 "Convert the orgtbl-mode TABLE to LaTeX.
11603 TABLE is a list, each entry either the symbol `hline' for a horizontal
11604 separator line, or a list of fields for that line.
11605 PARAMS is a property list of parameters that can influence the conversion.
11606 Currently this function recognizes the following parameters:
11608 :splice When set to t, return only table body lines, don't wrap
11609 them into a <table> environment. Default is nil.
11611 The general parameters :skip and :skipcols have already been applied when
11612 this function is called. The function does *not* use `orgtbl-to-generic',
11613 so you cannot specify parameters for it."
11614 (let* ((splicep (plist-get params :splice))
11615 html)
11616 ;; Just call the formatter we already have
11617 ;; We need to make text lines for it, so put the fields back together.
11618 (setq html (org-format-org-table-html
11619 (mapcar
11620 (lambda (x)
11621 (if (eq x 'hline)
11622 "|----+----|"
11623 (concat "| " (mapconcat 'identity x " | ") " |")))
11624 table)
11625 splicep))
11626 (if (string-match "\n+\\'" html)
11627 (setq html (replace-match "" t t html)))
11628 html))
11630 (defun orgtbl-to-texinfo (table params)
11631 "Convert the orgtbl-mode TABLE to TeXInfo.
11632 TABLE is a list, each entry either the symbol `hline' for a horizontal
11633 separator line, or a list of fields for that line.
11634 PARAMS is a property list of parameters that can influence the conversion.
11635 Supports all parameters from `orgtbl-to-generic'. Most important for
11636 TeXInfo are:
11638 :splice nil/t When set to t, return only table body lines, don't wrap
11639 them into a multitable environment. Default is nil.
11641 :fmt fmt A format to be used to wrap the field, should contain
11642 %s for the original field value. For example, to wrap
11643 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11644 This may also be a property list with column numbers and
11645 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11647 :cf \"f1 f2..\" The column fractions for the table. Bye default these
11648 are computed automatically from the width of the columns
11649 under org-mode.
11651 The general parameters :skip and :skipcols have already been applied when
11652 this function is called."
11653 (let* ((total (float (apply '+ org-table-last-column-widths)))
11654 (colfrac (or (plist-get params :cf)
11655 (mapconcat
11656 (lambda (x) (format "%.3f" (/ (float x) total)))
11657 org-table-last-column-widths " ")))
11658 (params2
11659 (list
11660 :tstart (concat "@multitable @columnfractions " colfrac)
11661 :tend "@end multitable"
11662 :lstart "@item " :lend "" :sep " @tab "
11663 :hlstart "@headitem ")))
11664 (orgtbl-to-generic table (org-combine-plists params2 params))))
11666 ;;;; Link Stuff
11668 ;;; Link abbreviations
11670 (defun org-link-expand-abbrev (link)
11671 "Apply replacements as defined in `org-link-abbrev-alist."
11672 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11673 (let* ((key (match-string 1 link))
11674 (as (or (assoc key org-link-abbrev-alist-local)
11675 (assoc key org-link-abbrev-alist)))
11676 (tag (and (match-end 2) (match-string 3 link)))
11677 rpl)
11678 (if (not as)
11679 link
11680 (setq rpl (cdr as))
11681 (cond
11682 ((symbolp rpl) (funcall rpl tag))
11683 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11684 (t (concat rpl tag)))))
11685 link))
11687 ;;; Storing and inserting links
11689 (defvar org-insert-link-history nil
11690 "Minibuffer history for links inserted with `org-insert-link'.")
11692 (defvar org-stored-links nil
11693 "Contains the links stored with `org-store-link'.")
11695 (defvar org-store-link-plist nil
11696 "Plist with info about the most recently link created with `org-store-link'.")
11698 (defvar org-link-protocols nil
11699 "Link protocols added to Org-mode using `org-add-link-type'.")
11701 (defvar org-store-link-functions nil
11702 "List of functions that are called to create and store a link.
11703 Each function will be called in turn until one returns a non-nil
11704 value. Each function should check if it is responsible for creating
11705 this link (for example by looking at the major mode).
11706 If not, it must exit and return nil.
11707 If yes, it should return a non-nil value after a calling
11708 `org-store-link-props' with a list of properties and values.
11709 Special properties are:
11711 :type The link prefix. like \"http\". This must be given.
11712 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11713 This is obligatory as well.
11714 :description Optional default description for the second pair
11715 of brackets in an Org-mode link. The user can still change
11716 this when inserting this link into an Org-mode buffer.
11718 In addition to these, any additional properties can be specified
11719 and then used in remember templates.")
11721 (defun org-add-link-type (type &optional follow publish)
11722 "Add TYPE to the list of `org-link-types'.
11723 Re-compute all regular expressions depending on `org-link-types'
11724 FOLLOW and PUBLISH are two functions. Both take the link path as
11725 an argument.
11726 FOLLOW should do whatever is necessary to follow the link, for example
11727 to find a file or display a mail message.
11729 PUBLISH takes the path and retuns the string that should be used when
11730 this document is published. FIMXE: This is actually not yet implemented."
11731 (add-to-list 'org-link-types type t)
11732 (org-make-link-regexps)
11733 (add-to-list 'org-link-protocols
11734 (list type follow publish)))
11736 (defun org-add-agenda-custom-command (entry)
11737 "Replace or add a command in `org-agenda-custom-commands'.
11738 This is mostly for hacking and trying a new command - once the command
11739 works you probably want to add it to `org-agenda-custom-commands' for good."
11740 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11741 (if ass
11742 (setcdr ass (cdr entry))
11743 (push entry org-agenda-custom-commands))))
11745 ;;;###autoload
11746 (defun org-store-link (arg)
11747 "\\<org-mode-map>Store an org-link to the current location.
11748 This link can later be inserted into an org-buffer with
11749 \\[org-insert-link].
11750 For some link types, a prefix arg is interpreted:
11751 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11752 For file links, arg negates `org-context-in-file-links'."
11753 (interactive "P")
11754 (setq org-store-link-plist nil) ; reset
11755 (let (link cpltxt desc description search txt)
11756 (cond
11758 ((run-hook-with-args-until-success 'org-store-link-functions)
11759 (setq link (plist-get org-store-link-plist :link)
11760 desc (or (plist-get org-store-link-plist :description) link)))
11762 ((eq major-mode 'bbdb-mode)
11763 (let ((name (bbdb-record-name (bbdb-current-record)))
11764 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11765 (setq cpltxt (concat "bbdb:" (or name company))
11766 link (org-make-link cpltxt))
11767 (org-store-link-props :type "bbdb" :name name :company company)))
11769 ((eq major-mode 'Info-mode)
11770 (setq link (org-make-link "info:"
11771 (file-name-nondirectory Info-current-file)
11772 ":" Info-current-node))
11773 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11774 ":" Info-current-node))
11775 (org-store-link-props :type "info" :file Info-current-file
11776 :node Info-current-node))
11778 ((eq major-mode 'calendar-mode)
11779 (let ((cd (calendar-cursor-to-date)))
11780 (setq link
11781 (format-time-string
11782 (car org-time-stamp-formats)
11783 (apply 'encode-time
11784 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11785 nil nil nil))))
11786 (org-store-link-props :type "calendar" :date cd)))
11788 ((or (eq major-mode 'vm-summary-mode)
11789 (eq major-mode 'vm-presentation-mode))
11790 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11791 (vm-follow-summary-cursor)
11792 (save-excursion
11793 (vm-select-folder-buffer)
11794 (let* ((message (car vm-message-pointer))
11795 (folder buffer-file-name)
11796 (subject (vm-su-subject message))
11797 (to (vm-get-header-contents message "To"))
11798 (from (vm-get-header-contents message "From"))
11799 (message-id (vm-su-message-id message)))
11800 (org-store-link-props :type "vm" :from from :to to :subject subject
11801 :message-id message-id)
11802 (setq message-id (org-remove-angle-brackets message-id))
11803 (setq folder (abbreviate-file-name folder))
11804 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11805 folder)
11806 (setq folder (replace-match "" t t folder)))
11807 (setq cpltxt (org-email-link-description))
11808 (setq link (org-make-link "vm:" folder "#" message-id)))))
11810 ((eq major-mode 'wl-summary-mode)
11811 (let* ((msgnum (wl-summary-message-number))
11812 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11813 msgnum 'message-id))
11814 (wl-message-entity
11815 (if (fboundp 'elmo-message-entity)
11816 (elmo-message-entity
11817 wl-summary-buffer-elmo-folder msgnum)
11818 (elmo-msgdb-overview-get-entity
11819 msgnum (wl-summary-buffer-msgdb))))
11820 (from (wl-summary-line-from))
11821 (to (car (elmo-message-entity-field wl-message-entity 'to)))
11822 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11823 (wl-summary-line-subject))))
11824 (org-store-link-props :type "wl" :from from :to to
11825 :subject subject :message-id message-id)
11826 (setq message-id (org-remove-angle-brackets message-id))
11827 (setq cpltxt (org-email-link-description))
11828 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11829 "#" message-id))))
11831 ((or (equal major-mode 'mh-folder-mode)
11832 (equal major-mode 'mh-show-mode))
11833 (let ((from (org-mhe-get-header "From:"))
11834 (to (org-mhe-get-header "To:"))
11835 (message-id (org-mhe-get-header "Message-Id:"))
11836 (subject (org-mhe-get-header "Subject:")))
11837 (org-store-link-props :type "mh" :from from :to to
11838 :subject subject :message-id message-id)
11839 (setq cpltxt (org-email-link-description))
11840 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11841 (org-remove-angle-brackets message-id)))))
11843 ((eq major-mode 'rmail-mode)
11844 (save-excursion
11845 (save-restriction
11846 (rmail-narrow-to-non-pruned-header)
11847 (let ((folder buffer-file-name)
11848 (message-id (mail-fetch-field "message-id"))
11849 (from (mail-fetch-field "from"))
11850 (to (mail-fetch-field "to"))
11851 (subject (mail-fetch-field "subject")))
11852 (org-store-link-props
11853 :type "rmail" :from from :to to
11854 :subject subject :message-id message-id)
11855 (setq message-id (org-remove-angle-brackets message-id))
11856 (setq cpltxt (org-email-link-description))
11857 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11859 ((eq major-mode 'gnus-group-mode)
11860 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11861 (gnus-group-group-name)) ; version
11862 ((fboundp 'gnus-group-name)
11863 (gnus-group-name))
11864 (t "???"))))
11865 (unless group (error "Not on a group"))
11866 (org-store-link-props :type "gnus" :group group)
11867 (setq cpltxt (concat
11868 (if (org-xor arg org-usenet-links-prefer-google)
11869 "http://groups.google.com/groups?group="
11870 "gnus:")
11871 group)
11872 link (org-make-link cpltxt))))
11874 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11875 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11876 (let* ((group gnus-newsgroup-name)
11877 (article (gnus-summary-article-number))
11878 (header (gnus-summary-article-header article))
11879 (from (mail-header-from header))
11880 (message-id (mail-header-id header))
11881 (date (mail-header-date header))
11882 (subject (gnus-summary-subject-string)))
11883 (org-store-link-props :type "gnus" :from from :subject subject
11884 :message-id message-id :group group)
11885 (setq cpltxt (org-email-link-description))
11886 (if (org-xor arg org-usenet-links-prefer-google)
11887 (setq link
11888 (concat
11889 cpltxt "\n "
11890 (format "http://groups.google.com/groups?as_umsgid=%s"
11891 (org-fixup-message-id-for-http message-id))))
11892 (setq link (org-make-link "gnus:" group
11893 "#" (number-to-string article))))))
11895 ((eq major-mode 'w3-mode)
11896 (setq cpltxt (url-view-url t)
11897 link (org-make-link cpltxt))
11898 (org-store-link-props :type "w3" :url (url-view-url t)))
11900 ((eq major-mode 'w3m-mode)
11901 (setq cpltxt (or w3m-current-title w3m-current-url)
11902 link (org-make-link w3m-current-url))
11903 (org-store-link-props :type "w3m" :url (url-view-url t)))
11905 ((setq search (run-hook-with-args-until-success
11906 'org-create-file-search-functions))
11907 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11908 "::" search))
11909 (setq cpltxt (or description link)))
11911 ((eq major-mode 'image-mode)
11912 (setq cpltxt (concat "file:"
11913 (abbreviate-file-name buffer-file-name))
11914 link (org-make-link cpltxt))
11915 (org-store-link-props :type "image" :file buffer-file-name))
11917 ((eq major-mode 'dired-mode)
11918 ;; link to the file in the current line
11919 (setq cpltxt (concat "file:"
11920 (abbreviate-file-name
11921 (expand-file-name
11922 (dired-get-filename nil t))))
11923 link (org-make-link cpltxt)))
11925 ((and buffer-file-name (org-mode-p))
11926 ;; Just link to current headline
11927 (setq cpltxt (concat "file:"
11928 (abbreviate-file-name buffer-file-name)))
11929 ;; Add a context search string
11930 (when (org-xor org-context-in-file-links arg)
11931 ;; Check if we are on a target
11932 (if (org-in-regexp "<<\\(.*?\\)>>")
11933 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11934 (setq txt (cond
11935 ((org-on-heading-p) nil)
11936 ((org-region-active-p)
11937 (buffer-substring (region-beginning) (region-end)))
11938 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11939 (when (or (null txt) (string-match "\\S-" txt))
11940 (setq cpltxt
11941 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11942 desc "NONE"))))
11943 (if (string-match "::\\'" cpltxt)
11944 (setq cpltxt (substring cpltxt 0 -2)))
11945 (setq link (org-make-link cpltxt)))
11947 ((buffer-file-name (buffer-base-buffer))
11948 ;; Just link to this file here.
11949 (setq cpltxt (concat "file:"
11950 (abbreviate-file-name
11951 (buffer-file-name (buffer-base-buffer)))))
11952 ;; Add a context string
11953 (when (org-xor org-context-in-file-links arg)
11954 (setq txt (if (org-region-active-p)
11955 (buffer-substring (region-beginning) (region-end))
11956 (buffer-substring (point-at-bol) (point-at-eol))))
11957 ;; Only use search option if there is some text.
11958 (when (string-match "\\S-" txt)
11959 (setq cpltxt
11960 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11961 desc "NONE")))
11962 (setq link (org-make-link cpltxt)))
11964 ((interactive-p)
11965 (error "Cannot link to a buffer which is not visiting a file"))
11967 (t (setq link nil)))
11969 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11970 (setq link (or link cpltxt)
11971 desc (or desc cpltxt))
11972 (if (equal desc "NONE") (setq desc nil))
11974 (if (and (interactive-p) link)
11975 (progn
11976 (setq org-stored-links
11977 (cons (list link desc) org-stored-links))
11978 (message "Stored: %s" (or desc link)))
11979 (and link (org-make-link-string link desc)))))
11981 (defun org-store-link-props (&rest plist)
11982 "Store link properties, extract names and addresses."
11983 (let (x adr)
11984 (when (setq x (plist-get plist :from))
11985 (setq adr (mail-extract-address-components x))
11986 (plist-put plist :fromname (car adr))
11987 (plist-put plist :fromaddress (nth 1 adr)))
11988 (when (setq x (plist-get plist :to))
11989 (setq adr (mail-extract-address-components x))
11990 (plist-put plist :toname (car adr))
11991 (plist-put plist :toaddress (nth 1 adr))))
11992 (let ((from (plist-get plist :from))
11993 (to (plist-get plist :to)))
11994 (when (and from to org-from-is-user-regexp)
11995 (plist-put plist :fromto
11996 (if (string-match org-from-is-user-regexp from)
11997 (concat "to %t")
11998 (concat "from %f")))))
11999 (setq org-store-link-plist plist))
12001 (defun org-email-link-description (&optional fmt)
12002 "Return the description part of an email link.
12003 This takes information from `org-store-link-plist' and formats it
12004 according to FMT (default from `org-email-link-description-format')."
12005 (setq fmt (or fmt org-email-link-description-format))
12006 (let* ((p org-store-link-plist)
12007 (to (plist-get p :toaddress))
12008 (from (plist-get p :fromaddress))
12009 (table
12010 (list
12011 (cons "%c" (plist-get p :fromto))
12012 (cons "%F" (plist-get p :from))
12013 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12014 (cons "%T" (plist-get p :to))
12015 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12016 (cons "%s" (plist-get p :subject))
12017 (cons "%m" (plist-get p :message-id)))))
12018 (when (string-match "%c" fmt)
12019 ;; Check if the user wrote this message
12020 (if (and org-from-is-user-regexp from to
12021 (save-match-data (string-match org-from-is-user-regexp from)))
12022 (setq fmt (replace-match "to %t" t t fmt))
12023 (setq fmt (replace-match "from %f" t t fmt))))
12024 (org-replace-escapes fmt table)))
12026 (defun org-make-org-heading-search-string (&optional string heading)
12027 "Make search string for STRING or current headline."
12028 (interactive)
12029 (let ((s (or string (org-get-heading))))
12030 (unless (and string (not heading))
12031 ;; We are using a headline, clean up garbage in there.
12032 (if (string-match org-todo-regexp s)
12033 (setq s (replace-match "" t t s)))
12034 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12035 (setq s (replace-match "" t t s)))
12036 (setq s (org-trim s))
12037 (if (string-match (concat "^\\(" org-quote-string "\\|"
12038 org-comment-string "\\)") s)
12039 (setq s (replace-match "" t t s)))
12040 (while (string-match org-ts-regexp s)
12041 (setq s (replace-match "" t t s))))
12042 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12043 (setq s (replace-match " " t t s)))
12044 (or string (setq s (concat "*" s))) ; Add * for headlines
12045 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12047 (defun org-make-link (&rest strings)
12048 "Concatenate STRINGS."
12049 (apply 'concat strings))
12051 (defun org-make-link-string (link &optional description)
12052 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12053 (unless (string-match "\\S-" link)
12054 (error "Empty link"))
12055 (when (stringp description)
12056 ;; Remove brackets from the description, they are fatal.
12057 (while (string-match "\\[" description)
12058 (setq description (replace-match "{" t t description)))
12059 (while (string-match "\\]" description)
12060 (setq description (replace-match "}" t t description))))
12061 (when (equal (org-link-escape link) description)
12062 ;; No description needed, it is identical
12063 (setq description nil))
12064 (when (and (not description)
12065 (not (equal link (org-link-escape link))))
12066 (setq description link))
12067 (concat "[[" (org-link-escape link) "]"
12068 (if description (concat "[" description "]") "")
12069 "]"))
12071 (defconst org-link-escape-chars
12072 '((?\ . "%20")
12073 (?\[ . "%5B")
12074 (?\] . "%5D")
12075 (?\340 . "%E0") ; `a
12076 (?\342 . "%E2") ; ^a
12077 (?\347 . "%E7") ; ,c
12078 (?\350 . "%E8") ; `e
12079 (?\351 . "%E9") ; 'e
12080 (?\352 . "%EA") ; ^e
12081 (?\356 . "%EE") ; ^i
12082 (?\364 . "%F4") ; ^o
12083 (?\371 . "%F9") ; `u
12084 (?\373 . "%FB") ; ^u
12085 (?\; . "%3B")
12086 (?? . "%3F")
12087 (?= . "%3D")
12088 (?+ . "%2B")
12090 "Association list of escapes for some characters problematic in links.
12091 This is the list that is used for internal purposes.")
12093 (defconst org-link-escape-chars-browser
12094 '((?\ . "%20")) ; 32 for the SPC char
12095 "Association list of escapes for some characters problematic in links.
12096 This is the list that is used before handing over to the browser.")
12098 (defun org-link-escape (text &optional table)
12099 "Escape charaters in TEXT that are problematic for links."
12100 (setq table (or table org-link-escape-chars))
12101 (when text
12102 (let ((re (mapconcat (lambda (x) (regexp-quote
12103 (char-to-string (car x))))
12104 table "\\|")))
12105 (while (string-match re text)
12106 (setq text
12107 (replace-match
12108 (cdr (assoc (string-to-char (match-string 0 text))
12109 table))
12110 t t text)))
12111 text)))
12113 (defun org-link-unescape (text &optional table)
12114 "Reverse the action of `org-link-escape'."
12115 (setq table (or table org-link-escape-chars))
12116 (when text
12117 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12118 table "\\|")))
12119 (while (string-match re text)
12120 (setq text
12121 (replace-match
12122 (char-to-string (car (rassoc (match-string 0 text) table)))
12123 t t text)))
12124 text)))
12126 (defun org-xor (a b)
12127 "Exclusive or."
12128 (if a (not b) b))
12130 (defun org-get-header (header)
12131 "Find a header field in the current buffer."
12132 (save-excursion
12133 (goto-char (point-min))
12134 (let ((case-fold-search t) s)
12135 (cond
12136 ((eq header 'from)
12137 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12138 (setq s (match-string 1)))
12139 (while (string-match "\"" s)
12140 (setq s (replace-match "" t t s)))
12141 (if (string-match "[<(].*" s)
12142 (setq s (replace-match "" t t s))))
12143 ((eq header 'message-id)
12144 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12145 (setq s (match-string 1))))
12146 ((eq header 'subject)
12147 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12148 (setq s (match-string 1)))))
12149 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12150 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12151 s)))
12154 (defun org-fixup-message-id-for-http (s)
12155 "Replace special characters in a message id, so it can be used in an http query."
12156 (while (string-match "<" s)
12157 (setq s (replace-match "%3C" t t s)))
12158 (while (string-match ">" s)
12159 (setq s (replace-match "%3E" t t s)))
12160 (while (string-match "@" s)
12161 (setq s (replace-match "%40" t t s)))
12164 ;;;###autoload
12165 (defun org-insert-link-global ()
12166 "Insert a link like Org-mode does.
12167 This command can be called in any mode to insert a link in Org-mode syntax."
12168 (interactive)
12169 (org-run-like-in-org-mode 'org-insert-link))
12171 (defun org-insert-link (&optional complete-file)
12172 "Insert a link. At the prompt, enter the link.
12174 Completion can be used to select a link previously stored with
12175 `org-store-link'. When the empty string is entered (i.e. if you just
12176 press RET at the prompt), the link defaults to the most recently
12177 stored link. As SPC triggers completion in the minibuffer, you need to
12178 use M-SPC or C-q SPC to force the insertion of a space character.
12180 You will also be prompted for a description, and if one is given, it will
12181 be displayed in the buffer instead of the link.
12183 If there is already a link at point, this command will allow you to edit link
12184 and description parts.
12186 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12187 selected using completion. The path to the file will be relative to
12188 the current directory if the file is in the current directory or a
12189 subdirectory. Otherwise, the link will be the absolute path as
12190 completed in the minibuffer (i.e. normally ~/path/to/file).
12192 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12193 is in the current directory or below.
12194 With three \\[universal-argument] prefixes, negate the meaning of
12195 `org-keep-stored-link-after-insertion'."
12196 (interactive "P")
12197 (let* ((wcf (current-window-configuration))
12198 (region (if (org-region-active-p)
12199 (buffer-substring (region-beginning) (region-end))))
12200 (remove (and region (list (region-beginning) (region-end))))
12201 (desc region)
12202 tmphist ; byte-compile incorrectly complains about this
12203 link entry file)
12204 (cond
12205 ((org-in-regexp org-bracket-link-regexp 1)
12206 ;; We do have a link at point, and we are going to edit it.
12207 (setq remove (list (match-beginning 0) (match-end 0)))
12208 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12209 (setq link (read-string "Link: "
12210 (org-link-unescape
12211 (org-match-string-no-properties 1)))))
12212 ((or (org-in-regexp org-angle-link-re)
12213 (org-in-regexp org-plain-link-re))
12214 ;; Convert to bracket link
12215 (setq remove (list (match-beginning 0) (match-end 0))
12216 link (read-string "Link: "
12217 (org-remove-angle-brackets (match-string 0)))))
12218 ((equal complete-file '(4))
12219 ;; Completing read for file names.
12220 (setq file (read-file-name "File: "))
12221 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12222 (pwd1 (file-name-as-directory (abbreviate-file-name
12223 (expand-file-name ".")))))
12224 (cond
12225 ((equal complete-file '(16))
12226 (setq link (org-make-link
12227 "file:"
12228 (abbreviate-file-name (expand-file-name file)))))
12229 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12230 (setq link (org-make-link "file:" (match-string 1 file))))
12231 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12232 (expand-file-name file))
12233 (setq link (org-make-link
12234 "file:" (match-string 1 (expand-file-name file)))))
12235 (t (setq link (org-make-link "file:" file))))))
12237 ;; Read link, with completion for stored links.
12238 (with-output-to-temp-buffer "*Org Links*"
12239 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12240 (when org-stored-links
12241 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12242 (princ (mapconcat
12243 (lambda (x)
12244 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12245 (reverse org-stored-links) "\n"))))
12246 (let ((cw (selected-window)))
12247 (select-window (get-buffer-window "*Org Links*"))
12248 (shrink-window-if-larger-than-buffer)
12249 (setq truncate-lines t)
12250 (select-window cw))
12251 ;; Fake a link history, containing the stored links.
12252 (setq tmphist (append (mapcar 'car org-stored-links)
12253 org-insert-link-history))
12254 (unwind-protect
12255 (setq link (org-completing-read
12256 "Link: "
12257 (append
12258 (mapcar (lambda (x) (list (concat (car x) ":")))
12259 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12260 (mapcar (lambda (x) (list (concat x ":")))
12261 org-link-types))
12262 nil nil nil
12263 'tmphist
12264 (or (car (car org-stored-links)))))
12265 (set-window-configuration wcf)
12266 (kill-buffer "*Org Links*"))
12267 (setq entry (assoc link org-stored-links))
12268 (or entry (push link org-insert-link-history))
12269 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12270 (not org-keep-stored-link-after-insertion))
12271 (setq org-stored-links (delq (assoc link org-stored-links)
12272 org-stored-links)))
12273 (setq desc (or desc (nth 1 entry)))))
12275 (if (string-match org-plain-link-re link)
12276 ;; URL-like link, normalize the use of angular brackets.
12277 (setq link (org-make-link (org-remove-angle-brackets link))))
12279 ;; Check if we are linking to the current file with a search option
12280 ;; If yes, simplify the link by using only the search option.
12281 (when (and buffer-file-name
12282 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12283 (let* ((path (match-string 1 link))
12284 (case-fold-search nil)
12285 (search (match-string 2 link)))
12286 (save-match-data
12287 (if (equal (file-truename buffer-file-name) (file-truename path))
12288 ;; We are linking to this same file, with a search option
12289 (setq link search)))))
12291 ;; Check if we can/should use a relative path. If yes, simplify the link
12292 (when (string-match "\\<file:\\(.*\\)" link)
12293 (let* ((path (match-string 1 link))
12294 (origpath path)
12295 (desc-is-link (equal link desc))
12296 (case-fold-search nil))
12297 (cond
12298 ((eq org-link-file-path-type 'absolute)
12299 (setq path (abbreviate-file-name (expand-file-name path))))
12300 ((eq org-link-file-path-type 'noabbrev)
12301 (setq path (expand-file-name path)))
12302 ((eq org-link-file-path-type 'relative)
12303 (setq path (file-relative-name path)))
12305 (save-match-data
12306 (if (string-match (concat "^" (regexp-quote
12307 (file-name-as-directory
12308 (expand-file-name "."))))
12309 (expand-file-name path))
12310 ;; We are linking a file with relative path name.
12311 (setq path (substring (expand-file-name path)
12312 (match-end 0)))))))
12313 (setq link (concat "file:" path))
12314 (if (equal desc origpath)
12315 (setq desc path))))
12317 (setq desc (read-string "Description: " desc))
12318 (unless (string-match "\\S-" desc) (setq desc nil))
12319 (if remove (apply 'delete-region remove))
12320 (insert (org-make-link-string link desc))))
12322 (defun org-completing-read (&rest args)
12323 (let ((minibuffer-local-completion-map
12324 (copy-keymap minibuffer-local-completion-map)))
12325 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12326 (apply 'completing-read args)))
12328 ;;; Opening/following a link
12329 (defvar org-link-search-failed nil)
12331 (defun org-next-link ()
12332 "Move forward to the next link.
12333 If the link is in hidden text, expose it."
12334 (interactive)
12335 (when (and org-link-search-failed (eq this-command last-command))
12336 (goto-char (point-min))
12337 (message "Link search wrapped back to beginning of buffer"))
12338 (setq org-link-search-failed nil)
12339 (let* ((pos (point))
12340 (ct (org-context))
12341 (a (assoc :link ct)))
12342 (if a (goto-char (nth 2 a)))
12343 (if (re-search-forward org-any-link-re nil t)
12344 (progn
12345 (goto-char (match-beginning 0))
12346 (if (org-invisible-p) (org-show-context)))
12347 (goto-char pos)
12348 (setq org-link-search-failed t)
12349 (error "No further link found"))))
12351 (defun org-previous-link ()
12352 "Move backward to the previous link.
12353 If the link is in hidden text, expose it."
12354 (interactive)
12355 (when (and org-link-search-failed (eq this-command last-command))
12356 (goto-char (point-max))
12357 (message "Link search wrapped back to end of buffer"))
12358 (setq org-link-search-failed nil)
12359 (let* ((pos (point))
12360 (ct (org-context))
12361 (a (assoc :link ct)))
12362 (if a (goto-char (nth 1 a)))
12363 (if (re-search-backward org-any-link-re nil t)
12364 (progn
12365 (goto-char (match-beginning 0))
12366 (if (org-invisible-p) (org-show-context)))
12367 (goto-char pos)
12368 (setq org-link-search-failed t)
12369 (error "No further link found"))))
12371 (defun org-find-file-at-mouse (ev)
12372 "Open file link or URL at mouse."
12373 (interactive "e")
12374 (mouse-set-point ev)
12375 (org-open-at-point 'in-emacs))
12377 (defun org-open-at-mouse (ev)
12378 "Open file link or URL at mouse."
12379 (interactive "e")
12380 (mouse-set-point ev)
12381 (org-open-at-point))
12383 (defvar org-window-config-before-follow-link nil
12384 "The window configuration before following a link.
12385 This is saved in case the need arises to restore it.")
12387 (defvar org-open-link-marker (make-marker)
12388 "Marker pointing to the location where `org-open-at-point; was called.")
12390 ;;;###autoload
12391 (defun org-open-at-point-global ()
12392 "Follow a link like Org-mode does.
12393 This command can be called in any mode to follow a link that has
12394 Org-mode syntax."
12395 (interactive)
12396 (org-run-like-in-org-mode 'org-open-at-point))
12398 (defun org-open-at-point (&optional in-emacs)
12399 "Open link at or after point.
12400 If there is no link at point, this function will search forward up to
12401 the end of the current subtree.
12402 Normally, files will be opened by an appropriate application. If the
12403 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12404 (interactive "P")
12405 (catch 'abort
12406 (move-marker org-open-link-marker (point))
12407 (setq org-window-config-before-follow-link (current-window-configuration))
12408 (org-remove-occur-highlights nil nil t)
12409 (if (org-at-timestamp-p t)
12410 (org-follow-timestamp-link)
12411 (let (type path link line search (pos (point)))
12412 (catch 'match
12413 (save-excursion
12414 (skip-chars-forward "^]\n\r")
12415 (when (org-in-regexp org-bracket-link-regexp)
12416 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12417 (while (string-match " *\n *" link)
12418 (setq link (replace-match " " t t link)))
12419 (setq link (org-link-expand-abbrev link))
12420 (if (string-match org-link-re-with-space2 link)
12421 (setq type (match-string 1 link) path (match-string 2 link))
12422 (setq type "thisfile" path link))
12423 (throw 'match t)))
12425 (when (get-text-property (point) 'org-linked-text)
12426 (setq type "thisfile"
12427 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12428 (1+ (point)) (point))
12429 path (buffer-substring
12430 (previous-single-property-change pos 'org-linked-text)
12431 (next-single-property-change pos 'org-linked-text)))
12432 (throw 'match t))
12434 (save-excursion
12435 (when (or (org-in-regexp org-angle-link-re)
12436 (org-in-regexp org-plain-link-re))
12437 (setq type (match-string 1) path (match-string 2))
12438 (throw 'match t)))
12439 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12440 (setq type "tree-match"
12441 path (match-string 1))
12442 (throw 'match t))
12443 (save-excursion
12444 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12445 (setq type "tags"
12446 path (match-string 1))
12447 (while (string-match ":" path)
12448 (setq path (replace-match "+" t t path)))
12449 (throw 'match t))))
12450 (unless path
12451 (error "No link found"))
12452 ;; Remove any trailing spaces in path
12453 (if (string-match " +\\'" path)
12454 (setq path (replace-match "" t t path)))
12456 (cond
12458 ((assoc type org-link-protocols)
12459 (funcall (nth 1 (assoc type org-link-protocols)) path))
12461 ((equal type "mailto")
12462 (let ((cmd (car org-link-mailto-program))
12463 (args (cdr org-link-mailto-program)) args1
12464 (address path) (subject "") a)
12465 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12466 (setq address (match-string 1 path)
12467 subject (org-link-escape (match-string 2 path))))
12468 (while args
12469 (cond
12470 ((not (stringp (car args))) (push (pop args) args1))
12471 (t (setq a (pop args))
12472 (if (string-match "%a" a)
12473 (setq a (replace-match address t t a)))
12474 (if (string-match "%s" a)
12475 (setq a (replace-match subject t t a)))
12476 (push a args1))))
12477 (apply cmd (nreverse args1))))
12479 ((member type '("http" "https" "ftp" "news"))
12480 (browse-url (concat type ":" (org-link-escape
12481 path org-link-escape-chars-browser))))
12483 ((string= type "tags")
12484 (org-tags-view in-emacs path))
12485 ((string= type "thisfile")
12486 (if in-emacs
12487 (switch-to-buffer-other-window
12488 (org-get-buffer-for-internal-link (current-buffer)))
12489 (org-mark-ring-push))
12490 (let ((cmd `(org-link-search
12491 ,path
12492 ,(cond ((equal in-emacs '(4)) 'occur)
12493 ((equal in-emacs '(16)) 'org-occur)
12494 (t nil))
12495 ,pos)))
12496 (condition-case nil (eval cmd)
12497 (error (progn (widen) (eval cmd))))))
12499 ((string= type "tree-match")
12500 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12502 ((string= type "file")
12503 (if (string-match "::\\([0-9]+\\)\\'" path)
12504 (setq line (string-to-number (match-string 1 path))
12505 path (substring path 0 (match-beginning 0)))
12506 (if (string-match "::\\(.+\\)\\'" path)
12507 (setq search (match-string 1 path)
12508 path (substring path 0 (match-beginning 0)))))
12509 (if (string-match "[*?{]" (file-name-nondirectory path))
12510 (dired path)
12511 (org-open-file path in-emacs line search)))
12513 ((string= type "news")
12514 (org-follow-gnus-link path))
12516 ((string= type "bbdb")
12517 (org-follow-bbdb-link path))
12519 ((string= type "info")
12520 (org-follow-info-link path))
12522 ((string= type "gnus")
12523 (let (group article)
12524 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12525 (error "Error in Gnus link"))
12526 (setq group (match-string 1 path)
12527 article (match-string 3 path))
12528 (org-follow-gnus-link group article)))
12530 ((string= type "vm")
12531 (let (folder article)
12532 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12533 (error "Error in VM link"))
12534 (setq folder (match-string 1 path)
12535 article (match-string 3 path))
12536 ;; in-emacs is the prefix arg, will be interpreted as read-only
12537 (org-follow-vm-link folder article in-emacs)))
12539 ((string= type "wl")
12540 (let (folder article)
12541 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12542 (error "Error in Wanderlust link"))
12543 (setq folder (match-string 1 path)
12544 article (match-string 3 path))
12545 (org-follow-wl-link folder article)))
12547 ((string= type "mhe")
12548 (let (folder article)
12549 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12550 (error "Error in MHE link"))
12551 (setq folder (match-string 1 path)
12552 article (match-string 3 path))
12553 (org-follow-mhe-link folder article)))
12555 ((string= type "rmail")
12556 (let (folder article)
12557 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12558 (error "Error in RMAIL link"))
12559 (setq folder (match-string 1 path)
12560 article (match-string 3 path))
12561 (org-follow-rmail-link folder article)))
12563 ((string= type "shell")
12564 (let ((cmd path))
12565 (if (or (not org-confirm-shell-link-function)
12566 (funcall org-confirm-shell-link-function
12567 (format "Execute \"%s\" in shell? "
12568 (org-add-props cmd nil
12569 'face 'org-warning))))
12570 (progn
12571 (message "Executing %s" cmd)
12572 (shell-command cmd))
12573 (error "Abort"))))
12575 ((string= type "elisp")
12576 (let ((cmd path))
12577 (if (or (not org-confirm-elisp-link-function)
12578 (funcall org-confirm-elisp-link-function
12579 (format "Execute \"%s\" as elisp? "
12580 (org-add-props cmd nil
12581 'face 'org-warning))))
12582 (message "%s => %s" cmd (eval (read cmd)))
12583 (error "Abort"))))
12586 (browse-url-at-point)))))
12587 (move-marker org-open-link-marker nil)))
12589 ;;; File search
12591 (defvar org-create-file-search-functions nil
12592 "List of functions to construct the right search string for a file link.
12593 These functions are called in turn with point at the location to
12594 which the link should point.
12596 A function in the hook should first test if it would like to
12597 handle this file type, for example by checking the major-mode or
12598 the file extension. If it decides not to handle this file, it
12599 should just return nil to give other functions a chance. If it
12600 does handle the file, it must return the search string to be used
12601 when following the link. The search string will be part of the
12602 file link, given after a double colon, and `org-open-at-point'
12603 will automatically search for it. If special measures must be
12604 taken to make the search successful, another function should be
12605 added to the companion hook `org-execute-file-search-functions',
12606 which see.
12608 A function in this hook may also use `setq' to set the variable
12609 `description' to provide a suggestion for the descriptive text to
12610 be used for this link when it gets inserted into an Org-mode
12611 buffer with \\[org-insert-link].")
12613 (defvar org-execute-file-search-functions nil
12614 "List of functions to execute a file search triggered by a link.
12616 Functions added to this hook must accept a single argument, the
12617 search string that was part of the file link, the part after the
12618 double colon. The function must first check if it would like to
12619 handle this search, for example by checking the major-mode or the
12620 file extension. If it decides not to handle this search, it
12621 should just return nil to give other functions a chance. If it
12622 does handle the search, it must return a non-nil value to keep
12623 other functions from trying.
12625 Each function can access the current prefix argument through the
12626 variable `current-prefix-argument'. Note that a single prefix is
12627 used to force opening a link in Emacs, so it may be good to only
12628 use a numeric or double prefix to guide the search function.
12630 In case this is needed, a function in this hook can also restore
12631 the window configuration before `org-open-at-point' was called using:
12633 (set-window-configuration org-window-config-before-follow-link)")
12635 (defun org-link-search (s &optional type avoid-pos)
12636 "Search for a link search option.
12637 If S is surrounded by forward slashes, it is interpreted as a
12638 regular expression. In org-mode files, this will create an `org-occur'
12639 sparse tree. In ordinary files, `occur' will be used to list matches.
12640 If the current buffer is in `dired-mode', grep will be used to search
12641 in all files. If AVOID-POS is given, ignore matches near that position."
12642 (let ((case-fold-search t)
12643 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12644 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12645 (append '(("") (" ") ("\t") ("\n"))
12646 org-emphasis-alist)
12647 "\\|") "\\)"))
12648 (pos (point))
12649 (pre "") (post "")
12650 words re0 re1 re2 re3 re4 re5 re2a reall)
12651 (cond
12652 ;; First check if there are any special
12653 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12654 ;; Now try the builtin stuff
12655 ((save-excursion
12656 (goto-char (point-min))
12657 (and
12658 (re-search-forward
12659 (concat "<<" (regexp-quote s0) ">>") nil t)
12660 (setq pos (match-beginning 0))))
12661 ;; There is an exact target for this
12662 (goto-char pos))
12663 ((string-match "^/\\(.*\\)/$" s)
12664 ;; A regular expression
12665 (cond
12666 ((org-mode-p)
12667 (org-occur (match-string 1 s)))
12668 ;;((eq major-mode 'dired-mode)
12669 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12670 (t (org-do-occur (match-string 1 s)))))
12672 ;; A normal search strings
12673 (when (equal (string-to-char s) ?*)
12674 ;; Anchor on headlines, post may include tags.
12675 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12676 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12677 s (substring s 1)))
12678 (remove-text-properties
12679 0 (length s)
12680 '(face nil mouse-face nil keymap nil fontified nil) s)
12681 ;; Make a series of regular expressions to find a match
12682 (setq words (org-split-string s "[ \n\r\t]+")
12683 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12684 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12685 "\\)" markers)
12686 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12687 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12688 re1 (concat pre re2 post)
12689 re3 (concat pre re4 post)
12690 re5 (concat pre ".*" re4)
12691 re2 (concat pre re2)
12692 re2a (concat pre re2a)
12693 re4 (concat pre re4)
12694 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12695 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12696 re5 "\\)"
12698 (cond
12699 ((eq type 'org-occur) (org-occur reall))
12700 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12701 (t (goto-char (point-min))
12702 (if (or (org-search-not-self 1 re0 nil t)
12703 (org-search-not-self 1 re1 nil t)
12704 (org-search-not-self 1 re2 nil t)
12705 (org-search-not-self 1 re2a nil t)
12706 (org-search-not-self 1 re3 nil t)
12707 (org-search-not-self 1 re4 nil t)
12708 (org-search-not-self 1 re5 nil t)
12710 (goto-char (match-beginning 1))
12711 (goto-char pos)
12712 (error "No match")))))
12714 ;; Normal string-search
12715 (goto-char (point-min))
12716 (if (search-forward s nil t)
12717 (goto-char (match-beginning 0))
12718 (error "No match"))))
12719 (and (org-mode-p) (org-show-context 'link-search))))
12721 (defun org-search-not-self (group &rest args)
12722 "Execute `re-search-forward', but only accept matches that do not
12723 enclose the position of `org-open-link-marker'."
12724 (let ((m org-open-link-marker))
12725 (catch 'exit
12726 (while (apply 're-search-forward args)
12727 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12728 (goto-char (match-end group))
12729 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12730 (> (match-beginning 0) (marker-position m))
12731 (< (match-end 0) (marker-position m)))
12732 (save-match-data
12733 (or (not (org-in-regexp
12734 org-bracket-link-analytic-regexp 1))
12735 (not (match-end 4)) ; no description
12736 (and (<= (match-beginning 4) (point))
12737 (>= (match-end 4) (point))))))
12738 (throw 'exit (point))))))))
12740 (defun org-get-buffer-for-internal-link (buffer)
12741 "Return a buffer to be used for displaying the link target of internal links."
12742 (cond
12743 ((not org-display-internal-link-with-indirect-buffer)
12744 buffer)
12745 ((string-match "(Clone)$" (buffer-name buffer))
12746 (message "Buffer is already a clone, not making another one")
12747 ;; we also do not modify visibility in this case
12748 buffer)
12749 (t ; make a new indirect buffer for displaying the link
12750 (let* ((bn (buffer-name buffer))
12751 (ibn (concat bn "(Clone)"))
12752 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12753 (with-current-buffer ib (org-overview))
12754 ib))))
12756 (defun org-do-occur (regexp &optional cleanup)
12757 "Call the Emacs command `occur'.
12758 If CLEANUP is non-nil, remove the printout of the regular expression
12759 in the *Occur* buffer. This is useful if the regex is long and not useful
12760 to read."
12761 (occur regexp)
12762 (when cleanup
12763 (let ((cwin (selected-window)) win beg end)
12764 (when (setq win (get-buffer-window "*Occur*"))
12765 (select-window win))
12766 (goto-char (point-min))
12767 (when (re-search-forward "match[a-z]+" nil t)
12768 (setq beg (match-end 0))
12769 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12770 (setq end (1- (match-beginning 0)))))
12771 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12772 (goto-char (point-min))
12773 (select-window cwin))))
12775 ;;; The mark ring for links jumps
12777 (defvar org-mark-ring nil
12778 "Mark ring for positions before jumps in Org-mode.")
12779 (defvar org-mark-ring-last-goto nil
12780 "Last position in the mark ring used to go back.")
12781 ;; Fill and close the ring
12782 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12783 (loop for i from 1 to org-mark-ring-length do
12784 (push (make-marker) org-mark-ring))
12785 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12786 org-mark-ring)
12788 (defun org-mark-ring-push (&optional pos buffer)
12789 "Put the current position or POS into the mark ring and rotate it."
12790 (interactive)
12791 (setq pos (or pos (point)))
12792 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12793 (move-marker (car org-mark-ring)
12794 (or pos (point))
12795 (or buffer (current-buffer)))
12796 (message "%s"
12797 (substitute-command-keys
12798 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12800 (defun org-mark-ring-goto (&optional n)
12801 "Jump to the previous position in the mark ring.
12802 With prefix arg N, jump back that many stored positions. When
12803 called several times in succession, walk through the entire ring.
12804 Org-mode commands jumping to a different position in the current file,
12805 or to another Org-mode file, automatically push the old position
12806 onto the ring."
12807 (interactive "p")
12808 (let (p m)
12809 (if (eq last-command this-command)
12810 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12811 (setq p org-mark-ring))
12812 (setq org-mark-ring-last-goto p)
12813 (setq m (car p))
12814 (switch-to-buffer (marker-buffer m))
12815 (goto-char m)
12816 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12818 (defun org-remove-angle-brackets (s)
12819 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12820 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12822 (defun org-add-angle-brackets (s)
12823 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12824 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12827 ;;; Following specific links
12829 (defun org-follow-timestamp-link ()
12830 (cond
12831 ((org-at-date-range-p t)
12832 (let ((org-agenda-start-on-weekday)
12833 (t1 (match-string 1))
12834 (t2 (match-string 2)))
12835 (setq t1 (time-to-days (org-time-string-to-time t1))
12836 t2 (time-to-days (org-time-string-to-time t2)))
12837 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12838 ((org-at-timestamp-p t)
12839 (org-agenda-list nil (time-to-days (org-time-string-to-time
12840 (substring (match-string 1) 0 10)))
12842 (t (error "This should not happen"))))
12845 (defun org-follow-bbdb-link (name)
12846 "Follow a BBDB link to NAME."
12847 (require 'bbdb)
12848 (let ((inhibit-redisplay (not debug-on-error))
12849 (bbdb-electric-p nil))
12850 (catch 'exit
12851 ;; Exact match on name
12852 (bbdb-name (concat "\\`" name "\\'") nil)
12853 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12854 ;; Exact match on name
12855 (bbdb-company (concat "\\`" name "\\'") nil)
12856 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12857 ;; Partial match on name
12858 (bbdb-name name nil)
12859 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12860 ;; Partial match on company
12861 (bbdb-company name nil)
12862 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12863 ;; General match including network address and notes
12864 (bbdb name nil)
12865 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12866 (delete-window (get-buffer-window "*BBDB*"))
12867 (error "No matching BBDB record")))))
12869 (defun org-follow-info-link (name)
12870 "Follow an info file & node link to NAME."
12871 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12872 (string-match "\\(.*\\)" name))
12873 (progn
12874 (require 'info)
12875 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12876 (Info-find-node (match-string 1 name) (match-string 2 name))
12877 (Info-find-node (match-string 1 name) "Top")))
12878 (message "Could not open: %s" name)))
12880 (defun org-follow-gnus-link (&optional group article)
12881 "Follow a Gnus link to GROUP and ARTICLE."
12882 (require 'gnus)
12883 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12884 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12885 (cond ((and group article)
12886 (gnus-group-read-group 1 nil group)
12887 (gnus-summary-goto-article (string-to-number article) nil t))
12888 (group (gnus-group-jump-to-group group))))
12890 (defun org-follow-vm-link (&optional folder article readonly)
12891 "Follow a VM link to FOLDER and ARTICLE."
12892 (require 'vm)
12893 (setq article (org-add-angle-brackets article))
12894 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12895 ;; ange-ftp or efs or tramp access
12896 (let ((user (or (match-string 1 folder) (user-login-name)))
12897 (host (match-string 2 folder))
12898 (file (match-string 3 folder)))
12899 (cond
12900 ((featurep 'tramp)
12901 ;; use tramp to access the file
12902 (if (featurep 'xemacs)
12903 (setq folder (format "[%s@%s]%s" user host file))
12904 (setq folder (format "/%s@%s:%s" user host file))))
12906 ;; use ange-ftp or efs
12907 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12908 (setq folder (format "/%s@%s:%s" user host file))))))
12909 (when folder
12910 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12911 (sit-for 0.1)
12912 (when article
12913 (vm-select-folder-buffer)
12914 (widen)
12915 (let ((case-fold-search t))
12916 (goto-char (point-min))
12917 (if (not (re-search-forward
12918 (concat "^" "message-id: *" (regexp-quote article))))
12919 (error "Could not find the specified message in this folder"))
12920 (vm-isearch-update)
12921 (vm-isearch-narrow)
12922 (vm-beginning-of-message)
12923 (vm-summarize)))))
12925 (defun org-follow-wl-link (folder article)
12926 "Follow a Wanderlust link to FOLDER and ARTICLE."
12927 (if (and (string= folder "%")
12928 article
12929 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12930 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12931 ;; Thus, we recompose folder and article ids.
12932 (setq folder (format "%s#%s" folder (match-string 1 article))
12933 article (match-string 3 article)))
12934 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12935 (error "No such folder: %s" folder))
12936 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12937 (and article
12938 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12939 (wl-summary-redisplay)))
12941 (defun org-follow-rmail-link (folder article)
12942 "Follow an RMAIL link to FOLDER and ARTICLE."
12943 (setq article (org-add-angle-brackets article))
12944 (let (message-number)
12945 (save-excursion
12946 (save-window-excursion
12947 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12948 (setq message-number
12949 (save-restriction
12950 (widen)
12951 (goto-char (point-max))
12952 (if (re-search-backward
12953 (concat "^Message-ID:\\s-+" (regexp-quote
12954 (or article "")))
12955 nil t)
12956 (rmail-what-message))))))
12957 (if message-number
12958 (progn
12959 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12960 (rmail-show-message message-number)
12961 message-number)
12962 (error "Message not found"))))
12964 ;;; mh-e integration based on planner-mode
12965 (defun org-mhe-get-message-real-folder ()
12966 "Return the name of the current message real folder, so if you use
12967 sequences, it will now work."
12968 (save-excursion
12969 (let* ((folder
12970 (if (equal major-mode 'mh-folder-mode)
12971 mh-current-folder
12972 ;; Refer to the show buffer
12973 mh-show-folder-buffer))
12974 (end-index
12975 (if (boundp 'mh-index-folder)
12976 (min (length mh-index-folder) (length folder))))
12978 ;; a simple test on mh-index-data does not work, because
12979 ;; mh-index-data is always nil in a show buffer.
12980 (if (and (boundp 'mh-index-folder)
12981 (string= mh-index-folder (substring folder 0 end-index)))
12982 (if (equal major-mode 'mh-show-mode)
12983 (save-window-excursion
12984 (let (pop-up-frames)
12985 (when (buffer-live-p (get-buffer folder))
12986 (progn
12987 (pop-to-buffer folder)
12988 (org-mhe-get-message-folder-from-index)
12991 (org-mhe-get-message-folder-from-index)
12993 folder
12997 (defun org-mhe-get-message-folder-from-index ()
12998 "Returns the name of the message folder in a index folder buffer."
12999 (save-excursion
13000 (mh-index-previous-folder)
13001 (re-search-forward "^\\(+.*\\)$" nil t)
13002 (message "%s" (match-string 1))))
13004 (defun org-mhe-get-message-folder ()
13005 "Return the name of the current message folder. Be careful if you
13006 use sequences."
13007 (save-excursion
13008 (if (equal major-mode 'mh-folder-mode)
13009 mh-current-folder
13010 ;; Refer to the show buffer
13011 mh-show-folder-buffer)))
13013 (defun org-mhe-get-message-num ()
13014 "Return the number of the current message. Be careful if you
13015 use sequences."
13016 (save-excursion
13017 (if (equal major-mode 'mh-folder-mode)
13018 (mh-get-msg-num nil)
13019 ;; Refer to the show buffer
13020 (mh-show-buffer-message-number))))
13022 (defun org-mhe-get-header (header)
13023 "Return a header of the message in folder mode. This will create a
13024 show buffer for the corresponding message. If you have a more clever
13025 idea..."
13026 (let* ((folder (org-mhe-get-message-folder))
13027 (num (org-mhe-get-message-num))
13028 (buffer (get-buffer-create (concat "show-" folder)))
13029 (header-field))
13030 (with-current-buffer buffer
13031 (mh-display-msg num folder)
13032 (if (equal major-mode 'mh-folder-mode)
13033 (mh-header-display)
13034 (mh-show-header-display))
13035 (set-buffer buffer)
13036 (setq header-field (mh-get-header-field header))
13037 (if (equal major-mode 'mh-folder-mode)
13038 (mh-show)
13039 (mh-show-show))
13040 header-field)))
13042 (defun org-follow-mhe-link (folder article)
13043 "Follow an MHE link to FOLDER and ARTICLE.
13044 If ARTICLE is nil FOLDER is shown. If the configuration variable
13045 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13046 ARTICLE is searched in all folders. Indexed searches (swish++,
13047 namazu, and others supported by MH-E) will always search in all
13048 folders."
13049 (require 'mh-e)
13050 (require 'mh-search)
13051 (require 'mh-utils)
13052 (mh-find-path)
13053 (if (not article)
13054 (mh-visit-folder (mh-normalize-folder-name folder))
13055 (setq article (org-add-angle-brackets article))
13056 (mh-search-choose)
13057 (if (equal mh-searcher 'pick)
13058 (progn
13059 (mh-search folder (list "--message-id" article))
13060 (when (and org-mhe-search-all-folders
13061 (not (org-mhe-get-message-real-folder)))
13062 (kill-this-buffer)
13063 (mh-search "+" (list "--message-id" article))))
13064 (mh-search "+" article))
13065 (if (org-mhe-get-message-real-folder)
13066 (mh-show-msg 1)
13067 (kill-this-buffer)
13068 (error "Message not found"))))
13070 ;;; BibTeX links
13072 ;; Use the custom search meachnism to construct and use search strings for
13073 ;; file links to BibTeX database entries.
13075 (defun org-create-file-search-in-bibtex ()
13076 "Create the search string and description for a BibTeX database entry."
13077 (when (eq major-mode 'bibtex-mode)
13078 ;; yes, we want to construct this search string.
13079 ;; Make a good description for this entry, using names, year and the title
13080 ;; Put it into the `description' variable which is dynamically scoped.
13081 (let ((bibtex-autokey-names 1)
13082 (bibtex-autokey-names-stretch 1)
13083 (bibtex-autokey-name-case-convert-function 'identity)
13084 (bibtex-autokey-name-separator " & ")
13085 (bibtex-autokey-additional-names " et al.")
13086 (bibtex-autokey-year-length 4)
13087 (bibtex-autokey-name-year-separator " ")
13088 (bibtex-autokey-titlewords 3)
13089 (bibtex-autokey-titleword-separator " ")
13090 (bibtex-autokey-titleword-case-convert-function 'identity)
13091 (bibtex-autokey-titleword-length 'infty)
13092 (bibtex-autokey-year-title-separator ": "))
13093 (setq description (bibtex-generate-autokey)))
13094 ;; Now parse the entry, get the key and return it.
13095 (save-excursion
13096 (bibtex-beginning-of-entry)
13097 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13099 (defun org-execute-file-search-in-bibtex (s)
13100 "Find the link search string S as a key for a database entry."
13101 (when (eq major-mode 'bibtex-mode)
13102 ;; Yes, we want to do the search in this file.
13103 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13104 (goto-char (point-min))
13105 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13106 (regexp-quote s) "[ \t\n]*,") nil t)
13107 (goto-char (match-beginning 0)))
13108 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13109 ;; Use double prefix to indicate that any web link should be browsed
13110 (let ((b (current-buffer)) (p (point)))
13111 ;; Restore the window configuration because we just use the web link
13112 (set-window-configuration org-window-config-before-follow-link)
13113 (save-excursion (set-buffer b) (goto-char p)
13114 (bibtex-url)))
13115 (recenter 0)) ; Move entry start to beginning of window
13116 ;; return t to indicate that the search is done.
13119 ;; Finally add the functions to the right hooks.
13120 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13121 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13123 ;; end of Bibtex link setup
13125 ;;; Following file links
13127 (defun org-open-file (path &optional in-emacs line search)
13128 "Open the file at PATH.
13129 First, this expands any special file name abbreviations. Then the
13130 configuration variable `org-file-apps' is checked if it contains an
13131 entry for this file type, and if yes, the corresponding command is launched.
13132 If no application is found, Emacs simply visits the file.
13133 With optional argument IN-EMACS, Emacs will visit the file.
13134 Optional LINE specifies a line to go to, optional SEARCH a string to
13135 search for. If LINE or SEARCH is given, the file will always be
13136 opened in Emacs.
13137 If the file does not exist, an error is thrown."
13138 (setq in-emacs (or in-emacs line search))
13139 (let* ((file (if (equal path "")
13140 buffer-file-name
13141 (substitute-in-file-name (expand-file-name path))))
13142 (apps (append org-file-apps (org-default-apps)))
13143 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13144 (dirp (if remp nil (file-directory-p file)))
13145 (dfile (downcase file))
13146 (old-buffer (current-buffer))
13147 (old-pos (point))
13148 (old-mode major-mode)
13149 ext cmd)
13150 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13151 (setq ext (match-string 1 dfile))
13152 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13153 (setq ext (match-string 1 dfile))))
13154 (if in-emacs
13155 (setq cmd 'emacs)
13156 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13157 (and dirp (cdr (assoc 'directory apps)))
13158 (cdr (assoc ext apps))
13159 (cdr (assoc t apps)))))
13160 (when (eq cmd 'mailcap)
13161 (require 'mailcap)
13162 (mailcap-parse-mailcaps)
13163 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13164 (command (mailcap-mime-info mime-type)))
13165 (if (stringp command)
13166 (setq cmd command)
13167 (setq cmd 'emacs))))
13168 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13169 (not (file-exists-p file))
13170 (not org-open-non-existing-files))
13171 (error "No such file: %s" file))
13172 (cond
13173 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13174 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13175 (while (string-match "['\"]%s['\"]" cmd)
13176 (setq cmd (replace-match "%s" t t cmd)))
13177 (while (string-match "%s" cmd)
13178 (setq cmd (replace-match (shell-quote-argument file) t t cmd)))
13179 (save-window-excursion
13180 (start-process-shell-command cmd nil cmd)))
13181 ((or (stringp cmd)
13182 (eq cmd 'emacs))
13183 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13184 (widen)
13185 (if line (goto-line line)
13186 (if search (org-link-search search))))
13187 ((consp cmd)
13188 (eval cmd))
13189 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13190 (and (org-mode-p) (eq old-mode 'org-mode)
13191 (or (not (equal old-buffer (current-buffer)))
13192 (not (equal old-pos (point))))
13193 (org-mark-ring-push old-pos old-buffer))))
13195 (defun org-default-apps ()
13196 "Return the default applications for this operating system."
13197 (cond
13198 ((eq system-type 'darwin)
13199 org-file-apps-defaults-macosx)
13200 ((eq system-type 'windows-nt)
13201 org-file-apps-defaults-windowsnt)
13202 (t org-file-apps-defaults-gnu)))
13204 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13205 (defun org-file-remote-p (file)
13206 "Test whether FILE specifies a location on a remote system.
13207 Return non-nil if the location is indeed remote.
13209 For example, the filename \"/user@host:/foo\" specifies a location
13210 on the system \"/user@host:\"."
13211 (cond ((fboundp 'file-remote-p)
13212 (file-remote-p file))
13213 ((fboundp 'tramp-handle-file-remote-p)
13214 (tramp-handle-file-remote-p file))
13215 ((and (boundp 'ange-ftp-name-format)
13216 (string-match (car ange-ftp-name-format) file))
13218 (t nil)))
13221 ;;;; Hooks for remember.el, and refiling
13223 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13224 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13226 ;;;###autoload
13227 (defun org-remember-insinuate ()
13228 "Setup remember.el for use wiht Org-mode."
13229 (require 'remember)
13230 (setq remember-annotation-functions '(org-remember-annotation))
13231 (setq remember-handler-functions '(org-remember-handler))
13232 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13234 ;;;###autoload
13235 (defun org-remember-annotation ()
13236 "Return a link to the current location as an annotation for remember.el.
13237 If you are using Org-mode files as target for data storage with
13238 remember.el, then the annotations should include a link compatible with the
13239 conventions in Org-mode. This function returns such a link."
13240 (org-store-link nil))
13242 (defconst org-remember-help
13243 "Select a destination location for the note.
13244 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13245 RET on headline -> Store as sublevel entry to current headline
13246 RET at beg-of-buf -> Append to file as level 2 headline
13247 <left>/<right> -> before/after current headline, same headings level")
13249 (defvar org-remember-previous-location nil)
13250 (defvar org-force-remember-template-char) ;; dynamically scoped
13252 (defun org-select-remember-template (&optional use-char)
13253 (when org-remember-templates
13254 (let* ((templates (mapcar (lambda (x)
13255 (if (stringp (car x))
13256 (append (list (nth 1 x) (car x)) (cddr x))
13257 (append (list (car x) "") (cdr x))))
13258 org-remember-templates))
13259 (char (or use-char
13260 (cond
13261 ((= (length templates) 1)
13262 (caar templates))
13263 ((and (boundp 'org-force-remember-template-char)
13264 org-force-remember-template-char)
13265 (if (stringp org-force-remember-template-char)
13266 (string-to-char org-force-remember-template-char)
13267 org-force-remember-template-char))
13269 (message "Select template: %s"
13270 (mapconcat
13271 (lambda (x)
13272 (cond
13273 ((not (string-match "\\S-" (nth 1 x)))
13274 (format "[%c]" (car x)))
13275 ((equal (downcase (car x))
13276 (downcase (aref (nth 1 x) 0)))
13277 (format "[%c]%s" (car x)
13278 (substring (nth 1 x) 1)))
13279 (t (format "[%c]%s" (car x) (nth 1 x)))))
13280 templates " "))
13281 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13282 (when (equal char0 ?\C-g)
13283 (jump-to-register remember-register)
13284 (kill-buffer remember-buffer))
13285 char0))))))
13286 (cddr (assoc char templates)))))
13288 (defvar x-last-selected-text)
13289 (defvar x-last-selected-text-primary)
13291 ;;;###autoload
13292 (defun org-remember-apply-template (&optional use-char skip-interactive)
13293 "Initialize *remember* buffer with template, invoke `org-mode'.
13294 This function should be placed into `remember-mode-hook' and in fact requires
13295 to be run from that hook to function properly."
13296 (unless (fboundp 'remember-finalize)
13297 (defalias 'remember-finalize 'remember-buffer))
13298 (if org-remember-templates
13299 (let* ((entry (org-select-remember-template use-char))
13300 (tpl (car entry))
13301 (plist-p (if org-store-link-plist t nil))
13302 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13303 (string-match "\\S-" (nth 1 entry)))
13304 (nth 1 entry)
13305 org-default-notes-file))
13306 (headline (nth 2 entry))
13307 (v-c (or (and (eq window-system 'x)
13308 (fboundp 'x-cut-buffer-or-selection-value)
13309 (x-cut-buffer-or-selection-value))
13310 (org-bound-and-true-p x-last-selected-text)
13311 (org-bound-and-true-p x-last-selected-text-primary)
13312 (and (> (length kill-ring) 0) (current-kill 0))))
13313 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13314 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13315 (v-u (concat "[" (substring v-t 1 -1) "]"))
13316 (v-U (concat "[" (substring v-T 1 -1) "]"))
13317 ;; `initial' and `annotation' are bound in `remember'
13318 (v-i (if (boundp 'initial) initial))
13319 (v-a (if (and (boundp 'annotation) annotation)
13320 (if (equal annotation "[[]]") "" annotation)
13321 ""))
13322 (v-A (if (and v-a
13323 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13324 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13325 v-a))
13326 (v-n user-full-name)
13327 (org-startup-folded nil)
13328 org-time-was-given org-end-time-was-given x
13329 prompt completions char time pos default histvar)
13330 (setq org-store-link-plist
13331 (append (list :annotation v-a :initial v-i)
13332 org-store-link-plist))
13333 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13334 (erase-buffer)
13335 (insert (substitute-command-keys
13336 (format
13337 "## Filing location: Select interactively, default, or last used:
13338 ## %s to select file and header location interactively.
13339 ## %s \"%s\" -> \"* %s\"
13340 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13341 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13342 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13343 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13344 (abbreviate-file-name (or file org-default-notes-file))
13345 (or headline "")
13346 (or (car org-remember-previous-location) "???")
13347 (or (cdr org-remember-previous-location) "???"))))
13348 (insert tpl) (goto-char (point-min))
13349 ;; Simple %-escapes
13350 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13351 (when (and initial (equal (match-string 0) "%i"))
13352 (save-match-data
13353 (let* ((lead (buffer-substring
13354 (point-at-bol) (match-beginning 0))))
13355 (setq v-i (mapconcat 'identity
13356 (org-split-string initial "\n")
13357 (concat "\n" lead))))))
13358 (replace-match
13359 (or (eval (intern (concat "v-" (match-string 1)))) "")
13360 t t))
13362 ;; %[] Insert contents of a file.
13363 (goto-char (point-min))
13364 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13365 (let ((start (match-beginning 0))
13366 (end (match-end 0))
13367 (filename (expand-file-name (match-string 1))))
13368 (goto-char start)
13369 (delete-region start end)
13370 (condition-case error
13371 (insert-file-contents filename)
13372 (error (insert (format "%%![Couldn't insert %s: %s]"
13373 filename error))))))
13374 ;; %() embedded elisp
13375 (goto-char (point-min))
13376 (while (re-search-forward "%\\((.+)\\)" nil t)
13377 (goto-char (match-beginning 0))
13378 (let ((template-start (point)))
13379 (forward-char 1)
13380 (let ((result
13381 (condition-case error
13382 (eval (read (current-buffer)))
13383 (error (format "%%![Error: %s]" error)))))
13384 (delete-region template-start (point))
13385 (insert result))))
13387 ;; From the property list
13388 (when plist-p
13389 (goto-char (point-min))
13390 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13391 (and (setq x (or (plist-get org-store-link-plist
13392 (intern (match-string 1))) ""))
13393 (replace-match x t t))))
13395 ;; Turn on org-mode in the remember buffer, set local variables
13396 (org-mode)
13397 (org-set-local 'org-finish-function 'remember-finalize)
13398 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13399 (org-set-local 'org-default-notes-file file))
13400 (if (and headline (stringp headline) (string-match "\\S-" headline))
13401 (org-set-local 'org-remember-default-headline headline))
13402 ;; Interactive template entries
13403 (goto-char (point-min))
13404 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
13405 (setq char (if (match-end 3) (match-string 3))
13406 prompt (if (match-end 2) (match-string 2)))
13407 (goto-char (match-beginning 0))
13408 (replace-match "")
13409 (setq completions nil default nil)
13410 (when prompt
13411 (setq completions (org-split-string prompt "|")
13412 prompt (pop completions)
13413 default (car completions)
13414 histvar (intern (concat
13415 "org-remember-template-prompt-history::"
13416 (or prompt "")))
13417 completions (mapcar 'list completions)))
13418 (cond
13419 ((member char '("G" "g"))
13420 (let* ((org-last-tags-completion-table
13421 (org-global-tags-completion-table
13422 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13423 (org-add-colon-after-tag-completion t)
13424 (ins (completing-read
13425 (if prompt (concat prompt ": ") "Tags: ")
13426 'org-tags-completion-function nil nil nil
13427 'org-tags-history)))
13428 (setq ins (mapconcat 'identity
13429 (org-split-string ins (org-re "[^[:alnum:]]+"))
13430 ":"))
13431 (when (string-match "\\S-" ins)
13432 (or (equal (char-before) ?:) (insert ":"))
13433 (insert ins)
13434 (or (equal (char-after) ?:) (insert ":")))))
13435 (char
13436 (setq org-time-was-given (equal (upcase char) char))
13437 (setq time (org-read-date (equal (upcase char) "U") t nil
13438 prompt))
13439 (org-insert-time-stamp time org-time-was-given
13440 (member char '("u" "U"))
13441 nil nil (list org-end-time-was-given)))
13443 (insert (org-completing-read
13444 (concat (if prompt prompt "Enter string")
13445 (if default (concat " [" default "]"))
13446 ": ")
13447 completions nil nil nil histvar default)))))
13448 (goto-char (point-min))
13449 (if (re-search-forward "%\\?" nil t)
13450 (replace-match "")
13451 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13452 (org-mode)
13453 (org-set-local 'org-finish-function 'remember-finalize))
13454 (when (save-excursion
13455 (goto-char (point-min))
13456 (re-search-forward "%!" nil t))
13457 (replace-match "")
13458 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13460 (defun org-remember-finish-immediately ()
13461 "File remember note immediately.
13462 This should be run in `post-command-hook' and will remove itself
13463 from that hook."
13464 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13465 (when org-finish-function
13466 (funcall org-finish-function)))
13469 ;;;###autoload
13470 (defun org-remember (&optional goto org-force-remember-template-char)
13471 "Call `remember'. If this is already a remember buffer, re-apply template.
13472 If there is an active region, make sure remember uses it as initial content
13473 of the remember buffer.
13475 When called interactively with a `C-u' prefix argument GOTO, don't remember
13476 anything, just go to the file/headline where the selected templated usually
13477 stores its notes. With a double prefix arg `C-u C-u', got to the last
13478 note stored by remember.
13480 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13481 associated with a template in `org-remember-tempates'."
13482 (interactive "P")
13483 (cond
13484 ((equal goto '(4)) (org-go-to-remember-target))
13485 ((equal goto '(16)) (org-remember-goto-last-stored))
13487 (if (memq org-finish-function '(remember-buffer remember-finalize))
13488 (progn
13489 (when (< (length org-remember-templates) 2)
13490 (error "No other template available"))
13491 (erase-buffer)
13492 (let ((annotation (plist-get org-store-link-plist :annotation))
13493 (initial (plist-get org-store-link-plist :initial)))
13494 (org-remember-apply-template))
13495 (message "Press C-c C-c to remember data"))
13496 (if (org-region-active-p)
13497 (remember (buffer-substring (point) (mark)))
13498 (call-interactively 'remember))))))
13500 (defun org-remember-goto-last-stored ()
13501 "Go to the location where the last remember note was stored."
13502 (interactive)
13503 (bookmark-jump "org-remember-last-stored")
13504 (message "This is the last note stored by remember"))
13506 (defun org-go-to-remember-target (&optional template-key)
13507 "Go to the target location of a remember template.
13508 The user is queried for the template."
13509 (interactive)
13510 (let* ((entry (org-select-remember-template template-key))
13511 (file (nth 1 entry))
13512 (heading (nth 2 entry))
13513 visiting)
13514 (unless (and file (stringp file) (string-match "\\S-" file))
13515 (setq file org-default-notes-file))
13516 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13517 (setq heading org-remember-default-headline))
13518 (setq visiting (org-find-base-buffer-visiting file))
13519 (if (not visiting) (find-file-noselect file))
13520 (switch-to-buffer (or visiting (get-file-buffer file)))
13521 (widen)
13522 (goto-char (point-min))
13523 (if (re-search-forward
13524 (concat "^\\*+[ \t]+" (regexp-quote heading)
13525 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13526 nil t)
13527 (goto-char (match-beginning 0))
13528 (error "Target headline not found: %s" heading))))
13530 (defvar org-note-abort nil) ; dynamically scoped
13532 ;;;###autoload
13533 (defun org-remember-handler ()
13534 "Store stuff from remember.el into an org file.
13535 First prompts for an org file. If the user just presses return, the value
13536 of `org-default-notes-file' is used.
13537 Then the command offers the headings tree of the selected file in order to
13538 file the text at a specific location.
13539 You can either immediately press RET to get the note appended to the
13540 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13541 find a better place. Then press RET or <left> or <right> in insert the note.
13543 Key Cursor position Note gets inserted
13544 -----------------------------------------------------------------------------
13545 RET buffer-start as level 1 heading at end of file
13546 RET on headline as sublevel of the heading at cursor
13547 RET no heading at cursor position, level taken from context.
13548 Or use prefix arg to specify level manually.
13549 <left> on headline as same level, before current heading
13550 <right> on headline as same level, after current heading
13552 So the fastest way to store the note is to press RET RET to append it to
13553 the default file. This way your current train of thought is not
13554 interrupted, in accordance with the principles of remember.el.
13555 You can also get the fast execution without prompting by using
13556 C-u C-c C-c to exit the remember buffer. See also the variable
13557 `org-remember-store-without-prompt'.
13559 Before being stored away, the function ensures that the text has a
13560 headline, i.e. a first line that starts with a \"*\". If not, a headline
13561 is constructed from the current date and some additional data.
13563 If the variable `org-adapt-indentation' is non-nil, the entire text is
13564 also indented so that it starts in the same column as the headline
13565 \(i.e. after the stars).
13567 See also the variable `org-reverse-note-order'."
13568 (goto-char (point-min))
13569 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13570 (replace-match ""))
13571 (goto-char (point-max))
13572 (beginning-of-line 1)
13573 (while (looking-at "[ \t]*$\\|##.*")
13574 (delete-region (1- (point)) (point-max))
13575 (beginning-of-line 1))
13576 (catch 'quit
13577 (if org-note-abort (throw 'quit nil))
13578 (let* ((txt (buffer-substring (point-min) (point-max)))
13579 (fastp (org-xor (equal current-prefix-arg '(4))
13580 org-remember-store-without-prompt))
13581 (file (if fastp org-default-notes-file (org-get-org-file)))
13582 (heading org-remember-default-headline)
13583 (visiting (org-find-base-buffer-visiting file))
13584 (org-startup-folded nil)
13585 (org-startup-align-all-tables nil)
13586 (org-goto-start-pos 1)
13587 spos exitcmd level indent reversed)
13588 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13589 (setq file (car org-remember-previous-location)
13590 heading (cdr org-remember-previous-location)))
13591 (setq current-prefix-arg nil)
13592 (if (string-match "[ \t\n]+\\'" txt)
13593 (setq txt (replace-match "" t t txt)))
13594 ;; Modify text so that it becomes a nice subtree which can be inserted
13595 ;; into an org tree.
13596 (let* ((lines (split-string txt "\n"))
13597 first)
13598 (setq first (car lines) lines (cdr lines))
13599 (if (string-match "^\\*+ " first)
13600 ;; Is already a headline
13601 (setq indent nil)
13602 ;; We need to add a headline: Use time and first buffer line
13603 (setq lines (cons first lines)
13604 first (concat "* " (current-time-string)
13605 " (" (remember-buffer-desc) ")")
13606 indent " "))
13607 (if (and org-adapt-indentation indent)
13608 (setq lines (mapcar
13609 (lambda (x)
13610 (if (string-match "\\S-" x)
13611 (concat indent x) x))
13612 lines)))
13613 (setq txt (concat first "\n"
13614 (mapconcat 'identity lines "\n"))))
13615 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13616 (setq txt (replace-match "\n\n" t t txt))
13617 (if (string-match "[ \t\n]*\\'" txt)
13618 (setq txt (replace-match "\n" t t txt))))
13619 ;; Find the file
13620 (if (not visiting) (find-file-noselect file))
13621 (with-current-buffer (or visiting (get-file-buffer file))
13622 (unless (org-mode-p)
13623 (error "Target files for remember notes must be in Org-mode"))
13624 (save-excursion
13625 (save-restriction
13626 (widen)
13627 (and (goto-char (point-min))
13628 (not (re-search-forward "^\\* " nil t))
13629 (insert "\n* " (or heading "Notes") "\n"))
13630 (setq reversed (org-notes-order-reversed-p))
13632 ;; Find the default location
13633 (when (and heading (stringp heading) (string-match "\\S-" heading))
13634 (goto-char (point-min))
13635 (if (re-search-forward
13636 (concat "^\\*+[ \t]+" (regexp-quote heading)
13637 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13638 nil t)
13639 (setq org-goto-start-pos (match-beginning 0))
13640 (when fastp
13641 (goto-char (point-max))
13642 (unless (bolp) (newline))
13643 (insert "* " heading "\n")
13644 (setq org-goto-start-pos (point-at-bol 0)))))
13646 ;; Ask the User for a location
13647 (if fastp
13648 (setq spos org-goto-start-pos
13649 exitcmd 'return)
13650 (setq spos (org-get-location (current-buffer) org-remember-help)
13651 exitcmd (cdr spos)
13652 spos (car spos)))
13653 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13654 ; not handle this note
13655 (goto-char spos)
13656 (cond ((org-on-heading-p t)
13657 (org-back-to-heading t)
13658 (setq level (funcall outline-level))
13659 (cond
13660 ((eq exitcmd 'return)
13661 ;; sublevel of current
13662 (setq org-remember-previous-location
13663 (cons (abbreviate-file-name file)
13664 (org-get-heading 'notags)))
13665 (if reversed
13666 (outline-next-heading)
13667 (org-end-of-subtree)
13668 (if (not (bolp))
13669 (if (looking-at "[ \t]*\n")
13670 (beginning-of-line 2)
13671 (end-of-line 1)
13672 (insert "\n"))))
13673 (bookmark-set "org-remember-last-stored")
13674 (org-paste-subtree (org-get-legal-level level 1) txt))
13675 ((eq exitcmd 'left)
13676 ;; before current
13677 (bookmark-set "org-remember-last-stored")
13678 (org-paste-subtree level txt))
13679 ((eq exitcmd 'right)
13680 ;; after current
13681 (org-end-of-subtree t)
13682 (bookmark-set "org-remember-last-stored")
13683 (org-paste-subtree level txt))
13684 (t (error "This should not happen"))))
13686 ((and (bobp) (not reversed))
13687 ;; Put it at the end, one level below level 1
13688 (save-restriction
13689 (widen)
13690 (goto-char (point-max))
13691 (if (not (bolp)) (newline))
13692 (bookmark-set "org-remember-last-stored")
13693 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13695 ((and (bobp) reversed)
13696 ;; Put it at the start, as level 1
13697 (save-restriction
13698 (widen)
13699 (goto-char (point-min))
13700 (re-search-forward "^\\*+ " nil t)
13701 (beginning-of-line 1)
13702 (bookmark-set "org-remember-last-stored")
13703 (org-paste-subtree 1 txt)))
13705 ;; Put it right there, with automatic level determined by
13706 ;; org-paste-subtree or from prefix arg
13707 (bookmark-set "org-remember-last-stored")
13708 (org-paste-subtree
13709 (if (numberp current-prefix-arg) current-prefix-arg)
13710 txt)))
13711 (when remember-save-after-remembering
13712 (save-buffer)
13713 (if (not visiting) (kill-buffer (current-buffer)))))))))
13715 t) ;; return t to indicate that we took care of this note.
13717 (defun org-get-org-file ()
13718 "Read a filename, with default directory `org-directory'."
13719 (let ((default (or org-default-notes-file remember-data-file)))
13720 (read-file-name (format "File name [%s]: " default)
13721 (file-name-as-directory org-directory)
13722 default)))
13724 (defun org-notes-order-reversed-p ()
13725 "Check if the current file should receive notes in reversed order."
13726 (cond
13727 ((not org-reverse-note-order) nil)
13728 ((eq t org-reverse-note-order) t)
13729 ((not (listp org-reverse-note-order)) nil)
13730 (t (catch 'exit
13731 (let ((all org-reverse-note-order)
13732 entry)
13733 (while (setq entry (pop all))
13734 (if (string-match (car entry) buffer-file-name)
13735 (throw 'exit (cdr entry))))
13736 nil)))))
13738 ;;; Refiling
13740 (defvar org-refile-target-table nil
13741 "The list of refile targets, created by `org-refile'.")
13743 (defvar org-agenda-new-buffers nil
13744 "Buffers created to visit agenda files.")
13746 (defun org-get-refile-targets ()
13747 "Produce a table with refile targets."
13748 (let ((entries org-refile-targets)
13749 org-agenda-new-files targets txt re files f desc descre)
13750 (while (setq entry (pop entries))
13751 (setq files (car entry) desc (cdr entry))
13752 (cond
13753 ((null files) (setq files (list (current-buffer))))
13754 ((eq files 'org-agenda-files)
13755 (setq files (org-agenda-files 'unrestricted)))
13756 ((and (symbolp files) (fboundp files))
13757 (setq files (funcall files)))
13758 ((and (symbolp files) (boundp files))
13759 (setq files (symbol-value files))))
13760 (if (stringp files) (setq files (list files)))
13761 (cond
13762 ((eq (car desc) :tag)
13763 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13764 ((eq (car desc) :todo)
13765 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13766 ((eq (car desc) :regexp)
13767 (setq descre (cdr desc)))
13768 ((eq (car desc) :level)
13769 (setq descre (concat "^\\*\\{" (number-to-string
13770 (if org-odd-levels-only
13771 (1- (* 2 (cdr desc)))
13772 (cdr desc)))
13773 "\\}[ \t]")))
13774 ((eq (car desc) :maxlevel)
13775 (setq descre (concat "^\\*\\{1," (number-to-string
13776 (if org-odd-levels-only
13777 (1- (* 2 (cdr desc)))
13778 (cdr desc)))
13779 "\\}[ \t]")))
13780 (t (error "Bad refiling target description %s" desc)))
13781 (while (setq f (pop files))
13782 (save-excursion
13783 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13784 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13785 (save-excursion
13786 (save-restriction
13787 (widen)
13788 (goto-char (point-min))
13789 (while (re-search-forward descre nil t)
13790 (goto-char (point-at-bol))
13791 (when (looking-at org-complex-heading-regexp)
13792 (setq txt (match-string 4)
13793 re (concat "^" (regexp-quote
13794 (buffer-substring (match-beginning 1)
13795 (match-end 4)))))
13796 (if (match-end 5) (setq re (concat re "[ \t]+"
13797 (regexp-quote
13798 (match-string 5)))))
13799 (setq re (concat re "[ \t]*$"))
13800 (when org-refile-use-outline-path
13801 (setq txt (mapconcat 'identity
13802 (append
13803 (if (eq org-refile-use-outline-path 'file)
13804 (list (file-name-nondirectory
13805 (buffer-file-name (buffer-base-buffer))))
13806 (if (eq org-refile-use-outline-path 'full-file-path)
13807 (list (buffer-file-name (buffer-base-buffer)))))
13808 (org-get-outline-path)
13809 (list txt))
13810 "/")))
13811 (push (list txt f re (point)) targets))
13812 (goto-char (point-at-eol))))))))
13813 (org-release-buffers org-agenda-new-buffers)
13814 (nreverse targets)))
13816 (defun org-get-outline-path ()
13817 (let (rtn)
13818 (save-excursion
13819 (while (org-up-heading-safe)
13820 (when (looking-at org-complex-heading-regexp)
13821 (push (org-match-string-no-properties 4) rtn)))
13822 rtn)))
13824 (defvar org-refile-history nil
13825 "History for refiling operations.")
13827 (defun org-refile (&optional reversed-or-update)
13828 "Move the entry at point to another heading.
13829 The list of target headings is compiled using the information in
13830 `org-refile-targets', which see. This list is created upon first use, and
13831 you can update it by calling this command with a double prefix (`C-u C-u').
13833 At the target location, the entry is filed as a subitem of the target heading.
13834 Depending on `org-reverse-note-order', the new subitem will either be the
13835 first of the last subitem. A single C-u prefix will toggle the value of this
13836 variable for the duration of the command."
13837 (interactive "P")
13838 (if (equal reversed-or-update '(16))
13839 (progn
13840 (setq org-refile-target-table (org-get-refile-targets))
13841 (message "Refile targets updated (%d targets)"
13842 (length org-refile-target-table)))
13843 (when (or (not org-refile-target-table)
13844 (and (= (length org-refile-targets) 1)
13845 (not (caar org-refile-targets))))
13846 (setq org-refile-target-table (org-get-refile-targets)))
13847 (unless org-refile-target-table
13848 (error "No refile targets"))
13849 (let* ((cbuf (current-buffer))
13850 (filename (buffer-file-name (buffer-base-buffer cbuf)))
13851 (fname (and filename (file-truename filename)))
13852 (tbl (mapcar
13853 (lambda (x)
13854 (if (not (equal fname (file-truename (nth 1 x))))
13855 (cons (concat (car x) " (" (file-name-nondirectory
13856 (nth 1 x)) ")")
13857 (cdr x))
13859 org-refile-target-table))
13860 (completion-ignore-case t)
13861 pos it nbuf file re level reversed)
13862 (when (setq it (completing-read "Refile to: " tbl
13863 nil t nil 'org-refile-history))
13864 (setq it (assoc it tbl)
13865 file (nth 1 it)
13866 re (nth 2 it))
13867 (org-copy-special)
13868 (save-excursion
13869 (set-buffer (setq nbuf (or (find-buffer-visiting file)
13870 (find-file-noselect file))))
13871 (setq reversed (org-notes-order-reversed-p))
13872 (if (equal reversed-or-update '(16)) (setq reversed (not reversed)))
13873 (save-excursion
13874 (save-restriction
13875 (widen)
13876 (goto-char (point-min))
13877 (unless (re-search-forward re nil t)
13878 (error "Cannot find target location - try again with `C-u' prefix."))
13879 (goto-char (match-beginning 0))
13880 (looking-at outline-regexp)
13881 (setq level (org-get-legal-level (funcall outline-level) 1))
13882 (goto-char (or (save-excursion
13883 (if reversed
13884 (outline-next-heading)
13885 (outline-get-next-sibling)))
13886 (point-max)))
13887 (org-paste-subtree level))))
13888 (org-cut-special)
13889 (message "Entry refiled to \"%s\"" (car it))))))
13891 ;;;; Dynamic blocks
13893 (defun org-find-dblock (name)
13894 "Find the first dynamic block with name NAME in the buffer.
13895 If not found, stay at current position and return nil."
13896 (let (pos)
13897 (save-excursion
13898 (goto-char (point-min))
13899 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
13900 nil t)
13901 (match-beginning 0))))
13902 (if pos (goto-char pos))
13903 pos))
13905 (defconst org-dblock-start-re
13906 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
13907 "Matches the startline of a dynamic block, with parameters.")
13909 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
13910 "Matches the end of a dyhamic block.")
13912 (defun org-create-dblock (plist)
13913 "Create a dynamic block section, with parameters taken from PLIST.
13914 PLIST must containe a :name entry which is used as name of the block."
13915 (unless (bolp) (newline))
13916 (let ((name (plist-get plist :name)))
13917 (insert "#+BEGIN: " name)
13918 (while plist
13919 (if (eq (car plist) :name)
13920 (setq plist (cddr plist))
13921 (insert " " (prin1-to-string (pop plist)))))
13922 (insert "\n\n#+END:\n")
13923 (beginning-of-line -2)))
13925 (defun org-prepare-dblock ()
13926 "Prepare dynamic block for refresh.
13927 This empties the block, puts the cursor at the insert position and returns
13928 the property list including an extra property :name with the block name."
13929 (unless (looking-at org-dblock-start-re)
13930 (error "Not at a dynamic block"))
13931 (let* ((begdel (1+ (match-end 0)))
13932 (name (org-no-properties (match-string 1)))
13933 (params (append (list :name name)
13934 (read (concat "(" (match-string 3) ")")))))
13935 (unless (re-search-forward org-dblock-end-re nil t)
13936 (error "Dynamic block not terminated"))
13937 (delete-region begdel (match-beginning 0))
13938 (goto-char begdel)
13939 (open-line 1)
13940 params))
13942 (defun org-map-dblocks (&optional command)
13943 "Apply COMMAND to all dynamic blocks in the current buffer.
13944 If COMMAND is not given, use `org-update-dblock'."
13945 (let ((cmd (or command 'org-update-dblock))
13946 pos)
13947 (save-excursion
13948 (goto-char (point-min))
13949 (while (re-search-forward org-dblock-start-re nil t)
13950 (goto-char (setq pos (match-beginning 0)))
13951 (condition-case nil
13952 (funcall cmd)
13953 (error (message "Error during update of dynamic block")))
13954 (goto-char pos)
13955 (unless (re-search-forward org-dblock-end-re nil t)
13956 (error "Dynamic block not terminated"))))))
13958 (defun org-dblock-update (&optional arg)
13959 "User command for updating dynamic blocks.
13960 Update the dynamic block at point. With prefix ARG, update all dynamic
13961 blocks in the buffer."
13962 (interactive "P")
13963 (if arg
13964 (org-update-all-dblocks)
13965 (or (looking-at org-dblock-start-re)
13966 (org-beginning-of-dblock))
13967 (org-update-dblock)))
13969 (defun org-update-dblock ()
13970 "Update the dynamic block at point
13971 This means to empty the block, parse for parameters and then call
13972 the correct writing function."
13973 (save-window-excursion
13974 (let* ((pos (point))
13975 (line (org-current-line))
13976 (params (org-prepare-dblock))
13977 (name (plist-get params :name))
13978 (cmd (intern (concat "org-dblock-write:" name))))
13979 (message "Updating dynamic block `%s' at line %d..." name line)
13980 (funcall cmd params)
13981 (message "Updating dynamic block `%s' at line %d...done" name line)
13982 (goto-char pos))))
13984 (defun org-beginning-of-dblock ()
13985 "Find the beginning of the dynamic block at point.
13986 Error if there is no scuh block at point."
13987 (let ((pos (point))
13988 beg)
13989 (end-of-line 1)
13990 (if (and (re-search-backward org-dblock-start-re nil t)
13991 (setq beg (match-beginning 0))
13992 (re-search-forward org-dblock-end-re nil t)
13993 (> (match-end 0) pos))
13994 (goto-char beg)
13995 (goto-char pos)
13996 (error "Not in a dynamic block"))))
13998 (defun org-update-all-dblocks ()
13999 "Update all dynamic blocks in the buffer.
14000 This function can be used in a hook."
14001 (when (org-mode-p)
14002 (org-map-dblocks 'org-update-dblock)))
14005 ;;;; Completion
14007 (defconst org-additional-option-like-keywords
14008 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14009 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14010 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14012 (defun org-complete (&optional arg)
14013 "Perform completion on word at point.
14014 At the beginning of a headline, this completes TODO keywords as given in
14015 `org-todo-keywords'.
14016 If the current word is preceded by a backslash, completes the TeX symbols
14017 that are supported for HTML support.
14018 If the current word is preceded by \"#+\", completes special words for
14019 setting file options.
14020 In the line after \"#+STARTUP:, complete valid keywords.\"
14021 At all other locations, this simply calls the value of
14022 `org-completion-fallback-command'."
14023 (interactive "P")
14024 (org-without-partial-completion
14025 (catch 'exit
14026 (let* ((end (point))
14027 (beg1 (save-excursion
14028 (skip-chars-backward (org-re "[:alnum:]_@"))
14029 (point)))
14030 (beg (save-excursion
14031 (skip-chars-backward "a-zA-Z0-9_:$")
14032 (point)))
14033 (confirm (lambda (x) (stringp (car x))))
14034 (searchhead (equal (char-before beg) ?*))
14035 (tag (and (equal (char-before beg1) ?:)
14036 (equal (char-after (point-at-bol)) ?*)))
14037 (prop (and (equal (char-before beg1) ?:)
14038 (not (equal (char-after (point-at-bol)) ?*))))
14039 (texp (equal (char-before beg) ?\\))
14040 (link (equal (char-before beg) ?\[))
14041 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14042 beg)
14043 "#+"))
14044 (startup (string-match "^#\\+STARTUP:.*"
14045 (buffer-substring (point-at-bol) (point))))
14046 (completion-ignore-case opt)
14047 (type nil)
14048 (tbl nil)
14049 (table (cond
14050 (opt
14051 (setq type :opt)
14052 (append
14053 (mapcar
14054 (lambda (x)
14055 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14056 (cons (match-string 2 x) (match-string 1 x)))
14057 (org-split-string (org-get-current-options) "\n"))
14058 (mapcar 'list org-additional-option-like-keywords)))
14059 (startup
14060 (setq type :startup)
14061 org-startup-options)
14062 (link (append org-link-abbrev-alist-local
14063 org-link-abbrev-alist))
14064 (texp
14065 (setq type :tex)
14066 org-html-entities)
14067 ((string-match "\\`\\*+[ \t]+\\'"
14068 (buffer-substring (point-at-bol) beg))
14069 (setq type :todo)
14070 (mapcar 'list org-todo-keywords-1))
14071 (searchhead
14072 (setq type :searchhead)
14073 (save-excursion
14074 (goto-char (point-min))
14075 (while (re-search-forward org-todo-line-regexp nil t)
14076 (push (list
14077 (org-make-org-heading-search-string
14078 (match-string 3) t))
14079 tbl)))
14080 tbl)
14081 (tag (setq type :tag beg beg1)
14082 (or org-tag-alist (org-get-buffer-tags)))
14083 (prop (setq type :prop beg beg1)
14084 (mapcar 'list (org-buffer-property-keys)))
14085 (t (progn
14086 (call-interactively org-completion-fallback-command)
14087 (throw 'exit nil)))))
14088 (pattern (buffer-substring-no-properties beg end))
14089 (completion (try-completion pattern table confirm)))
14090 (cond ((eq completion t)
14091 (if (not (assoc (upcase pattern) table))
14092 (message "Already complete")
14093 (if (equal type :opt)
14094 (insert (substring (cdr (assoc (upcase pattern) table))
14095 (length pattern)))
14096 (if (memq type '(:tag :prop)) (insert ":")))))
14097 ((null completion)
14098 (message "Can't find completion for \"%s\"" pattern)
14099 (ding))
14100 ((not (string= pattern completion))
14101 (delete-region beg end)
14102 (if (string-match " +$" completion)
14103 (setq completion (replace-match "" t t completion)))
14104 (insert completion)
14105 (if (get-buffer-window "*Completions*")
14106 (delete-window (get-buffer-window "*Completions*")))
14107 (if (assoc completion table)
14108 (if (eq type :todo) (insert " ")
14109 (if (memq type '(:tag :prop)) (insert ":"))))
14110 (if (and (equal type :opt) (assoc completion table))
14111 (message "%s" (substitute-command-keys
14112 "Press \\[org-complete] again to insert example settings"))))
14114 (message "Making completion list...")
14115 (let ((list (sort (all-completions pattern table confirm)
14116 'string<)))
14117 (with-output-to-temp-buffer "*Completions*"
14118 (condition-case nil
14119 ;; Protection needed for XEmacs and emacs 21
14120 (display-completion-list list pattern)
14121 (error (display-completion-list list)))))
14122 (message "Making completion list...%s" "done")))))))
14124 ;;;; TODO, DEADLINE, Comments
14126 (defun org-toggle-comment ()
14127 "Change the COMMENT state of an entry."
14128 (interactive)
14129 (save-excursion
14130 (org-back-to-heading)
14131 (let (case-fold-search)
14132 (if (looking-at (concat outline-regexp
14133 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14134 (replace-match "" t t nil 1)
14135 (if (looking-at outline-regexp)
14136 (progn
14137 (goto-char (match-end 0))
14138 (insert org-comment-string " ")))))))
14140 (defvar org-last-todo-state-is-todo nil
14141 "This is non-nil when the last TODO state change led to a TODO state.
14142 If the last change removed the TODO tag or switched to DONE, then
14143 this is nil.")
14145 (defvar org-setting-tags nil) ; dynamically skiped
14147 ;; FIXME: better place
14148 (defun org-property-or-variable-value (var &optional inherit)
14149 "Check if there is a property fixing the value of VAR.
14150 If yes, return this value. If not, return the current value of the variable."
14151 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14152 (if (and prop (stringp prop) (string-match "\\S-" prop))
14153 (read prop)
14154 (symbol-value var))))
14156 (defun org-parse-local-options (string var)
14157 "Parse STRING for startup setting relevant for variable VAR."
14158 (let ((rtn (symbol-value var))
14159 e opts)
14160 (save-match-data
14161 (if (or (not string) (not (string-match "\\S-" string)))
14163 (setq opts (delq nil (mapcar (lambda (x)
14164 (setq e (assoc x org-startup-options))
14165 (if (eq (nth 1 e) var) e nil))
14166 (org-split-string string "[ \t]+"))))
14167 (if (not opts)
14169 (setq rtn nil)
14170 (while (setq e (pop opts))
14171 (if (not (nth 3 e))
14172 (setq rtn (nth 2 e))
14173 (if (not (listp rtn)) (setq rtn nil))
14174 (push (nth 2 e) rtn)))
14175 rtn)))))
14177 (defvar org-blocker-hook nil
14178 "Hook for functions that are allowed to block a state change.
14180 Each function gets as its single argument a property list, see
14181 `org-trigger-hook' for more information about this list.
14183 If any of the functions in this hook returns nil, the state change
14184 is blocked.")
14186 (defvar org-trigger-hook nil
14187 "Hook for functions that are triggered by a state change.
14189 Each function gets as its single argument a property list with at least
14190 the following elements:
14192 (:type type-of-change :position pos-at-entry-start
14193 :from old-state :to new-state)
14195 Depending on the type, more properties may be present.
14197 This mechanism is currently implemented for:
14199 TODO state changes
14200 ------------------
14201 :type todo-state-change
14202 :from previous state (keyword as a string), or nil
14203 :to new state (keyword as a string), or nil")
14206 (defun org-todo (&optional arg)
14207 "Change the TODO state of an item.
14208 The state of an item is given by a keyword at the start of the heading,
14209 like
14210 *** TODO Write paper
14211 *** DONE Call mom
14213 The different keywords are specified in the variable `org-todo-keywords'.
14214 By default the available states are \"TODO\" and \"DONE\".
14215 So for this example: when the item starts with TODO, it is changed to DONE.
14216 When it starts with DONE, the DONE is removed. And when neither TODO nor
14217 DONE are present, add TODO at the beginning of the heading.
14219 With C-u prefix arg, use completion to determine the new state.
14220 With numeric prefix arg, switch to that state.
14222 For calling through lisp, arg is also interpreted in the following way:
14223 'none -> empty state
14224 \"\"(empty string) -> switch to empty state
14225 'done -> switch to DONE
14226 'nextset -> switch to the next set of keywords
14227 'previousset -> switch to the previous set of keywords
14228 \"WAITING\" -> switch to the specified keyword, but only if it
14229 really is a member of `org-todo-keywords'."
14230 (interactive "P")
14231 (save-excursion
14232 (catch 'exit
14233 (org-back-to-heading)
14234 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14235 (or (looking-at (concat " +" org-todo-regexp " *"))
14236 (looking-at " *"))
14237 (let* ((match-data (match-data))
14238 (startpos (point-at-bol))
14239 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14240 (org-log-done (org-parse-local-options logging 'org-log-done))
14241 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
14242 (this (match-string 1))
14243 (hl-pos (match-beginning 0))
14244 (head (org-get-todo-sequence-head this))
14245 (ass (assoc head org-todo-kwd-alist))
14246 (interpret (nth 1 ass))
14247 (done-word (nth 3 ass))
14248 (final-done-word (nth 4 ass))
14249 (last-state (or this ""))
14250 (completion-ignore-case t)
14251 (member (member this org-todo-keywords-1))
14252 (tail (cdr member))
14253 (state (cond
14254 ((and org-todo-key-trigger
14255 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14256 (and (not arg) org-use-fast-todo-selection
14257 (not (eq org-use-fast-todo-selection 'prefix)))))
14258 ;; Use fast selection
14259 (org-fast-todo-selection))
14260 ((and (equal arg '(4))
14261 (or (not org-use-fast-todo-selection)
14262 (not org-todo-key-trigger)))
14263 ;; Read a state with completion
14264 (completing-read "State: " (mapcar (lambda(x) (list x))
14265 org-todo-keywords-1)
14266 nil t))
14267 ((eq arg 'right)
14268 (if this
14269 (if tail (car tail) nil)
14270 (car org-todo-keywords-1)))
14271 ((eq arg 'left)
14272 (if (equal member org-todo-keywords-1)
14274 (if this
14275 (nth (- (length org-todo-keywords-1) (length tail) 2)
14276 org-todo-keywords-1)
14277 (org-last org-todo-keywords-1))))
14278 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14279 (setq arg nil))) ; hack to fall back to cycling
14280 (arg
14281 ;; user or caller requests a specific state
14282 (cond
14283 ((equal arg "") nil)
14284 ((eq arg 'none) nil)
14285 ((eq arg 'done) (or done-word (car org-done-keywords)))
14286 ((eq arg 'nextset)
14287 (or (car (cdr (member head org-todo-heads)))
14288 (car org-todo-heads)))
14289 ((eq arg 'previousset)
14290 (let ((org-todo-heads (reverse org-todo-heads)))
14291 (or (car (cdr (member head org-todo-heads)))
14292 (car org-todo-heads))))
14293 ((car (member arg org-todo-keywords-1)))
14294 ((nth (1- (prefix-numeric-value arg))
14295 org-todo-keywords-1))))
14296 ((null member) (or head (car org-todo-keywords-1)))
14297 ((equal this final-done-word) nil) ;; -> make empty
14298 ((null tail) nil) ;; -> first entry
14299 ((eq interpret 'sequence)
14300 (car tail))
14301 ((memq interpret '(type priority))
14302 (if (eq this-command last-command)
14303 (car tail)
14304 (if (> (length tail) 0)
14305 (or done-word (car org-done-keywords))
14306 nil)))
14307 (t nil)))
14308 (next (if state (concat " " state " ") " "))
14309 (change-plist (list :type 'todo-state-change :from this :to state
14310 :position startpos))
14311 dostates)
14312 (when org-blocker-hook
14313 (unless (save-excursion
14314 (save-match-data
14315 (run-hook-with-args-until-failure
14316 'org-blocker-hook change-plist)))
14317 (if (interactive-p)
14318 (error "TODO state change from %s to %s blocked" this state)
14319 ;; fail silently
14320 (message "TODO state change from %s to %s blocked" this state)
14321 (throw 'exit nil))))
14322 (store-match-data match-data)
14323 (replace-match next t t)
14324 (unless (pos-visible-in-window-p hl-pos)
14325 (message "TODO state changed to %s" (org-trim next)))
14326 (unless head
14327 (setq head (org-get-todo-sequence-head state)
14328 ass (assoc head org-todo-kwd-alist)
14329 interpret (nth 1 ass)
14330 done-word (nth 3 ass)
14331 final-done-word (nth 4 ass)))
14332 (when (memq arg '(nextset previousset))
14333 (message "Keyword-Set %d/%d: %s"
14334 (- (length org-todo-sets) -1
14335 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14336 (length org-todo-sets)
14337 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14338 (setq org-last-todo-state-is-todo
14339 (not (member state org-done-keywords)))
14340 (when (and org-log-done (not (memq arg '(nextset previousset))))
14341 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
14342 (or (not org-todo-log-states)
14343 (member state org-todo-log-states))))
14345 (cond
14346 ((and state (member state org-not-done-keywords)
14347 (not (member this org-not-done-keywords)))
14348 ;; This is now a todo state and was not one before
14349 ;; Remove any CLOSED timestamp, and possibly log the state change
14350 (org-add-planning-info nil nil 'closed)
14351 (and dostates (org-add-log-maybe 'state state 'findpos)))
14352 ((and state dostates)
14353 ;; This is a non-nil state, and we need to log it
14354 (org-add-log-maybe 'state state 'findpos))
14355 ((and (member state org-done-keywords)
14356 (not (member this org-done-keywords)))
14357 ;; It is now done, and it was not done before
14358 (org-add-planning-info 'closed (org-current-time))
14359 (org-add-log-maybe 'done state 'findpos))))
14360 ;; Fixup tag positioning
14361 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14362 (run-hooks 'org-after-todo-state-change-hook)
14363 (and (member state org-done-keywords) (org-auto-repeat-maybe))
14364 (if (and arg (not (member state org-done-keywords)))
14365 (setq head (org-get-todo-sequence-head state)))
14366 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14367 ;; Fixup cursor location if close to the keyword
14368 (if (and (outline-on-heading-p)
14369 (not (bolp))
14370 (save-excursion (beginning-of-line 1)
14371 (looking-at org-todo-line-regexp))
14372 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14373 (progn
14374 (goto-char (or (match-end 2) (match-end 1)))
14375 (just-one-space)))
14376 (when org-trigger-hook
14377 (save-excursion
14378 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14380 (defun org-get-todo-sequence-head (kwd)
14381 "Return the head of the TODO sequence to which KWD belongs.
14382 If KWD is not set, check if there is a text property remembering the
14383 right sequence."
14384 (let (p)
14385 (cond
14386 ((not kwd)
14387 (or (get-text-property (point-at-bol) 'org-todo-head)
14388 (progn
14389 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14390 nil (point-at-eol)))
14391 (get-text-property p 'org-todo-head))))
14392 ((not (member kwd org-todo-keywords-1))
14393 (car org-todo-keywords-1))
14394 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14396 (defun org-fast-todo-selection ()
14397 "Fast TODO keyword selection with single keys.
14398 Returns the new TODO keyword, or nil if no state change should occur."
14399 (let* ((fulltable org-todo-key-alist)
14400 (done-keywords org-done-keywords) ;; needed for the faces.
14401 (maxlen (apply 'max (mapcar
14402 (lambda (x)
14403 (if (stringp (car x)) (string-width (car x)) 0))
14404 fulltable)))
14405 (expert nil)
14406 (fwidth (+ maxlen 3 1 3))
14407 (ncol (/ (- (window-width) 4) fwidth))
14408 tg cnt e c tbl
14409 groups ingroup)
14410 (save-window-excursion
14411 (if expert
14412 (set-buffer (get-buffer-create " *Org todo*"))
14413 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14414 (erase-buffer)
14415 (org-set-local 'org-done-keywords done-keywords)
14416 (setq tbl fulltable cnt 0)
14417 (while (setq e (pop tbl))
14418 (cond
14419 ((equal e '(:startgroup))
14420 (push '() groups) (setq ingroup t)
14421 (when (not (= cnt 0))
14422 (setq cnt 0)
14423 (insert "\n"))
14424 (insert "{ "))
14425 ((equal e '(:endgroup))
14426 (setq ingroup nil cnt 0)
14427 (insert "}\n"))
14429 (setq tg (car e) c (cdr e))
14430 (if ingroup (push tg (car groups)))
14431 (setq tg (org-add-props tg nil 'face
14432 (org-get-todo-face tg)))
14433 (if (and (= cnt 0) (not ingroup)) (insert " "))
14434 (insert "[" c "] " tg (make-string
14435 (- fwidth 4 (length tg)) ?\ ))
14436 (when (= (setq cnt (1+ cnt)) ncol)
14437 (insert "\n")
14438 (if ingroup (insert " "))
14439 (setq cnt 0)))))
14440 (insert "\n")
14441 (goto-char (point-min))
14442 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14443 (fit-window-to-buffer))
14444 (message "[a-z..]:Set [SPC]:clear")
14445 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14446 (cond
14447 ((or (= c ?\C-g)
14448 (and (= c ?q) (not (rassoc c fulltable))))
14449 (setq quit-flag t))
14450 ((= c ?\ ) nil)
14451 ((setq e (rassoc c fulltable) tg (car e))
14453 (t (setq quit-flag t))))))
14455 (defun org-get-repeat ()
14456 "Check if tere is a deadline/schedule with repeater in this entry."
14457 (save-match-data
14458 (save-excursion
14459 (org-back-to-heading t)
14460 (if (re-search-forward
14461 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14462 (match-string 1)))))
14464 (defvar org-last-changed-timestamp)
14465 (defvar org-log-post-message)
14466 (defun org-auto-repeat-maybe ()
14467 "Check if the current headline contains a repeated deadline/schedule.
14468 If yes, set TODO state back to what it was and change the base date
14469 of repeating deadline/scheduled time stamps to new date.
14470 This function should be run in the `org-after-todo-state-change-hook'."
14471 ;; last-state is dynamically scoped into this function
14472 (let* ((repeat (org-get-repeat))
14473 (aa (assoc last-state org-todo-kwd-alist))
14474 (interpret (nth 1 aa))
14475 (head (nth 2 aa))
14476 (done-word (nth 3 aa))
14477 (whata '(("d" . day) ("m" . month) ("y" . year)))
14478 (msg "Entry repeats: ")
14479 (org-log-done)
14480 re type n what ts)
14481 (when repeat
14482 (org-todo (if (eq interpret 'type) last-state head))
14483 (when (and org-log-repeat
14484 (not (memq 'org-add-log-note
14485 (default-value 'post-command-hook))))
14486 ;; Make sure a note is taken
14487 (let ((org-log-done '(done)))
14488 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
14489 'findpos)))
14490 (org-back-to-heading t)
14491 (org-add-planning-info nil nil 'closed)
14492 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14493 org-deadline-time-regexp "\\)"))
14494 (while (re-search-forward
14495 re (save-excursion (outline-next-heading) (point)) t)
14496 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
14497 ts (match-string (if (match-end 2) 2 4)))
14498 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14499 (setq n (string-to-number (match-string 1 ts))
14500 what (match-string 2 ts))
14501 (if (equal what "w") (setq n (* n 7) what "d"))
14502 (org-timestamp-change n (cdr (assoc what whata))))
14503 (setq msg (concat msg type org-last-changed-timestamp " ")))
14504 (setq org-log-post-message msg)
14505 (message "%s" msg))))
14507 (defun org-show-todo-tree (arg)
14508 "Make a compact tree which shows all headlines marked with TODO.
14509 The tree will show the lines where the regexp matches, and all higher
14510 headlines above the match.
14511 With \\[universal-argument] prefix, also show the DONE entries.
14512 With a numeric prefix N, construct a sparse tree for the Nth element
14513 of `org-todo-keywords-1'."
14514 (interactive "P")
14515 (let ((case-fold-search nil)
14516 (kwd-re
14517 (cond ((null arg) org-not-done-regexp)
14518 ((equal arg '(4))
14519 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14520 (mapcar 'list org-todo-keywords-1))))
14521 (concat "\\("
14522 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14523 "\\)\\>")))
14524 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14525 (regexp-quote (nth (1- (prefix-numeric-value arg))
14526 org-todo-keywords-1)))
14527 (t (error "Invalid prefix argument: %s" arg)))))
14528 (message "%d TODO entries found"
14529 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14531 (defun org-deadline (&optional remove)
14532 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14533 With argument REMOVE, remove any deadline from the item."
14534 (interactive "P")
14535 (if remove
14536 (progn
14537 (org-add-planning-info nil nil 'deadline)
14538 (message "Item no longer has a deadline."))
14539 (org-add-planning-info 'deadline nil 'closed)))
14541 (defun org-schedule (&optional remove)
14542 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14543 With argument REMOVE, remove any scheduling date from the item."
14544 (interactive "P")
14545 (if remove
14546 (progn
14547 (org-add-planning-info nil nil 'scheduled)
14548 (message "Item is no longer scheduled."))
14549 (org-add-planning-info 'scheduled nil 'closed)))
14551 (defun org-add-planning-info (what &optional time &rest remove)
14552 "Insert new timestamp with keyword in the line directly after the headline.
14553 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14554 If non is given, the user is prompted for a date.
14555 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14556 be removed."
14557 (interactive)
14558 (let (org-time-was-given org-end-time-was-given)
14559 (when what (setq time (or time (org-read-date nil 'to-time))))
14560 (when (and org-insert-labeled-timestamps-at-point
14561 (member what '(scheduled deadline)))
14562 (insert
14563 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14564 (org-insert-time-stamp time org-time-was-given
14565 nil nil nil (list org-end-time-was-given))
14566 (setq what nil))
14567 (save-excursion
14568 (save-restriction
14569 (let (col list elt ts buffer-invisibility-spec)
14570 (org-back-to-heading t)
14571 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14572 (goto-char (match-end 1))
14573 (setq col (current-column))
14574 (goto-char (match-end 0))
14575 (if (eobp) (insert "\n") (forward-char 1))
14576 (if (and (not (looking-at outline-regexp))
14577 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14578 "[^\r\n]*"))
14579 (not (equal (match-string 1) org-clock-string)))
14580 (narrow-to-region (match-beginning 0) (match-end 0))
14581 (insert-before-markers "\n")
14582 (backward-char 1)
14583 (narrow-to-region (point) (point))
14584 (indent-to-column col))
14585 ;; Check if we have to remove something.
14586 (setq list (cons what remove))
14587 (while list
14588 (setq elt (pop list))
14589 (goto-char (point-min))
14590 (when (or (and (eq elt 'scheduled)
14591 (re-search-forward org-scheduled-time-regexp nil t))
14592 (and (eq elt 'deadline)
14593 (re-search-forward org-deadline-time-regexp nil t))
14594 (and (eq elt 'closed)
14595 (re-search-forward org-closed-time-regexp nil t)))
14596 (replace-match "")
14597 (if (looking-at "--+<[^>]+>") (replace-match ""))
14598 (if (looking-at " +") (replace-match ""))))
14599 (goto-char (point-max))
14600 (when what
14601 (insert
14602 (if (not (equal (char-before) ?\ )) " " "")
14603 (cond ((eq what 'scheduled) org-scheduled-string)
14604 ((eq what 'deadline) org-deadline-string)
14605 ((eq what 'closed) org-closed-string))
14606 " ")
14607 (setq ts (org-insert-time-stamp
14608 time
14609 (or org-time-was-given
14610 (and (eq what 'closed) org-log-done-with-time))
14611 (eq what 'closed)
14612 nil nil (list org-end-time-was-given)))
14613 (end-of-line 1))
14614 (goto-char (point-min))
14615 (widen)
14616 (if (looking-at "[ \t]+\r?\n")
14617 (replace-match ""))
14618 ts)))))
14620 (defvar org-log-note-marker (make-marker))
14621 (defvar org-log-note-purpose nil)
14622 (defvar org-log-note-state nil)
14623 (defvar org-log-note-window-configuration nil)
14624 (defvar org-log-note-return-to (make-marker))
14625 (defvar org-log-post-message nil
14626 "Message to be displayed after a log note has been stored.
14627 The auto-repeater uses this.")
14629 (defun org-add-log-maybe (&optional purpose state findpos)
14630 "Set up the post command hook to take a note."
14631 (save-excursion
14632 (when (and (listp org-log-done)
14633 (memq purpose org-log-done))
14634 (when findpos
14635 (org-back-to-heading t)
14636 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14637 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14638 "[^\r\n]*\\)?"))
14639 (goto-char (match-end 0))
14640 (unless org-log-states-order-reversed
14641 (and (= (char-after) ?\n) (forward-char 1))
14642 (org-skip-over-state-notes)
14643 (skip-chars-backward " \t\n\r")))
14644 (move-marker org-log-note-marker (point))
14645 (setq org-log-note-purpose purpose)
14646 (setq org-log-note-state state)
14647 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14649 (defun org-skip-over-state-notes ()
14650 "Skip past the list of State notes in an entry."
14651 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14652 (while (looking-at "[ \t]*- State")
14653 (condition-case nil
14654 (org-next-item)
14655 (error (org-end-of-item)))))
14657 (defun org-add-log-note (&optional purpose)
14658 "Pop up a window for taking a note, and add this note later at point."
14659 (remove-hook 'post-command-hook 'org-add-log-note)
14660 (setq org-log-note-window-configuration (current-window-configuration))
14661 (delete-other-windows)
14662 (move-marker org-log-note-return-to (point))
14663 (switch-to-buffer (marker-buffer org-log-note-marker))
14664 (goto-char org-log-note-marker)
14665 (org-switch-to-buffer-other-window "*Org Note*")
14666 (erase-buffer)
14667 (let ((org-inhibit-startup t)) (org-mode))
14668 (insert (format "# Insert note for %s.
14669 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14670 (cond
14671 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14672 ((eq org-log-note-purpose 'done) "closed todo item")
14673 ((eq org-log-note-purpose 'state)
14674 (format "state change to \"%s\"" org-log-note-state))
14675 (t (error "This should not happen")))))
14676 (org-set-local 'org-finish-function 'org-store-log-note))
14678 (defun org-store-log-note ()
14679 "Finish taking a log note, and insert it to where it belongs."
14680 (let ((txt (buffer-string))
14681 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14682 lines ind)
14683 (kill-buffer (current-buffer))
14684 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14685 (setq txt (replace-match "" t t txt)))
14686 (if (string-match "\\s-+\\'" txt)
14687 (setq txt (replace-match "" t t txt)))
14688 (setq lines (org-split-string txt "\n"))
14689 (when (and note (string-match "\\S-" note))
14690 (setq note
14691 (org-replace-escapes
14692 note
14693 (list (cons "%u" (user-login-name))
14694 (cons "%U" user-full-name)
14695 (cons "%t" (format-time-string
14696 (org-time-stamp-format 'long 'inactive)
14697 (current-time)))
14698 (cons "%s" (if org-log-note-state
14699 (concat "\"" org-log-note-state "\"")
14700 "")))))
14701 (if lines (setq note (concat note " \\\\")))
14702 (push note lines))
14703 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14704 (when lines
14705 (save-excursion
14706 (set-buffer (marker-buffer org-log-note-marker))
14707 (save-excursion
14708 (goto-char org-log-note-marker)
14709 (move-marker org-log-note-marker nil)
14710 (end-of-line 1)
14711 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14712 (indent-relative nil)
14713 (insert "- " (pop lines))
14714 (org-indent-line-function)
14715 (beginning-of-line 1)
14716 (looking-at "[ \t]*")
14717 (setq ind (concat (match-string 0) " "))
14718 (end-of-line 1)
14719 (while lines (insert "\n" ind (pop lines)))))))
14720 (set-window-configuration org-log-note-window-configuration)
14721 (with-current-buffer (marker-buffer org-log-note-return-to)
14722 (goto-char org-log-note-return-to))
14723 (move-marker org-log-note-return-to nil)
14724 (and org-log-post-message (message "%s" org-log-post-message)))
14726 ;; FIXME: what else would be useful?
14727 ;; - priority
14728 ;; - date
14730 (defun org-sparse-tree (&optional arg)
14731 "Create a sparse tree, prompt for the details.
14732 This command can create sparse trees. You first need to select the type
14733 of match used to create the tree:
14735 t Show entries with a specific TODO keyword.
14736 T Show entries selected by a tags match.
14737 p Enter a property name and its value (both with completion on existing
14738 names/values) and show entries with that property.
14739 r Show entries matching a regular expression
14740 d Show deadlines due within `org-deadline-warning-days'."
14741 (interactive "P")
14742 (let (ans kwd value)
14743 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
14744 (setq ans (read-char-exclusive))
14745 (cond
14746 ((equal ans ?d)
14747 (call-interactively 'org-check-deadlines))
14748 ((equal ans ?b)
14749 (call-interactively 'org-check-before-date))
14750 ((equal ans ?t)
14751 (org-show-todo-tree '(4)))
14752 ((equal ans ?T)
14753 (call-interactively 'org-tags-sparse-tree))
14754 ((member ans '(?p ?P))
14755 (setq kwd (completing-read "Property: "
14756 (mapcar 'list (org-buffer-property-keys))))
14757 (setq value (completing-read "Value: "
14758 (mapcar 'list (org-property-values kwd))))
14759 (unless (string-match "\\`{.*}\\'" value)
14760 (setq value (concat "\"" value "\"")))
14761 (org-tags-sparse-tree arg (concat kwd "=" value)))
14762 ((member ans '(?r ?R ?/))
14763 (call-interactively 'org-occur))
14764 (t (error "No such sparse tree command \"%c\"" ans)))))
14766 (defvar org-occur-highlights nil)
14767 (make-variable-buffer-local 'org-occur-highlights)
14769 (defun org-occur (regexp &optional keep-previous callback)
14770 "Make a compact tree which shows all matches of REGEXP.
14771 The tree will show the lines where the regexp matches, and all higher
14772 headlines above the match. It will also show the heading after the match,
14773 to make sure editing the matching entry is easy.
14774 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
14775 call to `org-occur' will be kept, to allow stacking of calls to this
14776 command.
14777 If CALLBACK is non-nil, it is a function which is called to confirm
14778 that the match should indeed be shown."
14779 (interactive "sRegexp: \nP")
14780 (or keep-previous (org-remove-occur-highlights nil nil t))
14781 (let ((cnt 0))
14782 (save-excursion
14783 (goto-char (point-min))
14784 (if (or (not keep-previous) ; do not want to keep
14785 (not org-occur-highlights)) ; no previous matches
14786 ;; hide everything
14787 (org-overview))
14788 (while (re-search-forward regexp nil t)
14789 (when (or (not callback)
14790 (save-match-data (funcall callback)))
14791 (setq cnt (1+ cnt))
14792 (when org-highlight-sparse-tree-matches
14793 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14794 (org-show-context 'occur-tree))))
14795 (when org-remove-highlights-with-change
14796 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
14797 nil 'local))
14798 (unless org-sparse-tree-open-archived-trees
14799 (org-hide-archived-subtrees (point-min) (point-max)))
14800 (run-hooks 'org-occur-hook)
14801 (if (interactive-p)
14802 (message "%d match(es) for regexp %s" cnt regexp))
14803 cnt))
14805 (defun org-show-context (&optional key)
14806 "Make sure point and context and visible.
14807 How much context is shown depends upon the variables
14808 `org-show-hierarchy-above', `org-show-following-heading'. and
14809 `org-show-siblings'."
14810 (let ((heading-p (org-on-heading-p t))
14811 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
14812 (following-p (org-get-alist-option org-show-following-heading key))
14813 (entry-p (org-get-alist-option org-show-entry-below key))
14814 (siblings-p (org-get-alist-option org-show-siblings key)))
14815 (catch 'exit
14816 ;; Show heading or entry text
14817 (if (and heading-p (not entry-p))
14818 (org-flag-heading nil) ; only show the heading
14819 (and (or entry-p (org-invisible-p) (org-invisible-p2))
14820 (org-show-hidden-entry))) ; show entire entry
14821 (when following-p
14822 ;; Show next sibling, or heading below text
14823 (save-excursion
14824 (and (if heading-p (org-goto-sibling) (outline-next-heading))
14825 (org-flag-heading nil))))
14826 (when siblings-p (org-show-siblings))
14827 (when hierarchy-p
14828 ;; show all higher headings, possibly with siblings
14829 (save-excursion
14830 (while (and (condition-case nil
14831 (progn (org-up-heading-all 1) t)
14832 (error nil))
14833 (not (bobp)))
14834 (org-flag-heading nil)
14835 (when siblings-p (org-show-siblings))))))))
14837 (defun org-reveal (&optional siblings)
14838 "Show current entry, hierarchy above it, and the following headline.
14839 This can be used to show a consistent set of context around locations
14840 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
14841 not t for the search context.
14843 With optional argument SIBLINGS, on each level of the hierarchy all
14844 siblings are shown. This repairs the tree structure to what it would
14845 look like when opened with hierarchical calls to `org-cycle'."
14846 (interactive "P")
14847 (let ((org-show-hierarchy-above t)
14848 (org-show-following-heading t)
14849 (org-show-siblings (if siblings t org-show-siblings)))
14850 (org-show-context nil)))
14852 (defun org-highlight-new-match (beg end)
14853 "Highlight from BEG to END and mark the highlight is an occur headline."
14854 (let ((ov (org-make-overlay beg end)))
14855 (org-overlay-put ov 'face 'secondary-selection)
14856 (push ov org-occur-highlights)))
14858 (defun org-remove-occur-highlights (&optional beg end noremove)
14859 "Remove the occur highlights from the buffer.
14860 BEG and END are ignored. If NOREMOVE is nil, remove this function
14861 from the `before-change-functions' in the current buffer."
14862 (interactive)
14863 (unless org-inhibit-highlight-removal
14864 (mapc 'org-delete-overlay org-occur-highlights)
14865 (setq org-occur-highlights nil)
14866 (unless noremove
14867 (remove-hook 'before-change-functions
14868 'org-remove-occur-highlights 'local))))
14870 ;;;; Priorities
14872 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14873 "Regular expression matching the priority indicator.")
14875 (defvar org-remove-priority-next-time nil)
14877 (defun org-priority-up ()
14878 "Increase the priority of the current item."
14879 (interactive)
14880 (org-priority 'up))
14882 (defun org-priority-down ()
14883 "Decrease the priority of the current item."
14884 (interactive)
14885 (org-priority 'down))
14887 (defun org-priority (&optional action)
14888 "Change the priority of an item by ARG.
14889 ACTION can be `set', `up', `down', or a character."
14890 (interactive)
14891 (setq action (or action 'set))
14892 (let (current new news have remove)
14893 (save-excursion
14894 (org-back-to-heading)
14895 (if (looking-at org-priority-regexp)
14896 (setq current (string-to-char (match-string 2))
14897 have t)
14898 (setq current org-default-priority))
14899 (cond
14900 ((or (eq action 'set) (integerp action))
14901 (if (integerp action)
14902 (setq new action)
14903 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
14904 (setq new (read-char-exclusive)))
14905 (if (and (= (upcase org-highest-priority) org-highest-priority)
14906 (= (upcase org-lowest-priority) org-lowest-priority))
14907 (setq new (upcase new)))
14908 (cond ((equal new ?\ ) (setq remove t))
14909 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14910 (error "Priority must be between `%c' and `%c'"
14911 org-highest-priority org-lowest-priority))))
14912 ((eq action 'up)
14913 (if (and (not have) (eq last-command this-command))
14914 (setq new org-lowest-priority)
14915 (setq new (if (and org-priority-start-cycle-with-default (not have))
14916 org-default-priority (1- current)))))
14917 ((eq action 'down)
14918 (if (and (not have) (eq last-command this-command))
14919 (setq new org-highest-priority)
14920 (setq new (if (and org-priority-start-cycle-with-default (not have))
14921 org-default-priority (1+ current)))))
14922 (t (error "Invalid action")))
14923 (if (or (< (upcase new) org-highest-priority)
14924 (> (upcase new) org-lowest-priority))
14925 (setq remove t))
14926 (setq news (format "%c" new))
14927 (if have
14928 (if remove
14929 (replace-match "" t t nil 1)
14930 (replace-match news t t nil 2))
14931 (if remove
14932 (error "No priority cookie found in line")
14933 (looking-at org-todo-line-regexp)
14934 (if (match-end 2)
14935 (progn
14936 (goto-char (match-end 2))
14937 (insert " [#" news "]"))
14938 (goto-char (match-beginning 3))
14939 (insert "[#" news "] ")))))
14940 (org-preserve-lc (org-set-tags nil 'align))
14941 (if remove
14942 (message "Priority removed")
14943 (message "Priority of current item set to %s" news))))
14946 (defun org-get-priority (s)
14947 "Find priority cookie and return priority."
14948 (save-match-data
14949 (if (not (string-match org-priority-regexp s))
14950 (* 1000 (- org-lowest-priority org-default-priority))
14951 (* 1000 (- org-lowest-priority
14952 (string-to-char (match-string 2 s)))))))
14954 ;;;; Tags
14956 (defun org-scan-tags (action matcher &optional todo-only)
14957 "Scan headline tags with inheritance and produce output ACTION.
14958 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
14959 evaluated, testing if a given set of tags qualifies a headline for
14960 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
14961 are included in the output."
14962 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
14963 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14964 (org-re
14965 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
14966 (props (list 'face nil
14967 'done-face 'org-done
14968 'undone-face nil
14969 'mouse-face 'highlight
14970 'org-not-done-regexp org-not-done-regexp
14971 'org-todo-regexp org-todo-regexp
14972 'keymap org-agenda-keymap
14973 'help-echo
14974 (format "mouse-2 or RET jump to org file %s"
14975 (abbreviate-file-name
14976 (or (buffer-file-name (buffer-base-buffer))
14977 (buffer-name (buffer-base-buffer)))))))
14978 (case-fold-search nil)
14979 lspos
14980 tags tags-list tags-alist (llast 0) rtn level category i txt
14981 todo marker entry priority)
14982 (save-excursion
14983 (goto-char (point-min))
14984 (when (eq action 'sparse-tree)
14985 (org-overview)
14986 (org-remove-occur-highlights))
14987 (while (re-search-forward re nil t)
14988 (catch :skip
14989 (setq todo (if (match-end 1) (match-string 2))
14990 tags (if (match-end 4) (match-string 4)))
14991 (goto-char (setq lspos (1+ (match-beginning 0))))
14992 (setq level (org-reduced-level (funcall outline-level))
14993 category (org-get-category))
14994 (setq i llast llast level)
14995 ;; remove tag lists from same and sublevels
14996 (while (>= i level)
14997 (when (setq entry (assoc i tags-alist))
14998 (setq tags-alist (delete entry tags-alist)))
14999 (setq i (1- i)))
15000 ;; add the nex tags
15001 (when tags
15002 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15003 tags-alist
15004 (cons (cons level tags) tags-alist)))
15005 ;; compile tags for current headline
15006 (setq tags-list
15007 (if org-use-tag-inheritance
15008 (apply 'append (mapcar 'cdr tags-alist))
15009 tags))
15010 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15011 (eval matcher)
15012 (or (not org-agenda-skip-archived-trees)
15013 (not (member org-archive-tag tags-list))))
15014 (and (eq action 'agenda) (org-agenda-skip))
15015 ;; list this headline
15017 (if (eq action 'sparse-tree)
15018 (progn
15019 (and org-highlight-sparse-tree-matches
15020 (org-get-heading) (match-end 0)
15021 (org-highlight-new-match
15022 (match-beginning 0) (match-beginning 1)))
15023 (org-show-context 'tags-tree))
15024 (setq txt (org-format-agenda-item
15026 (concat
15027 (if org-tags-match-list-sublevels
15028 (make-string (1- level) ?.) "")
15029 (org-get-heading))
15030 category tags-list)
15031 priority (org-get-priority txt))
15032 (goto-char lspos)
15033 (setq marker (org-agenda-new-marker))
15034 (org-add-props txt props
15035 'org-marker marker 'org-hd-marker marker 'org-category category
15036 'priority priority 'type "tagsmatch")
15037 (push txt rtn))
15038 ;; if we are to skip sublevels, jump to end of subtree
15039 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15040 (when (and (eq action 'sparse-tree)
15041 (not org-sparse-tree-open-archived-trees))
15042 (org-hide-archived-subtrees (point-min) (point-max)))
15043 (nreverse rtn)))
15045 (defvar todo-only) ;; dynamically scoped
15047 (defun org-tags-sparse-tree (&optional todo-only match)
15048 "Create a sparse tree according to tags string MATCH.
15049 MATCH can contain positive and negative selection of tags, like
15050 \"+WORK+URGENT-WITHBOSS\".
15051 If optional argument TODO_ONLY is non-nil, only select lines that are
15052 also TODO lines."
15053 (interactive "P")
15054 (org-prepare-agenda-buffers (list (current-buffer)))
15055 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15057 (defvar org-cached-props nil)
15058 (defun org-cached-entry-get (pom property)
15059 (if (or (eq t org-use-property-inheritance)
15060 (member property org-use-property-inheritance))
15061 ;; Caching is not possible, check it directly
15062 (org-entry-get pom property 'inherit)
15063 ;; Get all properties, so that we can do complicated checks easily
15064 (cdr (assoc property (or org-cached-props
15065 (setq org-cached-props
15066 (org-entry-properties pom)))))))
15068 (defun org-global-tags-completion-table (&optional files)
15069 "Return the list of all tags in all agenda buffer/files."
15070 (save-excursion
15071 (org-uniquify
15072 (apply 'append
15073 (mapcar
15074 (lambda (file)
15075 (set-buffer (find-file-noselect file))
15076 (org-get-buffer-tags))
15077 (if (and files (car files))
15078 files
15079 (org-agenda-files)))))))
15081 (defun org-make-tags-matcher (match)
15082 "Create the TAGS//TODO matcher form for the selection string MATCH."
15083 ;; todo-only is scoped dynamically into this function, and the function
15084 ;; may change it it the matcher asksk for it.
15085 (unless match
15086 ;; Get a new match request, with completion
15087 (let ((org-last-tags-completion-table
15088 (org-global-tags-completion-table)))
15089 (setq match (completing-read
15090 "Match: " 'org-tags-completion-function nil nil
15091 org-agenda-query-string
15092 'org-tags-history))))
15094 ;; Parse the string and create a lisp form
15095 (let ((match0 match)
15096 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
15097 minus tag mm
15098 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15099 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15100 (if (string-match "/+" match)
15101 ;; match contains also a todo-matching request
15102 (progn
15103 (setq tagsmatch (substring match 0 (match-beginning 0))
15104 todomatch (substring match (match-end 0)))
15105 (if (string-match "^!" todomatch)
15106 (setq todo-only t todomatch (substring todomatch 1)))
15107 (if (string-match "^\\s-*$" todomatch)
15108 (setq todomatch nil)))
15109 ;; only matching tags
15110 (setq tagsmatch match todomatch nil))
15112 ;; Make the tags matcher
15113 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15114 (setq tagsmatcher t)
15115 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15116 (while (setq term (pop orterms))
15117 (while (and (equal (substring term -1) "\\") orterms)
15118 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15119 (while (string-match re term)
15120 (setq minus (and (match-end 1)
15121 (equal (match-string 1 term) "-"))
15122 tag (match-string 2 term)
15123 re-p (equal (string-to-char tag) ?{)
15124 level-p (match-end 3)
15125 prop-p (match-end 4)
15126 mm (cond
15127 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15128 (level-p `(= level ,(string-to-number
15129 (match-string 3 term))))
15130 (prop-p
15131 (setq pn (match-string 4 term)
15132 pv (match-string 5 term)
15133 cat-p (equal pn "CATEGORY")
15134 re-p (equal (string-to-char pv) ?{)
15135 pv (substring pv 1 -1))
15136 (if (equal pn "CATEGORY")
15137 (setq gv '(get-text-property (point) 'org-category))
15138 (setq gv `(org-cached-entry-get nil ,pn)))
15139 (if re-p
15140 `(string-match ,pv (or ,gv ""))
15141 `(equal ,pv ,gv)))
15142 (t `(member ,(downcase tag) tags-list)))
15143 mm (if minus (list 'not mm) mm)
15144 term (substring term (match-end 0)))
15145 (push mm tagsmatcher))
15146 (push (if (> (length tagsmatcher) 1)
15147 (cons 'and tagsmatcher)
15148 (car tagsmatcher))
15149 orlist)
15150 (setq tagsmatcher nil))
15151 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15152 (setq tagsmatcher
15153 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15155 ;; Make the todo matcher
15156 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15157 (setq todomatcher t)
15158 (setq orterms (org-split-string todomatch "|") orlist nil)
15159 (while (setq term (pop orterms))
15160 (while (string-match re term)
15161 (setq minus (and (match-end 1)
15162 (equal (match-string 1 term) "-"))
15163 kwd (match-string 2 term)
15164 re-p (equal (string-to-char kwd) ?{)
15165 term (substring term (match-end 0))
15166 mm (if re-p
15167 `(string-match ,(substring kwd 1 -1) todo)
15168 (list 'equal 'todo kwd))
15169 mm (if minus (list 'not mm) mm))
15170 (push mm todomatcher))
15171 (push (if (> (length todomatcher) 1)
15172 (cons 'and todomatcher)
15173 (car todomatcher))
15174 orlist)
15175 (setq todomatcher nil))
15176 (setq todomatcher (if (> (length orlist) 1)
15177 (cons 'or orlist) (car orlist))))
15179 ;; Return the string and lisp forms of the matcher
15180 (setq matcher (if todomatcher
15181 (list 'and tagsmatcher todomatcher)
15182 tagsmatcher))
15183 (cons match0 matcher)))
15185 (defun org-match-any-p (re list)
15186 "Does re match any element of list?"
15187 (setq list (mapcar (lambda (x) (string-match re x)) list))
15188 (delq nil list))
15190 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15191 (defvar org-tags-overlay (org-make-overlay 1 1))
15192 (org-detach-overlay org-tags-overlay)
15194 (defun org-align-tags-here (to-col)
15195 ;; Assumes that this is a headline
15196 (let ((pos (point)) (col (current-column)) tags)
15197 (beginning-of-line 1)
15198 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15199 (< pos (match-beginning 2)))
15200 (progn
15201 (setq tags (match-string 2))
15202 (goto-char (match-beginning 1))
15203 (insert " ")
15204 (delete-region (point) (1+ (match-end 0)))
15205 (backward-char 1)
15206 (move-to-column
15207 (max (1+ (current-column))
15208 (1+ col)
15209 (if (> to-col 0)
15210 to-col
15211 (- (abs to-col) (length tags))))
15213 (insert tags)
15214 (move-to-column (min (current-column) col) t))
15215 (goto-char pos))))
15217 (defun org-set-tags (&optional arg just-align)
15218 "Set the tags for the current headline.
15219 With prefix ARG, realign all tags in headings in the current buffer."
15220 (interactive "P")
15221 (let* ((re (concat "^" outline-regexp))
15222 (current (org-get-tags-string))
15223 (col (current-column))
15224 (org-setting-tags t)
15225 table current-tags inherited-tags ; computed below when needed
15226 tags p0 c0 c1 rpl)
15227 (if arg
15228 (save-excursion
15229 (goto-char (point-min))
15230 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15231 (while (re-search-forward re nil t)
15232 (org-set-tags nil t)
15233 (end-of-line 1)))
15234 (message "All tags realigned to column %d" org-tags-column))
15235 (if just-align
15236 (setq tags current)
15237 ;; Get a new set of tags from the user
15238 (save-excursion
15239 (setq table (or org-tag-alist (org-get-buffer-tags))
15240 org-last-tags-completion-table table
15241 current-tags (org-split-string current ":")
15242 inherited-tags (nreverse
15243 (nthcdr (length current-tags)
15244 (nreverse (org-get-tags-at))))
15245 tags
15246 (if (or (eq t org-use-fast-tag-selection)
15247 (and org-use-fast-tag-selection
15248 (delq nil (mapcar 'cdr table))))
15249 (org-fast-tag-selection
15250 current-tags inherited-tags table
15251 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15252 (let ((org-add-colon-after-tag-completion t))
15253 (org-trim
15254 (org-without-partial-completion
15255 (completing-read "Tags: " 'org-tags-completion-function
15256 nil nil current 'org-tags-history)))))))
15257 (while (string-match "[-+&]+" tags)
15258 ;; No boolean logic, just a list
15259 (setq tags (replace-match ":" t t tags))))
15261 (if (string-match "\\`[\t ]*\\'" tags)
15262 (setq tags "")
15263 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15264 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15266 ;; Insert new tags at the correct column
15267 (beginning-of-line 1)
15268 (cond
15269 ((and (equal current "") (equal tags "")))
15270 ((re-search-forward
15271 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15272 (point-at-eol) t)
15273 (if (equal tags "")
15274 (setq rpl "")
15275 (goto-char (match-beginning 0))
15276 (setq c0 (current-column) p0 (point)
15277 c1 (max (1+ c0) (if (> org-tags-column 0)
15278 org-tags-column
15279 (- (- org-tags-column) (length tags))))
15280 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15281 (replace-match rpl t t)
15282 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
15283 tags)
15284 (t (error "Tags alignment failed")))
15285 (move-to-column col)
15286 (unless just-align
15287 (run-hooks 'org-after-tags-change-hook)))))
15289 (defun org-change-tag-in-region (beg end tag off)
15290 "Add or remove TAG for each entry in the region.
15291 This works in the agenda, and also in an org-mode buffer."
15292 (interactive
15293 (list (region-beginning) (region-end)
15294 (let ((org-last-tags-completion-table
15295 (if (org-mode-p)
15296 (org-get-buffer-tags)
15297 (org-global-tags-completion-table))))
15298 (completing-read
15299 "Tag: " 'org-tags-completion-function nil nil nil
15300 'org-tags-history))
15301 (progn
15302 (message "[s]et or [r]emove? ")
15303 (equal (read-char-exclusive) ?r))))
15304 (if (fboundp 'deactivate-mark) (deactivate-mark))
15305 (let ((agendap (equal major-mode 'org-agenda-mode))
15306 l1 l2 m buf pos newhead (cnt 0))
15307 (goto-char end)
15308 (setq l2 (1- (org-current-line)))
15309 (goto-char beg)
15310 (setq l1 (org-current-line))
15311 (loop for l from l1 to l2 do
15312 (goto-line l)
15313 (setq m (get-text-property (point) 'org-hd-marker))
15314 (when (or (and (org-mode-p) (org-on-heading-p))
15315 (and agendap m))
15316 (setq buf (if agendap (marker-buffer m) (current-buffer))
15317 pos (if agendap m (point)))
15318 (with-current-buffer buf
15319 (save-excursion
15320 (save-restriction
15321 (goto-char pos)
15322 (setq cnt (1+ cnt))
15323 (org-toggle-tag tag (if off 'off 'on))
15324 (setq newhead (org-get-heading)))))
15325 (and agendap (org-agenda-change-all-lines newhead m))))
15326 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15328 (defun org-tags-completion-function (string predicate &optional flag)
15329 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15330 (confirm (lambda (x) (stringp (car x)))))
15331 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15332 (setq s1 (match-string 1 string)
15333 s2 (match-string 2 string))
15334 (setq s1 "" s2 string))
15335 (cond
15336 ((eq flag nil)
15337 ;; try completion
15338 (setq rtn (try-completion s2 ctable confirm))
15339 (if (stringp rtn)
15340 (setq rtn
15341 (concat s1 s2 (substring rtn (length s2))
15342 (if (and org-add-colon-after-tag-completion
15343 (assoc rtn ctable))
15344 ":" ""))))
15345 rtn)
15346 ((eq flag t)
15347 ;; all-completions
15348 (all-completions s2 ctable confirm)
15350 ((eq flag 'lambda)
15351 ;; exact match?
15352 (assoc s2 ctable)))
15355 (defun org-fast-tag-insert (kwd tags face &optional end)
15356 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15357 (insert (format "%-12s" (concat kwd ":"))
15358 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15359 (or end "")))
15361 (defun org-fast-tag-show-exit (flag)
15362 (save-excursion
15363 (goto-line 3)
15364 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15365 (replace-match ""))
15366 (when flag
15367 (end-of-line 1)
15368 (move-to-column (- (window-width) 19) t)
15369 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15371 (defun org-set-current-tags-overlay (current prefix)
15372 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15373 (if (featurep 'xemacs)
15374 (org-overlay-display org-tags-overlay (concat prefix s)
15375 'secondary-selection)
15376 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15377 (org-overlay-display org-tags-overlay (concat prefix s)))))
15379 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15380 "Fast tag selection with single keys.
15381 CURRENT is the current list of tags in the headline, INHERITED is the
15382 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15383 possibly with grouping information. TODO-TABLE is a similar table with
15384 TODO keywords, should these have keys assigned to them.
15385 If the keys are nil, a-z are automatically assigned.
15386 Returns the new tags string, or nil to not change the current settings."
15387 (let* ((fulltable (append table todo-table))
15388 (maxlen (apply 'max (mapcar
15389 (lambda (x)
15390 (if (stringp (car x)) (string-width (car x)) 0))
15391 fulltable)))
15392 (buf (current-buffer))
15393 (expert (eq org-fast-tag-selection-single-key 'expert))
15394 (buffer-tags nil)
15395 (fwidth (+ maxlen 3 1 3))
15396 (ncol (/ (- (window-width) 4) fwidth))
15397 (i-face 'org-done)
15398 (c-face 'org-todo)
15399 tg cnt e c char c1 c2 ntable tbl rtn
15400 ov-start ov-end ov-prefix
15401 (exit-after-next org-fast-tag-selection-single-key)
15402 (done-keywords org-done-keywords)
15403 groups ingroup)
15404 (save-excursion
15405 (beginning-of-line 1)
15406 (if (looking-at
15407 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15408 (setq ov-start (match-beginning 1)
15409 ov-end (match-end 1)
15410 ov-prefix "")
15411 (setq ov-start (1- (point-at-eol))
15412 ov-end (1+ ov-start))
15413 (skip-chars-forward "^\n\r")
15414 (setq ov-prefix
15415 (concat
15416 (buffer-substring (1- (point)) (point))
15417 (if (> (current-column) org-tags-column)
15419 (make-string (- org-tags-column (current-column)) ?\ ))))))
15420 (org-move-overlay org-tags-overlay ov-start ov-end)
15421 (save-window-excursion
15422 (if expert
15423 (set-buffer (get-buffer-create " *Org tags*"))
15424 (delete-other-windows)
15425 (split-window-vertically)
15426 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15427 (erase-buffer)
15428 (org-set-local 'org-done-keywords done-keywords)
15429 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15430 (org-fast-tag-insert "Current" current c-face "\n\n")
15431 (org-fast-tag-show-exit exit-after-next)
15432 (org-set-current-tags-overlay current ov-prefix)
15433 (setq tbl fulltable char ?a cnt 0)
15434 (while (setq e (pop tbl))
15435 (cond
15436 ((equal e '(:startgroup))
15437 (push '() groups) (setq ingroup t)
15438 (when (not (= cnt 0))
15439 (setq cnt 0)
15440 (insert "\n"))
15441 (insert "{ "))
15442 ((equal e '(:endgroup))
15443 (setq ingroup nil cnt 0)
15444 (insert "}\n"))
15446 (setq tg (car e) c2 nil)
15447 (if (cdr e)
15448 (setq c (cdr e))
15449 ;; automatically assign a character.
15450 (setq c1 (string-to-char
15451 (downcase (substring
15452 tg (if (= (string-to-char tg) ?@) 1 0)))))
15453 (if (or (rassoc c1 ntable) (rassoc c1 table))
15454 (while (or (rassoc char ntable) (rassoc char table))
15455 (setq char (1+ char)))
15456 (setq c2 c1))
15457 (setq c (or c2 char)))
15458 (if ingroup (push tg (car groups)))
15459 (setq tg (org-add-props tg nil 'face
15460 (cond
15461 ((not (assoc tg table))
15462 (org-get-todo-face tg))
15463 ((member tg current) c-face)
15464 ((member tg inherited) i-face)
15465 (t nil))))
15466 (if (and (= cnt 0) (not ingroup)) (insert " "))
15467 (insert "[" c "] " tg (make-string
15468 (- fwidth 4 (length tg)) ?\ ))
15469 (push (cons tg c) ntable)
15470 (when (= (setq cnt (1+ cnt)) ncol)
15471 (insert "\n")
15472 (if ingroup (insert " "))
15473 (setq cnt 0)))))
15474 (setq ntable (nreverse ntable))
15475 (insert "\n")
15476 (goto-char (point-min))
15477 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15478 (fit-window-to-buffer))
15479 (setq rtn
15480 (catch 'exit
15481 (while t
15482 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15483 (if groups " [!] no groups" " [!]groups")
15484 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15485 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15486 (cond
15487 ((= c ?\r) (throw 'exit t))
15488 ((= c ?!)
15489 (setq groups (not groups))
15490 (goto-char (point-min))
15491 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15492 ((= c ?\C-c)
15493 (if (not expert)
15494 (org-fast-tag-show-exit
15495 (setq exit-after-next (not exit-after-next)))
15496 (setq expert nil)
15497 (delete-other-windows)
15498 (split-window-vertically)
15499 (org-switch-to-buffer-other-window " *Org tags*")
15500 (and (fboundp 'fit-window-to-buffer)
15501 (fit-window-to-buffer))))
15502 ((or (= c ?\C-g)
15503 (and (= c ?q) (not (rassoc c ntable))))
15504 (org-detach-overlay org-tags-overlay)
15505 (setq quit-flag t))
15506 ((= c ?\ )
15507 (setq current nil)
15508 (if exit-after-next (setq exit-after-next 'now)))
15509 ((= c ?\t)
15510 (condition-case nil
15511 (setq tg (completing-read
15512 "Tag: "
15513 (or buffer-tags
15514 (with-current-buffer buf
15515 (org-get-buffer-tags)))))
15516 (quit (setq tg "")))
15517 (when (string-match "\\S-" tg)
15518 (add-to-list 'buffer-tags (list tg))
15519 (if (member tg current)
15520 (setq current (delete tg current))
15521 (push tg current)))
15522 (if exit-after-next (setq exit-after-next 'now)))
15523 ((setq e (rassoc c todo-table) tg (car e))
15524 (with-current-buffer buf
15525 (save-excursion (org-todo tg)))
15526 (if exit-after-next (setq exit-after-next 'now)))
15527 ((setq e (rassoc c ntable) tg (car e))
15528 (if (member tg current)
15529 (setq current (delete tg current))
15530 (loop for g in groups do
15531 (if (member tg g)
15532 (mapc (lambda (x)
15533 (setq current (delete x current)))
15534 g)))
15535 (push tg current))
15536 (if exit-after-next (setq exit-after-next 'now))))
15538 ;; Create a sorted list
15539 (setq current
15540 (sort current
15541 (lambda (a b)
15542 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15543 (if (eq exit-after-next 'now) (throw 'exit t))
15544 (goto-char (point-min))
15545 (beginning-of-line 2)
15546 (delete-region (point) (point-at-eol))
15547 (org-fast-tag-insert "Current" current c-face)
15548 (org-set-current-tags-overlay current ov-prefix)
15549 (while (re-search-forward
15550 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15551 (setq tg (match-string 1))
15552 (add-text-properties
15553 (match-beginning 1) (match-end 1)
15554 (list 'face
15555 (cond
15556 ((member tg current) c-face)
15557 ((member tg inherited) i-face)
15558 (t (get-text-property (match-beginning 1) 'face))))))
15559 (goto-char (point-min)))))
15560 (org-detach-overlay org-tags-overlay)
15561 (if rtn
15562 (mapconcat 'identity current ":")
15563 nil))))
15565 (defun org-get-tags-string ()
15566 "Get the TAGS string in the current headline."
15567 (unless (org-on-heading-p t)
15568 (error "Not on a heading"))
15569 (save-excursion
15570 (beginning-of-line 1)
15571 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15572 (org-match-string-no-properties 1)
15573 "")))
15575 (defun org-get-tags ()
15576 "Get the list of tags specified in the current headline."
15577 (org-split-string (org-get-tags-string) ":"))
15579 (defun org-get-buffer-tags ()
15580 "Get a table of all tags used in the buffer, for completion."
15581 (let (tags)
15582 (save-excursion
15583 (goto-char (point-min))
15584 (while (re-search-forward
15585 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15586 (when (equal (char-after (point-at-bol 0)) ?*)
15587 (mapc (lambda (x) (add-to-list 'tags x))
15588 (org-split-string (org-match-string-no-properties 1) ":")))))
15589 (mapcar 'list tags)))
15592 ;;;; Properties
15594 ;;; Setting and retrieving properties
15596 (defconst org-special-properties
15597 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15598 "TIMESTAMP" "TIMESTAMP_IA")
15599 "The special properties valid in Org-mode.
15601 These are properties that are not defined in the property drawer,
15602 but in some other way.")
15604 (defconst org-default-properties
15605 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15606 "LOCATION" "LOGGING" "COLUMNS")
15607 "Some properties that are used by Org-mode for various purposes.
15608 Being in this list makes sure that they are offered for completion.")
15610 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15611 "Regular expression matching the first line of a property drawer.")
15613 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15614 "Regular expression matching the first line of a property drawer.")
15616 (defun org-property-action ()
15617 "Do an action on properties."
15618 (interactive)
15619 (let (c)
15620 (org-at-property-p)
15621 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15622 (setq c (read-char-exclusive))
15623 (cond
15624 ((equal c ?s)
15625 (call-interactively 'org-set-property))
15626 ((equal c ?d)
15627 (call-interactively 'org-delete-property))
15628 ((equal c ?D)
15629 (call-interactively 'org-delete-property-globally))
15630 ((equal c ?c)
15631 (call-interactively 'org-compute-property-at-point))
15632 (t (error "No such property action %c" c)))))
15634 (defun org-at-property-p ()
15635 "Is the cursor in a property line?"
15636 ;; FIXME: Does not check if we are actually in the drawer.
15637 ;; FIXME: also returns true on any drawers.....
15638 ;; This is used by C-c C-c for property action.
15639 (save-excursion
15640 (beginning-of-line 1)
15641 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15643 (defmacro org-with-point-at (pom &rest body)
15644 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15645 (declare (indent 1) (debug t))
15646 `(save-excursion
15647 (if (markerp pom) (set-buffer (marker-buffer pom)))
15648 (save-excursion
15649 (goto-char (or pom (point)))
15650 ,@body)))
15652 (defun org-get-property-block (&optional beg end force)
15653 "Return the (beg . end) range of the body of the property drawer.
15654 BEG and END can be beginning and end of subtree, if not given
15655 they will be found.
15656 If the drawer does not exist and FORCE is non-nil, create the drawer."
15657 (catch 'exit
15658 (save-excursion
15659 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15660 (end (or end (progn (outline-next-heading) (point)))))
15661 (goto-char beg)
15662 (if (re-search-forward org-property-start-re end t)
15663 (setq beg (1+ (match-end 0)))
15664 (if force
15665 (save-excursion
15666 (org-insert-property-drawer)
15667 (setq end (progn (outline-next-heading) (point))))
15668 (throw 'exit nil))
15669 (goto-char beg)
15670 (if (re-search-forward org-property-start-re end t)
15671 (setq beg (1+ (match-end 0)))))
15672 (if (re-search-forward org-property-end-re end t)
15673 (setq end (match-beginning 0))
15674 (or force (throw 'exit nil))
15675 (goto-char beg)
15676 (setq end beg)
15677 (org-indent-line-function)
15678 (insert ":END:\n"))
15679 (cons beg end)))))
15681 (defun org-entry-properties (&optional pom which)
15682 "Get all properties of the entry at point-or-marker POM.
15683 This includes the TODO keyword, the tags, time strings for deadline,
15684 scheduled, and clocking, and any additional properties defined in the
15685 entry. The return value is an alist, keys may occur multiple times
15686 if the property key was used several times.
15687 POM may also be nil, in which case the current entry is used.
15688 If WHICH is nil or `all', get all properties. If WHICH is
15689 `special' or `standard', only get that subclass."
15690 (setq which (or which 'all))
15691 (org-with-point-at pom
15692 (let ((clockstr (substring org-clock-string 0 -1))
15693 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15694 beg end range props sum-props key value string)
15695 (save-excursion
15696 (when (condition-case nil (org-back-to-heading t) (error nil))
15697 (setq beg (point))
15698 (setq sum-props (get-text-property (point) 'org-summaries))
15699 (outline-next-heading)
15700 (setq end (point))
15701 (when (memq which '(all special))
15702 ;; Get the special properties, like TODO and tags
15703 (goto-char beg)
15704 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15705 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15706 (when (looking-at org-priority-regexp)
15707 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15708 (when (and (setq value (org-get-tags-string))
15709 (string-match "\\S-" value))
15710 (push (cons "TAGS" value) props))
15711 (when (setq value (org-get-tags-at))
15712 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15713 props))
15714 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15715 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15716 string (if (equal key clockstr)
15717 (org-no-properties
15718 (org-trim
15719 (buffer-substring
15720 (match-beginning 3) (goto-char (point-at-eol)))))
15721 (substring (org-match-string-no-properties 3) 1 -1)))
15722 (unless key
15723 (if (= (char-after (match-beginning 3)) ?\[)
15724 (setq key "TIMESTAMP_IA")
15725 (setq key "TIMESTAMP")))
15726 (when (or (equal key clockstr) (not (assoc key props)))
15727 (push (cons key string) props)))
15731 (when (memq which '(all standard))
15732 ;; Get the standard properties, like :PORP: ...
15733 (setq range (org-get-property-block beg end))
15734 (when range
15735 (goto-char (car range))
15736 (while (re-search-forward
15737 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15738 (cdr range) t)
15739 (setq key (org-match-string-no-properties 1)
15740 value (org-trim (or (org-match-string-no-properties 2) "")))
15741 (unless (member key excluded)
15742 (push (cons key (or value "")) props)))))
15743 (append sum-props (nreverse props)))))))
15745 (defun org-entry-get (pom property &optional inherit)
15746 "Get value of PROPERTY for entry at point-or-marker POM.
15747 If INHERIT is non-nil and the entry does not have the property,
15748 then also check higher levels of the hierarchy.
15749 If the property is present but empty, the return value is the empty string.
15750 If the property is not present at all, nil is returned."
15751 (org-with-point-at pom
15752 (if inherit
15753 (org-entry-get-with-inheritance property)
15754 (if (member property org-special-properties)
15755 ;; We need a special property. Use brute force, get all properties.
15756 (cdr (assoc property (org-entry-properties nil 'special)))
15757 (let ((range (org-get-property-block)))
15758 (if (and range
15759 (goto-char (car range))
15760 (re-search-forward
15761 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
15762 (cdr range) t))
15763 ;; Found the property, return it.
15764 (if (match-end 1)
15765 (org-match-string-no-properties 1)
15766 "")))))))
15768 (defun org-entry-delete (pom property)
15769 "Delete the property PROPERTY from entry at point-or-marker POM."
15770 (org-with-point-at pom
15771 (if (member property org-special-properties)
15772 nil ; cannot delete these properties.
15773 (let ((range (org-get-property-block)))
15774 (if (and range
15775 (goto-char (car range))
15776 (re-search-forward
15777 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
15778 (cdr range) t))
15779 (progn
15780 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15782 nil)))))
15784 ;; Multi-values properties are properties that contain multiple values
15785 ;; These values are assumed to be single words, separated by whitespace.
15786 (defun org-entry-add-to-multivalued-property (pom property value)
15787 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15788 (let* ((old (org-entry-get pom property))
15789 (values (and old (org-split-string old "[ \t]"))))
15790 (unless (member value values)
15791 (setq values (cons value values))
15792 (org-entry-put pom property
15793 (mapconcat 'identity values " ")))))
15795 (defun org-entry-remove-from-multivalued-property (pom property value)
15796 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15797 (let* ((old (org-entry-get pom property))
15798 (values (and old (org-split-string old "[ \t]"))))
15799 (when (member value values)
15800 (setq values (delete value values))
15801 (org-entry-put pom property
15802 (mapconcat 'identity values " ")))))
15804 (defun org-entry-member-in-multivalued-property (pom property value)
15805 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15806 (let* ((old (org-entry-get pom property))
15807 (values (and old (org-split-string old "[ \t]"))))
15808 (member value values)))
15810 (defvar org-entry-property-inherited-from (make-marker))
15812 (defun org-entry-get-with-inheritance (property)
15813 "Get entry property, and search higher levels if not present."
15814 (let (tmp)
15815 (save-excursion
15816 (save-restriction
15817 (widen)
15818 (catch 'ex
15819 (while t
15820 (when (setq tmp (org-entry-get nil property))
15821 (org-back-to-heading t)
15822 (move-marker org-entry-property-inherited-from (point))
15823 (throw 'ex tmp))
15824 (or (org-up-heading-safe) (throw 'ex nil)))))
15825 (or tmp (cdr (assoc property org-local-properties))
15826 (cdr (assoc property org-global-properties))))))
15828 (defun org-entry-put (pom property value)
15829 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15830 (org-with-point-at pom
15831 (org-back-to-heading t)
15832 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15833 range)
15834 (cond
15835 ((equal property "TODO")
15836 (when (and (stringp value) (string-match "\\S-" value)
15837 (not (member value org-todo-keywords-1)))
15838 (error "\"%s\" is not a valid TODO state" value))
15839 (if (or (not value)
15840 (not (string-match "\\S-" value)))
15841 (setq value 'none))
15842 (org-todo value)
15843 (org-set-tags nil 'align))
15844 ((equal property "PRIORITY")
15845 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15846 (string-to-char value) ?\ ))
15847 (org-set-tags nil 'align))
15848 ((equal property "SCHEDULED")
15849 (if (re-search-forward org-scheduled-time-regexp end t)
15850 (cond
15851 ((eq value 'earlier) (org-timestamp-change -1 'day))
15852 ((eq value 'later) (org-timestamp-change 1 'day))
15853 (t (call-interactively 'org-schedule)))
15854 (call-interactively 'org-schedule)))
15855 ((equal property "DEADLINE")
15856 (if (re-search-forward org-deadline-time-regexp end t)
15857 (cond
15858 ((eq value 'earlier) (org-timestamp-change -1 'day))
15859 ((eq value 'later) (org-timestamp-change 1 'day))
15860 (t (call-interactively 'org-deadline)))
15861 (call-interactively 'org-deadline)))
15862 ((member property org-special-properties)
15863 (error "The %s property can not yet be set with `org-entry-put'"
15864 property))
15865 (t ; a non-special property
15866 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15867 (setq range (org-get-property-block beg end 'force))
15868 (goto-char (car range))
15869 (if (re-search-forward
15870 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
15871 (progn
15872 (delete-region (match-beginning 1) (match-end 1))
15873 (goto-char (match-beginning 1)))
15874 (goto-char (cdr range))
15875 (insert "\n")
15876 (backward-char 1)
15877 (org-indent-line-function)
15878 (insert ":" property ":"))
15879 (and value (insert " " value))
15880 (org-indent-line-function)))))))
15882 (defun org-buffer-property-keys (&optional include-specials include-defaults)
15883 "Get all property keys in the current buffer.
15884 With INCLUDE-SPECIALS, also list the special properties that relect things
15885 like tags and TODO state.
15886 With INCLUDE-DEFAULTS, also include properties that has special meaning
15887 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
15888 (let (rtn range)
15889 (save-excursion
15890 (save-restriction
15891 (widen)
15892 (goto-char (point-min))
15893 (while (re-search-forward org-property-start-re nil t)
15894 (setq range (org-get-property-block))
15895 (goto-char (car range))
15896 (while (re-search-forward
15897 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
15898 (cdr range) t)
15899 (add-to-list 'rtn (org-match-string-no-properties 1)))
15900 (outline-next-heading))))
15902 (when include-specials
15903 (setq rtn (append org-special-properties rtn)))
15905 (when include-defaults
15906 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
15908 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15910 (defun org-property-values (key)
15911 "Return a list of all values of property KEY."
15912 (save-excursion
15913 (save-restriction
15914 (widen)
15915 (goto-char (point-min))
15916 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
15917 values)
15918 (while (re-search-forward re nil t)
15919 (add-to-list 'values (org-trim (match-string 1))))
15920 (delete "" values)))))
15922 (defun org-insert-property-drawer ()
15923 "Insert a property drawer into the current entry."
15924 (interactive)
15925 (org-back-to-heading t)
15926 (looking-at outline-regexp)
15927 (let ((indent (- (match-end 0)(match-beginning 0)))
15928 (beg (point))
15929 (re (concat "^[ \t]*" org-keyword-time-regexp))
15930 end hiddenp)
15931 (outline-next-heading)
15932 (setq end (point))
15933 (goto-char beg)
15934 (while (re-search-forward re end t))
15935 (setq hiddenp (org-invisible-p))
15936 (end-of-line 1)
15937 (and (equal (char-after) ?\n) (forward-char 1))
15938 (org-skip-over-state-notes)
15939 (skip-chars-backward " \t\n\r")
15940 (if (eq (char-before) ?*) (forward-char 1))
15941 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15942 (beginning-of-line 0)
15943 (indent-to-column indent)
15944 (beginning-of-line 2)
15945 (indent-to-column indent)
15946 (beginning-of-line 0)
15947 (if hiddenp
15948 (save-excursion
15949 (org-back-to-heading t)
15950 (hide-entry))
15951 (org-flag-drawer t))))
15953 (defun org-set-property (property value)
15954 "In the current entry, set PROPERTY to VALUE.
15955 When called interactively, this will prompt for a property name, offering
15956 completion on existing and default properties. And then it will prompt
15957 for a value, offering competion either on allowed values (via an inherited
15958 xxx_ALL property) or on existing values in other instances of this property
15959 in the current file."
15960 (interactive
15961 (let* ((prop (completing-read
15962 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
15963 (cur (org-entry-get nil prop))
15964 (allowed (org-property-get-allowed-values nil prop 'table))
15965 (existing (mapcar 'list (org-property-values prop)))
15966 (val (if allowed
15967 (completing-read "Value: " allowed nil 'req-match)
15968 (completing-read
15969 (concat "Value" (if (and cur (string-match "\\S-" cur))
15970 (concat "[" cur "]") "")
15971 ": ")
15972 existing nil nil "" nil cur))))
15973 (list prop (if (equal val "") cur val))))
15974 (unless (equal (org-entry-get nil property) value)
15975 (org-entry-put nil property value)))
15977 (defun org-delete-property (property)
15978 "In the current entry, delete PROPERTY."
15979 (interactive
15980 (let* ((prop (completing-read
15981 "Property: " (org-entry-properties nil 'standard))))
15982 (list prop)))
15983 (message "Property %s %s" property
15984 (if (org-entry-delete nil property)
15985 "deleted"
15986 "was not present in the entry")))
15988 (defun org-delete-property-globally (property)
15989 "Remove PROPERTY globally, from all entries."
15990 (interactive
15991 (let* ((prop (completing-read
15992 "Globally remove property: "
15993 (mapcar 'list (org-buffer-property-keys)))))
15994 (list prop)))
15995 (save-excursion
15996 (save-restriction
15997 (widen)
15998 (goto-char (point-min))
15999 (let ((cnt 0))
16000 (while (re-search-forward
16001 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16002 nil t)
16003 (setq cnt (1+ cnt))
16004 (replace-match ""))
16005 (message "Property \"%s\" removed from %d entries" property cnt)))))
16007 (defvar org-columns-current-fmt-compiled) ; defined below
16009 (defun org-compute-property-at-point ()
16010 "Compute the property at point.
16011 This looks for an enclosing column format, extracts the operator and
16012 then applies it to the proerty in the column format's scope."
16013 (interactive)
16014 (unless (org-at-property-p)
16015 (error "Not at a property"))
16016 (let ((prop (org-match-string-no-properties 2)))
16017 (org-columns-get-format-and-top-level)
16018 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16019 (error "No operator defined for property %s" prop))
16020 (org-columns-compute prop)))
16022 (defun org-property-get-allowed-values (pom property &optional table)
16023 "Get allowed values for the property PROPERTY.
16024 When TABLE is non-nil, return an alist that can directly be used for
16025 completion."
16026 (let (vals)
16027 (cond
16028 ((equal property "TODO")
16029 (setq vals (org-with-point-at pom
16030 (append org-todo-keywords-1 '("")))))
16031 ((equal property "PRIORITY")
16032 (let ((n org-lowest-priority))
16033 (while (>= n org-highest-priority)
16034 (push (char-to-string n) vals)
16035 (setq n (1- n)))))
16036 ((member property org-special-properties))
16038 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16040 (when (and vals (string-match "\\S-" vals))
16041 (setq vals (car (read-from-string (concat "(" vals ")"))))
16042 (setq vals (mapcar (lambda (x)
16043 (cond ((stringp x) x)
16044 ((numberp x) (number-to-string x))
16045 ((symbolp x) (symbol-name x))
16046 (t "???")))
16047 vals)))))
16048 (if table (mapcar 'list vals) vals)))
16050 (defun org-property-previous-allowed-value (&optional previous)
16051 "Switch to the next allowed value for this property."
16052 (interactive)
16053 (org-property-next-allowed-value t))
16055 (defun org-property-next-allowed-value (&optional previous)
16056 "Switch to the next allowed value for this property."
16057 (interactive)
16058 (unless (org-at-property-p)
16059 (error "Not at a property"))
16060 (let* ((key (match-string 2))
16061 (value (match-string 3))
16062 (allowed (or (org-property-get-allowed-values (point) key)
16063 (and (member value '("[ ]" "[-]" "[X]"))
16064 '("[ ]" "[X]"))))
16065 nval)
16066 (unless allowed
16067 (error "Allowed values for this property have not been defined"))
16068 (if previous (setq allowed (reverse allowed)))
16069 (if (member value allowed)
16070 (setq nval (car (cdr (member value allowed)))))
16071 (setq nval (or nval (car allowed)))
16072 (if (equal nval value)
16073 (error "Only one allowed value for this property"))
16074 (org-at-property-p)
16075 (replace-match (concat " :" key ": " nval) t t)
16076 (org-indent-line-function)
16077 (beginning-of-line 1)
16078 (skip-chars-forward " \t")))
16080 (defun org-find-entry-with-id (ident)
16081 "Locate the entry that contains the ID property with exact value IDENT.
16082 IDENT can be a string, a symbol or a number, this function will search for
16083 the string representation of it.
16084 Return the position where this entry starts, or nil if there is no such entry."
16085 (let ((id (cond
16086 ((stringp ident) ident)
16087 ((symbol-name ident) (symbol-name ident))
16088 ((numberp ident) (number-to-string ident))
16089 (t (error "IDENT %s must be a string, symbol or number" ident))))
16090 (case-fold-search nil))
16091 (save-excursion
16092 (save-restriction
16093 (goto-char (point-min))
16094 (when (re-search-forward
16095 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16096 nil t)
16097 (org-back-to-heading)
16098 (point))))))
16100 ;;; Column View
16102 (defvar org-columns-overlays nil
16103 "Holds the list of current column overlays.")
16105 (defvar org-columns-current-fmt nil
16106 "Local variable, holds the currently active column format.")
16107 (defvar org-columns-current-fmt-compiled nil
16108 "Local variable, holds the currently active column format.
16109 This is the compiled version of the format.")
16110 (defvar org-columns-current-widths nil
16111 "Loval variable, holds the currently widths of fields.")
16112 (defvar org-columns-current-maxwidths nil
16113 "Loval variable, holds the currently active maximum column widths.")
16114 (defvar org-columns-begin-marker (make-marker)
16115 "Points to the position where last a column creation command was called.")
16116 (defvar org-columns-top-level-marker (make-marker)
16117 "Points to the position where current columns region starts.")
16119 (defvar org-columns-map (make-sparse-keymap)
16120 "The keymap valid in column display.")
16122 (defun org-columns-content ()
16123 "Switch to contents view while in columns view."
16124 (interactive)
16125 (org-overview)
16126 (org-content))
16128 (org-defkey org-columns-map "c" 'org-columns-content)
16129 (org-defkey org-columns-map "o" 'org-overview)
16130 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16131 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16132 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16133 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16134 (org-defkey org-columns-map "v" 'org-columns-show-value)
16135 (org-defkey org-columns-map "q" 'org-columns-quit)
16136 (org-defkey org-columns-map "r" 'org-columns-redo)
16137 (org-defkey org-columns-map [left] 'backward-char)
16138 (org-defkey org-columns-map "\M-b" 'backward-char)
16139 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16140 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16141 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16142 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16143 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16144 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16145 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16146 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16147 (org-defkey org-columns-map "<" 'org-columns-narrow)
16148 (org-defkey org-columns-map ">" 'org-columns-widen)
16149 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16150 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16151 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16152 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16154 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16155 '("Column"
16156 ["Edit property" org-columns-edit-value t]
16157 ["Next allowed value" org-columns-next-allowed-value t]
16158 ["Previous allowed value" org-columns-previous-allowed-value t]
16159 ["Show full value" org-columns-show-value t]
16160 ["Edit allowed values" org-columns-edit-allowed t]
16161 "--"
16162 ["Edit column attributes" org-columns-edit-attributes t]
16163 ["Increase column width" org-columns-widen t]
16164 ["Decrease column width" org-columns-narrow t]
16165 "--"
16166 ["Move column right" org-columns-move-right t]
16167 ["Move column left" org-columns-move-left t]
16168 ["Add column" org-columns-new t]
16169 ["Delete column" org-columns-delete t]
16170 "--"
16171 ["CONTENTS" org-columns-content t]
16172 ["OVERVIEW" org-overview t]
16173 ["Refresh columns display" org-columns-redo t]
16174 "--"
16175 ["Open link" org-columns-open-link t]
16176 "--"
16177 ["Quit" org-columns-quit t]))
16179 (defun org-columns-new-overlay (beg end &optional string face)
16180 "Create a new column overlay and add it to the list."
16181 (let ((ov (org-make-overlay beg end)))
16182 (org-overlay-put ov 'face (or face 'secondary-selection))
16183 (org-overlay-display ov string face)
16184 (push ov org-columns-overlays)
16185 ov))
16187 (defun org-columns-display-here (&optional props)
16188 "Overlay the current line with column display."
16189 (interactive)
16190 (let* ((fmt org-columns-current-fmt-compiled)
16191 (beg (point-at-bol))
16192 (level-face (save-excursion
16193 (beginning-of-line 1)
16194 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16195 (org-get-level-face 2))))
16196 (color (list :foreground
16197 (face-attribute (or level-face 'default) :foreground)))
16198 props pom property ass width f string ov column val modval)
16199 ;; Check if the entry is in another buffer.
16200 (unless props
16201 (if (eq major-mode 'org-agenda-mode)
16202 (setq pom (or (get-text-property (point) 'org-hd-marker)
16203 (get-text-property (point) 'org-marker))
16204 props (if pom (org-entry-properties pom) nil))
16205 (setq props (org-entry-properties nil))))
16206 ;; Walk the format
16207 (while (setq column (pop fmt))
16208 (setq property (car column)
16209 ass (if (equal property "ITEM")
16210 (cons "ITEM"
16211 (save-match-data
16212 (org-no-properties
16213 (org-remove-tabs
16214 (buffer-substring-no-properties
16215 (point-at-bol) (point-at-eol))))))
16216 (assoc property props))
16217 width (or (cdr (assoc property org-columns-current-maxwidths))
16218 (nth 2 column)
16219 (length property))
16220 f (format "%%-%d.%ds | " width width)
16221 val (or (cdr ass) "")
16222 modval (if (equal property "ITEM")
16223 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16224 string (format f (or modval val)))
16225 ;; Create the overlay
16226 (org-unmodified
16227 (setq ov (org-columns-new-overlay
16228 beg (setq beg (1+ beg)) string
16229 (list color 'org-column)))
16230 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16231 (org-overlay-put ov 'keymap org-columns-map)
16232 (org-overlay-put ov 'org-columns-key property)
16233 (org-overlay-put ov 'org-columns-value (cdr ass))
16234 (org-overlay-put ov 'org-columns-value-modified modval)
16235 (org-overlay-put ov 'org-columns-pom pom)
16236 (org-overlay-put ov 'org-columns-format f))
16237 (if (or (not (char-after beg))
16238 (equal (char-after beg) ?\n))
16239 (let ((inhibit-read-only t))
16240 (save-excursion
16241 (goto-char beg)
16242 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16243 ;; Make the rest of the line disappear.
16244 (org-unmodified
16245 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16246 (org-overlay-put ov 'invisible t)
16247 (org-overlay-put ov 'keymap org-columns-map)
16248 (org-overlay-put ov 'intangible t)
16249 (push ov org-columns-overlays)
16250 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16251 (org-overlay-put ov 'keymap org-columns-map)
16252 (push ov org-columns-overlays)
16253 (let ((inhibit-read-only t))
16254 (put-text-property (max (point-min) (1- (point-at-bol)))
16255 (min (point-max) (1+ (point-at-eol)))
16256 'read-only "Type `e' to edit property")))))
16258 (defvar org-previous-header-line-format nil
16259 "The header line format before column view was turned on.")
16260 (defvar org-columns-inhibit-recalculation nil
16261 "Inhibit recomputing of columns on column view startup.")
16264 (defvar header-line-format)
16265 (defun org-columns-display-here-title ()
16266 "Overlay the newline before the current line with the table title."
16267 (interactive)
16268 (let ((fmt org-columns-current-fmt-compiled)
16269 string (title "")
16270 property width f column str widths)
16271 (while (setq column (pop fmt))
16272 (setq property (car column)
16273 str (or (nth 1 column) property)
16274 width (or (cdr (assoc property org-columns-current-maxwidths))
16275 (nth 2 column)
16276 (length str))
16277 widths (push width widths)
16278 f (format "%%-%d.%ds | " width width)
16279 string (format f str)
16280 title (concat title string)))
16281 (setq title (concat
16282 (org-add-props " " nil 'display '(space :align-to 0))
16283 (org-add-props title nil 'face '(:weight bold :underline t))))
16284 (org-set-local 'org-previous-header-line-format header-line-format)
16285 (org-set-local 'org-columns-current-widths (nreverse widths))
16286 (setq header-line-format title)))
16288 (defun org-columns-remove-overlays ()
16289 "Remove all currently active column overlays."
16290 (interactive)
16291 (when (marker-buffer org-columns-begin-marker)
16292 (with-current-buffer (marker-buffer org-columns-begin-marker)
16293 (when (local-variable-p 'org-previous-header-line-format)
16294 (setq header-line-format org-previous-header-line-format)
16295 (kill-local-variable 'org-previous-header-line-format))
16296 (move-marker org-columns-begin-marker nil)
16297 (move-marker org-columns-top-level-marker nil)
16298 (org-unmodified
16299 (mapc 'org-delete-overlay org-columns-overlays)
16300 (setq org-columns-overlays nil)
16301 (let ((inhibit-read-only t))
16302 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16304 (defun org-columns-cleanup-item (item fmt)
16305 "Remove from ITEM what is a column in the format FMT."
16306 (if (not org-complex-heading-regexp)
16307 item
16308 (when (string-match org-complex-heading-regexp item)
16309 (concat
16310 (org-add-props (concat (match-string 1 item) " ") nil
16311 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16312 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16313 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16314 " " (match-string 4 item)
16315 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16317 (defun org-columns-show-value ()
16318 "Show the full value of the property."
16319 (interactive)
16320 (let ((value (get-char-property (point) 'org-columns-value)))
16321 (message "Value is: %s" (or value ""))))
16323 (defun org-columns-quit ()
16324 "Remove the column overlays and in this way exit column editing."
16325 (interactive)
16326 (org-unmodified
16327 (org-columns-remove-overlays)
16328 (let ((inhibit-read-only t))
16329 (remove-text-properties (point-min) (point-max) '(read-only t))))
16330 (when (eq major-mode 'org-agenda-mode)
16331 (message
16332 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16334 (defun org-columns-check-computed ()
16335 "Check if this column value is computed.
16336 If yes, throw an error indicating that changing it does not make sense."
16337 (let ((val (get-char-property (point) 'org-columns-value)))
16338 (when (and (stringp val)
16339 (get-char-property 0 'org-computed val))
16340 (error "This value is computed from the entry's children"))))
16342 (defun org-columns-todo (&optional arg)
16343 "Change the TODO state during column view."
16344 (interactive "P")
16345 (org-columns-edit-value "TODO"))
16347 (defun org-columns-set-tags-or-toggle (&optional arg)
16348 "Toggle checkbox at point, or set tags for current headline."
16349 (interactive "P")
16350 (if (string-match "\\`\\[[ xX-]\\]\\'"
16351 (get-char-property (point) 'org-columns-value))
16352 (org-columns-next-allowed-value)
16353 (org-columns-edit-value "TAGS")))
16355 (defun org-columns-edit-value (&optional key)
16356 "Edit the value of the property at point in column view.
16357 Where possible, use the standard interface for changing this line."
16358 (interactive)
16359 (org-columns-check-computed)
16360 (let* ((external-key key)
16361 (col (current-column))
16362 (key (or key (get-char-property (point) 'org-columns-key)))
16363 (value (get-char-property (point) 'org-columns-value))
16364 (bol (point-at-bol)) (eol (point-at-eol))
16365 (pom (or (get-text-property bol 'org-hd-marker)
16366 (point))) ; keep despite of compiler waring
16367 (line-overlays
16368 (delq nil (mapcar (lambda (x)
16369 (and (eq (overlay-buffer x) (current-buffer))
16370 (>= (overlay-start x) bol)
16371 (<= (overlay-start x) eol)
16373 org-columns-overlays)))
16374 nval eval allowed)
16375 (cond
16376 ((equal key "ITEM")
16377 (setq eval '(org-with-point-at pom
16378 (org-edit-headline))))
16379 ((equal key "TODO")
16380 (setq eval '(org-with-point-at pom
16381 (let ((current-prefix-arg
16382 (if external-key current-prefix-arg '(4))))
16383 (call-interactively 'org-todo)))))
16384 ((equal key "PRIORITY")
16385 (setq eval '(org-with-point-at pom
16386 (call-interactively 'org-priority))))
16387 ((equal key "TAGS")
16388 (setq eval '(org-with-point-at pom
16389 (let ((org-fast-tag-selection-single-key
16390 (if (eq org-fast-tag-selection-single-key 'expert)
16391 t org-fast-tag-selection-single-key)))
16392 (call-interactively 'org-set-tags)))))
16393 ((equal key "DEADLINE")
16394 (setq eval '(org-with-point-at pom
16395 (call-interactively 'org-deadline))))
16396 ((equal key "SCHEDULED")
16397 (setq eval '(org-with-point-at pom
16398 (call-interactively 'org-schedule))))
16400 (setq allowed (org-property-get-allowed-values pom key 'table))
16401 (if allowed
16402 (setq nval (completing-read "Value: " allowed nil t))
16403 (setq nval (read-string "Edit: " value)))
16404 (setq nval (org-trim nval))
16405 (when (not (equal nval value))
16406 (setq eval '(org-entry-put pom key nval)))))
16407 (when eval
16408 (let ((inhibit-read-only t))
16409 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16410 (unwind-protect
16411 (progn
16412 (setq org-columns-overlays
16413 (org-delete-all line-overlays org-columns-overlays))
16414 (mapc 'org-delete-overlay line-overlays)
16415 (org-columns-eval eval))
16416 (org-columns-display-here))))
16417 (move-to-column col)
16418 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
16419 (org-columns-update key))))
16421 (defun org-edit-headline () ; FIXME: this is not columns specific
16422 "Edit the current headline, the part without TODO keyword, TAGS."
16423 (org-back-to-heading)
16424 (when (looking-at org-todo-line-regexp)
16425 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16426 (txt (match-string 3))
16427 (post "")
16428 txt2)
16429 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16430 (setq post (match-string 0 txt)
16431 txt (substring txt 0 (match-beginning 0))))
16432 (setq txt2 (read-string "Edit: " txt))
16433 (when (not (equal txt txt2))
16434 (beginning-of-line 1)
16435 (insert pre txt2 post)
16436 (delete-region (point) (point-at-eol))
16437 (org-set-tags nil t)))))
16439 (defun org-columns-edit-allowed ()
16440 "Edit the list of allowed values for the current property."
16441 (interactive)
16442 (let* ((key (get-char-property (point) 'org-columns-key))
16443 (key1 (concat key "_ALL"))
16444 (allowed (org-entry-get (point) key1 t))
16445 nval)
16446 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16447 (setq nval (read-string "Allowed: " allowed))
16448 (org-entry-put
16449 (cond ((marker-position org-entry-property-inherited-from)
16450 org-entry-property-inherited-from)
16451 ((marker-position org-columns-top-level-marker)
16452 org-columns-top-level-marker))
16453 key1 nval)))
16455 (defmacro org-no-warnings (&rest body)
16456 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16458 (defun org-columns-eval (form)
16459 (let (hidep)
16460 (save-excursion
16461 (beginning-of-line 1)
16462 ;; `next-line' is needed here, because it skips invisible line.
16463 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16464 (setq hidep (org-on-heading-p 1)))
16465 (eval form)
16466 (and hidep (hide-entry))))
16468 (defun org-columns-previous-allowed-value ()
16469 "Switch to the previous allowed value for this column."
16470 (interactive)
16471 (org-columns-next-allowed-value t))
16473 (defun org-columns-next-allowed-value (&optional previous)
16474 "Switch to the next allowed value for this column."
16475 (interactive)
16476 (org-columns-check-computed)
16477 (let* ((col (current-column))
16478 (key (get-char-property (point) 'org-columns-key))
16479 (value (get-char-property (point) 'org-columns-value))
16480 (bol (point-at-bol)) (eol (point-at-eol))
16481 (pom (or (get-text-property bol 'org-hd-marker)
16482 (point))) ; keep despite of compiler waring
16483 (line-overlays
16484 (delq nil (mapcar (lambda (x)
16485 (and (eq (overlay-buffer x) (current-buffer))
16486 (>= (overlay-start x) bol)
16487 (<= (overlay-start x) eol)
16489 org-columns-overlays)))
16490 (allowed (or (org-property-get-allowed-values pom key)
16491 (and (equal
16492 (nth 4 (assoc key org-columns-current-fmt-compiled))
16493 'checkbox) '("[ ]" "[X]"))))
16494 nval)
16495 (when (equal key "ITEM")
16496 (error "Cannot edit item headline from here"))
16497 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16498 (error "Allowed values for this property have not been defined"))
16499 (if (member key '("SCHEDULED" "DEADLINE"))
16500 (setq nval (if previous 'earlier 'later))
16501 (if previous (setq allowed (reverse allowed)))
16502 (if (member value allowed)
16503 (setq nval (car (cdr (member value allowed)))))
16504 (setq nval (or nval (car allowed)))
16505 (if (equal nval value)
16506 (error "Only one allowed value for this property")))
16507 (let ((inhibit-read-only t))
16508 (remove-text-properties (1- bol) eol '(read-only t))
16509 (unwind-protect
16510 (progn
16511 (setq org-columns-overlays
16512 (org-delete-all line-overlays org-columns-overlays))
16513 (mapc 'org-delete-overlay line-overlays)
16514 (org-columns-eval '(org-entry-put pom key nval)))
16515 (org-columns-display-here)))
16516 (move-to-column col)
16517 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
16518 (org-columns-update key))))
16520 (defun org-verify-version (task)
16521 (cond
16522 ((eq task 'columns)
16523 (if (or (featurep 'xemacs)
16524 (< emacs-major-version 22))
16525 (error "Emacs 22 is required for the columns feature")))))
16527 (defun org-columns-open-link (&optional arg)
16528 (interactive "P")
16529 (let ((key (get-char-property (point) 'org-columns-key))
16530 (value (get-char-property (point) 'org-columns-value)))
16531 (org-open-link-from-string arg)))
16533 (defun org-open-link-from-string (s &optional arg)
16534 "Open a link in the string S, as if it was in Org-mode."
16535 (interactive)
16536 (with-temp-buffer
16537 (let ((org-inhibit-startup t))
16538 (org-mode)
16539 (insert s)
16540 (goto-char (point-min))
16541 (org-open-at-point arg))))
16543 (defun org-columns-get-format-and-top-level ()
16544 (let (fmt)
16545 (when (condition-case nil (org-back-to-heading) (error nil))
16546 (move-marker org-entry-property-inherited-from nil)
16547 (setq fmt (org-entry-get nil "COLUMNS" t)))
16548 (setq fmt (or fmt org-columns-default-format))
16549 (org-set-local 'org-columns-current-fmt fmt)
16550 (org-columns-compile-format fmt)
16551 (if (marker-position org-entry-property-inherited-from)
16552 (move-marker org-columns-top-level-marker
16553 org-entry-property-inherited-from)
16554 (move-marker org-columns-top-level-marker (point)))
16555 fmt))
16557 (defun org-columns ()
16558 "Turn on column view on an org-mode file."
16559 (interactive)
16560 (org-verify-version 'columns)
16561 (org-columns-remove-overlays)
16562 (move-marker org-columns-begin-marker (point))
16563 (let (beg end fmt cache maxwidths)
16564 (setq fmt (org-columns-get-format-and-top-level))
16565 (save-excursion
16566 (goto-char org-columns-top-level-marker)
16567 (setq beg (point))
16568 (unless org-columns-inhibit-recalculation
16569 (org-columns-compute-all))
16570 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16571 (point-max)))
16572 (goto-char beg)
16573 ;; Get and cache the properties
16574 (while (re-search-forward (concat "^" outline-regexp) end t)
16575 (push (cons (org-current-line) (org-entry-properties)) cache))
16576 (when cache
16577 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16578 (org-set-local 'org-columns-current-maxwidths maxwidths)
16579 (org-columns-display-here-title)
16580 (mapc (lambda (x)
16581 (goto-line (car x))
16582 (org-columns-display-here (cdr x)))
16583 cache)))))
16585 (defun org-columns-new (&optional prop title width op fmt)
16586 "Insert a new column, to the leeft o the current column."
16587 (interactive)
16588 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16589 cell)
16590 (setq prop (completing-read
16591 "Property: " (mapcar 'list (org-buffer-property-keys t))
16592 nil nil prop))
16593 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16594 (setq width (read-string "Column width: " (if width (number-to-string width))))
16595 (if (string-match "\\S-" width)
16596 (setq width (string-to-number width))
16597 (setq width nil))
16598 (setq fmt (completing-read "Summary [none]: "
16599 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16600 nil t))
16601 (if (string-match "\\S-" fmt)
16602 (setq fmt (intern fmt))
16603 (setq fmt nil))
16604 (if (eq fmt 'none) (setq fmt nil))
16605 (if editp
16606 (progn
16607 (setcar editp prop)
16608 (setcdr editp (list title width nil fmt)))
16609 (setq cell (nthcdr (1- (current-column))
16610 org-columns-current-fmt-compiled))
16611 (setcdr cell (cons (list prop title width nil fmt)
16612 (cdr cell))))
16613 (org-columns-store-format)
16614 (org-columns-redo)))
16616 (defun org-columns-delete ()
16617 "Delete the column at point from columns view."
16618 (interactive)
16619 (let* ((n (current-column))
16620 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16621 (when (y-or-n-p
16622 (format "Are you sure you want to remove column \"%s\"? " title))
16623 (setq org-columns-current-fmt-compiled
16624 (delq (nth n org-columns-current-fmt-compiled)
16625 org-columns-current-fmt-compiled))
16626 (org-columns-store-format)
16627 (org-columns-redo)
16628 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16629 (backward-char 1)))))
16631 (defun org-columns-edit-attributes ()
16632 "Edit the attributes of the current column."
16633 (interactive)
16634 (let* ((n (current-column))
16635 (info (nth n org-columns-current-fmt-compiled)))
16636 (apply 'org-columns-new info)))
16638 (defun org-columns-widen (arg)
16639 "Make the column wider by ARG characters."
16640 (interactive "p")
16641 (let* ((n (current-column))
16642 (entry (nth n org-columns-current-fmt-compiled))
16643 (width (or (nth 2 entry)
16644 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16645 (setq width (max 1 (+ width arg)))
16646 (setcar (nthcdr 2 entry) width)
16647 (org-columns-store-format)
16648 (org-columns-redo)))
16650 (defun org-columns-narrow (arg)
16651 "Make the column nrrower by ARG characters."
16652 (interactive "p")
16653 (org-columns-widen (- arg)))
16655 (defun org-columns-move-right ()
16656 "Swap this column with the one to the right."
16657 (interactive)
16658 (let* ((n (current-column))
16659 (cell (nthcdr n org-columns-current-fmt-compiled))
16661 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16662 (error "Cannot shift this column further to the right"))
16663 (setq e (car cell))
16664 (setcar cell (car (cdr cell)))
16665 (setcdr cell (cons e (cdr (cdr cell))))
16666 (org-columns-store-format)
16667 (org-columns-redo)
16668 (forward-char 1)))
16670 (defun org-columns-move-left ()
16671 "Swap this column with the one to the left."
16672 (interactive)
16673 (let* ((n (current-column)))
16674 (when (= n 0)
16675 (error "Cannot shift this column further to the left"))
16676 (backward-char 1)
16677 (org-columns-move-right)
16678 (backward-char 1)))
16680 (defun org-columns-store-format ()
16681 "Store the text version of the current columns format in appropriate place.
16682 This is either in the COLUMNS property of the node starting the current column
16683 display, or in the #+COLUMNS line of the current buffer."
16684 (let (fmt (cnt 0))
16685 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16686 (org-set-local 'org-columns-current-fmt fmt)
16687 (if (marker-position org-columns-top-level-marker)
16688 (save-excursion
16689 (goto-char org-columns-top-level-marker)
16690 (if (and (org-at-heading-p)
16691 (org-entry-get nil "COLUMNS"))
16692 (org-entry-put nil "COLUMNS" fmt)
16693 (goto-char (point-min))
16694 ;; Overwrite all #+COLUMNS lines....
16695 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16696 (setq cnt (1+ cnt))
16697 (replace-match (concat "#+COLUMNS: " fmt) t t))
16698 (unless (> cnt 0)
16699 (goto-char (point-min))
16700 (or (org-on-heading-p t) (outline-next-heading))
16701 (let ((inhibit-read-only t))
16702 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16703 (org-set-local 'org-columns-default-format fmt))))))
16705 (defvar org-overriding-columns-format nil
16706 "When set, overrides any other definition.")
16707 (defvar org-agenda-view-columns-initially nil
16708 "When set, switch to columns view immediately after creating the agenda.")
16710 (defun org-agenda-columns ()
16711 "Turn on column view in the agenda."
16712 (interactive)
16713 (org-verify-version 'columns)
16714 (org-columns-remove-overlays)
16715 (move-marker org-columns-begin-marker (point))
16716 (let (fmt cache maxwidths m)
16717 (cond
16718 ((and (local-variable-p 'org-overriding-columns-format)
16719 org-overriding-columns-format)
16720 (setq fmt org-overriding-columns-format))
16721 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16722 (setq fmt (org-entry-get m "COLUMNS" t)))
16723 ((and (boundp 'org-columns-current-fmt)
16724 (local-variable-p 'org-columns-current-fmt)
16725 org-columns-current-fmt)
16726 (setq fmt org-columns-current-fmt))
16727 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16728 (setq m (get-text-property m 'org-hd-marker))
16729 (setq fmt (org-entry-get m "COLUMNS" t))))
16730 (setq fmt (or fmt org-columns-default-format))
16731 (org-set-local 'org-columns-current-fmt fmt)
16732 (org-columns-compile-format fmt)
16733 (save-excursion
16734 ;; Get and cache the properties
16735 (goto-char (point-min))
16736 (while (not (eobp))
16737 (when (setq m (or (get-text-property (point) 'org-hd-marker)
16738 (get-text-property (point) 'org-marker)))
16739 (push (cons (org-current-line) (org-entry-properties m)) cache))
16740 (beginning-of-line 2))
16741 (when cache
16742 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16743 (org-set-local 'org-columns-current-maxwidths maxwidths)
16744 (org-columns-display-here-title)
16745 (mapc (lambda (x)
16746 (goto-line (car x))
16747 (org-columns-display-here (cdr x)))
16748 cache)))))
16750 (defun org-columns-get-autowidth-alist (s cache)
16751 "Derive the maximum column widths from the format and the cache."
16752 (let ((start 0) rtn)
16753 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
16754 (push (cons (match-string 1 s) 1) rtn)
16755 (setq start (match-end 0)))
16756 (mapc (lambda (x)
16757 (setcdr x (apply 'max
16758 (mapcar
16759 (lambda (y)
16760 (length (or (cdr (assoc (car x) (cdr y))) " ")))
16761 cache))))
16762 rtn)
16763 rtn))
16765 (defun org-columns-compute-all ()
16766 "Compute all columns that have operators defined."
16767 (org-unmodified
16768 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
16769 (let ((columns org-columns-current-fmt-compiled) col)
16770 (while (setq col (pop columns))
16771 (when (nth 3 col)
16772 (save-excursion
16773 (org-columns-compute (car col)))))))
16775 (defun org-columns-update (property)
16776 "Recompute PROPERTY, and update the columns display for it."
16777 (org-columns-compute property)
16778 (let (fmt val pos)
16779 (save-excursion
16780 (mapc (lambda (ov)
16781 (when (equal (org-overlay-get ov 'org-columns-key) property)
16782 (setq pos (org-overlay-start ov))
16783 (goto-char pos)
16784 (when (setq val (cdr (assoc property
16785 (get-text-property
16786 (point-at-bol) 'org-summaries))))
16787 (setq fmt (org-overlay-get ov 'org-columns-format))
16788 (org-overlay-put ov 'org-columns-value val)
16789 (org-overlay-put ov 'display (format fmt val)))))
16790 org-columns-overlays))))
16792 (defun org-columns-compute (property)
16793 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
16794 (interactive)
16795 (let* ((re (concat "^" outline-regexp))
16796 (lmax 30) ; Does anyone use deeper levels???
16797 (lsum (make-vector lmax 0))
16798 (lflag (make-vector lmax nil))
16799 (level 0)
16800 (ass (assoc property org-columns-current-fmt-compiled))
16801 (format (nth 4 ass))
16802 (printf (nth 5 ass))
16803 (beg org-columns-top-level-marker)
16804 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
16805 (save-excursion
16806 ;; Find the region to compute
16807 (goto-char beg)
16808 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
16809 (goto-char end)
16810 ;; Walk the tree from the back and do the computations
16811 (while (re-search-backward re beg t)
16812 (setq sumpos (match-beginning 0)
16813 last-level level
16814 level (org-outline-level)
16815 val (org-entry-get nil property)
16816 valflag (and val (string-match "\\S-" val)))
16817 (cond
16818 ((< level last-level)
16819 ;; put the sum of lower levels here as a property
16820 (setq sum (aref lsum last-level) ; current sum
16821 flag (aref lflag last-level) ; any valid entries from children?
16822 str (org-column-number-to-string sum format printf)
16823 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
16824 useval (if flag str1 (if valflag val ""))
16825 sum-alist (get-text-property sumpos 'org-summaries))
16826 (if (assoc property sum-alist)
16827 (setcdr (assoc property sum-alist) useval)
16828 (push (cons property useval) sum-alist)
16829 (org-unmodified
16830 (add-text-properties sumpos (1+ sumpos)
16831 (list 'org-summaries sum-alist))))
16832 (when val
16833 (org-entry-put nil property (if flag str val)))
16834 ;; add current to current level accumulator
16835 (when (or flag valflag)
16836 (aset lsum level (+ (aref lsum level)
16837 (if flag sum (org-column-string-to-number
16838 (if flag str val) format))))
16839 (aset lflag level t))
16840 ;; clear accumulators for deeper levels
16841 (loop for l from (1+ level) to (1- lmax) do
16842 (aset lsum l 0)
16843 (aset lflag l nil)))
16844 ((>= level last-level)
16845 ;; add what we have here to the accumulator for this level
16846 (aset lsum level (+ (aref lsum level)
16847 (org-column-string-to-number (or val "0") format)))
16848 (and valflag (aset lflag level t)))
16849 (t (error "This should not happen")))))))
16851 (defun org-columns-redo ()
16852 "Construct the column display again."
16853 (interactive)
16854 (message "Recomputing columns...")
16855 (save-excursion
16856 (if (marker-position org-columns-begin-marker)
16857 (goto-char org-columns-begin-marker))
16858 (org-columns-remove-overlays)
16859 (if (org-mode-p)
16860 (call-interactively 'org-columns)
16861 (call-interactively 'org-agenda-columns)))
16862 (message "Recomputing columns...done"))
16864 (defun org-columns-not-in-agenda ()
16865 (if (eq major-mode 'org-agenda-mode)
16866 (error "This command is only allowed in Org-mode buffers")))
16869 (defun org-string-to-number (s)
16870 "Convert string to number, and interpret hh:mm:ss."
16871 (if (not (string-match ":" s))
16872 (string-to-number s)
16873 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16874 (while l
16875 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16876 sum)))
16878 (defun org-column-number-to-string (n fmt printf)
16879 "Convert a computed column number to a string value, according to FMT."
16880 (cond
16881 ((eq fmt 'add_times)
16882 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
16883 (format "%d:%02d" h m)))
16884 ((eq fmt 'checkbox)
16885 (cond ((= n (floor n)) "[X]")
16886 ((> n 1.) "[-]")
16887 (t "[ ]")))
16888 (printf (format printf n))
16889 ((eq fmt 'currency)
16890 (format "%.2f" n))
16891 (t (number-to-string n))))
16893 (defun org-column-string-to-number (s fmt)
16894 "Convert a column value to a number that can be used for column computing."
16895 (cond
16896 ((string-match ":" s)
16897 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16898 (while l
16899 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16900 sum))
16901 ((eq fmt 'checkbox)
16902 (if (equal s "[X]") 1. 0.000001))
16903 (t (string-to-number s))))
16905 (defun org-columns-uncompile-format (cfmt)
16906 "Turn the compiled columns format back into a string representation."
16907 (let ((rtn "") e s prop title op width fmt printf)
16908 (while (setq e (pop cfmt))
16909 (setq prop (car e)
16910 title (nth 1 e)
16911 width (nth 2 e)
16912 op (nth 3 e)
16913 fmt (nth 4 e)
16914 printf (nth 5 e))
16915 (cond
16916 ((eq fmt 'add_times) (setq op ":"))
16917 ((eq fmt 'checkbox) (setq op "X"))
16918 ((eq fmt 'add_numbers) (setq op "+"))
16919 ((eq fmt 'currency) (setq op "$")))
16920 (if (and op printf) (setq op (concat op ";" printf)))
16921 (if (equal title prop) (setq title nil))
16922 (setq s (concat "%" (if width (number-to-string width))
16923 prop
16924 (if title (concat "(" title ")"))
16925 (if op (concat "{" op "}"))))
16926 (setq rtn (concat rtn " " s)))
16927 (org-trim rtn)))
16929 (defun org-columns-compile-format (fmt)
16930 "Turn a column format string into an alist of specifications.
16931 The alist has one entry for each column in the format. The elements of
16932 that list are:
16933 property the property
16934 title the title field for the columns
16935 width the column width in characters, can be nil for automatic
16936 operator the operator if any
16937 format the output format for computed results, derived from operator
16938 printf a printf format for computed values"
16939 (let ((start 0) width prop title op f printf)
16940 (setq org-columns-current-fmt-compiled nil)
16941 (while (string-match
16942 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
16943 fmt start)
16944 (setq start (match-end 0)
16945 width (match-string 1 fmt)
16946 prop (match-string 2 fmt)
16947 title (or (match-string 3 fmt) prop)
16948 op (match-string 4 fmt)
16949 f nil
16950 printf nil)
16951 (if width (setq width (string-to-number width)))
16952 (when (and op (string-match ";" op))
16953 (setq printf (substring op (match-end 0))
16954 op (substring op 0 (match-beginning 0))))
16955 (cond
16956 ((equal op "+") (setq f 'add_numbers))
16957 ((equal op "$") (setq f 'currency))
16958 ((equal op ":") (setq f 'add_times))
16959 ((equal op "X") (setq f 'checkbox)))
16960 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
16961 (setq org-columns-current-fmt-compiled
16962 (nreverse org-columns-current-fmt-compiled))))
16965 ;;; Dynamic block for Column view
16967 (defun org-columns-capture-view ()
16968 "Get the column view of the current buffer and return it as a list.
16969 The list will contains the title row and all other rows. Each row is
16970 a list of fields."
16971 (save-excursion
16972 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
16973 (n (length title)) row tbl)
16974 (goto-char (point-min))
16975 (while (re-search-forward "^\\*+ " nil t)
16976 (when (get-char-property (match-beginning 0) 'org-columns-key)
16977 (setq row nil)
16978 (loop for i from 0 to (1- n) do
16979 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
16980 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
16982 row))
16983 (setq row (nreverse row))
16984 (push row tbl)))
16985 (append (list title 'hline) (nreverse tbl)))))
16987 (defun org-dblock-write:columnview (params)
16988 "Write the column view table.
16989 PARAMS is a property list of parameters:
16991 :width enforce same column widths with <N> specifiers.
16992 :id the :ID: property of the entry where the columns view
16993 should be built, as a string. When `local', call locally.
16994 When `global' call column view with the cursor at the beginning
16995 of the buffer (usually this means that the whole buffer switches
16996 to column view).
16997 :hlines When t, insert a hline before each item. When a number, insert
16998 a hline before each level <= that number.
16999 :vlines When t, make each column a colgroup to enforce vertical lines."
17000 (let ((pos (move-marker (make-marker) (point)))
17001 (hlines (plist-get params :hlines))
17002 (vlines (plist-get params :vlines))
17003 tbl id idpos nfields tmp)
17004 (save-excursion
17005 (save-restriction
17006 (when (setq id (plist-get params :id))
17007 (cond ((not id) nil)
17008 ((eq id 'global) (goto-char (point-min)))
17009 ((eq id 'local) nil)
17010 ((setq idpos (org-find-entry-with-id id))
17011 (goto-char idpos))
17012 (t (error "Cannot find entry with :ID: %s" id))))
17013 (org-columns)
17014 (setq tbl (org-columns-capture-view))
17015 (setq nfields (length (car tbl)))
17016 (org-columns-quit)))
17017 (goto-char pos)
17018 (move-marker pos nil)
17019 (when tbl
17020 (when (plist-get params :hlines)
17021 (setq tmp nil)
17022 (while tbl
17023 (if (eq (car tbl) 'hline)
17024 (push (pop tbl) tmp)
17025 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17026 (if (and (not (eq (car tmp) 'hline))
17027 (or (eq hlines t)
17028 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17029 (push 'hline tmp)))
17030 (push (pop tbl) tmp)))
17031 (setq tbl (nreverse tmp)))
17032 (when vlines
17033 (setq tbl (mapcar (lambda (x)
17034 (if (eq 'hline x) x (cons "" x)))
17035 tbl))
17036 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17037 (setq pos (point))
17038 (insert (org-listtable-to-string tbl))
17039 (when (plist-get params :width)
17040 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17041 org-columns-current-widths "|")))
17042 (goto-char pos)
17043 (org-table-align))))
17045 (defun org-listtable-to-string (tbl)
17046 "Convert a listtable TBL to a string that contains the Org-mode table.
17047 The table still need to be alligned. The resulting string has no leading
17048 and tailing newline characters."
17049 (mapconcat
17050 (lambda (x)
17051 (cond
17052 ((listp x)
17053 (concat "|" (mapconcat 'identity x "|") "|"))
17054 ((eq x 'hline) "|-|")
17055 (t (error "Garbage in listtable: %s" x))))
17056 tbl "\n"))
17058 (defun org-insert-columns-dblock ()
17059 "Create a dynamic block capturing a column view table."
17060 (interactive)
17061 (let ((defaults '(:name "columnview" :hlines 1))
17062 (id (completing-read
17063 "Capture columns (local, global, entry with :ID: property) [local]: "
17064 (append '(("global") ("local"))
17065 (mapcar 'list (org-property-values "ID"))))))
17066 (if (equal id "") (setq id 'local))
17067 (if (equal id "global") (setq id 'global))
17068 (setq defaults (append defaults (list :id id)))
17069 (org-create-dblock defaults)
17070 (org-update-dblock)))
17072 ;;;; Timestamps
17074 (defvar org-last-changed-timestamp nil)
17075 (defvar org-time-was-given) ; dynamically scoped parameter
17076 (defvar org-end-time-was-given) ; dynamically scoped parameter
17077 (defvar org-ts-what) ; dynamically scoped parameter
17079 (defun org-time-stamp (arg)
17080 "Prompt for a date/time and insert a time stamp.
17081 If the user specifies a time like HH:MM, or if this command is called
17082 with a prefix argument, the time stamp will contain date and time.
17083 Otherwise, only the date will be included. All parts of a date not
17084 specified by the user will be filled in from the current date/time.
17085 So if you press just return without typing anything, the time stamp
17086 will represent the current date/time. If there is already a timestamp
17087 at the cursor, it will be modified."
17088 (interactive "P")
17089 (let* ((ts nil)
17090 (default-time
17091 ;; Default time is either today, or, when entering a range,
17092 ;; the range start.
17093 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17094 (save-excursion
17095 (re-search-backward
17096 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17097 (- (point) 20) t)))
17098 (apply 'encode-time (org-parse-time-string (match-string 1)))
17099 (current-time)))
17100 (default-input (and ts (org-get-compact-tod ts)))
17101 org-time-was-given org-end-time-was-given time)
17102 (cond
17103 ((and (org-at-timestamp-p)
17104 (eq last-command 'org-time-stamp)
17105 (eq this-command 'org-time-stamp))
17106 (insert "--")
17107 (setq time (let ((this-command this-command))
17108 (org-read-date arg 'totime nil nil default-time default-input)))
17109 (org-insert-time-stamp time (or org-time-was-given arg)))
17110 ((org-at-timestamp-p)
17111 (setq time (let ((this-command this-command))
17112 (org-read-date arg 'totime nil nil default-time default-input)))
17113 (when (org-at-timestamp-p) ; just to get the match data
17114 (replace-match "")
17115 (setq org-last-changed-timestamp
17116 (org-insert-time-stamp
17117 time (or org-time-was-given arg)
17118 nil nil nil (list org-end-time-was-given))))
17119 (message "Timestamp updated"))
17121 (setq time (let ((this-command this-command))
17122 (org-read-date arg 'totime nil nil default-time default-input)))
17123 (org-insert-time-stamp time (or org-time-was-given arg)
17124 nil nil nil (list org-end-time-was-given))))))
17126 ;; FIXME: can we use this for something else????
17127 ;; like computing time differences?????
17128 (defun org-get-compact-tod (s)
17129 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17130 (let* ((t1 (match-string 1 s))
17131 (h1 (string-to-number (match-string 2 s)))
17132 (m1 (string-to-number (match-string 3 s)))
17133 (t2 (and (match-end 4) (match-string 5 s)))
17134 (h2 (and t2 (string-to-number (match-string 6 s))))
17135 (m2 (and t2 (string-to-number (match-string 7 s))))
17136 dh dm)
17137 (if (not t2)
17139 (setq dh (- h2 h1) dm (- m2 m1))
17140 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17141 (concat t1 "+" (number-to-string dh)
17142 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17144 (defun org-time-stamp-inactive (&optional arg)
17145 "Insert an inactive time stamp.
17146 An inactive time stamp is enclosed in square brackets instead of angle
17147 brackets. It is inactive in the sense that it does not trigger agenda entries,
17148 does not link to the calendar and cannot be changed with the S-cursor keys.
17149 So these are more for recording a certain time/date."
17150 (interactive "P")
17151 (let (org-time-was-given org-end-time-was-given time)
17152 (setq time (org-read-date arg 'totime))
17153 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17154 nil nil (list org-end-time-was-given))))
17156 (defvar org-date-ovl (org-make-overlay 1 1))
17157 (org-overlay-put org-date-ovl 'face 'org-warning)
17158 (org-detach-overlay org-date-ovl)
17160 (defvar org-ans1) ; dynamically scoped parameter
17161 (defvar org-ans2) ; dynamically scoped parameter
17163 (defvar org-plain-time-of-day-regexp) ; defined below
17165 (defvar org-read-date-overlay nil)
17166 (defvar org-dcst nil) ; dynamically scoped
17168 (defun org-read-date (&optional with-time to-time from-string prompt
17169 default-time default-input)
17170 "Read a date, possibly a time, and make things smooth for the user.
17171 The prompt will suggest to enter an ISO date, but you can also enter anything
17172 which will at least partially be understood by `parse-time-string'.
17173 Unrecognized parts of the date will default to the current day, month, year,
17174 hour and minute. If this command is called to replace a timestamp at point,
17175 of to enter the second timestamp of a range, the default time is taken from the
17176 existing stamp. For example,
17177 3-2-5 --> 2003-02-05
17178 feb 15 --> currentyear-02-15
17179 sep 12 9 --> 2009-09-12
17180 12:45 --> today 12:45
17181 22 sept 0:34 --> currentyear-09-22 0:34
17182 12 --> currentyear-currentmonth-12
17183 Fri --> nearest Friday (today or later)
17184 etc.
17186 Furthermore you can specify a relative date by giving, as the *first* thing
17187 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17188 change in days weeks, months, years.
17189 With a single plus or minus, the date is relative to today. With a double
17190 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17191 +4d --> four days from today
17192 +4 --> same as above
17193 +2w --> two weeks from today
17194 ++5 --> five days from default date
17196 The function understands only English month and weekday abbreviations,
17197 but this can be configured with the variables `parse-time-months' and
17198 `parse-time-weekdays'.
17200 While prompting, a calendar is popped up - you can also select the
17201 date with the mouse (button 1). The calendar shows a period of three
17202 months. To scroll it to other months, use the keys `>' and `<'.
17203 If you don't like the calendar, turn it off with
17204 \(setq org-read-date-popup-calendar nil)
17206 With optional argument TO-TIME, the date will immediately be converted
17207 to an internal time.
17208 With an optional argument WITH-TIME, the prompt will suggest to also
17209 insert a time. Note that when WITH-TIME is not set, you can still
17210 enter a time, and this function will inform the calling routine about
17211 this change. The calling routine may then choose to change the format
17212 used to insert the time stamp into the buffer to include the time.
17213 With optional argument FROM-STRING, read from this string instead from
17214 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17215 the time/date that is used for everything that is not specified by the
17216 user."
17217 (require 'parse-time)
17218 (let* ((org-time-stamp-rounding-minutes
17219 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17220 (org-dcst org-display-custom-times)
17221 (ct (org-current-time))
17222 (def (or default-time ct))
17223 (defdecode (decode-time def))
17224 (dummy (progn
17225 (when (< (nth 2 defdecode) org-extend-today-until)
17226 (setcar (nthcdr 2 defdecode) -1)
17227 (setcar (nthcdr 1 defdecode) 59)
17228 (setq def (apply 'encode-time defdecode)
17229 defdecode (decode-time def)))))
17230 (calendar-move-hook nil)
17231 (view-diary-entries-initially nil)
17232 (view-calendar-holidays-initially nil)
17233 (timestr (format-time-string
17234 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17235 (prompt (concat (if prompt (concat prompt " ") "")
17236 (format "Date+time [%s]: " timestr)))
17237 ans (org-ans0 "") org-ans1 org-ans2 final)
17239 (cond
17240 (from-string (setq ans from-string))
17241 (org-read-date-popup-calendar
17242 (save-excursion
17243 (save-window-excursion
17244 (calendar)
17245 (calendar-forward-day (- (time-to-days def)
17246 (calendar-absolute-from-gregorian
17247 (calendar-current-date))))
17248 (org-eval-in-calendar nil t)
17249 (let* ((old-map (current-local-map))
17250 (map (copy-keymap calendar-mode-map))
17251 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17252 (org-defkey map (kbd "RET") 'org-calendar-select)
17253 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17254 'org-calendar-select-mouse)
17255 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17256 'org-calendar-select-mouse)
17257 (org-defkey minibuffer-local-map [(meta shift left)]
17258 (lambda () (interactive)
17259 (org-eval-in-calendar '(calendar-backward-month 1))))
17260 (org-defkey minibuffer-local-map [(meta shift right)]
17261 (lambda () (interactive)
17262 (org-eval-in-calendar '(calendar-forward-month 1))))
17263 (org-defkey minibuffer-local-map [(meta shift up)]
17264 (lambda () (interactive)
17265 (org-eval-in-calendar '(calendar-backward-year 1))))
17266 (org-defkey minibuffer-local-map [(meta shift down)]
17267 (lambda () (interactive)
17268 (org-eval-in-calendar '(calendar-forward-year 1))))
17269 (org-defkey minibuffer-local-map [(shift up)]
17270 (lambda () (interactive)
17271 (org-eval-in-calendar '(calendar-backward-week 1))))
17272 (org-defkey minibuffer-local-map [(shift down)]
17273 (lambda () (interactive)
17274 (org-eval-in-calendar '(calendar-forward-week 1))))
17275 (org-defkey minibuffer-local-map [(shift left)]
17276 (lambda () (interactive)
17277 (org-eval-in-calendar '(calendar-backward-day 1))))
17278 (org-defkey minibuffer-local-map [(shift right)]
17279 (lambda () (interactive)
17280 (org-eval-in-calendar '(calendar-forward-day 1))))
17281 (org-defkey minibuffer-local-map ">"
17282 (lambda () (interactive)
17283 (org-eval-in-calendar '(scroll-calendar-left 1))))
17284 (org-defkey minibuffer-local-map "<"
17285 (lambda () (interactive)
17286 (org-eval-in-calendar '(scroll-calendar-right 1))))
17287 (unwind-protect
17288 (progn
17289 (use-local-map map)
17290 (add-hook 'post-command-hook 'org-read-date-display)
17291 (setq org-ans0 (read-string prompt default-input nil nil))
17292 ;; org-ans0: from prompt
17293 ;; org-ans1: from mouse click
17294 ;; org-ans2: from calendar motion
17295 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17296 (remove-hook 'post-command-hook 'org-read-date-display)
17297 (use-local-map old-map)
17298 (when org-read-date-overlay
17299 (org-delete-overlay org-read-date-overlay)
17300 (setq org-read-date-overlay nil)))))))
17302 (t ; Naked prompt only
17303 (unwind-protect
17304 (setq ans (read-string prompt default-input nil timestr))
17305 (when org-read-date-overlay
17306 (org-delete-overlay org-read-date-overlay)
17307 (setq org-read-date-overlay nil)))))
17309 (setq final (org-read-date-analyze ans def defdecode))
17311 (if to-time
17312 (apply 'encode-time final)
17313 (if (and (boundp 'org-time-was-given) org-time-was-given)
17314 (format "%04d-%02d-%02d %02d:%02d"
17315 (nth 5 final) (nth 4 final) (nth 3 final)
17316 (nth 2 final) (nth 1 final))
17317 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17318 (defvar def)
17319 (defvar defdecode)
17320 (defvar with-time)
17321 (defun org-read-date-display ()
17322 "Display the currrent date prompt interpretation in the minibuffer."
17323 (when org-read-date-display-live
17324 (when org-read-date-overlay
17325 (org-delete-overlay org-read-date-overlay))
17326 (let ((p (point)))
17327 (end-of-line 1)
17328 (while (not (equal (buffer-substring
17329 (max (point-min) (- (point) 4)) (point))
17330 " "))
17331 (insert " "))
17332 (goto-char p))
17333 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17334 " " (or org-ans1 org-ans2)))
17335 (org-end-time-was-given nil)
17336 (f (org-read-date-analyze ans def defdecode))
17337 (fmts (if org-dcst
17338 org-time-stamp-custom-formats
17339 org-time-stamp-formats))
17340 (fmt (if (or with-time
17341 (and (boundp 'org-time-was-given) org-time-was-given))
17342 (cdr fmts)
17343 (car fmts)))
17344 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17345 (when (and org-end-time-was-given
17346 (string-match org-plain-time-of-day-regexp txt))
17347 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17348 org-end-time-was-given
17349 (substring txt (match-end 0)))))
17350 (setq org-read-date-overlay
17351 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17352 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17354 (defun org-read-date-analyze (ans def defdecode)
17355 "Analyze the combined answer of the date prompt."
17356 ;; FIXME: cleanup and comment
17357 (let (delta deltan deltaw deltadef year month day
17358 hour minute second wday pm h2 m2 tl wday1)
17360 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17361 (setq ans (replace-match "" t t ans)
17362 deltan (car delta)
17363 deltaw (nth 1 delta)
17364 deltadef (nth 2 delta)))
17366 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17367 (when (string-match
17368 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17369 (setq year (if (match-end 2)
17370 (string-to-number (match-string 2 ans))
17371 (string-to-number (format-time-string "%Y")))
17372 month (string-to-number (match-string 3 ans))
17373 day (string-to-number (match-string 4 ans)))
17374 (if (< year 100) (setq year (+ 2000 year)))
17375 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17376 t nil ans)))
17377 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17378 ;; If there is a time with am/pm, and *no* time without it, we convert
17379 ;; so that matching will be successful.
17380 (loop for i from 1 to 2 do ; twice, for end time as well
17381 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17382 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17383 (setq hour (string-to-number (match-string 1 ans))
17384 minute (if (match-end 3)
17385 (string-to-number (match-string 3 ans))
17387 pm (equal ?p
17388 (string-to-char (downcase (match-string 4 ans)))))
17389 (if (and (= hour 12) (not pm))
17390 (setq hour 0)
17391 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17392 (setq ans (replace-match (format "%02d:%02d" hour minute)
17393 t t ans))))
17395 ;; Check if a time range is given as a duration
17396 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17397 (setq hour (string-to-number (match-string 1 ans))
17398 h2 (+ hour (string-to-number (match-string 3 ans)))
17399 minute (string-to-number (match-string 2 ans))
17400 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17401 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17402 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17404 ;; Check if there is a time range
17405 (when (boundp 'org-end-time-was-given)
17406 (setq org-time-was-given nil)
17407 (when (and (string-match org-plain-time-of-day-regexp ans)
17408 (match-end 8))
17409 (setq org-end-time-was-given (match-string 8 ans))
17410 (setq ans (concat (substring ans 0 (match-beginning 7))
17411 (substring ans (match-end 7))))))
17413 (setq tl (parse-time-string ans)
17414 day (or (nth 3 tl) (nth 3 defdecode))
17415 month (or (nth 4 tl)
17416 (if (and org-read-date-prefer-future
17417 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17418 (1+ (nth 4 defdecode))
17419 (nth 4 defdecode)))
17420 year (or (nth 5 tl)
17421 (if (and org-read-date-prefer-future
17422 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17423 (1+ (nth 5 defdecode))
17424 (nth 5 defdecode)))
17425 hour (or (nth 2 tl) (nth 2 defdecode))
17426 minute (or (nth 1 tl) (nth 1 defdecode))
17427 second (or (nth 0 tl) 0)
17428 wday (nth 6 tl))
17429 (when deltan
17430 (unless deltadef
17431 (let ((now (decode-time (current-time))))
17432 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17433 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17434 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17435 ((equal deltaw "m") (setq month (+ month deltan)))
17436 ((equal deltaw "y") (setq year (+ year deltan)))))
17437 (when (and wday (not (nth 3 tl)))
17438 ;; Weekday was given, but no day, so pick that day in the week
17439 ;; on or after the derived date.
17440 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17441 (unless (equal wday wday1)
17442 (setq day (+ day (% (- wday wday1 -7) 7)))))
17443 (if (and (boundp 'org-time-was-given)
17444 (nth 2 tl))
17445 (setq org-time-was-given t))
17446 (if (< year 100) (setq year (+ 2000 year)))
17447 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17448 (list second minute hour day month year)))
17450 (defvar parse-time-weekdays)
17452 (defun org-read-date-get-relative (s today default)
17453 "Check string S for special relative date string.
17454 TODAY and DEFAULT are internal times, for today and for a default.
17455 Return shift list (N what def-flag)
17456 WHAT is \"d\", \"w\", \"m\", or \"y\" for day. week, month, year.
17457 N is the number if WHATs to shift
17458 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17459 the DEFAULT date rather than TODAY."
17460 (when (string-match
17461 (concat
17462 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17463 "\\([0-9]+\\)?"
17464 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17465 "\\([ \t]\\|$\\)") s)
17466 (let* ((dir (if (match-end 1)
17467 (string-to-char (substring (match-string 1 s) -1))
17468 ?+))
17469 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17470 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17471 (what (if (match-end 3) (match-string 3 s) "d"))
17472 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17473 (date (if rel default today))
17474 (wday (nth 6 (decode-time date)))
17475 delta)
17476 (if wday1
17477 (progn
17478 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17479 (if (= dir ?-) (setq delta (- delta 7)))
17480 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17481 (list delta "d" rel))
17482 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17484 (defun org-eval-in-calendar (form &optional keepdate)
17485 "Eval FORM in the calendar window and return to current window.
17486 Also, store the cursor date in variable org-ans2."
17487 (let ((sw (selected-window)))
17488 (select-window (get-buffer-window "*Calendar*"))
17489 (eval form)
17490 (when (and (not keepdate) (calendar-cursor-to-date))
17491 (let* ((date (calendar-cursor-to-date))
17492 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17493 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17494 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17495 (select-window sw)))
17497 ; ;; Update the prompt to show new default date
17498 ; (save-excursion
17499 ; (goto-char (point-min))
17500 ; (when (and org-ans2
17501 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17502 ; (get-text-property (match-end 0) 'field))
17503 ; (let ((inhibit-read-only t))
17504 ; (replace-match (concat "[" org-ans2 "]") t t)
17505 ; (add-text-properties (point-min) (1+ (match-end 0))
17506 ; (text-properties-at (1+ (point-min)))))))))
17508 (defun org-calendar-select ()
17509 "Return to `org-read-date' with the date currently selected.
17510 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17511 (interactive)
17512 (when (calendar-cursor-to-date)
17513 (let* ((date (calendar-cursor-to-date))
17514 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17515 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17516 (if (active-minibuffer-window) (exit-minibuffer))))
17518 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17519 "Insert a date stamp for the date given by the internal TIME.
17520 WITH-HM means, use the stamp format that includes the time of the day.
17521 INACTIVE means use square brackets instead of angular ones, so that the
17522 stamp will not contribute to the agenda.
17523 PRE and POST are optional strings to be inserted before and after the
17524 stamp.
17525 The command returns the inserted time stamp."
17526 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17527 stamp)
17528 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17529 (insert-before-markers (or pre ""))
17530 (insert-before-markers (setq stamp (format-time-string fmt time)))
17531 (when (listp extra)
17532 (setq extra (car extra))
17533 (if (and (stringp extra)
17534 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17535 (setq extra (format "-%02d:%02d"
17536 (string-to-number (match-string 1 extra))
17537 (string-to-number (match-string 2 extra))))
17538 (setq extra nil)))
17539 (when extra
17540 (backward-char 1)
17541 (insert-before-markers extra)
17542 (forward-char 1))
17543 (insert-before-markers (or post ""))
17544 stamp))
17546 (defun org-toggle-time-stamp-overlays ()
17547 "Toggle the use of custom time stamp formats."
17548 (interactive)
17549 (setq org-display-custom-times (not org-display-custom-times))
17550 (unless org-display-custom-times
17551 (let ((p (point-min)) (bmp (buffer-modified-p)))
17552 (while (setq p (next-single-property-change p 'display))
17553 (if (and (get-text-property p 'display)
17554 (eq (get-text-property p 'face) 'org-date))
17555 (remove-text-properties
17556 p (setq p (next-single-property-change p 'display))
17557 '(display t))))
17558 (set-buffer-modified-p bmp)))
17559 (if (featurep 'xemacs)
17560 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17561 (org-restart-font-lock)
17562 (setq org-table-may-need-update t)
17563 (if org-display-custom-times
17564 (message "Time stamps are overlayed with custom format")
17565 (message "Time stamp overlays removed")))
17567 (defun org-display-custom-time (beg end)
17568 "Overlay modified time stamp format over timestamp between BED and END."
17569 (let* ((ts (buffer-substring beg end))
17570 t1 w1 with-hm tf time str w2 (off 0))
17571 (save-match-data
17572 (setq t1 (org-parse-time-string ts t))
17573 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17574 (setq off (- (match-end 0) (match-beginning 0)))))
17575 (setq end (- end off))
17576 (setq w1 (- end beg)
17577 with-hm (and (nth 1 t1) (nth 2 t1))
17578 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17579 time (org-fix-decoded-time t1)
17580 str (org-add-props
17581 (format-time-string
17582 (substring tf 1 -1) (apply 'encode-time time))
17583 nil 'mouse-face 'highlight)
17584 w2 (length str))
17585 (if (not (= w2 w1))
17586 (add-text-properties (1+ beg) (+ 2 beg)
17587 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17588 (if (featurep 'xemacs)
17589 (progn
17590 (put-text-property beg end 'invisible t)
17591 (put-text-property beg end 'end-glyph (make-glyph str)))
17592 (put-text-property beg end 'display str))))
17594 (defun org-translate-time (string)
17595 "Translate all timestamps in STRING to custom format.
17596 But do this only if the variable `org-display-custom-times' is set."
17597 (when org-display-custom-times
17598 (save-match-data
17599 (let* ((start 0)
17600 (re org-ts-regexp-both)
17601 t1 with-hm inactive tf time str beg end)
17602 (while (setq start (string-match re string start))
17603 (setq beg (match-beginning 0)
17604 end (match-end 0)
17605 t1 (save-match-data
17606 (org-parse-time-string (substring string beg end) t))
17607 with-hm (and (nth 1 t1) (nth 2 t1))
17608 inactive (equal (substring string beg (1+ beg)) "[")
17609 tf (funcall (if with-hm 'cdr 'car)
17610 org-time-stamp-custom-formats)
17611 time (org-fix-decoded-time t1)
17612 str (format-time-string
17613 (concat
17614 (if inactive "[" "<") (substring tf 1 -1)
17615 (if inactive "]" ">"))
17616 (apply 'encode-time time))
17617 string (replace-match str t t string)
17618 start (+ start (length str)))))))
17619 string)
17621 (defun org-fix-decoded-time (time)
17622 "Set 0 instead of nil for the first 6 elements of time.
17623 Don't touch the rest."
17624 (let ((n 0))
17625 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17627 (defun org-days-to-time (timestamp-string)
17628 "Difference between TIMESTAMP-STRING and now in days."
17629 (- (time-to-days (org-time-string-to-time timestamp-string))
17630 (time-to-days (current-time))))
17632 (defun org-deadline-close (timestamp-string &optional ndays)
17633 "Is the time in TIMESTAMP-STRING close to the current date?"
17634 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17635 (and (< (org-days-to-time timestamp-string) ndays)
17636 (not (org-entry-is-done-p))))
17638 (defun org-get-wdays (ts)
17639 "Get the deadline lead time appropriate for timestring TS."
17640 (cond
17641 ((<= org-deadline-warning-days 0)
17642 ;; 0 or negative, enforce this value no matter what
17643 (- org-deadline-warning-days))
17644 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17645 ;; lead time is specified.
17646 (floor (* (string-to-number (match-string 1 ts))
17647 (cdr (assoc (match-string 2 ts)
17648 '(("d" . 1) ("w" . 7)
17649 ("m" . 30.4) ("y" . 365.25)))))))
17650 ;; go for the default.
17651 (t org-deadline-warning-days)))
17653 (defun org-calendar-select-mouse (ev)
17654 "Return to `org-read-date' with the date currently selected.
17655 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17656 (interactive "e")
17657 (mouse-set-point ev)
17658 (when (calendar-cursor-to-date)
17659 (let* ((date (calendar-cursor-to-date))
17660 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17661 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17662 (if (active-minibuffer-window) (exit-minibuffer))))
17664 (defun org-check-deadlines (ndays)
17665 "Check if there are any deadlines due or past due.
17666 A deadline is considered due if it happens within `org-deadline-warning-days'
17667 days from today's date. If the deadline appears in an entry marked DONE,
17668 it is not shown. The prefix arg NDAYS can be used to test that many
17669 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17670 (interactive "P")
17671 (let* ((org-warn-days
17672 (cond
17673 ((equal ndays '(4)) 100000)
17674 (ndays (prefix-numeric-value ndays))
17675 (t (abs org-deadline-warning-days))))
17676 (case-fold-search nil)
17677 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17678 (callback
17679 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17681 (message "%d deadlines past-due or due within %d days"
17682 (org-occur regexp nil callback)
17683 org-warn-days)))
17685 (defun org-check-before-date (date)
17686 "Check if there are deadlines or scheduled entries before DATE."
17687 (interactive (list (org-read-date)))
17688 (let ((case-fold-search nil)
17689 (regexp (concat "\\<\\(" org-deadline-string
17690 "\\|" org-scheduled-string
17691 "\\) *<\\([^>]+\\)>"))
17692 (callback
17693 (lambda () (time-less-p
17694 (org-time-string-to-time (match-string 2))
17695 (org-time-string-to-time date)))))
17696 (message "%d entries before %s"
17697 (org-occur regexp nil callback) date)))
17699 (defun org-evaluate-time-range (&optional to-buffer)
17700 "Evaluate a time range by computing the difference between start and end.
17701 Normally the result is just printed in the echo area, but with prefix arg
17702 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17703 If the time range is actually in a table, the result is inserted into the
17704 next column.
17705 For time difference computation, a year is assumed to be exactly 365
17706 days in order to avoid rounding problems."
17707 (interactive "P")
17709 (org-clock-update-time-maybe)
17710 (save-excursion
17711 (unless (org-at-date-range-p t)
17712 (goto-char (point-at-bol))
17713 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17714 (if (not (org-at-date-range-p t))
17715 (error "Not at a time-stamp range, and none found in current line")))
17716 (let* ((ts1 (match-string 1))
17717 (ts2 (match-string 2))
17718 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17719 (match-end (match-end 0))
17720 (time1 (org-time-string-to-time ts1))
17721 (time2 (org-time-string-to-time ts2))
17722 (t1 (time-to-seconds time1))
17723 (t2 (time-to-seconds time2))
17724 (diff (abs (- t2 t1)))
17725 (negative (< (- t2 t1) 0))
17726 ;; (ys (floor (* 365 24 60 60)))
17727 (ds (* 24 60 60))
17728 (hs (* 60 60))
17729 (fy "%dy %dd %02d:%02d")
17730 (fy1 "%dy %dd")
17731 (fd "%dd %02d:%02d")
17732 (fd1 "%dd")
17733 (fh "%02d:%02d")
17734 y d h m align)
17735 (if havetime
17736 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17738 d (floor (/ diff ds)) diff (mod diff ds)
17739 h (floor (/ diff hs)) diff (mod diff hs)
17740 m (floor (/ diff 60)))
17741 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17743 d (floor (+ (/ diff ds) 0.5))
17744 h 0 m 0))
17745 (if (not to-buffer)
17746 (message "%s" (org-make-tdiff-string y d h m))
17747 (if (org-at-table-p)
17748 (progn
17749 (goto-char match-end)
17750 (setq align t)
17751 (and (looking-at " *|") (goto-char (match-end 0))))
17752 (goto-char match-end))
17753 (if (looking-at
17754 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17755 (replace-match ""))
17756 (if negative (insert " -"))
17757 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17758 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17759 (insert " " (format fh h m))))
17760 (if align (org-table-align))
17761 (message "Time difference inserted")))))
17763 (defun org-make-tdiff-string (y d h m)
17764 (let ((fmt "")
17765 (l nil))
17766 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17767 l (push y l)))
17768 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17769 l (push d l)))
17770 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17771 l (push h l)))
17772 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17773 l (push m l)))
17774 (apply 'format fmt (nreverse l))))
17776 (defun org-time-string-to-time (s)
17777 (apply 'encode-time (org-parse-time-string s)))
17779 (defun org-time-string-to-absolute (s &optional daynr)
17780 "Convert a time stamp to an absolute day number.
17781 If there is a specifyer for a cyclic time stamp, get the closest date to
17782 DAYNR."
17783 (cond
17784 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17785 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17786 daynr
17787 (+ daynr 1000)))
17788 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
17789 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17790 (time-to-days (current-time))) (match-string 0 s)))
17791 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
17793 (defun org-time-from-absolute (d)
17794 "Return the time corresponding to date D.
17795 D may be an absolute day number, or a calendar-type list (month day year)."
17796 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17797 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17799 (defun org-calendar-holiday ()
17800 "List of holidays, for Diary display in Org-mode."
17801 (require 'holidays)
17802 (let ((hl (funcall
17803 (if (fboundp 'calendar-check-holidays)
17804 'calendar-check-holidays 'check-calendar-holidays) date)))
17805 (if hl (mapconcat 'identity hl "; "))))
17807 (defun org-diary-sexp-entry (sexp entry date)
17808 "Process a SEXP diary ENTRY for DATE."
17809 (require 'diary-lib)
17810 (let ((result (if calendar-debug-sexp
17811 (let ((stack-trace-on-error t))
17812 (eval (car (read-from-string sexp))))
17813 (condition-case nil
17814 (eval (car (read-from-string sexp)))
17815 (error
17816 (beep)
17817 (message "Bad sexp at line %d in %s: %s"
17818 (org-current-line)
17819 (buffer-file-name) sexp)
17820 (sleep-for 2))))))
17821 (cond ((stringp result) result)
17822 ((and (consp result)
17823 (stringp (cdr result))) (cdr result))
17824 (result entry)
17825 (t nil))))
17827 (defun org-diary-to-ical-string (frombuf)
17828 "Get iCalendar entries from diary entries in buffer FROMBUF.
17829 This uses the icalendar.el library."
17830 (let* ((tmpdir (if (featurep 'xemacs)
17831 (temp-directory)
17832 temporary-file-directory))
17833 (tmpfile (make-temp-name
17834 (expand-file-name "orgics" tmpdir)))
17835 buf rtn b e)
17836 (save-excursion
17837 (set-buffer frombuf)
17838 (icalendar-export-region (point-min) (point-max) tmpfile)
17839 (setq buf (find-buffer-visiting tmpfile))
17840 (set-buffer buf)
17841 (goto-char (point-min))
17842 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17843 (setq b (match-beginning 0)))
17844 (goto-char (point-max))
17845 (if (re-search-backward "^END:VEVENT" nil t)
17846 (setq e (match-end 0)))
17847 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17848 (kill-buffer buf)
17849 (kill-buffer frombuf)
17850 (delete-file tmpfile)
17851 rtn))
17853 (defun org-closest-date (start current change)
17854 "Find the date closest to CURRENT that is consistent with START and CHANGE."
17855 ;; Make the proper lists from the dates
17856 (catch 'exit
17857 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
17858 dn dw sday cday n1 n2
17859 d m y y1 y2 date1 date2 nmonths nm ny m2)
17861 (setq start (org-date-to-gregorian start)
17862 current (org-date-to-gregorian
17863 (if org-agenda-repeating-timestamp-show-all
17864 current
17865 (time-to-days (current-time))))
17866 sday (calendar-absolute-from-gregorian start)
17867 cday (calendar-absolute-from-gregorian current))
17869 (if (<= cday sday) (throw 'exit sday))
17871 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
17872 (setq dn (string-to-number (match-string 1 change))
17873 dw (cdr (assoc (match-string 2 change) a1)))
17874 (error "Invalid change specifyer: %s" change))
17875 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17876 (cond
17877 ((eq dw 'day)
17878 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17879 n2 (+ n1 dn)))
17880 ((eq dw 'year)
17881 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17882 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17883 (setq date1 (list m d y1)
17884 n1 (calendar-absolute-from-gregorian date1)
17885 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17886 n2 (calendar-absolute-from-gregorian date2)))
17887 ((eq dw 'month)
17888 ;; approx number of month between the tow dates
17889 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17890 ;; How often does dn fit in there?
17891 (setq d (nth 1 start) m (car start) y (nth 2 start)
17892 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17893 m (+ m nm)
17894 ny (floor (/ m 12))
17895 y (+ y ny)
17896 m (- m (* ny 12)))
17897 (while (> m 12) (setq m (- m 12) y (1+ y)))
17898 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17899 (setq m2 (+ m dn) y2 y)
17900 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17901 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17902 (while (< n2 cday)
17903 (setq n1 n2 m m2 y y2)
17904 (setq m2 (+ m dn) y2 y)
17905 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17906 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17908 (if org-agenda-repeating-timestamp-show-all
17909 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
17910 (if (= cday n1) n1 n2)))))
17912 (defun org-date-to-gregorian (date)
17913 "Turn any specification of DATE into a gregorian date for the calendar."
17914 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17915 ((and (listp date) (= (length date) 3)) date)
17916 ((stringp date)
17917 (setq date (org-parse-time-string date))
17918 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17919 ((listp date)
17920 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17922 (defun org-parse-time-string (s &optional nodefault)
17923 "Parse the standard Org-mode time string.
17924 This should be a lot faster than the normal `parse-time-string'.
17925 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17926 hour and minute fields will be nil if not given."
17927 (if (string-match org-ts-regexp0 s)
17928 (list 0
17929 (if (or (match-beginning 8) (not nodefault))
17930 (string-to-number (or (match-string 8 s) "0")))
17931 (if (or (match-beginning 7) (not nodefault))
17932 (string-to-number (or (match-string 7 s) "0")))
17933 (string-to-number (match-string 4 s))
17934 (string-to-number (match-string 3 s))
17935 (string-to-number (match-string 2 s))
17936 nil nil nil)
17937 (make-list 9 0)))
17939 (defun org-timestamp-up (&optional arg)
17940 "Increase the date item at the cursor by one.
17941 If the cursor is on the year, change the year. If it is on the month or
17942 the day, change that.
17943 With prefix ARG, change by that many units."
17944 (interactive "p")
17945 (org-timestamp-change (prefix-numeric-value arg)))
17947 (defun org-timestamp-down (&optional arg)
17948 "Decrease the date item at the cursor by one.
17949 If the cursor is on the year, change the year. If it is on the month or
17950 the day, change that.
17951 With prefix ARG, change by that many units."
17952 (interactive "p")
17953 (org-timestamp-change (- (prefix-numeric-value arg))))
17955 (defun org-timestamp-up-day (&optional arg)
17956 "Increase the date in the time stamp by one day.
17957 With prefix ARG, change that many days."
17958 (interactive "p")
17959 (if (and (not (org-at-timestamp-p t))
17960 (org-on-heading-p))
17961 (org-todo 'up)
17962 (org-timestamp-change (prefix-numeric-value arg) 'day)))
17964 (defun org-timestamp-down-day (&optional arg)
17965 "Decrease the date in the time stamp by one day.
17966 With prefix ARG, change that many days."
17967 (interactive "p")
17968 (if (and (not (org-at-timestamp-p t))
17969 (org-on-heading-p))
17970 (org-todo 'down)
17971 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
17973 (defsubst org-pos-in-match-range (pos n)
17974 (and (match-beginning n)
17975 (<= (match-beginning n) pos)
17976 (>= (match-end n) pos)))
17978 (defun org-at-timestamp-p (&optional inactive-ok)
17979 "Determine if the cursor is in or at a timestamp."
17980 (interactive)
17981 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17982 (pos (point))
17983 (ans (or (looking-at tsr)
17984 (save-excursion
17985 (skip-chars-backward "^[<\n\r\t")
17986 (if (> (point) (point-min)) (backward-char 1))
17987 (and (looking-at tsr)
17988 (> (- (match-end 0) pos) -1))))))
17989 (and ans
17990 (boundp 'org-ts-what)
17991 (setq org-ts-what
17992 (cond
17993 ((= pos (match-beginning 0)) 'bracket)
17994 ((= pos (1- (match-end 0))) 'bracket)
17995 ((org-pos-in-match-range pos 2) 'year)
17996 ((org-pos-in-match-range pos 3) 'month)
17997 ((org-pos-in-match-range pos 7) 'hour)
17998 ((org-pos-in-match-range pos 8) 'minute)
17999 ((or (org-pos-in-match-range pos 4)
18000 (org-pos-in-match-range pos 5)) 'day)
18001 ((and (> pos (or (match-end 8) (match-end 5)))
18002 (< pos (match-end 0)))
18003 (- pos (or (match-end 8) (match-end 5))))
18004 (t 'day))))
18005 ans))
18007 (defun org-toggle-timestamp-type ()
18009 (interactive)
18010 (when (org-at-timestamp-p t)
18011 (save-excursion
18012 (goto-char (match-beginning 0))
18013 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18014 (goto-char (1- (match-end 0)))
18015 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18016 (message "Timestamp is now %sactive"
18017 (if (equal (char-before) ?>) "in" ""))))
18019 (defun org-timestamp-change (n &optional what)
18020 "Change the date in the time stamp at point.
18021 The date will be changed by N times WHAT. WHAT can be `day', `month',
18022 `year', `minute', `second'. If WHAT is not given, the cursor position
18023 in the timestamp determines what will be changed."
18024 (let ((pos (point))
18025 with-hm inactive
18026 org-ts-what
18027 extra
18028 ts time time0)
18029 (if (not (org-at-timestamp-p t))
18030 (error "Not at a timestamp"))
18031 (if (and (not what) (eq org-ts-what 'bracket))
18032 (org-toggle-timestamp-type)
18033 (if (and (not what) (not (eq org-ts-what 'day))
18034 org-display-custom-times
18035 (get-text-property (point) 'display)
18036 (not (get-text-property (1- (point)) 'display)))
18037 (setq org-ts-what 'day))
18038 (setq org-ts-what (or what org-ts-what)
18039 inactive (= (char-after (match-beginning 0)) ?\[)
18040 ts (match-string 0))
18041 (replace-match "")
18042 (if (string-match
18043 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18045 (setq extra (match-string 1 ts)))
18046 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18047 (setq with-hm t))
18048 (setq time0 (org-parse-time-string ts))
18049 (setq time
18050 (encode-time (or (car time0) 0)
18051 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18052 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18053 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18054 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18055 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18056 (nthcdr 6 time0)))
18057 (when (integerp org-ts-what)
18058 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18059 (if (eq what 'calendar)
18060 (let ((cal-date (org-get-date-from-calendar)))
18061 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18062 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18063 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18064 (setcar time0 (or (car time0) 0))
18065 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18066 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18067 (setq time (apply 'encode-time time0))))
18068 (setq org-last-changed-timestamp
18069 (org-insert-time-stamp time with-hm inactive nil nil extra))
18070 (org-clock-update-time-maybe)
18071 (goto-char pos)
18072 ;; Try to recenter the calendar window, if any
18073 (if (and org-calendar-follow-timestamp-change
18074 (get-buffer-window "*Calendar*" t)
18075 (memq org-ts-what '(day month year)))
18076 (org-recenter-calendar (time-to-days time))))))
18078 ;; FIXME: does not yet work for lead times
18079 (defun org-modify-ts-extra (s pos n)
18080 "Change the different parts of the lead-time and repeat fields in timestamp."
18081 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18082 ng h m new)
18083 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18084 (cond
18085 ((or (org-pos-in-match-range pos 2)
18086 (org-pos-in-match-range pos 3))
18087 (setq m (string-to-number (match-string 3 s))
18088 h (string-to-number (match-string 2 s)))
18089 (if (org-pos-in-match-range pos 2)
18090 (setq h (+ h n))
18091 (setq m (+ m n)))
18092 (if (< m 0) (setq m (+ m 60) h (1- h)))
18093 (if (> m 59) (setq m (- m 60) h (1+ h)))
18094 (setq h (min 24 (max 0 h)))
18095 (setq ng 1 new (format "-%02d:%02d" h m)))
18096 ((org-pos-in-match-range pos 6)
18097 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18098 ((org-pos-in-match-range pos 5)
18099 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18101 (when ng
18102 (setq s (concat
18103 (substring s 0 (match-beginning ng))
18105 (substring s (match-end ng))))))
18108 (defun org-recenter-calendar (date)
18109 "If the calendar is visible, recenter it to DATE."
18110 (let* ((win (selected-window))
18111 (cwin (get-buffer-window "*Calendar*" t))
18112 (calendar-move-hook nil))
18113 (when cwin
18114 (select-window cwin)
18115 (calendar-goto-date (if (listp date) date
18116 (calendar-gregorian-from-absolute date)))
18117 (select-window win))))
18119 (defun org-goto-calendar (&optional arg)
18120 "Go to the Emacs calendar at the current date.
18121 If there is a time stamp in the current line, go to that date.
18122 A prefix ARG can be used to force the current date."
18123 (interactive "P")
18124 (let ((tsr org-ts-regexp) diff
18125 (calendar-move-hook nil)
18126 (view-calendar-holidays-initially nil)
18127 (view-diary-entries-initially nil))
18128 (if (or (org-at-timestamp-p)
18129 (save-excursion
18130 (beginning-of-line 1)
18131 (looking-at (concat ".*" tsr))))
18132 (let ((d1 (time-to-days (current-time)))
18133 (d2 (time-to-days
18134 (org-time-string-to-time (match-string 1)))))
18135 (setq diff (- d2 d1))))
18136 (calendar)
18137 (calendar-goto-today)
18138 (if (and diff (not arg)) (calendar-forward-day diff))))
18140 (defun org-get-date-from-calendar ()
18141 "Return a list (month day year) of date at point in calendar."
18142 (with-current-buffer "*Calendar*"
18143 (save-match-data
18144 (calendar-cursor-to-date))))
18146 (defun org-date-from-calendar ()
18147 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18148 If there is already a time stamp at the cursor position, update it."
18149 (interactive)
18150 (if (org-at-timestamp-p t)
18151 (org-timestamp-change 0 'calendar)
18152 (let ((cal-date (org-get-date-from-calendar)))
18153 (org-insert-time-stamp
18154 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18156 ;; Make appt aware of appointments from the agenda
18157 ;;;###autoload
18158 (defun org-agenda-to-appt (&optional filter)
18159 "Activate appointments found in `org-agenda-files'.
18160 When prefixed, prompt for a regular expression and use it as a
18161 filter: only add entries if they match this regular expression.
18163 FILTER can be a string. In this case, use this string as a
18164 regular expression to filter results.
18166 FILTER can also be an alist, with the car of each cell being
18167 either 'headline or 'category. For example:
18169 '((headline \"IMPORTANT\")
18170 (category \"Work\"))
18172 will only add headlines containing IMPORTANT or headlines
18173 belonging to the category \"Work\"."
18174 (interactive "P")
18175 (require 'calendar)
18176 (if (equal filter '(4))
18177 (setq filter (read-from-minibuffer "Regexp filter: ")))
18178 (let* ((cnt 0) ; count added events
18179 (org-agenda-new-buffers nil)
18180 (today (org-date-to-gregorian
18181 (time-to-days (current-time))))
18182 (files (org-agenda-files)) entries file)
18183 ;; Get all entries which may contain an appt
18184 (while (setq file (pop files))
18185 (setq entries
18186 (append entries
18187 (org-agenda-get-day-entries
18188 file today
18189 :timestamp :scheduled :deadline))))
18190 (setq entries (delq nil entries))
18191 ;; Map thru entries and find if they pass thru the filter
18192 (mapc
18193 (lambda(x)
18194 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18195 (cat (get-text-property 1 'org-category x))
18196 (tod (get-text-property 1 'time-of-day x))
18197 (ok (or (null filter)
18198 (and (stringp filter) (string-match filter evt))
18199 (and (listp filter)
18200 (or (string-match
18201 (cadr (assoc 'category filter)) cat)
18202 (string-match
18203 (cadr (assoc 'headline filter)) evt))))))
18204 ;; FIXME: Shall we remove text-properties for the appt text?
18205 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18206 (when (and ok tod)
18207 (setq tod (number-to-string tod)
18208 tod (when (string-match
18209 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18210 (concat (match-string 1 tod) ":"
18211 (match-string 2 tod))))
18212 (appt-add tod evt)
18213 (setq cnt (1+ cnt))))) entries)
18214 (org-release-buffers org-agenda-new-buffers)
18215 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
18217 ;;; The clock for measuring work time.
18219 (defvar org-mode-line-string "")
18220 (put 'org-mode-line-string 'risky-local-variable t)
18222 (defvar org-mode-line-timer nil)
18223 (defvar org-clock-heading "")
18224 (defvar org-clock-start-time "")
18226 (defun org-update-mode-line ()
18227 (let* ((delta (- (time-to-seconds (current-time))
18228 (time-to-seconds org-clock-start-time)))
18229 (h (floor delta 3600))
18230 (m (floor (- delta (* 3600 h)) 60)))
18231 (setq org-mode-line-string
18232 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18233 'help-echo "Org-mode clock is running"))
18234 (force-mode-line-update)))
18236 (defvar org-clock-marker (make-marker)
18237 "Marker recording the last clock-in.")
18238 (defvar org-clock-mode-line-entry nil
18239 "Information for the modeline about the running clock.")
18241 (defun org-clock-in ()
18242 "Start the clock on the current item.
18243 If necessary, clock-out of the currently active clock."
18244 (interactive)
18245 (org-clock-out t)
18246 (let (ts)
18247 (save-excursion
18248 (org-back-to-heading t)
18249 (when (and org-clock-in-switch-to-state
18250 (not (looking-at (concat outline-regexp "[ \t]*"
18251 org-clock-in-switch-to-state
18252 "\\>"))))
18253 (org-todo org-clock-in-switch-to-state))
18254 (if (and org-clock-heading-function
18255 (functionp org-clock-heading-function))
18256 (setq org-clock-heading (funcall org-clock-heading-function))
18257 (if (looking-at org-complex-heading-regexp)
18258 (setq org-clock-heading (match-string 4))
18259 (setq org-clock-heading "???")))
18260 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18261 (org-clock-find-position)
18263 (insert "\n") (backward-char 1)
18264 (indent-relative)
18265 (insert org-clock-string " ")
18266 (setq org-clock-start-time (current-time))
18267 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18268 (move-marker org-clock-marker (point) (buffer-base-buffer))
18269 (or global-mode-string (setq global-mode-string '("")))
18270 (or (memq 'org-mode-line-string global-mode-string)
18271 (setq global-mode-string
18272 (append global-mode-string '(org-mode-line-string))))
18273 (org-update-mode-line)
18274 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18275 (message "Clock started at %s" ts))))
18277 (defun org-clock-find-position ()
18278 "Find the location where the next clock line should be inserted."
18279 (org-back-to-heading t)
18280 (catch 'exit
18281 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18282 (re (concat "^[ \t]*" org-clock-string))
18283 (cnt 0)
18284 first last)
18285 (goto-char beg)
18286 (when (eobp) (newline) (setq end (max (point) end)))
18287 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18288 ;; we seem to have a CLOCK drawer, so go there.
18289 (beginning-of-line 2)
18290 (throw 'exit t))
18291 ;; Lets count the CLOCK lines
18292 (goto-char beg)
18293 (while (re-search-forward re end t)
18294 (setq first (or first (match-beginning 0))
18295 last (match-beginning 0)
18296 cnt (1+ cnt)))
18297 (when (and (integerp org-clock-into-drawer)
18298 (>= (1+ cnt) org-clock-into-drawer))
18299 ;; Wrap current entries into a new drawer
18300 (goto-char last)
18301 (beginning-of-line 2)
18302 (if (org-at-item-p) (org-end-of-item))
18303 (insert ":END:\n")
18304 (beginning-of-line 0)
18305 (org-indent-line-function)
18306 (goto-char first)
18307 (insert ":CLOCK:\n")
18308 (beginning-of-line 0)
18309 (org-indent-line-function)
18310 (org-flag-drawer t)
18311 (beginning-of-line 2)
18312 (throw 'exit nil))
18314 (goto-char beg)
18315 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18316 (not (equal (match-string 1) org-clock-string)))
18317 ;; Planning info, skip to after it
18318 (beginning-of-line 2)
18319 (or (bolp) (newline)))
18320 (when (eq t org-clock-into-drawer)
18321 (insert ":CLOCK:\n:END:\n")
18322 (beginning-of-line -1)
18323 (org-indent-line-function)
18324 (org-flag-drawer t)
18325 (beginning-of-line 2)
18326 (org-indent-line-function)))))
18328 (defun org-clock-out (&optional fail-quietly)
18329 "Stop the currently running clock.
18330 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18331 (interactive)
18332 (catch 'exit
18333 (if (not (marker-buffer org-clock-marker))
18334 (if fail-quietly (throw 'exit t) (error "No active clock")))
18335 (let (ts te s h m)
18336 (save-excursion
18337 (set-buffer (marker-buffer org-clock-marker))
18338 (goto-char org-clock-marker)
18339 (beginning-of-line 1)
18340 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18341 (equal (match-string 1) org-clock-string))
18342 (setq ts (match-string 2))
18343 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18344 (goto-char (match-end 0))
18345 (delete-region (point) (point-at-eol))
18346 (insert "--")
18347 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18348 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18349 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18350 h (floor (/ s 3600))
18351 s (- s (* 3600 h))
18352 m (floor (/ s 60))
18353 s (- s (* 60 s)))
18354 (insert " => " (format "%2d:%02d" h m))
18355 (move-marker org-clock-marker nil)
18356 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
18357 (org-log-done (org-parse-local-options logging 'org-log-done))
18358 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
18359 (org-add-log-maybe 'clock-out))
18360 (when org-mode-line-timer
18361 (cancel-timer org-mode-line-timer)
18362 (setq org-mode-line-timer nil))
18363 (setq global-mode-string
18364 (delq 'org-mode-line-string global-mode-string))
18365 (force-mode-line-update)
18366 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18368 (defun org-clock-cancel ()
18369 "Cancel the running clock be removing the start timestamp."
18370 (interactive)
18371 (if (not (marker-buffer org-clock-marker))
18372 (error "No active clock"))
18373 (save-excursion
18374 (set-buffer (marker-buffer org-clock-marker))
18375 (goto-char org-clock-marker)
18376 (delete-region (1- (point-at-bol)) (point-at-eol)))
18377 (setq global-mode-string
18378 (delq 'org-mode-line-string global-mode-string))
18379 (force-mode-line-update)
18380 (message "Clock canceled"))
18382 (defun org-clock-goto (&optional delete-windows)
18383 "Go to the currently clocked-in entry."
18384 (interactive "P")
18385 (if (not (marker-buffer org-clock-marker))
18386 (error "No active clock"))
18387 (switch-to-buffer-other-window
18388 (marker-buffer org-clock-marker))
18389 (if delete-windows (delete-other-windows))
18390 (goto-char org-clock-marker)
18391 (org-show-entry)
18392 (org-back-to-heading)
18393 (recenter))
18395 (defvar org-clock-file-total-minutes nil
18396 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18397 (make-variable-buffer-local 'org-clock-file-total-minutes)
18399 (defun org-clock-sum (&optional tstart tend)
18400 "Sum the times for each subtree.
18401 Puts the resulting times in minutes as a text property on each headline."
18402 (interactive)
18403 (let* ((bmp (buffer-modified-p))
18404 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18405 org-clock-string
18406 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18407 (lmax 30)
18408 (ltimes (make-vector lmax 0))
18409 (t1 0)
18410 (level 0)
18411 ts te dt
18412 time)
18413 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18414 (save-excursion
18415 (goto-char (point-max))
18416 (while (re-search-backward re nil t)
18417 (cond
18418 ((match-end 2)
18419 ;; Two time stamps
18420 (setq ts (match-string 2)
18421 te (match-string 3)
18422 ts (time-to-seconds
18423 (apply 'encode-time (org-parse-time-string ts)))
18424 te (time-to-seconds
18425 (apply 'encode-time (org-parse-time-string te)))
18426 ts (if tstart (max ts tstart) ts)
18427 te (if tend (min te tend) te)
18428 dt (- te ts)
18429 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18430 ((match-end 4)
18431 ;; A naket time
18432 (setq t1 (+ t1 (string-to-number (match-string 5))
18433 (* 60 (string-to-number (match-string 4))))))
18434 (t ;; A headline
18435 (setq level (- (match-end 1) (match-beginning 1)))
18436 (when (or (> t1 0) (> (aref ltimes level) 0))
18437 (loop for l from 0 to level do
18438 (aset ltimes l (+ (aref ltimes l) t1)))
18439 (setq t1 0 time (aref ltimes level))
18440 (loop for l from level to (1- lmax) do
18441 (aset ltimes l 0))
18442 (goto-char (match-beginning 0))
18443 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18444 (setq org-clock-file-total-minutes (aref ltimes 0)))
18445 (set-buffer-modified-p bmp)))
18447 (defun org-clock-display (&optional total-only)
18448 "Show subtree times in the entire buffer.
18449 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18450 in the echo area."
18451 (interactive)
18452 (org-remove-clock-overlays)
18453 (let (time h m p)
18454 (org-clock-sum)
18455 (unless total-only
18456 (save-excursion
18457 (goto-char (point-min))
18458 (while (or (and (equal (setq p (point)) (point-min))
18459 (get-text-property p :org-clock-minutes))
18460 (setq p (next-single-property-change
18461 (point) :org-clock-minutes)))
18462 (goto-char p)
18463 (when (setq time (get-text-property p :org-clock-minutes))
18464 (org-put-clock-overlay time (funcall outline-level))))
18465 (setq h (/ org-clock-file-total-minutes 60)
18466 m (- org-clock-file-total-minutes (* 60 h)))
18467 ;; Arrange to remove the overlays upon next change.
18468 (when org-remove-highlights-with-change
18469 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18470 nil 'local))))
18471 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18473 (defvar org-clock-overlays nil)
18474 (make-variable-buffer-local 'org-clock-overlays)
18476 (defun org-put-clock-overlay (time &optional level)
18477 "Put an overlays on the current line, displaying TIME.
18478 If LEVEL is given, prefix time with a corresponding number of stars.
18479 This creates a new overlay and stores it in `org-clock-overlays', so that it
18480 will be easy to remove."
18481 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18482 (l (if level (org-get-legal-level level 0) 0))
18483 (off 0)
18484 ov tx)
18485 (move-to-column c)
18486 (unless (eolp) (skip-chars-backward "^ \t"))
18487 (skip-chars-backward " \t")
18488 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18489 tx (concat (buffer-substring (1- (point)) (point))
18490 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18491 (org-add-props (format "%s %2d:%02d%s"
18492 (make-string l ?*) h m
18493 (make-string (- 10 l) ?\ ))
18494 '(face secondary-selection))
18495 ""))
18496 (if (not (featurep 'xemacs))
18497 (org-overlay-put ov 'display tx)
18498 (org-overlay-put ov 'invisible t)
18499 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18500 (push ov org-clock-overlays)))
18502 (defun org-remove-clock-overlays (&optional beg end noremove)
18503 "Remove the occur highlights from the buffer.
18504 BEG and END are ignored. If NOREMOVE is nil, remove this function
18505 from the `before-change-functions' in the current buffer."
18506 (interactive)
18507 (unless org-inhibit-highlight-removal
18508 (mapc 'org-delete-overlay org-clock-overlays)
18509 (setq org-clock-overlays nil)
18510 (unless noremove
18511 (remove-hook 'before-change-functions
18512 'org-remove-clock-overlays 'local))))
18514 (defun org-clock-out-if-current ()
18515 "Clock out if the current entry contains the running clock.
18516 This is used to stop the clock after a TODO entry is marked DONE,
18517 and is only done if the variable `org-clock-out-when-done' is not nil."
18518 (when (and org-clock-out-when-done
18519 (member state org-done-keywords)
18520 (equal (marker-buffer org-clock-marker) (current-buffer))
18521 (< (point) org-clock-marker)
18522 (> (save-excursion (outline-next-heading) (point))
18523 org-clock-marker))
18524 ;; Clock out, but don't accept a logging message for this.
18525 (let ((org-log-done (if (and (listp org-log-done)
18526 (member 'clock-out org-log-done))
18527 '(done)
18528 org-log-done)))
18529 (org-clock-out))))
18531 (add-hook 'org-after-todo-state-change-hook
18532 'org-clock-out-if-current)
18534 (defun org-check-running-clock ()
18535 "Check if the current buffer contains the running clock.
18536 If yes, offer to stop it and to save the buffer with the changes."
18537 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18538 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18539 (buffer-name))))
18540 (org-clock-out)
18541 (when (y-or-n-p "Save changed buffer?")
18542 (save-buffer))))
18544 (defun org-clock-report (&optional arg)
18545 "Create a table containing a report about clocked time.
18546 If the cursor is inside an existing clocktable block, then the table
18547 will be updated. If not, a new clocktable will be inserted.
18548 When called with a prefix argument, move to the first clock table in the
18549 buffer and update it."
18550 (interactive "P")
18551 (org-remove-clock-overlays)
18552 (when arg (org-find-dblock "clocktable"))
18553 (if (org-in-clocktable-p)
18554 (goto-char (org-in-clocktable-p))
18555 (org-create-dblock (list :name "clocktable"
18556 :maxlevel 2 :scope 'file)))
18557 (org-update-dblock))
18559 (defun org-in-clocktable-p ()
18560 "Check if the cursor is in a clocktable."
18561 (let ((pos (point)) start)
18562 (save-excursion
18563 (end-of-line 1)
18564 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18565 (setq start (match-beginning 0))
18566 (re-search-forward "^#\\+END:.*" nil t)
18567 (>= (match-end 0) pos)
18568 start))))
18570 (defun org-clock-update-time-maybe ()
18571 "If this is a CLOCK line, update it and return t.
18572 Otherwise, return nil."
18573 (interactive)
18574 (save-excursion
18575 (beginning-of-line 1)
18576 (skip-chars-forward " \t")
18577 (when (looking-at org-clock-string)
18578 (let ((re (concat "[ \t]*" org-clock-string
18579 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18580 "\\([ \t]*=>.*\\)?"))
18581 ts te h m s)
18582 (if (not (looking-at re))
18584 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18585 (end-of-line 1)
18586 (setq ts (match-string 1)
18587 te (match-string 2))
18588 (setq s (- (time-to-seconds
18589 (apply 'encode-time (org-parse-time-string te)))
18590 (time-to-seconds
18591 (apply 'encode-time (org-parse-time-string ts))))
18592 h (floor (/ s 3600))
18593 s (- s (* 3600 h))
18594 m (floor (/ s 60))
18595 s (- s (* 60 s)))
18596 (insert " => " (format "%2d:%02d" h m))
18597 t)))))
18599 (defun org-clock-special-range (key &optional time as-strings)
18600 "Return two times bordering a special time range.
18601 Key is a symbol specifying the range and can be one of `today', `yesterday',
18602 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18603 A week starts Monday 0:00 and ends Sunday 24:00.
18604 The range is determined relative to TIME. TIME defaults to the current time.
18605 The return value is a cons cell with two internal times like the ones
18606 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18607 the returned times will be formatted strings."
18608 (let* ((tm (decode-time (or time (current-time))))
18609 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18610 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18611 (dow (nth 6 tm))
18612 s1 m1 h1 d1 month1 y1 diff ts te fm)
18613 (cond
18614 ((eq key 'today)
18615 (setq h 0 m 0 h1 24 m1 0))
18616 ((eq key 'yesterday)
18617 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18618 ((eq key 'thisweek)
18619 (setq diff (if (= dow 0) 6 (1- dow))
18620 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18621 ((eq key 'lastweek)
18622 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18623 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18624 ((eq key 'thismonth)
18625 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18626 ((eq key 'lastmonth)
18627 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18628 ((eq key 'thisyear)
18629 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18630 ((eq key 'lastyear)
18631 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18632 (t (error "No such time block %s" key)))
18633 (setq ts (encode-time s m h d month y)
18634 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18635 (or d1 d) (or month1 month) (or y1 y)))
18636 (setq fm (cdr org-time-stamp-formats))
18637 (if as-strings
18638 (cons (format-time-string fm ts) (format-time-string fm te))
18639 (cons ts te))))
18641 (defun org-dblock-write:clocktable (params)
18642 "Write the standard clocktable."
18643 (let ((hlchars '((1 . "*") (2 . "/")))
18644 (emph nil)
18645 (ins (make-marker))
18646 (total-time nil)
18647 ipos time h m p level hlc hdl maxlevel
18648 ts te cc block beg end pos scope tbl tostring multifile)
18649 (setq scope (plist-get params :scope)
18650 tostring (plist-get params :tostring)
18651 multifile (plist-get params :multifile)
18652 maxlevel (or (plist-get params :maxlevel) 3)
18653 emph (plist-get params :emphasize)
18654 ts (plist-get params :tstart)
18655 te (plist-get params :tend)
18656 block (plist-get params :block))
18657 (when block
18658 (setq cc (org-clock-special-range block nil t)
18659 ts (car cc) te (cdr cc)))
18660 (if ts (setq ts (time-to-seconds
18661 (apply 'encode-time (org-parse-time-string ts)))))
18662 (if te (setq te (time-to-seconds
18663 (apply 'encode-time (org-parse-time-string te)))))
18664 (move-marker ins (point))
18665 (setq ipos (point))
18667 ;; Get the right scope
18668 (setq pos (point))
18669 (save-restriction
18670 (cond
18671 ((not scope))
18672 ((eq scope 'file) (widen))
18673 ((eq scope 'subtree) (org-narrow-to-subtree))
18674 ((eq scope 'tree)
18675 (while (org-up-heading-safe))
18676 (org-narrow-to-subtree))
18677 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18678 (symbol-name scope)))
18679 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18680 (catch 'exit
18681 (while (org-up-heading-safe)
18682 (looking-at outline-regexp)
18683 (if (<= (org-reduced-level (funcall outline-level)) level)
18684 (throw 'exit nil))))
18685 (org-narrow-to-subtree))
18686 ((or (listp scope) (eq scope 'agenda))
18687 (let* ((files (if (listp scope) scope (org-agenda-files)))
18688 (scope 'agenda)
18689 (p1 (copy-sequence params))
18690 file)
18691 (plist-put p1 :tostring t)
18692 (plist-put p1 :multifile t)
18693 (plist-put p1 :scope 'file)
18694 (org-prepare-agenda-buffers files)
18695 (while (setq file (pop files))
18696 (with-current-buffer (find-buffer-visiting file)
18697 (push (org-clocktable-add-file
18698 file (org-dblock-write:clocktable p1)) tbl)
18699 (setq total-time (+ (or total-time 0)
18700 org-clock-file-total-minutes)))))))
18701 (goto-char pos)
18703 (unless (eq scope 'agenda)
18704 (org-clock-sum ts te)
18705 (goto-char (point-min))
18706 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18707 (goto-char p)
18708 (when (setq time (get-text-property p :org-clock-minutes))
18709 (save-excursion
18710 (beginning-of-line 1)
18711 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18712 (setq level (org-reduced-level
18713 (- (match-end 1) (match-beginning 1))))
18714 (<= level maxlevel))
18715 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
18716 hdl (match-string 2)
18717 h (/ time 60)
18718 m (- time (* 60 h)))
18719 (if (and (not multifile) (= level 1)) (push "|-" tbl))
18720 (push (concat
18721 "| " (int-to-string level) "|" hlc hdl hlc " |"
18722 (make-string (1- level) ?|)
18723 hlc (format "%d:%02d" h m) hlc
18724 " |") tbl))))))
18725 (setq tbl (nreverse tbl))
18726 (if tostring
18727 (if tbl (mapconcat 'identity tbl "\n") nil)
18728 (goto-char ins)
18729 (insert-before-markers
18730 "Clock summary at ["
18731 (substring
18732 (format-time-string (cdr org-time-stamp-formats))
18733 1 -1)
18734 "]."
18735 (if block
18736 (format " Considered range is /%s/." block)
18738 "\n\n"
18739 (if (eq scope 'agenda) "|File" "")
18740 "|L|Headline|Time|\n")
18741 (setq total-time (or total-time org-clock-file-total-minutes)
18742 h (/ total-time 60)
18743 m (- total-time (* 60 h)))
18744 (insert-before-markers
18745 "|-\n|"
18746 (if (eq scope 'agenda) "|" "")
18748 "*Total time*| "
18749 (format "*%d:%02d*" h m)
18750 "|\n|-\n")
18751 (setq tbl (delq nil tbl))
18752 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
18753 (equal (substring (car tbl) 0 2) "|-"))
18754 (pop tbl))
18755 (insert-before-markers (mapconcat
18756 'identity (delq nil tbl)
18757 (if (eq scope 'agenda) "\n|-\n" "\n")))
18758 (backward-delete-char 1)
18759 (goto-char ipos)
18760 (skip-chars-forward "^|")
18761 (org-table-align)))))
18763 (defun org-clocktable-add-file (file table)
18764 (if table
18765 (let ((lines (org-split-string table "\n"))
18766 (ff (file-name-nondirectory file)))
18767 (mapconcat 'identity
18768 (mapcar (lambda (x)
18769 (if (string-match org-table-dataline-regexp x)
18770 (concat "|" ff x)
18772 lines)
18773 "\n"))))
18775 ;; FIXME: I don't think anybody uses this, ask David
18776 (defun org-collect-clock-time-entries ()
18777 "Return an internal list with clocking information.
18778 This list has one entry for each CLOCK interval.
18779 FIXME: describe the elements."
18780 (interactive)
18781 (let ((re (concat "^[ \t]*" org-clock-string
18782 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
18783 rtn beg end next cont level title total closedp leafp
18784 clockpos titlepos h m donep)
18785 (save-excursion
18786 (org-clock-sum)
18787 (goto-char (point-min))
18788 (while (re-search-forward re nil t)
18789 (setq clockpos (match-beginning 0)
18790 beg (match-string 1) end (match-string 2)
18791 cont (match-end 0))
18792 (setq beg (apply 'encode-time (org-parse-time-string beg))
18793 end (apply 'encode-time (org-parse-time-string end)))
18794 (org-back-to-heading t)
18795 (setq donep (org-entry-is-done-p))
18796 (setq titlepos (point)
18797 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
18798 h (/ total 60) m (- total (* 60 h))
18799 total (cons h m))
18800 (looking-at "\\(\\*+\\) +\\(.*\\)")
18801 (setq level (- (match-end 1) (match-beginning 1))
18802 title (org-match-string-no-properties 2))
18803 (save-excursion (outline-next-heading) (setq next (point)))
18804 (setq closedp (re-search-forward org-closed-time-regexp next t))
18805 (goto-char next)
18806 (setq leafp (and (looking-at "^\\*+ ")
18807 (<= (- (match-end 0) (point)) level)))
18808 (push (list beg end clockpos closedp donep
18809 total title titlepos level leafp)
18810 rtn)
18811 (goto-char cont)))
18812 (nreverse rtn)))
18814 ;;;; Agenda, and Diary Integration
18816 ;;; Define the Org-agenda-mode
18818 (defvar org-agenda-mode-map (make-sparse-keymap)
18819 "Keymap for `org-agenda-mode'.")
18821 (defvar org-agenda-menu) ; defined later in this file.
18822 (defvar org-agenda-follow-mode nil)
18823 (defvar org-agenda-show-log nil)
18824 (defvar org-agenda-redo-command nil)
18825 (defvar org-agenda-query-string nil)
18826 (defvar org-agenda-mode-hook nil)
18827 (defvar org-agenda-type nil)
18828 (defvar org-agenda-force-single-file nil)
18830 (defun org-agenda-mode ()
18831 "Mode for time-sorted view on action items in Org-mode files.
18833 The following commands are available:
18835 \\{org-agenda-mode-map}"
18836 (interactive)
18837 (kill-all-local-variables)
18838 (setq org-agenda-undo-list nil
18839 org-agenda-pending-undo-list nil)
18840 (setq major-mode 'org-agenda-mode)
18841 ;; Keep global-font-lock-mode from turning on font-lock-mode
18842 (org-set-local 'font-lock-global-modes (list 'not major-mode))
18843 (setq mode-name "Org-Agenda")
18844 (use-local-map org-agenda-mode-map)
18845 (easy-menu-add org-agenda-menu)
18846 (if org-startup-truncated (setq truncate-lines t))
18847 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
18848 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
18849 ;; Make sure properties are removed when copying text
18850 (when (boundp 'buffer-substring-filters)
18851 (org-set-local 'buffer-substring-filters
18852 (cons (lambda (x)
18853 (set-text-properties 0 (length x) nil x) x)
18854 buffer-substring-filters)))
18855 (unless org-agenda-keep-modes
18856 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
18857 org-agenda-show-log nil))
18858 (easy-menu-change
18859 '("Agenda") "Agenda Files"
18860 (append
18861 (list
18862 (vector
18863 (if (get 'org-agenda-files 'org-restrict)
18864 "Restricted to single file"
18865 "Edit File List")
18866 '(org-edit-agenda-file-list)
18867 (not (get 'org-agenda-files 'org-restrict)))
18868 "--")
18869 (mapcar 'org-file-menu-entry (org-agenda-files))))
18870 (org-agenda-set-mode-name)
18871 (apply
18872 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
18873 (list 'org-agenda-mode-hook)))
18875 (substitute-key-definition 'undo 'org-agenda-undo
18876 org-agenda-mode-map global-map)
18877 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
18878 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
18879 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
18880 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
18881 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
18882 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
18883 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
18884 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
18885 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
18886 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
18887 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
18888 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
18889 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
18890 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
18891 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
18892 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
18893 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
18894 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
18895 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
18896 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
18897 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
18898 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
18899 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
18900 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
18901 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
18902 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
18903 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
18904 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
18905 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
18907 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
18908 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
18909 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
18910 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
18911 (while l (org-defkey org-agenda-mode-map
18912 (int-to-string (pop l)) 'digit-argument)))
18914 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
18915 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
18916 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
18917 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
18918 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
18919 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
18920 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
18921 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
18922 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
18923 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
18924 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
18925 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
18926 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
18927 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
18928 (org-defkey org-agenda-mode-map "n" 'next-line)
18929 (org-defkey org-agenda-mode-map "p" 'previous-line)
18930 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
18931 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
18932 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
18933 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
18934 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
18935 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
18936 (eval-after-load "calendar"
18937 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
18938 'org-calendar-goto-agenda))
18939 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
18940 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
18941 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
18942 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
18943 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
18944 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
18945 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
18946 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
18947 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
18948 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
18949 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
18950 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18951 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
18952 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
18953 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
18954 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
18955 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
18956 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
18957 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
18958 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
18959 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
18960 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
18961 (org-defkey org-agenda-mode-map "=" 'org-agenda-query-clear-cmd)
18962 (org-defkey org-agenda-mode-map "/" 'org-agenda-query-and-cmd)
18963 (org-defkey org-agenda-mode-map ";" 'org-agenda-query-or-cmd)
18964 (org-defkey org-agenda-mode-map "\\" 'org-agenda-query-not-cmd)
18966 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
18967 "Local keymap for agenda entries from Org-mode.")
18969 (org-defkey org-agenda-keymap
18970 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
18971 (org-defkey org-agenda-keymap
18972 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
18973 (when org-agenda-mouse-1-follows-link
18974 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
18975 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
18976 '("Agenda"
18977 ("Agenda Files")
18978 "--"
18979 ["Show" org-agenda-show t]
18980 ["Go To (other window)" org-agenda-goto t]
18981 ["Go To (this window)" org-agenda-switch-to t]
18982 ["Follow Mode" org-agenda-follow-mode
18983 :style toggle :selected org-agenda-follow-mode :active t]
18984 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
18985 "--"
18986 ["Cycle TODO" org-agenda-todo t]
18987 ["Archive subtree" org-agenda-archive t]
18988 ["Delete subtree" org-agenda-kill t]
18989 "--"
18990 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
18991 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
18992 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
18993 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
18994 "--"
18995 ("Tags and Properties"
18996 ["Show all Tags" org-agenda-show-tags t]
18997 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
18998 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
18999 "--"
19000 ["Column View" org-columns t])
19001 ("Date/Schedule"
19002 ["Schedule" org-agenda-schedule t]
19003 ["Set Deadline" org-agenda-deadline t]
19004 "--"
19005 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19006 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19007 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19008 ("Clock"
19009 ["Clock in" org-agenda-clock-in t]
19010 ["Clock out" org-agenda-clock-out t]
19011 ["Clock cancel" org-agenda-clock-cancel t]
19012 ["Goto running clock" org-clock-goto t])
19013 ("Priority"
19014 ["Set Priority" org-agenda-priority t]
19015 ["Increase Priority" org-agenda-priority-up t]
19016 ["Decrease Priority" org-agenda-priority-down t]
19017 ["Show Priority" org-agenda-show-priority t])
19018 ("Calendar/Diary"
19019 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19020 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19021 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19022 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19023 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19024 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19025 "--"
19026 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19027 "--"
19028 ("View"
19029 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19030 :style radio :selected (equal org-agenda-ndays 1)]
19031 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19032 :style radio :selected (equal org-agenda-ndays 7)]
19033 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19034 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19035 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19036 :style radio :selected (member org-agenda-ndays '(365 366))]
19037 "--"
19038 ["Show Logbook entries" org-agenda-log-mode
19039 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19040 ["Include Diary" org-agenda-toggle-diary
19041 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19042 ["Use Time Grid" org-agenda-toggle-time-grid
19043 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19044 ["Write view to file" org-write-agenda t]
19045 ["Rebuild buffer" org-agenda-redo t]
19046 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19047 "--"
19048 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19049 "--"
19050 ["Quit" org-agenda-quit t]
19051 ["Exit and Release Buffers" org-agenda-exit t]
19054 ;;; Agenda undo
19056 (defvar org-agenda-allow-remote-undo t
19057 "Non-nil means, allow remote undo from the agenda buffer.")
19058 (defvar org-agenda-undo-list nil
19059 "List of undoable operations in the agenda since last refresh.")
19060 (defvar org-agenda-undo-has-started-in nil
19061 "Buffers that have already seen `undo-start' in the current undo sequence.")
19062 (defvar org-agenda-pending-undo-list nil
19063 "In a series of undo commands, this is the list of remaning undo items.")
19065 (defmacro org-if-unprotected (&rest body)
19066 "Execute BODY if there is no `org-protected' text property at point."
19067 (declare (debug t))
19068 `(unless (get-text-property (point) 'org-protected)
19069 ,@body))
19071 (defmacro org-with-remote-undo (_buffer &rest _body)
19072 "Execute BODY while recording undo information in two buffers."
19073 (declare (indent 1) (debug t))
19074 `(let ((_cline (org-current-line))
19075 (_cmd this-command)
19076 (_buf1 (current-buffer))
19077 (_buf2 ,_buffer)
19078 (_undo1 buffer-undo-list)
19079 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19080 _c1 _c2)
19081 ,@_body
19082 (when org-agenda-allow-remote-undo
19083 (setq _c1 (org-verify-change-for-undo
19084 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19085 _c2 (org-verify-change-for-undo
19086 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19087 (when (or _c1 _c2)
19088 ;; make sure there are undo boundaries
19089 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19090 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19091 ;; remember which buffer to undo
19092 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19093 org-agenda-undo-list)))))
19095 (defun org-agenda-undo ()
19096 "Undo a remote editing step in the agenda.
19097 This undoes changes both in the agenda buffer and in the remote buffer
19098 that have been changed along."
19099 (interactive)
19100 (or org-agenda-allow-remote-undo
19101 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19102 (if (not (eq this-command last-command))
19103 (setq org-agenda-undo-has-started-in nil
19104 org-agenda-pending-undo-list org-agenda-undo-list))
19105 (if (not org-agenda-pending-undo-list)
19106 (error "No further undo information"))
19107 (let* ((entry (pop org-agenda-pending-undo-list))
19108 buf line cmd rembuf)
19109 (setq cmd (pop entry) line (pop entry))
19110 (setq rembuf (nth 2 entry))
19111 (org-with-remote-undo rembuf
19112 (while (bufferp (setq buf (pop entry)))
19113 (if (pop entry)
19114 (with-current-buffer buf
19115 (let ((last-undo-buffer buf)
19116 (inhibit-read-only t))
19117 (unless (memq buf org-agenda-undo-has-started-in)
19118 (push buf org-agenda-undo-has-started-in)
19119 (make-local-variable 'pending-undo-list)
19120 (undo-start))
19121 (while (and pending-undo-list
19122 (listp pending-undo-list)
19123 (not (car pending-undo-list)))
19124 (pop pending-undo-list))
19125 (undo-more 1))))))
19126 (goto-line line)
19127 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19129 (defun org-verify-change-for-undo (l1 l2)
19130 "Verify that a real change occurred between the undo lists L1 and L2."
19131 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19132 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19133 (not (eq l1 l2)))
19135 ;;; Agenda dispatch
19137 (defvar org-agenda-restrict nil)
19138 (defvar org-agenda-restrict-begin (make-marker))
19139 (defvar org-agenda-restrict-end (make-marker))
19140 (defvar org-agenda-last-dispatch-buffer nil)
19141 (defvar org-agenda-overriding-restriction nil)
19143 ;;;###autoload
19144 (defun org-agenda (arg &optional keys restriction)
19145 "Dispatch agenda commands to collect entries to the agenda buffer.
19146 Prompts for a command to execute. Any prefix arg will be passed
19147 on to the selected command. The default selections are:
19149 a Call `org-agenda-list' to display the agenda for current day or week.
19150 t Call `org-todo-list' to display the global todo list.
19151 T Call `org-todo-list' to display the global todo list, select only
19152 entries with a specific TODO keyword (the user gets a prompt).
19153 m Call `org-tags-view' to display headlines with tags matching
19154 a condition (the user is prompted for the condition).
19155 M Like `m', but select only TODO entries, no ordinary headlines.
19156 L Create a timeline for the current buffer.
19157 e Export views to associated files.
19159 More commands can be added by configuring the variable
19160 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19161 searches can be pre-defined in this way.
19163 If the current buffer is in Org-mode and visiting a file, you can also
19164 first press `<' once to indicate that the agenda should be temporarily
19165 \(until the next use of \\[org-agenda]) restricted to the current file.
19166 Pressing `<' twice means to restrict to the current subtree or region
19167 \(if active)."
19168 (interactive "P")
19169 (catch 'exit
19170 (let* ((prefix-descriptions nil)
19171 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19172 (org-agenda-custom-commands
19173 ;; normalize different versions
19174 (delq nil
19175 (mapcar
19176 (lambda (x)
19177 (cond ((stringp (cdr x))
19178 (push x prefix-descriptions)
19179 nil)
19180 ((stringp (nth 1 x)) x)
19181 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19182 (t (cons (car x) (cons "" (cdr x))))))
19183 org-agenda-custom-commands)))
19184 (buf (current-buffer))
19185 (bfn (buffer-file-name (buffer-base-buffer)))
19186 entry key type match lprops ans)
19187 ;; Turn off restriction unless there is an overriding one
19188 (unless org-agenda-overriding-restriction
19189 (put 'org-agenda-files 'org-restrict nil)
19190 (setq org-agenda-restrict nil)
19191 (move-marker org-agenda-restrict-begin nil)
19192 (move-marker org-agenda-restrict-end nil))
19193 ;; Delete old local properties
19194 (put 'org-agenda-redo-command 'org-lprops nil)
19195 ;; Remember where this call originated
19196 (setq org-agenda-last-dispatch-buffer (current-buffer))
19197 (unless keys
19198 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19199 keys (car ans)
19200 restriction (cdr ans)))
19201 ;; Estabish the restriction, if any
19202 (when (and (not org-agenda-overriding-restriction) restriction)
19203 (put 'org-agenda-files 'org-restrict (list bfn))
19204 (cond
19205 ((eq restriction 'region)
19206 (setq org-agenda-restrict t)
19207 (move-marker org-agenda-restrict-begin (region-beginning))
19208 (move-marker org-agenda-restrict-end (region-end)))
19209 ((eq restriction 'subtree)
19210 (save-excursion
19211 (setq org-agenda-restrict t)
19212 (org-back-to-heading t)
19213 (move-marker org-agenda-restrict-begin (point))
19214 (move-marker org-agenda-restrict-end
19215 (progn (org-end-of-subtree t)))))))
19217 (require 'calendar) ; FIXME: can we avoid this for some commands?
19218 ;; For example the todo list should not need it (but does...)
19219 (cond
19220 ((setq entry (assoc keys org-agenda-custom-commands))
19221 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19222 (progn
19223 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19224 (put 'org-agenda-redo-command 'org-lprops lprops)
19225 (cond
19226 ((eq type 'agenda)
19227 (org-let lprops '(org-agenda-list current-prefix-arg)))
19228 ((eq type 'alltodo)
19229 (org-let lprops '(org-todo-list current-prefix-arg)))
19230 ((eq type 'stuck)
19231 (org-let lprops '(org-agenda-list-stuck-projects
19232 current-prefix-arg)))
19233 ((eq type 'tags)
19234 (org-let lprops '(org-tags-view current-prefix-arg match)))
19235 ((eq type 'tags-todo)
19236 (org-let lprops '(org-tags-view '(4) match)))
19237 ((eq type 'todo)
19238 (org-let lprops '(org-todo-list match)))
19239 ((eq type 'tags-tree)
19240 (org-check-for-org-mode)
19241 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19242 ((eq type 'todo-tree)
19243 (org-check-for-org-mode)
19244 (org-let lprops
19245 '(org-occur (concat "^" outline-regexp "[ \t]*"
19246 (regexp-quote match) "\\>"))))
19247 ((eq type 'occur-tree)
19248 (org-check-for-org-mode)
19249 (org-let lprops '(org-occur match)))
19250 ((functionp type)
19251 (org-let lprops '(funcall type match)))
19252 ((fboundp type)
19253 (org-let lprops '(funcall type match)))
19254 (t (error "Invalid custom agenda command type %s" type))))
19255 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19256 ((equal keys "C")
19257 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19258 (customize-variable 'org-agenda-custom-commands))
19259 ((equal keys "a") (call-interactively 'org-agenda-list))
19260 ((equal keys "t") (call-interactively 'org-todo-list))
19261 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19262 ((equal keys "m") (call-interactively 'org-tags-view))
19263 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19264 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19265 ((equal keys "L")
19266 (unless (org-mode-p)
19267 (error "This is not an Org-mode file"))
19268 (unless restriction
19269 (put 'org-agenda-files 'org-restrict (list bfn))
19270 (org-call-with-arg 'org-timeline arg)))
19271 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19272 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19273 ((equal keys "!") (customize-variable 'org-stuck-projects))
19274 (t (error "Invalid agenda key"))))))
19276 (defun org-agenda-normalize-custom-commands (cmds)
19277 (delq nil
19278 (mapcar
19279 (lambda (x)
19280 (cond ((stringp (cdr x)) nil)
19281 ((stringp (nth 1 x)) x)
19282 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19283 (t (cons (car x) (cons "" (cdr x))))))
19284 cmds)))
19286 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19287 "The user interface for selecting an agenda command."
19288 (catch 'exit
19289 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19290 (restrict-ok (and bfn (org-mode-p)))
19291 (region-p (org-region-active-p))
19292 (custom org-agenda-custom-commands)
19293 (selstring "")
19294 restriction second-time
19295 c entry key type match prefixes rmheader header-end custom1 desc)
19296 (save-window-excursion
19297 (delete-other-windows)
19298 (org-switch-to-buffer-other-window " *Agenda Commands*")
19299 (erase-buffer)
19300 (insert (eval-when-compile
19301 (let ((header
19303 Press key for an agenda command: < Buffer,subtree/region restriction
19304 -------------------------------- > Remove restriction
19305 a Agenda for current week or day e Export agenda views
19306 t List of all TODO entries T Entries with special TODO kwd
19307 m Match a TAGS query M Like m, but only TODO entries
19308 L Timeline for current buffer # List stuck projects (!=configure)
19309 / Multi-occur C Configure custom agenda commands
19311 (start 0))
19312 (while (string-match
19313 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19314 header start)
19315 (setq start (match-end 0))
19316 (add-text-properties (match-beginning 2) (match-end 2)
19317 '(face bold) header))
19318 header)))
19319 (setq header-end (move-marker (make-marker) (point)))
19320 (while t
19321 (setq custom1 custom)
19322 (when (eq rmheader t)
19323 (goto-line 1)
19324 (re-search-forward ":" nil t)
19325 (delete-region (match-end 0) (point-at-eol))
19326 (forward-char 1)
19327 (looking-at "-+")
19328 (delete-region (match-end 0) (point-at-eol))
19329 (move-marker header-end (match-end 0)))
19330 (goto-char header-end)
19331 (delete-region (point) (point-max))
19332 (while (setq entry (pop custom1))
19333 (setq key (car entry) desc (nth 1 entry)
19334 type (nth 2 entry) match (nth 3 entry))
19335 (if (> (length key) 1)
19336 (add-to-list 'prefixes (string-to-char key))
19337 (insert
19338 (format
19339 "\n%-4s%-14s: %s"
19340 (org-add-props (copy-sequence key)
19341 '(face bold))
19342 (cond
19343 ((string-match "\\S-" desc) desc)
19344 ((eq type 'agenda) "Agenda for current week or day")
19345 ((eq type 'alltodo) "List of all TODO entries")
19346 ((eq type 'stuck) "List of stuck projects")
19347 ((eq type 'todo) "TODO keyword")
19348 ((eq type 'tags) "Tags query")
19349 ((eq type 'tags-todo) "Tags (TODO)")
19350 ((eq type 'tags-tree) "Tags tree")
19351 ((eq type 'todo-tree) "TODO kwd tree")
19352 ((eq type 'occur-tree) "Occur tree")
19353 ((functionp type) (if (symbolp type)
19354 (symbol-name type)
19355 "Lambda expression"))
19356 (t "???"))
19357 (cond
19358 ((stringp match)
19359 (org-add-props match nil 'face 'org-warning))
19360 (match
19361 (format "set of %d commands" (length match)))
19362 (t ""))))))
19363 (when prefixes
19364 (mapc (lambda (x)
19365 (insert
19366 (format "\n%s %s"
19367 (org-add-props (char-to-string x)
19368 nil 'face 'bold)
19369 (or (cdr (assoc (concat selstring (char-to-string x))
19370 prefix-descriptions))
19371 "Prefix key"))))
19372 prefixes))
19373 (goto-char (point-min))
19374 (when (fboundp 'fit-window-to-buffer)
19375 (if second-time
19376 (if (not (pos-visible-in-window-p (point-max)))
19377 (fit-window-to-buffer))
19378 (setq second-time t)
19379 (fit-window-to-buffer)))
19380 (message "Press key for agenda command%s:"
19381 (if (or restrict-ok org-agenda-overriding-restriction)
19382 (if org-agenda-overriding-restriction
19383 " (restriction lock active)"
19384 (if restriction
19385 (format " (restricted to %s)" restriction)
19386 " (unrestricted)"))
19387 ""))
19388 (setq c (read-char-exclusive))
19389 (message "")
19390 (cond
19391 ((assoc (char-to-string c) custom)
19392 (setq selstring (concat selstring (char-to-string c)))
19393 (throw 'exit (cons selstring restriction)))
19394 ((memq c prefixes)
19395 (setq selstring (concat selstring (char-to-string c))
19396 prefixes nil
19397 rmheader (or rmheader t)
19398 custom (delq nil (mapcar
19399 (lambda (x)
19400 (if (or (= (length (car x)) 1)
19401 (/= (string-to-char (car x)) c))
19403 (cons (substring (car x) 1) (cdr x))))
19404 custom))))
19405 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19406 (message "Restriction is only possible in Org-mode buffers")
19407 (ding) (sit-for 1))
19408 ((eq c ?1)
19409 (org-agenda-remove-restriction-lock 'noupdate)
19410 (setq restriction 'buffer))
19411 ((eq c ?0)
19412 (org-agenda-remove-restriction-lock 'noupdate)
19413 (setq restriction (if region-p 'region 'subtree)))
19414 ((eq c ?<)
19415 (org-agenda-remove-restriction-lock 'noupdate)
19416 (setq restriction
19417 (cond
19418 ((eq restriction 'buffer)
19419 (if region-p 'region 'subtree))
19420 ((memq restriction '(subtree region))
19421 nil)
19422 (t 'buffer))))
19423 ((eq c ?>)
19424 (org-agenda-remove-restriction-lock 'noupdate)
19425 (setq restriction nil))
19426 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19427 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19428 ((and (> (length selstring) 0) (eq c ?\d))
19429 (delete-window)
19430 (org-agenda-get-restriction-and-command prefix-descriptions))
19432 ((equal c ?q) (error "Abort"))
19433 (t (error "Invalid key %c" c))))))))
19435 (defun org-run-agenda-series (name series)
19436 (org-prepare-agenda name)
19437 (let* ((org-agenda-multi t)
19438 (redo (list 'org-run-agenda-series name (list 'quote series)))
19439 (cmds (car series))
19440 (gprops (nth 1 series))
19441 match ;; The byte compiler incorrectly complains about this. Keep it!
19442 cmd type lprops)
19443 (while (setq cmd (pop cmds))
19444 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19445 (cond
19446 ((eq type 'agenda)
19447 (org-let2 gprops lprops
19448 '(call-interactively 'org-agenda-list)))
19449 ((eq type 'alltodo)
19450 (org-let2 gprops lprops
19451 '(call-interactively 'org-todo-list)))
19452 ((eq type 'stuck)
19453 (org-let2 gprops lprops
19454 '(call-interactively 'org-agenda-list-stuck-projects)))
19455 ((eq type 'tags)
19456 (org-let2 gprops lprops
19457 '(org-tags-view current-prefix-arg match)))
19458 ((eq type 'tags-todo)
19459 (org-let2 gprops lprops
19460 '(org-tags-view '(4) match)))
19461 ((eq type 'todo)
19462 (org-let2 gprops lprops
19463 '(org-todo-list match)))
19464 ((fboundp type)
19465 (org-let2 gprops lprops
19466 '(funcall type match)))
19467 (t (error "Invalid type in command series"))))
19468 (widen)
19469 (setq org-agenda-redo-command redo)
19470 (goto-char (point-min)))
19471 (org-finalize-agenda))
19473 ;;;###autoload
19474 (defmacro org-batch-agenda (cmd-key &rest parameters)
19475 "Run an agenda command in batch mode and send the result to STDOUT.
19476 If CMD-KEY is a string of length 1, it is used as a key in
19477 `org-agenda-custom-commands' and triggers this command. If it is a
19478 longer string is is used as a tags/todo match string.
19479 Paramters are alternating variable names and values that will be bound
19480 before running the agenda command."
19481 (let (pars)
19482 (while parameters
19483 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19484 (if (> (length cmd-key) 2)
19485 (eval (list 'let (nreverse pars)
19486 (list 'org-tags-view nil cmd-key)))
19487 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19488 (set-buffer org-agenda-buffer-name)
19489 (princ (org-encode-for-stdout (buffer-string)))))
19491 (defun org-encode-for-stdout (string)
19492 (if (fboundp 'encode-coding-string)
19493 (encode-coding-string string buffer-file-coding-system)
19494 string))
19496 (defvar org-agenda-info nil)
19498 ;;;###autoload
19499 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19500 "Run an agenda command in batch mode and send the result to STDOUT.
19501 If CMD-KEY is a string of length 1, it is used as a key in
19502 `org-agenda-custom-commands' and triggers this command. If it is a
19503 longer string is is used as a tags/todo match string.
19504 Paramters are alternating variable names and values that will be bound
19505 before running the agenda command.
19507 The output gives a line for each selected agenda item. Each
19508 item is a list of comma-separated values, like this:
19510 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19512 category The category of the item
19513 head The headline, without TODO kwd, TAGS and PRIORITY
19514 type The type of the agenda entry, can be
19515 todo selected in TODO match
19516 tagsmatch selected in tags match
19517 diary imported from diary
19518 deadline a deadline on given date
19519 scheduled scheduled on given date
19520 timestamp entry has timestamp on given date
19521 closed entry was closed on given date
19522 upcoming-deadline warning about deadline
19523 past-scheduled forwarded scheduled item
19524 block entry has date block including g. date
19525 todo The todo keyword, if any
19526 tags All tags including inherited ones, separated by colons
19527 date The relevant date, like 2007-2-14
19528 time The time, like 15:00-16:50
19529 extra Sting with extra planning info
19530 priority-l The priority letter if any was given
19531 priority-n The computed numerical priority
19532 agenda-day The day in the agenda where this is listed"
19534 (let (pars)
19535 (while parameters
19536 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19537 (push (list 'org-agenda-remove-tags t) pars)
19538 (if (> (length cmd-key) 2)
19539 (eval (list 'let (nreverse pars)
19540 (list 'org-tags-view nil cmd-key)))
19541 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19542 (set-buffer org-agenda-buffer-name)
19543 (let* ((lines (org-split-string (buffer-string) "\n"))
19544 line)
19545 (while (setq line (pop lines))
19546 (catch 'next
19547 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19548 (setq org-agenda-info
19549 (org-fix-agenda-info (text-properties-at 0 line)))
19550 (princ
19551 (org-encode-for-stdout
19552 (mapconcat 'org-agenda-export-csv-mapper
19553 '(org-category txt type todo tags date time-of-day extra
19554 priority-letter priority agenda-day)
19555 ",")))
19556 (princ "\n"))))))
19558 (defun org-fix-agenda-info (props)
19559 "Make sure all properties on an agenda item have a canonical form,
19560 so the the export commands caneasily use it."
19561 (let (tmp re)
19562 (when (setq tmp (plist-get props 'tags))
19563 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19564 (when (setq tmp (plist-get props 'date))
19565 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19566 (let ((calendar-date-display-form '(year "-" month "-" day)))
19567 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19569 (setq tmp (calendar-date-string tmp)))
19570 (setq props (plist-put props 'date tmp)))
19571 (when (setq tmp (plist-get props 'day))
19572 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19573 (let ((calendar-date-display-form '(year "-" month "-" day)))
19574 (setq tmp (calendar-date-string tmp)))
19575 (setq props (plist-put props 'day tmp))
19576 (setq props (plist-put props 'agenda-day tmp)))
19577 (when (setq tmp (plist-get props 'txt))
19578 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19579 (plist-put props 'priority-letter (match-string 1 tmp))
19580 (setq tmp (replace-match "" t t tmp)))
19581 (when (and (setq re (plist-get props 'org-todo-regexp))
19582 (setq re (concat "\\`\\.*" re " ?"))
19583 (string-match re tmp))
19584 (plist-put props 'todo (match-string 1 tmp))
19585 (setq tmp (replace-match "" t t tmp)))
19586 (plist-put props 'txt tmp)))
19587 props)
19589 (defun org-agenda-export-csv-mapper (prop)
19590 (let ((res (plist-get org-agenda-info prop)))
19591 (setq res
19592 (cond
19593 ((not res) "")
19594 ((stringp res) res)
19595 (t (prin1-to-string res))))
19596 (while (string-match "," res)
19597 (setq res (replace-match ";" t t res)))
19598 (org-trim res)))
19601 ;;;###autoload
19602 (defun org-store-agenda-views (&rest parameters)
19603 (interactive)
19604 (eval (list 'org-batch-store-agenda-views)))
19606 ;; FIXME, why is this a macro?????
19607 ;;;###autoload
19608 (defmacro org-batch-store-agenda-views (&rest parameters)
19609 "Run all custom agenda commands that have a file argument."
19610 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
19611 (pop-up-frames nil)
19612 (dir default-directory)
19613 pars cmd thiscmdkey files opts)
19614 (while parameters
19615 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19616 (setq pars (reverse pars))
19617 (save-window-excursion
19618 (while cmds
19619 (setq cmd (pop cmds)
19620 thiscmdkey (car cmd)
19621 opts (nth 4 cmd)
19622 files (nth 5 cmd))
19623 (if (stringp files) (setq files (list files)))
19624 (when files
19625 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19626 (list 'org-agenda nil thiscmdkey)))
19627 (set-buffer org-agenda-buffer-name)
19628 (while files
19629 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19630 (list 'org-write-agenda
19631 (expand-file-name (pop files) dir) t))))
19632 (and (get-buffer org-agenda-buffer-name)
19633 (kill-buffer org-agenda-buffer-name)))))))
19635 (defun org-write-agenda (file &optional nosettings)
19636 "Write the current buffer (an agenda view) as a file.
19637 Depending on the extension of the file name, plain text (.txt),
19638 HTML (.html or .htm) or Postscript (.ps) is produced.
19639 If NOSETTINGS is given, do not scope the settings of
19640 `org-agenda-exporter-settings' into the export commands. This is used when
19641 the settings have already been scoped and we do not wish to overrule other,
19642 higher priority settings."
19643 (interactive "FWrite agenda to file: ")
19644 (if (not (file-writable-p file))
19645 (error "Cannot write agenda to file %s" file))
19646 (cond
19647 ((string-match "\\.html?\\'" file) (require 'htmlize))
19648 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19649 (org-let (if nosettings nil org-agenda-exporter-settings)
19650 '(save-excursion
19651 (save-window-excursion
19652 (cond
19653 ((string-match "\\.html?\\'" file)
19654 (set-buffer (htmlize-buffer (current-buffer)))
19656 (when (and org-agenda-export-html-style
19657 (string-match "<style>" org-agenda-export-html-style))
19658 ;; replace <style> section with org-agenda-export-html-style
19659 (goto-char (point-min))
19660 (kill-region (- (search-forward "<style") 6)
19661 (search-forward "</style>"))
19662 (insert org-agenda-export-html-style))
19663 (write-file file)
19664 (kill-buffer (current-buffer))
19665 (message "HTML written to %s" file))
19666 ((string-match "\\.ps\\'" file)
19667 (ps-print-buffer-with-faces file)
19668 (message "Postscript written to %s" file))
19670 (let ((bs (buffer-string)))
19671 (find-file file)
19672 (insert bs)
19673 (save-buffer 0)
19674 (kill-buffer (current-buffer))
19675 (message "Plain text written to %s" file))))))
19676 (set-buffer org-agenda-buffer-name)))
19678 (defmacro org-no-read-only (&rest body)
19679 "Inhibit read-only for BODY."
19680 `(let ((inhibit-read-only t)) ,@body))
19682 (defun org-check-for-org-mode ()
19683 "Make sure current buffer is in org-mode. Error if not."
19684 (or (org-mode-p)
19685 (error "Cannot execute org-mode agenda command on buffer in %s."
19686 major-mode)))
19688 (defun org-fit-agenda-window ()
19689 "Fit the window to the buffer size."
19690 (and (memq org-agenda-window-setup '(reorganize-frame))
19691 (fboundp 'fit-window-to-buffer)
19692 (fit-window-to-buffer
19694 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
19695 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
19697 ;;; Agenda file list
19699 (defun org-agenda-files (&optional unrestricted)
19700 "Get the list of agenda files.
19701 Optional UNRESTRICTED means return the full list even if a restriction
19702 is currently in place."
19703 (let ((files
19704 (cond
19705 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
19706 ((stringp org-agenda-files) (org-read-agenda-file-list))
19707 ((listp org-agenda-files) org-agenda-files)
19708 (t (error "Invalid value of `org-agenda-files'")))))
19709 (setq files (apply 'append
19710 (mapcar (lambda (f)
19711 (if (file-directory-p f)
19712 (directory-files f t
19713 org-agenda-file-regexp)
19714 (list f)))
19715 files)))
19716 (if org-agenda-skip-unavailable-files
19717 (delq nil
19718 (mapcar (function
19719 (lambda (file)
19720 (and (file-readable-p file) file)))
19721 files))
19722 files))) ; `org-check-agenda-file' will remove them from the list
19724 (defun org-edit-agenda-file-list ()
19725 "Edit the list of agenda files.
19726 Depending on setup, this either uses customize to edit the variable
19727 `org-agenda-files', or it visits the file that is holding the list. In the
19728 latter case, the buffer is set up in a way that saving it automatically kills
19729 the buffer and restores the previous window configuration."
19730 (interactive)
19731 (if (stringp org-agenda-files)
19732 (let ((cw (current-window-configuration)))
19733 (find-file org-agenda-files)
19734 (org-set-local 'org-window-configuration cw)
19735 (org-add-hook 'after-save-hook
19736 (lambda ()
19737 (set-window-configuration
19738 (prog1 org-window-configuration
19739 (kill-buffer (current-buffer))))
19740 (org-install-agenda-files-menu)
19741 (message "New agenda file list installed"))
19742 nil 'local)
19743 (message "%s" (substitute-command-keys
19744 "Edit list and finish with \\[save-buffer]")))
19745 (customize-variable 'org-agenda-files)))
19747 (defun org-store-new-agenda-file-list (list)
19748 "Set new value for the agenda file list and save it correcly."
19749 (if (stringp org-agenda-files)
19750 (let ((f org-agenda-files) b)
19751 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
19752 (with-temp-file f
19753 (insert (mapconcat 'identity list "\n") "\n")))
19754 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
19755 (setq org-agenda-files list)
19756 (customize-save-variable 'org-agenda-files org-agenda-files))))
19758 (defun org-read-agenda-file-list ()
19759 "Read the list of agenda files from a file."
19760 (when (stringp org-agenda-files)
19761 (with-temp-buffer
19762 (insert-file-contents org-agenda-files)
19763 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
19766 ;;;###autoload
19767 (defun org-cycle-agenda-files ()
19768 "Cycle through the files in `org-agenda-files'.
19769 If the current buffer visits an agenda file, find the next one in the list.
19770 If the current buffer does not, find the first agenda file."
19771 (interactive)
19772 (let* ((fs (org-agenda-files t))
19773 (files (append fs (list (car fs))))
19774 (tcf (if buffer-file-name (file-truename buffer-file-name)))
19775 file)
19776 (unless files (error "No agenda files"))
19777 (catch 'exit
19778 (while (setq file (pop files))
19779 (if (equal (file-truename file) tcf)
19780 (when (car files)
19781 (find-file (car files))
19782 (throw 'exit t))))
19783 (find-file (car fs)))
19784 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
19786 (defun org-agenda-file-to-front (&optional to-end)
19787 "Move/add the current file to the top of the agenda file list.
19788 If the file is not present in the list, it is added to the front. If it is
19789 present, it is moved there. With optional argument TO-END, add/move to the
19790 end of the list."
19791 (interactive "P")
19792 (let ((org-agenda-skip-unavailable-files nil)
19793 (file-alist (mapcar (lambda (x)
19794 (cons (file-truename x) x))
19795 (org-agenda-files t)))
19796 (ctf (file-truename buffer-file-name))
19797 x had)
19798 (setq x (assoc ctf file-alist) had x)
19800 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
19801 (if to-end
19802 (setq file-alist (append (delq x file-alist) (list x)))
19803 (setq file-alist (cons x (delq x file-alist))))
19804 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
19805 (org-install-agenda-files-menu)
19806 (message "File %s to %s of agenda file list"
19807 (if had "moved" "added") (if to-end "end" "front"))))
19809 (defun org-remove-file (&optional file)
19810 "Remove current file from the list of files in variable `org-agenda-files'.
19811 These are the files which are being checked for agenda entries.
19812 Optional argument FILE means, use this file instead of the current."
19813 (interactive)
19814 (let* ((org-agenda-skip-unavailable-files nil)
19815 (file (or file buffer-file-name))
19816 (true-file (file-truename file))
19817 (afile (abbreviate-file-name file))
19818 (files (delq nil (mapcar
19819 (lambda (x)
19820 (if (equal true-file
19821 (file-truename x))
19822 nil x))
19823 (org-agenda-files t)))))
19824 (if (not (= (length files) (length (org-agenda-files t))))
19825 (progn
19826 (org-store-new-agenda-file-list files)
19827 (org-install-agenda-files-menu)
19828 (message "Removed file: %s" afile))
19829 (message "File was not in list: %s (not removed)" afile))))
19831 (defun org-file-menu-entry (file)
19832 (vector file (list 'find-file file) t))
19834 (defun org-check-agenda-file (file)
19835 "Make sure FILE exists. If not, ask user what to do."
19836 (when (not (file-exists-p file))
19837 (message "non-existent file %s. [R]emove from list or [A]bort?"
19838 (abbreviate-file-name file))
19839 (let ((r (downcase (read-char-exclusive))))
19840 (cond
19841 ((equal r ?r)
19842 (org-remove-file file)
19843 (throw 'nextfile t))
19844 (t (error "Abort"))))))
19846 ;;; Agenda prepare and finalize
19848 (defvar org-agenda-multi nil) ; dynammically scoped
19849 (defvar org-agenda-buffer-name "*Org Agenda*")
19850 (defvar org-pre-agenda-window-conf nil)
19851 (defvar org-agenda-name nil)
19852 (defun org-prepare-agenda (&optional name)
19853 (setq org-todo-keywords-for-agenda nil)
19854 (setq org-done-keywords-for-agenda nil)
19855 (if org-agenda-multi
19856 (progn
19857 (setq buffer-read-only nil)
19858 (goto-char (point-max))
19859 (unless (or (bobp) org-agenda-compact-blocks)
19860 (insert "\n" (make-string (window-width) ?=) "\n"))
19861 (narrow-to-region (point) (point-max)))
19862 (org-agenda-maybe-reset-markers 'force)
19863 (org-prepare-agenda-buffers (org-agenda-files))
19864 (setq org-todo-keywords-for-agenda
19865 (org-uniquify org-todo-keywords-for-agenda))
19866 (setq org-done-keywords-for-agenda
19867 (org-uniquify org-done-keywords-for-agenda))
19868 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
19869 (awin (get-buffer-window abuf)))
19870 (cond
19871 ((equal (current-buffer) abuf) nil)
19872 (awin (select-window awin))
19873 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
19874 ((equal org-agenda-window-setup 'current-window)
19875 (switch-to-buffer abuf))
19876 ((equal org-agenda-window-setup 'other-window)
19877 (org-switch-to-buffer-other-window abuf))
19878 ((equal org-agenda-window-setup 'other-frame)
19879 (switch-to-buffer-other-frame abuf))
19880 ((equal org-agenda-window-setup 'reorganize-frame)
19881 (delete-other-windows)
19882 (org-switch-to-buffer-other-window abuf))))
19883 (setq buffer-read-only nil)
19884 (erase-buffer)
19885 (org-agenda-mode)
19886 (and name (not org-agenda-name)
19887 (org-set-local 'org-agenda-name name)))
19888 (setq buffer-read-only nil))
19890 (defun org-finalize-agenda ()
19891 "Finishing touch for the agenda buffer, called just before displaying it."
19892 (unless org-agenda-multi
19893 (save-excursion
19894 (let ((inhibit-read-only t))
19895 (goto-char (point-min))
19896 (while (org-activate-bracket-links (point-max))
19897 (add-text-properties (match-beginning 0) (match-end 0)
19898 '(face org-link)))
19899 (org-agenda-align-tags)
19900 (unless org-agenda-with-colors
19901 (remove-text-properties (point-min) (point-max) '(face nil))))
19902 (if (and (boundp 'org-overriding-columns-format)
19903 org-overriding-columns-format)
19904 (org-set-local 'org-overriding-columns-format
19905 org-overriding-columns-format))
19906 (if (and (boundp 'org-agenda-view-columns-initially)
19907 org-agenda-view-columns-initially)
19908 (org-agenda-columns))
19909 (when org-agenda-fontify-priorities
19910 (org-fontify-priorities))
19911 (run-hooks 'org-finalize-agenda-hook))))
19913 (defun org-fontify-priorities ()
19914 "Make highest priority lines bold, and lowest italic."
19915 (interactive)
19916 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
19917 (org-delete-overlay o)))
19918 (org-overlays-in (point-min) (point-max)))
19919 (save-excursion
19920 (let ((inhibit-read-only t)
19921 b e p ov h l)
19922 (goto-char (point-min))
19923 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
19924 (setq h (or (get-char-property (point) 'org-highest-priority)
19925 org-highest-priority)
19926 l (or (get-char-property (point) 'org-lowest-priority)
19927 org-lowest-priority)
19928 p (string-to-char (match-string 1))
19929 b (match-beginning 0) e (point-at-eol)
19930 ov (org-make-overlay b e))
19931 (org-overlay-put
19932 ov 'face
19933 (cond ((listp org-agenda-fontify-priorities)
19934 (cdr (assoc p org-agenda-fontify-priorities)))
19935 ((equal p l) 'italic)
19936 ((equal p h) 'bold)))
19937 (org-overlay-put ov 'org-type 'org-priority)))))
19939 (defun org-prepare-agenda-buffers (files)
19940 "Create buffers for all agenda files, protect archived trees and comments."
19941 (interactive)
19942 (let ((pa '(:org-archived t))
19943 (pc '(:org-comment t))
19944 (pall '(:org-archived t :org-comment t))
19945 (inhibit-read-only t)
19946 (rea (concat ":" org-archive-tag ":"))
19947 bmp file re)
19948 (save-excursion
19949 (save-restriction
19950 (while (setq file (pop files))
19951 (if (bufferp file)
19952 (set-buffer file)
19953 (org-check-agenda-file file)
19954 (set-buffer (org-get-agenda-file-buffer file)))
19955 (widen)
19956 (setq bmp (buffer-modified-p))
19957 (org-refresh-category-properties)
19958 (setq org-todo-keywords-for-agenda
19959 (append org-todo-keywords-for-agenda org-todo-keywords-1))
19960 (setq org-done-keywords-for-agenda
19961 (append org-done-keywords-for-agenda org-done-keywords))
19962 (save-excursion
19963 (remove-text-properties (point-min) (point-max) pall)
19964 (when org-agenda-skip-archived-trees
19965 (goto-char (point-min))
19966 (while (re-search-forward rea nil t)
19967 (if (org-on-heading-p t)
19968 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
19969 (goto-char (point-min))
19970 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
19971 (while (re-search-forward re nil t)
19972 (add-text-properties
19973 (match-beginning 0) (org-end-of-subtree t) pc)))
19974 (set-buffer-modified-p bmp))))))
19976 (defvar org-agenda-skip-function nil
19977 "Function to be called at each match during agenda construction.
19978 If this function returns nil, the current match should not be skipped.
19979 Otherwise, the function must return a position from where the search
19980 should be continued.
19981 This may also be a Lisp form, it will be evaluated.
19982 Never set this variable using `setq' or so, because then it will apply
19983 to all future agenda commands. Instead, bind it with `let' to scope
19984 it dynamically into the agenda-constructing command. A good way to set
19985 it is through options in org-agenda-custom-commands.")
19987 (defun org-agenda-skip ()
19988 "Throw to `:skip' in places that should be skipped.
19989 Also moves point to the end of the skipped region, so that search can
19990 continue from there."
19991 (let ((p (point-at-bol)) to fp)
19992 (and org-agenda-skip-archived-trees
19993 (get-text-property p :org-archived)
19994 (org-end-of-subtree t)
19995 (throw :skip t))
19996 (and (get-text-property p :org-comment)
19997 (org-end-of-subtree t)
19998 (throw :skip t))
19999 (if (equal (char-after p) ?#) (throw :skip t))
20000 (when (and (or (setq fp (functionp org-agenda-skip-function))
20001 (consp org-agenda-skip-function))
20002 (setq to (save-excursion
20003 (save-match-data
20004 (if fp
20005 (funcall org-agenda-skip-function)
20006 (eval org-agenda-skip-function))))))
20007 (goto-char to)
20008 (throw :skip t))))
20010 (defvar org-agenda-markers nil
20011 "List of all currently active markers created by `org-agenda'.")
20012 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20013 "Creation time of the last agenda marker.")
20015 (defun org-agenda-new-marker (&optional pos)
20016 "Return a new agenda marker.
20017 Org-mode keeps a list of these markers and resets them when they are
20018 no longer in use."
20019 (let ((m (copy-marker (or pos (point)))))
20020 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20021 (push m org-agenda-markers)
20024 (defun org-agenda-maybe-reset-markers (&optional force)
20025 "Reset markers created by `org-agenda'. But only if they are old enough."
20026 (if (or (and force (not org-agenda-multi))
20027 (> (- (time-to-seconds (current-time))
20028 org-agenda-last-marker-time)
20030 (while org-agenda-markers
20031 (move-marker (pop org-agenda-markers) nil))))
20033 (defun org-get-agenda-file-buffer (file)
20034 "Get a buffer visiting FILE. If the buffer needs to be created, add
20035 it to the list of buffers which might be released later."
20036 (let ((buf (org-find-base-buffer-visiting file)))
20037 (if buf
20038 buf ; just return it
20039 ;; Make a new buffer and remember it
20040 (setq buf (find-file-noselect file))
20041 (if buf (push buf org-agenda-new-buffers))
20042 buf)))
20044 (defun org-release-buffers (blist)
20045 "Release all buffers in list, asking the user for confirmation when needed.
20046 When a buffer is unmodified, it is just killed. When modified, it is saved
20047 \(if the user agrees) and then killed."
20048 (let (buf file)
20049 (while (setq buf (pop blist))
20050 (setq file (buffer-file-name buf))
20051 (when (and (buffer-modified-p buf)
20052 file
20053 (y-or-n-p (format "Save file %s? " file)))
20054 (with-current-buffer buf (save-buffer)))
20055 (kill-buffer buf))))
20057 (defun org-get-category (&optional pos)
20058 "Get the category applying to position POS."
20059 (get-text-property (or pos (point)) 'org-category))
20061 ;;; Agenda timeline
20063 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20065 (defun org-timeline (&optional include-all)
20066 "Show a time-sorted view of the entries in the current org file.
20067 Only entries with a time stamp of today or later will be listed. With
20068 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20069 under the current date.
20070 If the buffer contains an active region, only check the region for
20071 dates."
20072 (interactive "P")
20073 (require 'calendar)
20074 (org-compile-prefix-format 'timeline)
20075 (org-set-sorting-strategy 'timeline)
20076 (let* ((dopast t)
20077 (dotodo include-all)
20078 (doclosed org-agenda-show-log)
20079 (entry buffer-file-name)
20080 (date (calendar-current-date))
20081 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20082 (end (if (org-region-active-p) (region-end) (point-max)))
20083 (day-numbers (org-get-all-dates beg end 'no-ranges
20084 t doclosed ; always include today
20085 org-timeline-show-empty-dates))
20086 (org-deadline-warning-days 0)
20087 (org-agenda-only-exact-dates t)
20088 (today (time-to-days (current-time)))
20089 (past t)
20090 args
20091 s e rtn d emptyp)
20092 (setq org-agenda-redo-command
20093 (list 'progn
20094 (list 'org-switch-to-buffer-other-window (current-buffer))
20095 (list 'org-timeline (list 'quote include-all))))
20096 (if (not dopast)
20097 ;; Remove past dates from the list of dates.
20098 (setq day-numbers (delq nil (mapcar (lambda(x)
20099 (if (>= x today) x nil))
20100 day-numbers))))
20101 (org-prepare-agenda (concat "Timeline "
20102 (file-name-nondirectory buffer-file-name)))
20103 (if doclosed (push :closed args))
20104 (push :timestamp args)
20105 (push :deadline args)
20106 (push :scheduled args)
20107 (push :sexp args)
20108 (if dotodo (push :todo args))
20109 (while (setq d (pop day-numbers))
20110 (if (and (listp d) (eq (car d) :omitted))
20111 (progn
20112 (setq s (point))
20113 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20114 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20115 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20116 (if (and (>= d today)
20117 dopast
20118 past)
20119 (progn
20120 (setq past nil)
20121 (insert (make-string 79 ?-) "\n")))
20122 (setq date (calendar-gregorian-from-absolute d))
20123 (setq s (point))
20124 (setq rtn (and (not emptyp)
20125 (apply 'org-agenda-get-day-entries entry
20126 date args)))
20127 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20128 (progn
20129 (insert
20130 (if (stringp org-agenda-format-date)
20131 (format-time-string org-agenda-format-date
20132 (org-time-from-absolute date))
20133 (funcall org-agenda-format-date date))
20134 "\n")
20135 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20136 (put-text-property s (1- (point)) 'org-date-line t)
20137 (if (equal d today)
20138 (put-text-property s (1- (point)) 'org-today t))
20139 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20140 (put-text-property s (1- (point)) 'day d)))))
20141 (goto-char (point-min))
20142 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20143 (point-min)))
20144 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20145 (org-finalize-agenda)
20146 (setq buffer-read-only t)))
20148 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
20149 "Return a list of all relevant day numbers from BEG to END buffer positions.
20150 If NO-RANGES is non-nil, include only the start and end dates of a range,
20151 not every single day in the range. If FORCE-TODAY is non-nil, make
20152 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20153 inactive time stamps (those in square brackets) are included.
20154 When EMPTY is non-nil, also include days without any entries."
20155 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
20156 dates dates1 date day day1 day2 ts1 ts2)
20157 (if force-today
20158 (setq dates (list (time-to-days (current-time)))))
20159 (save-excursion
20160 (goto-char beg)
20161 (while (re-search-forward re end t)
20162 (setq day (time-to-days (org-time-string-to-time
20163 (substring (match-string 1) 0 10))))
20164 (or (memq day dates) (push day dates)))
20165 (unless no-ranges
20166 (goto-char beg)
20167 (while (re-search-forward org-tr-regexp end t)
20168 (setq ts1 (substring (match-string 1) 0 10)
20169 ts2 (substring (match-string 2) 0 10)
20170 day1 (time-to-days (org-time-string-to-time ts1))
20171 day2 (time-to-days (org-time-string-to-time ts2)))
20172 (while (< (setq day1 (1+ day1)) day2)
20173 (or (memq day1 dates) (push day1 dates)))))
20174 (setq dates (sort dates '<))
20175 (when empty
20176 (while (setq day (pop dates))
20177 (setq day2 (car dates))
20178 (push day dates1)
20179 (when (and day2 empty)
20180 (if (or (eq empty t)
20181 (and (numberp empty) (<= (- day2 day) empty)))
20182 (while (< (setq day (1+ day)) day2)
20183 (push (list day) dates1))
20184 (push (cons :omitted (- day2 day)) dates1))))
20185 (setq dates (nreverse dates1)))
20186 dates)))
20188 ;;; Agenda Daily/Weekly
20190 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20191 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20192 (defvar org-agenda-last-arguments nil
20193 "The arguments of the previous call to org-agenda")
20194 (defvar org-starting-day nil) ; local variable in the agenda buffer
20195 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20196 (defvar org-include-all-loc nil) ; local variable
20197 (defvar org-agenda-remove-date nil) ; dynamically scoped
20199 ;;;###autoload
20200 (defun org-agenda-list (&optional include-all start-day ndays)
20201 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20202 The view will be for the current day or week, but from the overview buffer
20203 you will be able to go to other days/weeks.
20205 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20206 all unfinished TODO items will also be shown, before the agenda.
20207 This feature is considered obsolete, please use the TODO list or a block
20208 agenda instead.
20210 With a numeric prefix argument in an interactive call, the agenda will
20211 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20212 the number of days. NDAYS defaults to `org-agenda-ndays'.
20214 START-DAY defaults to TODAY, or to the most recent match for the weekday
20215 given in `org-agenda-start-on-weekday'."
20216 (interactive "P")
20217 (if (and (integerp include-all) (> include-all 0))
20218 (setq ndays include-all include-all nil))
20219 (setq ndays (or ndays org-agenda-ndays)
20220 start-day (or start-day org-agenda-start-day))
20221 (if org-agenda-overriding-arguments
20222 (setq include-all (car org-agenda-overriding-arguments)
20223 start-day (nth 1 org-agenda-overriding-arguments)
20224 ndays (nth 2 org-agenda-overriding-arguments)))
20225 (if (stringp start-day)
20226 ;; Convert to an absolute day number
20227 (setq start-day (time-to-days (org-read-date nil t start-day))))
20228 (setq org-agenda-last-arguments (list include-all start-day ndays))
20229 (org-compile-prefix-format 'agenda)
20230 (org-set-sorting-strategy 'agenda)
20231 (require 'calendar)
20232 (let* ((org-agenda-start-on-weekday
20233 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20234 org-agenda-start-on-weekday nil))
20235 (thefiles (org-agenda-files))
20236 (files thefiles)
20237 (today (time-to-days
20238 (time-subtract (current-time)
20239 (list 0 (* 3600 org-extend-today-until) 0))))
20240 (sd (or start-day today))
20241 (start (if (or (null org-agenda-start-on-weekday)
20242 (< org-agenda-ndays 7))
20244 (let* ((nt (calendar-day-of-week
20245 (calendar-gregorian-from-absolute sd)))
20246 (n1 org-agenda-start-on-weekday)
20247 (d (- nt n1)))
20248 (- sd (+ (if (< d 0) 7 0) d)))))
20249 (day-numbers (list start))
20250 (day-cnt 0)
20251 (inhibit-redisplay (not debug-on-error))
20252 s e rtn rtnall file date d start-pos end-pos todayp nd)
20253 (setq org-agenda-redo-command
20254 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20255 ;; Make the list of days
20256 (setq ndays (or ndays org-agenda-ndays)
20257 nd ndays)
20258 (while (> ndays 1)
20259 (push (1+ (car day-numbers)) day-numbers)
20260 (setq ndays (1- ndays)))
20261 (setq day-numbers (nreverse day-numbers))
20262 (org-prepare-agenda "Day/Week")
20263 (org-set-local 'org-starting-day (car day-numbers))
20264 (org-set-local 'org-include-all-loc include-all)
20265 (org-set-local 'org-agenda-span
20266 (org-agenda-ndays-to-span nd))
20267 (when (and (or include-all org-agenda-include-all-todo)
20268 (member today day-numbers))
20269 (setq files thefiles
20270 rtnall nil)
20271 (while (setq file (pop files))
20272 (catch 'nextfile
20273 (org-check-agenda-file file)
20274 (setq date (calendar-gregorian-from-absolute today)
20275 rtn (org-agenda-get-day-entries
20276 file date :todo))
20277 (setq rtnall (append rtnall rtn))))
20278 (when rtnall
20279 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20280 (add-text-properties (point-min) (1- (point))
20281 (list 'face 'org-agenda-structure))
20282 (insert (org-finalize-agenda-entries rtnall) "\n")))
20283 (unless org-agenda-compact-blocks
20284 (setq s (point))
20285 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20286 "-agenda:\n")
20287 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20288 'org-date-line t)))
20289 (while (setq d (pop day-numbers))
20290 (setq date (calendar-gregorian-from-absolute d)
20291 s (point))
20292 (if (or (setq todayp (= d today))
20293 (and (not start-pos) (= d sd)))
20294 (setq start-pos (point))
20295 (if (and start-pos (not end-pos))
20296 (setq end-pos (point))))
20297 (setq files thefiles
20298 rtnall nil)
20299 (while (setq file (pop files))
20300 (catch 'nextfile
20301 (org-check-agenda-file file)
20302 (if org-agenda-show-log
20303 (setq rtn (org-agenda-get-day-entries
20304 file date
20305 :deadline :scheduled :timestamp :sexp :closed))
20306 (setq rtn (org-agenda-get-day-entries
20307 file date
20308 :deadline :scheduled :sexp :timestamp)))
20309 (setq rtnall (append rtnall rtn))))
20310 (if org-agenda-include-diary
20311 (progn
20312 (require 'diary-lib)
20313 (setq rtn (org-get-entries-from-diary date))
20314 (setq rtnall (append rtnall rtn))))
20315 (if (or rtnall org-agenda-show-all-dates)
20316 (progn
20317 (setq day-cnt (1+ day-cnt))
20318 (insert
20319 (if (stringp org-agenda-format-date)
20320 (format-time-string org-agenda-format-date
20321 (org-time-from-absolute date))
20322 (funcall org-agenda-format-date date))
20323 "\n")
20324 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20325 (put-text-property s (1- (point)) 'org-date-line t)
20326 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20327 (if todayp (put-text-property s (1- (point)) 'org-today t))
20328 (if rtnall (insert
20329 (org-finalize-agenda-entries
20330 (org-agenda-add-time-grid-maybe
20331 rtnall nd todayp))
20332 "\n"))
20333 (put-text-property s (1- (point)) 'day d)
20334 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20335 (goto-char (point-min))
20336 (org-fit-agenda-window)
20337 (unless (and (pos-visible-in-window-p (point-min))
20338 (pos-visible-in-window-p (point-max)))
20339 (goto-char (1- (point-max)))
20340 (recenter -1)
20341 (if (not (pos-visible-in-window-p (or start-pos 1)))
20342 (progn
20343 (goto-char (or start-pos 1))
20344 (recenter 1))))
20345 (goto-char (or start-pos 1))
20346 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20347 (org-finalize-agenda)
20348 (setq buffer-read-only t)
20349 (message "")))
20351 (defun org-agenda-ndays-to-span (n)
20352 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20354 ;;; Agenda TODO list
20356 (defvar org-select-this-todo-keyword nil)
20357 (defvar org-last-arg nil)
20359 ;;;###autoload
20360 (defun org-todo-list (arg)
20361 "Show all TODO entries from all agenda file in a single list.
20362 The prefix arg can be used to select a specific TODO keyword and limit
20363 the list to these. When using \\[universal-argument], you will be prompted
20364 for a keyword. A numeric prefix directly selects the Nth keyword in
20365 `org-todo-keywords-1'."
20366 (interactive "P")
20367 (require 'calendar)
20368 (org-compile-prefix-format 'todo)
20369 (org-set-sorting-strategy 'todo)
20370 (org-prepare-agenda "TODO")
20371 (let* ((today (time-to-days (current-time)))
20372 (date (calendar-gregorian-from-absolute today))
20373 (kwds org-todo-keywords-for-agenda)
20374 (completion-ignore-case t)
20375 (org-select-this-todo-keyword
20376 (if (stringp arg) arg
20377 (and arg (integerp arg) (> arg 0)
20378 (nth (1- arg) kwds))))
20379 rtn rtnall files file pos)
20380 (when (equal arg '(4))
20381 (setq org-select-this-todo-keyword
20382 (completing-read "Keyword (or KWD1|K2D2|...): "
20383 (mapcar 'list kwds) nil nil)))
20384 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20385 (org-set-local 'org-last-arg arg)
20386 (setq org-agenda-redo-command
20387 '(org-todo-list (or current-prefix-arg org-last-arg)))
20388 (setq files (org-agenda-files)
20389 rtnall nil)
20390 (while (setq file (pop files))
20391 (catch 'nextfile
20392 (org-check-agenda-file file)
20393 (setq rtn (org-agenda-get-day-entries file date :todo))
20394 (setq rtnall (append rtnall rtn))))
20395 (if org-agenda-overriding-header
20396 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20397 nil 'face 'org-agenda-structure) "\n")
20398 (insert "Global list of TODO items of type: ")
20399 (add-text-properties (point-min) (1- (point))
20400 (list 'face 'org-agenda-structure))
20401 (setq pos (point))
20402 (insert (or org-select-this-todo-keyword "ALL") "\n")
20403 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20404 (setq pos (point))
20405 (unless org-agenda-multi
20406 (insert "Available with `N r': (0)ALL")
20407 (let ((n 0) s)
20408 (mapc (lambda (x)
20409 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20410 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20411 (insert "\n "))
20412 (insert " " s))
20413 kwds))
20414 (insert "\n"))
20415 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20416 (when rtnall
20417 (insert (org-finalize-agenda-entries rtnall) "\n"))
20418 (goto-char (point-min))
20419 (org-fit-agenda-window)
20420 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20421 (org-finalize-agenda)
20422 (setq buffer-read-only t)))
20424 ;;; Agenda tags match
20426 ;;;###autoload
20427 (defun org-tags-view (&optional todo-only match)
20428 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20429 The prefix arg TODO-ONLY limits the search to TODO entries."
20430 (interactive "P")
20431 (org-compile-prefix-format 'tags)
20432 (org-set-sorting-strategy 'tags)
20433 (let* ((org-tags-match-list-sublevels
20434 (if todo-only t org-tags-match-list-sublevels))
20435 (completion-ignore-case t)
20436 rtn rtnall files file pos matcher
20437 buffer)
20438 (setq matcher (org-make-tags-matcher match)
20439 match (car matcher) matcher (cdr matcher))
20440 (org-prepare-agenda (concat "TAGS " match))
20441 (setq org-agenda-query-string match)
20442 (setq org-agenda-redo-command
20443 (list 'org-tags-view (list 'quote todo-only)
20444 (list 'if 'current-prefix-arg nil 'org-agenda-query-string)))
20445 (setq files (org-agenda-files)
20446 rtnall nil)
20447 (while (setq file (pop files))
20448 (catch 'nextfile
20449 (org-check-agenda-file file)
20450 (setq buffer (if (file-exists-p file)
20451 (org-get-agenda-file-buffer file)
20452 (error "No such file %s" file)))
20453 (if (not buffer)
20454 ;; If file does not exist, merror message to agenda
20455 (setq rtn (list
20456 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20457 rtnall (append rtnall rtn))
20458 (with-current-buffer buffer
20459 (unless (org-mode-p)
20460 (error "Agenda file %s is not in `org-mode'" file))
20461 (save-excursion
20462 (save-restriction
20463 (if org-agenda-restrict
20464 (narrow-to-region org-agenda-restrict-begin
20465 org-agenda-restrict-end)
20466 (widen))
20467 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20468 (setq rtnall (append rtnall rtn))))))))
20469 (if org-agenda-overriding-header
20470 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20471 nil 'face 'org-agenda-structure) "\n")
20472 (insert "Headlines with TAGS match: ")
20473 (add-text-properties (point-min) (1- (point))
20474 (list 'face 'org-agenda-structure))
20475 (setq pos (point))
20476 (insert match "\n")
20477 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20478 (setq pos (point))
20479 (unless org-agenda-multi
20480 (insert "Press `C-u r' to enter new search string; use `/;\\=' to adjust interactively\n"))
20481 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20482 (when rtnall
20483 (insert (org-finalize-agenda-entries rtnall) "\n"))
20484 (goto-char (point-min))
20485 (org-fit-agenda-window)
20486 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20487 (org-finalize-agenda)
20488 (setq buffer-read-only t)))
20490 ;;; Agenda interactive query manipulation
20492 (defcustom org-agenda-query-selection-single-key t
20493 "Non-nil means, query manipulation exits after first change.
20494 When nil, you have to press RET to exit it.
20495 During query selection, you can toggle this flag with `C-c'.
20496 This variable can also have the value `expert'. In this case, the window
20497 displaying the tags menu is not even shown, until you press C-c again."
20498 :group 'org-agenda
20499 :type '(choice
20500 (const :tag "No" nil)
20501 (const :tag "Yes" t)
20502 (const :tag "Expert" expert)))
20504 (defun org-agenda-query-selection (current op table &optional todo-table)
20505 "Fast query manipulation with single keys.
20506 CURRENT is the current query string, OP is the initial
20507 operator (one of \"+|-=\"), TABLE is an alist of tags and
20508 corresponding keys, possibly with grouping information.
20509 TODO-TABLE is a similar table with TODO keywords, should these
20510 have keys assigned to them. If the keys are nil, a-z are
20511 automatically assigned. Returns the new query string, or nil to
20512 not change the current one."
20513 (let* ((fulltable (append table todo-table))
20514 (maxlen (apply 'max (mapcar
20515 (lambda (x)
20516 (if (stringp (car x)) (string-width (car x)) 0))
20517 fulltable)))
20518 (fwidth (+ maxlen 3 1 3))
20519 (ncol (/ (- (window-width) 4) fwidth))
20520 (expert (eq org-agenda-query-selection-single-key 'expert))
20521 (exit-after-next org-agenda-query-selection-single-key)
20522 (done-keywords org-done-keywords)
20523 tbl char cnt e groups ingroup
20524 tg c2 c c1 ntable rtn)
20525 (save-window-excursion
20526 (if expert
20527 (set-buffer (get-buffer-create " *Org tags*"))
20528 (delete-other-windows)
20529 (split-window-vertically)
20530 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
20531 (erase-buffer)
20532 (org-set-local 'org-done-keywords done-keywords)
20533 (insert "Query: " current "\n")
20534 (org-agenda-query-op-line op)
20535 (insert "\n\n")
20536 (org-fast-tag-show-exit exit-after-next)
20537 (setq tbl fulltable char ?a cnt 0)
20538 (while (setq e (pop tbl))
20539 (cond
20540 ((equal e '(:startgroup))
20541 (push '() groups) (setq ingroup t)
20542 (when (not (= cnt 0))
20543 (setq cnt 0)
20544 (insert "\n"))
20545 (insert "{ "))
20546 ((equal e '(:endgroup))
20547 (setq ingroup nil cnt 0)
20548 (insert "}\n"))
20550 (setq tg (car e) c2 nil)
20551 (if (cdr e)
20552 (setq c (cdr e))
20553 ;; automatically assign a character.
20554 (setq c1 (string-to-char
20555 (downcase (substring
20556 tg (if (= (string-to-char tg) ?@) 1 0)))))
20557 (if (or (rassoc c1 ntable) (rassoc c1 table))
20558 (while (or (rassoc char ntable) (rassoc char table))
20559 (setq char (1+ char)))
20560 (setq c2 c1))
20561 (setq c (or c2 char)))
20562 (if ingroup (push tg (car groups)))
20563 (setq tg (org-add-props tg nil 'face
20564 (cond
20565 ((not (assoc tg table))
20566 (org-get-todo-face tg))
20567 (t nil))))
20568 (if (and (= cnt 0) (not ingroup)) (insert " "))
20569 (insert "[" c "] " tg (make-string
20570 (- fwidth 4 (length tg)) ?\ ))
20571 (push (cons tg c) ntable)
20572 (when (= (setq cnt (1+ cnt)) ncol)
20573 (insert "\n")
20574 (if ingroup (insert " "))
20575 (setq cnt 0)))))
20576 (setq ntable (nreverse ntable))
20577 (insert "\n")
20578 (goto-char (point-min))
20579 (if (and (not expert) (fboundp 'fit-window-to-buffer))
20580 (fit-window-to-buffer))
20581 (setq rtn
20582 (catch 'exit
20583 (while t
20584 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
20585 (if groups " [!] no groups" " [!]groups")
20586 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
20587 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
20588 (cond
20589 ((= c ?\r) (throw 'exit t))
20590 ((= c ?!)
20591 (setq groups (not groups))
20592 (goto-char (point-min))
20593 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
20594 ((= c ?\C-c)
20595 (if (not expert)
20596 (org-fast-tag-show-exit
20597 (setq exit-after-next (not exit-after-next)))
20598 (setq expert nil)
20599 (delete-other-windows)
20600 (split-window-vertically)
20601 (org-switch-to-buffer-other-window " *Org tags*")
20602 (and (fboundp 'fit-window-to-buffer)
20603 (fit-window-to-buffer))))
20604 ((or (= c ?\C-g)
20605 (and (= c ?q) (not (rassoc c ntable))))
20606 (setq quit-flag t))
20607 ((= c ?\ )
20608 (setq current "")
20609 (if exit-after-next (setq exit-after-next 'now)))
20610 ((= c ?\[) ; clear left
20611 (org-agenda-query-decompose current)
20612 (setq current (concat "/" (match-string 2 current)))
20613 (if exit-after-next (setq exit-after-next 'now)))
20614 ((= c ?\]) ; clear right
20615 (org-agenda-query-decompose current)
20616 (setq current (match-string 1 current))
20617 (if exit-after-next (setq exit-after-next 'now)))
20618 ((= c ?\t)
20619 (condition-case nil
20620 (setq current (read-string "Query: " current))
20621 (quit))
20622 (if exit-after-next (setq exit-after-next 'now)))
20623 ;; operators
20624 ((or (= c ?/) (= c ?+)) (setq op "+"))
20625 ((or (= c ?\;) (= c ?|)) (setq op "|"))
20626 ((or (= c ?\\) (= c ?-)) (setq op "-"))
20627 ((= c ?=) (setq op "="))
20628 ;; todos
20629 ((setq e (rassoc c todo-table) tg (car e))
20630 (setq current (org-agenda-query-manip
20631 current op groups 'todo tg))
20632 (if exit-after-next (setq exit-after-next 'now)))
20633 ;; tags
20634 ((setq e (rassoc c ntable) tg (car e))
20635 (setq current (org-agenda-query-manip
20636 current op groups 'tag tg))
20637 (if exit-after-next (setq exit-after-next 'now))))
20638 (if (eq exit-after-next 'now) (throw 'exit t))
20639 (goto-char (point-min))
20640 (beginning-of-line 1)
20641 (delete-region (point) (point-at-eol))
20642 (insert "Query: " current)
20643 (beginning-of-line 2)
20644 (delete-region (point) (point-at-eol))
20645 (org-agenda-query-op-line op)
20646 (goto-char (point-min)))))
20647 (if rtn current nil))))
20649 (defun org-agenda-query-op-line (op)
20650 (insert "Operator: "
20651 (org-agenda-query-op-entry (equal op "+") "/+" "and")
20652 (org-agenda-query-op-entry (equal op "|") ";|" "or")
20653 (org-agenda-query-op-entry (equal op "-") "\\-" "not")
20654 (org-agenda-query-op-entry (equal op "=") "=" "clear")))
20656 (defun org-agenda-query-op-entry (matchp chars str)
20657 (if matchp
20658 (org-add-props (format "[%s %s] " chars (upcase str))
20659 nil 'face 'org-todo)
20660 (format "[%s]%s " chars str)))
20662 (defun org-agenda-query-decompose (current)
20663 (string-match "\\([^/]*\\)/?\\(.*\\)" current))
20665 (defun org-agenda-query-clear (current prefix tag)
20666 (if (string-match (concat prefix "\\b" (regexp-quote tag) "\\b") current)
20667 (replace-match "" t t current)
20668 current))
20670 (defun org-agenda-query-manip (current op groups kind tag)
20671 "Apply an operator to a query string and a tag.
20672 CURRENT is the current query string, OP is the operator, GROUPS is a
20673 list of lists of tags that are mutually exclusive. KIND is 'tag for a
20674 regular tag, or 'todo for a TODO keyword, and TAG is the tag or
20675 keyword string."
20676 ;; If this tag is already in query string, remove it.
20677 (setq current (org-agenda-query-clear current "[-\\+&|]?" tag))
20678 (if (equal op "=") current
20679 ;; When using AND, also remove mutually exclusive tags.
20680 (if (equal op "+")
20681 (loop for g in groups do
20682 (if (member tag g)
20683 (mapc (lambda (x)
20684 (setq current
20685 (org-agenda-query-clear current "\\+" x)))
20686 g))))
20687 ;; Decompose current query into q1 (tags) and q2 (TODOs).
20688 (org-agenda-query-decompose current)
20689 (let* ((q1 (match-string 1 current))
20690 (q2 (match-string 2 current)))
20691 (cond
20692 ((eq kind 'tag)
20693 (concat q1 op tag "/" q2))
20694 ;; It's a TODO; when using AND, drop all other TODOs.
20695 ((equal op "+")
20696 (concat q1 "/+" tag))
20698 (concat q1 "/" q2 op tag))))))
20700 (defun org-agenda-query-global-todo-keys (&optional files)
20701 "Return alist of all TODO keywords and their fast keys, in all FILES."
20702 (let (alist)
20703 (unless (and files (car files))
20704 (setq files (org-agenda-files)))
20705 (save-excursion
20706 (loop for f in files do
20707 (set-buffer (find-file-noselect f))
20708 (loop for k in org-todo-key-alist do
20709 (setq alist (org-agenda-query-merge-todo-key
20710 alist k)))))
20711 alist))
20713 (defun org-agenda-query-merge-todo-key (alist entry)
20714 (let (e)
20715 (cond
20716 ;; if this is not a keyword (:startgroup, etc), ignore it
20717 ((not (stringp (car entry))))
20718 ;; if keyword already exists, replace char if it's null
20719 ((setq e (assoc (car entry) alist))
20720 (when (null (cdr e)) (setcdr e (cdr entry))))
20721 ;; if char already exists, prepend keyword but drop char
20722 ((rassoc (cdr entry) alist)
20723 (error "TRACE POSITION 2")
20724 (setq alist (cons (cons (car entry) nil) alist)))
20725 ;; else, prepend COPY of entry
20727 (setq alist (cons (cons (car entry) (cdr entry)) alist)))))
20728 alist)
20730 (defun org-agenda-query-generic-cmd (op)
20731 "Activate query manipulation with OP as initial operator."
20732 (let ((q (org-agenda-query-selection org-agenda-query-string op
20733 org-tag-alist
20734 (org-agenda-query-global-todo-keys))))
20735 (when q
20736 (setq org-agenda-query-string q)
20737 (org-agenda-redo))))
20739 (defun org-agenda-query-clear-cmd ()
20740 "Activate query manipulation, to clear a tag from the string."
20741 (interactive)
20742 (org-agenda-query-generic-cmd "="))
20744 (defun org-agenda-query-and-cmd ()
20745 "Activate query manipulation, initially using the AND (+) operator."
20746 (interactive)
20747 (org-agenda-query-generic-cmd "+"))
20749 (defun org-agenda-query-or-cmd ()
20750 "Activate query manipulation, initially using the OR (|) operator."
20751 (interactive)
20752 (org-agenda-query-generic-cmd "|"))
20754 (defun org-agenda-query-not-cmd ()
20755 "Activate query manipulation, initially using the NOT (-) operator."
20756 (interactive)
20757 (org-agenda-query-generic-cmd "-"))
20759 ;;; Agenda Finding stuck projects
20761 (defvar org-agenda-skip-regexp nil
20762 "Regular expression used in skipping subtrees for the agenda.
20763 This is basically a temporary global variable that can be set and then
20764 used by user-defined selections using `org-agenda-skip-function'.")
20766 (defvar org-agenda-overriding-header nil
20767 "When this is set during todo and tags searches, will replace header.")
20769 (defun org-agenda-skip-subtree-when-regexp-matches ()
20770 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20771 If yes, it returns the end position of this tree, causing agenda commands
20772 to skip this subtree. This is a function that can be put into
20773 `org-agenda-skip-function' for the duration of a command."
20774 (let ((end (save-excursion (org-end-of-subtree t)))
20775 skip)
20776 (save-excursion
20777 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20778 (and skip end)))
20780 (defun org-agenda-skip-entry-if (&rest conditions)
20781 "Skip entry if any of CONDITIONS is true.
20782 See `org-agenda-skip-if' for details."
20783 (org-agenda-skip-if nil conditions))
20785 (defun org-agenda-skip-subtree-if (&rest conditions)
20786 "Skip entry if any of CONDITIONS is true.
20787 See `org-agenda-skip-if' for details."
20788 (org-agenda-skip-if t conditions))
20790 (defun org-agenda-skip-if (subtree conditions)
20791 "Checks current entity for CONDITIONS.
20792 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20793 the entry, i.e. the text before the next heading is checked.
20795 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20796 from different tests. Valid conditions are:
20798 scheduled Check if there is a scheduled cookie
20799 notscheduled Check if there is no scheduled cookie
20800 deadline Check if there is a deadline
20801 notdeadline Check if there is no deadline
20802 regexp Check if regexp matches
20803 notregexp Check if regexp does not match.
20805 The regexp is taken from the conditions list, it must come right after
20806 the `regexp' or `notregexp' element.
20808 If any of these conditions is met, this function returns the end point of
20809 the entity, causing the search to continue from there. This is a function
20810 that can be put into `org-agenda-skip-function' for the duration of a command."
20811 (let (beg end m)
20812 (org-back-to-heading t)
20813 (setq beg (point)
20814 end (if subtree
20815 (progn (org-end-of-subtree t) (point))
20816 (progn (outline-next-heading) (1- (point)))))
20817 (goto-char beg)
20818 (and
20820 (and (memq 'scheduled conditions)
20821 (re-search-forward org-scheduled-time-regexp end t))
20822 (and (memq 'notscheduled conditions)
20823 (not (re-search-forward org-scheduled-time-regexp end t)))
20824 (and (memq 'deadline conditions)
20825 (re-search-forward org-deadline-time-regexp end t))
20826 (and (memq 'notdeadline conditions)
20827 (not (re-search-forward org-deadline-time-regexp end t)))
20828 (and (setq m (memq 'regexp conditions))
20829 (stringp (nth 1 m))
20830 (re-search-forward (nth 1 m) end t))
20831 (and (setq m (memq 'notregexp conditions))
20832 (stringp (nth 1 m))
20833 (not (re-search-forward (nth 1 m) end t))))
20834 end)))
20836 ;;;###autoload
20837 (defun org-agenda-list-stuck-projects (&rest ignore)
20838 "Create agenda view for projects that are stuck.
20839 Stuck projects are project that have no next actions. For the definitions
20840 of what a project is and how to check if it stuck, customize the variable
20841 `org-stuck-projects'.
20842 MATCH is being ignored."
20843 (interactive)
20844 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20845 ;; FIXME: we could have used org-agenda-skip-if here.
20846 (org-agenda-overriding-header "List of stuck projects: ")
20847 (matcher (nth 0 org-stuck-projects))
20848 (todo (nth 1 org-stuck-projects))
20849 (todo-wds (if (member "*" todo)
20850 (progn
20851 (org-prepare-agenda-buffers (org-agenda-files))
20852 (org-delete-all
20853 org-done-keywords-for-agenda
20854 (copy-sequence org-todo-keywords-for-agenda)))
20855 todo))
20856 (todo-re (concat "^\\*+[ \t]+\\("
20857 (mapconcat 'identity todo-wds "\\|")
20858 "\\)\\>"))
20859 (tags (nth 2 org-stuck-projects))
20860 (tags-re (if (member "*" tags)
20861 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20862 (concat "^\\*+ .*:\\("
20863 (mapconcat 'identity tags "\\|")
20864 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20865 (gen-re (nth 3 org-stuck-projects))
20866 (re-list
20867 (delq nil
20868 (list
20869 (if todo todo-re)
20870 (if tags tags-re)
20871 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20872 gen-re)))))
20873 (setq org-agenda-skip-regexp
20874 (if re-list
20875 (mapconcat 'identity re-list "\\|")
20876 (error "No information how to identify unstuck projects")))
20877 (org-tags-view nil matcher)
20878 (with-current-buffer org-agenda-buffer-name
20879 (setq org-agenda-redo-command
20880 '(org-agenda-list-stuck-projects
20881 (or current-prefix-arg org-last-arg))))))
20883 ;;; Diary integration
20885 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20887 (defun org-get-entries-from-diary (date)
20888 "Get the (Emacs Calendar) diary entries for DATE."
20889 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20890 (diary-display-hook '(fancy-diary-display))
20891 (pop-up-frames nil)
20892 (list-diary-entries-hook
20893 (cons 'org-diary-default-entry list-diary-entries-hook))
20894 (diary-file-name-prefix-function nil) ; turn this feature off
20895 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20896 entries
20897 (org-disable-agenda-to-diary t))
20898 (save-excursion
20899 (save-window-excursion
20900 (funcall (if (fboundp 'diary-list-entries)
20901 'diary-list-entries 'list-diary-entries)
20902 date 1)))
20903 (if (not (get-buffer fancy-diary-buffer))
20904 (setq entries nil)
20905 (with-current-buffer fancy-diary-buffer
20906 (setq buffer-read-only nil)
20907 (if (zerop (buffer-size))
20908 ;; No entries
20909 (setq entries nil)
20910 ;; Omit the date and other unnecessary stuff
20911 (org-agenda-cleanup-fancy-diary)
20912 ;; Add prefix to each line and extend the text properties
20913 (if (zerop (buffer-size))
20914 (setq entries nil)
20915 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20916 (set-buffer-modified-p nil)
20917 (kill-buffer fancy-diary-buffer)))
20918 (when entries
20919 (setq entries (org-split-string entries "\n"))
20920 (setq entries
20921 (mapcar
20922 (lambda (x)
20923 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20924 ;; Extend the text properties to the beginning of the line
20925 (org-add-props x (text-properties-at (1- (length x)) x)
20926 'type "diary" 'date date))
20927 entries)))))
20929 (defun org-agenda-cleanup-fancy-diary ()
20930 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20931 This gets rid of the date, the underline under the date, and
20932 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20933 date. It also removes lines that contain only whitespace."
20934 (goto-char (point-min))
20935 (if (looking-at ".*?:[ \t]*")
20936 (progn
20937 (replace-match "")
20938 (re-search-forward "\n=+$" nil t)
20939 (replace-match "")
20940 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20941 (re-search-forward "\n=+$" nil t)
20942 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20943 (goto-char (point-min))
20944 (while (re-search-forward "^ +\n" nil t)
20945 (replace-match ""))
20946 (goto-char (point-min))
20947 (if (re-search-forward "^Org-mode dummy\n?" nil t)
20948 (replace-match "")))
20950 ;; Make sure entries from the diary have the right text properties.
20951 (eval-after-load "diary-lib"
20952 '(if (boundp 'diary-modify-entry-list-string-function)
20953 ;; We can rely on the hook, nothing to do
20955 ;; Hook not avaiable, must use advice to make this work
20956 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
20957 "Make the position visible."
20958 (if (and org-disable-agenda-to-diary ;; called from org-agenda
20959 (stringp string)
20960 buffer-file-name)
20961 (setq string (org-modify-diary-entry-string string))))))
20963 (defun org-modify-diary-entry-string (string)
20964 "Add text properties to string, allowing org-mode to act on it."
20965 (org-add-props string nil
20966 'mouse-face 'highlight
20967 'keymap org-agenda-keymap
20968 'help-echo (if buffer-file-name
20969 (format "mouse-2 or RET jump to diary file %s"
20970 (abbreviate-file-name buffer-file-name))
20972 'org-agenda-diary-link t
20973 'org-marker (org-agenda-new-marker (point-at-bol))))
20975 (defun org-diary-default-entry ()
20976 "Add a dummy entry to the diary.
20977 Needed to avoid empty dates which mess up holiday display."
20978 ;; Catch the error if dealing with the new add-to-diary-alist
20979 (when org-disable-agenda-to-diary
20980 (condition-case nil
20981 (add-to-diary-list original-date "Org-mode dummy" "")
20982 (error
20983 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
20985 ;;;###autoload
20986 (defun org-diary (&rest args)
20987 "Return diary information from org-files.
20988 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
20989 It accesses org files and extracts information from those files to be
20990 listed in the diary. The function accepts arguments specifying what
20991 items should be listed. The following arguments are allowed:
20993 :timestamp List the headlines of items containing a date stamp or
20994 date range matching the selected date. Deadlines will
20995 also be listed, on the expiration day.
20997 :sexp List entries resulting from diary-like sexps.
20999 :deadline List any deadlines past due, or due within
21000 `org-deadline-warning-days'. The listing occurs only
21001 in the diary for *today*, not at any other date. If
21002 an entry is marked DONE, it is no longer listed.
21004 :scheduled List all items which are scheduled for the given date.
21005 The diary for *today* also contains items which were
21006 scheduled earlier and are not yet marked DONE.
21008 :todo List all TODO items from the org-file. This may be a
21009 long list - so this is not turned on by default.
21010 Like deadlines, these entries only show up in the
21011 diary for *today*, not at any other date.
21013 The call in the diary file should look like this:
21015 &%%(org-diary) ~/path/to/some/orgfile.org
21017 Use a separate line for each org file to check. Or, if you omit the file name,
21018 all files listed in `org-agenda-files' will be checked automatically:
21020 &%%(org-diary)
21022 If you don't give any arguments (as in the example above), the default
21023 arguments (:deadline :scheduled :timestamp :sexp) are used.
21024 So the example above may also be written as
21026 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21028 The function expects the lisp variables `entry' and `date' to be provided
21029 by the caller, because this is how the calendar works. Don't use this
21030 function from a program - use `org-agenda-get-day-entries' instead."
21031 (org-agenda-maybe-reset-markers)
21032 (org-compile-prefix-format 'agenda)
21033 (org-set-sorting-strategy 'agenda)
21034 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21035 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21036 (list entry)
21037 (org-agenda-files t)))
21038 file rtn results)
21039 (org-prepare-agenda-buffers files)
21040 ;; If this is called during org-agenda, don't return any entries to
21041 ;; the calendar. Org Agenda will list these entries itself.
21042 (if org-disable-agenda-to-diary (setq files nil))
21043 (while (setq file (pop files))
21044 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21045 (setq results (append results rtn)))
21046 (if results
21047 (concat (org-finalize-agenda-entries results) "\n"))))
21049 ;;; Agenda entry finders
21051 (defun org-agenda-get-day-entries (file date &rest args)
21052 "Does the work for `org-diary' and `org-agenda'.
21053 FILE is the path to a file to be checked for entries. DATE is date like
21054 the one returned by `calendar-current-date'. ARGS are symbols indicating
21055 which kind of entries should be extracted. For details about these, see
21056 the documentation of `org-diary'."
21057 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21058 (let* ((org-startup-folded nil)
21059 (org-startup-align-all-tables nil)
21060 (buffer (if (file-exists-p file)
21061 (org-get-agenda-file-buffer file)
21062 (error "No such file %s" file)))
21063 arg results rtn)
21064 (if (not buffer)
21065 ;; If file does not exist, make sure an error message ends up in diary
21066 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21067 (with-current-buffer buffer
21068 (unless (org-mode-p)
21069 (error "Agenda file %s is not in `org-mode'" file))
21070 (let ((case-fold-search nil))
21071 (save-excursion
21072 (save-restriction
21073 (if org-agenda-restrict
21074 (narrow-to-region org-agenda-restrict-begin
21075 org-agenda-restrict-end)
21076 (widen))
21077 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21078 (while (setq arg (pop args))
21079 (cond
21080 ((and (eq arg :todo)
21081 (equal date (calendar-current-date)))
21082 (setq rtn (org-agenda-get-todos))
21083 (setq results (append results rtn)))
21084 ((eq arg :timestamp)
21085 (setq rtn (org-agenda-get-blocks))
21086 (setq results (append results rtn))
21087 (setq rtn (org-agenda-get-timestamps))
21088 (setq results (append results rtn)))
21089 ((eq arg :sexp)
21090 (setq rtn (org-agenda-get-sexps))
21091 (setq results (append results rtn)))
21092 ((eq arg :scheduled)
21093 (setq rtn (org-agenda-get-scheduled))
21094 (setq results (append results rtn)))
21095 ((eq arg :closed)
21096 (setq rtn (org-agenda-get-closed))
21097 (setq results (append results rtn)))
21098 ((eq arg :deadline)
21099 (setq rtn (org-agenda-get-deadlines))
21100 (setq results (append results rtn))))))))
21101 results))))
21103 (defun org-entry-is-todo-p ()
21104 (member (org-get-todo-state) org-not-done-keywords))
21106 (defun org-entry-is-done-p ()
21107 (member (org-get-todo-state) org-done-keywords))
21109 (defun org-get-todo-state ()
21110 (save-excursion
21111 (org-back-to-heading t)
21112 (and (looking-at org-todo-line-regexp)
21113 (match-end 2)
21114 (match-string 2))))
21116 (defun org-at-date-range-p (&optional inactive-ok)
21117 "Is the cursor inside a date range?"
21118 (interactive)
21119 (save-excursion
21120 (catch 'exit
21121 (let ((pos (point)))
21122 (skip-chars-backward "^[<\r\n")
21123 (skip-chars-backward "<[")
21124 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21125 (>= (match-end 0) pos)
21126 (throw 'exit t))
21127 (skip-chars-backward "^<[\r\n")
21128 (skip-chars-backward "<[")
21129 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21130 (>= (match-end 0) pos)
21131 (throw 'exit t)))
21132 nil)))
21134 (defun org-agenda-get-todos ()
21135 "Return the TODO information for agenda display."
21136 (let* ((props (list 'face nil
21137 'done-face 'org-done
21138 'org-not-done-regexp org-not-done-regexp
21139 'org-todo-regexp org-todo-regexp
21140 'mouse-face 'highlight
21141 'keymap org-agenda-keymap
21142 'help-echo
21143 (format "mouse-2 or RET jump to org file %s"
21144 (abbreviate-file-name buffer-file-name))))
21145 ;; FIXME: get rid of the \n at some point but watch out
21146 (regexp (concat "^\\*+[ \t]+\\("
21147 (if org-select-this-todo-keyword
21148 (if (equal org-select-this-todo-keyword "*")
21149 org-todo-regexp
21150 (concat "\\<\\("
21151 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21152 "\\)\\>"))
21153 org-not-done-regexp)
21154 "[^\n\r]*\\)"))
21155 marker priority category tags
21156 ee txt beg end)
21157 (goto-char (point-min))
21158 (while (re-search-forward regexp nil t)
21159 (catch :skip
21160 (save-match-data
21161 (beginning-of-line)
21162 (setq beg (point) end (progn (outline-next-heading) (point)))
21163 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21164 (re-search-forward org-ts-regexp end t))
21165 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21166 (re-search-forward org-scheduled-time-regexp end t))
21167 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21168 (re-search-forward org-deadline-time-regexp end t)
21169 (org-deadline-close (match-string 1))))
21170 (goto-char (1+ beg))
21171 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21172 (throw :skip nil)))
21173 (goto-char beg)
21174 (org-agenda-skip)
21175 (goto-char (match-beginning 1))
21176 (setq marker (org-agenda-new-marker (match-beginning 0))
21177 category (org-get-category)
21178 tags (org-get-tags-at (point))
21179 txt (org-format-agenda-item "" (match-string 1) category tags)
21180 priority (1+ (org-get-priority txt)))
21181 (org-add-props txt props
21182 'org-marker marker 'org-hd-marker marker
21183 'priority priority 'org-category category
21184 'type "todo")
21185 (push txt ee)
21186 (if org-agenda-todo-list-sublevels
21187 (goto-char (match-end 1))
21188 (org-end-of-subtree 'invisible))))
21189 (nreverse ee)))
21191 (defconst org-agenda-no-heading-message
21192 "No heading for this item in buffer or region.")
21194 (defun org-agenda-get-timestamps ()
21195 "Return the date stamp information for agenda display."
21196 (let* ((props (list 'face nil
21197 'org-not-done-regexp org-not-done-regexp
21198 'org-todo-regexp org-todo-regexp
21199 'mouse-face 'highlight
21200 'keymap org-agenda-keymap
21201 'help-echo
21202 (format "mouse-2 or RET jump to org file %s"
21203 (abbreviate-file-name buffer-file-name))))
21204 (d1 (calendar-absolute-from-gregorian date))
21205 (remove-re
21206 (concat
21207 (regexp-quote
21208 (format-time-string
21209 "<%Y-%m-%d"
21210 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21211 ".*?>"))
21212 (regexp
21213 (concat
21214 (regexp-quote
21215 (substring
21216 (format-time-string
21217 (car org-time-stamp-formats)
21218 (apply 'encode-time ; DATE bound by calendar
21219 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21220 0 11))
21221 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21222 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21223 marker hdmarker deadlinep scheduledp donep tmp priority category
21224 ee txt timestr tags b0 b3 e3 head)
21225 (goto-char (point-min))
21226 (while (re-search-forward regexp nil t)
21227 (setq b0 (match-beginning 0)
21228 b3 (match-beginning 3) e3 (match-end 3))
21229 (catch :skip
21230 (and (org-at-date-range-p) (throw :skip nil))
21231 (org-agenda-skip)
21232 (if (and (match-end 1)
21233 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21234 (throw :skip nil))
21235 (if (and e3
21236 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21237 (throw :skip nil))
21238 (setq marker (org-agenda-new-marker b0)
21239 category (org-get-category b0)
21240 tmp (buffer-substring (max (point-min)
21241 (- b0 org-ds-keyword-length))
21243 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21244 deadlinep (string-match org-deadline-regexp tmp)
21245 scheduledp (string-match org-scheduled-regexp tmp)
21246 donep (org-entry-is-done-p))
21247 (if (or scheduledp deadlinep) (throw :skip t))
21248 (if (string-match ">" timestr)
21249 ;; substring should only run to end of time stamp
21250 (setq timestr (substring timestr 0 (match-end 0))))
21251 (save-excursion
21252 (if (re-search-backward "^\\*+ " nil t)
21253 (progn
21254 (goto-char (match-beginning 0))
21255 (setq hdmarker (org-agenda-new-marker)
21256 tags (org-get-tags-at))
21257 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21258 (setq head (match-string 1))
21259 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21260 (setq txt (org-format-agenda-item
21261 nil head category tags timestr nil
21262 remove-re)))
21263 (setq txt org-agenda-no-heading-message))
21264 (setq priority (org-get-priority txt))
21265 (org-add-props txt props
21266 'org-marker marker 'org-hd-marker hdmarker)
21267 (org-add-props txt nil 'priority priority
21268 'org-category category 'date date
21269 'type "timestamp")
21270 (push txt ee))
21271 (outline-next-heading)))
21272 (nreverse ee)))
21274 (defun org-agenda-get-sexps ()
21275 "Return the sexp information for agenda display."
21276 (require 'diary-lib)
21277 (let* ((props (list 'face nil
21278 'mouse-face 'highlight
21279 'keymap org-agenda-keymap
21280 'help-echo
21281 (format "mouse-2 or RET jump to org file %s"
21282 (abbreviate-file-name buffer-file-name))))
21283 (regexp "^&?%%(")
21284 marker category ee txt tags entry result beg b sexp sexp-entry)
21285 (goto-char (point-min))
21286 (while (re-search-forward regexp nil t)
21287 (catch :skip
21288 (org-agenda-skip)
21289 (setq beg (match-beginning 0))
21290 (goto-char (1- (match-end 0)))
21291 (setq b (point))
21292 (forward-sexp 1)
21293 (setq sexp (buffer-substring b (point)))
21294 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21295 (org-trim (match-string 1))
21296 ""))
21297 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21298 (when result
21299 (setq marker (org-agenda-new-marker beg)
21300 category (org-get-category beg))
21302 (if (string-match "\\S-" result)
21303 (setq txt result)
21304 (setq txt "SEXP entry returned empty string"))
21306 (setq txt (org-format-agenda-item
21307 "" txt category tags 'time))
21308 (org-add-props txt props 'org-marker marker)
21309 (org-add-props txt nil
21310 'org-category category 'date date
21311 'type "sexp")
21312 (push txt ee))))
21313 (nreverse ee)))
21315 (defun org-agenda-get-closed ()
21316 "Return the logged TODO entries for agenda display."
21317 (let* ((props (list 'mouse-face 'highlight
21318 'org-not-done-regexp org-not-done-regexp
21319 'org-todo-regexp org-todo-regexp
21320 'keymap org-agenda-keymap
21321 'help-echo
21322 (format "mouse-2 or RET jump to org file %s"
21323 (abbreviate-file-name buffer-file-name))))
21324 (regexp (concat
21325 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21326 (regexp-quote
21327 (substring
21328 (format-time-string
21329 (car org-time-stamp-formats)
21330 (apply 'encode-time ; DATE bound by calendar
21331 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21332 1 11))))
21333 marker hdmarker priority category tags closedp
21334 ee txt timestr)
21335 (goto-char (point-min))
21336 (while (re-search-forward regexp nil t)
21337 (catch :skip
21338 (org-agenda-skip)
21339 (setq marker (org-agenda-new-marker (match-beginning 0))
21340 closedp (equal (match-string 1) org-closed-string)
21341 category (org-get-category (match-beginning 0))
21342 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21343 ;; donep (org-entry-is-done-p)
21345 (if (string-match "\\]" timestr)
21346 ;; substring should only run to end of time stamp
21347 (setq timestr (substring timestr 0 (match-end 0))))
21348 (save-excursion
21349 (if (re-search-backward "^\\*+ " nil t)
21350 (progn
21351 (goto-char (match-beginning 0))
21352 (setq hdmarker (org-agenda-new-marker)
21353 tags (org-get-tags-at))
21354 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21355 (setq txt (org-format-agenda-item
21356 (if closedp "Closed: " "Clocked: ")
21357 (match-string 1) category tags timestr)))
21358 (setq txt org-agenda-no-heading-message))
21359 (setq priority 100000)
21360 (org-add-props txt props
21361 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21362 'priority priority 'org-category category
21363 'type "closed" 'date date
21364 'undone-face 'org-warning 'done-face 'org-done)
21365 (push txt ee))
21366 (outline-next-heading)))
21367 (nreverse ee)))
21369 (defun org-agenda-get-deadlines ()
21370 "Return the deadline information for agenda display."
21371 (let* ((props (list 'mouse-face 'highlight
21372 'org-not-done-regexp org-not-done-regexp
21373 'org-todo-regexp org-todo-regexp
21374 'keymap org-agenda-keymap
21375 'help-echo
21376 (format "mouse-2 or RET jump to org file %s"
21377 (abbreviate-file-name buffer-file-name))))
21378 (regexp org-deadline-time-regexp)
21379 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21380 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21381 d2 diff dfrac wdays pos pos1 category tags
21382 ee txt head face s upcomingp donep timestr)
21383 (goto-char (point-min))
21384 (while (re-search-forward regexp nil t)
21385 (catch :skip
21386 (org-agenda-skip)
21387 (setq s (match-string 1)
21388 pos (1- (match-beginning 1))
21389 d2 (org-time-string-to-absolute (match-string 1) d1)
21390 diff (- d2 d1)
21391 wdays (org-get-wdays s)
21392 dfrac (/ (* 1.0 (- wdays diff)) wdays)
21393 upcomingp (and todayp (> diff 0)))
21394 ;; When to show a deadline in the calendar:
21395 ;; If the expiration is within wdays warning time.
21396 ;; Past-due deadlines are only shown on the current date
21397 (if (or (and (<= diff wdays)
21398 (and todayp (not org-agenda-only-exact-dates)))
21399 (= diff 0))
21400 (save-excursion
21401 (setq category (org-get-category))
21402 (if (re-search-backward "^\\*+[ \t]+" nil t)
21403 (progn
21404 (goto-char (match-end 0))
21405 (setq pos1 (match-beginning 0))
21406 (setq tags (org-get-tags-at pos1))
21407 (setq head (buffer-substring-no-properties
21408 (point)
21409 (progn (skip-chars-forward "^\r\n")
21410 (point))))
21411 (setq donep (string-match org-looking-at-done-regexp head))
21412 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21413 (setq timestr
21414 (concat (substring s (match-beginning 1)) " "))
21415 (setq timestr 'time))
21416 (if (and donep
21417 (or org-agenda-skip-deadline-if-done
21418 (not (= diff 0))))
21419 (setq txt nil)
21420 (setq txt (org-format-agenda-item
21421 (if (= diff 0)
21422 (car org-agenda-deadline-leaders)
21423 (format (nth 1 org-agenda-deadline-leaders)
21424 diff))
21425 head category tags timestr))))
21426 (setq txt org-agenda-no-heading-message))
21427 (when txt
21428 (setq face (org-agenda-deadline-face dfrac))
21429 (org-add-props txt props
21430 'org-marker (org-agenda-new-marker pos)
21431 'org-hd-marker (org-agenda-new-marker pos1)
21432 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
21433 (org-get-priority txt))
21434 'org-category category
21435 'type (if upcomingp "upcoming-deadline" "deadline")
21436 'date (if upcomingp date d2)
21437 'face (if donep 'org-done face)
21438 'undone-face face 'done-face 'org-done)
21439 (push txt ee))))))
21440 (nreverse ee)))
21442 (defun org-agenda-deadline-face (fraction)
21443 "Return the face to displaying a deadline item.
21444 FRACTION is what fraction of the head-warning time has passed."
21445 (let ((faces org-agenda-deadline-faces) f)
21446 (catch 'exit
21447 (while (setq f (pop faces))
21448 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21450 (defun org-agenda-get-scheduled ()
21451 "Return the scheduled information for agenda display."
21452 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21453 'org-todo-regexp org-todo-regexp
21454 'done-face 'org-done
21455 'mouse-face 'highlight
21456 'keymap org-agenda-keymap
21457 'help-echo
21458 (format "mouse-2 or RET jump to org file %s"
21459 (abbreviate-file-name buffer-file-name))))
21460 (regexp org-scheduled-time-regexp)
21461 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21462 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21463 d2 diff pos pos1 category tags
21464 ee txt head pastschedp donep face timestr s)
21465 (goto-char (point-min))
21466 (while (re-search-forward regexp nil t)
21467 (catch :skip
21468 (org-agenda-skip)
21469 (setq s (match-string 1)
21470 pos (1- (match-beginning 1))
21471 d2 (org-time-string-to-absolute (match-string 1) d1)
21472 diff (- d2 d1))
21473 (setq pastschedp (and todayp (< diff 0)))
21474 ;; When to show a scheduled item in the calendar:
21475 ;; If it is on or past the date.
21476 (if (or (and (< diff 0)
21477 (and todayp (not org-agenda-only-exact-dates)))
21478 (= diff 0))
21479 (save-excursion
21480 (setq category (org-get-category))
21481 (if (re-search-backward "^\\*+[ \t]+" nil t)
21482 (progn
21483 (goto-char (match-end 0))
21484 (setq pos1 (match-beginning 0))
21485 (setq tags (org-get-tags-at))
21486 (setq head (buffer-substring-no-properties
21487 (point)
21488 (progn (skip-chars-forward "^\r\n") (point))))
21489 (setq donep (string-match org-looking-at-done-regexp head))
21490 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21491 (setq timestr
21492 (concat (substring s (match-beginning 1)) " "))
21493 (setq timestr 'time))
21494 (if (and donep
21495 (or org-agenda-skip-scheduled-if-done
21496 (not (= diff 0))))
21497 (setq txt nil)
21498 (setq txt (org-format-agenda-item
21499 (if (= diff 0)
21500 (car org-agenda-scheduled-leaders)
21501 (format (nth 1 org-agenda-scheduled-leaders)
21502 (- 1 diff)))
21503 head category tags timestr))))
21504 (setq txt org-agenda-no-heading-message))
21505 (when txt
21506 (setq face (if pastschedp
21507 'org-scheduled-previously
21508 'org-scheduled-today))
21509 (org-add-props txt props
21510 'undone-face face
21511 'face (if donep 'org-done face)
21512 'org-marker (org-agenda-new-marker pos)
21513 'org-hd-marker (org-agenda-new-marker pos1)
21514 'type (if pastschedp "past-scheduled" "scheduled")
21515 'date (if pastschedp d2 date)
21516 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21517 'org-category category)
21518 (push txt ee))))))
21519 (nreverse ee)))
21521 (defun org-agenda-get-blocks ()
21522 "Return the date-range information for agenda display."
21523 (let* ((props (list 'face nil
21524 'org-not-done-regexp org-not-done-regexp
21525 'org-todo-regexp org-todo-regexp
21526 'mouse-face 'highlight
21527 'keymap org-agenda-keymap
21528 'help-echo
21529 (format "mouse-2 or RET jump to org file %s"
21530 (abbreviate-file-name buffer-file-name))))
21531 (regexp org-tr-regexp)
21532 (d0 (calendar-absolute-from-gregorian date))
21533 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21534 donep head)
21535 (goto-char (point-min))
21536 (while (re-search-forward regexp nil t)
21537 (catch :skip
21538 (org-agenda-skip)
21539 (setq pos (point))
21540 (setq timestr (match-string 0)
21541 s1 (match-string 1)
21542 s2 (match-string 2)
21543 d1 (time-to-days (org-time-string-to-time s1))
21544 d2 (time-to-days (org-time-string-to-time s2)))
21545 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21546 ;; Only allow days between the limits, because the normal
21547 ;; date stamps will catch the limits.
21548 (save-excursion
21549 (setq marker (org-agenda-new-marker (point)))
21550 (setq category (org-get-category))
21551 (if (re-search-backward "^\\*+ " nil t)
21552 (progn
21553 (goto-char (match-beginning 0))
21554 (setq hdmarker (org-agenda-new-marker (point)))
21555 (setq tags (org-get-tags-at))
21556 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21557 (setq head (match-string 1))
21558 (and org-agenda-skip-timestamp-if-done
21559 (org-entry-is-done-p)
21560 (throw :skip t))
21561 (setq txt (org-format-agenda-item
21562 (format (if (= d1 d2) "" "(%d/%d): ")
21563 (1+ (- d0 d1)) (1+ (- d2 d1)))
21564 head category tags
21565 (if (= d0 d1) timestr))))
21566 (setq txt org-agenda-no-heading-message))
21567 (org-add-props txt props
21568 'org-marker marker 'org-hd-marker hdmarker
21569 'type "block" 'date date
21570 'priority (org-get-priority txt) 'org-category category)
21571 (push txt ee)))
21572 (goto-char pos)))
21573 ;; Sort the entries by expiration date.
21574 (nreverse ee)))
21576 ;;; Agenda presentation and sorting
21578 (defconst org-plain-time-of-day-regexp
21579 (concat
21580 "\\(\\<[012]?[0-9]"
21581 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21582 "\\(--?"
21583 "\\(\\<[012]?[0-9]"
21584 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21585 "\\)?")
21586 "Regular expression to match a plain time or time range.
21587 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21588 groups carry important information:
21589 0 the full match
21590 1 the first time, range or not
21591 8 the second time, if it is a range.")
21593 (defconst org-plain-time-extension-regexp
21594 (concat
21595 "\\(\\<[012]?[0-9]"
21596 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21597 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21598 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21599 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21600 groups carry important information:
21601 0 the full match
21602 7 hours of duration
21603 9 minutes of duration")
21605 (defconst org-stamp-time-of-day-regexp
21606 (concat
21607 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21608 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21609 "\\(--?"
21610 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21611 "Regular expression to match a timestamp time or time range.
21612 After a match, the following groups carry important information:
21613 0 the full match
21614 1 date plus weekday, for backreferencing to make sure both times on same day
21615 2 the first time, range or not
21616 4 the second time, if it is a range.")
21618 (defvar org-prefix-has-time nil
21619 "A flag, set by `org-compile-prefix-format'.
21620 The flag is set if the currently compiled format contains a `%t'.")
21621 (defvar org-prefix-has-tag nil
21622 "A flag, set by `org-compile-prefix-format'.
21623 The flag is set if the currently compiled format contains a `%T'.")
21625 (defun org-format-agenda-item (extra txt &optional category tags dotime
21626 noprefix remove-re)
21627 "Format TXT to be inserted into the agenda buffer.
21628 In particular, it adds the prefix and corresponding text properties. EXTRA
21629 must be a string and replaces the `%s' specifier in the prefix format.
21630 CATEGORY (string, symbol or nil) may be used to overrule the default
21631 category taken from local variable or file name. It will replace the `%c'
21632 specifier in the format. DOTIME, when non-nil, indicates that a
21633 time-of-day should be extracted from TXT for sorting of this entry, and for
21634 the `%t' specifier in the format. When DOTIME is a string, this string is
21635 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21636 only the correctly processes TXT should be returned - this is used by
21637 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21638 Any match of REMOVE-RE will be removed from TXT."
21639 (save-match-data
21640 ;; Diary entries sometimes have extra whitespace at the beginning
21641 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21642 (let* ((category (or category
21643 org-category
21644 (if buffer-file-name
21645 (file-name-sans-extension
21646 (file-name-nondirectory buffer-file-name))
21647 "")))
21648 (tag (if tags (nth (1- (length tags)) tags) ""))
21649 time ; time and tag are needed for the eval of the prefix format
21650 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21651 (time-of-day (and dotime (org-get-time-of-day ts)))
21652 stamp plain s0 s1 s2 rtn srp)
21653 (when (and dotime time-of-day org-prefix-has-time)
21654 ;; Extract starting and ending time and move them to prefix
21655 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21656 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21657 (setq s0 (match-string 0 ts)
21658 srp (and stamp (match-end 3))
21659 s1 (match-string (if plain 1 2) ts)
21660 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21662 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21663 ;; them, we might want to remove them there to avoid duplication.
21664 ;; The user can turn this off with a variable.
21665 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21666 (string-match (concat (regexp-quote s0) " *") txt)
21667 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21668 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21669 (= (match-beginning 0) 0)
21671 (setq txt (replace-match "" nil nil txt))))
21672 ;; Normalize the time(s) to 24 hour
21673 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21674 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21676 (when (and s1 (not s2) org-agenda-default-appointment-duration
21677 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21678 (let ((m (+ (string-to-number (match-string 2 s1))
21679 (* 60 (string-to-number (match-string 1 s1)))
21680 org-agenda-default-appointment-duration))
21682 (setq h (/ m 60) m (- m (* h 60)))
21683 (setq s2 (format "%02d:%02d" h m))))
21685 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21686 txt)
21687 ;; Tags are in the string
21688 (if (or (eq org-agenda-remove-tags t)
21689 (and org-agenda-remove-tags
21690 org-prefix-has-tag))
21691 (setq txt (replace-match "" t t txt))
21692 (setq txt (replace-match
21693 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21694 (match-string 2 txt))
21695 t t txt))))
21697 (when remove-re
21698 (while (string-match remove-re txt)
21699 (setq txt (replace-match "" t t txt))))
21701 ;; Create the final string
21702 (if noprefix
21703 (setq rtn txt)
21704 ;; Prepare the variables needed in the eval of the compiled format
21705 (setq time (cond (s2 (concat s1 "-" s2))
21706 (s1 (concat s1 "......"))
21707 (t ""))
21708 extra (or extra "")
21709 category (if (symbolp category) (symbol-name category) category))
21710 ;; Evaluate the compiled format
21711 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21713 ;; And finally add the text properties
21714 (org-add-props rtn nil
21715 'org-category (downcase category) 'tags tags
21716 'org-highest-priority org-highest-priority
21717 'org-lowest-priority org-lowest-priority
21718 'prefix-length (- (length rtn) (length txt))
21719 'time-of-day time-of-day
21720 'txt txt
21721 'time time
21722 'extra extra
21723 'dotime dotime))))
21725 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21726 (defvar org-agenda-sorting-strategy-selected nil)
21728 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21729 (catch 'exit
21730 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21731 ((and todayp (member 'today (car org-agenda-time-grid))))
21732 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21733 ((member 'weekly (car org-agenda-time-grid)))
21734 (t (throw 'exit list)))
21735 (let* ((have (delq nil (mapcar
21736 (lambda (x) (get-text-property 1 'time-of-day x))
21737 list)))
21738 (string (nth 1 org-agenda-time-grid))
21739 (gridtimes (nth 2 org-agenda-time-grid))
21740 (req (car org-agenda-time-grid))
21741 (remove (member 'remove-match req))
21742 new time)
21743 (if (and (member 'require-timed req) (not have))
21744 ;; don't show empty grid
21745 (throw 'exit list))
21746 (while (setq time (pop gridtimes))
21747 (unless (and remove (member time have))
21748 (setq time (int-to-string time))
21749 (push (org-format-agenda-item
21750 nil string "" nil
21751 (concat (substring time 0 -2) ":" (substring time -2)))
21752 new)
21753 (put-text-property
21754 1 (length (car new)) 'face 'org-time-grid (car new))))
21755 (if (member 'time-up org-agenda-sorting-strategy-selected)
21756 (append new list)
21757 (append list new)))))
21759 (defun org-compile-prefix-format (key)
21760 "Compile the prefix format into a Lisp form that can be evaluated.
21761 The resulting form is returned and stored in the variable
21762 `org-prefix-format-compiled'."
21763 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21764 (let ((s (cond
21765 ((stringp org-agenda-prefix-format)
21766 org-agenda-prefix-format)
21767 ((assq key org-agenda-prefix-format)
21768 (cdr (assq key org-agenda-prefix-format)))
21769 (t " %-12:c%?-12t% s")))
21770 (start 0)
21771 varform vars var e c f opt)
21772 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21773 s start)
21774 (setq var (cdr (assoc (match-string 4 s)
21775 '(("c" . category) ("t" . time) ("s" . extra)
21776 ("T" . tag))))
21777 c (or (match-string 3 s) "")
21778 opt (match-beginning 1)
21779 start (1+ (match-beginning 0)))
21780 (if (equal var 'time) (setq org-prefix-has-time t))
21781 (if (equal var 'tag) (setq org-prefix-has-tag t))
21782 (setq f (concat "%" (match-string 2 s) "s"))
21783 (if opt
21784 (setq varform
21785 `(if (equal "" ,var)
21787 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21788 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21789 (setq s (replace-match "%s" t nil s))
21790 (push varform vars))
21791 (setq vars (nreverse vars))
21792 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21794 (defun org-set-sorting-strategy (key)
21795 (if (symbolp (car org-agenda-sorting-strategy))
21796 ;; the old format
21797 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21798 (setq org-agenda-sorting-strategy-selected
21799 (or (cdr (assq key org-agenda-sorting-strategy))
21800 (cdr (assq 'agenda org-agenda-sorting-strategy))
21801 '(time-up category-keep priority-down)))))
21803 (defun org-get-time-of-day (s &optional string mod24)
21804 "Check string S for a time of day.
21805 If found, return it as a military time number between 0 and 2400.
21806 If not found, return nil.
21807 The optional STRING argument forces conversion into a 5 character wide string
21808 HH:MM."
21809 (save-match-data
21810 (when
21811 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21812 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21813 (let* ((h (string-to-number (match-string 1 s)))
21814 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21815 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21816 (am-p (equal ampm "am"))
21817 (h1 (cond ((not ampm) h)
21818 ((= h 12) (if am-p 0 12))
21819 (t (+ h (if am-p 0 12)))))
21820 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21821 (mod h1 24) h1))
21822 (t0 (+ (* 100 h2) m))
21823 (t1 (concat (if (>= h1 24) "+" " ")
21824 (if (< t0 100) "0" "")
21825 (if (< t0 10) "0" "")
21826 (int-to-string t0))))
21827 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21829 (defun org-finalize-agenda-entries (list &optional nosort)
21830 "Sort and concatenate the agenda items."
21831 (setq list (mapcar 'org-agenda-highlight-todo list))
21832 (if nosort
21833 list
21834 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21836 (defun org-agenda-highlight-todo (x)
21837 (let (re pl)
21838 (if (eq x 'line)
21839 (save-excursion
21840 (beginning-of-line 1)
21841 (setq re (get-text-property (point) 'org-todo-regexp))
21842 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21843 (and (looking-at (concat "[ \t]*\\.*" re))
21844 (add-text-properties (match-beginning 0) (match-end 0)
21845 (list 'face (org-get-todo-face 0)))))
21846 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21847 pl (get-text-property 0 'prefix-length x))
21848 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
21849 (add-text-properties
21850 (or (match-end 1) (match-end 0)) (match-end 0)
21851 (list 'face (org-get-todo-face (match-string 2 x)))
21853 x)))
21855 (defsubst org-cmp-priority (a b)
21856 "Compare the priorities of string A and B."
21857 (let ((pa (or (get-text-property 1 'priority a) 0))
21858 (pb (or (get-text-property 1 'priority b) 0)))
21859 (cond ((> pa pb) +1)
21860 ((< pa pb) -1)
21861 (t nil))))
21863 (defsubst org-cmp-category (a b)
21864 "Compare the string values of categories of strings A and B."
21865 (let ((ca (or (get-text-property 1 'org-category a) ""))
21866 (cb (or (get-text-property 1 'org-category b) "")))
21867 (cond ((string-lessp ca cb) -1)
21868 ((string-lessp cb ca) +1)
21869 (t nil))))
21871 (defsubst org-cmp-tag (a b)
21872 "Compare the string values of categories of strings A and B."
21873 (let ((ta (car (last (get-text-property 1 'tags a))))
21874 (tb (car (last (get-text-property 1 'tags b)))))
21875 (cond ((not ta) +1)
21876 ((not tb) -1)
21877 ((string-lessp ta tb) -1)
21878 ((string-lessp tb ta) +1)
21879 (t nil))))
21881 (defsubst org-cmp-time (a b)
21882 "Compare the time-of-day values of strings A and B."
21883 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21884 (ta (or (get-text-property 1 'time-of-day a) def))
21885 (tb (or (get-text-property 1 'time-of-day b) def)))
21886 (cond ((< ta tb) -1)
21887 ((< tb ta) +1)
21888 (t nil))))
21890 (defun org-entries-lessp (a b)
21891 "Predicate for sorting agenda entries."
21892 ;; The following variables will be used when the form is evaluated.
21893 ;; So even though the compiler complains, keep them.
21894 (let* ((time-up (org-cmp-time a b))
21895 (time-down (if time-up (- time-up) nil))
21896 (priority-up (org-cmp-priority a b))
21897 (priority-down (if priority-up (- priority-up) nil))
21898 (category-up (org-cmp-category a b))
21899 (category-down (if category-up (- category-up) nil))
21900 (category-keep (if category-up +1 nil))
21901 (tag-up (org-cmp-tag a b))
21902 (tag-down (if tag-up (- tag-up) nil)))
21903 (cdr (assoc
21904 (eval (cons 'or org-agenda-sorting-strategy-selected))
21905 '((-1 . t) (1 . nil) (nil . nil))))))
21907 ;;; Agenda restriction lock
21909 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
21910 "Overlay to mark the headline to which arenda commands are restricted.")
21911 (org-overlay-put org-agenda-restriction-lock-overlay
21912 'face 'org-agenda-restriction-lock)
21913 (org-overlay-put org-agenda-restriction-lock-overlay
21914 'help-echo "Agendas are currently limited to this subtree.")
21915 (org-detach-overlay org-agenda-restriction-lock-overlay)
21916 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
21917 "Overlay marking the agenda restriction line in speedbar.")
21918 (org-overlay-put org-speedbar-restriction-lock-overlay
21919 'face 'org-agenda-restriction-lock)
21920 (org-overlay-put org-speedbar-restriction-lock-overlay
21921 'help-echo "Agendas are currently limited to this item.")
21922 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21924 (defun org-agenda-set-restriction-lock (&optional type)
21925 "Set restriction lock for agenda, to current subtree or file.
21926 Restriction will be the file if TYPE is `file', or if type is the
21927 universal prefix '(4), or if the cursor is before the first headline
21928 in the file. Otherwise, restriction will be to the current subtree."
21929 (interactive "P")
21930 (and (equal type '(4)) (setq type 'file))
21931 (setq type (cond
21932 (type type)
21933 ((org-at-heading-p) 'subtree)
21934 ((condition-case nil (org-back-to-heading t) (error nil))
21935 'subtree)
21936 (t 'file)))
21937 (if (eq type 'subtree)
21938 (progn
21939 (setq org-agenda-restrict t)
21940 (setq org-agenda-overriding-restriction 'subtree)
21941 (put 'org-agenda-files 'org-restrict
21942 (list (buffer-file-name (buffer-base-buffer))))
21943 (org-back-to-heading t)
21944 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
21945 (move-marker org-agenda-restrict-begin (point))
21946 (move-marker org-agenda-restrict-end
21947 (save-excursion (org-end-of-subtree t)))
21948 (message "Locking agenda restriction to subtree"))
21949 (put 'org-agenda-files 'org-restrict
21950 (list (buffer-file-name (buffer-base-buffer))))
21951 (setq org-agenda-restrict nil)
21952 (setq org-agenda-overriding-restriction 'file)
21953 (move-marker org-agenda-restrict-begin nil)
21954 (move-marker org-agenda-restrict-end nil)
21955 (message "Locking agenda restriction to file"))
21956 (setq current-prefix-arg nil)
21957 (org-agenda-maybe-redo))
21959 (defun org-agenda-remove-restriction-lock (&optional noupdate)
21960 "Remove the agenda restriction lock."
21961 (interactive "P")
21962 (org-detach-overlay org-agenda-restriction-lock-overlay)
21963 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21964 (setq org-agenda-overriding-restriction nil)
21965 (setq org-agenda-restrict nil)
21966 (put 'org-agenda-files 'org-restrict nil)
21967 (move-marker org-agenda-restrict-begin nil)
21968 (move-marker org-agenda-restrict-end nil)
21969 (setq current-prefix-arg nil)
21970 (message "Agenda restriction lock removed")
21971 (or noupdate (org-agenda-maybe-redo)))
21973 (defun org-agenda-maybe-redo ()
21974 "If there is any window showing the agenda view, update it."
21975 (let ((w (get-buffer-window org-agenda-buffer-name t))
21976 (w0 (selected-window)))
21977 (when w
21978 (select-window w)
21979 (org-agenda-redo)
21980 (select-window w0)
21981 (if org-agenda-overriding-restriction
21982 (message "Agenda view shifted to new %s restriction"
21983 org-agenda-overriding-restriction)
21984 (message "Agenda restriction lock removed")))))
21986 ;;; Agenda commands
21988 (defun org-agenda-check-type (error &rest types)
21989 "Check if agenda buffer is of allowed type.
21990 If ERROR is non-nil, throw an error, otherwise just return nil."
21991 (if (memq org-agenda-type types)
21993 (if error
21994 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
21995 nil)))
21997 (defun org-agenda-quit ()
21998 "Exit agenda by removing the window or the buffer."
21999 (interactive)
22000 (let ((buf (current-buffer)))
22001 (if (not (one-window-p)) (delete-window))
22002 (kill-buffer buf)
22003 (org-agenda-maybe-reset-markers 'force)
22004 (org-columns-remove-overlays))
22005 ;; Maybe restore the pre-agenda window configuration.
22006 (and org-agenda-restore-windows-after-quit
22007 (not (eq org-agenda-window-setup 'other-frame))
22008 org-pre-agenda-window-conf
22009 (set-window-configuration org-pre-agenda-window-conf)))
22011 (defun org-agenda-exit ()
22012 "Exit agenda by removing the window or the buffer.
22013 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22014 Org-mode buffers visited directly by the user will not be touched."
22015 (interactive)
22016 (org-release-buffers org-agenda-new-buffers)
22017 (setq org-agenda-new-buffers nil)
22018 (org-agenda-quit))
22020 (defun org-agenda-execute (arg)
22021 "Execute another agenda command, keeping same window.\\<global-map>
22022 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22023 (interactive "P")
22024 (let ((org-agenda-window-setup 'current-window))
22025 (org-agenda arg)))
22027 (defun org-save-all-org-buffers ()
22028 "Save all Org-mode buffers without user confirmation."
22029 (interactive)
22030 (message "Saving all Org-mode buffers...")
22031 (save-some-buffers t 'org-mode-p)
22032 (message "Saving all Org-mode buffers... done"))
22034 (defun org-agenda-redo ()
22035 "Rebuild Agenda.
22036 When this is the global TODO list, a prefix argument will be interpreted."
22037 (interactive)
22038 (let* ((org-agenda-keep-modes t)
22039 (line (org-current-line))
22040 (window-line (- line (org-current-line (window-start))))
22041 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22042 (message "Rebuilding agenda buffer...")
22043 (org-let lprops '(eval org-agenda-redo-command))
22044 (setq org-agenda-undo-list nil
22045 org-agenda-pending-undo-list nil)
22046 (message "Rebuilding agenda buffer...done")
22047 (goto-line line)
22048 (recenter window-line)))
22050 (defun org-agenda-goto-date (date)
22051 "Jump to DATE in agenda."
22052 (interactive (list (org-read-date)))
22053 (org-agenda-list nil date))
22055 (defun org-agenda-goto-today ()
22056 "Go to today."
22057 (interactive)
22058 (org-agenda-check-type t 'timeline 'agenda)
22059 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22060 (cond
22061 (tdpos (goto-char tdpos))
22062 ((eq org-agenda-type 'agenda)
22063 (let* ((sd (time-to-days
22064 (time-subtract (current-time)
22065 (list 0 (* 3600 org-extend-today-until) 0))))
22066 (comp (org-agenda-compute-time-span sd org-agenda-span))
22067 (org-agenda-overriding-arguments org-agenda-last-arguments))
22068 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22069 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22070 (org-agenda-redo)
22071 (org-agenda-find-same-or-today-or-agenda)))
22072 (t (error "Cannot find today")))))
22074 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22075 (goto-char
22076 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22077 (text-property-any (point-min) (point-max) 'org-today t)
22078 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22079 (point-min))))
22081 (defun org-agenda-later (arg)
22082 "Go forward in time by thee current span.
22083 With prefix ARG, go forward that many times the current span."
22084 (interactive "p")
22085 (org-agenda-check-type t 'agenda)
22086 (let* ((span org-agenda-span)
22087 (sd org-starting-day)
22088 (greg (calendar-gregorian-from-absolute sd))
22089 (cnt (get-text-property (point) 'org-day-cnt))
22090 greg2 nd)
22091 (cond
22092 ((eq span 'day)
22093 (setq sd (+ arg sd) nd 1))
22094 ((eq span 'week)
22095 (setq sd (+ (* 7 arg) sd) nd 7))
22096 ((eq span 'month)
22097 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22098 sd (calendar-absolute-from-gregorian greg2))
22099 (setcar greg2 (1+ (car greg2)))
22100 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22101 ((eq span 'year)
22102 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22103 sd (calendar-absolute-from-gregorian greg2))
22104 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22105 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22106 (let ((org-agenda-overriding-arguments
22107 (list (car org-agenda-last-arguments) sd nd t)))
22108 (org-agenda-redo)
22109 (org-agenda-find-same-or-today-or-agenda cnt))))
22111 (defun org-agenda-earlier (arg)
22112 "Go backward in time by the current span.
22113 With prefix ARG, go backward that many times the current span."
22114 (interactive "p")
22115 (org-agenda-later (- arg)))
22117 (defun org-agenda-day-view ()
22118 "Switch to daily view for agenda."
22119 (interactive)
22120 (setq org-agenda-ndays 1)
22121 (org-agenda-change-time-span 'day))
22122 (defun org-agenda-week-view ()
22123 "Switch to daily view for agenda."
22124 (interactive)
22125 (setq org-agenda-ndays 7)
22126 (org-agenda-change-time-span 'week))
22127 (defun org-agenda-month-view ()
22128 "Switch to daily view for agenda."
22129 (interactive)
22130 (org-agenda-change-time-span 'month))
22131 (defun org-agenda-year-view ()
22132 "Switch to daily view for agenda."
22133 (interactive)
22134 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22135 (org-agenda-change-time-span 'year)
22136 (error "Abort")))
22138 (defun org-agenda-change-time-span (span)
22139 "Change the agenda view to SPAN.
22140 SPAN may be `day', `week', `month', `year'."
22141 (org-agenda-check-type t 'agenda)
22142 (if (equal org-agenda-span span)
22143 (error "Viewing span is already \"%s\"" span))
22144 (let* ((sd (or (get-text-property (point) 'day)
22145 org-starting-day))
22146 (computed (org-agenda-compute-time-span sd span))
22147 (org-agenda-overriding-arguments
22148 (list (car org-agenda-last-arguments)
22149 (car computed) (cdr computed) t)))
22150 (org-agenda-redo)
22151 (org-agenda-find-same-or-today-or-agenda))
22152 (org-agenda-set-mode-name)
22153 (message "Switched to %s view" span))
22155 (defun org-agenda-compute-time-span (sd span)
22156 "Compute starting date and number of days for agenda.
22157 SPAN may be `day', `week', `month', `year'. The return value
22158 is a cons cell with the starting date and the number of days,
22159 so that the date SD will be in that range."
22160 (let* ((greg (calendar-gregorian-from-absolute sd))
22162 (cond
22163 ((eq span 'day)
22164 (setq nd 1))
22165 ((eq span 'week)
22166 (let* ((nt (calendar-day-of-week
22167 (calendar-gregorian-from-absolute sd)))
22168 (d (if org-agenda-start-on-weekday
22169 (- nt org-agenda-start-on-weekday)
22170 0)))
22171 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22172 (setq nd 7)))
22173 ((eq span 'month)
22174 (setq sd (calendar-absolute-from-gregorian
22175 (list (car greg) 1 (nth 2 greg)))
22176 nd (- (calendar-absolute-from-gregorian
22177 (list (1+ (car greg)) 1 (nth 2 greg)))
22178 sd)))
22179 ((eq span 'year)
22180 (setq sd (calendar-absolute-from-gregorian
22181 (list 1 1 (nth 2 greg)))
22182 nd (- (calendar-absolute-from-gregorian
22183 (list 1 1 (1+ (nth 2 greg))))
22184 sd))))
22185 (cons sd nd)))
22187 ;; FIXME: does not work if user makes date format that starts with a blank
22188 (defun org-agenda-next-date-line (&optional arg)
22189 "Jump to the next line indicating a date in agenda buffer."
22190 (interactive "p")
22191 (org-agenda-check-type t 'agenda 'timeline)
22192 (beginning-of-line 1)
22193 (if (looking-at "^\\S-") (forward-char 1))
22194 (if (not (re-search-forward "^\\S-" nil t arg))
22195 (progn
22196 (backward-char 1)
22197 (error "No next date after this line in this buffer")))
22198 (goto-char (match-beginning 0)))
22200 (defun org-agenda-previous-date-line (&optional arg)
22201 "Jump to the previous line indicating a date in agenda buffer."
22202 (interactive "p")
22203 (org-agenda-check-type t 'agenda 'timeline)
22204 (beginning-of-line 1)
22205 (if (not (re-search-backward "^\\S-" nil t arg))
22206 (error "No previous date before this line in this buffer")))
22208 ;; Initialize the highlight
22209 (defvar org-hl (org-make-overlay 1 1))
22210 (org-overlay-put org-hl 'face 'highlight)
22212 (defun org-highlight (begin end &optional buffer)
22213 "Highlight a region with overlay."
22214 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22215 org-hl begin end (or buffer (current-buffer))))
22217 (defun org-unhighlight ()
22218 "Detach overlay INDEX."
22219 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22221 ;; FIXME this is currently not used.
22222 (defun org-highlight-until-next-command (beg end &optional buffer)
22223 (org-highlight beg end buffer)
22224 (add-hook 'pre-command-hook 'org-unhighlight-once))
22225 (defun org-unhighlight-once ()
22226 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22227 (org-unhighlight))
22229 (defun org-agenda-follow-mode ()
22230 "Toggle follow mode in an agenda buffer."
22231 (interactive)
22232 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22233 (org-agenda-set-mode-name)
22234 (message "Follow mode is %s"
22235 (if org-agenda-follow-mode "on" "off")))
22237 (defun org-agenda-log-mode ()
22238 "Toggle log mode in an agenda buffer."
22239 (interactive)
22240 (org-agenda-check-type t 'agenda 'timeline)
22241 (setq org-agenda-show-log (not org-agenda-show-log))
22242 (org-agenda-set-mode-name)
22243 (org-agenda-redo)
22244 (message "Log mode is %s"
22245 (if org-agenda-show-log "on" "off")))
22247 (defun org-agenda-toggle-diary ()
22248 "Toggle diary inclusion in an agenda buffer."
22249 (interactive)
22250 (org-agenda-check-type t 'agenda)
22251 (setq org-agenda-include-diary (not org-agenda-include-diary))
22252 (org-agenda-redo)
22253 (org-agenda-set-mode-name)
22254 (message "Diary inclusion turned %s"
22255 (if org-agenda-include-diary "on" "off")))
22257 (defun org-agenda-toggle-time-grid ()
22258 "Toggle time grid in an agenda buffer."
22259 (interactive)
22260 (org-agenda-check-type t 'agenda)
22261 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22262 (org-agenda-redo)
22263 (org-agenda-set-mode-name)
22264 (message "Time-grid turned %s"
22265 (if org-agenda-use-time-grid "on" "off")))
22267 (defun org-agenda-set-mode-name ()
22268 "Set the mode name to indicate all the small mode settings."
22269 (setq mode-name
22270 (concat "Org-Agenda"
22271 (if (equal org-agenda-ndays 1) " Day" "")
22272 (if (equal org-agenda-ndays 7) " Week" "")
22273 (if org-agenda-follow-mode " Follow" "")
22274 (if org-agenda-include-diary " Diary" "")
22275 (if org-agenda-use-time-grid " Grid" "")
22276 (if org-agenda-show-log " Log" "")))
22277 (force-mode-line-update))
22279 (defun org-agenda-post-command-hook ()
22280 (and (eolp) (not (bolp)) (backward-char 1))
22281 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22282 (if (and org-agenda-follow-mode
22283 (get-text-property (point) 'org-marker))
22284 (org-agenda-show)))
22286 (defun org-agenda-show-priority ()
22287 "Show the priority of the current item.
22288 This priority is composed of the main priority given with the [#A] cookies,
22289 and by additional input from the age of a schedules or deadline entry."
22290 (interactive)
22291 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22292 (message "Priority is %d" (if pri pri -1000))))
22294 (defun org-agenda-show-tags ()
22295 "Show the tags applicable to the current item."
22296 (interactive)
22297 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22298 (if tags
22299 (message "Tags are :%s:"
22300 (org-no-properties (mapconcat 'identity tags ":")))
22301 (message "No tags associated with this line"))))
22303 (defun org-agenda-goto (&optional highlight)
22304 "Go to the Org-mode file which contains the item at point."
22305 (interactive)
22306 (let* ((marker (or (get-text-property (point) 'org-marker)
22307 (org-agenda-error)))
22308 (buffer (marker-buffer marker))
22309 (pos (marker-position marker)))
22310 (switch-to-buffer-other-window buffer)
22311 (widen)
22312 (goto-char pos)
22313 (when (org-mode-p)
22314 (org-show-context 'agenda)
22315 (save-excursion
22316 (and (outline-next-heading)
22317 (org-flag-heading nil)))) ; show the next heading
22318 (run-hooks 'org-agenda-after-show-hook)
22319 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22321 (defvar org-agenda-after-show-hook nil
22322 "Normal hook run after an item has been shown from the agenda.
22323 Point is in the buffer where the item originated.")
22325 (defun org-agenda-kill ()
22326 "Kill the entry or subtree belonging to the current agenda entry."
22327 (interactive)
22328 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22329 (let* ((marker (or (get-text-property (point) 'org-marker)
22330 (org-agenda-error)))
22331 (buffer (marker-buffer marker))
22332 (pos (marker-position marker))
22333 (type (get-text-property (point) 'type))
22334 dbeg dend (n 0) conf)
22335 (org-with-remote-undo buffer
22336 (with-current-buffer buffer
22337 (save-excursion
22338 (goto-char pos)
22339 (if (and (org-mode-p) (not (member type '("sexp"))))
22340 (setq dbeg (progn (org-back-to-heading t) (point))
22341 dend (org-end-of-subtree t t))
22342 (setq dbeg (point-at-bol)
22343 dend (min (point-max) (1+ (point-at-eol)))))
22344 (goto-char dbeg)
22345 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22346 (setq conf (or (eq t org-agenda-confirm-kill)
22347 (and (numberp org-agenda-confirm-kill)
22348 (> n org-agenda-confirm-kill))))
22349 (and conf
22350 (not (y-or-n-p
22351 (format "Delete entry with %d lines in buffer \"%s\"? "
22352 n (buffer-name buffer))))
22353 (error "Abort"))
22354 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22355 (with-current-buffer buffer (delete-region dbeg dend))
22356 (message "Agenda item and source killed"))))
22358 (defun org-agenda-archive ()
22359 "Kill the entry or subtree belonging to the current agenda entry."
22360 (interactive)
22361 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22362 (let* ((marker (or (get-text-property (point) 'org-marker)
22363 (org-agenda-error)))
22364 (buffer (marker-buffer marker))
22365 (pos (marker-position marker)))
22366 (org-with-remote-undo buffer
22367 (with-current-buffer buffer
22368 (if (org-mode-p)
22369 (save-excursion
22370 (goto-char pos)
22371 (org-remove-subtree-entries-from-agenda)
22372 (org-back-to-heading t)
22373 (org-archive-subtree))
22374 (error "Archiving works only in Org-mode files"))))))
22376 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22377 "Remove all lines in the agenda that correspond to a given subtree.
22378 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22379 If this information is not given, the function uses the tree at point."
22380 (let ((buf (or buf (current-buffer))) m p)
22381 (save-excursion
22382 (unless (and beg end)
22383 (org-back-to-heading t)
22384 (setq beg (point))
22385 (org-end-of-subtree t)
22386 (setq end (point)))
22387 (set-buffer (get-buffer org-agenda-buffer-name))
22388 (save-excursion
22389 (goto-char (point-max))
22390 (beginning-of-line 1)
22391 (while (not (bobp))
22392 (when (and (setq m (get-text-property (point) 'org-marker))
22393 (equal buf (marker-buffer m))
22394 (setq p (marker-position m))
22395 (>= p beg)
22396 (<= p end))
22397 (let ((inhibit-read-only t))
22398 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22399 (beginning-of-line 0))))))
22401 (defun org-agenda-open-link ()
22402 "Follow the link in the current line, if any."
22403 (interactive)
22404 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22405 (save-excursion
22406 (save-restriction
22407 (narrow-to-region (point-at-bol) (point-at-eol))
22408 (org-open-at-point))))
22410 (defun org-agenda-copy-local-variable (var)
22411 "Get a variable from a referenced buffer and install it here."
22412 (let ((m (get-text-property (point) 'org-marker)))
22413 (when (and m (buffer-live-p (marker-buffer m)))
22414 (org-set-local var (with-current-buffer (marker-buffer m)
22415 (symbol-value var))))))
22417 (defun org-agenda-switch-to (&optional delete-other-windows)
22418 "Go to the Org-mode file which contains the item at point."
22419 (interactive)
22420 (let* ((marker (or (get-text-property (point) 'org-marker)
22421 (org-agenda-error)))
22422 (buffer (marker-buffer marker))
22423 (pos (marker-position marker)))
22424 (switch-to-buffer buffer)
22425 (and delete-other-windows (delete-other-windows))
22426 (widen)
22427 (goto-char pos)
22428 (when (org-mode-p)
22429 (org-show-context 'agenda)
22430 (save-excursion
22431 (and (outline-next-heading)
22432 (org-flag-heading nil)))))) ; show the next heading
22434 (defun org-agenda-goto-mouse (ev)
22435 "Go to the Org-mode file which contains the item at the mouse click."
22436 (interactive "e")
22437 (mouse-set-point ev)
22438 (org-agenda-goto))
22440 (defun org-agenda-show ()
22441 "Display the Org-mode file which contains the item at point."
22442 (interactive)
22443 (let ((win (selected-window)))
22444 (org-agenda-goto t)
22445 (select-window win)))
22447 (defun org-agenda-recenter (arg)
22448 "Display the Org-mode file which contains the item at point and recenter."
22449 (interactive "P")
22450 (let ((win (selected-window)))
22451 (org-agenda-goto t)
22452 (recenter arg)
22453 (select-window win)))
22455 (defun org-agenda-show-mouse (ev)
22456 "Display the Org-mode file which contains the item at the mouse click."
22457 (interactive "e")
22458 (mouse-set-point ev)
22459 (org-agenda-show))
22461 (defun org-agenda-check-no-diary ()
22462 "Check if the entry is a diary link and abort if yes."
22463 (if (get-text-property (point) 'org-agenda-diary-link)
22464 (org-agenda-error)))
22466 (defun org-agenda-error ()
22467 (error "Command not allowed in this line"))
22469 (defun org-agenda-tree-to-indirect-buffer ()
22470 "Show the subtree corresponding to the current entry in an indirect buffer.
22471 This calls the command `org-tree-to-indirect-buffer' from the original
22472 Org-mode buffer.
22473 With numerical prefix arg ARG, go up to this level and then take that tree.
22474 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22475 dedicated frame)."
22476 (interactive)
22477 (org-agenda-check-no-diary)
22478 (let* ((marker (or (get-text-property (point) 'org-marker)
22479 (org-agenda-error)))
22480 (buffer (marker-buffer marker))
22481 (pos (marker-position marker)))
22482 (with-current-buffer buffer
22483 (save-excursion
22484 (goto-char pos)
22485 (call-interactively 'org-tree-to-indirect-buffer)))))
22487 (defvar org-last-heading-marker (make-marker)
22488 "Marker pointing to the headline that last changed its TODO state
22489 by a remote command from the agenda.")
22491 (defun org-agenda-todo-nextset ()
22492 "Switch TODO entry to next sequence."
22493 (interactive)
22494 (org-agenda-todo 'nextset))
22496 (defun org-agenda-todo-previousset ()
22497 "Switch TODO entry to previous sequence."
22498 (interactive)
22499 (org-agenda-todo 'previousset))
22501 (defun org-agenda-todo (&optional arg)
22502 "Cycle TODO state of line at point, also in Org-mode file.
22503 This changes the line at point, all other lines in the agenda referring to
22504 the same tree node, and the headline of the tree node in the Org-mode file."
22505 (interactive "P")
22506 (org-agenda-check-no-diary)
22507 (let* ((col (current-column))
22508 (marker (or (get-text-property (point) 'org-marker)
22509 (org-agenda-error)))
22510 (buffer (marker-buffer marker))
22511 (pos (marker-position marker))
22512 (hdmarker (get-text-property (point) 'org-hd-marker))
22513 (inhibit-read-only t)
22514 newhead)
22515 (org-with-remote-undo buffer
22516 (with-current-buffer buffer
22517 (widen)
22518 (goto-char pos)
22519 (org-show-context 'agenda)
22520 (save-excursion
22521 (and (outline-next-heading)
22522 (org-flag-heading nil))) ; show the next heading
22523 (org-todo arg)
22524 (and (bolp) (forward-char 1))
22525 (setq newhead (org-get-heading))
22526 (save-excursion
22527 (org-back-to-heading)
22528 (move-marker org-last-heading-marker (point))))
22529 (beginning-of-line 1)
22530 (save-excursion
22531 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22532 (move-to-column col))))
22534 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22535 "Change all lines in the agenda buffer which match HDMARKER.
22536 The new content of the line will be NEWHEAD (as modified by
22537 `org-format-agenda-item'). HDMARKER is checked with
22538 `equal' against all `org-hd-marker' text properties in the file.
22539 If FIXFACE is non-nil, the face of each item is modified acording to
22540 the new TODO state."
22541 (let* ((inhibit-read-only t)
22542 props m pl undone-face done-face finish new dotime cat tags)
22543 (save-excursion
22544 (goto-char (point-max))
22545 (beginning-of-line 1)
22546 (while (not finish)
22547 (setq finish (bobp))
22548 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22549 (equal m hdmarker))
22550 (setq props (text-properties-at (point))
22551 dotime (get-text-property (point) 'dotime)
22552 cat (get-text-property (point) 'org-category)
22553 tags (get-text-property (point) 'tags)
22554 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22555 pl (get-text-property (point) 'prefix-length)
22556 undone-face (get-text-property (point) 'undone-face)
22557 done-face (get-text-property (point) 'done-face))
22558 (move-to-column pl)
22559 (cond
22560 ((equal new "")
22561 (beginning-of-line 1)
22562 (and (looking-at ".*\n?") (replace-match "")))
22563 ((looking-at ".*")
22564 (replace-match new t t)
22565 (beginning-of-line 1)
22566 (add-text-properties (point-at-bol) (point-at-eol) props)
22567 (when fixface
22568 (add-text-properties
22569 (point-at-bol) (point-at-eol)
22570 (list 'face
22571 (if org-last-todo-state-is-todo
22572 undone-face done-face))))
22573 (org-agenda-highlight-todo 'line)
22574 (beginning-of-line 1))
22575 (t (error "Line update did not work"))))
22576 (beginning-of-line 0)))
22577 (org-finalize-agenda)))
22579 (defun org-agenda-align-tags (&optional line)
22580 "Align all tags in agenda items to `org-agenda-tags-column'."
22581 (let ((inhibit-read-only t) l c)
22582 (save-excursion
22583 (goto-char (if line (point-at-bol) (point-min)))
22584 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22585 (if line (point-at-eol) nil) t)
22586 (add-text-properties
22587 (match-beginning 2) (match-end 2)
22588 (list 'face (list 'org-tag (get-text-property
22589 (match-beginning 2) 'face))))
22590 (setq l (- (match-end 2) (match-beginning 2))
22591 c (if (< org-agenda-tags-column 0)
22592 (- (abs org-agenda-tags-column) l)
22593 org-agenda-tags-column))
22594 (delete-region (match-beginning 1) (match-end 1))
22595 (goto-char (match-beginning 1))
22596 (insert (org-add-props
22597 (make-string (max 1 (- c (current-column))) ?\ )
22598 (text-properties-at (point))))))))
22600 (defun org-agenda-priority-up ()
22601 "Increase the priority of line at point, also in Org-mode file."
22602 (interactive)
22603 (org-agenda-priority 'up))
22605 (defun org-agenda-priority-down ()
22606 "Decrease the priority of line at point, also in Org-mode file."
22607 (interactive)
22608 (org-agenda-priority 'down))
22610 (defun org-agenda-priority (&optional force-direction)
22611 "Set the priority of line at point, also in Org-mode file.
22612 This changes the line at point, all other lines in the agenda referring to
22613 the same tree node, and the headline of the tree node in the Org-mode file."
22614 (interactive)
22615 (org-agenda-check-no-diary)
22616 (let* ((marker (or (get-text-property (point) 'org-marker)
22617 (org-agenda-error)))
22618 (hdmarker (get-text-property (point) 'org-hd-marker))
22619 (buffer (marker-buffer hdmarker))
22620 (pos (marker-position hdmarker))
22621 (inhibit-read-only t)
22622 newhead)
22623 (org-with-remote-undo buffer
22624 (with-current-buffer buffer
22625 (widen)
22626 (goto-char pos)
22627 (org-show-context 'agenda)
22628 (save-excursion
22629 (and (outline-next-heading)
22630 (org-flag-heading nil))) ; show the next heading
22631 (funcall 'org-priority force-direction)
22632 (end-of-line 1)
22633 (setq newhead (org-get-heading)))
22634 (org-agenda-change-all-lines newhead hdmarker)
22635 (beginning-of-line 1))))
22637 (defun org-get-tags-at (&optional pos)
22638 "Get a list of all headline tags applicable at POS.
22639 POS defaults to point. If tags are inherited, the list contains
22640 the targets in the same sequence as the headlines appear, i.e.
22641 the tags of the current headline come last."
22642 (interactive)
22643 (let (tags lastpos)
22644 (save-excursion
22645 (save-restriction
22646 (widen)
22647 (goto-char (or pos (point)))
22648 (save-match-data
22649 (org-back-to-heading t)
22650 (condition-case nil
22651 (while (not (equal lastpos (point)))
22652 (setq lastpos (point))
22653 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22654 (setq tags (append (org-split-string
22655 (org-match-string-no-properties 1) ":")
22656 tags)))
22657 (or org-use-tag-inheritance (error ""))
22658 (org-up-heading-all 1))
22659 (error nil))))
22660 tags)))
22662 ;; FIXME: should fix the tags property of the agenda line.
22663 (defun org-agenda-set-tags ()
22664 "Set tags for the current headline."
22665 (interactive)
22666 (org-agenda-check-no-diary)
22667 (if (and (org-region-active-p) (interactive-p))
22668 (call-interactively 'org-change-tag-in-region)
22669 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22670 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22671 (org-agenda-error)))
22672 (buffer (marker-buffer hdmarker))
22673 (pos (marker-position hdmarker))
22674 (inhibit-read-only t)
22675 newhead)
22676 (org-with-remote-undo buffer
22677 (with-current-buffer buffer
22678 (widen)
22679 (goto-char pos)
22680 (save-excursion
22681 (org-show-context 'agenda))
22682 (save-excursion
22683 (and (outline-next-heading)
22684 (org-flag-heading nil))) ; show the next heading
22685 (goto-char pos)
22686 (call-interactively 'org-set-tags)
22687 (end-of-line 1)
22688 (setq newhead (org-get-heading)))
22689 (org-agenda-change-all-lines newhead hdmarker)
22690 (beginning-of-line 1)))))
22692 (defun org-agenda-toggle-archive-tag ()
22693 "Toggle the archive tag for the current entry."
22694 (interactive)
22695 (org-agenda-check-no-diary)
22696 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22697 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22698 (org-agenda-error)))
22699 (buffer (marker-buffer hdmarker))
22700 (pos (marker-position hdmarker))
22701 (inhibit-read-only t)
22702 newhead)
22703 (org-with-remote-undo buffer
22704 (with-current-buffer buffer
22705 (widen)
22706 (goto-char pos)
22707 (org-show-context 'agenda)
22708 (save-excursion
22709 (and (outline-next-heading)
22710 (org-flag-heading nil))) ; show the next heading
22711 (call-interactively 'org-toggle-archive-tag)
22712 (end-of-line 1)
22713 (setq newhead (org-get-heading)))
22714 (org-agenda-change-all-lines newhead hdmarker)
22715 (beginning-of-line 1))))
22717 (defun org-agenda-date-later (arg &optional what)
22718 "Change the date of this item to one day later."
22719 (interactive "p")
22720 (org-agenda-check-type t 'agenda 'timeline)
22721 (org-agenda-check-no-diary)
22722 (let* ((marker (or (get-text-property (point) 'org-marker)
22723 (org-agenda-error)))
22724 (buffer (marker-buffer marker))
22725 (pos (marker-position marker)))
22726 (org-with-remote-undo buffer
22727 (with-current-buffer buffer
22728 (widen)
22729 (goto-char pos)
22730 (if (not (org-at-timestamp-p))
22731 (error "Cannot find time stamp"))
22732 (org-timestamp-change arg (or what 'day)))
22733 (org-agenda-show-new-time marker org-last-changed-timestamp))
22734 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22736 (defun org-agenda-date-earlier (arg &optional what)
22737 "Change the date of this item to one day earlier."
22738 (interactive "p")
22739 (org-agenda-date-later (- arg) what))
22741 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22742 "Show new date stamp via text properties."
22743 ;; We use text properties to make this undoable
22744 (let ((inhibit-read-only t))
22745 (setq stamp (concat " " prefix " => " stamp))
22746 (save-excursion
22747 (goto-char (point-max))
22748 (while (not (bobp))
22749 (when (equal marker (get-text-property (point) 'org-marker))
22750 (move-to-column (- (window-width) (length stamp)) t)
22751 (if (featurep 'xemacs)
22752 ;; Use `duplicable' property to trigger undo recording
22753 (let ((ex (make-extent nil nil))
22754 (gl (make-glyph stamp)))
22755 (set-glyph-face gl 'secondary-selection)
22756 (set-extent-properties
22757 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22758 (insert-extent ex (1- (point)) (point-at-eol)))
22759 (add-text-properties
22760 (1- (point)) (point-at-eol)
22761 (list 'display (org-add-props stamp nil
22762 'face 'secondary-selection))))
22763 (beginning-of-line 1))
22764 (beginning-of-line 0)))))
22766 (defun org-agenda-date-prompt (arg)
22767 "Change the date of this item. Date is prompted for, with default today.
22768 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22769 be used to request time specification in the time stamp."
22770 (interactive "P")
22771 (org-agenda-check-type t 'agenda 'timeline)
22772 (org-agenda-check-no-diary)
22773 (let* ((marker (or (get-text-property (point) 'org-marker)
22774 (org-agenda-error)))
22775 (buffer (marker-buffer marker))
22776 (pos (marker-position marker)))
22777 (org-with-remote-undo buffer
22778 (with-current-buffer buffer
22779 (widen)
22780 (goto-char pos)
22781 (if (not (org-at-timestamp-p))
22782 (error "Cannot find time stamp"))
22783 (org-time-stamp arg)
22784 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22786 (defun org-agenda-schedule (arg)
22787 "Schedule the item at point."
22788 (interactive "P")
22789 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22790 (org-agenda-check-no-diary)
22791 (let* ((marker (or (get-text-property (point) 'org-marker)
22792 (org-agenda-error)))
22793 (buffer (marker-buffer marker))
22794 (pos (marker-position marker))
22795 (org-insert-labeled-timestamps-at-point nil)
22797 (org-with-remote-undo buffer
22798 (with-current-buffer buffer
22799 (widen)
22800 (goto-char pos)
22801 (setq ts (org-schedule arg)))
22802 (org-agenda-show-new-time marker ts "S"))
22803 (message "Item scheduled for %s" ts)))
22805 (defun org-agenda-deadline (arg)
22806 "Schedule the item at point."
22807 (interactive "P")
22808 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22809 (org-agenda-check-no-diary)
22810 (let* ((marker (or (get-text-property (point) 'org-marker)
22811 (org-agenda-error)))
22812 (buffer (marker-buffer marker))
22813 (pos (marker-position marker))
22814 (org-insert-labeled-timestamps-at-point nil)
22816 (org-with-remote-undo buffer
22817 (with-current-buffer buffer
22818 (widen)
22819 (goto-char pos)
22820 (setq ts (org-deadline arg)))
22821 (org-agenda-show-new-time marker ts "S"))
22822 (message "Deadline for this item set to %s" ts)))
22824 (defun org-get-heading (&optional no-tags)
22825 "Return the heading of the current entry, without the stars."
22826 (save-excursion
22827 (org-back-to-heading t)
22828 (if (looking-at
22829 (if no-tags
22830 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22831 "\\*+[ \t]+\\([^\r\n]*\\)"))
22832 (match-string 1) "")))
22834 (defun org-agenda-clock-in (&optional arg)
22835 "Start the clock on the currently selected item."
22836 (interactive "P")
22837 (org-agenda-check-no-diary)
22838 (let* ((marker (or (get-text-property (point) 'org-marker)
22839 (org-agenda-error)))
22840 (pos (marker-position marker)))
22841 (org-with-remote-undo (marker-buffer marker)
22842 (with-current-buffer (marker-buffer marker)
22843 (widen)
22844 (goto-char pos)
22845 (org-clock-in)))))
22847 (defun org-agenda-clock-out (&optional arg)
22848 "Stop the currently running clock."
22849 (interactive "P")
22850 (unless (marker-buffer org-clock-marker)
22851 (error "No running clock"))
22852 (org-with-remote-undo (marker-buffer org-clock-marker)
22853 (org-clock-out)))
22855 (defun org-agenda-clock-cancel (&optional arg)
22856 "Cancel the currently running clock."
22857 (interactive "P")
22858 (unless (marker-buffer org-clock-marker)
22859 (error "No running clock"))
22860 (org-with-remote-undo (marker-buffer org-clock-marker)
22861 (org-clock-cancel)))
22863 (defun org-agenda-diary-entry ()
22864 "Make a diary entry, like the `i' command from the calendar.
22865 All the standard commands work: block, weekly etc."
22866 (interactive)
22867 (org-agenda-check-type t 'agenda 'timeline)
22868 (require 'diary-lib)
22869 (let* ((char (progn
22870 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
22871 (read-char-exclusive)))
22872 (cmd (cdr (assoc char
22873 '((?d . insert-diary-entry)
22874 (?w . insert-weekly-diary-entry)
22875 (?m . insert-monthly-diary-entry)
22876 (?y . insert-yearly-diary-entry)
22877 (?a . insert-anniversary-diary-entry)
22878 (?b . insert-block-diary-entry)
22879 (?c . insert-cyclic-diary-entry)))))
22880 (oldf (symbol-function 'calendar-cursor-to-date))
22881 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
22882 (point (point))
22883 (mark (or (mark t) (point))))
22884 (unless cmd
22885 (error "No command associated with <%c>" char))
22886 (unless (and (get-text-property point 'day)
22887 (or (not (equal ?b char))
22888 (get-text-property mark 'day)))
22889 (error "Don't know which date to use for diary entry"))
22890 ;; We implement this by hacking the `calendar-cursor-to-date' function
22891 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
22892 (let ((calendar-mark-ring
22893 (list (calendar-gregorian-from-absolute
22894 (or (get-text-property mark 'day)
22895 (get-text-property point 'day))))))
22896 (unwind-protect
22897 (progn
22898 (fset 'calendar-cursor-to-date
22899 (lambda (&optional error)
22900 (calendar-gregorian-from-absolute
22901 (get-text-property point 'day))))
22902 (call-interactively cmd))
22903 (fset 'calendar-cursor-to-date oldf)))))
22906 (defun org-agenda-execute-calendar-command (cmd)
22907 "Execute a calendar command from the agenda, with the date associated to
22908 the cursor position."
22909 (org-agenda-check-type t 'agenda 'timeline)
22910 (require 'diary-lib)
22911 (unless (get-text-property (point) 'day)
22912 (error "Don't know which date to use for calendar command"))
22913 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
22914 (point (point))
22915 (date (calendar-gregorian-from-absolute
22916 (get-text-property point 'day)))
22917 ;; the following 3 vars are needed in the calendar
22918 (displayed-day (extract-calendar-day date))
22919 (displayed-month (extract-calendar-month date))
22920 (displayed-year (extract-calendar-year date)))
22921 (unwind-protect
22922 (progn
22923 (fset 'calendar-cursor-to-date
22924 (lambda (&optional error)
22925 (calendar-gregorian-from-absolute
22926 (get-text-property point 'day))))
22927 (call-interactively cmd))
22928 (fset 'calendar-cursor-to-date oldf))))
22930 (defun org-agenda-phases-of-moon ()
22931 "Display the phases of the moon for the 3 months around the cursor date."
22932 (interactive)
22933 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
22935 (defun org-agenda-holidays ()
22936 "Display the holidays for the 3 months around the cursor date."
22937 (interactive)
22938 (org-agenda-execute-calendar-command 'list-calendar-holidays))
22940 (defun org-agenda-sunrise-sunset (arg)
22941 "Display sunrise and sunset for the cursor date.
22942 Latitude and longitude can be specified with the variables
22943 `calendar-latitude' and `calendar-longitude'. When called with prefix
22944 argument, latitude and longitude will be prompted for."
22945 (interactive "P")
22946 (let ((calendar-longitude (if arg nil calendar-longitude))
22947 (calendar-latitude (if arg nil calendar-latitude))
22948 (calendar-location-name
22949 (if arg "the given coordinates" calendar-location-name)))
22950 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
22952 (defun org-agenda-goto-calendar ()
22953 "Open the Emacs calendar with the date at the cursor."
22954 (interactive)
22955 (org-agenda-check-type t 'agenda 'timeline)
22956 (let* ((day (or (get-text-property (point) 'day)
22957 (error "Don't know which date to open in calendar")))
22958 (date (calendar-gregorian-from-absolute day))
22959 (calendar-move-hook nil)
22960 (view-calendar-holidays-initially nil)
22961 (view-diary-entries-initially nil))
22962 (calendar)
22963 (calendar-goto-date date)))
22965 (defun org-calendar-goto-agenda ()
22966 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
22967 This is a command that has to be installed in `calendar-mode-map'."
22968 (interactive)
22969 (org-agenda-list nil (calendar-absolute-from-gregorian
22970 (calendar-cursor-to-date))
22971 nil))
22973 (defun org-agenda-convert-date ()
22974 (interactive)
22975 (org-agenda-check-type t 'agenda 'timeline)
22976 (let ((day (get-text-property (point) 'day))
22977 date s)
22978 (unless day
22979 (error "Don't know which date to convert"))
22980 (setq date (calendar-gregorian-from-absolute day))
22981 (setq s (concat
22982 "Gregorian: " (calendar-date-string date) "\n"
22983 "ISO: " (calendar-iso-date-string date) "\n"
22984 "Day of Yr: " (calendar-day-of-year-string date) "\n"
22985 "Julian: " (calendar-julian-date-string date) "\n"
22986 "Astron. JD: " (calendar-astro-date-string date)
22987 " (Julian date number at noon UTC)\n"
22988 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
22989 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
22990 "French: " (calendar-french-date-string date) "\n"
22991 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
22992 "Mayan: " (calendar-mayan-date-string date) "\n"
22993 "Coptic: " (calendar-coptic-date-string date) "\n"
22994 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
22995 "Persian: " (calendar-persian-date-string date) "\n"
22996 "Chinese: " (calendar-chinese-date-string date) "\n"))
22997 (with-output-to-temp-buffer "*Dates*"
22998 (princ s))
22999 (if (fboundp 'fit-window-to-buffer)
23000 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23003 ;;;; Embedded LaTeX
23005 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23006 "Keymap for the minor `org-cdlatex-mode'.")
23008 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23009 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23010 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23011 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23012 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23014 (defvar org-cdlatex-texmathp-advice-is-done nil
23015 "Flag remembering if we have applied the advice to texmathp already.")
23017 (define-minor-mode org-cdlatex-mode
23018 "Toggle the minor `org-cdlatex-mode'.
23019 This mode supports entering LaTeX environment and math in LaTeX fragments
23020 in Org-mode.
23021 \\{org-cdlatex-mode-map}"
23022 nil " OCDL" nil
23023 (when org-cdlatex-mode (require 'cdlatex))
23024 (unless org-cdlatex-texmathp-advice-is-done
23025 (setq org-cdlatex-texmathp-advice-is-done t)
23026 (defadvice texmathp (around org-math-always-on activate)
23027 "Always return t in org-mode buffers.
23028 This is because we want to insert math symbols without dollars even outside
23029 the LaTeX math segments. If Orgmode thinks that point is actually inside
23030 en embedded LaTeX fragement, let texmathp do its job.
23031 \\[org-cdlatex-mode-map]"
23032 (interactive)
23033 (let (p)
23034 (cond
23035 ((not (org-mode-p)) ad-do-it)
23036 ((eq this-command 'cdlatex-math-symbol)
23037 (setq ad-return-value t
23038 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23040 (let ((p (org-inside-LaTeX-fragment-p)))
23041 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23042 (setq ad-return-value t
23043 texmathp-why '("Org-mode embedded math" . 0))
23044 (if p ad-do-it)))))))))
23046 (defun turn-on-org-cdlatex ()
23047 "Unconditionally turn on `org-cdlatex-mode'."
23048 (org-cdlatex-mode 1))
23050 (defun org-inside-LaTeX-fragment-p ()
23051 "Test if point is inside a LaTeX fragment.
23052 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23053 sequence appearing also before point.
23054 Even though the matchers for math are configurable, this function assumes
23055 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23056 delimiters are skipped when they have been removed by customization.
23057 The return value is nil, or a cons cell with the delimiter and
23058 and the position of this delimiter.
23060 This function does a reasonably good job, but can locally be fooled by
23061 for example currency specifications. For example it will assume being in
23062 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23063 fragments that are properly closed, but during editing, we have to live
23064 with the uncertainty caused by missing closing delimiters. This function
23065 looks only before point, not after."
23066 (catch 'exit
23067 (let ((pos (point))
23068 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23069 (lim (progn
23070 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23071 (point)))
23072 dd-on str (start 0) m re)
23073 (goto-char pos)
23074 (when dodollar
23075 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23076 re (nth 1 (assoc "$" org-latex-regexps)))
23077 (while (string-match re str start)
23078 (cond
23079 ((= (match-end 0) (length str))
23080 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23081 ((= (match-end 0) (- (length str) 5))
23082 (throw 'exit nil))
23083 (t (setq start (match-end 0))))))
23084 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23085 (goto-char pos)
23086 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23087 (and (match-beginning 2) (throw 'exit nil))
23088 ;; count $$
23089 (while (re-search-backward "\\$\\$" lim t)
23090 (setq dd-on (not dd-on)))
23091 (goto-char pos)
23092 (if dd-on (cons "$$" m))))))
23095 (defun org-try-cdlatex-tab ()
23096 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23097 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23098 - inside a LaTeX fragment, or
23099 - after the first word in a line, where an abbreviation expansion could
23100 insert a LaTeX environment."
23101 (when org-cdlatex-mode
23102 (cond
23103 ((save-excursion
23104 (skip-chars-backward "a-zA-Z0-9*")
23105 (skip-chars-backward " \t")
23106 (bolp))
23107 (cdlatex-tab) t)
23108 ((org-inside-LaTeX-fragment-p)
23109 (cdlatex-tab) t)
23110 (t nil))))
23112 (defun org-cdlatex-underscore-caret (&optional arg)
23113 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23114 Revert to the normal definition outside of these fragments."
23115 (interactive "P")
23116 (if (org-inside-LaTeX-fragment-p)
23117 (call-interactively 'cdlatex-sub-superscript)
23118 (let (org-cdlatex-mode)
23119 (call-interactively (key-binding (vector last-input-event))))))
23121 (defun org-cdlatex-math-modify (&optional arg)
23122 "Execute `cdlatex-math-modify' in LaTeX fragments.
23123 Revert to the normal definition outside of these fragments."
23124 (interactive "P")
23125 (if (org-inside-LaTeX-fragment-p)
23126 (call-interactively 'cdlatex-math-modify)
23127 (let (org-cdlatex-mode)
23128 (call-interactively (key-binding (vector last-input-event))))))
23130 (defvar org-latex-fragment-image-overlays nil
23131 "List of overlays carrying the images of latex fragments.")
23132 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23134 (defun org-remove-latex-fragment-image-overlays ()
23135 "Remove all overlays with LaTeX fragment images in current buffer."
23136 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23137 (setq org-latex-fragment-image-overlays nil))
23139 (defun org-preview-latex-fragment (&optional subtree)
23140 "Preview the LaTeX fragment at point, or all locally or globally.
23141 If the cursor is in a LaTeX fragment, create the image and overlay
23142 it over the source code. If there is no fragment at point, display
23143 all fragments in the current text, from one headline to the next. With
23144 prefix SUBTREE, display all fragments in the current subtree. With a
23145 double prefix `C-u C-u', or when the cursor is before the first headline,
23146 display all fragments in the buffer.
23147 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23148 (interactive "P")
23149 (org-remove-latex-fragment-image-overlays)
23150 (save-excursion
23151 (save-restriction
23152 (let (beg end at msg)
23153 (cond
23154 ((or (equal subtree '(16))
23155 (not (save-excursion
23156 (re-search-backward (concat "^" outline-regexp) nil t))))
23157 (setq beg (point-min) end (point-max)
23158 msg "Creating images for buffer...%s"))
23159 ((equal subtree '(4))
23160 (org-back-to-heading)
23161 (setq beg (point) end (org-end-of-subtree t)
23162 msg "Creating images for subtree...%s"))
23164 (if (setq at (org-inside-LaTeX-fragment-p))
23165 (goto-char (max (point-min) (- (cdr at) 2)))
23166 (org-back-to-heading))
23167 (setq beg (point) end (progn (outline-next-heading) (point))
23168 msg (if at "Creating image...%s"
23169 "Creating images for entry...%s"))))
23170 (message msg "")
23171 (narrow-to-region beg end)
23172 (goto-char beg)
23173 (org-format-latex
23174 (concat "ltxpng/" (file-name-sans-extension
23175 (file-name-nondirectory
23176 buffer-file-name)))
23177 default-directory 'overlays msg at 'forbuffer)
23178 (message msg "done. Use `C-c C-c' to remove images.")))))
23180 (defvar org-latex-regexps
23181 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23182 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23183 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23184 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23185 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23186 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23187 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23188 "Regular expressions for matching embedded LaTeX.")
23190 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23191 "Replace LaTeX fragments with links to an image, and produce images."
23192 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23193 (let* ((prefixnodir (file-name-nondirectory prefix))
23194 (absprefix (expand-file-name prefix dir))
23195 (todir (file-name-directory absprefix))
23196 (opt org-format-latex-options)
23197 (matchers (plist-get opt :matchers))
23198 (re-list org-latex-regexps)
23199 (cnt 0) txt link beg end re e checkdir
23200 m n block linkfile movefile ov)
23201 ;; Check if there are old images files with this prefix, and remove them
23202 (when (file-directory-p todir)
23203 (mapc 'delete-file
23204 (directory-files
23205 todir 'full
23206 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23207 ;; Check the different regular expressions
23208 (while (setq e (pop re-list))
23209 (setq m (car e) re (nth 1 e) n (nth 2 e)
23210 block (if (nth 3 e) "\n\n" ""))
23211 (when (member m matchers)
23212 (goto-char (point-min))
23213 (while (re-search-forward re nil t)
23214 (when (or (not at) (equal (cdr at) (match-beginning n)))
23215 (setq txt (match-string n)
23216 beg (match-beginning n) end (match-end n)
23217 cnt (1+ cnt)
23218 linkfile (format "%s_%04d.png" prefix cnt)
23219 movefile (format "%s_%04d.png" absprefix cnt)
23220 link (concat block "[[file:" linkfile "]]" block))
23221 (if msg (message msg cnt))
23222 (goto-char beg)
23223 (unless checkdir ; make sure the directory exists
23224 (setq checkdir t)
23225 (or (file-directory-p todir) (make-directory todir)))
23226 (org-create-formula-image
23227 txt movefile opt forbuffer)
23228 (if overlays
23229 (progn
23230 (setq ov (org-make-overlay beg end))
23231 (if (featurep 'xemacs)
23232 (progn
23233 (org-overlay-put ov 'invisible t)
23234 (org-overlay-put
23235 ov 'end-glyph
23236 (make-glyph (vector 'png :file movefile))))
23237 (org-overlay-put
23238 ov 'display
23239 (list 'image :type 'png :file movefile :ascent 'center)))
23240 (push ov org-latex-fragment-image-overlays)
23241 (goto-char end))
23242 (delete-region beg end)
23243 (insert link))))))))
23245 ;; This function borrows from Ganesh Swami's latex2png.el
23246 (defun org-create-formula-image (string tofile options buffer)
23247 (let* ((tmpdir (if (featurep 'xemacs)
23248 (temp-directory)
23249 temporary-file-directory))
23250 (texfilebase (make-temp-name
23251 (expand-file-name "orgtex" tmpdir)))
23252 (texfile (concat texfilebase ".tex"))
23253 (dvifile (concat texfilebase ".dvi"))
23254 (pngfile (concat texfilebase ".png"))
23255 (fnh (face-attribute 'default :height nil))
23256 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23257 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23258 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23259 "Black"))
23260 (bg (or (plist-get options (if buffer :background :html-background))
23261 "Transparent")))
23262 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23263 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23264 (with-temp-file texfile
23265 (insert org-format-latex-header
23266 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23267 (let ((dir default-directory))
23268 (condition-case nil
23269 (progn
23270 (cd tmpdir)
23271 (call-process "latex" nil nil nil texfile))
23272 (error nil))
23273 (cd dir))
23274 (if (not (file-exists-p dvifile))
23275 (progn (message "Failed to create dvi file from %s" texfile) nil)
23276 (call-process "dvipng" nil nil nil
23277 "-E" "-fg" fg "-bg" bg
23278 "-D" dpi
23279 ;;"-x" scale "-y" scale
23280 "-T" "tight"
23281 "-o" pngfile
23282 dvifile)
23283 (if (not (file-exists-p pngfile))
23284 (progn (message "Failed to create png file from %s" texfile) nil)
23285 ;; Use the requested file name and clean up
23286 (copy-file pngfile tofile 'replace)
23287 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23288 (delete-file (concat texfilebase e)))
23289 pngfile))))
23291 (defun org-dvipng-color (attr)
23292 "Return an rgb color specification for dvipng."
23293 (apply 'format "rgb %s %s %s"
23294 (mapcar 'org-normalize-color
23295 (color-values (face-attribute 'default attr nil)))))
23297 (defun org-normalize-color (value)
23298 "Return string to be used as color value for an RGB component."
23299 (format "%g" (/ value 65535.0)))
23301 ;;;; Exporting
23303 ;;; Variables, constants, and parameter plists
23305 (defconst org-level-max 20)
23307 (defvar org-export-html-preamble nil
23308 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23309 (defvar org-export-html-postamble nil
23310 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23311 (defvar org-export-html-auto-preamble t
23312 "Should default preamble be inserted? Set by publishing functions.")
23313 (defvar org-export-html-auto-postamble t
23314 "Should default postamble be inserted? Set by publishing functions.")
23315 (defvar org-current-export-file nil) ; dynamically scoped parameter
23316 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23319 (defconst org-export-plist-vars
23320 '((:language . org-export-default-language)
23321 (:customtime . org-display-custom-times)
23322 (:headline-levels . org-export-headline-levels)
23323 (:section-numbers . org-export-with-section-numbers)
23324 (:table-of-contents . org-export-with-toc)
23325 (:preserve-breaks . org-export-preserve-breaks)
23326 (:archived-trees . org-export-with-archived-trees)
23327 (:emphasize . org-export-with-emphasize)
23328 (:sub-superscript . org-export-with-sub-superscripts)
23329 (:special-strings . org-export-with-special-strings)
23330 (:footnotes . org-export-with-footnotes)
23331 (:drawers . org-export-with-drawers)
23332 (:tags . org-export-with-tags)
23333 (:TeX-macros . org-export-with-TeX-macros)
23334 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23335 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23336 (:fixed-width . org-export-with-fixed-width)
23337 (:timestamps . org-export-with-timestamps)
23338 (:author-info . org-export-author-info)
23339 (:time-stamp-file . org-export-time-stamp-file)
23340 (:tables . org-export-with-tables)
23341 (:table-auto-headline . org-export-highlight-first-table-line)
23342 (:style . org-export-html-style)
23343 (:agenda-style . org-agenda-export-html-style)
23344 (:convert-org-links . org-export-html-link-org-files-as-html)
23345 (:inline-images . org-export-html-inline-images)
23346 (:html-extension . org-export-html-extension)
23347 (:html-table-tag . org-export-html-table-tag)
23348 (:expand-quoted-html . org-export-html-expand)
23349 (:timestamp . org-export-html-with-timestamp)
23350 (:publishing-directory . org-export-publishing-directory)
23351 (:preamble . org-export-html-preamble)
23352 (:postamble . org-export-html-postamble)
23353 (:auto-preamble . org-export-html-auto-preamble)
23354 (:auto-postamble . org-export-html-auto-postamble)
23355 (:author . user-full-name)
23356 (:email . user-mail-address)))
23358 (defun org-default-export-plist ()
23359 "Return the property list with default settings for the export variables."
23360 (let ((l org-export-plist-vars) rtn e)
23361 (while (setq e (pop l))
23362 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23363 rtn))
23365 (defun org-infile-export-plist ()
23366 "Return the property list with file-local settings for export."
23367 (save-excursion
23368 (save-restriction
23369 (widen)
23370 (goto-char 0)
23371 (let ((re (org-make-options-regexp
23372 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23373 p key val text options)
23374 (while (re-search-forward re nil t)
23375 (setq key (org-match-string-no-properties 1)
23376 val (org-match-string-no-properties 2))
23377 (cond
23378 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23379 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23380 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23381 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23382 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23383 ((string-equal key "TEXT")
23384 (setq text (if text (concat text "\n" val) val)))
23385 ((string-equal key "OPTIONS") (setq options val))))
23386 (setq p (plist-put p :text text))
23387 (when options
23388 (let ((op '(("H" . :headline-levels)
23389 ("num" . :section-numbers)
23390 ("toc" . :table-of-contents)
23391 ("\\n" . :preserve-breaks)
23392 ("@" . :expand-quoted-html)
23393 (":" . :fixed-width)
23394 ("|" . :tables)
23395 ("^" . :sub-superscript)
23396 ("-" . :special-strings)
23397 ("f" . :footnotes)
23398 ("d" . :drawers)
23399 ("tags" . :tags)
23400 ("*" . :emphasize)
23401 ("TeX" . :TeX-macros)
23402 ("LaTeX" . :LaTeX-fragments)
23403 ("skip" . :skip-before-1st-heading)
23404 ("author" . :author-info)
23405 ("timestamp" . :time-stamp-file)))
23407 (while (setq o (pop op))
23408 (if (string-match (concat (regexp-quote (car o))
23409 ":\\([^ \t\n\r;,.]*\\)")
23410 options)
23411 (setq p (plist-put p (cdr o)
23412 (car (read-from-string
23413 (match-string 1 options)))))))))
23414 p))))
23416 (defun org-export-directory (type plist)
23417 (let* ((val (plist-get plist :publishing-directory))
23418 (dir (if (listp val)
23419 (or (cdr (assoc type val)) ".")
23420 val)))
23421 dir))
23423 (defun org-skip-comments (lines)
23424 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23425 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23426 (re2 "^\\(\\*+\\)[ \t\n\r]")
23427 (case-fold-search nil)
23428 rtn line level)
23429 (while (setq line (pop lines))
23430 (cond
23431 ((and (string-match re1 line)
23432 (setq level (- (match-end 1) (match-beginning 1))))
23433 ;; Beginning of a COMMENT subtree. Skip it.
23434 (while (and (setq line (pop lines))
23435 (or (not (string-match re2 line))
23436 (> (- (match-end 1) (match-beginning 1)) level))))
23437 (setq lines (cons line lines)))
23438 ((string-match "^#" line)
23439 ;; an ordinary comment line
23441 ((and org-export-table-remove-special-lines
23442 (string-match "^[ \t]*|" line)
23443 (or (string-match "^[ \t]*| *[!_^] *|" line)
23444 (and (string-match "| *<[0-9]+> *|" line)
23445 (not (string-match "| *[^ <|]" line)))))
23446 ;; a special table line that should be removed
23448 (t (setq rtn (cons line rtn)))))
23449 (nreverse rtn)))
23451 (defun org-export (&optional arg)
23452 (interactive)
23453 (let ((help "[t] insert the export option template
23454 \[v] limit export to visible part of outline tree
23456 \[a] export as ASCII
23458 \[h] export as HTML
23459 \[H] export as HTML to temporary buffer
23460 \[R] export region as HTML
23461 \[b] export as HTML and browse immediately
23462 \[x] export as XOXO
23464 \[l] export as LaTeX
23465 \[L] export as LaTeX to temporary buffer
23467 \[i] export current file as iCalendar file
23468 \[I] export all agenda files as iCalendar files
23469 \[c] export agenda files into combined iCalendar file
23471 \[F] publish current file
23472 \[P] publish current project
23473 \[X] publish... (project will be prompted for)
23474 \[A] publish all projects")
23475 (cmds
23476 '((?t . org-insert-export-options-template)
23477 (?v . org-export-visible)
23478 (?a . org-export-as-ascii)
23479 (?h . org-export-as-html)
23480 (?b . org-export-as-html-and-open)
23481 (?H . org-export-as-html-to-buffer)
23482 (?R . org-export-region-as-html)
23483 (?x . org-export-as-xoxo)
23484 (?l . org-export-as-latex)
23485 (?L . org-export-as-latex-to-buffer)
23486 (?i . org-export-icalendar-this-file)
23487 (?I . org-export-icalendar-all-agenda-files)
23488 (?c . org-export-icalendar-combine-agenda-files)
23489 (?F . org-publish-current-file)
23490 (?P . org-publish-current-project)
23491 (?X . org-publish)
23492 (?A . org-publish-all)))
23493 r1 r2 ass)
23494 (save-window-excursion
23495 (delete-other-windows)
23496 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23497 (princ help))
23498 (message "Select command: ")
23499 (setq r1 (read-char-exclusive)))
23500 (setq r2 (if (< r1 27) (+ r1 96) r1))
23501 (if (setq ass (assq r2 cmds))
23502 (call-interactively (cdr ass))
23503 (error "No command associated with key %c" r1))))
23505 (defconst org-html-entities
23506 '(("nbsp")
23507 ("iexcl")
23508 ("cent")
23509 ("pound")
23510 ("curren")
23511 ("yen")
23512 ("brvbar")
23513 ("vert" . "&#124;")
23514 ("sect")
23515 ("uml")
23516 ("copy")
23517 ("ordf")
23518 ("laquo")
23519 ("not")
23520 ("shy")
23521 ("reg")
23522 ("macr")
23523 ("deg")
23524 ("plusmn")
23525 ("sup2")
23526 ("sup3")
23527 ("acute")
23528 ("micro")
23529 ("para")
23530 ("middot")
23531 ("odot"."o")
23532 ("star"."*")
23533 ("cedil")
23534 ("sup1")
23535 ("ordm")
23536 ("raquo")
23537 ("frac14")
23538 ("frac12")
23539 ("frac34")
23540 ("iquest")
23541 ("Agrave")
23542 ("Aacute")
23543 ("Acirc")
23544 ("Atilde")
23545 ("Auml")
23546 ("Aring") ("AA"."&Aring;")
23547 ("AElig")
23548 ("Ccedil")
23549 ("Egrave")
23550 ("Eacute")
23551 ("Ecirc")
23552 ("Euml")
23553 ("Igrave")
23554 ("Iacute")
23555 ("Icirc")
23556 ("Iuml")
23557 ("ETH")
23558 ("Ntilde")
23559 ("Ograve")
23560 ("Oacute")
23561 ("Ocirc")
23562 ("Otilde")
23563 ("Ouml")
23564 ("times")
23565 ("Oslash")
23566 ("Ugrave")
23567 ("Uacute")
23568 ("Ucirc")
23569 ("Uuml")
23570 ("Yacute")
23571 ("THORN")
23572 ("szlig")
23573 ("agrave")
23574 ("aacute")
23575 ("acirc")
23576 ("atilde")
23577 ("auml")
23578 ("aring")
23579 ("aelig")
23580 ("ccedil")
23581 ("egrave")
23582 ("eacute")
23583 ("ecirc")
23584 ("euml")
23585 ("igrave")
23586 ("iacute")
23587 ("icirc")
23588 ("iuml")
23589 ("eth")
23590 ("ntilde")
23591 ("ograve")
23592 ("oacute")
23593 ("ocirc")
23594 ("otilde")
23595 ("ouml")
23596 ("divide")
23597 ("oslash")
23598 ("ugrave")
23599 ("uacute")
23600 ("ucirc")
23601 ("uuml")
23602 ("yacute")
23603 ("thorn")
23604 ("yuml")
23605 ("fnof")
23606 ("Alpha")
23607 ("Beta")
23608 ("Gamma")
23609 ("Delta")
23610 ("Epsilon")
23611 ("Zeta")
23612 ("Eta")
23613 ("Theta")
23614 ("Iota")
23615 ("Kappa")
23616 ("Lambda")
23617 ("Mu")
23618 ("Nu")
23619 ("Xi")
23620 ("Omicron")
23621 ("Pi")
23622 ("Rho")
23623 ("Sigma")
23624 ("Tau")
23625 ("Upsilon")
23626 ("Phi")
23627 ("Chi")
23628 ("Psi")
23629 ("Omega")
23630 ("alpha")
23631 ("beta")
23632 ("gamma")
23633 ("delta")
23634 ("epsilon")
23635 ("varepsilon"."&epsilon;")
23636 ("zeta")
23637 ("eta")
23638 ("theta")
23639 ("iota")
23640 ("kappa")
23641 ("lambda")
23642 ("mu")
23643 ("nu")
23644 ("xi")
23645 ("omicron")
23646 ("pi")
23647 ("rho")
23648 ("sigmaf") ("varsigma"."&sigmaf;")
23649 ("sigma")
23650 ("tau")
23651 ("upsilon")
23652 ("phi")
23653 ("chi")
23654 ("psi")
23655 ("omega")
23656 ("thetasym") ("vartheta"."&thetasym;")
23657 ("upsih")
23658 ("piv")
23659 ("bull") ("bullet"."&bull;")
23660 ("hellip") ("dots"."&hellip;")
23661 ("prime")
23662 ("Prime")
23663 ("oline")
23664 ("frasl")
23665 ("weierp")
23666 ("image")
23667 ("real")
23668 ("trade")
23669 ("alefsym")
23670 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23671 ("uarr") ("uparrow"."&uarr;")
23672 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23673 ("darr")("downarrow"."&darr;")
23674 ("harr") ("leftrightarrow"."&harr;")
23675 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23676 ("lArr") ("Leftarrow"."&lArr;")
23677 ("uArr") ("Uparrow"."&uArr;")
23678 ("rArr") ("Rightarrow"."&rArr;")
23679 ("dArr") ("Downarrow"."&dArr;")
23680 ("hArr") ("Leftrightarrow"."&hArr;")
23681 ("forall")
23682 ("part") ("partial"."&part;")
23683 ("exist") ("exists"."&exist;")
23684 ("empty") ("emptyset"."&empty;")
23685 ("nabla")
23686 ("isin") ("in"."&isin;")
23687 ("notin")
23688 ("ni")
23689 ("prod")
23690 ("sum")
23691 ("minus")
23692 ("lowast") ("ast"."&lowast;")
23693 ("radic")
23694 ("prop") ("proptp"."&prop;")
23695 ("infin") ("infty"."&infin;")
23696 ("ang") ("angle"."&ang;")
23697 ("and") ("wedge"."&and;")
23698 ("or") ("vee"."&or;")
23699 ("cap")
23700 ("cup")
23701 ("int")
23702 ("there4")
23703 ("sim")
23704 ("cong") ("simeq"."&cong;")
23705 ("asymp")("approx"."&asymp;")
23706 ("ne") ("neq"."&ne;")
23707 ("equiv")
23708 ("le")
23709 ("ge")
23710 ("sub") ("subset"."&sub;")
23711 ("sup") ("supset"."&sup;")
23712 ("nsub")
23713 ("sube")
23714 ("supe")
23715 ("oplus")
23716 ("otimes")
23717 ("perp")
23718 ("sdot") ("cdot"."&sdot;")
23719 ("lceil")
23720 ("rceil")
23721 ("lfloor")
23722 ("rfloor")
23723 ("lang")
23724 ("rang")
23725 ("loz") ("Diamond"."&loz;")
23726 ("spades") ("spadesuit"."&spades;")
23727 ("clubs") ("clubsuit"."&clubs;")
23728 ("hearts") ("diamondsuit"."&hearts;")
23729 ("diams") ("diamondsuit"."&diams;")
23730 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23731 ("quot")
23732 ("amp")
23733 ("lt")
23734 ("gt")
23735 ("OElig")
23736 ("oelig")
23737 ("Scaron")
23738 ("scaron")
23739 ("Yuml")
23740 ("circ")
23741 ("tilde")
23742 ("ensp")
23743 ("emsp")
23744 ("thinsp")
23745 ("zwnj")
23746 ("zwj")
23747 ("lrm")
23748 ("rlm")
23749 ("ndash")
23750 ("mdash")
23751 ("lsquo")
23752 ("rsquo")
23753 ("sbquo")
23754 ("ldquo")
23755 ("rdquo")
23756 ("bdquo")
23757 ("dagger")
23758 ("Dagger")
23759 ("permil")
23760 ("lsaquo")
23761 ("rsaquo")
23762 ("euro")
23764 ("arccos"."arccos")
23765 ("arcsin"."arcsin")
23766 ("arctan"."arctan")
23767 ("arg"."arg")
23768 ("cos"."cos")
23769 ("cosh"."cosh")
23770 ("cot"."cot")
23771 ("coth"."coth")
23772 ("csc"."csc")
23773 ("deg"."deg")
23774 ("det"."det")
23775 ("dim"."dim")
23776 ("exp"."exp")
23777 ("gcd"."gcd")
23778 ("hom"."hom")
23779 ("inf"."inf")
23780 ("ker"."ker")
23781 ("lg"."lg")
23782 ("lim"."lim")
23783 ("liminf"."liminf")
23784 ("limsup"."limsup")
23785 ("ln"."ln")
23786 ("log"."log")
23787 ("max"."max")
23788 ("min"."min")
23789 ("Pr"."Pr")
23790 ("sec"."sec")
23791 ("sin"."sin")
23792 ("sinh"."sinh")
23793 ("sup"."sup")
23794 ("tan"."tan")
23795 ("tanh"."tanh")
23797 "Entities for TeX->HTML translation.
23798 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23799 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23800 In that case, \"\\ent\" will be translated to \"&other;\".
23801 The list contains HTML entities for Latin-1, Greek and other symbols.
23802 It is supplemented by a number of commonly used TeX macros with appropriate
23803 translations. There is currently no way for users to extend this.")
23805 ;;; General functions for all backends
23807 (defun org-cleaned-string-for-export (string &rest parameters)
23808 "Cleanup a buffer STRING so that links can be created safely."
23809 (interactive)
23810 (let* ((re-radio (and org-target-link-regexp
23811 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23812 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23813 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23814 (re-archive (concat ":" org-archive-tag ":"))
23815 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23816 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23817 (htmlp (plist-get parameters :for-html))
23818 (asciip (plist-get parameters :for-ascii))
23819 (latexp (plist-get parameters :for-LaTeX))
23820 (commentsp (plist-get parameters :comments))
23821 (archived-trees (plist-get parameters :archived-trees))
23822 (inhibit-read-only t)
23823 (drawers org-drawers)
23824 (exp-drawers (plist-get parameters :drawers))
23825 (outline-regexp "\\*+ ")
23826 a b xx
23827 rtn p)
23828 (with-current-buffer (get-buffer-create " org-mode-tmp")
23829 (erase-buffer)
23830 (insert string)
23831 ;; Remove license-to-kill stuff
23832 (while (setq p (text-property-any (point-min) (point-max)
23833 :org-license-to-kill t))
23834 (delete-region p (next-single-property-change p :org-license-to-kill)))
23836 (let ((org-inhibit-startup t)) (org-mode))
23837 (untabify (point-min) (point-max))
23839 ;; Get the correct stuff before the first headline
23840 (when (plist-get parameters :skip-before-1st-heading)
23841 (goto-char (point-min))
23842 (when (re-search-forward "^\\*+[ \t]" nil t)
23843 (delete-region (point-min) (match-beginning 0))
23844 (goto-char (point-min))
23845 (insert "\n")))
23846 (when (plist-get parameters :add-text)
23847 (goto-char (point-min))
23848 (insert (plist-get parameters :add-text) "\n"))
23850 ;; Get rid of archived trees
23851 (when (not (eq archived-trees t))
23852 (goto-char (point-min))
23853 (while (re-search-forward re-archive nil t)
23854 (if (not (org-on-heading-p t))
23855 (org-end-of-subtree t)
23856 (beginning-of-line 1)
23857 (setq a (if archived-trees
23858 (1+ (point-at-eol)) (point))
23859 b (org-end-of-subtree t))
23860 (if (> b a) (delete-region a b)))))
23862 ;; Get rid of drawers
23863 (unless (eq t exp-drawers)
23864 (goto-char (point-min))
23865 (let ((re (concat "^[ \t]*:\\("
23866 (mapconcat
23867 'identity
23868 (org-delete-all exp-drawers
23869 (copy-sequence drawers))
23870 "\\|")
23871 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23872 (while (re-search-forward re nil t)
23873 (replace-match ""))))
23875 ;; Find targets in comments and move them out of comments,
23876 ;; but mark them as targets that should be invisible
23877 (goto-char (point-min))
23878 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
23879 (replace-match "\\1(INVISIBLE)"))
23881 ;; Protect backend specific stuff, throw away the others.
23882 (let ((formatters
23883 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
23884 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
23885 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
23886 fmt)
23887 (goto-char (point-min))
23888 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
23889 (goto-char (match-end 0))
23890 (while (not (looking-at "#\\+END_EXAMPLE"))
23891 (insert ": ")
23892 (beginning-of-line 2)))
23893 (goto-char (point-min))
23894 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
23895 (add-text-properties (match-beginning 0) (match-end 0)
23896 '(org-protected t)))
23897 (while formatters
23898 (setq fmt (pop formatters))
23899 (when (car fmt)
23900 (goto-char (point-min))
23901 (while (re-search-forward (concat "^#\\+" (cadr fmt)
23902 ":[ \t]*\\(.*\\)") nil t)
23903 (replace-match "\\1" t)
23904 (add-text-properties
23905 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
23906 '(org-protected t))))
23907 (goto-char (point-min))
23908 (while (re-search-forward
23909 (concat "^#\\+"
23910 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
23911 (cadddr fmt) "\\>.*\n?") nil t)
23912 (if (car fmt)
23913 (add-text-properties (match-beginning 1) (1+ (match-end 1))
23914 '(org-protected t))
23915 (delete-region (match-beginning 0) (match-end 0))))))
23917 ;; Protect quoted subtrees
23918 (goto-char (point-min))
23919 (while (re-search-forward re-quote nil t)
23920 (goto-char (match-beginning 0))
23921 (end-of-line 1)
23922 (add-text-properties (point) (org-end-of-subtree t)
23923 '(org-protected t)))
23925 ;; Protect verbatim elements
23926 (goto-char (point-min))
23927 (while (re-search-forward org-verbatim-re nil t)
23928 (add-text-properties (match-beginning 4) (match-end 4)
23929 '(org-protected t))
23930 (goto-char (1+ (match-end 4))))
23932 ;; Remove subtrees that are commented
23933 (goto-char (point-min))
23934 (while (re-search-forward re-commented nil t)
23935 (goto-char (match-beginning 0))
23936 (delete-region (point) (org-end-of-subtree t)))
23938 ;; Remove special table lines
23939 (when org-export-table-remove-special-lines
23940 (goto-char (point-min))
23941 (while (re-search-forward "^[ \t]*|" nil t)
23942 (beginning-of-line 1)
23943 (if (or (looking-at "[ \t]*| *[!_^] *|")
23944 (and (looking-at ".*?| *<[0-9]+> *|")
23945 (not (looking-at ".*?| *[^ <|]"))))
23946 (delete-region (max (point-min) (1- (point-at-bol)))
23947 (point-at-eol))
23948 (end-of-line 1))))
23950 ;; Specific LaTeX stuff
23951 (when latexp
23952 (require 'org-export-latex nil)
23953 (org-export-latex-cleaned-string))
23955 (when asciip
23956 (org-export-ascii-clean-string))
23958 ;; Specific HTML stuff
23959 (when htmlp
23960 ;; Convert LaTeX fragments to images
23961 (when (plist-get parameters :LaTeX-fragments)
23962 (org-format-latex
23963 (concat "ltxpng/" (file-name-sans-extension
23964 (file-name-nondirectory
23965 org-current-export-file)))
23966 org-current-export-dir nil "Creating LaTeX image %s"))
23967 (message "Exporting..."))
23969 ;; Remove or replace comments
23970 (goto-char (point-min))
23971 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
23972 (if commentsp
23973 (progn (add-text-properties
23974 (match-beginning 0) (match-end 0) '(org-protected t))
23975 (replace-match (format commentsp (match-string 1)) t t))
23976 (replace-match "")))
23978 ;; Find matches for radio targets and turn them into internal links
23979 (goto-char (point-min))
23980 (when re-radio
23981 (while (re-search-forward re-radio nil t)
23982 (org-if-unprotected
23983 (replace-match "\\1[[\\2]]"))))
23985 ;; Find all links that contain a newline and put them into a single line
23986 (goto-char (point-min))
23987 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
23988 (org-if-unprotected
23989 (replace-match "\\1 \\3")
23990 (goto-char (match-beginning 0))))
23993 ;; Normalize links: Convert angle and plain links into bracket links
23994 ;; Expand link abbreviations
23995 (goto-char (point-min))
23996 (while (re-search-forward re-plain-link nil t)
23997 (goto-char (1- (match-end 0)))
23998 (org-if-unprotected
23999 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24000 ":" (match-string 3) "]]")))
24001 ;; added 'org-link face to links
24002 (put-text-property 0 (length s) 'face 'org-link s)
24003 (replace-match s t t))))
24004 (goto-char (point-min))
24005 (while (re-search-forward re-angle-link nil t)
24006 (goto-char (1- (match-end 0)))
24007 (org-if-unprotected
24008 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24009 ":" (match-string 3) "]]")))
24010 (put-text-property 0 (length s) 'face 'org-link s)
24011 (replace-match s t t))))
24012 (goto-char (point-min))
24013 (while (re-search-forward org-bracket-link-regexp nil t)
24014 (org-if-unprotected
24015 (let* ((s (concat "[[" (setq xx (save-match-data
24016 (org-link-expand-abbrev (match-string 1))))
24018 (if (match-end 3)
24019 (match-string 2)
24020 (concat "[" xx "]"))
24021 "]")))
24022 (put-text-property 0 (length s) 'face 'org-link s)
24023 (replace-match s t t))))
24025 ;; Find multiline emphasis and put them into single line
24026 (when (plist-get parameters :emph-multiline)
24027 (goto-char (point-min))
24028 (while (re-search-forward org-emph-re nil t)
24029 (if (not (= (char-after (match-beginning 3))
24030 (char-after (match-beginning 4))))
24031 (org-if-unprotected
24032 (subst-char-in-region (match-beginning 0) (match-end 0)
24033 ?\n ?\ t)
24034 (goto-char (1- (match-end 0))))
24035 (goto-char (1+ (match-beginning 0))))))
24037 (setq rtn (buffer-string)))
24038 (kill-buffer " org-mode-tmp")
24039 rtn))
24041 (defun org-export-grab-title-from-buffer ()
24042 "Get a title for the current document, from looking at the buffer."
24043 (let ((inhibit-read-only t))
24044 (save-excursion
24045 (goto-char (point-min))
24046 (let ((end (save-excursion (outline-next-heading) (point))))
24047 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24048 ;; Mark the line so that it will not be exported as normal text.
24049 (org-unmodified
24050 (add-text-properties (match-beginning 0) (match-end 0)
24051 (list :org-license-to-kill t)))
24052 ;; Return the title string
24053 (org-trim (match-string 0)))))))
24055 (defun org-export-get-title-from-subtree ()
24056 "Return subtree title and exclude it from export."
24057 (let (title (m (mark)))
24058 (save-excursion
24059 (goto-char (region-beginning))
24060 (when (and (org-at-heading-p)
24061 (>= (org-end-of-subtree t t) (region-end)))
24062 ;; This is a subtree, we take the title from the first heading
24063 (goto-char (region-beginning))
24064 (looking-at org-todo-line-regexp)
24065 (setq title (match-string 3))
24066 (org-unmodified
24067 (add-text-properties (point) (1+ (point-at-eol))
24068 (list :org-license-to-kill t)))))
24069 title))
24071 (defun org-solidify-link-text (s &optional alist)
24072 "Take link text and make a safe target out of it."
24073 (save-match-data
24074 (let* ((rtn
24075 (mapconcat
24076 'identity
24077 (org-split-string s "[ \t\r\n]+") "--"))
24078 (a (assoc rtn alist)))
24079 (or (cdr a) rtn))))
24081 (defun org-get-min-level (lines)
24082 "Get the minimum level in LINES."
24083 (let ((re "^\\(\\*+\\) ") l min)
24084 (catch 'exit
24085 (while (setq l (pop lines))
24086 (if (string-match re l)
24087 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24088 1)))
24090 ;; Variable holding the vector with section numbers
24091 (defvar org-section-numbers (make-vector org-level-max 0))
24093 (defun org-init-section-numbers ()
24094 "Initialize the vector for the section numbers."
24095 (let* ((level -1)
24096 (numbers (nreverse (org-split-string "" "\\.")))
24097 (depth (1- (length org-section-numbers)))
24098 (i depth) number-string)
24099 (while (>= i 0)
24100 (if (> i level)
24101 (aset org-section-numbers i 0)
24102 (setq number-string (or (car numbers) "0"))
24103 (if (string-match "\\`[A-Z]\\'" number-string)
24104 (aset org-section-numbers i
24105 (- (string-to-char number-string) ?A -1))
24106 (aset org-section-numbers i (string-to-number number-string)))
24107 (pop numbers))
24108 (setq i (1- i)))))
24110 (defun org-section-number (&optional level)
24111 "Return a string with the current section number.
24112 When LEVEL is non-nil, increase section numbers on that level."
24113 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24114 (when level
24115 (when (> level -1)
24116 (aset org-section-numbers
24117 level (1+ (aref org-section-numbers level))))
24118 (setq idx (1+ level))
24119 (while (<= idx depth)
24120 (if (not (= idx 1))
24121 (aset org-section-numbers idx 0))
24122 (setq idx (1+ idx))))
24123 (setq idx 0)
24124 (while (<= idx depth)
24125 (setq n (aref org-section-numbers idx))
24126 (setq string (concat string (if (not (string= string "")) "." "")
24127 (int-to-string n)))
24128 (setq idx (1+ idx)))
24129 (save-match-data
24130 (if (string-match "\\`\\([@0]\\.\\)+" string)
24131 (setq string (replace-match "" t nil string)))
24132 (if (string-match "\\(\\.0\\)+\\'" string)
24133 (setq string (replace-match "" t nil string))))
24134 string))
24136 ;;; ASCII export
24138 (defvar org-last-level nil) ; dynamically scoped variable
24139 (defvar org-min-level nil) ; dynamically scoped variable
24140 (defvar org-levels-open nil) ; dynamically scoped parameter
24141 (defvar org-ascii-current-indentation nil) ; For communication
24143 (defun org-export-as-ascii (arg)
24144 "Export the outline as a pretty ASCII file.
24145 If there is an active region, export only the region.
24146 The prefix ARG specifies how many levels of the outline should become
24147 underlined headlines. The default is 3."
24148 (interactive "P")
24149 (setq-default org-todo-line-regexp org-todo-line-regexp)
24150 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24151 (org-infile-export-plist)))
24152 (region-p (org-region-active-p))
24153 (subtree-p
24154 (when region-p
24155 (save-excursion
24156 (goto-char (region-beginning))
24157 (and (org-at-heading-p)
24158 (>= (org-end-of-subtree t t) (region-end))))))
24159 (custom-times org-display-custom-times)
24160 (org-ascii-current-indentation '(0 . 0))
24161 (level 0) line txt
24162 (umax nil)
24163 (umax-toc nil)
24164 (case-fold-search nil)
24165 (filename (concat (file-name-as-directory
24166 (org-export-directory :ascii opt-plist))
24167 (file-name-sans-extension
24168 (or (and subtree-p
24169 (org-entry-get (region-beginning)
24170 "EXPORT_FILE_NAME" t))
24171 (file-name-nondirectory buffer-file-name)))
24172 ".txt"))
24173 (filename (if (equal (file-truename filename)
24174 (file-truename buffer-file-name))
24175 (concat filename ".txt")
24176 filename))
24177 (buffer (find-file-noselect filename))
24178 (org-levels-open (make-vector org-level-max nil))
24179 (odd org-odd-levels-only)
24180 (date (plist-get opt-plist :date))
24181 (author (plist-get opt-plist :author))
24182 (title (or (and subtree-p (org-export-get-title-from-subtree))
24183 (plist-get opt-plist :title)
24184 (and (not
24185 (plist-get opt-plist :skip-before-1st-heading))
24186 (org-export-grab-title-from-buffer))
24187 (file-name-sans-extension
24188 (file-name-nondirectory buffer-file-name))))
24189 (email (plist-get opt-plist :email))
24190 (language (plist-get opt-plist :language))
24191 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24192 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24193 (todo nil)
24194 (lang-words nil)
24195 (region
24196 (buffer-substring
24197 (if (org-region-active-p) (region-beginning) (point-min))
24198 (if (org-region-active-p) (region-end) (point-max))))
24199 (lines (org-split-string
24200 (org-cleaned-string-for-export
24201 region
24202 :for-ascii t
24203 :skip-before-1st-heading
24204 (plist-get opt-plist :skip-before-1st-heading)
24205 :drawers (plist-get opt-plist :drawers)
24206 :verbatim-multiline t
24207 :archived-trees
24208 (plist-get opt-plist :archived-trees)
24209 :add-text (plist-get opt-plist :text))
24210 "\n"))
24211 thetoc have-headings first-heading-pos
24212 table-open table-buffer)
24214 (let ((inhibit-read-only t))
24215 (org-unmodified
24216 (remove-text-properties (point-min) (point-max)
24217 '(:org-license-to-kill t))))
24219 (setq org-min-level (org-get-min-level lines))
24220 (setq org-last-level org-min-level)
24221 (org-init-section-numbers)
24223 (find-file-noselect filename)
24225 (setq lang-words (or (assoc language org-export-language-setup)
24226 (assoc "en" org-export-language-setup)))
24227 (switch-to-buffer-other-window buffer)
24228 (erase-buffer)
24229 (fundamental-mode)
24230 ;; create local variables for all options, to make sure all called
24231 ;; functions get the correct information
24232 (mapc (lambda (x)
24233 (set (make-local-variable (cdr x))
24234 (plist-get opt-plist (car x))))
24235 org-export-plist-vars)
24236 (org-set-local 'org-odd-levels-only odd)
24237 (setq umax (if arg (prefix-numeric-value arg)
24238 org-export-headline-levels))
24239 (setq umax-toc (if (integerp org-export-with-toc)
24240 (min org-export-with-toc umax)
24241 umax))
24243 ;; File header
24244 (if title (org-insert-centered title ?=))
24245 (insert "\n")
24246 (if (and (or author email)
24247 org-export-author-info)
24248 (insert (concat (nth 1 lang-words) ": " (or author "")
24249 (if email (concat " <" email ">") "")
24250 "\n")))
24252 (cond
24253 ((and date (string-match "%" date))
24254 (setq date (format-time-string date (current-time))))
24255 (date)
24256 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24258 (if (and date org-export-time-stamp-file)
24259 (insert (concat (nth 2 lang-words) ": " date"\n")))
24261 (insert "\n\n")
24263 (if org-export-with-toc
24264 (progn
24265 (push (concat (nth 3 lang-words) "\n") thetoc)
24266 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24267 (mapc '(lambda (line)
24268 (if (string-match org-todo-line-regexp
24269 line)
24270 ;; This is a headline
24271 (progn
24272 (setq have-headings t)
24273 (setq level (- (match-end 1) (match-beginning 1))
24274 level (org-tr-level level)
24275 txt (match-string 3 line)
24276 todo
24277 (or (and org-export-mark-todo-in-toc
24278 (match-beginning 2)
24279 (not (member (match-string 2 line)
24280 org-done-keywords)))
24281 ; TODO, not DONE
24282 (and org-export-mark-todo-in-toc
24283 (= level umax-toc)
24284 (org-search-todo-below
24285 line lines level))))
24286 (setq txt (org-html-expand-for-ascii txt))
24288 (while (string-match org-bracket-link-regexp txt)
24289 (setq txt
24290 (replace-match
24291 (match-string (if (match-end 2) 3 1) txt)
24292 t t txt)))
24294 (if (and (memq org-export-with-tags '(not-in-toc nil))
24295 (string-match
24296 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24297 txt))
24298 (setq txt (replace-match "" t t txt)))
24299 (if (string-match quote-re0 txt)
24300 (setq txt (replace-match "" t t txt)))
24302 (if org-export-with-section-numbers
24303 (setq txt (concat (org-section-number level)
24304 " " txt)))
24305 (if (<= level umax-toc)
24306 (progn
24307 (push
24308 (concat
24309 (make-string
24310 (* (max 0 (- level org-min-level)) 4) ?\ )
24311 (format (if todo "%s (*)\n" "%s\n") txt))
24312 thetoc)
24313 (setq org-last-level level))
24314 ))))
24315 lines)
24316 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24318 (org-init-section-numbers)
24319 (while (setq line (pop lines))
24320 ;; Remove the quoted HTML tags.
24321 (setq line (org-html-expand-for-ascii line))
24322 ;; Remove targets
24323 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24324 (setq line (replace-match "" t t line)))
24325 ;; Replace internal links
24326 (while (string-match org-bracket-link-regexp line)
24327 (setq line (replace-match
24328 (if (match-end 3) "[\\3]" "[\\1]")
24329 t nil line)))
24330 (when custom-times
24331 (setq line (org-translate-time line)))
24332 (cond
24333 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24334 ;; a Headline
24335 (setq first-heading-pos (or first-heading-pos (point)))
24336 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24337 txt (match-string 2 line))
24338 (org-ascii-level-start level txt umax lines))
24340 ((and org-export-with-tables
24341 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24342 (if (not table-open)
24343 ;; New table starts
24344 (setq table-open t table-buffer nil))
24345 ;; Accumulate lines
24346 (setq table-buffer (cons line table-buffer))
24347 (when (or (not lines)
24348 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24349 (car lines))))
24350 (setq table-open nil
24351 table-buffer (nreverse table-buffer))
24352 (insert (mapconcat
24353 (lambda (x)
24354 (org-fix-indentation x org-ascii-current-indentation))
24355 (org-format-table-ascii table-buffer)
24356 "\n") "\n")))
24358 (setq line (org-fix-indentation line org-ascii-current-indentation))
24359 (if (and org-export-with-fixed-width
24360 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24361 (setq line (replace-match "\\1" nil nil line)))
24362 (insert line "\n"))))
24364 (normal-mode)
24366 ;; insert the table of contents
24367 (when thetoc
24368 (goto-char (point-min))
24369 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24370 (progn
24371 (goto-char (match-beginning 0))
24372 (replace-match ""))
24373 (goto-char first-heading-pos))
24374 (mapc 'insert thetoc)
24375 (or (looking-at "[ \t]*\n[ \t]*\n")
24376 (insert "\n\n")))
24378 ;; Convert whitespace place holders
24379 (goto-char (point-min))
24380 (let (beg end)
24381 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24382 (setq end (next-single-property-change beg 'org-whitespace))
24383 (goto-char beg)
24384 (delete-region beg end)
24385 (insert (make-string (- end beg) ?\ ))))
24387 (save-buffer)
24388 ;; remove display and invisible chars
24389 (let (beg end)
24390 (goto-char (point-min))
24391 (while (setq beg (next-single-property-change (point) 'display))
24392 (setq end (next-single-property-change beg 'display))
24393 (delete-region beg end)
24394 (goto-char beg)
24395 (insert "=>"))
24396 (goto-char (point-min))
24397 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24398 (setq end (next-single-property-change beg 'org-cwidth))
24399 (delete-region beg end)
24400 (goto-char beg)))
24401 (goto-char (point-min))))
24403 (defun org-export-ascii-clean-string ()
24404 "Do extra work for ASCII export"
24405 (goto-char (point-min))
24406 (while (re-search-forward org-verbatim-re nil t)
24407 (goto-char (match-end 2))
24408 (backward-delete-char 1) (insert "'")
24409 (goto-char (match-beginning 2))
24410 (delete-char 1) (insert "`")
24411 (goto-char (match-end 2))))
24413 (defun org-search-todo-below (line lines level)
24414 "Search the subtree below LINE for any TODO entries."
24415 (let ((rest (cdr (memq line lines)))
24416 (re org-todo-line-regexp)
24417 line lv todo)
24418 (catch 'exit
24419 (while (setq line (pop rest))
24420 (if (string-match re line)
24421 (progn
24422 (setq lv (- (match-end 1) (match-beginning 1))
24423 todo (and (match-beginning 2)
24424 (not (member (match-string 2 line)
24425 org-done-keywords))))
24426 ; TODO, not DONE
24427 (if (<= lv level) (throw 'exit nil))
24428 (if todo (throw 'exit t))))))))
24430 (defun org-html-expand-for-ascii (line)
24431 "Handle quoted HTML for ASCII export."
24432 (if org-export-html-expand
24433 (while (string-match "@<[^<>\n]*>" line)
24434 ;; We just remove the tags for now.
24435 (setq line (replace-match "" nil nil line))))
24436 line)
24438 (defun org-insert-centered (s &optional underline)
24439 "Insert the string S centered and underline it with character UNDERLINE."
24440 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24441 (insert (make-string ind ?\ ) s "\n")
24442 (if underline
24443 (insert (make-string ind ?\ )
24444 (make-string (string-width s) underline)
24445 "\n"))))
24447 (defun org-ascii-level-start (level title umax &optional lines)
24448 "Insert a new level in ASCII export."
24449 (let (char (n (- level umax 1)) (ind 0))
24450 (if (> level umax)
24451 (progn
24452 (insert (make-string (* 2 n) ?\ )
24453 (char-to-string (nth (% n (length org-export-ascii-bullets))
24454 org-export-ascii-bullets))
24455 " " title "\n")
24456 ;; find the indentation of the next non-empty line
24457 (catch 'stop
24458 (while lines
24459 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24460 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24461 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24462 (pop lines)))
24463 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24464 (if (or (not (equal (char-before) ?\n))
24465 (not (equal (char-before (1- (point))) ?\n)))
24466 (insert "\n"))
24467 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24468 (unless org-export-with-tags
24469 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24470 (setq title (replace-match "" t t title))))
24471 (if org-export-with-section-numbers
24472 (setq title (concat (org-section-number level) " " title)))
24473 (insert title "\n" (make-string (string-width title) char) "\n")
24474 (setq org-ascii-current-indentation '(0 . 0)))))
24476 (defun org-export-visible (type arg)
24477 "Create a copy of the visible part of the current buffer, and export it.
24478 The copy is created in a temporary buffer and removed after use.
24479 TYPE is the final key (as a string) that also select the export command in
24480 the `C-c C-e' export dispatcher.
24481 As a special case, if the you type SPC at the prompt, the temporary
24482 org-mode file will not be removed but presented to you so that you can
24483 continue to use it. The prefix arg ARG is passed through to the exporting
24484 command."
24485 (interactive
24486 (list (progn
24487 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24488 (read-char-exclusive))
24489 current-prefix-arg))
24490 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24491 (error "Invalid export key"))
24492 (let* ((binding (cdr (assoc type
24493 '((?a . org-export-as-ascii)
24494 (?\C-a . org-export-as-ascii)
24495 (?b . org-export-as-html-and-open)
24496 (?\C-b . org-export-as-html-and-open)
24497 (?h . org-export-as-html)
24498 (?H . org-export-as-html-to-buffer)
24499 (?R . org-export-region-as-html)
24500 (?x . org-export-as-xoxo)))))
24501 (keepp (equal type ?\ ))
24502 (file buffer-file-name)
24503 (buffer (get-buffer-create "*Org Export Visible*"))
24504 s e)
24505 ;; Need to hack the drawers here.
24506 (save-excursion
24507 (goto-char (point-min))
24508 (while (re-search-forward org-drawer-regexp nil t)
24509 (goto-char (match-beginning 1))
24510 (or (org-invisible-p) (org-flag-drawer nil))))
24511 (with-current-buffer buffer (erase-buffer))
24512 (save-excursion
24513 (setq s (goto-char (point-min)))
24514 (while (not (= (point) (point-max)))
24515 (goto-char (org-find-invisible))
24516 (append-to-buffer buffer s (point))
24517 (setq s (goto-char (org-find-visible))))
24518 (org-cycle-hide-drawers 'all)
24519 (goto-char (point-min))
24520 (unless keepp
24521 ;; Copy all comment lines to the end, to make sure #+ settings are
24522 ;; still available for the second export step. Kind of a hack, but
24523 ;; does do the trick.
24524 (if (looking-at "#[^\r\n]*")
24525 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24526 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24527 (append-to-buffer buffer (1+ (match-beginning 0))
24528 (min (point-max) (1+ (match-end 0))))))
24529 (set-buffer buffer)
24530 (let ((buffer-file-name file)
24531 (org-inhibit-startup t))
24532 (org-mode)
24533 (show-all)
24534 (unless keepp (funcall binding arg))))
24535 (if (not keepp)
24536 (kill-buffer buffer)
24537 (switch-to-buffer-other-window buffer)
24538 (goto-char (point-min)))))
24540 (defun org-find-visible ()
24541 (let ((s (point)))
24542 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24543 (get-char-property s 'invisible)))
24545 (defun org-find-invisible ()
24546 (let ((s (point)))
24547 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24548 (not (get-char-property s 'invisible))))
24551 ;;; HTML export
24553 (defun org-get-current-options ()
24554 "Return a string with current options as keyword options.
24555 Does include HTML export options as well as TODO and CATEGORY stuff."
24556 (format
24557 "#+TITLE: %s
24558 #+AUTHOR: %s
24559 #+EMAIL: %s
24560 #+LANGUAGE: %s
24561 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24562 #+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
24563 #+CATEGORY: %s
24564 #+SEQ_TODO: %s
24565 #+TYP_TODO: %s
24566 #+PRIORITIES: %c %c %c
24567 #+DRAWERS: %s
24568 #+STARTUP: %s %s %s %s %s
24569 #+TAGS: %s
24570 #+ARCHIVE: %s
24571 #+LINK: %s
24573 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24574 org-export-headline-levels
24575 org-export-with-section-numbers
24576 org-export-with-toc
24577 org-export-preserve-breaks
24578 org-export-html-expand
24579 org-export-with-fixed-width
24580 org-export-with-tables
24581 org-export-with-sub-superscripts
24582 org-export-with-special-strings
24583 org-export-with-footnotes
24584 org-export-with-emphasize
24585 org-export-with-TeX-macros
24586 org-export-with-LaTeX-fragments
24587 org-export-skip-text-before-1st-heading
24588 org-export-with-drawers
24589 org-export-with-tags
24590 (file-name-nondirectory buffer-file-name)
24591 "TODO FEEDBACK VERIFY DONE"
24592 "Me Jason Marie DONE"
24593 org-highest-priority org-lowest-priority org-default-priority
24594 (mapconcat 'identity org-drawers " ")
24595 (cdr (assoc org-startup-folded
24596 '((nil . "showall") (t . "overview") (content . "content"))))
24597 (if org-odd-levels-only "odd" "oddeven")
24598 (if org-hide-leading-stars "hidestars" "showstars")
24599 (if org-startup-align-all-tables "align" "noalign")
24600 (cond ((eq t org-log-done) "logdone")
24601 ((not org-log-done) "nologging")
24602 ((listp org-log-done)
24603 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
24604 org-log-done " ")))
24605 (or (mapconcat (lambda (x)
24606 (cond
24607 ((equal '(:startgroup) x) "{")
24608 ((equal '(:endgroup) x) "}")
24609 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24610 (t (car x))))
24611 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24612 org-archive-location
24613 "org file:~/org/%s.org"
24616 (defun org-insert-export-options-template ()
24617 "Insert into the buffer a template with information for exporting."
24618 (interactive)
24619 (if (not (bolp)) (newline))
24620 (let ((s (org-get-current-options)))
24621 (and (string-match "#\\+CATEGORY" s)
24622 (setq s (substring s 0 (match-beginning 0))))
24623 (insert s)))
24625 (defun org-toggle-fixed-width-section (arg)
24626 "Toggle the fixed-width export.
24627 If there is no active region, the QUOTE keyword at the current headline is
24628 inserted or removed. When present, it causes the text between this headline
24629 and the next to be exported as fixed-width text, and unmodified.
24630 If there is an active region, this command adds or removes a colon as the
24631 first character of this line. If the first character of a line is a colon,
24632 this line is also exported in fixed-width font."
24633 (interactive "P")
24634 (let* ((cc 0)
24635 (regionp (org-region-active-p))
24636 (beg (if regionp (region-beginning) (point)))
24637 (end (if regionp (region-end)))
24638 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24639 (case-fold-search nil)
24640 (re "[ \t]*\\(:\\)")
24641 off)
24642 (if regionp
24643 (save-excursion
24644 (goto-char beg)
24645 (setq cc (current-column))
24646 (beginning-of-line 1)
24647 (setq off (looking-at re))
24648 (while (> nlines 0)
24649 (setq nlines (1- nlines))
24650 (beginning-of-line 1)
24651 (cond
24652 (arg
24653 (move-to-column cc t)
24654 (insert ":\n")
24655 (forward-line -1))
24656 ((and off (looking-at re))
24657 (replace-match "" t t nil 1))
24658 ((not off) (move-to-column cc t) (insert ":")))
24659 (forward-line 1)))
24660 (save-excursion
24661 (org-back-to-heading)
24662 (if (looking-at (concat outline-regexp
24663 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24664 (replace-match "" t t nil 1)
24665 (if (looking-at outline-regexp)
24666 (progn
24667 (goto-char (match-end 0))
24668 (insert org-quote-string " "))))))))
24670 (defun org-export-as-html-and-open (arg)
24671 "Export the outline as HTML and immediately open it with a browser.
24672 If there is an active region, export only the region.
24673 The prefix ARG specifies how many levels of the outline should become
24674 headlines. The default is 3. Lower levels will become bulleted lists."
24675 (interactive "P")
24676 (org-export-as-html arg 'hidden)
24677 (org-open-file buffer-file-name))
24679 (defun org-export-as-html-batch ()
24680 "Call `org-export-as-html', may be used in batch processing as
24681 emacs --batch
24682 --load=$HOME/lib/emacs/org.el
24683 --eval \"(setq org-export-headline-levels 2)\"
24684 --visit=MyFile --funcall org-export-as-html-batch"
24685 (org-export-as-html org-export-headline-levels 'hidden))
24687 (defun org-export-as-html-to-buffer (arg)
24688 "Call `org-exort-as-html` with output to a temporary buffer.
24689 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24690 (interactive "P")
24691 (org-export-as-html arg nil nil "*Org HTML Export*")
24692 (switch-to-buffer-other-window "*Org HTML Export*"))
24694 (defun org-replace-region-by-html (beg end)
24695 "Assume the current region has org-mode syntax, and convert it to HTML.
24696 This can be used in any buffer. For example, you could write an
24697 itemized list in org-mode syntax in an HTML buffer and then use this
24698 command to convert it."
24699 (interactive "r")
24700 (let (reg html buf pop-up-frames)
24701 (save-window-excursion
24702 (if (org-mode-p)
24703 (setq html (org-export-region-as-html
24704 beg end t 'string))
24705 (setq reg (buffer-substring beg end)
24706 buf (get-buffer-create "*Org tmp*"))
24707 (with-current-buffer buf
24708 (erase-buffer)
24709 (insert reg)
24710 (org-mode)
24711 (setq html (org-export-region-as-html
24712 (point-min) (point-max) t 'string)))
24713 (kill-buffer buf)))
24714 (delete-region beg end)
24715 (insert html)))
24717 (defun org-export-region-as-html (beg end &optional body-only buffer)
24718 "Convert region from BEG to END in org-mode buffer to HTML.
24719 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24720 contents, and only produce the region of converted text, useful for
24721 cut-and-paste operations.
24722 If BUFFER is a buffer or a string, use/create that buffer as a target
24723 of the converted HTML. If BUFFER is the symbol `string', return the
24724 produced HTML as a string and leave not buffer behind. For example,
24725 a Lisp program could call this function in the following way:
24727 (setq html (org-export-region-as-html beg end t 'string))
24729 When called interactively, the output buffer is selected, and shown
24730 in a window. A non-interactive call will only retunr the buffer."
24731 (interactive "r\nP")
24732 (when (interactive-p)
24733 (setq buffer "*Org HTML Export*"))
24734 (let ((transient-mark-mode t) (zmacs-regions t)
24735 rtn)
24736 (goto-char end)
24737 (set-mark (point)) ;; to activate the region
24738 (goto-char beg)
24739 (setq rtn (org-export-as-html
24740 nil nil nil
24741 buffer body-only))
24742 (if (fboundp 'deactivate-mark) (deactivate-mark))
24743 (if (and (interactive-p) (bufferp rtn))
24744 (switch-to-buffer-other-window rtn)
24745 rtn)))
24747 (defvar html-table-tag nil) ; dynamically scoped into this.
24748 (defun org-export-as-html (arg &optional hidden ext-plist
24749 to-buffer body-only)
24750 "Export the outline as a pretty HTML file.
24751 If there is an active region, export only the region. The prefix
24752 ARG specifies how many levels of the outline should become
24753 headlines. The default is 3. Lower levels will become bulleted
24754 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24755 EXT-PLIST is a property list with external parameters overriding
24756 org-mode's default settings, but still inferior to file-local
24757 settings. When TO-BUFFER is non-nil, create a buffer with that
24758 name and export to that buffer. If TO-BUFFER is the symbol `string',
24759 don't leave any buffer behind but just return the resulting HTML as
24760 a string. When BODY-ONLY is set, don't produce the file header and footer,
24761 simply return the content of <body>...</body>, without even
24762 the body tags themselves."
24763 (interactive "P")
24765 ;; Make sure we have a file name when we need it.
24766 (when (and (not (or to-buffer body-only))
24767 (not buffer-file-name))
24768 (if (buffer-base-buffer)
24769 (org-set-local 'buffer-file-name
24770 (with-current-buffer (buffer-base-buffer)
24771 buffer-file-name))
24772 (error "Need a file name to be able to export.")))
24774 (message "Exporting...")
24775 (setq-default org-todo-line-regexp org-todo-line-regexp)
24776 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24777 (setq-default org-done-keywords org-done-keywords)
24778 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24779 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24780 ext-plist
24781 (org-infile-export-plist)))
24783 (style (plist-get opt-plist :style))
24784 (link-validate (plist-get opt-plist :link-validation-function))
24785 valid thetoc have-headings first-heading-pos
24786 (odd org-odd-levels-only)
24787 (region-p (org-region-active-p))
24788 (subtree-p
24789 (when region-p
24790 (save-excursion
24791 (goto-char (region-beginning))
24792 (and (org-at-heading-p)
24793 (>= (org-end-of-subtree t t) (region-end))))))
24794 ;; The following two are dynamically scoped into other
24795 ;; routines below.
24796 (org-current-export-dir (org-export-directory :html opt-plist))
24797 (org-current-export-file buffer-file-name)
24798 (level 0) (line "") (origline "") txt todo
24799 (umax nil)
24800 (umax-toc nil)
24801 (filename (if to-buffer nil
24802 (expand-file-name
24803 (concat
24804 (file-name-sans-extension
24805 (or (and subtree-p
24806 (org-entry-get (region-beginning)
24807 "EXPORT_FILE_NAME" t))
24808 (file-name-nondirectory buffer-file-name)))
24809 "." org-export-html-extension)
24810 (file-name-as-directory
24811 (org-export-directory :html opt-plist)))))
24812 (current-dir (if buffer-file-name
24813 (file-name-directory buffer-file-name)
24814 default-directory))
24815 (buffer (if to-buffer
24816 (cond
24817 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24818 (t (get-buffer-create to-buffer)))
24819 (find-file-noselect filename)))
24820 (org-levels-open (make-vector org-level-max nil))
24821 (date (plist-get opt-plist :date))
24822 (author (plist-get opt-plist :author))
24823 (title (or (and subtree-p (org-export-get-title-from-subtree))
24824 (plist-get opt-plist :title)
24825 (and (not
24826 (plist-get opt-plist :skip-before-1st-heading))
24827 (org-export-grab-title-from-buffer))
24828 (and buffer-file-name
24829 (file-name-sans-extension
24830 (file-name-nondirectory buffer-file-name)))
24831 "UNTITLED"))
24832 (html-table-tag (plist-get opt-plist :html-table-tag))
24833 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24834 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24835 (inquote nil)
24836 (infixed nil)
24837 (in-local-list nil)
24838 (local-list-num nil)
24839 (local-list-indent nil)
24840 (llt org-plain-list-ordered-item-terminator)
24841 (email (plist-get opt-plist :email))
24842 (language (plist-get opt-plist :language))
24843 (lang-words nil)
24844 (target-alist nil) tg
24845 (head-count 0) cnt
24846 (start 0)
24847 (coding-system (and (boundp 'buffer-file-coding-system)
24848 buffer-file-coding-system))
24849 (coding-system-for-write (or org-export-html-coding-system
24850 coding-system))
24851 (save-buffer-coding-system (or org-export-html-coding-system
24852 coding-system))
24853 (charset (and coding-system-for-write
24854 (fboundp 'coding-system-get)
24855 (coding-system-get coding-system-for-write
24856 'mime-charset)))
24857 (region
24858 (buffer-substring
24859 (if region-p (region-beginning) (point-min))
24860 (if region-p (region-end) (point-max))))
24861 (lines
24862 (org-split-string
24863 (org-cleaned-string-for-export
24864 region
24865 :emph-multiline t
24866 :for-html t
24867 :skip-before-1st-heading
24868 (plist-get opt-plist :skip-before-1st-heading)
24869 :drawers (plist-get opt-plist :drawers)
24870 :archived-trees
24871 (plist-get opt-plist :archived-trees)
24872 :add-text
24873 (plist-get opt-plist :text)
24874 :LaTeX-fragments
24875 (plist-get opt-plist :LaTeX-fragments))
24876 "[\r\n]"))
24877 table-open type
24878 table-buffer table-orig-buffer
24879 ind start-is-num starter didclose
24880 rpl path desc descp desc1 desc2 link
24883 (let ((inhibit-read-only t))
24884 (org-unmodified
24885 (remove-text-properties (point-min) (point-max)
24886 '(:org-license-to-kill t))))
24888 (message "Exporting...")
24890 (setq org-min-level (org-get-min-level lines))
24891 (setq org-last-level org-min-level)
24892 (org-init-section-numbers)
24894 (cond
24895 ((and date (string-match "%" date))
24896 (setq date (format-time-string date (current-time))))
24897 (date)
24898 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24900 ;; Get the language-dependent settings
24901 (setq lang-words (or (assoc language org-export-language-setup)
24902 (assoc "en" org-export-language-setup)))
24904 ;; Switch to the output buffer
24905 (set-buffer buffer)
24906 (erase-buffer)
24907 (fundamental-mode)
24909 (and (fboundp 'set-buffer-file-coding-system)
24910 (set-buffer-file-coding-system coding-system-for-write))
24912 (let ((case-fold-search nil)
24913 (org-odd-levels-only odd))
24914 ;; create local variables for all options, to make sure all called
24915 ;; functions get the correct information
24916 (mapc (lambda (x)
24917 (set (make-local-variable (cdr x))
24918 (plist-get opt-plist (car x))))
24919 org-export-plist-vars)
24920 (setq umax (if arg (prefix-numeric-value arg)
24921 org-export-headline-levels))
24922 (setq umax-toc (if (integerp org-export-with-toc)
24923 (min org-export-with-toc umax)
24924 umax))
24925 (unless body-only
24926 ;; File header
24927 (insert (format
24928 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
24929 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
24930 <html xmlns=\"http://www.w3.org/1999/xhtml\"
24931 lang=\"%s\" xml:lang=\"%s\">
24932 <head>
24933 <title>%s</title>
24934 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
24935 <meta name=\"generator\" content=\"Org-mode\"/>
24936 <meta name=\"generated\" content=\"%s\"/>
24937 <meta name=\"author\" content=\"%s\"/>
24939 </head><body>
24941 language language (org-html-expand title)
24942 (or charset "iso-8859-1") date author style))
24944 (insert (or (plist-get opt-plist :preamble) ""))
24946 (when (plist-get opt-plist :auto-preamble)
24947 (if title (insert (format org-export-html-title-format
24948 (org-html-expand title))))))
24950 (if (and org-export-with-toc (not body-only))
24951 (progn
24952 (push (format "<h%d>%s</h%d>\n"
24953 org-export-html-toplevel-hlevel
24954 (nth 3 lang-words)
24955 org-export-html-toplevel-hlevel)
24956 thetoc)
24957 (push "<ul>\n<li>" thetoc)
24958 (setq lines
24959 (mapcar '(lambda (line)
24960 (if (string-match org-todo-line-regexp line)
24961 ;; This is a headline
24962 (progn
24963 (setq have-headings t)
24964 (setq level (- (match-end 1) (match-beginning 1))
24965 level (org-tr-level level)
24966 txt (save-match-data
24967 (org-html-expand
24968 (org-export-cleanup-toc-line
24969 (match-string 3 line))))
24970 todo
24971 (or (and org-export-mark-todo-in-toc
24972 (match-beginning 2)
24973 (not (member (match-string 2 line)
24974 org-done-keywords)))
24975 ; TODO, not DONE
24976 (and org-export-mark-todo-in-toc
24977 (= level umax-toc)
24978 (org-search-todo-below
24979 line lines level))))
24980 (if (string-match
24981 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
24982 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
24983 (if (string-match quote-re0 txt)
24984 (setq txt (replace-match "" t t txt)))
24985 (if org-export-with-section-numbers
24986 (setq txt (concat (org-section-number level)
24987 " " txt)))
24988 (if (<= level (max umax umax-toc))
24989 (setq head-count (+ head-count 1)))
24990 (if (<= level umax-toc)
24991 (progn
24992 (if (> level org-last-level)
24993 (progn
24994 (setq cnt (- level org-last-level))
24995 (while (>= (setq cnt (1- cnt)) 0)
24996 (push "\n<ul>\n<li>" thetoc))
24997 (push "\n" thetoc)))
24998 (if (< level org-last-level)
24999 (progn
25000 (setq cnt (- org-last-level level))
25001 (while (>= (setq cnt (1- cnt)) 0)
25002 (push "</li>\n</ul>" thetoc))
25003 (push "\n" thetoc)))
25004 ;; Check for targets
25005 (while (string-match org-target-regexp line)
25006 (setq tg (match-string 1 line)
25007 line (replace-match
25008 (concat "@<span class=\"target\">" tg "@</span> ")
25009 t t line))
25010 (push (cons (org-solidify-link-text tg)
25011 (format "sec-%d" head-count))
25012 target-alist))
25013 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25014 (setq txt (replace-match "" t t txt)))
25015 (push
25016 (format
25017 (if todo
25018 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25019 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25020 head-count txt) thetoc)
25022 (setq org-last-level level))
25024 line)
25025 lines))
25026 (while (> org-last-level (1- org-min-level))
25027 (setq org-last-level (1- org-last-level))
25028 (push "</li>\n</ul>\n" thetoc))
25029 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25031 (setq head-count 0)
25032 (org-init-section-numbers)
25034 (while (setq line (pop lines) origline line)
25035 (catch 'nextline
25037 ;; end of quote section?
25038 (when (and inquote (string-match "^\\*+ " line))
25039 (insert "</pre>\n")
25040 (setq inquote nil))
25041 ;; inside a quote section?
25042 (when inquote
25043 (insert (org-html-protect line) "\n")
25044 (throw 'nextline nil))
25046 ;; verbatim lines
25047 (when (and org-export-with-fixed-width
25048 (string-match "^[ \t]*:\\(.*\\)" line))
25049 (when (not infixed)
25050 (setq infixed t)
25051 (insert "<pre>\n"))
25052 (insert (org-html-protect (match-string 1 line)) "\n")
25053 (when (and lines
25054 (not (string-match "^[ \t]*\\(:.*\\)"
25055 (car lines))))
25056 (setq infixed nil)
25057 (insert "</pre>\n"))
25058 (throw 'nextline nil))
25060 ;; Protected HTML
25061 (when (get-text-property 0 'org-protected line)
25062 (let (par)
25063 (when (re-search-backward
25064 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25065 (setq par (match-string 1))
25066 (replace-match "\\2\n"))
25067 (insert line "\n")
25068 (while (and lines
25069 (or (= (length (car lines)) 0)
25070 (get-text-property 0 'org-protected (car lines))))
25071 (insert (pop lines) "\n"))
25072 (and par (insert "<p>\n")))
25073 (throw 'nextline nil))
25075 ;; Horizontal line
25076 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25077 (insert "\n<hr/>\n")
25078 (throw 'nextline nil))
25080 ;; make targets to anchors
25081 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25082 (cond
25083 ((match-end 2)
25084 (setq line (replace-match
25085 (concat "@<a name=\""
25086 (org-solidify-link-text (match-string 1 line))
25087 "\">\\nbsp@</a>")
25088 t t line)))
25089 ((and org-export-with-toc (equal (string-to-char line) ?*))
25090 (setq line (replace-match
25091 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25092 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25093 t t line)))
25095 (setq line (replace-match
25096 (concat "@<a name=\""
25097 (org-solidify-link-text (match-string 1 line))
25098 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25099 t t line)))))
25101 (setq line (org-html-handle-time-stamps line))
25103 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25104 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25105 ;; Also handle sub_superscripts and checkboxes
25106 (or (string-match org-table-hline-regexp line)
25107 (setq line (org-html-expand line)))
25109 ;; Format the links
25110 (setq start 0)
25111 (while (string-match org-bracket-link-analytic-regexp line start)
25112 (setq start (match-beginning 0))
25113 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25114 (setq path (match-string 3 line))
25115 (setq desc1 (if (match-end 5) (match-string 5 line))
25116 desc2 (if (match-end 2) (concat type ":" path) path)
25117 descp (and desc1 (not (equal desc1 desc2)))
25118 desc (or desc1 desc2))
25119 ;; Make an image out of the description if that is so wanted
25120 (when (and descp (org-file-image-p desc))
25121 (save-match-data
25122 (if (string-match "^file:" desc)
25123 (setq desc (substring desc (match-end 0)))))
25124 (setq desc (concat "<img src=\"" desc "\"/>")))
25125 ;; FIXME: do we need to unescape here somewhere?
25126 (cond
25127 ((equal type "internal")
25128 (setq rpl
25129 (concat
25130 "<a href=\"#"
25131 (org-solidify-link-text
25132 (save-match-data (org-link-unescape path)) target-alist)
25133 "\">" desc "</a>")))
25134 ((member type '("http" "https"))
25135 ;; standard URL, just check if we need to inline an image
25136 (if (and (or (eq t org-export-html-inline-images)
25137 (and org-export-html-inline-images (not descp)))
25138 (org-file-image-p path))
25139 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25140 (setq link (concat type ":" path))
25141 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25142 ((member type '("ftp" "mailto" "news"))
25143 ;; standard URL
25144 (setq link (concat type ":" path))
25145 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25146 ((string= type "file")
25147 ;; FILE link
25148 (let* ((filename path)
25149 (abs-p (file-name-absolute-p filename))
25150 thefile file-is-image-p search)
25151 (save-match-data
25152 (if (string-match "::\\(.*\\)" filename)
25153 (setq search (match-string 1 filename)
25154 filename (replace-match "" t nil filename)))
25155 (setq valid
25156 (if (functionp link-validate)
25157 (funcall link-validate filename current-dir)
25159 (setq file-is-image-p (org-file-image-p filename))
25160 (setq thefile (if abs-p (expand-file-name filename) filename))
25161 (when (and org-export-html-link-org-files-as-html
25162 (string-match "\\.org$" thefile))
25163 (setq thefile (concat (substring thefile 0
25164 (match-beginning 0))
25165 "." org-export-html-extension))
25166 (if (and search
25167 ;; make sure this is can be used as target search
25168 (not (string-match "^[0-9]*$" search))
25169 (not (string-match "^\\*" search))
25170 (not (string-match "^/.*/$" search)))
25171 (setq thefile (concat thefile "#"
25172 (org-solidify-link-text
25173 (org-link-unescape search)))))
25174 (when (string-match "^file:" desc)
25175 (setq desc (replace-match "" t t desc))
25176 (if (string-match "\\.org$" desc)
25177 (setq desc (replace-match "" t t desc))))))
25178 (setq rpl (if (and file-is-image-p
25179 (or (eq t org-export-html-inline-images)
25180 (and org-export-html-inline-images
25181 (not descp))))
25182 (concat "<img src=\"" thefile "\"/>")
25183 (concat "<a href=\"" thefile "\">" desc "</a>")))
25184 (if (not valid) (setq rpl desc))))
25185 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25186 (setq rpl (concat "<i>&lt;" type ":"
25187 (save-match-data (org-link-unescape path))
25188 "&gt;</i>"))))
25189 (setq line (replace-match rpl t t line)
25190 start (+ start (length rpl))))
25192 ;; TODO items
25193 (if (and (string-match org-todo-line-regexp line)
25194 (match-beginning 2))
25196 (setq line
25197 (concat (substring line 0 (match-beginning 2))
25198 "<span class=\""
25199 (if (member (match-string 2 line)
25200 org-done-keywords)
25201 "done" "todo")
25202 "\">" (match-string 2 line)
25203 "</span>" (substring line (match-end 2)))))
25205 ;; Does this contain a reference to a footnote?
25206 (when org-export-with-footnotes
25207 (setq start 0)
25208 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25209 (if (get-text-property (match-beginning 2) 'org-protected line)
25210 (setq start (match-end 2))
25211 (let ((n (match-string 2 line)))
25212 (setq line
25213 (replace-match
25214 (format
25215 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25216 (match-string 1 line) n n n)
25217 t t line))))))
25219 (cond
25220 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25221 ;; This is a headline
25222 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25223 txt (match-string 2 line))
25224 (if (string-match quote-re0 txt)
25225 (setq txt (replace-match "" t t txt)))
25226 (if (<= level (max umax umax-toc))
25227 (setq head-count (+ head-count 1)))
25228 (when in-local-list
25229 ;; Close any local lists before inserting a new header line
25230 (while local-list-num
25231 (org-close-li)
25232 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25233 (pop local-list-num))
25234 (setq local-list-indent nil
25235 in-local-list nil))
25236 (setq first-heading-pos (or first-heading-pos (point)))
25237 (org-html-level-start level txt umax
25238 (and org-export-with-toc (<= level umax))
25239 head-count)
25240 ;; QUOTES
25241 (when (string-match quote-re line)
25242 (insert "<pre>")
25243 (setq inquote t)))
25245 ((and org-export-with-tables
25246 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25247 (if (not table-open)
25248 ;; New table starts
25249 (setq table-open t table-buffer nil table-orig-buffer nil))
25250 ;; Accumulate lines
25251 (setq table-buffer (cons line table-buffer)
25252 table-orig-buffer (cons origline table-orig-buffer))
25253 (when (or (not lines)
25254 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25255 (car lines))))
25256 (setq table-open nil
25257 table-buffer (nreverse table-buffer)
25258 table-orig-buffer (nreverse table-orig-buffer))
25259 (org-close-par-maybe)
25260 (insert (org-format-table-html table-buffer table-orig-buffer))))
25262 ;; Normal lines
25263 (when (string-match
25264 (cond
25265 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25266 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25267 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25268 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25269 line)
25270 (setq ind (org-get-string-indentation line)
25271 start-is-num (match-beginning 4)
25272 starter (if (match-beginning 2)
25273 (substring (match-string 2 line) 0 -1))
25274 line (substring line (match-beginning 5)))
25275 (unless (string-match "[^ \t]" line)
25276 ;; empty line. Pretend indentation is large.
25277 (setq ind (if org-empty-line-terminates-plain-lists
25279 (1+ (or (car local-list-indent) 1)))))
25280 (setq didclose nil)
25281 (while (and in-local-list
25282 (or (and (= ind (car local-list-indent))
25283 (not starter))
25284 (< ind (car local-list-indent))))
25285 (setq didclose t)
25286 (org-close-li)
25287 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25288 (pop local-list-num) (pop local-list-indent)
25289 (setq in-local-list local-list-indent))
25290 (cond
25291 ((and starter
25292 (or (not in-local-list)
25293 (> ind (car local-list-indent))))
25294 ;; Start new (level of) list
25295 (org-close-par-maybe)
25296 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25297 (push start-is-num local-list-num)
25298 (push ind local-list-indent)
25299 (setq in-local-list t))
25300 (starter
25301 ;; continue current list
25302 (org-close-li)
25303 (insert "<li>\n"))
25304 (didclose
25305 ;; we did close a list, normal text follows: need <p>
25306 (org-open-par)))
25307 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25308 (setq line
25309 (replace-match
25310 (if (equal (match-string 1 line) "X")
25311 "<b>[X]</b>"
25312 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25313 t t line))))
25315 ;; Empty lines start a new paragraph. If hand-formatted lists
25316 ;; are not fully interpreted, lines starting with "-", "+", "*"
25317 ;; also start a new paragraph.
25318 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25320 ;; Is this the start of a footnote?
25321 (when org-export-with-footnotes
25322 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25323 (org-close-par-maybe)
25324 (let ((n (match-string 1 line)))
25325 (setq line (replace-match
25326 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25328 ;; Check if the line break needs to be conserved
25329 (cond
25330 ((string-match "\\\\\\\\[ \t]*$" line)
25331 (setq line (replace-match "<br/>" t t line)))
25332 (org-export-preserve-breaks
25333 (setq line (concat line "<br/>"))))
25335 (insert line "\n")))))
25337 ;; Properly close all local lists and other lists
25338 (when inquote (insert "</pre>\n"))
25339 (when in-local-list
25340 ;; Close any local lists before inserting a new header line
25341 (while local-list-num
25342 (org-close-li)
25343 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25344 (pop local-list-num))
25345 (setq local-list-indent nil
25346 in-local-list nil))
25347 (org-html-level-start 1 nil umax
25348 (and org-export-with-toc (<= level umax))
25349 head-count)
25351 (unless body-only
25352 (when (plist-get opt-plist :auto-postamble)
25353 (insert "<div id=\"postamble\">")
25354 (when (and org-export-author-info author)
25355 (insert "<p class=\"author\"> "
25356 (nth 1 lang-words) ": " author "\n")
25357 (when email
25358 (if (listp (split-string email ",+ *"))
25359 (mapc (lambda(e)
25360 (insert "<a href=\"mailto:" e "\">&lt;"
25361 e "&gt;</a>\n"))
25362 (split-string email ",+ *"))
25363 (insert "<a href=\"mailto:" email "\">&lt;"
25364 email "&gt;</a>\n")))
25365 (insert "</p>\n"))
25366 (when (and date org-export-time-stamp-file)
25367 (insert "<p class=\"date\"> "
25368 (nth 2 lang-words) ": "
25369 date "</p>\n"))
25370 (insert "</div>"))
25372 (if org-export-html-with-timestamp
25373 (insert org-export-html-html-helper-timestamp))
25374 (insert (or (plist-get opt-plist :postamble) ""))
25375 (insert "</body>\n</html>\n"))
25377 (normal-mode)
25378 (if (eq major-mode default-major-mode) (html-mode))
25380 ;; insert the table of contents
25381 (goto-char (point-min))
25382 (when thetoc
25383 (if (or (re-search-forward
25384 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25385 (re-search-forward
25386 "\\[TABLE-OF-CONTENTS\\]" nil t))
25387 (progn
25388 (goto-char (match-beginning 0))
25389 (replace-match ""))
25390 (goto-char first-heading-pos)
25391 (when (looking-at "\\s-*</p>")
25392 (goto-char (match-end 0))
25393 (insert "\n")))
25394 (insert "<div id=\"table-of-contents\">\n")
25395 (mapc 'insert thetoc)
25396 (insert "</div>\n"))
25397 ;; remove empty paragraphs and lists
25398 (goto-char (point-min))
25399 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25400 (replace-match ""))
25401 (goto-char (point-min))
25402 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25403 (replace-match ""))
25404 ;; Convert whitespace place holders
25405 (goto-char (point-min))
25406 (let (beg end n)
25407 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25408 (setq n (get-text-property beg 'org-whitespace)
25409 end (next-single-property-change beg 'org-whitespace))
25410 (goto-char beg)
25411 (delete-region beg end)
25412 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25413 (make-string n ?x)))))
25415 (or to-buffer (save-buffer))
25416 (goto-char (point-min))
25417 (message "Exporting... done")
25418 (if (eq to-buffer 'string)
25419 (prog1 (buffer-substring (point-min) (point-max))
25420 (kill-buffer (current-buffer)))
25421 (current-buffer)))))
25423 (defvar org-table-colgroup-info nil)
25424 (defun org-format-table-ascii (lines)
25425 "Format a table for ascii export."
25426 (if (stringp lines)
25427 (setq lines (org-split-string lines "\n")))
25428 (if (not (string-match "^[ \t]*|" (car lines)))
25429 ;; Table made by table.el - test for spanning
25430 lines
25432 ;; A normal org table
25433 ;; Get rid of hlines at beginning and end
25434 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25435 (setq lines (nreverse lines))
25436 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25437 (setq lines (nreverse lines))
25438 (when org-export-table-remove-special-lines
25439 ;; Check if the table has a marking column. If yes remove the
25440 ;; column and the special lines
25441 (setq lines (org-table-clean-before-export lines)))
25442 ;; Get rid of the vertical lines except for grouping
25443 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25444 rtn line vl1 start)
25445 (while (setq line (pop lines))
25446 (if (string-match org-table-hline-regexp line)
25447 (and (string-match "|\\(.*\\)|" line)
25448 (setq line (replace-match " \\1" t nil line)))
25449 (setq start 0 vl1 vl)
25450 (while (string-match "|" line start)
25451 (setq start (match-end 0))
25452 (or (pop vl1) (setq line (replace-match " " t t line)))))
25453 (push line rtn))
25454 (nreverse rtn))))
25456 (defun org-colgroup-info-to-vline-list (info)
25457 (let (vl new last)
25458 (while info
25459 (setq last new new (pop info))
25460 (if (or (memq last '(:end :startend))
25461 (memq new '(:start :startend)))
25462 (push t vl)
25463 (push nil vl)))
25464 (setq vl (nreverse vl))
25465 (and vl (setcar vl nil))
25466 vl))
25468 (defun org-format-table-html (lines olines)
25469 "Find out which HTML converter to use and return the HTML code."
25470 (if (stringp lines)
25471 (setq lines (org-split-string lines "\n")))
25472 (if (string-match "^[ \t]*|" (car lines))
25473 ;; A normal org table
25474 (org-format-org-table-html lines)
25475 ;; Table made by table.el - test for spanning
25476 (let* ((hlines (delq nil (mapcar
25477 (lambda (x)
25478 (if (string-match "^[ \t]*\\+-" x) x
25479 nil))
25480 lines)))
25481 (first (car hlines))
25482 (ll (and (string-match "\\S-+" first)
25483 (match-string 0 first)))
25484 (re (concat "^[ \t]*" (regexp-quote ll)))
25485 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25486 hlines))))
25487 (if (and (not spanning)
25488 (not org-export-prefer-native-exporter-for-tables))
25489 ;; We can use my own converter with HTML conversions
25490 (org-format-table-table-html lines)
25491 ;; Need to use the code generator in table.el, with the original text.
25492 (org-format-table-table-html-using-table-generate-source olines)))))
25494 (defun org-format-org-table-html (lines &optional splice)
25495 "Format a table into HTML."
25496 ;; Get rid of hlines at beginning and end
25497 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25498 (setq lines (nreverse lines))
25499 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25500 (setq lines (nreverse lines))
25501 (when org-export-table-remove-special-lines
25502 ;; Check if the table has a marking column. If yes remove the
25503 ;; column and the special lines
25504 (setq lines (org-table-clean-before-export lines)))
25506 (let ((head (and org-export-highlight-first-table-line
25507 (delq nil (mapcar
25508 (lambda (x) (string-match "^[ \t]*|-" x))
25509 (cdr lines)))))
25510 (nlines 0) fnum i
25511 tbopen line fields html gr colgropen)
25512 (if splice (setq head nil))
25513 (unless splice (push (if head "<thead>" "<tbody>") html))
25514 (setq tbopen t)
25515 (while (setq line (pop lines))
25516 (catch 'next-line
25517 (if (string-match "^[ \t]*|-" line)
25518 (progn
25519 (unless splice
25520 (push (if head "</thead>" "</tbody>") html)
25521 (if lines (push "<tbody>" html) (setq tbopen nil)))
25522 (setq head nil) ;; head ends here, first time around
25523 ;; ignore this line
25524 (throw 'next-line t)))
25525 ;; Break the line into fields
25526 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25527 (unless fnum (setq fnum (make-vector (length fields) 0)))
25528 (setq nlines (1+ nlines) i -1)
25529 (push (concat "<tr>"
25530 (mapconcat
25531 (lambda (x)
25532 (setq i (1+ i))
25533 (if (and (< i nlines)
25534 (string-match org-table-number-regexp x))
25535 (incf (aref fnum i)))
25536 (if head
25537 (concat (car org-export-table-header-tags) x
25538 (cdr org-export-table-header-tags))
25539 (concat (car org-export-table-data-tags) x
25540 (cdr org-export-table-data-tags))))
25541 fields "")
25542 "</tr>")
25543 html)))
25544 (unless splice (if tbopen (push "</tbody>" html)))
25545 (unless splice (push "</table>\n" html))
25546 (setq html (nreverse html))
25547 (unless splice
25548 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25549 (push (mapconcat
25550 (lambda (x)
25551 (setq gr (pop org-table-colgroup-info))
25552 (format "%s<col align=\"%s\"></col>%s"
25553 (if (memq gr '(:start :startend))
25554 (prog1
25555 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25556 (setq colgropen t))
25558 (if (> (/ (float x) nlines) org-table-number-fraction)
25559 "right" "left")
25560 (if (memq gr '(:end :startend))
25561 (progn (setq colgropen nil) "</colgroup>")
25562 "")))
25563 fnum "")
25564 html)
25565 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25566 (push html-table-tag html))
25567 (concat (mapconcat 'identity html "\n") "\n")))
25569 (defun org-table-clean-before-export (lines)
25570 "Check if the table has a marking column.
25571 If yes remove the column and the special lines."
25572 (setq org-table-colgroup-info nil)
25573 (if (memq nil
25574 (mapcar
25575 (lambda (x) (or (string-match "^[ \t]*|-" x)
25576 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25577 lines))
25578 (progn
25579 (setq org-table-clean-did-remove-column nil)
25580 (delq nil
25581 (mapcar
25582 (lambda (x)
25583 (cond
25584 ((string-match "^[ \t]*| */ *|" x)
25585 (setq org-table-colgroup-info
25586 (mapcar (lambda (x)
25587 (cond ((member x '("<" "&lt;")) :start)
25588 ((member x '(">" "&gt;")) :end)
25589 ((member x '("<>" "&lt;&gt;")) :startend)
25590 (t nil)))
25591 (org-split-string x "[ \t]*|[ \t]*")))
25592 nil)
25593 (t x)))
25594 lines)))
25595 (setq org-table-clean-did-remove-column t)
25596 (delq nil
25597 (mapcar
25598 (lambda (x)
25599 (cond
25600 ((string-match "^[ \t]*| */ *|" x)
25601 (setq org-table-colgroup-info
25602 (mapcar (lambda (x)
25603 (cond ((member x '("<" "&lt;")) :start)
25604 ((member x '(">" "&gt;")) :end)
25605 ((member x '("<>" "&lt;&gt;")) :startend)
25606 (t nil)))
25607 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25608 nil)
25609 ((string-match "^[ \t]*| *[!_^/] *|" x)
25610 nil) ; ignore this line
25611 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25612 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25613 ;; remove the first column
25614 (replace-match "\\1|" t nil x))))
25615 lines))))
25617 (defun org-format-table-table-html (lines)
25618 "Format a table generated by table.el into HTML.
25619 This conversion does *not* use `table-generate-source' from table.el.
25620 This has the advantage that Org-mode's HTML conversions can be used.
25621 But it has the disadvantage, that no cell- or row-spanning is allowed."
25622 (let (line field-buffer
25623 (head org-export-highlight-first-table-line)
25624 fields html empty)
25625 (setq html (concat html-table-tag "\n"))
25626 (while (setq line (pop lines))
25627 (setq empty "&nbsp;")
25628 (catch 'next-line
25629 (if (string-match "^[ \t]*\\+-" line)
25630 (progn
25631 (if field-buffer
25632 (progn
25633 (setq
25634 html
25635 (concat
25636 html
25637 "<tr>"
25638 (mapconcat
25639 (lambda (x)
25640 (if (equal x "") (setq x empty))
25641 (if head
25642 (concat (car org-export-table-header-tags) x
25643 (cdr org-export-table-header-tags))
25644 (concat (car org-export-table-data-tags) x
25645 (cdr org-export-table-data-tags))))
25646 field-buffer "\n")
25647 "</tr>\n"))
25648 (setq head nil)
25649 (setq field-buffer nil)))
25650 ;; Ignore this line
25651 (throw 'next-line t)))
25652 ;; Break the line into fields and store the fields
25653 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25654 (if field-buffer
25655 (setq field-buffer (mapcar
25656 (lambda (x)
25657 (concat x "<br/>" (pop fields)))
25658 field-buffer))
25659 (setq field-buffer fields))))
25660 (setq html (concat html "</table>\n"))
25661 html))
25663 (defun org-format-table-table-html-using-table-generate-source (lines)
25664 "Format a table into html, using `table-generate-source' from table.el.
25665 This has the advantage that cell- or row-spanning is allowed.
25666 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25667 (require 'table)
25668 (with-current-buffer (get-buffer-create " org-tmp1 ")
25669 (erase-buffer)
25670 (insert (mapconcat 'identity lines "\n"))
25671 (goto-char (point-min))
25672 (if (not (re-search-forward "|[^+]" nil t))
25673 (error "Error processing table"))
25674 (table-recognize-table)
25675 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25676 (table-generate-source 'html " org-tmp2 ")
25677 (set-buffer " org-tmp2 ")
25678 (buffer-substring (point-min) (point-max))))
25680 (defun org-html-handle-time-stamps (s)
25681 "Format time stamps in string S, or remove them."
25682 (catch 'exit
25683 (let (r b)
25684 (while (string-match org-maybe-keyword-time-regexp s)
25685 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25686 ;; never export CLOCK
25687 (throw 'exit ""))
25688 (or b (setq b (substring s 0 (match-beginning 0))))
25689 (if (not org-export-with-timestamps)
25690 (setq r (concat r (substring s 0 (match-beginning 0)))
25691 s (substring s (match-end 0)))
25692 (setq r (concat
25693 r (substring s 0 (match-beginning 0))
25694 (if (match-end 1)
25695 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25696 (match-string 1 s)))
25697 (format " @<span class=\"timestamp\">%s@</span>"
25698 (substring
25699 (org-translate-time (match-string 3 s)) 1 -1)))
25700 s (substring s (match-end 0)))))
25701 ;; Line break if line started and ended with time stamp stuff
25702 (if (not r)
25704 (setq r (concat r s))
25705 (unless (string-match "\\S-" (concat b s))
25706 (setq r (concat r "@<br/>")))
25707 r))))
25709 (defun org-html-protect (s)
25710 ;; convert & to &amp;, < to &lt; and > to &gt;
25711 (let ((start 0))
25712 (while (string-match "&" s start)
25713 (setq s (replace-match "&amp;" t t s)
25714 start (1+ (match-beginning 0))))
25715 (while (string-match "<" s)
25716 (setq s (replace-match "&lt;" t t s)))
25717 (while (string-match ">" s)
25718 (setq s (replace-match "&gt;" t t s))))
25721 (defun org-export-cleanup-toc-line (s)
25722 "Remove tags and time staps from lines going into the toc."
25723 (when (memq org-export-with-tags '(not-in-toc nil))
25724 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25725 (setq s (replace-match "" t t s))))
25726 (when org-export-remove-timestamps-from-toc
25727 (while (string-match org-maybe-keyword-time-regexp s)
25728 (setq s (replace-match "" t t s))))
25729 (while (string-match org-bracket-link-regexp s)
25730 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25731 t t s)))
25734 (defun org-html-expand (string)
25735 "Prepare STRING for HTML export. Applies all active conversions.
25736 If there are links in the string, don't modify these."
25737 (let* ((re (concat org-bracket-link-regexp "\\|"
25738 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25739 m s l res)
25740 (while (setq m (string-match re string))
25741 (setq s (substring string 0 m)
25742 l (match-string 0 string)
25743 string (substring string (match-end 0)))
25744 (push (org-html-do-expand s) res)
25745 (push l res))
25746 (push (org-html-do-expand string) res)
25747 (apply 'concat (nreverse res))))
25749 (defun org-html-do-expand (s)
25750 "Apply all active conversions to translate special ASCII to HTML."
25751 (setq s (org-html-protect s))
25752 (if org-export-html-expand
25753 (let ((start 0))
25754 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25755 (setq s (replace-match "<\\1>" t nil s)))))
25756 (if org-export-with-emphasize
25757 (setq s (org-export-html-convert-emphasize s)))
25758 (if org-export-with-special-strings
25759 (setq s (org-export-html-convert-special-strings s)))
25760 (if org-export-with-sub-superscripts
25761 (setq s (org-export-html-convert-sub-super s)))
25762 (if org-export-with-TeX-macros
25763 (let ((start 0) wd ass)
25764 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25765 (if (get-text-property (match-beginning 0) 'org-protected s)
25766 (setq start (match-end 0))
25767 (setq wd (match-string 1 s))
25768 (if (setq ass (assoc wd org-html-entities))
25769 (setq s (replace-match (or (cdr ass)
25770 (concat "&" (car ass) ";"))
25771 t t s))
25772 (setq start (+ start (length wd))))))))
25775 (defun org-create-multibrace-regexp (left right n)
25776 "Create a regular expression which will match a balanced sexp.
25777 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25778 as single character strings.
25779 The regexp returned will match the entire expression including the
25780 delimiters. It will also define a single group which contains the
25781 match except for the outermost delimiters. The maximum depth of
25782 stacked delimiters is N. Escaping delimiters is not possible."
25783 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25784 (or "\\|")
25785 (re nothing)
25786 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25787 (while (> n 1)
25788 (setq n (1- n)
25789 re (concat re or next)
25790 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25791 (concat left "\\(" re "\\)" right)))
25793 (defvar org-match-substring-regexp
25794 (concat
25795 "\\([^\\]\\)\\([_^]\\)\\("
25796 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25797 "\\|"
25798 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25799 "\\|"
25800 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25801 "The regular expression matching a sub- or superscript.")
25803 (defvar org-match-substring-with-braces-regexp
25804 (concat
25805 "\\([^\\]\\)\\([_^]\\)\\("
25806 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25807 "\\)")
25808 "The regular expression matching a sub- or superscript, forcing braces.")
25810 (defconst org-export-html-special-string-regexps
25811 '(("\\\\-" . "&shy;")
25812 ("---\\([^-]\\)" . "&mdash;\\1")
25813 ("--\\([^-]\\)" . "&ndash;\\1")
25814 ("\\.\\.\\." . "&hellip;"))
25815 "Regular expressions for special string conversion.")
25817 (defun org-export-html-convert-special-strings (string)
25818 "Convert special characters in STRING to HTML."
25819 (let ((all org-export-html-special-string-regexps)
25820 e a re rpl start)
25821 (while (setq a (pop all))
25822 (setq re (car a) rpl (cdr a) start 0)
25823 (while (string-match re string start)
25824 (if (get-text-property (match-beginning 0) 'org-protected string)
25825 (setq start (match-end 0))
25826 (setq string (replace-match rpl t nil string)))))
25827 string))
25829 (defun org-export-html-convert-sub-super (string)
25830 "Convert sub- and superscripts in STRING to HTML."
25831 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25832 (while (string-match org-match-substring-regexp string s)
25833 (cond
25834 ((and requireb (match-end 8)) (setq s (match-end 2)))
25835 ((get-text-property (match-beginning 2) 'org-protected string)
25836 (setq s (match-end 2)))
25838 (setq s (match-end 1)
25839 key (if (string= (match-string 2 string) "_") "sub" "sup")
25840 c (or (match-string 8 string)
25841 (match-string 6 string)
25842 (match-string 5 string))
25843 string (replace-match
25844 (concat (match-string 1 string)
25845 "<" key ">" c "</" key ">")
25846 t t string)))))
25847 (while (string-match "\\\\\\([_^]\\)" string)
25848 (setq string (replace-match (match-string 1 string) t t string)))
25849 string))
25851 (defun org-export-html-convert-emphasize (string)
25852 "Apply emphasis."
25853 (let ((s 0) rpl)
25854 (while (string-match org-emph-re string s)
25855 (if (not (equal
25856 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25857 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25858 (setq s (match-beginning 0)
25860 (concat
25861 (match-string 1 string)
25862 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25863 (match-string 4 string)
25864 (nth 3 (assoc (match-string 3 string)
25865 org-emphasis-alist))
25866 (match-string 5 string))
25867 string (replace-match rpl t t string)
25868 s (+ s (- (length rpl) 2)))
25869 (setq s (1+ s))))
25870 string))
25872 (defvar org-par-open nil)
25873 (defun org-open-par ()
25874 "Insert <p>, but first close previous paragraph if any."
25875 (org-close-par-maybe)
25876 (insert "\n<p>")
25877 (setq org-par-open t))
25878 (defun org-close-par-maybe ()
25879 "Close paragraph if there is one open."
25880 (when org-par-open
25881 (insert "</p>")
25882 (setq org-par-open nil)))
25883 (defun org-close-li ()
25884 "Close <li> if necessary."
25885 (org-close-par-maybe)
25886 (insert "</li>\n"))
25888 (defvar body-only) ; dynamically scoped into this.
25889 (defun org-html-level-start (level title umax with-toc head-count)
25890 "Insert a new level in HTML export.
25891 When TITLE is nil, just close all open levels."
25892 (org-close-par-maybe)
25893 (let ((l org-level-max))
25894 (while (>= l level)
25895 (if (aref org-levels-open (1- l))
25896 (progn
25897 (org-html-level-close l umax)
25898 (aset org-levels-open (1- l) nil)))
25899 (setq l (1- l)))
25900 (when title
25901 ;; If title is nil, this means this function is called to close
25902 ;; all levels, so the rest is done only if title is given
25903 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25904 (setq title (replace-match
25905 (if org-export-with-tags
25906 (save-match-data
25907 (concat
25908 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
25909 (mapconcat 'identity (org-split-string
25910 (match-string 1 title) ":")
25911 "&nbsp;")
25912 "</span>"))
25914 t t title)))
25915 (if (> level umax)
25916 (progn
25917 (if (aref org-levels-open (1- level))
25918 (progn
25919 (org-close-li)
25920 (insert "<li>" title "<br/>\n"))
25921 (aset org-levels-open (1- level) t)
25922 (org-close-par-maybe)
25923 (insert "<ul>\n<li>" title "<br/>\n")))
25924 (aset org-levels-open (1- level) t)
25925 (if (and org-export-with-section-numbers (not body-only))
25926 (setq title (concat (org-section-number level) " " title)))
25927 (setq level (+ level org-export-html-toplevel-hlevel -1))
25928 (if with-toc
25929 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
25930 level level head-count title level))
25931 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
25932 (org-open-par)))))
25934 (defun org-html-level-close (level max-outline-level)
25935 "Terminate one level in HTML export."
25936 (if (<= level max-outline-level)
25937 (insert "</div>\n")
25938 (org-close-li)
25939 (insert "</ul>\n")))
25941 ;;; iCalendar export
25943 ;;;###autoload
25944 (defun org-export-icalendar-this-file ()
25945 "Export current file as an iCalendar file.
25946 The iCalendar file will be located in the same directory as the Org-mode
25947 file, but with extension `.ics'."
25948 (interactive)
25949 (org-export-icalendar nil buffer-file-name))
25951 ;;;###autoload
25952 (defun org-export-icalendar-all-agenda-files ()
25953 "Export all files in `org-agenda-files' to iCalendar .ics files.
25954 Each iCalendar file will be located in the same directory as the Org-mode
25955 file, but with extension `.ics'."
25956 (interactive)
25957 (apply 'org-export-icalendar nil (org-agenda-files t)))
25959 ;;;###autoload
25960 (defun org-export-icalendar-combine-agenda-files ()
25961 "Export all files in `org-agenda-files' to a single combined iCalendar file.
25962 The file is stored under the name `org-combined-agenda-icalendar-file'."
25963 (interactive)
25964 (apply 'org-export-icalendar t (org-agenda-files t)))
25966 (defun org-export-icalendar (combine &rest files)
25967 "Create iCalendar files for all elements of FILES.
25968 If COMBINE is non-nil, combine all calendar entries into a single large
25969 file and store it under the name `org-combined-agenda-icalendar-file'."
25970 (save-excursion
25971 (org-prepare-agenda-buffers files)
25972 (let* ((dir (org-export-directory
25973 :ical (list :publishing-directory
25974 org-export-publishing-directory)))
25975 file ical-file ical-buffer category started org-agenda-new-buffers)
25977 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
25978 (when combine
25979 (setq ical-file
25980 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
25981 org-combined-agenda-icalendar-file
25982 (expand-file-name org-combined-agenda-icalendar-file dir))
25983 ical-buffer (org-get-agenda-file-buffer ical-file))
25984 (set-buffer ical-buffer) (erase-buffer))
25985 (while (setq file (pop files))
25986 (catch 'nextfile
25987 (org-check-agenda-file file)
25988 (set-buffer (org-get-agenda-file-buffer file))
25989 (unless combine
25990 (setq ical-file (concat (file-name-as-directory dir)
25991 (file-name-sans-extension
25992 (file-name-nondirectory buffer-file-name))
25993 ".ics"))
25994 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
25995 (with-current-buffer ical-buffer (erase-buffer)))
25996 (setq category (or org-category
25997 (file-name-sans-extension
25998 (file-name-nondirectory buffer-file-name))))
25999 (if (symbolp category) (setq category (symbol-name category)))
26000 (let ((standard-output ical-buffer))
26001 (if combine
26002 (and (not started) (setq started t)
26003 (org-start-icalendar-file org-icalendar-combined-name))
26004 (org-start-icalendar-file category))
26005 (org-print-icalendar-entries combine)
26006 (when (or (and combine (not files)) (not combine))
26007 (org-finish-icalendar-file)
26008 (set-buffer ical-buffer)
26009 (save-buffer)
26010 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26011 (org-release-buffers org-agenda-new-buffers))))
26013 (defvar org-after-save-iCalendar-file-hook nil
26014 "Hook run after an iCalendar file has been saved.
26015 The iCalendar buffer is still current when this hook is run.
26016 A good way to use this is to tell a desktop calenndar application to re-read
26017 the iCalendar file.")
26019 (defun org-print-icalendar-entries (&optional combine)
26020 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26021 When COMBINE is non nil, add the category to each line."
26022 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26023 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26024 (dts (org-ical-ts-to-string
26025 (format-time-string (cdr org-time-stamp-formats) (current-time))
26026 "DTSTART"))
26027 hd ts ts2 state status (inc t) pos b sexp rrule
26028 scheduledp deadlinep tmp pri category entry location summary desc
26029 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26030 (org-refresh-category-properties)
26031 (save-excursion
26032 (goto-char (point-min))
26033 (while (re-search-forward re1 nil t)
26034 (catch :skip
26035 (org-agenda-skip)
26036 (setq pos (match-beginning 0)
26037 ts (match-string 0)
26038 inc t
26039 hd (org-get-heading)
26040 summary (org-icalendar-cleanup-string
26041 (org-entry-get nil "SUMMARY"))
26042 desc (org-icalendar-cleanup-string
26043 (or (org-entry-get nil "DESCRIPTION")
26044 (and org-icalendar-include-body (org-get-entry)))
26045 t org-icalendar-include-body)
26046 location (org-icalendar-cleanup-string
26047 (org-entry-get nil "LOCATION"))
26048 category (org-get-category))
26049 (if (looking-at re2)
26050 (progn
26051 (goto-char (match-end 0))
26052 (setq ts2 (match-string 1) inc nil))
26053 (setq tmp (buffer-substring (max (point-min)
26054 (- pos org-ds-keyword-length))
26055 pos)
26056 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26057 (progn
26058 (setq inc nil)
26059 (replace-match "\\1" t nil ts))
26061 deadlinep (string-match org-deadline-regexp tmp)
26062 scheduledp (string-match org-scheduled-regexp tmp)
26063 ;; donep (org-entry-is-done-p)
26065 (if (or (string-match org-tr-regexp hd)
26066 (string-match org-ts-regexp hd))
26067 (setq hd (replace-match "" t t hd)))
26068 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26069 (setq rrule
26070 (concat "\nRRULE:FREQ="
26071 (cdr (assoc
26072 (match-string 2 ts)
26073 '(("d" . "DAILY")("w" . "WEEKLY")
26074 ("m" . "MONTHLY")("y" . "YEARLY"))))
26075 ";INTERVAL=" (match-string 1 ts)))
26076 (setq rrule ""))
26077 (setq summary (or summary hd))
26078 (if (string-match org-bracket-link-regexp summary)
26079 (setq summary
26080 (replace-match (if (match-end 3)
26081 (match-string 3 summary)
26082 (match-string 1 summary))
26083 t t summary)))
26084 (if deadlinep (setq summary (concat "DL: " summary)))
26085 (if scheduledp (setq summary (concat "S: " summary)))
26086 (if (string-match "\\`<%%" ts)
26087 (with-current-buffer sexp-buffer
26088 (insert (substring ts 1 -1) " " summary "\n"))
26089 (princ (format "BEGIN:VEVENT
26091 %s%s
26092 SUMMARY:%s%s%s
26093 CATEGORIES:%s
26094 END:VEVENT\n"
26095 (org-ical-ts-to-string ts "DTSTART")
26096 (org-ical-ts-to-string ts2 "DTEND" inc)
26097 rrule summary
26098 (if (and desc (string-match "\\S-" desc))
26099 (concat "\nDESCRIPTION: " desc) "")
26100 (if (and location (string-match "\\S-" location))
26101 (concat "\nLOCATION: " location) "")
26102 category)))))
26104 (when (and org-icalendar-include-sexps
26105 (condition-case nil (require 'icalendar) (error nil))
26106 (fboundp 'icalendar-export-region))
26107 ;; Get all the literal sexps
26108 (goto-char (point-min))
26109 (while (re-search-forward "^&?%%(" nil t)
26110 (catch :skip
26111 (org-agenda-skip)
26112 (setq b (match-beginning 0))
26113 (goto-char (1- (match-end 0)))
26114 (forward-sexp 1)
26115 (end-of-line 1)
26116 (setq sexp (buffer-substring b (point)))
26117 (with-current-buffer sexp-buffer
26118 (insert sexp "\n"))
26119 (princ (org-diary-to-ical-string sexp-buffer)))))
26121 (when org-icalendar-include-todo
26122 (goto-char (point-min))
26123 (while (re-search-forward org-todo-line-regexp nil t)
26124 (catch :skip
26125 (org-agenda-skip)
26126 (setq state (match-string 2))
26127 (setq status (if (member state org-done-keywords)
26128 "COMPLETED" "NEEDS-ACTION"))
26129 (when (and state
26130 (or (not (member state org-done-keywords))
26131 (eq org-icalendar-include-todo 'all))
26132 (not (member org-archive-tag (org-get-tags-at)))
26134 (setq hd (match-string 3)
26135 summary (org-icalendar-cleanup-string
26136 (org-entry-get nil "SUMMARY"))
26137 desc (org-icalendar-cleanup-string
26138 (or (org-entry-get nil "DESCRIPTION")
26139 (and org-icalendar-include-body (org-get-entry)))
26140 t org-icalendar-include-body)
26141 location (org-icalendar-cleanup-string
26142 (org-entry-get nil "LOCATION")))
26143 (if (string-match org-bracket-link-regexp hd)
26144 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26145 (match-string 1 hd))
26146 t t hd)))
26147 (if (string-match org-priority-regexp hd)
26148 (setq pri (string-to-char (match-string 2 hd))
26149 hd (concat (substring hd 0 (match-beginning 1))
26150 (substring hd (match-end 1))))
26151 (setq pri org-default-priority))
26152 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26153 (- org-lowest-priority org-highest-priority))))))
26155 (princ (format "BEGIN:VTODO
26157 SUMMARY:%s%s%s
26158 CATEGORIES:%s
26159 SEQUENCE:1
26160 PRIORITY:%d
26161 STATUS:%s
26162 END:VTODO\n"
26164 (or summary hd)
26165 (if (and location (string-match "\\S-" location))
26166 (concat "\nLOCATION: " location) "")
26167 (if (and desc (string-match "\\S-" desc))
26168 (concat "\nDESCRIPTION: " desc) "")
26169 category pri status)))))))))
26171 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26172 "Take out stuff and quote what needs to be quoted.
26173 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26174 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26175 characters."
26176 (if (not s)
26178 (when is-body
26179 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26180 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26181 (while (string-match re s) (setq s (replace-match "" t t s)))
26182 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26183 (let ((start 0))
26184 (while (string-match "\\([,;\\]\\)" s start)
26185 (setq start (+ (match-beginning 0) 2)
26186 s (replace-match "\\\\\\1" nil nil s))))
26187 (when is-body
26188 (while (string-match "[ \t]*\n[ \t]*" s)
26189 (setq s (replace-match "\\n" t t s))))
26190 (setq s (org-trim s))
26191 (if is-body
26192 (if maxlength
26193 (if (and (numberp maxlength)
26194 (> (length s) maxlength))
26195 (setq s (substring s 0 maxlength)))))
26198 (defun org-get-entry ()
26199 "Clean-up description string."
26200 (save-excursion
26201 (org-back-to-heading t)
26202 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26204 (defun org-start-icalendar-file (name)
26205 "Start an iCalendar file by inserting the header."
26206 (let ((user user-full-name)
26207 (name (or name "unknown"))
26208 (timezone (cadr (current-time-zone))))
26209 (princ
26210 (format "BEGIN:VCALENDAR
26211 VERSION:2.0
26212 X-WR-CALNAME:%s
26213 PRODID:-//%s//Emacs with Org-mode//EN
26214 X-WR-TIMEZONE:%s
26215 CALSCALE:GREGORIAN\n" name user timezone))))
26217 (defun org-finish-icalendar-file ()
26218 "Finish an iCalendar file by inserting the END statement."
26219 (princ "END:VCALENDAR\n"))
26221 (defun org-ical-ts-to-string (s keyword &optional inc)
26222 "Take a time string S and convert it to iCalendar format.
26223 KEYWORD is added in front, to make a complete line like DTSTART....
26224 When INC is non-nil, increase the hour by two (if time string contains
26225 a time), or the day by one (if it does not contain a time)."
26226 (let ((t1 (org-parse-time-string s 'nodefault))
26227 t2 fmt have-time time)
26228 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26229 (setq t2 t1 have-time t)
26230 (setq t2 (org-parse-time-string s)))
26231 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26232 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26233 (when inc
26234 (if have-time
26235 (if org-agenda-default-appointment-duration
26236 (setq mi (+ org-agenda-default-appointment-duration mi))
26237 (setq h (+ 2 h)))
26238 (setq d (1+ d))))
26239 (setq time (encode-time s mi h d m y)))
26240 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26241 (concat keyword (format-time-string fmt time))))
26243 ;;; XOXO export
26245 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26246 (with-current-buffer buffer
26247 (apply 'insert output)))
26248 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26250 (defun org-export-as-xoxo (&optional buffer)
26251 "Export the org buffer as XOXO.
26252 The XOXO buffer is named *xoxo-<source buffer name>*"
26253 (interactive (list (current-buffer)))
26254 ;; A quickie abstraction
26256 ;; Output everything as XOXO
26257 (with-current-buffer (get-buffer buffer)
26258 (let* ((pos (point))
26259 (opt-plist (org-combine-plists (org-default-export-plist)
26260 (org-infile-export-plist)))
26261 (filename (concat (file-name-as-directory
26262 (org-export-directory :xoxo opt-plist))
26263 (file-name-sans-extension
26264 (file-name-nondirectory buffer-file-name))
26265 ".html"))
26266 (out (find-file-noselect filename))
26267 (last-level 1)
26268 (hanging-li nil))
26269 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26270 ;; Check the output buffer is empty.
26271 (with-current-buffer out (erase-buffer))
26272 ;; Kick off the output
26273 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26274 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26275 (let* ((hd (match-string-no-properties 1))
26276 (level (length hd))
26277 (text (concat
26278 (match-string-no-properties 2)
26279 (save-excursion
26280 (goto-char (match-end 0))
26281 (let ((str ""))
26282 (catch 'loop
26283 (while 't
26284 (forward-line)
26285 (if (looking-at "^[ \t]\\(.*\\)")
26286 (setq str (concat str (match-string-no-properties 1)))
26287 (throw 'loop str)))))))))
26289 ;; Handle level rendering
26290 (cond
26291 ((> level last-level)
26292 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26294 ((< level last-level)
26295 (dotimes (- (- last-level level) 1)
26296 (if hanging-li
26297 (org-export-as-xoxo-insert-into out "</li>\n"))
26298 (org-export-as-xoxo-insert-into out "</ol>\n"))
26299 (when hanging-li
26300 (org-export-as-xoxo-insert-into out "</li>\n")
26301 (setq hanging-li nil)))
26303 ((equal level last-level)
26304 (if hanging-li
26305 (org-export-as-xoxo-insert-into out "</li>\n")))
26308 (setq last-level level)
26310 ;; And output the new li
26311 (setq hanging-li 't)
26312 (if (equal ?+ (elt text 0))
26313 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26314 (org-export-as-xoxo-insert-into out "<li>" text))))
26316 ;; Finally finish off the ol
26317 (dotimes (- last-level 1)
26318 (if hanging-li
26319 (org-export-as-xoxo-insert-into out "</li>\n"))
26320 (org-export-as-xoxo-insert-into out "</ol>\n"))
26322 (goto-char pos)
26323 ;; Finish the buffer off and clean it up.
26324 (switch-to-buffer-other-window out)
26325 (indent-region (point-min) (point-max) nil)
26326 (save-buffer)
26327 (goto-char (point-min))
26331 ;;;; Key bindings
26333 ;; Make `C-c C-x' a prefix key
26334 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26336 ;; TAB key with modifiers
26337 (org-defkey org-mode-map "\C-i" 'org-cycle)
26338 (org-defkey org-mode-map [(tab)] 'org-cycle)
26339 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26340 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26341 (org-defkey org-mode-map "\M-\t" 'org-complete)
26342 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26343 ;; The following line is necessary under Suse GNU/Linux
26344 (unless (featurep 'xemacs)
26345 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26346 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26347 (define-key org-mode-map [backtab] 'org-shifttab)
26349 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26350 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26351 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26353 ;; Cursor keys with modifiers
26354 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26355 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26356 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26357 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26359 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26360 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26361 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26362 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26364 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26365 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26366 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26367 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26369 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26370 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26372 ;;; Extra keys for tty access.
26373 ;; We only set them when really needed because otherwise the
26374 ;; menus don't show the simple keys
26376 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26377 (not window-system))
26378 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26379 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26380 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26381 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26382 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26383 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26384 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26385 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26386 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26387 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26388 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26389 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26390 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26391 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26392 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26393 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26394 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26395 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26396 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26397 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26398 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26399 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26401 ;; All the other keys
26403 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26404 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26405 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26406 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26407 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26408 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26409 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26410 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26411 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26412 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26413 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26414 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26415 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26416 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26417 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26418 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26419 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26420 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26421 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26422 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26423 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26424 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26425 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26426 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26427 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26428 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26429 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26430 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26431 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26432 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26433 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26434 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26435 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26436 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26437 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26438 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26439 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26440 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26441 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26442 (org-defkey org-mode-map "\C-c^" 'org-sort)
26443 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26444 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26445 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26446 (org-defkey org-mode-map "\C-m" 'org-return)
26447 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26448 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26449 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26450 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26451 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26452 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26453 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26454 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26455 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26456 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26457 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26458 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26459 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26460 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26461 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26462 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26463 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26465 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26466 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26467 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26468 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26470 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26471 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26472 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26473 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26474 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26475 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26476 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26477 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26478 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26479 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26480 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26481 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26483 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26485 (when (featurep 'xemacs)
26486 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26488 (defsubst org-table-p () (org-at-table-p))
26490 (defun org-self-insert-command (N)
26491 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26492 If the cursor is in a table looking at whitespace, the whitespace is
26493 overwritten, and the table is not marked as requiring realignment."
26494 (interactive "p")
26495 (if (and (org-table-p)
26496 (progn
26497 ;; check if we blank the field, and if that triggers align
26498 (and org-table-auto-blank-field
26499 (member last-command
26500 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26501 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26502 ;; got extra space, this field does not determine column width
26503 (let (org-table-may-need-update) (org-table-blank-field))
26504 ;; no extra space, this field may determine column width
26505 (org-table-blank-field)))
26507 (eq N 1)
26508 (looking-at "[^|\n]* |"))
26509 (let (org-table-may-need-update)
26510 (goto-char (1- (match-end 0)))
26511 (delete-backward-char 1)
26512 (goto-char (match-beginning 0))
26513 (self-insert-command N))
26514 (setq org-table-may-need-update t)
26515 (self-insert-command N)
26516 (org-fix-tags-on-the-fly)))
26518 (defun org-fix-tags-on-the-fly ()
26519 (when (and (equal (char-after (point-at-bol)) ?*)
26520 (org-on-heading-p))
26521 (org-align-tags-here org-tags-column)))
26523 (defun org-delete-backward-char (N)
26524 "Like `delete-backward-char', insert whitespace at field end in tables.
26525 When deleting backwards, in tables this function will insert whitespace in
26526 front of the next \"|\" separator, to keep the table aligned. The table will
26527 still be marked for re-alignment if the field did fill the entire column,
26528 because, in this case the deletion might narrow the column."
26529 (interactive "p")
26530 (if (and (org-table-p)
26531 (eq N 1)
26532 (string-match "|" (buffer-substring (point-at-bol) (point)))
26533 (looking-at ".*?|"))
26534 (let ((pos (point))
26535 (noalign (looking-at "[^|\n\r]* |"))
26536 (c org-table-may-need-update))
26537 (backward-delete-char N)
26538 (skip-chars-forward "^|")
26539 (insert " ")
26540 (goto-char (1- pos))
26541 ;; noalign: if there were two spaces at the end, this field
26542 ;; does not determine the width of the column.
26543 (if noalign (setq org-table-may-need-update c)))
26544 (backward-delete-char N)
26545 (org-fix-tags-on-the-fly)))
26547 (defun org-delete-char (N)
26548 "Like `delete-char', but insert whitespace at field end in tables.
26549 When deleting characters, in tables this function will insert whitespace in
26550 front of the next \"|\" separator, to keep the table aligned. The table will
26551 still be marked for re-alignment if the field did fill the entire column,
26552 because, in this case the deletion might narrow the column."
26553 (interactive "p")
26554 (if (and (org-table-p)
26555 (not (bolp))
26556 (not (= (char-after) ?|))
26557 (eq N 1))
26558 (if (looking-at ".*?|")
26559 (let ((pos (point))
26560 (noalign (looking-at "[^|\n\r]* |"))
26561 (c org-table-may-need-update))
26562 (replace-match (concat
26563 (substring (match-string 0) 1 -1)
26564 " |"))
26565 (goto-char pos)
26566 ;; noalign: if there were two spaces at the end, this field
26567 ;; does not determine the width of the column.
26568 (if noalign (setq org-table-may-need-update c)))
26569 (delete-char N))
26570 (delete-char N)
26571 (org-fix-tags-on-the-fly)))
26573 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26574 (put 'org-self-insert-command 'delete-selection t)
26575 (put 'orgtbl-self-insert-command 'delete-selection t)
26576 (put 'org-delete-char 'delete-selection 'supersede)
26577 (put 'org-delete-backward-char 'delete-selection 'supersede)
26579 ;; Make `flyspell-mode' delay after some commands
26580 (put 'org-self-insert-command 'flyspell-delayed t)
26581 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26582 (put 'org-delete-char 'flyspell-delayed t)
26583 (put 'org-delete-backward-char 'flyspell-delayed t)
26585 ;; Make pabbrev-mode expand after org-mode commands
26586 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26587 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26589 ;; How to do this: Measure non-white length of current string
26590 ;; If equal to column width, we should realign.
26592 (defun org-remap (map &rest commands)
26593 "In MAP, remap the functions given in COMMANDS.
26594 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26595 (let (new old)
26596 (while commands
26597 (setq old (pop commands) new (pop commands))
26598 (if (fboundp 'command-remapping)
26599 (org-defkey map (vector 'remap old) new)
26600 (substitute-key-definition old new map global-map)))))
26602 (when (eq org-enable-table-editor 'optimized)
26603 ;; If the user wants maximum table support, we need to hijack
26604 ;; some standard editing functions
26605 (org-remap org-mode-map
26606 'self-insert-command 'org-self-insert-command
26607 'delete-char 'org-delete-char
26608 'delete-backward-char 'org-delete-backward-char)
26609 (org-defkey org-mode-map "|" 'org-force-self-insert))
26611 (defun org-shiftcursor-error ()
26612 "Throw an error because Shift-Cursor command was applied in wrong context."
26613 (error "This command is active in special context like tables, headlines or timestamps"))
26615 (defun org-shifttab (&optional arg)
26616 "Global visibility cycling or move to previous table field.
26617 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26618 on context.
26619 See the individual commands for more information."
26620 (interactive "P")
26621 (cond
26622 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26623 (arg (message "Content view to level: ")
26624 (org-content (prefix-numeric-value arg))
26625 (setq org-cycle-global-status 'overview))
26626 (t (call-interactively 'org-global-cycle))))
26628 (defun org-shiftmetaleft ()
26629 "Promote subtree or delete table column.
26630 Calls `org-promote-subtree', `org-outdent-item',
26631 or `org-table-delete-column', depending on context.
26632 See the individual commands for more information."
26633 (interactive)
26634 (cond
26635 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26636 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26637 ((org-at-item-p) (call-interactively 'org-outdent-item))
26638 (t (org-shiftcursor-error))))
26640 (defun org-shiftmetaright ()
26641 "Demote subtree or insert table column.
26642 Calls `org-demote-subtree', `org-indent-item',
26643 or `org-table-insert-column', depending on context.
26644 See the individual commands for more information."
26645 (interactive)
26646 (cond
26647 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26648 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26649 ((org-at-item-p) (call-interactively 'org-indent-item))
26650 (t (org-shiftcursor-error))))
26652 (defun org-shiftmetaup (&optional arg)
26653 "Move subtree up or kill table row.
26654 Calls `org-move-subtree-up' or `org-table-kill-row' or
26655 `org-move-item-up' depending on context. See the individual commands
26656 for more information."
26657 (interactive "P")
26658 (cond
26659 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26660 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26661 ((org-at-item-p) (call-interactively 'org-move-item-up))
26662 (t (org-shiftcursor-error))))
26663 (defun org-shiftmetadown (&optional arg)
26664 "Move subtree down or insert table row.
26665 Calls `org-move-subtree-down' or `org-table-insert-row' or
26666 `org-move-item-down', depending on context. See the individual
26667 commands for more information."
26668 (interactive "P")
26669 (cond
26670 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26671 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26672 ((org-at-item-p) (call-interactively 'org-move-item-down))
26673 (t (org-shiftcursor-error))))
26675 (defun org-metaleft (&optional arg)
26676 "Promote heading or move table column to left.
26677 Calls `org-do-promote' or `org-table-move-column', depending on context.
26678 With no specific context, calls the Emacs default `backward-word'.
26679 See the individual commands for more information."
26680 (interactive "P")
26681 (cond
26682 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26683 ((or (org-on-heading-p) (org-region-active-p))
26684 (call-interactively 'org-do-promote))
26685 ((org-at-item-p) (call-interactively 'org-outdent-item))
26686 (t (call-interactively 'backward-word))))
26688 (defun org-metaright (&optional arg)
26689 "Demote subtree or move table column to right.
26690 Calls `org-do-demote' or `org-table-move-column', depending on context.
26691 With no specific context, calls the Emacs default `forward-word'.
26692 See the individual commands for more information."
26693 (interactive "P")
26694 (cond
26695 ((org-at-table-p) (call-interactively 'org-table-move-column))
26696 ((or (org-on-heading-p) (org-region-active-p))
26697 (call-interactively 'org-do-demote))
26698 ((org-at-item-p) (call-interactively 'org-indent-item))
26699 (t (call-interactively 'forward-word))))
26701 (defun org-metaup (&optional arg)
26702 "Move subtree up or move table row up.
26703 Calls `org-move-subtree-up' or `org-table-move-row' or
26704 `org-move-item-up', depending on context. See the individual commands
26705 for more information."
26706 (interactive "P")
26707 (cond
26708 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26709 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26710 ((org-at-item-p) (call-interactively 'org-move-item-up))
26711 (t (transpose-lines 1) (beginning-of-line -1))))
26713 (defun org-metadown (&optional arg)
26714 "Move subtree down or move table row down.
26715 Calls `org-move-subtree-down' or `org-table-move-row' or
26716 `org-move-item-down', depending on context. See the individual
26717 commands for more information."
26718 (interactive "P")
26719 (cond
26720 ((org-at-table-p) (call-interactively 'org-table-move-row))
26721 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26722 ((org-at-item-p) (call-interactively 'org-move-item-down))
26723 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26725 (defun org-shiftup (&optional arg)
26726 "Increase item in timestamp or increase priority of current headline.
26727 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26728 depending on context. See the individual commands for more information."
26729 (interactive "P")
26730 (cond
26731 ((org-at-timestamp-p t)
26732 (call-interactively (if org-edit-timestamp-down-means-later
26733 'org-timestamp-down 'org-timestamp-up)))
26734 ((org-on-heading-p) (call-interactively 'org-priority-up))
26735 ((org-at-item-p) (call-interactively 'org-previous-item))
26736 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26738 (defun org-shiftdown (&optional arg)
26739 "Decrease item in timestamp or decrease priority of current headline.
26740 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26741 depending on context. See the individual commands for more information."
26742 (interactive "P")
26743 (cond
26744 ((org-at-timestamp-p t)
26745 (call-interactively (if org-edit-timestamp-down-means-later
26746 'org-timestamp-up 'org-timestamp-down)))
26747 ((org-on-heading-p) (call-interactively 'org-priority-down))
26748 (t (call-interactively 'org-next-item))))
26750 (defun org-shiftright ()
26751 "Next TODO keyword or timestamp one day later, depending on context."
26752 (interactive)
26753 (cond
26754 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26755 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26756 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26757 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26758 (t (org-shiftcursor-error))))
26760 (defun org-shiftleft ()
26761 "Previous TODO keyword or timestamp one day earlier, depending on context."
26762 (interactive)
26763 (cond
26764 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26765 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26766 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26767 ((org-at-property-p)
26768 (call-interactively 'org-property-previous-allowed-value))
26769 (t (org-shiftcursor-error))))
26771 (defun org-shiftcontrolright ()
26772 "Switch to next TODO set."
26773 (interactive)
26774 (cond
26775 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26776 (t (org-shiftcursor-error))))
26778 (defun org-shiftcontrolleft ()
26779 "Switch to previous TODO set."
26780 (interactive)
26781 (cond
26782 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26783 (t (org-shiftcursor-error))))
26785 (defun org-ctrl-c-ret ()
26786 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26787 (interactive)
26788 (cond
26789 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26790 (t (call-interactively 'org-insert-heading))))
26792 (defun org-copy-special ()
26793 "Copy region in table or copy current subtree.
26794 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26795 See the individual commands for more information."
26796 (interactive)
26797 (call-interactively
26798 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26800 (defun org-cut-special ()
26801 "Cut region in table or cut current subtree.
26802 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26803 See the individual commands for more information."
26804 (interactive)
26805 (call-interactively
26806 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26808 (defun org-paste-special (arg)
26809 "Paste rectangular region into table, or past subtree relative to level.
26810 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26811 See the individual commands for more information."
26812 (interactive "P")
26813 (if (org-at-table-p)
26814 (org-table-paste-rectangle)
26815 (org-paste-subtree arg)))
26817 (defun org-ctrl-c-ctrl-c (&optional arg)
26818 "Set tags in headline, or update according to changed information at point.
26820 This command does many different things, depending on context:
26822 - If the cursor is in a headline, prompt for tags and insert them
26823 into the current line, aligned to `org-tags-column'. When called
26824 with prefix arg, realign all tags in the current buffer.
26826 - If the cursor is in one of the special #+KEYWORD lines, this
26827 triggers scanning the buffer for these lines and updating the
26828 information.
26830 - If the cursor is inside a table, realign the table. This command
26831 works even if the automatic table editor has been turned off.
26833 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26834 the entire table.
26836 - If the cursor is a the beginning of a dynamic block, update it.
26838 - If the cursor is inside a table created by the table.el package,
26839 activate that table.
26841 - If the current buffer is a remember buffer, close note and file it.
26842 with a prefix argument, file it without further interaction to the default
26843 location.
26845 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26846 links in this buffer.
26848 - If the cursor is on a numbered item in a plain list, renumber the
26849 ordered list.
26851 - If the cursor is on a checkbox, toggle it."
26852 (interactive "P")
26853 (let ((org-enable-table-editor t))
26854 (cond
26855 ((or org-clock-overlays
26856 org-occur-highlights
26857 org-latex-fragment-image-overlays)
26858 (org-remove-clock-overlays)
26859 (org-remove-occur-highlights)
26860 (org-remove-latex-fragment-image-overlays)
26861 (message "Temporary highlights/overlays removed from current buffer"))
26862 ((and (local-variable-p 'org-finish-function (current-buffer))
26863 (fboundp org-finish-function))
26864 (funcall org-finish-function))
26865 ((org-at-property-p)
26866 (call-interactively 'org-property-action))
26867 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
26868 ((org-on-heading-p) (call-interactively 'org-set-tags))
26869 ((org-at-table.el-p)
26870 (require 'table)
26871 (beginning-of-line 1)
26872 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
26873 (call-interactively 'table-recognize-table))
26874 ((org-at-table-p)
26875 (org-table-maybe-eval-formula)
26876 (if arg
26877 (call-interactively 'org-table-recalculate)
26878 (org-table-maybe-recalculate-line))
26879 (call-interactively 'org-table-align))
26880 ((org-at-item-checkbox-p)
26881 (call-interactively 'org-toggle-checkbox))
26882 ((org-at-item-p)
26883 (call-interactively 'org-maybe-renumber-ordered-list))
26884 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
26885 ;; Dynamic block
26886 (beginning-of-line 1)
26887 (org-update-dblock))
26888 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
26889 (cond
26890 ((equal (match-string 1) "TBLFM")
26891 ;; Recalculate the table before this line
26892 (save-excursion
26893 (beginning-of-line 1)
26894 (skip-chars-backward " \r\n\t")
26895 (if (org-at-table-p)
26896 (org-call-with-arg 'org-table-recalculate t))))
26898 (call-interactively 'org-mode-restart))))
26899 (t (error "C-c C-c can do nothing useful at this location.")))))
26901 (defun org-mode-restart ()
26902 "Restart Org-mode, to scan again for special lines.
26903 Also updates the keyword regular expressions."
26904 (interactive)
26905 (let ((org-inhibit-startup t)) (org-mode))
26906 (message "Org-mode restarted to refresh keyword and special line setup"))
26908 (defun org-kill-note-or-show-branches ()
26909 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
26910 (interactive)
26911 (if (not org-finish-function)
26912 (call-interactively 'show-branches)
26913 (let ((org-note-abort t))
26914 (funcall org-finish-function))))
26916 (defun org-return (&optional indent)
26917 "Goto next table row or insert a newline.
26918 Calls `org-table-next-row' or `newline', depending on context.
26919 See the individual commands for more information."
26920 (interactive)
26921 (cond
26922 ((bobp) (if indent (newline-and-indent) (newline)))
26923 ((org-at-table-p)
26924 (org-table-justify-field-maybe)
26925 (call-interactively 'org-table-next-row))
26926 (t (if indent (newline-and-indent) (newline)))))
26928 (defun org-return-indent ()
26929 (interactive)
26930 "Goto next table row or insert a newline and indent.
26931 Calls `org-table-next-row' or `newline-and-indent', depending on
26932 context. See the individual commands for more information."
26933 (org-return t))
26935 (defun org-ctrl-c-minus ()
26936 "Insert separator line in table or modify bullet type in list.
26937 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
26938 depending on context."
26939 (interactive)
26940 (cond
26941 ((org-at-table-p)
26942 (call-interactively 'org-table-insert-hline))
26943 ((org-on-heading-p)
26944 ;; Convert to item
26945 (save-excursion
26946 (beginning-of-line 1)
26947 (if (looking-at "\\*+ ")
26948 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
26949 ((org-in-item-p)
26950 (call-interactively 'org-cycle-list-bullet))
26951 (t (error "`C-c -' does have no function here."))))
26953 (defun org-meta-return (&optional arg)
26954 "Insert a new heading or wrap a region in a table.
26955 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
26956 See the individual commands for more information."
26957 (interactive "P")
26958 (cond
26959 ((org-at-table-p)
26960 (call-interactively 'org-table-wrap-region))
26961 (t (call-interactively 'org-insert-heading))))
26963 ;;; Menu entries
26965 ;; Define the Org-mode menus
26966 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
26967 '("Tbl"
26968 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
26969 ["Next Field" org-cycle (org-at-table-p)]
26970 ["Previous Field" org-shifttab (org-at-table-p)]
26971 ["Next Row" org-return (org-at-table-p)]
26972 "--"
26973 ["Blank Field" org-table-blank-field (org-at-table-p)]
26974 ["Edit Field" org-table-edit-field (org-at-table-p)]
26975 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
26976 "--"
26977 ("Column"
26978 ["Move Column Left" org-metaleft (org-at-table-p)]
26979 ["Move Column Right" org-metaright (org-at-table-p)]
26980 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
26981 ["Insert Column" org-shiftmetaright (org-at-table-p)])
26982 ("Row"
26983 ["Move Row Up" org-metaup (org-at-table-p)]
26984 ["Move Row Down" org-metadown (org-at-table-p)]
26985 ["Delete Row" org-shiftmetaup (org-at-table-p)]
26986 ["Insert Row" org-shiftmetadown (org-at-table-p)]
26987 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
26988 "--"
26989 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
26990 ("Rectangle"
26991 ["Copy Rectangle" org-copy-special (org-at-table-p)]
26992 ["Cut Rectangle" org-cut-special (org-at-table-p)]
26993 ["Paste Rectangle" org-paste-special (org-at-table-p)]
26994 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
26995 "--"
26996 ("Calculate"
26997 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
26998 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
26999 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27000 "--"
27001 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27002 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27003 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27004 "--"
27005 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27006 "--"
27007 ["Sum Column/Rectangle" org-table-sum
27008 (or (org-at-table-p) (org-region-active-p))]
27009 ["Which Column?" org-table-current-column (org-at-table-p)])
27010 ["Debug Formulas"
27011 org-table-toggle-formula-debugger
27012 :style toggle :selected org-table-formula-debug]
27013 ["Show Col/Row Numbers"
27014 org-table-toggle-coordinate-overlays
27015 :style toggle :selected org-table-overlay-coordinates]
27016 "--"
27017 ["Create" org-table-create (and (not (org-at-table-p))
27018 org-enable-table-editor)]
27019 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27020 ["Import from File" org-table-import (not (org-at-table-p))]
27021 ["Export to File" org-table-export (org-at-table-p)]
27022 "--"
27023 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27025 (easy-menu-define org-org-menu org-mode-map "Org menu"
27026 '("Org"
27027 ("Show/Hide"
27028 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27029 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27030 ["Sparse Tree" org-occur t]
27031 ["Reveal Context" org-reveal t]
27032 ["Show All" show-all t]
27033 "--"
27034 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27035 "--"
27036 ["New Heading" org-insert-heading t]
27037 ("Navigate Headings"
27038 ["Up" outline-up-heading t]
27039 ["Next" outline-next-visible-heading t]
27040 ["Previous" outline-previous-visible-heading t]
27041 ["Next Same Level" outline-forward-same-level t]
27042 ["Previous Same Level" outline-backward-same-level t]
27043 "--"
27044 ["Jump" org-goto t])
27045 ("Edit Structure"
27046 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27047 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27048 "--"
27049 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27050 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27051 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27052 "--"
27053 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27054 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27055 ["Demote Heading" org-metaright (not (org-at-table-p))]
27056 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27057 "--"
27058 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27059 "--"
27060 ["Convert to odd levels" org-convert-to-odd-levels t]
27061 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27062 ("Editing"
27063 ["Emphasis..." org-emphasize t])
27064 ("Archive"
27065 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27066 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27067 ; :active t :keys "C-u C-c C-x C-a"]
27068 ["Sparse trees open ARCHIVE trees"
27069 (setq org-sparse-tree-open-archived-trees
27070 (not org-sparse-tree-open-archived-trees))
27071 :style toggle :selected org-sparse-tree-open-archived-trees]
27072 ["Cycling opens ARCHIVE trees"
27073 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27074 :style toggle :selected org-cycle-open-archived-trees]
27075 ["Agenda includes ARCHIVE trees"
27076 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27077 :style toggle :selected (not org-agenda-skip-archived-trees)]
27078 "--"
27079 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27080 ; ["Check and Move Children" (org-archive-subtree '(4))
27081 ; :active t :keys "C-u C-c C-x C-s"]
27083 "--"
27084 ("TODO Lists"
27085 ["TODO/DONE/-" org-todo t]
27086 ("Select keyword"
27087 ["Next keyword" org-shiftright (org-on-heading-p)]
27088 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27089 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27090 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27091 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27092 ["Show TODO Tree" org-show-todo-tree t]
27093 ["Global TODO list" org-todo-list t]
27094 "--"
27095 ["Set Priority" org-priority t]
27096 ["Priority Up" org-shiftup t]
27097 ["Priority Down" org-shiftdown t])
27098 ("TAGS and Properties"
27099 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27100 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27101 "--"
27102 ["Set property" 'org-set-property t]
27103 ["Column view of properties" org-columns t]
27104 ["Insert Column View DBlock" org-insert-columns-dblock t])
27105 ("Dates and Scheduling"
27106 ["Timestamp" org-time-stamp t]
27107 ["Timestamp (inactive)" org-time-stamp-inactive t]
27108 ("Change Date"
27109 ["1 Day Later" org-shiftright t]
27110 ["1 Day Earlier" org-shiftleft t]
27111 ["1 ... Later" org-shiftup t]
27112 ["1 ... Earlier" org-shiftdown t])
27113 ["Compute Time Range" org-evaluate-time-range t]
27114 ["Schedule Item" org-schedule t]
27115 ["Deadline" org-deadline t]
27116 "--"
27117 ["Custom time format" org-toggle-time-stamp-overlays
27118 :style radio :selected org-display-custom-times]
27119 "--"
27120 ["Goto Calendar" org-goto-calendar t]
27121 ["Date from Calendar" org-date-from-calendar t])
27122 ("Logging work"
27123 ["Clock in" org-clock-in t]
27124 ["Clock out" org-clock-out t]
27125 ["Clock cancel" org-clock-cancel t]
27126 ["Goto running clock" org-clock-goto t]
27127 ["Display times" org-clock-display t]
27128 ["Create clock table" org-clock-report t]
27129 "--"
27130 ["Record DONE time"
27131 (progn (setq org-log-done (not org-log-done))
27132 (message "Switching to %s will %s record a timestamp"
27133 (car org-done-keywords)
27134 (if org-log-done "automatically" "not")))
27135 :style toggle :selected org-log-done])
27136 "--"
27137 ["Agenda Command..." org-agenda t]
27138 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27139 ("File List for Agenda")
27140 ("Special views current file"
27141 ["TODO Tree" org-show-todo-tree t]
27142 ["Check Deadlines" org-check-deadlines t]
27143 ["Timeline" org-timeline t]
27144 ["Tags Tree" org-tags-sparse-tree t])
27145 "--"
27146 ("Hyperlinks"
27147 ["Store Link (Global)" org-store-link t]
27148 ["Insert Link" org-insert-link t]
27149 ["Follow Link" org-open-at-point t]
27150 "--"
27151 ["Next link" org-next-link t]
27152 ["Previous link" org-previous-link t]
27153 "--"
27154 ["Descriptive Links"
27155 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27156 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27157 ["Literal Links"
27158 (progn
27159 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27160 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27161 "--"
27162 ["Export/Publish..." org-export t]
27163 ("LaTeX"
27164 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27165 :selected org-cdlatex-mode]
27166 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27167 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27168 ["Modify math symbol" org-cdlatex-math-modify
27169 (org-inside-LaTeX-fragment-p)]
27170 ["Export LaTeX fragments as images"
27171 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27172 :style toggle :selected org-export-with-LaTeX-fragments])
27173 "--"
27174 ("Documentation"
27175 ["Show Version" org-version t]
27176 ["Info Documentation" org-info t])
27177 ("Customize"
27178 ["Browse Org Group" org-customize t]
27179 "--"
27180 ["Expand This Menu" org-create-customize-menu
27181 (fboundp 'customize-menu-create)])
27182 "--"
27183 ["Refresh setup" org-mode-restart t]
27186 (defun org-info (&optional node)
27187 "Read documentation for Org-mode in the info system.
27188 With optional NODE, go directly to that node."
27189 (interactive)
27190 (require 'info)
27191 (Info-goto-node (format "(org)%s" (or node ""))))
27193 (defun org-install-agenda-files-menu ()
27194 (let ((bl (buffer-list)))
27195 (save-excursion
27196 (while bl
27197 (set-buffer (pop bl))
27198 (if (org-mode-p) (setq bl nil)))
27199 (when (org-mode-p)
27200 (easy-menu-change
27201 '("Org") "File List for Agenda"
27202 (append
27203 (list
27204 ["Edit File List" (org-edit-agenda-file-list) t]
27205 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27206 ["Remove Current File from List" org-remove-file t]
27207 ["Cycle through agenda files" org-cycle-agenda-files t]
27208 ["Occur in all agenda files" org-occur-in-agenda-files t]
27209 "--")
27210 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27212 ;;;; Documentation
27214 (defun org-customize ()
27215 "Call the customize function with org as argument."
27216 (interactive)
27217 (customize-browse 'org))
27219 (defun org-create-customize-menu ()
27220 "Create a full customization menu for Org-mode, insert it into the menu."
27221 (interactive)
27222 (if (fboundp 'customize-menu-create)
27223 (progn
27224 (easy-menu-change
27225 '("Org") "Customize"
27226 `(["Browse Org group" org-customize t]
27227 "--"
27228 ,(customize-menu-create 'org)
27229 ["Set" Custom-set t]
27230 ["Save" Custom-save t]
27231 ["Reset to Current" Custom-reset-current t]
27232 ["Reset to Saved" Custom-reset-saved t]
27233 ["Reset to Standard Settings" Custom-reset-standard t]))
27234 (message "\"Org\"-menu now contains full customization menu"))
27235 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27237 ;;;; Miscellaneous stuff
27240 ;;; Generally useful functions
27242 (defun org-context ()
27243 "Return a list of contexts of the current cursor position.
27244 If several contexts apply, all are returned.
27245 Each context entry is a list with a symbol naming the context, and
27246 two positions indicating start and end of the context. Possible
27247 contexts are:
27249 :headline anywhere in a headline
27250 :headline-stars on the leading stars in a headline
27251 :todo-keyword on a TODO keyword (including DONE) in a headline
27252 :tags on the TAGS in a headline
27253 :priority on the priority cookie in a headline
27254 :item on the first line of a plain list item
27255 :item-bullet on the bullet/number of a plain list item
27256 :checkbox on the checkbox in a plain list item
27257 :table in an org-mode table
27258 :table-special on a special filed in a table
27259 :table-table in a table.el table
27260 :link on a hyperlink
27261 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27262 :target on a <<target>>
27263 :radio-target on a <<<radio-target>>>
27264 :latex-fragment on a LaTeX fragment
27265 :latex-preview on a LaTeX fragment with overlayed preview image
27267 This function expects the position to be visible because it uses font-lock
27268 faces as a help to recognize the following contexts: :table-special, :link,
27269 and :keyword."
27270 (let* ((f (get-text-property (point) 'face))
27271 (faces (if (listp f) f (list f)))
27272 (p (point)) clist o)
27273 ;; First the large context
27274 (cond
27275 ((org-on-heading-p t)
27276 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27277 (when (progn
27278 (beginning-of-line 1)
27279 (looking-at org-todo-line-tags-regexp))
27280 (push (org-point-in-group p 1 :headline-stars) clist)
27281 (push (org-point-in-group p 2 :todo-keyword) clist)
27282 (push (org-point-in-group p 4 :tags) clist))
27283 (goto-char p)
27284 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27285 (if (looking-at "\\[#[A-Z0-9]\\]")
27286 (push (org-point-in-group p 0 :priority) clist)))
27288 ((org-at-item-p)
27289 (push (org-point-in-group p 2 :item-bullet) clist)
27290 (push (list :item (point-at-bol)
27291 (save-excursion (org-end-of-item) (point)))
27292 clist)
27293 (and (org-at-item-checkbox-p)
27294 (push (org-point-in-group p 0 :checkbox) clist)))
27296 ((org-at-table-p)
27297 (push (list :table (org-table-begin) (org-table-end)) clist)
27298 (if (memq 'org-formula faces)
27299 (push (list :table-special
27300 (previous-single-property-change p 'face)
27301 (next-single-property-change p 'face)) clist)))
27302 ((org-at-table-p 'any)
27303 (push (list :table-table) clist)))
27304 (goto-char p)
27306 ;; Now the small context
27307 (cond
27308 ((org-at-timestamp-p)
27309 (push (org-point-in-group p 0 :timestamp) clist))
27310 ((memq 'org-link faces)
27311 (push (list :link
27312 (previous-single-property-change p 'face)
27313 (next-single-property-change p 'face)) clist))
27314 ((memq 'org-special-keyword faces)
27315 (push (list :keyword
27316 (previous-single-property-change p 'face)
27317 (next-single-property-change p 'face)) clist))
27318 ((org-on-target-p)
27319 (push (org-point-in-group p 0 :target) clist)
27320 (goto-char (1- (match-beginning 0)))
27321 (if (looking-at org-radio-target-regexp)
27322 (push (org-point-in-group p 0 :radio-target) clist))
27323 (goto-char p))
27324 ((setq o (car (delq nil
27325 (mapcar
27326 (lambda (x)
27327 (if (memq x org-latex-fragment-image-overlays) x))
27328 (org-overlays-at (point))))))
27329 (push (list :latex-fragment
27330 (org-overlay-start o) (org-overlay-end o)) clist)
27331 (push (list :latex-preview
27332 (org-overlay-start o) (org-overlay-end o)) clist))
27333 ((org-inside-LaTeX-fragment-p)
27334 ;; FIXME: positions wrong.
27335 (push (list :latex-fragment (point) (point)) clist)))
27337 (setq clist (nreverse (delq nil clist)))
27338 clist))
27340 ;; FIXME: Compare with at-regexp-p Do we need both?
27341 (defun org-in-regexp (re &optional nlines visually)
27342 "Check if point is inside a match of regexp.
27343 Normally only the current line is checked, but you can include NLINES extra
27344 lines both before and after point into the search.
27345 If VISUALLY is set, require that the cursor is not after the match but
27346 really on, so that the block visually is on the match."
27347 (catch 'exit
27348 (let ((pos (point))
27349 (eol (point-at-eol (+ 1 (or nlines 0))))
27350 (inc (if visually 1 0)))
27351 (save-excursion
27352 (beginning-of-line (- 1 (or nlines 0)))
27353 (while (re-search-forward re eol t)
27354 (if (and (<= (match-beginning 0) pos)
27355 (>= (+ inc (match-end 0)) pos))
27356 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27358 (defun org-at-regexp-p (regexp)
27359 "Is point inside a match of REGEXP in the current line?"
27360 (catch 'exit
27361 (save-excursion
27362 (let ((pos (point)) (end (point-at-eol)))
27363 (beginning-of-line 1)
27364 (while (re-search-forward regexp end t)
27365 (if (and (<= (match-beginning 0) pos)
27366 (>= (match-end 0) pos))
27367 (throw 'exit t)))
27368 nil))))
27370 (defun org-occur-in-agenda-files (regexp &optional nlines)
27371 "Call `multi-occur' with buffers for all agenda files."
27372 (interactive "sOrg-files matching: \np")
27373 (let* ((files (org-agenda-files))
27374 (tnames (mapcar 'file-truename files))
27375 (extra org-agenda-multi-occur-extra-files)
27377 (while (setq f (pop extra))
27378 (unless (member (file-truename f) tnames)
27379 (add-to-list 'files f 'append)
27380 (add-to-list 'tnames (file-truename f) 'append)))
27381 (multi-occur
27382 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27383 regexp)))
27385 (defun org-uniquify (list)
27386 "Remove duplicate elements from LIST."
27387 (let (res)
27388 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27389 res))
27391 (defun org-delete-all (elts list)
27392 "Remove all elements in ELTS from LIST."
27393 (while elts
27394 (setq list (delete (pop elts) list)))
27395 list)
27397 (defun org-back-over-empty-lines ()
27398 "Move backwards over witespace, to the beginning of the first empty line.
27399 Returns the number o empty lines passed."
27400 (let ((pos (point)))
27401 (skip-chars-backward " \t\n\r")
27402 (beginning-of-line 2)
27403 (count-lines (point) pos)))
27405 (defun org-skip-whitespace ()
27406 (skip-chars-forward " \t\n\r"))
27408 (defun org-point-in-group (point group &optional context)
27409 "Check if POINT is in match-group GROUP.
27410 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27411 match. If the match group does ot exist or point is not inside it,
27412 return nil."
27413 (and (match-beginning group)
27414 (>= point (match-beginning group))
27415 (<= point (match-end group))
27416 (if context
27417 (list context (match-beginning group) (match-end group))
27418 t)))
27420 (defun org-switch-to-buffer-other-window (&rest args)
27421 "Switch to buffer in a second window on the current frame.
27422 In particular, do not allow pop-up frames."
27423 (let (pop-up-frames special-display-buffer-names special-display-regexps
27424 special-display-function)
27425 (apply 'switch-to-buffer-other-window args)))
27427 (defun org-combine-plists (&rest plists)
27428 "Create a single property list from all plists in PLISTS.
27429 The process starts by copying the first list, and then setting properties
27430 from the other lists. Settings in the last list are the most significant
27431 ones and overrule settings in the other lists."
27432 (let ((rtn (copy-sequence (pop plists)))
27433 p v ls)
27434 (while plists
27435 (setq ls (pop plists))
27436 (while ls
27437 (setq p (pop ls) v (pop ls))
27438 (setq rtn (plist-put rtn p v))))
27439 rtn))
27441 (defun org-move-line-down (arg)
27442 "Move the current line down. With prefix argument, move it past ARG lines."
27443 (interactive "p")
27444 (let ((col (current-column))
27445 beg end pos)
27446 (beginning-of-line 1) (setq beg (point))
27447 (beginning-of-line 2) (setq end (point))
27448 (beginning-of-line (+ 1 arg))
27449 (setq pos (move-marker (make-marker) (point)))
27450 (insert (delete-and-extract-region beg end))
27451 (goto-char pos)
27452 (move-to-column col)))
27454 (defun org-move-line-up (arg)
27455 "Move the current line up. With prefix argument, move it past ARG lines."
27456 (interactive "p")
27457 (let ((col (current-column))
27458 beg end pos)
27459 (beginning-of-line 1) (setq beg (point))
27460 (beginning-of-line 2) (setq end (point))
27461 (beginning-of-line (- arg))
27462 (setq pos (move-marker (make-marker) (point)))
27463 (insert (delete-and-extract-region beg end))
27464 (goto-char pos)
27465 (move-to-column col)))
27467 (defun org-replace-escapes (string table)
27468 "Replace %-escapes in STRING with values in TABLE.
27469 TABLE is an association list with keys like \"%a\" and string values.
27470 The sequences in STRING may contain normal field width and padding information,
27471 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27472 so values can contain further %-escapes if they are define later in TABLE."
27473 (let ((case-fold-search nil)
27474 e re rpl)
27475 (while (setq e (pop table))
27476 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27477 (while (string-match re string)
27478 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27479 (cdr e)))
27480 (setq string (replace-match rpl t t string))))
27481 string))
27484 (defun org-sublist (list start end)
27485 "Return a section of LIST, from START to END.
27486 Counting starts at 1."
27487 (let (rtn (c start))
27488 (setq list (nthcdr (1- start) list))
27489 (while (and list (<= c end))
27490 (push (pop list) rtn)
27491 (setq c (1+ c)))
27492 (nreverse rtn)))
27494 (defun org-find-base-buffer-visiting (file)
27495 "Like `find-buffer-visiting' but alway return the base buffer and
27496 not an indirect buffer"
27497 (let ((buf (find-buffer-visiting file)))
27498 (if buf
27499 (or (buffer-base-buffer buf) buf)
27500 nil)))
27502 (defun org-image-file-name-regexp ()
27503 "Return regexp matching the file names of images."
27504 (if (fboundp 'image-file-name-regexp)
27505 (image-file-name-regexp)
27506 (let ((image-file-name-extensions
27507 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27508 "xbm" "xpm" "pbm" "pgm" "ppm")))
27509 (concat "\\."
27510 (regexp-opt (nconc (mapcar 'upcase
27511 image-file-name-extensions)
27512 image-file-name-extensions)
27514 "\\'"))))
27516 (defun org-file-image-p (file)
27517 "Return non-nil if FILE is an image."
27518 (save-match-data
27519 (string-match (org-image-file-name-regexp) file)))
27521 ;;; Paragraph filling stuff.
27522 ;; We want this to be just right, so use the full arsenal.
27524 (defun org-indent-line-function ()
27525 "Indent line like previous, but further if previous was headline or item."
27526 (interactive)
27527 (let* ((pos (point))
27528 (itemp (org-at-item-p))
27529 column bpos bcol tpos tcol bullet btype bullet-type)
27530 ;; Find the previous relevant line
27531 (beginning-of-line 1)
27532 (cond
27533 ((looking-at "#") (setq column 0))
27534 ((looking-at "\\*+ ") (setq column 0))
27536 (beginning-of-line 0)
27537 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27538 (beginning-of-line 0))
27539 (cond
27540 ((looking-at "\\*+[ \t]+")
27541 (goto-char (match-end 0))
27542 (setq column (current-column)))
27543 ((org-in-item-p)
27544 (org-beginning-of-item)
27545 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27546 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27547 (setq bpos (match-beginning 1) tpos (match-end 0)
27548 bcol (progn (goto-char bpos) (current-column))
27549 tcol (progn (goto-char tpos) (current-column))
27550 bullet (match-string 1)
27551 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27552 (if (not itemp)
27553 (setq column tcol)
27554 (goto-char pos)
27555 (beginning-of-line 1)
27556 (if (looking-at "\\S-")
27557 (progn
27558 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27559 (setq bullet (match-string 1)
27560 btype (if (string-match "[0-9]" bullet) "n" bullet))
27561 (setq column (if (equal btype bullet-type) bcol tcol)))
27562 (setq column (org-get-indentation)))))
27563 (t (setq column (org-get-indentation))))))
27564 (goto-char pos)
27565 (if (<= (current-column) (current-indentation))
27566 (indent-line-to column)
27567 (save-excursion (indent-line-to column)))
27568 (setq column (current-column))
27569 (beginning-of-line 1)
27570 (if (looking-at
27571 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27572 (replace-match (concat "\\1" (format org-property-format
27573 (match-string 2) (match-string 3)))
27574 t nil))
27575 (move-to-column column)))
27577 (defun org-set-autofill-regexps ()
27578 (interactive)
27579 ;; In the paragraph separator we include headlines, because filling
27580 ;; text in a line directly attached to a headline would otherwise
27581 ;; fill the headline as well.
27582 (org-set-local 'comment-start-skip "^#+[ \t]*")
27583 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27584 ;; The paragraph starter includes hand-formatted lists.
27585 (org-set-local 'paragraph-start
27586 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27587 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27588 ;; But only if the user has not turned off tables or fixed-width regions
27589 (org-set-local
27590 'auto-fill-inhibit-regexp
27591 (concat "\\*+ \\|#\\+"
27592 "\\|[ \t]*" org-keyword-time-regexp
27593 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27594 (concat
27595 "\\|[ \t]*["
27596 (if org-enable-table-editor "|" "")
27597 (if org-enable-fixed-width-editor ":" "")
27598 "]"))))
27599 ;; We use our own fill-paragraph function, to make sure that tables
27600 ;; and fixed-width regions are not wrapped. That function will pass
27601 ;; through to `fill-paragraph' when appropriate.
27602 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27603 ; Adaptive filling: To get full control, first make sure that
27604 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27605 (org-set-local 'adaptive-fill-regexp "\000")
27606 (org-set-local 'adaptive-fill-function
27607 'org-adaptive-fill-function))
27609 (defun org-fill-paragraph (&optional justify)
27610 "Re-align a table, pass through to fill-paragraph if no table."
27611 (let ((table-p (org-at-table-p))
27612 (table.el-p (org-at-table.el-p)))
27613 (cond ((and (equal (char-after (point-at-bol)) ?*)
27614 (save-excursion (goto-char (point-at-bol))
27615 (looking-at outline-regexp)))
27616 t) ; skip headlines
27617 (table.el-p t) ; skip table.el tables
27618 (table-p (org-table-align) t) ; align org-mode tables
27619 (t nil)))) ; call paragraph-fill
27621 ;; For reference, this is the default value of adaptive-fill-regexp
27622 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27624 (defun org-adaptive-fill-function ()
27625 "Return a fill prefix for org-mode files.
27626 In particular, this makes sure hanging paragraphs for hand-formatted lists
27627 work correctly."
27628 (cond ((looking-at "#[ \t]+")
27629 (match-string 0))
27630 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27631 (save-excursion
27632 (goto-char (match-end 0))
27633 (make-string (current-column) ?\ )))
27634 (t nil)))
27636 ;;;; Functions extending outline functionality
27638 (defun org-beginning-of-line (&optional arg)
27639 "Go to the beginning of the current line. If that is invisible, continue
27640 to a visible line beginning. This makes the function of C-a more intuitive.
27641 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27642 first attempt, and only move to after the tags when the cursor is already
27643 beyond the end of the headline."
27644 (interactive "P")
27645 (let ((pos (point)))
27646 (beginning-of-line 1)
27647 (if (bobp)
27649 (backward-char 1)
27650 (if (org-invisible-p)
27651 (while (and (not (bobp)) (org-invisible-p))
27652 (backward-char 1)
27653 (beginning-of-line 1))
27654 (forward-char 1)))
27655 (when org-special-ctrl-a/e
27656 (cond
27657 ((and (looking-at org-todo-line-regexp)
27658 (= (char-after (match-end 1)) ?\ ))
27659 (goto-char
27660 (if (eq org-special-ctrl-a/e t)
27661 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27662 ((= pos (point)) (match-beginning 3))
27663 (t (point)))
27664 (cond ((> pos (point)) (point))
27665 ((not (eq last-command this-command)) (point))
27666 (t (match-beginning 3))))))
27667 ((org-at-item-p)
27668 (goto-char
27669 (if (eq org-special-ctrl-a/e t)
27670 (cond ((> pos (match-end 4)) (match-end 4))
27671 ((= pos (point)) (match-end 4))
27672 (t (point)))
27673 (cond ((> pos (point)) (point))
27674 ((not (eq last-command this-command)) (point))
27675 (t (match-end 4))))))))))
27677 (defun org-end-of-line (&optional arg)
27678 "Go to the end of the line.
27679 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27680 first attempt, and only move to after the tags when the cursor is already
27681 beyond the end of the headline."
27682 (interactive "P")
27683 (if (or (not org-special-ctrl-a/e)
27684 (not (org-on-heading-p)))
27685 (end-of-line arg)
27686 (let ((pos (point)))
27687 (beginning-of-line 1)
27688 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27689 (if (eq org-special-ctrl-a/e t)
27690 (if (or (< pos (match-beginning 1))
27691 (= pos (match-end 0)))
27692 (goto-char (match-beginning 1))
27693 (goto-char (match-end 0)))
27694 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27695 (goto-char (match-end 0))
27696 (goto-char (match-beginning 1))))
27697 (end-of-line arg)))))
27699 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27700 (define-key org-mode-map "\C-e" 'org-end-of-line)
27702 (defun org-invisible-p ()
27703 "Check if point is at a character currently not visible."
27704 ;; Early versions of noutline don't have `outline-invisible-p'.
27705 (if (fboundp 'outline-invisible-p)
27706 (outline-invisible-p)
27707 (get-char-property (point) 'invisible)))
27709 (defun org-invisible-p2 ()
27710 "Check if point is at a character currently not visible."
27711 (save-excursion
27712 (if (and (eolp) (not (bobp))) (backward-char 1))
27713 ;; Early versions of noutline don't have `outline-invisible-p'.
27714 (if (fboundp 'outline-invisible-p)
27715 (outline-invisible-p)
27716 (get-char-property (point) 'invisible))))
27718 (defalias 'org-back-to-heading 'outline-back-to-heading)
27719 (defalias 'org-on-heading-p 'outline-on-heading-p)
27720 (defalias 'org-at-heading-p 'outline-on-heading-p)
27721 (defun org-at-heading-or-item-p ()
27722 (or (org-on-heading-p) (org-at-item-p)))
27724 (defun org-on-target-p ()
27725 (or (org-in-regexp org-radio-target-regexp)
27726 (org-in-regexp org-target-regexp)))
27728 (defun org-up-heading-all (arg)
27729 "Move to the heading line of which the present line is a subheading.
27730 This function considers both visible and invisible heading lines.
27731 With argument, move up ARG levels."
27732 (if (fboundp 'outline-up-heading-all)
27733 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27734 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27736 (defun org-up-heading-safe ()
27737 "Move to the heading line of which the present line is a subheading.
27738 This version will not throw an error. It will return the level of the
27739 headline found, or nil if no higher level is found."
27740 (let ((pos (point)) start-level level
27741 (re (concat "^" outline-regexp)))
27742 (catch 'exit
27743 (outline-back-to-heading t)
27744 (setq start-level (funcall outline-level))
27745 (if (equal start-level 1) (throw 'exit nil))
27746 (while (re-search-backward re nil t)
27747 (setq level (funcall outline-level))
27748 (if (< level start-level) (throw 'exit level)))
27749 nil)))
27751 (defun org-first-sibling-p ()
27752 "Is this heading the first child of its parents?"
27753 (interactive)
27754 (let ((re (concat "^" outline-regexp))
27755 level l)
27756 (unless (org-at-heading-p t)
27757 (error "Not at a heading"))
27758 (setq level (funcall outline-level))
27759 (save-excursion
27760 (if (not (re-search-backward re nil t))
27762 (setq l (funcall outline-level))
27763 (< l level)))))
27765 (defun org-goto-sibling (&optional previous)
27766 "Goto the next sibling, even if it is invisible.
27767 When PREVIOUS is set, go to the previous sibling instead. Returns t
27768 when a sibling was found. When none is found, return nil and don't
27769 move point."
27770 (let ((fun (if previous 're-search-backward 're-search-forward))
27771 (pos (point))
27772 (re (concat "^" outline-regexp))
27773 level l)
27774 (when (condition-case nil (org-back-to-heading t) (error nil))
27775 (setq level (funcall outline-level))
27776 (catch 'exit
27777 (or previous (forward-char 1))
27778 (while (funcall fun re nil t)
27779 (setq l (funcall outline-level))
27780 (when (< l level) (goto-char pos) (throw 'exit nil))
27781 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27782 (goto-char pos)
27783 nil))))
27785 (defun org-show-siblings ()
27786 "Show all siblings of the current headline."
27787 (save-excursion
27788 (while (org-goto-sibling) (org-flag-heading nil)))
27789 (save-excursion
27790 (while (org-goto-sibling 'previous)
27791 (org-flag-heading nil))))
27793 (defun org-show-hidden-entry ()
27794 "Show an entry where even the heading is hidden."
27795 (save-excursion
27796 (org-show-entry)))
27798 (defun org-flag-heading (flag &optional entry)
27799 "Flag the current heading. FLAG non-nil means make invisible.
27800 When ENTRY is non-nil, show the entire entry."
27801 (save-excursion
27802 (org-back-to-heading t)
27803 ;; Check if we should show the entire entry
27804 (if entry
27805 (progn
27806 (org-show-entry)
27807 (save-excursion
27808 (and (outline-next-heading)
27809 (org-flag-heading nil))))
27810 (outline-flag-region (max (point-min) (1- (point)))
27811 (save-excursion (outline-end-of-heading) (point))
27812 flag))))
27814 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27815 ;; This is an exact copy of the original function, but it uses
27816 ;; `org-back-to-heading', to make it work also in invisible
27817 ;; trees. And is uses an invisible-OK argument.
27818 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
27819 (org-back-to-heading invisible-OK)
27820 (let ((first t)
27821 (level (funcall outline-level)))
27822 (while (and (not (eobp))
27823 (or first (> (funcall outline-level) level)))
27824 (setq first nil)
27825 (outline-next-heading))
27826 (unless to-heading
27827 (if (memq (preceding-char) '(?\n ?\^M))
27828 (progn
27829 ;; Go to end of line before heading
27830 (forward-char -1)
27831 (if (memq (preceding-char) '(?\n ?\^M))
27832 ;; leave blank line before heading
27833 (forward-char -1))))))
27834 (point))
27836 (defun org-show-subtree ()
27837 "Show everything after this heading at deeper levels."
27838 (outline-flag-region
27839 (point)
27840 (save-excursion
27841 (outline-end-of-subtree) (outline-next-heading) (point))
27842 nil))
27844 (defun org-show-entry ()
27845 "Show the body directly following this heading.
27846 Show the heading too, if it is currently invisible."
27847 (interactive)
27848 (save-excursion
27849 (condition-case nil
27850 (progn
27851 (org-back-to-heading t)
27852 (outline-flag-region
27853 (max (point-min) (1- (point)))
27854 (save-excursion
27855 (re-search-forward
27856 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
27857 (or (match-beginning 1) (point-max)))
27858 nil))
27859 (error nil))))
27861 (defun org-make-options-regexp (kwds)
27862 "Make a regular expression for keyword lines."
27863 (concat
27865 "#?[ \t]*\\+\\("
27866 (mapconcat 'regexp-quote kwds "\\|")
27867 "\\):[ \t]*"
27868 "\\(.+\\)"))
27870 ;; Make isearch reveal the necessary context
27871 (defun org-isearch-end ()
27872 "Reveal context after isearch exits."
27873 (when isearch-success ; only if search was successful
27874 (if (featurep 'xemacs)
27875 ;; Under XEmacs, the hook is run in the correct place,
27876 ;; we directly show the context.
27877 (org-show-context 'isearch)
27878 ;; In Emacs the hook runs *before* restoring the overlays.
27879 ;; So we have to use a one-time post-command-hook to do this.
27880 ;; (Emacs 22 has a special variable, see function `org-mode')
27881 (unless (and (boundp 'isearch-mode-end-hook-quit)
27882 isearch-mode-end-hook-quit)
27883 ;; Only when the isearch was not quitted.
27884 (org-add-hook 'post-command-hook 'org-isearch-post-command
27885 'append 'local)))))
27887 (defun org-isearch-post-command ()
27888 "Remove self from hook, and show context."
27889 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
27890 (org-show-context 'isearch))
27893 ;;;; Integration with and fixes for other packages
27895 ;;; Imenu support
27897 (defvar org-imenu-markers nil
27898 "All markers currently used by Imenu.")
27899 (make-variable-buffer-local 'org-imenu-markers)
27901 (defun org-imenu-new-marker (&optional pos)
27902 "Return a new marker for use by Imenu, and remember the marker."
27903 (let ((m (make-marker)))
27904 (move-marker m (or pos (point)))
27905 (push m org-imenu-markers)
27908 (defun org-imenu-get-tree ()
27909 "Produce the index for Imenu."
27910 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
27911 (setq org-imenu-markers nil)
27912 (let* ((n org-imenu-depth)
27913 (re (concat "^" outline-regexp))
27914 (subs (make-vector (1+ n) nil))
27915 (last-level 0)
27916 m tree level head)
27917 (save-excursion
27918 (save-restriction
27919 (widen)
27920 (goto-char (point-max))
27921 (while (re-search-backward re nil t)
27922 (setq level (org-reduced-level (funcall outline-level)))
27923 (when (<= level n)
27924 (looking-at org-complex-heading-regexp)
27925 (setq head (org-match-string-no-properties 4)
27926 m (org-imenu-new-marker))
27927 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
27928 (if (>= level last-level)
27929 (push (cons head m) (aref subs level))
27930 (push (cons head (aref subs (1+ level))) (aref subs level))
27931 (loop for i from (1+ level) to n do (aset subs i nil)))
27932 (setq last-level level)))))
27933 (aref subs 1)))
27935 (eval-after-load "imenu"
27936 '(progn
27937 (add-hook 'imenu-after-jump-hook
27938 (lambda () (org-show-context 'org-goto)))))
27940 ;; Speedbar support
27942 (defun org-speedbar-set-agenda-restriction ()
27943 "Restrict future agenda commands to the location at point in speedbar.
27944 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
27945 (interactive)
27946 (let (p m tp np dir txt w)
27947 (cond
27948 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27949 'org-imenu t))
27950 (setq m (get-text-property p 'org-imenu-marker))
27951 (save-excursion
27952 (save-restriction
27953 (set-buffer (marker-buffer m))
27954 (goto-char m)
27955 (org-agenda-set-restriction-lock 'subtree))))
27956 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27957 'speedbar-function 'speedbar-find-file))
27958 (setq tp (previous-single-property-change
27959 (1+ p) 'speedbar-function)
27960 np (next-single-property-change
27961 tp 'speedbar-function)
27962 dir (speedbar-line-directory)
27963 txt (buffer-substring-no-properties (or tp (point-min))
27964 (or np (point-max))))
27965 (save-excursion
27966 (save-restriction
27967 (set-buffer (find-file-noselect
27968 (let ((default-directory dir))
27969 (expand-file-name txt))))
27970 (unless (org-mode-p)
27971 (error "Cannot restrict to non-Org-mode file"))
27972 (org-agenda-set-restriction-lock 'file))))
27973 (t (error "Don't know how to restrict Org-mode's agenda")))
27974 (org-move-overlay org-speedbar-restriction-lock-overlay
27975 (point-at-bol) (point-at-eol))
27976 (setq current-prefix-arg nil)
27977 (org-agenda-maybe-redo)))
27979 (eval-after-load "speedbar"
27980 '(progn
27981 (speedbar-add-supported-extension ".org")
27982 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
27983 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
27984 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
27985 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27986 (add-hook 'speedbar-visiting-tag-hook
27987 (lambda () (org-show-context 'org-goto)))))
27990 ;;; Fixes and Hacks
27992 ;; Make flyspell not check words in links, to not mess up our keymap
27993 (defun org-mode-flyspell-verify ()
27994 "Don't let flyspell put overlays at active buttons."
27995 (not (get-text-property (point) 'keymap)))
27997 ;; Make `bookmark-jump' show the jump location if it was hidden.
27998 (eval-after-load "bookmark"
27999 '(if (boundp 'bookmark-after-jump-hook)
28000 ;; We can use the hook
28001 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28002 ;; Hook not available, use advice
28003 (defadvice bookmark-jump (after org-make-visible activate)
28004 "Make the position visible."
28005 (org-bookmark-jump-unhide))))
28007 (defun org-bookmark-jump-unhide ()
28008 "Unhide the current position, to show the bookmark location."
28009 (and (org-mode-p)
28010 (or (org-invisible-p)
28011 (save-excursion (goto-char (max (point-min) (1- (point))))
28012 (org-invisible-p)))
28013 (org-show-context 'bookmark-jump)))
28015 ;; Fix a bug in htmlize where there are text properties (face nil)
28016 (eval-after-load "htmlize"
28017 '(progn
28018 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28019 "Make sure there are no nil faces"
28020 (setq ad-return-value (delq nil ad-return-value)))))
28022 ;; Make session.el ignore our circular variable
28023 (eval-after-load "session"
28024 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28026 ;;;; Experimental code
28028 (defun org-closed-in-range ()
28029 "Sparse tree of items closed in a certain time range.
28030 Still experimental, may disappear in the future."
28031 (interactive)
28032 ;; Get the time interval from the user.
28033 (let* ((time1 (time-to-seconds
28034 (org-read-date nil 'to-time nil "Starting date: ")))
28035 (time2 (time-to-seconds
28036 (org-read-date nil 'to-time nil "End date:")))
28037 ;; callback function
28038 (callback (lambda ()
28039 (let ((time
28040 (time-to-seconds
28041 (apply 'encode-time
28042 (org-parse-time-string
28043 (match-string 1))))))
28044 ;; check if time in interval
28045 (and (>= time time1) (<= time time2))))))
28046 ;; make tree, check each match with the callback
28047 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28049 ;;;; Finish up
28051 (provide 'org)
28053 (run-hooks 'org-load-hook)
28055 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28056 ;;; org.el ends here