Support for aling.el.
[org-mode.git] / org.el
blobbdf1e91d2709ab6355e84285e443045338d47feb
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.20
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.20"
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 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
328 "Regular expression for specifying repeated events.
329 After a match, group 1 contains the repeat expression.")
331 (defgroup org-structure nil
332 "Options concerning the general structure of Org-mode files."
333 :tag "Org Structure"
334 :group 'org)
336 (defgroup org-reveal-location nil
337 "Options about how to make context of a location visible."
338 :tag "Org Reveal Location"
339 :group 'org-structure)
341 (defconst org-context-choice
342 '(choice
343 (const :tag "Always" t)
344 (const :tag "Never" nil)
345 (repeat :greedy t :tag "Individual contexts"
346 (cons
347 (choice :tag "Context"
348 (const agenda)
349 (const org-goto)
350 (const occur-tree)
351 (const tags-tree)
352 (const link-search)
353 (const mark-goto)
354 (const bookmark-jump)
355 (const isearch)
356 (const default))
357 (boolean))))
358 "Contexts for the reveal options.")
360 (defcustom org-show-hierarchy-above '((default . t))
361 "Non-nil means, show full hierarchy when revealing a location.
362 Org-mode often shows locations in an org-mode file which might have
363 been invisible before. When this is set, the hierarchy of headings
364 above the exposed location is shown.
365 Turning this off for example for sparse trees makes them very compact.
366 Instead of t, this can also be an alist specifying this option for different
367 contexts. Valid contexts are
368 agenda when exposing an entry from the agenda
369 org-goto when using the command `org-goto' on key C-c C-j
370 occur-tree when using the command `org-occur' on key C-c /
371 tags-tree when constructing a sparse tree based on tags matches
372 link-search when exposing search matches associated with a link
373 mark-goto when exposing the jump goal of a mark
374 bookmark-jump when exposing a bookmark location
375 isearch when exiting from an incremental search
376 default default for all contexts not set explicitly"
377 :group 'org-reveal-location
378 :type org-context-choice)
380 (defcustom org-show-following-heading '((default . nil))
381 "Non-nil means, show following heading when revealing a location.
382 Org-mode often shows locations in an org-mode file which might have
383 been invisible before. When this is set, the heading following the
384 match is shown.
385 Turning this off for example for sparse trees makes them very compact,
386 but makes it harder to edit the location of the match. In such a case,
387 use the command \\[org-reveal] to show more context.
388 Instead of t, this can also be an alist specifying this option for different
389 contexts. See `org-show-hierarchy-above' for valid contexts."
390 :group 'org-reveal-location
391 :type org-context-choice)
393 (defcustom org-show-siblings '((default . nil) (isearch t))
394 "Non-nil means, show all sibling heading when revealing a location.
395 Org-mode often shows locations in an org-mode file which might have
396 been invisible before. When this is set, the sibling of the current entry
397 heading are all made visible. If `org-show-hierarchy-above' is t,
398 the same happens on each level of the hierarchy above the current entry.
400 By default this is on for the isearch context, off for all other contexts.
401 Turning this off for example for sparse trees makes them very compact,
402 but makes it harder to edit the location of the match. In such a case,
403 use the command \\[org-reveal] to show more context.
404 Instead of t, this can also be an alist specifying this option for different
405 contexts. See `org-show-hierarchy-above' for valid contexts."
406 :group 'org-reveal-location
407 :type org-context-choice)
409 (defcustom org-show-entry-below '((default . nil))
410 "Non-nil means, show the entry below a headline when revealing a location.
411 Org-mode often shows locations in an org-mode file which might have
412 been invisible before. When this is set, the text below the headline that is
413 exposed is also shown.
415 By default this is off for all contexts.
416 Instead of t, this can also be an alist specifying this option for different
417 contexts. See `org-show-hierarchy-above' for valid contexts."
418 :group 'org-reveal-location
419 :type org-context-choice)
421 (defgroup org-cycle nil
422 "Options concerning visibility cycling in Org-mode."
423 :tag "Org Cycle"
424 :group 'org-structure)
426 (defcustom org-drawers '("PROPERTIES" "CLOCK")
427 "Names of drawers. Drawers are not opened by cycling on the headline above.
428 Drawers only open with a TAB on the drawer line itself. A drawer looks like
429 this:
430 :DRAWERNAME:
431 .....
432 :END:
433 The drawer \"PROPERTIES\" is special for capturing properties through
434 the property API.
436 Drawers can be defined on the per-file basis with a line like:
438 #+DRAWERS: HIDDEN STATE PROPERTIES"
439 :group 'org-structure
440 :type '(repeat (string :tag "Drawer Name")))
442 (defcustom org-cycle-global-at-bob nil
443 "Cycle globally if cursor is at beginning of buffer and not at a headline.
444 This makes it possible to do global cycling without having to use S-TAB or
445 C-u TAB. For this special case to work, the first line of the buffer
446 must not be a headline - it may be empty ot some other text. When used in
447 this way, `org-cycle-hook' is disables temporarily, to make sure the
448 cursor stays at the beginning of the buffer.
449 When this option is nil, don't do anything special at the beginning
450 of the buffer."
451 :group 'org-cycle
452 :type 'boolean)
454 (defcustom org-cycle-emulate-tab t
455 "Where should `org-cycle' emulate TAB.
456 nil Never
457 white Only in completely white lines
458 whitestart Only at the beginning of lines, before the first non-white char
459 t Everywhere except in headlines
460 exc-hl-bol Everywhere except at the start of a headline
461 If TAB is used in a place where it does not emulate TAB, the current subtree
462 visibility is cycled."
463 :group 'org-cycle
464 :type '(choice (const :tag "Never" nil)
465 (const :tag "Only in completely white lines" white)
466 (const :tag "Before first char in a line" whitestart)
467 (const :tag "Everywhere except in headlines" t)
468 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
471 (defcustom org-cycle-separator-lines 2
472 "Number of empty lines needed to keep an empty line between collapsed trees.
473 If you leave an empty line between the end of a subtree and the following
474 headline, this empty line is hidden when the subtree is folded.
475 Org-mode will leave (exactly) one empty line visible if the number of
476 empty lines is equal or larger to the number given in this variable.
477 So the default 2 means, at least 2 empty lines after the end of a subtree
478 are needed to produce free space between a collapsed subtree and the
479 following headline.
481 Special case: when 0, never leave empty lines in collapsed view."
482 :group 'org-cycle
483 :type 'integer)
485 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
486 org-cycle-hide-drawers
487 org-cycle-show-empty-lines
488 org-optimize-window-after-visibility-change)
489 "Hook that is run after `org-cycle' has changed the buffer visibility.
490 The function(s) in this hook must accept a single argument which indicates
491 the new state that was set by the most recent `org-cycle' command. The
492 argument is a symbol. After a global state change, it can have the values
493 `overview', `content', or `all'. After a local state change, it can have
494 the values `folded', `children', or `subtree'."
495 :group 'org-cycle
496 :type 'hook)
498 (defgroup org-edit-structure nil
499 "Options concerning structure editing in Org-mode."
500 :tag "Org Edit Structure"
501 :group 'org-structure)
503 (defcustom org-special-ctrl-a/e nil
504 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
505 When t, `C-a' will bring back the cursor to the beginning of the
506 headline text, i.e. after the stars and after a possible TODO keyword.
507 In an item, this will be the position after the bullet.
508 When the cursor is already at that position, another `C-a' will bring
509 it to the beginning of the line.
510 `C-e' will jump to the end of the headline, ignoring the presence of tags
511 in the headline. A second `C-e' will then jump to the true end of the
512 line, after any tags.
513 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
514 and only a directly following, identical keypress will bring the cursor
515 to the special positions."
516 :group 'org-edit-structure
517 :type '(choice
518 (const :tag "off" nil)
519 (const :tag "after bullet first" t)
520 (const :tag "border first" reversed)))
522 (if (fboundp 'defvaralias)
523 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
525 (defcustom org-special-ctrl-k nil
526 "Non-nil means `C-k' will behave specially in headlines.
527 When nil, `C-k' will call the default `kill-line' command.
528 When t, the following will happen while the cursor is in the headline:
530 - When the cursor is at the beginning of a headline, kill the entire
531 line and possible the folded subtree below the line.
532 - When in the middle of the headline text, kill the headline up to the tags.
533 - When after the headline text, kill the tags."
534 :group 'org-edit-structure
535 :type 'boolean)
537 (defcustom org-odd-levels-only nil
538 "Non-nil means, skip even levels and only use odd levels for the outline.
539 This has the effect that two stars are being added/taken away in
540 promotion/demotion commands. It also influences how levels are
541 handled by the exporters.
542 Changing it requires restart of `font-lock-mode' to become effective
543 for fontification also in regions already fontified.
544 You may also set this on a per-file basis by adding one of the following
545 lines to the buffer:
547 #+STARTUP: odd
548 #+STARTUP: oddeven"
549 :group 'org-edit-structure
550 :group 'org-font-lock
551 :type 'boolean)
553 (defcustom org-adapt-indentation t
554 "Non-nil means, adapt indentation when promoting and demoting.
555 When this is set and the *entire* text in an entry is indented, the
556 indentation is increased by one space in a demotion command, and
557 decreased by one in a promotion command. If any line in the entry
558 body starts at column 0, indentation is not changed at all."
559 :group 'org-edit-structure
560 :type 'boolean)
562 (defcustom org-blank-before-new-entry '((heading . nil)
563 (plain-list-item . nil))
564 "Should `org-insert-heading' leave a blank line before new heading/item?
565 The value is an alist, with `heading' and `plain-list-item' as car,
566 and a boolean flag as cdr."
567 :group 'org-edit-structure
568 :type '(list
569 (cons (const heading) (boolean))
570 (cons (const plain-list-item) (boolean))))
572 (defcustom org-insert-heading-hook nil
573 "Hook being run after inserting a new heading."
574 :group 'org-edit-structure
575 :type 'hook)
577 (defcustom org-enable-fixed-width-editor t
578 "Non-nil means, lines starting with \":\" are treated as fixed-width.
579 This currently only means, they are never auto-wrapped.
580 When nil, such lines will be treated like ordinary lines.
581 See also the QUOTE keyword."
582 :group 'org-edit-structure
583 :type 'boolean)
585 (defcustom org-goto-auto-isearch t
586 "Non-nil means, typing characters in org-goto starts incremental search."
587 :group 'org-edit-structure
588 :type 'boolean)
590 (defgroup org-sparse-trees nil
591 "Options concerning sparse trees in Org-mode."
592 :tag "Org Sparse Trees"
593 :group 'org-structure)
595 (defcustom org-highlight-sparse-tree-matches t
596 "Non-nil means, highlight all matches that define a sparse tree.
597 The highlights will automatically disappear the next time the buffer is
598 changed by an edit command."
599 :group 'org-sparse-trees
600 :type 'boolean)
602 (defcustom org-remove-highlights-with-change t
603 "Non-nil means, any change to the buffer will remove temporary highlights.
604 Such highlights are created by `org-occur' and `org-clock-display'.
605 When nil, `C-c C-c needs to be used to get rid of the highlights.
606 The highlights created by `org-preview-latex-fragment' always need
607 `C-c C-c' to be removed."
608 :group 'org-sparse-trees
609 :group 'org-time
610 :type 'boolean)
613 (defcustom org-occur-hook '(org-first-headline-recenter)
614 "Hook that is run after `org-occur' has constructed a sparse tree.
615 This can be used to recenter the window to show as much of the structure
616 as possible."
617 :group 'org-sparse-trees
618 :type 'hook)
620 (defgroup org-plain-lists nil
621 "Options concerning plain lists in Org-mode."
622 :tag "Org Plain lists"
623 :group 'org-structure)
625 (defcustom org-cycle-include-plain-lists nil
626 "Non-nil means, include plain lists into visibility cycling.
627 This means that during cycling, plain list items will *temporarily* be
628 interpreted as outline headlines with a level given by 1000+i where i is the
629 indentation of the bullet. In all other operations, plain list items are
630 not seen as headlines. For example, you cannot assign a TODO keyword to
631 such an item."
632 :group 'org-plain-lists
633 :type 'boolean)
635 (defcustom org-plain-list-ordered-item-terminator t
636 "The character that makes a line with leading number an ordered list item.
637 Valid values are ?. and ?\). To get both terminators, use t. While
638 ?. may look nicer, it creates the danger that a line with leading
639 number may be incorrectly interpreted as an item. ?\) therefore is
640 the safe choice."
641 :group 'org-plain-lists
642 :type '(choice (const :tag "dot like in \"2.\"" ?.)
643 (const :tag "paren like in \"2)\"" ?\))
644 (const :tab "both" t)))
646 (defcustom org-auto-renumber-ordered-lists t
647 "Non-nil means, automatically renumber ordered plain lists.
648 Renumbering happens when the sequence have been changed with
649 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
650 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
651 :group 'org-plain-lists
652 :type 'boolean)
654 (defcustom org-provide-checkbox-statistics t
655 "Non-nil means, update checkbox statistics after insert and toggle.
656 When this is set, checkbox statistics is updated each time you either insert
657 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
658 with \\[org-ctrl-c-ctrl-c\\]."
659 :group 'org-plain-lists
660 :type 'boolean)
662 (defgroup org-archive nil
663 "Options concerning archiving in Org-mode."
664 :tag "Org Archive"
665 :group 'org-structure)
667 (defcustom org-archive-tag "ARCHIVE"
668 "The tag that marks a subtree as archived.
669 An archived subtree does not open during visibility cycling, and does
670 not contribute to the agenda listings.
671 After changing this, font-lock must be restarted in the relevant buffers to
672 get the proper fontification."
673 :group 'org-archive
674 :group 'org-keywords
675 :type 'string)
677 (defcustom org-agenda-skip-archived-trees t
678 "Non-nil means, the agenda will skip any items located in archived trees.
679 An archived tree is a tree marked with the tag ARCHIVE."
680 :group 'org-archive
681 :group 'org-agenda-skip
682 :type 'boolean)
684 (defcustom org-cycle-open-archived-trees nil
685 "Non-nil means, `org-cycle' will open archived trees.
686 An archived tree is a tree marked with the tag ARCHIVE.
687 When nil, archived trees will stay folded. You can still open them with
688 normal outline commands like `show-all', but not with the cycling commands."
689 :group 'org-archive
690 :group 'org-cycle
691 :type 'boolean)
693 (defcustom org-sparse-tree-open-archived-trees nil
694 "Non-nil means sparse tree construction shows matches in archived trees.
695 When nil, matches in these trees are highlighted, but the trees are kept in
696 collapsed state."
697 :group 'org-archive
698 :group 'org-sparse-trees
699 :type 'boolean)
701 (defcustom org-archive-location "%s_archive::"
702 "The location where subtrees should be archived.
703 This string consists of two parts, separated by a double-colon.
705 The first part is a file name - when omitted, archiving happens in the same
706 file. %s will be replaced by the current file name (without directory part).
707 Archiving to a different file is useful to keep archived entries from
708 contributing to the Org-mode Agenda.
710 The part after the double colon is a headline. The archived entries will be
711 filed under that headline. When omitted, the subtrees are simply filed away
712 at the end of the file, as top-level entries.
714 Here are a few examples:
715 \"%s_archive::\"
716 If the current file is Projects.org, archive in file
717 Projects.org_archive, as top-level trees. This is the default.
719 \"::* Archived Tasks\"
720 Archive in the current file, under the top-level headline
721 \"* Archived Tasks\".
723 \"~/org/archive.org::\"
724 Archive in file ~/org/archive.org (absolute path), as top-level trees.
726 \"basement::** Finished Tasks\"
727 Archive in file ./basement (relative path), as level 3 trees
728 below the level 2 heading \"** Finished Tasks\".
730 You may set this option on a per-file basis by adding to the buffer a
731 line like
733 #+ARCHIVE: basement::** Finished Tasks"
734 :group 'org-archive
735 :type 'string)
737 (defcustom org-archive-mark-done t
738 "Non-nil means, mark entries as DONE when they are moved to the archive file.
739 This can be a string to set the keyword to use. When t, Org-mode will
740 use the first keyword in its list that means done."
741 :group 'org-archive
742 :type '(choice
743 (const :tag "No" nil)
744 (const :tag "Yes" t)
745 (string :tag "Use this keyword")))
747 (defcustom org-archive-stamp-time t
748 "Non-nil means, add a time stamp to entries moved to an archive file.
749 This variable is obsolete and has no effect anymore, instead add ot remove
750 `time' from the variablle `org-archive-save-context-info'."
751 :group 'org-archive
752 :type 'boolean)
754 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
755 "Parts of context info that should be stored as properties when archiving.
756 When a subtree is moved to an archive file, it looses information given by
757 context, like inherited tags, the category, and possibly also the TODO
758 state (depending on the variable `org-archive-mark-done').
759 This variable can be a list of any of the following symbols:
761 time The time of archiving.
762 file The file where the entry originates.
763 itags The local tags, in the headline of the subtree.
764 ltags The tags the subtree inherits from further up the hierarchy.
765 todo The pre-archive TODO state.
766 category The category, taken from file name or #+CATEGORY lines.
767 olpath The outline path to the item. These are all headlines above
768 the current item, separated by /, like a file path.
770 For each symbol present in the list, a property will be created in
771 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
772 information."
773 :group 'org-archive
774 :type '(set :greedy t
775 (const :tag "Time" time)
776 (const :tag "File" file)
777 (const :tag "Category" category)
778 (const :tag "TODO state" todo)
779 (const :tag "TODO state" priority)
780 (const :tag "Inherited tags" itags)
781 (const :tag "Outline path" olpath)
782 (const :tag "Local tags" ltags)))
784 (defgroup org-imenu-and-speedbar nil
785 "Options concerning imenu and speedbar in Org-mode."
786 :tag "Org Imenu and Speedbar"
787 :group 'org-structure)
789 (defcustom org-imenu-depth 2
790 "The maximum level for Imenu access to Org-mode headlines.
791 This also applied for speedbar access."
792 :group 'org-imenu-and-speedbar
793 :type 'number)
795 (defgroup org-table nil
796 "Options concerning tables in Org-mode."
797 :tag "Org Table"
798 :group 'org)
800 (defcustom org-enable-table-editor 'optimized
801 "Non-nil means, lines starting with \"|\" are handled by the table editor.
802 When nil, such lines will be treated like ordinary lines.
804 When equal to the symbol `optimized', the table editor will be optimized to
805 do the following:
806 - Automatic overwrite mode in front of whitespace in table fields.
807 This makes the structure of the table stay in tact as long as the edited
808 field does not exceed the column width.
809 - Minimize the number of realigns. Normally, the table is aligned each time
810 TAB or RET are pressed to move to another field. With optimization this
811 happens only if changes to a field might have changed the column width.
812 Optimization requires replacing the functions `self-insert-command',
813 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
814 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
815 very good at guessing when a re-align will be necessary, but you can always
816 force one with \\[org-ctrl-c-ctrl-c].
818 If you would like to use the optimized version in Org-mode, but the
819 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
821 This variable can be used to turn on and off the table editor during a session,
822 but in order to toggle optimization, a restart is required.
824 See also the variable `org-table-auto-blank-field'."
825 :group 'org-table
826 :type '(choice
827 (const :tag "off" nil)
828 (const :tag "on" t)
829 (const :tag "on, optimized" optimized)))
831 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
832 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
833 In the optimized version, the table editor takes over all simple keys that
834 normally just insert a character. In tables, the characters are inserted
835 in a way to minimize disturbing the table structure (i.e. in overwrite mode
836 for empty fields). Outside tables, the correct binding of the keys is
837 restored.
839 The default for this option is t if the optimized version is also used in
840 Org-mode. See the variable `org-enable-table-editor' for details. Changing
841 this variable requires a restart of Emacs to become effective."
842 :group 'org-table
843 :type 'boolean)
845 (defcustom orgtbl-radio-table-templates
846 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
847 % END RECEIVE ORGTBL %n
848 \\begin{comment}
849 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
850 | | |
851 \\end{comment}\n")
852 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
853 @c END RECEIVE ORGTBL %n
854 @ignore
855 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
856 | | |
857 @end ignore\n")
858 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
859 <!-- END RECEIVE ORGTBL %n -->
860 <!--
861 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
862 | | |
863 -->\n"))
864 "Templates for radio tables in different major modes.
865 All occurrences of %n in a template will be replaced with the name of the
866 table, obtained by prompting the user."
867 :group 'org-table
868 :type '(repeat
869 (list (symbol :tag "Major mode")
870 (string :tag "Format"))))
872 (defgroup org-table-settings nil
873 "Settings for tables in Org-mode."
874 :tag "Org Table Settings"
875 :group 'org-table)
877 (defcustom org-table-default-size "5x2"
878 "The default size for newly created tables, Columns x Rows."
879 :group 'org-table-settings
880 :type 'string)
882 (defcustom org-table-number-regexp
883 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
884 "Regular expression for recognizing numbers in table columns.
885 If a table column contains mostly numbers, it will be aligned to the
886 right. If not, it will be aligned to the left.
888 The default value of this option is a regular expression which allows
889 anything which looks remotely like a number as used in scientific
890 context. For example, all of the following will be considered a
891 number:
892 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
894 Other options offered by the customize interface are more restrictive."
895 :group 'org-table-settings
896 :type '(choice
897 (const :tag "Positive Integers"
898 "^[0-9]+$")
899 (const :tag "Integers"
900 "^[-+]?[0-9]+$")
901 (const :tag "Floating Point Numbers"
902 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
903 (const :tag "Floating Point Number or Integer"
904 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
905 (const :tag "Exponential, Floating point, Integer"
906 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
907 (const :tag "Very General Number-Like, including hex"
908 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
909 (string :tag "Regexp:")))
911 (defcustom org-table-number-fraction 0.5
912 "Fraction of numbers in a column required to make the column align right.
913 In a column all non-white fields are considered. If at least this
914 fraction of fields is matched by `org-table-number-fraction',
915 alignment to the right border applies."
916 :group 'org-table-settings
917 :type 'number)
919 (defgroup org-table-editing nil
920 "Behavior of tables during editing in Org-mode."
921 :tag "Org Table Editing"
922 :group 'org-table)
924 (defcustom org-table-automatic-realign t
925 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
926 When nil, aligning is only done with \\[org-table-align], or after column
927 removal/insertion."
928 :group 'org-table-editing
929 :type 'boolean)
931 (defcustom org-table-auto-blank-field t
932 "Non-nil means, automatically blank table field when starting to type into it.
933 This only happens when typing immediately after a field motion
934 command (TAB, S-TAB or RET).
935 Only relevant when `org-enable-table-editor' is equal to `optimized'."
936 :group 'org-table-editing
937 :type 'boolean)
939 (defcustom org-table-tab-jumps-over-hlines t
940 "Non-nil means, tab in the last column of a table with jump over a hline.
941 If a horizontal separator line is following the current line,
942 `org-table-next-field' can either create a new row before that line, or jump
943 over the line. When this option is nil, a new line will be created before
944 this line."
945 :group 'org-table-editing
946 :type 'boolean)
948 (defcustom org-table-tab-recognizes-table.el t
949 "Non-nil means, TAB will automatically notice a table.el table.
950 When it sees such a table, it moves point into it and - if necessary -
951 calls `table-recognize-table'."
952 :group 'org-table-editing
953 :type 'boolean)
955 (defgroup org-table-calculation nil
956 "Options concerning tables in Org-mode."
957 :tag "Org Table Calculation"
958 :group 'org-table)
960 (defcustom org-table-use-standard-references t
961 "Should org-mode work with table refrences like B3 instead of @3$2?
962 Possible values are:
963 nil never use them
964 from accept as input, do not present for editing
965 t: accept as input and present for editing"
966 :group 'org-table-calculation
967 :type '(choice
968 (const :tag "Never, don't even check unser input for them" nil)
969 (const :tag "Always, both as user input, and when editing" t)
970 (const :tag "Convert user input, don't offer during editing" 'from)))
972 (defcustom org-table-copy-increment t
973 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
974 :group 'org-table-calculation
975 :type 'boolean)
977 (defcustom org-calc-default-modes
978 '(calc-internal-prec 12
979 calc-float-format (float 5)
980 calc-angle-mode deg
981 calc-prefer-frac nil
982 calc-symbolic-mode nil
983 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
984 calc-display-working-message t
986 "List with Calc mode settings for use in calc-eval for table formulas.
987 The list must contain alternating symbols (Calc modes variables and values).
988 Don't remove any of the default settings, just change the values. Org-mode
989 relies on the variables to be present in the list."
990 :group 'org-table-calculation
991 :type 'plist)
993 (defcustom org-table-formula-evaluate-inline t
994 "Non-nil means, TAB and RET evaluate a formula in current table field.
995 If the current field starts with an equal sign, it is assumed to be a formula
996 which should be evaluated as described in the manual and in the documentation
997 string of the command `org-table-eval-formula'. This feature requires the
998 Emacs calc package.
999 When this variable is nil, formula calculation is only available through
1000 the command \\[org-table-eval-formula]."
1001 :group 'org-table-calculation
1002 :type 'boolean)
1004 (defcustom org-table-formula-use-constants t
1005 "Non-nil means, interpret constants in formulas in tables.
1006 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1007 by the value given in `org-table-formula-constants', or by a value obtained
1008 from the `constants.el' package."
1009 :group 'org-table-calculation
1010 :type 'boolean)
1012 (defcustom org-table-formula-constants nil
1013 "Alist with constant names and values, for use in table formulas.
1014 The car of each element is a name of a constant, without the `$' before it.
1015 The cdr is the value as a string. For example, if you'd like to use the
1016 speed of light in a formula, you would configure
1018 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1020 and then use it in an equation like `$1*$c'.
1022 Constants can also be defined on a per-file basis using a line like
1024 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1025 :group 'org-table-calculation
1026 :type '(repeat
1027 (cons (string :tag "name")
1028 (string :tag "value"))))
1030 (defvar org-table-formula-constants-local nil
1031 "Local version of `org-table-formula-constants'.")
1032 (make-variable-buffer-local 'org-table-formula-constants-local)
1034 (defcustom org-table-allow-automatic-line-recalculation t
1035 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1036 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1037 :group 'org-table-calculation
1038 :type 'boolean)
1040 (defgroup org-link nil
1041 "Options concerning links in Org-mode."
1042 :tag "Org Link"
1043 :group 'org)
1045 (defvar org-link-abbrev-alist-local nil
1046 "Buffer-local version of `org-link-abbrev-alist', which see.
1047 The value of this is taken from the #+LINK lines.")
1048 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1050 (defcustom org-link-abbrev-alist nil
1051 "Alist of link abbreviations.
1052 The car of each element is a string, to be replaced at the start of a link.
1053 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1054 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1056 [[linkkey:tag][description]]
1058 If REPLACE is a string, the tag will simply be appended to create the link.
1059 If the string contains \"%s\", the tag will be inserted there.
1061 REPLACE may also be a function that will be called with the tag as the
1062 only argument to create the link, which should be returned as a string.
1064 See the manual for examples."
1065 :group 'org-link
1066 :type 'alist)
1068 (defcustom org-descriptive-links t
1069 "Non-nil means, hide link part and only show description of bracket links.
1070 Bracket links are like [[link][descritpion]]. This variable sets the initial
1071 state in new org-mode buffers. The setting can then be toggled on a
1072 per-buffer basis from the Org->Hyperlinks menu."
1073 :group 'org-link
1074 :type 'boolean)
1076 (defcustom org-link-file-path-type 'adaptive
1077 "How the path name in file links should be stored.
1078 Valid values are:
1080 relative Relative to the current directory, i.e. the directory of the file
1081 into which the link is being inserted.
1082 absolute Absolute path, if possible with ~ for home directory.
1083 noabbrev Absolute path, no abbreviation of home directory.
1084 adaptive Use relative path for files in the current directory and sub-
1085 directories of it. For other files, use an absolute path."
1086 :group 'org-link
1087 :type '(choice
1088 (const relative)
1089 (const absolute)
1090 (const noabbrev)
1091 (const adaptive)))
1093 (defcustom org-activate-links '(bracket angle plain radio tag date)
1094 "Types of links that should be activated in Org-mode files.
1095 This is a list of symbols, each leading to the activation of a certain link
1096 type. In principle, it does not hurt to turn on most link types - there may
1097 be a small gain when turning off unused link types. The types are:
1099 bracket The recommended [[link][description]] or [[link]] links with hiding.
1100 angular Links in angular brackes that may contain whitespace like
1101 <bbdb:Carsten Dominik>.
1102 plain Plain links in normal text, no whitespace, like http://google.com.
1103 radio Text that is matched by a radio target, see manual for details.
1104 tag Tag settings in a headline (link to tag search).
1105 date Time stamps (link to calendar).
1107 Changing this variable requires a restart of Emacs to become effective."
1108 :group 'org-link
1109 :type '(set (const :tag "Double bracket links (new style)" bracket)
1110 (const :tag "Angular bracket links (old style)" angular)
1111 (const :tag "plain text links" plain)
1112 (const :tag "Radio target matches" radio)
1113 (const :tag "Tags" tag)
1114 (const :tag "Tags" target)
1115 (const :tag "Timestamps" date)))
1117 (defgroup org-link-store nil
1118 "Options concerning storing links in Org-mode"
1119 :tag "Org Store Link"
1120 :group 'org-link)
1122 (defcustom org-email-link-description-format "Email %c: %.30s"
1123 "Format of the description part of a link to an email or usenet message.
1124 The following %-excapes will be replaced by corresponding information:
1126 %F full \"From\" field
1127 %f name, taken from \"From\" field, address if no name
1128 %T full \"To\" field
1129 %t first name in \"To\" field, address if no name
1130 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1131 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1132 %s subject
1133 %m message-id.
1135 You may use normal field width specification between the % and the letter.
1136 This is for example useful to limit the length of the subject.
1138 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1139 :group 'org-link-store
1140 :type 'string)
1142 (defcustom org-from-is-user-regexp
1143 (let (r1 r2)
1144 (when (and user-mail-address (not (string= user-mail-address "")))
1145 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1146 (when (and user-full-name (not (string= user-full-name "")))
1147 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1148 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1149 "Regexp mached against the \"From:\" header of an email or usenet message.
1150 It should match if the message is from the user him/herself."
1151 :group 'org-link-store
1152 :type 'regexp)
1154 (defcustom org-context-in-file-links t
1155 "Non-nil means, file links from `org-store-link' contain context.
1156 A search string will be added to the file name with :: as separator and
1157 used to find the context when the link is activated by the command
1158 `org-open-at-point'.
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 (defcustom org-keep-stored-link-after-insertion nil
1165 "Non-nil means, keep link in list for entire session.
1167 The command `org-store-link' adds a link pointing to the current
1168 location to an internal list. These links accumulate during a session.
1169 The command `org-insert-link' can be used to insert links into any
1170 Org-mode file (offering completion for all stored links). When this
1171 option is nil, every link which has been inserted once using \\[org-insert-link]
1172 will be removed from the list, to make completing the unused links
1173 more efficient."
1174 :group 'org-link-store
1175 :type 'boolean)
1177 (defcustom org-usenet-links-prefer-google nil
1178 "Non-nil means, `org-store-link' will create web links to Google groups.
1179 When nil, Gnus will be used for such links.
1180 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1181 negates this setting for the duration of the command."
1182 :group 'org-link-store
1183 :type 'boolean)
1185 (defgroup org-link-follow nil
1186 "Options concerning following links in Org-mode"
1187 :tag "Org Follow Link"
1188 :group 'org-link)
1190 (defcustom org-tab-follows-link nil
1191 "Non-nil means, on links TAB will follow the link.
1192 Needs to be set before org.el is loaded."
1193 :group 'org-link-follow
1194 :type 'boolean)
1196 (defcustom org-return-follows-link nil
1197 "Non-nil means, on links RET will follow the link.
1198 Needs to be set before org.el is loaded."
1199 :group 'org-link-follow
1200 :type 'boolean)
1202 (defcustom org-mouse-1-follows-link t
1203 "Non-nil means, mouse-1 on a link will follow the link.
1204 A longer mouse click will still set point. Does not wortk on XEmacs.
1205 Needs to be set before org.el is loaded."
1206 :group 'org-link-follow
1207 :type 'boolean)
1209 (defcustom org-mark-ring-length 4
1210 "Number of different positions to be recorded in the ring
1211 Changing this requires a restart of Emacs to work correctly."
1212 :group 'org-link-follow
1213 :type 'interger)
1215 (defcustom org-link-frame-setup
1216 '((vm . vm-visit-folder-other-frame)
1217 (gnus . gnus-other-frame)
1218 (file . find-file-other-window))
1219 "Setup the frame configuration for following links.
1220 When following a link with Emacs, it may often be useful to display
1221 this link in another window or frame. This variable can be used to
1222 set this up for the different types of links.
1223 For VM, use any of
1224 `vm-visit-folder'
1225 `vm-visit-folder-other-frame'
1226 For Gnus, use any of
1227 `gnus'
1228 `gnus-other-frame'
1229 For FILE, use any of
1230 `find-file'
1231 `find-file-other-window'
1232 `find-file-other-frame'
1233 For the calendar, use the variable `calendar-setup'.
1234 For BBDB, it is currently only possible to display the matches in
1235 another window."
1236 :group 'org-link-follow
1237 :type '(list
1238 (cons (const vm)
1239 (choice
1240 (const vm-visit-folder)
1241 (const vm-visit-folder-other-window)
1242 (const vm-visit-folder-other-frame)))
1243 (cons (const gnus)
1244 (choice
1245 (const gnus)
1246 (const gnus-other-frame)))
1247 (cons (const file)
1248 (choice
1249 (const find-file)
1250 (const find-file-other-window)
1251 (const find-file-other-frame)))))
1253 (defcustom org-display-internal-link-with-indirect-buffer nil
1254 "Non-nil means, use indirect buffer to display infile links.
1255 Activating internal links (from one location in a file to another location
1256 in the same file) normally just jumps to the location. When the link is
1257 activated with a C-u prefix (or with mouse-3), the link is displayed in
1258 another window. When this option is set, the other window actually displays
1259 an indirect buffer clone of the current buffer, to avoid any visibility
1260 changes to the current buffer."
1261 :group 'org-link-follow
1262 :type 'boolean)
1264 (defcustom org-open-non-existing-files nil
1265 "Non-nil means, `org-open-file' will open non-existing files.
1266 When nil, an error will be generated."
1267 :group 'org-link-follow
1268 :type 'boolean)
1270 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1271 "Function and arguments to call for following mailto links.
1272 This is a list with the first element being a lisp function, and the
1273 remaining elements being arguments to the function. In string arguments,
1274 %a will be replaced by the address, and %s will be replaced by the subject
1275 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1276 :group 'org-link-follow
1277 :type '(choice
1278 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1279 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1280 (const :tag "message-mail" (message-mail "%a" "%s"))
1281 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1283 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1284 "Non-nil means, ask for confirmation before executing shell links.
1285 Shell links can be dangerous: just think about a link
1287 [[shell:rm -rf ~/*][Google Search]]
1289 This link would show up in your Org-mode document as \"Google Search\",
1290 but really it would remove your entire home directory.
1291 Therefore we advise against setting this variable to nil.
1292 Just change it to `y-or-n-p' of you want to confirm with a
1293 single keystroke rather than having to type \"yes\"."
1294 :group 'org-link-follow
1295 :type '(choice
1296 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1297 (const :tag "with y-or-n (faster)" y-or-n-p)
1298 (const :tag "no confirmation (dangerous)" nil)))
1300 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1301 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1302 Elisp links can be dangerous: just think about a link
1304 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1306 This link would show up in your Org-mode document as \"Google Search\",
1307 but really it would remove your entire home directory.
1308 Therefore we advise against setting this variable to nil.
1309 Just change it to `y-or-n-p' of you want to confirm with a
1310 single keystroke rather than having to type \"yes\"."
1311 :group 'org-link-follow
1312 :type '(choice
1313 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1314 (const :tag "with y-or-n (faster)" y-or-n-p)
1315 (const :tag "no confirmation (dangerous)" nil)))
1317 (defconst org-file-apps-defaults-gnu
1318 '((remote . emacs)
1319 (t . mailcap))
1320 "Default file applications on a UNIX or GNU/Linux system.
1321 See `org-file-apps'.")
1323 (defconst org-file-apps-defaults-macosx
1324 '((remote . emacs)
1325 (t . "open %s")
1326 ("ps" . "gv %s")
1327 ("ps.gz" . "gv %s")
1328 ("eps" . "gv %s")
1329 ("eps.gz" . "gv %s")
1330 ("dvi" . "xdvi %s")
1331 ("fig" . "xfig %s"))
1332 "Default file applications on a MacOS X system.
1333 The system \"open\" is known as a default, but we use X11 applications
1334 for some files for which the OS does not have a good default.
1335 See `org-file-apps'.")
1337 (defconst org-file-apps-defaults-windowsnt
1338 (list
1339 '(remote . emacs)
1340 (cons t
1341 (list (if (featurep 'xemacs)
1342 'mswindows-shell-execute
1343 'w32-shell-execute)
1344 "open" 'file)))
1345 "Default file applications on a Windows NT system.
1346 The system \"open\" is used for most files.
1347 See `org-file-apps'.")
1349 (defcustom org-file-apps
1351 ("txt" . emacs)
1352 ("tex" . emacs)
1353 ("ltx" . emacs)
1354 ("org" . emacs)
1355 ("el" . emacs)
1356 ("bib" . emacs)
1358 "External applications for opening `file:path' items in a document.
1359 Org-mode uses system defaults for different file types, but
1360 you can use this variable to set the application for a given file
1361 extension. The entries in this list are cons cells where the car identifies
1362 files and the cdr the corresponding command. Possible values for the
1363 file identifier are
1364 \"ext\" A string identifying an extension
1365 `directory' Matches a directory
1366 `remote' Matches a remote file, accessible through tramp or efs.
1367 Remote files most likely should be visited through Emacs
1368 because external applications cannot handle such paths.
1369 t Default for all remaining files
1371 Possible values for the command are:
1372 `emacs' The file will be visited by the current Emacs process.
1373 `default' Use the default application for this file type.
1374 string A command to be executed by a shell; %s will be replaced
1375 by the path to the file.
1376 sexp A Lisp form which will be evaluated. The file path will
1377 be available in the Lisp variable `file'.
1378 For more examples, see the system specific constants
1379 `org-file-apps-defaults-macosx'
1380 `org-file-apps-defaults-windowsnt'
1381 `org-file-apps-defaults-gnu'."
1382 :group 'org-link-follow
1383 :type '(repeat
1384 (cons (choice :value ""
1385 (string :tag "Extension")
1386 (const :tag "Default for unrecognized files" t)
1387 (const :tag "Remote file" remote)
1388 (const :tag "Links to a directory" directory))
1389 (choice :value ""
1390 (const :tag "Visit with Emacs" emacs)
1391 (const :tag "Use system default" default)
1392 (string :tag "Command")
1393 (sexp :tag "Lisp form")))))
1395 (defcustom org-mhe-search-all-folders nil
1396 "Non-nil means, that the search for the mh-message will be extended to
1397 all folders if the message cannot be found in the folder given in the link.
1398 Searching all folders is very efficient with one of the search engines
1399 supported by MH-E, but will be slow with pick."
1400 :group 'org-link-follow
1401 :type 'boolean)
1403 (defgroup org-remember nil
1404 "Options concerning interaction with remember.el."
1405 :tag "Org Remember"
1406 :group 'org)
1408 (defcustom org-directory "~/org"
1409 "Directory with org files.
1410 This directory will be used as default to prompt for org files.
1411 Used by the hooks for remember.el."
1412 :group 'org-remember
1413 :type 'directory)
1415 (defcustom org-default-notes-file "~/.notes"
1416 "Default target for storing notes.
1417 Used by the hooks for remember.el. This can be a string, or nil to mean
1418 the value of `remember-data-file'.
1419 You can set this on a per-template basis with the variable
1420 `org-remember-templates'."
1421 :group 'org-remember
1422 :type '(choice
1423 (const :tag "Default from remember-data-file" nil)
1424 file))
1426 (defcustom org-remember-store-without-prompt t
1427 "Non-nil means, `C-c C-c' stores remember note without further promts.
1428 In this case, you need `C-u C-c C-c' to get the prompts for
1429 note file and headline.
1430 When this variable is nil, `C-c C-c' give you the prompts, and
1431 `C-u C-c C-c' trigger the fasttrack."
1432 :group 'org-remember
1433 :type 'boolean)
1435 (defcustom org-remember-interactive-interface 'refile
1436 "The interface to be used for interactive filing of remember notes.
1437 This is only used when the interactive mode for selecting a filing
1438 location is used (see the variable `org-remember-store-without-prompt').
1439 Allowed vaues are:
1440 outline The interface shows an outline of the relevant file
1441 and the correct heading is found by moving through
1442 the outline or by searching with incremental search.
1443 outline-path-completion Headlines in the current buffer are offered via
1444 completion.
1445 refile Use the refile interface, and offer headlines,
1446 possibly from different buffers."
1447 :group 'org-remember
1448 :type '(choice
1449 (const :tag "Refile" refile)
1450 (const :tag "Outline" outline)
1451 (const :tag "Outline-path-completion" outline-path-completion)))
1453 (defcustom org-goto-interface 'outline
1454 "The default interface to be used for `org-goto'.
1455 Allowed vaues are:
1456 outline The interface shows an outline of the relevant file
1457 and the correct heading is found by moving through
1458 the outline or by searching with incremental search.
1459 outline-path-completion Headlines in the current buffer are offered via
1460 completion."
1461 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1462 :type '(choice
1463 (const :tag "Outline" outline)
1464 (const :tag "Outline-path-completion" outline-path-completion)))
1466 (defcustom org-remember-default-headline ""
1467 "The headline that should be the default location in the notes file.
1468 When filing remember notes, the cursor will start at that position.
1469 You can set this on a per-template basis with the variable
1470 `org-remember-templates'."
1471 :group 'org-remember
1472 :type 'string)
1474 (defcustom org-remember-templates nil
1475 "Templates for the creation of remember buffers.
1476 When nil, just let remember make the buffer.
1477 When not nil, this is a list of 5-element lists. In each entry, the first
1478 element is the name of the template, which should be a single short word.
1479 The second element is a character, a unique key to select this template.
1480 The third element is the template. The fourth element is optional and can
1481 specify a destination file for remember items created with this template.
1482 The default file is given by `org-default-notes-file'. An optional fifth
1483 element can specify the headline in that file that should be offered
1484 first when the user is asked to file the entry. The default headline is
1485 given in the variable `org-remember-default-headline'.
1487 The template specifies the structure of the remember buffer. It should have
1488 a first line starting with a star, to act as the org-mode headline.
1489 Furthermore, the following %-escapes will be replaced with content:
1491 %^{prompt} Prompt the user for a string and replace this sequence with it.
1492 A default value and a completion table ca be specified like this:
1493 %^{prompt|default|completion2|completion3|...}
1494 %t time stamp, date only
1495 %T time stamp with date and time
1496 %u, %U like the above, but inactive time stamps
1497 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1498 You may define a prompt like %^{Please specify birthday}t
1499 %n user name (taken from `user-full-name')
1500 %a annotation, normally the link created with org-store-link
1501 %i initial content, the region when remember is called with C-u.
1502 If %i is indented, the entire inserted text will be indented
1503 as well.
1504 %c content of the clipboard, or current kill ring head
1505 %^g prompt for tags, with completion on tags in target file
1506 %^G prompt for tags, with completion all tags in all agenda files
1507 %:keyword specific information for certain link types, see below
1508 %[pathname] insert the contents of the file given by `pathname'
1509 %(sexp) evaluate elisp `(sexp)' and replace with the result
1510 %! Store this note immediately after filling the template
1512 %? After completing the template, position cursor here.
1514 Apart from these general escapes, you can access information specific to the
1515 link type that is created. For example, calling `remember' in emails or gnus
1516 will record the author and the subject of the message, which you can access
1517 with %:author and %:subject, respectively. Here is a complete list of what
1518 is recorded for each link type.
1520 Link type | Available information
1521 -------------------+------------------------------------------------------
1522 bbdb | %:type %:name %:company
1523 vm, wl, mh, rmail | %:type %:subject %:message-id
1524 | %:from %:fromname %:fromaddress
1525 | %:to %:toname %:toaddress
1526 | %:fromto (either \"to NAME\" or \"from NAME\")
1527 gnus | %:group, for messages also all email fields
1528 w3, w3m | %:type %:url
1529 info | %:type %:file %:node
1530 calendar | %:type %:date"
1531 :group 'org-remember
1532 :get (lambda (var) ; Make sure all entries have 5 elements
1533 (mapcar (lambda (x)
1534 (if (not (stringp (car x))) (setq x (cons "" x)))
1535 (cond ((= (length x) 4) (append x '("")))
1536 ((= (length x) 3) (append x '("" "")))
1537 (t x)))
1538 (default-value var)))
1539 :type '(repeat
1540 :tag "enabled"
1541 (list :value ("" ?a "\n" nil nil)
1542 (string :tag "Name")
1543 (character :tag "Selection Key")
1544 (string :tag "Template")
1545 (choice
1546 (file :tag "Destination file")
1547 (const :tag "Prompt for file" nil))
1548 (choice
1549 (string :tag "Destination headline")
1550 (const :tag "Selection interface for heading")))))
1552 (defcustom org-reverse-note-order nil
1553 "Non-nil means, store new notes at the beginning of a file or entry.
1554 When nil, new notes will be filed to the end of a file or entry.
1555 This can also be a list with cons cells of regular expressions that
1556 are matched against file names, and values."
1557 :group 'org-remember
1558 :type '(choice
1559 (const :tag "Reverse always" t)
1560 (const :tag "Reverse never" nil)
1561 (repeat :tag "By file name regexp"
1562 (cons regexp boolean))))
1564 (defcustom org-refile-targets nil
1565 "Targets for refiling entries with \\[org-refile].
1566 This is list of cons cells. Each cell contains:
1567 - a specification of the files to be considered, either a list of files,
1568 or a symbol whose function or value fields will be used to retrieve
1569 a file name or a list of file names. Nil means, refile to a different
1570 heading in the current buffer.
1571 - A specification of how to find candidate refile targets. This may be
1572 any of
1573 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1574 This tag has to be present in all target headlines, inheritance will
1575 not be considered.
1576 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1577 todo keyword.
1578 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1579 headlines that are refiling targets.
1580 - a cons cell (:level . N). Any headline of level N is considered a target.
1581 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1582 ;; FIXME: what if there are a var and func with same name???
1583 :group 'org-remember
1584 :type '(repeat
1585 (cons
1586 (choice :value org-agenda-files
1587 (const :tag "All agenda files" org-agenda-files)
1588 (const :tag "Current buffer" nil)
1589 (function) (variable) (file))
1590 (choice :tag "Identify target headline by"
1591 (cons :tag "Specific tag" (const :tag) (string))
1592 (cons :tag "TODO keyword" (const :todo) (string))
1593 (cons :tag "Regular expression" (const :regexp) (regexp))
1594 (cons :tag "Level number" (const :level) (integer))
1595 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1597 (defcustom org-refile-use-outline-path nil
1598 "Non-nil means, provide refile targets as paths.
1599 So a level 3 headline will be available as level1/level2/level3.
1600 When the value is `file', also include the file name (without directory)
1601 into the path. When `full-file-path', include the full file path."
1602 :group 'org-remember
1603 :type '(choice
1604 (const :tag "Not" nil)
1605 (const :tag "Yes" t)
1606 (const :tag "Start with file name" file)
1607 (const :tag "Start with full file path" full-file-path)))
1609 (defgroup org-todo nil
1610 "Options concerning TODO items in Org-mode."
1611 :tag "Org TODO"
1612 :group 'org)
1614 (defgroup org-progress nil
1615 "Options concerning Progress logging in Org-mode."
1616 :tag "Org Progress"
1617 :group 'org-time)
1619 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1620 "List of TODO entry keyword sequences and their interpretation.
1621 \\<org-mode-map>This is a list of sequences.
1623 Each sequence starts with a symbol, either `sequence' or `type',
1624 indicating if the keywords should be interpreted as a sequence of
1625 action steps, or as different types of TODO items. The first
1626 keywords are states requiring action - these states will select a headline
1627 for inclusion into the global TODO list Org-mode produces. If one of
1628 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1629 signify that no further action is necessary. If \"|\" is not found,
1630 the last keyword is treated as the only DONE state of the sequence.
1632 The command \\[org-todo] cycles an entry through these states, and one
1633 additional state where no keyword is present. For details about this
1634 cycling, see the manual.
1636 TODO keywords and interpretation can also be set on a per-file basis with
1637 the special #+SEQ_TODO and #+TYP_TODO lines.
1639 For backward compatibility, this variable may also be just a list
1640 of keywords - in this case the interptetation (sequence or type) will be
1641 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1642 :group 'org-todo
1643 :group 'org-keywords
1644 :type '(choice
1645 (repeat :tag "Old syntax, just keywords"
1646 (string :tag "Keyword"))
1647 (repeat :tag "New syntax"
1648 (cons
1649 (choice
1650 :tag "Interpretation"
1651 (const :tag "Sequence (cycling hits every state)" sequence)
1652 (const :tag "Type (cycling directly to DONE)" type))
1653 (repeat
1654 (string :tag "Keyword"))))))
1656 (defvar org-todo-keywords-1 nil)
1657 (make-variable-buffer-local 'org-todo-keywords-1)
1658 (defvar org-todo-keywords-for-agenda nil)
1659 (defvar org-done-keywords-for-agenda nil)
1660 (defvar org-not-done-keywords nil)
1661 (make-variable-buffer-local 'org-not-done-keywords)
1662 (defvar org-done-keywords nil)
1663 (make-variable-buffer-local 'org-done-keywords)
1664 (defvar org-todo-heads nil)
1665 (make-variable-buffer-local 'org-todo-heads)
1666 (defvar org-todo-sets nil)
1667 (make-variable-buffer-local 'org-todo-sets)
1668 (defvar org-todo-log-states nil)
1669 (make-variable-buffer-local 'org-todo-log-states)
1670 (defvar org-todo-kwd-alist nil)
1671 (make-variable-buffer-local 'org-todo-kwd-alist)
1672 (defvar org-todo-key-alist nil)
1673 (make-variable-buffer-local 'org-todo-key-alist)
1674 (defvar org-todo-key-trigger nil)
1675 (make-variable-buffer-local 'org-todo-key-trigger)
1677 (defcustom org-todo-interpretation 'sequence
1678 "Controls how TODO keywords are interpreted.
1679 This variable is in principle obsolete and is only used for
1680 backward compatibility, if the interpretation of todo keywords is
1681 not given already in `org-todo-keywords'. See that variable for
1682 more information."
1683 :group 'org-todo
1684 :group 'org-keywords
1685 :type '(choice (const sequence)
1686 (const type)))
1688 (defcustom org-use-fast-todo-selection 'prefix
1689 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1690 This variable describes if and under what circumstances the cycling
1691 mechanism for TODO keywords will be replaced by a single-key, direct
1692 selection scheme.
1694 When nil, fast selection is never used.
1696 When the symbol `prefix', it will be used when `org-todo' is called with
1697 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1698 in an agenda buffer.
1700 When t, fast selection is used by default. In this case, the prefix
1701 argument forces cycling instead.
1703 In all cases, the special interface is only used if access keys have actually
1704 been assigned by the user, i.e. if keywords in the configuration are followed
1705 by a letter in parenthesis, like TODO(t)."
1706 :group 'org-todo
1707 :type '(choice
1708 (const :tag "Never" nil)
1709 (const :tag "By default" t)
1710 (const :tag "Only with C-u C-c C-t" prefix)))
1712 (defcustom org-after-todo-state-change-hook nil
1713 "Hook which is run after the state of a TODO item was changed.
1714 The new state (a string with a TODO keyword, or nil) is available in the
1715 Lisp variable `state'."
1716 :group 'org-todo
1717 :type 'hook)
1719 (defcustom org-log-done nil
1720 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1721 When the state of an entry is changed from nothing or a DONE state to
1722 a not-done TODO state, remove a previous closing date.
1724 This can also be a list of symbols indicating under which conditions
1725 the time stamp recording the action should be annotated with a short note.
1726 Valid members of this list are
1728 done Offer to record a note when marking entries done
1729 state Offer to record a note whenever changing the TODO state
1730 of an item. This is only relevant if TODO keywords are
1731 interpreted as sequence, see variable `org-todo-interpretation'.
1732 When `state' is set, this includes tracking `done'.
1733 clock-out Offer to record a note when clocking out of an item.
1735 A separate window will then pop up and allow you to type a note.
1736 After finishing with C-c C-c, the note will be added directly after the
1737 timestamp, as a plain list item. See also the variable
1738 `org-log-note-headings'.
1740 Logging can also be configured on a per-file basis by adding one of
1741 the following lines anywhere in the buffer:
1743 #+STARTUP: logdone
1744 #+STARTUP: nologging
1745 #+STARTUP: lognotedone
1746 #+STARTUP: lognotestate
1747 #+STARTUP: lognoteclock-out
1749 You can have local logging settings for a subtree by setting the LOGGING
1750 property to one or more of these keywords."
1751 :group 'org-todo
1752 :group 'org-progress
1753 :type '(choice
1754 (const :tag "off" nil)
1755 (const :tag "on" t)
1756 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1757 (const :tag "when item is marked DONE" done)
1758 (const :tag "when TODO state changes" state)
1759 (const :tag "when clocking out" clock-out))))
1761 (defcustom org-log-done-with-time t
1762 "Non-nil means, the CLOSED time stamp will contain date and time.
1763 When nil, only the date will be recorded."
1764 :group 'org-progress
1765 :type 'boolean)
1767 (defcustom org-log-note-headings
1768 '((done . "CLOSING NOTE %t")
1769 (state . "State %-12s %t")
1770 (clock-out . ""))
1771 "Headings for notes added when clocking out or closing TODO items.
1772 The value is an alist, with the car being a symbol indicating the note
1773 context, and the cdr is the heading to be used. The heading may also be the
1774 empty string.
1775 %t in the heading will be replaced by a time stamp.
1776 %s will be replaced by the new TODO state, in double quotes.
1777 %u will be replaced by the user name.
1778 %U will be replaced by the full user name."
1779 :group 'org-todo
1780 :group 'org-progress
1781 :type '(list :greedy t
1782 (cons (const :tag "Heading when closing an item" done) string)
1783 (cons (const :tag
1784 "Heading when changing todo state (todo sequence only)"
1785 state) string)
1786 (cons (const :tag "Heading when clocking out" clock-out) string)))
1788 (defcustom org-log-states-order-reversed t
1789 "Non-nil means, the latest state change note will be directly after heading.
1790 When nil, the notes will be orderer according to time."
1791 :group 'org-todo
1792 :group 'org-progress
1793 :type 'boolean)
1795 (defcustom org-log-repeat t
1796 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1797 When nil, no note will be taken.
1798 This option can also be set with on a per-file-basis with
1800 #+STARTUP: logrepeat
1801 #+STARTUP: nologrepeat
1803 You can have local logging settings for a subtree by setting the LOGGING
1804 property to one or more of these keywords."
1805 :group 'org-todo
1806 :group 'org-progress
1807 :type 'boolean)
1809 (defcustom org-clock-into-drawer 2
1810 "Should clocking info be wrapped into a drawer?
1811 When t, clocking info will always be inserted into a :CLOCK: drawer.
1812 If necessary, the drawer will be created.
1813 When nil, the drawer will not be created, but used when present.
1814 When an integer and the number of clocking entries in an item
1815 reaches or exceeds this number, a drawer will be created."
1816 :group 'org-todo
1817 :group 'org-progress
1818 :type '(choice
1819 (const :tag "Always" t)
1820 (const :tag "Only when drawer exists" nil)
1821 (integer :tag "When at least N clock entries")))
1823 (defcustom org-clock-out-when-done t
1824 "When t, the clock will be stopped when the relevant entry is marked DONE.
1825 Nil means, clock will keep running until stopped explicitly with
1826 `C-c C-x C-o', or until the clock is started in a different item."
1827 :group 'org-progress
1828 :type 'boolean)
1830 (defcustom org-clock-in-switch-to-state nil
1831 "Set task to a special todo state while clocking it.
1832 The value should be the state to which the entry should be switched."
1833 :group 'org-progress
1834 :group 'org-todo
1835 :type '(choice
1836 (const :tag "Don't force a state" nil)
1837 (string :tag "State")))
1839 (defgroup org-priorities nil
1840 "Priorities in Org-mode."
1841 :tag "Org Priorities"
1842 :group 'org-todo)
1844 (defcustom org-highest-priority ?A
1845 "The highest priority of TODO items. A character like ?A, ?B etc.
1846 Must have a smaller ASCII number than `org-lowest-priority'."
1847 :group 'org-priorities
1848 :type 'character)
1850 (defcustom org-lowest-priority ?C
1851 "The lowest priority of TODO items. A character like ?A, ?B etc.
1852 Must have a larger ASCII number than `org-highest-priority'."
1853 :group 'org-priorities
1854 :type 'character)
1856 (defcustom org-default-priority ?B
1857 "The default priority of TODO items.
1858 This is the priority an item get if no explicit priority is given."
1859 :group 'org-priorities
1860 :type 'character)
1862 (defcustom org-priority-start-cycle-with-default t
1863 "Non-nil means, start with default priority when starting to cycle.
1864 When this is nil, the first step in the cycle will be (depending on the
1865 command used) one higher or lower that the default priority."
1866 :group 'org-priorities
1867 :type 'boolean)
1869 (defgroup org-time nil
1870 "Options concerning time stamps and deadlines in Org-mode."
1871 :tag "Org Time"
1872 :group 'org)
1874 (defcustom org-insert-labeled-timestamps-at-point nil
1875 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1876 When nil, these labeled time stamps are forces into the second line of an
1877 entry, just after the headline. When scheduling from the global TODO list,
1878 the time stamp will always be forced into the second line."
1879 :group 'org-time
1880 :type 'boolean)
1882 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1883 "Formats for `format-time-string' which are used for time stamps.
1884 It is not recommended to change this constant.")
1886 (defcustom org-time-stamp-rounding-minutes 0
1887 "Number of minutes to round time stamps to upon insertion.
1888 When zero, insert the time unmodified. Useful rounding numbers
1889 should be factors of 60, so for example 5, 10, 15.
1890 When this is not zero, you can still force an exact time-stamp by using
1891 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1892 :group 'org-time
1893 :type 'integer)
1895 (defcustom org-display-custom-times nil
1896 "Non-nil means, overlay custom formats over all time stamps.
1897 The formats are defined through the variable `org-time-stamp-custom-formats'.
1898 To turn this on on a per-file basis, insert anywhere in the file:
1899 #+STARTUP: customtime"
1900 :group 'org-time
1901 :set 'set-default
1902 :type 'sexp)
1903 (make-variable-buffer-local 'org-display-custom-times)
1905 (defcustom org-time-stamp-custom-formats
1906 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1907 "Custom formats for time stamps. See `format-time-string' for the syntax.
1908 These are overlayed over the default ISO format if the variable
1909 `org-display-custom-times' is set. Time like %H:%M should be at the
1910 end of the second format."
1911 :group 'org-time
1912 :type 'sexp)
1914 (defun org-time-stamp-format (&optional long inactive)
1915 "Get the right format for a time string."
1916 (let ((f (if long (cdr org-time-stamp-formats)
1917 (car org-time-stamp-formats))))
1918 (if inactive
1919 (concat "[" (substring f 1 -1) "]")
1920 f)))
1922 (defcustom org-read-date-prefer-future t
1923 "Non-nil means, assume future for incomplete date input from user.
1924 This affects the following situations:
1925 1. The user gives a day, but no month.
1926 For example, if today is the 15th, and you enter \"3\", Org-mode will
1927 read this as the third of *next* month. However, if you enter \"17\",
1928 it will be considered as *this* month.
1929 2. The user gives a month but not a year.
1930 For example, if it is april and you enter \"feb 2\", this will be read
1931 as feb 2, *next* year. \"May 5\", however, will be this year.
1933 When this option is nil, the current month and year will always be used
1934 as defaults."
1935 :group 'org-time
1936 :type 'boolean)
1938 (defcustom org-read-date-display-live t
1939 "Non-nil means, display current interpretation of date prompt live.
1940 This display will be in an overlay, in the minibuffer."
1941 :group 'org-time
1942 :type 'boolean)
1944 (defcustom org-read-date-popup-calendar t
1945 "Non-nil means, pop up a calendar when prompting for a date.
1946 In the calendar, the date can be selected with mouse-1. However, the
1947 minibuffer will also be active, and you can simply enter the date as well.
1948 When nil, only the minibuffer will be available."
1949 :group 'org-time
1950 :type 'boolean)
1951 (if (fboundp 'defvaralias)
1952 (defvaralias 'org-popup-calendar-for-date-prompt
1953 'org-read-date-popup-calendar))
1955 (defcustom org-extend-today-until 0
1956 "The hour when your day really ends.
1957 This has influence for the following applications:
1958 - When switching the agenda to \"today\". It it is still earlier than
1959 the time given here, the day recognized as TODAY is actually yesterday.
1960 - When a date is read from the user and it is still before the time given
1961 here, the current date and time will be assumed to be yesterday, 23:59.
1963 FIXME:
1964 IMPORTANT: This is still a very experimental feature, it may disappear
1965 again or it may be extended to mean more things."
1966 :group 'org-time
1967 :type 'number)
1969 (defcustom org-edit-timestamp-down-means-later nil
1970 "Non-nil means, S-down will increase the time in a time stamp.
1971 When nil, S-up will increase."
1972 :group 'org-time
1973 :type 'boolean)
1975 (defcustom org-calendar-follow-timestamp-change t
1976 "Non-nil means, make the calendar window follow timestamp changes.
1977 When a timestamp is modified and the calendar window is visible, it will be
1978 moved to the new date."
1979 :group 'org-time
1980 :type 'boolean)
1982 (defcustom org-clock-heading-function nil
1983 "When non-nil, should be a function to create `org-clock-heading'.
1984 This is the string shown in the mode line when a clock is running.
1985 The function is called with point at the beginning of the headline."
1986 :group 'org-time ; FIXME: Should we have a separate group????
1987 :type 'function)
1989 (defgroup org-tags nil
1990 "Options concerning tags in Org-mode."
1991 :tag "Org Tags"
1992 :group 'org)
1994 (defcustom org-tag-alist nil
1995 "List of tags allowed in Org-mode files.
1996 When this list is nil, Org-mode will base TAG input on what is already in the
1997 buffer.
1998 The value of this variable is an alist, the car of each entry must be a
1999 keyword as a string, the cdr may be a character that is used to select
2000 that tag through the fast-tag-selection interface.
2001 See the manual for details."
2002 :group 'org-tags
2003 :type '(repeat
2004 (choice
2005 (cons (string :tag "Tag name")
2006 (character :tag "Access char"))
2007 (const :tag "Start radio group" (:startgroup))
2008 (const :tag "End radio group" (:endgroup)))))
2010 (defcustom org-use-fast-tag-selection 'auto
2011 "Non-nil means, use fast tag selection scheme.
2012 This is a special interface to select and deselect tags with single keys.
2013 When nil, fast selection is never used.
2014 When the symbol `auto', fast selection is used if and only if selection
2015 characters for tags have been configured, either through the variable
2016 `org-tag-alist' or through a #+TAGS line in the buffer.
2017 When t, fast selection is always used and selection keys are assigned
2018 automatically if necessary."
2019 :group 'org-tags
2020 :type '(choice
2021 (const :tag "Always" t)
2022 (const :tag "Never" nil)
2023 (const :tag "When selection characters are configured" 'auto)))
2025 (defcustom org-fast-tag-selection-single-key nil
2026 "Non-nil means, fast tag selection exits after first change.
2027 When nil, you have to press RET to exit it.
2028 During fast tag selection, you can toggle this flag with `C-c'.
2029 This variable can also have the value `expert'. In this case, the window
2030 displaying the tags menu is not even shown, until you press C-c again."
2031 :group 'org-tags
2032 :type '(choice
2033 (const :tag "No" nil)
2034 (const :tag "Yes" t)
2035 (const :tag "Expert" expert)))
2037 (defvar org-fast-tag-selection-include-todo nil
2038 "Non-nil means, fast tags selection interface will also offer TODO states.
2039 This is an undocumented feature, you should not rely on it.")
2041 (defcustom org-tags-column -80
2042 "The column to which tags should be indented in a headline.
2043 If this number is positive, it specifies the column. If it is negative,
2044 it means that the tags should be flushright to that column. For example,
2045 -80 works well for a normal 80 character screen."
2046 :group 'org-tags
2047 :type 'integer)
2049 (defcustom org-auto-align-tags t
2050 "Non-nil means, realign tags after pro/demotion of TODO state change.
2051 These operations change the length of a headline and therefore shift
2052 the tags around. With this options turned on, after each such operation
2053 the tags are again aligned to `org-tags-column'."
2054 :group 'org-tags
2055 :type 'boolean)
2057 (defcustom org-use-tag-inheritance t
2058 "Non-nil means, tags in levels apply also for sublevels.
2059 When nil, only the tags directly given in a specific line apply there.
2060 If you turn off this option, you very likely want to turn on the
2061 companion option `org-tags-match-list-sublevels'."
2062 :group 'org-tags
2063 :type 'boolean)
2065 (defcustom org-tags-match-list-sublevels nil
2066 "Non-nil means list also sublevels of headlines matching tag search.
2067 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2068 the sublevels of a headline matching a tag search often also match
2069 the same search. Listing all of them can create very long lists.
2070 Setting this variable to nil causes subtrees of a match to be skipped.
2071 This option is off by default, because inheritance in on. If you turn
2072 inheritance off, you very likely want to turn this option on.
2074 As a special case, if the tag search is restricted to TODO items, the
2075 value of this variable is ignored and sublevels are always checked, to
2076 make sure all corresponding TODO items find their way into the list."
2077 :group 'org-tags
2078 :type 'boolean)
2080 (defvar org-tags-history nil
2081 "History of minibuffer reads for tags.")
2082 (defvar org-last-tags-completion-table nil
2083 "The last used completion table for tags.")
2084 (defvar org-after-tags-change-hook nil
2085 "Hook that is run after the tags in a line have changed.")
2087 (defgroup org-properties nil
2088 "Options concerning properties in Org-mode."
2089 :tag "Org Properties"
2090 :group 'org)
2092 (defcustom org-property-format "%-10s %s"
2093 "How property key/value pairs should be formatted by `indent-line'.
2094 When `indent-line' hits a property definition, it will format the line
2095 according to this format, mainly to make sure that the values are
2096 lined-up with respect to each other."
2097 :group 'org-properties
2098 :type 'string)
2100 (defcustom org-use-property-inheritance nil
2101 "Non-nil means, properties apply also for sublevels.
2102 This setting is only relevant during property searches, not when querying
2103 an entry with `org-entry-get'. To retrieve a property with inheritance,
2104 you need to call `org-entry-get' with the inheritance flag.
2105 Turning this on can cause significant overhead when doing a search, so
2106 this is turned off by default.
2107 When nil, only the properties directly given in the current entry count.
2108 The value may also be a list of properties that shouldhave inheritance.
2110 However, note that some special properties use inheritance under special
2111 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2112 and the properties ending in \"_ALL\" when they are used as descriptor
2113 for valid values of a property."
2114 :group 'org-properties
2115 :type '(choice
2116 (const :tag "Not" nil)
2117 (const :tag "Always" nil)
2118 (repeat :tag "Specific properties" (string :tag "Property"))))
2120 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2121 "The default column format, if no other format has been defined.
2122 This variable can be set on the per-file basis by inserting a line
2124 #+COLUMNS: %25ITEM ....."
2125 :group 'org-properties
2126 :type 'string)
2128 (defcustom org-global-properties nil
2129 "List of property/value pairs that can be inherited by any entry.
2130 You can set buffer-local values for this by adding lines like
2132 #+PROPERTY: NAME VALUE"
2133 :group 'org-properties
2134 :type '(repeat
2135 (cons (string :tag "Property")
2136 (string :tag "Value"))))
2138 (defvar org-local-properties nil
2139 "List of property/value pairs that can be inherited by any entry.
2140 Valid for the current buffer.
2141 This variable is populated from #+PROPERTY lines.")
2143 (defgroup org-agenda nil
2144 "Options concerning agenda views in Org-mode."
2145 :tag "Org Agenda"
2146 :group 'org)
2148 (defvar org-category nil
2149 "Variable used by org files to set a category for agenda display.
2150 Such files should use a file variable to set it, for example
2152 # -*- mode: org; org-category: \"ELisp\"
2154 or contain a special line
2156 #+CATEGORY: ELisp
2158 If the file does not specify a category, then file's base name
2159 is used instead.")
2160 (make-variable-buffer-local 'org-category)
2162 (defcustom org-agenda-files nil
2163 "The files to be used for agenda display.
2164 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2165 \\[org-remove-file]. You can also use customize to edit the list.
2167 If an entry is a directory, all files in that directory that are matched by
2168 `org-agenda-file-regexp' will be part of the file list.
2170 If the value of the variable is not a list but a single file name, then
2171 the list of agenda files is actually stored and maintained in that file, one
2172 agenda file per line."
2173 :group 'org-agenda
2174 :type '(choice
2175 (repeat :tag "List of files and directories" file)
2176 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2178 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2179 "Regular expression to match files for `org-agenda-files'.
2180 If any element in the list in that variable contains a directory instead
2181 of a normal file, all files in that directory that are matched by this
2182 regular expression will be included."
2183 :group 'org-agenda
2184 :type 'regexp)
2186 (defcustom org-agenda-skip-unavailable-files nil
2187 "t means to just skip non-reachable files in `org-agenda-files'.
2188 Nil means to remove them, after a query, from the list."
2189 :group 'org-agenda
2190 :type 'boolean)
2192 (defcustom org-agenda-multi-occur-extra-files nil
2193 "List of extra files to be searched by `org-occur-in-agenda-files'.
2194 The files in `org-agenda-files' are always searched."
2195 :group 'org-agenda
2196 :type '(repeat file))
2198 (defcustom org-agenda-confirm-kill 1
2199 "When set, remote killing from the agenda buffer needs confirmation.
2200 When t, a confirmation is always needed. When a number N, confirmation is
2201 only needed when the text to be killed contains more than N non-white lines."
2202 :group 'org-agenda
2203 :type '(choice
2204 (const :tag "Never" nil)
2205 (const :tag "Always" t)
2206 (number :tag "When more than N lines")))
2208 (defcustom org-calendar-to-agenda-key [?c]
2209 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2210 The command `org-calendar-goto-agenda' will be bound to this key. The
2211 default is the character `c' because then `c' can be used to switch back and
2212 forth between agenda and calendar."
2213 :group 'org-agenda
2214 :type 'sexp)
2216 (defcustom org-agenda-compact-blocks nil
2217 "Non-nil means, make the block agenda more compact.
2218 This is done by leaving out unnecessary lines."
2219 :group 'org-agenda
2220 :type nil)
2222 (defgroup org-agenda-export nil
2223 "Options concerning exporting agenda views in Org-mode."
2224 :tag "Org Agenda Export"
2225 :group 'org-agenda)
2227 (defcustom org-agenda-with-colors t
2228 "Non-nil means, use colors in agenda views."
2229 :group 'org-agenda-export
2230 :type 'boolean)
2232 (defcustom org-agenda-exporter-settings nil
2233 "Alist of variable/value pairs that should be active during agenda export.
2234 This is a good place to set uptions for ps-print and for htmlize."
2235 :group 'org-agenda-export
2236 :type '(repeat
2237 (list
2238 (variable)
2239 (sexp :tag "Value"))))
2241 (defcustom org-agenda-export-html-style ""
2242 "The style specification for exported HTML Agenda files.
2243 If this variable contains a string, it will replace the default <style>
2244 section as produced by `htmlize'.
2245 Since there are different ways of setting style information, this variable
2246 needs to contain the full HTML structure to provide a style, including the
2247 surrounding HTML tags. The style specifications should include definitions
2248 the fonts used by the agenda, here is an example:
2250 <style type=\"text/css\">
2251 p { font-weight: normal; color: gray; }
2252 .org-agenda-structure {
2253 font-size: 110%;
2254 color: #003399;
2255 font-weight: 600;
2257 .org-todo {
2258 color: #cc6666;Week-agenda:
2259 font-weight: bold;
2261 .org-done {
2262 color: #339933;
2264 .title { text-align: center; }
2265 .todo, .deadline { color: red; }
2266 .done { color: green; }
2267 </style>
2269 or, if you want to keep the style in a file,
2271 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2273 As the value of this option simply gets inserted into the HTML <head> header,
2274 you can \"misuse\" it to also add other text to the header. However,
2275 <style>...</style> is required, if not present the variable will be ignored."
2276 :group 'org-agenda-export
2277 :group 'org-export-html
2278 :type 'string)
2280 (defgroup org-agenda-custom-commands nil
2281 "Options concerning agenda views in Org-mode."
2282 :tag "Org Agenda Custom Commands"
2283 :group 'org-agenda)
2285 (defcustom org-agenda-custom-commands nil
2286 "Custom commands for the agenda.
2287 These commands will be offered on the splash screen displayed by the
2288 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2290 (key desc type match options files)
2292 key The key (one or more characters as a string) to be associated
2293 with the command.
2294 desc A description of the commend, when omitted or nil, a default
2295 description is built using MATCH.
2296 type The command type, any of the following symbols:
2297 todo Entries with a specific TODO keyword, in all agenda files.
2298 tags Tags match in all agenda files.
2299 tags-todo Tags match in all agenda files, TODO entries only.
2300 todo-tree Sparse tree of specific TODO keyword in *current* file.
2301 tags-tree Sparse tree with all tags matches in *current* file.
2302 occur-tree Occur sparse tree for *current* file.
2303 ... A user-defined function.
2304 match What to search for:
2305 - a single keyword for TODO keyword searches
2306 - a tags match expression for tags searches
2307 - a regular expression for occur searches
2308 options A list of option settings, similar to that in a let form, so like
2309 this: ((opt1 val1) (opt2 val2) ...)
2310 files A list of files file to write the produced agenda buffer to
2311 with the command `org-store-agenda-views'.
2312 If a file name ends in \".html\", an HTML version of the buffer
2313 is written out. If it ends in \".ps\", a postscript version is
2314 produced. Otherwide, only the plain text is written to the file.
2316 You can also define a set of commands, to create a composite agenda buffer.
2317 In this case, an entry looks like this:
2319 (key desc (cmd1 cmd2 ...) general-options file)
2321 where
2323 desc A description string to be displayed in the dispatcher menu.
2324 cmd An agenda command, similar to the above. However, tree commands
2325 are no allowed, but instead you can get agenda and global todo list.
2326 So valid commands for a set are:
2327 (agenda)
2328 (alltodo)
2329 (stuck)
2330 (todo \"match\" options files)
2331 (tags \"match\" options files)
2332 (tags-todo \"match\" options files)
2334 Each command can carry a list of options, and another set of options can be
2335 given for the whole set of commands. Individual command options take
2336 precedence over the general options.
2338 When using several characters as key to a command, the first characters
2339 are prefix commands. For the dispatcher to display useful information, you
2340 should provide a description for the prefix, like
2342 (setq org-agenda-custom-commands
2343 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2344 (\"hl\" tags \"+HOME+Lisa\")
2345 (\"hp\" tags \"+HOME+Peter\")
2346 (\"hk\" tags \"+HOME+Kim\")))"
2347 :group 'org-agenda-custom-commands
2348 :type '(repeat
2349 (choice :value ("a" "" tags "" nil)
2350 (list :tag "Single command"
2351 (string :tag "Access Key(s) ")
2352 (option (string :tag "Description"))
2353 (choice
2354 (const :tag "Agenda" agenda)
2355 (const :tag "TODO list" alltodo)
2356 (const :tag "Stuck projects" stuck)
2357 (const :tag "Tags search (all agenda files)" tags)
2358 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2359 (const :tag "TODO keyword search (all agenda files)" todo)
2360 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2361 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2362 (const :tag "Occur tree (current buffer)" occur-tree)
2363 (sexp :tag "Other, user-defined function"))
2364 (string :tag "Match")
2365 (repeat :tag "Local options"
2366 (list (variable :tag "Option") (sexp :tag "Value")))
2367 (option (repeat :tag "Export" (file :tag "Export to"))))
2368 (list :tag "Command series, all agenda files"
2369 (string :tag "Access Key(s)")
2370 (string :tag "Description ")
2371 (repeat
2372 (choice
2373 (const :tag "Agenda" (agenda))
2374 (const :tag "TODO list" (alltodo))
2375 (const :tag "Stuck projects" (stuck))
2376 (list :tag "Tags search"
2377 (const :format "" tags)
2378 (string :tag "Match")
2379 (repeat :tag "Local options"
2380 (list (variable :tag "Option")
2381 (sexp :tag "Value"))))
2383 (list :tag "Tags search, TODO entries only"
2384 (const :format "" tags-todo)
2385 (string :tag "Match")
2386 (repeat :tag "Local options"
2387 (list (variable :tag "Option")
2388 (sexp :tag "Value"))))
2390 (list :tag "TODO keyword search"
2391 (const :format "" todo)
2392 (string :tag "Match")
2393 (repeat :tag "Local options"
2394 (list (variable :tag "Option")
2395 (sexp :tag "Value"))))
2397 (list :tag "Other, user-defined function"
2398 (symbol :tag "function")
2399 (string :tag "Match")
2400 (repeat :tag "Local options"
2401 (list (variable :tag "Option")
2402 (sexp :tag "Value"))))))
2404 (repeat :tag "General options"
2405 (list (variable :tag "Option")
2406 (sexp :tag "Value")))
2407 (option (repeat :tag "Export" (file :tag "Export to"))))
2408 (cons :tag "Prefix key documentation"
2409 (string :tag "Access Key(s)")
2410 (string :tag "Description ")))))
2412 (defcustom org-stuck-projects
2413 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2414 "How to identify stuck projects.
2415 This is a list of four items:
2416 1. A tags/todo matcher string that is used to identify a project.
2417 The entire tree below a headline matched by this is considered one project.
2418 2. A list of TODO keywords identifying non-stuck projects.
2419 If the project subtree contains any headline with one of these todo
2420 keywords, the project is considered to be not stuck. If you specify
2421 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2422 3. A list of tags identifying non-stuck projects.
2423 If the project subtree contains any headline with one of these tags,
2424 the project is considered to be not stuck. If you specify \"*\" as
2425 a tag, any tag will mark the project unstuck.
2426 4. An arbitrary regular expression matching non-stuck projects.
2428 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2429 or `C-c a #' to produce the list."
2430 :group 'org-agenda-custom-commands
2431 :type '(list
2432 (string :tag "Tags/TODO match to identify a project")
2433 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2434 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2435 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2438 (defgroup org-agenda-skip nil
2439 "Options concerning skipping parts of agenda files."
2440 :tag "Org Agenda Skip"
2441 :group 'org-agenda)
2443 (defcustom org-agenda-todo-list-sublevels t
2444 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2445 When nil, the sublevels of a TODO entry are not checked, resulting in
2446 potentially much shorter TODO lists."
2447 :group 'org-agenda-skip
2448 :group 'org-todo
2449 :type 'boolean)
2451 (defcustom org-agenda-todo-ignore-with-date nil
2452 "Non-nil means, don't show entries with a date in the global todo list.
2453 You can use this if you prefer to mark mere appointments with a TODO keyword,
2454 but don't want them to show up in the TODO list.
2455 When this is set, it also covers deadlines and scheduled items, the settings
2456 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2457 will be ignored."
2458 :group 'org-agenda-skip
2459 :group 'org-todo
2460 :type 'boolean)
2462 (defcustom org-agenda-todo-ignore-scheduled nil
2463 "Non-nil means, don't show scheduled entries in the global todo list.
2464 The idea behind this is that by scheduling it, you have already taken care
2465 of this item.
2466 See also `org-agenda-todo-ignore-with-date'."
2467 :group 'org-agenda-skip
2468 :group 'org-todo
2469 :type 'boolean)
2471 (defcustom org-agenda-todo-ignore-deadlines nil
2472 "Non-nil means, don't show near deadline entries in the global todo list.
2473 Near means closer than `org-deadline-warning-days' days.
2474 The idea behind this is that such items will appear in the agenda anyway.
2475 See also `org-agenda-todo-ignore-with-date'."
2476 :group 'org-agenda-skip
2477 :group 'org-todo
2478 :type 'boolean)
2480 (defcustom org-agenda-skip-scheduled-if-done nil
2481 "Non-nil means don't show scheduled items in agenda when they are done.
2482 This is relevant for the daily/weekly agenda, not for the TODO list. And
2483 it applies only to the actual date of the scheduling. Warnings about
2484 an item with a past scheduling dates are always turned off when the item
2485 is DONE."
2486 :group 'org-agenda-skip
2487 :type 'boolean)
2489 (defcustom org-agenda-skip-deadline-if-done nil
2490 "Non-nil means don't show deadines when the corresponding item is done.
2491 When nil, the deadline is still shown and should give you a happy feeling.
2492 This is relevant for the daily/weekly agenda. And it applied only to the
2493 actualy date of the deadline. Warnings about approching and past-due
2494 deadlines are always turned off when the item is DONE."
2495 :group 'org-agenda-skip
2496 :type 'boolean)
2498 (defcustom org-agenda-skip-timestamp-if-done nil
2499 "Non-nil means don't select item by timestamp or -range if it is DONE."
2500 :group 'org-agenda-skip
2501 :type 'boolean)
2503 (defcustom org-timeline-show-empty-dates 3
2504 "Non-nil means, `org-timeline' also shows dates without an entry.
2505 When nil, only the days which actually have entries are shown.
2506 When t, all days between the first and the last date are shown.
2507 When an integer, show also empty dates, but if there is a gap of more than
2508 N days, just insert a special line indicating the size of the gap."
2509 :group 'org-agenda-skip
2510 :type '(choice
2511 (const :tag "None" nil)
2512 (const :tag "All" t)
2513 (number :tag "at most")))
2516 (defgroup org-agenda-startup nil
2517 "Options concerning initial settings in the Agenda in Org Mode."
2518 :tag "Org Agenda Startup"
2519 :group 'org-agenda)
2521 (defcustom org-finalize-agenda-hook nil
2522 "Hook run just before displaying an agenda buffer."
2523 :group 'org-agenda-startup
2524 :type 'hook)
2526 (defcustom org-agenda-mouse-1-follows-link nil
2527 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2528 A longer mouse click will still set point. Does not wortk on XEmacs.
2529 Needs to be set before org.el is loaded."
2530 :group 'org-agenda-startup
2531 :type 'boolean)
2533 (defcustom org-agenda-start-with-follow-mode nil
2534 "The initial value of follow-mode in a newly created agenda window."
2535 :group 'org-agenda-startup
2536 :type 'boolean)
2538 (defgroup org-agenda-windows nil
2539 "Options concerning the windows used by the Agenda in Org Mode."
2540 :tag "Org Agenda Windows"
2541 :group 'org-agenda)
2543 (defcustom org-agenda-window-setup 'reorganize-frame
2544 "How the agenda buffer should be displayed.
2545 Possible values for this option are:
2547 current-window Show agenda in the current window, keeping all other windows.
2548 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2549 other-window Use `switch-to-buffer-other-window' to display agenda.
2550 reorganize-frame Show only two windows on the current frame, the current
2551 window and the agenda.
2552 See also the variable `org-agenda-restore-windows-after-quit'."
2553 :group 'org-agenda-windows
2554 :type '(choice
2555 (const current-window)
2556 (const other-frame)
2557 (const other-window)
2558 (const reorganize-frame)))
2560 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2561 "The min and max height of the agenda window as a fraction of frame height.
2562 The value of the variable is a cons cell with two numbers between 0 and 1.
2563 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2564 :group 'org-agenda-windows
2565 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2567 (defcustom org-agenda-restore-windows-after-quit nil
2568 "Non-nil means, restore window configuration open exiting agenda.
2569 Before the window configuration is changed for displaying the agenda,
2570 the current status is recorded. When the agenda is exited with
2571 `q' or `x' and this option is set, the old state is restored. If
2572 `org-agenda-window-setup' is `other-frame', the value of this
2573 option will be ignored.."
2574 :group 'org-agenda-windows
2575 :type 'boolean)
2577 (defcustom org-indirect-buffer-display 'other-window
2578 "How should indirect tree buffers be displayed?
2579 This applies to indirect buffers created with the commands
2580 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2581 Valid values are:
2582 current-window Display in the current window
2583 other-window Just display in another window.
2584 dedicated-frame Create one new frame, and re-use it each time.
2585 new-frame Make a new frame each time. Note that in this case
2586 previously-made indirect buffers are kept, and you need to
2587 kill these buffers yourself."
2588 :group 'org-structure
2589 :group 'org-agenda-windows
2590 :type '(choice
2591 (const :tag "In current window" current-window)
2592 (const :tag "In current frame, other window" other-window)
2593 (const :tag "Each time a new frame" new-frame)
2594 (const :tag "One dedicated frame" dedicated-frame)))
2596 (defgroup org-agenda-daily/weekly nil
2597 "Options concerning the daily/weekly agenda."
2598 :tag "Org Agenda Daily/Weekly"
2599 :group 'org-agenda)
2601 (defcustom org-agenda-ndays 7
2602 "Number of days to include in overview display.
2603 Should be 1 or 7."
2604 :group 'org-agenda-daily/weekly
2605 :type 'number)
2607 (defcustom org-agenda-start-on-weekday 1
2608 "Non-nil means, start the overview always on the specified weekday.
2609 0 denotes Sunday, 1 denotes Monday etc.
2610 When nil, always start on the current day."
2611 :group 'org-agenda-daily/weekly
2612 :type '(choice (const :tag "Today" nil)
2613 (number :tag "Weekday No.")))
2615 (defcustom org-agenda-show-all-dates t
2616 "Non-nil means, `org-agenda' shows every day in the selected range.
2617 When nil, only the days which actually have entries are shown."
2618 :group 'org-agenda-daily/weekly
2619 :type 'boolean)
2621 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2622 "Format string for displaying dates in the agenda.
2623 Used by the daily/weekly agenda and by the timeline. This should be
2624 a format string understood by `format-time-string', or a function returning
2625 the formatted date as a string. The function must take a single argument,
2626 a calendar-style date list like (month day year)."
2627 :group 'org-agenda-daily/weekly
2628 :type '(choice
2629 (string :tag "Format string")
2630 (function :tag "Function")))
2632 (defun org-agenda-format-date-aligned (date)
2633 "Format a date string for display in the daily/weekly agenda, or timeline.
2634 This function makes sure that dates are aligned for easy reading."
2635 (format "%-9s %2d %s %4d"
2636 (calendar-day-name date)
2637 (extract-calendar-day date)
2638 (calendar-month-name (extract-calendar-month date))
2639 (extract-calendar-year date)))
2641 (defcustom org-agenda-include-diary nil
2642 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2643 :group 'org-agenda-daily/weekly
2644 :type 'boolean)
2646 (defcustom org-agenda-include-all-todo nil
2647 "Set means weekly/daily agenda will always contain all TODO entries.
2648 The TODO entries will be listed at the top of the agenda, before
2649 the entries for specific days."
2650 :group 'org-agenda-daily/weekly
2651 :type 'boolean)
2653 (defcustom org-agenda-repeating-timestamp-show-all t
2654 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2655 When nil, only one occurence is shown, either today or the
2656 nearest into the future."
2657 :group 'org-agenda-daily/weekly
2658 :type 'boolean)
2660 (defcustom org-deadline-warning-days 14
2661 "No. of days before expiration during which a deadline becomes active.
2662 This variable governs the display in sparse trees and in the agenda.
2663 When negative, it means use this number (the absolute value of it)
2664 even if a deadline has a different individual lead time specified."
2665 :group 'org-time
2666 :group 'org-agenda-daily/weekly
2667 :type 'number)
2669 (defcustom org-scheduled-past-days 10000
2670 "No. of days to continue listing scheduled items that are not marked DONE.
2671 When an item is scheduled on a date, it shows up in the agenda on this
2672 day and will be listed until it is marked done for the number of days
2673 given here."
2674 :group 'org-agenda-daily/weekly
2675 :type 'number)
2677 (defgroup org-agenda-time-grid nil
2678 "Options concerning the time grid in the Org-mode Agenda."
2679 :tag "Org Agenda Time Grid"
2680 :group 'org-agenda)
2682 (defcustom org-agenda-use-time-grid t
2683 "Non-nil means, show a time grid in the agenda schedule.
2684 A time grid is a set of lines for specific times (like every two hours between
2685 8:00 and 20:00). The items scheduled for a day at specific times are
2686 sorted in between these lines.
2687 For details about when the grid will be shown, and what it will look like, see
2688 the variable `org-agenda-time-grid'."
2689 :group 'org-agenda-time-grid
2690 :type 'boolean)
2692 (defcustom org-agenda-time-grid
2693 '((daily today require-timed)
2694 "----------------"
2695 (800 1000 1200 1400 1600 1800 2000))
2697 "The settings for time grid for agenda display.
2698 This is a list of three items. The first item is again a list. It contains
2699 symbols specifying conditions when the grid should be displayed:
2701 daily if the agenda shows a single day
2702 weekly if the agenda shows an entire week
2703 today show grid on current date, independent of daily/weekly display
2704 require-timed show grid only if at least one item has a time specification
2706 The second item is a string which will be places behing the grid time.
2708 The third item is a list of integers, indicating the times that should have
2709 a grid line."
2710 :group 'org-agenda-time-grid
2711 :type
2712 '(list
2713 (set :greedy t :tag "Grid Display Options"
2714 (const :tag "Show grid in single day agenda display" daily)
2715 (const :tag "Show grid in weekly agenda display" weekly)
2716 (const :tag "Always show grid for today" today)
2717 (const :tag "Show grid only if any timed entries are present"
2718 require-timed)
2719 (const :tag "Skip grid times already present in an entry"
2720 remove-match))
2721 (string :tag "Grid String")
2722 (repeat :tag "Grid Times" (integer :tag "Time"))))
2724 (defgroup org-agenda-sorting nil
2725 "Options concerning sorting in the Org-mode Agenda."
2726 :tag "Org Agenda Sorting"
2727 :group 'org-agenda)
2729 (defconst org-sorting-choice
2730 '(choice
2731 (const time-up) (const time-down)
2732 (const category-keep) (const category-up) (const category-down)
2733 (const tag-down) (const tag-up)
2734 (const priority-up) (const priority-down))
2735 "Sorting choices.")
2737 (defcustom org-agenda-sorting-strategy
2738 '((agenda time-up category-keep priority-down)
2739 (todo category-keep priority-down)
2740 (tags category-keep priority-down))
2741 "Sorting structure for the agenda items of a single day.
2742 This is a list of symbols which will be used in sequence to determine
2743 if an entry should be listed before another entry. The following
2744 symbols are recognized:
2746 time-up Put entries with time-of-day indications first, early first
2747 time-down Put entries with time-of-day indications first, late first
2748 category-keep Keep the default order of categories, corresponding to the
2749 sequence in `org-agenda-files'.
2750 category-up Sort alphabetically by category, A-Z.
2751 category-down Sort alphabetically by category, Z-A.
2752 tag-up Sort alphabetically by last tag, A-Z.
2753 tag-down Sort alphabetically by last tag, Z-A.
2754 priority-up Sort numerically by priority, high priority last.
2755 priority-down Sort numerically by priority, high priority first.
2757 The different possibilities will be tried in sequence, and testing stops
2758 if one comparison returns a \"not-equal\". For example, the default
2759 '(time-up category-keep priority-down)
2760 means: Pull out all entries having a specified time of day and sort them,
2761 in order to make a time schedule for the current day the first thing in the
2762 agenda listing for the day. Of the entries without a time indication, keep
2763 the grouped in categories, don't sort the categories, but keep them in
2764 the sequence given in `org-agenda-files'. Within each category sort by
2765 priority.
2767 Leaving out `category-keep' would mean that items will be sorted across
2768 categories by priority.
2770 Instead of a single list, this can also be a set of list for specific
2771 contents, with a context symbol in the car of the list, any of
2772 `agenda', `todo', `tags' for the corresponding agenda views."
2773 :group 'org-agenda-sorting
2774 :type `(choice
2775 (repeat :tag "General" ,org-sorting-choice)
2776 (list :tag "Individually"
2777 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2778 (repeat ,org-sorting-choice))
2779 (cons (const :tag "Strategy for TODO lists" todo)
2780 (repeat ,org-sorting-choice))
2781 (cons (const :tag "Strategy for Tags matches" tags)
2782 (repeat ,org-sorting-choice)))))
2784 (defcustom org-sort-agenda-notime-is-late t
2785 "Non-nil means, items without time are considered late.
2786 This is only relevant for sorting. When t, items which have no explicit
2787 time like 15:30 will be considered as 99:01, i.e. later than any items which
2788 do have a time. When nil, the default time is before 0:00. You can use this
2789 option to decide if the schedule for today should come before or after timeless
2790 agenda entries."
2791 :group 'org-agenda-sorting
2792 :type 'boolean)
2794 (defgroup org-agenda-line-format nil
2795 "Options concerning the entry prefix in the Org-mode agenda display."
2796 :tag "Org Agenda Line Format"
2797 :group 'org-agenda)
2799 (defcustom org-agenda-prefix-format
2800 '((agenda . " %-12:c%?-12t% s")
2801 (timeline . " % s")
2802 (todo . " %-12:c")
2803 (tags . " %-12:c"))
2804 "Format specifications for the prefix of items in the agenda views.
2805 An alist with four entries, for the different agenda types. The keys to the
2806 sublists are `agenda', `timeline', `todo', and `tags'. The values
2807 are format strings.
2808 This format works similar to a printf format, with the following meaning:
2810 %c the category of the item, \"Diary\" for entries from the diary, or
2811 as given by the CATEGORY keyword or derived from the file name.
2812 %T the *last* tag of the item. Last because inherited tags come
2813 first in the list.
2814 %t the time-of-day specification if one applies to the entry, in the
2815 format HH:MM
2816 %s Scheduling/Deadline information, a short string
2818 All specifiers work basically like the standard `%s' of printf, but may
2819 contain two additional characters: A question mark just after the `%' and
2820 a whitespace/punctuation character just before the final letter.
2822 If the first character after `%' is a question mark, the entire field
2823 will only be included if the corresponding value applies to the
2824 current entry. This is useful for fields which should have fixed
2825 width when present, but zero width when absent. For example,
2826 \"%?-12t\" will result in a 12 character time field if a time of the
2827 day is specified, but will completely disappear in entries which do
2828 not contain a time.
2830 If there is punctuation or whitespace character just before the final
2831 format letter, this character will be appended to the field value if
2832 the value is not empty. For example, the format \"%-12:c\" leads to
2833 \"Diary: \" if the category is \"Diary\". If the category were be
2834 empty, no additional colon would be interted.
2836 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2837 - Indent the line with two space characters
2838 - Give the category in a 12 chars wide field, padded with whitespace on
2839 the right (because of `-'). Append a colon if there is a category
2840 (because of `:').
2841 - If there is a time-of-day, put it into a 12 chars wide field. If no
2842 time, don't put in an empty field, just skip it (because of '?').
2843 - Finally, put the scheduling information and append a whitespace.
2845 As another example, if you don't want the time-of-day of entries in
2846 the prefix, you could use:
2848 (setq org-agenda-prefix-format \" %-11:c% s\")
2850 See also the variables `org-agenda-remove-times-when-in-prefix' and
2851 `org-agenda-remove-tags'."
2852 :type '(choice
2853 (string :tag "General format")
2854 (list :greedy t :tag "View dependent"
2855 (cons (const agenda) (string :tag "Format"))
2856 (cons (const timeline) (string :tag "Format"))
2857 (cons (const todo) (string :tag "Format"))
2858 (cons (const tags) (string :tag "Format"))))
2859 :group 'org-agenda-line-format)
2861 (defvar org-prefix-format-compiled nil
2862 "The compiled version of the most recently used prefix format.
2863 See the variable `org-agenda-prefix-format'.")
2865 (defcustom org-agenda-todo-keyword-format "%-1s"
2866 "Format for the TODO keyword in agenda lines.
2867 Set this to something like \"%-12s\" if you want all TODO keywords
2868 to occupy a fixed space in the agenda display."
2869 :group 'org-agenda-line-format
2870 :type 'string)
2872 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2873 "Text preceeding scheduled items in the agenda view.
2874 This is a list with two strings. The first applies when the item is
2875 scheduled on the current day. The second applies when it has been scheduled
2876 previously, it may contain a %d to capture how many days ago the item was
2877 scheduled."
2878 :group 'org-agenda-line-format
2879 :type '(list
2880 (string :tag "Scheduled today ")
2881 (string :tag "Scheduled previously")))
2883 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2884 "Text preceeding deadline items in the agenda view.
2885 This is a list with two strings. The first applies when the item has its
2886 deadline on the current day. The second applies when it is in the past or
2887 in the future, it may contain %d to capture how many days away the deadline
2888 is (was)."
2889 :group 'org-agenda-line-format
2890 :type '(list
2891 (string :tag "Deadline today ")
2892 (string :tag "Deadline relative")))
2894 (defcustom org-agenda-remove-times-when-in-prefix t
2895 "Non-nil means, remove duplicate time specifications in agenda items.
2896 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2897 time-of-day specification in a headline or diary entry is extracted and
2898 placed into the prefix. If this option is non-nil, the original specification
2899 \(a timestamp or -range, or just a plain time(range) specification like
2900 11:30-4pm) will be removed for agenda display. This makes the agenda less
2901 cluttered.
2902 The option can be t or nil. It may also be the symbol `beg', indicating
2903 that the time should only be removed what it is located at the beginning of
2904 the headline/diary entry."
2905 :group 'org-agenda-line-format
2906 :type '(choice
2907 (const :tag "Always" t)
2908 (const :tag "Never" nil)
2909 (const :tag "When at beginning of entry" beg)))
2912 (defcustom org-agenda-default-appointment-duration nil
2913 "Default duration for appointments that only have a starting time.
2914 When nil, no duration is specified in such cases.
2915 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2916 :group 'org-agenda-line-format
2917 :type '(choice
2918 (integer :tag "Minutes")
2919 (const :tag "No default duration")))
2922 (defcustom org-agenda-remove-tags nil
2923 "Non-nil means, remove the tags from the headline copy in the agenda.
2924 When this is the symbol `prefix', only remove tags when
2925 `org-agenda-prefix-format' contains a `%T' specifier."
2926 :group 'org-agenda-line-format
2927 :type '(choice
2928 (const :tag "Always" t)
2929 (const :tag "Never" nil)
2930 (const :tag "When prefix format contains %T" prefix)))
2932 (if (fboundp 'defvaralias)
2933 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2934 'org-agenda-remove-tags))
2936 (defcustom org-agenda-tags-column -80
2937 "Shift tags in agenda items to this column.
2938 If this number is positive, it specifies the column. If it is negative,
2939 it means that the tags should be flushright to that column. For example,
2940 -80 works well for a normal 80 character screen."
2941 :group 'org-agenda-line-format
2942 :type 'integer)
2944 (if (fboundp 'defvaralias)
2945 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2947 (defcustom org-agenda-fontify-priorities t
2948 "Non-nil means, highlight low and high priorities in agenda.
2949 When t, the highest priority entries are bold, lowest priority italic.
2950 This may also be an association list of priority faces. The face may be
2951 a names face, or a list like `(:background \"Red\")'."
2952 :group 'org-agenda-line-format
2953 :type '(choice
2954 (const :tag "Never" nil)
2955 (const :tag "Defaults" t)
2956 (repeat :tag "Specify"
2957 (list (character :tag "Priority" :value ?A)
2958 (sexp :tag "face")))))
2960 (defgroup org-latex nil
2961 "Options for embedding LaTeX code into Org-mode"
2962 :tag "Org LaTeX"
2963 :group 'org)
2965 (defcustom org-format-latex-options
2966 '(:foreground default :background default :scale 1.0
2967 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2968 :matchers ("begin" "$" "$$" "\\(" "\\["))
2969 "Options for creating images from LaTeX fragments.
2970 This is a property list with the following properties:
2971 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2972 `default' means use the forground of the default face.
2973 :background the background color, or \"Transparent\".
2974 `default' means use the background of the default face.
2975 :scale a scaling factor for the size of the images
2976 :html-foreground, :html-background, :html-scale
2977 The same numbers for HTML export.
2978 :matchers a list indicating which matchers should be used to
2979 find LaTeX fragments. Valid members of this list are:
2980 \"begin\" find environments
2981 \"$\" find math expressions surrounded by $...$
2982 \"$$\" find math expressions surrounded by $$....$$
2983 \"\\(\" find math expressions surrounded by \\(...\\)
2984 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2985 :group 'org-latex
2986 :type 'plist)
2988 (defcustom org-format-latex-header "\\documentclass{article}
2989 \\usepackage{fullpage} % do not remove
2990 \\usepackage{amssymb}
2991 \\usepackage[usenames]{color}
2992 \\usepackage{amsmath}
2993 \\usepackage{latexsym}
2994 \\usepackage[mathscr]{eucal}
2995 \\pagestyle{empty} % do not remove"
2996 "The document header used for processing LaTeX fragments."
2997 :group 'org-latex
2998 :type 'string)
3000 (defgroup org-export nil
3001 "Options for exporting org-listings."
3002 :tag "Org Export"
3003 :group 'org)
3005 (defgroup org-export-general nil
3006 "General options for exporting Org-mode files."
3007 :tag "Org Export General"
3008 :group 'org-export)
3010 ;; FIXME
3011 (defvar org-export-publishing-directory nil)
3013 (defcustom org-export-with-special-strings t
3014 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3015 When this option is turned on, these strings will be exported as:
3017 Org HTML LaTeX
3018 -----+----------+--------
3019 \\- &shy; \\-
3020 -- &ndash; --
3021 --- &mdash; ---
3022 ... &hellip; \ldots
3024 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3025 :group 'org-export-translation
3026 :type 'boolean)
3028 (defcustom org-export-language-setup
3029 '(("en" "Author" "Date" "Table of Contents")
3030 ("cs" "Autor" "Datum" "Obsah")
3031 ("da" "Ophavsmand" "Dato" "Indhold")
3032 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3033 ("es" "Autor" "Fecha" "\xcdndice")
3034 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3035 ("it" "Autore" "Data" "Indice")
3036 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3037 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3038 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3039 "Terms used in export text, translated to different languages.
3040 Use the variable `org-export-default-language' to set the language,
3041 or use the +OPTION lines for a per-file setting."
3042 :group 'org-export-general
3043 :type '(repeat
3044 (list
3045 (string :tag "HTML language tag")
3046 (string :tag "Author")
3047 (string :tag "Date")
3048 (string :tag "Table of Contents"))))
3050 (defcustom org-export-default-language "en"
3051 "The default language of HTML export, as a string.
3052 This should have an association in `org-export-language-setup'."
3053 :group 'org-export-general
3054 :type 'string)
3056 (defcustom org-export-skip-text-before-1st-heading t
3057 "Non-nil means, skip all text before the first headline when exporting.
3058 When nil, that text is exported as well."
3059 :group 'org-export-general
3060 :type 'boolean)
3062 (defcustom org-export-headline-levels 3
3063 "The last level which is still exported as a headline.
3064 Inferior levels will produce itemize lists when exported.
3065 Note that a numeric prefix argument to an exporter function overrides
3066 this setting.
3068 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3069 :group 'org-export-general
3070 :type 'number)
3072 (defcustom org-export-with-section-numbers t
3073 "Non-nil means, add section numbers to headlines when exporting.
3075 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3076 :group 'org-export-general
3077 :type 'boolean)
3079 (defcustom org-export-with-toc t
3080 "Non-nil means, create a table of contents in exported files.
3081 The TOC contains headlines with levels up to`org-export-headline-levels'.
3082 When an integer, include levels up to N in the toc, this may then be
3083 different from `org-export-headline-levels', but it will not be allowed
3084 to be larger than the number of headline levels.
3085 When nil, no table of contents is made.
3087 Headlines which contain any TODO items will be marked with \"(*)\" in
3088 ASCII export, and with red color in HTML output, if the option
3089 `org-export-mark-todo-in-toc' is set.
3091 In HTML output, the TOC will be clickable.
3093 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3094 or \"toc:3\"."
3095 :group 'org-export-general
3096 :type '(choice
3097 (const :tag "No Table of Contents" nil)
3098 (const :tag "Full Table of Contents" t)
3099 (integer :tag "TOC to level")))
3101 (defcustom org-export-mark-todo-in-toc nil
3102 "Non-nil means, mark TOC lines that contain any open TODO items."
3103 :group 'org-export-general
3104 :type 'boolean)
3106 (defcustom org-export-preserve-breaks nil
3107 "Non-nil means, preserve all line breaks when exporting.
3108 Normally, in HTML output paragraphs will be reformatted. In ASCII
3109 export, line breaks will always be preserved, regardless of this variable.
3111 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3112 :group 'org-export-general
3113 :type 'boolean)
3115 (defcustom org-export-with-archived-trees 'headline
3116 "Whether subtrees with the ARCHIVE tag should be exported.
3117 This can have three different values
3118 nil Do not export, pretend this tree is not present
3119 t Do export the entire tree
3120 headline Only export the headline, but skip the tree below it."
3121 :group 'org-export-general
3122 :group 'org-archive
3123 :type '(choice
3124 (const :tag "not at all" nil)
3125 (const :tag "headline only" 'headline)
3126 (const :tag "entirely" t)))
3128 (defcustom org-export-author-info t
3129 "Non-nil means, insert author name and email into the exported file.
3131 This option can also be set with the +OPTIONS line,
3132 e.g. \"author-info:nil\"."
3133 :group 'org-export-general
3134 :type 'boolean)
3136 (defcustom org-export-time-stamp-file t
3137 "Non-nil means, insert a time stamp into the exported file.
3138 The time stamp shows when the file was created.
3140 This option can also be set with the +OPTIONS line,
3141 e.g. \"timestamp:nil\"."
3142 :group 'org-export-general
3143 :type 'boolean)
3145 (defcustom org-export-with-timestamps t
3146 "If nil, do not export time stamps and associated keywords."
3147 :group 'org-export-general
3148 :type 'boolean)
3150 (defcustom org-export-remove-timestamps-from-toc t
3151 "If nil, remove timestamps from the table of contents entries."
3152 :group 'org-export-general
3153 :type 'boolean)
3155 (defcustom org-export-with-tags 'not-in-toc
3156 "If nil, do not export tags, just remove them from headlines.
3157 If this is the symbol `not-in-toc', tags will be removed from table of
3158 contents entries, but still be shown in the headlines of the document.
3160 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3161 :group 'org-export-general
3162 :type '(choice
3163 (const :tag "Off" nil)
3164 (const :tag "Not in TOC" not-in-toc)
3165 (const :tag "On" t)))
3167 (defcustom org-export-with-drawers nil
3168 "Non-nil means, export with drawers like the property drawer.
3169 When t, all drawers are exported. This may also be a list of
3170 drawer names to export."
3171 :group 'org-export-general
3172 :type '(choice
3173 (const :tag "All drawers" t)
3174 (const :tag "None" nil)
3175 (repeat :tag "Selected drawers"
3176 (string :tag "Drawer name"))))
3178 (defgroup org-export-translation nil
3179 "Options for translating special ascii sequences for the export backends."
3180 :tag "Org Export Translation"
3181 :group 'org-export)
3183 (defcustom org-export-with-emphasize t
3184 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3185 If the export target supports emphasizing text, the word will be
3186 typeset in bold, italic, or underlined, respectively. Works only for
3187 single words, but you can say: I *really* *mean* *this*.
3188 Not all export backends support this.
3190 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3191 :group 'org-export-translation
3192 :type 'boolean)
3194 (defcustom org-export-with-footnotes t
3195 "If nil, export [1] as a footnote marker.
3196 Lines starting with [1] will be formatted as footnotes.
3198 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3199 :group 'org-export-translation
3200 :type 'boolean)
3202 (defcustom org-export-with-sub-superscripts t
3203 "Non-nil means, interpret \"_\" and \"^\" for export.
3204 When this option is turned on, you can use TeX-like syntax for sub- and
3205 superscripts. Several characters after \"_\" or \"^\" will be
3206 considered as a single item - so grouping with {} is normally not
3207 needed. For example, the following things will be parsed as single
3208 sub- or superscripts.
3210 10^24 or 10^tau several digits will be considered 1 item.
3211 10^-12 or 10^-tau a leading sign with digits or a word
3212 x^2-y^3 will be read as x^2 - y^3, because items are
3213 terminated by almost any nonword/nondigit char.
3214 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3216 Still, ambiguity is possible - so when in doubt use {} to enclose the
3217 sub/superscript. If you set this variable to the symbol `{}',
3218 the braces are *required* in order to trigger interpretations as
3219 sub/superscript. This can be helpful in documents that need \"_\"
3220 frequently in plain text.
3222 Not all export backends support this, but HTML does.
3224 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3225 :group 'org-export-translation
3226 :type '(choice
3227 (const :tag "Always interpret" t)
3228 (const :tag "Only with braces" {})
3229 (const :tag "Never interpret" nil)))
3231 (defcustom org-export-with-special-strings t
3232 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3233 When this option is turned on, these strings will be exported as:
3235 \\- : &shy;
3236 -- : &ndash;
3237 --- : &mdash;
3239 Not all export backends support this, but HTML does.
3241 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3242 :group 'org-export-translation
3243 :type 'boolean)
3245 (defcustom org-export-with-TeX-macros t
3246 "Non-nil means, interpret simple TeX-like macros when exporting.
3247 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3248 No only real TeX macros will work here, but the standard HTML entities
3249 for math can be used as macro names as well. For a list of supported
3250 names in HTML export, see the constant `org-html-entities'.
3251 Not all export backends support this.
3253 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3254 :group 'org-export-translation
3255 :group 'org-export-latex
3256 :type 'boolean)
3258 (defcustom org-export-with-LaTeX-fragments nil
3259 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3260 When set, the exporter will find LaTeX environments if the \\begin line is
3261 the first non-white thing on a line. It will also find the math delimiters
3262 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3263 display math.
3265 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3266 :group 'org-export-translation
3267 :group 'org-export-latex
3268 :type 'boolean)
3270 (defcustom org-export-with-fixed-width t
3271 "Non-nil means, lines starting with \":\" will be in fixed width font.
3272 This can be used to have pre-formatted text, fragments of code etc. For
3273 example:
3274 : ;; Some Lisp examples
3275 : (while (defc cnt)
3276 : (ding))
3277 will be looking just like this in also HTML. See also the QUOTE keyword.
3278 Not all export backends support this.
3280 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3281 :group 'org-export-translation
3282 :type 'boolean)
3284 (defcustom org-match-sexp-depth 3
3285 "Number of stacked braces for sub/superscript matching.
3286 This has to be set before loading org.el to be effective."
3287 :group 'org-export-translation
3288 :type 'integer)
3290 (defgroup org-export-tables nil
3291 "Options for exporting tables in Org-mode."
3292 :tag "Org Export Tables"
3293 :group 'org-export)
3295 (defcustom org-export-with-tables t
3296 "If non-nil, lines starting with \"|\" define a table.
3297 For example:
3299 | Name | Address | Birthday |
3300 |-------------+----------+-----------|
3301 | Arthur Dent | England | 29.2.2100 |
3303 Not all export backends support this.
3305 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3306 :group 'org-export-tables
3307 :type 'boolean)
3309 (defcustom org-export-highlight-first-table-line t
3310 "Non-nil means, highlight the first table line.
3311 In HTML export, this means use <th> instead of <td>.
3312 In tables created with table.el, this applies to the first table line.
3313 In Org-mode tables, all lines before the first horizontal separator
3314 line will be formatted with <th> tags."
3315 :group 'org-export-tables
3316 :type 'boolean)
3318 (defcustom org-export-table-remove-special-lines t
3319 "Remove special lines and marking characters in calculating tables.
3320 This removes the special marking character column from tables that are set
3321 up for spreadsheet calculations. It also removes the entire lines
3322 marked with `!', `_', or `^'. The lines with `$' are kept, because
3323 the values of constants may be useful to have."
3324 :group 'org-export-tables
3325 :type 'boolean)
3327 (defcustom org-export-prefer-native-exporter-for-tables nil
3328 "Non-nil means, always export tables created with table.el natively.
3329 Natively means, use the HTML code generator in table.el.
3330 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3331 the table does not use row- or column-spanning). This has the
3332 advantage, that the automatic HTML conversions for math symbols and
3333 sub/superscripts can be applied. Org-mode's HTML generator is also
3334 much faster."
3335 :group 'org-export-tables
3336 :type 'boolean)
3338 (defgroup org-export-ascii nil
3339 "Options specific for ASCII export of Org-mode files."
3340 :tag "Org Export ASCII"
3341 :group 'org-export)
3343 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3344 "Characters for underlining headings in ASCII export.
3345 In the given sequence, these characters will be used for level 1, 2, ..."
3346 :group 'org-export-ascii
3347 :type '(repeat character))
3349 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3350 "Bullet characters for headlines converted to lists in ASCII export.
3351 The first character is used for the first lest level generated in this
3352 way, and so on. If there are more levels than characters given here,
3353 the list will be repeated.
3354 Note that plain lists will keep the same bullets as the have in the
3355 Org-mode file."
3356 :group 'org-export-ascii
3357 :type '(repeat character))
3359 (defgroup org-export-xml nil
3360 "Options specific for XML export of Org-mode files."
3361 :tag "Org Export XML"
3362 :group 'org-export)
3364 (defgroup org-export-html nil
3365 "Options specific for HTML export of Org-mode files."
3366 :tag "Org Export HTML"
3367 :group 'org-export)
3369 (defcustom org-export-html-coding-system nil
3371 :group 'org-export-html
3372 :type 'coding-system)
3374 (defcustom org-export-html-extension "html"
3375 "The extension for exported HTML files."
3376 :group 'org-export-html
3377 :type 'string)
3379 (defcustom org-export-html-style
3380 "<style type=\"text/css\">
3381 html {
3382 font-family: Times, serif;
3383 font-size: 12pt;
3385 .title { text-align: center; }
3386 .todo { color: red; }
3387 .done { color: green; }
3388 .timestamp { color: grey }
3389 .timestamp-kwd { color: CadetBlue }
3390 .tag { background-color:lightblue; font-weight:normal }
3391 .target { background-color: lavender; }
3392 pre {
3393 border: 1pt solid #AEBDCC;
3394 background-color: #F3F5F7;
3395 padding: 5pt;
3396 font-family: courier, monospace;
3398 table { border-collapse: collapse; }
3399 td, th {
3400 vertical-align: top;
3401 <!--border: 1pt solid #ADB9CC;-->
3403 </style>"
3404 "The default style specification for exported HTML files.
3405 Since there are different ways of setting style information, this variable
3406 needs to contain the full HTML structure to provide a style, including the
3407 surrounding HTML tags. The style specifications should include definitions
3408 for new classes todo, done, title, and deadline. For example, legal values
3409 would be:
3411 <style type=\"text/css\">
3412 p { font-weight: normal; color: gray; }
3413 h1 { color: black; }
3414 .title { text-align: center; }
3415 .todo, .deadline { color: red; }
3416 .done { color: green; }
3417 </style>
3419 or, if you want to keep the style in a file,
3421 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3423 As the value of this option simply gets inserted into the HTML <head> header,
3424 you can \"misuse\" it to add arbitrary text to the header."
3425 :group 'org-export-html
3426 :type 'string)
3429 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3430 "Format for typesetting the document title in HTML export."
3431 :group 'org-export-html
3432 :type 'string)
3434 (defcustom org-export-html-toplevel-hlevel 2
3435 "The <H> level for level 1 headings in HTML export."
3436 :group 'org-export-html
3437 :type 'string)
3439 (defcustom org-export-html-link-org-files-as-html t
3440 "Non-nil means, make file links to `file.org' point to `file.html'.
3441 When org-mode is exporting an org-mode file to HTML, links to
3442 non-html files are directly put into a href tag in HTML.
3443 However, links to other Org-mode files (recognized by the
3444 extension `.org.) should become links to the corresponding html
3445 file, assuming that the linked org-mode file will also be
3446 converted to HTML.
3447 When nil, the links still point to the plain `.org' file."
3448 :group 'org-export-html
3449 :type 'boolean)
3451 (defcustom org-export-html-inline-images 'maybe
3452 "Non-nil means, inline images into exported HTML pages.
3453 This is done using an <img> tag. When nil, an anchor with href is used to
3454 link to the image. If this option is `maybe', then images in links with
3455 an empty description will be inlined, while images with a description will
3456 be linked only."
3457 :group 'org-export-html
3458 :type '(choice (const :tag "Never" nil)
3459 (const :tag "Always" t)
3460 (const :tag "When there is no description" maybe)))
3462 ;; FIXME: rename
3463 (defcustom org-export-html-expand t
3464 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3465 When nil, these tags will be exported as plain text and therefore
3466 not be interpreted by a browser.
3468 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3469 :group 'org-export-html
3470 :type 'boolean)
3472 (defcustom org-export-html-table-tag
3473 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3474 "The HTML tag that is used to start a table.
3475 This must be a <table> tag, but you may change the options like
3476 borders and spacing."
3477 :group 'org-export-html
3478 :type 'string)
3480 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3481 "The opening tag for table header fields.
3482 This is customizable so that alignment options can be specified."
3483 :group 'org-export-tables
3484 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3486 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3487 "The opening tag for table data fields.
3488 This is customizable so that alignment options can be specified."
3489 :group 'org-export-tables
3490 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3492 (defcustom org-export-html-with-timestamp nil
3493 "If non-nil, write `org-export-html-html-helper-timestamp'
3494 into the exported HTML text. Otherwise, the buffer will just be saved
3495 to a file."
3496 :group 'org-export-html
3497 :type 'boolean)
3499 (defcustom org-export-html-html-helper-timestamp
3500 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3501 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3502 :group 'org-export-html
3503 :type 'string)
3505 (defgroup org-export-icalendar nil
3506 "Options specific for iCalendar export of Org-mode files."
3507 :tag "Org Export iCalendar"
3508 :group 'org-export)
3510 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3511 "The file name for the iCalendar file covering all agenda files.
3512 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3513 The file name should be absolute, the file will be overwritten without warning."
3514 :group 'org-export-icalendar
3515 :type 'file)
3517 (defcustom org-icalendar-include-todo nil
3518 "Non-nil means, export to iCalendar files should also cover TODO items."
3519 :group 'org-export-icalendar
3520 :type '(choice
3521 (const :tag "None" nil)
3522 (const :tag "Unfinished" t)
3523 (const :tag "All" all)))
3525 (defcustom org-icalendar-include-sexps t
3526 "Non-nil means, export to iCalendar files should also cover sexp entries.
3527 These are entries like in the diary, but directly in an Org-mode file."
3528 :group 'org-export-icalendar
3529 :type 'boolean)
3531 (defcustom org-icalendar-include-body 100
3532 "Amount of text below headline to be included in iCalendar export.
3533 This is a number of characters that should maximally be included.
3534 Properties, scheduling and clocking lines will always be removed.
3535 The text will be inserted into the DESCRIPTION field."
3536 :group 'org-export-icalendar
3537 :type '(choice
3538 (const :tag "Nothing" nil)
3539 (const :tag "Everything" t)
3540 (integer :tag "Max characters")))
3542 (defcustom org-icalendar-combined-name "OrgMode"
3543 "Calendar name for the combined iCalendar representing all agenda files."
3544 :group 'org-export-icalendar
3545 :type 'string)
3547 (defgroup org-font-lock nil
3548 "Font-lock settings for highlighting in Org-mode."
3549 :tag "Org Font Lock"
3550 :group 'org)
3552 (defcustom org-level-color-stars-only nil
3553 "Non-nil means fontify only the stars in each headline.
3554 When nil, the entire headline is fontified.
3555 Changing it requires restart of `font-lock-mode' to become effective
3556 also in regions already fontified."
3557 :group 'org-font-lock
3558 :type 'boolean)
3560 (defcustom org-hide-leading-stars nil
3561 "Non-nil means, hide the first N-1 stars in a headline.
3562 This works by using the face `org-hide' for these stars. This
3563 face is white for a light background, and black for a dark
3564 background. You may have to customize the face `org-hide' to
3565 make this work.
3566 Changing it requires restart of `font-lock-mode' to become effective
3567 also in regions already fontified.
3568 You may also set this on a per-file basis by adding one of the following
3569 lines to the buffer:
3571 #+STARTUP: hidestars
3572 #+STARTUP: showstars"
3573 :group 'org-font-lock
3574 :type 'boolean)
3576 (defcustom org-fontify-done-headline nil
3577 "Non-nil means, change the face of a headline if it is marked DONE.
3578 Normally, only the TODO/DONE keyword indicates the state of a headline.
3579 When this is non-nil, the headline after the keyword is set to the
3580 `org-headline-done' as an additional indication."
3581 :group 'org-font-lock
3582 :type 'boolean)
3584 (defcustom org-fontify-emphasized-text t
3585 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3586 Changing this variable requires a restart of Emacs to take effect."
3587 :group 'org-font-lock
3588 :type 'boolean)
3590 (defcustom org-highlight-latex-fragments-and-specials nil
3591 "Non-nil means, fontify what is treated specially by the exporters."
3592 :group 'org-font-lock
3593 :type 'boolean)
3595 (defcustom org-hide-emphasis-markers nil
3596 "Non-nil mean font-lock should hide the emphasis marker characters."
3597 :group 'org-font-lock
3598 :type 'boolean)
3600 (defvar org-emph-re nil
3601 "Regular expression for matching emphasis.")
3602 (defvar org-verbatim-re nil
3603 "Regular expression for matching verbatim text.")
3604 (defvar org-emphasis-regexp-components) ; defined just below
3605 (defvar org-emphasis-alist) ; defined just below
3606 (defun org-set-emph-re (var val)
3607 "Set variable and compute the emphasis regular expression."
3608 (set var val)
3609 (when (and (boundp 'org-emphasis-alist)
3610 (boundp 'org-emphasis-regexp-components)
3611 org-emphasis-alist org-emphasis-regexp-components)
3612 (let* ((e org-emphasis-regexp-components)
3613 (pre (car e))
3614 (post (nth 1 e))
3615 (border (nth 2 e))
3616 (body (nth 3 e))
3617 (nl (nth 4 e))
3618 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3619 (body1 (concat body "*?"))
3620 (markers (mapconcat 'car org-emphasis-alist ""))
3621 (vmarkers (mapconcat
3622 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3623 org-emphasis-alist "")))
3624 ;; make sure special characters appear at the right position in the class
3625 (if (string-match "\\^" markers)
3626 (setq markers (concat (replace-match "" t t markers) "^")))
3627 (if (string-match "-" markers)
3628 (setq markers (concat (replace-match "" t t markers) "-")))
3629 (if (string-match "\\^" vmarkers)
3630 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3631 (if (string-match "-" vmarkers)
3632 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3633 (if (> nl 0)
3634 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3635 (int-to-string nl) "\\}")))
3636 ;; Make the regexp
3637 (setq org-emph-re
3638 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3639 "\\("
3640 "\\([" markers "]\\)"
3641 "\\("
3642 "[^" border "]\\|"
3643 "[^" border (if (and nil stacked) markers) "]"
3644 body1
3645 "[^" border (if (and nil stacked) markers) "]"
3646 "\\)"
3647 "\\3\\)"
3648 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3649 (setq org-verbatim-re
3650 (concat "\\([" pre "]\\|^\\)"
3651 "\\("
3652 "\\([" vmarkers "]\\)"
3653 "\\("
3654 "[^" border "]\\|"
3655 "[^" border "]"
3656 body1
3657 "[^" border "]"
3658 "\\)"
3659 "\\3\\)"
3660 "\\([" post "]\\|$\\)")))))
3662 (defcustom org-emphasis-regexp-components
3663 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3664 "Components used to build the regular expression for emphasis.
3665 This is a list with 6 entries. Terminology: In an emphasis string
3666 like \" *strong word* \", we call the initial space PREMATCH, the final
3667 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3668 and \"trong wor\" is the body. The different components in this variable
3669 specify what is allowed/forbidden in each part:
3671 pre Chars allowed as prematch. Beginning of line will be allowed too.
3672 post Chars allowed as postmatch. End of line will be allowed too.
3673 border The chars *forbidden* as border characters.
3674 body-regexp A regexp like \".\" to match a body character. Don't use
3675 non-shy groups here, and don't allow newline here.
3676 newline The maximum number of newlines allowed in an emphasis exp.
3678 Use customize to modify this, or restart Emacs after changing it."
3679 :group 'org-font-lock
3680 :set 'org-set-emph-re
3681 :type '(list
3682 (sexp :tag "Allowed chars in pre ")
3683 (sexp :tag "Allowed chars in post ")
3684 (sexp :tag "Forbidden chars in border ")
3685 (sexp :tag "Regexp for body ")
3686 (integer :tag "number of newlines allowed")
3687 (option (boolean :tag "Stacking (DISABLED) "))))
3689 (defcustom org-emphasis-alist
3690 '(("*" bold "<b>" "</b>")
3691 ("/" italic "<i>" "</i>")
3692 ("_" underline "<u>" "</u>")
3693 ("=" org-code "<code>" "</code>" verbatim)
3694 ("~" org-verbatim "" "" verbatim)
3695 ("+" (:strike-through t) "<del>" "</del>")
3697 "Special syntax for emphasized text.
3698 Text starting and ending with a special character will be emphasized, for
3699 example *bold*, _underlined_ and /italic/. This variable sets the marker
3700 characters, the face to be used by font-lock for highlighting in Org-mode
3701 Emacs buffers, and the HTML tags to be used for this.
3702 Use customize to modify this, or restart Emacs after changing it."
3703 :group 'org-font-lock
3704 :set 'org-set-emph-re
3705 :type '(repeat
3706 (list
3707 (string :tag "Marker character")
3708 (choice
3709 (face :tag "Font-lock-face")
3710 (plist :tag "Face property list"))
3711 (string :tag "HTML start tag")
3712 (string :tag "HTML end tag")
3713 (option (const verbatim)))))
3715 ;;; The faces
3717 (defgroup org-faces nil
3718 "Faces in Org-mode."
3719 :tag "Org Faces"
3720 :group 'org-font-lock)
3722 (defun org-compatible-face (inherits specs)
3723 "Make a compatible face specification.
3724 If INHERITS is an existing face and if the Emacs version supports it,
3725 just inherit the face. If not, use SPECS to define the face.
3726 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3727 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3728 to the top of the list. The `min-colors' attribute will be removed from
3729 any other entries, and any resulting duplicates will be removed entirely."
3730 (cond
3731 ((and inherits (facep inherits)
3732 (not (featurep 'xemacs)) (> emacs-major-version 22))
3733 ;; In Emacs 23, we use inheritance where possible.
3734 ;; We only do this in Emacs 23, because only there the outline
3735 ;; faces have been changed to the original org-mode-level-faces.
3736 (list (list t :inherit inherits)))
3737 ((or (featurep 'xemacs) (< emacs-major-version 22))
3738 ;; These do not understand the `min-colors' attribute.
3739 (let (r e a)
3740 (while (setq e (pop specs))
3741 (cond
3742 ((memq (car e) '(t default)) (push e r))
3743 ((setq a (member '(min-colors 8) (car e)))
3744 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3745 (cdr e)))))
3746 ((setq a (assq 'min-colors (car e)))
3747 (setq e (cons (delq a (car e)) (cdr e)))
3748 (or (assoc (car e) r) (push e r)))
3749 (t (or (assoc (car e) r) (push e r)))))
3750 (nreverse r)))
3751 (t specs)))
3752 (put 'org-compatible-face 'lisp-indent-function 1)
3754 (defface org-hide
3755 '((((background light)) (:foreground "white"))
3756 (((background dark)) (:foreground "black")))
3757 "Face used to hide leading stars in headlines.
3758 The forground color of this face should be equal to the background
3759 color of the frame."
3760 :group 'org-faces)
3762 (defface org-level-1 ;; font-lock-function-name-face
3763 (org-compatible-face 'outline-1
3764 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3765 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3766 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3767 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3768 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3769 (t (:bold t))))
3770 "Face used for level 1 headlines."
3771 :group 'org-faces)
3773 (defface org-level-2 ;; font-lock-variable-name-face
3774 (org-compatible-face 'outline-2
3775 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3776 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3777 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3778 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3779 (t (:bold t))))
3780 "Face used for level 2 headlines."
3781 :group 'org-faces)
3783 (defface org-level-3 ;; font-lock-keyword-face
3784 (org-compatible-face 'outline-3
3785 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3786 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3787 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3788 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3789 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3790 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3791 (t (:bold t))))
3792 "Face used for level 3 headlines."
3793 :group 'org-faces)
3795 (defface org-level-4 ;; font-lock-comment-face
3796 (org-compatible-face 'outline-4
3797 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3798 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3799 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3800 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3801 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3802 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3803 (t (:bold t))))
3804 "Face used for level 4 headlines."
3805 :group 'org-faces)
3807 (defface org-level-5 ;; font-lock-type-face
3808 (org-compatible-face 'outline-5
3809 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3810 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3811 (((class color) (min-colors 8)) (:foreground "green"))))
3812 "Face used for level 5 headlines."
3813 :group 'org-faces)
3815 (defface org-level-6 ;; font-lock-constant-face
3816 (org-compatible-face 'outline-6
3817 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3818 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3819 (((class color) (min-colors 8)) (:foreground "magenta"))))
3820 "Face used for level 6 headlines."
3821 :group 'org-faces)
3823 (defface org-level-7 ;; font-lock-builtin-face
3824 (org-compatible-face 'outline-7
3825 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3826 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3827 (((class color) (min-colors 8)) (:foreground "blue"))))
3828 "Face used for level 7 headlines."
3829 :group 'org-faces)
3831 (defface org-level-8 ;; font-lock-string-face
3832 (org-compatible-face 'outline-8
3833 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3834 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3835 (((class color) (min-colors 8)) (:foreground "green"))))
3836 "Face used for level 8 headlines."
3837 :group 'org-faces)
3839 (defface org-special-keyword ;; font-lock-string-face
3840 (org-compatible-face nil
3841 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3842 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3843 (t (:italic t))))
3844 "Face used for special keywords."
3845 :group 'org-faces)
3847 (defface org-drawer ;; font-lock-function-name-face
3848 (org-compatible-face nil
3849 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3850 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3851 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3852 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3853 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3854 (t (:bold t))))
3855 "Face used for drawers."
3856 :group 'org-faces)
3858 (defface org-property-value nil
3859 "Face used for the value of a property."
3860 :group 'org-faces)
3862 (defface org-column
3863 (org-compatible-face nil
3864 '((((class color) (min-colors 16) (background light))
3865 (:background "grey90"))
3866 (((class color) (min-colors 16) (background dark))
3867 (:background "grey30"))
3868 (((class color) (min-colors 8))
3869 (:background "cyan" :foreground "black"))
3870 (t (:inverse-video t))))
3871 "Face for column display of entry properties."
3872 :group 'org-faces)
3874 (when (fboundp 'set-face-attribute)
3875 ;; Make sure that a fixed-width face is used when we have a column table.
3876 (set-face-attribute 'org-column nil
3877 :height (face-attribute 'default :height)
3878 :family (face-attribute 'default :family)))
3880 (defface org-warning
3881 (org-compatible-face 'font-lock-warning-face
3882 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3883 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3884 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3885 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3886 (t (:bold t))))
3887 "Face for deadlines and TODO keywords."
3888 :group 'org-faces)
3890 (defface org-archived ; similar to shadow
3891 (org-compatible-face 'shadow
3892 '((((class color grayscale) (min-colors 88) (background light))
3893 (:foreground "grey50"))
3894 (((class color grayscale) (min-colors 88) (background dark))
3895 (:foreground "grey70"))
3896 (((class color) (min-colors 8) (background light))
3897 (:foreground "green"))
3898 (((class color) (min-colors 8) (background dark))
3899 (:foreground "yellow"))))
3900 "Face for headline with the ARCHIVE tag."
3901 :group 'org-faces)
3903 (defface org-link
3904 '((((class color) (background light)) (:foreground "Purple" :underline t))
3905 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3906 (t (:underline t)))
3907 "Face for links."
3908 :group 'org-faces)
3910 (defface org-ellipsis
3911 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3912 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3913 (t (:strike-through t)))
3914 "Face for the ellipsis in folded text."
3915 :group 'org-faces)
3917 (defface org-target
3918 '((((class color) (background light)) (:underline t))
3919 (((class color) (background dark)) (:underline t))
3920 (t (:underline t)))
3921 "Face for links."
3922 :group 'org-faces)
3924 (defface org-date
3925 '((((class color) (background light)) (:foreground "Purple" :underline t))
3926 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3927 (t (:underline t)))
3928 "Face for links."
3929 :group 'org-faces)
3931 (defface org-sexp-date
3932 '((((class color) (background light)) (:foreground "Purple"))
3933 (((class color) (background dark)) (:foreground "Cyan"))
3934 (t (:underline t)))
3935 "Face for links."
3936 :group 'org-faces)
3938 (defface org-tag
3939 '((t (:bold t)))
3940 "Face for tags."
3941 :group 'org-faces)
3943 (defface org-todo ; font-lock-warning-face
3944 (org-compatible-face nil
3945 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3946 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3947 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3948 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3949 (t (:inverse-video t :bold t))))
3950 "Face for TODO keywords."
3951 :group 'org-faces)
3953 (defface org-done ;; font-lock-type-face
3954 (org-compatible-face nil
3955 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3956 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3957 (((class color) (min-colors 8)) (:foreground "green"))
3958 (t (:bold t))))
3959 "Face used for todo keywords that indicate DONE items."
3960 :group 'org-faces)
3962 (defface org-headline-done ;; font-lock-string-face
3963 (org-compatible-face nil
3964 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3965 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3966 (((class color) (min-colors 8) (background light)) (:bold nil))))
3967 "Face used to indicate that a headline is DONE.
3968 This face is only used if `org-fontify-done-headline' is set. If applies
3969 to the part of the headline after the DONE keyword."
3970 :group 'org-faces)
3972 (defcustom org-todo-keyword-faces nil
3973 "Faces for specific TODO keywords.
3974 This is a list of cons cells, with TODO keywords in the car
3975 and faces in the cdr. The face can be a symbol, or a property
3976 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3977 :group 'org-faces
3978 :group 'org-todo
3979 :type '(repeat
3980 (cons
3981 (string :tag "keyword")
3982 (sexp :tag "face"))))
3984 (defface org-table ;; font-lock-function-name-face
3985 (org-compatible-face nil
3986 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3987 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3988 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3989 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3990 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3991 (((class color) (min-colors 8) (background dark)))))
3992 "Face used for tables."
3993 :group 'org-faces)
3995 (defface org-formula
3996 (org-compatible-face nil
3997 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3998 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3999 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4000 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4001 (t (:bold t :italic t))))
4002 "Face for formulas."
4003 :group 'org-faces)
4005 (defface org-code
4006 (org-compatible-face nil
4007 '((((class color grayscale) (min-colors 88) (background light))
4008 (:foreground "grey50"))
4009 (((class color grayscale) (min-colors 88) (background dark))
4010 (:foreground "grey70"))
4011 (((class color) (min-colors 8) (background light))
4012 (:foreground "green"))
4013 (((class color) (min-colors 8) (background dark))
4014 (:foreground "yellow"))))
4015 "Face for fixed-with text like code snippets."
4016 :group 'org-faces
4017 :version "22.1")
4019 (defface org-verbatim
4020 (org-compatible-face nil
4021 '((((class color grayscale) (min-colors 88) (background light))
4022 (:foreground "grey50" :underline t))
4023 (((class color grayscale) (min-colors 88) (background dark))
4024 (:foreground "grey70" :underline t))
4025 (((class color) (min-colors 8) (background light))
4026 (:foreground "green" :underline t))
4027 (((class color) (min-colors 8) (background dark))
4028 (:foreground "yellow" :underline t))))
4029 "Face for fixed-with text like code snippets."
4030 :group 'org-faces
4031 :version "22.1")
4033 (defface org-agenda-structure ;; font-lock-function-name-face
4034 (org-compatible-face nil
4035 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4036 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4037 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4038 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4039 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4040 (t (:bold t))))
4041 "Face used in agenda for captions and dates."
4042 :group 'org-faces)
4044 (defface org-scheduled-today
4045 (org-compatible-face nil
4046 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4047 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4048 (((class color) (min-colors 8)) (:foreground "green"))
4049 (t (:bold t :italic t))))
4050 "Face for items scheduled for a certain day."
4051 :group 'org-faces)
4053 (defface org-scheduled-previously
4054 (org-compatible-face nil
4055 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4056 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4057 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4058 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4059 (t (:bold t))))
4060 "Face for items scheduled previously, and not yet done."
4061 :group 'org-faces)
4063 (defface org-upcoming-deadline
4064 (org-compatible-face nil
4065 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4066 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4067 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4068 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4069 (t (:bold t))))
4070 "Face for items scheduled previously, and not yet done."
4071 :group 'org-faces)
4073 (defcustom org-agenda-deadline-faces
4074 '((1.0 . org-warning)
4075 (0.5 . org-upcoming-deadline)
4076 (0.0 . default))
4077 "Faces for showing deadlines in the agenda.
4078 This is a list of cons cells. The cdr of each cell is a face to be used,
4079 and it can also just be like '(:foreground \"yellow\").
4080 Each car is a fraction of the head-warning time that must have passed for
4081 this the face in the cdr to be used for display. The numbers must be
4082 given in descending order. The head-warning time is normally taken
4083 from `org-deadline-warning-days', but can also be specified in the deadline
4084 timestamp itself, like this:
4086 DEADLINE: <2007-08-13 Mon -8d>
4088 You may use d for days, w for weeks, m for months and y for years. Months
4089 and years will only be treated in an approximate fashion (30.4 days for a
4090 month and 365.24 days for a year)."
4091 :group 'org-faces
4092 :group 'org-agenda-daily/weekly
4093 :type '(repeat
4094 (cons
4095 (number :tag "Fraction of head-warning time passed")
4096 (sexp :tag "Face"))))
4098 ;; FIXME: this is not a good face yet.
4099 (defface org-agenda-restriction-lock
4100 (org-compatible-face nil
4101 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4102 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4103 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4104 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4105 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4106 (t (:inverse-video t))))
4107 "Face for showing the agenda restriction lock."
4108 :group 'org-faces)
4110 (defface org-time-grid ;; font-lock-variable-name-face
4111 (org-compatible-face nil
4112 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4113 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4114 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4115 "Face used for time grids."
4116 :group 'org-faces)
4118 (defconst org-level-faces
4119 '(org-level-1 org-level-2 org-level-3 org-level-4
4120 org-level-5 org-level-6 org-level-7 org-level-8
4123 (defcustom org-n-level-faces (length org-level-faces)
4124 "The number different faces to be used for headlines.
4125 Org-mode defines 8 different headline faces, so this can be at most 8.
4126 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4127 :type 'number
4128 :group 'org-faces)
4130 ;;; Functions and variables from ther packages
4131 ;; Declared here to avoid compiler warnings
4133 (eval-and-compile
4134 (unless (fboundp 'declare-function)
4135 (defmacro declare-function (fn file &optional arglist fileonly))))
4137 ;; XEmacs only
4138 (defvar outline-mode-menu-heading)
4139 (defvar outline-mode-menu-show)
4140 (defvar outline-mode-menu-hide)
4141 (defvar zmacs-regions) ; XEmacs regions
4143 ;; Emacs only
4144 (defvar mark-active)
4146 ;; Various packages
4147 ;; FIXME: get the argument lists for the UNKNOWN stuff
4148 (declare-function add-to-diary-list "diary-lib"
4149 (date string specifier &optional marker globcolor literal))
4150 (declare-function table--at-cell-p "table" (position &optional object at-column))
4151 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4152 (declare-function Info-goto-node "info" (nodename &optional fork))
4153 (declare-function bbdb "ext:bbdb-com" (string elidep))
4154 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4155 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4156 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4157 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4158 (declare-function bbdb-record-name "ext:bbdb" (record))
4159 (declare-function bibtex-beginning-of-entry "bibtex" ())
4160 (declare-function bibtex-generate-autokey "bibtex" ())
4161 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4162 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4163 (defvar calc-embedded-close-formula)
4164 (defvar calc-embedded-open-formula)
4165 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4166 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4167 (declare-function calendar-check-holidays "holidays" (date))
4168 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4169 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4170 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4171 (declare-function calendar-forward-day "cal-move" (arg))
4172 (declare-function calendar-french-date-string "cal-french" (&optional date))
4173 (declare-function calendar-goto-date "cal-move" (date))
4174 (declare-function calendar-goto-today "cal-move" ())
4175 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4176 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4177 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4178 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4179 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4180 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4181 (defvar calendar-mode-map)
4182 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4183 (declare-function cdlatex-tab "ext:cdlatex" ())
4184 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4185 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4186 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4187 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4188 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4189 (defvar font-lock-unfontify-region-function)
4190 (declare-function gnus-article-show-summary "gnus-art" ())
4191 (declare-function gnus-summary-last-subject "gnus-sum" ())
4192 (defvar gnus-other-frame-object)
4193 (defvar gnus-group-name)
4194 (defvar gnus-article-current)
4195 (defvar Info-current-file)
4196 (defvar Info-current-node)
4197 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4198 (declare-function mh-find-path "mh-utils" ())
4199 (declare-function mh-get-header-field "mh-utils" (field))
4200 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4201 (declare-function mh-header-display "mh-show" ())
4202 (declare-function mh-index-previous-folder "mh-search" ())
4203 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4204 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4205 (declare-function mh-search-choose "mh-search" (&optional searcher))
4206 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4207 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4208 (declare-function mh-show-header-display "mh-show" t t)
4209 (declare-function mh-show-msg "mh-show" (msg))
4210 (declare-function mh-show-show "mh-show" t t)
4211 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4212 (defvar mh-progs)
4213 (defvar mh-current-folder)
4214 (defvar mh-show-folder-buffer)
4215 (defvar mh-index-folder)
4216 (defvar mh-searcher)
4217 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4218 (declare-function parse-time-string "parse-time" (string))
4219 (declare-function remember "remember" (&optional initial))
4220 (declare-function remember-buffer-desc "remember" ())
4221 (defvar remember-save-after-remembering)
4222 (defvar remember-data-file)
4223 (defvar remember-register)
4224 (defvar remember-buffer)
4225 (defvar remember-handler-functions)
4226 (defvar remember-annotation-functions)
4227 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4228 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4229 (declare-function rmail-what-message "rmail" ())
4230 (defvar texmathp-why)
4231 (declare-function vm-beginning-of-message "ext:vm-page" ())
4232 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4233 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4234 (declare-function vm-isearch-narrow "ext:vm-search" ())
4235 (declare-function vm-isearch-update "ext:vm-search" ())
4236 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4237 (declare-function vm-su-message-id "ext:vm-summary" (m))
4238 (declare-function vm-su-subject "ext:vm-summary" (m))
4239 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4240 (defvar vm-message-pointer)
4241 (defvar vm-folder-directory)
4242 (defvar w3m-current-url)
4243 (defvar w3m-current-title)
4244 ;; backward compatibility to old version of wl
4245 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4246 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4247 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4248 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4249 (declare-function wl-summary-line-from "ext:wl-summary" ())
4250 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4251 (declare-function wl-summary-message-number "ext:wl-summary" ())
4252 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4253 (defvar wl-summary-buffer-elmo-folder)
4254 (defvar wl-summary-buffer-folder-name)
4255 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4257 (defvar org-latex-regexps)
4258 (defvar constants-unit-system)
4260 ;;; Variables for pre-computed regular expressions, all buffer local
4262 (defvar org-drawer-regexp nil
4263 "Matches first line of a hidden block.")
4264 (make-variable-buffer-local 'org-drawer-regexp)
4265 (defvar org-todo-regexp nil
4266 "Matches any of the TODO state keywords.")
4267 (make-variable-buffer-local 'org-todo-regexp)
4268 (defvar org-not-done-regexp nil
4269 "Matches any of the TODO state keywords except the last one.")
4270 (make-variable-buffer-local 'org-not-done-regexp)
4271 (defvar org-todo-line-regexp nil
4272 "Matches a headline and puts TODO state into group 2 if present.")
4273 (make-variable-buffer-local 'org-todo-line-regexp)
4274 (defvar org-complex-heading-regexp nil
4275 "Matches a headline and puts everything into groups:
4276 group 1: the stars
4277 group 2: The todo keyword, maybe
4278 group 3: Priority cookie
4279 group 4: True headline
4280 group 5: Tags")
4281 (make-variable-buffer-local 'org-complex-heading-regexp)
4282 (defvar org-todo-line-tags-regexp nil
4283 "Matches a headline and puts TODO state into group 2 if present.
4284 Also put tags into group 4 if tags are present.")
4285 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4286 (defvar org-nl-done-regexp nil
4287 "Matches newline followed by a headline with the DONE keyword.")
4288 (make-variable-buffer-local 'org-nl-done-regexp)
4289 (defvar org-looking-at-done-regexp nil
4290 "Matches the DONE keyword a point.")
4291 (make-variable-buffer-local 'org-looking-at-done-regexp)
4292 (defvar org-ds-keyword-length 12
4293 "Maximum length of the Deadline and SCHEDULED keywords.")
4294 (make-variable-buffer-local 'org-ds-keyword-length)
4295 (defvar org-deadline-regexp nil
4296 "Matches the DEADLINE keyword.")
4297 (make-variable-buffer-local 'org-deadline-regexp)
4298 (defvar org-deadline-time-regexp nil
4299 "Matches the DEADLINE keyword together with a time stamp.")
4300 (make-variable-buffer-local 'org-deadline-time-regexp)
4301 (defvar org-deadline-line-regexp nil
4302 "Matches the DEADLINE keyword and the rest of the line.")
4303 (make-variable-buffer-local 'org-deadline-line-regexp)
4304 (defvar org-scheduled-regexp nil
4305 "Matches the SCHEDULED keyword.")
4306 (make-variable-buffer-local 'org-scheduled-regexp)
4307 (defvar org-scheduled-time-regexp nil
4308 "Matches the SCHEDULED keyword together with a time stamp.")
4309 (make-variable-buffer-local 'org-scheduled-time-regexp)
4310 (defvar org-closed-time-regexp nil
4311 "Matches the CLOSED keyword together with a time stamp.")
4312 (make-variable-buffer-local 'org-closed-time-regexp)
4314 (defvar org-keyword-time-regexp nil
4315 "Matches any of the 4 keywords, together with the time stamp.")
4316 (make-variable-buffer-local 'org-keyword-time-regexp)
4317 (defvar org-keyword-time-not-clock-regexp nil
4318 "Matches any of the 3 keywords, together with the time stamp.")
4319 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4320 (defvar org-maybe-keyword-time-regexp nil
4321 "Matches a timestamp, possibly preceeded by a keyword.")
4322 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4323 (defvar org-planning-or-clock-line-re nil
4324 "Matches a line with planning or clock info.")
4325 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4327 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4328 rear-nonsticky t mouse-map t fontified t)
4329 "Properties to remove when a string without properties is wanted.")
4331 (defsubst org-match-string-no-properties (num &optional string)
4332 (if (featurep 'xemacs)
4333 (let ((s (match-string num string)))
4334 (remove-text-properties 0 (length s) org-rm-props s)
4336 (match-string-no-properties num string)))
4338 (defsubst org-no-properties (s)
4339 (if (fboundp 'set-text-properties)
4340 (set-text-properties 0 (length s) nil s)
4341 (remove-text-properties 0 (length s) org-rm-props s))
4344 (defsubst org-get-alist-option (option key)
4345 (cond ((eq key t) t)
4346 ((eq option t) t)
4347 ((assoc key option) (cdr (assoc key option)))
4348 (t (cdr (assq 'default option)))))
4350 (defsubst org-inhibit-invisibility ()
4351 "Modified `buffer-invisibility-spec' for Emacs 21.
4352 Some ops with invisible text do not work correctly on Emacs 21. For these
4353 we turn off invisibility temporarily. Use this in a `let' form."
4354 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4356 (defsubst org-set-local (var value)
4357 "Make VAR local in current buffer and set it to VALUE."
4358 (set (make-variable-buffer-local var) value))
4360 (defsubst org-mode-p ()
4361 "Check if the current buffer is in Org-mode."
4362 (eq major-mode 'org-mode))
4364 (defsubst org-last (list)
4365 "Return the last element of LIST."
4366 (car (last list)))
4368 (defun org-let (list &rest body)
4369 (eval (cons 'let (cons list body))))
4370 (put 'org-let 'lisp-indent-function 1)
4372 (defun org-let2 (list1 list2 &rest body)
4373 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4374 (put 'org-let2 'lisp-indent-function 2)
4375 (defconst org-startup-options
4376 '(("fold" org-startup-folded t)
4377 ("overview" org-startup-folded t)
4378 ("nofold" org-startup-folded nil)
4379 ("showall" org-startup-folded nil)
4380 ("content" org-startup-folded content)
4381 ("hidestars" org-hide-leading-stars t)
4382 ("showstars" org-hide-leading-stars nil)
4383 ("odd" org-odd-levels-only t)
4384 ("oddeven" org-odd-levels-only nil)
4385 ("align" org-startup-align-all-tables t)
4386 ("noalign" org-startup-align-all-tables nil)
4387 ("customtime" org-display-custom-times t)
4388 ("logging" org-log-done t)
4389 ("logdone" org-log-done t)
4390 ("nologging" org-log-done nil)
4391 ("lognotedone" org-log-done done push)
4392 ("lognotestate" org-log-done state push)
4393 ("lognoteclock-out" org-log-done clock-out push)
4394 ("logrepeat" org-log-repeat t)
4395 ("nologrepeat" org-log-repeat nil)
4396 ("constcgs" constants-unit-system cgs)
4397 ("constSI" constants-unit-system SI))
4398 "Variable associated with STARTUP options for org-mode.
4399 Each element is a list of three items: The startup options as written
4400 in the #+STARTUP line, the corresponding variable, and the value to
4401 set this variable to if the option is found. An optional forth element PUSH
4402 means to push this value onto the list in the variable.")
4404 (defun org-set-regexps-and-options ()
4405 "Precompute regular expressions for current buffer."
4406 (when (org-mode-p)
4407 (org-set-local 'org-todo-kwd-alist nil)
4408 (org-set-local 'org-todo-key-alist nil)
4409 (org-set-local 'org-todo-key-trigger nil)
4410 (org-set-local 'org-todo-keywords-1 nil)
4411 (org-set-local 'org-done-keywords nil)
4412 (org-set-local 'org-todo-heads nil)
4413 (org-set-local 'org-todo-sets nil)
4414 (org-set-local 'org-todo-log-states nil)
4415 (let ((re (org-make-options-regexp
4416 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4417 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4418 "CONSTANTS" "PROPERTY" "DRAWERS")))
4419 (splitre "[ \t]+")
4420 kwds kws0 kwsa key value cat arch tags const links hw dws
4421 tail sep kws1 prio props drawers
4422 ex log)
4423 (save-excursion
4424 (save-restriction
4425 (widen)
4426 (goto-char (point-min))
4427 (while (re-search-forward re nil t)
4428 (setq key (match-string 1) value (org-match-string-no-properties 2))
4429 (cond
4430 ((equal key "CATEGORY")
4431 (if (string-match "[ \t]+$" value)
4432 (setq value (replace-match "" t t value)))
4433 (setq cat value))
4434 ((member key '("SEQ_TODO" "TODO"))
4435 (push (cons 'sequence (org-split-string value splitre)) kwds))
4436 ((equal key "TYP_TODO")
4437 (push (cons 'type (org-split-string value splitre)) kwds))
4438 ((equal key "TAGS")
4439 (setq tags (append tags (org-split-string value splitre))))
4440 ((equal key "COLUMNS")
4441 (org-set-local 'org-columns-default-format value))
4442 ((equal key "LINK")
4443 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4444 (push (cons (match-string 1 value)
4445 (org-trim (match-string 2 value)))
4446 links)))
4447 ((equal key "PRIORITIES")
4448 (setq prio (org-split-string value " +")))
4449 ((equal key "PROPERTY")
4450 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4451 (push (cons (match-string 1 value) (match-string 2 value))
4452 props)))
4453 ((equal key "DRAWERS")
4454 (setq drawers (org-split-string value splitre)))
4455 ((equal key "CONSTANTS")
4456 (setq const (append const (org-split-string value splitre))))
4457 ((equal key "STARTUP")
4458 (let ((opts (org-split-string value splitre))
4459 l var val)
4460 (while (setq l (pop opts))
4461 (when (setq l (assoc l org-startup-options))
4462 (setq var (nth 1 l) val (nth 2 l))
4463 (if (not (nth 3 l))
4464 (set (make-local-variable var) val)
4465 (if (not (listp (symbol-value var)))
4466 (set (make-local-variable var) nil))
4467 (set (make-local-variable var) (symbol-value var))
4468 (add-to-list var val))))))
4469 ((equal key "ARCHIVE")
4470 (string-match " *$" value)
4471 (setq arch (replace-match "" t t value))
4472 (remove-text-properties 0 (length arch)
4473 '(face t fontified t) arch)))
4475 (when cat
4476 (org-set-local 'org-category (intern cat))
4477 (push (cons "CATEGORY" cat) props))
4478 (when prio
4479 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4480 (setq prio (mapcar 'string-to-char prio))
4481 (org-set-local 'org-highest-priority (nth 0 prio))
4482 (org-set-local 'org-lowest-priority (nth 1 prio))
4483 (org-set-local 'org-default-priority (nth 2 prio)))
4484 (and props (org-set-local 'org-local-properties (nreverse props)))
4485 (and drawers (org-set-local 'org-drawers drawers))
4486 (and arch (org-set-local 'org-archive-location arch))
4487 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4488 ;; Process the TODO keywords
4489 (unless kwds
4490 ;; Use the global values as if they had been given locally.
4491 (setq kwds (default-value 'org-todo-keywords))
4492 (if (stringp (car kwds))
4493 (setq kwds (list (cons org-todo-interpretation
4494 (default-value 'org-todo-keywords)))))
4495 (setq kwds (reverse kwds)))
4496 (setq kwds (nreverse kwds))
4497 (let (inter kws kw)
4498 (while (setq kws (pop kwds))
4499 (setq inter (pop kws) sep (member "|" kws)
4500 kws0 (delete "|" (copy-sequence kws))
4501 kwsa nil
4502 kws1 (mapcar
4503 (lambda (x)
4504 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4505 (progn
4506 (setq kw (match-string 1 x)
4507 ex (and (match-end 2) (match-string 2 x))
4508 log (and ex (string-match "@" ex))
4509 key (and ex (substring ex 0 1)))
4510 (if (equal key "@") (setq key nil))
4511 (push (cons kw (and key (string-to-char key))) kwsa)
4512 (and log (push kw org-todo-log-states))
4514 (error "Invalid TODO keyword %s" x)))
4515 kws0)
4516 kwsa (if kwsa (append '((:startgroup))
4517 (nreverse kwsa)
4518 '((:endgroup))))
4519 hw (car kws1)
4520 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4521 tail (list inter hw (car dws) (org-last dws)))
4522 (add-to-list 'org-todo-heads hw 'append)
4523 (push kws1 org-todo-sets)
4524 (setq org-done-keywords (append org-done-keywords dws nil))
4525 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4526 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4527 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4528 (setq org-todo-sets (nreverse org-todo-sets)
4529 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4530 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4531 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4532 ;; Process the constants
4533 (when const
4534 (let (e cst)
4535 (while (setq e (pop const))
4536 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4537 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4538 (setq org-table-formula-constants-local cst)))
4540 ;; Process the tags.
4541 (when tags
4542 (let (e tgs)
4543 (while (setq e (pop tags))
4544 (cond
4545 ((equal e "{") (push '(:startgroup) tgs))
4546 ((equal e "}") (push '(:endgroup) tgs))
4547 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4548 (push (cons (match-string 1 e)
4549 (string-to-char (match-string 2 e)))
4550 tgs))
4551 (t (push (list e) tgs))))
4552 (org-set-local 'org-tag-alist nil)
4553 (while (setq e (pop tgs))
4554 (or (and (stringp (car e))
4555 (assoc (car e) org-tag-alist))
4556 (push e org-tag-alist))))))
4558 ;; Compute the regular expressions and other local variables
4559 (if (not org-done-keywords)
4560 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4561 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4562 (length org-scheduled-string)))
4563 org-drawer-regexp
4564 (concat "^[ \t]*:\\("
4565 (mapconcat 'regexp-quote org-drawers "\\|")
4566 "\\):[ \t]*$")
4567 org-not-done-keywords
4568 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4569 org-todo-regexp
4570 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4571 "\\|") "\\)\\>")
4572 org-not-done-regexp
4573 (concat "\\<\\("
4574 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4575 "\\)\\>")
4576 org-todo-line-regexp
4577 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4578 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4579 "\\)\\>\\)?[ \t]*\\(.*\\)")
4580 org-complex-heading-regexp
4581 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4582 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4583 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4584 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4585 org-nl-done-regexp
4586 (concat "\n\\*+[ \t]+"
4587 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4588 "\\)" "\\>")
4589 org-todo-line-tags-regexp
4590 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4591 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4592 (org-re
4593 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4594 org-looking-at-done-regexp
4595 (concat "^" "\\(?:"
4596 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4597 "\\>")
4598 org-deadline-regexp (concat "\\<" org-deadline-string)
4599 org-deadline-time-regexp
4600 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4601 org-deadline-line-regexp
4602 (concat "\\<\\(" org-deadline-string "\\).*")
4603 org-scheduled-regexp
4604 (concat "\\<" org-scheduled-string)
4605 org-scheduled-time-regexp
4606 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4607 org-closed-time-regexp
4608 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4609 org-keyword-time-regexp
4610 (concat "\\<\\(" org-scheduled-string
4611 "\\|" org-deadline-string
4612 "\\|" org-closed-string
4613 "\\|" org-clock-string "\\)"
4614 " *[[<]\\([^]>]+\\)[]>]")
4615 org-keyword-time-not-clock-regexp
4616 (concat "\\<\\(" org-scheduled-string
4617 "\\|" org-deadline-string
4618 "\\|" org-closed-string
4619 "\\)"
4620 " *[[<]\\([^]>]+\\)[]>]")
4621 org-maybe-keyword-time-regexp
4622 (concat "\\(\\<\\(" org-scheduled-string
4623 "\\|" org-deadline-string
4624 "\\|" org-closed-string
4625 "\\|" org-clock-string "\\)\\)?"
4626 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4627 org-planning-or-clock-line-re
4628 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4629 "\\|" org-deadline-string
4630 "\\|" org-closed-string "\\|" org-clock-string
4631 "\\)\\>\\)")
4633 (org-compute-latex-and-specials-regexp)
4634 (org-set-font-lock-defaults)))
4636 (defun org-remove-keyword-keys (list)
4637 (mapcar (lambda (x)
4638 (if (string-match "(..?)$" x)
4639 (substring x 0 (match-beginning 0))
4641 list))
4643 ;; FIXME: this could be done much better, using second characters etc.
4644 (defun org-assign-fast-keys (alist)
4645 "Assign fast keys to a keyword-key alist.
4646 Respect keys that are already there."
4647 (let (new e k c c1 c2 (char ?a))
4648 (while (setq e (pop alist))
4649 (cond
4650 ((equal e '(:startgroup)) (push e new))
4651 ((equal e '(:endgroup)) (push e new))
4653 (setq k (car e) c2 nil)
4654 (if (cdr e)
4655 (setq c (cdr e))
4656 ;; automatically assign a character.
4657 (setq c1 (string-to-char
4658 (downcase (substring
4659 k (if (= (string-to-char k) ?@) 1 0)))))
4660 (if (or (rassoc c1 new) (rassoc c1 alist))
4661 (while (or (rassoc char new) (rassoc char alist))
4662 (setq char (1+ char)))
4663 (setq c2 c1))
4664 (setq c (or c2 char)))
4665 (push (cons k c) new))))
4666 (nreverse new)))
4668 ;;; Some variables ujsed in various places
4670 (defvar org-window-configuration nil
4671 "Used in various places to store a window configuration.")
4672 (defvar org-finish-function nil
4673 "Function to be called when `C-c C-c' is used.
4674 This is for getting out of special buffers like remember.")
4677 ;; FIXME: Occasionally check by commenting these, to make sure
4678 ;; no other functions uses these, forgetting to let-bind them.
4679 (defvar entry)
4680 (defvar state)
4681 (defvar last-state)
4682 (defvar date)
4683 (defvar description)
4685 ;; Defined somewhere in this file, but used before definition.
4686 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4687 (defvar org-agenda-buffer-name)
4688 (defvar org-agenda-undo-list)
4689 (defvar org-agenda-pending-undo-list)
4690 (defvar org-agenda-overriding-header)
4691 (defvar orgtbl-mode)
4692 (defvar org-html-entities)
4693 (defvar org-struct-menu)
4694 (defvar org-org-menu)
4695 (defvar org-tbl-menu)
4696 (defvar org-agenda-keymap)
4698 ;;;; Emacs/XEmacs compatibility
4700 ;; Overlay compatibility functions
4701 (defun org-make-overlay (beg end &optional buffer)
4702 (if (featurep 'xemacs)
4703 (make-extent beg end buffer)
4704 (make-overlay beg end buffer)))
4705 (defun org-delete-overlay (ovl)
4706 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4707 (defun org-detach-overlay (ovl)
4708 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4709 (defun org-move-overlay (ovl beg end &optional buffer)
4710 (if (featurep 'xemacs)
4711 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4712 (move-overlay ovl beg end buffer)))
4713 (defun org-overlay-put (ovl prop value)
4714 (if (featurep 'xemacs)
4715 (set-extent-property ovl prop value)
4716 (overlay-put ovl prop value)))
4717 (defun org-overlay-display (ovl text &optional face evap)
4718 "Make overlay OVL display TEXT with face FACE."
4719 (if (featurep 'xemacs)
4720 (let ((gl (make-glyph text)))
4721 (and face (set-glyph-face gl face))
4722 (set-extent-property ovl 'invisible t)
4723 (set-extent-property ovl 'end-glyph gl))
4724 (overlay-put ovl 'display text)
4725 (if face (overlay-put ovl 'face face))
4726 (if evap (overlay-put ovl 'evaporate t))))
4727 (defun org-overlay-before-string (ovl text &optional face evap)
4728 "Make overlay OVL display TEXT with face FACE."
4729 (if (featurep 'xemacs)
4730 (let ((gl (make-glyph text)))
4731 (and face (set-glyph-face gl face))
4732 (set-extent-property ovl 'begin-glyph gl))
4733 (if face (org-add-props text nil 'face face))
4734 (overlay-put ovl 'before-string text)
4735 (if evap (overlay-put ovl 'evaporate t))))
4736 (defun org-overlay-get (ovl prop)
4737 (if (featurep 'xemacs)
4738 (extent-property ovl prop)
4739 (overlay-get ovl prop)))
4740 (defun org-overlays-at (pos)
4741 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4742 (defun org-overlays-in (&optional start end)
4743 (if (featurep 'xemacs)
4744 (extent-list nil start end)
4745 (overlays-in start end)))
4746 (defun org-overlay-start (o)
4747 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4748 (defun org-overlay-end (o)
4749 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4750 (defun org-find-overlays (prop &optional pos delete)
4751 "Find all overlays specifying PROP at POS or point.
4752 If DELETE is non-nil, delete all those overlays."
4753 (let ((overlays (org-overlays-at (or pos (point))))
4754 ov found)
4755 (while (setq ov (pop overlays))
4756 (if (org-overlay-get ov prop)
4757 (if delete (org-delete-overlay ov) (push ov found))))
4758 found))
4760 ;; Region compatibility
4762 (defun org-add-hook (hook function &optional append local)
4763 "Add-hook, compatible with both Emacsen."
4764 (if (and local (featurep 'xemacs))
4765 (add-local-hook hook function append)
4766 (add-hook hook function append local)))
4768 (defvar org-ignore-region nil
4769 "To temporarily disable the active region.")
4771 (defun org-region-active-p ()
4772 "Is `transient-mark-mode' on and the region active?
4773 Works on both Emacs and XEmacs."
4774 (if org-ignore-region
4776 (if (featurep 'xemacs)
4777 (and zmacs-regions (region-active-p))
4778 (if (fboundp 'use-region-p)
4779 (use-region-p)
4780 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4782 ;; Invisibility compatibility
4784 (defun org-add-to-invisibility-spec (arg)
4785 "Add elements to `buffer-invisibility-spec'.
4786 See documentation for `buffer-invisibility-spec' for the kind of elements
4787 that can be added."
4788 (cond
4789 ((fboundp 'add-to-invisibility-spec)
4790 (add-to-invisibility-spec arg))
4791 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4792 (setq buffer-invisibility-spec (list arg)))
4794 (setq buffer-invisibility-spec
4795 (cons arg buffer-invisibility-spec)))))
4797 (defun org-remove-from-invisibility-spec (arg)
4798 "Remove elements from `buffer-invisibility-spec'."
4799 (if (fboundp 'remove-from-invisibility-spec)
4800 (remove-from-invisibility-spec arg)
4801 (if (consp buffer-invisibility-spec)
4802 (setq buffer-invisibility-spec
4803 (delete arg buffer-invisibility-spec)))))
4805 (defun org-in-invisibility-spec-p (arg)
4806 "Is ARG a member of `buffer-invisibility-spec'?"
4807 (if (consp buffer-invisibility-spec)
4808 (member arg buffer-invisibility-spec)
4809 nil))
4811 ;;;; Define the Org-mode
4813 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4814 (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."))
4817 ;; We use a before-change function to check if a table might need
4818 ;; an update.
4819 (defvar org-table-may-need-update t
4820 "Indicates that a table might need an update.
4821 This variable is set by `org-before-change-function'.
4822 `org-table-align' sets it back to nil.")
4823 (defvar org-mode-map)
4824 (defvar org-mode-hook nil)
4825 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4826 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4827 (defvar org-table-buffer-is-an nil)
4828 (defconst org-outline-regexp "\\*+ ")
4830 ;;;###autoload
4831 (define-derived-mode org-mode outline-mode "Org"
4832 "Outline-based notes management and organizer, alias
4833 \"Carsten's outline-mode for keeping track of everything.\"
4835 Org-mode develops organizational tasks around a NOTES file which
4836 contains information about projects as plain text. Org-mode is
4837 implemented on top of outline-mode, which is ideal to keep the content
4838 of large files well structured. It supports ToDo items, deadlines and
4839 time stamps, which magically appear in the diary listing of the Emacs
4840 calendar. Tables are easily created with a built-in table editor.
4841 Plain text URL-like links connect to websites, emails (VM), Usenet
4842 messages (Gnus), BBDB entries, and any files related to the project.
4843 For printing and sharing of notes, an Org-mode file (or a part of it)
4844 can be exported as a structured ASCII or HTML file.
4846 The following commands are available:
4848 \\{org-mode-map}"
4850 ;; Get rid of Outline menus, they are not needed
4851 ;; Need to do this here because define-derived-mode sets up
4852 ;; the keymap so late. Still, it is a waste to call this each time
4853 ;; we switch another buffer into org-mode.
4854 (if (featurep 'xemacs)
4855 (when (boundp 'outline-mode-menu-heading)
4856 ;; Assume this is Greg's port, it used easymenu
4857 (easy-menu-remove outline-mode-menu-heading)
4858 (easy-menu-remove outline-mode-menu-show)
4859 (easy-menu-remove outline-mode-menu-hide))
4860 (define-key org-mode-map [menu-bar headings] 'undefined)
4861 (define-key org-mode-map [menu-bar hide] 'undefined)
4862 (define-key org-mode-map [menu-bar show] 'undefined))
4864 (easy-menu-add org-org-menu)
4865 (easy-menu-add org-tbl-menu)
4866 (org-install-agenda-files-menu)
4867 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4868 (org-add-to-invisibility-spec '(org-cwidth))
4869 (when (featurep 'xemacs)
4870 (org-set-local 'line-move-ignore-invisible t))
4871 (org-set-local 'outline-regexp org-outline-regexp)
4872 (org-set-local 'outline-level 'org-outline-level)
4873 (when (and org-ellipsis
4874 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4875 (fboundp 'make-glyph-code))
4876 (unless org-display-table
4877 (setq org-display-table (make-display-table)))
4878 (set-display-table-slot
4879 org-display-table 4
4880 (vconcat (mapcar
4881 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4882 org-ellipsis)))
4883 (if (stringp org-ellipsis) org-ellipsis "..."))))
4884 (setq buffer-display-table org-display-table))
4885 (org-set-regexps-and-options)
4886 ;; Calc embedded
4887 (org-set-local 'calc-embedded-open-mode "# ")
4888 (modify-syntax-entry ?# "<")
4889 (modify-syntax-entry ?@ "w")
4890 (if org-startup-truncated (setq truncate-lines t))
4891 (org-set-local 'font-lock-unfontify-region-function
4892 'org-unfontify-region)
4893 ;; Activate before-change-function
4894 (org-set-local 'org-table-may-need-update t)
4895 (org-add-hook 'before-change-functions 'org-before-change-function nil
4896 'local)
4897 ;; Check for running clock before killing a buffer
4898 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4899 ;; Paragraphs and auto-filling
4900 (org-set-autofill-regexps)
4901 (setq indent-line-function 'org-indent-line-function)
4902 (org-update-radio-target-regexp)
4904 ;; Comment characters
4905 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4906 (org-set-local 'comment-padding " ")
4908 ;; Align options lines
4909 (org-set-local
4910 'align-mode-rules-list
4911 '((org-in-buffer-settings
4912 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4913 (modes . '(org-mode)))))
4915 ;; Imenu
4916 (org-set-local 'imenu-create-index-function
4917 'org-imenu-get-tree)
4919 ;; Make isearch reveal context
4920 (if (or (featurep 'xemacs)
4921 (not (boundp 'outline-isearch-open-invisible-function)))
4922 ;; Emacs 21 and XEmacs make use of the hook
4923 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4924 ;; Emacs 22 deals with this through a special variable
4925 (org-set-local 'outline-isearch-open-invisible-function
4926 (lambda (&rest ignore) (org-show-context 'isearch))))
4928 ;; If empty file that did not turn on org-mode automatically, make it to.
4929 (if (and org-insert-mode-line-in-empty-file
4930 (interactive-p)
4931 (= (point-min) (point-max)))
4932 (insert "# -*- mode: org -*-\n\n"))
4934 (unless org-inhibit-startup
4935 (when org-startup-align-all-tables
4936 (let ((bmp (buffer-modified-p)))
4937 (org-table-map-tables 'org-table-align)
4938 (set-buffer-modified-p bmp)))
4939 (org-cycle-hide-drawers 'all)
4940 (cond
4941 ((eq org-startup-folded t)
4942 (org-cycle '(4)))
4943 ((eq org-startup-folded 'content)
4944 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4945 (org-cycle '(4)) (org-cycle '(4)))))))
4947 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4949 (defsubst org-call-with-arg (command arg)
4950 "Call COMMAND interactively, but pretend prefix are was ARG."
4951 (let ((current-prefix-arg arg)) (call-interactively command)))
4953 (defsubst org-current-line (&optional pos)
4954 (save-excursion
4955 (and pos (goto-char pos))
4956 ;; works also in narrowed buffer, because we start at 1, not point-min
4957 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4959 (defun org-current-time ()
4960 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4961 (if (> org-time-stamp-rounding-minutes 0)
4962 (let ((r org-time-stamp-rounding-minutes)
4963 (time (decode-time)))
4964 (apply 'encode-time
4965 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4966 (nthcdr 2 time))))
4967 (current-time)))
4969 (defun org-add-props (string plist &rest props)
4970 "Add text properties to entire string, from beginning to end.
4971 PLIST may be a list of properties, PROPS are individual properties and values
4972 that will be added to PLIST. Returns the string that was modified."
4973 (add-text-properties
4974 0 (length string) (if props (append plist props) plist) string)
4975 string)
4976 (put 'org-add-props 'lisp-indent-function 2)
4979 ;;;; Font-Lock stuff, including the activators
4981 (defvar org-mouse-map (make-sparse-keymap))
4982 (org-defkey org-mouse-map
4983 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4984 (org-defkey org-mouse-map
4985 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4986 (when org-mouse-1-follows-link
4987 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4988 (when org-tab-follows-link
4989 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4990 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4991 (when org-return-follows-link
4992 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4993 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4995 (require 'font-lock)
4997 (defconst org-non-link-chars "]\t\n\r<>")
4998 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4999 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5000 (defvar org-link-re-with-space nil
5001 "Matches a link with spaces, optional angular brackets around it.")
5002 (defvar org-link-re-with-space2 nil
5003 "Matches a link with spaces, optional angular brackets around it.")
5004 (defvar org-angle-link-re nil
5005 "Matches link with angular brackets, spaces are allowed.")
5006 (defvar org-plain-link-re nil
5007 "Matches plain link, without spaces.")
5008 (defvar org-bracket-link-regexp nil
5009 "Matches a link in double brackets.")
5010 (defvar org-bracket-link-analytic-regexp nil
5011 "Regular expression used to analyze links.
5012 Here is what the match groups contain after a match:
5013 1: http:
5014 2: http
5015 3: path
5016 4: [desc]
5017 5: desc")
5018 (defvar org-any-link-re nil
5019 "Regular expression matching any link.")
5021 (defun org-make-link-regexps ()
5022 "Update the link regular expressions.
5023 This should be called after the variable `org-link-types' has changed."
5024 (setq org-link-re-with-space
5025 (concat
5026 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5027 "\\([^" org-non-link-chars " ]"
5028 "[^" org-non-link-chars "]*"
5029 "[^" org-non-link-chars " ]\\)>?")
5030 org-link-re-with-space2
5031 (concat
5032 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5033 "\\([^" org-non-link-chars " ]"
5034 "[^]\t\n\r]*"
5035 "[^" org-non-link-chars " ]\\)>?")
5036 org-angle-link-re
5037 (concat
5038 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5039 "\\([^" org-non-link-chars " ]"
5040 "[^" org-non-link-chars "]*"
5041 "\\)>")
5042 org-plain-link-re
5043 (concat
5044 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5045 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5046 org-bracket-link-regexp
5047 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5048 org-bracket-link-analytic-regexp
5049 (concat
5050 "\\[\\["
5051 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5052 "\\([^]]+\\)"
5053 "\\]"
5054 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5055 "\\]")
5056 org-any-link-re
5057 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5058 org-angle-link-re "\\)\\|\\("
5059 org-plain-link-re "\\)")))
5061 (org-make-link-regexps)
5063 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5064 "Regular expression for fast time stamp matching.")
5065 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5066 "Regular expression for fast time stamp matching.")
5067 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5068 "Regular expression matching time strings for analysis.
5069 This one does not require the space after the date.")
5070 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5071 "Regular expression matching time strings for analysis.")
5072 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5073 "Regular expression matching time stamps, with groups.")
5074 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5075 "Regular expression matching time stamps (also [..]), with groups.")
5076 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5077 "Regular expression matching a time stamp range.")
5078 (defconst org-tr-regexp-both
5079 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5080 "Regular expression matching a time stamp range.")
5081 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5082 org-ts-regexp "\\)?")
5083 "Regular expression matching a time stamp or time stamp range.")
5084 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5085 org-ts-regexp-both "\\)?")
5086 "Regular expression matching a time stamp or time stamp range.
5087 The time stamps may be either active or inactive.")
5089 (defvar org-emph-face nil)
5091 (defun org-do-emphasis-faces (limit)
5092 "Run through the buffer and add overlays to links."
5093 (let (rtn)
5094 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5095 (if (not (= (char-after (match-beginning 3))
5096 (char-after (match-beginning 4))))
5097 (progn
5098 (setq rtn t)
5099 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5100 'face
5101 (nth 1 (assoc (match-string 3)
5102 org-emphasis-alist)))
5103 (add-text-properties (match-beginning 2) (match-end 2)
5104 '(font-lock-multiline t))
5105 (when org-hide-emphasis-markers
5106 (add-text-properties (match-end 4) (match-beginning 5)
5107 '(invisible org-link))
5108 (add-text-properties (match-beginning 3) (match-end 3)
5109 '(invisible org-link)))))
5110 (backward-char 1))
5111 rtn))
5113 (defun org-emphasize (&optional char)
5114 "Insert or change an emphasis, i.e. a font like bold or italic.
5115 If there is an active region, change that region to a new emphasis.
5116 If there is no region, just insert the marker characters and position
5117 the cursor between them.
5118 CHAR should be either the marker character, or the first character of the
5119 HTML tag associated with that emphasis. If CHAR is a space, the means
5120 to remove the emphasis of the selected region.
5121 If char is not given (for example in an interactive call) it
5122 will be prompted for."
5123 (interactive)
5124 (let ((eal org-emphasis-alist) e det
5125 (erc org-emphasis-regexp-components)
5126 (prompt "")
5127 (string "") beg end move tag c s)
5128 (if (org-region-active-p)
5129 (setq beg (region-beginning) end (region-end)
5130 string (buffer-substring beg end))
5131 (setq move t))
5133 (while (setq e (pop eal))
5134 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5135 c (aref tag 0))
5136 (push (cons c (string-to-char (car e))) det)
5137 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5138 (substring tag 1)))))
5139 (unless char
5140 (message "%s" (concat "Emphasis marker or tag:" prompt))
5141 (setq char (read-char-exclusive)))
5142 (setq char (or (cdr (assoc char det)) char))
5143 (if (equal char ?\ )
5144 (setq s "" move nil)
5145 (unless (assoc (char-to-string char) org-emphasis-alist)
5146 (error "No such emphasis marker: \"%c\"" char))
5147 (setq s (char-to-string char)))
5148 (while (and (> (length string) 1)
5149 (equal (substring string 0 1) (substring string -1))
5150 (assoc (substring string 0 1) org-emphasis-alist))
5151 (setq string (substring string 1 -1)))
5152 (setq string (concat s string s))
5153 (if beg (delete-region beg end))
5154 (unless (or (bolp)
5155 (string-match (concat "[" (nth 0 erc) "\n]")
5156 (char-to-string (char-before (point)))))
5157 (insert " "))
5158 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5159 (char-to-string (char-after (point))))
5160 (insert " ") (backward-char 1))
5161 (insert string)
5162 (and move (backward-char 1))))
5164 (defconst org-nonsticky-props
5165 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5168 (defun org-activate-plain-links (limit)
5169 "Run through the buffer and add overlays to links."
5170 (catch 'exit
5171 (let (f)
5172 (while (re-search-forward org-plain-link-re limit t)
5173 (setq f (get-text-property (match-beginning 0) 'face))
5174 (if (or (eq f 'org-tag)
5175 (and (listp f) (memq 'org-tag f)))
5177 (add-text-properties (match-beginning 0) (match-end 0)
5178 (list 'mouse-face 'highlight
5179 'rear-nonsticky org-nonsticky-props
5180 'keymap org-mouse-map
5182 (throw 'exit t))))))
5184 (defun org-activate-code (limit)
5185 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5186 (unless (get-text-property (match-beginning 1) 'face)
5187 (remove-text-properties (match-beginning 0) (match-end 0)
5188 '(display t invisible t intangible t))
5189 t)))
5191 (defun org-activate-angle-links (limit)
5192 "Run through the buffer and add overlays to links."
5193 (if (re-search-forward org-angle-link-re limit t)
5194 (progn
5195 (add-text-properties (match-beginning 0) (match-end 0)
5196 (list 'mouse-face 'highlight
5197 'rear-nonsticky org-nonsticky-props
5198 'keymap org-mouse-map
5200 t)))
5202 (defmacro org-maybe-intangible (props)
5203 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5204 In emacs 21, invisible text is not avoided by the command loop, so the
5205 intangible property is needed to make sure point skips this text.
5206 In Emacs 22, this is not necessary. The intangible text property has
5207 led to problems with flyspell. These problems are fixed in flyspell.el,
5208 but we still avoid setting the property in Emacs 22 and later.
5209 We use a macro so that the test can happen at compilation time."
5210 (if (< emacs-major-version 22)
5211 `(append '(intangible t) ,props)
5212 props))
5214 (defun org-activate-bracket-links (limit)
5215 "Run through the buffer and add overlays to bracketed links."
5216 (if (re-search-forward org-bracket-link-regexp limit t)
5217 (let* ((help (concat "LINK: "
5218 (org-match-string-no-properties 1)))
5219 ;; FIXME: above we should remove the escapes.
5220 ;; but that requires another match, protecting match data,
5221 ;; a lot of overhead for font-lock.
5222 (ip (org-maybe-intangible
5223 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5224 'keymap org-mouse-map 'mouse-face 'highlight
5225 'font-lock-multiline t 'help-echo help)))
5226 (vp (list 'rear-nonsticky org-nonsticky-props
5227 'keymap org-mouse-map 'mouse-face 'highlight
5228 ' font-lock-multiline t 'help-echo help)))
5229 ;; We need to remove the invisible property here. Table narrowing
5230 ;; may have made some of this invisible.
5231 (remove-text-properties (match-beginning 0) (match-end 0)
5232 '(invisible nil))
5233 (if (match-end 3)
5234 (progn
5235 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5236 (add-text-properties (match-beginning 3) (match-end 3) vp)
5237 (add-text-properties (match-end 3) (match-end 0) ip))
5238 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5239 (add-text-properties (match-beginning 1) (match-end 1) vp)
5240 (add-text-properties (match-end 1) (match-end 0) ip))
5241 t)))
5243 (defun org-activate-dates (limit)
5244 "Run through the buffer and add overlays to dates."
5245 (if (re-search-forward org-tsr-regexp-both limit t)
5246 (progn
5247 (add-text-properties (match-beginning 0) (match-end 0)
5248 (list 'mouse-face 'highlight
5249 'rear-nonsticky org-nonsticky-props
5250 'keymap org-mouse-map))
5251 (when org-display-custom-times
5252 (if (match-end 3)
5253 (org-display-custom-time (match-beginning 3) (match-end 3)))
5254 (org-display-custom-time (match-beginning 1) (match-end 1)))
5255 t)))
5257 (defvar org-target-link-regexp nil
5258 "Regular expression matching radio targets in plain text.")
5259 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5260 "Regular expression matching a link target.")
5261 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5262 "Regular expression matching a radio target.")
5263 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5264 "Regular expression matching any target.")
5266 (defun org-activate-target-links (limit)
5267 "Run through the buffer and add overlays to target matches."
5268 (when org-target-link-regexp
5269 (let ((case-fold-search t))
5270 (if (re-search-forward org-target-link-regexp limit t)
5271 (progn
5272 (add-text-properties (match-beginning 0) (match-end 0)
5273 (list 'mouse-face 'highlight
5274 'rear-nonsticky org-nonsticky-props
5275 'keymap org-mouse-map
5276 'help-echo "Radio target link"
5277 'org-linked-text t))
5278 t)))))
5280 (defun org-update-radio-target-regexp ()
5281 "Find all radio targets in this file and update the regular expression."
5282 (interactive)
5283 (when (memq 'radio org-activate-links)
5284 (setq org-target-link-regexp
5285 (org-make-target-link-regexp (org-all-targets 'radio)))
5286 (org-restart-font-lock)))
5288 (defun org-hide-wide-columns (limit)
5289 (let (s e)
5290 (setq s (text-property-any (point) (or limit (point-max))
5291 'org-cwidth t))
5292 (when s
5293 (setq e (next-single-property-change s 'org-cwidth))
5294 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5295 (goto-char e)
5296 t)))
5298 (defvar org-latex-and-specials-regexp nil
5299 "Regular expression for highlighting export special stuff.")
5300 (defvar org-match-substring-regexp)
5301 (defvar org-match-substring-with-braces-regexp)
5302 (defvar org-export-html-special-string-regexps)
5304 (defun org-compute-latex-and-specials-regexp ()
5305 "Compute regular expression for stuff treated specially by exporters."
5306 (if (not org-highlight-latex-fragments-and-specials)
5307 (org-set-local 'org-latex-and-specials-regexp nil)
5308 (let*
5309 ((matchers (plist-get org-format-latex-options :matchers))
5310 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5311 org-latex-regexps)))
5312 (options (org-combine-plists (org-default-export-plist)
5313 (org-infile-export-plist)))
5314 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5315 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5316 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5317 (org-export-html-expand (plist-get options :expand-quoted-html))
5318 (org-export-with-special-strings (plist-get options :special-strings))
5319 (re-sub
5320 (cond
5321 ((equal org-export-with-sub-superscripts '{})
5322 (list org-match-substring-with-braces-regexp))
5323 (org-export-with-sub-superscripts
5324 (list org-match-substring-regexp))
5325 (t nil)))
5326 (re-latex
5327 (if org-export-with-LaTeX-fragments
5328 (mapcar (lambda (x) (nth 1 x)) latexs)))
5329 (re-macros
5330 (if org-export-with-TeX-macros
5331 (list (concat "\\\\"
5332 (regexp-opt
5333 (append (mapcar 'car org-html-entities)
5334 (if (boundp 'org-latex-entities)
5335 org-latex-entities nil))
5336 'words))) ; FIXME
5338 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5339 (re-special (if org-export-with-special-strings
5340 (mapcar (lambda (x) (car x))
5341 org-export-html-special-string-regexps)))
5342 (re-rest
5343 (delq nil
5344 (list
5345 (if org-export-html-expand "@<[^>\n]+>")
5346 ))))
5347 (org-set-local
5348 'org-latex-and-specials-regexp
5349 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5350 re-rest) "\\|")))))
5352 (defface org-latex-and-export-specials
5353 (let ((font (cond ((assq :inherit custom-face-attributes)
5354 '(:inherit underline))
5355 (t '(:underline t)))))
5356 `((((class grayscale) (background light))
5357 (:foreground "DimGray" ,@font))
5358 (((class grayscale) (background dark))
5359 (:foreground "LightGray" ,@font))
5360 (((class color) (background light))
5361 (:foreground "SaddleBrown"))
5362 (((class color) (background dark))
5363 (:foreground "burlywood"))
5364 (t (,@font))))
5365 "Face used to highlight math latex and other special exporter stuff."
5366 :group 'org-faces)
5368 (defun org-do-latex-and-special-faces (limit)
5369 "Run through the buffer and add overlays to links."
5370 (when org-latex-and-specials-regexp
5371 (let (rtn d)
5372 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5373 limit t))
5374 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5375 'face))
5376 '(org-code org-verbatim underline)))
5377 (progn
5378 (setq rtn t
5379 d (cond ((member (char-after (1+ (match-beginning 0)))
5380 '(?_ ?^)) 1)
5381 (t 0)))
5382 (font-lock-prepend-text-property
5383 (+ d (match-beginning 0)) (match-end 0)
5384 'face 'org-latex-and-export-specials)
5385 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5386 '(font-lock-multiline t)))))
5387 rtn)))
5389 (defun org-restart-font-lock ()
5390 "Restart font-lock-mode, to force refontification."
5391 (when (and (boundp 'font-lock-mode) font-lock-mode)
5392 (font-lock-mode -1)
5393 (font-lock-mode 1)))
5395 (defun org-all-targets (&optional radio)
5396 "Return a list of all targets in this file.
5397 With optional argument RADIO, only find radio targets."
5398 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5399 rtn)
5400 (save-excursion
5401 (goto-char (point-min))
5402 (while (re-search-forward re nil t)
5403 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5404 rtn)))
5406 (defun org-make-target-link-regexp (targets)
5407 "Make regular expression matching all strings in TARGETS.
5408 The regular expression finds the targets also if there is a line break
5409 between words."
5410 (and targets
5411 (concat
5412 "\\<\\("
5413 (mapconcat
5414 (lambda (x)
5415 (while (string-match " +" x)
5416 (setq x (replace-match "\\s-+" t t x)))
5418 targets
5419 "\\|")
5420 "\\)\\>")))
5422 (defun org-activate-tags (limit)
5423 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5424 (progn
5425 (add-text-properties (match-beginning 1) (match-end 1)
5426 (list 'mouse-face 'highlight
5427 'rear-nonsticky org-nonsticky-props
5428 'keymap org-mouse-map))
5429 t)))
5431 (defun org-outline-level ()
5432 (save-excursion
5433 (looking-at outline-regexp)
5434 (if (match-beginning 1)
5435 (+ (org-get-string-indentation (match-string 1)) 1000)
5436 (1- (- (match-end 0) (match-beginning 0))))))
5438 (defvar org-font-lock-keywords nil)
5440 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5441 "Regular expression matching a property line.")
5443 (defun org-set-font-lock-defaults ()
5444 (let* ((em org-fontify-emphasized-text)
5445 (lk org-activate-links)
5446 (org-font-lock-extra-keywords
5447 (list
5448 ;; Headlines
5449 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5450 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5451 ;; Table lines
5452 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5453 (1 'org-table t))
5454 ;; Table internals
5455 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5456 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5457 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5458 ;; Drawers
5459 (list org-drawer-regexp '(0 'org-special-keyword t))
5460 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5461 ;; Properties
5462 (list org-property-re
5463 '(1 'org-special-keyword t)
5464 '(3 'org-property-value t))
5465 (if org-format-transports-properties-p
5466 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5467 ;; Links
5468 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5469 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5470 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5471 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5472 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5473 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5474 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5475 '(org-hide-wide-columns (0 nil append))
5476 ;; TODO lines
5477 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5478 '(1 (org-get-todo-face 1) t))
5479 ;; DONE
5480 (if org-fontify-done-headline
5481 (list (concat "^[*]+ +\\<\\("
5482 (mapconcat 'regexp-quote org-done-keywords "\\|")
5483 "\\)\\(.*\\)")
5484 '(2 'org-headline-done t))
5485 nil)
5486 ;; Priorities
5487 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5488 ;; Special keywords
5489 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5490 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5491 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5492 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5493 ;; Emphasis
5494 (if em
5495 (if (featurep 'xemacs)
5496 '(org-do-emphasis-faces (0 nil append))
5497 '(org-do-emphasis-faces)))
5498 ;; Checkboxes
5499 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5500 2 'bold prepend)
5501 (if org-provide-checkbox-statistics
5502 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5503 (0 (org-get-checkbox-statistics-face) t)))
5504 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5505 '(1 'org-archived prepend))
5506 ;; Specials
5507 '(org-do-latex-and-special-faces)
5508 ;; Code
5509 '(org-activate-code (1 'org-code t))
5510 ;; COMMENT
5511 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5512 "\\|" org-quote-string "\\)\\>")
5513 '(1 'org-special-keyword t))
5514 '("^#.*" (0 'font-lock-comment-face t))
5516 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5517 ;; Now set the full font-lock-keywords
5518 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5519 (org-set-local 'font-lock-defaults
5520 '(org-font-lock-keywords t nil nil backward-paragraph))
5521 (kill-local-variable 'font-lock-keywords) nil))
5523 (defvar org-m nil)
5524 (defvar org-l nil)
5525 (defvar org-f nil)
5526 (defun org-get-level-face (n)
5527 "Get the right face for match N in font-lock matching of healdines."
5528 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5529 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5530 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5531 (cond
5532 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5533 ((eq n 2) org-f)
5534 (t (if org-level-color-stars-only nil org-f))))
5536 (defun org-get-todo-face (kwd)
5537 "Get the right face for a TODO keyword KWD.
5538 If KWD is a number, get the corresponding match group."
5539 (if (numberp kwd) (setq kwd (match-string kwd)))
5540 (or (cdr (assoc kwd org-todo-keyword-faces))
5541 (and (member kwd org-done-keywords) 'org-done)
5542 'org-todo))
5544 (defun org-unfontify-region (beg end &optional maybe_loudly)
5545 "Remove fontification and activation overlays from links."
5546 (font-lock-default-unfontify-region beg end)
5547 (let* ((buffer-undo-list t)
5548 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5549 (inhibit-modification-hooks t)
5550 deactivate-mark buffer-file-name buffer-file-truename)
5551 (remove-text-properties beg end
5552 '(mouse-face t keymap t org-linked-text t
5553 invisible t intangible t))))
5555 ;;;; Visibility cycling, including org-goto and indirect buffer
5557 ;;; Cycling
5559 (defvar org-cycle-global-status nil)
5560 (make-variable-buffer-local 'org-cycle-global-status)
5561 (defvar org-cycle-subtree-status nil)
5562 (make-variable-buffer-local 'org-cycle-subtree-status)
5564 ;;;###autoload
5565 (defun org-cycle (&optional arg)
5566 "Visibility cycling for Org-mode.
5568 - When this function is called with a prefix argument, rotate the entire
5569 buffer through 3 states (global cycling)
5570 1. OVERVIEW: Show only top-level headlines.
5571 2. CONTENTS: Show all headlines of all levels, but no body text.
5572 3. SHOW ALL: Show everything.
5574 - When point is at the beginning of a headline, rotate the subtree started
5575 by this line through 3 different states (local cycling)
5576 1. FOLDED: Only the main headline is shown.
5577 2. CHILDREN: The main headline and the direct children are shown.
5578 From this state, you can move to one of the children
5579 and zoom in further.
5580 3. SUBTREE: Show the entire subtree, including body text.
5582 - When there is a numeric prefix, go up to a heading with level ARG, do
5583 a `show-subtree' and return to the previous cursor position. If ARG
5584 is negative, go up that many levels.
5586 - When point is not at the beginning of a headline, execute
5587 `indent-relative', like TAB normally does. See the option
5588 `org-cycle-emulate-tab' for details.
5590 - Special case: if point is at the beginning of the buffer and there is
5591 no headline in line 1, this function will act as if called with prefix arg.
5592 But only if also the variable `org-cycle-global-at-bob' is t."
5593 (interactive "P")
5594 (let* ((outline-regexp
5595 (if (and (org-mode-p) org-cycle-include-plain-lists)
5596 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5597 outline-regexp))
5598 (bob-special (and org-cycle-global-at-bob (bobp)
5599 (not (looking-at outline-regexp))))
5600 (org-cycle-hook
5601 (if bob-special
5602 (delq 'org-optimize-window-after-visibility-change
5603 (copy-sequence org-cycle-hook))
5604 org-cycle-hook))
5605 (pos (point)))
5607 (if (or bob-special (equal arg '(4)))
5608 ;; special case: use global cycling
5609 (setq arg t))
5611 (cond
5613 ((org-at-table-p 'any)
5614 ;; Enter the table or move to the next field in the table
5615 (or (org-table-recognize-table.el)
5616 (progn
5617 (if arg (org-table-edit-field t)
5618 (org-table-justify-field-maybe)
5619 (call-interactively 'org-table-next-field)))))
5621 ((eq arg t) ;; Global cycling
5623 (cond
5624 ((and (eq last-command this-command)
5625 (eq org-cycle-global-status 'overview))
5626 ;; We just created the overview - now do table of contents
5627 ;; This can be slow in very large buffers, so indicate action
5628 (message "CONTENTS...")
5629 (org-content)
5630 (message "CONTENTS...done")
5631 (setq org-cycle-global-status 'contents)
5632 (run-hook-with-args 'org-cycle-hook 'contents))
5634 ((and (eq last-command this-command)
5635 (eq org-cycle-global-status 'contents))
5636 ;; We just showed the table of contents - now show everything
5637 (show-all)
5638 (message "SHOW ALL")
5639 (setq org-cycle-global-status 'all)
5640 (run-hook-with-args 'org-cycle-hook 'all))
5643 ;; Default action: go to overview
5644 (org-overview)
5645 (message "OVERVIEW")
5646 (setq org-cycle-global-status 'overview)
5647 (run-hook-with-args 'org-cycle-hook 'overview))))
5649 ((and org-drawers org-drawer-regexp
5650 (save-excursion
5651 (beginning-of-line 1)
5652 (looking-at org-drawer-regexp)))
5653 ;; Toggle block visibility
5654 (org-flag-drawer
5655 (not (get-char-property (match-end 0) 'invisible))))
5657 ((integerp arg)
5658 ;; Show-subtree, ARG levels up from here.
5659 (save-excursion
5660 (org-back-to-heading)
5661 (outline-up-heading (if (< arg 0) (- arg)
5662 (- (funcall outline-level) arg)))
5663 (org-show-subtree)))
5665 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5666 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5667 ;; At a heading: rotate between three different views
5668 (org-back-to-heading)
5669 (let ((goal-column 0) eoh eol eos)
5670 ;; First, some boundaries
5671 (save-excursion
5672 (org-back-to-heading)
5673 (save-excursion
5674 (beginning-of-line 2)
5675 (while (and (not (eobp)) ;; this is like `next-line'
5676 (get-char-property (1- (point)) 'invisible))
5677 (beginning-of-line 2)) (setq eol (point)))
5678 (outline-end-of-heading) (setq eoh (point))
5679 (org-end-of-subtree t)
5680 (unless (eobp)
5681 (skip-chars-forward " \t\n")
5682 (beginning-of-line 1) ; in case this is an item
5684 (setq eos (1- (point))))
5685 ;; Find out what to do next and set `this-command'
5686 (cond
5687 ((= eos eoh)
5688 ;; Nothing is hidden behind this heading
5689 (message "EMPTY ENTRY")
5690 (setq org-cycle-subtree-status nil)
5691 (save-excursion
5692 (goto-char eos)
5693 (outline-next-heading)
5694 (if (org-invisible-p) (org-flag-heading nil))))
5695 ((or (>= eol eos)
5696 (not (string-match "\\S-" (buffer-substring eol eos))))
5697 ;; Entire subtree is hidden in one line: open it
5698 (org-show-entry)
5699 (show-children)
5700 (message "CHILDREN")
5701 (save-excursion
5702 (goto-char eos)
5703 (outline-next-heading)
5704 (if (org-invisible-p) (org-flag-heading nil)))
5705 (setq org-cycle-subtree-status 'children)
5706 (run-hook-with-args 'org-cycle-hook 'children))
5707 ((and (eq last-command this-command)
5708 (eq org-cycle-subtree-status 'children))
5709 ;; We just showed the children, now show everything.
5710 (org-show-subtree)
5711 (message "SUBTREE")
5712 (setq org-cycle-subtree-status 'subtree)
5713 (run-hook-with-args 'org-cycle-hook 'subtree))
5715 ;; Default action: hide the subtree.
5716 (hide-subtree)
5717 (message "FOLDED")
5718 (setq org-cycle-subtree-status 'folded)
5719 (run-hook-with-args 'org-cycle-hook 'folded)))))
5721 ;; TAB emulation
5722 (buffer-read-only (org-back-to-heading))
5724 ((org-try-cdlatex-tab))
5726 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5727 (or (not (bolp))
5728 (not (looking-at outline-regexp))))
5729 (call-interactively (global-key-binding "\t")))
5731 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5732 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5733 (or (and (eq org-cycle-emulate-tab 'white)
5734 (= (match-end 0) (point-at-eol)))
5735 (and (eq org-cycle-emulate-tab 'whitestart)
5736 (>= (match-end 0) pos))))
5738 (eq org-cycle-emulate-tab t))
5739 ; (if (and (looking-at "[ \n\r\t]")
5740 ; (string-match "^[ \t]*$" (buffer-substring
5741 ; (point-at-bol) (point))))
5742 ; (progn
5743 ; (beginning-of-line 1)
5744 ; (and (looking-at "[ \t]+") (replace-match ""))))
5745 (call-interactively (global-key-binding "\t")))
5747 (t (save-excursion
5748 (org-back-to-heading)
5749 (org-cycle))))))
5751 ;;;###autoload
5752 (defun org-global-cycle (&optional arg)
5753 "Cycle the global visibility. For details see `org-cycle'."
5754 (interactive "P")
5755 (let ((org-cycle-include-plain-lists
5756 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5757 (if (integerp arg)
5758 (progn
5759 (show-all)
5760 (hide-sublevels arg)
5761 (setq org-cycle-global-status 'contents))
5762 (org-cycle '(4)))))
5764 (defun org-overview ()
5765 "Switch to overview mode, shoing only top-level headlines.
5766 Really, this shows all headlines with level equal or greater than the level
5767 of the first headline in the buffer. This is important, because if the
5768 first headline is not level one, then (hide-sublevels 1) gives confusing
5769 results."
5770 (interactive)
5771 (let ((level (save-excursion
5772 (goto-char (point-min))
5773 (if (re-search-forward (concat "^" outline-regexp) nil t)
5774 (progn
5775 (goto-char (match-beginning 0))
5776 (funcall outline-level))))))
5777 (and level (hide-sublevels level))))
5779 (defun org-content (&optional arg)
5780 "Show all headlines in the buffer, like a table of contents.
5781 With numerical argument N, show content up to level N."
5782 (interactive "P")
5783 (save-excursion
5784 ;; Visit all headings and show their offspring
5785 (and (integerp arg) (org-overview))
5786 (goto-char (point-max))
5787 (catch 'exit
5788 (while (and (progn (condition-case nil
5789 (outline-previous-visible-heading 1)
5790 (error (goto-char (point-min))))
5792 (looking-at outline-regexp))
5793 (if (integerp arg)
5794 (show-children (1- arg))
5795 (show-branches))
5796 (if (bobp) (throw 'exit nil))))))
5799 (defun org-optimize-window-after-visibility-change (state)
5800 "Adjust the window after a change in outline visibility.
5801 This function is the default value of the hook `org-cycle-hook'."
5802 (when (get-buffer-window (current-buffer))
5803 (cond
5804 ; ((eq state 'overview) (org-first-headline-recenter 1))
5805 ; ((eq state 'overview) (org-beginning-of-line))
5806 ((eq state 'content) nil)
5807 ((eq state 'all) nil)
5808 ((eq state 'folded) nil)
5809 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5810 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5812 (defun org-compact-display-after-subtree-move ()
5813 (let (beg end)
5814 (save-excursion
5815 (if (org-up-heading-safe)
5816 (progn
5817 (hide-subtree)
5818 (show-entry)
5819 (show-children)
5820 (org-cycle-show-empty-lines 'children)
5821 (org-cycle-hide-drawers 'children))
5822 (org-overview)))))
5824 (defun org-cycle-show-empty-lines (state)
5825 "Show empty lines above all visible headlines.
5826 The region to be covered depends on STATE when called through
5827 `org-cycle-hook'. Lisp program can use t for STATE to get the
5828 entire buffer covered. Note that an empty line is only shown if there
5829 are at least `org-cycle-separator-lines' empty lines before the headeline."
5830 (when (> org-cycle-separator-lines 0)
5831 (save-excursion
5832 (let* ((n org-cycle-separator-lines)
5833 (re (cond
5834 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5835 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5836 (t (let ((ns (number-to-string (- n 2))))
5837 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5838 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5839 beg end)
5840 (cond
5841 ((memq state '(overview contents t))
5842 (setq beg (point-min) end (point-max)))
5843 ((memq state '(children folded))
5844 (setq beg (point) end (progn (org-end-of-subtree t t)
5845 (beginning-of-line 2)
5846 (point)))))
5847 (when beg
5848 (goto-char beg)
5849 (while (re-search-forward re end t)
5850 (if (not (get-char-property (match-end 1) 'invisible))
5851 (outline-flag-region
5852 (match-beginning 1) (match-end 1) nil)))))))
5853 ;; Never hide empty lines at the end of the file.
5854 (save-excursion
5855 (goto-char (point-max))
5856 (outline-previous-heading)
5857 (outline-end-of-heading)
5858 (if (and (looking-at "[ \t\n]+")
5859 (= (match-end 0) (point-max)))
5860 (outline-flag-region (point) (match-end 0) nil))))
5862 (defun org-subtree-end-visible-p ()
5863 "Is the end of the current subtree visible?"
5864 (pos-visible-in-window-p
5865 (save-excursion (org-end-of-subtree t) (point))))
5867 (defun org-first-headline-recenter (&optional N)
5868 "Move cursor to the first headline and recenter the headline.
5869 Optional argument N means, put the headline into the Nth line of the window."
5870 (goto-char (point-min))
5871 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5872 (beginning-of-line)
5873 (recenter (prefix-numeric-value N))))
5875 ;;; Org-goto
5877 (defvar org-goto-window-configuration nil)
5878 (defvar org-goto-marker nil)
5879 (defvar org-goto-map
5880 (let ((map (make-sparse-keymap)))
5881 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5882 (while (setq cmd (pop cmds))
5883 (substitute-key-definition cmd cmd map global-map)))
5884 (suppress-keymap map)
5885 (org-defkey map "\C-m" 'org-goto-ret)
5886 (org-defkey map [(return)] 'org-goto-ret)
5887 (org-defkey map [(left)] 'org-goto-left)
5888 (org-defkey map [(right)] 'org-goto-right)
5889 (org-defkey map [(control ?g)] 'org-goto-quit)
5890 (org-defkey map "\C-i" 'org-cycle)
5891 (org-defkey map [(tab)] 'org-cycle)
5892 (org-defkey map [(down)] 'outline-next-visible-heading)
5893 (org-defkey map [(up)] 'outline-previous-visible-heading)
5894 (if org-goto-auto-isearch
5895 (if (fboundp 'define-key-after)
5896 (define-key-after map [t] 'org-goto-local-auto-isearch)
5897 nil)
5898 (org-defkey map "q" 'org-goto-quit)
5899 (org-defkey map "n" 'outline-next-visible-heading)
5900 (org-defkey map "p" 'outline-previous-visible-heading)
5901 (org-defkey map "f" 'outline-forward-same-level)
5902 (org-defkey map "b" 'outline-backward-same-level)
5903 (org-defkey map "u" 'outline-up-heading))
5904 (org-defkey map "/" 'org-occur)
5905 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5906 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5907 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5908 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5909 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5910 map))
5912 (defconst org-goto-help
5913 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5914 RET=jump to location [Q]uit and return to previous location
5915 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5917 (defvar org-goto-start-pos) ; dynamically scoped parameter
5919 (defun org-goto (&optional alternative-interface)
5920 "Look up a different location in the current file, keeping current visibility.
5922 When you want look-up or go to a different location in a document, the
5923 fastest way is often to fold the entire buffer and then dive into the tree.
5924 This method has the disadvantage, that the previous location will be folded,
5925 which may not be what you want.
5927 This command works around this by showing a copy of the current buffer
5928 in an indirect buffer, in overview mode. You can dive into the tree in
5929 that copy, use org-occur and incremental search to find a location.
5930 When pressing RET or `Q', the command returns to the original buffer in
5931 which the visibility is still unchanged. After RET is will also jump to
5932 the location selected in the indirect buffer and expose the
5933 the headline hierarchy above."
5934 (interactive "P")
5935 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
5936 (org-refile-use-outline-path t)
5937 (interface
5938 (if (not alternative-interface)
5939 org-goto-interface
5940 (if (eq org-goto-interface 'outline)
5941 'outline-path-completion
5942 'outline)))
5943 (org-goto-start-pos (point))
5944 (selected-point
5945 (if (eq interface 'outline)
5946 (car (org-get-location (current-buffer) org-goto-help))
5947 (nth 3 (org-refile-get-location "Goto: ")))))
5948 (if selected-point
5949 (progn
5950 (org-mark-ring-push org-goto-start-pos)
5951 (goto-char selected-point)
5952 (if (or (org-invisible-p) (org-invisible-p2))
5953 (org-show-context 'org-goto)))
5954 (message "Quit"))))
5956 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5957 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5959 (defun org-get-location (buf help)
5960 "Let the user select a location in the Org-mode buffer BUF.
5961 This function uses a recursive edit. It returns the selected position
5962 or nil."
5963 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5964 (isearch-hide-immediately nil)
5965 (isearch-search-fun-function
5966 (lambda () 'org-goto-local-search-forward-headings))
5967 (org-goto-selected-point org-goto-exit-command))
5968 (save-excursion
5969 (save-window-excursion
5970 (delete-other-windows)
5971 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5972 (switch-to-buffer
5973 (condition-case nil
5974 (make-indirect-buffer (current-buffer) "*org-goto*")
5975 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5976 (with-output-to-temp-buffer "*Help*"
5977 (princ help))
5978 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5979 (setq buffer-read-only nil)
5980 (let ((org-startup-truncated t)
5981 (org-startup-folded nil)
5982 (org-startup-align-all-tables nil))
5983 (org-mode)
5984 (org-overview))
5985 (setq buffer-read-only t)
5986 (if (and (boundp 'org-goto-start-pos)
5987 (integer-or-marker-p org-goto-start-pos))
5988 (let ((org-show-hierarchy-above t)
5989 (org-show-siblings t)
5990 (org-show-following-heading t))
5991 (goto-char org-goto-start-pos)
5992 (and (org-invisible-p) (org-show-context)))
5993 (goto-char (point-min)))
5994 (org-beginning-of-line)
5995 (message "Select location and press RET")
5996 (use-local-map org-goto-map)
5997 (recursive-edit)
5999 (kill-buffer "*org-goto*")
6000 (cons org-goto-selected-point org-goto-exit-command)))
6002 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6003 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6004 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6005 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6007 (defun org-goto-local-search-forward-headings (string bound noerror)
6008 "Search and make sure that anu matches are in headlines."
6009 (catch 'return
6010 (while (search-forward string bound noerror)
6011 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6012 (and (member :headline context)
6013 (not (member :tags context))))
6014 (throw 'return (point))))))
6016 (defun org-goto-local-auto-isearch ()
6017 "Start isearch."
6018 (interactive)
6019 (goto-char (point-min))
6020 (let ((keys (this-command-keys)))
6021 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6022 (isearch-mode t)
6023 (isearch-process-search-char (string-to-char keys)))))
6025 (defun org-goto-ret (&optional arg)
6026 "Finish `org-goto' by going to the new location."
6027 (interactive "P")
6028 (setq org-goto-selected-point (point)
6029 org-goto-exit-command 'return)
6030 (throw 'exit nil))
6032 (defun org-goto-left ()
6033 "Finish `org-goto' by going to the new location."
6034 (interactive)
6035 (if (org-on-heading-p)
6036 (progn
6037 (beginning-of-line 1)
6038 (setq org-goto-selected-point (point)
6039 org-goto-exit-command 'left)
6040 (throw 'exit nil))
6041 (error "Not on a heading")))
6043 (defun org-goto-right ()
6044 "Finish `org-goto' by going to the new location."
6045 (interactive)
6046 (if (org-on-heading-p)
6047 (progn
6048 (setq org-goto-selected-point (point)
6049 org-goto-exit-command 'right)
6050 (throw 'exit nil))
6051 (error "Not on a heading")))
6053 (defun org-goto-quit ()
6054 "Finish `org-goto' without cursor motion."
6055 (interactive)
6056 (setq org-goto-selected-point nil)
6057 (setq org-goto-exit-command 'quit)
6058 (throw 'exit nil))
6060 ;;; Indirect buffer display of subtrees
6062 (defvar org-indirect-dedicated-frame nil
6063 "This is the frame being used for indirect tree display.")
6064 (defvar org-last-indirect-buffer nil)
6066 (defun org-tree-to-indirect-buffer (&optional arg)
6067 "Create indirect buffer and narrow it to current subtree.
6068 With numerical prefix ARG, go up to this level and then take that tree.
6069 If ARG is negative, go up that many levels.
6070 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6071 indirect buffer previously made with this command, to avoid proliferation of
6072 indirect buffers. However, when you call the command with a `C-u' prefix, or
6073 when `org-indirect-buffer-display' is `new-frame', the last buffer
6074 is kept so that you can work with several indirect buffers at the same time.
6075 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6076 requests that a new frame be made for the new buffer, so that the dedicated
6077 frame is not changed."
6078 (interactive "P")
6079 (let ((cbuf (current-buffer))
6080 (cwin (selected-window))
6081 (pos (point))
6082 beg end level heading ibuf)
6083 (save-excursion
6084 (org-back-to-heading t)
6085 (when (numberp arg)
6086 (setq level (org-outline-level))
6087 (if (< arg 0) (setq arg (+ level arg)))
6088 (while (> (setq level (org-outline-level)) arg)
6089 (outline-up-heading 1 t)))
6090 (setq beg (point)
6091 heading (org-get-heading))
6092 (org-end-of-subtree t) (setq end (point)))
6093 (if (and (buffer-live-p org-last-indirect-buffer)
6094 (not (eq org-indirect-buffer-display 'new-frame))
6095 (not arg))
6096 (kill-buffer org-last-indirect-buffer))
6097 (setq ibuf (org-get-indirect-buffer cbuf)
6098 org-last-indirect-buffer ibuf)
6099 (cond
6100 ((or (eq org-indirect-buffer-display 'new-frame)
6101 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6102 (select-frame (make-frame))
6103 (delete-other-windows)
6104 (switch-to-buffer ibuf)
6105 (org-set-frame-title heading))
6106 ((eq org-indirect-buffer-display 'dedicated-frame)
6107 (raise-frame
6108 (select-frame (or (and org-indirect-dedicated-frame
6109 (frame-live-p org-indirect-dedicated-frame)
6110 org-indirect-dedicated-frame)
6111 (setq org-indirect-dedicated-frame (make-frame)))))
6112 (delete-other-windows)
6113 (switch-to-buffer ibuf)
6114 (org-set-frame-title (concat "Indirect: " heading)))
6115 ((eq org-indirect-buffer-display 'current-window)
6116 (switch-to-buffer ibuf))
6117 ((eq org-indirect-buffer-display 'other-window)
6118 (pop-to-buffer ibuf))
6119 (t (error "Invalid value.")))
6120 (if (featurep 'xemacs)
6121 (save-excursion (org-mode) (turn-on-font-lock)))
6122 (narrow-to-region beg end)
6123 (show-all)
6124 (goto-char pos)
6125 (and (window-live-p cwin) (select-window cwin))))
6127 (defun org-get-indirect-buffer (&optional buffer)
6128 (setq buffer (or buffer (current-buffer)))
6129 (let ((n 1) (base (buffer-name buffer)) bname)
6130 (while (buffer-live-p
6131 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6132 (setq n (1+ n)))
6133 (condition-case nil
6134 (make-indirect-buffer buffer bname 'clone)
6135 (error (make-indirect-buffer buffer bname)))))
6137 (defun org-set-frame-title (title)
6138 "Set the title of the current frame to the string TITLE."
6139 ;; FIXME: how to name a single frame in XEmacs???
6140 (unless (featurep 'xemacs)
6141 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6143 ;;;; Structure editing
6145 ;;; Inserting headlines
6147 (defun org-insert-heading (&optional force-heading)
6148 "Insert a new heading or item with same depth at point.
6149 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6150 If point is at the beginning of a headline, insert a sibling before the
6151 current headline. If point is in the middle of a headline, split the headline
6152 at that position and make the rest of the headline part of the sibling below
6153 the current headline."
6154 (interactive "P")
6155 (if (= (buffer-size) 0)
6156 (insert "\n* ")
6157 (when (or force-heading (not (org-insert-item)))
6158 (let* ((head (save-excursion
6159 (condition-case nil
6160 (progn
6161 (org-back-to-heading)
6162 (match-string 0))
6163 (error "*"))))
6164 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6165 pos)
6166 (cond
6167 ((and (org-on-heading-p) (bolp)
6168 (or (bobp)
6169 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6170 (open-line (if blank 2 1)))
6171 ((and (bolp)
6172 (or (bobp)
6173 (save-excursion
6174 (backward-char 1) (not (org-invisible-p)))))
6175 nil)
6176 (t (newline (if blank 2 1))))
6177 (insert head) (just-one-space)
6178 (setq pos (point))
6179 (end-of-line 1)
6180 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6181 (run-hooks 'org-insert-heading-hook)))))
6183 (defun org-insert-heading-after-current ()
6184 "Insert a new heading with same level as current, after current subtree."
6185 (interactive)
6186 (org-back-to-heading)
6187 (org-insert-heading)
6188 (org-move-subtree-down)
6189 (end-of-line 1))
6191 (defun org-insert-todo-heading (arg)
6192 "Insert a new heading with the same level and TODO state as current heading.
6193 If the heading has no TODO state, or if the state is DONE, use the first
6194 state (TODO by default). Also with prefix arg, force first state."
6195 (interactive "P")
6196 (when (not (org-insert-item 'checkbox))
6197 (org-insert-heading)
6198 (save-excursion
6199 (org-back-to-heading)
6200 (outline-previous-heading)
6201 (looking-at org-todo-line-regexp))
6202 (if (or arg
6203 (not (match-beginning 2))
6204 (member (match-string 2) org-done-keywords))
6205 (insert (car org-todo-keywords-1) " ")
6206 (insert (match-string 2) " "))))
6208 (defun org-insert-subheading (arg)
6209 "Insert a new subheading and demote it.
6210 Works for outline headings and for plain lists alike."
6211 (interactive "P")
6212 (org-insert-heading arg)
6213 (cond
6214 ((org-on-heading-p) (org-do-demote))
6215 ((org-at-item-p) (org-indent-item 1))))
6217 (defun org-insert-todo-subheading (arg)
6218 "Insert a new subheading with TODO keyword or checkbox and demote it.
6219 Works for outline headings and for plain lists alike."
6220 (interactive "P")
6221 (org-insert-todo-heading arg)
6222 (cond
6223 ((org-on-heading-p) (org-do-demote))
6224 ((org-at-item-p) (org-indent-item 1))))
6226 ;;; Promotion and Demotion
6228 (defun org-promote-subtree ()
6229 "Promote the entire subtree.
6230 See also `org-promote'."
6231 (interactive)
6232 (save-excursion
6233 (org-map-tree 'org-promote))
6234 (org-fix-position-after-promote))
6236 (defun org-demote-subtree ()
6237 "Demote the entire subtree. See `org-demote'.
6238 See also `org-promote'."
6239 (interactive)
6240 (save-excursion
6241 (org-map-tree 'org-demote))
6242 (org-fix-position-after-promote))
6245 (defun org-do-promote ()
6246 "Promote the current heading higher up the tree.
6247 If the region is active in `transient-mark-mode', promote all headings
6248 in the region."
6249 (interactive)
6250 (save-excursion
6251 (if (org-region-active-p)
6252 (org-map-region 'org-promote (region-beginning) (region-end))
6253 (org-promote)))
6254 (org-fix-position-after-promote))
6256 (defun org-do-demote ()
6257 "Demote the current heading lower down the tree.
6258 If the region is active in `transient-mark-mode', demote all headings
6259 in the region."
6260 (interactive)
6261 (save-excursion
6262 (if (org-region-active-p)
6263 (org-map-region 'org-demote (region-beginning) (region-end))
6264 (org-demote)))
6265 (org-fix-position-after-promote))
6267 (defun org-fix-position-after-promote ()
6268 "Make sure that after pro/demotion cursor position is right."
6269 (let ((pos (point)))
6270 (when (save-excursion
6271 (beginning-of-line 1)
6272 (looking-at org-todo-line-regexp)
6273 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6274 (cond ((eobp) (insert " "))
6275 ((eolp) (insert " "))
6276 ((equal (char-after) ?\ ) (forward-char 1))))))
6278 (defun org-reduced-level (l)
6279 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6281 (defun org-get-legal-level (level &optional change)
6282 "Rectify a level change under the influence of `org-odd-levels-only'
6283 LEVEL is a current level, CHANGE is by how much the level should be
6284 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6285 even level numbers will become the next higher odd number."
6286 (if org-odd-levels-only
6287 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6288 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6289 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6290 (max 1 (+ level change))))
6292 (defun org-promote ()
6293 "Promote the current heading higher up the tree.
6294 If the region is active in `transient-mark-mode', promote all headings
6295 in the region."
6296 (org-back-to-heading t)
6297 (let* ((level (save-match-data (funcall outline-level)))
6298 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6299 (diff (abs (- level (length up-head) -1))))
6300 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6301 (replace-match up-head nil t)
6302 ;; Fixup tag positioning
6303 (and org-auto-align-tags (org-set-tags nil t))
6304 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6306 (defun org-demote ()
6307 "Demote the current heading lower down the tree.
6308 If the region is active in `transient-mark-mode', demote all headings
6309 in the region."
6310 (org-back-to-heading t)
6311 (let* ((level (save-match-data (funcall outline-level)))
6312 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6313 (diff (abs (- level (length down-head) -1))))
6314 (replace-match down-head nil t)
6315 ;; Fixup tag positioning
6316 (and org-auto-align-tags (org-set-tags nil t))
6317 (if org-adapt-indentation (org-fixup-indentation diff))))
6319 (defun org-map-tree (fun)
6320 "Call FUN for every heading underneath the current one."
6321 (org-back-to-heading)
6322 (let ((level (funcall outline-level)))
6323 (save-excursion
6324 (funcall fun)
6325 (while (and (progn
6326 (outline-next-heading)
6327 (> (funcall outline-level) level))
6328 (not (eobp)))
6329 (funcall fun)))))
6331 (defun org-map-region (fun beg end)
6332 "Call FUN for every heading between BEG and END."
6333 (let ((org-ignore-region t))
6334 (save-excursion
6335 (setq end (copy-marker end))
6336 (goto-char beg)
6337 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6338 (< (point) end))
6339 (funcall fun))
6340 (while (and (progn
6341 (outline-next-heading)
6342 (< (point) end))
6343 (not (eobp)))
6344 (funcall fun)))))
6346 (defun org-fixup-indentation (diff)
6347 "Change the indentation in the current entry by DIFF
6348 However, if any line in the current entry has no indentation, or if it
6349 would end up with no indentation after the change, nothing at all is done."
6350 (save-excursion
6351 (let ((end (save-excursion (outline-next-heading)
6352 (point-marker)))
6353 (prohibit (if (> diff 0)
6354 "^\\S-"
6355 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6356 col)
6357 (unless (save-excursion (end-of-line 1)
6358 (re-search-forward prohibit end t))
6359 (while (and (< (point) end)
6360 (re-search-forward "^[ \t]+" end t))
6361 (goto-char (match-end 0))
6362 (setq col (current-column))
6363 (if (< diff 0) (replace-match ""))
6364 (indent-to (+ diff col))))
6365 (move-marker end nil))))
6367 (defun org-convert-to-odd-levels ()
6368 "Convert an org-mode file with all levels allowed to one with odd levels.
6369 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6370 level 5 etc."
6371 (interactive)
6372 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6373 (let ((org-odd-levels-only nil) n)
6374 (save-excursion
6375 (goto-char (point-min))
6376 (while (re-search-forward "^\\*\\*+ " nil t)
6377 (setq n (- (length (match-string 0)) 2))
6378 (while (>= (setq n (1- n)) 0)
6379 (org-demote))
6380 (end-of-line 1))))))
6383 (defun org-convert-to-oddeven-levels ()
6384 "Convert an org-mode file with only odd levels to one with odd and even levels.
6385 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6386 section with an even level, conversion would destroy the structure of the file. An error
6387 is signaled in this case."
6388 (interactive)
6389 (goto-char (point-min))
6390 ;; First check if there are no even levels
6391 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6392 (org-show-context t)
6393 (error "Not all levels are odd in this file. Conversion not possible."))
6394 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6395 (let ((org-odd-levels-only nil) n)
6396 (save-excursion
6397 (goto-char (point-min))
6398 (while (re-search-forward "^\\*\\*+ " nil t)
6399 (setq n (/ (1- (length (match-string 0))) 2))
6400 (while (>= (setq n (1- n)) 0)
6401 (org-promote))
6402 (end-of-line 1))))))
6404 (defun org-tr-level (n)
6405 "Make N odd if required."
6406 (if org-odd-levels-only (1+ (/ n 2)) n))
6408 ;;; Vertical tree motion, cutting and pasting of subtrees
6410 (defun org-move-subtree-up (&optional arg)
6411 "Move the current subtree up past ARG headlines of the same level."
6412 (interactive "p")
6413 (org-move-subtree-down (- (prefix-numeric-value arg))))
6415 (defun org-move-subtree-down (&optional arg)
6416 "Move the current subtree down past ARG headlines of the same level."
6417 (interactive "p")
6418 (setq arg (prefix-numeric-value arg))
6419 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6420 'outline-get-last-sibling))
6421 (ins-point (make-marker))
6422 (cnt (abs arg))
6423 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6424 ;; Select the tree
6425 (org-back-to-heading)
6426 (setq beg0 (point))
6427 (save-excursion
6428 (setq ne-beg (org-back-over-empty-lines))
6429 (setq beg (point)))
6430 (save-match-data
6431 (save-excursion (outline-end-of-heading)
6432 (setq folded (org-invisible-p)))
6433 (outline-end-of-subtree))
6434 (outline-next-heading)
6435 (setq ne-end (org-back-over-empty-lines))
6436 (setq end (point))
6437 (goto-char beg0)
6438 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6439 ;; include less whitespace
6440 (save-excursion
6441 (goto-char beg)
6442 (forward-line (- ne-beg ne-end))
6443 (setq beg (point))))
6444 ;; Find insertion point, with error handling
6445 (while (> cnt 0)
6446 (or (and (funcall movfunc) (looking-at outline-regexp))
6447 (progn (goto-char beg0)
6448 (error "Cannot move past superior level or buffer limit")))
6449 (setq cnt (1- cnt)))
6450 (if (> arg 0)
6451 ;; Moving forward - still need to move over subtree
6452 (progn (org-end-of-subtree t t)
6453 (save-excursion
6454 (org-back-over-empty-lines)
6455 (or (bolp) (newline)))))
6456 (setq ne-ins (org-back-over-empty-lines))
6457 (move-marker ins-point (point))
6458 (setq txt (buffer-substring beg end))
6459 (delete-region beg end)
6460 (outline-flag-region (1- beg) beg nil)
6461 (outline-flag-region (1- (point)) (point) nil)
6462 (insert txt)
6463 (or (bolp) (insert "\n"))
6464 (setq ins-end (point))
6465 (goto-char ins-point)
6466 (org-skip-whitespace)
6467 (when (and (< arg 0)
6468 (org-first-sibling-p)
6469 (> ne-ins ne-beg))
6470 ;; Move whitespace back to beginning
6471 (save-excursion
6472 (goto-char ins-end)
6473 (let ((kill-whole-line t))
6474 (kill-line (- ne-ins ne-beg)) (point)))
6475 (insert (make-string (- ne-ins ne-beg) ?\n)))
6476 (move-marker ins-point nil)
6477 (org-compact-display-after-subtree-move)
6478 (unless folded
6479 (org-show-entry)
6480 (show-children)
6481 (org-cycle-hide-drawers 'children))))
6483 (defvar org-subtree-clip ""
6484 "Clipboard for cut and paste of subtrees.
6485 This is actually only a copy of the kill, because we use the normal kill
6486 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6488 (defvar org-subtree-clip-folded nil
6489 "Was the last copied subtree folded?
6490 This is used to fold the tree back after pasting.")
6492 (defun org-cut-subtree (&optional n)
6493 "Cut the current subtree into the clipboard.
6494 With prefix arg N, cut this many sequential subtrees.
6495 This is a short-hand for marking the subtree and then cutting it."
6496 (interactive "p")
6497 (org-copy-subtree n 'cut))
6499 (defun org-copy-subtree (&optional n cut)
6500 "Cut the current subtree into the clipboard.
6501 With prefix arg N, cut this many sequential subtrees.
6502 This is a short-hand for marking the subtree and then copying it.
6503 If CUT is non-nil, actually cut the subtree."
6504 (interactive "p")
6505 (let (beg end folded (beg0 (point)))
6506 (if (interactive-p)
6507 (org-back-to-heading nil) ; take what looks like a subtree
6508 (org-back-to-heading t)) ; take what is really there
6509 (org-back-over-empty-lines)
6510 (setq beg (point))
6511 (skip-chars-forward " \t\r\n")
6512 (save-match-data
6513 (save-excursion (outline-end-of-heading)
6514 (setq folded (org-invisible-p)))
6515 (condition-case nil
6516 (outline-forward-same-level (1- n))
6517 (error nil))
6518 (org-end-of-subtree t t))
6519 (org-back-over-empty-lines)
6520 (setq end (point))
6521 (goto-char beg0)
6522 (when (> end beg)
6523 (setq org-subtree-clip-folded folded)
6524 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6525 (setq org-subtree-clip (current-kill 0))
6526 (message "%s: Subtree(s) with %d characters"
6527 (if cut "Cut" "Copied")
6528 (length org-subtree-clip)))))
6530 (defun org-paste-subtree (&optional level tree)
6531 "Paste the clipboard as a subtree, with modification of headline level.
6532 The entire subtree is promoted or demoted in order to match a new headline
6533 level. By default, the new level is derived from the visible headings
6534 before and after the insertion point, and taken to be the inferior headline
6535 level of the two. So if the previous visible heading is level 3 and the
6536 next is level 4 (or vice versa), level 4 will be used for insertion.
6537 This makes sure that the subtree remains an independent subtree and does
6538 not swallow low level entries.
6540 You can also force a different level, either by using a numeric prefix
6541 argument, or by inserting the heading marker by hand. For example, if the
6542 cursor is after \"*****\", then the tree will be shifted to level 5.
6544 If you want to insert the tree as is, just use \\[yank].
6546 If optional TREE is given, use this text instead of the kill ring."
6547 (interactive "P")
6548 (unless (org-kill-is-subtree-p tree)
6549 (error "%s"
6550 (substitute-command-keys
6551 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6552 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6553 (^re (concat "^\\(" outline-regexp "\\)"))
6554 (re (concat "\\(" outline-regexp "\\)"))
6555 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6557 (old-level (if (string-match ^re txt)
6558 (- (match-end 0) (match-beginning 0) 1)
6559 -1))
6560 (force-level (cond (level (prefix-numeric-value level))
6561 ((string-match
6562 ^re_ (buffer-substring (point-at-bol) (point)))
6563 (- (match-end 1) (match-beginning 1)))
6564 (t nil)))
6565 (previous-level (save-excursion
6566 (condition-case nil
6567 (progn
6568 (outline-previous-visible-heading 1)
6569 (if (looking-at re)
6570 (- (match-end 0) (match-beginning 0) 1)
6572 (error 1))))
6573 (next-level (save-excursion
6574 (condition-case nil
6575 (progn
6576 (or (looking-at outline-regexp)
6577 (outline-next-visible-heading 1))
6578 (if (looking-at re)
6579 (- (match-end 0) (match-beginning 0) 1)
6581 (error 1))))
6582 (new-level (or force-level (max previous-level next-level)))
6583 (shift (if (or (= old-level -1)
6584 (= new-level -1)
6585 (= old-level new-level))
6587 (- new-level old-level)))
6588 (delta (if (> shift 0) -1 1))
6589 (func (if (> shift 0) 'org-demote 'org-promote))
6590 (org-odd-levels-only nil)
6591 beg end)
6592 ;; Remove the forced level indicator
6593 (if force-level
6594 (delete-region (point-at-bol) (point)))
6595 ;; Paste
6596 (beginning-of-line 1)
6597 (org-back-over-empty-lines) ;; FIXME: correct fix????
6598 (setq beg (point))
6599 (insert-before-markers txt) ;; FIXME: correct fix????
6600 (unless (string-match "\n\\'" txt) (insert "\n"))
6601 (setq end (point))
6602 (goto-char beg)
6603 (skip-chars-forward " \t\n\r")
6604 (setq beg (point))
6605 ;; Shift if necessary
6606 (unless (= shift 0)
6607 (save-restriction
6608 (narrow-to-region beg end)
6609 (while (not (= shift 0))
6610 (org-map-region func (point-min) (point-max))
6611 (setq shift (+ delta shift)))
6612 (goto-char (point-min))))
6613 (when (interactive-p)
6614 (message "Clipboard pasted as level %d subtree" new-level))
6615 (if (and kill-ring
6616 (eq org-subtree-clip (current-kill 0))
6617 org-subtree-clip-folded)
6618 ;; The tree was folded before it was killed/copied
6619 (hide-subtree))))
6621 (defun org-kill-is-subtree-p (&optional txt)
6622 "Check if the current kill is an outline subtree, or a set of trees.
6623 Returns nil if kill does not start with a headline, or if the first
6624 headline level is not the largest headline level in the tree.
6625 So this will actually accept several entries of equal levels as well,
6626 which is OK for `org-paste-subtree'.
6627 If optional TXT is given, check this string instead of the current kill."
6628 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6629 (start-level (and kill
6630 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6631 org-outline-regexp "\\)")
6632 kill)
6633 (- (match-end 2) (match-beginning 2) 1)))
6634 (re (concat "^" org-outline-regexp))
6635 (start (1+ (match-beginning 2))))
6636 (if (not start-level)
6637 (progn
6638 nil) ;; does not even start with a heading
6639 (catch 'exit
6640 (while (setq start (string-match re kill (1+ start)))
6641 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6642 (throw 'exit nil)))
6643 t))))
6645 (defun org-narrow-to-subtree ()
6646 "Narrow buffer to the current subtree."
6647 (interactive)
6648 (save-excursion
6649 (narrow-to-region
6650 (progn (org-back-to-heading) (point))
6651 (progn (org-end-of-subtree t t) (point)))))
6654 ;;; Outline Sorting
6656 (defun org-sort (with-case)
6657 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6658 Optional argument WITH-CASE means sort case-sensitively."
6659 (interactive "P")
6660 (if (org-at-table-p)
6661 (org-call-with-arg 'org-table-sort-lines with-case)
6662 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6664 (defvar org-priority-regexp) ; defined later in the file
6666 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6667 "Sort entries on a certain level of an outline tree.
6668 If there is an active region, the entries in the region are sorted.
6669 Else, if the cursor is before the first entry, sort the top-level items.
6670 Else, the children of the entry at point are sorted.
6672 Sorting can be alphabetically, numerically, and by date/time as given by
6673 the first time stamp in the entry. The command prompts for the sorting
6674 type unless it has been given to the function through the SORTING-TYPE
6675 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6676 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6677 called with point at the beginning of the record. It must return either
6678 a string or a number that should serve as the sorting key for that record.
6680 Comparing entries ignores case by default. However, with an optional argument
6681 WITH-CASE, the sorting considers case as well."
6682 (interactive "P")
6683 (let ((case-func (if with-case 'identity 'downcase))
6684 start beg end stars re re2
6685 txt what tmp plain-list-p)
6686 ;; Find beginning and end of region to sort
6687 (cond
6688 ((org-region-active-p)
6689 ;; we will sort the region
6690 (setq end (region-end)
6691 what "region")
6692 (goto-char (region-beginning))
6693 (if (not (org-on-heading-p)) (outline-next-heading))
6694 (setq start (point)))
6695 ((org-at-item-p)
6696 ;; we will sort this plain list
6697 (org-beginning-of-item-list) (setq start (point))
6698 (org-end-of-item-list) (setq end (point))
6699 (goto-char start)
6700 (setq plain-list-p t
6701 what "plain list"))
6702 ((or (org-on-heading-p)
6703 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6704 ;; we will sort the children of the current headline
6705 (org-back-to-heading)
6706 (setq start (point)
6707 end (progn (org-end-of-subtree t t)
6708 (org-back-over-empty-lines)
6709 (point))
6710 what "children")
6711 (goto-char start)
6712 (show-subtree)
6713 (outline-next-heading))
6715 ;; we will sort the top-level entries in this file
6716 (goto-char (point-min))
6717 (or (org-on-heading-p) (outline-next-heading))
6718 (setq start (point) end (point-max) what "top-level")
6719 (goto-char start)
6720 (show-all)))
6722 (setq beg (point))
6723 (if (>= beg end) (error "Nothing to sort"))
6725 (unless plain-list-p
6726 (looking-at "\\(\\*+\\)")
6727 (setq stars (match-string 1)
6728 re (concat "^" (regexp-quote stars) " +")
6729 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6730 txt (buffer-substring beg end))
6731 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6732 (if (and (not (equal stars "*")) (string-match re2 txt))
6733 (error "Region to sort contains a level above the first entry")))
6735 (unless sorting-type
6736 (message
6737 (if plain-list-p
6738 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6739 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6740 what)
6741 (setq sorting-type (read-char-exclusive))
6743 (and (= (downcase sorting-type) ?f)
6744 (setq getkey-func
6745 (completing-read "Sort using function: "
6746 obarray 'fboundp t nil nil))
6747 (setq getkey-func (intern getkey-func)))
6749 (and (= (downcase sorting-type) ?r)
6750 (setq property
6751 (completing-read "Property: "
6752 (mapcar 'list (org-buffer-property-keys t))
6753 nil t))))
6755 (message "Sorting entries...")
6757 (save-restriction
6758 (narrow-to-region start end)
6760 (let ((dcst (downcase sorting-type))
6761 (now (current-time)))
6762 (sort-subr
6763 (/= dcst sorting-type)
6764 ;; This function moves to the beginning character of the "record" to
6765 ;; be sorted.
6766 (if plain-list-p
6767 (lambda nil
6768 (if (org-at-item-p) t (goto-char (point-max))))
6769 (lambda nil
6770 (if (re-search-forward re nil t)
6771 (goto-char (match-beginning 0))
6772 (goto-char (point-max)))))
6773 ;; This function moves to the last character of the "record" being
6774 ;; sorted.
6775 (if plain-list-p
6776 'org-end-of-item
6777 (lambda nil
6778 (save-match-data
6779 (condition-case nil
6780 (outline-forward-same-level 1)
6781 (error
6782 (goto-char (point-max)))))))
6784 ;; This function returns the value that gets sorted against.
6785 (if plain-list-p
6786 (lambda nil
6787 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6788 (cond
6789 ((= dcst ?n)
6790 (string-to-number (buffer-substring (match-end 0)
6791 (point-at-eol))))
6792 ((= dcst ?a)
6793 (buffer-substring (match-end 0) (point-at-eol)))
6794 ((= dcst ?t)
6795 (if (re-search-forward org-ts-regexp
6796 (point-at-eol) t)
6797 (org-time-string-to-time (match-string 0))
6798 now))
6799 ((= dcst ?f)
6800 (if getkey-func
6801 (progn
6802 (setq tmp (funcall getkey-func))
6803 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6804 tmp)
6805 (error "Invalid key function `%s'" getkey-func)))
6806 (t (error "Invalid sorting type `%c'" sorting-type)))))
6807 (lambda nil
6808 (cond
6809 ((= dcst ?n)
6810 (if (looking-at outline-regexp)
6811 (string-to-number (buffer-substring (match-end 0)
6812 (point-at-eol)))
6813 nil))
6814 ((= dcst ?a)
6815 (funcall case-func (buffer-substring (point-at-bol)
6816 (point-at-eol))))
6817 ((= dcst ?t)
6818 (if (re-search-forward org-ts-regexp
6819 (save-excursion
6820 (forward-line 2)
6821 (point)) t)
6822 (org-time-string-to-time (match-string 0))
6823 now))
6824 ((= dcst ?p)
6825 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6826 (string-to-char (match-string 2))
6827 org-default-priority))
6828 ((= dcst ?r)
6829 (or (org-entry-get nil property) ""))
6830 ((= dcst ?f)
6831 (if getkey-func
6832 (progn
6833 (setq tmp (funcall getkey-func))
6834 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6835 tmp)
6836 (error "Invalid key function `%s'" getkey-func)))
6837 (t (error "Invalid sorting type `%c'" sorting-type)))))
6839 (cond
6840 ((= dcst ?a) 'string<)
6841 ((= dcst ?t) 'time-less-p)
6842 (t nil)))))
6843 (message "Sorting entries...done")))
6845 (defun org-do-sort (table what &optional with-case sorting-type)
6846 "Sort TABLE of WHAT according to SORTING-TYPE.
6847 The user will be prompted for the SORTING-TYPE if the call to this
6848 function does not specify it. WHAT is only for the prompt, to indicate
6849 what is being sorted. The sorting key will be extracted from
6850 the car of the elements of the table.
6851 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6852 (unless sorting-type
6853 (message
6854 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6855 what)
6856 (setq sorting-type (read-char-exclusive)))
6857 (let ((dcst (downcase sorting-type))
6858 extractfun comparefun)
6859 ;; Define the appropriate functions
6860 (cond
6861 ((= dcst ?n)
6862 (setq extractfun 'string-to-number
6863 comparefun (if (= dcst sorting-type) '< '>)))
6864 ((= dcst ?a)
6865 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6866 (lambda(x) (downcase (org-sort-remove-invisible x))))
6867 comparefun (if (= dcst sorting-type)
6868 'string<
6869 (lambda (a b) (and (not (string< a b))
6870 (not (string= a b)))))))
6871 ((= dcst ?t)
6872 (setq extractfun
6873 (lambda (x)
6874 (if (string-match org-ts-regexp x)
6875 (time-to-seconds
6876 (org-time-string-to-time (match-string 0 x)))
6878 comparefun (if (= dcst sorting-type) '< '>)))
6879 (t (error "Invalid sorting type `%c'" sorting-type)))
6881 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6882 table)
6883 (lambda (a b) (funcall comparefun (car a) (car b))))))
6885 ;;;; Plain list items, including checkboxes
6887 ;;; Plain list items
6889 (defun org-at-item-p ()
6890 "Is point in a line starting a hand-formatted item?"
6891 (let ((llt org-plain-list-ordered-item-terminator))
6892 (save-excursion
6893 (goto-char (point-at-bol))
6894 (looking-at
6895 (cond
6896 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6897 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6898 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6899 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6901 (defun org-in-item-p ()
6902 "It the cursor inside a plain list item.
6903 Does not have to be the first line."
6904 (save-excursion
6905 (condition-case nil
6906 (progn
6907 (org-beginning-of-item)
6908 (org-at-item-p)
6910 (error nil))))
6912 (defun org-insert-item (&optional checkbox)
6913 "Insert a new item at the current level.
6914 Return t when things worked, nil when we are not in an item."
6915 (when (save-excursion
6916 (condition-case nil
6917 (progn
6918 (org-beginning-of-item)
6919 (org-at-item-p)
6920 (if (org-invisible-p) (error "Invisible item"))
6922 (error nil)))
6923 (let* ((bul (match-string 0))
6924 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6925 (match-end 0)))
6926 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6927 pos)
6928 (cond
6929 ((and (org-at-item-p) (<= (point) eow))
6930 ;; before the bullet
6931 (beginning-of-line 1)
6932 (open-line (if blank 2 1)))
6933 ((<= (point) eow)
6934 (beginning-of-line 1))
6935 (t (newline (if blank 2 1))))
6936 (insert bul (if checkbox "[ ]" ""))
6937 (just-one-space)
6938 (setq pos (point))
6939 (end-of-line 1)
6940 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6941 (org-maybe-renumber-ordered-list)
6942 (and checkbox (org-update-checkbox-count-maybe))
6945 ;;; Checkboxes
6947 (defun org-at-item-checkbox-p ()
6948 "Is point at a line starting a plain-list item with a checklet?"
6949 (and (org-at-item-p)
6950 (save-excursion
6951 (goto-char (match-end 0))
6952 (skip-chars-forward " \t")
6953 (looking-at "\\[[- X]\\]"))))
6955 (defun org-toggle-checkbox (&optional arg)
6956 "Toggle the checkbox in the current line."
6957 (interactive "P")
6958 (catch 'exit
6959 (let (beg end status (firstnew 'unknown))
6960 (cond
6961 ((org-region-active-p)
6962 (setq beg (region-beginning) end (region-end)))
6963 ((org-on-heading-p)
6964 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6965 ((org-at-item-checkbox-p)
6966 (let ((pos (point)))
6967 (replace-match
6968 (cond (arg "[-]")
6969 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6970 (t "[ ]"))
6971 t t)
6972 (goto-char pos))
6973 (throw 'exit t))
6974 (t (error "Not at a checkbox or heading, and no active region")))
6975 (save-excursion
6976 (goto-char beg)
6977 (while (< (point) end)
6978 (when (org-at-item-checkbox-p)
6979 (setq status (equal (match-string 0) "[X]"))
6980 (when (eq firstnew 'unknown)
6981 (setq firstnew (not status)))
6982 (replace-match
6983 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6984 (beginning-of-line 2)))))
6985 (org-update-checkbox-count-maybe))
6987 (defun org-update-checkbox-count-maybe ()
6988 "Update checkbox statistics unless turned off by user."
6989 (when org-provide-checkbox-statistics
6990 (org-update-checkbox-count)))
6992 (defun org-update-checkbox-count (&optional all)
6993 "Update the checkbox statistics in the current section.
6994 This will find all statistic cookies like [57%] and [6/12] and update them
6995 with the current numbers. With optional prefix argument ALL, do this for
6996 the whole buffer."
6997 (interactive "P")
6998 (save-excursion
6999 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7000 (beg (condition-case nil
7001 (progn (outline-back-to-heading) (point))
7002 (error (point-min))))
7003 (end (move-marker (make-marker)
7004 (progn (outline-next-heading) (point))))
7005 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
7006 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7007 b1 e1 f1 c-on c-off lim (cstat 0))
7008 (when all
7009 (goto-char (point-min))
7010 (outline-next-heading)
7011 (setq beg (point) end (point-max)))
7012 (goto-char beg)
7013 (while (re-search-forward re end t)
7014 (setq cstat (1+ cstat)
7015 b1 (match-beginning 0)
7016 e1 (match-end 0)
7017 f1 (match-beginning 1)
7018 lim (cond
7019 ((org-on-heading-p) (outline-next-heading) (point))
7020 ((org-at-item-p) (org-end-of-item) (point))
7021 (t nil))
7022 c-on 0 c-off 0)
7023 (goto-char e1)
7024 (when lim
7025 (while (re-search-forward re-box lim t)
7026 (if (member (match-string 2) '("[ ]" "[-]"))
7027 (setq c-off (1+ c-off))
7028 (setq c-on (1+ c-on))))
7029 ; (delete-region b1 e1)
7030 (goto-char b1)
7031 (insert (if f1
7032 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7033 (format "[%d/%d]" c-on (+ c-on c-off))))
7034 (and (looking-at "\\[.*?\\]")
7035 (replace-match ""))))
7036 (when (interactive-p)
7037 (message "Checkbox satistics updated %s (%d places)"
7038 (if all "in entire file" "in current outline entry") cstat)))))
7040 (defun org-get-checkbox-statistics-face ()
7041 "Select the face for checkbox statistics.
7042 The face will be `org-done' when all relevant boxes are checked. Otherwise
7043 it will be `org-todo'."
7044 (if (match-end 1)
7045 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7046 (if (and (> (match-end 2) (match-beginning 2))
7047 (equal (match-string 2) (match-string 3)))
7048 'org-done
7049 'org-todo)))
7051 (defun org-get-indentation (&optional line)
7052 "Get the indentation of the current line, interpreting tabs.
7053 When LINE is given, assume it represents a line and compute its indentation."
7054 (if line
7055 (if (string-match "^ *" (org-remove-tabs line))
7056 (match-end 0))
7057 (save-excursion
7058 (beginning-of-line 1)
7059 (skip-chars-forward " \t")
7060 (current-column))))
7062 (defun org-remove-tabs (s &optional width)
7063 "Replace tabulators in S with spaces.
7064 Assumes that s is a single line, starting in column 0."
7065 (setq width (or width tab-width))
7066 (while (string-match "\t" s)
7067 (setq s (replace-match
7068 (make-string
7069 (- (* width (/ (+ (match-beginning 0) width) width))
7070 (match-beginning 0)) ?\ )
7071 t t s)))
7074 (defun org-fix-indentation (line ind)
7075 "Fix indentation in LINE.
7076 IND is a cons cell with target and minimum indentation.
7077 If the current indenation in LINE is smaller than the minimum,
7078 leave it alone. If it is larger than ind, set it to the target."
7079 (let* ((l (org-remove-tabs line))
7080 (i (org-get-indentation l))
7081 (i1 (car ind)) (i2 (cdr ind)))
7082 (if (>= i i2) (setq l (substring line i2)))
7083 (if (> i1 0)
7084 (concat (make-string i1 ?\ ) l)
7085 l)))
7087 (defcustom org-empty-line-terminates-plain-lists nil
7088 "Non-nil means, an empty line ends all plain list levels.
7089 When nil, empty lines are part of the preceeding item."
7090 :group 'org-plain-lists
7091 :type 'boolean)
7093 (defun org-beginning-of-item ()
7094 "Go to the beginning of the current hand-formatted item.
7095 If the cursor is not in an item, throw an error."
7096 (interactive)
7097 (let ((pos (point))
7098 (limit (save-excursion
7099 (condition-case nil
7100 (progn
7101 (org-back-to-heading)
7102 (beginning-of-line 2) (point))
7103 (error (point-min)))))
7104 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7105 ind ind1)
7106 (if (org-at-item-p)
7107 (beginning-of-line 1)
7108 (beginning-of-line 1)
7109 (skip-chars-forward " \t")
7110 (setq ind (current-column))
7111 (if (catch 'exit
7112 (while t
7113 (beginning-of-line 0)
7114 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7116 (if (looking-at "[ \t]*$")
7117 (setq ind1 ind-empty)
7118 (skip-chars-forward " \t")
7119 (setq ind1 (current-column)))
7120 (if (< ind1 ind)
7121 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7123 (goto-char pos)
7124 (error "Not in an item")))))
7126 (defun org-end-of-item ()
7127 "Go to the end of the current hand-formatted item.
7128 If the cursor is not in an item, throw an error."
7129 (interactive)
7130 (let* ((pos (point))
7131 ind1
7132 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7133 (limit (save-excursion (outline-next-heading) (point)))
7134 (ind (save-excursion
7135 (org-beginning-of-item)
7136 (skip-chars-forward " \t")
7137 (current-column)))
7138 (end (catch 'exit
7139 (while t
7140 (beginning-of-line 2)
7141 (if (eobp) (throw 'exit (point)))
7142 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7143 (if (looking-at "[ \t]*$")
7144 (setq ind1 ind-empty)
7145 (skip-chars-forward " \t")
7146 (setq ind1 (current-column)))
7147 (if (<= ind1 ind)
7148 (throw 'exit (point-at-bol)))))))
7149 (if end
7150 (goto-char end)
7151 (goto-char pos)
7152 (error "Not in an item"))))
7154 (defun org-next-item ()
7155 "Move to the beginning of the next item in the current plain list.
7156 Error if not at a plain list, or if this is the last item in the list."
7157 (interactive)
7158 (let (ind ind1 (pos (point)))
7159 (org-beginning-of-item)
7160 (setq ind (org-get-indentation))
7161 (org-end-of-item)
7162 (setq ind1 (org-get-indentation))
7163 (unless (and (org-at-item-p) (= ind ind1))
7164 (goto-char pos)
7165 (error "On last item"))))
7167 (defun org-previous-item ()
7168 "Move to the beginning of the previous item in the current plain list.
7169 Error if not at a plain list, or if this is the first item in the list."
7170 (interactive)
7171 (let (beg ind ind1 (pos (point)))
7172 (org-beginning-of-item)
7173 (setq beg (point))
7174 (setq ind (org-get-indentation))
7175 (goto-char beg)
7176 (catch 'exit
7177 (while t
7178 (beginning-of-line 0)
7179 (if (looking-at "[ \t]*$")
7181 (if (<= (setq ind1 (org-get-indentation)) ind)
7182 (throw 'exit t)))))
7183 (condition-case nil
7184 (if (or (not (org-at-item-p))
7185 (< ind1 (1- ind)))
7186 (error "")
7187 (org-beginning-of-item))
7188 (error (goto-char pos)
7189 (error "On first item")))))
7191 (defun org-first-list-item-p ()
7192 "Is this heading the item in a plain list?"
7193 (unless (org-at-item-p)
7194 (error "Not at a plain list item"))
7195 (org-beginning-of-item)
7196 (= (point) (save-excursion (org-beginning-of-item-list))))
7198 (defun org-move-item-down ()
7199 "Move the plain list item at point down, i.e. swap with following item.
7200 Subitems (items with larger indentation) are considered part of the item,
7201 so this really moves item trees."
7202 (interactive)
7203 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7204 (org-beginning-of-item)
7205 (setq beg0 (point))
7206 (save-excursion
7207 (setq ne-beg (org-back-over-empty-lines))
7208 (setq beg (point)))
7209 (goto-char beg0)
7210 (setq ind (org-get-indentation))
7211 (org-end-of-item)
7212 (setq end0 (point))
7213 (setq ind1 (org-get-indentation))
7214 (setq ne-end (org-back-over-empty-lines))
7215 (setq end (point))
7216 (goto-char beg0)
7217 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7218 ;; include less whitespace
7219 (save-excursion
7220 (goto-char beg)
7221 (forward-line (- ne-beg ne-end))
7222 (setq beg (point))))
7223 (goto-char end0)
7224 (if (and (org-at-item-p) (= ind ind1))
7225 (progn
7226 (org-end-of-item)
7227 (org-back-over-empty-lines)
7228 (setq txt (buffer-substring beg end))
7229 (save-excursion
7230 (delete-region beg end))
7231 (setq pos (point))
7232 (insert txt)
7233 (goto-char pos) (org-skip-whitespace)
7234 (org-maybe-renumber-ordered-list))
7235 (goto-char pos)
7236 (error "Cannot move this item further down"))))
7238 (defun org-move-item-up (arg)
7239 "Move the plain list item at point up, i.e. swap with previous item.
7240 Subitems (items with larger indentation) are considered part of the item,
7241 so this really moves item trees."
7242 (interactive "p")
7243 (let (beg beg0 end end0 ind ind1 (pos (point)) txt
7244 ne-beg ne-end ne-ins ins-end)
7245 (org-beginning-of-item)
7246 (setq beg0 (point))
7247 (setq ind (org-get-indentation))
7248 (save-excursion
7249 (setq ne-beg (org-back-over-empty-lines))
7250 (setq beg (point)))
7251 (goto-char beg0)
7252 (org-end-of-item)
7253 (setq ne-end (org-back-over-empty-lines))
7254 (setq end (point))
7255 (goto-char beg0)
7256 (catch 'exit
7257 (while t
7258 (beginning-of-line 0)
7259 (if (looking-at "[ \t]*$")
7260 (if org-empty-line-terminates-plain-lists
7261 (progn
7262 (goto-char pos)
7263 (error "Cannot move this item further up"))
7264 nil)
7265 (if (<= (setq ind1 (org-get-indentation)) ind)
7266 (throw 'exit t)))))
7267 (condition-case nil
7268 (org-beginning-of-item)
7269 (error (goto-char beg)
7270 (error "Cannot move this item further up")))
7271 (setq ind1 (org-get-indentation))
7272 (if (and (org-at-item-p) (= ind ind1))
7273 (progn
7274 (setq ne-ins (org-back-over-empty-lines))
7275 (setq txt (buffer-substring beg end))
7276 (save-excursion
7277 (delete-region beg end))
7278 (setq pos (point))
7279 (insert txt)
7280 (setq ins-end (point))
7281 (goto-char pos) (org-skip-whitespace)
7283 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7284 ;; Move whitespace back to beginning
7285 (save-excursion
7286 (goto-char ins-end)
7287 (let ((kill-whole-line t))
7288 (kill-line (- ne-ins ne-beg)) (point)))
7289 (insert (make-string (- ne-ins ne-beg) ?\n)))
7291 (org-maybe-renumber-ordered-list))
7292 (goto-char pos)
7293 (error "Cannot move this item further up"))))
7295 (defun org-maybe-renumber-ordered-list ()
7296 "Renumber the ordered list at point if setup allows it.
7297 This tests the user option `org-auto-renumber-ordered-lists' before
7298 doing the renumbering."
7299 (interactive)
7300 (when (and org-auto-renumber-ordered-lists
7301 (org-at-item-p))
7302 (if (match-beginning 3)
7303 (org-renumber-ordered-list 1)
7304 (org-fix-bullet-type))))
7306 (defun org-maybe-renumber-ordered-list-safe ()
7307 (condition-case nil
7308 (save-excursion
7309 (org-maybe-renumber-ordered-list))
7310 (error nil)))
7312 (defun org-cycle-list-bullet (&optional which)
7313 "Cycle through the different itemize/enumerate bullets.
7314 This cycle the entire list level through the sequence:
7316 `-' -> `+' -> `*' -> `1.' -> `1)'
7318 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7319 0 meand `-', 1 means `+' etc."
7320 (interactive "P")
7321 (org-preserve-lc
7322 (org-beginning-of-item-list)
7323 (org-at-item-p)
7324 (beginning-of-line 1)
7325 (let ((current (match-string 0))
7326 (prevp (eq which 'previous))
7327 new)
7328 (setq new (cond
7329 ((and (numberp which)
7330 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7331 ((string-match "-" current) (if prevp "1)" "+"))
7332 ((string-match "\\+" current)
7333 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7334 ((string-match "\\*" current) (if prevp "+" "1."))
7335 ((string-match "\\." current) (if prevp "*" "1)"))
7336 ((string-match ")" current) (if prevp "1." "-"))
7337 (t (error "This should not happen"))))
7338 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7339 (org-fix-bullet-type)
7340 (org-maybe-renumber-ordered-list))))
7342 (defun org-get-string-indentation (s)
7343 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7344 (let ((n -1) (i 0) (w tab-width) c)
7345 (catch 'exit
7346 (while (< (setq n (1+ n)) (length s))
7347 (setq c (aref s n))
7348 (cond ((= c ?\ ) (setq i (1+ i)))
7349 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7350 (t (throw 'exit t)))))
7353 (defun org-renumber-ordered-list (arg)
7354 "Renumber an ordered plain list.
7355 Cursor needs to be in the first line of an item, the line that starts
7356 with something like \"1.\" or \"2)\"."
7357 (interactive "p")
7358 (unless (and (org-at-item-p)
7359 (match-beginning 3))
7360 (error "This is not an ordered list"))
7361 (let ((line (org-current-line))
7362 (col (current-column))
7363 (ind (org-get-string-indentation
7364 (buffer-substring (point-at-bol) (match-beginning 3))))
7365 ;; (term (substring (match-string 3) -1))
7366 ind1 (n (1- arg))
7367 fmt)
7368 ;; find where this list begins
7369 (org-beginning-of-item-list)
7370 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7371 (setq fmt (concat "%d" (match-string 1)))
7372 (beginning-of-line 0)
7373 ;; walk forward and replace these numbers
7374 (catch 'exit
7375 (while t
7376 (catch 'next
7377 (beginning-of-line 2)
7378 (if (eobp) (throw 'exit nil))
7379 (if (looking-at "[ \t]*$") (throw 'next nil))
7380 (skip-chars-forward " \t") (setq ind1 (current-column))
7381 (if (> ind1 ind) (throw 'next t))
7382 (if (< ind1 ind) (throw 'exit t))
7383 (if (not (org-at-item-p)) (throw 'exit nil))
7384 (delete-region (match-beginning 2) (match-end 2))
7385 (goto-char (match-beginning 2))
7386 (insert (format fmt (setq n (1+ n)))))))
7387 (goto-line line)
7388 (move-to-column col)))
7390 (defun org-fix-bullet-type ()
7391 "Make sure all items in this list have the same bullet as the firsst item."
7392 (interactive)
7393 (unless (org-at-item-p) (error "This is not a list"))
7394 (let ((line (org-current-line))
7395 (col (current-column))
7396 (ind (current-indentation))
7397 ind1 bullet)
7398 ;; find where this list begins
7399 (org-beginning-of-item-list)
7400 (beginning-of-line 1)
7401 ;; find out what the bullet type is
7402 (looking-at "[ \t]*\\(\\S-+\\)")
7403 (setq bullet (match-string 1))
7404 ;; walk forward and replace these numbers
7405 (beginning-of-line 0)
7406 (catch 'exit
7407 (while t
7408 (catch 'next
7409 (beginning-of-line 2)
7410 (if (eobp) (throw 'exit nil))
7411 (if (looking-at "[ \t]*$") (throw 'next nil))
7412 (skip-chars-forward " \t") (setq ind1 (current-column))
7413 (if (> ind1 ind) (throw 'next t))
7414 (if (< ind1 ind) (throw 'exit t))
7415 (if (not (org-at-item-p)) (throw 'exit nil))
7416 (skip-chars-forward " \t")
7417 (looking-at "\\S-+")
7418 (replace-match bullet))))
7419 (goto-line line)
7420 (move-to-column col)
7421 (if (string-match "[0-9]" bullet)
7422 (org-renumber-ordered-list 1))))
7424 (defun org-beginning-of-item-list ()
7425 "Go to the beginning of the current item list.
7426 I.e. to the first item in this list."
7427 (interactive)
7428 (org-beginning-of-item)
7429 (let ((pos (point-at-bol))
7430 (ind (org-get-indentation))
7431 ind1)
7432 ;; find where this list begins
7433 (catch 'exit
7434 (while t
7435 (catch 'next
7436 (beginning-of-line 0)
7437 (if (looking-at "[ \t]*$")
7438 (throw (if (bobp) 'exit 'next) t))
7439 (skip-chars-forward " \t") (setq ind1 (current-column))
7440 (if (or (< ind1 ind)
7441 (and (= ind1 ind)
7442 (not (org-at-item-p)))
7443 (bobp))
7444 (throw 'exit t)
7445 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7446 (goto-char pos)))
7449 (defun org-end-of-item-list ()
7450 "Go to the end of the current item list.
7451 I.e. to the text after the last item."
7452 (interactive)
7453 (org-beginning-of-item)
7454 (let ((pos (point-at-bol))
7455 (ind (org-get-indentation))
7456 ind1)
7457 ;; find where this list begins
7458 (catch 'exit
7459 (while t
7460 (catch 'next
7461 (beginning-of-line 2)
7462 (if (looking-at "[ \t]*$")
7463 (throw (if (eobp) 'exit 'next) t))
7464 (skip-chars-forward " \t") (setq ind1 (current-column))
7465 (if (or (< ind1 ind)
7466 (and (= ind1 ind)
7467 (not (org-at-item-p)))
7468 (eobp))
7469 (progn
7470 (setq pos (point-at-bol))
7471 (throw 'exit t))))))
7472 (goto-char pos)))
7475 (defvar org-last-indent-begin-marker (make-marker))
7476 (defvar org-last-indent-end-marker (make-marker))
7478 (defun org-outdent-item (arg)
7479 "Outdent a local list item."
7480 (interactive "p")
7481 (org-indent-item (- arg)))
7483 (defun org-indent-item (arg)
7484 "Indent a local list item."
7485 (interactive "p")
7486 (unless (org-at-item-p)
7487 (error "Not on an item"))
7488 (save-excursion
7489 (let (beg end ind ind1 tmp delta ind-down ind-up)
7490 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7491 (setq beg org-last-indent-begin-marker
7492 end org-last-indent-end-marker)
7493 (org-beginning-of-item)
7494 (setq beg (move-marker org-last-indent-begin-marker (point)))
7495 (org-end-of-item)
7496 (setq end (move-marker org-last-indent-end-marker (point))))
7497 (goto-char beg)
7498 (setq tmp (org-item-indent-positions)
7499 ind (car tmp)
7500 ind-down (nth 2 tmp)
7501 ind-up (nth 1 tmp)
7502 delta (if (> arg 0)
7503 (if ind-down (- ind-down ind) 2)
7504 (if ind-up (- ind-up ind) -2)))
7505 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7506 (while (< (point) end)
7507 (beginning-of-line 1)
7508 (skip-chars-forward " \t") (setq ind1 (current-column))
7509 (delete-region (point-at-bol) (point))
7510 (or (eolp) (indent-to-column (+ ind1 delta)))
7511 (beginning-of-line 2))))
7512 (org-fix-bullet-type)
7513 (org-maybe-renumber-ordered-list-safe)
7514 (save-excursion
7515 (beginning-of-line 0)
7516 (condition-case nil (org-beginning-of-item) (error nil))
7517 (org-maybe-renumber-ordered-list-safe)))
7519 (defun org-item-indent-positions ()
7520 "Return indentation for plain list items.
7521 This returns a list with three values: The current indentation, the
7522 parent indentation and the indentation a child should habe.
7523 Assumes cursor in item line."
7524 (let* ((bolpos (point-at-bol))
7525 (ind (org-get-indentation))
7526 ind-down ind-up pos)
7527 (save-excursion
7528 (org-beginning-of-item-list)
7529 (skip-chars-backward "\n\r \t")
7530 (when (org-in-item-p)
7531 (org-beginning-of-item)
7532 (setq ind-up (org-get-indentation))))
7533 (setq pos (point))
7534 (save-excursion
7535 (cond
7536 ((and (condition-case nil (progn (org-previous-item) t)
7537 (error nil))
7538 (or (forward-char 1) t)
7539 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7540 (setq ind-down (org-get-indentation)))
7541 ((and (goto-char pos)
7542 (org-at-item-p))
7543 (goto-char (match-end 0))
7544 (skip-chars-forward " \t")
7545 (setq ind-down (current-column)))))
7546 (list ind ind-up ind-down)))
7548 ;;; The orgstruct minor mode
7550 ;; Define a minor mode which can be used in other modes in order to
7551 ;; integrate the org-mode structure editing commands.
7553 ;; This is really a hack, because the org-mode structure commands use
7554 ;; keys which normally belong to the major mode. Here is how it
7555 ;; works: The minor mode defines all the keys necessary to operate the
7556 ;; structure commands, but wraps the commands into a function which
7557 ;; tests if the cursor is currently at a headline or a plain list
7558 ;; item. If that is the case, the structure command is used,
7559 ;; temporarily setting many Org-mode variables like regular
7560 ;; expressions for filling etc. However, when any of those keys is
7561 ;; used at a different location, function uses `key-binding' to look
7562 ;; up if the key has an associated command in another currently active
7563 ;; keymap (minor modes, major mode, global), and executes that
7564 ;; command. There might be problems if any of the keys is otherwise
7565 ;; used as a prefix key.
7567 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7568 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7569 ;; addresses this by checking explicitly for both bindings.
7571 (defvar orgstruct-mode-map (make-sparse-keymap)
7572 "Keymap for the minor `orgstruct-mode'.")
7574 (defvar org-local-vars nil
7575 "List of local variables, for use by `orgstruct-mode'")
7577 ;;;###autoload
7578 (define-minor-mode orgstruct-mode
7579 "Toggle the minor more `orgstruct-mode'.
7580 This mode is for using Org-mode structure commands in other modes.
7581 The following key behave as if Org-mode was active, if the cursor
7582 is on a headline, or on a plain list item (both in the definition
7583 of Org-mode).
7585 M-up Move entry/item up
7586 M-down Move entry/item down
7587 M-left Promote
7588 M-right Demote
7589 M-S-up Move entry/item up
7590 M-S-down Move entry/item down
7591 M-S-left Promote subtree
7592 M-S-right Demote subtree
7593 M-q Fill paragraph and items like in Org-mode
7594 C-c ^ Sort entries
7595 C-c - Cycle list bullet
7596 TAB Cycle item visibility
7597 M-RET Insert new heading/item
7598 S-M-RET Insert new TODO heading / Chekbox item
7599 C-c C-c Set tags / toggle checkbox"
7600 nil " OrgStruct" nil
7601 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7603 ;;;###autoload
7604 (defun turn-on-orgstruct ()
7605 "Unconditionally turn on `orgstruct-mode'."
7606 (orgstruct-mode 1))
7608 ;;;###autoload
7609 (defun turn-on-orgstruct++ ()
7610 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7611 In addition to setting orgstruct-mode, this also exports all indentation and
7612 autofilling variables from org-mode into the buffer. Note that turning
7613 off orgstruct-mode will *not* remove these additional settings."
7614 (orgstruct-mode 1)
7615 (let (var val)
7616 (mapc
7617 (lambda (x)
7618 (when (string-match
7619 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7620 (symbol-name (car x)))
7621 (setq var (car x) val (nth 1 x))
7622 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7623 org-local-vars)))
7625 (defun orgstruct-error ()
7626 "Error when there is no default binding for a structure key."
7627 (interactive)
7628 (error "This key has no function outside structure elements"))
7630 (defun orgstruct-setup ()
7631 "Setup orgstruct keymaps."
7632 (let ((nfunc 0)
7633 (bindings
7634 (list
7635 '([(meta up)] org-metaup)
7636 '([(meta down)] org-metadown)
7637 '([(meta left)] org-metaleft)
7638 '([(meta right)] org-metaright)
7639 '([(meta shift up)] org-shiftmetaup)
7640 '([(meta shift down)] org-shiftmetadown)
7641 '([(meta shift left)] org-shiftmetaleft)
7642 '([(meta shift right)] org-shiftmetaright)
7643 '([(shift up)] org-shiftup)
7644 '([(shift down)] org-shiftdown)
7645 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7646 '("\M-q" fill-paragraph)
7647 '("\C-c^" org-sort)
7648 '("\C-c-" org-cycle-list-bullet)))
7649 elt key fun cmd)
7650 (while (setq elt (pop bindings))
7651 (setq nfunc (1+ nfunc))
7652 (setq key (org-key (car elt))
7653 fun (nth 1 elt)
7654 cmd (orgstruct-make-binding fun nfunc key))
7655 (org-defkey orgstruct-mode-map key cmd))
7657 ;; Special treatment needed for TAB and RET
7658 (org-defkey orgstruct-mode-map [(tab)]
7659 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7660 (org-defkey orgstruct-mode-map "\C-i"
7661 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7663 (org-defkey orgstruct-mode-map "\M-\C-m"
7664 (orgstruct-make-binding 'org-insert-heading 105
7665 "\M-\C-m" [(meta return)]))
7666 (org-defkey orgstruct-mode-map [(meta return)]
7667 (orgstruct-make-binding 'org-insert-heading 106
7668 [(meta return)] "\M-\C-m"))
7670 (org-defkey orgstruct-mode-map [(shift meta return)]
7671 (orgstruct-make-binding 'org-insert-todo-heading 107
7672 [(meta return)] "\M-\C-m"))
7674 (unless org-local-vars
7675 (setq org-local-vars (org-get-local-variables)))
7679 (defun orgstruct-make-binding (fun n &rest keys)
7680 "Create a function for binding in the structure minor mode.
7681 FUN is the command to call inside a table. N is used to create a unique
7682 command name. KEYS are keys that should be checked in for a command
7683 to execute outside of tables."
7684 (eval
7685 (list 'defun
7686 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7687 '(arg)
7688 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7689 "Outside of structure, run the binding of `"
7690 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7691 "'.")
7692 '(interactive "p")
7693 (list 'if
7694 '(org-context-p 'headline 'item)
7695 (list 'org-run-like-in-org-mode (list 'quote fun))
7696 (list 'let '(orgstruct-mode)
7697 (list 'call-interactively
7698 (append '(or)
7699 (mapcar (lambda (k)
7700 (list 'key-binding k))
7701 keys)
7702 '('orgstruct-error))))))))
7704 (defun org-context-p (&rest contexts)
7705 "Check if local context is and of CONTEXTS.
7706 Possible values in the list of contexts are `table', `headline', and `item'."
7707 (let ((pos (point)))
7708 (goto-char (point-at-bol))
7709 (prog1 (or (and (memq 'table contexts)
7710 (looking-at "[ \t]*|"))
7711 (and (memq 'headline contexts)
7712 (looking-at "\\*+"))
7713 (and (memq 'item contexts)
7714 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7715 (goto-char pos))))
7717 (defun org-get-local-variables ()
7718 "Return a list of all local variables in an org-mode buffer."
7719 (let (varlist)
7720 (with-current-buffer (get-buffer-create "*Org tmp*")
7721 (erase-buffer)
7722 (org-mode)
7723 (setq varlist (buffer-local-variables)))
7724 (kill-buffer "*Org tmp*")
7725 (delq nil
7726 (mapcar
7727 (lambda (x)
7728 (setq x
7729 (if (symbolp x)
7730 (list x)
7731 (list (car x) (list 'quote (cdr x)))))
7732 (if (string-match
7733 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7734 (symbol-name (car x)))
7735 x nil))
7736 varlist))))
7738 ;;;###autoload
7739 (defun org-run-like-in-org-mode (cmd)
7740 (unless org-local-vars
7741 (setq org-local-vars (org-get-local-variables)))
7742 (eval (list 'let org-local-vars
7743 (list 'call-interactively (list 'quote cmd)))))
7745 ;;;; Archiving
7747 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7749 (defun org-archive-subtree (&optional find-done)
7750 "Move the current subtree to the archive.
7751 The archive can be a certain top-level heading in the current file, or in
7752 a different file. The tree will be moved to that location, the subtree
7753 heading be marked DONE, and the current time will be added.
7755 When called with prefix argument FIND-DONE, find whole trees without any
7756 open TODO items and archive them (after getting confirmation from the user).
7757 If the cursor is not at a headline when this comand is called, try all level
7758 1 trees. If the cursor is on a headline, only try the direct children of
7759 this heading."
7760 (interactive "P")
7761 (if find-done
7762 (org-archive-all-done)
7763 ;; Save all relevant TODO keyword-relatex variables
7765 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7766 (tr-org-todo-keywords-1 org-todo-keywords-1)
7767 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7768 (tr-org-done-keywords org-done-keywords)
7769 (tr-org-todo-regexp org-todo-regexp)
7770 (tr-org-todo-line-regexp org-todo-line-regexp)
7771 (tr-org-odd-levels-only org-odd-levels-only)
7772 (this-buffer (current-buffer))
7773 (org-archive-location org-archive-location)
7774 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7775 ;; start of variables that will be used for saving context
7776 ;; The compiler complains about them - keep them anyway!
7777 (file (abbreviate-file-name (buffer-file-name)))
7778 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7779 (time (format-time-string
7780 (substring (cdr org-time-stamp-formats) 1 -1)
7781 (current-time)))
7782 afile heading buffer level newfile-p
7783 category todo priority
7784 ;; start of variables that will be used for savind context
7785 ltags itags prop)
7787 ;; Try to find a local archive location
7788 (save-excursion
7789 (save-restriction
7790 (widen)
7791 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7792 (if (and prop (string-match "\\S-" prop))
7793 (setq org-archive-location prop)
7794 (if (or (re-search-backward re nil t)
7795 (re-search-forward re nil t))
7796 (setq org-archive-location (match-string 1))))))
7798 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7799 (progn
7800 (setq afile (format (match-string 1 org-archive-location)
7801 (file-name-nondirectory buffer-file-name))
7802 heading (match-string 2 org-archive-location)))
7803 (error "Invalid `org-archive-location'"))
7804 (if (> (length afile) 0)
7805 (setq newfile-p (not (file-exists-p afile))
7806 buffer (find-file-noselect afile))
7807 (setq buffer (current-buffer)))
7808 (unless buffer
7809 (error "Cannot access file \"%s\"" afile))
7810 (if (and (> (length heading) 0)
7811 (string-match "^\\*+" heading))
7812 (setq level (match-end 0))
7813 (setq heading nil level 0))
7814 (save-excursion
7815 (org-back-to-heading t)
7816 ;; Get context information that will be lost by moving the tree
7817 (org-refresh-category-properties)
7818 (setq category (org-get-category)
7819 todo (and (looking-at org-todo-line-regexp)
7820 (match-string 2))
7821 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7822 ltags (org-get-tags)
7823 itags (org-delete-all ltags (org-get-tags-at)))
7824 (setq ltags (mapconcat 'identity ltags " ")
7825 itags (mapconcat 'identity itags " "))
7826 ;; We first only copy, in case something goes wrong
7827 ;; we need to protect this-command, to avoid kill-region sets it,
7828 ;; which would lead to duplication of subtrees
7829 (let (this-command) (org-copy-subtree))
7830 (set-buffer buffer)
7831 ;; Enforce org-mode for the archive buffer
7832 (if (not (org-mode-p))
7833 ;; Force the mode for future visits.
7834 (let ((org-insert-mode-line-in-empty-file t)
7835 (org-inhibit-startup t))
7836 (call-interactively 'org-mode)))
7837 (when newfile-p
7838 (goto-char (point-max))
7839 (insert (format "\nArchived entries from file %s\n\n"
7840 (buffer-file-name this-buffer))))
7841 ;; Force the TODO keywords of the original buffer
7842 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7843 (org-todo-keywords-1 tr-org-todo-keywords-1)
7844 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7845 (org-done-keywords tr-org-done-keywords)
7846 (org-todo-regexp tr-org-todo-regexp)
7847 (org-todo-line-regexp tr-org-todo-line-regexp)
7848 (org-odd-levels-only
7849 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7850 org-odd-levels-only
7851 tr-org-odd-levels-only)))
7852 (goto-char (point-min))
7853 (if heading
7854 (progn
7855 (if (re-search-forward
7856 (concat "^" (regexp-quote heading)
7857 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7858 nil t)
7859 (goto-char (match-end 0))
7860 ;; Heading not found, just insert it at the end
7861 (goto-char (point-max))
7862 (or (bolp) (insert "\n"))
7863 (insert "\n" heading "\n")
7864 (end-of-line 0))
7865 ;; Make the subtree visible
7866 (show-subtree)
7867 (org-end-of-subtree t)
7868 (skip-chars-backward " \t\r\n")
7869 (and (looking-at "[ \t\r\n]*")
7870 (replace-match "\n\n")))
7871 ;; No specific heading, just go to end of file.
7872 (goto-char (point-max)) (insert "\n"))
7873 ;; Paste
7874 (org-paste-subtree (org-get-legal-level level 1))
7876 ;; Mark the entry as done
7877 (when (and org-archive-mark-done
7878 (looking-at org-todo-line-regexp)
7879 (or (not (match-end 2))
7880 (not (member (match-string 2) org-done-keywords))))
7881 (let (org-log-done)
7882 (org-todo
7883 (car (or (member org-archive-mark-done org-done-keywords)
7884 org-done-keywords)))))
7886 ;; Add the context info
7887 (when org-archive-save-context-info
7888 (let ((l org-archive-save-context-info) e n v)
7889 (while (setq e (pop l))
7890 (when (and (setq v (symbol-value e))
7891 (stringp v) (string-match "\\S-" v))
7892 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7893 (org-entry-put (point) n v)))))
7895 ;; Save the buffer, if it is not the same buffer.
7896 (if (not (eq this-buffer buffer)) (save-buffer))))
7897 ;; Here we are back in the original buffer. Everything seems to have
7898 ;; worked. So now cut the tree and finish up.
7899 (let (this-command) (org-cut-subtree))
7900 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7901 (message "Subtree archived %s"
7902 (if (eq this-buffer buffer)
7903 (concat "under heading: " heading)
7904 (concat "in file: " (abbreviate-file-name afile)))))))
7906 (defun org-refresh-category-properties ()
7907 "Refresh category text properties in teh buffer."
7908 (let ((def-cat (cond
7909 ((null org-category)
7910 (if buffer-file-name
7911 (file-name-sans-extension
7912 (file-name-nondirectory buffer-file-name))
7913 "???"))
7914 ((symbolp org-category) (symbol-name org-category))
7915 (t org-category)))
7916 beg end cat pos optionp)
7917 (org-unmodified
7918 (save-excursion
7919 (save-restriction
7920 (widen)
7921 (goto-char (point-min))
7922 (put-text-property (point) (point-max) 'org-category def-cat)
7923 (while (re-search-forward
7924 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7925 (setq pos (match-end 0)
7926 optionp (equal (char-after (match-beginning 0)) ?#)
7927 cat (org-trim (match-string 2)))
7928 (if optionp
7929 (setq beg (point-at-bol) end (point-max))
7930 (org-back-to-heading t)
7931 (setq beg (point) end (org-end-of-subtree t t)))
7932 (put-text-property beg end 'org-category cat)
7933 (goto-char pos)))))))
7935 (defun org-archive-all-done (&optional tag)
7936 "Archive sublevels of the current tree without open TODO items.
7937 If the cursor is not on a headline, try all level 1 trees. If
7938 it is on a headline, try all direct children.
7939 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7940 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7941 (rea (concat ".*:" org-archive-tag ":"))
7942 (begm (make-marker))
7943 (endm (make-marker))
7944 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7945 "Move subtree to archive (no open TODO items)? "))
7946 beg end (cntarch 0))
7947 (if (org-on-heading-p)
7948 (progn
7949 (setq re1 (concat "^" (regexp-quote
7950 (make-string
7951 (1+ (- (match-end 0) (match-beginning 0) 1))
7952 ?*))
7953 " "))
7954 (move-marker begm (point))
7955 (move-marker endm (org-end-of-subtree t)))
7956 (setq re1 "^* ")
7957 (move-marker begm (point-min))
7958 (move-marker endm (point-max)))
7959 (save-excursion
7960 (goto-char begm)
7961 (while (re-search-forward re1 endm t)
7962 (setq beg (match-beginning 0)
7963 end (save-excursion (org-end-of-subtree t) (point)))
7964 (goto-char beg)
7965 (if (re-search-forward re end t)
7966 (goto-char end)
7967 (goto-char beg)
7968 (if (and (or (not tag) (not (looking-at rea)))
7969 (y-or-n-p question))
7970 (progn
7971 (if tag
7972 (org-toggle-tag org-archive-tag 'on)
7973 (org-archive-subtree))
7974 (setq cntarch (1+ cntarch)))
7975 (goto-char end)))))
7976 (message "%d trees archived" cntarch)))
7978 (defun org-cycle-hide-drawers (state)
7979 "Re-hide all drawers after a visibility state change."
7980 (when (and (org-mode-p)
7981 (not (memq state '(overview folded))))
7982 (save-excursion
7983 (let* ((globalp (memq state '(contents all)))
7984 (beg (if globalp (point-min) (point)))
7985 (end (if globalp (point-max) (org-end-of-subtree t))))
7986 (goto-char beg)
7987 (while (re-search-forward org-drawer-regexp end t)
7988 (org-flag-drawer t))))))
7990 (defun org-flag-drawer (flag)
7991 (save-excursion
7992 (beginning-of-line 1)
7993 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7994 (let ((b (match-end 0))
7995 (outline-regexp org-outline-regexp))
7996 (if (re-search-forward
7997 "^[ \t]*:END:"
7998 (save-excursion (outline-next-heading) (point)) t)
7999 (outline-flag-region b (point-at-eol) flag)
8000 (error ":END: line missing"))))))
8002 (defun org-cycle-hide-archived-subtrees (state)
8003 "Re-hide all archived subtrees after a visibility state change."
8004 (when (and (not org-cycle-open-archived-trees)
8005 (not (memq state '(overview folded))))
8006 (save-excursion
8007 (let* ((globalp (memq state '(contents all)))
8008 (beg (if globalp (point-min) (point)))
8009 (end (if globalp (point-max) (org-end-of-subtree t))))
8010 (org-hide-archived-subtrees beg end)
8011 (goto-char beg)
8012 (if (looking-at (concat ".*:" org-archive-tag ":"))
8013 (message "%s" (substitute-command-keys
8014 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8016 (defun org-force-cycle-archived ()
8017 "Cycle subtree even if it is archived."
8018 (interactive)
8019 (setq this-command 'org-cycle)
8020 (let ((org-cycle-open-archived-trees t))
8021 (call-interactively 'org-cycle)))
8023 (defun org-hide-archived-subtrees (beg end)
8024 "Re-hide all archived subtrees after a visibility state change."
8025 (save-excursion
8026 (let* ((re (concat ":" org-archive-tag ":")))
8027 (goto-char beg)
8028 (while (re-search-forward re end t)
8029 (and (org-on-heading-p) (hide-subtree))
8030 (org-end-of-subtree t)))))
8032 (defun org-toggle-tag (tag &optional onoff)
8033 "Toggle the tag TAG for the current line.
8034 If ONOFF is `on' or `off', don't toggle but set to this state."
8035 (unless (org-on-heading-p t) (error "Not on headling"))
8036 (let (res current)
8037 (save-excursion
8038 (beginning-of-line)
8039 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8040 (point-at-eol) t)
8041 (progn
8042 (setq current (match-string 1))
8043 (replace-match ""))
8044 (setq current ""))
8045 (setq current (nreverse (org-split-string current ":")))
8046 (cond
8047 ((eq onoff 'on)
8048 (setq res t)
8049 (or (member tag current) (push tag current)))
8050 ((eq onoff 'off)
8051 (or (not (member tag current)) (setq current (delete tag current))))
8052 (t (if (member tag current)
8053 (setq current (delete tag current))
8054 (setq res t)
8055 (push tag current))))
8056 (end-of-line 1)
8057 (if current
8058 (progn
8059 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8060 (org-set-tags nil t))
8061 (delete-horizontal-space))
8062 (run-hooks 'org-after-tags-change-hook))
8063 res))
8065 (defun org-toggle-archive-tag (&optional arg)
8066 "Toggle the archive tag for the current headline.
8067 With prefix ARG, check all children of current headline and offer tagging
8068 the children that do not contain any open TODO items."
8069 (interactive "P")
8070 (if arg
8071 (org-archive-all-done 'tag)
8072 (let (set)
8073 (save-excursion
8074 (org-back-to-heading t)
8075 (setq set (org-toggle-tag org-archive-tag))
8076 (when set (hide-subtree)))
8077 (and set (beginning-of-line 1))
8078 (message "Subtree %s" (if set "archived" "unarchived")))))
8081 ;;;; Tables
8083 ;;; The table editor
8085 ;; Watch out: Here we are talking about two different kind of tables.
8086 ;; Most of the code is for the tables created with the Org-mode table editor.
8087 ;; Sometimes, we talk about tables created and edited with the table.el
8088 ;; Emacs package. We call the former org-type tables, and the latter
8089 ;; table.el-type tables.
8091 (defun org-before-change-function (beg end)
8092 "Every change indicates that a table might need an update."
8093 (setq org-table-may-need-update t))
8095 (defconst org-table-line-regexp "^[ \t]*|"
8096 "Detects an org-type table line.")
8097 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8098 "Detects an org-type table line.")
8099 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8100 "Detects a table line marked for automatic recalculation.")
8101 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8102 "Detects a table line marked for automatic recalculation.")
8103 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8104 "Detects a table line marked for automatic recalculation.")
8105 (defconst org-table-hline-regexp "^[ \t]*|-"
8106 "Detects an org-type table hline.")
8107 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8108 "Detects a table-type table hline.")
8109 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8110 "Detects an org-type or table-type table.")
8111 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8112 "Searching from within a table (any type) this finds the first line
8113 outside the table.")
8114 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8115 "Searching from within a table (any type) this finds the first line
8116 outside the table.")
8118 (defvar org-table-last-highlighted-reference nil)
8119 (defvar org-table-formula-history nil)
8121 (defvar org-table-column-names nil
8122 "Alist with column names, derived from the `!' line.")
8123 (defvar org-table-column-name-regexp nil
8124 "Regular expression matching the current column names.")
8125 (defvar org-table-local-parameters nil
8126 "Alist with parameter names, derived from the `$' line.")
8127 (defvar org-table-named-field-locations nil
8128 "Alist with locations of named fields.")
8130 (defvar org-table-current-line-types nil
8131 "Table row types, non-nil only for the duration of a comand.")
8132 (defvar org-table-current-begin-line nil
8133 "Table begin line, non-nil only for the duration of a comand.")
8134 (defvar org-table-current-begin-pos nil
8135 "Table begin position, non-nil only for the duration of a comand.")
8136 (defvar org-table-dlines nil
8137 "Vector of data line line numbers in the current table.")
8138 (defvar org-table-hlines nil
8139 "Vector of hline line numbers in the current table.")
8141 (defconst org-table-range-regexp
8142 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8143 ;; 1 2 3 4 5
8144 "Regular expression for matching ranges in formulas.")
8146 (defconst org-table-range-regexp2
8147 (concat
8148 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8149 "\\.\\."
8150 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8151 "Match a range for reference display.")
8153 (defconst org-table-translate-regexp
8154 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8155 "Match a reference that needs translation, for reference display.")
8157 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8159 (defun org-table-create-with-table.el ()
8160 "Use the table.el package to insert a new table.
8161 If there is already a table at point, convert between Org-mode tables
8162 and table.el tables."
8163 (interactive)
8164 (require 'table)
8165 (cond
8166 ((org-at-table.el-p)
8167 (if (y-or-n-p "Convert table to Org-mode table? ")
8168 (org-table-convert)))
8169 ((org-at-table-p)
8170 (if (y-or-n-p "Convert table to table.el table? ")
8171 (org-table-convert)))
8172 (t (call-interactively 'table-insert))))
8174 (defun org-table-create-or-convert-from-region (arg)
8175 "Convert region to table, or create an empty table.
8176 If there is an active region, convert it to a table, using the function
8177 `org-table-convert-region'. See the documentation of that function
8178 to learn how the prefix argument is interpreted to determine the field
8179 separator.
8180 If there is no such region, create an empty table with `org-table-create'."
8181 (interactive "P")
8182 (if (org-region-active-p)
8183 (org-table-convert-region (region-beginning) (region-end) arg)
8184 (org-table-create arg)))
8186 (defun org-table-create (&optional size)
8187 "Query for a size and insert a table skeleton.
8188 SIZE is a string Columns x Rows like for example \"3x2\"."
8189 (interactive "P")
8190 (unless size
8191 (setq size (read-string
8192 (concat "Table size Columns x Rows [e.g. "
8193 org-table-default-size "]: ")
8194 "" nil org-table-default-size)))
8196 (let* ((pos (point))
8197 (indent (make-string (current-column) ?\ ))
8198 (split (org-split-string size " *x *"))
8199 (rows (string-to-number (nth 1 split)))
8200 (columns (string-to-number (car split)))
8201 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8202 "\n")))
8203 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8204 (point-at-bol) (point)))
8205 (beginning-of-line 1)
8206 (newline))
8207 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8208 (dotimes (i rows) (insert line))
8209 (goto-char pos)
8210 (if (> rows 1)
8211 ;; Insert a hline after the first row.
8212 (progn
8213 (end-of-line 1)
8214 (insert "\n|-")
8215 (goto-char pos)))
8216 (org-table-align)))
8218 (defun org-table-convert-region (beg0 end0 &optional separator)
8219 "Convert region to a table.
8220 The region goes from BEG0 to END0, but these borders will be moved
8221 slightly, to make sure a beginning of line in the first line is included.
8223 SEPARATOR specifies the field separator in the lines. It can have the
8224 following values:
8226 '(4) Use the comma as a field separator
8227 '(16) Use a TAB as field separator
8228 integer When a number, use that many spaces as field separator
8229 nil When nil, the command tries to be smart and figure out the
8230 separator in the following way:
8231 - when each line contains a TAB, assume TAB-separated material
8232 - when each line contains a comme, assume CSV material
8233 - else, assume one or more SPACE charcters as separator."
8234 (interactive "rP")
8235 (let* ((beg (min beg0 end0))
8236 (end (max beg0 end0))
8238 (goto-char beg)
8239 (beginning-of-line 1)
8240 (setq beg (move-marker (make-marker) (point)))
8241 (goto-char end)
8242 (if (bolp) (backward-char 1) (end-of-line 1))
8243 (setq end (move-marker (make-marker) (point)))
8244 ;; Get the right field separator
8245 (unless separator
8246 (goto-char beg)
8247 (setq separator
8248 (cond
8249 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8250 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8251 (t 1))))
8252 (setq re (cond
8253 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8254 ((equal separator '(16)) "^\\|\t")
8255 ((integerp separator)
8256 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8257 (t (error "This should not happen"))))
8258 (goto-char beg)
8259 (while (re-search-forward re end t)
8260 (replace-match "| " t t))
8261 (goto-char beg)
8262 (insert " ")
8263 (org-table-align)))
8265 (defun org-table-import (file arg)
8266 "Import FILE as a table.
8267 The file is assumed to be tab-separated. Such files can be produced by most
8268 spreadsheet and database applications. If no tabs (at least one per line)
8269 are found, lines will be split on whitespace into fields."
8270 (interactive "f\nP")
8271 (or (bolp) (newline))
8272 (let ((beg (point))
8273 (pm (point-max)))
8274 (insert-file-contents file)
8275 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8277 (defun org-table-export ()
8278 "Export table as a tab-separated file.
8279 Such a file can be imported into a spreadsheet program like Excel."
8280 (interactive)
8281 (let* ((beg (org-table-begin))
8282 (end (org-table-end))
8283 (table (buffer-substring beg end))
8284 (file (read-file-name "Export table to: "))
8285 buf)
8286 (unless (or (not (file-exists-p file))
8287 (y-or-n-p (format "Overwrite file %s? " file)))
8288 (error "Abort"))
8289 (with-current-buffer (find-file-noselect file)
8290 (setq buf (current-buffer))
8291 (erase-buffer)
8292 (fundamental-mode)
8293 (insert table)
8294 (goto-char (point-min))
8295 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8296 (replace-match "" t t)
8297 (end-of-line 1))
8298 (goto-char (point-min))
8299 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8300 (replace-match "" t t)
8301 (goto-char (min (1+ (point)) (point-max))))
8302 (goto-char (point-min))
8303 (while (re-search-forward "^-[-+]*$" nil t)
8304 (replace-match "")
8305 (if (looking-at "\n")
8306 (delete-char 1)))
8307 (goto-char (point-min))
8308 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8309 (replace-match "\t" t t))
8310 (save-buffer))
8311 (kill-buffer buf)))
8313 (defvar org-table-aligned-begin-marker (make-marker)
8314 "Marker at the beginning of the table last aligned.
8315 Used to check if cursor still is in that table, to minimize realignment.")
8316 (defvar org-table-aligned-end-marker (make-marker)
8317 "Marker at the end of the table last aligned.
8318 Used to check if cursor still is in that table, to minimize realignment.")
8319 (defvar org-table-last-alignment nil
8320 "List of flags for flushright alignment, from the last re-alignment.
8321 This is being used to correctly align a single field after TAB or RET.")
8322 (defvar org-table-last-column-widths nil
8323 "List of max width of fields in each column.
8324 This is being used to correctly align a single field after TAB or RET.")
8325 (defvar org-table-overlay-coordinates nil
8326 "Overlay coordinates after each align of a table.")
8327 (make-variable-buffer-local 'org-table-overlay-coordinates)
8329 (defvar org-last-recalc-line nil)
8330 (defconst org-narrow-column-arrow "=>"
8331 "Used as display property in narrowed table columns.")
8333 (defun org-table-align ()
8334 "Align the table at point by aligning all vertical bars."
8335 (interactive)
8336 (let* (
8337 ;; Limits of table
8338 (beg (org-table-begin))
8339 (end (org-table-end))
8340 ;; Current cursor position
8341 (linepos (org-current-line))
8342 (colpos (org-table-current-column))
8343 (winstart (window-start))
8344 (winstartline (org-current-line (min winstart (1- (point-max)))))
8345 lines (new "") lengths l typenums ty fields maxfields i
8346 column
8347 (indent "") cnt frac
8348 rfmt hfmt
8349 (spaces '(1 . 1))
8350 (sp1 (car spaces))
8351 (sp2 (cdr spaces))
8352 (rfmt1 (concat
8353 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8354 (hfmt1 (concat
8355 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8356 emptystrings links dates emph narrow fmax f1 len c e)
8357 (untabify beg end)
8358 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8359 ;; Check if we have links or dates
8360 (goto-char beg)
8361 (setq links (re-search-forward org-bracket-link-regexp end t))
8362 (goto-char beg)
8363 (setq emph (and org-hide-emphasis-markers
8364 (re-search-forward org-emph-re end t)))
8365 (goto-char beg)
8366 (setq dates (and org-display-custom-times
8367 (re-search-forward org-ts-regexp-both end t)))
8368 ;; Make sure the link properties are right
8369 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8370 ;; Make sure the date properties are right
8371 (when dates (goto-char beg) (while (org-activate-dates end)))
8372 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8374 ;; Check if we are narrowing any columns
8375 (goto-char beg)
8376 (setq narrow (and org-format-transports-properties-p
8377 (re-search-forward "<[0-9]+>" end t)))
8378 ;; Get the rows
8379 (setq lines (org-split-string
8380 (buffer-substring beg end) "\n"))
8381 ;; Store the indentation of the first line
8382 (if (string-match "^ *" (car lines))
8383 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8384 ;; Mark the hlines by setting the corresponding element to nil
8385 ;; At the same time, we remove trailing space.
8386 (setq lines (mapcar (lambda (l)
8387 (if (string-match "^ *|-" l)
8389 (if (string-match "[ \t]+$" l)
8390 (substring l 0 (match-beginning 0))
8391 l)))
8392 lines))
8393 ;; Get the data fields by splitting the lines.
8394 (setq fields (mapcar
8395 (lambda (l)
8396 (org-split-string l " *| *"))
8397 (delq nil (copy-sequence lines))))
8398 ;; How many fields in the longest line?
8399 (condition-case nil
8400 (setq maxfields (apply 'max (mapcar 'length fields)))
8401 (error
8402 (kill-region beg end)
8403 (org-table-create org-table-default-size)
8404 (error "Empty table - created default table")))
8405 ;; A list of empty strings to fill any short rows on output
8406 (setq emptystrings (make-list maxfields ""))
8407 ;; Check for special formatting.
8408 (setq i -1)
8409 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8410 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8411 ;; Check if there is an explicit width specified
8412 (when narrow
8413 (setq c column fmax nil)
8414 (while c
8415 (setq e (pop c))
8416 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8417 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8418 ;; Find fields that are wider than fmax, and shorten them
8419 (when fmax
8420 (loop for xx in column do
8421 (when (and (stringp xx)
8422 (> (org-string-width xx) fmax))
8423 (org-add-props xx nil
8424 'help-echo
8425 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8426 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8427 (unless (> f1 1)
8428 (error "Cannot narrow field starting with wide link \"%s\""
8429 (match-string 0 xx)))
8430 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8431 (add-text-properties (- f1 2) f1
8432 (list 'display org-narrow-column-arrow)
8433 xx)))))
8434 ;; Get the maximum width for each column
8435 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8436 ;; Get the fraction of numbers, to decide about alignment of the column
8437 (setq cnt 0 frac 0.0)
8438 (loop for x in column do
8439 (if (equal x "")
8441 (setq frac ( / (+ (* frac cnt)
8442 (if (string-match org-table-number-regexp x) 1 0))
8443 (setq cnt (1+ cnt))))))
8444 (push (>= frac org-table-number-fraction) typenums))
8445 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8447 ;; Store the alignment of this table, for later editing of single fields
8448 (setq org-table-last-alignment typenums
8449 org-table-last-column-widths lengths)
8451 ;; With invisible characters, `format' does not get the field width right
8452 ;; So we need to make these fields wide by hand.
8453 (when (or links emph)
8454 (loop for i from 0 upto (1- maxfields) do
8455 (setq len (nth i lengths))
8456 (loop for j from 0 upto (1- (length fields)) do
8457 (setq c (nthcdr i (car (nthcdr j fields))))
8458 (if (and (stringp (car c))
8459 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8460 ; (string-match org-bracket-link-regexp (car c))
8461 (< (org-string-width (car c)) len))
8462 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8464 ;; Compute the formats needed for output of the table
8465 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8466 (while (setq l (pop lengths))
8467 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8468 (setq rfmt (concat rfmt (format rfmt1 ty l))
8469 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8470 (setq rfmt (concat rfmt "\n")
8471 hfmt (concat (substring hfmt 0 -1) "|\n"))
8473 (setq new (mapconcat
8474 (lambda (l)
8475 (if l (apply 'format rfmt
8476 (append (pop fields) emptystrings))
8477 hfmt))
8478 lines ""))
8479 ;; Replace the old one
8480 (delete-region beg end)
8481 (move-marker end nil)
8482 (move-marker org-table-aligned-begin-marker (point))
8483 (insert new)
8484 (move-marker org-table-aligned-end-marker (point))
8485 (when (and orgtbl-mode (not (org-mode-p)))
8486 (goto-char org-table-aligned-begin-marker)
8487 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8488 ;; Try to move to the old location
8489 (goto-line winstartline)
8490 (setq winstart (point-at-bol))
8491 (goto-line linepos)
8492 (set-window-start (selected-window) winstart 'noforce)
8493 (org-table-goto-column colpos)
8494 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8495 (setq org-table-may-need-update nil)
8498 (defun org-string-width (s)
8499 "Compute width of string, ignoring invisible characters.
8500 This ignores character with invisibility property `org-link', and also
8501 characters with property `org-cwidth', because these will become invisible
8502 upon the next fontification round."
8503 (let (b l)
8504 (when (or (eq t buffer-invisibility-spec)
8505 (assq 'org-link buffer-invisibility-spec))
8506 (while (setq b (text-property-any 0 (length s)
8507 'invisible 'org-link s))
8508 (setq s (concat (substring s 0 b)
8509 (substring s (or (next-single-property-change
8510 b 'invisible s) (length s)))))))
8511 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8512 (setq s (concat (substring s 0 b)
8513 (substring s (or (next-single-property-change
8514 b 'org-cwidth s) (length s))))))
8515 (setq l (string-width s) b -1)
8516 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8517 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8520 (defun org-table-begin (&optional table-type)
8521 "Find the beginning of the table and return its position.
8522 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8523 (save-excursion
8524 (if (not (re-search-backward
8525 (if table-type org-table-any-border-regexp
8526 org-table-border-regexp)
8527 nil t))
8528 (progn (goto-char (point-min)) (point))
8529 (goto-char (match-beginning 0))
8530 (beginning-of-line 2)
8531 (point))))
8533 (defun org-table-end (&optional table-type)
8534 "Find the end of the table and return its position.
8535 With argument TABLE-TYPE, go to the end of a table.el-type table."
8536 (save-excursion
8537 (if (not (re-search-forward
8538 (if table-type org-table-any-border-regexp
8539 org-table-border-regexp)
8540 nil t))
8541 (goto-char (point-max))
8542 (goto-char (match-beginning 0)))
8543 (point-marker)))
8545 (defun org-table-justify-field-maybe (&optional new)
8546 "Justify the current field, text to left, number to right.
8547 Optional argument NEW may specify text to replace the current field content."
8548 (cond
8549 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8550 ((org-at-table-hline-p))
8551 ((and (not new)
8552 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8553 (current-buffer)))
8554 (< (point) org-table-aligned-begin-marker)
8555 (>= (point) org-table-aligned-end-marker)))
8556 ;; This is not the same table, force a full re-align
8557 (setq org-table-may-need-update t))
8558 (t ;; realign the current field, based on previous full realign
8559 (let* ((pos (point)) s
8560 (col (org-table-current-column))
8561 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8562 l f n o e)
8563 (when (> col 0)
8564 (skip-chars-backward "^|\n")
8565 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8566 (progn
8567 (setq s (match-string 1)
8568 o (match-string 0)
8569 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8570 e (not (= (match-beginning 2) (match-end 2))))
8571 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8572 l (if e "|" (setq org-table-may-need-update t) ""))
8573 n (format f s))
8574 (if new
8575 (if (<= (length new) l) ;; FIXME: length -> str-width?
8576 (setq n (format f new))
8577 (setq n (concat new "|") org-table-may-need-update t)))
8578 (or (equal n o)
8579 (let (org-table-may-need-update)
8580 (replace-match n t t))))
8581 (setq org-table-may-need-update t))
8582 (goto-char pos))))))
8584 (defun org-table-next-field ()
8585 "Go to the next field in the current table, creating new lines as needed.
8586 Before doing so, re-align the table if necessary."
8587 (interactive)
8588 (org-table-maybe-eval-formula)
8589 (org-table-maybe-recalculate-line)
8590 (if (and org-table-automatic-realign
8591 org-table-may-need-update)
8592 (org-table-align))
8593 (let ((end (org-table-end)))
8594 (if (org-at-table-hline-p)
8595 (end-of-line 1))
8596 (condition-case nil
8597 (progn
8598 (re-search-forward "|" end)
8599 (if (looking-at "[ \t]*$")
8600 (re-search-forward "|" end))
8601 (if (and (looking-at "-")
8602 org-table-tab-jumps-over-hlines
8603 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8604 (goto-char (match-beginning 1)))
8605 (if (looking-at "-")
8606 (progn
8607 (beginning-of-line 0)
8608 (org-table-insert-row 'below))
8609 (if (looking-at " ") (forward-char 1))))
8610 (error
8611 (org-table-insert-row 'below)))))
8613 (defun org-table-previous-field ()
8614 "Go to the previous field in the table.
8615 Before doing so, re-align the table if necessary."
8616 (interactive)
8617 (org-table-justify-field-maybe)
8618 (org-table-maybe-recalculate-line)
8619 (if (and org-table-automatic-realign
8620 org-table-may-need-update)
8621 (org-table-align))
8622 (if (org-at-table-hline-p)
8623 (end-of-line 1))
8624 (re-search-backward "|" (org-table-begin))
8625 (re-search-backward "|" (org-table-begin))
8626 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8627 (re-search-backward "|" (org-table-begin)))
8628 (if (looking-at "| ?")
8629 (goto-char (match-end 0))))
8631 (defun org-table-next-row ()
8632 "Go to the next row (same column) in the current table.
8633 Before doing so, re-align the table if necessary."
8634 (interactive)
8635 (org-table-maybe-eval-formula)
8636 (org-table-maybe-recalculate-line)
8637 (if (or (looking-at "[ \t]*$")
8638 (save-excursion (skip-chars-backward " \t") (bolp)))
8639 (newline)
8640 (if (and org-table-automatic-realign
8641 org-table-may-need-update)
8642 (org-table-align))
8643 (let ((col (org-table-current-column)))
8644 (beginning-of-line 2)
8645 (if (or (not (org-at-table-p))
8646 (org-at-table-hline-p))
8647 (progn
8648 (beginning-of-line 0)
8649 (org-table-insert-row 'below)))
8650 (org-table-goto-column col)
8651 (skip-chars-backward "^|\n\r")
8652 (if (looking-at " ") (forward-char 1)))))
8654 (defun org-table-copy-down (n)
8655 "Copy a field down in the current column.
8656 If the field at the cursor is empty, copy into it the content of the nearest
8657 non-empty field above. With argument N, use the Nth non-empty field.
8658 If the current field is not empty, it is copied down to the next row, and
8659 the cursor is moved with it. Therefore, repeating this command causes the
8660 column to be filled row-by-row.
8661 If the variable `org-table-copy-increment' is non-nil and the field is an
8662 integer or a timestamp, it will be incremented while copying. In the case of
8663 a timestamp, if the cursor is on the year, change the year. If it is on the
8664 month or the day, change that. Point will stay on the current date field
8665 in order to easily repeat the interval."
8666 (interactive "p")
8667 (let* ((colpos (org-table-current-column))
8668 (col (current-column))
8669 (field (org-table-get-field))
8670 (non-empty (string-match "[^ \t]" field))
8671 (beg (org-table-begin))
8672 txt)
8673 (org-table-check-inside-data-field)
8674 (if non-empty
8675 (progn
8676 (setq txt (org-trim field))
8677 (org-table-next-row)
8678 (org-table-blank-field))
8679 (save-excursion
8680 (setq txt
8681 (catch 'exit
8682 (while (progn (beginning-of-line 1)
8683 (re-search-backward org-table-dataline-regexp
8684 beg t))
8685 (org-table-goto-column colpos t)
8686 (if (and (looking-at
8687 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8688 (= (setq n (1- n)) 0))
8689 (throw 'exit (match-string 1))))))))
8690 (if txt
8691 (progn
8692 (if (and org-table-copy-increment
8693 (string-match "^[0-9]+$" txt))
8694 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8695 (insert txt)
8696 (move-to-column col)
8697 (if (and org-table-copy-increment (org-at-timestamp-p t))
8698 (org-timestamp-up 1)
8699 (org-table-maybe-recalculate-line))
8700 (org-table-align)
8701 (move-to-column col))
8702 (error "No non-empty field found"))))
8704 (defun org-table-check-inside-data-field ()
8705 "Is point inside a table data field?
8706 I.e. not on a hline or before the first or after the last column?
8707 This actually throws an error, so it aborts the current command."
8708 (if (or (not (org-at-table-p))
8709 (= (org-table-current-column) 0)
8710 (org-at-table-hline-p)
8711 (looking-at "[ \t]*$"))
8712 (error "Not in table data field")))
8714 (defvar org-table-clip nil
8715 "Clipboard for table regions.")
8717 (defun org-table-blank-field ()
8718 "Blank the current table field or active region."
8719 (interactive)
8720 (org-table-check-inside-data-field)
8721 (if (and (interactive-p) (org-region-active-p))
8722 (let (org-table-clip)
8723 (org-table-cut-region (region-beginning) (region-end)))
8724 (skip-chars-backward "^|")
8725 (backward-char 1)
8726 (if (looking-at "|[^|\n]+")
8727 (let* ((pos (match-beginning 0))
8728 (match (match-string 0))
8729 (len (org-string-width match)))
8730 (replace-match (concat "|" (make-string (1- len) ?\ )))
8731 (goto-char (+ 2 pos))
8732 (substring match 1)))))
8734 (defun org-table-get-field (&optional n replace)
8735 "Return the value of the field in column N of current row.
8736 N defaults to current field.
8737 If REPLACE is a string, replace field with this value. The return value
8738 is always the old value."
8739 (and n (org-table-goto-column n))
8740 (skip-chars-backward "^|\n")
8741 (backward-char 1)
8742 (if (looking-at "|[^|\r\n]*")
8743 (let* ((pos (match-beginning 0))
8744 (val (buffer-substring (1+ pos) (match-end 0))))
8745 (if replace
8746 (replace-match (concat "|" replace) t t))
8747 (goto-char (min (point-at-eol) (+ 2 pos)))
8748 val)
8749 (forward-char 1) ""))
8751 (defun org-table-field-info (arg)
8752 "Show info about the current field, and highlight any reference at point."
8753 (interactive "P")
8754 (org-table-get-specials)
8755 (save-excursion
8756 (let* ((pos (point))
8757 (col (org-table-current-column))
8758 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8759 (name (car (rassoc (list (org-current-line) col)
8760 org-table-named-field-locations)))
8761 (eql (org-table-get-stored-formulas))
8762 (dline (org-table-current-dline))
8763 (ref (format "@%d$%d" dline col))
8764 (ref1 (org-table-convert-refs-to-an ref))
8765 (fequation (or (assoc name eql) (assoc ref eql)))
8766 (cequation (assoc (int-to-string col) eql))
8767 (eqn (or fequation cequation)))
8768 (goto-char pos)
8769 (condition-case nil
8770 (org-table-show-reference 'local)
8771 (error nil))
8772 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8773 dline col
8774 (if cname (concat " or $" cname) "")
8775 dline col ref1
8776 (if name (concat " or $" name) "")
8777 ;; FIXME: formula info not correct if special table line
8778 (if eqn
8779 (concat ", formula: "
8780 (org-table-formula-to-user
8781 (concat
8782 (if (string-match "^[$@]"(car eqn)) "" "$")
8783 (car eqn) "=" (cdr eqn))))
8784 "")))))
8786 (defun org-table-current-column ()
8787 "Find out which column we are in.
8788 When called interactively, column is also displayed in echo area."
8789 (interactive)
8790 (if (interactive-p) (org-table-check-inside-data-field))
8791 (save-excursion
8792 (let ((cnt 0) (pos (point)))
8793 (beginning-of-line 1)
8794 (while (search-forward "|" pos t)
8795 (setq cnt (1+ cnt)))
8796 (if (interactive-p) (message "This is table column %d" cnt))
8797 cnt)))
8799 (defun org-table-current-dline ()
8800 "Find out what table data line we are in.
8801 Only datalins count for this."
8802 (interactive)
8803 (if (interactive-p) (org-table-check-inside-data-field))
8804 (save-excursion
8805 (let ((cnt 0) (pos (point)))
8806 (goto-char (org-table-begin))
8807 (while (<= (point) pos)
8808 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8809 (beginning-of-line 2))
8810 (if (interactive-p) (message "This is table line %d" cnt))
8811 cnt)))
8813 (defun org-table-goto-column (n &optional on-delim force)
8814 "Move the cursor to the Nth column in the current table line.
8815 With optional argument ON-DELIM, stop with point before the left delimiter
8816 of the field.
8817 If there are less than N fields, just go to after the last delimiter.
8818 However, when FORCE is non-nil, create new columns if necessary."
8819 (interactive "p")
8820 (let ((pos (point-at-eol)))
8821 (beginning-of-line 1)
8822 (when (> n 0)
8823 (while (and (> (setq n (1- n)) -1)
8824 (or (search-forward "|" pos t)
8825 (and force
8826 (progn (end-of-line 1)
8827 (skip-chars-backward "^|")
8828 (insert " | "))))))
8829 ; (backward-char 2) t)))))
8830 (when (and force (not (looking-at ".*|")))
8831 (save-excursion (end-of-line 1) (insert " | ")))
8832 (if on-delim
8833 (backward-char 1)
8834 (if (looking-at " ") (forward-char 1))))))
8836 (defun org-at-table-p (&optional table-type)
8837 "Return t if the cursor is inside an org-type table.
8838 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8839 (if org-enable-table-editor
8840 (save-excursion
8841 (beginning-of-line 1)
8842 (looking-at (if table-type org-table-any-line-regexp
8843 org-table-line-regexp)))
8844 nil))
8846 (defun org-at-table.el-p ()
8847 "Return t if and only if we are at a table.el table."
8848 (and (org-at-table-p 'any)
8849 (save-excursion
8850 (goto-char (org-table-begin 'any))
8851 (looking-at org-table1-hline-regexp))))
8853 (defun org-table-recognize-table.el ()
8854 "If there is a table.el table nearby, recognize it and move into it."
8855 (if org-table-tab-recognizes-table.el
8856 (if (org-at-table.el-p)
8857 (progn
8858 (beginning-of-line 1)
8859 (if (looking-at org-table-dataline-regexp)
8861 (if (looking-at org-table1-hline-regexp)
8862 (progn
8863 (beginning-of-line 2)
8864 (if (looking-at org-table-any-border-regexp)
8865 (beginning-of-line -1)))))
8866 (if (re-search-forward "|" (org-table-end t) t)
8867 (progn
8868 (require 'table)
8869 (if (table--at-cell-p (point))
8871 (message "recognizing table.el table...")
8872 (table-recognize-table)
8873 (message "recognizing table.el table...done")))
8874 (error "This should not happen..."))
8876 nil)
8877 nil))
8879 (defun org-at-table-hline-p ()
8880 "Return t if the cursor is inside a hline in a table."
8881 (if org-enable-table-editor
8882 (save-excursion
8883 (beginning-of-line 1)
8884 (looking-at org-table-hline-regexp))
8885 nil))
8887 (defun org-table-insert-column ()
8888 "Insert a new column into the table."
8889 (interactive)
8890 (if (not (org-at-table-p))
8891 (error "Not at a table"))
8892 (org-table-find-dataline)
8893 (let* ((col (max 1 (org-table-current-column)))
8894 (beg (org-table-begin))
8895 (end (org-table-end))
8896 ;; Current cursor position
8897 (linepos (org-current-line))
8898 (colpos col))
8899 (goto-char beg)
8900 (while (< (point) end)
8901 (if (org-at-table-hline-p)
8903 (org-table-goto-column col t)
8904 (insert "| "))
8905 (beginning-of-line 2))
8906 (move-marker end nil)
8907 (goto-line linepos)
8908 (org-table-goto-column colpos)
8909 (org-table-align)
8910 (org-table-fix-formulas "$" nil (1- col) 1)))
8912 (defun org-table-find-dataline ()
8913 "Find a dataline in the current table, which is needed for column commands."
8914 (if (and (org-at-table-p)
8915 (not (org-at-table-hline-p)))
8917 (let ((col (current-column))
8918 (end (org-table-end)))
8919 (move-to-column col)
8920 (while (and (< (point) end)
8921 (or (not (= (current-column) col))
8922 (org-at-table-hline-p)))
8923 (beginning-of-line 2)
8924 (move-to-column col))
8925 (if (and (org-at-table-p)
8926 (not (org-at-table-hline-p)))
8928 (error
8929 "Please position cursor in a data line for column operations")))))
8931 (defun org-table-delete-column ()
8932 "Delete a column from the table."
8933 (interactive)
8934 (if (not (org-at-table-p))
8935 (error "Not at a table"))
8936 (org-table-find-dataline)
8937 (org-table-check-inside-data-field)
8938 (let* ((col (org-table-current-column))
8939 (beg (org-table-begin))
8940 (end (org-table-end))
8941 ;; Current cursor position
8942 (linepos (org-current-line))
8943 (colpos col))
8944 (goto-char beg)
8945 (while (< (point) end)
8946 (if (org-at-table-hline-p)
8948 (org-table-goto-column col t)
8949 (and (looking-at "|[^|\n]+|")
8950 (replace-match "|")))
8951 (beginning-of-line 2))
8952 (move-marker end nil)
8953 (goto-line linepos)
8954 (org-table-goto-column colpos)
8955 (org-table-align)
8956 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8957 col -1 col)))
8959 (defun org-table-move-column-right ()
8960 "Move column to the right."
8961 (interactive)
8962 (org-table-move-column nil))
8963 (defun org-table-move-column-left ()
8964 "Move column to the left."
8965 (interactive)
8966 (org-table-move-column 'left))
8968 (defun org-table-move-column (&optional left)
8969 "Move the current column to the right. With arg LEFT, move to the left."
8970 (interactive "P")
8971 (if (not (org-at-table-p))
8972 (error "Not at a table"))
8973 (org-table-find-dataline)
8974 (org-table-check-inside-data-field)
8975 (let* ((col (org-table-current-column))
8976 (col1 (if left (1- col) col))
8977 (beg (org-table-begin))
8978 (end (org-table-end))
8979 ;; Current cursor position
8980 (linepos (org-current-line))
8981 (colpos (if left (1- col) (1+ col))))
8982 (if (and left (= col 1))
8983 (error "Cannot move column further left"))
8984 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8985 (error "Cannot move column further right"))
8986 (goto-char beg)
8987 (while (< (point) end)
8988 (if (org-at-table-hline-p)
8990 (org-table-goto-column col1 t)
8991 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8992 (replace-match "|\\2|\\1|")))
8993 (beginning-of-line 2))
8994 (move-marker end nil)
8995 (goto-line linepos)
8996 (org-table-goto-column colpos)
8997 (org-table-align)
8998 (org-table-fix-formulas
8999 "$" (list (cons (number-to-string col) (number-to-string colpos))
9000 (cons (number-to-string colpos) (number-to-string col))))))
9002 (defun org-table-move-row-down ()
9003 "Move table row down."
9004 (interactive)
9005 (org-table-move-row nil))
9006 (defun org-table-move-row-up ()
9007 "Move table row up."
9008 (interactive)
9009 (org-table-move-row 'up))
9011 (defun org-table-move-row (&optional up)
9012 "Move the current table line down. With arg UP, move it up."
9013 (interactive "P")
9014 (let* ((col (current-column))
9015 (pos (point))
9016 (hline1p (save-excursion (beginning-of-line 1)
9017 (looking-at org-table-hline-regexp)))
9018 (dline1 (org-table-current-dline))
9019 (dline2 (+ dline1 (if up -1 1)))
9020 (tonew (if up 0 2))
9021 txt hline2p)
9022 (beginning-of-line tonew)
9023 (unless (org-at-table-p)
9024 (goto-char pos)
9025 (error "Cannot move row further"))
9026 (setq hline2p (looking-at org-table-hline-regexp))
9027 (goto-char pos)
9028 (beginning-of-line 1)
9029 (setq pos (point))
9030 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9031 (delete-region (point) (1+ (point-at-eol)))
9032 (beginning-of-line tonew)
9033 (insert txt)
9034 (beginning-of-line 0)
9035 (move-to-column col)
9036 (unless (or hline1p hline2p)
9037 (org-table-fix-formulas
9038 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9039 (cons (number-to-string dline2) (number-to-string dline1)))))))
9041 (defun org-table-insert-row (&optional arg)
9042 "Insert a new row above the current line into the table.
9043 With prefix ARG, insert below the current line."
9044 (interactive "P")
9045 (if (not (org-at-table-p))
9046 (error "Not at a table"))
9047 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9048 (new (org-table-clean-line line)))
9049 ;; Fix the first field if necessary
9050 (if (string-match "^[ \t]*| *[#$] *|" line)
9051 (setq new (replace-match (match-string 0 line) t t new)))
9052 (beginning-of-line (if arg 2 1))
9053 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9054 (beginning-of-line 0)
9055 (re-search-forward "| ?" (point-at-eol) t)
9056 (and (or org-table-may-need-update org-table-overlay-coordinates)
9057 (org-table-align))
9058 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9060 (defun org-table-insert-hline (&optional above)
9061 "Insert a horizontal-line below the current line into the table.
9062 With prefix ABOVE, insert above the current line."
9063 (interactive "P")
9064 (if (not (org-at-table-p))
9065 (error "Not at a table"))
9066 (let ((line (org-table-clean-line
9067 (buffer-substring (point-at-bol) (point-at-eol))))
9068 (col (current-column)))
9069 (while (string-match "|\\( +\\)|" line)
9070 (setq line (replace-match
9071 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9072 ?-) "|") t t line)))
9073 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9074 (beginning-of-line (if above 1 2))
9075 (insert line "\n")
9076 (beginning-of-line (if above 1 -1))
9077 (move-to-column col)
9078 (and org-table-overlay-coordinates (org-table-align))))
9080 (defun org-table-hline-and-move (&optional same-column)
9081 "Insert a hline and move to the row below that line."
9082 (interactive "P")
9083 (let ((col (org-table-current-column)))
9084 (org-table-maybe-eval-formula)
9085 (org-table-maybe-recalculate-line)
9086 (org-table-insert-hline)
9087 (end-of-line 2)
9088 (if (looking-at "\n[ \t]*|-")
9089 (progn (insert "\n|") (org-table-align))
9090 (org-table-next-field))
9091 (if same-column (org-table-goto-column col))))
9093 (defun org-table-clean-line (s)
9094 "Convert a table line S into a string with only \"|\" and space.
9095 In particular, this does handle wide and invisible characters."
9096 (if (string-match "^[ \t]*|-" s)
9097 ;; It's a hline, just map the characters
9098 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9099 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9100 (setq s (replace-match
9101 (concat "|" (make-string (org-string-width (match-string 1 s))
9102 ?\ ) "|")
9103 t t s)))
9106 (defun org-table-kill-row ()
9107 "Delete the current row or horizontal line from the table."
9108 (interactive)
9109 (if (not (org-at-table-p))
9110 (error "Not at a table"))
9111 (let ((col (current-column))
9112 (dline (org-table-current-dline)))
9113 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9114 (if (not (org-at-table-p)) (beginning-of-line 0))
9115 (move-to-column col)
9116 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9117 dline -1 dline)))
9119 (defun org-table-sort-lines (with-case &optional sorting-type)
9120 "Sort table lines according to the column at point.
9122 The position of point indicates the column to be used for
9123 sorting, and the range of lines is the range between the nearest
9124 horizontal separator lines, or the entire table of no such lines
9125 exist. If point is before the first column, you will be prompted
9126 for the sorting column. If there is an active region, the mark
9127 specifies the first line and the sorting column, while point
9128 should be in the last line to be included into the sorting.
9130 The command then prompts for the sorting type which can be
9131 alphabetically, numerically, or by time (as given in a time stamp
9132 in the field). Sorting in reverse order is also possible.
9134 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9136 If SORTING-TYPE is specified when this function is called from a Lisp
9137 program, no prompting will take place. SORTING-TYPE must be a character,
9138 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9139 should be done in reverse order."
9140 (interactive "P")
9141 (let* ((thisline (org-current-line))
9142 (thiscol (org-table-current-column))
9143 beg end bcol ecol tend tbeg column lns pos)
9144 (when (equal thiscol 0)
9145 (if (interactive-p)
9146 (setq thiscol
9147 (string-to-number
9148 (read-string "Use column N for sorting: ")))
9149 (setq thiscol 1))
9150 (org-table-goto-column thiscol))
9151 (org-table-check-inside-data-field)
9152 (if (org-region-active-p)
9153 (progn
9154 (setq beg (region-beginning) end (region-end))
9155 (goto-char beg)
9156 (setq column (org-table-current-column)
9157 beg (point-at-bol))
9158 (goto-char end)
9159 (setq end (point-at-bol 2)))
9160 (setq column (org-table-current-column)
9161 pos (point)
9162 tbeg (org-table-begin)
9163 tend (org-table-end))
9164 (if (re-search-backward org-table-hline-regexp tbeg t)
9165 (setq beg (point-at-bol 2))
9166 (goto-char tbeg)
9167 (setq beg (point-at-bol 1)))
9168 (goto-char pos)
9169 (if (re-search-forward org-table-hline-regexp tend t)
9170 (setq end (point-at-bol 1))
9171 (goto-char tend)
9172 (setq end (point-at-bol))))
9173 (setq beg (move-marker (make-marker) beg)
9174 end (move-marker (make-marker) end))
9175 (untabify beg end)
9176 (goto-char beg)
9177 (org-table-goto-column column)
9178 (skip-chars-backward "^|")
9179 (setq bcol (current-column))
9180 (org-table-goto-column (1+ column))
9181 (skip-chars-backward "^|")
9182 (setq ecol (1- (current-column)))
9183 (org-table-goto-column column)
9184 (setq lns (mapcar (lambda(x) (cons
9185 (org-sort-remove-invisible
9186 (nth (1- column)
9187 (org-split-string x "[ \t]*|[ \t]*")))
9189 (org-split-string (buffer-substring beg end) "\n")))
9190 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9191 (delete-region beg end)
9192 (move-marker beg nil)
9193 (move-marker end nil)
9194 (insert (mapconcat 'cdr lns "\n") "\n")
9195 (goto-line thisline)
9196 (org-table-goto-column thiscol)
9197 (message "%d lines sorted, based on column %d" (length lns) column)))
9199 ;; FIXME: maybe we will not need this? Table sorting is broken....
9200 (defun org-sort-remove-invisible (s)
9201 (remove-text-properties 0 (length s) org-rm-props s)
9202 (while (string-match org-bracket-link-regexp s)
9203 (setq s (replace-match (if (match-end 2)
9204 (match-string 3 s)
9205 (match-string 1 s)) t t s)))
9208 (defun org-table-cut-region (beg end)
9209 "Copy region in table to the clipboard and blank all relevant fields."
9210 (interactive "r")
9211 (org-table-copy-region beg end 'cut))
9213 (defun org-table-copy-region (beg end &optional cut)
9214 "Copy rectangular region in table to clipboard.
9215 A special clipboard is used which can only be accessed
9216 with `org-table-paste-rectangle'."
9217 (interactive "rP")
9218 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9219 region cols
9220 (rpl (if cut " " nil)))
9221 (goto-char beg)
9222 (org-table-check-inside-data-field)
9223 (setq l01 (org-current-line)
9224 c01 (org-table-current-column))
9225 (goto-char end)
9226 (org-table-check-inside-data-field)
9227 (setq l02 (org-current-line)
9228 c02 (org-table-current-column))
9229 (setq l1 (min l01 l02) l2 (max l01 l02)
9230 c1 (min c01 c02) c2 (max c01 c02))
9231 (catch 'exit
9232 (while t
9233 (catch 'nextline
9234 (if (> l1 l2) (throw 'exit t))
9235 (goto-line l1)
9236 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9237 (setq cols nil ic1 c1 ic2 c2)
9238 (while (< ic1 (1+ ic2))
9239 (push (org-table-get-field ic1 rpl) cols)
9240 (setq ic1 (1+ ic1)))
9241 (push (nreverse cols) region)
9242 (setq l1 (1+ l1)))))
9243 (setq org-table-clip (nreverse region))
9244 (if cut (org-table-align))
9245 org-table-clip))
9247 (defun org-table-paste-rectangle ()
9248 "Paste a rectangular region into a table.
9249 The upper right corner ends up in the current field. All involved fields
9250 will be overwritten. If the rectangle does not fit into the present table,
9251 the table is enlarged as needed. The process ignores horizontal separator
9252 lines."
9253 (interactive)
9254 (unless (and org-table-clip (listp org-table-clip))
9255 (error "First cut/copy a region to paste!"))
9256 (org-table-check-inside-data-field)
9257 (let* ((clip org-table-clip)
9258 (line (org-current-line))
9259 (col (org-table-current-column))
9260 (org-enable-table-editor t)
9261 (org-table-automatic-realign nil)
9262 c cols field)
9263 (while (setq cols (pop clip))
9264 (while (org-at-table-hline-p) (beginning-of-line 2))
9265 (if (not (org-at-table-p))
9266 (progn (end-of-line 0) (org-table-next-field)))
9267 (setq c col)
9268 (while (setq field (pop cols))
9269 (org-table-goto-column c nil 'force)
9270 (org-table-get-field nil field)
9271 (setq c (1+ c)))
9272 (beginning-of-line 2))
9273 (goto-line line)
9274 (org-table-goto-column col)
9275 (org-table-align)))
9277 (defun org-table-convert ()
9278 "Convert from `org-mode' table to table.el and back.
9279 Obviously, this only works within limits. When an Org-mode table is
9280 converted to table.el, all horizontal separator lines get lost, because
9281 table.el uses these as cell boundaries and has no notion of horizontal lines.
9282 A table.el table can be converted to an Org-mode table only if it does not
9283 do row or column spanning. Multiline cells will become multiple cells.
9284 Beware, Org-mode does not test if the table can be successfully converted - it
9285 blindly applies a recipe that works for simple tables."
9286 (interactive)
9287 (require 'table)
9288 (if (org-at-table.el-p)
9289 ;; convert to Org-mode table
9290 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9291 (end (move-marker (make-marker) (org-table-end t))))
9292 (table-unrecognize-region beg end)
9293 (goto-char beg)
9294 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9295 (replace-match ""))
9296 (goto-char beg))
9297 (if (org-at-table-p)
9298 ;; convert to table.el table
9299 (let ((beg (move-marker (make-marker) (org-table-begin)))
9300 (end (move-marker (make-marker) (org-table-end))))
9301 ;; first, get rid of all horizontal lines
9302 (goto-char beg)
9303 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9304 (replace-match ""))
9305 ;; insert a hline before first
9306 (goto-char beg)
9307 (org-table-insert-hline 'above)
9308 (beginning-of-line -1)
9309 ;; insert a hline after each line
9310 (while (progn (beginning-of-line 3) (< (point) end))
9311 (org-table-insert-hline))
9312 (goto-char beg)
9313 (setq end (move-marker end (org-table-end)))
9314 ;; replace "+" at beginning and ending of hlines
9315 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9316 (replace-match "\\1+-"))
9317 (goto-char beg)
9318 (while (re-search-forward "-|[ \t]*$" end t)
9319 (replace-match "-+"))
9320 (goto-char beg)))))
9322 (defun org-table-wrap-region (arg)
9323 "Wrap several fields in a column like a paragraph.
9324 This is useful if you'd like to spread the contents of a field over several
9325 lines, in order to keep the table compact.
9327 If there is an active region, and both point and mark are in the same column,
9328 the text in the column is wrapped to minimum width for the given number of
9329 lines. Generally, this makes the table more compact. A prefix ARG may be
9330 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9331 formats the selected text to two lines. If the region was longer than two
9332 lines, the remaining lines remain empty. A negative prefix argument reduces
9333 the current number of lines by that amount. The wrapped text is pasted back
9334 into the table. If you formatted it to more lines than it was before, fields
9335 further down in the table get overwritten - so you might need to make space in
9336 the table first.
9338 If there is no region, the current field is split at the cursor position and
9339 the text fragment to the right of the cursor is prepended to the field one
9340 line down.
9342 If there is no region, but you specify a prefix ARG, the current field gets
9343 blank, and the content is appended to the field above."
9344 (interactive "P")
9345 (org-table-check-inside-data-field)
9346 (if (org-region-active-p)
9347 ;; There is a region: fill as a paragraph
9348 (let* ((beg (region-beginning))
9349 (cline (save-excursion (goto-char beg) (org-current-line)))
9350 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9351 nlines)
9352 (org-table-cut-region (region-beginning) (region-end))
9353 (if (> (length (car org-table-clip)) 1)
9354 (error "Region must be limited to single column"))
9355 (setq nlines (if arg
9356 (if (< arg 1)
9357 (+ (length org-table-clip) arg)
9358 arg)
9359 (length org-table-clip)))
9360 (setq org-table-clip
9361 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9362 nil nlines)))
9363 (goto-line cline)
9364 (org-table-goto-column ccol)
9365 (org-table-paste-rectangle))
9366 ;; No region, split the current field at point
9367 (if arg
9368 ;; combine with field above
9369 (let ((s (org-table-blank-field))
9370 (col (org-table-current-column)))
9371 (beginning-of-line 0)
9372 (while (org-at-table-hline-p) (beginning-of-line 0))
9373 (org-table-goto-column col)
9374 (skip-chars-forward "^|")
9375 (skip-chars-backward " ")
9376 (insert " " (org-trim s))
9377 (org-table-align))
9378 ;; split field
9379 (when (looking-at "\\([^|]+\\)+|")
9380 (let ((s (match-string 1)))
9381 (replace-match " |")
9382 (goto-char (match-beginning 0))
9383 (org-table-next-row)
9384 (insert (org-trim s) " ")
9385 (org-table-align))))))
9387 (defvar org-field-marker nil)
9389 (defun org-table-edit-field (arg)
9390 "Edit table field in a different window.
9391 This is mainly useful for fields that contain hidden parts.
9392 When called with a \\[universal-argument] prefix, just make the full field visible so that
9393 it can be edited in place."
9394 (interactive "P")
9395 (if arg
9396 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9397 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9398 (remove-text-properties b e '(org-cwidth t invisible t
9399 display t intangible t))
9400 (if (and (boundp 'font-lock-mode) font-lock-mode)
9401 (font-lock-fontify-block)))
9402 (let ((pos (move-marker (make-marker) (point)))
9403 (field (org-table-get-field))
9404 (cw (current-window-configuration))
9406 (org-switch-to-buffer-other-window "*Org tmp*")
9407 (erase-buffer)
9408 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9409 (let ((org-inhibit-startup t)) (org-mode))
9410 (goto-char (setq p (point-max)))
9411 (insert (org-trim field))
9412 (remove-text-properties p (point-max)
9413 '(invisible t org-cwidth t display t
9414 intangible t))
9415 (goto-char p)
9416 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9417 (org-set-local 'org-window-configuration cw)
9418 (org-set-local 'org-field-marker pos)
9419 (message "Edit and finish with C-c C-c"))))
9421 (defun org-table-finish-edit-field ()
9422 "Finish editing a table data field.
9423 Remove all newline characters, insert the result into the table, realign
9424 the table and kill the editing buffer."
9425 (let ((pos org-field-marker)
9426 (cw org-window-configuration)
9427 (cb (current-buffer))
9428 text)
9429 (goto-char (point-min))
9430 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9431 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9432 (replace-match " "))
9433 (setq text (org-trim (buffer-string)))
9434 (set-window-configuration cw)
9435 (kill-buffer cb)
9436 (select-window (get-buffer-window (marker-buffer pos)))
9437 (goto-char pos)
9438 (move-marker pos nil)
9439 (org-table-check-inside-data-field)
9440 (org-table-get-field nil text)
9441 (org-table-align)
9442 (message "New field value inserted")))
9444 (defun org-trim (s)
9445 "Remove whitespace at beginning and end of string."
9446 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9447 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9450 (defun org-wrap (string &optional width lines)
9451 "Wrap string to either a number of lines, or a width in characters.
9452 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9453 that costs. If there is a word longer than WIDTH, the text is actually
9454 wrapped to the length of that word.
9455 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9456 many lines, whatever width that takes.
9457 The return value is a list of lines, without newlines at the end."
9458 (let* ((words (org-split-string string "[ \t\n]+"))
9459 (maxword (apply 'max (mapcar 'org-string-width words)))
9460 w ll)
9461 (cond (width
9462 (org-do-wrap words (max maxword width)))
9463 (lines
9464 (setq w maxword)
9465 (setq ll (org-do-wrap words maxword))
9466 (if (<= (length ll) lines)
9468 (setq ll words)
9469 (while (> (length ll) lines)
9470 (setq w (1+ w))
9471 (setq ll (org-do-wrap words w)))
9472 ll))
9473 (t (error "Cannot wrap this")))))
9476 (defun org-do-wrap (words width)
9477 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9478 (let (lines line)
9479 (while words
9480 (setq line (pop words))
9481 (while (and words (< (+ (length line) (length (car words))) width))
9482 (setq line (concat line " " (pop words))))
9483 (setq lines (push line lines)))
9484 (nreverse lines)))
9486 (defun org-split-string (string &optional separators)
9487 "Splits STRING into substrings at SEPARATORS.
9488 No empty strings are returned if there are matches at the beginning
9489 and end of string."
9490 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9491 (start 0)
9492 notfirst
9493 (list nil))
9494 (while (and (string-match rexp string
9495 (if (and notfirst
9496 (= start (match-beginning 0))
9497 (< start (length string)))
9498 (1+ start) start))
9499 (< (match-beginning 0) (length string)))
9500 (setq notfirst t)
9501 (or (eq (match-beginning 0) 0)
9502 (and (eq (match-beginning 0) (match-end 0))
9503 (eq (match-beginning 0) start))
9504 (setq list
9505 (cons (substring string start (match-beginning 0))
9506 list)))
9507 (setq start (match-end 0)))
9508 (or (eq start (length string))
9509 (setq list
9510 (cons (substring string start)
9511 list)))
9512 (nreverse list)))
9514 (defun org-table-map-tables (function)
9515 "Apply FUNCTION to the start of all tables in the buffer."
9516 (save-excursion
9517 (save-restriction
9518 (widen)
9519 (goto-char (point-min))
9520 (while (re-search-forward org-table-any-line-regexp nil t)
9521 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9522 (beginning-of-line 1)
9523 (if (looking-at org-table-line-regexp)
9524 (save-excursion (funcall function)))
9525 (re-search-forward org-table-any-border-regexp nil 1))))
9526 (message "Mapping tables: done"))
9528 (defvar org-timecnt) ; dynamically scoped parameter
9530 (defun org-table-sum (&optional beg end nlast)
9531 "Sum numbers in region of current table column.
9532 The result will be displayed in the echo area, and will be available
9533 as kill to be inserted with \\[yank].
9535 If there is an active region, it is interpreted as a rectangle and all
9536 numbers in that rectangle will be summed. If there is no active
9537 region and point is located in a table column, sum all numbers in that
9538 column.
9540 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9541 numbers are assumed to be times as well (in decimal hours) and the
9542 numbers are added as such.
9544 If NLAST is a number, only the NLAST fields will actually be summed."
9545 (interactive)
9546 (save-excursion
9547 (let (col (org-timecnt 0) diff h m s org-table-clip)
9548 (cond
9549 ((and beg end)) ; beg and end given explicitly
9550 ((org-region-active-p)
9551 (setq beg (region-beginning) end (region-end)))
9553 (setq col (org-table-current-column))
9554 (goto-char (org-table-begin))
9555 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9556 (error "No table data"))
9557 (org-table-goto-column col)
9558 (setq beg (point))
9559 (goto-char (org-table-end))
9560 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9561 (error "No table data"))
9562 (org-table-goto-column col)
9563 (setq end (point))))
9564 (let* ((items (apply 'append (org-table-copy-region beg end)))
9565 (items1 (cond ((not nlast) items)
9566 ((>= nlast (length items)) items)
9567 (t (setq items (reverse items))
9568 (setcdr (nthcdr (1- nlast) items) nil)
9569 (nreverse items))))
9570 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9571 items1)))
9572 (res (apply '+ numbers))
9573 (sres (if (= org-timecnt 0)
9574 (format "%g" res)
9575 (setq diff (* 3600 res)
9576 h (floor (/ diff 3600)) diff (mod diff 3600)
9577 m (floor (/ diff 60)) diff (mod diff 60)
9578 s diff)
9579 (format "%d:%02d:%02d" h m s))))
9580 (kill-new sres)
9581 (if (interactive-p)
9582 (message "%s"
9583 (substitute-command-keys
9584 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9585 (length numbers) sres))))
9586 sres))))
9588 (defun org-table-get-number-for-summing (s)
9589 (let (n)
9590 (if (string-match "^ *|? *" s)
9591 (setq s (replace-match "" nil nil s)))
9592 (if (string-match " *|? *$" s)
9593 (setq s (replace-match "" nil nil s)))
9594 (setq n (string-to-number s))
9595 (cond
9596 ((and (string-match "0" s)
9597 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9598 ((string-match "\\`[ \t]+\\'" s) nil)
9599 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9600 (let ((h (string-to-number (or (match-string 1 s) "0")))
9601 (m (string-to-number (or (match-string 2 s) "0")))
9602 (s (string-to-number (or (match-string 4 s) "0"))))
9603 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9604 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9605 ((equal n 0) nil)
9606 (t n))))
9608 (defun org-table-current-field-formula (&optional key noerror)
9609 "Return the formula active for the current field.
9610 Assumes that specials are in place.
9611 If KEY is given, return the key to this formula.
9612 Otherwise return the formula preceeded with \"=\" or \":=\"."
9613 (let* ((name (car (rassoc (list (org-current-line)
9614 (org-table-current-column))
9615 org-table-named-field-locations)))
9616 (col (org-table-current-column))
9617 (scol (int-to-string col))
9618 (ref (format "@%d$%d" (org-table-current-dline) col))
9619 (stored-list (org-table-get-stored-formulas noerror))
9620 (ass (or (assoc name stored-list)
9621 (assoc ref stored-list)
9622 (assoc scol stored-list))))
9623 (if key
9624 (car ass)
9625 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9626 (cdr ass))))))
9628 (defun org-table-get-formula (&optional equation named)
9629 "Read a formula from the minibuffer, offer stored formula as default.
9630 When NAMED is non-nil, look for a named equation."
9631 (let* ((stored-list (org-table-get-stored-formulas))
9632 (name (car (rassoc (list (org-current-line)
9633 (org-table-current-column))
9634 org-table-named-field-locations)))
9635 (ref (format "@%d$%d" (org-table-current-dline)
9636 (org-table-current-column)))
9637 (refass (assoc ref stored-list))
9638 (scol (if named
9639 (if name name ref)
9640 (int-to-string (org-table-current-column))))
9641 (dummy (and (or name refass) (not named)
9642 (not (y-or-n-p "Replace field formula with column formula? " ))
9643 (error "Abort")))
9644 (name (or name ref))
9645 (org-table-may-need-update nil)
9646 (stored (cdr (assoc scol stored-list)))
9647 (eq (cond
9648 ((and stored equation (string-match "^ *=? *$" equation))
9649 stored)
9650 ((stringp equation)
9651 equation)
9652 (t (org-table-formula-from-user
9653 (read-string
9654 (org-table-formula-to-user
9655 (format "%s formula %s%s="
9656 (if named "Field" "Column")
9657 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9658 scol))
9659 (if stored (org-table-formula-to-user stored) "")
9660 'org-table-formula-history
9661 )))))
9662 mustsave)
9663 (when (not (string-match "\\S-" eq))
9664 ;; remove formula
9665 (setq stored-list (delq (assoc scol stored-list) stored-list))
9666 (org-table-store-formulas stored-list)
9667 (error "Formula removed"))
9668 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9669 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9670 (if (and name (not named))
9671 ;; We set the column equation, delete the named one.
9672 (setq stored-list (delq (assoc name stored-list) stored-list)
9673 mustsave t))
9674 (if stored
9675 (setcdr (assoc scol stored-list) eq)
9676 (setq stored-list (cons (cons scol eq) stored-list)))
9677 (if (or mustsave (not (equal stored eq)))
9678 (org-table-store-formulas stored-list))
9679 eq))
9681 (defun org-table-store-formulas (alist)
9682 "Store the list of formulas below the current table."
9683 (setq alist (sort alist 'org-table-formula-less-p))
9684 (save-excursion
9685 (goto-char (org-table-end))
9686 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9687 (progn
9688 ;; don't overwrite TBLFM, we might use text properties to store stuff
9689 (goto-char (match-beginning 2))
9690 (delete-region (match-beginning 2) (match-end 0)))
9691 (insert "#+TBLFM:"))
9692 (insert " "
9693 (mapconcat (lambda (x)
9694 (concat
9695 (if (equal (string-to-char (car x)) ?@) "" "$")
9696 (car x) "=" (cdr x)))
9697 alist "::")
9698 "\n")))
9700 (defsubst org-table-formula-make-cmp-string (a)
9701 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9702 (concat
9703 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9704 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9705 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9707 (defun org-table-formula-less-p (a b)
9708 "Compare two formulas for sorting."
9709 (let ((as (org-table-formula-make-cmp-string (car a)))
9710 (bs (org-table-formula-make-cmp-string (car b))))
9711 (and as bs (string< as bs))))
9713 (defun org-table-get-stored-formulas (&optional noerror)
9714 "Return an alist with the stored formulas directly after current table."
9715 (interactive)
9716 (let (scol eq eq-alist strings string seen)
9717 (save-excursion
9718 (goto-char (org-table-end))
9719 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9720 (setq strings (org-split-string (match-string 2) " *:: *"))
9721 (while (setq string (pop strings))
9722 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9723 (setq scol (if (match-end 2)
9724 (match-string 2 string)
9725 (match-string 1 string))
9726 eq (match-string 3 string)
9727 eq-alist (cons (cons scol eq) eq-alist))
9728 (if (member scol seen)
9729 (if noerror
9730 (progn
9731 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9732 (ding)
9733 (sit-for 2))
9734 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9735 (push scol seen))))))
9736 (nreverse eq-alist)))
9738 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9739 "Modify the equations after the table structure has been edited.
9740 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9741 For all numbers larger than LIMIT, shift them by DELTA."
9742 (save-excursion
9743 (goto-char (org-table-end))
9744 (when (looking-at "#\\+TBLFM:")
9745 (let ((re (concat key "\\([0-9]+\\)"))
9746 (re2
9747 (when remove
9748 (if (equal key "$")
9749 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9750 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9751 s n a)
9752 (when remove
9753 (while (re-search-forward re2 (point-at-eol) t)
9754 (replace-match "")))
9755 (while (re-search-forward re (point-at-eol) t)
9756 (setq s (match-string 1) n (string-to-number s))
9757 (cond
9758 ((setq a (assoc s replace))
9759 (replace-match (concat key (cdr a)) t t))
9760 ((and limit (> n limit))
9761 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9763 (defun org-table-get-specials ()
9764 "Get the column names and local parameters for this table."
9765 (save-excursion
9766 (let ((beg (org-table-begin)) (end (org-table-end))
9767 names name fields fields1 field cnt
9768 c v l line col types dlines hlines)
9769 (setq org-table-column-names nil
9770 org-table-local-parameters nil
9771 org-table-named-field-locations nil
9772 org-table-current-begin-line nil
9773 org-table-current-begin-pos nil
9774 org-table-current-line-types nil)
9775 (goto-char beg)
9776 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9777 (setq names (org-split-string (match-string 1) " *| *")
9778 cnt 1)
9779 (while (setq name (pop names))
9780 (setq cnt (1+ cnt))
9781 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9782 (push (cons name (int-to-string cnt)) org-table-column-names))))
9783 (setq org-table-column-names (nreverse org-table-column-names))
9784 (setq org-table-column-name-regexp
9785 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9786 (goto-char beg)
9787 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9788 (setq fields (org-split-string (match-string 1) " *| *"))
9789 (while (setq field (pop fields))
9790 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9791 (push (cons (match-string 1 field) (match-string 2 field))
9792 org-table-local-parameters))))
9793 (goto-char beg)
9794 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9795 (setq c (match-string 1)
9796 fields (org-split-string (match-string 2) " *| *"))
9797 (save-excursion
9798 (beginning-of-line (if (equal c "_") 2 0))
9799 (setq line (org-current-line) col 1)
9800 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9801 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9802 (while (and fields1 (setq field (pop fields)))
9803 (setq v (pop fields1) col (1+ col))
9804 (when (and (stringp field) (stringp v)
9805 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9806 (push (cons field v) org-table-local-parameters)
9807 (push (list field line col) org-table-named-field-locations))))
9808 ;; Analyse the line types
9809 (goto-char beg)
9810 (setq org-table-current-begin-line (org-current-line)
9811 org-table-current-begin-pos (point)
9812 l org-table-current-begin-line)
9813 (while (looking-at "[ \t]*|\\(-\\)?")
9814 (push (if (match-end 1) 'hline 'dline) types)
9815 (if (match-end 1) (push l hlines) (push l dlines))
9816 (beginning-of-line 2)
9817 (setq l (1+ l)))
9818 (setq org-table-current-line-types (apply 'vector (nreverse types))
9819 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9820 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9822 (defun org-table-maybe-eval-formula ()
9823 "Check if the current field starts with \"=\" or \":=\".
9824 If yes, store the formula and apply it."
9825 ;; We already know we are in a table. Get field will only return a formula
9826 ;; when appropriate. It might return a separator line, but no problem.
9827 (when org-table-formula-evaluate-inline
9828 (let* ((field (org-trim (or (org-table-get-field) "")))
9829 named eq)
9830 (when (string-match "^:?=\\(.*\\)" field)
9831 (setq named (equal (string-to-char field) ?:)
9832 eq (match-string 1 field))
9833 (if (or (fboundp 'calc-eval)
9834 (equal (substring eq 0 (min 2 (length eq))) "'("))
9835 (org-table-eval-formula (if named '(4) nil)
9836 (org-table-formula-from-user eq))
9837 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9839 (defvar org-recalc-commands nil
9840 "List of commands triggering the recalculation of a line.
9841 Will be filled automatically during use.")
9843 (defvar org-recalc-marks
9844 '((" " . "Unmarked: no special line, no automatic recalculation")
9845 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9846 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9847 ("!" . "Column name definition line. Reference in formula as $name.")
9848 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9849 ("_" . "Names for values in row below this one.")
9850 ("^" . "Names for values in row above this one.")))
9852 (defun org-table-rotate-recalc-marks (&optional newchar)
9853 "Rotate the recalculation mark in the first column.
9854 If in any row, the first field is not consistent with a mark,
9855 insert a new column for the markers.
9856 When there is an active region, change all the lines in the region,
9857 after prompting for the marking character.
9858 After each change, a message will be displayed indicating the meaning
9859 of the new mark."
9860 (interactive)
9861 (unless (org-at-table-p) (error "Not at a table"))
9862 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9863 (beg (org-table-begin))
9864 (end (org-table-end))
9865 (l (org-current-line))
9866 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9867 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9868 (have-col
9869 (save-excursion
9870 (goto-char beg)
9871 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9872 (col (org-table-current-column))
9873 (forcenew (car (assoc newchar org-recalc-marks)))
9874 epos new)
9875 (when l1
9876 (message "Change region to what mark? Type # * ! $ or SPC: ")
9877 (setq newchar (char-to-string (read-char-exclusive))
9878 forcenew (car (assoc newchar org-recalc-marks))))
9879 (if (and newchar (not forcenew))
9880 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9881 newchar))
9882 (if l1 (goto-line l1))
9883 (save-excursion
9884 (beginning-of-line 1)
9885 (unless (looking-at org-table-dataline-regexp)
9886 (error "Not at a table data line")))
9887 (unless have-col
9888 (org-table-goto-column 1)
9889 (org-table-insert-column)
9890 (org-table-goto-column (1+ col)))
9891 (setq epos (point-at-eol))
9892 (save-excursion
9893 (beginning-of-line 1)
9894 (org-table-get-field
9895 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9896 (concat " "
9897 (setq new (or forcenew
9898 (cadr (member (match-string 1) marks))))
9899 " ")
9900 " # ")))
9901 (if (and l1 l2)
9902 (progn
9903 (goto-line l1)
9904 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9905 (and (looking-at org-table-dataline-regexp)
9906 (org-table-get-field 1 (concat " " new " "))))
9907 (goto-line l1)))
9908 (if (not (= epos (point-at-eol))) (org-table-align))
9909 (goto-line l)
9910 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
9912 (defun org-table-maybe-recalculate-line ()
9913 "Recompute the current line if marked for it, and if we haven't just done it."
9914 (interactive)
9915 (and org-table-allow-automatic-line-recalculation
9916 (not (and (memq last-command org-recalc-commands)
9917 (equal org-last-recalc-line (org-current-line))))
9918 (save-excursion (beginning-of-line 1)
9919 (looking-at org-table-auto-recalculate-regexp))
9920 (org-table-recalculate) t))
9922 (defvar org-table-formula-debug nil
9923 "Non-nil means, debug table formulas.
9924 When nil, simply write \"#ERROR\" in corrupted fields.")
9925 (make-variable-buffer-local 'org-table-formula-debug)
9927 (defvar modes)
9928 (defsubst org-set-calc-mode (var &optional value)
9929 (if (stringp var)
9930 (setq var (assoc var '(("D" calc-angle-mode deg)
9931 ("R" calc-angle-mode rad)
9932 ("F" calc-prefer-frac t)
9933 ("S" calc-symbolic-mode t)))
9934 value (nth 2 var) var (nth 1 var)))
9935 (if (memq var modes)
9936 (setcar (cdr (memq var modes)) value)
9937 (cons var (cons value modes)))
9938 modes)
9940 (defun org-table-eval-formula (&optional arg equation
9941 suppress-align suppress-const
9942 suppress-store suppress-analysis)
9943 "Replace the table field value at the cursor by the result of a calculation.
9945 This function makes use of Dave Gillespie's Calc package, in my view the
9946 most exciting program ever written for GNU Emacs. So you need to have Calc
9947 installed in order to use this function.
9949 In a table, this command replaces the value in the current field with the
9950 result of a formula. It also installs the formula as the \"current\" column
9951 formula, by storing it in a special line below the table. When called
9952 with a `C-u' prefix, the current field must ba a named field, and the
9953 formula is installed as valid in only this specific field.
9955 When called with two `C-u' prefixes, insert the active equation
9956 for the field back into the current field, so that it can be
9957 edited there. This is useful in order to use \\[org-table-show-reference]
9958 to check the referenced fields.
9960 When called, the command first prompts for a formula, which is read in
9961 the minibuffer. Previously entered formulas are available through the
9962 history list, and the last used formula is offered as a default.
9963 These stored formulas are adapted correctly when moving, inserting, or
9964 deleting columns with the corresponding commands.
9966 The formula can be any algebraic expression understood by the Calc package.
9967 For details, see the Org-mode manual.
9969 This function can also be called from Lisp programs and offers
9970 additional arguments: EQUATION can be the formula to apply. If this
9971 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9972 used to speed-up recursive calls by by-passing unnecessary aligns.
9973 SUPPRESS-CONST suppresses the interpretation of constants in the
9974 formula, assuming that this has been done already outside the function.
9975 SUPPRESS-STORE means the formula should not be stored, either because
9976 it is already stored, or because it is a modified equation that should
9977 not overwrite the stored one."
9978 (interactive "P")
9979 (org-table-check-inside-data-field)
9980 (or suppress-analysis (org-table-get-specials))
9981 (if (equal arg '(16))
9982 (let ((eq (org-table-current-field-formula)))
9983 (or eq (error "No equation active for current field"))
9984 (org-table-get-field nil eq)
9985 (org-table-align)
9986 (setq org-table-may-need-update t))
9987 (let* (fields
9988 (ndown (if (integerp arg) arg 1))
9989 (org-table-automatic-realign nil)
9990 (case-fold-search nil)
9991 (down (> ndown 1))
9992 (formula (if (and equation suppress-store)
9993 equation
9994 (org-table-get-formula equation (equal arg '(4)))))
9995 (n0 (org-table-current-column))
9996 (modes (copy-sequence org-calc-default-modes))
9997 (numbers nil) ; was a variable, now fixed default
9998 (keep-empty nil)
9999 n form form0 bw fmt x ev orig c lispp literal)
10000 ;; Parse the format string. Since we have a lot of modes, this is
10001 ;; a lot of work. However, I think calc still uses most of the time.
10002 (if (string-match ";" formula)
10003 (let ((tmp (org-split-string formula ";")))
10004 (setq formula (car tmp)
10005 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10006 (nth 1 tmp)))
10007 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10008 (setq c (string-to-char (match-string 1 fmt))
10009 n (string-to-number (match-string 2 fmt)))
10010 (if (= c ?p)
10011 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10012 (setq modes (org-set-calc-mode
10013 'calc-float-format
10014 (list (cdr (assoc c '((?n . float) (?f . fix)
10015 (?s . sci) (?e . eng))))
10016 n))))
10017 (setq fmt (replace-match "" t t fmt)))
10018 (if (string-match "[NT]" fmt)
10019 (setq numbers (equal (match-string 0 fmt) "N")
10020 fmt (replace-match "" t t fmt)))
10021 (if (string-match "L" fmt)
10022 (setq literal t
10023 fmt (replace-match "" t t fmt)))
10024 (if (string-match "E" fmt)
10025 (setq keep-empty t
10026 fmt (replace-match "" t t fmt)))
10027 (while (string-match "[DRFS]" fmt)
10028 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10029 (setq fmt (replace-match "" t t fmt)))
10030 (unless (string-match "\\S-" fmt)
10031 (setq fmt nil))))
10032 (if (and (not suppress-const) org-table-formula-use-constants)
10033 (setq formula (org-table-formula-substitute-names formula)))
10034 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10035 (while (> ndown 0)
10036 (setq fields (org-split-string
10037 (org-no-properties
10038 (buffer-substring (point-at-bol) (point-at-eol)))
10039 " *| *"))
10040 (if (eq numbers t)
10041 (setq fields (mapcar
10042 (lambda (x) (number-to-string (string-to-number x)))
10043 fields)))
10044 (setq ndown (1- ndown))
10045 (setq form (copy-sequence formula)
10046 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10047 (if (and lispp literal) (setq lispp 'literal))
10048 ;; Check for old vertical references
10049 (setq form (org-rewrite-old-row-references form))
10050 ;; Insert complex ranges
10051 (while (string-match org-table-range-regexp form)
10052 (setq form
10053 (replace-match
10054 (save-match-data
10055 (org-table-make-reference
10056 (org-table-get-range (match-string 0 form) nil n0)
10057 keep-empty numbers lispp))
10058 t t form)))
10059 ;; Insert simple ranges
10060 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10061 (setq form
10062 (replace-match
10063 (save-match-data
10064 (org-table-make-reference
10065 (org-sublist
10066 fields (string-to-number (match-string 1 form))
10067 (string-to-number (match-string 2 form)))
10068 keep-empty numbers lispp))
10069 t t form)))
10070 (setq form0 form)
10071 ;; Insert the references to fields in same row
10072 (while (string-match "\\$\\([0-9]+\\)" form)
10073 (setq n (string-to-number (match-string 1 form))
10074 x (nth (1- (if (= n 0) n0 n)) fields))
10075 (unless x (error "Invalid field specifier \"%s\""
10076 (match-string 0 form)))
10077 (setq form (replace-match
10078 (save-match-data
10079 (org-table-make-reference x nil numbers lispp))
10080 t t form)))
10082 (if lispp
10083 (setq ev (condition-case nil
10084 (eval (eval (read form)))
10085 (error "#ERROR"))
10086 ev (if (numberp ev) (number-to-string ev) ev))
10087 (or (fboundp 'calc-eval)
10088 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10089 (setq ev (calc-eval (cons form modes)
10090 (if numbers 'num))))
10092 (when org-table-formula-debug
10093 (with-output-to-temp-buffer "*Substitution History*"
10094 (princ (format "Substitution history of formula
10095 Orig: %s
10096 $xyz-> %s
10097 @r$c-> %s
10098 $1-> %s\n" orig formula form0 form))
10099 (if (listp ev)
10100 (princ (format " %s^\nError: %s"
10101 (make-string (car ev) ?\-) (nth 1 ev)))
10102 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10103 ev (or fmt "NONE")
10104 (if fmt (format fmt (string-to-number ev)) ev)))))
10105 (setq bw (get-buffer-window "*Substitution History*"))
10106 (shrink-window-if-larger-than-buffer bw)
10107 (unless (and (interactive-p) (not ndown))
10108 (unless (let (inhibit-redisplay)
10109 (y-or-n-p "Debugging Formula. Continue to next? "))
10110 (org-table-align)
10111 (error "Abort"))
10112 (delete-window bw)
10113 (message "")))
10114 (if (listp ev) (setq fmt nil ev "#ERROR"))
10115 (org-table-justify-field-maybe
10116 (if fmt (format fmt (string-to-number ev)) ev))
10117 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10118 (call-interactively 'org-return)
10119 (setq ndown 0)))
10120 (and down (org-table-maybe-recalculate-line))
10121 (or suppress-align (and org-table-may-need-update
10122 (org-table-align))))))
10124 (defun org-table-put-field-property (prop value)
10125 (save-excursion
10126 (put-text-property (progn (skip-chars-backward "^|") (point))
10127 (progn (skip-chars-forward "^|") (point))
10128 prop value)))
10130 (defun org-table-get-range (desc &optional tbeg col highlight)
10131 "Get a calc vector from a column, accorting to descriptor DESC.
10132 Optional arguments TBEG and COL can give the beginning of the table and
10133 the current column, to avoid unnecessary parsing.
10134 HIGHLIGHT means, just highlight the range."
10135 (if (not (equal (string-to-char desc) ?@))
10136 (setq desc (concat "@" desc)))
10137 (save-excursion
10138 (or tbeg (setq tbeg (org-table-begin)))
10139 (or col (setq col (org-table-current-column)))
10140 (let ((thisline (org-current-line))
10141 beg end c1 c2 r1 r2 rangep tmp)
10142 (unless (string-match org-table-range-regexp desc)
10143 (error "Invalid table range specifier `%s'" desc))
10144 (setq rangep (match-end 3)
10145 r1 (and (match-end 1) (match-string 1 desc))
10146 r2 (and (match-end 4) (match-string 4 desc))
10147 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10148 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10150 (and c1 (setq c1 (+ (string-to-number c1)
10151 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10152 (and c2 (setq c2 (+ (string-to-number c2)
10153 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10154 (if (equal r1 "") (setq r1 nil))
10155 (if (equal r2 "") (setq r2 nil))
10156 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10157 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10158 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10159 (if (not r1) (setq r1 thisline))
10160 (if (not r2) (setq r2 thisline))
10161 (if (not c1) (setq c1 col))
10162 (if (not c2) (setq c2 col))
10163 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10164 ;; just one field
10165 (progn
10166 (goto-line r1)
10167 (while (not (looking-at org-table-dataline-regexp))
10168 (beginning-of-line 2))
10169 (prog1 (org-trim (org-table-get-field c1))
10170 (if highlight (org-table-highlight-rectangle (point) (point)))))
10171 ;; A range, return a vector
10172 ;; First sort the numbers to get a regular ractangle
10173 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10174 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10175 (goto-line r1)
10176 (while (not (looking-at org-table-dataline-regexp))
10177 (beginning-of-line 2))
10178 (org-table-goto-column c1)
10179 (setq beg (point))
10180 (goto-line r2)
10181 (while (not (looking-at org-table-dataline-regexp))
10182 (beginning-of-line 0))
10183 (org-table-goto-column c2)
10184 (setq end (point))
10185 (if highlight
10186 (org-table-highlight-rectangle
10187 beg (progn (skip-chars-forward "^|\n") (point))))
10188 ;; return string representation of calc vector
10189 (mapcar 'org-trim
10190 (apply 'append (org-table-copy-region beg end)))))))
10192 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10193 "Analyze descriptor DESC and retrieve the corresponding line number.
10194 The cursor is currently in line CLINE, the table begins in line BLINE,
10195 and TABLE is a vector with line types."
10196 (if (string-match "^[0-9]+$" desc)
10197 (aref org-table-dlines (string-to-number desc))
10198 (setq cline (or cline (org-current-line))
10199 bline (or bline org-table-current-begin-line)
10200 table (or table org-table-current-line-types))
10201 (if (or
10202 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10203 ;; 1 2 3 4 5 6
10204 (and (not (match-end 3)) (not (match-end 6)))
10205 (and (match-end 3) (match-end 6) (not (match-end 5))))
10206 (error "invalid row descriptor `%s'" desc))
10207 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10208 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10209 (odir (and (match-end 5) (match-string 5 desc)))
10210 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10211 (i (- cline bline))
10212 (rel (and (match-end 6)
10213 (or (and (match-end 1) (not (match-end 3)))
10214 (match-end 5)))))
10215 (if (and hn (not hdir))
10216 (progn
10217 (setq i 0 hdir "+")
10218 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10219 (if (and (not hn) on (not odir))
10220 (error "should never happen");;(aref org-table-dlines on)
10221 (if (and hn (> hn 0))
10222 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10223 (if on
10224 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10225 (+ bline i)))))
10227 (defun org-find-row-type (table i type backwards relative n)
10228 (let ((l (length table)))
10229 (while (> n 0)
10230 (while (and (setq i (+ i (if backwards -1 1)))
10231 (>= i 0) (< i l)
10232 (not (eq (aref table i) type))
10233 (if (and relative (eq (aref table i) 'hline))
10234 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10235 t)))
10236 (setq n (1- n)))
10237 (if (or (< i 0) (>= i l))
10238 (error "Row descriptior leads outside table")
10239 i)))
10241 (defun org-rewrite-old-row-references (s)
10242 (if (string-match "&[-+0-9I]" s)
10243 (error "Formula contains old &row reference, please rewrite using @-syntax")
10246 (defun org-table-make-reference (elements keep-empty numbers lispp)
10247 "Convert list ELEMENTS to something appropriate to insert into formula.
10248 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10249 NUMBERS indicates that everything should be converted to numbers.
10250 LISPP means to return something appropriate for a Lisp list."
10251 (if (stringp elements) ; just a single val
10252 (if lispp
10253 (if (eq lispp 'literal)
10254 elements
10255 (prin1-to-string (if numbers (string-to-number elements) elements)))
10256 (if (equal elements "") (setq elements "0"))
10257 (if numbers (number-to-string (string-to-number elements)) elements))
10258 (unless keep-empty
10259 (setq elements
10260 (delq nil
10261 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10262 elements))))
10263 (setq elements (or elements '("0")))
10264 (if lispp
10265 (mapconcat
10266 (lambda (x)
10267 (if (eq lispp 'literal)
10269 (prin1-to-string (if numbers (string-to-number x) x))))
10270 elements " ")
10271 (concat "[" (mapconcat
10272 (lambda (x)
10273 (if numbers (number-to-string (string-to-number x)) x))
10274 elements
10275 ",") "]"))))
10277 (defun org-table-recalculate (&optional all noalign)
10278 "Recalculate the current table line by applying all stored formulas.
10279 With prefix arg ALL, do this for all lines in the table."
10280 (interactive "P")
10281 (or (memq this-command org-recalc-commands)
10282 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10283 (unless (org-at-table-p) (error "Not at a table"))
10284 (if (equal all '(16))
10285 (org-table-iterate)
10286 (org-table-get-specials)
10287 (let* ((eqlist (sort (org-table-get-stored-formulas)
10288 (lambda (a b) (string< (car a) (car b)))))
10289 (inhibit-redisplay (not debug-on-error))
10290 (line-re org-table-dataline-regexp)
10291 (thisline (org-current-line))
10292 (thiscol (org-table-current-column))
10293 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10294 ;; Insert constants in all formulas
10295 (setq eqlist
10296 (mapcar (lambda (x)
10297 (setcdr x (org-table-formula-substitute-names (cdr x)))
10299 eqlist))
10300 ;; Split the equation list
10301 (while (setq eq (pop eqlist))
10302 (if (<= (string-to-char (car eq)) ?9)
10303 (push eq eqlnum)
10304 (push eq eqlname)))
10305 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10306 (if all
10307 (progn
10308 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10309 (goto-char (setq beg (org-table-begin)))
10310 (if (re-search-forward org-table-calculate-mark-regexp end t)
10311 ;; This is a table with marked lines, compute selected lines
10312 (setq line-re org-table-recalculate-regexp)
10313 ;; Move forward to the first non-header line
10314 (if (and (re-search-forward org-table-dataline-regexp end t)
10315 (re-search-forward org-table-hline-regexp end t)
10316 (re-search-forward org-table-dataline-regexp end t))
10317 (setq beg (match-beginning 0))
10318 nil))) ;; just leave beg where it is
10319 (setq beg (point-at-bol)
10320 end (move-marker (make-marker) (1+ (point-at-eol)))))
10321 (goto-char beg)
10322 (and all (message "Re-applying formulas to full table..."))
10324 ;; First find the named fields, and mark them untouchanble
10325 (remove-text-properties beg end '(org-untouchable t))
10326 (while (setq eq (pop eqlname))
10327 (setq name (car eq)
10328 a (assoc name org-table-named-field-locations))
10329 (and (not a)
10330 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10331 (setq a (list name
10332 (aref org-table-dlines
10333 (string-to-number (match-string 1 name)))
10334 (string-to-number (match-string 2 name)))))
10335 (when (and a (or all (equal (nth 1 a) thisline)))
10336 (message "Re-applying formula to field: %s" name)
10337 (goto-line (nth 1 a))
10338 (org-table-goto-column (nth 2 a))
10339 (push (append a (list (cdr eq))) eqlname1)
10340 (org-table-put-field-property :org-untouchable t)))
10342 ;; Now evauluate the column formulas, but skip fields covered by
10343 ;; field formulas
10344 (goto-char beg)
10345 (while (re-search-forward line-re end t)
10346 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10347 ;; Unprotected line, recalculate
10348 (and all (message "Re-applying formulas to full table...(line %d)"
10349 (setq cnt (1+ cnt))))
10350 (setq org-last-recalc-line (org-current-line))
10351 (setq eql eqlnum)
10352 (while (setq entry (pop eql))
10353 (goto-line org-last-recalc-line)
10354 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10355 (unless (get-text-property (point) :org-untouchable)
10356 (org-table-eval-formula nil (cdr entry)
10357 'noalign 'nocst 'nostore 'noanalysis)))))
10359 ;; Now evaluate the field formulas
10360 (while (setq eq (pop eqlname1))
10361 (message "Re-applying formula to field: %s" (car eq))
10362 (goto-line (nth 1 eq))
10363 (org-table-goto-column (nth 2 eq))
10364 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10365 'nostore 'noanalysis))
10367 (goto-line thisline)
10368 (org-table-goto-column thiscol)
10369 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10370 (or noalign (and org-table-may-need-update (org-table-align))
10371 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10373 ;; back to initial position
10374 (message "Re-applying formulas...done")
10375 (goto-line thisline)
10376 (org-table-goto-column thiscol)
10377 (or noalign (and org-table-may-need-update (org-table-align))
10378 (and all (message "Re-applying formulas...done"))))))
10380 (defun org-table-iterate (&optional arg)
10381 "Recalculate the table until it does not change anymore."
10382 (interactive "P")
10383 (let ((imax (if arg (prefix-numeric-value arg) 10))
10384 (i 0)
10385 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10386 thistbl)
10387 (catch 'exit
10388 (while (< i imax)
10389 (setq i (1+ i))
10390 (org-table-recalculate 'all)
10391 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10392 (if (not (string= lasttbl thistbl))
10393 (setq lasttbl thistbl)
10394 (if (> i 1)
10395 (message "Convergence after %d iterations" i)
10396 (message "Table was already stable"))
10397 (throw 'exit t)))
10398 (error "No convergence after %d iterations" i))))
10400 (defun org-table-formula-substitute-names (f)
10401 "Replace $const with values in string F."
10402 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10403 ;; First, check for column names
10404 (while (setq start (string-match org-table-column-name-regexp f start))
10405 (setq start (1+ start))
10406 (setq a (assoc (match-string 1 f) org-table-column-names))
10407 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10408 ;; Parameters and constants
10409 (setq start 0)
10410 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10411 (setq start (1+ start))
10412 (if (setq a (save-match-data
10413 (org-table-get-constant (match-string 1 f))))
10414 (setq f (replace-match
10415 (concat (if pp "(") a (if pp ")")) t t f))))
10416 (if org-table-formula-debug
10417 (put-text-property 0 (length f) :orig-formula f1 f))
10420 (defun org-table-get-constant (const)
10421 "Find the value for a parameter or constant in a formula.
10422 Parameters get priority."
10423 (or (cdr (assoc const org-table-local-parameters))
10424 (cdr (assoc const org-table-formula-constants-local))
10425 (cdr (assoc const org-table-formula-constants))
10426 (and (fboundp 'constants-get) (constants-get const))
10427 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10428 (org-entry-get nil (substring const 5) 'inherit))
10429 "#UNDEFINED_NAME"))
10431 (defvar org-table-fedit-map
10432 (let ((map (make-sparse-keymap)))
10433 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10434 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10435 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10436 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10437 (org-defkey map "\C-c?" 'org-table-show-reference)
10438 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10439 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10440 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10441 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10442 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10443 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10444 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10445 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10446 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10447 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10448 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10449 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10450 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10451 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10452 map))
10454 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10455 '("Edit-Formulas"
10456 ["Finish and Install" org-table-fedit-finish t]
10457 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10458 ["Abort" org-table-fedit-abort t]
10459 "--"
10460 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10461 ["Complete Lisp Symbol" lisp-complete-symbol t]
10462 "--"
10463 "Shift Reference at Point"
10464 ["Up" org-table-fedit-ref-up t]
10465 ["Down" org-table-fedit-ref-down t]
10466 ["Left" org-table-fedit-ref-left t]
10467 ["Right" org-table-fedit-ref-right t]
10469 "Change Test Row for Column Formulas"
10470 ["Up" org-table-fedit-line-up t]
10471 ["Down" org-table-fedit-line-down t]
10472 "--"
10473 ["Scroll Table Window" org-table-fedit-scroll t]
10474 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10475 ["Show Table Grid" org-table-fedit-toggle-coordinates
10476 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10477 org-table-overlay-coordinates)]
10478 "--"
10479 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10480 :style toggle :selected org-table-buffer-is-an]))
10482 (defvar org-pos)
10484 (defun org-table-edit-formulas ()
10485 "Edit the formulas of the current table in a separate buffer."
10486 (interactive)
10487 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10488 (beginning-of-line 0))
10489 (unless (org-at-table-p) (error "Not at a table"))
10490 (org-table-get-specials)
10491 (let ((key (org-table-current-field-formula 'key 'noerror))
10492 (eql (sort (org-table-get-stored-formulas 'noerror)
10493 'org-table-formula-less-p))
10494 (pos (move-marker (make-marker) (point)))
10495 (startline 1)
10496 (wc (current-window-configuration))
10497 (titles '((column . "# Column Formulas\n")
10498 (field . "# Field Formulas\n")
10499 (named . "# Named Field Formulas\n")))
10500 entry s type title)
10501 (org-switch-to-buffer-other-window "*Edit Formulas*")
10502 (erase-buffer)
10503 ;; Keep global-font-lock-mode from turning on font-lock-mode
10504 (let ((font-lock-global-modes '(not fundamental-mode)))
10505 (fundamental-mode))
10506 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10507 (org-set-local 'org-pos pos)
10508 (org-set-local 'org-window-configuration wc)
10509 (use-local-map org-table-fedit-map)
10510 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10511 (easy-menu-add org-table-fedit-menu)
10512 (setq startline (org-current-line))
10513 (while (setq entry (pop eql))
10514 (setq type (cond
10515 ((equal (string-to-char (car entry)) ?@) 'field)
10516 ((string-match "^[0-9]" (car entry)) 'column)
10517 (t 'named)))
10518 (when (setq title (assq type titles))
10519 (or (bobp) (insert "\n"))
10520 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10521 (setq titles (delq title titles)))
10522 (if (equal key (car entry)) (setq startline (org-current-line)))
10523 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10524 (car entry) " = " (cdr entry) "\n"))
10525 (remove-text-properties 0 (length s) '(face nil) s)
10526 (insert s))
10527 (if (eq org-table-use-standard-references t)
10528 (org-table-fedit-toggle-ref-type))
10529 (goto-line startline)
10530 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10532 (defun org-table-fedit-post-command ()
10533 (when (not (memq this-command '(lisp-complete-symbol)))
10534 (let ((win (selected-window)))
10535 (save-excursion
10536 (condition-case nil
10537 (org-table-show-reference)
10538 (error nil))
10539 (select-window win)))))
10541 (defun org-table-formula-to-user (s)
10542 "Convert a formula from internal to user representation."
10543 (if (eq org-table-use-standard-references t)
10544 (org-table-convert-refs-to-an s)
10547 (defun org-table-formula-from-user (s)
10548 "Convert a formula from user to internal representation."
10549 (if org-table-use-standard-references
10550 (org-table-convert-refs-to-rc s)
10553 (defun org-table-convert-refs-to-rc (s)
10554 "Convert spreadsheet references from AB7 to @7$28.
10555 Works for single references, but also for entire formulas and even the
10556 full TBLFM line."
10557 (let ((start 0))
10558 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10559 (cond
10560 ((match-end 3)
10561 ;; format match, just advance
10562 (setq start (match-end 0)))
10563 ((and (> (match-beginning 0) 0)
10564 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10565 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10566 ;; 3.e5 or something like this.
10567 (setq start (match-end 0)))
10569 (setq start (match-beginning 0)
10570 s (replace-match
10571 (if (equal (match-string 2 s) "&")
10572 (format "$%d" (org-letters-to-number (match-string 1 s)))
10573 (format "@%d$%d"
10574 (string-to-number (match-string 2 s))
10575 (org-letters-to-number (match-string 1 s))))
10576 t t s)))))
10579 (defun org-table-convert-refs-to-an (s)
10580 "Convert spreadsheet references from to @7$28 to AB7.
10581 Works for single references, but also for entire formulas and even the
10582 full TBLFM line."
10583 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10584 (setq s (replace-match
10585 (format "%s%d"
10586 (org-number-to-letters
10587 (string-to-number (match-string 2 s)))
10588 (string-to-number (match-string 1 s)))
10589 t t s)))
10590 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10591 (setq s (replace-match (concat "\\1"
10592 (org-number-to-letters
10593 (string-to-number (match-string 2 s))) "&")
10594 t nil s)))
10597 (defun org-letters-to-number (s)
10598 "Convert a base 26 number represented by letters into an integer.
10599 For example: AB -> 28."
10600 (let ((n 0))
10601 (setq s (upcase s))
10602 (while (> (length s) 0)
10603 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10604 s (substring s 1)))
10607 (defun org-number-to-letters (n)
10608 "Convert an integer into a base 26 number represented by letters.
10609 For example: 28 -> AB."
10610 (let ((s ""))
10611 (while (> n 0)
10612 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10613 n (/ (1- n) 26)))
10616 (defun org-table-fedit-convert-buffer (function)
10617 "Convert all references in this buffer, using FUNTION."
10618 (let ((line (org-current-line)))
10619 (goto-char (point-min))
10620 (while (not (eobp))
10621 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10622 (delete-region (point) (point-at-eol))
10623 (or (eobp) (forward-char 1)))
10624 (goto-line line)))
10626 (defun org-table-fedit-toggle-ref-type ()
10627 "Convert all references in the buffer from B3 to @3$2 and back."
10628 (interactive)
10629 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10630 (org-table-fedit-convert-buffer
10631 (if org-table-buffer-is-an
10632 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10633 (message "Reference type switched to %s"
10634 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10636 (defun org-table-fedit-ref-up ()
10637 "Shift the reference at point one row/hline up."
10638 (interactive)
10639 (org-table-fedit-shift-reference 'up))
10640 (defun org-table-fedit-ref-down ()
10641 "Shift the reference at point one row/hline down."
10642 (interactive)
10643 (org-table-fedit-shift-reference 'down))
10644 (defun org-table-fedit-ref-left ()
10645 "Shift the reference at point one field to the left."
10646 (interactive)
10647 (org-table-fedit-shift-reference 'left))
10648 (defun org-table-fedit-ref-right ()
10649 "Shift the reference at point one field to the right."
10650 (interactive)
10651 (org-table-fedit-shift-reference 'right))
10653 (defun org-table-fedit-shift-reference (dir)
10654 (cond
10655 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10656 (if (memq dir '(left right))
10657 (org-rematch-and-replace 1 (eq dir 'left))
10658 (error "Cannot shift reference in this direction")))
10659 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10660 ;; A B3-like reference
10661 (if (memq dir '(up down))
10662 (org-rematch-and-replace 2 (eq dir 'up))
10663 (org-rematch-and-replace 1 (eq dir 'left))))
10664 ((org-at-regexp-p
10665 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10666 ;; An internal reference
10667 (if (memq dir '(up down))
10668 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10669 (org-rematch-and-replace 5 (eq dir 'left))))))
10671 (defun org-rematch-and-replace (n &optional decr hline)
10672 "Re-match the group N, and replace it with the shifted refrence."
10673 (or (match-end n) (error "Cannot shift reference in this direction"))
10674 (goto-char (match-beginning n))
10675 (and (looking-at (regexp-quote (match-string n)))
10676 (replace-match (org-shift-refpart (match-string 0) decr hline)
10677 t t)))
10679 (defun org-shift-refpart (ref &optional decr hline)
10680 "Shift a refrence part REF.
10681 If DECR is set, decrease the references row/column, else increase.
10682 If HLINE is set, this may be a hline reference, it certainly is not
10683 a translation reference."
10684 (save-match-data
10685 (let* ((sign (string-match "^[-+]" ref)) n)
10687 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10688 (cond
10689 ((and hline (string-match "^I+" ref))
10690 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10691 (setq n (+ n (if decr -1 1)))
10692 (if (= n 0) (setq n (+ n (if decr -1 1))))
10693 (if sign
10694 (setq sign (if (< n 0) "-" "+") n (abs n))
10695 (setq n (max 1 n)))
10696 (concat sign (make-string n ?I)))
10698 ((string-match "^[0-9]+" ref)
10699 (setq n (string-to-number (concat sign ref)))
10700 (setq n (+ n (if decr -1 1)))
10701 (if sign
10702 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10703 (number-to-string (max 1 n))))
10705 ((string-match "^[a-zA-Z]+" ref)
10706 (org-number-to-letters
10707 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10709 (t (error "Cannot shift reference"))))))
10711 (defun org-table-fedit-toggle-coordinates ()
10712 "Toggle the display of coordinates in the refrenced table."
10713 (interactive)
10714 (let ((pos (marker-position org-pos)))
10715 (with-current-buffer (marker-buffer org-pos)
10716 (save-excursion
10717 (goto-char pos)
10718 (org-table-toggle-coordinate-overlays)))))
10720 (defun org-table-fedit-finish (&optional arg)
10721 "Parse the buffer for formula definitions and install them.
10722 With prefix ARG, apply the new formulas to the table."
10723 (interactive "P")
10724 (org-table-remove-rectangle-highlight)
10725 (if org-table-use-standard-references
10726 (progn
10727 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10728 (setq org-table-buffer-is-an nil)))
10729 (let ((pos org-pos) eql var form)
10730 (goto-char (point-min))
10731 (while (re-search-forward
10732 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10733 nil t)
10734 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10735 form (match-string 3))
10736 (setq form (org-trim form))
10737 (when (not (equal form ""))
10738 (while (string-match "[ \t]*\n[ \t]*" form)
10739 (setq form (replace-match " " t t form)))
10740 (when (assoc var eql)
10741 (error "Double formulas for %s" var))
10742 (push (cons var form) eql)))
10743 (setq org-pos nil)
10744 (set-window-configuration org-window-configuration)
10745 (select-window (get-buffer-window (marker-buffer pos)))
10746 (goto-char pos)
10747 (unless (org-at-table-p)
10748 (error "Lost table position - cannot install formulae"))
10749 (org-table-store-formulas eql)
10750 (move-marker pos nil)
10751 (kill-buffer "*Edit Formulas*")
10752 (if arg
10753 (org-table-recalculate 'all)
10754 (message "New formulas installed - press C-u C-c C-c to apply."))))
10756 (defun org-table-fedit-abort ()
10757 "Abort editing formulas, without installing the changes."
10758 (interactive)
10759 (org-table-remove-rectangle-highlight)
10760 (let ((pos org-pos))
10761 (set-window-configuration org-window-configuration)
10762 (select-window (get-buffer-window (marker-buffer pos)))
10763 (goto-char pos)
10764 (move-marker pos nil)
10765 (message "Formula editing aborted without installing changes")))
10767 (defun org-table-fedit-lisp-indent ()
10768 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10769 (interactive)
10770 (let ((pos (point)) beg end ind)
10771 (beginning-of-line 1)
10772 (cond
10773 ((looking-at "[ \t]")
10774 (goto-char pos)
10775 (call-interactively 'lisp-indent-line))
10776 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10777 ((not (fboundp 'pp-buffer))
10778 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10779 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10780 (goto-char (- (match-end 0) 2))
10781 (setq beg (point))
10782 (setq ind (make-string (current-column) ?\ ))
10783 (condition-case nil (forward-sexp 1)
10784 (error
10785 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10786 (setq end (point))
10787 (save-restriction
10788 (narrow-to-region beg end)
10789 (if (eq last-command this-command)
10790 (progn
10791 (goto-char (point-min))
10792 (setq this-command nil)
10793 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10794 (replace-match " ")))
10795 (pp-buffer)
10796 (untabify (point-min) (point-max))
10797 (goto-char (1+ (point-min)))
10798 (while (re-search-forward "^." nil t)
10799 (beginning-of-line 1)
10800 (insert ind))
10801 (goto-char (point-max))
10802 (backward-delete-char 1)))
10803 (goto-char beg))
10804 (t nil))))
10806 (defvar org-show-positions nil)
10808 (defun org-table-show-reference (&optional local)
10809 "Show the location/value of the $ expression at point."
10810 (interactive)
10811 (org-table-remove-rectangle-highlight)
10812 (catch 'exit
10813 (let ((pos (if local (point) org-pos))
10814 (face2 'highlight)
10815 (org-inhibit-highlight-removal t)
10816 (win (selected-window))
10817 (org-show-positions nil)
10818 var name e what match dest)
10819 (if local (org-table-get-specials))
10820 (setq what (cond
10821 ((or (org-at-regexp-p org-table-range-regexp2)
10822 (org-at-regexp-p org-table-translate-regexp)
10823 (org-at-regexp-p org-table-range-regexp))
10824 (setq match
10825 (save-match-data
10826 (org-table-convert-refs-to-rc (match-string 0))))
10827 'range)
10828 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10829 ((org-at-regexp-p "\\$[0-9]+") 'column)
10830 ((not local) nil)
10831 (t (error "No reference at point")))
10832 match (and what (or match (match-string 0))))
10833 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10834 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10835 'secondary-selection))
10836 (org-add-hook 'before-change-functions
10837 'org-table-remove-rectangle-highlight)
10838 (if (eq what 'name) (setq var (substring match 1)))
10839 (when (eq what 'range)
10840 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10841 (setq match (org-table-formula-substitute-names match)))
10842 (unless local
10843 (save-excursion
10844 (end-of-line 1)
10845 (re-search-backward "^\\S-" nil t)
10846 (beginning-of-line 1)
10847 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10848 (setq dest
10849 (save-match-data
10850 (org-table-convert-refs-to-rc (match-string 1))))
10851 (org-table-add-rectangle-overlay
10852 (match-beginning 1) (match-end 1) face2))))
10853 (if (and (markerp pos) (marker-buffer pos))
10854 (if (get-buffer-window (marker-buffer pos))
10855 (select-window (get-buffer-window (marker-buffer pos)))
10856 (org-switch-to-buffer-other-window (get-buffer-window
10857 (marker-buffer pos)))))
10858 (goto-char pos)
10859 (org-table-force-dataline)
10860 (when dest
10861 (setq name (substring dest 1))
10862 (cond
10863 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10864 (setq e (assoc name org-table-named-field-locations))
10865 (goto-line (nth 1 e))
10866 (org-table-goto-column (nth 2 e)))
10867 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10868 (let ((l (string-to-number (match-string 1 dest)))
10869 (c (string-to-number (match-string 2 dest))))
10870 (goto-line (aref org-table-dlines l))
10871 (org-table-goto-column c)))
10872 (t (org-table-goto-column (string-to-number name))))
10873 (move-marker pos (point))
10874 (org-table-highlight-rectangle nil nil face2))
10875 (cond
10876 ((equal dest match))
10877 ((not match))
10878 ((eq what 'range)
10879 (condition-case nil
10880 (save-excursion
10881 (org-table-get-range match nil nil 'highlight))
10882 (error nil)))
10883 ((setq e (assoc var org-table-named-field-locations))
10884 (goto-line (nth 1 e))
10885 (org-table-goto-column (nth 2 e))
10886 (org-table-highlight-rectangle (point) (point))
10887 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10888 ((setq e (assoc var org-table-column-names))
10889 (org-table-goto-column (string-to-number (cdr e)))
10890 (org-table-highlight-rectangle (point) (point))
10891 (goto-char (org-table-begin))
10892 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10893 (org-table-end) t)
10894 (progn
10895 (goto-char (match-beginning 1))
10896 (org-table-highlight-rectangle)
10897 (message "Named column (column %s)" (cdr e)))
10898 (error "Column name not found")))
10899 ((eq what 'column)
10900 ;; column number
10901 (org-table-goto-column (string-to-number (substring match 1)))
10902 (org-table-highlight-rectangle (point) (point))
10903 (message "Column %s" (substring match 1)))
10904 ((setq e (assoc var org-table-local-parameters))
10905 (goto-char (org-table-begin))
10906 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10907 (progn
10908 (goto-char (match-beginning 1))
10909 (org-table-highlight-rectangle)
10910 (message "Local parameter."))
10911 (error "Parameter not found")))
10913 (cond
10914 ((not var) (error "No reference at point"))
10915 ((setq e (assoc var org-table-formula-constants-local))
10916 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10917 var (cdr e)))
10918 ((setq e (assoc var org-table-formula-constants))
10919 (message "Constant: $%s=%s in `org-table-formula-constants'."
10920 var (cdr e)))
10921 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10922 (message "Constant: $%s=%s, from `constants.el'%s."
10923 var e (format " (%s units)" constants-unit-system)))
10924 (t (error "Undefined name $%s" var)))))
10925 (goto-char pos)
10926 (when (and org-show-positions
10927 (not (memq this-command '(org-table-fedit-scroll
10928 org-table-fedit-scroll-down))))
10929 (push pos org-show-positions)
10930 (push org-table-current-begin-pos org-show-positions)
10931 (let ((min (apply 'min org-show-positions))
10932 (max (apply 'max org-show-positions)))
10933 (goto-char min) (recenter 0)
10934 (goto-char max)
10935 (or (pos-visible-in-window-p max) (recenter -1))))
10936 (select-window win))))
10938 (defun org-table-force-dataline ()
10939 "Make sure the cursor is in a dataline in a table."
10940 (unless (save-excursion
10941 (beginning-of-line 1)
10942 (looking-at org-table-dataline-regexp))
10943 (let* ((re org-table-dataline-regexp)
10944 (p1 (save-excursion (re-search-forward re nil 'move)))
10945 (p2 (save-excursion (re-search-backward re nil 'move))))
10946 (cond ((and p1 p2)
10947 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10948 p1 p2)))
10949 ((or p1 p2) (goto-char (or p1 p2)))
10950 (t (error "No table dataline around here"))))))
10952 (defun org-table-fedit-line-up ()
10953 "Move cursor one line up in the window showing the table."
10954 (interactive)
10955 (org-table-fedit-move 'previous-line))
10957 (defun org-table-fedit-line-down ()
10958 "Move cursor one line down in the window showing the table."
10959 (interactive)
10960 (org-table-fedit-move 'next-line))
10962 (defun org-table-fedit-move (command)
10963 "Move the cursor in the window shoinw the table.
10964 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10965 (let ((org-table-allow-automatic-line-recalculation nil)
10966 (pos org-pos) (win (selected-window)) p)
10967 (select-window (get-buffer-window (marker-buffer org-pos)))
10968 (setq p (point))
10969 (call-interactively command)
10970 (while (and (org-at-table-p)
10971 (org-at-table-hline-p))
10972 (call-interactively command))
10973 (or (org-at-table-p) (goto-char p))
10974 (move-marker pos (point))
10975 (select-window win)))
10977 (defun org-table-fedit-scroll (N)
10978 (interactive "p")
10979 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10980 (scroll-other-window N)))
10982 (defun org-table-fedit-scroll-down (N)
10983 (interactive "p")
10984 (org-table-fedit-scroll (- N)))
10986 (defvar org-table-rectangle-overlays nil)
10988 (defun org-table-add-rectangle-overlay (beg end &optional face)
10989 "Add a new overlay."
10990 (let ((ov (org-make-overlay beg end)))
10991 (org-overlay-put ov 'face (or face 'secondary-selection))
10992 (push ov org-table-rectangle-overlays)))
10994 (defun org-table-highlight-rectangle (&optional beg end face)
10995 "Highlight rectangular region in a table."
10996 (setq beg (or beg (point)) end (or end (point)))
10997 (let ((b (min beg end))
10998 (e (max beg end))
10999 l1 c1 l2 c2 tmp)
11000 (and (boundp 'org-show-positions)
11001 (setq org-show-positions (cons b (cons e org-show-positions))))
11002 (goto-char (min beg end))
11003 (setq l1 (org-current-line)
11004 c1 (org-table-current-column))
11005 (goto-char (max beg end))
11006 (setq l2 (org-current-line)
11007 c2 (org-table-current-column))
11008 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11009 (goto-line l1)
11010 (beginning-of-line 1)
11011 (loop for line from l1 to l2 do
11012 (when (looking-at org-table-dataline-regexp)
11013 (org-table-goto-column c1)
11014 (skip-chars-backward "^|\n") (setq beg (point))
11015 (org-table-goto-column c2)
11016 (skip-chars-forward "^|\n") (setq end (point))
11017 (org-table-add-rectangle-overlay beg end face))
11018 (beginning-of-line 2))
11019 (goto-char b))
11020 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11022 (defun org-table-remove-rectangle-highlight (&rest ignore)
11023 "Remove the rectangle overlays."
11024 (unless org-inhibit-highlight-removal
11025 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11026 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11027 (setq org-table-rectangle-overlays nil)))
11029 (defvar org-table-coordinate-overlays nil
11030 "Collects the cooordinate grid overlays, so that they can be removed.")
11031 (make-variable-buffer-local 'org-table-coordinate-overlays)
11033 (defun org-table-overlay-coordinates ()
11034 "Add overlays to the table at point, to show row/column coordinates."
11035 (interactive)
11036 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11037 (setq org-table-coordinate-overlays nil)
11038 (save-excursion
11039 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11040 (goto-char (org-table-begin))
11041 (while (org-at-table-p)
11042 (setq eol (point-at-eol))
11043 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11044 (push ov org-table-coordinate-overlays)
11045 (setq hline (looking-at org-table-hline-regexp))
11046 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11047 (format "%4d" (setq id (1+ id)))))
11048 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11049 (when hline
11050 (setq ic 0)
11051 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11052 (setq beg (1+ (match-beginning 0))
11053 ic (1+ ic)
11054 s1 (concat "$" (int-to-string ic))
11055 s2 (org-number-to-letters ic)
11056 str (if (eq org-table-use-standard-references t) s2 s1))
11057 (setq ov (org-make-overlay beg (+ beg (length str))))
11058 (push ov org-table-coordinate-overlays)
11059 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11060 (beginning-of-line 2)))))
11062 (defun org-table-toggle-coordinate-overlays ()
11063 "Toggle the display of Row/Column numbers in tables."
11064 (interactive)
11065 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11066 (message "Row/Column number display turned %s"
11067 (if org-table-overlay-coordinates "on" "off"))
11068 (if (and (org-at-table-p) org-table-overlay-coordinates)
11069 (org-table-align))
11070 (unless org-table-overlay-coordinates
11071 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11072 (setq org-table-coordinate-overlays nil)))
11074 (defun org-table-toggle-formula-debugger ()
11075 "Toggle the formula debugger in tables."
11076 (interactive)
11077 (setq org-table-formula-debug (not org-table-formula-debug))
11078 (message "Formula debugging has been turned %s"
11079 (if org-table-formula-debug "on" "off")))
11081 ;;; The orgtbl minor mode
11083 ;; Define a minor mode which can be used in other modes in order to
11084 ;; integrate the org-mode table editor.
11086 ;; This is really a hack, because the org-mode table editor uses several
11087 ;; keys which normally belong to the major mode, for example the TAB and
11088 ;; RET keys. Here is how it works: The minor mode defines all the keys
11089 ;; necessary to operate the table editor, but wraps the commands into a
11090 ;; function which tests if the cursor is currently inside a table. If that
11091 ;; is the case, the table editor command is executed. However, when any of
11092 ;; those keys is used outside a table, the function uses `key-binding' to
11093 ;; look up if the key has an associated command in another currently active
11094 ;; keymap (minor modes, major mode, global), and executes that command.
11095 ;; There might be problems if any of the keys used by the table editor is
11096 ;; otherwise used as a prefix key.
11098 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11099 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11100 ;; addresses this by checking explicitly for both bindings.
11102 ;; The optimized version (see variable `orgtbl-optimized') takes over
11103 ;; all keys which are bound to `self-insert-command' in the *global map*.
11104 ;; Some modes bind other commands to simple characters, for example
11105 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11106 ;; active, this binding is ignored inside tables and replaced with a
11107 ;; modified self-insert.
11109 (defvar orgtbl-mode nil
11110 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11111 table editor in arbitrary modes.")
11112 (make-variable-buffer-local 'orgtbl-mode)
11114 (defvar orgtbl-mode-map (make-keymap)
11115 "Keymap for `orgtbl-mode'.")
11117 ;;;###autoload
11118 (defun turn-on-orgtbl ()
11119 "Unconditionally turn on `orgtbl-mode'."
11120 (orgtbl-mode 1))
11122 (defvar org-old-auto-fill-inhibit-regexp nil
11123 "Local variable used by `orgtbl-mode'")
11125 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11126 "Matches a line belonging to an orgtbl.")
11128 (defconst orgtbl-extra-font-lock-keywords
11129 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11130 0 (quote 'org-table) 'prepend))
11131 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11133 ;;;###autoload
11134 (defun orgtbl-mode (&optional arg)
11135 "The `org-mode' table editor as a minor mode for use in other modes."
11136 (interactive)
11137 (if (org-mode-p)
11138 ;; Exit without error, in case some hook functions calls this
11139 ;; by accident in org-mode.
11140 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11141 (setq orgtbl-mode
11142 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11143 (if orgtbl-mode
11144 (progn
11145 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11146 ;; Make sure we are first in minor-mode-map-alist
11147 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11148 (and c (setq minor-mode-map-alist
11149 (cons c (delq c minor-mode-map-alist)))))
11150 (org-set-local (quote org-table-may-need-update) t)
11151 (org-add-hook 'before-change-functions 'org-before-change-function
11152 nil 'local)
11153 (org-set-local 'org-old-auto-fill-inhibit-regexp
11154 auto-fill-inhibit-regexp)
11155 (org-set-local 'auto-fill-inhibit-regexp
11156 (if auto-fill-inhibit-regexp
11157 (concat orgtbl-line-start-regexp "\\|"
11158 auto-fill-inhibit-regexp)
11159 orgtbl-line-start-regexp))
11160 (org-add-to-invisibility-spec '(org-cwidth))
11161 (when (fboundp 'font-lock-add-keywords)
11162 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11163 (org-restart-font-lock))
11164 (easy-menu-add orgtbl-mode-menu)
11165 (run-hooks 'orgtbl-mode-hook))
11166 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11167 (org-cleanup-narrow-column-properties)
11168 (org-remove-from-invisibility-spec '(org-cwidth))
11169 (remove-hook 'before-change-functions 'org-before-change-function t)
11170 (when (fboundp 'font-lock-remove-keywords)
11171 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11172 (org-restart-font-lock))
11173 (easy-menu-remove orgtbl-mode-menu)
11174 (force-mode-line-update 'all))))
11176 (defun org-cleanup-narrow-column-properties ()
11177 "Remove all properties related to narrow-column invisibility."
11178 (let ((s 1))
11179 (while (setq s (text-property-any s (point-max)
11180 'display org-narrow-column-arrow))
11181 (remove-text-properties s (1+ s) '(display t)))
11182 (setq s 1)
11183 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11184 (remove-text-properties s (1+ s) '(org-cwidth t)))
11185 (setq s 1)
11186 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11187 (remove-text-properties s (1+ s) '(invisible t)))))
11189 ;; Install it as a minor mode.
11190 (put 'orgtbl-mode :included t)
11191 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11192 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11194 (defun orgtbl-make-binding (fun n &rest keys)
11195 "Create a function for binding in the table minor mode.
11196 FUN is the command to call inside a table. N is used to create a unique
11197 command name. KEYS are keys that should be checked in for a command
11198 to execute outside of tables."
11199 (eval
11200 (list 'defun
11201 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11202 '(arg)
11203 (concat "In tables, run `" (symbol-name fun) "'.\n"
11204 "Outside of tables, run the binding of `"
11205 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11206 "'.")
11207 '(interactive "p")
11208 (list 'if
11209 '(org-at-table-p)
11210 (list 'call-interactively (list 'quote fun))
11211 (list 'let '(orgtbl-mode)
11212 (list 'call-interactively
11213 (append '(or)
11214 (mapcar (lambda (k)
11215 (list 'key-binding k))
11216 keys)
11217 '('orgtbl-error))))))))
11219 (defun orgtbl-error ()
11220 "Error when there is no default binding for a table key."
11221 (interactive)
11222 (error "This key has no function outside tables"))
11224 (defun orgtbl-setup ()
11225 "Setup orgtbl keymaps."
11226 (let ((nfunc 0)
11227 (bindings
11228 (list
11229 '([(meta shift left)] org-table-delete-column)
11230 '([(meta left)] org-table-move-column-left)
11231 '([(meta right)] org-table-move-column-right)
11232 '([(meta shift right)] org-table-insert-column)
11233 '([(meta shift up)] org-table-kill-row)
11234 '([(meta shift down)] org-table-insert-row)
11235 '([(meta up)] org-table-move-row-up)
11236 '([(meta down)] org-table-move-row-down)
11237 '("\C-c\C-w" org-table-cut-region)
11238 '("\C-c\M-w" org-table-copy-region)
11239 '("\C-c\C-y" org-table-paste-rectangle)
11240 '("\C-c-" org-table-insert-hline)
11241 '("\C-c}" org-table-toggle-coordinate-overlays)
11242 '("\C-c{" org-table-toggle-formula-debugger)
11243 '("\C-m" org-table-next-row)
11244 '([(shift return)] org-table-copy-down)
11245 '("\C-c\C-q" org-table-wrap-region)
11246 '("\C-c?" org-table-field-info)
11247 '("\C-c " org-table-blank-field)
11248 '("\C-c+" org-table-sum)
11249 '("\C-c=" org-table-eval-formula)
11250 '("\C-c'" org-table-edit-formulas)
11251 '("\C-c`" org-table-edit-field)
11252 '("\C-c*" org-table-recalculate)
11253 '("\C-c|" org-table-create-or-convert-from-region)
11254 '("\C-c^" org-table-sort-lines)
11255 '([(control ?#)] org-table-rotate-recalc-marks)))
11256 elt key fun cmd)
11257 (while (setq elt (pop bindings))
11258 (setq nfunc (1+ nfunc))
11259 (setq key (org-key (car elt))
11260 fun (nth 1 elt)
11261 cmd (orgtbl-make-binding fun nfunc key))
11262 (org-defkey orgtbl-mode-map key cmd))
11264 ;; Special treatment needed for TAB and RET
11265 (org-defkey orgtbl-mode-map [(return)]
11266 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11267 (org-defkey orgtbl-mode-map "\C-m"
11268 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11270 (org-defkey orgtbl-mode-map [(tab)]
11271 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11272 (org-defkey orgtbl-mode-map "\C-i"
11273 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11275 (org-defkey orgtbl-mode-map [(shift tab)]
11276 (orgtbl-make-binding 'org-table-previous-field 104
11277 [(shift tab)] [(tab)] "\C-i"))
11279 (org-defkey orgtbl-mode-map "\M-\C-m"
11280 (orgtbl-make-binding 'org-table-wrap-region 105
11281 "\M-\C-m" [(meta return)]))
11282 (org-defkey orgtbl-mode-map [(meta return)]
11283 (orgtbl-make-binding 'org-table-wrap-region 106
11284 [(meta return)] "\M-\C-m"))
11286 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11287 (when orgtbl-optimized
11288 ;; If the user wants maximum table support, we need to hijack
11289 ;; some standard editing functions
11290 (org-remap orgtbl-mode-map
11291 'self-insert-command 'orgtbl-self-insert-command
11292 'delete-char 'org-delete-char
11293 'delete-backward-char 'org-delete-backward-char)
11294 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11295 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11296 '("OrgTbl"
11297 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11298 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11299 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11300 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11301 "--"
11302 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11303 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11304 ["Copy Field from Above"
11305 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11306 "--"
11307 ("Column"
11308 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11309 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11310 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11311 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11312 ("Row"
11313 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11314 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11315 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11316 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11317 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11318 "--"
11319 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11320 ("Rectangle"
11321 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11322 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11323 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11324 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11325 "--"
11326 ("Radio tables"
11327 ["Insert table template" orgtbl-insert-radio-table
11328 (assq major-mode orgtbl-radio-table-templates)]
11329 ["Comment/uncomment table" orgtbl-toggle-comment t])
11330 "--"
11331 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11332 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11333 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11334 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11335 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11336 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11337 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11338 ["Sum Column/Rectangle" org-table-sum
11339 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11340 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11341 ["Debug Formulas"
11342 org-table-toggle-formula-debugger :active (org-at-table-p)
11343 :keys "C-c {"
11344 :style toggle :selected org-table-formula-debug]
11345 ["Show Col/Row Numbers"
11346 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11347 :keys "C-c }"
11348 :style toggle :selected org-table-overlay-coordinates]
11352 (defun orgtbl-ctrl-c-ctrl-c (arg)
11353 "If the cursor is inside a table, realign the table.
11354 It it is a table to be sent away to a receiver, do it.
11355 With prefix arg, also recompute table."
11356 (interactive "P")
11357 (let ((pos (point)) action)
11358 (save-excursion
11359 (beginning-of-line 1)
11360 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11361 ((looking-at "[ \t]*|") pos)
11362 ((looking-at "#\\+TBLFM:") 'recalc))))
11363 (cond
11364 ((integerp action)
11365 (goto-char action)
11366 (org-table-maybe-eval-formula)
11367 (if arg
11368 (call-interactively 'org-table-recalculate)
11369 (org-table-maybe-recalculate-line))
11370 (call-interactively 'org-table-align)
11371 (orgtbl-send-table 'maybe))
11372 ((eq action 'recalc)
11373 (save-excursion
11374 (beginning-of-line 1)
11375 (skip-chars-backward " \r\n\t")
11376 (if (org-at-table-p)
11377 (org-call-with-arg 'org-table-recalculate t))))
11378 (t (let (orgtbl-mode)
11379 (call-interactively (key-binding "\C-c\C-c")))))))
11381 (defun orgtbl-tab (arg)
11382 "Justification and field motion for `orgtbl-mode'."
11383 (interactive "P")
11384 (if arg (org-table-edit-field t)
11385 (org-table-justify-field-maybe)
11386 (org-table-next-field)))
11388 (defun orgtbl-ret ()
11389 "Justification and field motion for `orgtbl-mode'."
11390 (interactive)
11391 (org-table-justify-field-maybe)
11392 (org-table-next-row))
11394 (defun orgtbl-self-insert-command (N)
11395 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11396 If the cursor is in a table looking at whitespace, the whitespace is
11397 overwritten, and the table is not marked as requiring realignment."
11398 (interactive "p")
11399 (if (and (org-at-table-p)
11401 (and org-table-auto-blank-field
11402 (member last-command
11403 '(orgtbl-hijacker-command-100
11404 orgtbl-hijacker-command-101
11405 orgtbl-hijacker-command-102
11406 orgtbl-hijacker-command-103
11407 orgtbl-hijacker-command-104
11408 orgtbl-hijacker-command-105))
11409 (org-table-blank-field))
11411 (eq N 1)
11412 (looking-at "[^|\n]* +|"))
11413 (let (org-table-may-need-update)
11414 (goto-char (1- (match-end 0)))
11415 (delete-backward-char 1)
11416 (goto-char (match-beginning 0))
11417 (self-insert-command N))
11418 (setq org-table-may-need-update t)
11419 (let (orgtbl-mode)
11420 (call-interactively (key-binding (vector last-input-event))))))
11422 (defun org-force-self-insert (N)
11423 "Needed to enforce self-insert under remapping."
11424 (interactive "p")
11425 (self-insert-command N))
11427 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11428 "Regula expression matching exponentials as produced by calc.")
11430 (defvar org-table-clean-did-remove-column nil)
11432 (defun orgtbl-export (table target)
11433 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11434 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11435 org-table-last-alignment org-table-last-column-widths
11436 maxcol column)
11437 (if (not (fboundp func))
11438 (error "Cannot export orgtbl table to %s" target))
11439 (setq lines (org-table-clean-before-export lines))
11440 (setq table
11441 (mapcar
11442 (lambda (x)
11443 (if (string-match org-table-hline-regexp x)
11444 'hline
11445 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11446 lines))
11447 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11448 table)))
11449 (loop for i from (1- maxcol) downto 0 do
11450 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11451 (setq column (delq nil column))
11452 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11453 (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))
11454 (funcall func table nil)))
11456 (defun orgtbl-send-table (&optional maybe)
11457 "Send a tranformed version of this table to the receiver position.
11458 With argument MAYBE, fail quietly if no transformation is defined for
11459 this table."
11460 (interactive)
11461 (catch 'exit
11462 (unless (org-at-table-p) (error "Not at a table"))
11463 ;; when non-interactive, we assume align has just happened.
11464 (when (interactive-p) (org-table-align))
11465 (save-excursion
11466 (goto-char (org-table-begin))
11467 (beginning-of-line 0)
11468 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11469 (if maybe
11470 (throw 'exit nil)
11471 (error "Don't know how to transform this table."))))
11472 (let* ((name (match-string 1))
11474 (transform (intern (match-string 2)))
11475 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11476 (skip (plist-get params :skip))
11477 (skipcols (plist-get params :skipcols))
11478 (txt (buffer-substring-no-properties
11479 (org-table-begin) (org-table-end)))
11480 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11481 (lines (org-table-clean-before-export lines))
11482 (i0 (if org-table-clean-did-remove-column 2 1))
11483 (table (mapcar
11484 (lambda (x)
11485 (if (string-match org-table-hline-regexp x)
11486 'hline
11487 (org-remove-by-index
11488 (org-split-string (org-trim x) "\\s-*|\\s-*")
11489 skipcols i0)))
11490 lines))
11491 (fun (if (= i0 2) 'cdr 'identity))
11492 (org-table-last-alignment
11493 (org-remove-by-index (funcall fun org-table-last-alignment)
11494 skipcols i0))
11495 (org-table-last-column-widths
11496 (org-remove-by-index (funcall fun org-table-last-column-widths)
11497 skipcols i0)))
11499 (unless (fboundp transform)
11500 (error "No such transformation function %s" transform))
11501 (setq txt (funcall transform table params))
11502 ;; Find the insertion place
11503 (save-excursion
11504 (goto-char (point-min))
11505 (unless (re-search-forward
11506 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11507 (error "Don't know where to insert translated table"))
11508 (goto-char (match-beginning 0))
11509 (beginning-of-line 2)
11510 (setq beg (point))
11511 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11512 (error "Cannot find end of insertion region"))
11513 (beginning-of-line 1)
11514 (delete-region beg (point))
11515 (goto-char beg)
11516 (insert txt "\n"))
11517 (message "Table converted and installed at receiver location"))))
11519 (defun org-remove-by-index (list indices &optional i0)
11520 "Remove the elements in LIST with indices in INDICES.
11521 First element has index 0, or I0 if given."
11522 (if (not indices)
11523 list
11524 (if (integerp indices) (setq indices (list indices)))
11525 (setq i0 (1- (or i0 0)))
11526 (delq :rm (mapcar (lambda (x)
11527 (setq i0 (1+ i0))
11528 (if (memq i0 indices) :rm x))
11529 list))))
11531 (defun orgtbl-toggle-comment ()
11532 "Comment or uncomment the orgtbl at point."
11533 (interactive)
11534 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11535 (re2 (concat "^" orgtbl-line-start-regexp))
11536 (commented (save-excursion (beginning-of-line 1)
11537 (cond ((looking-at re1) t)
11538 ((looking-at re2) nil)
11539 (t (error "Not at an org table")))))
11540 (re (if commented re1 re2))
11541 beg end)
11542 (save-excursion
11543 (beginning-of-line 1)
11544 (while (looking-at re) (beginning-of-line 0))
11545 (beginning-of-line 2)
11546 (setq beg (point))
11547 (while (looking-at re) (beginning-of-line 2))
11548 (setq end (point)))
11549 (comment-region beg end (if commented '(4) nil))))
11551 (defun orgtbl-insert-radio-table ()
11552 "Insert a radio table template appropriate for this major mode."
11553 (interactive)
11554 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11555 (txt (nth 1 e))
11556 name pos)
11557 (unless e (error "No radio table setup defined for %s" major-mode))
11558 (setq name (read-string "Table name: "))
11559 (while (string-match "%n" txt)
11560 (setq txt (replace-match name t t txt)))
11561 (or (bolp) (insert "\n"))
11562 (setq pos (point))
11563 (insert txt)
11564 (goto-char pos)))
11566 (defun org-get-param (params header i sym &optional hsym)
11567 "Get parameter value for symbol SYM.
11568 If this is a header line, actually get the value for the symbol with an
11569 additional \"h\" inserted after the colon.
11570 If the value is a protperty list, get the element for the current column.
11571 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11572 (let ((val (plist-get params sym)))
11573 (and hsym header (setq val (or (plist-get params hsym) val)))
11574 (if (consp val) (plist-get val i) val)))
11576 (defun orgtbl-to-generic (table params)
11577 "Convert the orgtbl-mode TABLE to some other format.
11578 This generic routine can be used for many standard cases.
11579 TABLE is a list, each entry either the symbol `hline' for a horizontal
11580 separator line, or a list of fields for that line.
11581 PARAMS is a property list of parameters that can influence the conversion.
11582 For the generic converter, some parameters are obligatory: You need to
11583 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11584 :splice, you must have :tstart and :tend.
11586 Valid parameters are
11588 :tstart String to start the table. Ignored when :splice is t.
11589 :tend String to end the table. Ignored when :splice is t.
11591 :splice When set to t, return only table body lines, don't wrap
11592 them into :tstart and :tend. Default is nil.
11594 :hline String to be inserted on horizontal separation lines.
11595 May be nil to ignore hlines.
11597 :lstart String to start a new table line.
11598 :lend String to end a table line
11599 :sep Separator between two fields
11600 :lfmt Format for entire line, with enough %s to capture all fields.
11601 If this is present, :lstart, :lend, and :sep are ignored.
11602 :fmt A format to be used to wrap the field, should contain
11603 %s for the original field value. For example, to wrap
11604 everything in dollars, you could use :fmt \"$%s$\".
11605 This may also be a property list with column numbers and
11606 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11608 :hlstart :hlend :hlsep :hlfmt :hfmt
11609 Same as above, specific for the header lines in the table.
11610 All lines before the first hline are treated as header.
11611 If any of these is not present, the data line value is used.
11613 :efmt Use this format to print numbers with exponentials.
11614 The format should have %s twice for inserting mantissa
11615 and exponent, for example \"%s\\\\times10^{%s}\". This
11616 may also be a property list with column numbers and
11617 formats. :fmt will still be applied after :efmt.
11619 In addition to this, the parameters :skip and :skipcols are always handled
11620 directly by `orgtbl-send-table'. See manual."
11621 (interactive)
11622 (let* ((p params)
11623 (splicep (plist-get p :splice))
11624 (hline (plist-get p :hline))
11625 rtn line i fm efm lfmt h)
11627 ;; Do we have a header?
11628 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11629 (setq h t))
11631 ;; Put header
11632 (unless splicep
11633 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11635 ;; Now loop over all lines
11636 (while (setq line (pop table))
11637 (if (eq line 'hline)
11638 ;; A horizontal separator line
11639 (progn (if hline (push hline rtn))
11640 (setq h nil)) ; no longer in header
11641 ;; A normal line. Convert the fields, push line onto the result list
11642 (setq i 0)
11643 (setq line
11644 (mapcar
11645 (lambda (f)
11646 (setq i (1+ i)
11647 fm (org-get-param p h i :fmt :hfmt)
11648 efm (org-get-param p h i :efmt))
11649 (if (and efm (string-match orgtbl-exp-regexp f))
11650 (setq f (format
11651 efm (match-string 1 f) (match-string 2 f))))
11652 (if fm (setq f (format fm f)))
11654 line))
11655 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11656 (push (apply 'format lfmt line) rtn)
11657 (push (concat
11658 (org-get-param p h i :lstart :hlstart)
11659 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11660 (org-get-param p h i :lend :hlend))
11661 rtn))))
11663 (unless splicep
11664 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11666 (mapconcat 'identity (nreverse rtn) "\n")))
11668 (defun orgtbl-to-latex (table params)
11669 "Convert the orgtbl-mode TABLE to LaTeX.
11670 TABLE is a list, each entry either the symbol `hline' for a horizontal
11671 separator line, or a list of fields for that line.
11672 PARAMS is a property list of parameters that can influence the conversion.
11673 Supports all parameters from `orgtbl-to-generic'. Most important for
11674 LaTeX are:
11676 :splice When set to t, return only table body lines, don't wrap
11677 them into a tabular environment. Default is nil.
11679 :fmt A format to be used to wrap the field, should contain %s for the
11680 original field value. For example, to wrap everything in dollars,
11681 use :fmt \"$%s$\". This may also be a property list with column
11682 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11684 :efmt Format for transforming numbers with exponentials. The format
11685 should have %s twice for inserting mantissa and exponent, for
11686 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11687 This may also be a property list with column numbers and formats.
11689 The general parameters :skip and :skipcols have already been applied when
11690 this function is called."
11691 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11692 org-table-last-alignment ""))
11693 (params2
11694 (list
11695 :tstart (concat "\\begin{tabular}{" alignment "}")
11696 :tend "\\end{tabular}"
11697 :lstart "" :lend " \\\\" :sep " & "
11698 :efmt "%s\\,(%s)" :hline "\\hline")))
11699 (orgtbl-to-generic table (org-combine-plists params2 params))))
11701 (defun orgtbl-to-html (table params)
11702 "Convert the orgtbl-mode TABLE to LaTeX.
11703 TABLE is a list, each entry either the symbol `hline' for a horizontal
11704 separator line, or a list of fields for that line.
11705 PARAMS is a property list of parameters that can influence the conversion.
11706 Currently this function recognizes the following parameters:
11708 :splice When set to t, return only table body lines, don't wrap
11709 them into a <table> environment. Default is nil.
11711 The general parameters :skip and :skipcols have already been applied when
11712 this function is called. The function does *not* use `orgtbl-to-generic',
11713 so you cannot specify parameters for it."
11714 (let* ((splicep (plist-get params :splice))
11715 html)
11716 ;; Just call the formatter we already have
11717 ;; We need to make text lines for it, so put the fields back together.
11718 (setq html (org-format-org-table-html
11719 (mapcar
11720 (lambda (x)
11721 (if (eq x 'hline)
11722 "|----+----|"
11723 (concat "| " (mapconcat 'identity x " | ") " |")))
11724 table)
11725 splicep))
11726 (if (string-match "\n+\\'" html)
11727 (setq html (replace-match "" t t html)))
11728 html))
11730 (defun orgtbl-to-texinfo (table params)
11731 "Convert the orgtbl-mode TABLE to TeXInfo.
11732 TABLE is a list, each entry either the symbol `hline' for a horizontal
11733 separator line, or a list of fields for that line.
11734 PARAMS is a property list of parameters that can influence the conversion.
11735 Supports all parameters from `orgtbl-to-generic'. Most important for
11736 TeXInfo are:
11738 :splice nil/t When set to t, return only table body lines, don't wrap
11739 them into a multitable environment. Default is nil.
11741 :fmt fmt A format to be used to wrap the field, should contain
11742 %s for the original field value. For example, to wrap
11743 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11744 This may also be a property list with column numbers and
11745 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11747 :cf \"f1 f2..\" The column fractions for the table. By default these
11748 are computed automatically from the width of the columns
11749 under org-mode.
11751 The general parameters :skip and :skipcols have already been applied when
11752 this function is called."
11753 (let* ((total (float (apply '+ org-table-last-column-widths)))
11754 (colfrac (or (plist-get params :cf)
11755 (mapconcat
11756 (lambda (x) (format "%.3f" (/ (float x) total)))
11757 org-table-last-column-widths " ")))
11758 (params2
11759 (list
11760 :tstart (concat "@multitable @columnfractions " colfrac)
11761 :tend "@end multitable"
11762 :lstart "@item " :lend "" :sep " @tab "
11763 :hlstart "@headitem ")))
11764 (orgtbl-to-generic table (org-combine-plists params2 params))))
11766 ;;;; Link Stuff
11768 ;;; Link abbreviations
11770 (defun org-link-expand-abbrev (link)
11771 "Apply replacements as defined in `org-link-abbrev-alist."
11772 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11773 (let* ((key (match-string 1 link))
11774 (as (or (assoc key org-link-abbrev-alist-local)
11775 (assoc key org-link-abbrev-alist)))
11776 (tag (and (match-end 2) (match-string 3 link)))
11777 rpl)
11778 (if (not as)
11779 link
11780 (setq rpl (cdr as))
11781 (cond
11782 ((symbolp rpl) (funcall rpl tag))
11783 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11784 (t (concat rpl tag)))))
11785 link))
11787 ;;; Storing and inserting links
11789 (defvar org-insert-link-history nil
11790 "Minibuffer history for links inserted with `org-insert-link'.")
11792 (defvar org-stored-links nil
11793 "Contains the links stored with `org-store-link'.")
11795 (defvar org-store-link-plist nil
11796 "Plist with info about the most recently link created with `org-store-link'.")
11798 (defvar org-link-protocols nil
11799 "Link protocols added to Org-mode using `org-add-link-type'.")
11801 (defvar org-store-link-functions nil
11802 "List of functions that are called to create and store a link.
11803 Each function will be called in turn until one returns a non-nil
11804 value. Each function should check if it is responsible for creating
11805 this link (for example by looking at the major mode).
11806 If not, it must exit and return nil.
11807 If yes, it should return a non-nil value after a calling
11808 `org-store-link-props' with a list of properties and values.
11809 Special properties are:
11811 :type The link prefix. like \"http\". This must be given.
11812 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11813 This is obligatory as well.
11814 :description Optional default description for the second pair
11815 of brackets in an Org-mode link. The user can still change
11816 this when inserting this link into an Org-mode buffer.
11818 In addition to these, any additional properties can be specified
11819 and then used in remember templates.")
11821 (defun org-add-link-type (type &optional follow publish)
11822 "Add TYPE to the list of `org-link-types'.
11823 Re-compute all regular expressions depending on `org-link-types'
11824 FOLLOW and PUBLISH are two functions. Both take the link path as
11825 an argument.
11826 FOLLOW should do whatever is necessary to follow the link, for example
11827 to find a file or display a mail message.
11829 PUBLISH takes the path and retuns the string that should be used when
11830 this document is published. FIMXE: This is actually not yet implemented."
11831 (add-to-list 'org-link-types type t)
11832 (org-make-link-regexps)
11833 (add-to-list 'org-link-protocols
11834 (list type follow publish)))
11836 (defun org-add-agenda-custom-command (entry)
11837 "Replace or add a command in `org-agenda-custom-commands'.
11838 This is mostly for hacking and trying a new command - once the command
11839 works you probably want to add it to `org-agenda-custom-commands' for good."
11840 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11841 (if ass
11842 (setcdr ass (cdr entry))
11843 (push entry org-agenda-custom-commands))))
11845 ;;;###autoload
11846 (defun org-store-link (arg)
11847 "\\<org-mode-map>Store an org-link to the current location.
11848 This link can later be inserted into an org-buffer with
11849 \\[org-insert-link].
11850 For some link types, a prefix arg is interpreted:
11851 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11852 For file links, arg negates `org-context-in-file-links'."
11853 (interactive "P")
11854 (setq org-store-link-plist nil) ; reset
11855 (let (link cpltxt desc description search txt)
11856 (cond
11858 ((run-hook-with-args-until-success 'org-store-link-functions)
11859 (setq link (plist-get org-store-link-plist :link)
11860 desc (or (plist-get org-store-link-plist :description) link)))
11862 ((eq major-mode 'bbdb-mode)
11863 (let ((name (bbdb-record-name (bbdb-current-record)))
11864 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11865 (setq cpltxt (concat "bbdb:" (or name company))
11866 link (org-make-link cpltxt))
11867 (org-store-link-props :type "bbdb" :name name :company company)))
11869 ((eq major-mode 'Info-mode)
11870 (setq link (org-make-link "info:"
11871 (file-name-nondirectory Info-current-file)
11872 ":" Info-current-node))
11873 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11874 ":" Info-current-node))
11875 (org-store-link-props :type "info" :file Info-current-file
11876 :node Info-current-node))
11878 ((eq major-mode 'calendar-mode)
11879 (let ((cd (calendar-cursor-to-date)))
11880 (setq link
11881 (format-time-string
11882 (car org-time-stamp-formats)
11883 (apply 'encode-time
11884 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11885 nil nil nil))))
11886 (org-store-link-props :type "calendar" :date cd)))
11888 ((or (eq major-mode 'vm-summary-mode)
11889 (eq major-mode 'vm-presentation-mode))
11890 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11891 (vm-follow-summary-cursor)
11892 (save-excursion
11893 (vm-select-folder-buffer)
11894 (let* ((message (car vm-message-pointer))
11895 (folder buffer-file-name)
11896 (subject (vm-su-subject message))
11897 (to (vm-get-header-contents message "To"))
11898 (from (vm-get-header-contents message "From"))
11899 (message-id (vm-su-message-id message)))
11900 (org-store-link-props :type "vm" :from from :to to :subject subject
11901 :message-id message-id)
11902 (setq message-id (org-remove-angle-brackets message-id))
11903 (setq folder (abbreviate-file-name folder))
11904 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11905 folder)
11906 (setq folder (replace-match "" t t folder)))
11907 (setq cpltxt (org-email-link-description))
11908 (setq link (org-make-link "vm:" folder "#" message-id)))))
11910 ((eq major-mode 'wl-summary-mode)
11911 (let* ((msgnum (wl-summary-message-number))
11912 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11913 msgnum 'message-id))
11914 (wl-message-entity
11915 (if (fboundp 'elmo-message-entity)
11916 (elmo-message-entity
11917 wl-summary-buffer-elmo-folder msgnum)
11918 (elmo-msgdb-overview-get-entity
11919 msgnum (wl-summary-buffer-msgdb))))
11920 (from (wl-summary-line-from))
11921 (to (car (elmo-message-entity-field wl-message-entity 'to)))
11922 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11923 (wl-summary-line-subject))))
11924 (org-store-link-props :type "wl" :from from :to to
11925 :subject subject :message-id message-id)
11926 (setq message-id (org-remove-angle-brackets message-id))
11927 (setq cpltxt (org-email-link-description))
11928 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11929 "#" message-id))))
11931 ((or (equal major-mode 'mh-folder-mode)
11932 (equal major-mode 'mh-show-mode))
11933 (let ((from (org-mhe-get-header "From:"))
11934 (to (org-mhe-get-header "To:"))
11935 (message-id (org-mhe-get-header "Message-Id:"))
11936 (subject (org-mhe-get-header "Subject:")))
11937 (org-store-link-props :type "mh" :from from :to to
11938 :subject subject :message-id message-id)
11939 (setq cpltxt (org-email-link-description))
11940 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11941 (org-remove-angle-brackets message-id)))))
11943 ((eq major-mode 'rmail-mode)
11944 (save-excursion
11945 (save-restriction
11946 (rmail-narrow-to-non-pruned-header)
11947 (let ((folder buffer-file-name)
11948 (message-id (mail-fetch-field "message-id"))
11949 (from (mail-fetch-field "from"))
11950 (to (mail-fetch-field "to"))
11951 (subject (mail-fetch-field "subject")))
11952 (org-store-link-props
11953 :type "rmail" :from from :to to
11954 :subject subject :message-id message-id)
11955 (setq message-id (org-remove-angle-brackets message-id))
11956 (setq cpltxt (org-email-link-description))
11957 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11959 ((eq major-mode 'gnus-group-mode)
11960 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11961 (gnus-group-group-name)) ; version
11962 ((fboundp 'gnus-group-name)
11963 (gnus-group-name))
11964 (t "???"))))
11965 (unless group (error "Not on a group"))
11966 (org-store-link-props :type "gnus" :group group)
11967 (setq cpltxt (concat
11968 (if (org-xor arg org-usenet-links-prefer-google)
11969 "http://groups.google.com/groups?group="
11970 "gnus:")
11971 group)
11972 link (org-make-link cpltxt))))
11974 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11975 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11976 (let* ((group gnus-newsgroup-name)
11977 (article (gnus-summary-article-number))
11978 (header (gnus-summary-article-header article))
11979 (from (mail-header-from header))
11980 (message-id (mail-header-id header))
11981 (date (mail-header-date header))
11982 (subject (gnus-summary-subject-string)))
11983 (org-store-link-props :type "gnus" :from from :subject subject
11984 :message-id message-id :group group)
11985 (setq cpltxt (org-email-link-description))
11986 (if (org-xor arg org-usenet-links-prefer-google)
11987 (setq link
11988 (concat
11989 cpltxt "\n "
11990 (format "http://groups.google.com/groups?as_umsgid=%s"
11991 (org-fixup-message-id-for-http message-id))))
11992 (setq link (org-make-link "gnus:" group
11993 "#" (number-to-string article))))))
11995 ((eq major-mode 'w3-mode)
11996 (setq cpltxt (url-view-url t)
11997 link (org-make-link cpltxt))
11998 (org-store-link-props :type "w3" :url (url-view-url t)))
12000 ((eq major-mode 'w3m-mode)
12001 (setq cpltxt (or w3m-current-title w3m-current-url)
12002 link (org-make-link w3m-current-url))
12003 (org-store-link-props :type "w3m" :url (url-view-url t)))
12005 ((setq search (run-hook-with-args-until-success
12006 'org-create-file-search-functions))
12007 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12008 "::" search))
12009 (setq cpltxt (or description link)))
12011 ((eq major-mode 'image-mode)
12012 (setq cpltxt (concat "file:"
12013 (abbreviate-file-name buffer-file-name))
12014 link (org-make-link cpltxt))
12015 (org-store-link-props :type "image" :file buffer-file-name))
12017 ((eq major-mode 'dired-mode)
12018 ;; link to the file in the current line
12019 (setq cpltxt (concat "file:"
12020 (abbreviate-file-name
12021 (expand-file-name
12022 (dired-get-filename nil t))))
12023 link (org-make-link cpltxt)))
12025 ((and buffer-file-name (org-mode-p))
12026 ;; Just link to current headline
12027 (setq cpltxt (concat "file:"
12028 (abbreviate-file-name buffer-file-name)))
12029 ;; Add a context search string
12030 (when (org-xor org-context-in-file-links arg)
12031 ;; Check if we are on a target
12032 (if (org-in-regexp "<<\\(.*?\\)>>")
12033 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12034 (setq txt (cond
12035 ((org-on-heading-p) nil)
12036 ((org-region-active-p)
12037 (buffer-substring (region-beginning) (region-end)))
12038 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12039 (when (or (null txt) (string-match "\\S-" txt))
12040 (setq cpltxt
12041 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12042 desc "NONE"))))
12043 (if (string-match "::\\'" cpltxt)
12044 (setq cpltxt (substring cpltxt 0 -2)))
12045 (setq link (org-make-link cpltxt)))
12047 ((buffer-file-name (buffer-base-buffer))
12048 ;; Just link to this file here.
12049 (setq cpltxt (concat "file:"
12050 (abbreviate-file-name
12051 (buffer-file-name (buffer-base-buffer)))))
12052 ;; Add a context string
12053 (when (org-xor org-context-in-file-links arg)
12054 (setq txt (if (org-region-active-p)
12055 (buffer-substring (region-beginning) (region-end))
12056 (buffer-substring (point-at-bol) (point-at-eol))))
12057 ;; Only use search option if there is some text.
12058 (when (string-match "\\S-" txt)
12059 (setq cpltxt
12060 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12061 desc "NONE")))
12062 (setq link (org-make-link cpltxt)))
12064 ((interactive-p)
12065 (error "Cannot link to a buffer which is not visiting a file"))
12067 (t (setq link nil)))
12069 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12070 (setq link (or link cpltxt)
12071 desc (or desc cpltxt))
12072 (if (equal desc "NONE") (setq desc nil))
12074 (if (and (interactive-p) link)
12075 (progn
12076 (setq org-stored-links
12077 (cons (list link desc) org-stored-links))
12078 (message "Stored: %s" (or desc link)))
12079 (and link (org-make-link-string link desc)))))
12081 (defun org-store-link-props (&rest plist)
12082 "Store link properties, extract names and addresses."
12083 (let (x adr)
12084 (when (setq x (plist-get plist :from))
12085 (setq adr (mail-extract-address-components x))
12086 (plist-put plist :fromname (car adr))
12087 (plist-put plist :fromaddress (nth 1 adr)))
12088 (when (setq x (plist-get plist :to))
12089 (setq adr (mail-extract-address-components x))
12090 (plist-put plist :toname (car adr))
12091 (plist-put plist :toaddress (nth 1 adr))))
12092 (let ((from (plist-get plist :from))
12093 (to (plist-get plist :to)))
12094 (when (and from to org-from-is-user-regexp)
12095 (plist-put plist :fromto
12096 (if (string-match org-from-is-user-regexp from)
12097 (concat "to %t")
12098 (concat "from %f")))))
12099 (setq org-store-link-plist plist))
12101 (defun org-email-link-description (&optional fmt)
12102 "Return the description part of an email link.
12103 This takes information from `org-store-link-plist' and formats it
12104 according to FMT (default from `org-email-link-description-format')."
12105 (setq fmt (or fmt org-email-link-description-format))
12106 (let* ((p org-store-link-plist)
12107 (to (plist-get p :toaddress))
12108 (from (plist-get p :fromaddress))
12109 (table
12110 (list
12111 (cons "%c" (plist-get p :fromto))
12112 (cons "%F" (plist-get p :from))
12113 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12114 (cons "%T" (plist-get p :to))
12115 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12116 (cons "%s" (plist-get p :subject))
12117 (cons "%m" (plist-get p :message-id)))))
12118 (when (string-match "%c" fmt)
12119 ;; Check if the user wrote this message
12120 (if (and org-from-is-user-regexp from to
12121 (save-match-data (string-match org-from-is-user-regexp from)))
12122 (setq fmt (replace-match "to %t" t t fmt))
12123 (setq fmt (replace-match "from %f" t t fmt))))
12124 (org-replace-escapes fmt table)))
12126 (defun org-make-org-heading-search-string (&optional string heading)
12127 "Make search string for STRING or current headline."
12128 (interactive)
12129 (let ((s (or string (org-get-heading))))
12130 (unless (and string (not heading))
12131 ;; We are using a headline, clean up garbage in there.
12132 (if (string-match org-todo-regexp s)
12133 (setq s (replace-match "" t t s)))
12134 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12135 (setq s (replace-match "" t t s)))
12136 (setq s (org-trim s))
12137 (if (string-match (concat "^\\(" org-quote-string "\\|"
12138 org-comment-string "\\)") s)
12139 (setq s (replace-match "" t t s)))
12140 (while (string-match org-ts-regexp s)
12141 (setq s (replace-match "" t t s))))
12142 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12143 (setq s (replace-match " " t t s)))
12144 (or string (setq s (concat "*" s))) ; Add * for headlines
12145 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12147 (defun org-make-link (&rest strings)
12148 "Concatenate STRINGS."
12149 (apply 'concat strings))
12151 (defun org-make-link-string (link &optional description)
12152 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12153 (unless (string-match "\\S-" link)
12154 (error "Empty link"))
12155 (when (stringp description)
12156 ;; Remove brackets from the description, they are fatal.
12157 (while (string-match "\\[" description)
12158 (setq description (replace-match "{" t t description)))
12159 (while (string-match "\\]" description)
12160 (setq description (replace-match "}" t t description))))
12161 (when (equal (org-link-escape link) description)
12162 ;; No description needed, it is identical
12163 (setq description nil))
12164 (when (and (not description)
12165 (not (equal link (org-link-escape link))))
12166 (setq description link))
12167 (concat "[[" (org-link-escape link) "]"
12168 (if description (concat "[" description "]") "")
12169 "]"))
12171 (defconst org-link-escape-chars
12172 '((?\ . "%20")
12173 (?\[ . "%5B")
12174 (?\] . "%5D")
12175 (?\340 . "%E0") ; `a
12176 (?\342 . "%E2") ; ^a
12177 (?\347 . "%E7") ; ,c
12178 (?\350 . "%E8") ; `e
12179 (?\351 . "%E9") ; 'e
12180 (?\352 . "%EA") ; ^e
12181 (?\356 . "%EE") ; ^i
12182 (?\364 . "%F4") ; ^o
12183 (?\371 . "%F9") ; `u
12184 (?\373 . "%FB") ; ^u
12185 (?\; . "%3B")
12186 (?? . "%3F")
12187 (?= . "%3D")
12188 (?+ . "%2B")
12190 "Association list of escapes for some characters problematic in links.
12191 This is the list that is used for internal purposes.")
12193 (defconst org-link-escape-chars-browser
12194 '((?\ . "%20")) ; 32 for the SPC char
12195 "Association list of escapes for some characters problematic in links.
12196 This is the list that is used before handing over to the browser.")
12198 (defun org-link-escape (text &optional table)
12199 "Escape charaters in TEXT that are problematic for links."
12200 (setq table (or table org-link-escape-chars))
12201 (when text
12202 (let ((re (mapconcat (lambda (x) (regexp-quote
12203 (char-to-string (car x))))
12204 table "\\|")))
12205 (while (string-match re text)
12206 (setq text
12207 (replace-match
12208 (cdr (assoc (string-to-char (match-string 0 text))
12209 table))
12210 t t text)))
12211 text)))
12213 (defun org-link-unescape (text &optional table)
12214 "Reverse the action of `org-link-escape'."
12215 (setq table (or table org-link-escape-chars))
12216 (when text
12217 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12218 table "\\|")))
12219 (while (string-match re text)
12220 (setq text
12221 (replace-match
12222 (char-to-string (car (rassoc (match-string 0 text) table)))
12223 t t text)))
12224 text)))
12226 (defun org-xor (a b)
12227 "Exclusive or."
12228 (if a (not b) b))
12230 (defun org-get-header (header)
12231 "Find a header field in the current buffer."
12232 (save-excursion
12233 (goto-char (point-min))
12234 (let ((case-fold-search t) s)
12235 (cond
12236 ((eq header 'from)
12237 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12238 (setq s (match-string 1)))
12239 (while (string-match "\"" s)
12240 (setq s (replace-match "" t t s)))
12241 (if (string-match "[<(].*" s)
12242 (setq s (replace-match "" t t s))))
12243 ((eq header 'message-id)
12244 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12245 (setq s (match-string 1))))
12246 ((eq header 'subject)
12247 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12248 (setq s (match-string 1)))))
12249 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12250 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12251 s)))
12254 (defun org-fixup-message-id-for-http (s)
12255 "Replace special characters in a message id, so it can be used in an http query."
12256 (while (string-match "<" s)
12257 (setq s (replace-match "%3C" t t s)))
12258 (while (string-match ">" s)
12259 (setq s (replace-match "%3E" t t s)))
12260 (while (string-match "@" s)
12261 (setq s (replace-match "%40" t t s)))
12264 ;;;###autoload
12265 (defun org-insert-link-global ()
12266 "Insert a link like Org-mode does.
12267 This command can be called in any mode to insert a link in Org-mode syntax."
12268 (interactive)
12269 (org-run-like-in-org-mode 'org-insert-link))
12271 (defun org-insert-link (&optional complete-file)
12272 "Insert a link. At the prompt, enter the link.
12274 Completion can be used to select a link previously stored with
12275 `org-store-link'. When the empty string is entered (i.e. if you just
12276 press RET at the prompt), the link defaults to the most recently
12277 stored link. As SPC triggers completion in the minibuffer, you need to
12278 use M-SPC or C-q SPC to force the insertion of a space character.
12280 You will also be prompted for a description, and if one is given, it will
12281 be displayed in the buffer instead of the link.
12283 If there is already a link at point, this command will allow you to edit link
12284 and description parts.
12286 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12287 selected using completion. The path to the file will be relative to
12288 the current directory if the file is in the current directory or a
12289 subdirectory. Otherwise, the link will be the absolute path as
12290 completed in the minibuffer (i.e. normally ~/path/to/file).
12292 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12293 is in the current directory or below.
12294 With three \\[universal-argument] prefixes, negate the meaning of
12295 `org-keep-stored-link-after-insertion'."
12296 (interactive "P")
12297 (let* ((wcf (current-window-configuration))
12298 (region (if (org-region-active-p)
12299 (buffer-substring (region-beginning) (region-end))))
12300 (remove (and region (list (region-beginning) (region-end))))
12301 (desc region)
12302 tmphist ; byte-compile incorrectly complains about this
12303 link entry file)
12304 (cond
12305 ((org-in-regexp org-bracket-link-regexp 1)
12306 ;; We do have a link at point, and we are going to edit it.
12307 (setq remove (list (match-beginning 0) (match-end 0)))
12308 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12309 (setq link (read-string "Link: "
12310 (org-link-unescape
12311 (org-match-string-no-properties 1)))))
12312 ((or (org-in-regexp org-angle-link-re)
12313 (org-in-regexp org-plain-link-re))
12314 ;; Convert to bracket link
12315 (setq remove (list (match-beginning 0) (match-end 0))
12316 link (read-string "Link: "
12317 (org-remove-angle-brackets (match-string 0)))))
12318 ((equal complete-file '(4))
12319 ;; Completing read for file names.
12320 (setq file (read-file-name "File: "))
12321 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12322 (pwd1 (file-name-as-directory (abbreviate-file-name
12323 (expand-file-name ".")))))
12324 (cond
12325 ((equal complete-file '(16))
12326 (setq link (org-make-link
12327 "file:"
12328 (abbreviate-file-name (expand-file-name file)))))
12329 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12330 (setq link (org-make-link "file:" (match-string 1 file))))
12331 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12332 (expand-file-name file))
12333 (setq link (org-make-link
12334 "file:" (match-string 1 (expand-file-name file)))))
12335 (t (setq link (org-make-link "file:" file))))))
12337 ;; Read link, with completion for stored links.
12338 (with-output-to-temp-buffer "*Org Links*"
12339 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12340 (when org-stored-links
12341 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12342 (princ (mapconcat
12343 (lambda (x)
12344 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12345 (reverse org-stored-links) "\n"))))
12346 (let ((cw (selected-window)))
12347 (select-window (get-buffer-window "*Org Links*"))
12348 (shrink-window-if-larger-than-buffer)
12349 (setq truncate-lines t)
12350 (select-window cw))
12351 ;; Fake a link history, containing the stored links.
12352 (setq tmphist (append (mapcar 'car org-stored-links)
12353 org-insert-link-history))
12354 (unwind-protect
12355 (setq link (org-completing-read
12356 "Link: "
12357 (append
12358 (mapcar (lambda (x) (list (concat (car x) ":")))
12359 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12360 (mapcar (lambda (x) (list (concat x ":")))
12361 org-link-types))
12362 nil nil nil
12363 'tmphist
12364 (or (car (car org-stored-links)))))
12365 (set-window-configuration wcf)
12366 (kill-buffer "*Org Links*"))
12367 (setq entry (assoc link org-stored-links))
12368 (or entry (push link org-insert-link-history))
12369 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12370 (not org-keep-stored-link-after-insertion))
12371 (setq org-stored-links (delq (assoc link org-stored-links)
12372 org-stored-links)))
12373 (setq desc (or desc (nth 1 entry)))))
12375 (if (string-match org-plain-link-re link)
12376 ;; URL-like link, normalize the use of angular brackets.
12377 (setq link (org-make-link (org-remove-angle-brackets link))))
12379 ;; Check if we are linking to the current file with a search option
12380 ;; If yes, simplify the link by using only the search option.
12381 (when (and buffer-file-name
12382 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12383 (let* ((path (match-string 1 link))
12384 (case-fold-search nil)
12385 (search (match-string 2 link)))
12386 (save-match-data
12387 (if (equal (file-truename buffer-file-name) (file-truename path))
12388 ;; We are linking to this same file, with a search option
12389 (setq link search)))))
12391 ;; Check if we can/should use a relative path. If yes, simplify the link
12392 (when (string-match "\\<file:\\(.*\\)" link)
12393 (let* ((path (match-string 1 link))
12394 (origpath path)
12395 (desc-is-link (equal link desc))
12396 (case-fold-search nil))
12397 (cond
12398 ((eq org-link-file-path-type 'absolute)
12399 (setq path (abbreviate-file-name (expand-file-name path))))
12400 ((eq org-link-file-path-type 'noabbrev)
12401 (setq path (expand-file-name path)))
12402 ((eq org-link-file-path-type 'relative)
12403 (setq path (file-relative-name path)))
12405 (save-match-data
12406 (if (string-match (concat "^" (regexp-quote
12407 (file-name-as-directory
12408 (expand-file-name "."))))
12409 (expand-file-name path))
12410 ;; We are linking a file with relative path name.
12411 (setq path (substring (expand-file-name path)
12412 (match-end 0)))))))
12413 (setq link (concat "file:" path))
12414 (if (equal desc origpath)
12415 (setq desc path))))
12417 (setq desc (read-string "Description: " desc))
12418 (unless (string-match "\\S-" desc) (setq desc nil))
12419 (if remove (apply 'delete-region remove))
12420 (insert (org-make-link-string link desc))))
12422 (defun org-completing-read (&rest args)
12423 (let ((minibuffer-local-completion-map
12424 (copy-keymap minibuffer-local-completion-map)))
12425 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12426 (apply 'completing-read args)))
12428 ;;; Opening/following a link
12429 (defvar org-link-search-failed nil)
12431 (defun org-next-link ()
12432 "Move forward to the next link.
12433 If the link is in hidden text, expose it."
12434 (interactive)
12435 (when (and org-link-search-failed (eq this-command last-command))
12436 (goto-char (point-min))
12437 (message "Link search wrapped back to beginning of buffer"))
12438 (setq org-link-search-failed nil)
12439 (let* ((pos (point))
12440 (ct (org-context))
12441 (a (assoc :link ct)))
12442 (if a (goto-char (nth 2 a)))
12443 (if (re-search-forward org-any-link-re nil t)
12444 (progn
12445 (goto-char (match-beginning 0))
12446 (if (org-invisible-p) (org-show-context)))
12447 (goto-char pos)
12448 (setq org-link-search-failed t)
12449 (error "No further link found"))))
12451 (defun org-previous-link ()
12452 "Move backward to the previous link.
12453 If the link is in hidden text, expose it."
12454 (interactive)
12455 (when (and org-link-search-failed (eq this-command last-command))
12456 (goto-char (point-max))
12457 (message "Link search wrapped back to end of buffer"))
12458 (setq org-link-search-failed nil)
12459 (let* ((pos (point))
12460 (ct (org-context))
12461 (a (assoc :link ct)))
12462 (if a (goto-char (nth 1 a)))
12463 (if (re-search-backward org-any-link-re nil t)
12464 (progn
12465 (goto-char (match-beginning 0))
12466 (if (org-invisible-p) (org-show-context)))
12467 (goto-char pos)
12468 (setq org-link-search-failed t)
12469 (error "No further link found"))))
12471 (defun org-find-file-at-mouse (ev)
12472 "Open file link or URL at mouse."
12473 (interactive "e")
12474 (mouse-set-point ev)
12475 (org-open-at-point 'in-emacs))
12477 (defun org-open-at-mouse (ev)
12478 "Open file link or URL at mouse."
12479 (interactive "e")
12480 (mouse-set-point ev)
12481 (org-open-at-point))
12483 (defvar org-window-config-before-follow-link nil
12484 "The window configuration before following a link.
12485 This is saved in case the need arises to restore it.")
12487 (defvar org-open-link-marker (make-marker)
12488 "Marker pointing to the location where `org-open-at-point; was called.")
12490 ;;;###autoload
12491 (defun org-open-at-point-global ()
12492 "Follow a link like Org-mode does.
12493 This command can be called in any mode to follow a link that has
12494 Org-mode syntax."
12495 (interactive)
12496 (org-run-like-in-org-mode 'org-open-at-point))
12498 (defun org-open-at-point (&optional in-emacs)
12499 "Open link at or after point.
12500 If there is no link at point, this function will search forward up to
12501 the end of the current subtree.
12502 Normally, files will be opened by an appropriate application. If the
12503 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12504 (interactive "P")
12505 (catch 'abort
12506 (move-marker org-open-link-marker (point))
12507 (setq org-window-config-before-follow-link (current-window-configuration))
12508 (org-remove-occur-highlights nil nil t)
12509 (if (org-at-timestamp-p t)
12510 (org-follow-timestamp-link)
12511 (let (type path link line search (pos (point)))
12512 (catch 'match
12513 (save-excursion
12514 (skip-chars-forward "^]\n\r")
12515 (when (org-in-regexp org-bracket-link-regexp)
12516 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12517 (while (string-match " *\n *" link)
12518 (setq link (replace-match " " t t link)))
12519 (setq link (org-link-expand-abbrev link))
12520 (if (string-match org-link-re-with-space2 link)
12521 (setq type (match-string 1 link) path (match-string 2 link))
12522 (setq type "thisfile" path link))
12523 (throw 'match t)))
12525 (when (get-text-property (point) 'org-linked-text)
12526 (setq type "thisfile"
12527 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12528 (1+ (point)) (point))
12529 path (buffer-substring
12530 (previous-single-property-change pos 'org-linked-text)
12531 (next-single-property-change pos 'org-linked-text)))
12532 (throw 'match t))
12534 (save-excursion
12535 (when (or (org-in-regexp org-angle-link-re)
12536 (org-in-regexp org-plain-link-re))
12537 (setq type (match-string 1) path (match-string 2))
12538 (throw 'match t)))
12539 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12540 (setq type "tree-match"
12541 path (match-string 1))
12542 (throw 'match t))
12543 (save-excursion
12544 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12545 (setq type "tags"
12546 path (match-string 1))
12547 (while (string-match ":" path)
12548 (setq path (replace-match "+" t t path)))
12549 (throw 'match t))))
12550 (unless path
12551 (error "No link found"))
12552 ;; Remove any trailing spaces in path
12553 (if (string-match " +\\'" path)
12554 (setq path (replace-match "" t t path)))
12556 (cond
12558 ((assoc type org-link-protocols)
12559 (funcall (nth 1 (assoc type org-link-protocols)) path))
12561 ((equal type "mailto")
12562 (let ((cmd (car org-link-mailto-program))
12563 (args (cdr org-link-mailto-program)) args1
12564 (address path) (subject "") a)
12565 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12566 (setq address (match-string 1 path)
12567 subject (org-link-escape (match-string 2 path))))
12568 (while args
12569 (cond
12570 ((not (stringp (car args))) (push (pop args) args1))
12571 (t (setq a (pop args))
12572 (if (string-match "%a" a)
12573 (setq a (replace-match address t t a)))
12574 (if (string-match "%s" a)
12575 (setq a (replace-match subject t t a)))
12576 (push a args1))))
12577 (apply cmd (nreverse args1))))
12579 ((member type '("http" "https" "ftp" "news"))
12580 (browse-url (concat type ":" (org-link-escape
12581 path org-link-escape-chars-browser))))
12583 ((member type '("message"))
12584 (browse-url (concat type ":" path)))
12586 ((string= type "tags")
12587 (org-tags-view in-emacs path))
12588 ((string= type "thisfile")
12589 (if in-emacs
12590 (switch-to-buffer-other-window
12591 (org-get-buffer-for-internal-link (current-buffer)))
12592 (org-mark-ring-push))
12593 (let ((cmd `(org-link-search
12594 ,path
12595 ,(cond ((equal in-emacs '(4)) 'occur)
12596 ((equal in-emacs '(16)) 'org-occur)
12597 (t nil))
12598 ,pos)))
12599 (condition-case nil (eval cmd)
12600 (error (progn (widen) (eval cmd))))))
12602 ((string= type "tree-match")
12603 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12605 ((string= type "file")
12606 (if (string-match "::\\([0-9]+\\)\\'" path)
12607 (setq line (string-to-number (match-string 1 path))
12608 path (substring path 0 (match-beginning 0)))
12609 (if (string-match "::\\(.+\\)\\'" path)
12610 (setq search (match-string 1 path)
12611 path (substring path 0 (match-beginning 0)))))
12612 (if (string-match "[*?{]" (file-name-nondirectory path))
12613 (dired path)
12614 (org-open-file path in-emacs line search)))
12616 ((string= type "news")
12617 (org-follow-gnus-link path))
12619 ((string= type "bbdb")
12620 (org-follow-bbdb-link path))
12622 ((string= type "info")
12623 (org-follow-info-link path))
12625 ((string= type "gnus")
12626 (let (group article)
12627 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12628 (error "Error in Gnus link"))
12629 (setq group (match-string 1 path)
12630 article (match-string 3 path))
12631 (org-follow-gnus-link group article)))
12633 ((string= type "vm")
12634 (let (folder article)
12635 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12636 (error "Error in VM link"))
12637 (setq folder (match-string 1 path)
12638 article (match-string 3 path))
12639 ;; in-emacs is the prefix arg, will be interpreted as read-only
12640 (org-follow-vm-link folder article in-emacs)))
12642 ((string= type "wl")
12643 (let (folder article)
12644 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12645 (error "Error in Wanderlust link"))
12646 (setq folder (match-string 1 path)
12647 article (match-string 3 path))
12648 (org-follow-wl-link folder article)))
12650 ((string= type "mhe")
12651 (let (folder article)
12652 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12653 (error "Error in MHE link"))
12654 (setq folder (match-string 1 path)
12655 article (match-string 3 path))
12656 (org-follow-mhe-link folder article)))
12658 ((string= type "rmail")
12659 (let (folder article)
12660 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12661 (error "Error in RMAIL link"))
12662 (setq folder (match-string 1 path)
12663 article (match-string 3 path))
12664 (org-follow-rmail-link folder article)))
12666 ((string= type "shell")
12667 (let ((cmd path))
12668 (if (or (not org-confirm-shell-link-function)
12669 (funcall org-confirm-shell-link-function
12670 (format "Execute \"%s\" in shell? "
12671 (org-add-props cmd nil
12672 'face 'org-warning))))
12673 (progn
12674 (message "Executing %s" cmd)
12675 (shell-command cmd))
12676 (error "Abort"))))
12678 ((string= type "elisp")
12679 (let ((cmd path))
12680 (if (or (not org-confirm-elisp-link-function)
12681 (funcall org-confirm-elisp-link-function
12682 (format "Execute \"%s\" as elisp? "
12683 (org-add-props cmd nil
12684 'face 'org-warning))))
12685 (message "%s => %s" cmd (eval (read cmd)))
12686 (error "Abort"))))
12689 (browse-url-at-point)))))
12690 (move-marker org-open-link-marker nil)))
12692 ;;; File search
12694 (defvar org-create-file-search-functions nil
12695 "List of functions to construct the right search string for a file link.
12696 These functions are called in turn with point at the location to
12697 which the link should point.
12699 A function in the hook should first test if it would like to
12700 handle this file type, for example by checking the major-mode or
12701 the file extension. If it decides not to handle this file, it
12702 should just return nil to give other functions a chance. If it
12703 does handle the file, it must return the search string to be used
12704 when following the link. The search string will be part of the
12705 file link, given after a double colon, and `org-open-at-point'
12706 will automatically search for it. If special measures must be
12707 taken to make the search successful, another function should be
12708 added to the companion hook `org-execute-file-search-functions',
12709 which see.
12711 A function in this hook may also use `setq' to set the variable
12712 `description' to provide a suggestion for the descriptive text to
12713 be used for this link when it gets inserted into an Org-mode
12714 buffer with \\[org-insert-link].")
12716 (defvar org-execute-file-search-functions nil
12717 "List of functions to execute a file search triggered by a link.
12719 Functions added to this hook must accept a single argument, the
12720 search string that was part of the file link, the part after the
12721 double colon. The function must first check if it would like to
12722 handle this search, for example by checking the major-mode or the
12723 file extension. If it decides not to handle this search, it
12724 should just return nil to give other functions a chance. If it
12725 does handle the search, it must return a non-nil value to keep
12726 other functions from trying.
12728 Each function can access the current prefix argument through the
12729 variable `current-prefix-argument'. Note that a single prefix is
12730 used to force opening a link in Emacs, so it may be good to only
12731 use a numeric or double prefix to guide the search function.
12733 In case this is needed, a function in this hook can also restore
12734 the window configuration before `org-open-at-point' was called using:
12736 (set-window-configuration org-window-config-before-follow-link)")
12738 (defun org-link-search (s &optional type avoid-pos)
12739 "Search for a link search option.
12740 If S is surrounded by forward slashes, it is interpreted as a
12741 regular expression. In org-mode files, this will create an `org-occur'
12742 sparse tree. In ordinary files, `occur' will be used to list matches.
12743 If the current buffer is in `dired-mode', grep will be used to search
12744 in all files. If AVOID-POS is given, ignore matches near that position."
12745 (let ((case-fold-search t)
12746 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12747 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12748 (append '(("") (" ") ("\t") ("\n"))
12749 org-emphasis-alist)
12750 "\\|") "\\)"))
12751 (pos (point))
12752 (pre "") (post "")
12753 words re0 re1 re2 re3 re4 re5 re2a reall)
12754 (cond
12755 ;; First check if there are any special
12756 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12757 ;; Now try the builtin stuff
12758 ((save-excursion
12759 (goto-char (point-min))
12760 (and
12761 (re-search-forward
12762 (concat "<<" (regexp-quote s0) ">>") nil t)
12763 (setq pos (match-beginning 0))))
12764 ;; There is an exact target for this
12765 (goto-char pos))
12766 ((string-match "^/\\(.*\\)/$" s)
12767 ;; A regular expression
12768 (cond
12769 ((org-mode-p)
12770 (org-occur (match-string 1 s)))
12771 ;;((eq major-mode 'dired-mode)
12772 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12773 (t (org-do-occur (match-string 1 s)))))
12775 ;; A normal search strings
12776 (when (equal (string-to-char s) ?*)
12777 ;; Anchor on headlines, post may include tags.
12778 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12779 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12780 s (substring s 1)))
12781 (remove-text-properties
12782 0 (length s)
12783 '(face nil mouse-face nil keymap nil fontified nil) s)
12784 ;; Make a series of regular expressions to find a match
12785 (setq words (org-split-string s "[ \n\r\t]+")
12786 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12787 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12788 "\\)" markers)
12789 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12790 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12791 re1 (concat pre re2 post)
12792 re3 (concat pre re4 post)
12793 re5 (concat pre ".*" re4)
12794 re2 (concat pre re2)
12795 re2a (concat pre re2a)
12796 re4 (concat pre re4)
12797 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12798 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12799 re5 "\\)"
12801 (cond
12802 ((eq type 'org-occur) (org-occur reall))
12803 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12804 (t (goto-char (point-min))
12805 (if (or (org-search-not-self 1 re0 nil t)
12806 (org-search-not-self 1 re1 nil t)
12807 (org-search-not-self 1 re2 nil t)
12808 (org-search-not-self 1 re2a nil t)
12809 (org-search-not-self 1 re3 nil t)
12810 (org-search-not-self 1 re4 nil t)
12811 (org-search-not-self 1 re5 nil t)
12813 (goto-char (match-beginning 1))
12814 (goto-char pos)
12815 (error "No match")))))
12817 ;; Normal string-search
12818 (goto-char (point-min))
12819 (if (search-forward s nil t)
12820 (goto-char (match-beginning 0))
12821 (error "No match"))))
12822 (and (org-mode-p) (org-show-context 'link-search))))
12824 (defun org-search-not-self (group &rest args)
12825 "Execute `re-search-forward', but only accept matches that do not
12826 enclose the position of `org-open-link-marker'."
12827 (let ((m org-open-link-marker))
12828 (catch 'exit
12829 (while (apply 're-search-forward args)
12830 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12831 (goto-char (match-end group))
12832 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12833 (> (match-beginning 0) (marker-position m))
12834 (< (match-end 0) (marker-position m)))
12835 (save-match-data
12836 (or (not (org-in-regexp
12837 org-bracket-link-analytic-regexp 1))
12838 (not (match-end 4)) ; no description
12839 (and (<= (match-beginning 4) (point))
12840 (>= (match-end 4) (point))))))
12841 (throw 'exit (point))))))))
12843 (defun org-get-buffer-for-internal-link (buffer)
12844 "Return a buffer to be used for displaying the link target of internal links."
12845 (cond
12846 ((not org-display-internal-link-with-indirect-buffer)
12847 buffer)
12848 ((string-match "(Clone)$" (buffer-name buffer))
12849 (message "Buffer is already a clone, not making another one")
12850 ;; we also do not modify visibility in this case
12851 buffer)
12852 (t ; make a new indirect buffer for displaying the link
12853 (let* ((bn (buffer-name buffer))
12854 (ibn (concat bn "(Clone)"))
12855 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12856 (with-current-buffer ib (org-overview))
12857 ib))))
12859 (defun org-do-occur (regexp &optional cleanup)
12860 "Call the Emacs command `occur'.
12861 If CLEANUP is non-nil, remove the printout of the regular expression
12862 in the *Occur* buffer. This is useful if the regex is long and not useful
12863 to read."
12864 (occur regexp)
12865 (when cleanup
12866 (let ((cwin (selected-window)) win beg end)
12867 (when (setq win (get-buffer-window "*Occur*"))
12868 (select-window win))
12869 (goto-char (point-min))
12870 (when (re-search-forward "match[a-z]+" nil t)
12871 (setq beg (match-end 0))
12872 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12873 (setq end (1- (match-beginning 0)))))
12874 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12875 (goto-char (point-min))
12876 (select-window cwin))))
12878 ;;; The mark ring for links jumps
12880 (defvar org-mark-ring nil
12881 "Mark ring for positions before jumps in Org-mode.")
12882 (defvar org-mark-ring-last-goto nil
12883 "Last position in the mark ring used to go back.")
12884 ;; Fill and close the ring
12885 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12886 (loop for i from 1 to org-mark-ring-length do
12887 (push (make-marker) org-mark-ring))
12888 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12889 org-mark-ring)
12891 (defun org-mark-ring-push (&optional pos buffer)
12892 "Put the current position or POS into the mark ring and rotate it."
12893 (interactive)
12894 (setq pos (or pos (point)))
12895 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12896 (move-marker (car org-mark-ring)
12897 (or pos (point))
12898 (or buffer (current-buffer)))
12899 (message "%s"
12900 (substitute-command-keys
12901 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12903 (defun org-mark-ring-goto (&optional n)
12904 "Jump to the previous position in the mark ring.
12905 With prefix arg N, jump back that many stored positions. When
12906 called several times in succession, walk through the entire ring.
12907 Org-mode commands jumping to a different position in the current file,
12908 or to another Org-mode file, automatically push the old position
12909 onto the ring."
12910 (interactive "p")
12911 (let (p m)
12912 (if (eq last-command this-command)
12913 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12914 (setq p org-mark-ring))
12915 (setq org-mark-ring-last-goto p)
12916 (setq m (car p))
12917 (switch-to-buffer (marker-buffer m))
12918 (goto-char m)
12919 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12921 (defun org-remove-angle-brackets (s)
12922 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12923 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12925 (defun org-add-angle-brackets (s)
12926 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12927 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12930 ;;; Following specific links
12932 (defun org-follow-timestamp-link ()
12933 (cond
12934 ((org-at-date-range-p t)
12935 (let ((org-agenda-start-on-weekday)
12936 (t1 (match-string 1))
12937 (t2 (match-string 2)))
12938 (setq t1 (time-to-days (org-time-string-to-time t1))
12939 t2 (time-to-days (org-time-string-to-time t2)))
12940 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12941 ((org-at-timestamp-p t)
12942 (org-agenda-list nil (time-to-days (org-time-string-to-time
12943 (substring (match-string 1) 0 10)))
12945 (t (error "This should not happen"))))
12948 (defun org-follow-bbdb-link (name)
12949 "Follow a BBDB link to NAME."
12950 (require 'bbdb)
12951 (let ((inhibit-redisplay (not debug-on-error))
12952 (bbdb-electric-p nil))
12953 (catch 'exit
12954 ;; Exact match on name
12955 (bbdb-name (concat "\\`" name "\\'") nil)
12956 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12957 ;; Exact match on name
12958 (bbdb-company (concat "\\`" name "\\'") nil)
12959 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12960 ;; Partial match on name
12961 (bbdb-name name nil)
12962 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12963 ;; Partial match on company
12964 (bbdb-company name nil)
12965 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12966 ;; General match including network address and notes
12967 (bbdb name nil)
12968 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12969 (delete-window (get-buffer-window "*BBDB*"))
12970 (error "No matching BBDB record")))))
12972 (defun org-follow-info-link (name)
12973 "Follow an info file & node link to NAME."
12974 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12975 (string-match "\\(.*\\)" name))
12976 (progn
12977 (require 'info)
12978 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12979 (Info-find-node (match-string 1 name) (match-string 2 name))
12980 (Info-find-node (match-string 1 name) "Top")))
12981 (message "Could not open: %s" name)))
12983 (defun org-follow-gnus-link (&optional group article)
12984 "Follow a Gnus link to GROUP and ARTICLE."
12985 (require 'gnus)
12986 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12987 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12988 (cond ((and group article)
12989 (gnus-group-read-group 1 nil group)
12990 (gnus-summary-goto-article (string-to-number article) nil t))
12991 (group (gnus-group-jump-to-group group))))
12993 (defun org-follow-vm-link (&optional folder article readonly)
12994 "Follow a VM link to FOLDER and ARTICLE."
12995 (require 'vm)
12996 (setq article (org-add-angle-brackets article))
12997 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12998 ;; ange-ftp or efs or tramp access
12999 (let ((user (or (match-string 1 folder) (user-login-name)))
13000 (host (match-string 2 folder))
13001 (file (match-string 3 folder)))
13002 (cond
13003 ((featurep 'tramp)
13004 ;; use tramp to access the file
13005 (if (featurep 'xemacs)
13006 (setq folder (format "[%s@%s]%s" user host file))
13007 (setq folder (format "/%s@%s:%s" user host file))))
13009 ;; use ange-ftp or efs
13010 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13011 (setq folder (format "/%s@%s:%s" user host file))))))
13012 (when folder
13013 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13014 (sit-for 0.1)
13015 (when article
13016 (vm-select-folder-buffer)
13017 (widen)
13018 (let ((case-fold-search t))
13019 (goto-char (point-min))
13020 (if (not (re-search-forward
13021 (concat "^" "message-id: *" (regexp-quote article))))
13022 (error "Could not find the specified message in this folder"))
13023 (vm-isearch-update)
13024 (vm-isearch-narrow)
13025 (vm-beginning-of-message)
13026 (vm-summarize)))))
13028 (defun org-follow-wl-link (folder article)
13029 "Follow a Wanderlust link to FOLDER and ARTICLE."
13030 (if (and (string= folder "%")
13031 article
13032 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13033 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13034 ;; Thus, we recompose folder and article ids.
13035 (setq folder (format "%s#%s" folder (match-string 1 article))
13036 article (match-string 3 article)))
13037 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13038 (error "No such folder: %s" folder))
13039 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13040 (and article
13041 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13042 (wl-summary-redisplay)))
13044 (defun org-follow-rmail-link (folder article)
13045 "Follow an RMAIL link to FOLDER and ARTICLE."
13046 (setq article (org-add-angle-brackets article))
13047 (let (message-number)
13048 (save-excursion
13049 (save-window-excursion
13050 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13051 (setq message-number
13052 (save-restriction
13053 (widen)
13054 (goto-char (point-max))
13055 (if (re-search-backward
13056 (concat "^Message-ID:\\s-+" (regexp-quote
13057 (or article "")))
13058 nil t)
13059 (rmail-what-message))))))
13060 (if message-number
13061 (progn
13062 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13063 (rmail-show-message message-number)
13064 message-number)
13065 (error "Message not found"))))
13067 ;;; mh-e integration based on planner-mode
13068 (defun org-mhe-get-message-real-folder ()
13069 "Return the name of the current message real folder, so if you use
13070 sequences, it will now work."
13071 (save-excursion
13072 (let* ((folder
13073 (if (equal major-mode 'mh-folder-mode)
13074 mh-current-folder
13075 ;; Refer to the show buffer
13076 mh-show-folder-buffer))
13077 (end-index
13078 (if (boundp 'mh-index-folder)
13079 (min (length mh-index-folder) (length folder))))
13081 ;; a simple test on mh-index-data does not work, because
13082 ;; mh-index-data is always nil in a show buffer.
13083 (if (and (boundp 'mh-index-folder)
13084 (string= mh-index-folder (substring folder 0 end-index)))
13085 (if (equal major-mode 'mh-show-mode)
13086 (save-window-excursion
13087 (let (pop-up-frames)
13088 (when (buffer-live-p (get-buffer folder))
13089 (progn
13090 (pop-to-buffer folder)
13091 (org-mhe-get-message-folder-from-index)
13094 (org-mhe-get-message-folder-from-index)
13096 folder
13100 (defun org-mhe-get-message-folder-from-index ()
13101 "Returns the name of the message folder in a index folder buffer."
13102 (save-excursion
13103 (mh-index-previous-folder)
13104 (re-search-forward "^\\(+.*\\)$" nil t)
13105 (message "%s" (match-string 1))))
13107 (defun org-mhe-get-message-folder ()
13108 "Return the name of the current message folder. Be careful if you
13109 use sequences."
13110 (save-excursion
13111 (if (equal major-mode 'mh-folder-mode)
13112 mh-current-folder
13113 ;; Refer to the show buffer
13114 mh-show-folder-buffer)))
13116 (defun org-mhe-get-message-num ()
13117 "Return the number of the current message. Be careful if you
13118 use sequences."
13119 (save-excursion
13120 (if (equal major-mode 'mh-folder-mode)
13121 (mh-get-msg-num nil)
13122 ;; Refer to the show buffer
13123 (mh-show-buffer-message-number))))
13125 (defun org-mhe-get-header (header)
13126 "Return a header of the message in folder mode. This will create a
13127 show buffer for the corresponding message. If you have a more clever
13128 idea..."
13129 (let* ((folder (org-mhe-get-message-folder))
13130 (num (org-mhe-get-message-num))
13131 (buffer (get-buffer-create (concat "show-" folder)))
13132 (header-field))
13133 (with-current-buffer buffer
13134 (mh-display-msg num folder)
13135 (if (equal major-mode 'mh-folder-mode)
13136 (mh-header-display)
13137 (mh-show-header-display))
13138 (set-buffer buffer)
13139 (setq header-field (mh-get-header-field header))
13140 (if (equal major-mode 'mh-folder-mode)
13141 (mh-show)
13142 (mh-show-show))
13143 header-field)))
13145 (defun org-follow-mhe-link (folder article)
13146 "Follow an MHE link to FOLDER and ARTICLE.
13147 If ARTICLE is nil FOLDER is shown. If the configuration variable
13148 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13149 ARTICLE is searched in all folders. Indexed searches (swish++,
13150 namazu, and others supported by MH-E) will always search in all
13151 folders."
13152 (require 'mh-e)
13153 (require 'mh-search)
13154 (require 'mh-utils)
13155 (mh-find-path)
13156 (if (not article)
13157 (mh-visit-folder (mh-normalize-folder-name folder))
13158 (setq article (org-add-angle-brackets article))
13159 (mh-search-choose)
13160 (if (equal mh-searcher 'pick)
13161 (progn
13162 (mh-search folder (list "--message-id" article))
13163 (when (and org-mhe-search-all-folders
13164 (not (org-mhe-get-message-real-folder)))
13165 (kill-this-buffer)
13166 (mh-search "+" (list "--message-id" article))))
13167 (mh-search "+" article))
13168 (if (org-mhe-get-message-real-folder)
13169 (mh-show-msg 1)
13170 (kill-this-buffer)
13171 (error "Message not found"))))
13173 ;;; BibTeX links
13175 ;; Use the custom search meachnism to construct and use search strings for
13176 ;; file links to BibTeX database entries.
13178 (defun org-create-file-search-in-bibtex ()
13179 "Create the search string and description for a BibTeX database entry."
13180 (when (eq major-mode 'bibtex-mode)
13181 ;; yes, we want to construct this search string.
13182 ;; Make a good description for this entry, using names, year and the title
13183 ;; Put it into the `description' variable which is dynamically scoped.
13184 (let ((bibtex-autokey-names 1)
13185 (bibtex-autokey-names-stretch 1)
13186 (bibtex-autokey-name-case-convert-function 'identity)
13187 (bibtex-autokey-name-separator " & ")
13188 (bibtex-autokey-additional-names " et al.")
13189 (bibtex-autokey-year-length 4)
13190 (bibtex-autokey-name-year-separator " ")
13191 (bibtex-autokey-titlewords 3)
13192 (bibtex-autokey-titleword-separator " ")
13193 (bibtex-autokey-titleword-case-convert-function 'identity)
13194 (bibtex-autokey-titleword-length 'infty)
13195 (bibtex-autokey-year-title-separator ": "))
13196 (setq description (bibtex-generate-autokey)))
13197 ;; Now parse the entry, get the key and return it.
13198 (save-excursion
13199 (bibtex-beginning-of-entry)
13200 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13202 (defun org-execute-file-search-in-bibtex (s)
13203 "Find the link search string S as a key for a database entry."
13204 (when (eq major-mode 'bibtex-mode)
13205 ;; Yes, we want to do the search in this file.
13206 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13207 (goto-char (point-min))
13208 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13209 (regexp-quote s) "[ \t\n]*,") nil t)
13210 (goto-char (match-beginning 0)))
13211 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13212 ;; Use double prefix to indicate that any web link should be browsed
13213 (let ((b (current-buffer)) (p (point)))
13214 ;; Restore the window configuration because we just use the web link
13215 (set-window-configuration org-window-config-before-follow-link)
13216 (save-excursion (set-buffer b) (goto-char p)
13217 (bibtex-url)))
13218 (recenter 0)) ; Move entry start to beginning of window
13219 ;; return t to indicate that the search is done.
13222 ;; Finally add the functions to the right hooks.
13223 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13224 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13226 ;; end of Bibtex link setup
13228 ;;; Following file links
13230 (defun org-open-file (path &optional in-emacs line search)
13231 "Open the file at PATH.
13232 First, this expands any special file name abbreviations. Then the
13233 configuration variable `org-file-apps' is checked if it contains an
13234 entry for this file type, and if yes, the corresponding command is launched.
13235 If no application is found, Emacs simply visits the file.
13236 With optional argument IN-EMACS, Emacs will visit the file.
13237 Optional LINE specifies a line to go to, optional SEARCH a string to
13238 search for. If LINE or SEARCH is given, the file will always be
13239 opened in Emacs.
13240 If the file does not exist, an error is thrown."
13241 (setq in-emacs (or in-emacs line search))
13242 (let* ((file (if (equal path "")
13243 buffer-file-name
13244 (substitute-in-file-name (expand-file-name path))))
13245 (apps (append org-file-apps (org-default-apps)))
13246 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13247 (dirp (if remp nil (file-directory-p file)))
13248 (dfile (downcase file))
13249 (old-buffer (current-buffer))
13250 (old-pos (point))
13251 (old-mode major-mode)
13252 ext cmd)
13253 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13254 (setq ext (match-string 1 dfile))
13255 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13256 (setq ext (match-string 1 dfile))))
13257 (if in-emacs
13258 (setq cmd 'emacs)
13259 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13260 (and dirp (cdr (assoc 'directory apps)))
13261 (cdr (assoc ext apps))
13262 (cdr (assoc t apps)))))
13263 (when (eq cmd 'mailcap)
13264 (require 'mailcap)
13265 (mailcap-parse-mailcaps)
13266 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13267 (command (mailcap-mime-info mime-type)))
13268 (if (stringp command)
13269 (setq cmd command)
13270 (setq cmd 'emacs))))
13271 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13272 (not (file-exists-p file))
13273 (not org-open-non-existing-files))
13274 (error "No such file: %s" file))
13275 (cond
13276 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13277 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13278 (while (string-match "['\"]%s['\"]" cmd)
13279 (setq cmd (replace-match "%s" t t cmd)))
13280 (while (string-match "%s" cmd)
13281 (setq cmd (replace-match
13282 (save-match-data (shell-quote-argument file))
13283 t t cmd)))
13284 (save-window-excursion
13285 (start-process-shell-command cmd nil cmd)))
13286 ((or (stringp cmd)
13287 (eq cmd 'emacs))
13288 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13289 (widen)
13290 (if line (goto-line line)
13291 (if search (org-link-search search))))
13292 ((consp cmd)
13293 (eval cmd))
13294 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13295 (and (org-mode-p) (eq old-mode 'org-mode)
13296 (or (not (equal old-buffer (current-buffer)))
13297 (not (equal old-pos (point))))
13298 (org-mark-ring-push old-pos old-buffer))))
13300 (defun org-default-apps ()
13301 "Return the default applications for this operating system."
13302 (cond
13303 ((eq system-type 'darwin)
13304 org-file-apps-defaults-macosx)
13305 ((eq system-type 'windows-nt)
13306 org-file-apps-defaults-windowsnt)
13307 (t org-file-apps-defaults-gnu)))
13309 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13310 (defun org-file-remote-p (file)
13311 "Test whether FILE specifies a location on a remote system.
13312 Return non-nil if the location is indeed remote.
13314 For example, the filename \"/user@host:/foo\" specifies a location
13315 on the system \"/user@host:\"."
13316 (cond ((fboundp 'file-remote-p)
13317 (file-remote-p file))
13318 ((fboundp 'tramp-handle-file-remote-p)
13319 (tramp-handle-file-remote-p file))
13320 ((and (boundp 'ange-ftp-name-format)
13321 (string-match (car ange-ftp-name-format) file))
13323 (t nil)))
13326 ;;;; Hooks for remember.el, and refiling
13328 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13329 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13331 ;;;###autoload
13332 (defun org-remember-insinuate ()
13333 "Setup remember.el for use wiht Org-mode."
13334 (require 'remember)
13335 (setq remember-annotation-functions '(org-remember-annotation))
13336 (setq remember-handler-functions '(org-remember-handler))
13337 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13339 ;;;###autoload
13340 (defun org-remember-annotation ()
13341 "Return a link to the current location as an annotation for remember.el.
13342 If you are using Org-mode files as target for data storage with
13343 remember.el, then the annotations should include a link compatible with the
13344 conventions in Org-mode. This function returns such a link."
13345 (org-store-link nil))
13347 (defconst org-remember-help
13348 "Select a destination location for the note.
13349 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13350 RET on headline -> Store as sublevel entry to current headline
13351 RET at beg-of-buf -> Append to file as level 2 headline
13352 <left>/<right> -> before/after current headline, same headings level")
13354 (defvar org-remember-previous-location nil)
13355 (defvar org-force-remember-template-char) ;; dynamically scoped
13357 (defun org-select-remember-template (&optional use-char)
13358 (when org-remember-templates
13359 (let* ((templates (mapcar (lambda (x)
13360 (if (stringp (car x))
13361 (append (list (nth 1 x) (car x)) (cddr x))
13362 (append (list (car x) "") (cdr x))))
13363 org-remember-templates))
13364 (char (or use-char
13365 (cond
13366 ((= (length templates) 1)
13367 (caar templates))
13368 ((and (boundp 'org-force-remember-template-char)
13369 org-force-remember-template-char)
13370 (if (stringp org-force-remember-template-char)
13371 (string-to-char org-force-remember-template-char)
13372 org-force-remember-template-char))
13374 (message "Select template: %s"
13375 (mapconcat
13376 (lambda (x)
13377 (cond
13378 ((not (string-match "\\S-" (nth 1 x)))
13379 (format "[%c]" (car x)))
13380 ((equal (downcase (car x))
13381 (downcase (aref (nth 1 x) 0)))
13382 (format "[%c]%s" (car x)
13383 (substring (nth 1 x) 1)))
13384 (t (format "[%c]%s" (car x) (nth 1 x)))))
13385 templates " "))
13386 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13387 (when (equal char0 ?\C-g)
13388 (jump-to-register remember-register)
13389 (kill-buffer remember-buffer))
13390 char0))))))
13391 (cddr (assoc char templates)))))
13393 (defvar x-last-selected-text)
13394 (defvar x-last-selected-text-primary)
13396 ;;;###autoload
13397 (defun org-remember-apply-template (&optional use-char skip-interactive)
13398 "Initialize *remember* buffer with template, invoke `org-mode'.
13399 This function should be placed into `remember-mode-hook' and in fact requires
13400 to be run from that hook to function properly."
13401 (if org-remember-templates
13402 (let* ((entry (org-select-remember-template use-char))
13403 (tpl (car entry))
13404 (plist-p (if org-store-link-plist t nil))
13405 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13406 (string-match "\\S-" (nth 1 entry)))
13407 (nth 1 entry)
13408 org-default-notes-file))
13409 (headline (nth 2 entry))
13410 (v-c (or (and (eq window-system 'x)
13411 (fboundp 'x-cut-buffer-or-selection-value)
13412 (x-cut-buffer-or-selection-value))
13413 (org-bound-and-true-p x-last-selected-text)
13414 (org-bound-and-true-p x-last-selected-text-primary)
13415 (and (> (length kill-ring) 0) (current-kill 0))))
13416 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13417 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13418 (v-u (concat "[" (substring v-t 1 -1) "]"))
13419 (v-U (concat "[" (substring v-T 1 -1) "]"))
13420 ;; `initial' and `annotation' are bound in `remember'
13421 (v-i (if (boundp 'initial) initial))
13422 (v-a (if (and (boundp 'annotation) annotation)
13423 (if (equal annotation "[[]]") "" annotation)
13424 ""))
13425 (v-A (if (and v-a
13426 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13427 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13428 v-a))
13429 (v-n user-full-name)
13430 (org-startup-folded nil)
13431 org-time-was-given org-end-time-was-given x
13432 prompt completions char time pos default histvar)
13433 (setq org-store-link-plist
13434 (append (list :annotation v-a :initial v-i)
13435 org-store-link-plist))
13436 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13437 (erase-buffer)
13438 (insert (substitute-command-keys
13439 (format
13440 "## Filing location: Select interactively, default, or last used:
13441 ## %s to select file and header location interactively.
13442 ## %s \"%s\" -> \"* %s\"
13443 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13444 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13445 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13446 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13447 (abbreviate-file-name (or file org-default-notes-file))
13448 (or headline "")
13449 (or (car org-remember-previous-location) "???")
13450 (or (cdr org-remember-previous-location) "???"))))
13451 (insert tpl) (goto-char (point-min))
13452 ;; Simple %-escapes
13453 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13454 (when (and initial (equal (match-string 0) "%i"))
13455 (save-match-data
13456 (let* ((lead (buffer-substring
13457 (point-at-bol) (match-beginning 0))))
13458 (setq v-i (mapconcat 'identity
13459 (org-split-string initial "\n")
13460 (concat "\n" lead))))))
13461 (replace-match
13462 (or (eval (intern (concat "v-" (match-string 1)))) "")
13463 t t))
13465 ;; %[] Insert contents of a file.
13466 (goto-char (point-min))
13467 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13468 (let ((start (match-beginning 0))
13469 (end (match-end 0))
13470 (filename (expand-file-name (match-string 1))))
13471 (goto-char start)
13472 (delete-region start end)
13473 (condition-case error
13474 (insert-file-contents filename)
13475 (error (insert (format "%%![Couldn't insert %s: %s]"
13476 filename error))))))
13477 ;; %() embedded elisp
13478 (goto-char (point-min))
13479 (while (re-search-forward "%\\((.+)\\)" nil t)
13480 (goto-char (match-beginning 0))
13481 (let ((template-start (point)))
13482 (forward-char 1)
13483 (let ((result
13484 (condition-case error
13485 (eval (read (current-buffer)))
13486 (error (format "%%![Error: %s]" error)))))
13487 (delete-region template-start (point))
13488 (insert result))))
13490 ;; From the property list
13491 (when plist-p
13492 (goto-char (point-min))
13493 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13494 (and (setq x (or (plist-get org-store-link-plist
13495 (intern (match-string 1))) ""))
13496 (replace-match x t t))))
13498 ;; Turn on org-mode in the remember buffer, set local variables
13499 (org-mode)
13500 (org-set-local 'org-finish-function 'org-remember-finalize)
13501 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13502 (org-set-local 'org-default-notes-file file))
13503 (if (and headline (stringp headline) (string-match "\\S-" headline))
13504 (org-set-local 'org-remember-default-headline headline))
13505 ;; Interactive template entries
13506 (goto-char (point-min))
13507 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13508 (setq char (if (match-end 3) (match-string 3))
13509 prompt (if (match-end 2) (match-string 2)))
13510 (goto-char (match-beginning 0))
13511 (replace-match "")
13512 (setq completions nil default nil)
13513 (when prompt
13514 (setq completions (org-split-string prompt "|")
13515 prompt (pop completions)
13516 default (car completions)
13517 histvar (intern (concat
13518 "org-remember-template-prompt-history::"
13519 (or prompt "")))
13520 completions (mapcar 'list completions)))
13521 (cond
13522 ((member char '("G" "g"))
13523 (let* ((org-last-tags-completion-table
13524 (org-global-tags-completion-table
13525 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13526 (org-add-colon-after-tag-completion t)
13527 (ins (completing-read
13528 (if prompt (concat prompt ": ") "Tags: ")
13529 'org-tags-completion-function nil nil nil
13530 'org-tags-history)))
13531 (setq ins (mapconcat 'identity
13532 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13533 ":"))
13534 (when (string-match "\\S-" ins)
13535 (or (equal (char-before) ?:) (insert ":"))
13536 (insert ins)
13537 (or (equal (char-after) ?:) (insert ":")))))
13538 (char
13539 (setq org-time-was-given (equal (upcase char) char))
13540 (setq time (org-read-date (equal (upcase char) "U") t nil
13541 prompt))
13542 (org-insert-time-stamp time org-time-was-given
13543 (member char '("u" "U"))
13544 nil nil (list org-end-time-was-given)))
13546 (insert (org-completing-read
13547 (concat (if prompt prompt "Enter string")
13548 (if default (concat " [" default "]"))
13549 ": ")
13550 completions nil nil nil histvar default)))))
13551 (goto-char (point-min))
13552 (if (re-search-forward "%\\?" nil t)
13553 (replace-match "")
13554 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13555 (org-mode)
13556 (org-set-local 'org-finish-function 'org-remember-finalize))
13557 (when (save-excursion
13558 (goto-char (point-min))
13559 (re-search-forward "%!" nil t))
13560 (replace-match "")
13561 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13563 (defun org-remember-finish-immediately ()
13564 "File remember note immediately.
13565 This should be run in `post-command-hook' and will remove itself
13566 from that hook."
13567 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13568 (when org-finish-function
13569 (funcall org-finish-function)))
13571 (defun org-remember-finalize ()
13572 "Finalize the remember process."
13573 (unless (fboundp 'remember-finalize)
13574 (defalias 'remember-finalize 'remember-buffer))
13575 (when (and org-clock-marker
13576 (equal (marker-buffer org-clock-marker) (current-buffer)))
13577 ;; FIXME: test this, this is w/o notetaking!
13578 (let (org-log-done) (org-clock-out)))
13579 (when buffer-file-name
13580 (save-buffer)
13581 (setq buffer-file-name nil))
13582 (remember-finalize))
13584 ;;;###autoload
13585 (defun org-remember (&optional goto org-force-remember-template-char)
13586 "Call `remember'. If this is already a remember buffer, re-apply template.
13587 If there is an active region, make sure remember uses it as initial content
13588 of the remember buffer.
13590 When called interactively with a `C-u' prefix argument GOTO, don't remember
13591 anything, just go to the file/headline where the selected template usually
13592 stores its notes. With a double prefix arg `C-u C-u', go to the last
13593 note stored by remember.
13595 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13596 associated with a template in `org-remember-templates'."
13597 (interactive "P")
13598 (cond
13599 ((equal goto '(4)) (org-go-to-remember-target))
13600 ((equal goto '(16)) (org-remember-goto-last-stored))
13602 (if (memq org-finish-function '(remember-buffer remember-finalize))
13603 (progn
13604 (when (< (length org-remember-templates) 2)
13605 (error "No other template available"))
13606 (erase-buffer)
13607 (let ((annotation (plist-get org-store-link-plist :annotation))
13608 (initial (plist-get org-store-link-plist :initial)))
13609 (org-remember-apply-template))
13610 (message "Press C-c C-c to remember data"))
13611 (if (org-region-active-p)
13612 (remember (buffer-substring (point) (mark)))
13613 (call-interactively 'remember))))))
13615 (defun org-remember-goto-last-stored ()
13616 "Go to the location where the last remember note was stored."
13617 (interactive)
13618 (bookmark-jump "org-remember-last-stored")
13619 (message "This is the last note stored by remember"))
13621 (defun org-go-to-remember-target (&optional template-key)
13622 "Go to the target location of a remember template.
13623 The user is queried for the template."
13624 (interactive)
13625 (let* ((entry (org-select-remember-template template-key))
13626 (file (nth 1 entry))
13627 (heading (nth 2 entry))
13628 visiting)
13629 (unless (and file (stringp file) (string-match "\\S-" file))
13630 (setq file org-default-notes-file))
13631 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13632 (setq heading org-remember-default-headline))
13633 (setq visiting (org-find-base-buffer-visiting file))
13634 (if (not visiting) (find-file-noselect file))
13635 (switch-to-buffer (or visiting (get-file-buffer file)))
13636 (widen)
13637 (goto-char (point-min))
13638 (if (re-search-forward
13639 (concat "^\\*+[ \t]+" (regexp-quote heading)
13640 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13641 nil t)
13642 (goto-char (match-beginning 0))
13643 (error "Target headline not found: %s" heading))))
13645 (defvar org-note-abort nil) ; dynamically scoped
13647 ;;;###autoload
13648 (defun org-remember-handler ()
13649 "Store stuff from remember.el into an org file.
13650 First prompts for an org file. If the user just presses return, the value
13651 of `org-default-notes-file' is used.
13652 Then the command offers the headings tree of the selected file in order to
13653 file the text at a specific location.
13654 You can either immediately press RET to get the note appended to the
13655 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13656 find a better place. Then press RET or <left> or <right> in insert the note.
13658 Key Cursor position Note gets inserted
13659 -----------------------------------------------------------------------------
13660 RET buffer-start as level 1 heading at end of file
13661 RET on headline as sublevel of the heading at cursor
13662 RET no heading at cursor position, level taken from context.
13663 Or use prefix arg to specify level manually.
13664 <left> on headline as same level, before current heading
13665 <right> on headline as same level, after current heading
13667 So the fastest way to store the note is to press RET RET to append it to
13668 the default file. This way your current train of thought is not
13669 interrupted, in accordance with the principles of remember.el.
13670 You can also get the fast execution without prompting by using
13671 C-u C-c C-c to exit the remember buffer. See also the variable
13672 `org-remember-store-without-prompt'.
13674 Before being stored away, the function ensures that the text has a
13675 headline, i.e. a first line that starts with a \"*\". If not, a headline
13676 is constructed from the current date and some additional data.
13678 If the variable `org-adapt-indentation' is non-nil, the entire text is
13679 also indented so that it starts in the same column as the headline
13680 \(i.e. after the stars).
13682 See also the variable `org-reverse-note-order'."
13683 (goto-char (point-min))
13684 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13685 (replace-match ""))
13686 (goto-char (point-max))
13687 (beginning-of-line 1)
13688 (while (looking-at "[ \t]*$\\|##.*")
13689 (delete-region (1- (point)) (point-max))
13690 (beginning-of-line 1))
13691 (catch 'quit
13692 (if org-note-abort (throw 'quit nil))
13693 (let* ((txt (buffer-substring (point-min) (point-max)))
13694 (fastp (org-xor (equal current-prefix-arg '(4))
13695 org-remember-store-without-prompt))
13696 (file (cond
13697 (fastp org-default-notes-file)
13698 ((and (eq org-remember-interactive-interface 'refile)
13699 org-refile-targets)
13700 org-default-notes-file)
13701 ((not (and (equal current-prefix-arg '(16))
13702 org-remember-previous-location))
13703 (org-get-org-file))))
13704 (heading org-remember-default-headline)
13705 (visiting (and file (org-find-base-buffer-visiting file)))
13706 (org-startup-folded nil)
13707 (org-startup-align-all-tables nil)
13708 (org-goto-start-pos 1)
13709 spos exitcmd level indent reversed)
13710 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13711 (setq file (car org-remember-previous-location)
13712 heading (cdr org-remember-previous-location)
13713 fastp t))
13714 (setq current-prefix-arg nil)
13715 (if (string-match "[ \t\n]+\\'" txt)
13716 (setq txt (replace-match "" t t txt)))
13717 ;; Modify text so that it becomes a nice subtree which can be inserted
13718 ;; into an org tree.
13719 (let* ((lines (split-string txt "\n"))
13720 first)
13721 (setq first (car lines) lines (cdr lines))
13722 (if (string-match "^\\*+ " first)
13723 ;; Is already a headline
13724 (setq indent nil)
13725 ;; We need to add a headline: Use time and first buffer line
13726 (setq lines (cons first lines)
13727 first (concat "* " (current-time-string)
13728 " (" (remember-buffer-desc) ")")
13729 indent " "))
13730 (if (and org-adapt-indentation indent)
13731 (setq lines (mapcar
13732 (lambda (x)
13733 (if (string-match "\\S-" x)
13734 (concat indent x) x))
13735 lines)))
13736 (setq txt (concat first "\n"
13737 (mapconcat 'identity lines "\n"))))
13738 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13739 (setq txt (replace-match "\n\n" t t txt))
13740 (if (string-match "[ \t\n]*\\'" txt)
13741 (setq txt (replace-match "\n" t t txt))))
13742 ;; Put the modified text back into the remember buffer, for refile.
13743 (erase-buffer)
13744 (insert txt)
13745 (goto-char (point-min))
13746 (when (and (eq org-remember-interactive-interface 'refile)
13747 (not fastp))
13748 (org-refile nil (or visiting (find-file-noselect file)))
13749 (throw 'quit t))
13750 ;; Find the file
13751 (if (not visiting) (find-file-noselect file))
13752 (with-current-buffer (or visiting (get-file-buffer file))
13753 (unless (org-mode-p)
13754 (error "Target files for remember notes must be in Org-mode"))
13755 (save-excursion
13756 (save-restriction
13757 (widen)
13758 (and (goto-char (point-min))
13759 (not (re-search-forward "^\\* " nil t))
13760 (insert "\n* " (or heading "Notes") "\n"))
13761 (setq reversed (org-notes-order-reversed-p))
13763 ;; Find the default location
13764 (when (and heading (stringp heading) (string-match "\\S-" heading))
13765 (goto-char (point-min))
13766 (if (re-search-forward
13767 (concat "^\\*+[ \t]+" (regexp-quote heading)
13768 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13769 nil t)
13770 (setq org-goto-start-pos (match-beginning 0))
13771 (when fastp
13772 (goto-char (point-max))
13773 (unless (bolp) (newline))
13774 (insert "* " heading "\n")
13775 (setq org-goto-start-pos (point-at-bol 0)))))
13777 ;; Ask the User for a location, using the appropriate interface
13778 (cond
13779 (fastp (setq spos org-goto-start-pos
13780 exitcmd 'return))
13781 ((eq org-remember-interactive-interface 'outline)
13782 (setq spos (org-get-location (current-buffer)
13783 org-remember-help)
13784 exitcmd (cdr spos)
13785 spos (car spos)))
13786 ((eq org-remember-interactive-interface 'outline-path-completion)
13787 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13788 (org-refile-use-outline-path t))
13789 (setq spos (org-refile-get-location "Heading: ")
13790 exitcmd 'return
13791 spos (nth 3 spos))))
13792 (t (error "this should not hapen")))
13793 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13794 ; not handle this note
13795 (goto-char spos)
13796 (cond ((org-on-heading-p t)
13797 (org-back-to-heading t)
13798 (setq level (funcall outline-level))
13799 (cond
13800 ((eq exitcmd 'return)
13801 ;; sublevel of current
13802 (setq org-remember-previous-location
13803 (cons (abbreviate-file-name file)
13804 (org-get-heading 'notags)))
13805 (if reversed
13806 (outline-next-heading)
13807 (org-end-of-subtree t)
13808 (if (not (bolp))
13809 (if (looking-at "[ \t]*\n")
13810 (beginning-of-line 2)
13811 (end-of-line 1)
13812 (insert "\n"))))
13813 (bookmark-set "org-remember-last-stored")
13814 (org-paste-subtree (org-get-legal-level level 1) txt))
13815 ((eq exitcmd 'left)
13816 ;; before current
13817 (bookmark-set "org-remember-last-stored")
13818 (org-paste-subtree level txt))
13819 ((eq exitcmd 'right)
13820 ;; after current
13821 (org-end-of-subtree t)
13822 (bookmark-set "org-remember-last-stored")
13823 (org-paste-subtree level txt))
13824 (t (error "This should not happen"))))
13826 ((and (bobp) (not reversed))
13827 ;; Put it at the end, one level below level 1
13828 (save-restriction
13829 (widen)
13830 (goto-char (point-max))
13831 (if (not (bolp)) (newline))
13832 (bookmark-set "org-remember-last-stored")
13833 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13835 ((and (bobp) reversed)
13836 ;; Put it at the start, as level 1
13837 (save-restriction
13838 (widen)
13839 (goto-char (point-min))
13840 (re-search-forward "^\\*+ " nil t)
13841 (beginning-of-line 1)
13842 (bookmark-set "org-remember-last-stored")
13843 (org-paste-subtree 1 txt)))
13845 ;; Put it right there, with automatic level determined by
13846 ;; org-paste-subtree or from prefix arg
13847 (bookmark-set "org-remember-last-stored")
13848 (org-paste-subtree
13849 (if (numberp current-prefix-arg) current-prefix-arg)
13850 txt)))
13851 (when remember-save-after-remembering
13852 (save-buffer)
13853 (if (not visiting) (kill-buffer (current-buffer)))))))))
13855 t) ;; return t to indicate that we took care of this note.
13857 (defun org-get-org-file ()
13858 "Read a filename, with default directory `org-directory'."
13859 (let ((default (or org-default-notes-file remember-data-file)))
13860 (read-file-name (format "File name [%s]: " default)
13861 (file-name-as-directory org-directory)
13862 default)))
13864 (defun org-notes-order-reversed-p ()
13865 "Check if the current file should receive notes in reversed order."
13866 (cond
13867 ((not org-reverse-note-order) nil)
13868 ((eq t org-reverse-note-order) t)
13869 ((not (listp org-reverse-note-order)) nil)
13870 (t (catch 'exit
13871 (let ((all org-reverse-note-order)
13872 entry)
13873 (while (setq entry (pop all))
13874 (if (string-match (car entry) buffer-file-name)
13875 (throw 'exit (cdr entry))))
13876 nil)))))
13878 ;;; Refiling
13880 (defvar org-refile-target-table nil
13881 "The list of refile targets, created by `org-refile'.")
13883 (defvar org-agenda-new-buffers nil
13884 "Buffers created to visit agenda files.")
13886 (defun org-get-refile-targets (&optional default-buffer)
13887 "Produce a table with refile targets."
13888 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
13889 targets txt re files f desc descre)
13890 (with-current-buffer (or default-buffer (current-buffer))
13891 (while (setq entry (pop entries))
13892 (setq files (car entry) desc (cdr entry))
13893 (cond
13894 ((null files) (setq files (list (current-buffer))))
13895 ((eq files 'org-agenda-files)
13896 (setq files (org-agenda-files 'unrestricted)))
13897 ((and (symbolp files) (fboundp files))
13898 (setq files (funcall files)))
13899 ((and (symbolp files) (boundp files))
13900 (setq files (symbol-value files))))
13901 (if (stringp files) (setq files (list files)))
13902 (cond
13903 ((eq (car desc) :tag)
13904 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13905 ((eq (car desc) :todo)
13906 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13907 ((eq (car desc) :regexp)
13908 (setq descre (cdr desc)))
13909 ((eq (car desc) :level)
13910 (setq descre (concat "^\\*\\{" (number-to-string
13911 (if org-odd-levels-only
13912 (1- (* 2 (cdr desc)))
13913 (cdr desc)))
13914 "\\}[ \t]")))
13915 ((eq (car desc) :maxlevel)
13916 (setq descre (concat "^\\*\\{1," (number-to-string
13917 (if org-odd-levels-only
13918 (1- (* 2 (cdr desc)))
13919 (cdr desc)))
13920 "\\}[ \t]")))
13921 (t (error "Bad refiling target description %s" desc)))
13922 (while (setq f (pop files))
13923 (save-excursion
13924 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13925 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13926 (save-excursion
13927 (save-restriction
13928 (widen)
13929 (goto-char (point-min))
13930 (while (re-search-forward descre nil t)
13931 (goto-char (point-at-bol))
13932 (when (looking-at org-complex-heading-regexp)
13933 (setq txt (match-string 4)
13934 re (concat "^" (regexp-quote
13935 (buffer-substring (match-beginning 1)
13936 (match-end 4)))))
13937 (if (match-end 5) (setq re (concat re "[ \t]+"
13938 (regexp-quote
13939 (match-string 5)))))
13940 (setq re (concat re "[ \t]*$"))
13941 (when org-refile-use-outline-path
13942 (setq txt (mapconcat 'identity
13943 (append
13944 (if (eq org-refile-use-outline-path 'file)
13945 (list (file-name-nondirectory
13946 (buffer-file-name (buffer-base-buffer))))
13947 (if (eq org-refile-use-outline-path 'full-file-path)
13948 (list (buffer-file-name (buffer-base-buffer)))))
13949 (org-get-outline-path)
13950 (list txt))
13951 "/")))
13952 (push (list txt f re (point)) targets))
13953 (goto-char (point-at-eol))))))))
13954 (nreverse targets))))
13956 (defun org-get-outline-path ()
13957 "Return the outline path to the current entry, as a list."
13958 (let (rtn)
13959 (save-excursion
13960 (while (org-up-heading-safe)
13961 (when (looking-at org-complex-heading-regexp)
13962 (push (org-match-string-no-properties 4) rtn)))
13963 rtn)))
13965 (defvar org-refile-history nil
13966 "History for refiling operations.")
13968 (defun org-refile (&optional goto default-buffer)
13969 "Move the entry at point to another heading.
13970 The list of target headings is compiled using the information in
13971 `org-refile-targets', which see. This list is created upon first use, and
13972 you can update it by calling this command with a double prefix (`C-u C-u').
13973 FIXME: Can we find a better way of updating?
13975 At the target location, the entry is filed as a subitem of the target heading.
13976 Depending on `org-reverse-note-order', the new subitem will either be the
13977 first of the last subitem.
13979 With prefix are GOTO, the command will only visit the target location,
13980 not actually move anything.
13981 With a double prefix `C-c C-c', go to the location where the last refiling
13982 operation has put the subtree.
13984 With a double prefix argument, the command can be used to jump to any
13985 heading in the current buffer."
13986 (interactive "P")
13987 (let* ((cbuf (current-buffer))
13988 (filename (buffer-file-name (buffer-base-buffer cbuf)))
13989 (fname (and filename (file-truename filename)))
13990 pos it nbuf file re level reversed)
13991 (if (equal goto '(16))
13992 (org-refile-goto-last-stored)
13993 (when (setq it (org-refile-get-location
13994 (if goto "Goto: " "Refile to: ") default-buffer))
13995 (setq file (nth 1 it)
13996 re (nth 2 it)
13997 pos (nth 3 it))
13998 (setq nbuf (or (find-buffer-visiting file)
13999 (find-file-noselect file)))
14000 (if goto
14001 (progn
14002 (switch-to-buffer nbuf)
14003 (goto-char pos)
14004 (org-show-context 'org-goto))
14005 (org-copy-special)
14006 (save-excursion
14007 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14008 (find-file-noselect file))))
14009 (setq reversed (org-notes-order-reversed-p))
14010 (save-excursion
14011 (save-restriction
14012 (widen)
14013 (goto-char pos)
14014 (looking-at outline-regexp)
14015 (setq level (org-get-legal-level (funcall outline-level) 1))
14016 (goto-char (or (save-excursion
14017 (if reversed
14018 (outline-next-heading)
14019 (outline-get-next-sibling)))
14020 (point-max)))
14021 (bookmark-set "org-refile-last-stored")
14022 (org-paste-subtree level))))
14023 (org-cut-special)
14024 (message "Entry refiled to \"%s\"" (car it)))))))
14026 (defun org-refile-goto-last-stored ()
14027 "Go to the location where the last refile was stored."
14028 (interactive)
14029 (bookmark-jump "org-refile-last-stored")
14030 (message "This is the location of the last refile"))
14032 (defun org-refile-get-location (&optional prompt default-buffer)
14033 "Prompt the user for a refile location, using PROMPT."
14034 (let ((org-refile-targets org-refile-targets)
14035 (org-refile-use-outline-path org-refile-use-outline-path))
14036 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14037 (unless org-refile-target-table
14038 (error "No refile targets"))
14039 (let* ((cbuf (current-buffer))
14040 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14041 (fname (and filename (file-truename filename)))
14042 (tbl (mapcar
14043 (lambda (x)
14044 (if (not (equal fname (file-truename (nth 1 x))))
14045 (cons (concat (car x) " (" (file-name-nondirectory
14046 (nth 1 x)) ")")
14047 (cdr x))
14049 org-refile-target-table))
14050 (completion-ignore-case t)
14051 pos it nbuf file re level reversed)
14052 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14053 tbl)))
14055 ;;;; Dynamic blocks
14057 (defun org-find-dblock (name)
14058 "Find the first dynamic block with name NAME in the buffer.
14059 If not found, stay at current position and return nil."
14060 (let (pos)
14061 (save-excursion
14062 (goto-char (point-min))
14063 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14064 nil t)
14065 (match-beginning 0))))
14066 (if pos (goto-char pos))
14067 pos))
14069 (defconst org-dblock-start-re
14070 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14071 "Matches the startline of a dynamic block, with parameters.")
14073 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14074 "Matches the end of a dyhamic block.")
14076 (defun org-create-dblock (plist)
14077 "Create a dynamic block section, with parameters taken from PLIST.
14078 PLIST must containe a :name entry which is used as name of the block."
14079 (unless (bolp) (newline))
14080 (let ((name (plist-get plist :name)))
14081 (insert "#+BEGIN: " name)
14082 (while plist
14083 (if (eq (car plist) :name)
14084 (setq plist (cddr plist))
14085 (insert " " (prin1-to-string (pop plist)))))
14086 (insert "\n\n#+END:\n")
14087 (beginning-of-line -2)))
14089 (defun org-prepare-dblock ()
14090 "Prepare dynamic block for refresh.
14091 This empties the block, puts the cursor at the insert position and returns
14092 the property list including an extra property :name with the block name."
14093 (unless (looking-at org-dblock-start-re)
14094 (error "Not at a dynamic block"))
14095 (let* ((begdel (1+ (match-end 0)))
14096 (name (org-no-properties (match-string 1)))
14097 (params (append (list :name name)
14098 (read (concat "(" (match-string 3) ")")))))
14099 (unless (re-search-forward org-dblock-end-re nil t)
14100 (error "Dynamic block not terminated"))
14101 (delete-region begdel (match-beginning 0))
14102 (goto-char begdel)
14103 (open-line 1)
14104 params))
14106 (defun org-map-dblocks (&optional command)
14107 "Apply COMMAND to all dynamic blocks in the current buffer.
14108 If COMMAND is not given, use `org-update-dblock'."
14109 (let ((cmd (or command 'org-update-dblock))
14110 pos)
14111 (save-excursion
14112 (goto-char (point-min))
14113 (while (re-search-forward org-dblock-start-re nil t)
14114 (goto-char (setq pos (match-beginning 0)))
14115 (condition-case nil
14116 (funcall cmd)
14117 (error (message "Error during update of dynamic block")))
14118 (goto-char pos)
14119 (unless (re-search-forward org-dblock-end-re nil t)
14120 (error "Dynamic block not terminated"))))))
14122 (defun org-dblock-update (&optional arg)
14123 "User command for updating dynamic blocks.
14124 Update the dynamic block at point. With prefix ARG, update all dynamic
14125 blocks in the buffer."
14126 (interactive "P")
14127 (if arg
14128 (org-update-all-dblocks)
14129 (or (looking-at org-dblock-start-re)
14130 (org-beginning-of-dblock))
14131 (org-update-dblock)))
14133 (defun org-update-dblock ()
14134 "Update the dynamic block at point
14135 This means to empty the block, parse for parameters and then call
14136 the correct writing function."
14137 (save-window-excursion
14138 (let* ((pos (point))
14139 (line (org-current-line))
14140 (params (org-prepare-dblock))
14141 (name (plist-get params :name))
14142 (cmd (intern (concat "org-dblock-write:" name))))
14143 (message "Updating dynamic block `%s' at line %d..." name line)
14144 (funcall cmd params)
14145 (message "Updating dynamic block `%s' at line %d...done" name line)
14146 (goto-char pos))))
14148 (defun org-beginning-of-dblock ()
14149 "Find the beginning of the dynamic block at point.
14150 Error if there is no scuh block at point."
14151 (let ((pos (point))
14152 beg)
14153 (end-of-line 1)
14154 (if (and (re-search-backward org-dblock-start-re nil t)
14155 (setq beg (match-beginning 0))
14156 (re-search-forward org-dblock-end-re nil t)
14157 (> (match-end 0) pos))
14158 (goto-char beg)
14159 (goto-char pos)
14160 (error "Not in a dynamic block"))))
14162 (defun org-update-all-dblocks ()
14163 "Update all dynamic blocks in the buffer.
14164 This function can be used in a hook."
14165 (when (org-mode-p)
14166 (org-map-dblocks 'org-update-dblock)))
14169 ;;;; Completion
14171 (defconst org-additional-option-like-keywords
14172 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14173 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14174 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14176 (defun org-complete (&optional arg)
14177 "Perform completion on word at point.
14178 At the beginning of a headline, this completes TODO keywords as given in
14179 `org-todo-keywords'.
14180 If the current word is preceded by a backslash, completes the TeX symbols
14181 that are supported for HTML support.
14182 If the current word is preceded by \"#+\", completes special words for
14183 setting file options.
14184 In the line after \"#+STARTUP:, complete valid keywords.\"
14185 At all other locations, this simply calls the value of
14186 `org-completion-fallback-command'."
14187 (interactive "P")
14188 (org-without-partial-completion
14189 (catch 'exit
14190 (let* ((end (point))
14191 (beg1 (save-excursion
14192 (skip-chars-backward (org-re "[:alnum:]_@"))
14193 (point)))
14194 (beg (save-excursion
14195 (skip-chars-backward "a-zA-Z0-9_:$")
14196 (point)))
14197 (confirm (lambda (x) (stringp (car x))))
14198 (searchhead (equal (char-before beg) ?*))
14199 (tag (and (equal (char-before beg1) ?:)
14200 (equal (char-after (point-at-bol)) ?*)))
14201 (prop (and (equal (char-before beg1) ?:)
14202 (not (equal (char-after (point-at-bol)) ?*))))
14203 (texp (equal (char-before beg) ?\\))
14204 (link (equal (char-before beg) ?\[))
14205 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14206 beg)
14207 "#+"))
14208 (startup (string-match "^#\\+STARTUP:.*"
14209 (buffer-substring (point-at-bol) (point))))
14210 (completion-ignore-case opt)
14211 (type nil)
14212 (tbl nil)
14213 (table (cond
14214 (opt
14215 (setq type :opt)
14216 (append
14217 (mapcar
14218 (lambda (x)
14219 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14220 (cons (match-string 2 x) (match-string 1 x)))
14221 (org-split-string (org-get-current-options) "\n"))
14222 (mapcar 'list org-additional-option-like-keywords)))
14223 (startup
14224 (setq type :startup)
14225 org-startup-options)
14226 (link (append org-link-abbrev-alist-local
14227 org-link-abbrev-alist))
14228 (texp
14229 (setq type :tex)
14230 org-html-entities)
14231 ((string-match "\\`\\*+[ \t]+\\'"
14232 (buffer-substring (point-at-bol) beg))
14233 (setq type :todo)
14234 (mapcar 'list org-todo-keywords-1))
14235 (searchhead
14236 (setq type :searchhead)
14237 (save-excursion
14238 (goto-char (point-min))
14239 (while (re-search-forward org-todo-line-regexp nil t)
14240 (push (list
14241 (org-make-org-heading-search-string
14242 (match-string 3) t))
14243 tbl)))
14244 tbl)
14245 (tag (setq type :tag beg beg1)
14246 (or org-tag-alist (org-get-buffer-tags)))
14247 (prop (setq type :prop beg beg1)
14248 (mapcar 'list (org-buffer-property-keys)))
14249 (t (progn
14250 (call-interactively org-completion-fallback-command)
14251 (throw 'exit nil)))))
14252 (pattern (buffer-substring-no-properties beg end))
14253 (completion (try-completion pattern table confirm)))
14254 (cond ((eq completion t)
14255 (if (not (assoc (upcase pattern) table))
14256 (message "Already complete")
14257 (if (equal type :opt)
14258 (insert (substring (cdr (assoc (upcase pattern) table))
14259 (length pattern)))
14260 (if (memq type '(:tag :prop)) (insert ":")))))
14261 ((null completion)
14262 (message "Can't find completion for \"%s\"" pattern)
14263 (ding))
14264 ((not (string= pattern completion))
14265 (delete-region beg end)
14266 (if (string-match " +$" completion)
14267 (setq completion (replace-match "" t t completion)))
14268 (insert completion)
14269 (if (get-buffer-window "*Completions*")
14270 (delete-window (get-buffer-window "*Completions*")))
14271 (if (assoc completion table)
14272 (if (eq type :todo) (insert " ")
14273 (if (memq type '(:tag :prop)) (insert ":"))))
14274 (if (and (equal type :opt) (assoc completion table))
14275 (message "%s" (substitute-command-keys
14276 "Press \\[org-complete] again to insert example settings"))))
14278 (message "Making completion list...")
14279 (let ((list (sort (all-completions pattern table confirm)
14280 'string<)))
14281 (with-output-to-temp-buffer "*Completions*"
14282 (condition-case nil
14283 ;; Protection needed for XEmacs and emacs 21
14284 (display-completion-list list pattern)
14285 (error (display-completion-list list)))))
14286 (message "Making completion list...%s" "done")))))))
14288 ;;;; TODO, DEADLINE, Comments
14290 (defun org-toggle-comment ()
14291 "Change the COMMENT state of an entry."
14292 (interactive)
14293 (save-excursion
14294 (org-back-to-heading)
14295 (let (case-fold-search)
14296 (if (looking-at (concat outline-regexp
14297 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14298 (replace-match "" t t nil 1)
14299 (if (looking-at outline-regexp)
14300 (progn
14301 (goto-char (match-end 0))
14302 (insert org-comment-string " ")))))))
14304 (defvar org-last-todo-state-is-todo nil
14305 "This is non-nil when the last TODO state change led to a TODO state.
14306 If the last change removed the TODO tag or switched to DONE, then
14307 this is nil.")
14309 (defvar org-setting-tags nil) ; dynamically skiped
14311 ;; FIXME: better place
14312 (defun org-property-or-variable-value (var &optional inherit)
14313 "Check if there is a property fixing the value of VAR.
14314 If yes, return this value. If not, return the current value of the variable."
14315 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14316 (if (and prop (stringp prop) (string-match "\\S-" prop))
14317 (read prop)
14318 (symbol-value var))))
14320 (defun org-parse-local-options (string var)
14321 "Parse STRING for startup setting relevant for variable VAR."
14322 (let ((rtn (symbol-value var))
14323 e opts)
14324 (save-match-data
14325 (if (or (not string) (not (string-match "\\S-" string)))
14327 (setq opts (delq nil (mapcar (lambda (x)
14328 (setq e (assoc x org-startup-options))
14329 (if (eq (nth 1 e) var) e nil))
14330 (org-split-string string "[ \t]+"))))
14331 (if (not opts)
14333 (setq rtn nil)
14334 (while (setq e (pop opts))
14335 (if (not (nth 3 e))
14336 (setq rtn (nth 2 e))
14337 (if (not (listp rtn)) (setq rtn nil))
14338 (push (nth 2 e) rtn)))
14339 rtn)))))
14341 (defvar org-blocker-hook nil
14342 "Hook for functions that are allowed to block a state change.
14344 Each function gets as its single argument a property list, see
14345 `org-trigger-hook' for more information about this list.
14347 If any of the functions in this hook returns nil, the state change
14348 is blocked.")
14350 (defvar org-trigger-hook nil
14351 "Hook for functions that are triggered by a state change.
14353 Each function gets as its single argument a property list with at least
14354 the following elements:
14356 (:type type-of-change :position pos-at-entry-start
14357 :from old-state :to new-state)
14359 Depending on the type, more properties may be present.
14361 This mechanism is currently implemented for:
14363 TODO state changes
14364 ------------------
14365 :type todo-state-change
14366 :from previous state (keyword as a string), or nil
14367 :to new state (keyword as a string), or nil")
14370 (defun org-todo (&optional arg)
14371 "Change the TODO state of an item.
14372 The state of an item is given by a keyword at the start of the heading,
14373 like
14374 *** TODO Write paper
14375 *** DONE Call mom
14377 The different keywords are specified in the variable `org-todo-keywords'.
14378 By default the available states are \"TODO\" and \"DONE\".
14379 So for this example: when the item starts with TODO, it is changed to DONE.
14380 When it starts with DONE, the DONE is removed. And when neither TODO nor
14381 DONE are present, add TODO at the beginning of the heading.
14383 With C-u prefix arg, use completion to determine the new state.
14384 With numeric prefix arg, switch to that state.
14386 For calling through lisp, arg is also interpreted in the following way:
14387 'none -> empty state
14388 \"\"(empty string) -> switch to empty state
14389 'done -> switch to DONE
14390 'nextset -> switch to the next set of keywords
14391 'previousset -> switch to the previous set of keywords
14392 \"WAITING\" -> switch to the specified keyword, but only if it
14393 really is a member of `org-todo-keywords'."
14394 (interactive "P")
14395 (save-excursion
14396 (catch 'exit
14397 (org-back-to-heading)
14398 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14399 (or (looking-at (concat " +" org-todo-regexp " *"))
14400 (looking-at " *"))
14401 (let* ((match-data (match-data))
14402 (startpos (point-at-bol))
14403 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14404 (org-log-done (org-parse-local-options logging 'org-log-done))
14405 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
14406 (this (match-string 1))
14407 (hl-pos (match-beginning 0))
14408 (head (org-get-todo-sequence-head this))
14409 (ass (assoc head org-todo-kwd-alist))
14410 (interpret (nth 1 ass))
14411 (done-word (nth 3 ass))
14412 (final-done-word (nth 4 ass))
14413 (last-state (or this ""))
14414 (completion-ignore-case t)
14415 (member (member this org-todo-keywords-1))
14416 (tail (cdr member))
14417 (state (cond
14418 ((and org-todo-key-trigger
14419 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14420 (and (not arg) org-use-fast-todo-selection
14421 (not (eq org-use-fast-todo-selection 'prefix)))))
14422 ;; Use fast selection
14423 (org-fast-todo-selection))
14424 ((and (equal arg '(4))
14425 (or (not org-use-fast-todo-selection)
14426 (not org-todo-key-trigger)))
14427 ;; Read a state with completion
14428 (completing-read "State: " (mapcar (lambda(x) (list x))
14429 org-todo-keywords-1)
14430 nil t))
14431 ((eq arg 'right)
14432 (if this
14433 (if tail (car tail) nil)
14434 (car org-todo-keywords-1)))
14435 ((eq arg 'left)
14436 (if (equal member org-todo-keywords-1)
14438 (if this
14439 (nth (- (length org-todo-keywords-1) (length tail) 2)
14440 org-todo-keywords-1)
14441 (org-last org-todo-keywords-1))))
14442 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14443 (setq arg nil))) ; hack to fall back to cycling
14444 (arg
14445 ;; user or caller requests a specific state
14446 (cond
14447 ((equal arg "") nil)
14448 ((eq arg 'none) nil)
14449 ((eq arg 'done) (or done-word (car org-done-keywords)))
14450 ((eq arg 'nextset)
14451 (or (car (cdr (member head org-todo-heads)))
14452 (car org-todo-heads)))
14453 ((eq arg 'previousset)
14454 (let ((org-todo-heads (reverse org-todo-heads)))
14455 (or (car (cdr (member head org-todo-heads)))
14456 (car org-todo-heads))))
14457 ((car (member arg org-todo-keywords-1)))
14458 ((nth (1- (prefix-numeric-value arg))
14459 org-todo-keywords-1))))
14460 ((null member) (or head (car org-todo-keywords-1)))
14461 ((equal this final-done-word) nil) ;; -> make empty
14462 ((null tail) nil) ;; -> first entry
14463 ((eq interpret 'sequence)
14464 (car tail))
14465 ((memq interpret '(type priority))
14466 (if (eq this-command last-command)
14467 (car tail)
14468 (if (> (length tail) 0)
14469 (or done-word (car org-done-keywords))
14470 nil)))
14471 (t nil)))
14472 (next (if state (concat " " state " ") " "))
14473 (change-plist (list :type 'todo-state-change :from this :to state
14474 :position startpos))
14475 dostates)
14476 (when org-blocker-hook
14477 (unless (save-excursion
14478 (save-match-data
14479 (run-hook-with-args-until-failure
14480 'org-blocker-hook change-plist)))
14481 (if (interactive-p)
14482 (error "TODO state change from %s to %s blocked" this state)
14483 ;; fail silently
14484 (message "TODO state change from %s to %s blocked" this state)
14485 (throw 'exit nil))))
14486 (store-match-data match-data)
14487 (replace-match next t t)
14488 (unless (pos-visible-in-window-p hl-pos)
14489 (message "TODO state changed to %s" (org-trim next)))
14490 (unless head
14491 (setq head (org-get-todo-sequence-head state)
14492 ass (assoc head org-todo-kwd-alist)
14493 interpret (nth 1 ass)
14494 done-word (nth 3 ass)
14495 final-done-word (nth 4 ass)))
14496 (when (memq arg '(nextset previousset))
14497 (message "Keyword-Set %d/%d: %s"
14498 (- (length org-todo-sets) -1
14499 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14500 (length org-todo-sets)
14501 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14502 (setq org-last-todo-state-is-todo
14503 (not (member state org-done-keywords)))
14504 (when (and org-log-done (not (memq arg '(nextset previousset))))
14505 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
14506 (or (not org-todo-log-states)
14507 (member state org-todo-log-states))))
14509 (cond
14510 ((and state (member state org-not-done-keywords)
14511 (not (member this org-not-done-keywords)))
14512 ;; This is now a todo state and was not one before
14513 ;; Remove any CLOSED timestamp, and possibly log the state change
14514 (org-add-planning-info nil nil 'closed)
14515 (and dostates (org-add-log-maybe 'state state 'findpos)))
14516 ((and state dostates)
14517 ;; This is a non-nil state, and we need to log it
14518 (org-add-log-maybe 'state state 'findpos))
14519 ((and (member state org-done-keywords)
14520 (not (member this org-done-keywords)))
14521 ;; It is now done, and it was not done before
14522 (org-add-planning-info 'closed (org-current-time))
14523 (org-add-log-maybe 'done state 'findpos))))
14524 ;; Fixup tag positioning
14525 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14526 (run-hooks 'org-after-todo-state-change-hook)
14527 (and (member state org-done-keywords) (org-auto-repeat-maybe))
14528 (if (and arg (not (member state org-done-keywords)))
14529 (setq head (org-get-todo-sequence-head state)))
14530 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14531 ;; Fixup cursor location if close to the keyword
14532 (if (and (outline-on-heading-p)
14533 (not (bolp))
14534 (save-excursion (beginning-of-line 1)
14535 (looking-at org-todo-line-regexp))
14536 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14537 (progn
14538 (goto-char (or (match-end 2) (match-end 1)))
14539 (just-one-space)))
14540 (when org-trigger-hook
14541 (save-excursion
14542 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14544 (defun org-get-todo-sequence-head (kwd)
14545 "Return the head of the TODO sequence to which KWD belongs.
14546 If KWD is not set, check if there is a text property remembering the
14547 right sequence."
14548 (let (p)
14549 (cond
14550 ((not kwd)
14551 (or (get-text-property (point-at-bol) 'org-todo-head)
14552 (progn
14553 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14554 nil (point-at-eol)))
14555 (get-text-property p 'org-todo-head))))
14556 ((not (member kwd org-todo-keywords-1))
14557 (car org-todo-keywords-1))
14558 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14560 (defun org-fast-todo-selection ()
14561 "Fast TODO keyword selection with single keys.
14562 Returns the new TODO keyword, or nil if no state change should occur."
14563 (let* ((fulltable org-todo-key-alist)
14564 (done-keywords org-done-keywords) ;; needed for the faces.
14565 (maxlen (apply 'max (mapcar
14566 (lambda (x)
14567 (if (stringp (car x)) (string-width (car x)) 0))
14568 fulltable)))
14569 (expert nil)
14570 (fwidth (+ maxlen 3 1 3))
14571 (ncol (/ (- (window-width) 4) fwidth))
14572 tg cnt e c tbl
14573 groups ingroup)
14574 (save-window-excursion
14575 (if expert
14576 (set-buffer (get-buffer-create " *Org todo*"))
14577 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14578 (erase-buffer)
14579 (org-set-local 'org-done-keywords done-keywords)
14580 (setq tbl fulltable cnt 0)
14581 (while (setq e (pop tbl))
14582 (cond
14583 ((equal e '(:startgroup))
14584 (push '() groups) (setq ingroup t)
14585 (when (not (= cnt 0))
14586 (setq cnt 0)
14587 (insert "\n"))
14588 (insert "{ "))
14589 ((equal e '(:endgroup))
14590 (setq ingroup nil cnt 0)
14591 (insert "}\n"))
14593 (setq tg (car e) c (cdr e))
14594 (if ingroup (push tg (car groups)))
14595 (setq tg (org-add-props tg nil 'face
14596 (org-get-todo-face tg)))
14597 (if (and (= cnt 0) (not ingroup)) (insert " "))
14598 (insert "[" c "] " tg (make-string
14599 (- fwidth 4 (length tg)) ?\ ))
14600 (when (= (setq cnt (1+ cnt)) ncol)
14601 (insert "\n")
14602 (if ingroup (insert " "))
14603 (setq cnt 0)))))
14604 (insert "\n")
14605 (goto-char (point-min))
14606 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14607 (fit-window-to-buffer))
14608 (message "[a-z..]:Set [SPC]:clear")
14609 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14610 (cond
14611 ((or (= c ?\C-g)
14612 (and (= c ?q) (not (rassoc c fulltable))))
14613 (setq quit-flag t))
14614 ((= c ?\ ) nil)
14615 ((setq e (rassoc c fulltable) tg (car e))
14617 (t (setq quit-flag t))))))
14619 (defun org-get-repeat ()
14620 "Check if tere is a deadline/schedule with repeater in this entry."
14621 (save-match-data
14622 (save-excursion
14623 (org-back-to-heading t)
14624 (if (re-search-forward
14625 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14626 (match-string 1)))))
14628 (defvar org-last-changed-timestamp)
14629 (defvar org-log-post-message)
14630 (defun org-auto-repeat-maybe ()
14631 "Check if the current headline contains a repeated deadline/schedule.
14632 If yes, set TODO state back to what it was and change the base date
14633 of repeating deadline/scheduled time stamps to new date.
14634 This function should be run in the `org-after-todo-state-change-hook'."
14635 ;; last-state is dynamically scoped into this function
14636 (let* ((repeat (org-get-repeat))
14637 (aa (assoc last-state org-todo-kwd-alist))
14638 (interpret (nth 1 aa))
14639 (head (nth 2 aa))
14640 (done-word (nth 3 aa))
14641 (whata '(("d" . day) ("m" . month) ("y" . year)))
14642 (msg "Entry repeats: ")
14643 (org-log-done)
14644 re type n what ts)
14645 (when repeat
14646 (org-todo (if (eq interpret 'type) last-state head))
14647 (when (and org-log-repeat
14648 (not (memq 'org-add-log-note
14649 (default-value 'post-command-hook))))
14650 ;; Make sure a note is taken
14651 (let ((org-log-done '(done)))
14652 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
14653 'findpos)))
14654 (org-back-to-heading t)
14655 (org-add-planning-info nil nil 'closed)
14656 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14657 org-deadline-time-regexp "\\)\\|\\("
14658 org-ts-regexp "\\)"))
14659 (while (re-search-forward
14660 re (save-excursion (outline-next-heading) (point)) t)
14661 (setq type (if (match-end 1) org-scheduled-string
14662 (if (match-end 3) org-deadline-string "Plain:"))
14663 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14664 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14665 (setq n (string-to-number (match-string 1 ts))
14666 what (match-string 2 ts))
14667 (if (equal what "w") (setq n (* n 7) what "d"))
14668 (org-timestamp-change n (cdr (assoc what whata)))
14669 (setq msg (concat msg type org-last-changed-timestamp " "))))
14670 (setq org-log-post-message msg)
14671 (message "%s" msg))))
14673 (defun org-show-todo-tree (arg)
14674 "Make a compact tree which shows all headlines marked with TODO.
14675 The tree will show the lines where the regexp matches, and all higher
14676 headlines above the match.
14677 With \\[universal-argument] prefix, also show the DONE entries.
14678 With a numeric prefix N, construct a sparse tree for the Nth element
14679 of `org-todo-keywords-1'."
14680 (interactive "P")
14681 (let ((case-fold-search nil)
14682 (kwd-re
14683 (cond ((null arg) org-not-done-regexp)
14684 ((equal arg '(4))
14685 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14686 (mapcar 'list org-todo-keywords-1))))
14687 (concat "\\("
14688 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14689 "\\)\\>")))
14690 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14691 (regexp-quote (nth (1- (prefix-numeric-value arg))
14692 org-todo-keywords-1)))
14693 (t (error "Invalid prefix argument: %s" arg)))))
14694 (message "%d TODO entries found"
14695 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14697 (defun org-deadline (&optional remove)
14698 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14699 With argument REMOVE, remove any deadline from the item."
14700 (interactive "P")
14701 (if remove
14702 (progn
14703 (org-remove-timestamp-with-keyword org-deadline-string)
14704 (message "Item no longer has a deadline."))
14705 (org-add-planning-info 'deadline nil 'closed)))
14707 (defun org-schedule (&optional remove)
14708 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14709 With argument REMOVE, remove any scheduling date from the item."
14710 (interactive "P")
14711 (if remove
14712 (progn
14713 (org-remove-timestamp-with-keyword org-scheduled-string)
14714 (message "Item is no longer scheduled."))
14715 (org-add-planning-info 'scheduled nil 'closed)))
14717 (defun org-remove-timestamp-with-keyword (keyword)
14718 "Remove all time stamps with KEYWORD in the current entry."
14719 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14720 beg)
14721 (save-excursion
14722 (org-back-to-heading t)
14723 (setq beg (point))
14724 (org-end-of-subtree t t)
14725 (while (re-search-backward re beg t)
14726 (replace-match "")
14727 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14728 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14730 (defun org-add-planning-info (what &optional time &rest remove)
14731 "Insert new timestamp with keyword in the line directly after the headline.
14732 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14733 If non is given, the user is prompted for a date.
14734 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14735 be removed."
14736 (interactive)
14737 (let (org-time-was-given org-end-time-was-given)
14738 (when what (setq time (or time (org-read-date nil 'to-time))))
14739 (when (and org-insert-labeled-timestamps-at-point
14740 (member what '(scheduled deadline)))
14741 (insert
14742 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14743 (org-insert-time-stamp time org-time-was-given
14744 nil nil nil (list org-end-time-was-given))
14745 (setq what nil))
14746 (save-excursion
14747 (save-restriction
14748 (let (col list elt ts buffer-invisibility-spec)
14749 (org-back-to-heading t)
14750 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14751 (goto-char (match-end 1))
14752 (setq col (current-column))
14753 (goto-char (match-end 0))
14754 (if (eobp) (insert "\n") (forward-char 1))
14755 (if (and (not (looking-at outline-regexp))
14756 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14757 "[^\r\n]*"))
14758 (not (equal (match-string 1) org-clock-string)))
14759 (narrow-to-region (match-beginning 0) (match-end 0))
14760 (insert-before-markers "\n")
14761 (backward-char 1)
14762 (narrow-to-region (point) (point))
14763 (indent-to-column col))
14764 ;; Check if we have to remove something.
14765 (setq list (cons what remove))
14766 (while list
14767 (setq elt (pop list))
14768 (goto-char (point-min))
14769 (when (or (and (eq elt 'scheduled)
14770 (re-search-forward org-scheduled-time-regexp nil t))
14771 (and (eq elt 'deadline)
14772 (re-search-forward org-deadline-time-regexp nil t))
14773 (and (eq elt 'closed)
14774 (re-search-forward org-closed-time-regexp nil t)))
14775 (replace-match "")
14776 (if (looking-at "--+<[^>]+>") (replace-match ""))
14777 (if (looking-at " +") (replace-match ""))))
14778 (goto-char (point-max))
14779 (when what
14780 (insert
14781 (if (not (equal (char-before) ?\ )) " " "")
14782 (cond ((eq what 'scheduled) org-scheduled-string)
14783 ((eq what 'deadline) org-deadline-string)
14784 ((eq what 'closed) org-closed-string))
14785 " ")
14786 (setq ts (org-insert-time-stamp
14787 time
14788 (or org-time-was-given
14789 (and (eq what 'closed) org-log-done-with-time))
14790 (eq what 'closed)
14791 nil nil (list org-end-time-was-given)))
14792 (end-of-line 1))
14793 (goto-char (point-min))
14794 (widen)
14795 (if (looking-at "[ \t]+\r?\n")
14796 (replace-match ""))
14797 ts)))))
14799 (defvar org-log-note-marker (make-marker))
14800 (defvar org-log-note-purpose nil)
14801 (defvar org-log-note-state nil)
14802 (defvar org-log-note-window-configuration nil)
14803 (defvar org-log-note-return-to (make-marker))
14804 (defvar org-log-post-message nil
14805 "Message to be displayed after a log note has been stored.
14806 The auto-repeater uses this.")
14808 (defun org-add-log-maybe (&optional purpose state findpos)
14809 "Set up the post command hook to take a note."
14810 (save-excursion
14811 (when (and (listp org-log-done)
14812 (memq purpose org-log-done))
14813 (when findpos
14814 (org-back-to-heading t)
14815 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14816 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14817 "[^\r\n]*\\)?"))
14818 (goto-char (match-end 0))
14819 (unless org-log-states-order-reversed
14820 (and (= (char-after) ?\n) (forward-char 1))
14821 (org-skip-over-state-notes)
14822 (skip-chars-backward " \t\n\r")))
14823 (move-marker org-log-note-marker (point))
14824 (setq org-log-note-purpose purpose)
14825 (setq org-log-note-state state)
14826 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14828 (defun org-skip-over-state-notes ()
14829 "Skip past the list of State notes in an entry."
14830 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14831 (while (looking-at "[ \t]*- State")
14832 (condition-case nil
14833 (org-next-item)
14834 (error (org-end-of-item)))))
14836 (defun org-add-log-note (&optional purpose)
14837 "Pop up a window for taking a note, and add this note later at point."
14838 (remove-hook 'post-command-hook 'org-add-log-note)
14839 (setq org-log-note-window-configuration (current-window-configuration))
14840 (delete-other-windows)
14841 (move-marker org-log-note-return-to (point))
14842 (switch-to-buffer (marker-buffer org-log-note-marker))
14843 (goto-char org-log-note-marker)
14844 (org-switch-to-buffer-other-window "*Org Note*")
14845 (erase-buffer)
14846 (let ((org-inhibit-startup t)) (org-mode))
14847 (insert (format "# Insert note for %s.
14848 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14849 (cond
14850 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14851 ((eq org-log-note-purpose 'done) "closed todo item")
14852 ((eq org-log-note-purpose 'state)
14853 (format "state change to \"%s\"" org-log-note-state))
14854 (t (error "This should not happen")))))
14855 (org-set-local 'org-finish-function 'org-store-log-note))
14857 (defun org-store-log-note ()
14858 "Finish taking a log note, and insert it to where it belongs."
14859 (let ((txt (buffer-string))
14860 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14861 lines ind)
14862 (kill-buffer (current-buffer))
14863 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14864 (setq txt (replace-match "" t t txt)))
14865 (if (string-match "\\s-+\\'" txt)
14866 (setq txt (replace-match "" t t txt)))
14867 (setq lines (org-split-string txt "\n"))
14868 (when (and note (string-match "\\S-" note))
14869 (setq note
14870 (org-replace-escapes
14871 note
14872 (list (cons "%u" (user-login-name))
14873 (cons "%U" user-full-name)
14874 (cons "%t" (format-time-string
14875 (org-time-stamp-format 'long 'inactive)
14876 (current-time)))
14877 (cons "%s" (if org-log-note-state
14878 (concat "\"" org-log-note-state "\"")
14879 "")))))
14880 (if lines (setq note (concat note " \\\\")))
14881 (push note lines))
14882 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14883 (when lines
14884 (save-excursion
14885 (set-buffer (marker-buffer org-log-note-marker))
14886 (save-excursion
14887 (goto-char org-log-note-marker)
14888 (move-marker org-log-note-marker nil)
14889 (end-of-line 1)
14890 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14891 (indent-relative nil)
14892 (insert "- " (pop lines))
14893 (org-indent-line-function)
14894 (beginning-of-line 1)
14895 (looking-at "[ \t]*")
14896 (setq ind (concat (match-string 0) " "))
14897 (end-of-line 1)
14898 (while lines (insert "\n" ind (pop lines)))))))
14899 (set-window-configuration org-log-note-window-configuration)
14900 (with-current-buffer (marker-buffer org-log-note-return-to)
14901 (goto-char org-log-note-return-to))
14902 (move-marker org-log-note-return-to nil)
14903 (and org-log-post-message (message "%s" org-log-post-message)))
14905 ;; FIXME: what else would be useful?
14906 ;; - priority
14907 ;; - date
14909 (defun org-sparse-tree (&optional arg)
14910 "Create a sparse tree, prompt for the details.
14911 This command can create sparse trees. You first need to select the type
14912 of match used to create the tree:
14914 t Show entries with a specific TODO keyword.
14915 T Show entries selected by a tags match.
14916 p Enter a property name and its value (both with completion on existing
14917 names/values) and show entries with that property.
14918 r Show entries matching a regular expression
14919 d Show deadlines due within `org-deadline-warning-days'."
14920 (interactive "P")
14921 (let (ans kwd value)
14922 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
14923 (setq ans (read-char-exclusive))
14924 (cond
14925 ((equal ans ?d)
14926 (call-interactively 'org-check-deadlines))
14927 ((equal ans ?b)
14928 (call-interactively 'org-check-before-date))
14929 ((equal ans ?t)
14930 (org-show-todo-tree '(4)))
14931 ((equal ans ?T)
14932 (call-interactively 'org-tags-sparse-tree))
14933 ((member ans '(?p ?P))
14934 (setq kwd (completing-read "Property: "
14935 (mapcar 'list (org-buffer-property-keys))))
14936 (setq value (completing-read "Value: "
14937 (mapcar 'list (org-property-values kwd))))
14938 (unless (string-match "\\`{.*}\\'" value)
14939 (setq value (concat "\"" value "\"")))
14940 (org-tags-sparse-tree arg (concat kwd "=" value)))
14941 ((member ans '(?r ?R ?/))
14942 (call-interactively 'org-occur))
14943 (t (error "No such sparse tree command \"%c\"" ans)))))
14945 (defvar org-occur-highlights nil)
14946 (make-variable-buffer-local 'org-occur-highlights)
14948 (defun org-occur (regexp &optional keep-previous callback)
14949 "Make a compact tree which shows all matches of REGEXP.
14950 The tree will show the lines where the regexp matches, and all higher
14951 headlines above the match. It will also show the heading after the match,
14952 to make sure editing the matching entry is easy.
14953 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
14954 call to `org-occur' will be kept, to allow stacking of calls to this
14955 command.
14956 If CALLBACK is non-nil, it is a function which is called to confirm
14957 that the match should indeed be shown."
14958 (interactive "sRegexp: \nP")
14959 (or keep-previous (org-remove-occur-highlights nil nil t))
14960 (let ((cnt 0))
14961 (save-excursion
14962 (goto-char (point-min))
14963 (if (or (not keep-previous) ; do not want to keep
14964 (not org-occur-highlights)) ; no previous matches
14965 ;; hide everything
14966 (org-overview))
14967 (while (re-search-forward regexp nil t)
14968 (when (or (not callback)
14969 (save-match-data (funcall callback)))
14970 (setq cnt (1+ cnt))
14971 (when org-highlight-sparse-tree-matches
14972 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14973 (org-show-context 'occur-tree))))
14974 (when org-remove-highlights-with-change
14975 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
14976 nil 'local))
14977 (unless org-sparse-tree-open-archived-trees
14978 (org-hide-archived-subtrees (point-min) (point-max)))
14979 (run-hooks 'org-occur-hook)
14980 (if (interactive-p)
14981 (message "%d match(es) for regexp %s" cnt regexp))
14982 cnt))
14984 (defun org-show-context (&optional key)
14985 "Make sure point and context and visible.
14986 How much context is shown depends upon the variables
14987 `org-show-hierarchy-above', `org-show-following-heading'. and
14988 `org-show-siblings'."
14989 (let ((heading-p (org-on-heading-p t))
14990 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
14991 (following-p (org-get-alist-option org-show-following-heading key))
14992 (entry-p (org-get-alist-option org-show-entry-below key))
14993 (siblings-p (org-get-alist-option org-show-siblings key)))
14994 (catch 'exit
14995 ;; Show heading or entry text
14996 (if (and heading-p (not entry-p))
14997 (org-flag-heading nil) ; only show the heading
14998 (and (or entry-p (org-invisible-p) (org-invisible-p2))
14999 (org-show-hidden-entry))) ; show entire entry
15000 (when following-p
15001 ;; Show next sibling, or heading below text
15002 (save-excursion
15003 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15004 (org-flag-heading nil))))
15005 (when siblings-p (org-show-siblings))
15006 (when hierarchy-p
15007 ;; show all higher headings, possibly with siblings
15008 (save-excursion
15009 (while (and (condition-case nil
15010 (progn (org-up-heading-all 1) t)
15011 (error nil))
15012 (not (bobp)))
15013 (org-flag-heading nil)
15014 (when siblings-p (org-show-siblings))))))))
15016 (defun org-reveal (&optional siblings)
15017 "Show current entry, hierarchy above it, and the following headline.
15018 This can be used to show a consistent set of context around locations
15019 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15020 not t for the search context.
15022 With optional argument SIBLINGS, on each level of the hierarchy all
15023 siblings are shown. This repairs the tree structure to what it would
15024 look like when opened with hierarchical calls to `org-cycle'."
15025 (interactive "P")
15026 (let ((org-show-hierarchy-above t)
15027 (org-show-following-heading t)
15028 (org-show-siblings (if siblings t org-show-siblings)))
15029 (org-show-context nil)))
15031 (defun org-highlight-new-match (beg end)
15032 "Highlight from BEG to END and mark the highlight is an occur headline."
15033 (let ((ov (org-make-overlay beg end)))
15034 (org-overlay-put ov 'face 'secondary-selection)
15035 (push ov org-occur-highlights)))
15037 (defun org-remove-occur-highlights (&optional beg end noremove)
15038 "Remove the occur highlights from the buffer.
15039 BEG and END are ignored. If NOREMOVE is nil, remove this function
15040 from the `before-change-functions' in the current buffer."
15041 (interactive)
15042 (unless org-inhibit-highlight-removal
15043 (mapc 'org-delete-overlay org-occur-highlights)
15044 (setq org-occur-highlights nil)
15045 (unless noremove
15046 (remove-hook 'before-change-functions
15047 'org-remove-occur-highlights 'local))))
15049 ;;;; Priorities
15051 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15052 "Regular expression matching the priority indicator.")
15054 (defvar org-remove-priority-next-time nil)
15056 (defun org-priority-up ()
15057 "Increase the priority of the current item."
15058 (interactive)
15059 (org-priority 'up))
15061 (defun org-priority-down ()
15062 "Decrease the priority of the current item."
15063 (interactive)
15064 (org-priority 'down))
15066 (defun org-priority (&optional action)
15067 "Change the priority of an item by ARG.
15068 ACTION can be `set', `up', `down', or a character."
15069 (interactive)
15070 (setq action (or action 'set))
15071 (let (current new news have remove)
15072 (save-excursion
15073 (org-back-to-heading)
15074 (if (looking-at org-priority-regexp)
15075 (setq current (string-to-char (match-string 2))
15076 have t)
15077 (setq current org-default-priority))
15078 (cond
15079 ((or (eq action 'set) (integerp action))
15080 (if (integerp action)
15081 (setq new action)
15082 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15083 (setq new (read-char-exclusive)))
15084 (if (and (= (upcase org-highest-priority) org-highest-priority)
15085 (= (upcase org-lowest-priority) org-lowest-priority))
15086 (setq new (upcase new)))
15087 (cond ((equal new ?\ ) (setq remove t))
15088 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15089 (error "Priority must be between `%c' and `%c'"
15090 org-highest-priority org-lowest-priority))))
15091 ((eq action 'up)
15092 (if (and (not have) (eq last-command this-command))
15093 (setq new org-lowest-priority)
15094 (setq new (if (and org-priority-start-cycle-with-default (not have))
15095 org-default-priority (1- current)))))
15096 ((eq action 'down)
15097 (if (and (not have) (eq last-command this-command))
15098 (setq new org-highest-priority)
15099 (setq new (if (and org-priority-start-cycle-with-default (not have))
15100 org-default-priority (1+ current)))))
15101 (t (error "Invalid action")))
15102 (if (or (< (upcase new) org-highest-priority)
15103 (> (upcase new) org-lowest-priority))
15104 (setq remove t))
15105 (setq news (format "%c" new))
15106 (if have
15107 (if remove
15108 (replace-match "" t t nil 1)
15109 (replace-match news t t nil 2))
15110 (if remove
15111 (error "No priority cookie found in line")
15112 (looking-at org-todo-line-regexp)
15113 (if (match-end 2)
15114 (progn
15115 (goto-char (match-end 2))
15116 (insert " [#" news "]"))
15117 (goto-char (match-beginning 3))
15118 (insert "[#" news "] ")))))
15119 (org-preserve-lc (org-set-tags nil 'align))
15120 (if remove
15121 (message "Priority removed")
15122 (message "Priority of current item set to %s" news))))
15125 (defun org-get-priority (s)
15126 "Find priority cookie and return priority."
15127 (save-match-data
15128 (if (not (string-match org-priority-regexp s))
15129 (* 1000 (- org-lowest-priority org-default-priority))
15130 (* 1000 (- org-lowest-priority
15131 (string-to-char (match-string 2 s)))))))
15133 ;;;; Tags
15135 (defun org-scan-tags (action matcher &optional todo-only)
15136 "Scan headline tags with inheritance and produce output ACTION.
15137 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15138 evaluated, testing if a given set of tags qualifies a headline for
15139 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15140 are included in the output."
15141 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15142 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15143 (org-re
15144 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15145 (props (list 'face nil
15146 'done-face 'org-done
15147 'undone-face nil
15148 'mouse-face 'highlight
15149 'org-not-done-regexp org-not-done-regexp
15150 'org-todo-regexp org-todo-regexp
15151 'keymap org-agenda-keymap
15152 'help-echo
15153 (format "mouse-2 or RET jump to org file %s"
15154 (abbreviate-file-name
15155 (or (buffer-file-name (buffer-base-buffer))
15156 (buffer-name (buffer-base-buffer)))))))
15157 (case-fold-search nil)
15158 lspos
15159 tags tags-list tags-alist (llast 0) rtn level category i txt
15160 todo marker entry priority)
15161 (save-excursion
15162 (goto-char (point-min))
15163 (when (eq action 'sparse-tree)
15164 (org-overview)
15165 (org-remove-occur-highlights))
15166 (while (re-search-forward re nil t)
15167 (catch :skip
15168 (setq todo (if (match-end 1) (match-string 2))
15169 tags (if (match-end 4) (match-string 4)))
15170 (goto-char (setq lspos (1+ (match-beginning 0))))
15171 (setq level (org-reduced-level (funcall outline-level))
15172 category (org-get-category))
15173 (setq i llast llast level)
15174 ;; remove tag lists from same and sublevels
15175 (while (>= i level)
15176 (when (setq entry (assoc i tags-alist))
15177 (setq tags-alist (delete entry tags-alist)))
15178 (setq i (1- i)))
15179 ;; add the nex tags
15180 (when tags
15181 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15182 tags-alist
15183 (cons (cons level tags) tags-alist)))
15184 ;; compile tags for current headline
15185 (setq tags-list
15186 (if org-use-tag-inheritance
15187 (apply 'append (mapcar 'cdr tags-alist))
15188 tags))
15189 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15190 (eval matcher)
15191 (or (not org-agenda-skip-archived-trees)
15192 (not (member org-archive-tag tags-list))))
15193 (and (eq action 'agenda) (org-agenda-skip))
15194 ;; list this headline
15196 (if (eq action 'sparse-tree)
15197 (progn
15198 (and org-highlight-sparse-tree-matches
15199 (org-get-heading) (match-end 0)
15200 (org-highlight-new-match
15201 (match-beginning 0) (match-beginning 1)))
15202 (org-show-context 'tags-tree))
15203 (setq txt (org-format-agenda-item
15205 (concat
15206 (if org-tags-match-list-sublevels
15207 (make-string (1- level) ?.) "")
15208 (org-get-heading))
15209 category tags-list)
15210 priority (org-get-priority txt))
15211 (goto-char lspos)
15212 (setq marker (org-agenda-new-marker))
15213 (org-add-props txt props
15214 'org-marker marker 'org-hd-marker marker 'org-category category
15215 'priority priority 'type "tagsmatch")
15216 (push txt rtn))
15217 ;; if we are to skip sublevels, jump to end of subtree
15218 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15219 (when (and (eq action 'sparse-tree)
15220 (not org-sparse-tree-open-archived-trees))
15221 (org-hide-archived-subtrees (point-min) (point-max)))
15222 (nreverse rtn)))
15224 (defvar todo-only) ;; dynamically scoped
15226 (defun org-tags-sparse-tree (&optional todo-only match)
15227 "Create a sparse tree according to tags string MATCH.
15228 MATCH can contain positive and negative selection of tags, like
15229 \"+WORK+URGENT-WITHBOSS\".
15230 If optional argument TODO_ONLY is non-nil, only select lines that are
15231 also TODO lines."
15232 (interactive "P")
15233 (org-prepare-agenda-buffers (list (current-buffer)))
15234 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15236 (defvar org-cached-props nil)
15237 (defun org-cached-entry-get (pom property)
15238 (if (or (eq t org-use-property-inheritance)
15239 (member property org-use-property-inheritance))
15240 ;; Caching is not possible, check it directly
15241 (org-entry-get pom property 'inherit)
15242 ;; Get all properties, so that we can do complicated checks easily
15243 (cdr (assoc property (or org-cached-props
15244 (setq org-cached-props
15245 (org-entry-properties pom)))))))
15247 (defun org-global-tags-completion-table (&optional files)
15248 "Return the list of all tags in all agenda buffer/files."
15249 (save-excursion
15250 (org-uniquify
15251 (delq nil
15252 (apply 'append
15253 (mapcar
15254 (lambda (file)
15255 (set-buffer (find-file-noselect file))
15256 (append (org-get-buffer-tags)
15257 (mapcar (lambda (x) (if (stringp (car-safe x))
15258 (list (car-safe x)) nil))
15259 org-tag-alist)))
15260 (if (and files (car files))
15261 files
15262 (org-agenda-files))))))))
15264 (defun org-make-tags-matcher (match)
15265 "Create the TAGS//TODO matcher form for the selection string MATCH."
15266 ;; todo-only is scoped dynamically into this function, and the function
15267 ;; may change it it the matcher asksk for it.
15268 (unless match
15269 ;; Get a new match request, with completion
15270 (let ((org-last-tags-completion-table
15271 (org-global-tags-completion-table)))
15272 (setq match (completing-read
15273 "Match: " 'org-tags-completion-function nil nil nil
15274 'org-tags-history))))
15276 ;; Parse the string and create a lisp form
15277 (let ((match0 match)
15278 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
15279 minus tag mm
15280 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15281 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15282 (if (string-match "/+" match)
15283 ;; match contains also a todo-matching request
15284 (progn
15285 (setq tagsmatch (substring match 0 (match-beginning 0))
15286 todomatch (substring match (match-end 0)))
15287 (if (string-match "^!" todomatch)
15288 (setq todo-only t todomatch (substring todomatch 1)))
15289 (if (string-match "^\\s-*$" todomatch)
15290 (setq todomatch nil)))
15291 ;; only matching tags
15292 (setq tagsmatch match todomatch nil))
15294 ;; Make the tags matcher
15295 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15296 (setq tagsmatcher t)
15297 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15298 (while (setq term (pop orterms))
15299 (while (and (equal (substring term -1) "\\") orterms)
15300 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15301 (while (string-match re term)
15302 (setq minus (and (match-end 1)
15303 (equal (match-string 1 term) "-"))
15304 tag (match-string 2 term)
15305 re-p (equal (string-to-char tag) ?{)
15306 level-p (match-end 3)
15307 prop-p (match-end 4)
15308 mm (cond
15309 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15310 (level-p `(= level ,(string-to-number
15311 (match-string 3 term))))
15312 (prop-p
15313 (setq pn (match-string 4 term)
15314 pv (match-string 5 term)
15315 cat-p (equal pn "CATEGORY")
15316 re-p (equal (string-to-char pv) ?{)
15317 pv (substring pv 1 -1))
15318 (if (equal pn "CATEGORY")
15319 (setq gv '(get-text-property (point) 'org-category))
15320 (setq gv `(org-cached-entry-get nil ,pn)))
15321 (if re-p
15322 `(string-match ,pv (or ,gv ""))
15323 `(equal ,pv ,gv)))
15324 (t `(member ,(downcase tag) tags-list)))
15325 mm (if minus (list 'not mm) mm)
15326 term (substring term (match-end 0)))
15327 (push mm tagsmatcher))
15328 (push (if (> (length tagsmatcher) 1)
15329 (cons 'and tagsmatcher)
15330 (car tagsmatcher))
15331 orlist)
15332 (setq tagsmatcher nil))
15333 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15334 (setq tagsmatcher
15335 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15337 ;; Make the todo matcher
15338 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15339 (setq todomatcher t)
15340 (setq orterms (org-split-string todomatch "|") orlist nil)
15341 (while (setq term (pop orterms))
15342 (while (string-match re term)
15343 (setq minus (and (match-end 1)
15344 (equal (match-string 1 term) "-"))
15345 kwd (match-string 2 term)
15346 re-p (equal (string-to-char kwd) ?{)
15347 term (substring term (match-end 0))
15348 mm (if re-p
15349 `(string-match ,(substring kwd 1 -1) todo)
15350 (list 'equal 'todo kwd))
15351 mm (if minus (list 'not mm) mm))
15352 (push mm todomatcher))
15353 (push (if (> (length todomatcher) 1)
15354 (cons 'and todomatcher)
15355 (car todomatcher))
15356 orlist)
15357 (setq todomatcher nil))
15358 (setq todomatcher (if (> (length orlist) 1)
15359 (cons 'or orlist) (car orlist))))
15361 ;; Return the string and lisp forms of the matcher
15362 (setq matcher (if todomatcher
15363 (list 'and tagsmatcher todomatcher)
15364 tagsmatcher))
15365 (cons match0 matcher)))
15367 (defun org-match-any-p (re list)
15368 "Does re match any element of list?"
15369 (setq list (mapcar (lambda (x) (string-match re x)) list))
15370 (delq nil list))
15372 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15373 (defvar org-tags-overlay (org-make-overlay 1 1))
15374 (org-detach-overlay org-tags-overlay)
15376 (defun org-align-tags-here (to-col)
15377 ;; Assumes that this is a headline
15378 (let ((pos (point)) (col (current-column)) tags)
15379 (beginning-of-line 1)
15380 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15381 (< pos (match-beginning 2)))
15382 (progn
15383 (setq tags (match-string 2))
15384 (goto-char (match-beginning 1))
15385 (insert " ")
15386 (delete-region (point) (1+ (match-end 0)))
15387 (backward-char 1)
15388 (move-to-column
15389 (max (1+ (current-column))
15390 (1+ col)
15391 (if (> to-col 0)
15392 to-col
15393 (- (abs to-col) (length tags))))
15395 (insert tags)
15396 (move-to-column (min (current-column) col) t))
15397 (goto-char pos))))
15399 (defun org-set-tags (&optional arg just-align)
15400 "Set the tags for the current headline.
15401 With prefix ARG, realign all tags in headings in the current buffer."
15402 (interactive "P")
15403 (let* ((re (concat "^" outline-regexp))
15404 (current (org-get-tags-string))
15405 (col (current-column))
15406 (org-setting-tags t)
15407 table current-tags inherited-tags ; computed below when needed
15408 tags p0 c0 c1 rpl)
15409 (if arg
15410 (save-excursion
15411 (goto-char (point-min))
15412 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15413 (while (re-search-forward re nil t)
15414 (org-set-tags nil t)
15415 (end-of-line 1)))
15416 (message "All tags realigned to column %d" org-tags-column))
15417 (if just-align
15418 (setq tags current)
15419 ;; Get a new set of tags from the user
15420 (save-excursion
15421 (setq table (or org-tag-alist (org-get-buffer-tags))
15422 org-last-tags-completion-table table
15423 current-tags (org-split-string current ":")
15424 inherited-tags (nreverse
15425 (nthcdr (length current-tags)
15426 (nreverse (org-get-tags-at))))
15427 tags
15428 (if (or (eq t org-use-fast-tag-selection)
15429 (and org-use-fast-tag-selection
15430 (delq nil (mapcar 'cdr table))))
15431 (org-fast-tag-selection
15432 current-tags inherited-tags table
15433 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15434 (let ((org-add-colon-after-tag-completion t))
15435 (org-trim
15436 (org-without-partial-completion
15437 (completing-read "Tags: " 'org-tags-completion-function
15438 nil nil current 'org-tags-history)))))))
15439 (while (string-match "[-+&]+" tags)
15440 ;; No boolean logic, just a list
15441 (setq tags (replace-match ":" t t tags))))
15443 (if (string-match "\\`[\t ]*\\'" tags)
15444 (setq tags "")
15445 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15446 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15448 ;; Insert new tags at the correct column
15449 (beginning-of-line 1)
15450 (cond
15451 ((and (equal current "") (equal tags "")))
15452 ((re-search-forward
15453 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15454 (point-at-eol) t)
15455 (if (equal tags "")
15456 (setq rpl "")
15457 (goto-char (match-beginning 0))
15458 (setq c0 (current-column) p0 (point)
15459 c1 (max (1+ c0) (if (> org-tags-column 0)
15460 org-tags-column
15461 (- (- org-tags-column) (length tags))))
15462 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15463 (replace-match rpl t t)
15464 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15465 tags)
15466 (t (error "Tags alignment failed")))
15467 (move-to-column col)
15468 (unless just-align
15469 (run-hooks 'org-after-tags-change-hook)))))
15471 (defun org-change-tag-in-region (beg end tag off)
15472 "Add or remove TAG for each entry in the region.
15473 This works in the agenda, and also in an org-mode buffer."
15474 (interactive
15475 (list (region-beginning) (region-end)
15476 (let ((org-last-tags-completion-table
15477 (if (org-mode-p)
15478 (org-get-buffer-tags)
15479 (org-global-tags-completion-table))))
15480 (completing-read
15481 "Tag: " 'org-tags-completion-function nil nil nil
15482 'org-tags-history))
15483 (progn
15484 (message "[s]et or [r]emove? ")
15485 (equal (read-char-exclusive) ?r))))
15486 (if (fboundp 'deactivate-mark) (deactivate-mark))
15487 (let ((agendap (equal major-mode 'org-agenda-mode))
15488 l1 l2 m buf pos newhead (cnt 0))
15489 (goto-char end)
15490 (setq l2 (1- (org-current-line)))
15491 (goto-char beg)
15492 (setq l1 (org-current-line))
15493 (loop for l from l1 to l2 do
15494 (goto-line l)
15495 (setq m (get-text-property (point) 'org-hd-marker))
15496 (when (or (and (org-mode-p) (org-on-heading-p))
15497 (and agendap m))
15498 (setq buf (if agendap (marker-buffer m) (current-buffer))
15499 pos (if agendap m (point)))
15500 (with-current-buffer buf
15501 (save-excursion
15502 (save-restriction
15503 (goto-char pos)
15504 (setq cnt (1+ cnt))
15505 (org-toggle-tag tag (if off 'off 'on))
15506 (setq newhead (org-get-heading)))))
15507 (and agendap (org-agenda-change-all-lines newhead m))))
15508 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15510 (defun org-tags-completion-function (string predicate &optional flag)
15511 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15512 (confirm (lambda (x) (stringp (car x)))))
15513 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15514 (setq s1 (match-string 1 string)
15515 s2 (match-string 2 string))
15516 (setq s1 "" s2 string))
15517 (cond
15518 ((eq flag nil)
15519 ;; try completion
15520 (setq rtn (try-completion s2 ctable confirm))
15521 (if (stringp rtn)
15522 (setq rtn
15523 (concat s1 s2 (substring rtn (length s2))
15524 (if (and org-add-colon-after-tag-completion
15525 (assoc rtn ctable))
15526 ":" ""))))
15527 rtn)
15528 ((eq flag t)
15529 ;; all-completions
15530 (all-completions s2 ctable confirm)
15532 ((eq flag 'lambda)
15533 ;; exact match?
15534 (assoc s2 ctable)))
15537 (defun org-fast-tag-insert (kwd tags face &optional end)
15538 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15539 (insert (format "%-12s" (concat kwd ":"))
15540 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15541 (or end "")))
15543 (defun org-fast-tag-show-exit (flag)
15544 (save-excursion
15545 (goto-line 3)
15546 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15547 (replace-match ""))
15548 (when flag
15549 (end-of-line 1)
15550 (move-to-column (- (window-width) 19) t)
15551 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15553 (defun org-set-current-tags-overlay (current prefix)
15554 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15555 (if (featurep 'xemacs)
15556 (org-overlay-display org-tags-overlay (concat prefix s)
15557 'secondary-selection)
15558 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15559 (org-overlay-display org-tags-overlay (concat prefix s)))))
15561 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15562 "Fast tag selection with single keys.
15563 CURRENT is the current list of tags in the headline, INHERITED is the
15564 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15565 possibly with grouping information. TODO-TABLE is a similar table with
15566 TODO keywords, should these have keys assigned to them.
15567 If the keys are nil, a-z are automatically assigned.
15568 Returns the new tags string, or nil to not change the current settings."
15569 (let* ((fulltable (append table todo-table))
15570 (maxlen (apply 'max (mapcar
15571 (lambda (x)
15572 (if (stringp (car x)) (string-width (car x)) 0))
15573 fulltable)))
15574 (buf (current-buffer))
15575 (expert (eq org-fast-tag-selection-single-key 'expert))
15576 (buffer-tags nil)
15577 (fwidth (+ maxlen 3 1 3))
15578 (ncol (/ (- (window-width) 4) fwidth))
15579 (i-face 'org-done)
15580 (c-face 'org-todo)
15581 tg cnt e c char c1 c2 ntable tbl rtn
15582 ov-start ov-end ov-prefix
15583 (exit-after-next org-fast-tag-selection-single-key)
15584 (done-keywords org-done-keywords)
15585 groups ingroup)
15586 (save-excursion
15587 (beginning-of-line 1)
15588 (if (looking-at
15589 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15590 (setq ov-start (match-beginning 1)
15591 ov-end (match-end 1)
15592 ov-prefix "")
15593 (setq ov-start (1- (point-at-eol))
15594 ov-end (1+ ov-start))
15595 (skip-chars-forward "^\n\r")
15596 (setq ov-prefix
15597 (concat
15598 (buffer-substring (1- (point)) (point))
15599 (if (> (current-column) org-tags-column)
15601 (make-string (- org-tags-column (current-column)) ?\ ))))))
15602 (org-move-overlay org-tags-overlay ov-start ov-end)
15603 (save-window-excursion
15604 (if expert
15605 (set-buffer (get-buffer-create " *Org tags*"))
15606 (delete-other-windows)
15607 (split-window-vertically)
15608 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15609 (erase-buffer)
15610 (org-set-local 'org-done-keywords done-keywords)
15611 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15612 (org-fast-tag-insert "Current" current c-face "\n\n")
15613 (org-fast-tag-show-exit exit-after-next)
15614 (org-set-current-tags-overlay current ov-prefix)
15615 (setq tbl fulltable char ?a cnt 0)
15616 (while (setq e (pop tbl))
15617 (cond
15618 ((equal e '(:startgroup))
15619 (push '() groups) (setq ingroup t)
15620 (when (not (= cnt 0))
15621 (setq cnt 0)
15622 (insert "\n"))
15623 (insert "{ "))
15624 ((equal e '(:endgroup))
15625 (setq ingroup nil cnt 0)
15626 (insert "}\n"))
15628 (setq tg (car e) c2 nil)
15629 (if (cdr e)
15630 (setq c (cdr e))
15631 ;; automatically assign a character.
15632 (setq c1 (string-to-char
15633 (downcase (substring
15634 tg (if (= (string-to-char tg) ?@) 1 0)))))
15635 (if (or (rassoc c1 ntable) (rassoc c1 table))
15636 (while (or (rassoc char ntable) (rassoc char table))
15637 (setq char (1+ char)))
15638 (setq c2 c1))
15639 (setq c (or c2 char)))
15640 (if ingroup (push tg (car groups)))
15641 (setq tg (org-add-props tg nil 'face
15642 (cond
15643 ((not (assoc tg table))
15644 (org-get-todo-face tg))
15645 ((member tg current) c-face)
15646 ((member tg inherited) i-face)
15647 (t nil))))
15648 (if (and (= cnt 0) (not ingroup)) (insert " "))
15649 (insert "[" c "] " tg (make-string
15650 (- fwidth 4 (length tg)) ?\ ))
15651 (push (cons tg c) ntable)
15652 (when (= (setq cnt (1+ cnt)) ncol)
15653 (insert "\n")
15654 (if ingroup (insert " "))
15655 (setq cnt 0)))))
15656 (setq ntable (nreverse ntable))
15657 (insert "\n")
15658 (goto-char (point-min))
15659 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15660 (fit-window-to-buffer))
15661 (setq rtn
15662 (catch 'exit
15663 (while t
15664 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15665 (if groups " [!] no groups" " [!]groups")
15666 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15667 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15668 (cond
15669 ((= c ?\r) (throw 'exit t))
15670 ((= c ?!)
15671 (setq groups (not groups))
15672 (goto-char (point-min))
15673 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15674 ((= c ?\C-c)
15675 (if (not expert)
15676 (org-fast-tag-show-exit
15677 (setq exit-after-next (not exit-after-next)))
15678 (setq expert nil)
15679 (delete-other-windows)
15680 (split-window-vertically)
15681 (org-switch-to-buffer-other-window " *Org tags*")
15682 (and (fboundp 'fit-window-to-buffer)
15683 (fit-window-to-buffer))))
15684 ((or (= c ?\C-g)
15685 (and (= c ?q) (not (rassoc c ntable))))
15686 (org-detach-overlay org-tags-overlay)
15687 (setq quit-flag t))
15688 ((= c ?\ )
15689 (setq current nil)
15690 (if exit-after-next (setq exit-after-next 'now)))
15691 ((= c ?\t)
15692 (condition-case nil
15693 (setq tg (completing-read
15694 "Tag: "
15695 (or buffer-tags
15696 (with-current-buffer buf
15697 (org-get-buffer-tags)))))
15698 (quit (setq tg "")))
15699 (when (string-match "\\S-" tg)
15700 (add-to-list 'buffer-tags (list tg))
15701 (if (member tg current)
15702 (setq current (delete tg current))
15703 (push tg current)))
15704 (if exit-after-next (setq exit-after-next 'now)))
15705 ((setq e (rassoc c todo-table) tg (car e))
15706 (with-current-buffer buf
15707 (save-excursion (org-todo tg)))
15708 (if exit-after-next (setq exit-after-next 'now)))
15709 ((setq e (rassoc c ntable) tg (car e))
15710 (if (member tg current)
15711 (setq current (delete tg current))
15712 (loop for g in groups do
15713 (if (member tg g)
15714 (mapc (lambda (x)
15715 (setq current (delete x current)))
15716 g)))
15717 (push tg current))
15718 (if exit-after-next (setq exit-after-next 'now))))
15720 ;; Create a sorted list
15721 (setq current
15722 (sort current
15723 (lambda (a b)
15724 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15725 (if (eq exit-after-next 'now) (throw 'exit t))
15726 (goto-char (point-min))
15727 (beginning-of-line 2)
15728 (delete-region (point) (point-at-eol))
15729 (org-fast-tag-insert "Current" current c-face)
15730 (org-set-current-tags-overlay current ov-prefix)
15731 (while (re-search-forward
15732 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15733 (setq tg (match-string 1))
15734 (add-text-properties
15735 (match-beginning 1) (match-end 1)
15736 (list 'face
15737 (cond
15738 ((member tg current) c-face)
15739 ((member tg inherited) i-face)
15740 (t (get-text-property (match-beginning 1) 'face))))))
15741 (goto-char (point-min)))))
15742 (org-detach-overlay org-tags-overlay)
15743 (if rtn
15744 (mapconcat 'identity current ":")
15745 nil))))
15747 (defun org-get-tags-string ()
15748 "Get the TAGS string in the current headline."
15749 (unless (org-on-heading-p t)
15750 (error "Not on a heading"))
15751 (save-excursion
15752 (beginning-of-line 1)
15753 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15754 (org-match-string-no-properties 1)
15755 "")))
15757 (defun org-get-tags ()
15758 "Get the list of tags specified in the current headline."
15759 (org-split-string (org-get-tags-string) ":"))
15761 (defun org-get-buffer-tags ()
15762 "Get a table of all tags used in the buffer, for completion."
15763 (let (tags)
15764 (save-excursion
15765 (goto-char (point-min))
15766 (while (re-search-forward
15767 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15768 (when (equal (char-after (point-at-bol 0)) ?*)
15769 (mapc (lambda (x) (add-to-list 'tags x))
15770 (org-split-string (org-match-string-no-properties 1) ":")))))
15771 (mapcar 'list tags)))
15774 ;;;; Properties
15776 ;;; Setting and retrieving properties
15778 (defconst org-special-properties
15779 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15780 "TIMESTAMP" "TIMESTAMP_IA")
15781 "The special properties valid in Org-mode.
15783 These are properties that are not defined in the property drawer,
15784 but in some other way.")
15786 (defconst org-default-properties
15787 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15788 "LOCATION" "LOGGING" "COLUMNS")
15789 "Some properties that are used by Org-mode for various purposes.
15790 Being in this list makes sure that they are offered for completion.")
15792 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15793 "Regular expression matching the first line of a property drawer.")
15795 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15796 "Regular expression matching the first line of a property drawer.")
15798 (defun org-property-action ()
15799 "Do an action on properties."
15800 (interactive)
15801 (let (c)
15802 (org-at-property-p)
15803 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15804 (setq c (read-char-exclusive))
15805 (cond
15806 ((equal c ?s)
15807 (call-interactively 'org-set-property))
15808 ((equal c ?d)
15809 (call-interactively 'org-delete-property))
15810 ((equal c ?D)
15811 (call-interactively 'org-delete-property-globally))
15812 ((equal c ?c)
15813 (call-interactively 'org-compute-property-at-point))
15814 (t (error "No such property action %c" c)))))
15816 (defun org-at-property-p ()
15817 "Is the cursor in a property line?"
15818 ;; FIXME: Does not check if we are actually in the drawer.
15819 ;; FIXME: also returns true on any drawers.....
15820 ;; This is used by C-c C-c for property action.
15821 (save-excursion
15822 (beginning-of-line 1)
15823 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15825 (defmacro org-with-point-at (pom &rest body)
15826 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15827 (declare (indent 1) (debug t))
15828 `(save-excursion
15829 (if (markerp pom) (set-buffer (marker-buffer pom)))
15830 (save-excursion
15831 (goto-char (or pom (point)))
15832 ,@body)))
15834 (defun org-get-property-block (&optional beg end force)
15835 "Return the (beg . end) range of the body of the property drawer.
15836 BEG and END can be beginning and end of subtree, if not given
15837 they will be found.
15838 If the drawer does not exist and FORCE is non-nil, create the drawer."
15839 (catch 'exit
15840 (save-excursion
15841 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15842 (end (or end (progn (outline-next-heading) (point)))))
15843 (goto-char beg)
15844 (if (re-search-forward org-property-start-re end t)
15845 (setq beg (1+ (match-end 0)))
15846 (if force
15847 (save-excursion
15848 (org-insert-property-drawer)
15849 (setq end (progn (outline-next-heading) (point))))
15850 (throw 'exit nil))
15851 (goto-char beg)
15852 (if (re-search-forward org-property-start-re end t)
15853 (setq beg (1+ (match-end 0)))))
15854 (if (re-search-forward org-property-end-re end t)
15855 (setq end (match-beginning 0))
15856 (or force (throw 'exit nil))
15857 (goto-char beg)
15858 (setq end beg)
15859 (org-indent-line-function)
15860 (insert ":END:\n"))
15861 (cons beg end)))))
15863 (defun org-entry-properties (&optional pom which)
15864 "Get all properties of the entry at point-or-marker POM.
15865 This includes the TODO keyword, the tags, time strings for deadline,
15866 scheduled, and clocking, and any additional properties defined in the
15867 entry. The return value is an alist, keys may occur multiple times
15868 if the property key was used several times.
15869 POM may also be nil, in which case the current entry is used.
15870 If WHICH is nil or `all', get all properties. If WHICH is
15871 `special' or `standard', only get that subclass."
15872 (setq which (or which 'all))
15873 (org-with-point-at pom
15874 (let ((clockstr (substring org-clock-string 0 -1))
15875 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15876 beg end range props sum-props key value string clocksum)
15877 (save-excursion
15878 (when (condition-case nil (org-back-to-heading t) (error nil))
15879 (setq beg (point))
15880 (setq sum-props (get-text-property (point) 'org-summaries))
15881 (setq clocksum (get-text-property (point) :org-clock-minutes))
15882 (outline-next-heading)
15883 (setq end (point))
15884 (when (memq which '(all special))
15885 ;; Get the special properties, like TODO and tags
15886 (goto-char beg)
15887 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15888 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15889 (when (looking-at org-priority-regexp)
15890 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15891 (when (and (setq value (org-get-tags-string))
15892 (string-match "\\S-" value))
15893 (push (cons "TAGS" value) props))
15894 (when (setq value (org-get-tags-at))
15895 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15896 props))
15897 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15898 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15899 string (if (equal key clockstr)
15900 (org-no-properties
15901 (org-trim
15902 (buffer-substring
15903 (match-beginning 3) (goto-char (point-at-eol)))))
15904 (substring (org-match-string-no-properties 3) 1 -1)))
15905 (unless key
15906 (if (= (char-after (match-beginning 3)) ?\[)
15907 (setq key "TIMESTAMP_IA")
15908 (setq key "TIMESTAMP")))
15909 (when (or (equal key clockstr) (not (assoc key props)))
15910 (push (cons key string) props)))
15914 (when (memq which '(all standard))
15915 ;; Get the standard properties, like :PORP: ...
15916 (setq range (org-get-property-block beg end))
15917 (when range
15918 (goto-char (car range))
15919 (while (re-search-forward
15920 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15921 (cdr range) t)
15922 (setq key (org-match-string-no-properties 1)
15923 value (org-trim (or (org-match-string-no-properties 2) "")))
15924 (unless (member key excluded)
15925 (push (cons key (or value "")) props)))))
15926 (if clocksum
15927 (push (cons "CLOCKSUM"
15928 (org-column-number-to-string (/ (float clocksum) 60.)
15929 'add_times))
15930 props))
15931 (append sum-props (nreverse props)))))))
15933 (defun org-entry-get (pom property &optional inherit)
15934 "Get value of PROPERTY for entry at point-or-marker POM.
15935 If INHERIT is non-nil and the entry does not have the property,
15936 then also check higher levels of the hierarchy.
15937 If the property is present but empty, the return value is the empty string.
15938 If the property is not present at all, nil is returned."
15939 (org-with-point-at pom
15940 (if inherit
15941 (org-entry-get-with-inheritance property)
15942 (if (member property org-special-properties)
15943 ;; We need a special property. Use brute force, get all properties.
15944 (cdr (assoc property (org-entry-properties nil 'special)))
15945 (let ((range (org-get-property-block)))
15946 (if (and range
15947 (goto-char (car range))
15948 (re-search-forward
15949 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
15950 (cdr range) t))
15951 ;; Found the property, return it.
15952 (if (match-end 1)
15953 (org-match-string-no-properties 1)
15954 "")))))))
15956 (defun org-entry-delete (pom property)
15957 "Delete the property PROPERTY from entry at point-or-marker POM."
15958 (org-with-point-at pom
15959 (if (member property org-special-properties)
15960 nil ; cannot delete these properties.
15961 (let ((range (org-get-property-block)))
15962 (if (and range
15963 (goto-char (car range))
15964 (re-search-forward
15965 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
15966 (cdr range) t))
15967 (progn
15968 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15970 nil)))))
15972 ;; Multi-values properties are properties that contain multiple values
15973 ;; These values are assumed to be single words, separated by whitespace.
15974 (defun org-entry-add-to-multivalued-property (pom property value)
15975 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15976 (let* ((old (org-entry-get pom property))
15977 (values (and old (org-split-string old "[ \t]"))))
15978 (unless (member value values)
15979 (setq values (cons value values))
15980 (org-entry-put pom property
15981 (mapconcat 'identity values " ")))))
15983 (defun org-entry-remove-from-multivalued-property (pom property value)
15984 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15985 (let* ((old (org-entry-get pom property))
15986 (values (and old (org-split-string old "[ \t]"))))
15987 (when (member value values)
15988 (setq values (delete value values))
15989 (org-entry-put pom property
15990 (mapconcat 'identity values " ")))))
15992 (defun org-entry-member-in-multivalued-property (pom property value)
15993 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15994 (let* ((old (org-entry-get pom property))
15995 (values (and old (org-split-string old "[ \t]"))))
15996 (member value values)))
15998 (defvar org-entry-property-inherited-from (make-marker))
16000 (defun org-entry-get-with-inheritance (property)
16001 "Get entry property, and search higher levels if not present."
16002 (let (tmp)
16003 (save-excursion
16004 (save-restriction
16005 (widen)
16006 (catch 'ex
16007 (while t
16008 (when (setq tmp (org-entry-get nil property))
16009 (org-back-to-heading t)
16010 (move-marker org-entry-property-inherited-from (point))
16011 (throw 'ex tmp))
16012 (or (org-up-heading-safe) (throw 'ex nil)))))
16013 (or tmp (cdr (assoc property org-local-properties))
16014 (cdr (assoc property org-global-properties))))))
16016 (defun org-entry-put (pom property value)
16017 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16018 (org-with-point-at pom
16019 (org-back-to-heading t)
16020 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16021 range)
16022 (cond
16023 ((equal property "TODO")
16024 (when (and (stringp value) (string-match "\\S-" value)
16025 (not (member value org-todo-keywords-1)))
16026 (error "\"%s\" is not a valid TODO state" value))
16027 (if (or (not value)
16028 (not (string-match "\\S-" value)))
16029 (setq value 'none))
16030 (org-todo value)
16031 (org-set-tags nil 'align))
16032 ((equal property "PRIORITY")
16033 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16034 (string-to-char value) ?\ ))
16035 (org-set-tags nil 'align))
16036 ((equal property "SCHEDULED")
16037 (if (re-search-forward org-scheduled-time-regexp end t)
16038 (cond
16039 ((eq value 'earlier) (org-timestamp-change -1 'day))
16040 ((eq value 'later) (org-timestamp-change 1 'day))
16041 (t (call-interactively 'org-schedule)))
16042 (call-interactively 'org-schedule)))
16043 ((equal property "DEADLINE")
16044 (if (re-search-forward org-deadline-time-regexp end t)
16045 (cond
16046 ((eq value 'earlier) (org-timestamp-change -1 'day))
16047 ((eq value 'later) (org-timestamp-change 1 'day))
16048 (t (call-interactively 'org-deadline)))
16049 (call-interactively 'org-deadline)))
16050 ((member property org-special-properties)
16051 (error "The %s property can not yet be set with `org-entry-put'"
16052 property))
16053 (t ; a non-special property
16054 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16055 (setq range (org-get-property-block beg end 'force))
16056 (goto-char (car range))
16057 (if (re-search-forward
16058 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16059 (progn
16060 (delete-region (match-beginning 1) (match-end 1))
16061 (goto-char (match-beginning 1)))
16062 (goto-char (cdr range))
16063 (insert "\n")
16064 (backward-char 1)
16065 (org-indent-line-function)
16066 (insert ":" property ":"))
16067 (and value (insert " " value))
16068 (org-indent-line-function)))))))
16070 (defun org-buffer-property-keys (&optional include-specials include-defaults)
16071 "Get all property keys in the current buffer.
16072 With INCLUDE-SPECIALS, also list the special properties that relect things
16073 like tags and TODO state.
16074 With INCLUDE-DEFAULTS, also include properties that has special meaning
16075 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
16076 (let (rtn range)
16077 (save-excursion
16078 (save-restriction
16079 (widen)
16080 (goto-char (point-min))
16081 (while (re-search-forward org-property-start-re nil t)
16082 (setq range (org-get-property-block))
16083 (goto-char (car range))
16084 (while (re-search-forward
16085 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
16086 (cdr range) t)
16087 (add-to-list 'rtn (org-match-string-no-properties 1)))
16088 (outline-next-heading))))
16090 (when include-specials
16091 (setq rtn (append org-special-properties rtn)))
16093 (when include-defaults
16094 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16096 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16098 (defun org-property-values (key)
16099 "Return a list of all values of property KEY."
16100 (save-excursion
16101 (save-restriction
16102 (widen)
16103 (goto-char (point-min))
16104 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16105 values)
16106 (while (re-search-forward re nil t)
16107 (add-to-list 'values (org-trim (match-string 1))))
16108 (delete "" values)))))
16110 (defun org-insert-property-drawer ()
16111 "Insert a property drawer into the current entry."
16112 (interactive)
16113 (org-back-to-heading t)
16114 (looking-at outline-regexp)
16115 (let ((indent (- (match-end 0)(match-beginning 0)))
16116 (beg (point))
16117 (re (concat "^[ \t]*" org-keyword-time-regexp))
16118 end hiddenp)
16119 (outline-next-heading)
16120 (setq end (point))
16121 (goto-char beg)
16122 (while (re-search-forward re end t))
16123 (setq hiddenp (org-invisible-p))
16124 (end-of-line 1)
16125 (and (equal (char-after) ?\n) (forward-char 1))
16126 (org-skip-over-state-notes)
16127 (skip-chars-backward " \t\n\r")
16128 (if (eq (char-before) ?*) (forward-char 1))
16129 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16130 (beginning-of-line 0)
16131 (indent-to-column indent)
16132 (beginning-of-line 2)
16133 (indent-to-column indent)
16134 (beginning-of-line 0)
16135 (if hiddenp
16136 (save-excursion
16137 (org-back-to-heading t)
16138 (hide-entry))
16139 (org-flag-drawer t))))
16141 (defun org-set-property (property value)
16142 "In the current entry, set PROPERTY to VALUE.
16143 When called interactively, this will prompt for a property name, offering
16144 completion on existing and default properties. And then it will prompt
16145 for a value, offering competion either on allowed values (via an inherited
16146 xxx_ALL property) or on existing values in other instances of this property
16147 in the current file."
16148 (interactive
16149 (let* ((prop (completing-read
16150 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
16151 (cur (org-entry-get nil prop))
16152 (allowed (org-property-get-allowed-values nil prop 'table))
16153 (existing (mapcar 'list (org-property-values prop)))
16154 (val (if allowed
16155 (completing-read "Value: " allowed nil 'req-match)
16156 (completing-read
16157 (concat "Value" (if (and cur (string-match "\\S-" cur))
16158 (concat "[" cur "]") "")
16159 ": ")
16160 existing nil nil "" nil cur))))
16161 (list prop (if (equal val "") cur val))))
16162 (unless (equal (org-entry-get nil property) value)
16163 (org-entry-put nil property value)))
16165 (defun org-delete-property (property)
16166 "In the current entry, delete PROPERTY."
16167 (interactive
16168 (let* ((prop (completing-read
16169 "Property: " (org-entry-properties nil 'standard))))
16170 (list prop)))
16171 (message "Property %s %s" property
16172 (if (org-entry-delete nil property)
16173 "deleted"
16174 "was not present in the entry")))
16176 (defun org-delete-property-globally (property)
16177 "Remove PROPERTY globally, from all entries."
16178 (interactive
16179 (let* ((prop (completing-read
16180 "Globally remove property: "
16181 (mapcar 'list (org-buffer-property-keys)))))
16182 (list prop)))
16183 (save-excursion
16184 (save-restriction
16185 (widen)
16186 (goto-char (point-min))
16187 (let ((cnt 0))
16188 (while (re-search-forward
16189 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16190 nil t)
16191 (setq cnt (1+ cnt))
16192 (replace-match ""))
16193 (message "Property \"%s\" removed from %d entries" property cnt)))))
16195 (defvar org-columns-current-fmt-compiled) ; defined below
16197 (defun org-compute-property-at-point ()
16198 "Compute the property at point.
16199 This looks for an enclosing column format, extracts the operator and
16200 then applies it to the proerty in the column format's scope."
16201 (interactive)
16202 (unless (org-at-property-p)
16203 (error "Not at a property"))
16204 (let ((prop (org-match-string-no-properties 2)))
16205 (org-columns-get-format-and-top-level)
16206 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16207 (error "No operator defined for property %s" prop))
16208 (org-columns-compute prop)))
16210 (defun org-property-get-allowed-values (pom property &optional table)
16211 "Get allowed values for the property PROPERTY.
16212 When TABLE is non-nil, return an alist that can directly be used for
16213 completion."
16214 (let (vals)
16215 (cond
16216 ((equal property "TODO")
16217 (setq vals (org-with-point-at pom
16218 (append org-todo-keywords-1 '("")))))
16219 ((equal property "PRIORITY")
16220 (let ((n org-lowest-priority))
16221 (while (>= n org-highest-priority)
16222 (push (char-to-string n) vals)
16223 (setq n (1- n)))))
16224 ((member property org-special-properties))
16226 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16228 (when (and vals (string-match "\\S-" vals))
16229 (setq vals (car (read-from-string (concat "(" vals ")"))))
16230 (setq vals (mapcar (lambda (x)
16231 (cond ((stringp x) x)
16232 ((numberp x) (number-to-string x))
16233 ((symbolp x) (symbol-name x))
16234 (t "???")))
16235 vals)))))
16236 (if table (mapcar 'list vals) vals)))
16238 (defun org-property-previous-allowed-value (&optional previous)
16239 "Switch to the next allowed value for this property."
16240 (interactive)
16241 (org-property-next-allowed-value t))
16243 (defun org-property-next-allowed-value (&optional previous)
16244 "Switch to the next allowed value for this property."
16245 (interactive)
16246 (unless (org-at-property-p)
16247 (error "Not at a property"))
16248 (let* ((key (match-string 2))
16249 (value (match-string 3))
16250 (allowed (or (org-property-get-allowed-values (point) key)
16251 (and (member value '("[ ]" "[-]" "[X]"))
16252 '("[ ]" "[X]"))))
16253 nval)
16254 (unless allowed
16255 (error "Allowed values for this property have not been defined"))
16256 (if previous (setq allowed (reverse allowed)))
16257 (if (member value allowed)
16258 (setq nval (car (cdr (member value allowed)))))
16259 (setq nval (or nval (car allowed)))
16260 (if (equal nval value)
16261 (error "Only one allowed value for this property"))
16262 (org-at-property-p)
16263 (replace-match (concat " :" key ": " nval) t t)
16264 (org-indent-line-function)
16265 (beginning-of-line 1)
16266 (skip-chars-forward " \t")))
16268 (defun org-find-entry-with-id (ident)
16269 "Locate the entry that contains the ID property with exact value IDENT.
16270 IDENT can be a string, a symbol or a number, this function will search for
16271 the string representation of it.
16272 Return the position where this entry starts, or nil if there is no such entry."
16273 (let ((id (cond
16274 ((stringp ident) ident)
16275 ((symbol-name ident) (symbol-name ident))
16276 ((numberp ident) (number-to-string ident))
16277 (t (error "IDENT %s must be a string, symbol or number" ident))))
16278 (case-fold-search nil))
16279 (save-excursion
16280 (save-restriction
16281 (goto-char (point-min))
16282 (when (re-search-forward
16283 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16284 nil t)
16285 (org-back-to-heading)
16286 (point))))))
16288 ;;; Column View
16290 (defvar org-columns-overlays nil
16291 "Holds the list of current column overlays.")
16293 (defvar org-columns-current-fmt nil
16294 "Local variable, holds the currently active column format.")
16295 (defvar org-columns-current-fmt-compiled nil
16296 "Local variable, holds the currently active column format.
16297 This is the compiled version of the format.")
16298 (defvar org-columns-current-widths nil
16299 "Loval variable, holds the currently widths of fields.")
16300 (defvar org-columns-current-maxwidths nil
16301 "Loval variable, holds the currently active maximum column widths.")
16302 (defvar org-columns-begin-marker (make-marker)
16303 "Points to the position where last a column creation command was called.")
16304 (defvar org-columns-top-level-marker (make-marker)
16305 "Points to the position where current columns region starts.")
16307 (defvar org-columns-map (make-sparse-keymap)
16308 "The keymap valid in column display.")
16310 (defun org-columns-content ()
16311 "Switch to contents view while in columns view."
16312 (interactive)
16313 (org-overview)
16314 (org-content))
16316 (org-defkey org-columns-map "c" 'org-columns-content)
16317 (org-defkey org-columns-map "o" 'org-overview)
16318 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16319 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16320 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16321 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16322 (org-defkey org-columns-map "v" 'org-columns-show-value)
16323 (org-defkey org-columns-map "q" 'org-columns-quit)
16324 (org-defkey org-columns-map "r" 'org-columns-redo)
16325 (org-defkey org-columns-map "g" 'org-columns-redo)
16326 (org-defkey org-columns-map [left] 'backward-char)
16327 (org-defkey org-columns-map "\M-b" 'backward-char)
16328 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16329 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16330 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16331 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16332 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16333 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16334 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16335 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16336 (org-defkey org-columns-map "<" 'org-columns-narrow)
16337 (org-defkey org-columns-map ">" 'org-columns-widen)
16338 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16339 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16340 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16341 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16343 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16344 '("Column"
16345 ["Edit property" org-columns-edit-value t]
16346 ["Next allowed value" org-columns-next-allowed-value t]
16347 ["Previous allowed value" org-columns-previous-allowed-value t]
16348 ["Show full value" org-columns-show-value t]
16349 ["Edit allowed values" org-columns-edit-allowed t]
16350 "--"
16351 ["Edit column attributes" org-columns-edit-attributes t]
16352 ["Increase column width" org-columns-widen t]
16353 ["Decrease column width" org-columns-narrow t]
16354 "--"
16355 ["Move column right" org-columns-move-right t]
16356 ["Move column left" org-columns-move-left t]
16357 ["Add column" org-columns-new t]
16358 ["Delete column" org-columns-delete t]
16359 "--"
16360 ["CONTENTS" org-columns-content t]
16361 ["OVERVIEW" org-overview t]
16362 ["Refresh columns display" org-columns-redo t]
16363 "--"
16364 ["Open link" org-columns-open-link t]
16365 "--"
16366 ["Quit" org-columns-quit t]))
16368 (defun org-columns-new-overlay (beg end &optional string face)
16369 "Create a new column overlay and add it to the list."
16370 (let ((ov (org-make-overlay beg end)))
16371 (org-overlay-put ov 'face (or face 'secondary-selection))
16372 (org-overlay-display ov string face)
16373 (push ov org-columns-overlays)
16374 ov))
16376 (defun org-columns-display-here (&optional props)
16377 "Overlay the current line with column display."
16378 (interactive)
16379 (let* ((fmt org-columns-current-fmt-compiled)
16380 (beg (point-at-bol))
16381 (level-face (save-excursion
16382 (beginning-of-line 1)
16383 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16384 (org-get-level-face 2))))
16385 (color (list :foreground
16386 (face-attribute (or level-face 'default) :foreground)))
16387 props pom property ass width f string ov column val modval)
16388 ;; Check if the entry is in another buffer.
16389 (unless props
16390 (if (eq major-mode 'org-agenda-mode)
16391 (setq pom (or (get-text-property (point) 'org-hd-marker)
16392 (get-text-property (point) 'org-marker))
16393 props (if pom (org-entry-properties pom) nil))
16394 (setq props (org-entry-properties nil))))
16395 ;; Walk the format
16396 (while (setq column (pop fmt))
16397 (setq property (car column)
16398 ass (if (equal property "ITEM")
16399 (cons "ITEM"
16400 (save-match-data
16401 (org-no-properties
16402 (org-remove-tabs
16403 (buffer-substring-no-properties
16404 (point-at-bol) (point-at-eol))))))
16405 (assoc property props))
16406 width (or (cdr (assoc property org-columns-current-maxwidths))
16407 (nth 2 column)
16408 (length property))
16409 f (format "%%-%d.%ds | " width width)
16410 val (or (cdr ass) "")
16411 modval (if (equal property "ITEM")
16412 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16413 string (format f (or modval val)))
16414 ;; Create the overlay
16415 (org-unmodified
16416 (setq ov (org-columns-new-overlay
16417 beg (setq beg (1+ beg)) string
16418 (list color 'org-column)))
16419 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16420 (org-overlay-put ov 'keymap org-columns-map)
16421 (org-overlay-put ov 'org-columns-key property)
16422 (org-overlay-put ov 'org-columns-value (cdr ass))
16423 (org-overlay-put ov 'org-columns-value-modified modval)
16424 (org-overlay-put ov 'org-columns-pom pom)
16425 (org-overlay-put ov 'org-columns-format f))
16426 (if (or (not (char-after beg))
16427 (equal (char-after beg) ?\n))
16428 (let ((inhibit-read-only t))
16429 (save-excursion
16430 (goto-char beg)
16431 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16432 ;; Make the rest of the line disappear.
16433 (org-unmodified
16434 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16435 (org-overlay-put ov 'invisible t)
16436 (org-overlay-put ov 'keymap org-columns-map)
16437 (org-overlay-put ov 'intangible t)
16438 (push ov org-columns-overlays)
16439 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16440 (org-overlay-put ov 'keymap org-columns-map)
16441 (push ov org-columns-overlays)
16442 (let ((inhibit-read-only t))
16443 (put-text-property (max (point-min) (1- (point-at-bol)))
16444 (min (point-max) (1+ (point-at-eol)))
16445 'read-only "Type `e' to edit property")))))
16447 (defvar org-previous-header-line-format nil
16448 "The header line format before column view was turned on.")
16449 (defvar org-columns-inhibit-recalculation nil
16450 "Inhibit recomputing of columns on column view startup.")
16453 (defvar header-line-format)
16454 (defun org-columns-display-here-title ()
16455 "Overlay the newline before the current line with the table title."
16456 (interactive)
16457 (let ((fmt org-columns-current-fmt-compiled)
16458 string (title "")
16459 property width f column str widths)
16460 (while (setq column (pop fmt))
16461 (setq property (car column)
16462 str (or (nth 1 column) property)
16463 width (or (cdr (assoc property org-columns-current-maxwidths))
16464 (nth 2 column)
16465 (length str))
16466 widths (push width widths)
16467 f (format "%%-%d.%ds | " width width)
16468 string (format f str)
16469 title (concat title string)))
16470 (setq title (concat
16471 (org-add-props " " nil 'display '(space :align-to 0))
16472 (org-add-props title nil 'face '(:weight bold :underline t))))
16473 (org-set-local 'org-previous-header-line-format header-line-format)
16474 (org-set-local 'org-columns-current-widths (nreverse widths))
16475 (setq header-line-format title)))
16477 (defun org-columns-remove-overlays ()
16478 "Remove all currently active column overlays."
16479 (interactive)
16480 (when (marker-buffer org-columns-begin-marker)
16481 (with-current-buffer (marker-buffer org-columns-begin-marker)
16482 (when (local-variable-p 'org-previous-header-line-format)
16483 (setq header-line-format org-previous-header-line-format)
16484 (kill-local-variable 'org-previous-header-line-format))
16485 (move-marker org-columns-begin-marker nil)
16486 (move-marker org-columns-top-level-marker nil)
16487 (org-unmodified
16488 (mapc 'org-delete-overlay org-columns-overlays)
16489 (setq org-columns-overlays nil)
16490 (let ((inhibit-read-only t))
16491 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16493 (defun org-columns-cleanup-item (item fmt)
16494 "Remove from ITEM what is a column in the format FMT."
16495 (if (not org-complex-heading-regexp)
16496 item
16497 (when (string-match org-complex-heading-regexp item)
16498 (concat
16499 (org-add-props (concat (match-string 1 item) " ") nil
16500 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16501 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16502 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16503 " " (match-string 4 item)
16504 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16506 (defun org-columns-show-value ()
16507 "Show the full value of the property."
16508 (interactive)
16509 (let ((value (get-char-property (point) 'org-columns-value)))
16510 (message "Value is: %s" (or value ""))))
16512 (defun org-columns-quit ()
16513 "Remove the column overlays and in this way exit column editing."
16514 (interactive)
16515 (org-unmodified
16516 (org-columns-remove-overlays)
16517 (let ((inhibit-read-only t))
16518 (remove-text-properties (point-min) (point-max) '(read-only t))))
16519 (when (eq major-mode 'org-agenda-mode)
16520 (message
16521 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16523 (defun org-columns-check-computed ()
16524 "Check if this column value is computed.
16525 If yes, throw an error indicating that changing it does not make sense."
16526 (let ((val (get-char-property (point) 'org-columns-value)))
16527 (when (and (stringp val)
16528 (get-char-property 0 'org-computed val))
16529 (error "This value is computed from the entry's children"))))
16531 (defun org-columns-todo (&optional arg)
16532 "Change the TODO state during column view."
16533 (interactive "P")
16534 (org-columns-edit-value "TODO"))
16536 (defun org-columns-set-tags-or-toggle (&optional arg)
16537 "Toggle checkbox at point, or set tags for current headline."
16538 (interactive "P")
16539 (if (string-match "\\`\\[[ xX-]\\]\\'"
16540 (get-char-property (point) 'org-columns-value))
16541 (org-columns-next-allowed-value)
16542 (org-columns-edit-value "TAGS")))
16544 (defun org-columns-edit-value (&optional key)
16545 "Edit the value of the property at point in column view.
16546 Where possible, use the standard interface for changing this line."
16547 (interactive)
16548 (org-columns-check-computed)
16549 (let* ((external-key key)
16550 (col (current-column))
16551 (key (or key (get-char-property (point) 'org-columns-key)))
16552 (value (get-char-property (point) 'org-columns-value))
16553 (bol (point-at-bol)) (eol (point-at-eol))
16554 (pom (or (get-text-property bol 'org-hd-marker)
16555 (point))) ; keep despite of compiler waring
16556 (line-overlays
16557 (delq nil (mapcar (lambda (x)
16558 (and (eq (overlay-buffer x) (current-buffer))
16559 (>= (overlay-start x) bol)
16560 (<= (overlay-start x) eol)
16562 org-columns-overlays)))
16563 nval eval allowed)
16564 (cond
16565 ((equal key "CLOCKSUM")
16566 (error "This special column cannot be edited"))
16567 ((equal key "ITEM")
16568 (setq eval '(org-with-point-at pom
16569 (org-edit-headline))))
16570 ((equal key "TODO")
16571 (setq eval '(org-with-point-at pom
16572 (let ((current-prefix-arg
16573 (if external-key current-prefix-arg '(4))))
16574 (call-interactively 'org-todo)))))
16575 ((equal key "PRIORITY")
16576 (setq eval '(org-with-point-at pom
16577 (call-interactively 'org-priority))))
16578 ((equal key "TAGS")
16579 (setq eval '(org-with-point-at pom
16580 (let ((org-fast-tag-selection-single-key
16581 (if (eq org-fast-tag-selection-single-key 'expert)
16582 t org-fast-tag-selection-single-key)))
16583 (call-interactively 'org-set-tags)))))
16584 ((equal key "DEADLINE")
16585 (setq eval '(org-with-point-at pom
16586 (call-interactively 'org-deadline))))
16587 ((equal key "SCHEDULED")
16588 (setq eval '(org-with-point-at pom
16589 (call-interactively 'org-schedule))))
16591 (setq allowed (org-property-get-allowed-values pom key 'table))
16592 (if allowed
16593 (setq nval (completing-read "Value: " allowed nil t))
16594 (setq nval (read-string "Edit: " value)))
16595 (setq nval (org-trim nval))
16596 (when (not (equal nval value))
16597 (setq eval '(org-entry-put pom key nval)))))
16598 (when eval
16599 (let ((inhibit-read-only t))
16600 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16601 (unwind-protect
16602 (progn
16603 (setq org-columns-overlays
16604 (org-delete-all line-overlays org-columns-overlays))
16605 (mapc 'org-delete-overlay line-overlays)
16606 (org-columns-eval eval))
16607 (org-columns-display-here))))
16608 (move-to-column col)
16609 (if (and (org-mode-p)
16610 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16611 (org-columns-update key))))
16613 (defun org-edit-headline () ; FIXME: this is not columns specific
16614 "Edit the current headline, the part without TODO keyword, TAGS."
16615 (org-back-to-heading)
16616 (when (looking-at org-todo-line-regexp)
16617 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16618 (txt (match-string 3))
16619 (post "")
16620 txt2)
16621 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16622 (setq post (match-string 0 txt)
16623 txt (substring txt 0 (match-beginning 0))))
16624 (setq txt2 (read-string "Edit: " txt))
16625 (when (not (equal txt txt2))
16626 (beginning-of-line 1)
16627 (insert pre txt2 post)
16628 (delete-region (point) (point-at-eol))
16629 (org-set-tags nil t)))))
16631 (defun org-columns-edit-allowed ()
16632 "Edit the list of allowed values for the current property."
16633 (interactive)
16634 (let* ((key (get-char-property (point) 'org-columns-key))
16635 (key1 (concat key "_ALL"))
16636 (allowed (org-entry-get (point) key1 t))
16637 nval)
16638 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16639 (setq nval (read-string "Allowed: " allowed))
16640 (org-entry-put
16641 (cond ((marker-position org-entry-property-inherited-from)
16642 org-entry-property-inherited-from)
16643 ((marker-position org-columns-top-level-marker)
16644 org-columns-top-level-marker))
16645 key1 nval)))
16647 (defmacro org-no-warnings (&rest body)
16648 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16650 (defun org-columns-eval (form)
16651 (let (hidep)
16652 (save-excursion
16653 (beginning-of-line 1)
16654 ;; `next-line' is needed here, because it skips invisible line.
16655 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16656 (setq hidep (org-on-heading-p 1)))
16657 (eval form)
16658 (and hidep (hide-entry))))
16660 (defun org-columns-previous-allowed-value ()
16661 "Switch to the previous allowed value for this column."
16662 (interactive)
16663 (org-columns-next-allowed-value t))
16665 (defun org-columns-next-allowed-value (&optional previous)
16666 "Switch to the next allowed value for this column."
16667 (interactive)
16668 (org-columns-check-computed)
16669 (let* ((col (current-column))
16670 (key (get-char-property (point) 'org-columns-key))
16671 (value (get-char-property (point) 'org-columns-value))
16672 (bol (point-at-bol)) (eol (point-at-eol))
16673 (pom (or (get-text-property bol 'org-hd-marker)
16674 (point))) ; keep despite of compiler waring
16675 (line-overlays
16676 (delq nil (mapcar (lambda (x)
16677 (and (eq (overlay-buffer x) (current-buffer))
16678 (>= (overlay-start x) bol)
16679 (<= (overlay-start x) eol)
16681 org-columns-overlays)))
16682 (allowed (or (org-property-get-allowed-values pom key)
16683 (and (equal
16684 (nth 4 (assoc key org-columns-current-fmt-compiled))
16685 'checkbox) '("[ ]" "[X]"))))
16686 nval)
16687 (when (equal key "ITEM")
16688 (error "Cannot edit item headline from here"))
16689 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16690 (error "Allowed values for this property have not been defined"))
16691 (if (member key '("SCHEDULED" "DEADLINE"))
16692 (setq nval (if previous 'earlier 'later))
16693 (if previous (setq allowed (reverse allowed)))
16694 (if (member value allowed)
16695 (setq nval (car (cdr (member value allowed)))))
16696 (setq nval (or nval (car allowed)))
16697 (if (equal nval value)
16698 (error "Only one allowed value for this property")))
16699 (let ((inhibit-read-only t))
16700 (remove-text-properties (1- bol) eol '(read-only t))
16701 (unwind-protect
16702 (progn
16703 (setq org-columns-overlays
16704 (org-delete-all line-overlays org-columns-overlays))
16705 (mapc 'org-delete-overlay line-overlays)
16706 (org-columns-eval '(org-entry-put pom key nval)))
16707 (org-columns-display-here)))
16708 (move-to-column col)
16709 (if (and (org-mode-p)
16710 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16711 (org-columns-update key))))
16713 (defun org-verify-version (task)
16714 (cond
16715 ((eq task 'columns)
16716 (if (or (featurep 'xemacs)
16717 (< emacs-major-version 22))
16718 (error "Emacs 22 is required for the columns feature")))))
16720 (defun org-columns-open-link (&optional arg)
16721 (interactive "P")
16722 (let ((key (get-char-property (point) 'org-columns-key))
16723 (value (get-char-property (point) 'org-columns-value)))
16724 (org-open-link-from-string arg)))
16726 (defun org-open-link-from-string (s &optional arg)
16727 "Open a link in the string S, as if it was in Org-mode."
16728 (interactive)
16729 (with-temp-buffer
16730 (let ((org-inhibit-startup t))
16731 (org-mode)
16732 (insert s)
16733 (goto-char (point-min))
16734 (org-open-at-point arg))))
16736 (defun org-columns-get-format-and-top-level ()
16737 (let (fmt)
16738 (when (condition-case nil (org-back-to-heading) (error nil))
16739 (move-marker org-entry-property-inherited-from nil)
16740 (setq fmt (org-entry-get nil "COLUMNS" t)))
16741 (setq fmt (or fmt org-columns-default-format))
16742 (org-set-local 'org-columns-current-fmt fmt)
16743 (org-columns-compile-format fmt)
16744 (if (marker-position org-entry-property-inherited-from)
16745 (move-marker org-columns-top-level-marker
16746 org-entry-property-inherited-from)
16747 (move-marker org-columns-top-level-marker (point)))
16748 fmt))
16750 (defun org-columns ()
16751 "Turn on column view on an org-mode file."
16752 (interactive)
16753 (org-verify-version 'columns)
16754 (org-columns-remove-overlays)
16755 (move-marker org-columns-begin-marker (point))
16756 (let (beg end fmt cache maxwidths clocksump)
16757 (setq fmt (org-columns-get-format-and-top-level))
16758 (save-excursion
16759 (goto-char org-columns-top-level-marker)
16760 (setq beg (point))
16761 (unless org-columns-inhibit-recalculation
16762 (org-columns-compute-all))
16763 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16764 (point-max)))
16765 ;; Get and cache the properties
16766 (goto-char beg)
16767 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16768 (setq clocksump t)
16769 (save-excursion
16770 (save-restriction
16771 (narrow-to-region beg end)
16772 (org-clock-sum))))
16773 (while (re-search-forward (concat "^" outline-regexp) end t)
16774 (push (cons (org-current-line) (org-entry-properties)) cache))
16775 (when cache
16776 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16777 (org-set-local 'org-columns-current-maxwidths maxwidths)
16778 (org-columns-display-here-title)
16779 (mapc (lambda (x)
16780 (goto-line (car x))
16781 (org-columns-display-here (cdr x)))
16782 cache)))))
16784 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16785 "Insert a new column, to the leeft o the current column."
16786 (interactive)
16787 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16788 cell)
16789 (setq prop (completing-read
16790 "Property: " (mapcar 'list (org-buffer-property-keys t))
16791 nil nil prop))
16792 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16793 (setq width (read-string "Column width: " (if width (number-to-string width))))
16794 (if (string-match "\\S-" width)
16795 (setq width (string-to-number width))
16796 (setq width nil))
16797 (setq fmt (completing-read "Summary [none]: "
16798 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16799 nil t))
16800 (if (string-match "\\S-" fmt)
16801 (setq fmt (intern fmt))
16802 (setq fmt nil))
16803 (if (eq fmt 'none) (setq fmt nil))
16804 (if editp
16805 (progn
16806 (setcar editp prop)
16807 (setcdr editp (list title width nil fmt)))
16808 (setq cell (nthcdr (1- (current-column))
16809 org-columns-current-fmt-compiled))
16810 (setcdr cell (cons (list prop title width nil fmt)
16811 (cdr cell))))
16812 (org-columns-store-format)
16813 (org-columns-redo)))
16815 (defun org-columns-delete ()
16816 "Delete the column at point from columns view."
16817 (interactive)
16818 (let* ((n (current-column))
16819 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16820 (when (y-or-n-p
16821 (format "Are you sure you want to remove column \"%s\"? " title))
16822 (setq org-columns-current-fmt-compiled
16823 (delq (nth n org-columns-current-fmt-compiled)
16824 org-columns-current-fmt-compiled))
16825 (org-columns-store-format)
16826 (org-columns-redo)
16827 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16828 (backward-char 1)))))
16830 (defun org-columns-edit-attributes ()
16831 "Edit the attributes of the current column."
16832 (interactive)
16833 (let* ((n (current-column))
16834 (info (nth n org-columns-current-fmt-compiled)))
16835 (apply 'org-columns-new info)))
16837 (defun org-columns-widen (arg)
16838 "Make the column wider by ARG characters."
16839 (interactive "p")
16840 (let* ((n (current-column))
16841 (entry (nth n org-columns-current-fmt-compiled))
16842 (width (or (nth 2 entry)
16843 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16844 (setq width (max 1 (+ width arg)))
16845 (setcar (nthcdr 2 entry) width)
16846 (org-columns-store-format)
16847 (org-columns-redo)))
16849 (defun org-columns-narrow (arg)
16850 "Make the column nrrower by ARG characters."
16851 (interactive "p")
16852 (org-columns-widen (- arg)))
16854 (defun org-columns-move-right ()
16855 "Swap this column with the one to the right."
16856 (interactive)
16857 (let* ((n (current-column))
16858 (cell (nthcdr n org-columns-current-fmt-compiled))
16860 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16861 (error "Cannot shift this column further to the right"))
16862 (setq e (car cell))
16863 (setcar cell (car (cdr cell)))
16864 (setcdr cell (cons e (cdr (cdr cell))))
16865 (org-columns-store-format)
16866 (org-columns-redo)
16867 (forward-char 1)))
16869 (defun org-columns-move-left ()
16870 "Swap this column with the one to the left."
16871 (interactive)
16872 (let* ((n (current-column)))
16873 (when (= n 0)
16874 (error "Cannot shift this column further to the left"))
16875 (backward-char 1)
16876 (org-columns-move-right)
16877 (backward-char 1)))
16879 (defun org-columns-store-format ()
16880 "Store the text version of the current columns format in appropriate place.
16881 This is either in the COLUMNS property of the node starting the current column
16882 display, or in the #+COLUMNS line of the current buffer."
16883 (let (fmt (cnt 0))
16884 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16885 (org-set-local 'org-columns-current-fmt fmt)
16886 (if (marker-position org-columns-top-level-marker)
16887 (save-excursion
16888 (goto-char org-columns-top-level-marker)
16889 (if (and (org-at-heading-p)
16890 (org-entry-get nil "COLUMNS"))
16891 (org-entry-put nil "COLUMNS" fmt)
16892 (goto-char (point-min))
16893 ;; Overwrite all #+COLUMNS lines....
16894 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16895 (setq cnt (1+ cnt))
16896 (replace-match (concat "#+COLUMNS: " fmt) t t))
16897 (unless (> cnt 0)
16898 (goto-char (point-min))
16899 (or (org-on-heading-p t) (outline-next-heading))
16900 (let ((inhibit-read-only t))
16901 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16902 (org-set-local 'org-columns-default-format fmt))))))
16904 (defvar org-overriding-columns-format nil
16905 "When set, overrides any other definition.")
16906 (defvar org-agenda-view-columns-initially nil
16907 "When set, switch to columns view immediately after creating the agenda.")
16909 (defun org-agenda-columns ()
16910 "Turn on column view in the agenda."
16911 (interactive)
16912 (org-verify-version 'columns)
16913 (org-columns-remove-overlays)
16914 (move-marker org-columns-begin-marker (point))
16915 (let (fmt cache maxwidths m)
16916 (cond
16917 ((and (local-variable-p 'org-overriding-columns-format)
16918 org-overriding-columns-format)
16919 (setq fmt org-overriding-columns-format))
16920 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16921 (setq fmt (org-entry-get m "COLUMNS" t)))
16922 ((and (boundp 'org-columns-current-fmt)
16923 (local-variable-p 'org-columns-current-fmt)
16924 org-columns-current-fmt)
16925 (setq fmt org-columns-current-fmt))
16926 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16927 (setq m (get-text-property m 'org-hd-marker))
16928 (setq fmt (org-entry-get m "COLUMNS" t))))
16929 (setq fmt (or fmt org-columns-default-format))
16930 (org-set-local 'org-columns-current-fmt fmt)
16931 (org-columns-compile-format fmt)
16932 (save-excursion
16933 ;; Get and cache the properties
16934 (goto-char (point-min))
16935 (while (not (eobp))
16936 (when (setq m (or (get-text-property (point) 'org-hd-marker)
16937 (get-text-property (point) 'org-marker)))
16938 (push (cons (org-current-line) (org-entry-properties m)) cache))
16939 (beginning-of-line 2))
16940 (when cache
16941 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16942 (org-set-local 'org-columns-current-maxwidths maxwidths)
16943 (org-columns-display-here-title)
16944 (mapc (lambda (x)
16945 (goto-line (car x))
16946 (org-columns-display-here (cdr x)))
16947 cache)))))
16949 (defun org-columns-get-autowidth-alist (s cache)
16950 "Derive the maximum column widths from the format and the cache."
16951 (let ((start 0) rtn)
16952 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
16953 (push (cons (match-string 1 s) 1) rtn)
16954 (setq start (match-end 0)))
16955 (mapc (lambda (x)
16956 (setcdr x (apply 'max
16957 (mapcar
16958 (lambda (y)
16959 (length (or (cdr (assoc (car x) (cdr y))) " ")))
16960 cache))))
16961 rtn)
16962 rtn))
16964 (defun org-columns-compute-all ()
16965 "Compute all columns that have operators defined."
16966 (org-unmodified
16967 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
16968 (let ((columns org-columns-current-fmt-compiled) col)
16969 (while (setq col (pop columns))
16970 (when (nth 3 col)
16971 (save-excursion
16972 (org-columns-compute (car col)))))))
16974 (defun org-columns-update (property)
16975 "Recompute PROPERTY, and update the columns display for it."
16976 (org-columns-compute property)
16977 (let (fmt val pos)
16978 (save-excursion
16979 (mapc (lambda (ov)
16980 (when (equal (org-overlay-get ov 'org-columns-key) property)
16981 (setq pos (org-overlay-start ov))
16982 (goto-char pos)
16983 (when (setq val (cdr (assoc property
16984 (get-text-property
16985 (point-at-bol) 'org-summaries))))
16986 (setq fmt (org-overlay-get ov 'org-columns-format))
16987 (org-overlay-put ov 'org-columns-value val)
16988 (org-overlay-put ov 'display (format fmt val)))))
16989 org-columns-overlays))))
16991 (defun org-columns-compute (property)
16992 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
16993 (interactive)
16994 (let* ((re (concat "^" outline-regexp))
16995 (lmax 30) ; Does anyone use deeper levels???
16996 (lsum (make-vector lmax 0))
16997 (lflag (make-vector lmax nil))
16998 (level 0)
16999 (ass (assoc property org-columns-current-fmt-compiled))
17000 (format (nth 4 ass))
17001 (printf (nth 5 ass))
17002 (beg org-columns-top-level-marker)
17003 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17004 (save-excursion
17005 ;; Find the region to compute
17006 (goto-char beg)
17007 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17008 (goto-char end)
17009 ;; Walk the tree from the back and do the computations
17010 (while (re-search-backward re beg t)
17011 (setq sumpos (match-beginning 0)
17012 last-level level
17013 level (org-outline-level)
17014 val (org-entry-get nil property)
17015 valflag (and val (string-match "\\S-" val)))
17016 (cond
17017 ((< level last-level)
17018 ;; put the sum of lower levels here as a property
17019 (setq sum (aref lsum last-level) ; current sum
17020 flag (aref lflag last-level) ; any valid entries from children?
17021 str (org-column-number-to-string sum format printf)
17022 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17023 useval (if flag str1 (if valflag val ""))
17024 sum-alist (get-text-property sumpos 'org-summaries))
17025 (if (assoc property sum-alist)
17026 (setcdr (assoc property sum-alist) useval)
17027 (push (cons property useval) sum-alist)
17028 (org-unmodified
17029 (add-text-properties sumpos (1+ sumpos)
17030 (list 'org-summaries sum-alist))))
17031 (when val
17032 (org-entry-put nil property (if flag str val)))
17033 ;; add current to current level accumulator
17034 (when (or flag valflag)
17035 (aset lsum level (+ (aref lsum level)
17036 (if flag sum (org-column-string-to-number
17037 (if flag str val) format))))
17038 (aset lflag level t))
17039 ;; clear accumulators for deeper levels
17040 (loop for l from (1+ level) to (1- lmax) do
17041 (aset lsum l 0)
17042 (aset lflag l nil)))
17043 ((>= level last-level)
17044 ;; add what we have here to the accumulator for this level
17045 (aset lsum level (+ (aref lsum level)
17046 (org-column-string-to-number (or val "0") format)))
17047 (and valflag (aset lflag level t)))
17048 (t (error "This should not happen")))))))
17050 (defun org-columns-redo ()
17051 "Construct the column display again."
17052 (interactive)
17053 (message "Recomputing columns...")
17054 (save-excursion
17055 (if (marker-position org-columns-begin-marker)
17056 (goto-char org-columns-begin-marker))
17057 (org-columns-remove-overlays)
17058 (if (org-mode-p)
17059 (call-interactively 'org-columns)
17060 (call-interactively 'org-agenda-columns)))
17061 (message "Recomputing columns...done"))
17063 (defun org-columns-not-in-agenda ()
17064 (if (eq major-mode 'org-agenda-mode)
17065 (error "This command is only allowed in Org-mode buffers")))
17068 (defun org-string-to-number (s)
17069 "Convert string to number, and interpret hh:mm:ss."
17070 (if (not (string-match ":" s))
17071 (string-to-number s)
17072 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17073 (while l
17074 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17075 sum)))
17077 (defun org-column-number-to-string (n fmt &optional printf)
17078 "Convert a computed column number to a string value, according to FMT."
17079 (cond
17080 ((eq fmt 'add_times)
17081 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17082 (format "%d:%02d" h m)))
17083 ((eq fmt 'checkbox)
17084 (cond ((= n (floor n)) "[X]")
17085 ((> n 1.) "[-]")
17086 (t "[ ]")))
17087 (printf (format printf n))
17088 ((eq fmt 'currency)
17089 (format "%.2f" n))
17090 (t (number-to-string n))))
17092 (defun org-column-string-to-number (s fmt)
17093 "Convert a column value to a number that can be used for column computing."
17094 (cond
17095 ((string-match ":" s)
17096 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17097 (while l
17098 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17099 sum))
17100 ((eq fmt 'checkbox)
17101 (if (equal s "[X]") 1. 0.000001))
17102 (t (string-to-number s))))
17104 (defun org-columns-uncompile-format (cfmt)
17105 "Turn the compiled columns format back into a string representation."
17106 (let ((rtn "") e s prop title op width fmt printf)
17107 (while (setq e (pop cfmt))
17108 (setq prop (car e)
17109 title (nth 1 e)
17110 width (nth 2 e)
17111 op (nth 3 e)
17112 fmt (nth 4 e)
17113 printf (nth 5 e))
17114 (cond
17115 ((eq fmt 'add_times) (setq op ":"))
17116 ((eq fmt 'checkbox) (setq op "X"))
17117 ((eq fmt 'add_numbers) (setq op "+"))
17118 ((eq fmt 'currency) (setq op "$")))
17119 (if (and op printf) (setq op (concat op ";" printf)))
17120 (if (equal title prop) (setq title nil))
17121 (setq s (concat "%" (if width (number-to-string width))
17122 prop
17123 (if title (concat "(" title ")"))
17124 (if op (concat "{" op "}"))))
17125 (setq rtn (concat rtn " " s)))
17126 (org-trim rtn)))
17128 (defun org-columns-compile-format (fmt)
17129 "Turn a column format string into an alist of specifications.
17130 The alist has one entry for each column in the format. The elements of
17131 that list are:
17132 property the property
17133 title the title field for the columns
17134 width the column width in characters, can be nil for automatic
17135 operator the operator if any
17136 format the output format for computed results, derived from operator
17137 printf a printf format for computed values"
17138 (let ((start 0) width prop title op f printf)
17139 (setq org-columns-current-fmt-compiled nil)
17140 (while (string-match
17141 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17142 fmt start)
17143 (setq start (match-end 0)
17144 width (match-string 1 fmt)
17145 prop (match-string 2 fmt)
17146 title (or (match-string 3 fmt) prop)
17147 op (match-string 4 fmt)
17148 f nil
17149 printf nil)
17150 (if width (setq width (string-to-number width)))
17151 (when (and op (string-match ";" op))
17152 (setq printf (substring op (match-end 0))
17153 op (substring op 0 (match-beginning 0))))
17154 (cond
17155 ((equal op "+") (setq f 'add_numbers))
17156 ((equal op "$") (setq f 'currency))
17157 ((equal op ":") (setq f 'add_times))
17158 ((equal op "X") (setq f 'checkbox)))
17159 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17160 (setq org-columns-current-fmt-compiled
17161 (nreverse org-columns-current-fmt-compiled))))
17164 ;;; Dynamic block for Column view
17166 (defun org-columns-capture-view ()
17167 "Get the column view of the current buffer and return it as a list.
17168 The list will contains the title row and all other rows. Each row is
17169 a list of fields."
17170 (save-excursion
17171 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17172 (n (length title)) row tbl)
17173 (goto-char (point-min))
17174 (while (re-search-forward "^\\*+ " nil t)
17175 (when (get-char-property (match-beginning 0) 'org-columns-key)
17176 (setq row nil)
17177 (loop for i from 0 to (1- n) do
17178 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17179 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17181 row))
17182 (setq row (nreverse row))
17183 (push row tbl)))
17184 (append (list title 'hline) (nreverse tbl)))))
17186 (defun org-dblock-write:columnview (params)
17187 "Write the column view table.
17188 PARAMS is a property list of parameters:
17190 :width enforce same column widths with <N> specifiers.
17191 :id the :ID: property of the entry where the columns view
17192 should be built, as a string. When `local', call locally.
17193 When `global' call column view with the cursor at the beginning
17194 of the buffer (usually this means that the whole buffer switches
17195 to column view).
17196 :hlines When t, insert a hline before each item. When a number, insert
17197 a hline before each level <= that number.
17198 :vlines When t, make each column a colgroup to enforce vertical lines."
17199 (let ((pos (move-marker (make-marker) (point)))
17200 (hlines (plist-get params :hlines))
17201 (vlines (plist-get params :vlines))
17202 tbl id idpos nfields tmp)
17203 (save-excursion
17204 (save-restriction
17205 (when (setq id (plist-get params :id))
17206 (cond ((not id) nil)
17207 ((eq id 'global) (goto-char (point-min)))
17208 ((eq id 'local) nil)
17209 ((setq idpos (org-find-entry-with-id id))
17210 (goto-char idpos))
17211 (t (error "Cannot find entry with :ID: %s" id))))
17212 (org-columns)
17213 (setq tbl (org-columns-capture-view))
17214 (setq nfields (length (car tbl)))
17215 (org-columns-quit)))
17216 (goto-char pos)
17217 (move-marker pos nil)
17218 (when tbl
17219 (when (plist-get params :hlines)
17220 (setq tmp nil)
17221 (while tbl
17222 (if (eq (car tbl) 'hline)
17223 (push (pop tbl) tmp)
17224 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17225 (if (and (not (eq (car tmp) 'hline))
17226 (or (eq hlines t)
17227 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17228 (push 'hline tmp)))
17229 (push (pop tbl) tmp)))
17230 (setq tbl (nreverse tmp)))
17231 (when vlines
17232 (setq tbl (mapcar (lambda (x)
17233 (if (eq 'hline x) x (cons "" x)))
17234 tbl))
17235 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17236 (setq pos (point))
17237 (insert (org-listtable-to-string tbl))
17238 (when (plist-get params :width)
17239 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17240 org-columns-current-widths "|")))
17241 (goto-char pos)
17242 (org-table-align))))
17244 (defun org-listtable-to-string (tbl)
17245 "Convert a listtable TBL to a string that contains the Org-mode table.
17246 The table still need to be alligned. The resulting string has no leading
17247 and tailing newline characters."
17248 (mapconcat
17249 (lambda (x)
17250 (cond
17251 ((listp x)
17252 (concat "|" (mapconcat 'identity x "|") "|"))
17253 ((eq x 'hline) "|-|")
17254 (t (error "Garbage in listtable: %s" x))))
17255 tbl "\n"))
17257 (defun org-insert-columns-dblock ()
17258 "Create a dynamic block capturing a column view table."
17259 (interactive)
17260 (let ((defaults '(:name "columnview" :hlines 1))
17261 (id (completing-read
17262 "Capture columns (local, global, entry with :ID: property) [local]: "
17263 (append '(("global") ("local"))
17264 (mapcar 'list (org-property-values "ID"))))))
17265 (if (equal id "") (setq id 'local))
17266 (if (equal id "global") (setq id 'global))
17267 (setq defaults (append defaults (list :id id)))
17268 (org-create-dblock defaults)
17269 (org-update-dblock)))
17271 ;;;; Timestamps
17273 (defvar org-last-changed-timestamp nil)
17274 (defvar org-time-was-given) ; dynamically scoped parameter
17275 (defvar org-end-time-was-given) ; dynamically scoped parameter
17276 (defvar org-ts-what) ; dynamically scoped parameter
17278 (defun org-time-stamp (arg)
17279 "Prompt for a date/time and insert a time stamp.
17280 If the user specifies a time like HH:MM, or if this command is called
17281 with a prefix argument, the time stamp will contain date and time.
17282 Otherwise, only the date will be included. All parts of a date not
17283 specified by the user will be filled in from the current date/time.
17284 So if you press just return without typing anything, the time stamp
17285 will represent the current date/time. If there is already a timestamp
17286 at the cursor, it will be modified."
17287 (interactive "P")
17288 (let* ((ts nil)
17289 (default-time
17290 ;; Default time is either today, or, when entering a range,
17291 ;; the range start.
17292 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17293 (save-excursion
17294 (re-search-backward
17295 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17296 (- (point) 20) t)))
17297 (apply 'encode-time (org-parse-time-string (match-string 1)))
17298 (current-time)))
17299 (default-input (and ts (org-get-compact-tod ts)))
17300 org-time-was-given org-end-time-was-given time)
17301 (cond
17302 ((and (org-at-timestamp-p)
17303 (eq last-command 'org-time-stamp)
17304 (eq this-command 'org-time-stamp))
17305 (insert "--")
17306 (setq time (let ((this-command this-command))
17307 (org-read-date arg 'totime nil nil default-time default-input)))
17308 (org-insert-time-stamp time (or org-time-was-given arg)))
17309 ((org-at-timestamp-p)
17310 (setq time (let ((this-command this-command))
17311 (org-read-date arg 'totime nil nil default-time default-input)))
17312 (when (org-at-timestamp-p) ; just to get the match data
17313 (replace-match "")
17314 (setq org-last-changed-timestamp
17315 (org-insert-time-stamp
17316 time (or org-time-was-given arg)
17317 nil nil nil (list org-end-time-was-given))))
17318 (message "Timestamp updated"))
17320 (setq time (let ((this-command this-command))
17321 (org-read-date arg 'totime nil nil default-time default-input)))
17322 (org-insert-time-stamp time (or org-time-was-given arg)
17323 nil nil nil (list org-end-time-was-given))))))
17325 ;; FIXME: can we use this for something else????
17326 ;; like computing time differences?????
17327 (defun org-get-compact-tod (s)
17328 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17329 (let* ((t1 (match-string 1 s))
17330 (h1 (string-to-number (match-string 2 s)))
17331 (m1 (string-to-number (match-string 3 s)))
17332 (t2 (and (match-end 4) (match-string 5 s)))
17333 (h2 (and t2 (string-to-number (match-string 6 s))))
17334 (m2 (and t2 (string-to-number (match-string 7 s))))
17335 dh dm)
17336 (if (not t2)
17338 (setq dh (- h2 h1) dm (- m2 m1))
17339 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17340 (concat t1 "+" (number-to-string dh)
17341 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17343 (defun org-time-stamp-inactive (&optional arg)
17344 "Insert an inactive time stamp.
17345 An inactive time stamp is enclosed in square brackets instead of angle
17346 brackets. It is inactive in the sense that it does not trigger agenda entries,
17347 does not link to the calendar and cannot be changed with the S-cursor keys.
17348 So these are more for recording a certain time/date."
17349 (interactive "P")
17350 (let (org-time-was-given org-end-time-was-given time)
17351 (setq time (org-read-date arg 'totime))
17352 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17353 nil nil (list org-end-time-was-given))))
17355 (defvar org-date-ovl (org-make-overlay 1 1))
17356 (org-overlay-put org-date-ovl 'face 'org-warning)
17357 (org-detach-overlay org-date-ovl)
17359 (defvar org-ans1) ; dynamically scoped parameter
17360 (defvar org-ans2) ; dynamically scoped parameter
17362 (defvar org-plain-time-of-day-regexp) ; defined below
17364 (defvar org-read-date-overlay nil)
17365 (defvar org-dcst nil) ; dynamically scoped
17367 (defun org-read-date (&optional with-time to-time from-string prompt
17368 default-time default-input)
17369 "Read a date, possibly a time, and make things smooth for the user.
17370 The prompt will suggest to enter an ISO date, but you can also enter anything
17371 which will at least partially be understood by `parse-time-string'.
17372 Unrecognized parts of the date will default to the current day, month, year,
17373 hour and minute. If this command is called to replace a timestamp at point,
17374 of to enter the second timestamp of a range, the default time is taken from the
17375 existing stamp. For example,
17376 3-2-5 --> 2003-02-05
17377 feb 15 --> currentyear-02-15
17378 sep 12 9 --> 2009-09-12
17379 12:45 --> today 12:45
17380 22 sept 0:34 --> currentyear-09-22 0:34
17381 12 --> currentyear-currentmonth-12
17382 Fri --> nearest Friday (today or later)
17383 etc.
17385 Furthermore you can specify a relative date by giving, as the *first* thing
17386 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17387 change in days weeks, months, years.
17388 With a single plus or minus, the date is relative to today. With a double
17389 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17390 +4d --> four days from today
17391 +4 --> same as above
17392 +2w --> two weeks from today
17393 ++5 --> five days from default date
17395 The function understands only English month and weekday abbreviations,
17396 but this can be configured with the variables `parse-time-months' and
17397 `parse-time-weekdays'.
17399 While prompting, a calendar is popped up - you can also select the
17400 date with the mouse (button 1). The calendar shows a period of three
17401 months. To scroll it to other months, use the keys `>' and `<'.
17402 If you don't like the calendar, turn it off with
17403 \(setq org-read-date-popup-calendar nil)
17405 With optional argument TO-TIME, the date will immediately be converted
17406 to an internal time.
17407 With an optional argument WITH-TIME, the prompt will suggest to also
17408 insert a time. Note that when WITH-TIME is not set, you can still
17409 enter a time, and this function will inform the calling routine about
17410 this change. The calling routine may then choose to change the format
17411 used to insert the time stamp into the buffer to include the time.
17412 With optional argument FROM-STRING, read from this string instead from
17413 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17414 the time/date that is used for everything that is not specified by the
17415 user."
17416 (require 'parse-time)
17417 (let* ((org-time-stamp-rounding-minutes
17418 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17419 (org-dcst org-display-custom-times)
17420 (ct (org-current-time))
17421 (def (or default-time ct))
17422 (defdecode (decode-time def))
17423 (dummy (progn
17424 (when (< (nth 2 defdecode) org-extend-today-until)
17425 (setcar (nthcdr 2 defdecode) -1)
17426 (setcar (nthcdr 1 defdecode) 59)
17427 (setq def (apply 'encode-time defdecode)
17428 defdecode (decode-time def)))))
17429 (calendar-move-hook nil)
17430 (view-diary-entries-initially nil)
17431 (view-calendar-holidays-initially nil)
17432 (timestr (format-time-string
17433 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17434 (prompt (concat (if prompt (concat prompt " ") "")
17435 (format "Date+time [%s]: " timestr)))
17436 ans (org-ans0 "") org-ans1 org-ans2 final)
17438 (cond
17439 (from-string (setq ans from-string))
17440 (org-read-date-popup-calendar
17441 (save-excursion
17442 (save-window-excursion
17443 (calendar)
17444 (calendar-forward-day (- (time-to-days def)
17445 (calendar-absolute-from-gregorian
17446 (calendar-current-date))))
17447 (org-eval-in-calendar nil t)
17448 (let* ((old-map (current-local-map))
17449 (map (copy-keymap calendar-mode-map))
17450 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17451 (org-defkey map (kbd "RET") 'org-calendar-select)
17452 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17453 'org-calendar-select-mouse)
17454 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17455 'org-calendar-select-mouse)
17456 (org-defkey minibuffer-local-map [(meta shift left)]
17457 (lambda () (interactive)
17458 (org-eval-in-calendar '(calendar-backward-month 1))))
17459 (org-defkey minibuffer-local-map [(meta shift right)]
17460 (lambda () (interactive)
17461 (org-eval-in-calendar '(calendar-forward-month 1))))
17462 (org-defkey minibuffer-local-map [(meta shift up)]
17463 (lambda () (interactive)
17464 (org-eval-in-calendar '(calendar-backward-year 1))))
17465 (org-defkey minibuffer-local-map [(meta shift down)]
17466 (lambda () (interactive)
17467 (org-eval-in-calendar '(calendar-forward-year 1))))
17468 (org-defkey minibuffer-local-map [(shift up)]
17469 (lambda () (interactive)
17470 (org-eval-in-calendar '(calendar-backward-week 1))))
17471 (org-defkey minibuffer-local-map [(shift down)]
17472 (lambda () (interactive)
17473 (org-eval-in-calendar '(calendar-forward-week 1))))
17474 (org-defkey minibuffer-local-map [(shift left)]
17475 (lambda () (interactive)
17476 (org-eval-in-calendar '(calendar-backward-day 1))))
17477 (org-defkey minibuffer-local-map [(shift right)]
17478 (lambda () (interactive)
17479 (org-eval-in-calendar '(calendar-forward-day 1))))
17480 (org-defkey minibuffer-local-map ">"
17481 (lambda () (interactive)
17482 (org-eval-in-calendar '(scroll-calendar-left 1))))
17483 (org-defkey minibuffer-local-map "<"
17484 (lambda () (interactive)
17485 (org-eval-in-calendar '(scroll-calendar-right 1))))
17486 (unwind-protect
17487 (progn
17488 (use-local-map map)
17489 (add-hook 'post-command-hook 'org-read-date-display)
17490 (setq org-ans0 (read-string prompt default-input nil nil))
17491 ;; org-ans0: from prompt
17492 ;; org-ans1: from mouse click
17493 ;; org-ans2: from calendar motion
17494 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17495 (remove-hook 'post-command-hook 'org-read-date-display)
17496 (use-local-map old-map)
17497 (when org-read-date-overlay
17498 (org-delete-overlay org-read-date-overlay)
17499 (setq org-read-date-overlay nil)))))))
17501 (t ; Naked prompt only
17502 (unwind-protect
17503 (setq ans (read-string prompt default-input nil timestr))
17504 (when org-read-date-overlay
17505 (org-delete-overlay org-read-date-overlay)
17506 (setq org-read-date-overlay nil)))))
17508 (setq final (org-read-date-analyze ans def defdecode))
17510 (if to-time
17511 (apply 'encode-time final)
17512 (if (and (boundp 'org-time-was-given) org-time-was-given)
17513 (format "%04d-%02d-%02d %02d:%02d"
17514 (nth 5 final) (nth 4 final) (nth 3 final)
17515 (nth 2 final) (nth 1 final))
17516 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17517 (defvar def)
17518 (defvar defdecode)
17519 (defvar with-time)
17520 (defun org-read-date-display ()
17521 "Display the currrent date prompt interpretation in the minibuffer."
17522 (when org-read-date-display-live
17523 (when org-read-date-overlay
17524 (org-delete-overlay org-read-date-overlay))
17525 (let ((p (point)))
17526 (end-of-line 1)
17527 (while (not (equal (buffer-substring
17528 (max (point-min) (- (point) 4)) (point))
17529 " "))
17530 (insert " "))
17531 (goto-char p))
17532 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17533 " " (or org-ans1 org-ans2)))
17534 (org-end-time-was-given nil)
17535 (f (org-read-date-analyze ans def defdecode))
17536 (fmts (if org-dcst
17537 org-time-stamp-custom-formats
17538 org-time-stamp-formats))
17539 (fmt (if (or with-time
17540 (and (boundp 'org-time-was-given) org-time-was-given))
17541 (cdr fmts)
17542 (car fmts)))
17543 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17544 (when (and org-end-time-was-given
17545 (string-match org-plain-time-of-day-regexp txt))
17546 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17547 org-end-time-was-given
17548 (substring txt (match-end 0)))))
17549 (setq org-read-date-overlay
17550 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17551 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17553 (defun org-read-date-analyze (ans def defdecode)
17554 "Analyze the combined answer of the date prompt."
17555 ;; FIXME: cleanup and comment
17556 (let (delta deltan deltaw deltadef year month day
17557 hour minute second wday pm h2 m2 tl wday1)
17559 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17560 (setq ans (replace-match "" t t ans)
17561 deltan (car delta)
17562 deltaw (nth 1 delta)
17563 deltadef (nth 2 delta)))
17565 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17566 (when (string-match
17567 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17568 (setq year (if (match-end 2)
17569 (string-to-number (match-string 2 ans))
17570 (string-to-number (format-time-string "%Y")))
17571 month (string-to-number (match-string 3 ans))
17572 day (string-to-number (match-string 4 ans)))
17573 (if (< year 100) (setq year (+ 2000 year)))
17574 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17575 t nil ans)))
17576 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17577 ;; If there is a time with am/pm, and *no* time without it, we convert
17578 ;; so that matching will be successful.
17579 (loop for i from 1 to 2 do ; twice, for end time as well
17580 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17581 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17582 (setq hour (string-to-number (match-string 1 ans))
17583 minute (if (match-end 3)
17584 (string-to-number (match-string 3 ans))
17586 pm (equal ?p
17587 (string-to-char (downcase (match-string 4 ans)))))
17588 (if (and (= hour 12) (not pm))
17589 (setq hour 0)
17590 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17591 (setq ans (replace-match (format "%02d:%02d" hour minute)
17592 t t ans))))
17594 ;; Check if a time range is given as a duration
17595 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17596 (setq hour (string-to-number (match-string 1 ans))
17597 h2 (+ hour (string-to-number (match-string 3 ans)))
17598 minute (string-to-number (match-string 2 ans))
17599 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17600 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17601 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17603 ;; Check if there is a time range
17604 (when (boundp 'org-end-time-was-given)
17605 (setq org-time-was-given nil)
17606 (when (and (string-match org-plain-time-of-day-regexp ans)
17607 (match-end 8))
17608 (setq org-end-time-was-given (match-string 8 ans))
17609 (setq ans (concat (substring ans 0 (match-beginning 7))
17610 (substring ans (match-end 7))))))
17612 (setq tl (parse-time-string ans)
17613 day (or (nth 3 tl) (nth 3 defdecode))
17614 month (or (nth 4 tl)
17615 (if (and org-read-date-prefer-future
17616 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17617 (1+ (nth 4 defdecode))
17618 (nth 4 defdecode)))
17619 year (or (nth 5 tl)
17620 (if (and org-read-date-prefer-future
17621 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17622 (1+ (nth 5 defdecode))
17623 (nth 5 defdecode)))
17624 hour (or (nth 2 tl) (nth 2 defdecode))
17625 minute (or (nth 1 tl) (nth 1 defdecode))
17626 second (or (nth 0 tl) 0)
17627 wday (nth 6 tl))
17628 (when deltan
17629 (unless deltadef
17630 (let ((now (decode-time (current-time))))
17631 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17632 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17633 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17634 ((equal deltaw "m") (setq month (+ month deltan)))
17635 ((equal deltaw "y") (setq year (+ year deltan)))))
17636 (when (and wday (not (nth 3 tl)))
17637 ;; Weekday was given, but no day, so pick that day in the week
17638 ;; on or after the derived date.
17639 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17640 (unless (equal wday wday1)
17641 (setq day (+ day (% (- wday wday1 -7) 7)))))
17642 (if (and (boundp 'org-time-was-given)
17643 (nth 2 tl))
17644 (setq org-time-was-given t))
17645 (if (< year 100) (setq year (+ 2000 year)))
17646 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17647 (list second minute hour day month year)))
17649 (defvar parse-time-weekdays)
17651 (defun org-read-date-get-relative (s today default)
17652 "Check string S for special relative date string.
17653 TODAY and DEFAULT are internal times, for today and for a default.
17654 Return shift list (N what def-flag)
17655 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17656 N is the number of WHATs to shift.
17657 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17658 the DEFAULT date rather than TODAY."
17659 (when (string-match
17660 (concat
17661 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17662 "\\([0-9]+\\)?"
17663 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17664 "\\([ \t]\\|$\\)") s)
17665 (let* ((dir (if (match-end 1)
17666 (string-to-char (substring (match-string 1 s) -1))
17667 ?+))
17668 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17669 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17670 (what (if (match-end 3) (match-string 3 s) "d"))
17671 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17672 (date (if rel default today))
17673 (wday (nth 6 (decode-time date)))
17674 delta)
17675 (if wday1
17676 (progn
17677 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17678 (if (= dir ?-) (setq delta (- delta 7)))
17679 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17680 (list delta "d" rel))
17681 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17683 (defun org-eval-in-calendar (form &optional keepdate)
17684 "Eval FORM in the calendar window and return to current window.
17685 Also, store the cursor date in variable org-ans2."
17686 (let ((sw (selected-window)))
17687 (select-window (get-buffer-window "*Calendar*"))
17688 (eval form)
17689 (when (and (not keepdate) (calendar-cursor-to-date))
17690 (let* ((date (calendar-cursor-to-date))
17691 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17692 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17693 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17694 (select-window sw)))
17696 ; ;; Update the prompt to show new default date
17697 ; (save-excursion
17698 ; (goto-char (point-min))
17699 ; (when (and org-ans2
17700 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17701 ; (get-text-property (match-end 0) 'field))
17702 ; (let ((inhibit-read-only t))
17703 ; (replace-match (concat "[" org-ans2 "]") t t)
17704 ; (add-text-properties (point-min) (1+ (match-end 0))
17705 ; (text-properties-at (1+ (point-min)))))))))
17707 (defun org-calendar-select ()
17708 "Return to `org-read-date' with the date currently selected.
17709 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17710 (interactive)
17711 (when (calendar-cursor-to-date)
17712 (let* ((date (calendar-cursor-to-date))
17713 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17714 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17715 (if (active-minibuffer-window) (exit-minibuffer))))
17717 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17718 "Insert a date stamp for the date given by the internal TIME.
17719 WITH-HM means, use the stamp format that includes the time of the day.
17720 INACTIVE means use square brackets instead of angular ones, so that the
17721 stamp will not contribute to the agenda.
17722 PRE and POST are optional strings to be inserted before and after the
17723 stamp.
17724 The command returns the inserted time stamp."
17725 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17726 stamp)
17727 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17728 (insert-before-markers (or pre ""))
17729 (insert-before-markers (setq stamp (format-time-string fmt time)))
17730 (when (listp extra)
17731 (setq extra (car extra))
17732 (if (and (stringp extra)
17733 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17734 (setq extra (format "-%02d:%02d"
17735 (string-to-number (match-string 1 extra))
17736 (string-to-number (match-string 2 extra))))
17737 (setq extra nil)))
17738 (when extra
17739 (backward-char 1)
17740 (insert-before-markers extra)
17741 (forward-char 1))
17742 (insert-before-markers (or post ""))
17743 stamp))
17745 (defun org-toggle-time-stamp-overlays ()
17746 "Toggle the use of custom time stamp formats."
17747 (interactive)
17748 (setq org-display-custom-times (not org-display-custom-times))
17749 (unless org-display-custom-times
17750 (let ((p (point-min)) (bmp (buffer-modified-p)))
17751 (while (setq p (next-single-property-change p 'display))
17752 (if (and (get-text-property p 'display)
17753 (eq (get-text-property p 'face) 'org-date))
17754 (remove-text-properties
17755 p (setq p (next-single-property-change p 'display))
17756 '(display t))))
17757 (set-buffer-modified-p bmp)))
17758 (if (featurep 'xemacs)
17759 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17760 (org-restart-font-lock)
17761 (setq org-table-may-need-update t)
17762 (if org-display-custom-times
17763 (message "Time stamps are overlayed with custom format")
17764 (message "Time stamp overlays removed")))
17766 (defun org-display-custom-time (beg end)
17767 "Overlay modified time stamp format over timestamp between BED and END."
17768 (let* ((ts (buffer-substring beg end))
17769 t1 w1 with-hm tf time str w2 (off 0))
17770 (save-match-data
17771 (setq t1 (org-parse-time-string ts t))
17772 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17773 (setq off (- (match-end 0) (match-beginning 0)))))
17774 (setq end (- end off))
17775 (setq w1 (- end beg)
17776 with-hm (and (nth 1 t1) (nth 2 t1))
17777 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17778 time (org-fix-decoded-time t1)
17779 str (org-add-props
17780 (format-time-string
17781 (substring tf 1 -1) (apply 'encode-time time))
17782 nil 'mouse-face 'highlight)
17783 w2 (length str))
17784 (if (not (= w2 w1))
17785 (add-text-properties (1+ beg) (+ 2 beg)
17786 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17787 (if (featurep 'xemacs)
17788 (progn
17789 (put-text-property beg end 'invisible t)
17790 (put-text-property beg end 'end-glyph (make-glyph str)))
17791 (put-text-property beg end 'display str))))
17793 (defun org-translate-time (string)
17794 "Translate all timestamps in STRING to custom format.
17795 But do this only if the variable `org-display-custom-times' is set."
17796 (when org-display-custom-times
17797 (save-match-data
17798 (let* ((start 0)
17799 (re org-ts-regexp-both)
17800 t1 with-hm inactive tf time str beg end)
17801 (while (setq start (string-match re string start))
17802 (setq beg (match-beginning 0)
17803 end (match-end 0)
17804 t1 (save-match-data
17805 (org-parse-time-string (substring string beg end) t))
17806 with-hm (and (nth 1 t1) (nth 2 t1))
17807 inactive (equal (substring string beg (1+ beg)) "[")
17808 tf (funcall (if with-hm 'cdr 'car)
17809 org-time-stamp-custom-formats)
17810 time (org-fix-decoded-time t1)
17811 str (format-time-string
17812 (concat
17813 (if inactive "[" "<") (substring tf 1 -1)
17814 (if inactive "]" ">"))
17815 (apply 'encode-time time))
17816 string (replace-match str t t string)
17817 start (+ start (length str)))))))
17818 string)
17820 (defun org-fix-decoded-time (time)
17821 "Set 0 instead of nil for the first 6 elements of time.
17822 Don't touch the rest."
17823 (let ((n 0))
17824 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17826 (defun org-days-to-time (timestamp-string)
17827 "Difference between TIMESTAMP-STRING and now in days."
17828 (- (time-to-days (org-time-string-to-time timestamp-string))
17829 (time-to-days (current-time))))
17831 (defun org-deadline-close (timestamp-string &optional ndays)
17832 "Is the time in TIMESTAMP-STRING close to the current date?"
17833 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17834 (and (< (org-days-to-time timestamp-string) ndays)
17835 (not (org-entry-is-done-p))))
17837 (defun org-get-wdays (ts)
17838 "Get the deadline lead time appropriate for timestring TS."
17839 (cond
17840 ((<= org-deadline-warning-days 0)
17841 ;; 0 or negative, enforce this value no matter what
17842 (- org-deadline-warning-days))
17843 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17844 ;; lead time is specified.
17845 (floor (* (string-to-number (match-string 1 ts))
17846 (cdr (assoc (match-string 2 ts)
17847 '(("d" . 1) ("w" . 7)
17848 ("m" . 30.4) ("y" . 365.25)))))))
17849 ;; go for the default.
17850 (t org-deadline-warning-days)))
17852 (defun org-calendar-select-mouse (ev)
17853 "Return to `org-read-date' with the date currently selected.
17854 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17855 (interactive "e")
17856 (mouse-set-point ev)
17857 (when (calendar-cursor-to-date)
17858 (let* ((date (calendar-cursor-to-date))
17859 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17860 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17861 (if (active-minibuffer-window) (exit-minibuffer))))
17863 (defun org-check-deadlines (ndays)
17864 "Check if there are any deadlines due or past due.
17865 A deadline is considered due if it happens within `org-deadline-warning-days'
17866 days from today's date. If the deadline appears in an entry marked DONE,
17867 it is not shown. The prefix arg NDAYS can be used to test that many
17868 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17869 (interactive "P")
17870 (let* ((org-warn-days
17871 (cond
17872 ((equal ndays '(4)) 100000)
17873 (ndays (prefix-numeric-value ndays))
17874 (t (abs org-deadline-warning-days))))
17875 (case-fold-search nil)
17876 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17877 (callback
17878 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17880 (message "%d deadlines past-due or due within %d days"
17881 (org-occur regexp nil callback)
17882 org-warn-days)))
17884 (defun org-check-before-date (date)
17885 "Check if there are deadlines or scheduled entries before DATE."
17886 (interactive (list (org-read-date)))
17887 (let ((case-fold-search nil)
17888 (regexp (concat "\\<\\(" org-deadline-string
17889 "\\|" org-scheduled-string
17890 "\\) *<\\([^>]+\\)>"))
17891 (callback
17892 (lambda () (time-less-p
17893 (org-time-string-to-time (match-string 2))
17894 (org-time-string-to-time date)))))
17895 (message "%d entries before %s"
17896 (org-occur regexp nil callback) date)))
17898 (defun org-evaluate-time-range (&optional to-buffer)
17899 "Evaluate a time range by computing the difference between start and end.
17900 Normally the result is just printed in the echo area, but with prefix arg
17901 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17902 If the time range is actually in a table, the result is inserted into the
17903 next column.
17904 For time difference computation, a year is assumed to be exactly 365
17905 days in order to avoid rounding problems."
17906 (interactive "P")
17908 (org-clock-update-time-maybe)
17909 (save-excursion
17910 (unless (org-at-date-range-p t)
17911 (goto-char (point-at-bol))
17912 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17913 (if (not (org-at-date-range-p t))
17914 (error "Not at a time-stamp range, and none found in current line")))
17915 (let* ((ts1 (match-string 1))
17916 (ts2 (match-string 2))
17917 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17918 (match-end (match-end 0))
17919 (time1 (org-time-string-to-time ts1))
17920 (time2 (org-time-string-to-time ts2))
17921 (t1 (time-to-seconds time1))
17922 (t2 (time-to-seconds time2))
17923 (diff (abs (- t2 t1)))
17924 (negative (< (- t2 t1) 0))
17925 ;; (ys (floor (* 365 24 60 60)))
17926 (ds (* 24 60 60))
17927 (hs (* 60 60))
17928 (fy "%dy %dd %02d:%02d")
17929 (fy1 "%dy %dd")
17930 (fd "%dd %02d:%02d")
17931 (fd1 "%dd")
17932 (fh "%02d:%02d")
17933 y d h m align)
17934 (if havetime
17935 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17937 d (floor (/ diff ds)) diff (mod diff ds)
17938 h (floor (/ diff hs)) diff (mod diff hs)
17939 m (floor (/ diff 60)))
17940 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17942 d (floor (+ (/ diff ds) 0.5))
17943 h 0 m 0))
17944 (if (not to-buffer)
17945 (message "%s" (org-make-tdiff-string y d h m))
17946 (if (org-at-table-p)
17947 (progn
17948 (goto-char match-end)
17949 (setq align t)
17950 (and (looking-at " *|") (goto-char (match-end 0))))
17951 (goto-char match-end))
17952 (if (looking-at
17953 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17954 (replace-match ""))
17955 (if negative (insert " -"))
17956 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17957 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17958 (insert " " (format fh h m))))
17959 (if align (org-table-align))
17960 (message "Time difference inserted")))))
17962 (defun org-make-tdiff-string (y d h m)
17963 (let ((fmt "")
17964 (l nil))
17965 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17966 l (push y l)))
17967 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17968 l (push d l)))
17969 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17970 l (push h l)))
17971 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17972 l (push m l)))
17973 (apply 'format fmt (nreverse l))))
17975 (defun org-time-string-to-time (s)
17976 (apply 'encode-time (org-parse-time-string s)))
17978 (defun org-time-string-to-absolute (s &optional daynr prefer)
17979 "Convert a time stamp to an absolute day number.
17980 If there is a specifyer for a cyclic time stamp, get the closest date to
17981 DAYNR."
17982 (cond
17983 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17984 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17985 daynr
17986 (+ daynr 1000)))
17987 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
17988 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17989 (time-to-days (current-time))) (match-string 0 s)
17990 prefer))
17991 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
17993 (defun org-time-from-absolute (d)
17994 "Return the time corresponding to date D.
17995 D may be an absolute day number, or a calendar-type list (month day year)."
17996 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17997 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17999 (defun org-calendar-holiday ()
18000 "List of holidays, for Diary display in Org-mode."
18001 (require 'holidays)
18002 (let ((hl (funcall
18003 (if (fboundp 'calendar-check-holidays)
18004 'calendar-check-holidays 'check-calendar-holidays) date)))
18005 (if hl (mapconcat 'identity hl "; "))))
18007 (defun org-diary-sexp-entry (sexp entry date)
18008 "Process a SEXP diary ENTRY for DATE."
18009 (require 'diary-lib)
18010 (let ((result (if calendar-debug-sexp
18011 (let ((stack-trace-on-error t))
18012 (eval (car (read-from-string sexp))))
18013 (condition-case nil
18014 (eval (car (read-from-string sexp)))
18015 (error
18016 (beep)
18017 (message "Bad sexp at line %d in %s: %s"
18018 (org-current-line)
18019 (buffer-file-name) sexp)
18020 (sleep-for 2))))))
18021 (cond ((stringp result) result)
18022 ((and (consp result)
18023 (stringp (cdr result))) (cdr result))
18024 (result entry)
18025 (t nil))))
18027 (defun org-diary-to-ical-string (frombuf)
18028 "Get iCalendar entries from diary entries in buffer FROMBUF.
18029 This uses the icalendar.el library."
18030 (let* ((tmpdir (if (featurep 'xemacs)
18031 (temp-directory)
18032 temporary-file-directory))
18033 (tmpfile (make-temp-name
18034 (expand-file-name "orgics" tmpdir)))
18035 buf rtn b e)
18036 (save-excursion
18037 (set-buffer frombuf)
18038 (icalendar-export-region (point-min) (point-max) tmpfile)
18039 (setq buf (find-buffer-visiting tmpfile))
18040 (set-buffer buf)
18041 (goto-char (point-min))
18042 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18043 (setq b (match-beginning 0)))
18044 (goto-char (point-max))
18045 (if (re-search-backward "^END:VEVENT" nil t)
18046 (setq e (match-end 0)))
18047 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18048 (kill-buffer buf)
18049 (kill-buffer frombuf)
18050 (delete-file tmpfile)
18051 rtn))
18053 (defun org-closest-date (start current change prefer)
18054 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18055 When PREFER is `past' return a date that is either CURRENT or past.
18056 When PREFER is `future', return a date that is either CURRENT or future."
18057 ;; Make the proper lists from the dates
18058 (catch 'exit
18059 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18060 dn dw sday cday n1 n2
18061 d m y y1 y2 date1 date2 nmonths nm ny m2)
18063 (setq start (org-date-to-gregorian start)
18064 current (org-date-to-gregorian
18065 (if org-agenda-repeating-timestamp-show-all
18066 current
18067 (time-to-days (current-time))))
18068 sday (calendar-absolute-from-gregorian start)
18069 cday (calendar-absolute-from-gregorian current))
18071 (if (<= cday sday) (throw 'exit sday))
18073 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18074 (setq dn (string-to-number (match-string 1 change))
18075 dw (cdr (assoc (match-string 2 change) a1)))
18076 (error "Invalid change specifyer: %s" change))
18077 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18078 (cond
18079 ((eq dw 'day)
18080 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18081 n2 (+ n1 dn)))
18082 ((eq dw 'year)
18083 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18084 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18085 (setq date1 (list m d y1)
18086 n1 (calendar-absolute-from-gregorian date1)
18087 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18088 n2 (calendar-absolute-from-gregorian date2)))
18089 ((eq dw 'month)
18090 ;; approx number of month between the tow dates
18091 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18092 ;; How often does dn fit in there?
18093 (setq d (nth 1 start) m (car start) y (nth 2 start)
18094 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18095 m (+ m nm)
18096 ny (floor (/ m 12))
18097 y (+ y ny)
18098 m (- m (* ny 12)))
18099 (while (> m 12) (setq m (- m 12) y (1+ y)))
18100 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18101 (setq m2 (+ m dn) y2 y)
18102 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18103 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18104 (while (< n2 cday)
18105 (setq n1 n2 m m2 y y2)
18106 (setq m2 (+ m dn) y2 y)
18107 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18108 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18110 (if org-agenda-repeating-timestamp-show-all
18111 (cond
18112 ((eq prefer 'past) n1)
18113 ((eq prefer 'future) (if (= cday n1) n1 n2))
18114 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18115 (cond
18116 ((eq prefer 'past) n1)
18117 ((eq prefer 'future) (if (= cday n1) n1 n2))
18118 (t (if (= cday n1) n1 n2)))))))
18120 (defun org-date-to-gregorian (date)
18121 "Turn any specification of DATE into a gregorian date for the calendar."
18122 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18123 ((and (listp date) (= (length date) 3)) date)
18124 ((stringp date)
18125 (setq date (org-parse-time-string date))
18126 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18127 ((listp date)
18128 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18130 (defun org-parse-time-string (s &optional nodefault)
18131 "Parse the standard Org-mode time string.
18132 This should be a lot faster than the normal `parse-time-string'.
18133 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18134 hour and minute fields will be nil if not given."
18135 (if (string-match org-ts-regexp0 s)
18136 (list 0
18137 (if (or (match-beginning 8) (not nodefault))
18138 (string-to-number (or (match-string 8 s) "0")))
18139 (if (or (match-beginning 7) (not nodefault))
18140 (string-to-number (or (match-string 7 s) "0")))
18141 (string-to-number (match-string 4 s))
18142 (string-to-number (match-string 3 s))
18143 (string-to-number (match-string 2 s))
18144 nil nil nil)
18145 (make-list 9 0)))
18147 (defun org-timestamp-up (&optional arg)
18148 "Increase the date item at the cursor by one.
18149 If the cursor is on the year, change the year. If it is on the month or
18150 the day, change that.
18151 With prefix ARG, change by that many units."
18152 (interactive "p")
18153 (org-timestamp-change (prefix-numeric-value arg)))
18155 (defun org-timestamp-down (&optional arg)
18156 "Decrease the date item at the cursor by one.
18157 If the cursor is on the year, change the year. If it is on the month or
18158 the day, change that.
18159 With prefix ARG, change by that many units."
18160 (interactive "p")
18161 (org-timestamp-change (- (prefix-numeric-value arg))))
18163 (defun org-timestamp-up-day (&optional arg)
18164 "Increase the date in the time stamp by one day.
18165 With prefix ARG, change that many days."
18166 (interactive "p")
18167 (if (and (not (org-at-timestamp-p t))
18168 (org-on-heading-p))
18169 (org-todo 'up)
18170 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18172 (defun org-timestamp-down-day (&optional arg)
18173 "Decrease the date in the time stamp by one day.
18174 With prefix ARG, change that many days."
18175 (interactive "p")
18176 (if (and (not (org-at-timestamp-p t))
18177 (org-on-heading-p))
18178 (org-todo 'down)
18179 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18181 (defsubst org-pos-in-match-range (pos n)
18182 (and (match-beginning n)
18183 (<= (match-beginning n) pos)
18184 (>= (match-end n) pos)))
18186 (defun org-at-timestamp-p (&optional inactive-ok)
18187 "Determine if the cursor is in or at a timestamp."
18188 (interactive)
18189 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18190 (pos (point))
18191 (ans (or (looking-at tsr)
18192 (save-excursion
18193 (skip-chars-backward "^[<\n\r\t")
18194 (if (> (point) (point-min)) (backward-char 1))
18195 (and (looking-at tsr)
18196 (> (- (match-end 0) pos) -1))))))
18197 (and ans
18198 (boundp 'org-ts-what)
18199 (setq org-ts-what
18200 (cond
18201 ((= pos (match-beginning 0)) 'bracket)
18202 ((= pos (1- (match-end 0))) 'bracket)
18203 ((org-pos-in-match-range pos 2) 'year)
18204 ((org-pos-in-match-range pos 3) 'month)
18205 ((org-pos-in-match-range pos 7) 'hour)
18206 ((org-pos-in-match-range pos 8) 'minute)
18207 ((or (org-pos-in-match-range pos 4)
18208 (org-pos-in-match-range pos 5)) 'day)
18209 ((and (> pos (or (match-end 8) (match-end 5)))
18210 (< pos (match-end 0)))
18211 (- pos (or (match-end 8) (match-end 5))))
18212 (t 'day))))
18213 ans))
18215 (defun org-toggle-timestamp-type ()
18217 (interactive)
18218 (when (org-at-timestamp-p t)
18219 (save-excursion
18220 (goto-char (match-beginning 0))
18221 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18222 (goto-char (1- (match-end 0)))
18223 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18224 (message "Timestamp is now %sactive"
18225 (if (equal (char-before) ?>) "in" ""))))
18227 (defun org-timestamp-change (n &optional what)
18228 "Change the date in the time stamp at point.
18229 The date will be changed by N times WHAT. WHAT can be `day', `month',
18230 `year', `minute', `second'. If WHAT is not given, the cursor position
18231 in the timestamp determines what will be changed."
18232 (let ((pos (point))
18233 with-hm inactive
18234 org-ts-what
18235 extra
18236 ts time time0)
18237 (if (not (org-at-timestamp-p t))
18238 (error "Not at a timestamp"))
18239 (if (and (not what) (eq org-ts-what 'bracket))
18240 (org-toggle-timestamp-type)
18241 (if (and (not what) (not (eq org-ts-what 'day))
18242 org-display-custom-times
18243 (get-text-property (point) 'display)
18244 (not (get-text-property (1- (point)) 'display)))
18245 (setq org-ts-what 'day))
18246 (setq org-ts-what (or what org-ts-what)
18247 inactive (= (char-after (match-beginning 0)) ?\[)
18248 ts (match-string 0))
18249 (replace-match "")
18250 (if (string-match
18251 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18253 (setq extra (match-string 1 ts)))
18254 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18255 (setq with-hm t))
18256 (setq time0 (org-parse-time-string ts))
18257 (setq time
18258 (encode-time (or (car time0) 0)
18259 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18260 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18261 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18262 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18263 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18264 (nthcdr 6 time0)))
18265 (when (integerp org-ts-what)
18266 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18267 (if (eq what 'calendar)
18268 (let ((cal-date (org-get-date-from-calendar)))
18269 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18270 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18271 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18272 (setcar time0 (or (car time0) 0))
18273 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18274 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18275 (setq time (apply 'encode-time time0))))
18276 (setq org-last-changed-timestamp
18277 (org-insert-time-stamp time with-hm inactive nil nil extra))
18278 (org-clock-update-time-maybe)
18279 (goto-char pos)
18280 ;; Try to recenter the calendar window, if any
18281 (if (and org-calendar-follow-timestamp-change
18282 (get-buffer-window "*Calendar*" t)
18283 (memq org-ts-what '(day month year)))
18284 (org-recenter-calendar (time-to-days time))))))
18286 ;; FIXME: does not yet work for lead times
18287 (defun org-modify-ts-extra (s pos n)
18288 "Change the different parts of the lead-time and repeat fields in timestamp."
18289 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18290 ng h m new)
18291 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18292 (cond
18293 ((or (org-pos-in-match-range pos 2)
18294 (org-pos-in-match-range pos 3))
18295 (setq m (string-to-number (match-string 3 s))
18296 h (string-to-number (match-string 2 s)))
18297 (if (org-pos-in-match-range pos 2)
18298 (setq h (+ h n))
18299 (setq m (+ m n)))
18300 (if (< m 0) (setq m (+ m 60) h (1- h)))
18301 (if (> m 59) (setq m (- m 60) h (1+ h)))
18302 (setq h (min 24 (max 0 h)))
18303 (setq ng 1 new (format "-%02d:%02d" h m)))
18304 ((org-pos-in-match-range pos 6)
18305 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18306 ((org-pos-in-match-range pos 5)
18307 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18309 (when ng
18310 (setq s (concat
18311 (substring s 0 (match-beginning ng))
18313 (substring s (match-end ng))))))
18316 (defun org-recenter-calendar (date)
18317 "If the calendar is visible, recenter it to DATE."
18318 (let* ((win (selected-window))
18319 (cwin (get-buffer-window "*Calendar*" t))
18320 (calendar-move-hook nil))
18321 (when cwin
18322 (select-window cwin)
18323 (calendar-goto-date (if (listp date) date
18324 (calendar-gregorian-from-absolute date)))
18325 (select-window win))))
18327 (defun org-goto-calendar (&optional arg)
18328 "Go to the Emacs calendar at the current date.
18329 If there is a time stamp in the current line, go to that date.
18330 A prefix ARG can be used to force the current date."
18331 (interactive "P")
18332 (let ((tsr org-ts-regexp) diff
18333 (calendar-move-hook nil)
18334 (view-calendar-holidays-initially nil)
18335 (view-diary-entries-initially nil))
18336 (if (or (org-at-timestamp-p)
18337 (save-excursion
18338 (beginning-of-line 1)
18339 (looking-at (concat ".*" tsr))))
18340 (let ((d1 (time-to-days (current-time)))
18341 (d2 (time-to-days
18342 (org-time-string-to-time (match-string 1)))))
18343 (setq diff (- d2 d1))))
18344 (calendar)
18345 (calendar-goto-today)
18346 (if (and diff (not arg)) (calendar-forward-day diff))))
18348 (defun org-get-date-from-calendar ()
18349 "Return a list (month day year) of date at point in calendar."
18350 (with-current-buffer "*Calendar*"
18351 (save-match-data
18352 (calendar-cursor-to-date))))
18354 (defun org-date-from-calendar ()
18355 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18356 If there is already a time stamp at the cursor position, update it."
18357 (interactive)
18358 (if (org-at-timestamp-p t)
18359 (org-timestamp-change 0 'calendar)
18360 (let ((cal-date (org-get-date-from-calendar)))
18361 (org-insert-time-stamp
18362 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18364 ;; Make appt aware of appointments from the agenda
18365 ;;;###autoload
18366 (defun org-agenda-to-appt (&optional filter)
18367 "Activate appointments found in `org-agenda-files'.
18368 When prefixed, prompt for a regular expression and use it as a
18369 filter: only add entries if they match this regular expression.
18371 FILTER can be a string. In this case, use this string as a
18372 regular expression to filter results.
18374 FILTER can also be an alist, with the car of each cell being
18375 either 'headline or 'category. For example:
18377 '((headline \"IMPORTANT\")
18378 (category \"Work\"))
18380 will only add headlines containing IMPORTANT or headlines
18381 belonging to the category \"Work\"."
18382 (interactive "P")
18383 (require 'calendar)
18384 (if (equal filter '(4))
18385 (setq filter (read-from-minibuffer "Regexp filter: ")))
18386 (let* ((cnt 0) ; count added events
18387 (org-agenda-new-buffers nil)
18388 (today (org-date-to-gregorian
18389 (time-to-days (current-time))))
18390 (files (org-agenda-files)) entries file)
18391 ;; Get all entries which may contain an appt
18392 (while (setq file (pop files))
18393 (setq entries
18394 (append entries
18395 (org-agenda-get-day-entries
18396 file today
18397 :timestamp :scheduled :deadline))))
18398 (setq entries (delq nil entries))
18399 ;; Map thru entries and find if they pass thru the filter
18400 (mapc
18401 (lambda(x)
18402 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18403 (cat (get-text-property 1 'org-category x))
18404 (tod (get-text-property 1 'time-of-day x))
18405 (ok (or (null filter)
18406 (and (stringp filter) (string-match filter evt))
18407 (and (listp filter)
18408 (or (string-match
18409 (cadr (assoc 'category filter)) cat)
18410 (string-match
18411 (cadr (assoc 'headline filter)) evt))))))
18412 ;; FIXME: Shall we remove text-properties for the appt text?
18413 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18414 (when (and ok tod)
18415 (setq tod (number-to-string tod)
18416 tod (when (string-match
18417 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18418 (concat (match-string 1 tod) ":"
18419 (match-string 2 tod))))
18420 (appt-add tod evt)
18421 (setq cnt (1+ cnt))))) entries)
18422 (org-release-buffers org-agenda-new-buffers)
18423 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
18425 ;;; The clock for measuring work time.
18427 (defvar org-mode-line-string "")
18428 (put 'org-mode-line-string 'risky-local-variable t)
18430 (defvar org-mode-line-timer nil)
18431 (defvar org-clock-heading "")
18432 (defvar org-clock-start-time "")
18434 (defun org-update-mode-line ()
18435 (let* ((delta (- (time-to-seconds (current-time))
18436 (time-to-seconds org-clock-start-time)))
18437 (h (floor delta 3600))
18438 (m (floor (- delta (* 3600 h)) 60)))
18439 (setq org-mode-line-string
18440 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18441 'help-echo "Org-mode clock is running"))
18442 (force-mode-line-update)))
18444 (defvar org-clock-marker (make-marker)
18445 "Marker recording the last clock-in.")
18446 (defvar org-clock-mode-line-entry nil
18447 "Information for the modeline about the running clock.")
18449 (defun org-clock-in ()
18450 "Start the clock on the current item.
18451 If necessary, clock-out of the currently active clock."
18452 (interactive)
18453 (org-clock-out t)
18454 (let (ts)
18455 (save-excursion
18456 (org-back-to-heading t)
18457 (when (and org-clock-in-switch-to-state
18458 (not (looking-at (concat outline-regexp "[ \t]*"
18459 org-clock-in-switch-to-state
18460 "\\>"))))
18461 (org-todo org-clock-in-switch-to-state))
18462 (if (and org-clock-heading-function
18463 (functionp org-clock-heading-function))
18464 (setq org-clock-heading (funcall org-clock-heading-function))
18465 (if (looking-at org-complex-heading-regexp)
18466 (setq org-clock-heading (match-string 4))
18467 (setq org-clock-heading "???")))
18468 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18469 (org-clock-find-position)
18471 (insert "\n") (backward-char 1)
18472 (indent-relative)
18473 (insert org-clock-string " ")
18474 (setq org-clock-start-time (current-time))
18475 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18476 (move-marker org-clock-marker (point) (buffer-base-buffer))
18477 (or global-mode-string (setq global-mode-string '("")))
18478 (or (memq 'org-mode-line-string global-mode-string)
18479 (setq global-mode-string
18480 (append global-mode-string '(org-mode-line-string))))
18481 (org-update-mode-line)
18482 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18483 (message "Clock started at %s" ts))))
18485 (defun org-clock-find-position ()
18486 "Find the location where the next clock line should be inserted."
18487 (org-back-to-heading t)
18488 (catch 'exit
18489 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18490 (re (concat "^[ \t]*" org-clock-string))
18491 (cnt 0)
18492 first last)
18493 (goto-char beg)
18494 (when (eobp) (newline) (setq end (max (point) end)))
18495 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18496 ;; we seem to have a CLOCK drawer, so go there.
18497 (beginning-of-line 2)
18498 (throw 'exit t))
18499 ;; Lets count the CLOCK lines
18500 (goto-char beg)
18501 (while (re-search-forward re end t)
18502 (setq first (or first (match-beginning 0))
18503 last (match-beginning 0)
18504 cnt (1+ cnt)))
18505 (when (and (integerp org-clock-into-drawer)
18506 (>= (1+ cnt) org-clock-into-drawer))
18507 ;; Wrap current entries into a new drawer
18508 (goto-char last)
18509 (beginning-of-line 2)
18510 (if (org-at-item-p) (org-end-of-item))
18511 (insert ":END:\n")
18512 (beginning-of-line 0)
18513 (org-indent-line-function)
18514 (goto-char first)
18515 (insert ":CLOCK:\n")
18516 (beginning-of-line 0)
18517 (org-indent-line-function)
18518 (org-flag-drawer t)
18519 (beginning-of-line 2)
18520 (throw 'exit nil))
18522 (goto-char beg)
18523 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18524 (not (equal (match-string 1) org-clock-string)))
18525 ;; Planning info, skip to after it
18526 (beginning-of-line 2)
18527 (or (bolp) (newline)))
18528 (when (eq t org-clock-into-drawer)
18529 (insert ":CLOCK:\n:END:\n")
18530 (beginning-of-line -1)
18531 (org-indent-line-function)
18532 (org-flag-drawer t)
18533 (beginning-of-line 2)
18534 (org-indent-line-function)))))
18536 (defun org-clock-out (&optional fail-quietly)
18537 "Stop the currently running clock.
18538 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18539 (interactive)
18540 (catch 'exit
18541 (if (not (marker-buffer org-clock-marker))
18542 (if fail-quietly (throw 'exit t) (error "No active clock")))
18543 (let (ts te s h m)
18544 (save-excursion
18545 (set-buffer (marker-buffer org-clock-marker))
18546 (goto-char org-clock-marker)
18547 (beginning-of-line 1)
18548 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18549 (equal (match-string 1) org-clock-string))
18550 (setq ts (match-string 2))
18551 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18552 (goto-char (match-end 0))
18553 (delete-region (point) (point-at-eol))
18554 (insert "--")
18555 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18556 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18557 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18558 h (floor (/ s 3600))
18559 s (- s (* 3600 h))
18560 m (floor (/ s 60))
18561 s (- s (* 60 s)))
18562 (insert " => " (format "%2d:%02d" h m))
18563 (move-marker org-clock-marker nil)
18564 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
18565 (org-log-done (org-parse-local-options logging 'org-log-done))
18566 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
18567 (org-add-log-maybe 'clock-out))
18568 (when org-mode-line-timer
18569 (cancel-timer org-mode-line-timer)
18570 (setq org-mode-line-timer nil))
18571 (setq global-mode-string
18572 (delq 'org-mode-line-string global-mode-string))
18573 (force-mode-line-update)
18574 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18576 (defun org-clock-cancel ()
18577 "Cancel the running clock be removing the start timestamp."
18578 (interactive)
18579 (if (not (marker-buffer org-clock-marker))
18580 (error "No active clock"))
18581 (save-excursion
18582 (set-buffer (marker-buffer org-clock-marker))
18583 (goto-char org-clock-marker)
18584 (delete-region (1- (point-at-bol)) (point-at-eol)))
18585 (setq global-mode-string
18586 (delq 'org-mode-line-string global-mode-string))
18587 (force-mode-line-update)
18588 (message "Clock canceled"))
18590 (defun org-clock-goto (&optional delete-windows)
18591 "Go to the currently clocked-in entry."
18592 (interactive "P")
18593 (if (not (marker-buffer org-clock-marker))
18594 (error "No active clock"))
18595 (switch-to-buffer-other-window
18596 (marker-buffer org-clock-marker))
18597 (if delete-windows (delete-other-windows))
18598 (goto-char org-clock-marker)
18599 (org-show-entry)
18600 (org-back-to-heading)
18601 (recenter))
18603 (defvar org-clock-file-total-minutes nil
18604 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18605 (make-variable-buffer-local 'org-clock-file-total-minutes)
18607 (defun org-clock-sum (&optional tstart tend)
18608 "Sum the times for each subtree.
18609 Puts the resulting times in minutes as a text property on each headline."
18610 (interactive)
18611 (let* ((bmp (buffer-modified-p))
18612 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18613 org-clock-string
18614 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18615 (lmax 30)
18616 (ltimes (make-vector lmax 0))
18617 (t1 0)
18618 (level 0)
18619 ts te dt
18620 time)
18621 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18622 (save-excursion
18623 (goto-char (point-max))
18624 (while (re-search-backward re nil t)
18625 (cond
18626 ((match-end 2)
18627 ;; Two time stamps
18628 (setq ts (match-string 2)
18629 te (match-string 3)
18630 ts (time-to-seconds
18631 (apply 'encode-time (org-parse-time-string ts)))
18632 te (time-to-seconds
18633 (apply 'encode-time (org-parse-time-string te)))
18634 ts (if tstart (max ts tstart) ts)
18635 te (if tend (min te tend) te)
18636 dt (- te ts)
18637 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18638 ((match-end 4)
18639 ;; A naket time
18640 (setq t1 (+ t1 (string-to-number (match-string 5))
18641 (* 60 (string-to-number (match-string 4))))))
18642 (t ;; A headline
18643 (setq level (- (match-end 1) (match-beginning 1)))
18644 (when (or (> t1 0) (> (aref ltimes level) 0))
18645 (loop for l from 0 to level do
18646 (aset ltimes l (+ (aref ltimes l) t1)))
18647 (setq t1 0 time (aref ltimes level))
18648 (loop for l from level to (1- lmax) do
18649 (aset ltimes l 0))
18650 (goto-char (match-beginning 0))
18651 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18652 (setq org-clock-file-total-minutes (aref ltimes 0)))
18653 (set-buffer-modified-p bmp)))
18655 (defun org-clock-display (&optional total-only)
18656 "Show subtree times in the entire buffer.
18657 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18658 in the echo area."
18659 (interactive)
18660 (org-remove-clock-overlays)
18661 (let (time h m p)
18662 (org-clock-sum)
18663 (unless total-only
18664 (save-excursion
18665 (goto-char (point-min))
18666 (while (or (and (equal (setq p (point)) (point-min))
18667 (get-text-property p :org-clock-minutes))
18668 (setq p (next-single-property-change
18669 (point) :org-clock-minutes)))
18670 (goto-char p)
18671 (when (setq time (get-text-property p :org-clock-minutes))
18672 (org-put-clock-overlay time (funcall outline-level))))
18673 (setq h (/ org-clock-file-total-minutes 60)
18674 m (- org-clock-file-total-minutes (* 60 h)))
18675 ;; Arrange to remove the overlays upon next change.
18676 (when org-remove-highlights-with-change
18677 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18678 nil 'local))))
18679 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18681 (defvar org-clock-overlays nil)
18682 (make-variable-buffer-local 'org-clock-overlays)
18684 (defun org-put-clock-overlay (time &optional level)
18685 "Put an overlays on the current line, displaying TIME.
18686 If LEVEL is given, prefix time with a corresponding number of stars.
18687 This creates a new overlay and stores it in `org-clock-overlays', so that it
18688 will be easy to remove."
18689 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18690 (l (if level (org-get-legal-level level 0) 0))
18691 (off 0)
18692 ov tx)
18693 (move-to-column c)
18694 (unless (eolp) (skip-chars-backward "^ \t"))
18695 (skip-chars-backward " \t")
18696 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18697 tx (concat (buffer-substring (1- (point)) (point))
18698 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18699 (org-add-props (format "%s %2d:%02d%s"
18700 (make-string l ?*) h m
18701 (make-string (- 10 l) ?\ ))
18702 '(face secondary-selection))
18703 ""))
18704 (if (not (featurep 'xemacs))
18705 (org-overlay-put ov 'display tx)
18706 (org-overlay-put ov 'invisible t)
18707 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18708 (push ov org-clock-overlays)))
18710 (defun org-remove-clock-overlays (&optional beg end noremove)
18711 "Remove the occur highlights from the buffer.
18712 BEG and END are ignored. If NOREMOVE is nil, remove this function
18713 from the `before-change-functions' in the current buffer."
18714 (interactive)
18715 (unless org-inhibit-highlight-removal
18716 (mapc 'org-delete-overlay org-clock-overlays)
18717 (setq org-clock-overlays nil)
18718 (unless noremove
18719 (remove-hook 'before-change-functions
18720 'org-remove-clock-overlays 'local))))
18722 (defun org-clock-out-if-current ()
18723 "Clock out if the current entry contains the running clock.
18724 This is used to stop the clock after a TODO entry is marked DONE,
18725 and is only done if the variable `org-clock-out-when-done' is not nil."
18726 (when (and org-clock-out-when-done
18727 (member state org-done-keywords)
18728 (equal (marker-buffer org-clock-marker) (current-buffer))
18729 (< (point) org-clock-marker)
18730 (> (save-excursion (outline-next-heading) (point))
18731 org-clock-marker))
18732 ;; Clock out, but don't accept a logging message for this.
18733 (let ((org-log-done (if (and (listp org-log-done)
18734 (member 'clock-out org-log-done))
18735 '(done)
18736 org-log-done)))
18737 (org-clock-out))))
18739 (add-hook 'org-after-todo-state-change-hook
18740 'org-clock-out-if-current)
18742 (defun org-check-running-clock ()
18743 "Check if the current buffer contains the running clock.
18744 If yes, offer to stop it and to save the buffer with the changes."
18745 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18746 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18747 (buffer-name))))
18748 (org-clock-out)
18749 (when (y-or-n-p "Save changed buffer?")
18750 (save-buffer))))
18752 (defun org-clock-report (&optional arg)
18753 "Create a table containing a report about clocked time.
18754 If the cursor is inside an existing clocktable block, then the table
18755 will be updated. If not, a new clocktable will be inserted.
18756 When called with a prefix argument, move to the first clock table in the
18757 buffer and update it."
18758 (interactive "P")
18759 (org-remove-clock-overlays)
18760 (when arg (org-find-dblock "clocktable"))
18761 (if (org-in-clocktable-p)
18762 (goto-char (org-in-clocktable-p))
18763 (org-create-dblock (list :name "clocktable"
18764 :maxlevel 2 :scope 'file)))
18765 (org-update-dblock))
18767 (defun org-in-clocktable-p ()
18768 "Check if the cursor is in a clocktable."
18769 (let ((pos (point)) start)
18770 (save-excursion
18771 (end-of-line 1)
18772 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18773 (setq start (match-beginning 0))
18774 (re-search-forward "^#\\+END:.*" nil t)
18775 (>= (match-end 0) pos)
18776 start))))
18778 (defun org-clock-update-time-maybe ()
18779 "If this is a CLOCK line, update it and return t.
18780 Otherwise, return nil."
18781 (interactive)
18782 (save-excursion
18783 (beginning-of-line 1)
18784 (skip-chars-forward " \t")
18785 (when (looking-at org-clock-string)
18786 (let ((re (concat "[ \t]*" org-clock-string
18787 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18788 "\\([ \t]*=>.*\\)?"))
18789 ts te h m s)
18790 (if (not (looking-at re))
18792 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18793 (end-of-line 1)
18794 (setq ts (match-string 1)
18795 te (match-string 2))
18796 (setq s (- (time-to-seconds
18797 (apply 'encode-time (org-parse-time-string te)))
18798 (time-to-seconds
18799 (apply 'encode-time (org-parse-time-string ts))))
18800 h (floor (/ s 3600))
18801 s (- s (* 3600 h))
18802 m (floor (/ s 60))
18803 s (- s (* 60 s)))
18804 (insert " => " (format "%2d:%02d" h m))
18805 t)))))
18807 (defun org-clock-special-range (key &optional time as-strings)
18808 "Return two times bordering a special time range.
18809 Key is a symbol specifying the range and can be one of `today', `yesterday',
18810 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18811 A week starts Monday 0:00 and ends Sunday 24:00.
18812 The range is determined relative to TIME. TIME defaults to the current time.
18813 The return value is a cons cell with two internal times like the ones
18814 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18815 the returned times will be formatted strings."
18816 (let* ((tm (decode-time (or time (current-time))))
18817 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18818 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18819 (dow (nth 6 tm))
18820 s1 m1 h1 d1 month1 y1 diff ts te fm)
18821 (cond
18822 ((eq key 'today)
18823 (setq h 0 m 0 h1 24 m1 0))
18824 ((eq key 'yesterday)
18825 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18826 ((eq key 'thisweek)
18827 (setq diff (if (= dow 0) 6 (1- dow))
18828 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18829 ((eq key 'lastweek)
18830 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18831 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18832 ((eq key 'thismonth)
18833 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18834 ((eq key 'lastmonth)
18835 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18836 ((eq key 'thisyear)
18837 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18838 ((eq key 'lastyear)
18839 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18840 (t (error "No such time block %s" key)))
18841 (setq ts (encode-time s m h d month y)
18842 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18843 (or d1 d) (or month1 month) (or y1 y)))
18844 (setq fm (cdr org-time-stamp-formats))
18845 (if as-strings
18846 (cons (format-time-string fm ts) (format-time-string fm te))
18847 (cons ts te))))
18849 (defun org-dblock-write:clocktable (params)
18850 "Write the standard clocktable."
18851 (catch 'exit
18852 (let* ((hlchars '((1 . "*") (2 . "/")))
18853 (ins (make-marker))
18854 (total-time nil)
18855 (scope (plist-get params :scope))
18856 (tostring (plist-get params :tostring))
18857 (multifile (plist-get params :multifile))
18858 (header (plist-get params :header))
18859 (maxlevel (or (plist-get params :maxlevel) 3))
18860 (step (plist-get params :step))
18861 (emph (plist-get params :emphasize))
18862 (ts (plist-get params :tstart))
18863 (te (plist-get params :tend))
18864 (block (plist-get params :block))
18865 ipos time h m p level hlc hdl
18866 cc beg end pos tbl)
18867 (when step
18868 (org-clocktable-steps params)
18869 (throw 'exit nil))
18870 (when block
18871 (setq cc (org-clock-special-range block nil t)
18872 ts (car cc) te (cdr cc)))
18873 (if ts (setq ts (time-to-seconds
18874 (apply 'encode-time (org-parse-time-string ts)))))
18875 (if te (setq te (time-to-seconds
18876 (apply 'encode-time (org-parse-time-string te)))))
18877 (move-marker ins (point))
18878 (setq ipos (point))
18880 ;; Get the right scope
18881 (setq pos (point))
18882 (save-restriction
18883 (cond
18884 ((not scope))
18885 ((eq scope 'file) (widen))
18886 ((eq scope 'subtree) (org-narrow-to-subtree))
18887 ((eq scope 'tree)
18888 (while (org-up-heading-safe))
18889 (org-narrow-to-subtree))
18890 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18891 (symbol-name scope)))
18892 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18893 (catch 'exit
18894 (while (org-up-heading-safe)
18895 (looking-at outline-regexp)
18896 (if (<= (org-reduced-level (funcall outline-level)) level)
18897 (throw 'exit nil))))
18898 (org-narrow-to-subtree))
18899 ((or (listp scope) (eq scope 'agenda))
18900 (let* ((files (if (listp scope) scope (org-agenda-files)))
18901 (scope 'agenda)
18902 (p1 (copy-sequence params))
18903 file)
18904 (plist-put p1 :tostring t)
18905 (plist-put p1 :multifile t)
18906 (plist-put p1 :scope 'file)
18907 (org-prepare-agenda-buffers files)
18908 (while (setq file (pop files))
18909 (with-current-buffer (find-buffer-visiting file)
18910 (push (org-clocktable-add-file
18911 file (org-dblock-write:clocktable p1)) tbl)
18912 (setq total-time (+ (or total-time 0)
18913 org-clock-file-total-minutes)))))))
18914 (goto-char pos)
18916 (unless (eq scope 'agenda)
18917 (org-clock-sum ts te)
18918 (goto-char (point-min))
18919 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18920 (goto-char p)
18921 (when (setq time (get-text-property p :org-clock-minutes))
18922 (save-excursion
18923 (beginning-of-line 1)
18924 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18925 (setq level (org-reduced-level
18926 (- (match-end 1) (match-beginning 1))))
18927 (<= level maxlevel))
18928 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
18929 hdl (match-string 2)
18930 h (/ time 60)
18931 m (- time (* 60 h)))
18932 (if (and (not multifile) (= level 1)) (push "|-" tbl))
18933 (push (concat
18934 "| " (int-to-string level) "|" hlc hdl hlc " |"
18935 (make-string (1- level) ?|)
18936 hlc (format "%d:%02d" h m) hlc
18937 " |") tbl))))))
18938 (setq tbl (nreverse tbl))
18939 (if tostring
18940 (if tbl (mapconcat 'identity tbl "\n") nil)
18941 (goto-char ins)
18942 (insert-before-markers
18943 (or header
18944 (concat
18945 "Clock summary at ["
18946 (substring
18947 (format-time-string (cdr org-time-stamp-formats))
18948 1 -1)
18949 "]."
18950 (if block
18951 (format " Considered range is /%s/." block)
18953 "\n\n"))
18954 (if (eq scope 'agenda) "|File" "")
18955 "|L|Headline|Time|\n")
18956 (setq total-time (or total-time org-clock-file-total-minutes)
18957 h (/ total-time 60)
18958 m (- total-time (* 60 h)))
18959 (insert-before-markers
18960 "|-\n|"
18961 (if (eq scope 'agenda) "|" "")
18963 "*Total time*| "
18964 (format "*%d:%02d*" h m)
18965 "|\n|-\n")
18966 (setq tbl (delq nil tbl))
18967 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
18968 (equal (substring (car tbl) 0 2) "|-"))
18969 (pop tbl))
18970 (insert-before-markers (mapconcat
18971 'identity (delq nil tbl)
18972 (if (eq scope 'agenda) "\n|-\n" "\n")))
18973 (backward-delete-char 1)
18974 (goto-char ipos)
18975 (skip-chars-forward "^|")
18976 (org-table-align))))))
18978 (defun org-clocktable-steps (params)
18979 (let* ((p1 (copy-sequence params))
18980 (ts (plist-get p1 :tstart))
18981 (te (plist-get p1 :tend))
18982 (step0 (plist-get p1 :step))
18983 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
18984 (block (plist-get p1 :block))
18986 (when block
18987 (setq cc (org-clock-special-range block nil t)
18988 ts (car cc) te (cdr cc)))
18989 (if ts (setq ts (time-to-seconds
18990 (apply 'encode-time (org-parse-time-string ts)))))
18991 (if te (setq te (time-to-seconds
18992 (apply 'encode-time (org-parse-time-string te)))))
18993 (plist-put p1 :header "")
18994 (plist-put p1 :step nil)
18995 (plist-put p1 :block nil)
18996 (while (< ts te)
18997 (or (bolp) (insert "\n"))
18998 (plist-put p1 :tstart (format-time-string
18999 (car org-time-stamp-formats)
19000 (seconds-to-time ts)))
19001 (plist-put p1 :tend (format-time-string
19002 (car org-time-stamp-formats)
19003 (seconds-to-time (setq ts (+ ts step)))))
19004 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19005 (plist-get p1 :tstart) "\n")
19006 (org-dblock-write:clocktable p1)
19007 (re-search-forward "#\\+END:")
19008 (end-of-line 0))))
19011 (defun org-clocktable-add-file (file table)
19012 (if table
19013 (let ((lines (org-split-string table "\n"))
19014 (ff (file-name-nondirectory file)))
19015 (mapconcat 'identity
19016 (mapcar (lambda (x)
19017 (if (string-match org-table-dataline-regexp x)
19018 (concat "|" ff x)
19020 lines)
19021 "\n"))))
19023 ;; FIXME: I don't think anybody uses this, ask David
19024 (defun org-collect-clock-time-entries ()
19025 "Return an internal list with clocking information.
19026 This list has one entry for each CLOCK interval.
19027 FIXME: describe the elements."
19028 (interactive)
19029 (let ((re (concat "^[ \t]*" org-clock-string
19030 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19031 rtn beg end next cont level title total closedp leafp
19032 clockpos titlepos h m donep)
19033 (save-excursion
19034 (org-clock-sum)
19035 (goto-char (point-min))
19036 (while (re-search-forward re nil t)
19037 (setq clockpos (match-beginning 0)
19038 beg (match-string 1) end (match-string 2)
19039 cont (match-end 0))
19040 (setq beg (apply 'encode-time (org-parse-time-string beg))
19041 end (apply 'encode-time (org-parse-time-string end)))
19042 (org-back-to-heading t)
19043 (setq donep (org-entry-is-done-p))
19044 (setq titlepos (point)
19045 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19046 h (/ total 60) m (- total (* 60 h))
19047 total (cons h m))
19048 (looking-at "\\(\\*+\\) +\\(.*\\)")
19049 (setq level (- (match-end 1) (match-beginning 1))
19050 title (org-match-string-no-properties 2))
19051 (save-excursion (outline-next-heading) (setq next (point)))
19052 (setq closedp (re-search-forward org-closed-time-regexp next t))
19053 (goto-char next)
19054 (setq leafp (and (looking-at "^\\*+ ")
19055 (<= (- (match-end 0) (point)) level)))
19056 (push (list beg end clockpos closedp donep
19057 total title titlepos level leafp)
19058 rtn)
19059 (goto-char cont)))
19060 (nreverse rtn)))
19062 ;;;; Agenda, and Diary Integration
19064 ;;; Define the Org-agenda-mode
19066 (defvar org-agenda-mode-map (make-sparse-keymap)
19067 "Keymap for `org-agenda-mode'.")
19069 (defvar org-agenda-menu) ; defined later in this file.
19070 (defvar org-agenda-follow-mode nil)
19071 (defvar org-agenda-show-log nil)
19072 (defvar org-agenda-redo-command nil)
19073 (defvar org-agenda-mode-hook nil)
19074 (defvar org-agenda-type nil)
19075 (defvar org-agenda-force-single-file nil)
19077 (defun org-agenda-mode ()
19078 "Mode for time-sorted view on action items in Org-mode files.
19080 The following commands are available:
19082 \\{org-agenda-mode-map}"
19083 (interactive)
19084 (kill-all-local-variables)
19085 (setq org-agenda-undo-list nil
19086 org-agenda-pending-undo-list nil)
19087 (setq major-mode 'org-agenda-mode)
19088 ;; Keep global-font-lock-mode from turning on font-lock-mode
19089 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19090 (setq mode-name "Org-Agenda")
19091 (use-local-map org-agenda-mode-map)
19092 (easy-menu-add org-agenda-menu)
19093 (if org-startup-truncated (setq truncate-lines t))
19094 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19095 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19096 ;; Make sure properties are removed when copying text
19097 (when (boundp 'buffer-substring-filters)
19098 (org-set-local 'buffer-substring-filters
19099 (cons (lambda (x)
19100 (set-text-properties 0 (length x) nil x) x)
19101 buffer-substring-filters)))
19102 (unless org-agenda-keep-modes
19103 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19104 org-agenda-show-log nil))
19105 (easy-menu-change
19106 '("Agenda") "Agenda Files"
19107 (append
19108 (list
19109 (vector
19110 (if (get 'org-agenda-files 'org-restrict)
19111 "Restricted to single file"
19112 "Edit File List")
19113 '(org-edit-agenda-file-list)
19114 (not (get 'org-agenda-files 'org-restrict)))
19115 "--")
19116 (mapcar 'org-file-menu-entry (org-agenda-files))))
19117 (org-agenda-set-mode-name)
19118 (apply
19119 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19120 (list 'org-agenda-mode-hook)))
19122 (substitute-key-definition 'undo 'org-agenda-undo
19123 org-agenda-mode-map global-map)
19124 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19125 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19126 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19127 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19128 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19129 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19130 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19131 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19132 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19133 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19134 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19135 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19136 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19137 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19138 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19139 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19140 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19141 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19142 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19143 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19144 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19145 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19146 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19147 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19148 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19149 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19150 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19151 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19152 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19154 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19155 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19156 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19157 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19158 (while l (org-defkey org-agenda-mode-map
19159 (int-to-string (pop l)) 'digit-argument)))
19161 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19162 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19163 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19164 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19165 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19166 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19167 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19168 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19169 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19170 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19171 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19172 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19173 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19174 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19175 (org-defkey org-agenda-mode-map "n" 'next-line)
19176 (org-defkey org-agenda-mode-map "p" 'previous-line)
19177 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19178 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19179 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19180 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19181 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19182 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19183 (eval-after-load "calendar"
19184 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19185 'org-calendar-goto-agenda))
19186 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19187 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19188 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19189 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19190 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19191 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19192 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19193 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19194 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19195 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19196 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19197 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19198 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19199 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19200 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19201 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19202 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19203 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19204 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19205 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19206 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19207 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19209 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19210 "Local keymap for agenda entries from Org-mode.")
19212 (org-defkey org-agenda-keymap
19213 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19214 (org-defkey org-agenda-keymap
19215 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19216 (when org-agenda-mouse-1-follows-link
19217 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19218 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19219 '("Agenda"
19220 ("Agenda Files")
19221 "--"
19222 ["Show" org-agenda-show t]
19223 ["Go To (other window)" org-agenda-goto t]
19224 ["Go To (this window)" org-agenda-switch-to t]
19225 ["Follow Mode" org-agenda-follow-mode
19226 :style toggle :selected org-agenda-follow-mode :active t]
19227 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19228 "--"
19229 ["Cycle TODO" org-agenda-todo t]
19230 ["Archive subtree" org-agenda-archive t]
19231 ["Delete subtree" org-agenda-kill t]
19232 "--"
19233 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19234 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19235 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19236 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19237 "--"
19238 ("Tags and Properties"
19239 ["Show all Tags" org-agenda-show-tags t]
19240 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19241 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19242 "--"
19243 ["Column View" org-columns t])
19244 ("Date/Schedule"
19245 ["Schedule" org-agenda-schedule t]
19246 ["Set Deadline" org-agenda-deadline t]
19247 "--"
19248 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19249 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19250 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19251 ("Clock"
19252 ["Clock in" org-agenda-clock-in t]
19253 ["Clock out" org-agenda-clock-out t]
19254 ["Clock cancel" org-agenda-clock-cancel t]
19255 ["Goto running clock" org-clock-goto t])
19256 ("Priority"
19257 ["Set Priority" org-agenda-priority t]
19258 ["Increase Priority" org-agenda-priority-up t]
19259 ["Decrease Priority" org-agenda-priority-down t]
19260 ["Show Priority" org-agenda-show-priority t])
19261 ("Calendar/Diary"
19262 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19263 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19264 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19265 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19266 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19267 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19268 "--"
19269 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19270 "--"
19271 ("View"
19272 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19273 :style radio :selected (equal org-agenda-ndays 1)]
19274 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19275 :style radio :selected (equal org-agenda-ndays 7)]
19276 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19277 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19278 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19279 :style radio :selected (member org-agenda-ndays '(365 366))]
19280 "--"
19281 ["Show Logbook entries" org-agenda-log-mode
19282 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19283 ["Include Diary" org-agenda-toggle-diary
19284 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19285 ["Use Time Grid" org-agenda-toggle-time-grid
19286 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19287 ["Write view to file" org-write-agenda t]
19288 ["Rebuild buffer" org-agenda-redo t]
19289 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19290 "--"
19291 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19292 "--"
19293 ["Quit" org-agenda-quit t]
19294 ["Exit and Release Buffers" org-agenda-exit t]
19297 ;;; Agenda undo
19299 (defvar org-agenda-allow-remote-undo t
19300 "Non-nil means, allow remote undo from the agenda buffer.")
19301 (defvar org-agenda-undo-list nil
19302 "List of undoable operations in the agenda since last refresh.")
19303 (defvar org-agenda-undo-has-started-in nil
19304 "Buffers that have already seen `undo-start' in the current undo sequence.")
19305 (defvar org-agenda-pending-undo-list nil
19306 "In a series of undo commands, this is the list of remaning undo items.")
19308 (defmacro org-if-unprotected (&rest body)
19309 "Execute BODY if there is no `org-protected' text property at point."
19310 (declare (debug t))
19311 `(unless (get-text-property (point) 'org-protected)
19312 ,@body))
19314 (defmacro org-with-remote-undo (_buffer &rest _body)
19315 "Execute BODY while recording undo information in two buffers."
19316 (declare (indent 1) (debug t))
19317 `(let ((_cline (org-current-line))
19318 (_cmd this-command)
19319 (_buf1 (current-buffer))
19320 (_buf2 ,_buffer)
19321 (_undo1 buffer-undo-list)
19322 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19323 _c1 _c2)
19324 ,@_body
19325 (when org-agenda-allow-remote-undo
19326 (setq _c1 (org-verify-change-for-undo
19327 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19328 _c2 (org-verify-change-for-undo
19329 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19330 (when (or _c1 _c2)
19331 ;; make sure there are undo boundaries
19332 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19333 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19334 ;; remember which buffer to undo
19335 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19336 org-agenda-undo-list)))))
19338 (defun org-agenda-undo ()
19339 "Undo a remote editing step in the agenda.
19340 This undoes changes both in the agenda buffer and in the remote buffer
19341 that have been changed along."
19342 (interactive)
19343 (or org-agenda-allow-remote-undo
19344 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19345 (if (not (eq this-command last-command))
19346 (setq org-agenda-undo-has-started-in nil
19347 org-agenda-pending-undo-list org-agenda-undo-list))
19348 (if (not org-agenda-pending-undo-list)
19349 (error "No further undo information"))
19350 (let* ((entry (pop org-agenda-pending-undo-list))
19351 buf line cmd rembuf)
19352 (setq cmd (pop entry) line (pop entry))
19353 (setq rembuf (nth 2 entry))
19354 (org-with-remote-undo rembuf
19355 (while (bufferp (setq buf (pop entry)))
19356 (if (pop entry)
19357 (with-current-buffer buf
19358 (let ((last-undo-buffer buf)
19359 (inhibit-read-only t))
19360 (unless (memq buf org-agenda-undo-has-started-in)
19361 (push buf org-agenda-undo-has-started-in)
19362 (make-local-variable 'pending-undo-list)
19363 (undo-start))
19364 (while (and pending-undo-list
19365 (listp pending-undo-list)
19366 (not (car pending-undo-list)))
19367 (pop pending-undo-list))
19368 (undo-more 1))))))
19369 (goto-line line)
19370 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19372 (defun org-verify-change-for-undo (l1 l2)
19373 "Verify that a real change occurred between the undo lists L1 and L2."
19374 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19375 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19376 (not (eq l1 l2)))
19378 ;;; Agenda dispatch
19380 (defvar org-agenda-restrict nil)
19381 (defvar org-agenda-restrict-begin (make-marker))
19382 (defvar org-agenda-restrict-end (make-marker))
19383 (defvar org-agenda-last-dispatch-buffer nil)
19384 (defvar org-agenda-overriding-restriction nil)
19386 ;;;###autoload
19387 (defun org-agenda (arg &optional keys restriction)
19388 "Dispatch agenda commands to collect entries to the agenda buffer.
19389 Prompts for a command to execute. Any prefix arg will be passed
19390 on to the selected command. The default selections are:
19392 a Call `org-agenda-list' to display the agenda for current day or week.
19393 t Call `org-todo-list' to display the global todo list.
19394 T Call `org-todo-list' to display the global todo list, select only
19395 entries with a specific TODO keyword (the user gets a prompt).
19396 m Call `org-tags-view' to display headlines with tags matching
19397 a condition (the user is prompted for the condition).
19398 M Like `m', but select only TODO entries, no ordinary headlines.
19399 L Create a timeline for the current buffer.
19400 e Export views to associated files.
19402 More commands can be added by configuring the variable
19403 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19404 searches can be pre-defined in this way.
19406 If the current buffer is in Org-mode and visiting a file, you can also
19407 first press `<' once to indicate that the agenda should be temporarily
19408 \(until the next use of \\[org-agenda]) restricted to the current file.
19409 Pressing `<' twice means to restrict to the current subtree or region
19410 \(if active)."
19411 (interactive "P")
19412 (catch 'exit
19413 (let* ((prefix-descriptions nil)
19414 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19415 (org-agenda-custom-commands
19416 ;; normalize different versions
19417 (delq nil
19418 (mapcar
19419 (lambda (x)
19420 (cond ((stringp (cdr x))
19421 (push x prefix-descriptions)
19422 nil)
19423 ((stringp (nth 1 x)) x)
19424 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19425 (t (cons (car x) (cons "" (cdr x))))))
19426 org-agenda-custom-commands)))
19427 (buf (current-buffer))
19428 (bfn (buffer-file-name (buffer-base-buffer)))
19429 entry key type match lprops ans)
19430 ;; Turn off restriction unless there is an overriding one
19431 (unless org-agenda-overriding-restriction
19432 (put 'org-agenda-files 'org-restrict nil)
19433 (setq org-agenda-restrict nil)
19434 (move-marker org-agenda-restrict-begin nil)
19435 (move-marker org-agenda-restrict-end nil))
19436 ;; Delete old local properties
19437 (put 'org-agenda-redo-command 'org-lprops nil)
19438 ;; Remember where this call originated
19439 (setq org-agenda-last-dispatch-buffer (current-buffer))
19440 (unless keys
19441 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19442 keys (car ans)
19443 restriction (cdr ans)))
19444 ;; Estabish the restriction, if any
19445 (when (and (not org-agenda-overriding-restriction) restriction)
19446 (put 'org-agenda-files 'org-restrict (list bfn))
19447 (cond
19448 ((eq restriction 'region)
19449 (setq org-agenda-restrict t)
19450 (move-marker org-agenda-restrict-begin (region-beginning))
19451 (move-marker org-agenda-restrict-end (region-end)))
19452 ((eq restriction 'subtree)
19453 (save-excursion
19454 (setq org-agenda-restrict t)
19455 (org-back-to-heading t)
19456 (move-marker org-agenda-restrict-begin (point))
19457 (move-marker org-agenda-restrict-end
19458 (progn (org-end-of-subtree t)))))))
19460 (require 'calendar) ; FIXME: can we avoid this for some commands?
19461 ;; For example the todo list should not need it (but does...)
19462 (cond
19463 ((setq entry (assoc keys org-agenda-custom-commands))
19464 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19465 (progn
19466 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19467 (put 'org-agenda-redo-command 'org-lprops lprops)
19468 (cond
19469 ((eq type 'agenda)
19470 (org-let lprops '(org-agenda-list current-prefix-arg)))
19471 ((eq type 'alltodo)
19472 (org-let lprops '(org-todo-list current-prefix-arg)))
19473 ((eq type 'stuck)
19474 (org-let lprops '(org-agenda-list-stuck-projects
19475 current-prefix-arg)))
19476 ((eq type 'tags)
19477 (org-let lprops '(org-tags-view current-prefix-arg match)))
19478 ((eq type 'tags-todo)
19479 (org-let lprops '(org-tags-view '(4) match)))
19480 ((eq type 'todo)
19481 (org-let lprops '(org-todo-list match)))
19482 ((eq type 'tags-tree)
19483 (org-check-for-org-mode)
19484 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19485 ((eq type 'todo-tree)
19486 (org-check-for-org-mode)
19487 (org-let lprops
19488 '(org-occur (concat "^" outline-regexp "[ \t]*"
19489 (regexp-quote match) "\\>"))))
19490 ((eq type 'occur-tree)
19491 (org-check-for-org-mode)
19492 (org-let lprops '(org-occur match)))
19493 ((functionp type)
19494 (org-let lprops '(funcall type match)))
19495 ((fboundp type)
19496 (org-let lprops '(funcall type match)))
19497 (t (error "Invalid custom agenda command type %s" type))))
19498 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19499 ((equal keys "C")
19500 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19501 (customize-variable 'org-agenda-custom-commands))
19502 ((equal keys "a") (call-interactively 'org-agenda-list))
19503 ((equal keys "t") (call-interactively 'org-todo-list))
19504 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19505 ((equal keys "m") (call-interactively 'org-tags-view))
19506 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19507 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19508 ((equal keys "L")
19509 (unless (org-mode-p)
19510 (error "This is not an Org-mode file"))
19511 (unless restriction
19512 (put 'org-agenda-files 'org-restrict (list bfn))
19513 (org-call-with-arg 'org-timeline arg)))
19514 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19515 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19516 ((equal keys "!") (customize-variable 'org-stuck-projects))
19517 (t (error "Invalid agenda key"))))))
19519 (defun org-agenda-normalize-custom-commands (cmds)
19520 (delq nil
19521 (mapcar
19522 (lambda (x)
19523 (cond ((stringp (cdr x)) nil)
19524 ((stringp (nth 1 x)) x)
19525 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19526 (t (cons (car x) (cons "" (cdr x))))))
19527 cmds)))
19529 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19530 "The user interface for selecting an agenda command."
19531 (catch 'exit
19532 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19533 (restrict-ok (and bfn (org-mode-p)))
19534 (region-p (org-region-active-p))
19535 (custom org-agenda-custom-commands)
19536 (selstring "")
19537 restriction second-time
19538 c entry key type match prefixes rmheader header-end custom1 desc)
19539 (save-window-excursion
19540 (delete-other-windows)
19541 (org-switch-to-buffer-other-window " *Agenda Commands*")
19542 (erase-buffer)
19543 (insert (eval-when-compile
19544 (let ((header
19546 Press key for an agenda command: < Buffer,subtree/region restriction
19547 -------------------------------- > Remove restriction
19548 a Agenda for current week or day e Export agenda views
19549 t List of all TODO entries T Entries with special TODO kwd
19550 m Match a TAGS query M Like m, but only TODO entries
19551 L Timeline for current buffer # List stuck projects (!=configure)
19552 / Multi-occur C Configure custom agenda commands
19554 (start 0))
19555 (while (string-match
19556 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19557 header start)
19558 (setq start (match-end 0))
19559 (add-text-properties (match-beginning 2) (match-end 2)
19560 '(face bold) header))
19561 header)))
19562 (setq header-end (move-marker (make-marker) (point)))
19563 (while t
19564 (setq custom1 custom)
19565 (when (eq rmheader t)
19566 (goto-line 1)
19567 (re-search-forward ":" nil t)
19568 (delete-region (match-end 0) (point-at-eol))
19569 (forward-char 1)
19570 (looking-at "-+")
19571 (delete-region (match-end 0) (point-at-eol))
19572 (move-marker header-end (match-end 0)))
19573 (goto-char header-end)
19574 (delete-region (point) (point-max))
19575 (while (setq entry (pop custom1))
19576 (setq key (car entry) desc (nth 1 entry)
19577 type (nth 2 entry) match (nth 3 entry))
19578 (if (> (length key) 1)
19579 (add-to-list 'prefixes (string-to-char key))
19580 (insert
19581 (format
19582 "\n%-4s%-14s: %s"
19583 (org-add-props (copy-sequence key)
19584 '(face bold))
19585 (cond
19586 ((string-match "\\S-" desc) desc)
19587 ((eq type 'agenda) "Agenda for current week or day")
19588 ((eq type 'alltodo) "List of all TODO entries")
19589 ((eq type 'stuck) "List of stuck projects")
19590 ((eq type 'todo) "TODO keyword")
19591 ((eq type 'tags) "Tags query")
19592 ((eq type 'tags-todo) "Tags (TODO)")
19593 ((eq type 'tags-tree) "Tags tree")
19594 ((eq type 'todo-tree) "TODO kwd tree")
19595 ((eq type 'occur-tree) "Occur tree")
19596 ((functionp type) (if (symbolp type)
19597 (symbol-name type)
19598 "Lambda expression"))
19599 (t "???"))
19600 (cond
19601 ((stringp match)
19602 (org-add-props match nil 'face 'org-warning))
19603 (match
19604 (format "set of %d commands" (length match)))
19605 (t ""))))))
19606 (when prefixes
19607 (mapc (lambda (x)
19608 (insert
19609 (format "\n%s %s"
19610 (org-add-props (char-to-string x)
19611 nil 'face 'bold)
19612 (or (cdr (assoc (concat selstring (char-to-string x))
19613 prefix-descriptions))
19614 "Prefix key"))))
19615 prefixes))
19616 (goto-char (point-min))
19617 (when (fboundp 'fit-window-to-buffer)
19618 (if second-time
19619 (if (not (pos-visible-in-window-p (point-max)))
19620 (fit-window-to-buffer))
19621 (setq second-time t)
19622 (fit-window-to-buffer)))
19623 (message "Press key for agenda command%s:"
19624 (if (or restrict-ok org-agenda-overriding-restriction)
19625 (if org-agenda-overriding-restriction
19626 " (restriction lock active)"
19627 (if restriction
19628 (format " (restricted to %s)" restriction)
19629 " (unrestricted)"))
19630 ""))
19631 (setq c (read-char-exclusive))
19632 (message "")
19633 (cond
19634 ((assoc (char-to-string c) custom)
19635 (setq selstring (concat selstring (char-to-string c)))
19636 (throw 'exit (cons selstring restriction)))
19637 ((memq c prefixes)
19638 (setq selstring (concat selstring (char-to-string c))
19639 prefixes nil
19640 rmheader (or rmheader t)
19641 custom (delq nil (mapcar
19642 (lambda (x)
19643 (if (or (= (length (car x)) 1)
19644 (/= (string-to-char (car x)) c))
19646 (cons (substring (car x) 1) (cdr x))))
19647 custom))))
19648 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19649 (message "Restriction is only possible in Org-mode buffers")
19650 (ding) (sit-for 1))
19651 ((eq c ?1)
19652 (org-agenda-remove-restriction-lock 'noupdate)
19653 (setq restriction 'buffer))
19654 ((eq c ?0)
19655 (org-agenda-remove-restriction-lock 'noupdate)
19656 (setq restriction (if region-p 'region 'subtree)))
19657 ((eq c ?<)
19658 (org-agenda-remove-restriction-lock 'noupdate)
19659 (setq restriction
19660 (cond
19661 ((eq restriction 'buffer)
19662 (if region-p 'region 'subtree))
19663 ((memq restriction '(subtree region))
19664 nil)
19665 (t 'buffer))))
19666 ((eq c ?>)
19667 (org-agenda-remove-restriction-lock 'noupdate)
19668 (setq restriction nil))
19669 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19670 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19671 ((and (> (length selstring) 0) (eq c ?\d))
19672 (delete-window)
19673 (org-agenda-get-restriction-and-command prefix-descriptions))
19675 ((equal c ?q) (error "Abort"))
19676 (t (error "Invalid key %c" c))))))))
19678 (defun org-run-agenda-series (name series)
19679 (org-prepare-agenda name)
19680 (let* ((org-agenda-multi t)
19681 (redo (list 'org-run-agenda-series name (list 'quote series)))
19682 (cmds (car series))
19683 (gprops (nth 1 series))
19684 match ;; The byte compiler incorrectly complains about this. Keep it!
19685 cmd type lprops)
19686 (while (setq cmd (pop cmds))
19687 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19688 (cond
19689 ((eq type 'agenda)
19690 (org-let2 gprops lprops
19691 '(call-interactively 'org-agenda-list)))
19692 ((eq type 'alltodo)
19693 (org-let2 gprops lprops
19694 '(call-interactively 'org-todo-list)))
19695 ((eq type 'stuck)
19696 (org-let2 gprops lprops
19697 '(call-interactively 'org-agenda-list-stuck-projects)))
19698 ((eq type 'tags)
19699 (org-let2 gprops lprops
19700 '(org-tags-view current-prefix-arg match)))
19701 ((eq type 'tags-todo)
19702 (org-let2 gprops lprops
19703 '(org-tags-view '(4) match)))
19704 ((eq type 'todo)
19705 (org-let2 gprops lprops
19706 '(org-todo-list match)))
19707 ((fboundp type)
19708 (org-let2 gprops lprops
19709 '(funcall type match)))
19710 (t (error "Invalid type in command series"))))
19711 (widen)
19712 (setq org-agenda-redo-command redo)
19713 (goto-char (point-min)))
19714 (org-finalize-agenda))
19716 ;;;###autoload
19717 (defmacro org-batch-agenda (cmd-key &rest parameters)
19718 "Run an agenda command in batch mode and send the result to STDOUT.
19719 If CMD-KEY is a string of length 1, it is used as a key in
19720 `org-agenda-custom-commands' and triggers this command. If it is a
19721 longer string it is used as a tags/todo match string.
19722 Paramters are alternating variable names and values that will be bound
19723 before running the agenda command."
19724 (let (pars)
19725 (while parameters
19726 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19727 (if (> (length cmd-key) 2)
19728 (eval (list 'let (nreverse pars)
19729 (list 'org-tags-view nil cmd-key)))
19730 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19731 (set-buffer org-agenda-buffer-name)
19732 (princ (org-encode-for-stdout (buffer-string)))))
19734 (defun org-encode-for-stdout (string)
19735 (if (fboundp 'encode-coding-string)
19736 (encode-coding-string string buffer-file-coding-system)
19737 string))
19739 (defvar org-agenda-info nil)
19741 ;;;###autoload
19742 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19743 "Run an agenda command in batch mode and send the result to STDOUT.
19744 If CMD-KEY is a string of length 1, it is used as a key in
19745 `org-agenda-custom-commands' and triggers this command. If it is a
19746 longer string it is used as a tags/todo match string.
19747 Paramters are alternating variable names and values that will be bound
19748 before running the agenda command.
19750 The output gives a line for each selected agenda item. Each
19751 item is a list of comma-separated values, like this:
19753 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19755 category The category of the item
19756 head The headline, without TODO kwd, TAGS and PRIORITY
19757 type The type of the agenda entry, can be
19758 todo selected in TODO match
19759 tagsmatch selected in tags match
19760 diary imported from diary
19761 deadline a deadline on given date
19762 scheduled scheduled on given date
19763 timestamp entry has timestamp on given date
19764 closed entry was closed on given date
19765 upcoming-deadline warning about deadline
19766 past-scheduled forwarded scheduled item
19767 block entry has date block including g. date
19768 todo The todo keyword, if any
19769 tags All tags including inherited ones, separated by colons
19770 date The relevant date, like 2007-2-14
19771 time The time, like 15:00-16:50
19772 extra Sting with extra planning info
19773 priority-l The priority letter if any was given
19774 priority-n The computed numerical priority
19775 agenda-day The day in the agenda where this is listed"
19777 (let (pars)
19778 (while parameters
19779 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19780 (push (list 'org-agenda-remove-tags t) pars)
19781 (if (> (length cmd-key) 2)
19782 (eval (list 'let (nreverse pars)
19783 (list 'org-tags-view nil cmd-key)))
19784 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19785 (set-buffer org-agenda-buffer-name)
19786 (let* ((lines (org-split-string (buffer-string) "\n"))
19787 line)
19788 (while (setq line (pop lines))
19789 (catch 'next
19790 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19791 (setq org-agenda-info
19792 (org-fix-agenda-info (text-properties-at 0 line)))
19793 (princ
19794 (org-encode-for-stdout
19795 (mapconcat 'org-agenda-export-csv-mapper
19796 '(org-category txt type todo tags date time-of-day extra
19797 priority-letter priority agenda-day)
19798 ",")))
19799 (princ "\n"))))))
19801 (defun org-fix-agenda-info (props)
19802 "Make sure all properties on an agenda item have a canonical form,
19803 so the export commands can easily use it."
19804 (let (tmp re)
19805 (when (setq tmp (plist-get props 'tags))
19806 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19807 (when (setq tmp (plist-get props 'date))
19808 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19809 (let ((calendar-date-display-form '(year "-" month "-" day)))
19810 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19812 (setq tmp (calendar-date-string tmp)))
19813 (setq props (plist-put props 'date tmp)))
19814 (when (setq tmp (plist-get props 'day))
19815 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19816 (let ((calendar-date-display-form '(year "-" month "-" day)))
19817 (setq tmp (calendar-date-string tmp)))
19818 (setq props (plist-put props 'day tmp))
19819 (setq props (plist-put props 'agenda-day tmp)))
19820 (when (setq tmp (plist-get props 'txt))
19821 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19822 (plist-put props 'priority-letter (match-string 1 tmp))
19823 (setq tmp (replace-match "" t t tmp)))
19824 (when (and (setq re (plist-get props 'org-todo-regexp))
19825 (setq re (concat "\\`\\.*" re " ?"))
19826 (string-match re tmp))
19827 (plist-put props 'todo (match-string 1 tmp))
19828 (setq tmp (replace-match "" t t tmp)))
19829 (plist-put props 'txt tmp)))
19830 props)
19832 (defun org-agenda-export-csv-mapper (prop)
19833 (let ((res (plist-get org-agenda-info prop)))
19834 (setq res
19835 (cond
19836 ((not res) "")
19837 ((stringp res) res)
19838 (t (prin1-to-string res))))
19839 (while (string-match "," res)
19840 (setq res (replace-match ";" t t res)))
19841 (org-trim res)))
19844 ;;;###autoload
19845 (defun org-store-agenda-views (&rest parameters)
19846 (interactive)
19847 (eval (list 'org-batch-store-agenda-views)))
19849 ;; FIXME, why is this a macro?????
19850 ;;;###autoload
19851 (defmacro org-batch-store-agenda-views (&rest parameters)
19852 "Run all custom agenda commands that have a file argument."
19853 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
19854 (pop-up-frames nil)
19855 (dir default-directory)
19856 pars cmd thiscmdkey files opts)
19857 (while parameters
19858 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19859 (setq pars (reverse pars))
19860 (save-window-excursion
19861 (while cmds
19862 (setq cmd (pop cmds)
19863 thiscmdkey (car cmd)
19864 opts (nth 4 cmd)
19865 files (nth 5 cmd))
19866 (if (stringp files) (setq files (list files)))
19867 (when files
19868 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19869 (list 'org-agenda nil thiscmdkey)))
19870 (set-buffer org-agenda-buffer-name)
19871 (while files
19872 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19873 (list 'org-write-agenda
19874 (expand-file-name (pop files) dir) t))))
19875 (and (get-buffer org-agenda-buffer-name)
19876 (kill-buffer org-agenda-buffer-name)))))))
19878 (defun org-write-agenda (file &optional nosettings)
19879 "Write the current buffer (an agenda view) as a file.
19880 Depending on the extension of the file name, plain text (.txt),
19881 HTML (.html or .htm) or Postscript (.ps) is produced.
19882 If NOSETTINGS is given, do not scope the settings of
19883 `org-agenda-exporter-settings' into the export commands. This is used when
19884 the settings have already been scoped and we do not wish to overrule other,
19885 higher priority settings."
19886 (interactive "FWrite agenda to file: ")
19887 (if (not (file-writable-p file))
19888 (error "Cannot write agenda to file %s" file))
19889 (cond
19890 ((string-match "\\.html?\\'" file) (require 'htmlize))
19891 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19892 (org-let (if nosettings nil org-agenda-exporter-settings)
19893 '(save-excursion
19894 (save-window-excursion
19895 (cond
19896 ((string-match "\\.html?\\'" file)
19897 (set-buffer (htmlize-buffer (current-buffer)))
19899 (when (and org-agenda-export-html-style
19900 (string-match "<style>" org-agenda-export-html-style))
19901 ;; replace <style> section with org-agenda-export-html-style
19902 (goto-char (point-min))
19903 (kill-region (- (search-forward "<style") 6)
19904 (search-forward "</style>"))
19905 (insert org-agenda-export-html-style))
19906 (write-file file)
19907 (kill-buffer (current-buffer))
19908 (message "HTML written to %s" file))
19909 ((string-match "\\.ps\\'" file)
19910 (ps-print-buffer-with-faces file)
19911 (message "Postscript written to %s" file))
19913 (let ((bs (buffer-string)))
19914 (find-file file)
19915 (insert bs)
19916 (save-buffer 0)
19917 (kill-buffer (current-buffer))
19918 (message "Plain text written to %s" file))))))
19919 (set-buffer org-agenda-buffer-name)))
19921 (defmacro org-no-read-only (&rest body)
19922 "Inhibit read-only for BODY."
19923 `(let ((inhibit-read-only t)) ,@body))
19925 (defun org-check-for-org-mode ()
19926 "Make sure current buffer is in org-mode. Error if not."
19927 (or (org-mode-p)
19928 (error "Cannot execute org-mode agenda command on buffer in %s."
19929 major-mode)))
19931 (defun org-fit-agenda-window ()
19932 "Fit the window to the buffer size."
19933 (and (memq org-agenda-window-setup '(reorganize-frame))
19934 (fboundp 'fit-window-to-buffer)
19935 (fit-window-to-buffer
19937 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
19938 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
19940 ;;; Agenda file list
19942 (defun org-agenda-files (&optional unrestricted)
19943 "Get the list of agenda files.
19944 Optional UNRESTRICTED means return the full list even if a restriction
19945 is currently in place."
19946 (let ((files
19947 (cond
19948 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
19949 ((stringp org-agenda-files) (org-read-agenda-file-list))
19950 ((listp org-agenda-files) org-agenda-files)
19951 (t (error "Invalid value of `org-agenda-files'")))))
19952 (setq files (apply 'append
19953 (mapcar (lambda (f)
19954 (if (file-directory-p f)
19955 (directory-files f t
19956 org-agenda-file-regexp)
19957 (list f)))
19958 files)))
19959 (if org-agenda-skip-unavailable-files
19960 (delq nil
19961 (mapcar (function
19962 (lambda (file)
19963 (and (file-readable-p file) file)))
19964 files))
19965 files))) ; `org-check-agenda-file' will remove them from the list
19967 (defun org-edit-agenda-file-list ()
19968 "Edit the list of agenda files.
19969 Depending on setup, this either uses customize to edit the variable
19970 `org-agenda-files', or it visits the file that is holding the list. In the
19971 latter case, the buffer is set up in a way that saving it automatically kills
19972 the buffer and restores the previous window configuration."
19973 (interactive)
19974 (if (stringp org-agenda-files)
19975 (let ((cw (current-window-configuration)))
19976 (find-file org-agenda-files)
19977 (org-set-local 'org-window-configuration cw)
19978 (org-add-hook 'after-save-hook
19979 (lambda ()
19980 (set-window-configuration
19981 (prog1 org-window-configuration
19982 (kill-buffer (current-buffer))))
19983 (org-install-agenda-files-menu)
19984 (message "New agenda file list installed"))
19985 nil 'local)
19986 (message "%s" (substitute-command-keys
19987 "Edit list and finish with \\[save-buffer]")))
19988 (customize-variable 'org-agenda-files)))
19990 (defun org-store-new-agenda-file-list (list)
19991 "Set new value for the agenda file list and save it correcly."
19992 (if (stringp org-agenda-files)
19993 (let ((f org-agenda-files) b)
19994 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
19995 (with-temp-file f
19996 (insert (mapconcat 'identity list "\n") "\n")))
19997 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
19998 (setq org-agenda-files list)
19999 (customize-save-variable 'org-agenda-files org-agenda-files))))
20001 (defun org-read-agenda-file-list ()
20002 "Read the list of agenda files from a file."
20003 (when (stringp org-agenda-files)
20004 (with-temp-buffer
20005 (insert-file-contents org-agenda-files)
20006 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20009 ;;;###autoload
20010 (defun org-cycle-agenda-files ()
20011 "Cycle through the files in `org-agenda-files'.
20012 If the current buffer visits an agenda file, find the next one in the list.
20013 If the current buffer does not, find the first agenda file."
20014 (interactive)
20015 (let* ((fs (org-agenda-files t))
20016 (files (append fs (list (car fs))))
20017 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20018 file)
20019 (unless files (error "No agenda files"))
20020 (catch 'exit
20021 (while (setq file (pop files))
20022 (if (equal (file-truename file) tcf)
20023 (when (car files)
20024 (find-file (car files))
20025 (throw 'exit t))))
20026 (find-file (car fs)))
20027 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20029 (defun org-agenda-file-to-front (&optional to-end)
20030 "Move/add the current file to the top of the agenda file list.
20031 If the file is not present in the list, it is added to the front. If it is
20032 present, it is moved there. With optional argument TO-END, add/move to the
20033 end of the list."
20034 (interactive "P")
20035 (let ((org-agenda-skip-unavailable-files nil)
20036 (file-alist (mapcar (lambda (x)
20037 (cons (file-truename x) x))
20038 (org-agenda-files t)))
20039 (ctf (file-truename buffer-file-name))
20040 x had)
20041 (setq x (assoc ctf file-alist) had x)
20043 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20044 (if to-end
20045 (setq file-alist (append (delq x file-alist) (list x)))
20046 (setq file-alist (cons x (delq x file-alist))))
20047 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20048 (org-install-agenda-files-menu)
20049 (message "File %s to %s of agenda file list"
20050 (if had "moved" "added") (if to-end "end" "front"))))
20052 (defun org-remove-file (&optional file)
20053 "Remove current file from the list of files in variable `org-agenda-files'.
20054 These are the files which are being checked for agenda entries.
20055 Optional argument FILE means, use this file instead of the current."
20056 (interactive)
20057 (let* ((org-agenda-skip-unavailable-files nil)
20058 (file (or file buffer-file-name))
20059 (true-file (file-truename file))
20060 (afile (abbreviate-file-name file))
20061 (files (delq nil (mapcar
20062 (lambda (x)
20063 (if (equal true-file
20064 (file-truename x))
20065 nil x))
20066 (org-agenda-files t)))))
20067 (if (not (= (length files) (length (org-agenda-files t))))
20068 (progn
20069 (org-store-new-agenda-file-list files)
20070 (org-install-agenda-files-menu)
20071 (message "Removed file: %s" afile))
20072 (message "File was not in list: %s (not removed)" afile))))
20074 (defun org-file-menu-entry (file)
20075 (vector file (list 'find-file file) t))
20077 (defun org-check-agenda-file (file)
20078 "Make sure FILE exists. If not, ask user what to do."
20079 (when (not (file-exists-p file))
20080 (message "non-existent file %s. [R]emove from list or [A]bort?"
20081 (abbreviate-file-name file))
20082 (let ((r (downcase (read-char-exclusive))))
20083 (cond
20084 ((equal r ?r)
20085 (org-remove-file file)
20086 (throw 'nextfile t))
20087 (t (error "Abort"))))))
20089 ;;; Agenda prepare and finalize
20091 (defvar org-agenda-multi nil) ; dynammically scoped
20092 (defvar org-agenda-buffer-name "*Org Agenda*")
20093 (defvar org-pre-agenda-window-conf nil)
20094 (defvar org-agenda-name nil)
20095 (defun org-prepare-agenda (&optional name)
20096 (setq org-todo-keywords-for-agenda nil)
20097 (setq org-done-keywords-for-agenda nil)
20098 (if org-agenda-multi
20099 (progn
20100 (setq buffer-read-only nil)
20101 (goto-char (point-max))
20102 (unless (or (bobp) org-agenda-compact-blocks)
20103 (insert "\n" (make-string (window-width) ?=) "\n"))
20104 (narrow-to-region (point) (point-max)))
20105 (org-agenda-maybe-reset-markers 'force)
20106 (org-prepare-agenda-buffers (org-agenda-files))
20107 (setq org-todo-keywords-for-agenda
20108 (org-uniquify org-todo-keywords-for-agenda))
20109 (setq org-done-keywords-for-agenda
20110 (org-uniquify org-done-keywords-for-agenda))
20111 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20112 (awin (get-buffer-window abuf)))
20113 (cond
20114 ((equal (current-buffer) abuf) nil)
20115 (awin (select-window awin))
20116 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20117 ((equal org-agenda-window-setup 'current-window)
20118 (switch-to-buffer abuf))
20119 ((equal org-agenda-window-setup 'other-window)
20120 (org-switch-to-buffer-other-window abuf))
20121 ((equal org-agenda-window-setup 'other-frame)
20122 (switch-to-buffer-other-frame abuf))
20123 ((equal org-agenda-window-setup 'reorganize-frame)
20124 (delete-other-windows)
20125 (org-switch-to-buffer-other-window abuf))))
20126 (setq buffer-read-only nil)
20127 (erase-buffer)
20128 (org-agenda-mode)
20129 (and name (not org-agenda-name)
20130 (org-set-local 'org-agenda-name name)))
20131 (setq buffer-read-only nil))
20133 (defun org-finalize-agenda ()
20134 "Finishing touch for the agenda buffer, called just before displaying it."
20135 (unless org-agenda-multi
20136 (save-excursion
20137 (let ((inhibit-read-only t))
20138 (goto-char (point-min))
20139 (while (org-activate-bracket-links (point-max))
20140 (add-text-properties (match-beginning 0) (match-end 0)
20141 '(face org-link)))
20142 (org-agenda-align-tags)
20143 (unless org-agenda-with-colors
20144 (remove-text-properties (point-min) (point-max) '(face nil))))
20145 (if (and (boundp 'org-overriding-columns-format)
20146 org-overriding-columns-format)
20147 (org-set-local 'org-overriding-columns-format
20148 org-overriding-columns-format))
20149 (if (and (boundp 'org-agenda-view-columns-initially)
20150 org-agenda-view-columns-initially)
20151 (org-agenda-columns))
20152 (when org-agenda-fontify-priorities
20153 (org-fontify-priorities))
20154 (run-hooks 'org-finalize-agenda-hook)
20155 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20158 (defun org-fontify-priorities ()
20159 "Make highest priority lines bold, and lowest italic."
20160 (interactive)
20161 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20162 (org-delete-overlay o)))
20163 (org-overlays-in (point-min) (point-max)))
20164 (save-excursion
20165 (let ((inhibit-read-only t)
20166 b e p ov h l)
20167 (goto-char (point-min))
20168 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20169 (setq h (or (get-char-property (point) 'org-highest-priority)
20170 org-highest-priority)
20171 l (or (get-char-property (point) 'org-lowest-priority)
20172 org-lowest-priority)
20173 p (string-to-char (match-string 1))
20174 b (match-beginning 0) e (point-at-eol)
20175 ov (org-make-overlay b e))
20176 (org-overlay-put
20177 ov 'face
20178 (cond ((listp org-agenda-fontify-priorities)
20179 (cdr (assoc p org-agenda-fontify-priorities)))
20180 ((equal p l) 'italic)
20181 ((equal p h) 'bold)))
20182 (org-overlay-put ov 'org-type 'org-priority)))))
20184 (defun org-prepare-agenda-buffers (files)
20185 "Create buffers for all agenda files, protect archived trees and comments."
20186 (interactive)
20187 (let ((pa '(:org-archived t))
20188 (pc '(:org-comment t))
20189 (pall '(:org-archived t :org-comment t))
20190 (inhibit-read-only t)
20191 (rea (concat ":" org-archive-tag ":"))
20192 bmp file re)
20193 (save-excursion
20194 (save-restriction
20195 (while (setq file (pop files))
20196 (if (bufferp file)
20197 (set-buffer file)
20198 (org-check-agenda-file file)
20199 (set-buffer (org-get-agenda-file-buffer file)))
20200 (widen)
20201 (setq bmp (buffer-modified-p))
20202 (org-refresh-category-properties)
20203 (setq org-todo-keywords-for-agenda
20204 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20205 (setq org-done-keywords-for-agenda
20206 (append org-done-keywords-for-agenda org-done-keywords))
20207 (save-excursion
20208 (remove-text-properties (point-min) (point-max) pall)
20209 (when org-agenda-skip-archived-trees
20210 (goto-char (point-min))
20211 (while (re-search-forward rea nil t)
20212 (if (org-on-heading-p t)
20213 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20214 (goto-char (point-min))
20215 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20216 (while (re-search-forward re nil t)
20217 (add-text-properties
20218 (match-beginning 0) (org-end-of-subtree t) pc)))
20219 (set-buffer-modified-p bmp))))))
20221 (defvar org-agenda-skip-function nil
20222 "Function to be called at each match during agenda construction.
20223 If this function returns nil, the current match should not be skipped.
20224 Otherwise, the function must return a position from where the search
20225 should be continued.
20226 This may also be a Lisp form, it will be evaluated.
20227 Never set this variable using `setq' or so, because then it will apply
20228 to all future agenda commands. Instead, bind it with `let' to scope
20229 it dynamically into the agenda-constructing command. A good way to set
20230 it is through options in org-agenda-custom-commands.")
20232 (defun org-agenda-skip ()
20233 "Throw to `:skip' in places that should be skipped.
20234 Also moves point to the end of the skipped region, so that search can
20235 continue from there."
20236 (let ((p (point-at-bol)) to fp)
20237 (and org-agenda-skip-archived-trees
20238 (get-text-property p :org-archived)
20239 (org-end-of-subtree t)
20240 (throw :skip t))
20241 (and (get-text-property p :org-comment)
20242 (org-end-of-subtree t)
20243 (throw :skip t))
20244 (if (equal (char-after p) ?#) (throw :skip t))
20245 (when (and (or (setq fp (functionp org-agenda-skip-function))
20246 (consp org-agenda-skip-function))
20247 (setq to (save-excursion
20248 (save-match-data
20249 (if fp
20250 (funcall org-agenda-skip-function)
20251 (eval org-agenda-skip-function))))))
20252 (goto-char to)
20253 (throw :skip t))))
20255 (defvar org-agenda-markers nil
20256 "List of all currently active markers created by `org-agenda'.")
20257 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20258 "Creation time of the last agenda marker.")
20260 (defun org-agenda-new-marker (&optional pos)
20261 "Return a new agenda marker.
20262 Org-mode keeps a list of these markers and resets them when they are
20263 no longer in use."
20264 (let ((m (copy-marker (or pos (point)))))
20265 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20266 (push m org-agenda-markers)
20269 (defun org-agenda-maybe-reset-markers (&optional force)
20270 "Reset markers created by `org-agenda'. But only if they are old enough."
20271 (if (or (and force (not org-agenda-multi))
20272 (> (- (time-to-seconds (current-time))
20273 org-agenda-last-marker-time)
20275 (while org-agenda-markers
20276 (move-marker (pop org-agenda-markers) nil))))
20278 (defun org-get-agenda-file-buffer (file)
20279 "Get a buffer visiting FILE. If the buffer needs to be created, add
20280 it to the list of buffers which might be released later."
20281 (let ((buf (org-find-base-buffer-visiting file)))
20282 (if buf
20283 buf ; just return it
20284 ;; Make a new buffer and remember it
20285 (setq buf (find-file-noselect file))
20286 (if buf (push buf org-agenda-new-buffers))
20287 buf)))
20289 (defun org-release-buffers (blist)
20290 "Release all buffers in list, asking the user for confirmation when needed.
20291 When a buffer is unmodified, it is just killed. When modified, it is saved
20292 \(if the user agrees) and then killed."
20293 (let (buf file)
20294 (while (setq buf (pop blist))
20295 (setq file (buffer-file-name buf))
20296 (when (and (buffer-modified-p buf)
20297 file
20298 (y-or-n-p (format "Save file %s? " file)))
20299 (with-current-buffer buf (save-buffer)))
20300 (kill-buffer buf))))
20302 (defun org-get-category (&optional pos)
20303 "Get the category applying to position POS."
20304 (get-text-property (or pos (point)) 'org-category))
20306 ;;; Agenda timeline
20308 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20310 (defun org-timeline (&optional include-all)
20311 "Show a time-sorted view of the entries in the current org file.
20312 Only entries with a time stamp of today or later will be listed. With
20313 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20314 under the current date.
20315 If the buffer contains an active region, only check the region for
20316 dates."
20317 (interactive "P")
20318 (require 'calendar)
20319 (org-compile-prefix-format 'timeline)
20320 (org-set-sorting-strategy 'timeline)
20321 (let* ((dopast t)
20322 (dotodo include-all)
20323 (doclosed org-agenda-show-log)
20324 (entry buffer-file-name)
20325 (date (calendar-current-date))
20326 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20327 (end (if (org-region-active-p) (region-end) (point-max)))
20328 (day-numbers (org-get-all-dates beg end 'no-ranges
20329 t doclosed ; always include today
20330 org-timeline-show-empty-dates))
20331 (org-deadline-warning-days 0)
20332 (org-agenda-only-exact-dates t)
20333 (today (time-to-days (current-time)))
20334 (past t)
20335 args
20336 s e rtn d emptyp)
20337 (setq org-agenda-redo-command
20338 (list 'progn
20339 (list 'org-switch-to-buffer-other-window (current-buffer))
20340 (list 'org-timeline (list 'quote include-all))))
20341 (if (not dopast)
20342 ;; Remove past dates from the list of dates.
20343 (setq day-numbers (delq nil (mapcar (lambda(x)
20344 (if (>= x today) x nil))
20345 day-numbers))))
20346 (org-prepare-agenda (concat "Timeline "
20347 (file-name-nondirectory buffer-file-name)))
20348 (if doclosed (push :closed args))
20349 (push :timestamp args)
20350 (push :deadline args)
20351 (push :scheduled args)
20352 (push :sexp args)
20353 (if dotodo (push :todo args))
20354 (while (setq d (pop day-numbers))
20355 (if (and (listp d) (eq (car d) :omitted))
20356 (progn
20357 (setq s (point))
20358 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20359 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20360 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20361 (if (and (>= d today)
20362 dopast
20363 past)
20364 (progn
20365 (setq past nil)
20366 (insert (make-string 79 ?-) "\n")))
20367 (setq date (calendar-gregorian-from-absolute d))
20368 (setq s (point))
20369 (setq rtn (and (not emptyp)
20370 (apply 'org-agenda-get-day-entries entry
20371 date args)))
20372 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20373 (progn
20374 (insert
20375 (if (stringp org-agenda-format-date)
20376 (format-time-string org-agenda-format-date
20377 (org-time-from-absolute date))
20378 (funcall org-agenda-format-date date))
20379 "\n")
20380 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20381 (put-text-property s (1- (point)) 'org-date-line t)
20382 (if (equal d today)
20383 (put-text-property s (1- (point)) 'org-today t))
20384 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20385 (put-text-property s (1- (point)) 'day d)))))
20386 (goto-char (point-min))
20387 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20388 (point-min)))
20389 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20390 (org-finalize-agenda)
20391 (setq buffer-read-only t)))
20393 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20394 "Return a list of all relevant day numbers from BEG to END buffer positions.
20395 If NO-RANGES is non-nil, include only the start and end dates of a range,
20396 not every single day in the range. If FORCE-TODAY is non-nil, make
20397 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20398 inactive time stamps (those in square brackets) are included.
20399 When EMPTY is non-nil, also include days without any entries."
20400 (let ((re (concat
20401 (if pre-re pre-re "")
20402 (if inactive org-ts-regexp-both org-ts-regexp)))
20403 dates dates1 date day day1 day2 ts1 ts2)
20404 (if force-today
20405 (setq dates (list (time-to-days (current-time)))))
20406 (save-excursion
20407 (goto-char beg)
20408 (while (re-search-forward re end t)
20409 (setq day (time-to-days (org-time-string-to-time
20410 (substring (match-string 1) 0 10))))
20411 (or (memq day dates) (push day dates)))
20412 (unless no-ranges
20413 (goto-char beg)
20414 (while (re-search-forward org-tr-regexp end t)
20415 (setq ts1 (substring (match-string 1) 0 10)
20416 ts2 (substring (match-string 2) 0 10)
20417 day1 (time-to-days (org-time-string-to-time ts1))
20418 day2 (time-to-days (org-time-string-to-time ts2)))
20419 (while (< (setq day1 (1+ day1)) day2)
20420 (or (memq day1 dates) (push day1 dates)))))
20421 (setq dates (sort dates '<))
20422 (when empty
20423 (while (setq day (pop dates))
20424 (setq day2 (car dates))
20425 (push day dates1)
20426 (when (and day2 empty)
20427 (if (or (eq empty t)
20428 (and (numberp empty) (<= (- day2 day) empty)))
20429 (while (< (setq day (1+ day)) day2)
20430 (push (list day) dates1))
20431 (push (cons :omitted (- day2 day)) dates1))))
20432 (setq dates (nreverse dates1)))
20433 dates)))
20435 ;;; Agenda Daily/Weekly
20437 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20438 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20439 (defvar org-agenda-last-arguments nil
20440 "The arguments of the previous call to org-agenda")
20441 (defvar org-starting-day nil) ; local variable in the agenda buffer
20442 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20443 (defvar org-include-all-loc nil) ; local variable
20444 (defvar org-agenda-remove-date nil) ; dynamically scoped
20446 ;;;###autoload
20447 (defun org-agenda-list (&optional include-all start-day ndays)
20448 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20449 The view will be for the current day or week, but from the overview buffer
20450 you will be able to go to other days/weeks.
20452 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20453 all unfinished TODO items will also be shown, before the agenda.
20454 This feature is considered obsolete, please use the TODO list or a block
20455 agenda instead.
20457 With a numeric prefix argument in an interactive call, the agenda will
20458 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20459 the number of days. NDAYS defaults to `org-agenda-ndays'.
20461 START-DAY defaults to TODAY, or to the most recent match for the weekday
20462 given in `org-agenda-start-on-weekday'."
20463 (interactive "P")
20464 (if (and (integerp include-all) (> include-all 0))
20465 (setq ndays include-all include-all nil))
20466 (setq ndays (or ndays org-agenda-ndays)
20467 start-day (or start-day org-agenda-start-day))
20468 (if org-agenda-overriding-arguments
20469 (setq include-all (car org-agenda-overriding-arguments)
20470 start-day (nth 1 org-agenda-overriding-arguments)
20471 ndays (nth 2 org-agenda-overriding-arguments)))
20472 (if (stringp start-day)
20473 ;; Convert to an absolute day number
20474 (setq start-day (time-to-days (org-read-date nil t start-day))))
20475 (setq org-agenda-last-arguments (list include-all start-day ndays))
20476 (org-compile-prefix-format 'agenda)
20477 (org-set-sorting-strategy 'agenda)
20478 (require 'calendar)
20479 (let* ((org-agenda-start-on-weekday
20480 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20481 org-agenda-start-on-weekday nil))
20482 (thefiles (org-agenda-files))
20483 (files thefiles)
20484 (today (time-to-days
20485 (time-subtract (current-time)
20486 (list 0 (* 3600 org-extend-today-until) 0))))
20487 (sd (or start-day today))
20488 (start (if (or (null org-agenda-start-on-weekday)
20489 (< org-agenda-ndays 7))
20491 (let* ((nt (calendar-day-of-week
20492 (calendar-gregorian-from-absolute sd)))
20493 (n1 org-agenda-start-on-weekday)
20494 (d (- nt n1)))
20495 (- sd (+ (if (< d 0) 7 0) d)))))
20496 (day-numbers (list start))
20497 (day-cnt 0)
20498 (inhibit-redisplay (not debug-on-error))
20499 s e rtn rtnall file date d start-pos end-pos todayp nd)
20500 (setq org-agenda-redo-command
20501 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20502 ;; Make the list of days
20503 (setq ndays (or ndays org-agenda-ndays)
20504 nd ndays)
20505 (while (> ndays 1)
20506 (push (1+ (car day-numbers)) day-numbers)
20507 (setq ndays (1- ndays)))
20508 (setq day-numbers (nreverse day-numbers))
20509 (org-prepare-agenda "Day/Week")
20510 (org-set-local 'org-starting-day (car day-numbers))
20511 (org-set-local 'org-include-all-loc include-all)
20512 (org-set-local 'org-agenda-span
20513 (org-agenda-ndays-to-span nd))
20514 (when (and (or include-all org-agenda-include-all-todo)
20515 (member today day-numbers))
20516 (setq files thefiles
20517 rtnall nil)
20518 (while (setq file (pop files))
20519 (catch 'nextfile
20520 (org-check-agenda-file file)
20521 (setq date (calendar-gregorian-from-absolute today)
20522 rtn (org-agenda-get-day-entries
20523 file date :todo))
20524 (setq rtnall (append rtnall rtn))))
20525 (when rtnall
20526 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20527 (add-text-properties (point-min) (1- (point))
20528 (list 'face 'org-agenda-structure))
20529 (insert (org-finalize-agenda-entries rtnall) "\n")))
20530 (unless org-agenda-compact-blocks
20531 (setq s (point))
20532 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20533 "-agenda:\n")
20534 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20535 'org-date-line t)))
20536 (while (setq d (pop day-numbers))
20537 (setq date (calendar-gregorian-from-absolute d)
20538 s (point))
20539 (if (or (setq todayp (= d today))
20540 (and (not start-pos) (= d sd)))
20541 (setq start-pos (point))
20542 (if (and start-pos (not end-pos))
20543 (setq end-pos (point))))
20544 (setq files thefiles
20545 rtnall nil)
20546 (while (setq file (pop files))
20547 (catch 'nextfile
20548 (org-check-agenda-file file)
20549 (if org-agenda-show-log
20550 (setq rtn (org-agenda-get-day-entries
20551 file date
20552 :deadline :scheduled :timestamp :sexp :closed))
20553 (setq rtn (org-agenda-get-day-entries
20554 file date
20555 :deadline :scheduled :sexp :timestamp)))
20556 (setq rtnall (append rtnall rtn))))
20557 (if org-agenda-include-diary
20558 (progn
20559 (require 'diary-lib)
20560 (setq rtn (org-get-entries-from-diary date))
20561 (setq rtnall (append rtnall rtn))))
20562 (if (or rtnall org-agenda-show-all-dates)
20563 (progn
20564 (setq day-cnt (1+ day-cnt))
20565 (insert
20566 (if (stringp org-agenda-format-date)
20567 (format-time-string org-agenda-format-date
20568 (org-time-from-absolute date))
20569 (funcall org-agenda-format-date date))
20570 "\n")
20571 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20572 (put-text-property s (1- (point)) 'org-date-line t)
20573 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20574 (if todayp (put-text-property s (1- (point)) 'org-today t))
20575 (if rtnall (insert
20576 (org-finalize-agenda-entries
20577 (org-agenda-add-time-grid-maybe
20578 rtnall nd todayp))
20579 "\n"))
20580 (put-text-property s (1- (point)) 'day d)
20581 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20582 (goto-char (point-min))
20583 (org-fit-agenda-window)
20584 (unless (and (pos-visible-in-window-p (point-min))
20585 (pos-visible-in-window-p (point-max)))
20586 (goto-char (1- (point-max)))
20587 (recenter -1)
20588 (if (not (pos-visible-in-window-p (or start-pos 1)))
20589 (progn
20590 (goto-char (or start-pos 1))
20591 (recenter 1))))
20592 (goto-char (or start-pos 1))
20593 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20594 (org-finalize-agenda)
20595 (setq buffer-read-only t)
20596 (message "")))
20598 (defun org-agenda-ndays-to-span (n)
20599 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20601 ;;; Agenda TODO list
20603 (defvar org-select-this-todo-keyword nil)
20604 (defvar org-last-arg nil)
20606 ;;;###autoload
20607 (defun org-todo-list (arg)
20608 "Show all TODO entries from all agenda file in a single list.
20609 The prefix arg can be used to select a specific TODO keyword and limit
20610 the list to these. When using \\[universal-argument], you will be prompted
20611 for a keyword. A numeric prefix directly selects the Nth keyword in
20612 `org-todo-keywords-1'."
20613 (interactive "P")
20614 (require 'calendar)
20615 (org-compile-prefix-format 'todo)
20616 (org-set-sorting-strategy 'todo)
20617 (org-prepare-agenda "TODO")
20618 (let* ((today (time-to-days (current-time)))
20619 (date (calendar-gregorian-from-absolute today))
20620 (kwds org-todo-keywords-for-agenda)
20621 (completion-ignore-case t)
20622 (org-select-this-todo-keyword
20623 (if (stringp arg) arg
20624 (and arg (integerp arg) (> arg 0)
20625 (nth (1- arg) kwds))))
20626 rtn rtnall files file pos)
20627 (when (equal arg '(4))
20628 (setq org-select-this-todo-keyword
20629 (completing-read "Keyword (or KWD1|K2D2|...): "
20630 (mapcar 'list kwds) nil nil)))
20631 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20632 (org-set-local 'org-last-arg arg)
20633 (setq org-agenda-redo-command
20634 '(org-todo-list (or current-prefix-arg org-last-arg)))
20635 (setq files (org-agenda-files)
20636 rtnall nil)
20637 (while (setq file (pop files))
20638 (catch 'nextfile
20639 (org-check-agenda-file file)
20640 (setq rtn (org-agenda-get-day-entries file date :todo))
20641 (setq rtnall (append rtnall rtn))))
20642 (if org-agenda-overriding-header
20643 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20644 nil 'face 'org-agenda-structure) "\n")
20645 (insert "Global list of TODO items of type: ")
20646 (add-text-properties (point-min) (1- (point))
20647 (list 'face 'org-agenda-structure))
20648 (setq pos (point))
20649 (insert (or org-select-this-todo-keyword "ALL") "\n")
20650 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20651 (setq pos (point))
20652 (unless org-agenda-multi
20653 (insert "Available with `N r': (0)ALL")
20654 (let ((n 0) s)
20655 (mapc (lambda (x)
20656 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20657 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20658 (insert "\n "))
20659 (insert " " s))
20660 kwds))
20661 (insert "\n"))
20662 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20663 (when rtnall
20664 (insert (org-finalize-agenda-entries rtnall) "\n"))
20665 (goto-char (point-min))
20666 (org-fit-agenda-window)
20667 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20668 (org-finalize-agenda)
20669 (setq buffer-read-only t)))
20671 ;;; Agenda tags match
20673 ;;;###autoload
20674 (defun org-tags-view (&optional todo-only match)
20675 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20676 The prefix arg TODO-ONLY limits the search to TODO entries."
20677 (interactive "P")
20678 (org-compile-prefix-format 'tags)
20679 (org-set-sorting-strategy 'tags)
20680 (let* ((org-tags-match-list-sublevels
20681 (if todo-only t org-tags-match-list-sublevels))
20682 (completion-ignore-case t)
20683 rtn rtnall files file pos matcher
20684 buffer)
20685 (setq matcher (org-make-tags-matcher match)
20686 match (car matcher) matcher (cdr matcher))
20687 (org-prepare-agenda (concat "TAGS " match))
20688 (setq org-agenda-redo-command
20689 (list 'org-tags-view (list 'quote todo-only)
20690 (list 'if 'current-prefix-arg nil match)))
20691 (setq files (org-agenda-files)
20692 rtnall nil)
20693 (while (setq file (pop files))
20694 (catch 'nextfile
20695 (org-check-agenda-file file)
20696 (setq buffer (if (file-exists-p file)
20697 (org-get-agenda-file-buffer file)
20698 (error "No such file %s" file)))
20699 (if (not buffer)
20700 ;; If file does not exist, merror message to agenda
20701 (setq rtn (list
20702 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20703 rtnall (append rtnall rtn))
20704 (with-current-buffer buffer
20705 (unless (org-mode-p)
20706 (error "Agenda file %s is not in `org-mode'" file))
20707 (save-excursion
20708 (save-restriction
20709 (if org-agenda-restrict
20710 (narrow-to-region org-agenda-restrict-begin
20711 org-agenda-restrict-end)
20712 (widen))
20713 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20714 (setq rtnall (append rtnall rtn))))))))
20715 (if org-agenda-overriding-header
20716 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20717 nil 'face 'org-agenda-structure) "\n")
20718 (insert "Headlines with TAGS match: ")
20719 (add-text-properties (point-min) (1- (point))
20720 (list 'face 'org-agenda-structure))
20721 (setq pos (point))
20722 (insert match "\n")
20723 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20724 (setq pos (point))
20725 (unless org-agenda-multi
20726 (insert "Press `C-u r' to search again with new search string\n"))
20727 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20728 (when rtnall
20729 (insert (org-finalize-agenda-entries rtnall) "\n"))
20730 (goto-char (point-min))
20731 (org-fit-agenda-window)
20732 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20733 (org-finalize-agenda)
20734 (setq buffer-read-only t)))
20736 ;;; Agenda Finding stuck projects
20738 (defvar org-agenda-skip-regexp nil
20739 "Regular expression used in skipping subtrees for the agenda.
20740 This is basically a temporary global variable that can be set and then
20741 used by user-defined selections using `org-agenda-skip-function'.")
20743 (defvar org-agenda-overriding-header nil
20744 "When this is set during todo and tags searches, will replace header.")
20746 (defun org-agenda-skip-subtree-when-regexp-matches ()
20747 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20748 If yes, it returns the end position of this tree, causing agenda commands
20749 to skip this subtree. This is a function that can be put into
20750 `org-agenda-skip-function' for the duration of a command."
20751 (let ((end (save-excursion (org-end-of-subtree t)))
20752 skip)
20753 (save-excursion
20754 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20755 (and skip end)))
20757 (defun org-agenda-skip-entry-if (&rest conditions)
20758 "Skip entry if any of CONDITIONS is true.
20759 See `org-agenda-skip-if' for details."
20760 (org-agenda-skip-if nil conditions))
20762 (defun org-agenda-skip-subtree-if (&rest conditions)
20763 "Skip entry if any of CONDITIONS is true.
20764 See `org-agenda-skip-if' for details."
20765 (org-agenda-skip-if t conditions))
20767 (defun org-agenda-skip-if (subtree conditions)
20768 "Checks current entity for CONDITIONS.
20769 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20770 the entry, i.e. the text before the next heading is checked.
20772 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20773 from different tests. Valid conditions are:
20775 scheduled Check if there is a scheduled cookie
20776 notscheduled Check if there is no scheduled cookie
20777 deadline Check if there is a deadline
20778 notdeadline Check if there is no deadline
20779 regexp Check if regexp matches
20780 notregexp Check if regexp does not match.
20782 The regexp is taken from the conditions list, it must come right after
20783 the `regexp' or `notregexp' element.
20785 If any of these conditions is met, this function returns the end point of
20786 the entity, causing the search to continue from there. This is a function
20787 that can be put into `org-agenda-skip-function' for the duration of a command."
20788 (let (beg end m)
20789 (org-back-to-heading t)
20790 (setq beg (point)
20791 end (if subtree
20792 (progn (org-end-of-subtree t) (point))
20793 (progn (outline-next-heading) (1- (point)))))
20794 (goto-char beg)
20795 (and
20797 (and (memq 'scheduled conditions)
20798 (re-search-forward org-scheduled-time-regexp end t))
20799 (and (memq 'notscheduled conditions)
20800 (not (re-search-forward org-scheduled-time-regexp end t)))
20801 (and (memq 'deadline conditions)
20802 (re-search-forward org-deadline-time-regexp end t))
20803 (and (memq 'notdeadline conditions)
20804 (not (re-search-forward org-deadline-time-regexp end t)))
20805 (and (setq m (memq 'regexp conditions))
20806 (stringp (nth 1 m))
20807 (re-search-forward (nth 1 m) end t))
20808 (and (setq m (memq 'notregexp conditions))
20809 (stringp (nth 1 m))
20810 (not (re-search-forward (nth 1 m) end t))))
20811 end)))
20813 ;;;###autoload
20814 (defun org-agenda-list-stuck-projects (&rest ignore)
20815 "Create agenda view for projects that are stuck.
20816 Stuck projects are project that have no next actions. For the definitions
20817 of what a project is and how to check if it stuck, customize the variable
20818 `org-stuck-projects'.
20819 MATCH is being ignored."
20820 (interactive)
20821 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20822 ;; FIXME: we could have used org-agenda-skip-if here.
20823 (org-agenda-overriding-header "List of stuck projects: ")
20824 (matcher (nth 0 org-stuck-projects))
20825 (todo (nth 1 org-stuck-projects))
20826 (todo-wds (if (member "*" todo)
20827 (progn
20828 (org-prepare-agenda-buffers (org-agenda-files))
20829 (org-delete-all
20830 org-done-keywords-for-agenda
20831 (copy-sequence org-todo-keywords-for-agenda)))
20832 todo))
20833 (todo-re (concat "^\\*+[ \t]+\\("
20834 (mapconcat 'identity todo-wds "\\|")
20835 "\\)\\>"))
20836 (tags (nth 2 org-stuck-projects))
20837 (tags-re (if (member "*" tags)
20838 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20839 (concat "^\\*+ .*:\\("
20840 (mapconcat 'identity tags "\\|")
20841 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20842 (gen-re (nth 3 org-stuck-projects))
20843 (re-list
20844 (delq nil
20845 (list
20846 (if todo todo-re)
20847 (if tags tags-re)
20848 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20849 gen-re)))))
20850 (setq org-agenda-skip-regexp
20851 (if re-list
20852 (mapconcat 'identity re-list "\\|")
20853 (error "No information how to identify unstuck projects")))
20854 (org-tags-view nil matcher)
20855 (with-current-buffer org-agenda-buffer-name
20856 (setq org-agenda-redo-command
20857 '(org-agenda-list-stuck-projects
20858 (or current-prefix-arg org-last-arg))))))
20860 ;;; Diary integration
20862 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20864 (defun org-get-entries-from-diary (date)
20865 "Get the (Emacs Calendar) diary entries for DATE."
20866 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20867 (diary-display-hook '(fancy-diary-display))
20868 (pop-up-frames nil)
20869 (list-diary-entries-hook
20870 (cons 'org-diary-default-entry list-diary-entries-hook))
20871 (diary-file-name-prefix-function nil) ; turn this feature off
20872 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20873 entries
20874 (org-disable-agenda-to-diary t))
20875 (save-excursion
20876 (save-window-excursion
20877 (funcall (if (fboundp 'diary-list-entries)
20878 'diary-list-entries 'list-diary-entries)
20879 date 1)))
20880 (if (not (get-buffer fancy-diary-buffer))
20881 (setq entries nil)
20882 (with-current-buffer fancy-diary-buffer
20883 (setq buffer-read-only nil)
20884 (if (zerop (buffer-size))
20885 ;; No entries
20886 (setq entries nil)
20887 ;; Omit the date and other unnecessary stuff
20888 (org-agenda-cleanup-fancy-diary)
20889 ;; Add prefix to each line and extend the text properties
20890 (if (zerop (buffer-size))
20891 (setq entries nil)
20892 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20893 (set-buffer-modified-p nil)
20894 (kill-buffer fancy-diary-buffer)))
20895 (when entries
20896 (setq entries (org-split-string entries "\n"))
20897 (setq entries
20898 (mapcar
20899 (lambda (x)
20900 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20901 ;; Extend the text properties to the beginning of the line
20902 (org-add-props x (text-properties-at (1- (length x)) x)
20903 'type "diary" 'date date))
20904 entries)))))
20906 (defun org-agenda-cleanup-fancy-diary ()
20907 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20908 This gets rid of the date, the underline under the date, and
20909 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20910 date. It also removes lines that contain only whitespace."
20911 (goto-char (point-min))
20912 (if (looking-at ".*?:[ \t]*")
20913 (progn
20914 (replace-match "")
20915 (re-search-forward "\n=+$" nil t)
20916 (replace-match "")
20917 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20918 (re-search-forward "\n=+$" nil t)
20919 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20920 (goto-char (point-min))
20921 (while (re-search-forward "^ +\n" nil t)
20922 (replace-match ""))
20923 (goto-char (point-min))
20924 (if (re-search-forward "^Org-mode dummy\n?" nil t)
20925 (replace-match "")))
20927 ;; Make sure entries from the diary have the right text properties.
20928 (eval-after-load "diary-lib"
20929 '(if (boundp 'diary-modify-entry-list-string-function)
20930 ;; We can rely on the hook, nothing to do
20932 ;; Hook not avaiable, must use advice to make this work
20933 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
20934 "Make the position visible."
20935 (if (and org-disable-agenda-to-diary ;; called from org-agenda
20936 (stringp string)
20937 buffer-file-name)
20938 (setq string (org-modify-diary-entry-string string))))))
20940 (defun org-modify-diary-entry-string (string)
20941 "Add text properties to string, allowing org-mode to act on it."
20942 (org-add-props string nil
20943 'mouse-face 'highlight
20944 'keymap org-agenda-keymap
20945 'help-echo (if buffer-file-name
20946 (format "mouse-2 or RET jump to diary file %s"
20947 (abbreviate-file-name buffer-file-name))
20949 'org-agenda-diary-link t
20950 'org-marker (org-agenda-new-marker (point-at-bol))))
20952 (defun org-diary-default-entry ()
20953 "Add a dummy entry to the diary.
20954 Needed to avoid empty dates which mess up holiday display."
20955 ;; Catch the error if dealing with the new add-to-diary-alist
20956 (when org-disable-agenda-to-diary
20957 (condition-case nil
20958 (add-to-diary-list original-date "Org-mode dummy" "")
20959 (error
20960 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
20962 ;;;###autoload
20963 (defun org-diary (&rest args)
20964 "Return diary information from org-files.
20965 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
20966 It accesses org files and extracts information from those files to be
20967 listed in the diary. The function accepts arguments specifying what
20968 items should be listed. The following arguments are allowed:
20970 :timestamp List the headlines of items containing a date stamp or
20971 date range matching the selected date. Deadlines will
20972 also be listed, on the expiration day.
20974 :sexp List entries resulting from diary-like sexps.
20976 :deadline List any deadlines past due, or due within
20977 `org-deadline-warning-days'. The listing occurs only
20978 in the diary for *today*, not at any other date. If
20979 an entry is marked DONE, it is no longer listed.
20981 :scheduled List all items which are scheduled for the given date.
20982 The diary for *today* also contains items which were
20983 scheduled earlier and are not yet marked DONE.
20985 :todo List all TODO items from the org-file. This may be a
20986 long list - so this is not turned on by default.
20987 Like deadlines, these entries only show up in the
20988 diary for *today*, not at any other date.
20990 The call in the diary file should look like this:
20992 &%%(org-diary) ~/path/to/some/orgfile.org
20994 Use a separate line for each org file to check. Or, if you omit the file name,
20995 all files listed in `org-agenda-files' will be checked automatically:
20997 &%%(org-diary)
20999 If you don't give any arguments (as in the example above), the default
21000 arguments (:deadline :scheduled :timestamp :sexp) are used.
21001 So the example above may also be written as
21003 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21005 The function expects the lisp variables `entry' and `date' to be provided
21006 by the caller, because this is how the calendar works. Don't use this
21007 function from a program - use `org-agenda-get-day-entries' instead."
21008 (org-agenda-maybe-reset-markers)
21009 (org-compile-prefix-format 'agenda)
21010 (org-set-sorting-strategy 'agenda)
21011 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21012 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21013 (list entry)
21014 (org-agenda-files t)))
21015 file rtn results)
21016 (org-prepare-agenda-buffers files)
21017 ;; If this is called during org-agenda, don't return any entries to
21018 ;; the calendar. Org Agenda will list these entries itself.
21019 (if org-disable-agenda-to-diary (setq files nil))
21020 (while (setq file (pop files))
21021 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21022 (setq results (append results rtn)))
21023 (if results
21024 (concat (org-finalize-agenda-entries results) "\n"))))
21026 ;;; Agenda entry finders
21028 (defun org-agenda-get-day-entries (file date &rest args)
21029 "Does the work for `org-diary' and `org-agenda'.
21030 FILE is the path to a file to be checked for entries. DATE is date like
21031 the one returned by `calendar-current-date'. ARGS are symbols indicating
21032 which kind of entries should be extracted. For details about these, see
21033 the documentation of `org-diary'."
21034 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21035 (let* ((org-startup-folded nil)
21036 (org-startup-align-all-tables nil)
21037 (buffer (if (file-exists-p file)
21038 (org-get-agenda-file-buffer file)
21039 (error "No such file %s" file)))
21040 arg results rtn)
21041 (if (not buffer)
21042 ;; If file does not exist, make sure an error message ends up in diary
21043 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21044 (with-current-buffer buffer
21045 (unless (org-mode-p)
21046 (error "Agenda file %s is not in `org-mode'" file))
21047 (let ((case-fold-search nil))
21048 (save-excursion
21049 (save-restriction
21050 (if org-agenda-restrict
21051 (narrow-to-region org-agenda-restrict-begin
21052 org-agenda-restrict-end)
21053 (widen))
21054 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21055 (while (setq arg (pop args))
21056 (cond
21057 ((and (eq arg :todo)
21058 (equal date (calendar-current-date)))
21059 (setq rtn (org-agenda-get-todos))
21060 (setq results (append results rtn)))
21061 ((eq arg :timestamp)
21062 (setq rtn (org-agenda-get-blocks))
21063 (setq results (append results rtn))
21064 (setq rtn (org-agenda-get-timestamps))
21065 (setq results (append results rtn)))
21066 ((eq arg :sexp)
21067 (setq rtn (org-agenda-get-sexps))
21068 (setq results (append results rtn)))
21069 ((eq arg :scheduled)
21070 (setq rtn (org-agenda-get-scheduled))
21071 (setq results (append results rtn)))
21072 ((eq arg :closed)
21073 (setq rtn (org-agenda-get-closed))
21074 (setq results (append results rtn)))
21075 ((eq arg :deadline)
21076 (setq rtn (org-agenda-get-deadlines))
21077 (setq results (append results rtn))))))))
21078 results))))
21080 (defun org-entry-is-todo-p ()
21081 (member (org-get-todo-state) org-not-done-keywords))
21083 (defun org-entry-is-done-p ()
21084 (member (org-get-todo-state) org-done-keywords))
21086 (defun org-get-todo-state ()
21087 (save-excursion
21088 (org-back-to-heading t)
21089 (and (looking-at org-todo-line-regexp)
21090 (match-end 2)
21091 (match-string 2))))
21093 (defun org-at-date-range-p (&optional inactive-ok)
21094 "Is the cursor inside a date range?"
21095 (interactive)
21096 (save-excursion
21097 (catch 'exit
21098 (let ((pos (point)))
21099 (skip-chars-backward "^[<\r\n")
21100 (skip-chars-backward "<[")
21101 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21102 (>= (match-end 0) pos)
21103 (throw 'exit t))
21104 (skip-chars-backward "^<[\r\n")
21105 (skip-chars-backward "<[")
21106 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21107 (>= (match-end 0) pos)
21108 (throw 'exit t)))
21109 nil)))
21111 (defun org-agenda-get-todos ()
21112 "Return the TODO information for agenda display."
21113 (let* ((props (list 'face nil
21114 'done-face 'org-done
21115 'org-not-done-regexp org-not-done-regexp
21116 'org-todo-regexp org-todo-regexp
21117 'mouse-face 'highlight
21118 'keymap org-agenda-keymap
21119 'help-echo
21120 (format "mouse-2 or RET jump to org file %s"
21121 (abbreviate-file-name buffer-file-name))))
21122 ;; FIXME: get rid of the \n at some point but watch out
21123 (regexp (concat "^\\*+[ \t]+\\("
21124 (if org-select-this-todo-keyword
21125 (if (equal org-select-this-todo-keyword "*")
21126 org-todo-regexp
21127 (concat "\\<\\("
21128 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21129 "\\)\\>"))
21130 org-not-done-regexp)
21131 "[^\n\r]*\\)"))
21132 marker priority category tags
21133 ee txt beg end)
21134 (goto-char (point-min))
21135 (while (re-search-forward regexp nil t)
21136 (catch :skip
21137 (save-match-data
21138 (beginning-of-line)
21139 (setq beg (point) end (progn (outline-next-heading) (point)))
21140 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21141 (re-search-forward org-ts-regexp end t))
21142 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21143 (re-search-forward org-scheduled-time-regexp end t))
21144 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21145 (re-search-forward org-deadline-time-regexp end t)
21146 (org-deadline-close (match-string 1))))
21147 (goto-char (1+ beg))
21148 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21149 (throw :skip nil)))
21150 (goto-char beg)
21151 (org-agenda-skip)
21152 (goto-char (match-beginning 1))
21153 (setq marker (org-agenda-new-marker (match-beginning 0))
21154 category (org-get-category)
21155 tags (org-get-tags-at (point))
21156 txt (org-format-agenda-item "" (match-string 1) category tags)
21157 priority (1+ (org-get-priority txt)))
21158 (org-add-props txt props
21159 'org-marker marker 'org-hd-marker marker
21160 'priority priority 'org-category category
21161 'type "todo")
21162 (push txt ee)
21163 (if org-agenda-todo-list-sublevels
21164 (goto-char (match-end 1))
21165 (org-end-of-subtree 'invisible))))
21166 (nreverse ee)))
21168 (defconst org-agenda-no-heading-message
21169 "No heading for this item in buffer or region.")
21171 (defun org-agenda-get-timestamps ()
21172 "Return the date stamp information for agenda display."
21173 (let* ((props (list 'face nil
21174 'org-not-done-regexp org-not-done-regexp
21175 'org-todo-regexp org-todo-regexp
21176 'mouse-face 'highlight
21177 'keymap org-agenda-keymap
21178 'help-echo
21179 (format "mouse-2 or RET jump to org file %s"
21180 (abbreviate-file-name buffer-file-name))))
21181 (d1 (calendar-absolute-from-gregorian date))
21182 (remove-re
21183 (concat
21184 (regexp-quote
21185 (format-time-string
21186 "<%Y-%m-%d"
21187 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21188 ".*?>"))
21189 (regexp
21190 (concat
21191 (regexp-quote
21192 (substring
21193 (format-time-string
21194 (car org-time-stamp-formats)
21195 (apply 'encode-time ; DATE bound by calendar
21196 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21197 0 11))
21198 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21199 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21200 marker hdmarker deadlinep scheduledp donep tmp priority category
21201 ee txt timestr tags b0 b3 e3 head)
21202 (goto-char (point-min))
21203 (while (re-search-forward regexp nil t)
21204 (setq b0 (match-beginning 0)
21205 b3 (match-beginning 3) e3 (match-end 3))
21206 (catch :skip
21207 (and (org-at-date-range-p) (throw :skip nil))
21208 (org-agenda-skip)
21209 (if (and (match-end 1)
21210 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21211 (throw :skip nil))
21212 (if (and e3
21213 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21214 (throw :skip nil))
21215 (setq marker (org-agenda-new-marker b0)
21216 category (org-get-category b0)
21217 tmp (buffer-substring (max (point-min)
21218 (- b0 org-ds-keyword-length))
21220 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21221 deadlinep (string-match org-deadline-regexp tmp)
21222 scheduledp (string-match org-scheduled-regexp tmp)
21223 donep (org-entry-is-done-p))
21224 (if (or scheduledp deadlinep) (throw :skip t))
21225 (if (string-match ">" timestr)
21226 ;; substring should only run to end of time stamp
21227 (setq timestr (substring timestr 0 (match-end 0))))
21228 (save-excursion
21229 (if (re-search-backward "^\\*+ " nil t)
21230 (progn
21231 (goto-char (match-beginning 0))
21232 (setq hdmarker (org-agenda-new-marker)
21233 tags (org-get-tags-at))
21234 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21235 (setq head (match-string 1))
21236 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21237 (setq txt (org-format-agenda-item
21238 nil head category tags timestr nil
21239 remove-re)))
21240 (setq txt org-agenda-no-heading-message))
21241 (setq priority (org-get-priority txt))
21242 (org-add-props txt props
21243 'org-marker marker 'org-hd-marker hdmarker)
21244 (org-add-props txt nil 'priority priority
21245 'org-category category 'date date
21246 'type "timestamp")
21247 (push txt ee))
21248 (outline-next-heading)))
21249 (nreverse ee)))
21251 (defun org-agenda-get-sexps ()
21252 "Return the sexp information for agenda display."
21253 (require 'diary-lib)
21254 (let* ((props (list 'face nil
21255 'mouse-face 'highlight
21256 'keymap org-agenda-keymap
21257 'help-echo
21258 (format "mouse-2 or RET jump to org file %s"
21259 (abbreviate-file-name buffer-file-name))))
21260 (regexp "^&?%%(")
21261 marker category ee txt tags entry result beg b sexp sexp-entry)
21262 (goto-char (point-min))
21263 (while (re-search-forward regexp nil t)
21264 (catch :skip
21265 (org-agenda-skip)
21266 (setq beg (match-beginning 0))
21267 (goto-char (1- (match-end 0)))
21268 (setq b (point))
21269 (forward-sexp 1)
21270 (setq sexp (buffer-substring b (point)))
21271 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21272 (org-trim (match-string 1))
21273 ""))
21274 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21275 (when result
21276 (setq marker (org-agenda-new-marker beg)
21277 category (org-get-category beg))
21279 (if (string-match "\\S-" result)
21280 (setq txt result)
21281 (setq txt "SEXP entry returned empty string"))
21283 (setq txt (org-format-agenda-item
21284 "" txt category tags 'time))
21285 (org-add-props txt props 'org-marker marker)
21286 (org-add-props txt nil
21287 'org-category category 'date date
21288 'type "sexp")
21289 (push txt ee))))
21290 (nreverse ee)))
21292 (defun org-agenda-get-closed ()
21293 "Return the logged TODO entries for agenda display."
21294 (let* ((props (list 'mouse-face 'highlight
21295 'org-not-done-regexp org-not-done-regexp
21296 'org-todo-regexp org-todo-regexp
21297 'keymap org-agenda-keymap
21298 'help-echo
21299 (format "mouse-2 or RET jump to org file %s"
21300 (abbreviate-file-name buffer-file-name))))
21301 (regexp (concat
21302 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21303 (regexp-quote
21304 (substring
21305 (format-time-string
21306 (car org-time-stamp-formats)
21307 (apply 'encode-time ; DATE bound by calendar
21308 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21309 1 11))))
21310 marker hdmarker priority category tags closedp
21311 ee txt timestr)
21312 (goto-char (point-min))
21313 (while (re-search-forward regexp nil t)
21314 (catch :skip
21315 (org-agenda-skip)
21316 (setq marker (org-agenda-new-marker (match-beginning 0))
21317 closedp (equal (match-string 1) org-closed-string)
21318 category (org-get-category (match-beginning 0))
21319 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21320 ;; donep (org-entry-is-done-p)
21322 (if (string-match "\\]" timestr)
21323 ;; substring should only run to end of time stamp
21324 (setq timestr (substring timestr 0 (match-end 0))))
21325 (save-excursion
21326 (if (re-search-backward "^\\*+ " nil t)
21327 (progn
21328 (goto-char (match-beginning 0))
21329 (setq hdmarker (org-agenda-new-marker)
21330 tags (org-get-tags-at))
21331 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21332 (setq txt (org-format-agenda-item
21333 (if closedp "Closed: " "Clocked: ")
21334 (match-string 1) category tags timestr)))
21335 (setq txt org-agenda-no-heading-message))
21336 (setq priority 100000)
21337 (org-add-props txt props
21338 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21339 'priority priority 'org-category category
21340 'type "closed" 'date date
21341 'undone-face 'org-warning 'done-face 'org-done)
21342 (push txt ee))
21343 (goto-char (point-at-eol))))
21344 ; (outline-next-heading)))
21345 (nreverse ee)))
21347 (defun org-agenda-get-deadlines ()
21348 "Return the deadline information for agenda display."
21349 (let* ((props (list 'mouse-face 'highlight
21350 'org-not-done-regexp org-not-done-regexp
21351 'org-todo-regexp org-todo-regexp
21352 'keymap org-agenda-keymap
21353 'help-echo
21354 (format "mouse-2 or RET jump to org file %s"
21355 (abbreviate-file-name buffer-file-name))))
21356 (regexp org-deadline-time-regexp)
21357 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21358 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21359 d2 diff dfrac wdays pos pos1 category tags
21360 ee txt head face s upcomingp donep timestr)
21361 (goto-char (point-min))
21362 (while (re-search-forward regexp nil t)
21363 (catch :skip
21364 (org-agenda-skip)
21365 (setq s (match-string 1)
21366 pos (1- (match-beginning 1))
21367 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21368 diff (- d2 d1)
21369 wdays (org-get-wdays s)
21370 dfrac (/ (* 1.0 (- wdays diff)) wdays)
21371 upcomingp (and todayp (> diff 0)))
21372 ;; When to show a deadline in the calendar:
21373 ;; If the expiration is within wdays warning time.
21374 ;; Past-due deadlines are only shown on the current date
21375 (if (or (and (<= diff wdays)
21376 (and todayp (not org-agenda-only-exact-dates)))
21377 (= diff 0))
21378 (save-excursion
21379 (setq category (org-get-category))
21380 (if (re-search-backward "^\\*+[ \t]+" nil t)
21381 (progn
21382 (goto-char (match-end 0))
21383 (setq pos1 (match-beginning 0))
21384 (setq tags (org-get-tags-at pos1))
21385 (setq head (buffer-substring-no-properties
21386 (point)
21387 (progn (skip-chars-forward "^\r\n")
21388 (point))))
21389 (setq donep (string-match org-looking-at-done-regexp head))
21390 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21391 (setq timestr
21392 (concat (substring s (match-beginning 1)) " "))
21393 (setq timestr 'time))
21394 (if (and donep
21395 (or org-agenda-skip-deadline-if-done
21396 (not (= diff 0))))
21397 (setq txt nil)
21398 (setq txt (org-format-agenda-item
21399 (if (= diff 0)
21400 (car org-agenda-deadline-leaders)
21401 (format (nth 1 org-agenda-deadline-leaders)
21402 diff))
21403 head category tags timestr))))
21404 (setq txt org-agenda-no-heading-message))
21405 (when txt
21406 (setq face (org-agenda-deadline-face dfrac))
21407 (org-add-props txt props
21408 'org-marker (org-agenda-new-marker pos)
21409 'org-hd-marker (org-agenda-new-marker pos1)
21410 'priority (+ (floor (* dfrac 100.))
21411 (org-get-priority txt))
21412 'org-category category
21413 'type (if upcomingp "upcoming-deadline" "deadline")
21414 'date (if upcomingp date d2)
21415 'face (if donep 'org-done face)
21416 'undone-face face 'done-face 'org-done)
21417 (push txt ee))))))
21418 (nreverse ee)))
21420 (defun org-agenda-deadline-face (fraction)
21421 "Return the face to displaying a deadline item.
21422 FRACTION is what fraction of the head-warning time has passed."
21423 (let ((faces org-agenda-deadline-faces) f)
21424 (catch 'exit
21425 (while (setq f (pop faces))
21426 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21428 (defun org-agenda-get-scheduled ()
21429 "Return the scheduled information for agenda display."
21430 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21431 'org-todo-regexp org-todo-regexp
21432 'done-face 'org-done
21433 'mouse-face 'highlight
21434 'keymap org-agenda-keymap
21435 'help-echo
21436 (format "mouse-2 or RET jump to org file %s"
21437 (abbreviate-file-name buffer-file-name))))
21438 (regexp org-scheduled-time-regexp)
21439 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21440 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21441 d2 diff pos pos1 category tags
21442 ee txt head pastschedp donep face timestr s)
21443 (goto-char (point-min))
21444 (while (re-search-forward regexp nil t)
21445 (catch :skip
21446 (org-agenda-skip)
21447 (setq s (match-string 1)
21448 pos (1- (match-beginning 1))
21449 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21450 ;;; is this right?
21451 ;;; do we need to do this for deadleine too????
21452 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21453 diff (- d2 d1))
21454 (setq pastschedp (and todayp (< diff 0)))
21455 ;; When to show a scheduled item in the calendar:
21456 ;; If it is on or past the date.
21457 (if (or (and (< diff 0)
21458 (and todayp (not org-agenda-only-exact-dates)))
21459 (= diff 0))
21460 (save-excursion
21461 (setq category (org-get-category))
21462 (if (re-search-backward "^\\*+[ \t]+" nil t)
21463 (progn
21464 (goto-char (match-end 0))
21465 (setq pos1 (match-beginning 0))
21466 (setq tags (org-get-tags-at))
21467 (setq head (buffer-substring-no-properties
21468 (point)
21469 (progn (skip-chars-forward "^\r\n") (point))))
21470 (setq donep (string-match org-looking-at-done-regexp head))
21471 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21472 (setq timestr
21473 (concat (substring s (match-beginning 1)) " "))
21474 (setq timestr 'time))
21475 (if (and donep
21476 (or org-agenda-skip-scheduled-if-done
21477 (not (= diff 0))))
21478 (setq txt nil)
21479 (setq txt (org-format-agenda-item
21480 (if (= diff 0)
21481 (car org-agenda-scheduled-leaders)
21482 (format (nth 1 org-agenda-scheduled-leaders)
21483 (- 1 diff)))
21484 head category tags timestr))))
21485 (setq txt org-agenda-no-heading-message))
21486 (when txt
21487 (setq face (if pastschedp
21488 'org-scheduled-previously
21489 'org-scheduled-today))
21490 (org-add-props txt props
21491 'undone-face face
21492 'face (if donep 'org-done face)
21493 'org-marker (org-agenda-new-marker pos)
21494 'org-hd-marker (org-agenda-new-marker pos1)
21495 'type (if pastschedp "past-scheduled" "scheduled")
21496 'date (if pastschedp d2 date)
21497 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21498 'org-category category)
21499 (push txt ee))))))
21500 (nreverse ee)))
21502 (defun org-agenda-get-blocks ()
21503 "Return the date-range information for agenda display."
21504 (let* ((props (list 'face nil
21505 'org-not-done-regexp org-not-done-regexp
21506 'org-todo-regexp org-todo-regexp
21507 'mouse-face 'highlight
21508 'keymap org-agenda-keymap
21509 'help-echo
21510 (format "mouse-2 or RET jump to org file %s"
21511 (abbreviate-file-name buffer-file-name))))
21512 (regexp org-tr-regexp)
21513 (d0 (calendar-absolute-from-gregorian date))
21514 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21515 donep head)
21516 (goto-char (point-min))
21517 (while (re-search-forward regexp nil t)
21518 (catch :skip
21519 (org-agenda-skip)
21520 (setq pos (point))
21521 (setq timestr (match-string 0)
21522 s1 (match-string 1)
21523 s2 (match-string 2)
21524 d1 (time-to-days (org-time-string-to-time s1))
21525 d2 (time-to-days (org-time-string-to-time s2)))
21526 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21527 ;; Only allow days between the limits, because the normal
21528 ;; date stamps will catch the limits.
21529 (save-excursion
21530 (setq marker (org-agenda-new-marker (point)))
21531 (setq category (org-get-category))
21532 (if (re-search-backward "^\\*+ " nil t)
21533 (progn
21534 (goto-char (match-beginning 0))
21535 (setq hdmarker (org-agenda-new-marker (point)))
21536 (setq tags (org-get-tags-at))
21537 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21538 (setq head (match-string 1))
21539 (and org-agenda-skip-timestamp-if-done
21540 (org-entry-is-done-p)
21541 (throw :skip t))
21542 (setq txt (org-format-agenda-item
21543 (format (if (= d1 d2) "" "(%d/%d): ")
21544 (1+ (- d0 d1)) (1+ (- d2 d1)))
21545 head category tags
21546 (if (= d0 d1) timestr))))
21547 (setq txt org-agenda-no-heading-message))
21548 (org-add-props txt props
21549 'org-marker marker 'org-hd-marker hdmarker
21550 'type "block" 'date date
21551 'priority (org-get-priority txt) 'org-category category)
21552 (push txt ee)))
21553 (goto-char pos)))
21554 ;; Sort the entries by expiration date.
21555 (nreverse ee)))
21557 ;;; Agenda presentation and sorting
21559 (defconst org-plain-time-of-day-regexp
21560 (concat
21561 "\\(\\<[012]?[0-9]"
21562 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21563 "\\(--?"
21564 "\\(\\<[012]?[0-9]"
21565 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21566 "\\)?")
21567 "Regular expression to match a plain time or time range.
21568 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21569 groups carry important information:
21570 0 the full match
21571 1 the first time, range or not
21572 8 the second time, if it is a range.")
21574 (defconst org-plain-time-extension-regexp
21575 (concat
21576 "\\(\\<[012]?[0-9]"
21577 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21578 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21579 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21580 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21581 groups carry important information:
21582 0 the full match
21583 7 hours of duration
21584 9 minutes of duration")
21586 (defconst org-stamp-time-of-day-regexp
21587 (concat
21588 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21589 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21590 "\\(--?"
21591 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21592 "Regular expression to match a timestamp time or time range.
21593 After a match, the following groups carry important information:
21594 0 the full match
21595 1 date plus weekday, for backreferencing to make sure both times on same day
21596 2 the first time, range or not
21597 4 the second time, if it is a range.")
21599 (defvar org-prefix-has-time nil
21600 "A flag, set by `org-compile-prefix-format'.
21601 The flag is set if the currently compiled format contains a `%t'.")
21602 (defvar org-prefix-has-tag nil
21603 "A flag, set by `org-compile-prefix-format'.
21604 The flag is set if the currently compiled format contains a `%T'.")
21606 (defun org-format-agenda-item (extra txt &optional category tags dotime
21607 noprefix remove-re)
21608 "Format TXT to be inserted into the agenda buffer.
21609 In particular, it adds the prefix and corresponding text properties. EXTRA
21610 must be a string and replaces the `%s' specifier in the prefix format.
21611 CATEGORY (string, symbol or nil) may be used to overrule the default
21612 category taken from local variable or file name. It will replace the `%c'
21613 specifier in the format. DOTIME, when non-nil, indicates that a
21614 time-of-day should be extracted from TXT for sorting of this entry, and for
21615 the `%t' specifier in the format. When DOTIME is a string, this string is
21616 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21617 only the correctly processes TXT should be returned - this is used by
21618 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21619 Any match of REMOVE-RE will be removed from TXT."
21620 (save-match-data
21621 ;; Diary entries sometimes have extra whitespace at the beginning
21622 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21623 (let* ((category (or category
21624 org-category
21625 (if buffer-file-name
21626 (file-name-sans-extension
21627 (file-name-nondirectory buffer-file-name))
21628 "")))
21629 (tag (if tags (nth (1- (length tags)) tags) ""))
21630 time ; time and tag are needed for the eval of the prefix format
21631 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21632 (time-of-day (and dotime (org-get-time-of-day ts)))
21633 stamp plain s0 s1 s2 rtn srp)
21634 (when (and dotime time-of-day org-prefix-has-time)
21635 ;; Extract starting and ending time and move them to prefix
21636 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21637 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21638 (setq s0 (match-string 0 ts)
21639 srp (and stamp (match-end 3))
21640 s1 (match-string (if plain 1 2) ts)
21641 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21643 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21644 ;; them, we might want to remove them there to avoid duplication.
21645 ;; The user can turn this off with a variable.
21646 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21647 (string-match (concat (regexp-quote s0) " *") txt)
21648 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21649 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21650 (= (match-beginning 0) 0)
21652 (setq txt (replace-match "" nil nil txt))))
21653 ;; Normalize the time(s) to 24 hour
21654 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21655 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21657 (when (and s1 (not s2) org-agenda-default-appointment-duration
21658 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21659 (let ((m (+ (string-to-number (match-string 2 s1))
21660 (* 60 (string-to-number (match-string 1 s1)))
21661 org-agenda-default-appointment-duration))
21663 (setq h (/ m 60) m (- m (* h 60)))
21664 (setq s2 (format "%02d:%02d" h m))))
21666 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21667 txt)
21668 ;; Tags are in the string
21669 (if (or (eq org-agenda-remove-tags t)
21670 (and org-agenda-remove-tags
21671 org-prefix-has-tag))
21672 (setq txt (replace-match "" t t txt))
21673 (setq txt (replace-match
21674 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21675 (match-string 2 txt))
21676 t t txt))))
21678 (when remove-re
21679 (while (string-match remove-re txt)
21680 (setq txt (replace-match "" t t txt))))
21682 ;; Create the final string
21683 (if noprefix
21684 (setq rtn txt)
21685 ;; Prepare the variables needed in the eval of the compiled format
21686 (setq time (cond (s2 (concat s1 "-" s2))
21687 (s1 (concat s1 "......"))
21688 (t ""))
21689 extra (or extra "")
21690 category (if (symbolp category) (symbol-name category) category))
21691 ;; Evaluate the compiled format
21692 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21694 ;; And finally add the text properties
21695 (org-add-props rtn nil
21696 'org-category (downcase category) 'tags tags
21697 'org-highest-priority org-highest-priority
21698 'org-lowest-priority org-lowest-priority
21699 'prefix-length (- (length rtn) (length txt))
21700 'time-of-day time-of-day
21701 'txt txt
21702 'time time
21703 'extra extra
21704 'dotime dotime))))
21706 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21707 (defvar org-agenda-sorting-strategy-selected nil)
21709 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21710 (catch 'exit
21711 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21712 ((and todayp (member 'today (car org-agenda-time-grid))))
21713 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21714 ((member 'weekly (car org-agenda-time-grid)))
21715 (t (throw 'exit list)))
21716 (let* ((have (delq nil (mapcar
21717 (lambda (x) (get-text-property 1 'time-of-day x))
21718 list)))
21719 (string (nth 1 org-agenda-time-grid))
21720 (gridtimes (nth 2 org-agenda-time-grid))
21721 (req (car org-agenda-time-grid))
21722 (remove (member 'remove-match req))
21723 new time)
21724 (if (and (member 'require-timed req) (not have))
21725 ;; don't show empty grid
21726 (throw 'exit list))
21727 (while (setq time (pop gridtimes))
21728 (unless (and remove (member time have))
21729 (setq time (int-to-string time))
21730 (push (org-format-agenda-item
21731 nil string "" nil
21732 (concat (substring time 0 -2) ":" (substring time -2)))
21733 new)
21734 (put-text-property
21735 1 (length (car new)) 'face 'org-time-grid (car new))))
21736 (if (member 'time-up org-agenda-sorting-strategy-selected)
21737 (append new list)
21738 (append list new)))))
21740 (defun org-compile-prefix-format (key)
21741 "Compile the prefix format into a Lisp form that can be evaluated.
21742 The resulting form is returned and stored in the variable
21743 `org-prefix-format-compiled'."
21744 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21745 (let ((s (cond
21746 ((stringp org-agenda-prefix-format)
21747 org-agenda-prefix-format)
21748 ((assq key org-agenda-prefix-format)
21749 (cdr (assq key org-agenda-prefix-format)))
21750 (t " %-12:c%?-12t% s")))
21751 (start 0)
21752 varform vars var e c f opt)
21753 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21754 s start)
21755 (setq var (cdr (assoc (match-string 4 s)
21756 '(("c" . category) ("t" . time) ("s" . extra)
21757 ("T" . tag))))
21758 c (or (match-string 3 s) "")
21759 opt (match-beginning 1)
21760 start (1+ (match-beginning 0)))
21761 (if (equal var 'time) (setq org-prefix-has-time t))
21762 (if (equal var 'tag) (setq org-prefix-has-tag t))
21763 (setq f (concat "%" (match-string 2 s) "s"))
21764 (if opt
21765 (setq varform
21766 `(if (equal "" ,var)
21768 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21769 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21770 (setq s (replace-match "%s" t nil s))
21771 (push varform vars))
21772 (setq vars (nreverse vars))
21773 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21775 (defun org-set-sorting-strategy (key)
21776 (if (symbolp (car org-agenda-sorting-strategy))
21777 ;; the old format
21778 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21779 (setq org-agenda-sorting-strategy-selected
21780 (or (cdr (assq key org-agenda-sorting-strategy))
21781 (cdr (assq 'agenda org-agenda-sorting-strategy))
21782 '(time-up category-keep priority-down)))))
21784 (defun org-get-time-of-day (s &optional string mod24)
21785 "Check string S for a time of day.
21786 If found, return it as a military time number between 0 and 2400.
21787 If not found, return nil.
21788 The optional STRING argument forces conversion into a 5 character wide string
21789 HH:MM."
21790 (save-match-data
21791 (when
21792 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21793 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21794 (let* ((h (string-to-number (match-string 1 s)))
21795 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21796 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21797 (am-p (equal ampm "am"))
21798 (h1 (cond ((not ampm) h)
21799 ((= h 12) (if am-p 0 12))
21800 (t (+ h (if am-p 0 12)))))
21801 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21802 (mod h1 24) h1))
21803 (t0 (+ (* 100 h2) m))
21804 (t1 (concat (if (>= h1 24) "+" " ")
21805 (if (< t0 100) "0" "")
21806 (if (< t0 10) "0" "")
21807 (int-to-string t0))))
21808 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21810 (defun org-finalize-agenda-entries (list &optional nosort)
21811 "Sort and concatenate the agenda items."
21812 (setq list (mapcar 'org-agenda-highlight-todo list))
21813 (if nosort
21814 list
21815 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21817 (defun org-agenda-highlight-todo (x)
21818 (let (re pl)
21819 (if (eq x 'line)
21820 (save-excursion
21821 (beginning-of-line 1)
21822 (setq re (get-text-property (point) 'org-todo-regexp))
21823 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21824 (when (looking-at (concat "[ \t]*\\.*" re " +"))
21825 (add-text-properties (match-beginning 0) (match-end 0)
21826 (list 'face (org-get-todo-face 0)))
21827 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
21828 (delete-region (match-beginning 1) (1- (match-end 0)))
21829 (goto-char (match-beginning 1))
21830 (insert (format org-agenda-todo-keyword-format s)))))
21831 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21832 pl (get-text-property 0 'prefix-length x))
21833 ; (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
21834 ; (add-text-properties
21835 ; (or (match-end 1) (match-end 0)) (match-end 0)
21836 ; (list 'face (org-get-todo-face (match-string 2 x)))
21837 ; x))
21838 (when (and re
21839 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
21840 x (or pl 0)) pl))
21841 (add-text-properties
21842 (or (match-end 1) (match-end 0)) (match-end 0)
21843 (list 'face (org-get-todo-face (match-string 2 x)))
21845 (setq x (concat (substring x 0 (match-end 1))
21846 (format org-agenda-todo-keyword-format
21847 (match-string 2 x))
21849 (substring x (match-end 3)))))
21850 x)))
21852 (defsubst org-cmp-priority (a b)
21853 "Compare the priorities of string A and B."
21854 (let ((pa (or (get-text-property 1 'priority a) 0))
21855 (pb (or (get-text-property 1 'priority b) 0)))
21856 (cond ((> pa pb) +1)
21857 ((< pa pb) -1)
21858 (t nil))))
21860 (defsubst org-cmp-category (a b)
21861 "Compare the string values of categories of strings A and B."
21862 (let ((ca (or (get-text-property 1 'org-category a) ""))
21863 (cb (or (get-text-property 1 'org-category b) "")))
21864 (cond ((string-lessp ca cb) -1)
21865 ((string-lessp cb ca) +1)
21866 (t nil))))
21868 (defsubst org-cmp-tag (a b)
21869 "Compare the string values of categories of strings A and B."
21870 (let ((ta (car (last (get-text-property 1 'tags a))))
21871 (tb (car (last (get-text-property 1 'tags b)))))
21872 (cond ((not ta) +1)
21873 ((not tb) -1)
21874 ((string-lessp ta tb) -1)
21875 ((string-lessp tb ta) +1)
21876 (t nil))))
21878 (defsubst org-cmp-time (a b)
21879 "Compare the time-of-day values of strings A and B."
21880 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21881 (ta (or (get-text-property 1 'time-of-day a) def))
21882 (tb (or (get-text-property 1 'time-of-day b) def)))
21883 (cond ((< ta tb) -1)
21884 ((< tb ta) +1)
21885 (t nil))))
21887 (defun org-entries-lessp (a b)
21888 "Predicate for sorting agenda entries."
21889 ;; The following variables will be used when the form is evaluated.
21890 ;; So even though the compiler complains, keep them.
21891 (let* ((time-up (org-cmp-time a b))
21892 (time-down (if time-up (- time-up) nil))
21893 (priority-up (org-cmp-priority a b))
21894 (priority-down (if priority-up (- priority-up) nil))
21895 (category-up (org-cmp-category a b))
21896 (category-down (if category-up (- category-up) nil))
21897 (category-keep (if category-up +1 nil))
21898 (tag-up (org-cmp-tag a b))
21899 (tag-down (if tag-up (- tag-up) nil)))
21900 (cdr (assoc
21901 (eval (cons 'or org-agenda-sorting-strategy-selected))
21902 '((-1 . t) (1 . nil) (nil . nil))))))
21904 ;;; Agenda restriction lock
21906 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
21907 "Overlay to mark the headline to which arenda commands are restricted.")
21908 (org-overlay-put org-agenda-restriction-lock-overlay
21909 'face 'org-agenda-restriction-lock)
21910 (org-overlay-put org-agenda-restriction-lock-overlay
21911 'help-echo "Agendas are currently limited to this subtree.")
21912 (org-detach-overlay org-agenda-restriction-lock-overlay)
21913 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
21914 "Overlay marking the agenda restriction line in speedbar.")
21915 (org-overlay-put org-speedbar-restriction-lock-overlay
21916 'face 'org-agenda-restriction-lock)
21917 (org-overlay-put org-speedbar-restriction-lock-overlay
21918 'help-echo "Agendas are currently limited to this item.")
21919 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21921 (defun org-agenda-set-restriction-lock (&optional type)
21922 "Set restriction lock for agenda, to current subtree or file.
21923 Restriction will be the file if TYPE is `file', or if type is the
21924 universal prefix '(4), or if the cursor is before the first headline
21925 in the file. Otherwise, restriction will be to the current subtree."
21926 (interactive "P")
21927 (and (equal type '(4)) (setq type 'file))
21928 (setq type (cond
21929 (type type)
21930 ((org-at-heading-p) 'subtree)
21931 ((condition-case nil (org-back-to-heading t) (error nil))
21932 'subtree)
21933 (t 'file)))
21934 (if (eq type 'subtree)
21935 (progn
21936 (setq org-agenda-restrict t)
21937 (setq org-agenda-overriding-restriction 'subtree)
21938 (put 'org-agenda-files 'org-restrict
21939 (list (buffer-file-name (buffer-base-buffer))))
21940 (org-back-to-heading t)
21941 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
21942 (move-marker org-agenda-restrict-begin (point))
21943 (move-marker org-agenda-restrict-end
21944 (save-excursion (org-end-of-subtree t)))
21945 (message "Locking agenda restriction to subtree"))
21946 (put 'org-agenda-files 'org-restrict
21947 (list (buffer-file-name (buffer-base-buffer))))
21948 (setq org-agenda-restrict nil)
21949 (setq org-agenda-overriding-restriction 'file)
21950 (move-marker org-agenda-restrict-begin nil)
21951 (move-marker org-agenda-restrict-end nil)
21952 (message "Locking agenda restriction to file"))
21953 (setq current-prefix-arg nil)
21954 (org-agenda-maybe-redo))
21956 (defun org-agenda-remove-restriction-lock (&optional noupdate)
21957 "Remove the agenda restriction lock."
21958 (interactive "P")
21959 (org-detach-overlay org-agenda-restriction-lock-overlay)
21960 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21961 (setq org-agenda-overriding-restriction nil)
21962 (setq org-agenda-restrict nil)
21963 (put 'org-agenda-files 'org-restrict nil)
21964 (move-marker org-agenda-restrict-begin nil)
21965 (move-marker org-agenda-restrict-end nil)
21966 (setq current-prefix-arg nil)
21967 (message "Agenda restriction lock removed")
21968 (or noupdate (org-agenda-maybe-redo)))
21970 (defun org-agenda-maybe-redo ()
21971 "If there is any window showing the agenda view, update it."
21972 (let ((w (get-buffer-window org-agenda-buffer-name t))
21973 (w0 (selected-window)))
21974 (when w
21975 (select-window w)
21976 (org-agenda-redo)
21977 (select-window w0)
21978 (if org-agenda-overriding-restriction
21979 (message "Agenda view shifted to new %s restriction"
21980 org-agenda-overriding-restriction)
21981 (message "Agenda restriction lock removed")))))
21983 ;;; Agenda commands
21985 (defun org-agenda-check-type (error &rest types)
21986 "Check if agenda buffer is of allowed type.
21987 If ERROR is non-nil, throw an error, otherwise just return nil."
21988 (if (memq org-agenda-type types)
21990 (if error
21991 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
21992 nil)))
21994 (defun org-agenda-quit ()
21995 "Exit agenda by removing the window or the buffer."
21996 (interactive)
21997 (let ((buf (current-buffer)))
21998 (if (not (one-window-p)) (delete-window))
21999 (kill-buffer buf)
22000 (org-agenda-maybe-reset-markers 'force)
22001 (org-columns-remove-overlays))
22002 ;; Maybe restore the pre-agenda window configuration.
22003 (and org-agenda-restore-windows-after-quit
22004 (not (eq org-agenda-window-setup 'other-frame))
22005 org-pre-agenda-window-conf
22006 (set-window-configuration org-pre-agenda-window-conf)))
22008 (defun org-agenda-exit ()
22009 "Exit agenda by removing the window or the buffer.
22010 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22011 Org-mode buffers visited directly by the user will not be touched."
22012 (interactive)
22013 (org-release-buffers org-agenda-new-buffers)
22014 (setq org-agenda-new-buffers nil)
22015 (org-agenda-quit))
22017 (defun org-agenda-execute (arg)
22018 "Execute another agenda command, keeping same window.\\<global-map>
22019 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22020 (interactive "P")
22021 (let ((org-agenda-window-setup 'current-window))
22022 (org-agenda arg)))
22024 (defun org-save-all-org-buffers ()
22025 "Save all Org-mode buffers without user confirmation."
22026 (interactive)
22027 (message "Saving all Org-mode buffers...")
22028 (save-some-buffers t 'org-mode-p)
22029 (message "Saving all Org-mode buffers... done"))
22031 (defun org-agenda-redo ()
22032 "Rebuild Agenda.
22033 When this is the global TODO list, a prefix argument will be interpreted."
22034 (interactive)
22035 (let* ((org-agenda-keep-modes t)
22036 (line (org-current-line))
22037 (window-line (- line (org-current-line (window-start))))
22038 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22039 (message "Rebuilding agenda buffer...")
22040 (org-let lprops '(eval org-agenda-redo-command))
22041 (setq org-agenda-undo-list nil
22042 org-agenda-pending-undo-list nil)
22043 (message "Rebuilding agenda buffer...done")
22044 (goto-line line)
22045 (recenter window-line)))
22047 (defun org-agenda-goto-date (date)
22048 "Jump to DATE in agenda."
22049 (interactive (list (org-read-date)))
22050 (org-agenda-list nil date))
22052 (defun org-agenda-goto-today ()
22053 "Go to today."
22054 (interactive)
22055 (org-agenda-check-type t 'timeline 'agenda)
22056 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22057 (cond
22058 (tdpos (goto-char tdpos))
22059 ((eq org-agenda-type 'agenda)
22060 (let* ((sd (time-to-days
22061 (time-subtract (current-time)
22062 (list 0 (* 3600 org-extend-today-until) 0))))
22063 (comp (org-agenda-compute-time-span sd org-agenda-span))
22064 (org-agenda-overriding-arguments org-agenda-last-arguments))
22065 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22066 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22067 (org-agenda-redo)
22068 (org-agenda-find-same-or-today-or-agenda)))
22069 (t (error "Cannot find today")))))
22071 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22072 (goto-char
22073 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22074 (text-property-any (point-min) (point-max) 'org-today t)
22075 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22076 (point-min))))
22078 (defun org-agenda-later (arg)
22079 "Go forward in time by thee current span.
22080 With prefix ARG, go forward that many times the current span."
22081 (interactive "p")
22082 (org-agenda-check-type t 'agenda)
22083 (let* ((span org-agenda-span)
22084 (sd org-starting-day)
22085 (greg (calendar-gregorian-from-absolute sd))
22086 (cnt (get-text-property (point) 'org-day-cnt))
22087 greg2 nd)
22088 (cond
22089 ((eq span 'day)
22090 (setq sd (+ arg sd) nd 1))
22091 ((eq span 'week)
22092 (setq sd (+ (* 7 arg) sd) nd 7))
22093 ((eq span 'month)
22094 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22095 sd (calendar-absolute-from-gregorian greg2))
22096 (setcar greg2 (1+ (car greg2)))
22097 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22098 ((eq span 'year)
22099 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22100 sd (calendar-absolute-from-gregorian greg2))
22101 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22102 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22103 (let ((org-agenda-overriding-arguments
22104 (list (car org-agenda-last-arguments) sd nd t)))
22105 (org-agenda-redo)
22106 (org-agenda-find-same-or-today-or-agenda cnt))))
22108 (defun org-agenda-earlier (arg)
22109 "Go backward in time by the current span.
22110 With prefix ARG, go backward that many times the current span."
22111 (interactive "p")
22112 (org-agenda-later (- arg)))
22114 (defun org-agenda-day-view ()
22115 "Switch to daily view for agenda."
22116 (interactive)
22117 (setq org-agenda-ndays 1)
22118 (org-agenda-change-time-span 'day))
22119 (defun org-agenda-week-view ()
22120 "Switch to daily view for agenda."
22121 (interactive)
22122 (setq org-agenda-ndays 7)
22123 (org-agenda-change-time-span 'week))
22124 (defun org-agenda-month-view ()
22125 "Switch to daily view for agenda."
22126 (interactive)
22127 (org-agenda-change-time-span 'month))
22128 (defun org-agenda-year-view ()
22129 "Switch to daily view for agenda."
22130 (interactive)
22131 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22132 (org-agenda-change-time-span 'year)
22133 (error "Abort")))
22135 (defun org-agenda-change-time-span (span)
22136 "Change the agenda view to SPAN.
22137 SPAN may be `day', `week', `month', `year'."
22138 (org-agenda-check-type t 'agenda)
22139 (if (equal org-agenda-span span)
22140 (error "Viewing span is already \"%s\"" span))
22141 (let* ((sd (or (get-text-property (point) 'day)
22142 org-starting-day))
22143 (computed (org-agenda-compute-time-span sd span))
22144 (org-agenda-overriding-arguments
22145 (list (car org-agenda-last-arguments)
22146 (car computed) (cdr computed) t)))
22147 (org-agenda-redo)
22148 (org-agenda-find-same-or-today-or-agenda))
22149 (org-agenda-set-mode-name)
22150 (message "Switched to %s view" span))
22152 (defun org-agenda-compute-time-span (sd span)
22153 "Compute starting date and number of days for agenda.
22154 SPAN may be `day', `week', `month', `year'. The return value
22155 is a cons cell with the starting date and the number of days,
22156 so that the date SD will be in that range."
22157 (let* ((greg (calendar-gregorian-from-absolute sd))
22159 (cond
22160 ((eq span 'day)
22161 (setq nd 1))
22162 ((eq span 'week)
22163 (let* ((nt (calendar-day-of-week
22164 (calendar-gregorian-from-absolute sd)))
22165 (d (if org-agenda-start-on-weekday
22166 (- nt org-agenda-start-on-weekday)
22167 0)))
22168 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22169 (setq nd 7)))
22170 ((eq span 'month)
22171 (setq sd (calendar-absolute-from-gregorian
22172 (list (car greg) 1 (nth 2 greg)))
22173 nd (- (calendar-absolute-from-gregorian
22174 (list (1+ (car greg)) 1 (nth 2 greg)))
22175 sd)))
22176 ((eq span 'year)
22177 (setq sd (calendar-absolute-from-gregorian
22178 (list 1 1 (nth 2 greg)))
22179 nd (- (calendar-absolute-from-gregorian
22180 (list 1 1 (1+ (nth 2 greg))))
22181 sd))))
22182 (cons sd nd)))
22184 ;; FIXME: does not work if user makes date format that starts with a blank
22185 (defun org-agenda-next-date-line (&optional arg)
22186 "Jump to the next line indicating a date in agenda buffer."
22187 (interactive "p")
22188 (org-agenda-check-type t 'agenda 'timeline)
22189 (beginning-of-line 1)
22190 (if (looking-at "^\\S-") (forward-char 1))
22191 (if (not (re-search-forward "^\\S-" nil t arg))
22192 (progn
22193 (backward-char 1)
22194 (error "No next date after this line in this buffer")))
22195 (goto-char (match-beginning 0)))
22197 (defun org-agenda-previous-date-line (&optional arg)
22198 "Jump to the previous line indicating a date in agenda buffer."
22199 (interactive "p")
22200 (org-agenda-check-type t 'agenda 'timeline)
22201 (beginning-of-line 1)
22202 (if (not (re-search-backward "^\\S-" nil t arg))
22203 (error "No previous date before this line in this buffer")))
22205 ;; Initialize the highlight
22206 (defvar org-hl (org-make-overlay 1 1))
22207 (org-overlay-put org-hl 'face 'highlight)
22209 (defun org-highlight (begin end &optional buffer)
22210 "Highlight a region with overlay."
22211 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22212 org-hl begin end (or buffer (current-buffer))))
22214 (defun org-unhighlight ()
22215 "Detach overlay INDEX."
22216 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22218 ;; FIXME this is currently not used.
22219 (defun org-highlight-until-next-command (beg end &optional buffer)
22220 (org-highlight beg end buffer)
22221 (add-hook 'pre-command-hook 'org-unhighlight-once))
22222 (defun org-unhighlight-once ()
22223 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22224 (org-unhighlight))
22226 (defun org-agenda-follow-mode ()
22227 "Toggle follow mode in an agenda buffer."
22228 (interactive)
22229 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22230 (org-agenda-set-mode-name)
22231 (message "Follow mode is %s"
22232 (if org-agenda-follow-mode "on" "off")))
22234 (defun org-agenda-log-mode ()
22235 "Toggle log mode in an agenda buffer."
22236 (interactive)
22237 (org-agenda-check-type t 'agenda 'timeline)
22238 (setq org-agenda-show-log (not org-agenda-show-log))
22239 (org-agenda-set-mode-name)
22240 (org-agenda-redo)
22241 (message "Log mode is %s"
22242 (if org-agenda-show-log "on" "off")))
22244 (defun org-agenda-toggle-diary ()
22245 "Toggle diary inclusion in an agenda buffer."
22246 (interactive)
22247 (org-agenda-check-type t 'agenda)
22248 (setq org-agenda-include-diary (not org-agenda-include-diary))
22249 (org-agenda-redo)
22250 (org-agenda-set-mode-name)
22251 (message "Diary inclusion turned %s"
22252 (if org-agenda-include-diary "on" "off")))
22254 (defun org-agenda-toggle-time-grid ()
22255 "Toggle time grid in an agenda buffer."
22256 (interactive)
22257 (org-agenda-check-type t 'agenda)
22258 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22259 (org-agenda-redo)
22260 (org-agenda-set-mode-name)
22261 (message "Time-grid turned %s"
22262 (if org-agenda-use-time-grid "on" "off")))
22264 (defun org-agenda-set-mode-name ()
22265 "Set the mode name to indicate all the small mode settings."
22266 (setq mode-name
22267 (concat "Org-Agenda"
22268 (if (equal org-agenda-ndays 1) " Day" "")
22269 (if (equal org-agenda-ndays 7) " Week" "")
22270 (if org-agenda-follow-mode " Follow" "")
22271 (if org-agenda-include-diary " Diary" "")
22272 (if org-agenda-use-time-grid " Grid" "")
22273 (if org-agenda-show-log " Log" "")))
22274 (force-mode-line-update))
22276 (defun org-agenda-post-command-hook ()
22277 (and (eolp) (not (bolp)) (backward-char 1))
22278 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22279 (if (and org-agenda-follow-mode
22280 (get-text-property (point) 'org-marker))
22281 (org-agenda-show)))
22283 (defun org-agenda-show-priority ()
22284 "Show the priority of the current item.
22285 This priority is composed of the main priority given with the [#A] cookies,
22286 and by additional input from the age of a schedules or deadline entry."
22287 (interactive)
22288 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22289 (message "Priority is %d" (if pri pri -1000))))
22291 (defun org-agenda-show-tags ()
22292 "Show the tags applicable to the current item."
22293 (interactive)
22294 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22295 (if tags
22296 (message "Tags are :%s:"
22297 (org-no-properties (mapconcat 'identity tags ":")))
22298 (message "No tags associated with this line"))))
22300 (defun org-agenda-goto (&optional highlight)
22301 "Go to the Org-mode file which contains the item at point."
22302 (interactive)
22303 (let* ((marker (or (get-text-property (point) 'org-marker)
22304 (org-agenda-error)))
22305 (buffer (marker-buffer marker))
22306 (pos (marker-position marker)))
22307 (switch-to-buffer-other-window buffer)
22308 (widen)
22309 (goto-char pos)
22310 (when (org-mode-p)
22311 (org-show-context 'agenda)
22312 (save-excursion
22313 (and (outline-next-heading)
22314 (org-flag-heading nil)))) ; show the next heading
22315 (run-hooks 'org-agenda-after-show-hook)
22316 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22318 (defvar org-agenda-after-show-hook nil
22319 "Normal hook run after an item has been shown from the agenda.
22320 Point is in the buffer where the item originated.")
22322 (defun org-agenda-kill ()
22323 "Kill the entry or subtree belonging to the current agenda entry."
22324 (interactive)
22325 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22326 (let* ((marker (or (get-text-property (point) 'org-marker)
22327 (org-agenda-error)))
22328 (buffer (marker-buffer marker))
22329 (pos (marker-position marker))
22330 (type (get-text-property (point) 'type))
22331 dbeg dend (n 0) conf)
22332 (org-with-remote-undo buffer
22333 (with-current-buffer buffer
22334 (save-excursion
22335 (goto-char pos)
22336 (if (and (org-mode-p) (not (member type '("sexp"))))
22337 (setq dbeg (progn (org-back-to-heading t) (point))
22338 dend (org-end-of-subtree t t))
22339 (setq dbeg (point-at-bol)
22340 dend (min (point-max) (1+ (point-at-eol)))))
22341 (goto-char dbeg)
22342 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22343 (setq conf (or (eq t org-agenda-confirm-kill)
22344 (and (numberp org-agenda-confirm-kill)
22345 (> n org-agenda-confirm-kill))))
22346 (and conf
22347 (not (y-or-n-p
22348 (format "Delete entry with %d lines in buffer \"%s\"? "
22349 n (buffer-name buffer))))
22350 (error "Abort"))
22351 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22352 (with-current-buffer buffer (delete-region dbeg dend))
22353 (message "Agenda item and source killed"))))
22355 (defun org-agenda-archive ()
22356 "Kill the entry or subtree belonging to the current agenda entry."
22357 (interactive)
22358 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22359 (let* ((marker (or (get-text-property (point) 'org-marker)
22360 (org-agenda-error)))
22361 (buffer (marker-buffer marker))
22362 (pos (marker-position marker)))
22363 (org-with-remote-undo buffer
22364 (with-current-buffer buffer
22365 (if (org-mode-p)
22366 (save-excursion
22367 (goto-char pos)
22368 (org-remove-subtree-entries-from-agenda)
22369 (org-back-to-heading t)
22370 (org-archive-subtree))
22371 (error "Archiving works only in Org-mode files"))))))
22373 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22374 "Remove all lines in the agenda that correspond to a given subtree.
22375 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22376 If this information is not given, the function uses the tree at point."
22377 (let ((buf (or buf (current-buffer))) m p)
22378 (save-excursion
22379 (unless (and beg end)
22380 (org-back-to-heading t)
22381 (setq beg (point))
22382 (org-end-of-subtree t)
22383 (setq end (point)))
22384 (set-buffer (get-buffer org-agenda-buffer-name))
22385 (save-excursion
22386 (goto-char (point-max))
22387 (beginning-of-line 1)
22388 (while (not (bobp))
22389 (when (and (setq m (get-text-property (point) 'org-marker))
22390 (equal buf (marker-buffer m))
22391 (setq p (marker-position m))
22392 (>= p beg)
22393 (<= p end))
22394 (let ((inhibit-read-only t))
22395 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22396 (beginning-of-line 0))))))
22398 (defun org-agenda-open-link ()
22399 "Follow the link in the current line, if any."
22400 (interactive)
22401 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22402 (save-excursion
22403 (save-restriction
22404 (narrow-to-region (point-at-bol) (point-at-eol))
22405 (org-open-at-point))))
22407 (defun org-agenda-copy-local-variable (var)
22408 "Get a variable from a referenced buffer and install it here."
22409 (let ((m (get-text-property (point) 'org-marker)))
22410 (when (and m (buffer-live-p (marker-buffer m)))
22411 (org-set-local var (with-current-buffer (marker-buffer m)
22412 (symbol-value var))))))
22414 (defun org-agenda-switch-to (&optional delete-other-windows)
22415 "Go to the Org-mode file which contains the item at point."
22416 (interactive)
22417 (let* ((marker (or (get-text-property (point) 'org-marker)
22418 (org-agenda-error)))
22419 (buffer (marker-buffer marker))
22420 (pos (marker-position marker)))
22421 (switch-to-buffer buffer)
22422 (and delete-other-windows (delete-other-windows))
22423 (widen)
22424 (goto-char pos)
22425 (when (org-mode-p)
22426 (org-show-context 'agenda)
22427 (save-excursion
22428 (and (outline-next-heading)
22429 (org-flag-heading nil)))))) ; show the next heading
22431 (defun org-agenda-goto-mouse (ev)
22432 "Go to the Org-mode file which contains the item at the mouse click."
22433 (interactive "e")
22434 (mouse-set-point ev)
22435 (org-agenda-goto))
22437 (defun org-agenda-show ()
22438 "Display the Org-mode file which contains the item at point."
22439 (interactive)
22440 (let ((win (selected-window)))
22441 (org-agenda-goto t)
22442 (select-window win)))
22444 (defun org-agenda-recenter (arg)
22445 "Display the Org-mode file which contains the item at point and recenter."
22446 (interactive "P")
22447 (let ((win (selected-window)))
22448 (org-agenda-goto t)
22449 (recenter arg)
22450 (select-window win)))
22452 (defun org-agenda-show-mouse (ev)
22453 "Display the Org-mode file which contains the item at the mouse click."
22454 (interactive "e")
22455 (mouse-set-point ev)
22456 (org-agenda-show))
22458 (defun org-agenda-check-no-diary ()
22459 "Check if the entry is a diary link and abort if yes."
22460 (if (get-text-property (point) 'org-agenda-diary-link)
22461 (org-agenda-error)))
22463 (defun org-agenda-error ()
22464 (error "Command not allowed in this line"))
22466 (defun org-agenda-tree-to-indirect-buffer ()
22467 "Show the subtree corresponding to the current entry in an indirect buffer.
22468 This calls the command `org-tree-to-indirect-buffer' from the original
22469 Org-mode buffer.
22470 With numerical prefix arg ARG, go up to this level and then take that tree.
22471 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22472 dedicated frame)."
22473 (interactive)
22474 (org-agenda-check-no-diary)
22475 (let* ((marker (or (get-text-property (point) 'org-marker)
22476 (org-agenda-error)))
22477 (buffer (marker-buffer marker))
22478 (pos (marker-position marker)))
22479 (with-current-buffer buffer
22480 (save-excursion
22481 (goto-char pos)
22482 (call-interactively 'org-tree-to-indirect-buffer)))))
22484 (defvar org-last-heading-marker (make-marker)
22485 "Marker pointing to the headline that last changed its TODO state
22486 by a remote command from the agenda.")
22488 (defun org-agenda-todo-nextset ()
22489 "Switch TODO entry to next sequence."
22490 (interactive)
22491 (org-agenda-todo 'nextset))
22493 (defun org-agenda-todo-previousset ()
22494 "Switch TODO entry to previous sequence."
22495 (interactive)
22496 (org-agenda-todo 'previousset))
22498 (defun org-agenda-todo (&optional arg)
22499 "Cycle TODO state of line at point, also in Org-mode file.
22500 This changes the line at point, all other lines in the agenda referring to
22501 the same tree node, and the headline of the tree node in the Org-mode file."
22502 (interactive "P")
22503 (org-agenda-check-no-diary)
22504 (let* ((col (current-column))
22505 (marker (or (get-text-property (point) 'org-marker)
22506 (org-agenda-error)))
22507 (buffer (marker-buffer marker))
22508 (pos (marker-position marker))
22509 (hdmarker (get-text-property (point) 'org-hd-marker))
22510 (inhibit-read-only t)
22511 newhead)
22512 (org-with-remote-undo buffer
22513 (with-current-buffer buffer
22514 (widen)
22515 (goto-char pos)
22516 (org-show-context 'agenda)
22517 (save-excursion
22518 (and (outline-next-heading)
22519 (org-flag-heading nil))) ; show the next heading
22520 (org-todo arg)
22521 (and (bolp) (forward-char 1))
22522 (setq newhead (org-get-heading))
22523 (save-excursion
22524 (org-back-to-heading)
22525 (move-marker org-last-heading-marker (point))))
22526 (beginning-of-line 1)
22527 (save-excursion
22528 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22529 (move-to-column col))))
22531 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22532 "Change all lines in the agenda buffer which match HDMARKER.
22533 The new content of the line will be NEWHEAD (as modified by
22534 `org-format-agenda-item'). HDMARKER is checked with
22535 `equal' against all `org-hd-marker' text properties in the file.
22536 If FIXFACE is non-nil, the face of each item is modified acording to
22537 the new TODO state."
22538 (let* ((inhibit-read-only t)
22539 props m pl undone-face done-face finish new dotime cat tags)
22540 (save-excursion
22541 (goto-char (point-max))
22542 (beginning-of-line 1)
22543 (while (not finish)
22544 (setq finish (bobp))
22545 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22546 (equal m hdmarker))
22547 (setq props (text-properties-at (point))
22548 dotime (get-text-property (point) 'dotime)
22549 cat (get-text-property (point) 'org-category)
22550 tags (get-text-property (point) 'tags)
22551 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22552 pl (get-text-property (point) 'prefix-length)
22553 undone-face (get-text-property (point) 'undone-face)
22554 done-face (get-text-property (point) 'done-face))
22555 (move-to-column pl)
22556 (cond
22557 ((equal new "")
22558 (beginning-of-line 1)
22559 (and (looking-at ".*\n?") (replace-match "")))
22560 ((looking-at ".*")
22561 (replace-match new t t)
22562 (beginning-of-line 1)
22563 (add-text-properties (point-at-bol) (point-at-eol) props)
22564 (when fixface
22565 (add-text-properties
22566 (point-at-bol) (point-at-eol)
22567 (list 'face
22568 (if org-last-todo-state-is-todo
22569 undone-face done-face))))
22570 (org-agenda-highlight-todo 'line)
22571 (beginning-of-line 1))
22572 (t (error "Line update did not work"))))
22573 (beginning-of-line 0)))
22574 (org-finalize-agenda)))
22576 (defun org-agenda-align-tags (&optional line)
22577 "Align all tags in agenda items to `org-agenda-tags-column'."
22578 (let ((inhibit-read-only t) l c)
22579 (save-excursion
22580 (goto-char (if line (point-at-bol) (point-min)))
22581 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22582 (if line (point-at-eol) nil) t)
22583 (add-text-properties
22584 (match-beginning 2) (match-end 2)
22585 (list 'face (list 'org-tag (get-text-property
22586 (match-beginning 2) 'face))))
22587 (setq l (- (match-end 2) (match-beginning 2))
22588 c (if (< org-agenda-tags-column 0)
22589 (- (abs org-agenda-tags-column) l)
22590 org-agenda-tags-column))
22591 (delete-region (match-beginning 1) (match-end 1))
22592 (goto-char (match-beginning 1))
22593 (insert (org-add-props
22594 (make-string (max 1 (- c (current-column))) ?\ )
22595 (text-properties-at (point))))))))
22597 (defun org-agenda-priority-up ()
22598 "Increase the priority of line at point, also in Org-mode file."
22599 (interactive)
22600 (org-agenda-priority 'up))
22602 (defun org-agenda-priority-down ()
22603 "Decrease the priority of line at point, also in Org-mode file."
22604 (interactive)
22605 (org-agenda-priority 'down))
22607 (defun org-agenda-priority (&optional force-direction)
22608 "Set the priority of line at point, also in Org-mode file.
22609 This changes the line at point, all other lines in the agenda referring to
22610 the same tree node, and the headline of the tree node in the Org-mode file."
22611 (interactive)
22612 (org-agenda-check-no-diary)
22613 (let* ((marker (or (get-text-property (point) 'org-marker)
22614 (org-agenda-error)))
22615 (hdmarker (get-text-property (point) 'org-hd-marker))
22616 (buffer (marker-buffer hdmarker))
22617 (pos (marker-position hdmarker))
22618 (inhibit-read-only t)
22619 newhead)
22620 (org-with-remote-undo buffer
22621 (with-current-buffer buffer
22622 (widen)
22623 (goto-char pos)
22624 (org-show-context 'agenda)
22625 (save-excursion
22626 (and (outline-next-heading)
22627 (org-flag-heading nil))) ; show the next heading
22628 (funcall 'org-priority force-direction)
22629 (end-of-line 1)
22630 (setq newhead (org-get-heading)))
22631 (org-agenda-change-all-lines newhead hdmarker)
22632 (beginning-of-line 1))))
22634 (defun org-get-tags-at (&optional pos)
22635 "Get a list of all headline tags applicable at POS.
22636 POS defaults to point. If tags are inherited, the list contains
22637 the targets in the same sequence as the headlines appear, i.e.
22638 the tags of the current headline come last."
22639 (interactive)
22640 (let (tags lastpos)
22641 (save-excursion
22642 (save-restriction
22643 (widen)
22644 (goto-char (or pos (point)))
22645 (save-match-data
22646 (org-back-to-heading t)
22647 (condition-case nil
22648 (while (not (equal lastpos (point)))
22649 (setq lastpos (point))
22650 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22651 (setq tags (append (org-split-string
22652 (org-match-string-no-properties 1) ":")
22653 tags)))
22654 (or org-use-tag-inheritance (error ""))
22655 (org-up-heading-all 1))
22656 (error nil))))
22657 tags)))
22659 ;; FIXME: should fix the tags property of the agenda line.
22660 (defun org-agenda-set-tags ()
22661 "Set tags for the current headline."
22662 (interactive)
22663 (org-agenda-check-no-diary)
22664 (if (and (org-region-active-p) (interactive-p))
22665 (call-interactively 'org-change-tag-in-region)
22666 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22667 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22668 (org-agenda-error)))
22669 (buffer (marker-buffer hdmarker))
22670 (pos (marker-position hdmarker))
22671 (inhibit-read-only t)
22672 newhead)
22673 (org-with-remote-undo buffer
22674 (with-current-buffer buffer
22675 (widen)
22676 (goto-char pos)
22677 (save-excursion
22678 (org-show-context 'agenda))
22679 (save-excursion
22680 (and (outline-next-heading)
22681 (org-flag-heading nil))) ; show the next heading
22682 (goto-char pos)
22683 (call-interactively 'org-set-tags)
22684 (end-of-line 1)
22685 (setq newhead (org-get-heading)))
22686 (org-agenda-change-all-lines newhead hdmarker)
22687 (beginning-of-line 1)))))
22689 (defun org-agenda-toggle-archive-tag ()
22690 "Toggle the archive tag for the current entry."
22691 (interactive)
22692 (org-agenda-check-no-diary)
22693 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22694 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22695 (org-agenda-error)))
22696 (buffer (marker-buffer hdmarker))
22697 (pos (marker-position hdmarker))
22698 (inhibit-read-only t)
22699 newhead)
22700 (org-with-remote-undo buffer
22701 (with-current-buffer buffer
22702 (widen)
22703 (goto-char pos)
22704 (org-show-context 'agenda)
22705 (save-excursion
22706 (and (outline-next-heading)
22707 (org-flag-heading nil))) ; show the next heading
22708 (call-interactively 'org-toggle-archive-tag)
22709 (end-of-line 1)
22710 (setq newhead (org-get-heading)))
22711 (org-agenda-change-all-lines newhead hdmarker)
22712 (beginning-of-line 1))))
22714 (defun org-agenda-date-later (arg &optional what)
22715 "Change the date of this item to one day later."
22716 (interactive "p")
22717 (org-agenda-check-type t 'agenda 'timeline)
22718 (org-agenda-check-no-diary)
22719 (let* ((marker (or (get-text-property (point) 'org-marker)
22720 (org-agenda-error)))
22721 (buffer (marker-buffer marker))
22722 (pos (marker-position marker)))
22723 (org-with-remote-undo buffer
22724 (with-current-buffer buffer
22725 (widen)
22726 (goto-char pos)
22727 (if (not (org-at-timestamp-p))
22728 (error "Cannot find time stamp"))
22729 (org-timestamp-change arg (or what 'day)))
22730 (org-agenda-show-new-time marker org-last-changed-timestamp))
22731 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22733 (defun org-agenda-date-earlier (arg &optional what)
22734 "Change the date of this item to one day earlier."
22735 (interactive "p")
22736 (org-agenda-date-later (- arg) what))
22738 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22739 "Show new date stamp via text properties."
22740 ;; We use text properties to make this undoable
22741 (let ((inhibit-read-only t))
22742 (setq stamp (concat " " prefix " => " stamp))
22743 (save-excursion
22744 (goto-char (point-max))
22745 (while (not (bobp))
22746 (when (equal marker (get-text-property (point) 'org-marker))
22747 (move-to-column (- (window-width) (length stamp)) t)
22748 (if (featurep 'xemacs)
22749 ;; Use `duplicable' property to trigger undo recording
22750 (let ((ex (make-extent nil nil))
22751 (gl (make-glyph stamp)))
22752 (set-glyph-face gl 'secondary-selection)
22753 (set-extent-properties
22754 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22755 (insert-extent ex (1- (point)) (point-at-eol)))
22756 (add-text-properties
22757 (1- (point)) (point-at-eol)
22758 (list 'display (org-add-props stamp nil
22759 'face 'secondary-selection))))
22760 (beginning-of-line 1))
22761 (beginning-of-line 0)))))
22763 (defun org-agenda-date-prompt (arg)
22764 "Change the date of this item. Date is prompted for, with default today.
22765 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22766 be used to request time specification in the time stamp."
22767 (interactive "P")
22768 (org-agenda-check-type t 'agenda 'timeline)
22769 (org-agenda-check-no-diary)
22770 (let* ((marker (or (get-text-property (point) 'org-marker)
22771 (org-agenda-error)))
22772 (buffer (marker-buffer marker))
22773 (pos (marker-position marker)))
22774 (org-with-remote-undo buffer
22775 (with-current-buffer buffer
22776 (widen)
22777 (goto-char pos)
22778 (if (not (org-at-timestamp-p))
22779 (error "Cannot find time stamp"))
22780 (org-time-stamp arg)
22781 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22783 (defun org-agenda-schedule (arg)
22784 "Schedule the item at point."
22785 (interactive "P")
22786 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22787 (org-agenda-check-no-diary)
22788 (let* ((marker (or (get-text-property (point) 'org-marker)
22789 (org-agenda-error)))
22790 (buffer (marker-buffer marker))
22791 (pos (marker-position marker))
22792 (org-insert-labeled-timestamps-at-point nil)
22794 (org-with-remote-undo buffer
22795 (with-current-buffer buffer
22796 (widen)
22797 (goto-char pos)
22798 (setq ts (org-schedule arg)))
22799 (org-agenda-show-new-time marker ts "S"))
22800 (message "Item scheduled for %s" ts)))
22802 (defun org-agenda-deadline (arg)
22803 "Schedule the item at point."
22804 (interactive "P")
22805 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22806 (org-agenda-check-no-diary)
22807 (let* ((marker (or (get-text-property (point) 'org-marker)
22808 (org-agenda-error)))
22809 (buffer (marker-buffer marker))
22810 (pos (marker-position marker))
22811 (org-insert-labeled-timestamps-at-point nil)
22813 (org-with-remote-undo buffer
22814 (with-current-buffer buffer
22815 (widen)
22816 (goto-char pos)
22817 (setq ts (org-deadline arg)))
22818 (org-agenda-show-new-time marker ts "S"))
22819 (message "Deadline for this item set to %s" ts)))
22821 (defun org-get-heading (&optional no-tags)
22822 "Return the heading of the current entry, without the stars."
22823 (save-excursion
22824 (org-back-to-heading t)
22825 (if (looking-at
22826 (if no-tags
22827 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22828 "\\*+[ \t]+\\([^\r\n]*\\)"))
22829 (match-string 1) "")))
22831 (defun org-agenda-clock-in (&optional arg)
22832 "Start the clock on the currently selected item."
22833 (interactive "P")
22834 (org-agenda-check-no-diary)
22835 (let* ((marker (or (get-text-property (point) 'org-marker)
22836 (org-agenda-error)))
22837 (pos (marker-position marker)))
22838 (org-with-remote-undo (marker-buffer marker)
22839 (with-current-buffer (marker-buffer marker)
22840 (widen)
22841 (goto-char pos)
22842 (org-clock-in)))))
22844 (defun org-agenda-clock-out (&optional arg)
22845 "Stop the currently running clock."
22846 (interactive "P")
22847 (unless (marker-buffer org-clock-marker)
22848 (error "No running clock"))
22849 (org-with-remote-undo (marker-buffer org-clock-marker)
22850 (org-clock-out)))
22852 (defun org-agenda-clock-cancel (&optional arg)
22853 "Cancel the currently running clock."
22854 (interactive "P")
22855 (unless (marker-buffer org-clock-marker)
22856 (error "No running clock"))
22857 (org-with-remote-undo (marker-buffer org-clock-marker)
22858 (org-clock-cancel)))
22860 (defun org-agenda-diary-entry ()
22861 "Make a diary entry, like the `i' command from the calendar.
22862 All the standard commands work: block, weekly etc."
22863 (interactive)
22864 (org-agenda-check-type t 'agenda 'timeline)
22865 (require 'diary-lib)
22866 (let* ((char (progn
22867 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
22868 (read-char-exclusive)))
22869 (cmd (cdr (assoc char
22870 '((?d . insert-diary-entry)
22871 (?w . insert-weekly-diary-entry)
22872 (?m . insert-monthly-diary-entry)
22873 (?y . insert-yearly-diary-entry)
22874 (?a . insert-anniversary-diary-entry)
22875 (?b . insert-block-diary-entry)
22876 (?c . insert-cyclic-diary-entry)))))
22877 (oldf (symbol-function 'calendar-cursor-to-date))
22878 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
22879 (point (point))
22880 (mark (or (mark t) (point))))
22881 (unless cmd
22882 (error "No command associated with <%c>" char))
22883 (unless (and (get-text-property point 'day)
22884 (or (not (equal ?b char))
22885 (get-text-property mark 'day)))
22886 (error "Don't know which date to use for diary entry"))
22887 ;; We implement this by hacking the `calendar-cursor-to-date' function
22888 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
22889 (let ((calendar-mark-ring
22890 (list (calendar-gregorian-from-absolute
22891 (or (get-text-property mark 'day)
22892 (get-text-property point 'day))))))
22893 (unwind-protect
22894 (progn
22895 (fset 'calendar-cursor-to-date
22896 (lambda (&optional error)
22897 (calendar-gregorian-from-absolute
22898 (get-text-property point 'day))))
22899 (call-interactively cmd))
22900 (fset 'calendar-cursor-to-date oldf)))))
22903 (defun org-agenda-execute-calendar-command (cmd)
22904 "Execute a calendar command from the agenda, with the date associated to
22905 the cursor position."
22906 (org-agenda-check-type t 'agenda 'timeline)
22907 (require 'diary-lib)
22908 (unless (get-text-property (point) 'day)
22909 (error "Don't know which date to use for calendar command"))
22910 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
22911 (point (point))
22912 (date (calendar-gregorian-from-absolute
22913 (get-text-property point 'day)))
22914 ;; the following 3 vars are needed in the calendar
22915 (displayed-day (extract-calendar-day date))
22916 (displayed-month (extract-calendar-month date))
22917 (displayed-year (extract-calendar-year date)))
22918 (unwind-protect
22919 (progn
22920 (fset 'calendar-cursor-to-date
22921 (lambda (&optional error)
22922 (calendar-gregorian-from-absolute
22923 (get-text-property point 'day))))
22924 (call-interactively cmd))
22925 (fset 'calendar-cursor-to-date oldf))))
22927 (defun org-agenda-phases-of-moon ()
22928 "Display the phases of the moon for the 3 months around the cursor date."
22929 (interactive)
22930 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
22932 (defun org-agenda-holidays ()
22933 "Display the holidays for the 3 months around the cursor date."
22934 (interactive)
22935 (org-agenda-execute-calendar-command 'list-calendar-holidays))
22937 (defun org-agenda-sunrise-sunset (arg)
22938 "Display sunrise and sunset for the cursor date.
22939 Latitude and longitude can be specified with the variables
22940 `calendar-latitude' and `calendar-longitude'. When called with prefix
22941 argument, latitude and longitude will be prompted for."
22942 (interactive "P")
22943 (let ((calendar-longitude (if arg nil calendar-longitude))
22944 (calendar-latitude (if arg nil calendar-latitude))
22945 (calendar-location-name
22946 (if arg "the given coordinates" calendar-location-name)))
22947 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
22949 (defun org-agenda-goto-calendar ()
22950 "Open the Emacs calendar with the date at the cursor."
22951 (interactive)
22952 (org-agenda-check-type t 'agenda 'timeline)
22953 (let* ((day (or (get-text-property (point) 'day)
22954 (error "Don't know which date to open in calendar")))
22955 (date (calendar-gregorian-from-absolute day))
22956 (calendar-move-hook nil)
22957 (view-calendar-holidays-initially nil)
22958 (view-diary-entries-initially nil))
22959 (calendar)
22960 (calendar-goto-date date)))
22962 (defun org-calendar-goto-agenda ()
22963 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
22964 This is a command that has to be installed in `calendar-mode-map'."
22965 (interactive)
22966 (org-agenda-list nil (calendar-absolute-from-gregorian
22967 (calendar-cursor-to-date))
22968 nil))
22970 (defun org-agenda-convert-date ()
22971 (interactive)
22972 (org-agenda-check-type t 'agenda 'timeline)
22973 (let ((day (get-text-property (point) 'day))
22974 date s)
22975 (unless day
22976 (error "Don't know which date to convert"))
22977 (setq date (calendar-gregorian-from-absolute day))
22978 (setq s (concat
22979 "Gregorian: " (calendar-date-string date) "\n"
22980 "ISO: " (calendar-iso-date-string date) "\n"
22981 "Day of Yr: " (calendar-day-of-year-string date) "\n"
22982 "Julian: " (calendar-julian-date-string date) "\n"
22983 "Astron. JD: " (calendar-astro-date-string date)
22984 " (Julian date number at noon UTC)\n"
22985 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
22986 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
22987 "French: " (calendar-french-date-string date) "\n"
22988 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
22989 "Mayan: " (calendar-mayan-date-string date) "\n"
22990 "Coptic: " (calendar-coptic-date-string date) "\n"
22991 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
22992 "Persian: " (calendar-persian-date-string date) "\n"
22993 "Chinese: " (calendar-chinese-date-string date) "\n"))
22994 (with-output-to-temp-buffer "*Dates*"
22995 (princ s))
22996 (if (fboundp 'fit-window-to-buffer)
22997 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23000 ;;;; Embedded LaTeX
23002 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23003 "Keymap for the minor `org-cdlatex-mode'.")
23005 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23006 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23007 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23008 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23009 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23011 (defvar org-cdlatex-texmathp-advice-is-done nil
23012 "Flag remembering if we have applied the advice to texmathp already.")
23014 (define-minor-mode org-cdlatex-mode
23015 "Toggle the minor `org-cdlatex-mode'.
23016 This mode supports entering LaTeX environment and math in LaTeX fragments
23017 in Org-mode.
23018 \\{org-cdlatex-mode-map}"
23019 nil " OCDL" nil
23020 (when org-cdlatex-mode (require 'cdlatex))
23021 (unless org-cdlatex-texmathp-advice-is-done
23022 (setq org-cdlatex-texmathp-advice-is-done t)
23023 (defadvice texmathp (around org-math-always-on activate)
23024 "Always return t in org-mode buffers.
23025 This is because we want to insert math symbols without dollars even outside
23026 the LaTeX math segments. If Orgmode thinks that point is actually inside
23027 en embedded LaTeX fragement, let texmathp do its job.
23028 \\[org-cdlatex-mode-map]"
23029 (interactive)
23030 (let (p)
23031 (cond
23032 ((not (org-mode-p)) ad-do-it)
23033 ((eq this-command 'cdlatex-math-symbol)
23034 (setq ad-return-value t
23035 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23037 (let ((p (org-inside-LaTeX-fragment-p)))
23038 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23039 (setq ad-return-value t
23040 texmathp-why '("Org-mode embedded math" . 0))
23041 (if p ad-do-it)))))))))
23043 (defun turn-on-org-cdlatex ()
23044 "Unconditionally turn on `org-cdlatex-mode'."
23045 (org-cdlatex-mode 1))
23047 (defun org-inside-LaTeX-fragment-p ()
23048 "Test if point is inside a LaTeX fragment.
23049 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23050 sequence appearing also before point.
23051 Even though the matchers for math are configurable, this function assumes
23052 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23053 delimiters are skipped when they have been removed by customization.
23054 The return value is nil, or a cons cell with the delimiter and
23055 and the position of this delimiter.
23057 This function does a reasonably good job, but can locally be fooled by
23058 for example currency specifications. For example it will assume being in
23059 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23060 fragments that are properly closed, but during editing, we have to live
23061 with the uncertainty caused by missing closing delimiters. This function
23062 looks only before point, not after."
23063 (catch 'exit
23064 (let ((pos (point))
23065 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23066 (lim (progn
23067 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23068 (point)))
23069 dd-on str (start 0) m re)
23070 (goto-char pos)
23071 (when dodollar
23072 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23073 re (nth 1 (assoc "$" org-latex-regexps)))
23074 (while (string-match re str start)
23075 (cond
23076 ((= (match-end 0) (length str))
23077 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23078 ((= (match-end 0) (- (length str) 5))
23079 (throw 'exit nil))
23080 (t (setq start (match-end 0))))))
23081 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23082 (goto-char pos)
23083 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23084 (and (match-beginning 2) (throw 'exit nil))
23085 ;; count $$
23086 (while (re-search-backward "\\$\\$" lim t)
23087 (setq dd-on (not dd-on)))
23088 (goto-char pos)
23089 (if dd-on (cons "$$" m))))))
23092 (defun org-try-cdlatex-tab ()
23093 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23094 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23095 - inside a LaTeX fragment, or
23096 - after the first word in a line, where an abbreviation expansion could
23097 insert a LaTeX environment."
23098 (when org-cdlatex-mode
23099 (cond
23100 ((save-excursion
23101 (skip-chars-backward "a-zA-Z0-9*")
23102 (skip-chars-backward " \t")
23103 (bolp))
23104 (cdlatex-tab) t)
23105 ((org-inside-LaTeX-fragment-p)
23106 (cdlatex-tab) t)
23107 (t nil))))
23109 (defun org-cdlatex-underscore-caret (&optional arg)
23110 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23111 Revert to the normal definition outside of these fragments."
23112 (interactive "P")
23113 (if (org-inside-LaTeX-fragment-p)
23114 (call-interactively 'cdlatex-sub-superscript)
23115 (let (org-cdlatex-mode)
23116 (call-interactively (key-binding (vector last-input-event))))))
23118 (defun org-cdlatex-math-modify (&optional arg)
23119 "Execute `cdlatex-math-modify' in LaTeX fragments.
23120 Revert to the normal definition outside of these fragments."
23121 (interactive "P")
23122 (if (org-inside-LaTeX-fragment-p)
23123 (call-interactively 'cdlatex-math-modify)
23124 (let (org-cdlatex-mode)
23125 (call-interactively (key-binding (vector last-input-event))))))
23127 (defvar org-latex-fragment-image-overlays nil
23128 "List of overlays carrying the images of latex fragments.")
23129 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23131 (defun org-remove-latex-fragment-image-overlays ()
23132 "Remove all overlays with LaTeX fragment images in current buffer."
23133 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23134 (setq org-latex-fragment-image-overlays nil))
23136 (defun org-preview-latex-fragment (&optional subtree)
23137 "Preview the LaTeX fragment at point, or all locally or globally.
23138 If the cursor is in a LaTeX fragment, create the image and overlay
23139 it over the source code. If there is no fragment at point, display
23140 all fragments in the current text, from one headline to the next. With
23141 prefix SUBTREE, display all fragments in the current subtree. With a
23142 double prefix `C-u C-u', or when the cursor is before the first headline,
23143 display all fragments in the buffer.
23144 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23145 (interactive "P")
23146 (org-remove-latex-fragment-image-overlays)
23147 (save-excursion
23148 (save-restriction
23149 (let (beg end at msg)
23150 (cond
23151 ((or (equal subtree '(16))
23152 (not (save-excursion
23153 (re-search-backward (concat "^" outline-regexp) nil t))))
23154 (setq beg (point-min) end (point-max)
23155 msg "Creating images for buffer...%s"))
23156 ((equal subtree '(4))
23157 (org-back-to-heading)
23158 (setq beg (point) end (org-end-of-subtree t)
23159 msg "Creating images for subtree...%s"))
23161 (if (setq at (org-inside-LaTeX-fragment-p))
23162 (goto-char (max (point-min) (- (cdr at) 2)))
23163 (org-back-to-heading))
23164 (setq beg (point) end (progn (outline-next-heading) (point))
23165 msg (if at "Creating image...%s"
23166 "Creating images for entry...%s"))))
23167 (message msg "")
23168 (narrow-to-region beg end)
23169 (goto-char beg)
23170 (org-format-latex
23171 (concat "ltxpng/" (file-name-sans-extension
23172 (file-name-nondirectory
23173 buffer-file-name)))
23174 default-directory 'overlays msg at 'forbuffer)
23175 (message msg "done. Use `C-c C-c' to remove images.")))))
23177 (defvar org-latex-regexps
23178 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23179 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23180 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23181 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23182 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23183 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23184 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23185 "Regular expressions for matching embedded LaTeX.")
23187 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23188 "Replace LaTeX fragments with links to an image, and produce images."
23189 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23190 (let* ((prefixnodir (file-name-nondirectory prefix))
23191 (absprefix (expand-file-name prefix dir))
23192 (todir (file-name-directory absprefix))
23193 (opt org-format-latex-options)
23194 (matchers (plist-get opt :matchers))
23195 (re-list org-latex-regexps)
23196 (cnt 0) txt link beg end re e checkdir
23197 m n block linkfile movefile ov)
23198 ;; Check if there are old images files with this prefix, and remove them
23199 (when (file-directory-p todir)
23200 (mapc 'delete-file
23201 (directory-files
23202 todir 'full
23203 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23204 ;; Check the different regular expressions
23205 (while (setq e (pop re-list))
23206 (setq m (car e) re (nth 1 e) n (nth 2 e)
23207 block (if (nth 3 e) "\n\n" ""))
23208 (when (member m matchers)
23209 (goto-char (point-min))
23210 (while (re-search-forward re nil t)
23211 (when (or (not at) (equal (cdr at) (match-beginning n)))
23212 (setq txt (match-string n)
23213 beg (match-beginning n) end (match-end n)
23214 cnt (1+ cnt)
23215 linkfile (format "%s_%04d.png" prefix cnt)
23216 movefile (format "%s_%04d.png" absprefix cnt)
23217 link (concat block "[[file:" linkfile "]]" block))
23218 (if msg (message msg cnt))
23219 (goto-char beg)
23220 (unless checkdir ; make sure the directory exists
23221 (setq checkdir t)
23222 (or (file-directory-p todir) (make-directory todir)))
23223 (org-create-formula-image
23224 txt movefile opt forbuffer)
23225 (if overlays
23226 (progn
23227 (setq ov (org-make-overlay beg end))
23228 (if (featurep 'xemacs)
23229 (progn
23230 (org-overlay-put ov 'invisible t)
23231 (org-overlay-put
23232 ov 'end-glyph
23233 (make-glyph (vector 'png :file movefile))))
23234 (org-overlay-put
23235 ov 'display
23236 (list 'image :type 'png :file movefile :ascent 'center)))
23237 (push ov org-latex-fragment-image-overlays)
23238 (goto-char end))
23239 (delete-region beg end)
23240 (insert link))))))))
23242 ;; This function borrows from Ganesh Swami's latex2png.el
23243 (defun org-create-formula-image (string tofile options buffer)
23244 (let* ((tmpdir (if (featurep 'xemacs)
23245 (temp-directory)
23246 temporary-file-directory))
23247 (texfilebase (make-temp-name
23248 (expand-file-name "orgtex" tmpdir)))
23249 (texfile (concat texfilebase ".tex"))
23250 (dvifile (concat texfilebase ".dvi"))
23251 (pngfile (concat texfilebase ".png"))
23252 (fnh (face-attribute 'default :height nil))
23253 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23254 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23255 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23256 "Black"))
23257 (bg (or (plist-get options (if buffer :background :html-background))
23258 "Transparent")))
23259 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23260 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23261 (with-temp-file texfile
23262 (insert org-format-latex-header
23263 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23264 (let ((dir default-directory))
23265 (condition-case nil
23266 (progn
23267 (cd tmpdir)
23268 (call-process "latex" nil nil nil texfile))
23269 (error nil))
23270 (cd dir))
23271 (if (not (file-exists-p dvifile))
23272 (progn (message "Failed to create dvi file from %s" texfile) nil)
23273 (call-process "dvipng" nil nil nil
23274 "-E" "-fg" fg "-bg" bg
23275 "-D" dpi
23276 ;;"-x" scale "-y" scale
23277 "-T" "tight"
23278 "-o" pngfile
23279 dvifile)
23280 (if (not (file-exists-p pngfile))
23281 (progn (message "Failed to create png file from %s" texfile) nil)
23282 ;; Use the requested file name and clean up
23283 (copy-file pngfile tofile 'replace)
23284 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23285 (delete-file (concat texfilebase e)))
23286 pngfile))))
23288 (defun org-dvipng-color (attr)
23289 "Return an rgb color specification for dvipng."
23290 (apply 'format "rgb %s %s %s"
23291 (mapcar 'org-normalize-color
23292 (color-values (face-attribute 'default attr nil)))))
23294 (defun org-normalize-color (value)
23295 "Return string to be used as color value for an RGB component."
23296 (format "%g" (/ value 65535.0)))
23298 ;;;; Exporting
23300 ;;; Variables, constants, and parameter plists
23302 (defconst org-level-max 20)
23304 (defvar org-export-html-preamble nil
23305 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23306 (defvar org-export-html-postamble nil
23307 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23308 (defvar org-export-html-auto-preamble t
23309 "Should default preamble be inserted? Set by publishing functions.")
23310 (defvar org-export-html-auto-postamble t
23311 "Should default postamble be inserted? Set by publishing functions.")
23312 (defvar org-current-export-file nil) ; dynamically scoped parameter
23313 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23316 (defconst org-export-plist-vars
23317 '((:language . org-export-default-language)
23318 (:customtime . org-display-custom-times)
23319 (:headline-levels . org-export-headline-levels)
23320 (:section-numbers . org-export-with-section-numbers)
23321 (:table-of-contents . org-export-with-toc)
23322 (:preserve-breaks . org-export-preserve-breaks)
23323 (:archived-trees . org-export-with-archived-trees)
23324 (:emphasize . org-export-with-emphasize)
23325 (:sub-superscript . org-export-with-sub-superscripts)
23326 (:special-strings . org-export-with-special-strings)
23327 (:footnotes . org-export-with-footnotes)
23328 (:drawers . org-export-with-drawers)
23329 (:tags . org-export-with-tags)
23330 (:TeX-macros . org-export-with-TeX-macros)
23331 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23332 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23333 (:fixed-width . org-export-with-fixed-width)
23334 (:timestamps . org-export-with-timestamps)
23335 (:author-info . org-export-author-info)
23336 (:time-stamp-file . org-export-time-stamp-file)
23337 (:tables . org-export-with-tables)
23338 (:table-auto-headline . org-export-highlight-first-table-line)
23339 (:style . org-export-html-style)
23340 (:agenda-style . org-agenda-export-html-style)
23341 (:convert-org-links . org-export-html-link-org-files-as-html)
23342 (:inline-images . org-export-html-inline-images)
23343 (:html-extension . org-export-html-extension)
23344 (:html-table-tag . org-export-html-table-tag)
23345 (:expand-quoted-html . org-export-html-expand)
23346 (:timestamp . org-export-html-with-timestamp)
23347 (:publishing-directory . org-export-publishing-directory)
23348 (:preamble . org-export-html-preamble)
23349 (:postamble . org-export-html-postamble)
23350 (:auto-preamble . org-export-html-auto-preamble)
23351 (:auto-postamble . org-export-html-auto-postamble)
23352 (:author . user-full-name)
23353 (:email . user-mail-address)))
23355 (defun org-default-export-plist ()
23356 "Return the property list with default settings for the export variables."
23357 (let ((l org-export-plist-vars) rtn e)
23358 (while (setq e (pop l))
23359 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23360 rtn))
23362 (defun org-infile-export-plist ()
23363 "Return the property list with file-local settings for export."
23364 (save-excursion
23365 (save-restriction
23366 (widen)
23367 (goto-char 0)
23368 (let ((re (org-make-options-regexp
23369 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23370 p key val text options)
23371 (while (re-search-forward re nil t)
23372 (setq key (org-match-string-no-properties 1)
23373 val (org-match-string-no-properties 2))
23374 (cond
23375 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23376 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23377 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23378 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23379 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23380 ((string-equal key "TEXT")
23381 (setq text (if text (concat text "\n" val) val)))
23382 ((string-equal key "OPTIONS") (setq options val))))
23383 (setq p (plist-put p :text text))
23384 (when options
23385 (let ((op '(("H" . :headline-levels)
23386 ("num" . :section-numbers)
23387 ("toc" . :table-of-contents)
23388 ("\\n" . :preserve-breaks)
23389 ("@" . :expand-quoted-html)
23390 (":" . :fixed-width)
23391 ("|" . :tables)
23392 ("^" . :sub-superscript)
23393 ("-" . :special-strings)
23394 ("f" . :footnotes)
23395 ("d" . :drawers)
23396 ("tags" . :tags)
23397 ("*" . :emphasize)
23398 ("TeX" . :TeX-macros)
23399 ("LaTeX" . :LaTeX-fragments)
23400 ("skip" . :skip-before-1st-heading)
23401 ("author" . :author-info)
23402 ("timestamp" . :time-stamp-file)))
23404 (while (setq o (pop op))
23405 (if (string-match (concat (regexp-quote (car o))
23406 ":\\([^ \t\n\r;,.]*\\)")
23407 options)
23408 (setq p (plist-put p (cdr o)
23409 (car (read-from-string
23410 (match-string 1 options)))))))))
23411 p))))
23413 (defun org-export-directory (type plist)
23414 (let* ((val (plist-get plist :publishing-directory))
23415 (dir (if (listp val)
23416 (or (cdr (assoc type val)) ".")
23417 val)))
23418 dir))
23420 (defun org-skip-comments (lines)
23421 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23422 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23423 (re2 "^\\(\\*+\\)[ \t\n\r]")
23424 (case-fold-search nil)
23425 rtn line level)
23426 (while (setq line (pop lines))
23427 (cond
23428 ((and (string-match re1 line)
23429 (setq level (- (match-end 1) (match-beginning 1))))
23430 ;; Beginning of a COMMENT subtree. Skip it.
23431 (while (and (setq line (pop lines))
23432 (or (not (string-match re2 line))
23433 (> (- (match-end 1) (match-beginning 1)) level))))
23434 (setq lines (cons line lines)))
23435 ((string-match "^#" line)
23436 ;; an ordinary comment line
23438 ((and org-export-table-remove-special-lines
23439 (string-match "^[ \t]*|" line)
23440 (or (string-match "^[ \t]*| *[!_^] *|" line)
23441 (and (string-match "| *<[0-9]+> *|" line)
23442 (not (string-match "| *[^ <|]" line)))))
23443 ;; a special table line that should be removed
23445 (t (setq rtn (cons line rtn)))))
23446 (nreverse rtn)))
23448 (defun org-export (&optional arg)
23449 (interactive)
23450 (let ((help "[t] insert the export option template
23451 \[v] limit export to visible part of outline tree
23453 \[a] export as ASCII
23455 \[h] export as HTML
23456 \[H] export as HTML to temporary buffer
23457 \[R] export region as HTML
23458 \[b] export as HTML and browse immediately
23459 \[x] export as XOXO
23461 \[l] export as LaTeX
23462 \[L] export as LaTeX to temporary buffer
23464 \[i] export current file as iCalendar file
23465 \[I] export all agenda files as iCalendar files
23466 \[c] export agenda files into combined iCalendar file
23468 \[F] publish current file
23469 \[P] publish current project
23470 \[X] publish... (project will be prompted for)
23471 \[A] publish all projects")
23472 (cmds
23473 '((?t . org-insert-export-options-template)
23474 (?v . org-export-visible)
23475 (?a . org-export-as-ascii)
23476 (?h . org-export-as-html)
23477 (?b . org-export-as-html-and-open)
23478 (?H . org-export-as-html-to-buffer)
23479 (?R . org-export-region-as-html)
23480 (?x . org-export-as-xoxo)
23481 (?l . org-export-as-latex)
23482 (?L . org-export-as-latex-to-buffer)
23483 (?i . org-export-icalendar-this-file)
23484 (?I . org-export-icalendar-all-agenda-files)
23485 (?c . org-export-icalendar-combine-agenda-files)
23486 (?F . org-publish-current-file)
23487 (?P . org-publish-current-project)
23488 (?X . org-publish)
23489 (?A . org-publish-all)))
23490 r1 r2 ass)
23491 (save-window-excursion
23492 (delete-other-windows)
23493 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23494 (princ help))
23495 (message "Select command: ")
23496 (setq r1 (read-char-exclusive)))
23497 (setq r2 (if (< r1 27) (+ r1 96) r1))
23498 (if (setq ass (assq r2 cmds))
23499 (call-interactively (cdr ass))
23500 (error "No command associated with key %c" r1))))
23502 (defconst org-html-entities
23503 '(("nbsp")
23504 ("iexcl")
23505 ("cent")
23506 ("pound")
23507 ("curren")
23508 ("yen")
23509 ("brvbar")
23510 ("vert" . "&#124;")
23511 ("sect")
23512 ("uml")
23513 ("copy")
23514 ("ordf")
23515 ("laquo")
23516 ("not")
23517 ("shy")
23518 ("reg")
23519 ("macr")
23520 ("deg")
23521 ("plusmn")
23522 ("sup2")
23523 ("sup3")
23524 ("acute")
23525 ("micro")
23526 ("para")
23527 ("middot")
23528 ("odot"."o")
23529 ("star"."*")
23530 ("cedil")
23531 ("sup1")
23532 ("ordm")
23533 ("raquo")
23534 ("frac14")
23535 ("frac12")
23536 ("frac34")
23537 ("iquest")
23538 ("Agrave")
23539 ("Aacute")
23540 ("Acirc")
23541 ("Atilde")
23542 ("Auml")
23543 ("Aring") ("AA"."&Aring;")
23544 ("AElig")
23545 ("Ccedil")
23546 ("Egrave")
23547 ("Eacute")
23548 ("Ecirc")
23549 ("Euml")
23550 ("Igrave")
23551 ("Iacute")
23552 ("Icirc")
23553 ("Iuml")
23554 ("ETH")
23555 ("Ntilde")
23556 ("Ograve")
23557 ("Oacute")
23558 ("Ocirc")
23559 ("Otilde")
23560 ("Ouml")
23561 ("times")
23562 ("Oslash")
23563 ("Ugrave")
23564 ("Uacute")
23565 ("Ucirc")
23566 ("Uuml")
23567 ("Yacute")
23568 ("THORN")
23569 ("szlig")
23570 ("agrave")
23571 ("aacute")
23572 ("acirc")
23573 ("atilde")
23574 ("auml")
23575 ("aring")
23576 ("aelig")
23577 ("ccedil")
23578 ("egrave")
23579 ("eacute")
23580 ("ecirc")
23581 ("euml")
23582 ("igrave")
23583 ("iacute")
23584 ("icirc")
23585 ("iuml")
23586 ("eth")
23587 ("ntilde")
23588 ("ograve")
23589 ("oacute")
23590 ("ocirc")
23591 ("otilde")
23592 ("ouml")
23593 ("divide")
23594 ("oslash")
23595 ("ugrave")
23596 ("uacute")
23597 ("ucirc")
23598 ("uuml")
23599 ("yacute")
23600 ("thorn")
23601 ("yuml")
23602 ("fnof")
23603 ("Alpha")
23604 ("Beta")
23605 ("Gamma")
23606 ("Delta")
23607 ("Epsilon")
23608 ("Zeta")
23609 ("Eta")
23610 ("Theta")
23611 ("Iota")
23612 ("Kappa")
23613 ("Lambda")
23614 ("Mu")
23615 ("Nu")
23616 ("Xi")
23617 ("Omicron")
23618 ("Pi")
23619 ("Rho")
23620 ("Sigma")
23621 ("Tau")
23622 ("Upsilon")
23623 ("Phi")
23624 ("Chi")
23625 ("Psi")
23626 ("Omega")
23627 ("alpha")
23628 ("beta")
23629 ("gamma")
23630 ("delta")
23631 ("epsilon")
23632 ("varepsilon"."&epsilon;")
23633 ("zeta")
23634 ("eta")
23635 ("theta")
23636 ("iota")
23637 ("kappa")
23638 ("lambda")
23639 ("mu")
23640 ("nu")
23641 ("xi")
23642 ("omicron")
23643 ("pi")
23644 ("rho")
23645 ("sigmaf") ("varsigma"."&sigmaf;")
23646 ("sigma")
23647 ("tau")
23648 ("upsilon")
23649 ("phi")
23650 ("chi")
23651 ("psi")
23652 ("omega")
23653 ("thetasym") ("vartheta"."&thetasym;")
23654 ("upsih")
23655 ("piv")
23656 ("bull") ("bullet"."&bull;")
23657 ("hellip") ("dots"."&hellip;")
23658 ("prime")
23659 ("Prime")
23660 ("oline")
23661 ("frasl")
23662 ("weierp")
23663 ("image")
23664 ("real")
23665 ("trade")
23666 ("alefsym")
23667 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23668 ("uarr") ("uparrow"."&uarr;")
23669 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23670 ("darr")("downarrow"."&darr;")
23671 ("harr") ("leftrightarrow"."&harr;")
23672 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23673 ("lArr") ("Leftarrow"."&lArr;")
23674 ("uArr") ("Uparrow"."&uArr;")
23675 ("rArr") ("Rightarrow"."&rArr;")
23676 ("dArr") ("Downarrow"."&dArr;")
23677 ("hArr") ("Leftrightarrow"."&hArr;")
23678 ("forall")
23679 ("part") ("partial"."&part;")
23680 ("exist") ("exists"."&exist;")
23681 ("empty") ("emptyset"."&empty;")
23682 ("nabla")
23683 ("isin") ("in"."&isin;")
23684 ("notin")
23685 ("ni")
23686 ("prod")
23687 ("sum")
23688 ("minus")
23689 ("lowast") ("ast"."&lowast;")
23690 ("radic")
23691 ("prop") ("proptp"."&prop;")
23692 ("infin") ("infty"."&infin;")
23693 ("ang") ("angle"."&ang;")
23694 ("and") ("wedge"."&and;")
23695 ("or") ("vee"."&or;")
23696 ("cap")
23697 ("cup")
23698 ("int")
23699 ("there4")
23700 ("sim")
23701 ("cong") ("simeq"."&cong;")
23702 ("asymp")("approx"."&asymp;")
23703 ("ne") ("neq"."&ne;")
23704 ("equiv")
23705 ("le")
23706 ("ge")
23707 ("sub") ("subset"."&sub;")
23708 ("sup") ("supset"."&sup;")
23709 ("nsub")
23710 ("sube")
23711 ("supe")
23712 ("oplus")
23713 ("otimes")
23714 ("perp")
23715 ("sdot") ("cdot"."&sdot;")
23716 ("lceil")
23717 ("rceil")
23718 ("lfloor")
23719 ("rfloor")
23720 ("lang")
23721 ("rang")
23722 ("loz") ("Diamond"."&loz;")
23723 ("spades") ("spadesuit"."&spades;")
23724 ("clubs") ("clubsuit"."&clubs;")
23725 ("hearts") ("diamondsuit"."&hearts;")
23726 ("diams") ("diamondsuit"."&diams;")
23727 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23728 ("quot")
23729 ("amp")
23730 ("lt")
23731 ("gt")
23732 ("OElig")
23733 ("oelig")
23734 ("Scaron")
23735 ("scaron")
23736 ("Yuml")
23737 ("circ")
23738 ("tilde")
23739 ("ensp")
23740 ("emsp")
23741 ("thinsp")
23742 ("zwnj")
23743 ("zwj")
23744 ("lrm")
23745 ("rlm")
23746 ("ndash")
23747 ("mdash")
23748 ("lsquo")
23749 ("rsquo")
23750 ("sbquo")
23751 ("ldquo")
23752 ("rdquo")
23753 ("bdquo")
23754 ("dagger")
23755 ("Dagger")
23756 ("permil")
23757 ("lsaquo")
23758 ("rsaquo")
23759 ("euro")
23761 ("arccos"."arccos")
23762 ("arcsin"."arcsin")
23763 ("arctan"."arctan")
23764 ("arg"."arg")
23765 ("cos"."cos")
23766 ("cosh"."cosh")
23767 ("cot"."cot")
23768 ("coth"."coth")
23769 ("csc"."csc")
23770 ("deg"."deg")
23771 ("det"."det")
23772 ("dim"."dim")
23773 ("exp"."exp")
23774 ("gcd"."gcd")
23775 ("hom"."hom")
23776 ("inf"."inf")
23777 ("ker"."ker")
23778 ("lg"."lg")
23779 ("lim"."lim")
23780 ("liminf"."liminf")
23781 ("limsup"."limsup")
23782 ("ln"."ln")
23783 ("log"."log")
23784 ("max"."max")
23785 ("min"."min")
23786 ("Pr"."Pr")
23787 ("sec"."sec")
23788 ("sin"."sin")
23789 ("sinh"."sinh")
23790 ("sup"."sup")
23791 ("tan"."tan")
23792 ("tanh"."tanh")
23794 "Entities for TeX->HTML translation.
23795 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23796 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23797 In that case, \"\\ent\" will be translated to \"&other;\".
23798 The list contains HTML entities for Latin-1, Greek and other symbols.
23799 It is supplemented by a number of commonly used TeX macros with appropriate
23800 translations. There is currently no way for users to extend this.")
23802 ;;; General functions for all backends
23804 (defun org-cleaned-string-for-export (string &rest parameters)
23805 "Cleanup a buffer STRING so that links can be created safely."
23806 (interactive)
23807 (let* ((re-radio (and org-target-link-regexp
23808 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23809 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23810 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23811 (re-archive (concat ":" org-archive-tag ":"))
23812 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23813 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23814 (htmlp (plist-get parameters :for-html))
23815 (asciip (plist-get parameters :for-ascii))
23816 (latexp (plist-get parameters :for-LaTeX))
23817 (commentsp (plist-get parameters :comments))
23818 (archived-trees (plist-get parameters :archived-trees))
23819 (inhibit-read-only t)
23820 (drawers org-drawers)
23821 (exp-drawers (plist-get parameters :drawers))
23822 (outline-regexp "\\*+ ")
23823 a b xx
23824 rtn p)
23825 (with-current-buffer (get-buffer-create " org-mode-tmp")
23826 (erase-buffer)
23827 (insert string)
23828 ;; Remove license-to-kill stuff
23829 (while (setq p (text-property-any (point-min) (point-max)
23830 :org-license-to-kill t))
23831 (delete-region p (next-single-property-change p :org-license-to-kill)))
23833 (let ((org-inhibit-startup t)) (org-mode))
23834 (untabify (point-min) (point-max))
23836 ;; Get the correct stuff before the first headline
23837 (when (plist-get parameters :skip-before-1st-heading)
23838 (goto-char (point-min))
23839 (when (re-search-forward "^\\*+[ \t]" nil t)
23840 (delete-region (point-min) (match-beginning 0))
23841 (goto-char (point-min))
23842 (insert "\n")))
23843 (when (plist-get parameters :add-text)
23844 (goto-char (point-min))
23845 (insert (plist-get parameters :add-text) "\n"))
23847 ;; Get rid of archived trees
23848 (when (not (eq archived-trees t))
23849 (goto-char (point-min))
23850 (while (re-search-forward re-archive nil t)
23851 (if (not (org-on-heading-p t))
23852 (org-end-of-subtree t)
23853 (beginning-of-line 1)
23854 (setq a (if archived-trees
23855 (1+ (point-at-eol)) (point))
23856 b (org-end-of-subtree t))
23857 (if (> b a) (delete-region a b)))))
23859 ;; Get rid of drawers
23860 (unless (eq t exp-drawers)
23861 (goto-char (point-min))
23862 (let ((re (concat "^[ \t]*:\\("
23863 (mapconcat
23864 'identity
23865 (org-delete-all exp-drawers
23866 (copy-sequence drawers))
23867 "\\|")
23868 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23869 (while (re-search-forward re nil t)
23870 (replace-match ""))))
23872 ;; Find targets in comments and move them out of comments,
23873 ;; but mark them as targets that should be invisible
23874 (goto-char (point-min))
23875 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
23876 (replace-match "\\1(INVISIBLE)"))
23878 ;; Protect backend specific stuff, throw away the others.
23879 (let ((formatters
23880 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
23881 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
23882 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
23883 fmt)
23884 (goto-char (point-min))
23885 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
23886 (goto-char (match-end 0))
23887 (while (not (looking-at "#\\+END_EXAMPLE"))
23888 (insert ": ")
23889 (beginning-of-line 2)))
23890 (goto-char (point-min))
23891 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
23892 (add-text-properties (match-beginning 0) (match-end 0)
23893 '(org-protected t)))
23894 (while formatters
23895 (setq fmt (pop formatters))
23896 (when (car fmt)
23897 (goto-char (point-min))
23898 (while (re-search-forward (concat "^#\\+" (cadr fmt)
23899 ":[ \t]*\\(.*\\)") nil t)
23900 (replace-match "\\1" t)
23901 (add-text-properties
23902 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
23903 '(org-protected t))))
23904 (goto-char (point-min))
23905 (while (re-search-forward
23906 (concat "^#\\+"
23907 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
23908 (cadddr fmt) "\\>.*\n?") nil t)
23909 (if (car fmt)
23910 (add-text-properties (match-beginning 1) (1+ (match-end 1))
23911 '(org-protected t))
23912 (delete-region (match-beginning 0) (match-end 0))))))
23914 ;; Protect quoted subtrees
23915 (goto-char (point-min))
23916 (while (re-search-forward re-quote nil t)
23917 (goto-char (match-beginning 0))
23918 (end-of-line 1)
23919 (add-text-properties (point) (org-end-of-subtree t)
23920 '(org-protected t)))
23922 ;; Protect verbatim elements
23923 (goto-char (point-min))
23924 (while (re-search-forward org-verbatim-re nil t)
23925 (add-text-properties (match-beginning 4) (match-end 4)
23926 '(org-protected t))
23927 (goto-char (1+ (match-end 4))))
23929 ;; Remove subtrees that are commented
23930 (goto-char (point-min))
23931 (while (re-search-forward re-commented nil t)
23932 (goto-char (match-beginning 0))
23933 (delete-region (point) (org-end-of-subtree t)))
23935 ;; Remove special table lines
23936 (when org-export-table-remove-special-lines
23937 (goto-char (point-min))
23938 (while (re-search-forward "^[ \t]*|" nil t)
23939 (beginning-of-line 1)
23940 (if (or (looking-at "[ \t]*| *[!_^] *|")
23941 (and (looking-at ".*?| *<[0-9]+> *|")
23942 (not (looking-at ".*?| *[^ <|]"))))
23943 (delete-region (max (point-min) (1- (point-at-bol)))
23944 (point-at-eol))
23945 (end-of-line 1))))
23947 ;; Specific LaTeX stuff
23948 (when latexp
23949 (require 'org-export-latex nil)
23950 (org-export-latex-cleaned-string))
23952 (when asciip
23953 (org-export-ascii-clean-string))
23955 ;; Specific HTML stuff
23956 (when htmlp
23957 ;; Convert LaTeX fragments to images
23958 (when (plist-get parameters :LaTeX-fragments)
23959 (org-format-latex
23960 (concat "ltxpng/" (file-name-sans-extension
23961 (file-name-nondirectory
23962 org-current-export-file)))
23963 org-current-export-dir nil "Creating LaTeX image %s"))
23964 (message "Exporting..."))
23966 ;; Remove or replace comments
23967 (goto-char (point-min))
23968 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
23969 (if commentsp
23970 (progn (add-text-properties
23971 (match-beginning 0) (match-end 0) '(org-protected t))
23972 (replace-match (format commentsp (match-string 1)) t t))
23973 (replace-match "")))
23975 ;; Find matches for radio targets and turn them into internal links
23976 (goto-char (point-min))
23977 (when re-radio
23978 (while (re-search-forward re-radio nil t)
23979 (org-if-unprotected
23980 (replace-match "\\1[[\\2]]"))))
23982 ;; Find all links that contain a newline and put them into a single line
23983 (goto-char (point-min))
23984 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
23985 (org-if-unprotected
23986 (replace-match "\\1 \\3")
23987 (goto-char (match-beginning 0))))
23990 ;; Normalize links: Convert angle and plain links into bracket links
23991 ;; Expand link abbreviations
23992 (goto-char (point-min))
23993 (while (re-search-forward re-plain-link nil t)
23994 (goto-char (1- (match-end 0)))
23995 (org-if-unprotected
23996 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23997 ":" (match-string 3) "]]")))
23998 ;; added 'org-link face to links
23999 (put-text-property 0 (length s) 'face 'org-link s)
24000 (replace-match s t t))))
24001 (goto-char (point-min))
24002 (while (re-search-forward re-angle-link nil t)
24003 (goto-char (1- (match-end 0)))
24004 (org-if-unprotected
24005 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24006 ":" (match-string 3) "]]")))
24007 (put-text-property 0 (length s) 'face 'org-link s)
24008 (replace-match s t t))))
24009 (goto-char (point-min))
24010 (while (re-search-forward org-bracket-link-regexp nil t)
24011 (org-if-unprotected
24012 (let* ((s (concat "[[" (setq xx (save-match-data
24013 (org-link-expand-abbrev (match-string 1))))
24015 (if (match-end 3)
24016 (match-string 2)
24017 (concat "[" xx "]"))
24018 "]")))
24019 (put-text-property 0 (length s) 'face 'org-link s)
24020 (replace-match s t t))))
24022 ;; Find multiline emphasis and put them into single line
24023 (when (plist-get parameters :emph-multiline)
24024 (goto-char (point-min))
24025 (while (re-search-forward org-emph-re nil t)
24026 (if (not (= (char-after (match-beginning 3))
24027 (char-after (match-beginning 4))))
24028 (org-if-unprotected
24029 (subst-char-in-region (match-beginning 0) (match-end 0)
24030 ?\n ?\ t)
24031 (goto-char (1- (match-end 0))))
24032 (goto-char (1+ (match-beginning 0))))))
24034 (setq rtn (buffer-string)))
24035 (kill-buffer " org-mode-tmp")
24036 rtn))
24038 (defun org-export-grab-title-from-buffer ()
24039 "Get a title for the current document, from looking at the buffer."
24040 (let ((inhibit-read-only t))
24041 (save-excursion
24042 (goto-char (point-min))
24043 (let ((end (save-excursion (outline-next-heading) (point))))
24044 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24045 ;; Mark the line so that it will not be exported as normal text.
24046 (org-unmodified
24047 (add-text-properties (match-beginning 0) (match-end 0)
24048 (list :org-license-to-kill t)))
24049 ;; Return the title string
24050 (org-trim (match-string 0)))))))
24052 (defun org-export-get-title-from-subtree ()
24053 "Return subtree title and exclude it from export."
24054 (let (title (m (mark)))
24055 (save-excursion
24056 (goto-char (region-beginning))
24057 (when (and (org-at-heading-p)
24058 (>= (org-end-of-subtree t t) (region-end)))
24059 ;; This is a subtree, we take the title from the first heading
24060 (goto-char (region-beginning))
24061 (looking-at org-todo-line-regexp)
24062 (setq title (match-string 3))
24063 (org-unmodified
24064 (add-text-properties (point) (1+ (point-at-eol))
24065 (list :org-license-to-kill t)))))
24066 title))
24068 (defun org-solidify-link-text (s &optional alist)
24069 "Take link text and make a safe target out of it."
24070 (save-match-data
24071 (let* ((rtn
24072 (mapconcat
24073 'identity
24074 (org-split-string s "[ \t\r\n]+") "--"))
24075 (a (assoc rtn alist)))
24076 (or (cdr a) rtn))))
24078 (defun org-get-min-level (lines)
24079 "Get the minimum level in LINES."
24080 (let ((re "^\\(\\*+\\) ") l min)
24081 (catch 'exit
24082 (while (setq l (pop lines))
24083 (if (string-match re l)
24084 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24085 1)))
24087 ;; Variable holding the vector with section numbers
24088 (defvar org-section-numbers (make-vector org-level-max 0))
24090 (defun org-init-section-numbers ()
24091 "Initialize the vector for the section numbers."
24092 (let* ((level -1)
24093 (numbers (nreverse (org-split-string "" "\\.")))
24094 (depth (1- (length org-section-numbers)))
24095 (i depth) number-string)
24096 (while (>= i 0)
24097 (if (> i level)
24098 (aset org-section-numbers i 0)
24099 (setq number-string (or (car numbers) "0"))
24100 (if (string-match "\\`[A-Z]\\'" number-string)
24101 (aset org-section-numbers i
24102 (- (string-to-char number-string) ?A -1))
24103 (aset org-section-numbers i (string-to-number number-string)))
24104 (pop numbers))
24105 (setq i (1- i)))))
24107 (defun org-section-number (&optional level)
24108 "Return a string with the current section number.
24109 When LEVEL is non-nil, increase section numbers on that level."
24110 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24111 (when level
24112 (when (> level -1)
24113 (aset org-section-numbers
24114 level (1+ (aref org-section-numbers level))))
24115 (setq idx (1+ level))
24116 (while (<= idx depth)
24117 (if (not (= idx 1))
24118 (aset org-section-numbers idx 0))
24119 (setq idx (1+ idx))))
24120 (setq idx 0)
24121 (while (<= idx depth)
24122 (setq n (aref org-section-numbers idx))
24123 (setq string (concat string (if (not (string= string "")) "." "")
24124 (int-to-string n)))
24125 (setq idx (1+ idx)))
24126 (save-match-data
24127 (if (string-match "\\`\\([@0]\\.\\)+" string)
24128 (setq string (replace-match "" t nil string)))
24129 (if (string-match "\\(\\.0\\)+\\'" string)
24130 (setq string (replace-match "" t nil string))))
24131 string))
24133 ;;; ASCII export
24135 (defvar org-last-level nil) ; dynamically scoped variable
24136 (defvar org-min-level nil) ; dynamically scoped variable
24137 (defvar org-levels-open nil) ; dynamically scoped parameter
24138 (defvar org-ascii-current-indentation nil) ; For communication
24140 (defun org-export-as-ascii (arg)
24141 "Export the outline as a pretty ASCII file.
24142 If there is an active region, export only the region.
24143 The prefix ARG specifies how many levels of the outline should become
24144 underlined headlines. The default is 3."
24145 (interactive "P")
24146 (setq-default org-todo-line-regexp org-todo-line-regexp)
24147 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24148 (org-infile-export-plist)))
24149 (region-p (org-region-active-p))
24150 (subtree-p
24151 (when region-p
24152 (save-excursion
24153 (goto-char (region-beginning))
24154 (and (org-at-heading-p)
24155 (>= (org-end-of-subtree t t) (region-end))))))
24156 (custom-times org-display-custom-times)
24157 (org-ascii-current-indentation '(0 . 0))
24158 (level 0) line txt
24159 (umax nil)
24160 (umax-toc nil)
24161 (case-fold-search nil)
24162 (filename (concat (file-name-as-directory
24163 (org-export-directory :ascii opt-plist))
24164 (file-name-sans-extension
24165 (or (and subtree-p
24166 (org-entry-get (region-beginning)
24167 "EXPORT_FILE_NAME" t))
24168 (file-name-nondirectory buffer-file-name)))
24169 ".txt"))
24170 (filename (if (equal (file-truename filename)
24171 (file-truename buffer-file-name))
24172 (concat filename ".txt")
24173 filename))
24174 (buffer (find-file-noselect filename))
24175 (org-levels-open (make-vector org-level-max nil))
24176 (odd org-odd-levels-only)
24177 (date (plist-get opt-plist :date))
24178 (author (plist-get opt-plist :author))
24179 (title (or (and subtree-p (org-export-get-title-from-subtree))
24180 (plist-get opt-plist :title)
24181 (and (not
24182 (plist-get opt-plist :skip-before-1st-heading))
24183 (org-export-grab-title-from-buffer))
24184 (file-name-sans-extension
24185 (file-name-nondirectory buffer-file-name))))
24186 (email (plist-get opt-plist :email))
24187 (language (plist-get opt-plist :language))
24188 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24189 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24190 (todo nil)
24191 (lang-words nil)
24192 (region
24193 (buffer-substring
24194 (if (org-region-active-p) (region-beginning) (point-min))
24195 (if (org-region-active-p) (region-end) (point-max))))
24196 (lines (org-split-string
24197 (org-cleaned-string-for-export
24198 region
24199 :for-ascii t
24200 :skip-before-1st-heading
24201 (plist-get opt-plist :skip-before-1st-heading)
24202 :drawers (plist-get opt-plist :drawers)
24203 :verbatim-multiline t
24204 :archived-trees
24205 (plist-get opt-plist :archived-trees)
24206 :add-text (plist-get opt-plist :text))
24207 "\n"))
24208 thetoc have-headings first-heading-pos
24209 table-open table-buffer)
24211 (let ((inhibit-read-only t))
24212 (org-unmodified
24213 (remove-text-properties (point-min) (point-max)
24214 '(:org-license-to-kill t))))
24216 (setq org-min-level (org-get-min-level lines))
24217 (setq org-last-level org-min-level)
24218 (org-init-section-numbers)
24220 (find-file-noselect filename)
24222 (setq lang-words (or (assoc language org-export-language-setup)
24223 (assoc "en" org-export-language-setup)))
24224 (switch-to-buffer-other-window buffer)
24225 (erase-buffer)
24226 (fundamental-mode)
24227 ;; create local variables for all options, to make sure all called
24228 ;; functions get the correct information
24229 (mapc (lambda (x)
24230 (set (make-local-variable (cdr x))
24231 (plist-get opt-plist (car x))))
24232 org-export-plist-vars)
24233 (org-set-local 'org-odd-levels-only odd)
24234 (setq umax (if arg (prefix-numeric-value arg)
24235 org-export-headline-levels))
24236 (setq umax-toc (if (integerp org-export-with-toc)
24237 (min org-export-with-toc umax)
24238 umax))
24240 ;; File header
24241 (if title (org-insert-centered title ?=))
24242 (insert "\n")
24243 (if (and (or author email)
24244 org-export-author-info)
24245 (insert (concat (nth 1 lang-words) ": " (or author "")
24246 (if email (concat " <" email ">") "")
24247 "\n")))
24249 (cond
24250 ((and date (string-match "%" date))
24251 (setq date (format-time-string date (current-time))))
24252 (date)
24253 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24255 (if (and date org-export-time-stamp-file)
24256 (insert (concat (nth 2 lang-words) ": " date"\n")))
24258 (insert "\n\n")
24260 (if org-export-with-toc
24261 (progn
24262 (push (concat (nth 3 lang-words) "\n") thetoc)
24263 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24264 (mapc '(lambda (line)
24265 (if (string-match org-todo-line-regexp
24266 line)
24267 ;; This is a headline
24268 (progn
24269 (setq have-headings t)
24270 (setq level (- (match-end 1) (match-beginning 1))
24271 level (org-tr-level level)
24272 txt (match-string 3 line)
24273 todo
24274 (or (and org-export-mark-todo-in-toc
24275 (match-beginning 2)
24276 (not (member (match-string 2 line)
24277 org-done-keywords)))
24278 ; TODO, not DONE
24279 (and org-export-mark-todo-in-toc
24280 (= level umax-toc)
24281 (org-search-todo-below
24282 line lines level))))
24283 (setq txt (org-html-expand-for-ascii txt))
24285 (while (string-match org-bracket-link-regexp txt)
24286 (setq txt
24287 (replace-match
24288 (match-string (if (match-end 2) 3 1) txt)
24289 t t txt)))
24291 (if (and (memq org-export-with-tags '(not-in-toc nil))
24292 (string-match
24293 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24294 txt))
24295 (setq txt (replace-match "" t t txt)))
24296 (if (string-match quote-re0 txt)
24297 (setq txt (replace-match "" t t txt)))
24299 (if org-export-with-section-numbers
24300 (setq txt (concat (org-section-number level)
24301 " " txt)))
24302 (if (<= level umax-toc)
24303 (progn
24304 (push
24305 (concat
24306 (make-string
24307 (* (max 0 (- level org-min-level)) 4) ?\ )
24308 (format (if todo "%s (*)\n" "%s\n") txt))
24309 thetoc)
24310 (setq org-last-level level))
24311 ))))
24312 lines)
24313 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24315 (org-init-section-numbers)
24316 (while (setq line (pop lines))
24317 ;; Remove the quoted HTML tags.
24318 (setq line (org-html-expand-for-ascii line))
24319 ;; Remove targets
24320 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24321 (setq line (replace-match "" t t line)))
24322 ;; Replace internal links
24323 (while (string-match org-bracket-link-regexp line)
24324 (setq line (replace-match
24325 (if (match-end 3) "[\\3]" "[\\1]")
24326 t nil line)))
24327 (when custom-times
24328 (setq line (org-translate-time line)))
24329 (cond
24330 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24331 ;; a Headline
24332 (setq first-heading-pos (or first-heading-pos (point)))
24333 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24334 txt (match-string 2 line))
24335 (org-ascii-level-start level txt umax lines))
24337 ((and org-export-with-tables
24338 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24339 (if (not table-open)
24340 ;; New table starts
24341 (setq table-open t table-buffer nil))
24342 ;; Accumulate lines
24343 (setq table-buffer (cons line table-buffer))
24344 (when (or (not lines)
24345 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24346 (car lines))))
24347 (setq table-open nil
24348 table-buffer (nreverse table-buffer))
24349 (insert (mapconcat
24350 (lambda (x)
24351 (org-fix-indentation x org-ascii-current-indentation))
24352 (org-format-table-ascii table-buffer)
24353 "\n") "\n")))
24355 (setq line (org-fix-indentation line org-ascii-current-indentation))
24356 (if (and org-export-with-fixed-width
24357 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24358 (setq line (replace-match "\\1" nil nil line)))
24359 (insert line "\n"))))
24361 (normal-mode)
24363 ;; insert the table of contents
24364 (when thetoc
24365 (goto-char (point-min))
24366 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24367 (progn
24368 (goto-char (match-beginning 0))
24369 (replace-match ""))
24370 (goto-char first-heading-pos))
24371 (mapc 'insert thetoc)
24372 (or (looking-at "[ \t]*\n[ \t]*\n")
24373 (insert "\n\n")))
24375 ;; Convert whitespace place holders
24376 (goto-char (point-min))
24377 (let (beg end)
24378 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24379 (setq end (next-single-property-change beg 'org-whitespace))
24380 (goto-char beg)
24381 (delete-region beg end)
24382 (insert (make-string (- end beg) ?\ ))))
24384 (save-buffer)
24385 ;; remove display and invisible chars
24386 (let (beg end)
24387 (goto-char (point-min))
24388 (while (setq beg (next-single-property-change (point) 'display))
24389 (setq end (next-single-property-change beg 'display))
24390 (delete-region beg end)
24391 (goto-char beg)
24392 (insert "=>"))
24393 (goto-char (point-min))
24394 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24395 (setq end (next-single-property-change beg 'org-cwidth))
24396 (delete-region beg end)
24397 (goto-char beg)))
24398 (goto-char (point-min))))
24400 (defun org-export-ascii-clean-string ()
24401 "Do extra work for ASCII export"
24402 (goto-char (point-min))
24403 (while (re-search-forward org-verbatim-re nil t)
24404 (goto-char (match-end 2))
24405 (backward-delete-char 1) (insert "'")
24406 (goto-char (match-beginning 2))
24407 (delete-char 1) (insert "`")
24408 (goto-char (match-end 2))))
24410 (defun org-search-todo-below (line lines level)
24411 "Search the subtree below LINE for any TODO entries."
24412 (let ((rest (cdr (memq line lines)))
24413 (re org-todo-line-regexp)
24414 line lv todo)
24415 (catch 'exit
24416 (while (setq line (pop rest))
24417 (if (string-match re line)
24418 (progn
24419 (setq lv (- (match-end 1) (match-beginning 1))
24420 todo (and (match-beginning 2)
24421 (not (member (match-string 2 line)
24422 org-done-keywords))))
24423 ; TODO, not DONE
24424 (if (<= lv level) (throw 'exit nil))
24425 (if todo (throw 'exit t))))))))
24427 (defun org-html-expand-for-ascii (line)
24428 "Handle quoted HTML for ASCII export."
24429 (if org-export-html-expand
24430 (while (string-match "@<[^<>\n]*>" line)
24431 ;; We just remove the tags for now.
24432 (setq line (replace-match "" nil nil line))))
24433 line)
24435 (defun org-insert-centered (s &optional underline)
24436 "Insert the string S centered and underline it with character UNDERLINE."
24437 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24438 (insert (make-string ind ?\ ) s "\n")
24439 (if underline
24440 (insert (make-string ind ?\ )
24441 (make-string (string-width s) underline)
24442 "\n"))))
24444 (defun org-ascii-level-start (level title umax &optional lines)
24445 "Insert a new level in ASCII export."
24446 (let (char (n (- level umax 1)) (ind 0))
24447 (if (> level umax)
24448 (progn
24449 (insert (make-string (* 2 n) ?\ )
24450 (char-to-string (nth (% n (length org-export-ascii-bullets))
24451 org-export-ascii-bullets))
24452 " " title "\n")
24453 ;; find the indentation of the next non-empty line
24454 (catch 'stop
24455 (while lines
24456 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24457 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24458 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24459 (pop lines)))
24460 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24461 (if (or (not (equal (char-before) ?\n))
24462 (not (equal (char-before (1- (point))) ?\n)))
24463 (insert "\n"))
24464 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24465 (unless org-export-with-tags
24466 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24467 (setq title (replace-match "" t t title))))
24468 (if org-export-with-section-numbers
24469 (setq title (concat (org-section-number level) " " title)))
24470 (insert title "\n" (make-string (string-width title) char) "\n")
24471 (setq org-ascii-current-indentation '(0 . 0)))))
24473 (defun org-export-visible (type arg)
24474 "Create a copy of the visible part of the current buffer, and export it.
24475 The copy is created in a temporary buffer and removed after use.
24476 TYPE is the final key (as a string) that also select the export command in
24477 the `C-c C-e' export dispatcher.
24478 As a special case, if the you type SPC at the prompt, the temporary
24479 org-mode file will not be removed but presented to you so that you can
24480 continue to use it. The prefix arg ARG is passed through to the exporting
24481 command."
24482 (interactive
24483 (list (progn
24484 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24485 (read-char-exclusive))
24486 current-prefix-arg))
24487 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24488 (error "Invalid export key"))
24489 (let* ((binding (cdr (assoc type
24490 '((?a . org-export-as-ascii)
24491 (?\C-a . org-export-as-ascii)
24492 (?b . org-export-as-html-and-open)
24493 (?\C-b . org-export-as-html-and-open)
24494 (?h . org-export-as-html)
24495 (?H . org-export-as-html-to-buffer)
24496 (?R . org-export-region-as-html)
24497 (?x . org-export-as-xoxo)))))
24498 (keepp (equal type ?\ ))
24499 (file buffer-file-name)
24500 (buffer (get-buffer-create "*Org Export Visible*"))
24501 s e)
24502 ;; Need to hack the drawers here.
24503 (save-excursion
24504 (goto-char (point-min))
24505 (while (re-search-forward org-drawer-regexp nil t)
24506 (goto-char (match-beginning 1))
24507 (or (org-invisible-p) (org-flag-drawer nil))))
24508 (with-current-buffer buffer (erase-buffer))
24509 (save-excursion
24510 (setq s (goto-char (point-min)))
24511 (while (not (= (point) (point-max)))
24512 (goto-char (org-find-invisible))
24513 (append-to-buffer buffer s (point))
24514 (setq s (goto-char (org-find-visible))))
24515 (org-cycle-hide-drawers 'all)
24516 (goto-char (point-min))
24517 (unless keepp
24518 ;; Copy all comment lines to the end, to make sure #+ settings are
24519 ;; still available for the second export step. Kind of a hack, but
24520 ;; does do the trick.
24521 (if (looking-at "#[^\r\n]*")
24522 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24523 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24524 (append-to-buffer buffer (1+ (match-beginning 0))
24525 (min (point-max) (1+ (match-end 0))))))
24526 (set-buffer buffer)
24527 (let ((buffer-file-name file)
24528 (org-inhibit-startup t))
24529 (org-mode)
24530 (show-all)
24531 (unless keepp (funcall binding arg))))
24532 (if (not keepp)
24533 (kill-buffer buffer)
24534 (switch-to-buffer-other-window buffer)
24535 (goto-char (point-min)))))
24537 (defun org-find-visible ()
24538 (let ((s (point)))
24539 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24540 (get-char-property s 'invisible)))
24542 (defun org-find-invisible ()
24543 (let ((s (point)))
24544 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24545 (not (get-char-property s 'invisible))))
24548 ;;; HTML export
24550 (defun org-get-current-options ()
24551 "Return a string with current options as keyword options.
24552 Does include HTML export options as well as TODO and CATEGORY stuff."
24553 (format
24554 "#+TITLE: %s
24555 #+AUTHOR: %s
24556 #+EMAIL: %s
24557 #+LANGUAGE: %s
24558 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24559 #+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
24560 #+CATEGORY: %s
24561 #+SEQ_TODO: %s
24562 #+TYP_TODO: %s
24563 #+PRIORITIES: %c %c %c
24564 #+DRAWERS: %s
24565 #+STARTUP: %s %s %s %s %s
24566 #+TAGS: %s
24567 #+ARCHIVE: %s
24568 #+LINK: %s
24570 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24571 org-export-headline-levels
24572 org-export-with-section-numbers
24573 org-export-with-toc
24574 org-export-preserve-breaks
24575 org-export-html-expand
24576 org-export-with-fixed-width
24577 org-export-with-tables
24578 org-export-with-sub-superscripts
24579 org-export-with-special-strings
24580 org-export-with-footnotes
24581 org-export-with-emphasize
24582 org-export-with-TeX-macros
24583 org-export-with-LaTeX-fragments
24584 org-export-skip-text-before-1st-heading
24585 org-export-with-drawers
24586 org-export-with-tags
24587 (file-name-nondirectory buffer-file-name)
24588 "TODO FEEDBACK VERIFY DONE"
24589 "Me Jason Marie DONE"
24590 org-highest-priority org-lowest-priority org-default-priority
24591 (mapconcat 'identity org-drawers " ")
24592 (cdr (assoc org-startup-folded
24593 '((nil . "showall") (t . "overview") (content . "content"))))
24594 (if org-odd-levels-only "odd" "oddeven")
24595 (if org-hide-leading-stars "hidestars" "showstars")
24596 (if org-startup-align-all-tables "align" "noalign")
24597 (cond ((eq t org-log-done) "logdone")
24598 ((not org-log-done) "nologging")
24599 ((listp org-log-done)
24600 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
24601 org-log-done " ")))
24602 (or (mapconcat (lambda (x)
24603 (cond
24604 ((equal '(:startgroup) x) "{")
24605 ((equal '(:endgroup) x) "}")
24606 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24607 (t (car x))))
24608 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24609 org-archive-location
24610 "org file:~/org/%s.org"
24613 (defun org-insert-export-options-template ()
24614 "Insert into the buffer a template with information for exporting."
24615 (interactive)
24616 (if (not (bolp)) (newline))
24617 (let ((s (org-get-current-options)))
24618 (and (string-match "#\\+CATEGORY" s)
24619 (setq s (substring s 0 (match-beginning 0))))
24620 (insert s)))
24622 (defun org-toggle-fixed-width-section (arg)
24623 "Toggle the fixed-width export.
24624 If there is no active region, the QUOTE keyword at the current headline is
24625 inserted or removed. When present, it causes the text between this headline
24626 and the next to be exported as fixed-width text, and unmodified.
24627 If there is an active region, this command adds or removes a colon as the
24628 first character of this line. If the first character of a line is a colon,
24629 this line is also exported in fixed-width font."
24630 (interactive "P")
24631 (let* ((cc 0)
24632 (regionp (org-region-active-p))
24633 (beg (if regionp (region-beginning) (point)))
24634 (end (if regionp (region-end)))
24635 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24636 (case-fold-search nil)
24637 (re "[ \t]*\\(:\\)")
24638 off)
24639 (if regionp
24640 (save-excursion
24641 (goto-char beg)
24642 (setq cc (current-column))
24643 (beginning-of-line 1)
24644 (setq off (looking-at re))
24645 (while (> nlines 0)
24646 (setq nlines (1- nlines))
24647 (beginning-of-line 1)
24648 (cond
24649 (arg
24650 (move-to-column cc t)
24651 (insert ":\n")
24652 (forward-line -1))
24653 ((and off (looking-at re))
24654 (replace-match "" t t nil 1))
24655 ((not off) (move-to-column cc t) (insert ":")))
24656 (forward-line 1)))
24657 (save-excursion
24658 (org-back-to-heading)
24659 (if (looking-at (concat outline-regexp
24660 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24661 (replace-match "" t t nil 1)
24662 (if (looking-at outline-regexp)
24663 (progn
24664 (goto-char (match-end 0))
24665 (insert org-quote-string " "))))))))
24667 (defun org-export-as-html-and-open (arg)
24668 "Export the outline as HTML and immediately open it with a browser.
24669 If there is an active region, export only the region.
24670 The prefix ARG specifies how many levels of the outline should become
24671 headlines. The default is 3. Lower levels will become bulleted lists."
24672 (interactive "P")
24673 (org-export-as-html arg 'hidden)
24674 (org-open-file buffer-file-name))
24676 (defun org-export-as-html-batch ()
24677 "Call `org-export-as-html', may be used in batch processing as
24678 emacs --batch
24679 --load=$HOME/lib/emacs/org.el
24680 --eval \"(setq org-export-headline-levels 2)\"
24681 --visit=MyFile --funcall org-export-as-html-batch"
24682 (org-export-as-html org-export-headline-levels 'hidden))
24684 (defun org-export-as-html-to-buffer (arg)
24685 "Call `org-exort-as-html` with output to a temporary buffer.
24686 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24687 (interactive "P")
24688 (org-export-as-html arg nil nil "*Org HTML Export*")
24689 (switch-to-buffer-other-window "*Org HTML Export*"))
24691 (defun org-replace-region-by-html (beg end)
24692 "Assume the current region has org-mode syntax, and convert it to HTML.
24693 This can be used in any buffer. For example, you could write an
24694 itemized list in org-mode syntax in an HTML buffer and then use this
24695 command to convert it."
24696 (interactive "r")
24697 (let (reg html buf pop-up-frames)
24698 (save-window-excursion
24699 (if (org-mode-p)
24700 (setq html (org-export-region-as-html
24701 beg end t 'string))
24702 (setq reg (buffer-substring beg end)
24703 buf (get-buffer-create "*Org tmp*"))
24704 (with-current-buffer buf
24705 (erase-buffer)
24706 (insert reg)
24707 (org-mode)
24708 (setq html (org-export-region-as-html
24709 (point-min) (point-max) t 'string)))
24710 (kill-buffer buf)))
24711 (delete-region beg end)
24712 (insert html)))
24714 (defun org-export-region-as-html (beg end &optional body-only buffer)
24715 "Convert region from BEG to END in org-mode buffer to HTML.
24716 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24717 contents, and only produce the region of converted text, useful for
24718 cut-and-paste operations.
24719 If BUFFER is a buffer or a string, use/create that buffer as a target
24720 of the converted HTML. If BUFFER is the symbol `string', return the
24721 produced HTML as a string and leave not buffer behind. For example,
24722 a Lisp program could call this function in the following way:
24724 (setq html (org-export-region-as-html beg end t 'string))
24726 When called interactively, the output buffer is selected, and shown
24727 in a window. A non-interactive call will only retunr the buffer."
24728 (interactive "r\nP")
24729 (when (interactive-p)
24730 (setq buffer "*Org HTML Export*"))
24731 (let ((transient-mark-mode t) (zmacs-regions t)
24732 rtn)
24733 (goto-char end)
24734 (set-mark (point)) ;; to activate the region
24735 (goto-char beg)
24736 (setq rtn (org-export-as-html
24737 nil nil nil
24738 buffer body-only))
24739 (if (fboundp 'deactivate-mark) (deactivate-mark))
24740 (if (and (interactive-p) (bufferp rtn))
24741 (switch-to-buffer-other-window rtn)
24742 rtn)))
24744 (defvar html-table-tag nil) ; dynamically scoped into this.
24745 (defun org-export-as-html (arg &optional hidden ext-plist
24746 to-buffer body-only)
24747 "Export the outline as a pretty HTML file.
24748 If there is an active region, export only the region. The prefix
24749 ARG specifies how many levels of the outline should become
24750 headlines. The default is 3. Lower levels will become bulleted
24751 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24752 EXT-PLIST is a property list with external parameters overriding
24753 org-mode's default settings, but still inferior to file-local
24754 settings. When TO-BUFFER is non-nil, create a buffer with that
24755 name and export to that buffer. If TO-BUFFER is the symbol `string',
24756 don't leave any buffer behind but just return the resulting HTML as
24757 a string. When BODY-ONLY is set, don't produce the file header and footer,
24758 simply return the content of <body>...</body>, without even
24759 the body tags themselves."
24760 (interactive "P")
24762 ;; Make sure we have a file name when we need it.
24763 (when (and (not (or to-buffer body-only))
24764 (not buffer-file-name))
24765 (if (buffer-base-buffer)
24766 (org-set-local 'buffer-file-name
24767 (with-current-buffer (buffer-base-buffer)
24768 buffer-file-name))
24769 (error "Need a file name to be able to export.")))
24771 (message "Exporting...")
24772 (setq-default org-todo-line-regexp org-todo-line-regexp)
24773 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24774 (setq-default org-done-keywords org-done-keywords)
24775 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24776 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24777 ext-plist
24778 (org-infile-export-plist)))
24780 (style (plist-get opt-plist :style))
24781 (link-validate (plist-get opt-plist :link-validation-function))
24782 valid thetoc have-headings first-heading-pos
24783 (odd org-odd-levels-only)
24784 (region-p (org-region-active-p))
24785 (subtree-p
24786 (when region-p
24787 (save-excursion
24788 (goto-char (region-beginning))
24789 (and (org-at-heading-p)
24790 (>= (org-end-of-subtree t t) (region-end))))))
24791 ;; The following two are dynamically scoped into other
24792 ;; routines below.
24793 (org-current-export-dir (org-export-directory :html opt-plist))
24794 (org-current-export-file buffer-file-name)
24795 (level 0) (line "") (origline "") txt todo
24796 (umax nil)
24797 (umax-toc nil)
24798 (filename (if to-buffer nil
24799 (expand-file-name
24800 (concat
24801 (file-name-sans-extension
24802 (or (and subtree-p
24803 (org-entry-get (region-beginning)
24804 "EXPORT_FILE_NAME" t))
24805 (file-name-nondirectory buffer-file-name)))
24806 "." org-export-html-extension)
24807 (file-name-as-directory
24808 (org-export-directory :html opt-plist)))))
24809 (current-dir (if buffer-file-name
24810 (file-name-directory buffer-file-name)
24811 default-directory))
24812 (buffer (if to-buffer
24813 (cond
24814 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24815 (t (get-buffer-create to-buffer)))
24816 (find-file-noselect filename)))
24817 (org-levels-open (make-vector org-level-max nil))
24818 (date (plist-get opt-plist :date))
24819 (author (plist-get opt-plist :author))
24820 (title (or (and subtree-p (org-export-get-title-from-subtree))
24821 (plist-get opt-plist :title)
24822 (and (not
24823 (plist-get opt-plist :skip-before-1st-heading))
24824 (org-export-grab-title-from-buffer))
24825 (and buffer-file-name
24826 (file-name-sans-extension
24827 (file-name-nondirectory buffer-file-name)))
24828 "UNTITLED"))
24829 (html-table-tag (plist-get opt-plist :html-table-tag))
24830 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24831 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24832 (inquote nil)
24833 (infixed nil)
24834 (in-local-list nil)
24835 (local-list-num nil)
24836 (local-list-indent nil)
24837 (llt org-plain-list-ordered-item-terminator)
24838 (email (plist-get opt-plist :email))
24839 (language (plist-get opt-plist :language))
24840 (lang-words nil)
24841 (target-alist nil) tg
24842 (head-count 0) cnt
24843 (start 0)
24844 (coding-system (and (boundp 'buffer-file-coding-system)
24845 buffer-file-coding-system))
24846 (coding-system-for-write (or org-export-html-coding-system
24847 coding-system))
24848 (save-buffer-coding-system (or org-export-html-coding-system
24849 coding-system))
24850 (charset (and coding-system-for-write
24851 (fboundp 'coding-system-get)
24852 (coding-system-get coding-system-for-write
24853 'mime-charset)))
24854 (region
24855 (buffer-substring
24856 (if region-p (region-beginning) (point-min))
24857 (if region-p (region-end) (point-max))))
24858 (lines
24859 (org-split-string
24860 (org-cleaned-string-for-export
24861 region
24862 :emph-multiline t
24863 :for-html t
24864 :skip-before-1st-heading
24865 (plist-get opt-plist :skip-before-1st-heading)
24866 :drawers (plist-get opt-plist :drawers)
24867 :archived-trees
24868 (plist-get opt-plist :archived-trees)
24869 :add-text
24870 (plist-get opt-plist :text)
24871 :LaTeX-fragments
24872 (plist-get opt-plist :LaTeX-fragments))
24873 "[\r\n]"))
24874 table-open type
24875 table-buffer table-orig-buffer
24876 ind start-is-num starter didclose
24877 rpl path desc descp desc1 desc2 link
24880 (let ((inhibit-read-only t))
24881 (org-unmodified
24882 (remove-text-properties (point-min) (point-max)
24883 '(:org-license-to-kill t))))
24885 (message "Exporting...")
24887 (setq org-min-level (org-get-min-level lines))
24888 (setq org-last-level org-min-level)
24889 (org-init-section-numbers)
24891 (cond
24892 ((and date (string-match "%" date))
24893 (setq date (format-time-string date (current-time))))
24894 (date)
24895 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24897 ;; Get the language-dependent settings
24898 (setq lang-words (or (assoc language org-export-language-setup)
24899 (assoc "en" org-export-language-setup)))
24901 ;; Switch to the output buffer
24902 (set-buffer buffer)
24903 (let ((inhibit-read-only t)) (erase-buffer))
24904 (fundamental-mode)
24906 (and (fboundp 'set-buffer-file-coding-system)
24907 (set-buffer-file-coding-system coding-system-for-write))
24909 (let ((case-fold-search nil)
24910 (org-odd-levels-only odd))
24911 ;; create local variables for all options, to make sure all called
24912 ;; functions get the correct information
24913 (mapc (lambda (x)
24914 (set (make-local-variable (cdr x))
24915 (plist-get opt-plist (car x))))
24916 org-export-plist-vars)
24917 (setq umax (if arg (prefix-numeric-value arg)
24918 org-export-headline-levels))
24919 (setq umax-toc (if (integerp org-export-with-toc)
24920 (min org-export-with-toc umax)
24921 umax))
24922 (unless body-only
24923 ;; File header
24924 (insert (format
24925 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
24926 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
24927 <html xmlns=\"http://www.w3.org/1999/xhtml\"
24928 lang=\"%s\" xml:lang=\"%s\">
24929 <head>
24930 <title>%s</title>
24931 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
24932 <meta name=\"generator\" content=\"Org-mode\"/>
24933 <meta name=\"generated\" content=\"%s\"/>
24934 <meta name=\"author\" content=\"%s\"/>
24936 </head><body>
24938 language language (org-html-expand title)
24939 (or charset "iso-8859-1") date author style))
24941 (insert (or (plist-get opt-plist :preamble) ""))
24943 (when (plist-get opt-plist :auto-preamble)
24944 (if title (insert (format org-export-html-title-format
24945 (org-html-expand title))))))
24947 (if (and org-export-with-toc (not body-only))
24948 (progn
24949 (push (format "<h%d>%s</h%d>\n"
24950 org-export-html-toplevel-hlevel
24951 (nth 3 lang-words)
24952 org-export-html-toplevel-hlevel)
24953 thetoc)
24954 (push "<ul>\n<li>" thetoc)
24955 (setq lines
24956 (mapcar '(lambda (line)
24957 (if (string-match org-todo-line-regexp line)
24958 ;; This is a headline
24959 (progn
24960 (setq have-headings t)
24961 (setq level (- (match-end 1) (match-beginning 1))
24962 level (org-tr-level level)
24963 txt (save-match-data
24964 (org-html-expand
24965 (org-export-cleanup-toc-line
24966 (match-string 3 line))))
24967 todo
24968 (or (and org-export-mark-todo-in-toc
24969 (match-beginning 2)
24970 (not (member (match-string 2 line)
24971 org-done-keywords)))
24972 ; TODO, not DONE
24973 (and org-export-mark-todo-in-toc
24974 (= level umax-toc)
24975 (org-search-todo-below
24976 line lines level))))
24977 (if (string-match
24978 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
24979 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
24980 (if (string-match quote-re0 txt)
24981 (setq txt (replace-match "" t t txt)))
24982 (if org-export-with-section-numbers
24983 (setq txt (concat (org-section-number level)
24984 " " txt)))
24985 (if (<= level (max umax umax-toc))
24986 (setq head-count (+ head-count 1)))
24987 (if (<= level umax-toc)
24988 (progn
24989 (if (> level org-last-level)
24990 (progn
24991 (setq cnt (- level org-last-level))
24992 (while (>= (setq cnt (1- cnt)) 0)
24993 (push "\n<ul>\n<li>" thetoc))
24994 (push "\n" thetoc)))
24995 (if (< level org-last-level)
24996 (progn
24997 (setq cnt (- org-last-level level))
24998 (while (>= (setq cnt (1- cnt)) 0)
24999 (push "</li>\n</ul>" thetoc))
25000 (push "\n" thetoc)))
25001 ;; Check for targets
25002 (while (string-match org-target-regexp line)
25003 (setq tg (match-string 1 line)
25004 line (replace-match
25005 (concat "@<span class=\"target\">" tg "@</span> ")
25006 t t line))
25007 (push (cons (org-solidify-link-text tg)
25008 (format "sec-%d" head-count))
25009 target-alist))
25010 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25011 (setq txt (replace-match "" t t txt)))
25012 (push
25013 (format
25014 (if todo
25015 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25016 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25017 head-count txt) thetoc)
25019 (setq org-last-level level))
25021 line)
25022 lines))
25023 (while (> org-last-level (1- org-min-level))
25024 (setq org-last-level (1- org-last-level))
25025 (push "</li>\n</ul>\n" thetoc))
25026 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25028 (setq head-count 0)
25029 (org-init-section-numbers)
25031 (while (setq line (pop lines) origline line)
25032 (catch 'nextline
25034 ;; end of quote section?
25035 (when (and inquote (string-match "^\\*+ " line))
25036 (insert "</pre>\n")
25037 (setq inquote nil))
25038 ;; inside a quote section?
25039 (when inquote
25040 (insert (org-html-protect line) "\n")
25041 (throw 'nextline nil))
25043 ;; verbatim lines
25044 (when (and org-export-with-fixed-width
25045 (string-match "^[ \t]*:\\(.*\\)" line))
25046 (when (not infixed)
25047 (setq infixed t)
25048 (insert "<pre>\n"))
25049 (insert (org-html-protect (match-string 1 line)) "\n")
25050 (when (and lines
25051 (not (string-match "^[ \t]*\\(:.*\\)"
25052 (car lines))))
25053 (setq infixed nil)
25054 (insert "</pre>\n"))
25055 (throw 'nextline nil))
25057 ;; Protected HTML
25058 (when (get-text-property 0 'org-protected line)
25059 (let (par)
25060 (when (re-search-backward
25061 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25062 (setq par (match-string 1))
25063 (replace-match "\\2\n"))
25064 (insert line "\n")
25065 (while (and lines
25066 (or (= (length (car lines)) 0)
25067 (get-text-property 0 'org-protected (car lines))))
25068 (insert (pop lines) "\n"))
25069 (and par (insert "<p>\n")))
25070 (throw 'nextline nil))
25072 ;; Horizontal line
25073 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25074 (insert "\n<hr/>\n")
25075 (throw 'nextline nil))
25077 ;; make targets to anchors
25078 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25079 (cond
25080 ((match-end 2)
25081 (setq line (replace-match
25082 (concat "@<a name=\""
25083 (org-solidify-link-text (match-string 1 line))
25084 "\">\\nbsp@</a>")
25085 t t line)))
25086 ((and org-export-with-toc (equal (string-to-char line) ?*))
25087 (setq line (replace-match
25088 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25089 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25090 t t line)))
25092 (setq line (replace-match
25093 (concat "@<a name=\""
25094 (org-solidify-link-text (match-string 1 line))
25095 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25096 t t line)))))
25098 (setq line (org-html-handle-time-stamps line))
25100 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25101 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25102 ;; Also handle sub_superscripts and checkboxes
25103 (or (string-match org-table-hline-regexp line)
25104 (setq line (org-html-expand line)))
25106 ;; Format the links
25107 (setq start 0)
25108 (while (string-match org-bracket-link-analytic-regexp line start)
25109 (setq start (match-beginning 0))
25110 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25111 (setq path (match-string 3 line))
25112 (setq desc1 (if (match-end 5) (match-string 5 line))
25113 desc2 (if (match-end 2) (concat type ":" path) path)
25114 descp (and desc1 (not (equal desc1 desc2)))
25115 desc (or desc1 desc2))
25116 ;; Make an image out of the description if that is so wanted
25117 (when (and descp (org-file-image-p desc))
25118 (save-match-data
25119 (if (string-match "^file:" desc)
25120 (setq desc (substring desc (match-end 0)))))
25121 (setq desc (concat "<img src=\"" desc "\"/>")))
25122 ;; FIXME: do we need to unescape here somewhere?
25123 (cond
25124 ((equal type "internal")
25125 (setq rpl
25126 (concat
25127 "<a href=\"#"
25128 (org-solidify-link-text
25129 (save-match-data (org-link-unescape path)) target-alist)
25130 "\">" desc "</a>")))
25131 ((member type '("http" "https"))
25132 ;; standard URL, just check if we need to inline an image
25133 (if (and (or (eq t org-export-html-inline-images)
25134 (and org-export-html-inline-images (not descp)))
25135 (org-file-image-p path))
25136 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25137 (setq link (concat type ":" path))
25138 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25139 ((member type '("ftp" "mailto" "news"))
25140 ;; standard URL
25141 (setq link (concat type ":" path))
25142 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25143 ((string= type "file")
25144 ;; FILE link
25145 (let* ((filename path)
25146 (abs-p (file-name-absolute-p filename))
25147 thefile file-is-image-p search)
25148 (save-match-data
25149 (if (string-match "::\\(.*\\)" filename)
25150 (setq search (match-string 1 filename)
25151 filename (replace-match "" t nil filename)))
25152 (setq valid
25153 (if (functionp link-validate)
25154 (funcall link-validate filename current-dir)
25156 (setq file-is-image-p (org-file-image-p filename))
25157 (setq thefile (if abs-p (expand-file-name filename) filename))
25158 (when (and org-export-html-link-org-files-as-html
25159 (string-match "\\.org$" thefile))
25160 (setq thefile (concat (substring thefile 0
25161 (match-beginning 0))
25162 "." org-export-html-extension))
25163 (if (and search
25164 ;; make sure this is can be used as target search
25165 (not (string-match "^[0-9]*$" search))
25166 (not (string-match "^\\*" search))
25167 (not (string-match "^/.*/$" search)))
25168 (setq thefile (concat thefile "#"
25169 (org-solidify-link-text
25170 (org-link-unescape search)))))
25171 (when (string-match "^file:" desc)
25172 (setq desc (replace-match "" t t desc))
25173 (if (string-match "\\.org$" desc)
25174 (setq desc (replace-match "" t t desc))))))
25175 (setq rpl (if (and file-is-image-p
25176 (or (eq t org-export-html-inline-images)
25177 (and org-export-html-inline-images
25178 (not descp))))
25179 (concat "<img src=\"" thefile "\"/>")
25180 (concat "<a href=\"" thefile "\">" desc "</a>")))
25181 (if (not valid) (setq rpl desc))))
25182 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25183 (setq rpl (concat "<i>&lt;" type ":"
25184 (save-match-data (org-link-unescape path))
25185 "&gt;</i>"))))
25186 (setq line (replace-match rpl t t line)
25187 start (+ start (length rpl))))
25189 ;; TODO items
25190 (if (and (string-match org-todo-line-regexp line)
25191 (match-beginning 2))
25193 (setq line
25194 (concat (substring line 0 (match-beginning 2))
25195 "<span class=\""
25196 (if (member (match-string 2 line)
25197 org-done-keywords)
25198 "done" "todo")
25199 "\">" (match-string 2 line)
25200 "</span>" (substring line (match-end 2)))))
25202 ;; Does this contain a reference to a footnote?
25203 (when org-export-with-footnotes
25204 (setq start 0)
25205 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25206 (if (get-text-property (match-beginning 2) 'org-protected line)
25207 (setq start (match-end 2))
25208 (let ((n (match-string 2 line)))
25209 (setq line
25210 (replace-match
25211 (format
25212 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25213 (match-string 1 line) n n n)
25214 t t line))))))
25216 (cond
25217 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25218 ;; This is a headline
25219 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25220 txt (match-string 2 line))
25221 (if (string-match quote-re0 txt)
25222 (setq txt (replace-match "" t t txt)))
25223 (if (<= level (max umax umax-toc))
25224 (setq head-count (+ head-count 1)))
25225 (when in-local-list
25226 ;; Close any local lists before inserting a new header line
25227 (while local-list-num
25228 (org-close-li)
25229 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25230 (pop local-list-num))
25231 (setq local-list-indent nil
25232 in-local-list nil))
25233 (setq first-heading-pos (or first-heading-pos (point)))
25234 (org-html-level-start level txt umax
25235 (and org-export-with-toc (<= level umax))
25236 head-count)
25237 ;; QUOTES
25238 (when (string-match quote-re line)
25239 (insert "<pre>")
25240 (setq inquote t)))
25242 ((and org-export-with-tables
25243 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25244 (if (not table-open)
25245 ;; New table starts
25246 (setq table-open t table-buffer nil table-orig-buffer nil))
25247 ;; Accumulate lines
25248 (setq table-buffer (cons line table-buffer)
25249 table-orig-buffer (cons origline table-orig-buffer))
25250 (when (or (not lines)
25251 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25252 (car lines))))
25253 (setq table-open nil
25254 table-buffer (nreverse table-buffer)
25255 table-orig-buffer (nreverse table-orig-buffer))
25256 (org-close-par-maybe)
25257 (insert (org-format-table-html table-buffer table-orig-buffer))))
25259 ;; Normal lines
25260 (when (string-match
25261 (cond
25262 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25263 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25264 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25265 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25266 line)
25267 (setq ind (org-get-string-indentation line)
25268 start-is-num (match-beginning 4)
25269 starter (if (match-beginning 2)
25270 (substring (match-string 2 line) 0 -1))
25271 line (substring line (match-beginning 5)))
25272 (unless (string-match "[^ \t]" line)
25273 ;; empty line. Pretend indentation is large.
25274 (setq ind (if org-empty-line-terminates-plain-lists
25276 (1+ (or (car local-list-indent) 1)))))
25277 (setq didclose nil)
25278 (while (and in-local-list
25279 (or (and (= ind (car local-list-indent))
25280 (not starter))
25281 (< ind (car local-list-indent))))
25282 (setq didclose t)
25283 (org-close-li)
25284 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25285 (pop local-list-num) (pop local-list-indent)
25286 (setq in-local-list local-list-indent))
25287 (cond
25288 ((and starter
25289 (or (not in-local-list)
25290 (> ind (car local-list-indent))))
25291 ;; Start new (level of) list
25292 (org-close-par-maybe)
25293 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25294 (push start-is-num local-list-num)
25295 (push ind local-list-indent)
25296 (setq in-local-list t))
25297 (starter
25298 ;; continue current list
25299 (org-close-li)
25300 (insert "<li>\n"))
25301 (didclose
25302 ;; we did close a list, normal text follows: need <p>
25303 (org-open-par)))
25304 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25305 (setq line
25306 (replace-match
25307 (if (equal (match-string 1 line) "X")
25308 "<b>[X]</b>"
25309 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25310 t t line))))
25312 ;; Empty lines start a new paragraph. If hand-formatted lists
25313 ;; are not fully interpreted, lines starting with "-", "+", "*"
25314 ;; also start a new paragraph.
25315 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25317 ;; Is this the start of a footnote?
25318 (when org-export-with-footnotes
25319 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25320 (org-close-par-maybe)
25321 (let ((n (match-string 1 line)))
25322 (setq line (replace-match
25323 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25325 ;; Check if the line break needs to be conserved
25326 (cond
25327 ((string-match "\\\\\\\\[ \t]*$" line)
25328 (setq line (replace-match "<br/>" t t line)))
25329 (org-export-preserve-breaks
25330 (setq line (concat line "<br/>"))))
25332 (insert line "\n")))))
25334 ;; Properly close all local lists and other lists
25335 (when inquote (insert "</pre>\n"))
25336 (when in-local-list
25337 ;; Close any local lists before inserting a new header line
25338 (while local-list-num
25339 (org-close-li)
25340 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25341 (pop local-list-num))
25342 (setq local-list-indent nil
25343 in-local-list nil))
25344 (org-html-level-start 1 nil umax
25345 (and org-export-with-toc (<= level umax))
25346 head-count)
25348 (unless body-only
25349 (when (plist-get opt-plist :auto-postamble)
25350 (insert "<div id=\"postamble\">")
25351 (when (and org-export-author-info author)
25352 (insert "<p class=\"author\"> "
25353 (nth 1 lang-words) ": " author "\n")
25354 (when email
25355 (if (listp (split-string email ",+ *"))
25356 (mapc (lambda(e)
25357 (insert "<a href=\"mailto:" e "\">&lt;"
25358 e "&gt;</a>\n"))
25359 (split-string email ",+ *"))
25360 (insert "<a href=\"mailto:" email "\">&lt;"
25361 email "&gt;</a>\n")))
25362 (insert "</p>\n"))
25363 (when (and date org-export-time-stamp-file)
25364 (insert "<p class=\"date\"> "
25365 (nth 2 lang-words) ": "
25366 date "</p>\n"))
25367 (insert "</div>"))
25369 (if org-export-html-with-timestamp
25370 (insert org-export-html-html-helper-timestamp))
25371 (insert (or (plist-get opt-plist :postamble) ""))
25372 (insert "</body>\n</html>\n"))
25374 (normal-mode)
25375 (if (eq major-mode default-major-mode) (html-mode))
25377 ;; insert the table of contents
25378 (goto-char (point-min))
25379 (when thetoc
25380 (if (or (re-search-forward
25381 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25382 (re-search-forward
25383 "\\[TABLE-OF-CONTENTS\\]" nil t))
25384 (progn
25385 (goto-char (match-beginning 0))
25386 (replace-match ""))
25387 (goto-char first-heading-pos)
25388 (when (looking-at "\\s-*</p>")
25389 (goto-char (match-end 0))
25390 (insert "\n")))
25391 (insert "<div id=\"table-of-contents\">\n")
25392 (mapc 'insert thetoc)
25393 (insert "</div>\n"))
25394 ;; remove empty paragraphs and lists
25395 (goto-char (point-min))
25396 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25397 (replace-match ""))
25398 (goto-char (point-min))
25399 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25400 (replace-match ""))
25401 ;; Convert whitespace place holders
25402 (goto-char (point-min))
25403 (let (beg end n)
25404 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25405 (setq n (get-text-property beg 'org-whitespace)
25406 end (next-single-property-change beg 'org-whitespace))
25407 (goto-char beg)
25408 (delete-region beg end)
25409 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25410 (make-string n ?x)))))
25412 (or to-buffer (save-buffer))
25413 (goto-char (point-min))
25414 (message "Exporting... done")
25415 (if (eq to-buffer 'string)
25416 (prog1 (buffer-substring (point-min) (point-max))
25417 (kill-buffer (current-buffer)))
25418 (current-buffer)))))
25420 (defvar org-table-colgroup-info nil)
25421 (defun org-format-table-ascii (lines)
25422 "Format a table for ascii export."
25423 (if (stringp lines)
25424 (setq lines (org-split-string lines "\n")))
25425 (if (not (string-match "^[ \t]*|" (car lines)))
25426 ;; Table made by table.el - test for spanning
25427 lines
25429 ;; A normal org table
25430 ;; Get rid of hlines at beginning and end
25431 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25432 (setq lines (nreverse lines))
25433 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25434 (setq lines (nreverse lines))
25435 (when org-export-table-remove-special-lines
25436 ;; Check if the table has a marking column. If yes remove the
25437 ;; column and the special lines
25438 (setq lines (org-table-clean-before-export lines)))
25439 ;; Get rid of the vertical lines except for grouping
25440 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25441 rtn line vl1 start)
25442 (while (setq line (pop lines))
25443 (if (string-match org-table-hline-regexp line)
25444 (and (string-match "|\\(.*\\)|" line)
25445 (setq line (replace-match " \\1" t nil line)))
25446 (setq start 0 vl1 vl)
25447 (while (string-match "|" line start)
25448 (setq start (match-end 0))
25449 (or (pop vl1) (setq line (replace-match " " t t line)))))
25450 (push line rtn))
25451 (nreverse rtn))))
25453 (defun org-colgroup-info-to-vline-list (info)
25454 (let (vl new last)
25455 (while info
25456 (setq last new new (pop info))
25457 (if (or (memq last '(:end :startend))
25458 (memq new '(:start :startend)))
25459 (push t vl)
25460 (push nil vl)))
25461 (setq vl (nreverse vl))
25462 (and vl (setcar vl nil))
25463 vl))
25465 (defun org-format-table-html (lines olines)
25466 "Find out which HTML converter to use and return the HTML code."
25467 (if (stringp lines)
25468 (setq lines (org-split-string lines "\n")))
25469 (if (string-match "^[ \t]*|" (car lines))
25470 ;; A normal org table
25471 (org-format-org-table-html lines)
25472 ;; Table made by table.el - test for spanning
25473 (let* ((hlines (delq nil (mapcar
25474 (lambda (x)
25475 (if (string-match "^[ \t]*\\+-" x) x
25476 nil))
25477 lines)))
25478 (first (car hlines))
25479 (ll (and (string-match "\\S-+" first)
25480 (match-string 0 first)))
25481 (re (concat "^[ \t]*" (regexp-quote ll)))
25482 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25483 hlines))))
25484 (if (and (not spanning)
25485 (not org-export-prefer-native-exporter-for-tables))
25486 ;; We can use my own converter with HTML conversions
25487 (org-format-table-table-html lines)
25488 ;; Need to use the code generator in table.el, with the original text.
25489 (org-format-table-table-html-using-table-generate-source olines)))))
25491 (defun org-format-org-table-html (lines &optional splice)
25492 "Format a table into HTML."
25493 ;; Get rid of hlines at beginning and end
25494 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25495 (setq lines (nreverse lines))
25496 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25497 (setq lines (nreverse lines))
25498 (when org-export-table-remove-special-lines
25499 ;; Check if the table has a marking column. If yes remove the
25500 ;; column and the special lines
25501 (setq lines (org-table-clean-before-export lines)))
25503 (let ((head (and org-export-highlight-first-table-line
25504 (delq nil (mapcar
25505 (lambda (x) (string-match "^[ \t]*|-" x))
25506 (cdr lines)))))
25507 (nlines 0) fnum i
25508 tbopen line fields html gr colgropen)
25509 (if splice (setq head nil))
25510 (unless splice (push (if head "<thead>" "<tbody>") html))
25511 (setq tbopen t)
25512 (while (setq line (pop lines))
25513 (catch 'next-line
25514 (if (string-match "^[ \t]*|-" line)
25515 (progn
25516 (unless splice
25517 (push (if head "</thead>" "</tbody>") html)
25518 (if lines (push "<tbody>" html) (setq tbopen nil)))
25519 (setq head nil) ;; head ends here, first time around
25520 ;; ignore this line
25521 (throw 'next-line t)))
25522 ;; Break the line into fields
25523 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25524 (unless fnum (setq fnum (make-vector (length fields) 0)))
25525 (setq nlines (1+ nlines) i -1)
25526 (push (concat "<tr>"
25527 (mapconcat
25528 (lambda (x)
25529 (setq i (1+ i))
25530 (if (and (< i nlines)
25531 (string-match org-table-number-regexp x))
25532 (incf (aref fnum i)))
25533 (if head
25534 (concat (car org-export-table-header-tags) x
25535 (cdr org-export-table-header-tags))
25536 (concat (car org-export-table-data-tags) x
25537 (cdr org-export-table-data-tags))))
25538 fields "")
25539 "</tr>")
25540 html)))
25541 (unless splice (if tbopen (push "</tbody>" html)))
25542 (unless splice (push "</table>\n" html))
25543 (setq html (nreverse html))
25544 (unless splice
25545 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25546 (push (mapconcat
25547 (lambda (x)
25548 (setq gr (pop org-table-colgroup-info))
25549 (format "%s<col align=\"%s\"></col>%s"
25550 (if (memq gr '(:start :startend))
25551 (prog1
25552 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25553 (setq colgropen t))
25555 (if (> (/ (float x) nlines) org-table-number-fraction)
25556 "right" "left")
25557 (if (memq gr '(:end :startend))
25558 (progn (setq colgropen nil) "</colgroup>")
25559 "")))
25560 fnum "")
25561 html)
25562 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25563 (push html-table-tag html))
25564 (concat (mapconcat 'identity html "\n") "\n")))
25566 (defun org-table-clean-before-export (lines)
25567 "Check if the table has a marking column.
25568 If yes remove the column and the special lines."
25569 (setq org-table-colgroup-info nil)
25570 (if (memq nil
25571 (mapcar
25572 (lambda (x) (or (string-match "^[ \t]*|-" x)
25573 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25574 lines))
25575 (progn
25576 (setq org-table-clean-did-remove-column nil)
25577 (delq nil
25578 (mapcar
25579 (lambda (x)
25580 (cond
25581 ((string-match "^[ \t]*| */ *|" x)
25582 (setq org-table-colgroup-info
25583 (mapcar (lambda (x)
25584 (cond ((member x '("<" "&lt;")) :start)
25585 ((member x '(">" "&gt;")) :end)
25586 ((member x '("<>" "&lt;&gt;")) :startend)
25587 (t nil)))
25588 (org-split-string x "[ \t]*|[ \t]*")))
25589 nil)
25590 (t x)))
25591 lines)))
25592 (setq org-table-clean-did-remove-column t)
25593 (delq nil
25594 (mapcar
25595 (lambda (x)
25596 (cond
25597 ((string-match "^[ \t]*| */ *|" x)
25598 (setq org-table-colgroup-info
25599 (mapcar (lambda (x)
25600 (cond ((member x '("<" "&lt;")) :start)
25601 ((member x '(">" "&gt;")) :end)
25602 ((member x '("<>" "&lt;&gt;")) :startend)
25603 (t nil)))
25604 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25605 nil)
25606 ((string-match "^[ \t]*| *[!_^/] *|" x)
25607 nil) ; ignore this line
25608 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25609 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25610 ;; remove the first column
25611 (replace-match "\\1|" t nil x))))
25612 lines))))
25614 (defun org-format-table-table-html (lines)
25615 "Format a table generated by table.el into HTML.
25616 This conversion does *not* use `table-generate-source' from table.el.
25617 This has the advantage that Org-mode's HTML conversions can be used.
25618 But it has the disadvantage, that no cell- or row-spanning is allowed."
25619 (let (line field-buffer
25620 (head org-export-highlight-first-table-line)
25621 fields html empty)
25622 (setq html (concat html-table-tag "\n"))
25623 (while (setq line (pop lines))
25624 (setq empty "&nbsp;")
25625 (catch 'next-line
25626 (if (string-match "^[ \t]*\\+-" line)
25627 (progn
25628 (if field-buffer
25629 (progn
25630 (setq
25631 html
25632 (concat
25633 html
25634 "<tr>"
25635 (mapconcat
25636 (lambda (x)
25637 (if (equal x "") (setq x empty))
25638 (if head
25639 (concat (car org-export-table-header-tags) x
25640 (cdr org-export-table-header-tags))
25641 (concat (car org-export-table-data-tags) x
25642 (cdr org-export-table-data-tags))))
25643 field-buffer "\n")
25644 "</tr>\n"))
25645 (setq head nil)
25646 (setq field-buffer nil)))
25647 ;; Ignore this line
25648 (throw 'next-line t)))
25649 ;; Break the line into fields and store the fields
25650 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25651 (if field-buffer
25652 (setq field-buffer (mapcar
25653 (lambda (x)
25654 (concat x "<br/>" (pop fields)))
25655 field-buffer))
25656 (setq field-buffer fields))))
25657 (setq html (concat html "</table>\n"))
25658 html))
25660 (defun org-format-table-table-html-using-table-generate-source (lines)
25661 "Format a table into html, using `table-generate-source' from table.el.
25662 This has the advantage that cell- or row-spanning is allowed.
25663 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25664 (require 'table)
25665 (with-current-buffer (get-buffer-create " org-tmp1 ")
25666 (erase-buffer)
25667 (insert (mapconcat 'identity lines "\n"))
25668 (goto-char (point-min))
25669 (if (not (re-search-forward "|[^+]" nil t))
25670 (error "Error processing table"))
25671 (table-recognize-table)
25672 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25673 (table-generate-source 'html " org-tmp2 ")
25674 (set-buffer " org-tmp2 ")
25675 (buffer-substring (point-min) (point-max))))
25677 (defun org-html-handle-time-stamps (s)
25678 "Format time stamps in string S, or remove them."
25679 (catch 'exit
25680 (let (r b)
25681 (while (string-match org-maybe-keyword-time-regexp s)
25682 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25683 ;; never export CLOCK
25684 (throw 'exit ""))
25685 (or b (setq b (substring s 0 (match-beginning 0))))
25686 (if (not org-export-with-timestamps)
25687 (setq r (concat r (substring s 0 (match-beginning 0)))
25688 s (substring s (match-end 0)))
25689 (setq r (concat
25690 r (substring s 0 (match-beginning 0))
25691 (if (match-end 1)
25692 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25693 (match-string 1 s)))
25694 (format " @<span class=\"timestamp\">%s@</span>"
25695 (substring
25696 (org-translate-time (match-string 3 s)) 1 -1)))
25697 s (substring s (match-end 0)))))
25698 ;; Line break if line started and ended with time stamp stuff
25699 (if (not r)
25701 (setq r (concat r s))
25702 (unless (string-match "\\S-" (concat b s))
25703 (setq r (concat r "@<br/>")))
25704 r))))
25706 (defun org-html-protect (s)
25707 ;; convert & to &amp;, < to &lt; and > to &gt;
25708 (let ((start 0))
25709 (while (string-match "&" s start)
25710 (setq s (replace-match "&amp;" t t s)
25711 start (1+ (match-beginning 0))))
25712 (while (string-match "<" s)
25713 (setq s (replace-match "&lt;" t t s)))
25714 (while (string-match ">" s)
25715 (setq s (replace-match "&gt;" t t s))))
25718 (defun org-export-cleanup-toc-line (s)
25719 "Remove tags and time staps from lines going into the toc."
25720 (when (memq org-export-with-tags '(not-in-toc nil))
25721 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25722 (setq s (replace-match "" t t s))))
25723 (when org-export-remove-timestamps-from-toc
25724 (while (string-match org-maybe-keyword-time-regexp s)
25725 (setq s (replace-match "" t t s))))
25726 (while (string-match org-bracket-link-regexp s)
25727 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25728 t t s)))
25731 (defun org-html-expand (string)
25732 "Prepare STRING for HTML export. Applies all active conversions.
25733 If there are links in the string, don't modify these."
25734 (let* ((re (concat org-bracket-link-regexp "\\|"
25735 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25736 m s l res)
25737 (while (setq m (string-match re string))
25738 (setq s (substring string 0 m)
25739 l (match-string 0 string)
25740 string (substring string (match-end 0)))
25741 (push (org-html-do-expand s) res)
25742 (push l res))
25743 (push (org-html-do-expand string) res)
25744 (apply 'concat (nreverse res))))
25746 (defun org-html-do-expand (s)
25747 "Apply all active conversions to translate special ASCII to HTML."
25748 (setq s (org-html-protect s))
25749 (if org-export-html-expand
25750 (let ((start 0))
25751 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25752 (setq s (replace-match "<\\1>" t nil s)))))
25753 (if org-export-with-emphasize
25754 (setq s (org-export-html-convert-emphasize s)))
25755 (if org-export-with-special-strings
25756 (setq s (org-export-html-convert-special-strings s)))
25757 (if org-export-with-sub-superscripts
25758 (setq s (org-export-html-convert-sub-super s)))
25759 (if org-export-with-TeX-macros
25760 (let ((start 0) wd ass)
25761 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25762 (if (get-text-property (match-beginning 0) 'org-protected s)
25763 (setq start (match-end 0))
25764 (setq wd (match-string 1 s))
25765 (if (setq ass (assoc wd org-html-entities))
25766 (setq s (replace-match (or (cdr ass)
25767 (concat "&" (car ass) ";"))
25768 t t s))
25769 (setq start (+ start (length wd))))))))
25772 (defun org-create-multibrace-regexp (left right n)
25773 "Create a regular expression which will match a balanced sexp.
25774 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25775 as single character strings.
25776 The regexp returned will match the entire expression including the
25777 delimiters. It will also define a single group which contains the
25778 match except for the outermost delimiters. The maximum depth of
25779 stacked delimiters is N. Escaping delimiters is not possible."
25780 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25781 (or "\\|")
25782 (re nothing)
25783 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25784 (while (> n 1)
25785 (setq n (1- n)
25786 re (concat re or next)
25787 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25788 (concat left "\\(" re "\\)" right)))
25790 (defvar org-match-substring-regexp
25791 (concat
25792 "\\([^\\]\\)\\([_^]\\)\\("
25793 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25794 "\\|"
25795 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25796 "\\|"
25797 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25798 "The regular expression matching a sub- or superscript.")
25800 (defvar org-match-substring-with-braces-regexp
25801 (concat
25802 "\\([^\\]\\)\\([_^]\\)\\("
25803 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25804 "\\)")
25805 "The regular expression matching a sub- or superscript, forcing braces.")
25807 (defconst org-export-html-special-string-regexps
25808 '(("\\\\-" . "&shy;")
25809 ("---\\([^-]\\)" . "&mdash;\\1")
25810 ("--\\([^-]\\)" . "&ndash;\\1")
25811 ("\\.\\.\\." . "&hellip;"))
25812 "Regular expressions for special string conversion.")
25814 (defun org-export-html-convert-special-strings (string)
25815 "Convert special characters in STRING to HTML."
25816 (let ((all org-export-html-special-string-regexps)
25817 e a re rpl start)
25818 (while (setq a (pop all))
25819 (setq re (car a) rpl (cdr a) start 0)
25820 (while (string-match re string start)
25821 (if (get-text-property (match-beginning 0) 'org-protected string)
25822 (setq start (match-end 0))
25823 (setq string (replace-match rpl t nil string)))))
25824 string))
25826 (defun org-export-html-convert-sub-super (string)
25827 "Convert sub- and superscripts in STRING to HTML."
25828 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25829 (while (string-match org-match-substring-regexp string s)
25830 (cond
25831 ((and requireb (match-end 8)) (setq s (match-end 2)))
25832 ((get-text-property (match-beginning 2) 'org-protected string)
25833 (setq s (match-end 2)))
25835 (setq s (match-end 1)
25836 key (if (string= (match-string 2 string) "_") "sub" "sup")
25837 c (or (match-string 8 string)
25838 (match-string 6 string)
25839 (match-string 5 string))
25840 string (replace-match
25841 (concat (match-string 1 string)
25842 "<" key ">" c "</" key ">")
25843 t t string)))))
25844 (while (string-match "\\\\\\([_^]\\)" string)
25845 (setq string (replace-match (match-string 1 string) t t string)))
25846 string))
25848 (defun org-export-html-convert-emphasize (string)
25849 "Apply emphasis."
25850 (let ((s 0) rpl)
25851 (while (string-match org-emph-re string s)
25852 (if (not (equal
25853 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25854 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25855 (setq s (match-beginning 0)
25857 (concat
25858 (match-string 1 string)
25859 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25860 (match-string 4 string)
25861 (nth 3 (assoc (match-string 3 string)
25862 org-emphasis-alist))
25863 (match-string 5 string))
25864 string (replace-match rpl t t string)
25865 s (+ s (- (length rpl) 2)))
25866 (setq s (1+ s))))
25867 string))
25869 (defvar org-par-open nil)
25870 (defun org-open-par ()
25871 "Insert <p>, but first close previous paragraph if any."
25872 (org-close-par-maybe)
25873 (insert "\n<p>")
25874 (setq org-par-open t))
25875 (defun org-close-par-maybe ()
25876 "Close paragraph if there is one open."
25877 (when org-par-open
25878 (insert "</p>")
25879 (setq org-par-open nil)))
25880 (defun org-close-li ()
25881 "Close <li> if necessary."
25882 (org-close-par-maybe)
25883 (insert "</li>\n"))
25885 (defvar body-only) ; dynamically scoped into this.
25886 (defun org-html-level-start (level title umax with-toc head-count)
25887 "Insert a new level in HTML export.
25888 When TITLE is nil, just close all open levels."
25889 (org-close-par-maybe)
25890 (let ((l org-level-max))
25891 (while (>= l level)
25892 (if (aref org-levels-open (1- l))
25893 (progn
25894 (org-html-level-close l umax)
25895 (aset org-levels-open (1- l) nil)))
25896 (setq l (1- l)))
25897 (when title
25898 ;; If title is nil, this means this function is called to close
25899 ;; all levels, so the rest is done only if title is given
25900 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25901 (setq title (replace-match
25902 (if org-export-with-tags
25903 (save-match-data
25904 (concat
25905 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
25906 (mapconcat 'identity (org-split-string
25907 (match-string 1 title) ":")
25908 "&nbsp;")
25909 "</span>"))
25911 t t title)))
25912 (if (> level umax)
25913 (progn
25914 (if (aref org-levels-open (1- level))
25915 (progn
25916 (org-close-li)
25917 (insert "<li>" title "<br/>\n"))
25918 (aset org-levels-open (1- level) t)
25919 (org-close-par-maybe)
25920 (insert "<ul>\n<li>" title "<br/>\n")))
25921 (aset org-levels-open (1- level) t)
25922 (if (and org-export-with-section-numbers (not body-only))
25923 (setq title (concat (org-section-number level) " " title)))
25924 (setq level (+ level org-export-html-toplevel-hlevel -1))
25925 (if with-toc
25926 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
25927 level level head-count title level))
25928 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
25929 (org-open-par)))))
25931 (defun org-html-level-close (level max-outline-level)
25932 "Terminate one level in HTML export."
25933 (if (<= level max-outline-level)
25934 (insert "</div>\n")
25935 (org-close-li)
25936 (insert "</ul>\n")))
25938 ;;; iCalendar export
25940 ;;;###autoload
25941 (defun org-export-icalendar-this-file ()
25942 "Export current file as an iCalendar file.
25943 The iCalendar file will be located in the same directory as the Org-mode
25944 file, but with extension `.ics'."
25945 (interactive)
25946 (org-export-icalendar nil buffer-file-name))
25948 ;;;###autoload
25949 (defun org-export-icalendar-all-agenda-files ()
25950 "Export all files in `org-agenda-files' to iCalendar .ics files.
25951 Each iCalendar file will be located in the same directory as the Org-mode
25952 file, but with extension `.ics'."
25953 (interactive)
25954 (apply 'org-export-icalendar nil (org-agenda-files t)))
25956 ;;;###autoload
25957 (defun org-export-icalendar-combine-agenda-files ()
25958 "Export all files in `org-agenda-files' to a single combined iCalendar file.
25959 The file is stored under the name `org-combined-agenda-icalendar-file'."
25960 (interactive)
25961 (apply 'org-export-icalendar t (org-agenda-files t)))
25963 (defun org-export-icalendar (combine &rest files)
25964 "Create iCalendar files for all elements of FILES.
25965 If COMBINE is non-nil, combine all calendar entries into a single large
25966 file and store it under the name `org-combined-agenda-icalendar-file'."
25967 (save-excursion
25968 (org-prepare-agenda-buffers files)
25969 (let* ((dir (org-export-directory
25970 :ical (list :publishing-directory
25971 org-export-publishing-directory)))
25972 file ical-file ical-buffer category started org-agenda-new-buffers)
25974 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
25975 (when combine
25976 (setq ical-file
25977 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
25978 org-combined-agenda-icalendar-file
25979 (expand-file-name org-combined-agenda-icalendar-file dir))
25980 ical-buffer (org-get-agenda-file-buffer ical-file))
25981 (set-buffer ical-buffer) (erase-buffer))
25982 (while (setq file (pop files))
25983 (catch 'nextfile
25984 (org-check-agenda-file file)
25985 (set-buffer (org-get-agenda-file-buffer file))
25986 (unless combine
25987 (setq ical-file (concat (file-name-as-directory dir)
25988 (file-name-sans-extension
25989 (file-name-nondirectory buffer-file-name))
25990 ".ics"))
25991 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
25992 (with-current-buffer ical-buffer (erase-buffer)))
25993 (setq category (or org-category
25994 (file-name-sans-extension
25995 (file-name-nondirectory buffer-file-name))))
25996 (if (symbolp category) (setq category (symbol-name category)))
25997 (let ((standard-output ical-buffer))
25998 (if combine
25999 (and (not started) (setq started t)
26000 (org-start-icalendar-file org-icalendar-combined-name))
26001 (org-start-icalendar-file category))
26002 (org-print-icalendar-entries combine)
26003 (when (or (and combine (not files)) (not combine))
26004 (org-finish-icalendar-file)
26005 (set-buffer ical-buffer)
26006 (save-buffer)
26007 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26008 (org-release-buffers org-agenda-new-buffers))))
26010 (defvar org-after-save-iCalendar-file-hook nil
26011 "Hook run after an iCalendar file has been saved.
26012 The iCalendar buffer is still current when this hook is run.
26013 A good way to use this is to tell a desktop calenndar application to re-read
26014 the iCalendar file.")
26016 (defun org-print-icalendar-entries (&optional combine)
26017 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26018 When COMBINE is non nil, add the category to each line."
26019 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26020 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26021 (dts (org-ical-ts-to-string
26022 (format-time-string (cdr org-time-stamp-formats) (current-time))
26023 "DTSTART"))
26024 hd ts ts2 state status (inc t) pos b sexp rrule
26025 scheduledp deadlinep tmp pri category entry location summary desc
26026 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26027 (org-refresh-category-properties)
26028 (save-excursion
26029 (goto-char (point-min))
26030 (while (re-search-forward re1 nil t)
26031 (catch :skip
26032 (org-agenda-skip)
26033 (setq pos (match-beginning 0)
26034 ts (match-string 0)
26035 inc t
26036 hd (org-get-heading)
26037 summary (org-icalendar-cleanup-string
26038 (org-entry-get nil "SUMMARY"))
26039 desc (org-icalendar-cleanup-string
26040 (or (org-entry-get nil "DESCRIPTION")
26041 (and org-icalendar-include-body (org-get-entry)))
26042 t org-icalendar-include-body)
26043 location (org-icalendar-cleanup-string
26044 (org-entry-get nil "LOCATION"))
26045 category (org-get-category))
26046 (if (looking-at re2)
26047 (progn
26048 (goto-char (match-end 0))
26049 (setq ts2 (match-string 1) inc nil))
26050 (setq tmp (buffer-substring (max (point-min)
26051 (- pos org-ds-keyword-length))
26052 pos)
26053 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26054 (progn
26055 (setq inc nil)
26056 (replace-match "\\1" t nil ts))
26058 deadlinep (string-match org-deadline-regexp tmp)
26059 scheduledp (string-match org-scheduled-regexp tmp)
26060 ;; donep (org-entry-is-done-p)
26062 (if (or (string-match org-tr-regexp hd)
26063 (string-match org-ts-regexp hd))
26064 (setq hd (replace-match "" t t hd)))
26065 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26066 (setq rrule
26067 (concat "\nRRULE:FREQ="
26068 (cdr (assoc
26069 (match-string 2 ts)
26070 '(("d" . "DAILY")("w" . "WEEKLY")
26071 ("m" . "MONTHLY")("y" . "YEARLY"))))
26072 ";INTERVAL=" (match-string 1 ts)))
26073 (setq rrule ""))
26074 (setq summary (or summary hd))
26075 (if (string-match org-bracket-link-regexp summary)
26076 (setq summary
26077 (replace-match (if (match-end 3)
26078 (match-string 3 summary)
26079 (match-string 1 summary))
26080 t t summary)))
26081 (if deadlinep (setq summary (concat "DL: " summary)))
26082 (if scheduledp (setq summary (concat "S: " summary)))
26083 (if (string-match "\\`<%%" ts)
26084 (with-current-buffer sexp-buffer
26085 (insert (substring ts 1 -1) " " summary "\n"))
26086 (princ (format "BEGIN:VEVENT
26088 %s%s
26089 SUMMARY:%s%s%s
26090 CATEGORIES:%s
26091 END:VEVENT\n"
26092 (org-ical-ts-to-string ts "DTSTART")
26093 (org-ical-ts-to-string ts2 "DTEND" inc)
26094 rrule summary
26095 (if (and desc (string-match "\\S-" desc))
26096 (concat "\nDESCRIPTION: " desc) "")
26097 (if (and location (string-match "\\S-" location))
26098 (concat "\nLOCATION: " location) "")
26099 category)))))
26101 (when (and org-icalendar-include-sexps
26102 (condition-case nil (require 'icalendar) (error nil))
26103 (fboundp 'icalendar-export-region))
26104 ;; Get all the literal sexps
26105 (goto-char (point-min))
26106 (while (re-search-forward "^&?%%(" nil t)
26107 (catch :skip
26108 (org-agenda-skip)
26109 (setq b (match-beginning 0))
26110 (goto-char (1- (match-end 0)))
26111 (forward-sexp 1)
26112 (end-of-line 1)
26113 (setq sexp (buffer-substring b (point)))
26114 (with-current-buffer sexp-buffer
26115 (insert sexp "\n"))
26116 (princ (org-diary-to-ical-string sexp-buffer)))))
26118 (when org-icalendar-include-todo
26119 (goto-char (point-min))
26120 (while (re-search-forward org-todo-line-regexp nil t)
26121 (catch :skip
26122 (org-agenda-skip)
26123 (setq state (match-string 2))
26124 (setq status (if (member state org-done-keywords)
26125 "COMPLETED" "NEEDS-ACTION"))
26126 (when (and state
26127 (or (not (member state org-done-keywords))
26128 (eq org-icalendar-include-todo 'all))
26129 (not (member org-archive-tag (org-get-tags-at)))
26131 (setq hd (match-string 3)
26132 summary (org-icalendar-cleanup-string
26133 (org-entry-get nil "SUMMARY"))
26134 desc (org-icalendar-cleanup-string
26135 (or (org-entry-get nil "DESCRIPTION")
26136 (and org-icalendar-include-body (org-get-entry)))
26137 t org-icalendar-include-body)
26138 location (org-icalendar-cleanup-string
26139 (org-entry-get nil "LOCATION")))
26140 (if (string-match org-bracket-link-regexp hd)
26141 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26142 (match-string 1 hd))
26143 t t hd)))
26144 (if (string-match org-priority-regexp hd)
26145 (setq pri (string-to-char (match-string 2 hd))
26146 hd (concat (substring hd 0 (match-beginning 1))
26147 (substring hd (match-end 1))))
26148 (setq pri org-default-priority))
26149 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26150 (- org-lowest-priority org-highest-priority))))))
26152 (princ (format "BEGIN:VTODO
26154 SUMMARY:%s%s%s
26155 CATEGORIES:%s
26156 SEQUENCE:1
26157 PRIORITY:%d
26158 STATUS:%s
26159 END:VTODO\n"
26161 (or summary hd)
26162 (if (and location (string-match "\\S-" location))
26163 (concat "\nLOCATION: " location) "")
26164 (if (and desc (string-match "\\S-" desc))
26165 (concat "\nDESCRIPTION: " desc) "")
26166 category pri status)))))))))
26168 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26169 "Take out stuff and quote what needs to be quoted.
26170 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26171 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26172 characters."
26173 (if (not s)
26175 (when is-body
26176 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26177 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26178 (while (string-match re s) (setq s (replace-match "" t t s)))
26179 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26180 (let ((start 0))
26181 (while (string-match "\\([,;\\]\\)" s start)
26182 (setq start (+ (match-beginning 0) 2)
26183 s (replace-match "\\\\\\1" nil nil s))))
26184 (when is-body
26185 (while (string-match "[ \t]*\n[ \t]*" s)
26186 (setq s (replace-match "\\n" t t s))))
26187 (setq s (org-trim s))
26188 (if is-body
26189 (if maxlength
26190 (if (and (numberp maxlength)
26191 (> (length s) maxlength))
26192 (setq s (substring s 0 maxlength)))))
26195 (defun org-get-entry ()
26196 "Clean-up description string."
26197 (save-excursion
26198 (org-back-to-heading t)
26199 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26201 (defun org-start-icalendar-file (name)
26202 "Start an iCalendar file by inserting the header."
26203 (let ((user user-full-name)
26204 (name (or name "unknown"))
26205 (timezone (cadr (current-time-zone))))
26206 (princ
26207 (format "BEGIN:VCALENDAR
26208 VERSION:2.0
26209 X-WR-CALNAME:%s
26210 PRODID:-//%s//Emacs with Org-mode//EN
26211 X-WR-TIMEZONE:%s
26212 CALSCALE:GREGORIAN\n" name user timezone))))
26214 (defun org-finish-icalendar-file ()
26215 "Finish an iCalendar file by inserting the END statement."
26216 (princ "END:VCALENDAR\n"))
26218 (defun org-ical-ts-to-string (s keyword &optional inc)
26219 "Take a time string S and convert it to iCalendar format.
26220 KEYWORD is added in front, to make a complete line like DTSTART....
26221 When INC is non-nil, increase the hour by two (if time string contains
26222 a time), or the day by one (if it does not contain a time)."
26223 (let ((t1 (org-parse-time-string s 'nodefault))
26224 t2 fmt have-time time)
26225 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26226 (setq t2 t1 have-time t)
26227 (setq t2 (org-parse-time-string s)))
26228 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26229 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26230 (when inc
26231 (if have-time
26232 (if org-agenda-default-appointment-duration
26233 (setq mi (+ org-agenda-default-appointment-duration mi))
26234 (setq h (+ 2 h)))
26235 (setq d (1+ d))))
26236 (setq time (encode-time s mi h d m y)))
26237 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26238 (concat keyword (format-time-string fmt time))))
26240 ;;; XOXO export
26242 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26243 (with-current-buffer buffer
26244 (apply 'insert output)))
26245 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26247 (defun org-export-as-xoxo (&optional buffer)
26248 "Export the org buffer as XOXO.
26249 The XOXO buffer is named *xoxo-<source buffer name>*"
26250 (interactive (list (current-buffer)))
26251 ;; A quickie abstraction
26253 ;; Output everything as XOXO
26254 (with-current-buffer (get-buffer buffer)
26255 (let* ((pos (point))
26256 (opt-plist (org-combine-plists (org-default-export-plist)
26257 (org-infile-export-plist)))
26258 (filename (concat (file-name-as-directory
26259 (org-export-directory :xoxo opt-plist))
26260 (file-name-sans-extension
26261 (file-name-nondirectory buffer-file-name))
26262 ".html"))
26263 (out (find-file-noselect filename))
26264 (last-level 1)
26265 (hanging-li nil))
26266 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26267 ;; Check the output buffer is empty.
26268 (with-current-buffer out (erase-buffer))
26269 ;; Kick off the output
26270 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26271 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26272 (let* ((hd (match-string-no-properties 1))
26273 (level (length hd))
26274 (text (concat
26275 (match-string-no-properties 2)
26276 (save-excursion
26277 (goto-char (match-end 0))
26278 (let ((str ""))
26279 (catch 'loop
26280 (while 't
26281 (forward-line)
26282 (if (looking-at "^[ \t]\\(.*\\)")
26283 (setq str (concat str (match-string-no-properties 1)))
26284 (throw 'loop str)))))))))
26286 ;; Handle level rendering
26287 (cond
26288 ((> level last-level)
26289 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26291 ((< level last-level)
26292 (dotimes (- (- last-level level) 1)
26293 (if hanging-li
26294 (org-export-as-xoxo-insert-into out "</li>\n"))
26295 (org-export-as-xoxo-insert-into out "</ol>\n"))
26296 (when hanging-li
26297 (org-export-as-xoxo-insert-into out "</li>\n")
26298 (setq hanging-li nil)))
26300 ((equal level last-level)
26301 (if hanging-li
26302 (org-export-as-xoxo-insert-into out "</li>\n")))
26305 (setq last-level level)
26307 ;; And output the new li
26308 (setq hanging-li 't)
26309 (if (equal ?+ (elt text 0))
26310 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26311 (org-export-as-xoxo-insert-into out "<li>" text))))
26313 ;; Finally finish off the ol
26314 (dotimes (- last-level 1)
26315 (if hanging-li
26316 (org-export-as-xoxo-insert-into out "</li>\n"))
26317 (org-export-as-xoxo-insert-into out "</ol>\n"))
26319 (goto-char pos)
26320 ;; Finish the buffer off and clean it up.
26321 (switch-to-buffer-other-window out)
26322 (indent-region (point-min) (point-max) nil)
26323 (save-buffer)
26324 (goto-char (point-min))
26328 ;;;; Key bindings
26330 ;; Make `C-c C-x' a prefix key
26331 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26333 ;; TAB key with modifiers
26334 (org-defkey org-mode-map "\C-i" 'org-cycle)
26335 (org-defkey org-mode-map [(tab)] 'org-cycle)
26336 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26337 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26338 (org-defkey org-mode-map "\M-\t" 'org-complete)
26339 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26340 ;; The following line is necessary under Suse GNU/Linux
26341 (unless (featurep 'xemacs)
26342 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26343 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26344 (define-key org-mode-map [backtab] 'org-shifttab)
26346 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26347 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26348 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26350 ;; Cursor keys with modifiers
26351 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26352 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26353 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26354 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26356 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26357 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26358 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26359 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26361 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26362 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26363 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26364 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26366 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26367 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26369 ;;; Extra keys for tty access.
26370 ;; We only set them when really needed because otherwise the
26371 ;; menus don't show the simple keys
26373 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26374 (not window-system))
26375 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26376 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26377 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26378 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26379 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26380 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26381 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26382 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26383 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26384 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26385 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26386 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26387 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26388 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26389 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26390 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26391 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26392 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26393 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26394 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26395 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26396 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26398 ;; All the other keys
26400 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26401 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26402 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26403 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26404 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26405 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26406 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26407 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26408 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26409 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26410 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26411 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26412 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26413 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26414 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26415 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26416 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26417 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26418 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26419 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26420 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26421 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26422 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26423 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26424 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26425 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26426 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26427 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26428 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26429 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26430 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26431 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26432 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26433 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26434 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26435 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26436 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26437 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26438 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26439 (org-defkey org-mode-map "\C-c^" 'org-sort)
26440 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26441 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26442 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26443 (org-defkey org-mode-map "\C-m" 'org-return)
26444 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26445 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26446 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26447 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26448 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26449 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26450 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26451 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26452 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26453 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26454 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26455 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26456 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26457 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26458 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26459 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26460 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26462 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26463 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26464 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26465 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26467 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26468 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26469 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26470 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26471 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26472 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26473 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26474 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26475 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26476 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26477 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26478 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26480 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26482 (when (featurep 'xemacs)
26483 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26485 (defsubst org-table-p () (org-at-table-p))
26487 (defun org-self-insert-command (N)
26488 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26489 If the cursor is in a table looking at whitespace, the whitespace is
26490 overwritten, and the table is not marked as requiring realignment."
26491 (interactive "p")
26492 (if (and (org-table-p)
26493 (progn
26494 ;; check if we blank the field, and if that triggers align
26495 (and org-table-auto-blank-field
26496 (member last-command
26497 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26498 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26499 ;; got extra space, this field does not determine column width
26500 (let (org-table-may-need-update) (org-table-blank-field))
26501 ;; no extra space, this field may determine column width
26502 (org-table-blank-field)))
26504 (eq N 1)
26505 (looking-at "[^|\n]* |"))
26506 (let (org-table-may-need-update)
26507 (goto-char (1- (match-end 0)))
26508 (delete-backward-char 1)
26509 (goto-char (match-beginning 0))
26510 (self-insert-command N))
26511 (setq org-table-may-need-update t)
26512 (self-insert-command N)
26513 (org-fix-tags-on-the-fly)))
26515 (defun org-fix-tags-on-the-fly ()
26516 (when (and (equal (char-after (point-at-bol)) ?*)
26517 (org-on-heading-p))
26518 (org-align-tags-here org-tags-column)))
26520 (defun org-delete-backward-char (N)
26521 "Like `delete-backward-char', insert whitespace at field end in tables.
26522 When deleting backwards, in tables this function will insert whitespace in
26523 front of the next \"|\" separator, to keep the table aligned. The table will
26524 still be marked for re-alignment if the field did fill the entire column,
26525 because, in this case the deletion might narrow the column."
26526 (interactive "p")
26527 (if (and (org-table-p)
26528 (eq N 1)
26529 (string-match "|" (buffer-substring (point-at-bol) (point)))
26530 (looking-at ".*?|"))
26531 (let ((pos (point))
26532 (noalign (looking-at "[^|\n\r]* |"))
26533 (c org-table-may-need-update))
26534 (backward-delete-char N)
26535 (skip-chars-forward "^|")
26536 (insert " ")
26537 (goto-char (1- pos))
26538 ;; noalign: if there were two spaces at the end, this field
26539 ;; does not determine the width of the column.
26540 (if noalign (setq org-table-may-need-update c)))
26541 (backward-delete-char N)
26542 (org-fix-tags-on-the-fly)))
26544 (defun org-delete-char (N)
26545 "Like `delete-char', but insert whitespace at field end in tables.
26546 When deleting characters, in tables this function will insert whitespace in
26547 front of the next \"|\" separator, to keep the table aligned. The table will
26548 still be marked for re-alignment if the field did fill the entire column,
26549 because, in this case the deletion might narrow the column."
26550 (interactive "p")
26551 (if (and (org-table-p)
26552 (not (bolp))
26553 (not (= (char-after) ?|))
26554 (eq N 1))
26555 (if (looking-at ".*?|")
26556 (let ((pos (point))
26557 (noalign (looking-at "[^|\n\r]* |"))
26558 (c org-table-may-need-update))
26559 (replace-match (concat
26560 (substring (match-string 0) 1 -1)
26561 " |"))
26562 (goto-char pos)
26563 ;; noalign: if there were two spaces at the end, this field
26564 ;; does not determine the width of the column.
26565 (if noalign (setq org-table-may-need-update c)))
26566 (delete-char N))
26567 (delete-char N)
26568 (org-fix-tags-on-the-fly)))
26570 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26571 (put 'org-self-insert-command 'delete-selection t)
26572 (put 'orgtbl-self-insert-command 'delete-selection t)
26573 (put 'org-delete-char 'delete-selection 'supersede)
26574 (put 'org-delete-backward-char 'delete-selection 'supersede)
26576 ;; Make `flyspell-mode' delay after some commands
26577 (put 'org-self-insert-command 'flyspell-delayed t)
26578 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26579 (put 'org-delete-char 'flyspell-delayed t)
26580 (put 'org-delete-backward-char 'flyspell-delayed t)
26582 ;; Make pabbrev-mode expand after org-mode commands
26583 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26584 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26586 ;; How to do this: Measure non-white length of current string
26587 ;; If equal to column width, we should realign.
26589 (defun org-remap (map &rest commands)
26590 "In MAP, remap the functions given in COMMANDS.
26591 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26592 (let (new old)
26593 (while commands
26594 (setq old (pop commands) new (pop commands))
26595 (if (fboundp 'command-remapping)
26596 (org-defkey map (vector 'remap old) new)
26597 (substitute-key-definition old new map global-map)))))
26599 (when (eq org-enable-table-editor 'optimized)
26600 ;; If the user wants maximum table support, we need to hijack
26601 ;; some standard editing functions
26602 (org-remap org-mode-map
26603 'self-insert-command 'org-self-insert-command
26604 'delete-char 'org-delete-char
26605 'delete-backward-char 'org-delete-backward-char)
26606 (org-defkey org-mode-map "|" 'org-force-self-insert))
26608 (defun org-shiftcursor-error ()
26609 "Throw an error because Shift-Cursor command was applied in wrong context."
26610 (error "This command is active in special context like tables, headlines or timestamps"))
26612 (defun org-shifttab (&optional arg)
26613 "Global visibility cycling or move to previous table field.
26614 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26615 on context.
26616 See the individual commands for more information."
26617 (interactive "P")
26618 (cond
26619 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26620 (arg (message "Content view to level: ")
26621 (org-content (prefix-numeric-value arg))
26622 (setq org-cycle-global-status 'overview))
26623 (t (call-interactively 'org-global-cycle))))
26625 (defun org-shiftmetaleft ()
26626 "Promote subtree or delete table column.
26627 Calls `org-promote-subtree', `org-outdent-item',
26628 or `org-table-delete-column', depending on context.
26629 See the individual commands for more information."
26630 (interactive)
26631 (cond
26632 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26633 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26634 ((org-at-item-p) (call-interactively 'org-outdent-item))
26635 (t (org-shiftcursor-error))))
26637 (defun org-shiftmetaright ()
26638 "Demote subtree or insert table column.
26639 Calls `org-demote-subtree', `org-indent-item',
26640 or `org-table-insert-column', depending on context.
26641 See the individual commands for more information."
26642 (interactive)
26643 (cond
26644 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26645 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26646 ((org-at-item-p) (call-interactively 'org-indent-item))
26647 (t (org-shiftcursor-error))))
26649 (defun org-shiftmetaup (&optional arg)
26650 "Move subtree up or kill table row.
26651 Calls `org-move-subtree-up' or `org-table-kill-row' or
26652 `org-move-item-up' depending on context. See the individual commands
26653 for more information."
26654 (interactive "P")
26655 (cond
26656 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26657 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26658 ((org-at-item-p) (call-interactively 'org-move-item-up))
26659 (t (org-shiftcursor-error))))
26660 (defun org-shiftmetadown (&optional arg)
26661 "Move subtree down or insert table row.
26662 Calls `org-move-subtree-down' or `org-table-insert-row' or
26663 `org-move-item-down', depending on context. See the individual
26664 commands for more information."
26665 (interactive "P")
26666 (cond
26667 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26668 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26669 ((org-at-item-p) (call-interactively 'org-move-item-down))
26670 (t (org-shiftcursor-error))))
26672 (defun org-metaleft (&optional arg)
26673 "Promote heading or move table column to left.
26674 Calls `org-do-promote' or `org-table-move-column', depending on context.
26675 With no specific context, calls the Emacs default `backward-word'.
26676 See the individual commands for more information."
26677 (interactive "P")
26678 (cond
26679 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26680 ((or (org-on-heading-p) (org-region-active-p))
26681 (call-interactively 'org-do-promote))
26682 ((org-at-item-p) (call-interactively 'org-outdent-item))
26683 (t (call-interactively 'backward-word))))
26685 (defun org-metaright (&optional arg)
26686 "Demote subtree or move table column to right.
26687 Calls `org-do-demote' or `org-table-move-column', depending on context.
26688 With no specific context, calls the Emacs default `forward-word'.
26689 See the individual commands for more information."
26690 (interactive "P")
26691 (cond
26692 ((org-at-table-p) (call-interactively 'org-table-move-column))
26693 ((or (org-on-heading-p) (org-region-active-p))
26694 (call-interactively 'org-do-demote))
26695 ((org-at-item-p) (call-interactively 'org-indent-item))
26696 (t (call-interactively 'forward-word))))
26698 (defun org-metaup (&optional arg)
26699 "Move subtree up or move table row up.
26700 Calls `org-move-subtree-up' or `org-table-move-row' or
26701 `org-move-item-up', depending on context. See the individual commands
26702 for more information."
26703 (interactive "P")
26704 (cond
26705 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26706 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26707 ((org-at-item-p) (call-interactively 'org-move-item-up))
26708 (t (transpose-lines 1) (beginning-of-line -1))))
26710 (defun org-metadown (&optional arg)
26711 "Move subtree down or move table row down.
26712 Calls `org-move-subtree-down' or `org-table-move-row' or
26713 `org-move-item-down', depending on context. See the individual
26714 commands for more information."
26715 (interactive "P")
26716 (cond
26717 ((org-at-table-p) (call-interactively 'org-table-move-row))
26718 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26719 ((org-at-item-p) (call-interactively 'org-move-item-down))
26720 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26722 (defun org-shiftup (&optional arg)
26723 "Increase item in timestamp or increase priority of current headline.
26724 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26725 depending on context. See the individual commands for more information."
26726 (interactive "P")
26727 (cond
26728 ((org-at-timestamp-p t)
26729 (call-interactively (if org-edit-timestamp-down-means-later
26730 'org-timestamp-down 'org-timestamp-up)))
26731 ((org-on-heading-p) (call-interactively 'org-priority-up))
26732 ((org-at-item-p) (call-interactively 'org-previous-item))
26733 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26735 (defun org-shiftdown (&optional arg)
26736 "Decrease item in timestamp or decrease priority of current headline.
26737 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26738 depending on context. See the individual commands for more information."
26739 (interactive "P")
26740 (cond
26741 ((org-at-timestamp-p t)
26742 (call-interactively (if org-edit-timestamp-down-means-later
26743 'org-timestamp-up 'org-timestamp-down)))
26744 ((org-on-heading-p) (call-interactively 'org-priority-down))
26745 (t (call-interactively 'org-next-item))))
26747 (defun org-shiftright ()
26748 "Next TODO keyword or timestamp one day later, depending on context."
26749 (interactive)
26750 (cond
26751 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26752 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26753 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26754 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26755 (t (org-shiftcursor-error))))
26757 (defun org-shiftleft ()
26758 "Previous TODO keyword or timestamp one day earlier, depending on context."
26759 (interactive)
26760 (cond
26761 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26762 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26763 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26764 ((org-at-property-p)
26765 (call-interactively 'org-property-previous-allowed-value))
26766 (t (org-shiftcursor-error))))
26768 (defun org-shiftcontrolright ()
26769 "Switch to next TODO set."
26770 (interactive)
26771 (cond
26772 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26773 (t (org-shiftcursor-error))))
26775 (defun org-shiftcontrolleft ()
26776 "Switch to previous TODO set."
26777 (interactive)
26778 (cond
26779 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26780 (t (org-shiftcursor-error))))
26782 (defun org-ctrl-c-ret ()
26783 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26784 (interactive)
26785 (cond
26786 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26787 (t (call-interactively 'org-insert-heading))))
26789 (defun org-copy-special ()
26790 "Copy region in table or copy current subtree.
26791 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26792 See the individual commands for more information."
26793 (interactive)
26794 (call-interactively
26795 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26797 (defun org-cut-special ()
26798 "Cut region in table or cut current subtree.
26799 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26800 See the individual commands for more information."
26801 (interactive)
26802 (call-interactively
26803 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26805 (defun org-paste-special (arg)
26806 "Paste rectangular region into table, or past subtree relative to level.
26807 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26808 See the individual commands for more information."
26809 (interactive "P")
26810 (if (org-at-table-p)
26811 (org-table-paste-rectangle)
26812 (org-paste-subtree arg)))
26814 (defun org-ctrl-c-ctrl-c (&optional arg)
26815 "Set tags in headline, or update according to changed information at point.
26817 This command does many different things, depending on context:
26819 - If the cursor is in a headline, prompt for tags and insert them
26820 into the current line, aligned to `org-tags-column'. When called
26821 with prefix arg, realign all tags in the current buffer.
26823 - If the cursor is in one of the special #+KEYWORD lines, this
26824 triggers scanning the buffer for these lines and updating the
26825 information.
26827 - If the cursor is inside a table, realign the table. This command
26828 works even if the automatic table editor has been turned off.
26830 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26831 the entire table.
26833 - If the cursor is a the beginning of a dynamic block, update it.
26835 - If the cursor is inside a table created by the table.el package,
26836 activate that table.
26838 - If the current buffer is a remember buffer, close note and file it.
26839 with a prefix argument, file it without further interaction to the default
26840 location.
26842 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26843 links in this buffer.
26845 - If the cursor is on a numbered item in a plain list, renumber the
26846 ordered list.
26848 - If the cursor is on a checkbox, toggle it."
26849 (interactive "P")
26850 (let ((org-enable-table-editor t))
26851 (cond
26852 ((or org-clock-overlays
26853 org-occur-highlights
26854 org-latex-fragment-image-overlays)
26855 (org-remove-clock-overlays)
26856 (org-remove-occur-highlights)
26857 (org-remove-latex-fragment-image-overlays)
26858 (message "Temporary highlights/overlays removed from current buffer"))
26859 ((and (local-variable-p 'org-finish-function (current-buffer))
26860 (fboundp org-finish-function))
26861 (funcall org-finish-function))
26862 ((org-at-property-p)
26863 (call-interactively 'org-property-action))
26864 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
26865 ((org-on-heading-p) (call-interactively 'org-set-tags))
26866 ((org-at-table.el-p)
26867 (require 'table)
26868 (beginning-of-line 1)
26869 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
26870 (call-interactively 'table-recognize-table))
26871 ((org-at-table-p)
26872 (org-table-maybe-eval-formula)
26873 (if arg
26874 (call-interactively 'org-table-recalculate)
26875 (org-table-maybe-recalculate-line))
26876 (call-interactively 'org-table-align))
26877 ((org-at-item-checkbox-p)
26878 (call-interactively 'org-toggle-checkbox))
26879 ((org-at-item-p)
26880 (call-interactively 'org-maybe-renumber-ordered-list))
26881 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
26882 ;; Dynamic block
26883 (beginning-of-line 1)
26884 (org-update-dblock))
26885 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
26886 (cond
26887 ((equal (match-string 1) "TBLFM")
26888 ;; Recalculate the table before this line
26889 (save-excursion
26890 (beginning-of-line 1)
26891 (skip-chars-backward " \r\n\t")
26892 (if (org-at-table-p)
26893 (org-call-with-arg 'org-table-recalculate t))))
26895 (call-interactively 'org-mode-restart))))
26896 (t (error "C-c C-c can do nothing useful at this location.")))))
26898 (defun org-mode-restart ()
26899 "Restart Org-mode, to scan again for special lines.
26900 Also updates the keyword regular expressions."
26901 (interactive)
26902 (let ((org-inhibit-startup t)) (org-mode))
26903 (message "Org-mode restarted to refresh keyword and special line setup"))
26905 (defun org-kill-note-or-show-branches ()
26906 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
26907 (interactive)
26908 (if (not org-finish-function)
26909 (call-interactively 'show-branches)
26910 (let ((org-note-abort t))
26911 (funcall org-finish-function))))
26913 (defun org-return (&optional indent)
26914 "Goto next table row or insert a newline.
26915 Calls `org-table-next-row' or `newline', depending on context.
26916 See the individual commands for more information."
26917 (interactive)
26918 (cond
26919 ((bobp) (if indent (newline-and-indent) (newline)))
26920 ((org-at-table-p)
26921 (org-table-justify-field-maybe)
26922 (call-interactively 'org-table-next-row))
26923 (t (if indent (newline-and-indent) (newline)))))
26925 (defun org-return-indent ()
26926 (interactive)
26927 "Goto next table row or insert a newline and indent.
26928 Calls `org-table-next-row' or `newline-and-indent', depending on
26929 context. See the individual commands for more information."
26930 (org-return t))
26932 (defun org-ctrl-c-minus ()
26933 "Insert separator line in table or modify bullet type in list.
26934 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
26935 depending on context."
26936 (interactive)
26937 (cond
26938 ((org-at-table-p)
26939 (call-interactively 'org-table-insert-hline))
26940 ((org-on-heading-p)
26941 ;; Convert to item
26942 (save-excursion
26943 (beginning-of-line 1)
26944 (if (looking-at "\\*+ ")
26945 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
26946 ((org-in-item-p)
26947 (call-interactively 'org-cycle-list-bullet))
26948 (t (error "`C-c -' does have no function here."))))
26950 (defun org-meta-return (&optional arg)
26951 "Insert a new heading or wrap a region in a table.
26952 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
26953 See the individual commands for more information."
26954 (interactive "P")
26955 (cond
26956 ((org-at-table-p)
26957 (call-interactively 'org-table-wrap-region))
26958 (t (call-interactively 'org-insert-heading))))
26960 ;;; Menu entries
26962 ;; Define the Org-mode menus
26963 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
26964 '("Tbl"
26965 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
26966 ["Next Field" org-cycle (org-at-table-p)]
26967 ["Previous Field" org-shifttab (org-at-table-p)]
26968 ["Next Row" org-return (org-at-table-p)]
26969 "--"
26970 ["Blank Field" org-table-blank-field (org-at-table-p)]
26971 ["Edit Field" org-table-edit-field (org-at-table-p)]
26972 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
26973 "--"
26974 ("Column"
26975 ["Move Column Left" org-metaleft (org-at-table-p)]
26976 ["Move Column Right" org-metaright (org-at-table-p)]
26977 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
26978 ["Insert Column" org-shiftmetaright (org-at-table-p)])
26979 ("Row"
26980 ["Move Row Up" org-metaup (org-at-table-p)]
26981 ["Move Row Down" org-metadown (org-at-table-p)]
26982 ["Delete Row" org-shiftmetaup (org-at-table-p)]
26983 ["Insert Row" org-shiftmetadown (org-at-table-p)]
26984 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
26985 "--"
26986 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
26987 ("Rectangle"
26988 ["Copy Rectangle" org-copy-special (org-at-table-p)]
26989 ["Cut Rectangle" org-cut-special (org-at-table-p)]
26990 ["Paste Rectangle" org-paste-special (org-at-table-p)]
26991 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
26992 "--"
26993 ("Calculate"
26994 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
26995 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
26996 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
26997 "--"
26998 ["Recalculate line" org-table-recalculate (org-at-table-p)]
26999 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27000 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27001 "--"
27002 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27003 "--"
27004 ["Sum Column/Rectangle" org-table-sum
27005 (or (org-at-table-p) (org-region-active-p))]
27006 ["Which Column?" org-table-current-column (org-at-table-p)])
27007 ["Debug Formulas"
27008 org-table-toggle-formula-debugger
27009 :style toggle :selected org-table-formula-debug]
27010 ["Show Col/Row Numbers"
27011 org-table-toggle-coordinate-overlays
27012 :style toggle :selected org-table-overlay-coordinates]
27013 "--"
27014 ["Create" org-table-create (and (not (org-at-table-p))
27015 org-enable-table-editor)]
27016 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27017 ["Import from File" org-table-import (not (org-at-table-p))]
27018 ["Export to File" org-table-export (org-at-table-p)]
27019 "--"
27020 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27022 (easy-menu-define org-org-menu org-mode-map "Org menu"
27023 '("Org"
27024 ("Show/Hide"
27025 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27026 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27027 ["Sparse Tree" org-occur t]
27028 ["Reveal Context" org-reveal t]
27029 ["Show All" show-all t]
27030 "--"
27031 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27032 "--"
27033 ["New Heading" org-insert-heading t]
27034 ("Navigate Headings"
27035 ["Up" outline-up-heading t]
27036 ["Next" outline-next-visible-heading t]
27037 ["Previous" outline-previous-visible-heading t]
27038 ["Next Same Level" outline-forward-same-level t]
27039 ["Previous Same Level" outline-backward-same-level t]
27040 "--"
27041 ["Jump" org-goto t])
27042 ("Edit Structure"
27043 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27044 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27045 "--"
27046 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27047 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27048 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27049 "--"
27050 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27051 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27052 ["Demote Heading" org-metaright (not (org-at-table-p))]
27053 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27054 "--"
27055 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27056 "--"
27057 ["Convert to odd levels" org-convert-to-odd-levels t]
27058 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27059 ("Editing"
27060 ["Emphasis..." org-emphasize t])
27061 ("Archive"
27062 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27063 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27064 ; :active t :keys "C-u C-c C-x C-a"]
27065 ["Sparse trees open ARCHIVE trees"
27066 (setq org-sparse-tree-open-archived-trees
27067 (not org-sparse-tree-open-archived-trees))
27068 :style toggle :selected org-sparse-tree-open-archived-trees]
27069 ["Cycling opens ARCHIVE trees"
27070 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27071 :style toggle :selected org-cycle-open-archived-trees]
27072 ["Agenda includes ARCHIVE trees"
27073 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27074 :style toggle :selected (not org-agenda-skip-archived-trees)]
27075 "--"
27076 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27077 ; ["Check and Move Children" (org-archive-subtree '(4))
27078 ; :active t :keys "C-u C-c C-x C-s"]
27080 "--"
27081 ("TODO Lists"
27082 ["TODO/DONE/-" org-todo t]
27083 ("Select keyword"
27084 ["Next keyword" org-shiftright (org-on-heading-p)]
27085 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27086 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27087 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27088 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27089 ["Show TODO Tree" org-show-todo-tree t]
27090 ["Global TODO list" org-todo-list t]
27091 "--"
27092 ["Set Priority" org-priority t]
27093 ["Priority Up" org-shiftup t]
27094 ["Priority Down" org-shiftdown t])
27095 ("TAGS and Properties"
27096 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27097 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27098 "--"
27099 ["Set property" 'org-set-property t]
27100 ["Column view of properties" org-columns t]
27101 ["Insert Column View DBlock" org-insert-columns-dblock t])
27102 ("Dates and Scheduling"
27103 ["Timestamp" org-time-stamp t]
27104 ["Timestamp (inactive)" org-time-stamp-inactive t]
27105 ("Change Date"
27106 ["1 Day Later" org-shiftright t]
27107 ["1 Day Earlier" org-shiftleft t]
27108 ["1 ... Later" org-shiftup t]
27109 ["1 ... Earlier" org-shiftdown t])
27110 ["Compute Time Range" org-evaluate-time-range t]
27111 ["Schedule Item" org-schedule t]
27112 ["Deadline" org-deadline t]
27113 "--"
27114 ["Custom time format" org-toggle-time-stamp-overlays
27115 :style radio :selected org-display-custom-times]
27116 "--"
27117 ["Goto Calendar" org-goto-calendar t]
27118 ["Date from Calendar" org-date-from-calendar t])
27119 ("Logging work"
27120 ["Clock in" org-clock-in t]
27121 ["Clock out" org-clock-out t]
27122 ["Clock cancel" org-clock-cancel t]
27123 ["Goto running clock" org-clock-goto t]
27124 ["Display times" org-clock-display t]
27125 ["Create clock table" org-clock-report t]
27126 "--"
27127 ["Record DONE time"
27128 (progn (setq org-log-done (not org-log-done))
27129 (message "Switching to %s will %s record a timestamp"
27130 (car org-done-keywords)
27131 (if org-log-done "automatically" "not")))
27132 :style toggle :selected org-log-done])
27133 "--"
27134 ["Agenda Command..." org-agenda t]
27135 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27136 ("File List for Agenda")
27137 ("Special views current file"
27138 ["TODO Tree" org-show-todo-tree t]
27139 ["Check Deadlines" org-check-deadlines t]
27140 ["Timeline" org-timeline t]
27141 ["Tags Tree" org-tags-sparse-tree t])
27142 "--"
27143 ("Hyperlinks"
27144 ["Store Link (Global)" org-store-link t]
27145 ["Insert Link" org-insert-link t]
27146 ["Follow Link" org-open-at-point t]
27147 "--"
27148 ["Next link" org-next-link t]
27149 ["Previous link" org-previous-link t]
27150 "--"
27151 ["Descriptive Links"
27152 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27153 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27154 ["Literal Links"
27155 (progn
27156 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27157 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27158 "--"
27159 ["Export/Publish..." org-export t]
27160 ("LaTeX"
27161 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27162 :selected org-cdlatex-mode]
27163 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27164 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27165 ["Modify math symbol" org-cdlatex-math-modify
27166 (org-inside-LaTeX-fragment-p)]
27167 ["Export LaTeX fragments as images"
27168 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27169 :style toggle :selected org-export-with-LaTeX-fragments])
27170 "--"
27171 ("Documentation"
27172 ["Show Version" org-version t]
27173 ["Info Documentation" org-info t])
27174 ("Customize"
27175 ["Browse Org Group" org-customize t]
27176 "--"
27177 ["Expand This Menu" org-create-customize-menu
27178 (fboundp 'customize-menu-create)])
27179 "--"
27180 ["Refresh setup" org-mode-restart t]
27183 (defun org-info (&optional node)
27184 "Read documentation for Org-mode in the info system.
27185 With optional NODE, go directly to that node."
27186 (interactive)
27187 (require 'info)
27188 (Info-goto-node (format "(org)%s" (or node ""))))
27190 (defun org-install-agenda-files-menu ()
27191 (let ((bl (buffer-list)))
27192 (save-excursion
27193 (while bl
27194 (set-buffer (pop bl))
27195 (if (org-mode-p) (setq bl nil)))
27196 (when (org-mode-p)
27197 (easy-menu-change
27198 '("Org") "File List for Agenda"
27199 (append
27200 (list
27201 ["Edit File List" (org-edit-agenda-file-list) t]
27202 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27203 ["Remove Current File from List" org-remove-file t]
27204 ["Cycle through agenda files" org-cycle-agenda-files t]
27205 ["Occur in all agenda files" org-occur-in-agenda-files t]
27206 "--")
27207 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27209 ;;;; Documentation
27211 (defun org-customize ()
27212 "Call the customize function with org as argument."
27213 (interactive)
27214 (customize-browse 'org))
27216 (defun org-create-customize-menu ()
27217 "Create a full customization menu for Org-mode, insert it into the menu."
27218 (interactive)
27219 (if (fboundp 'customize-menu-create)
27220 (progn
27221 (easy-menu-change
27222 '("Org") "Customize"
27223 `(["Browse Org group" org-customize t]
27224 "--"
27225 ,(customize-menu-create 'org)
27226 ["Set" Custom-set t]
27227 ["Save" Custom-save t]
27228 ["Reset to Current" Custom-reset-current t]
27229 ["Reset to Saved" Custom-reset-saved t]
27230 ["Reset to Standard Settings" Custom-reset-standard t]))
27231 (message "\"Org\"-menu now contains full customization menu"))
27232 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27234 ;;;; Miscellaneous stuff
27237 ;;; Generally useful functions
27239 (defun org-context ()
27240 "Return a list of contexts of the current cursor position.
27241 If several contexts apply, all are returned.
27242 Each context entry is a list with a symbol naming the context, and
27243 two positions indicating start and end of the context. Possible
27244 contexts are:
27246 :headline anywhere in a headline
27247 :headline-stars on the leading stars in a headline
27248 :todo-keyword on a TODO keyword (including DONE) in a headline
27249 :tags on the TAGS in a headline
27250 :priority on the priority cookie in a headline
27251 :item on the first line of a plain list item
27252 :item-bullet on the bullet/number of a plain list item
27253 :checkbox on the checkbox in a plain list item
27254 :table in an org-mode table
27255 :table-special on a special filed in a table
27256 :table-table in a table.el table
27257 :link on a hyperlink
27258 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27259 :target on a <<target>>
27260 :radio-target on a <<<radio-target>>>
27261 :latex-fragment on a LaTeX fragment
27262 :latex-preview on a LaTeX fragment with overlayed preview image
27264 This function expects the position to be visible because it uses font-lock
27265 faces as a help to recognize the following contexts: :table-special, :link,
27266 and :keyword."
27267 (let* ((f (get-text-property (point) 'face))
27268 (faces (if (listp f) f (list f)))
27269 (p (point)) clist o)
27270 ;; First the large context
27271 (cond
27272 ((org-on-heading-p t)
27273 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27274 (when (progn
27275 (beginning-of-line 1)
27276 (looking-at org-todo-line-tags-regexp))
27277 (push (org-point-in-group p 1 :headline-stars) clist)
27278 (push (org-point-in-group p 2 :todo-keyword) clist)
27279 (push (org-point-in-group p 4 :tags) clist))
27280 (goto-char p)
27281 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27282 (if (looking-at "\\[#[A-Z0-9]\\]")
27283 (push (org-point-in-group p 0 :priority) clist)))
27285 ((org-at-item-p)
27286 (push (org-point-in-group p 2 :item-bullet) clist)
27287 (push (list :item (point-at-bol)
27288 (save-excursion (org-end-of-item) (point)))
27289 clist)
27290 (and (org-at-item-checkbox-p)
27291 (push (org-point-in-group p 0 :checkbox) clist)))
27293 ((org-at-table-p)
27294 (push (list :table (org-table-begin) (org-table-end)) clist)
27295 (if (memq 'org-formula faces)
27296 (push (list :table-special
27297 (previous-single-property-change p 'face)
27298 (next-single-property-change p 'face)) clist)))
27299 ((org-at-table-p 'any)
27300 (push (list :table-table) clist)))
27301 (goto-char p)
27303 ;; Now the small context
27304 (cond
27305 ((org-at-timestamp-p)
27306 (push (org-point-in-group p 0 :timestamp) clist))
27307 ((memq 'org-link faces)
27308 (push (list :link
27309 (previous-single-property-change p 'face)
27310 (next-single-property-change p 'face)) clist))
27311 ((memq 'org-special-keyword faces)
27312 (push (list :keyword
27313 (previous-single-property-change p 'face)
27314 (next-single-property-change p 'face)) clist))
27315 ((org-on-target-p)
27316 (push (org-point-in-group p 0 :target) clist)
27317 (goto-char (1- (match-beginning 0)))
27318 (if (looking-at org-radio-target-regexp)
27319 (push (org-point-in-group p 0 :radio-target) clist))
27320 (goto-char p))
27321 ((setq o (car (delq nil
27322 (mapcar
27323 (lambda (x)
27324 (if (memq x org-latex-fragment-image-overlays) x))
27325 (org-overlays-at (point))))))
27326 (push (list :latex-fragment
27327 (org-overlay-start o) (org-overlay-end o)) clist)
27328 (push (list :latex-preview
27329 (org-overlay-start o) (org-overlay-end o)) clist))
27330 ((org-inside-LaTeX-fragment-p)
27331 ;; FIXME: positions wrong.
27332 (push (list :latex-fragment (point) (point)) clist)))
27334 (setq clist (nreverse (delq nil clist)))
27335 clist))
27337 ;; FIXME: Compare with at-regexp-p Do we need both?
27338 (defun org-in-regexp (re &optional nlines visually)
27339 "Check if point is inside a match of regexp.
27340 Normally only the current line is checked, but you can include NLINES extra
27341 lines both before and after point into the search.
27342 If VISUALLY is set, require that the cursor is not after the match but
27343 really on, so that the block visually is on the match."
27344 (catch 'exit
27345 (let ((pos (point))
27346 (eol (point-at-eol (+ 1 (or nlines 0))))
27347 (inc (if visually 1 0)))
27348 (save-excursion
27349 (beginning-of-line (- 1 (or nlines 0)))
27350 (while (re-search-forward re eol t)
27351 (if (and (<= (match-beginning 0) pos)
27352 (>= (+ inc (match-end 0)) pos))
27353 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27355 (defun org-at-regexp-p (regexp)
27356 "Is point inside a match of REGEXP in the current line?"
27357 (catch 'exit
27358 (save-excursion
27359 (let ((pos (point)) (end (point-at-eol)))
27360 (beginning-of-line 1)
27361 (while (re-search-forward regexp end t)
27362 (if (and (<= (match-beginning 0) pos)
27363 (>= (match-end 0) pos))
27364 (throw 'exit t)))
27365 nil))))
27367 (defun org-occur-in-agenda-files (regexp &optional nlines)
27368 "Call `multi-occur' with buffers for all agenda files."
27369 (interactive "sOrg-files matching: \np")
27370 (let* ((files (org-agenda-files))
27371 (tnames (mapcar 'file-truename files))
27372 (extra org-agenda-multi-occur-extra-files)
27374 (while (setq f (pop extra))
27375 (unless (member (file-truename f) tnames)
27376 (add-to-list 'files f 'append)
27377 (add-to-list 'tnames (file-truename f) 'append)))
27378 (multi-occur
27379 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27380 regexp)))
27382 (if (boundp 'occur-mode-find-occurrence-hook)
27383 ;; Emacs 23
27384 (add-hook 'occur-mode-find-occurrence-hook
27385 (lambda ()
27386 (when (org-mode-p)
27387 (org-reveal))))
27388 ;; Emacs 22
27389 (defadvice occur-mode-goto-occurrence
27390 (after org-occur-reveal activate)
27391 (and (org-mode-p) (org-reveal)))
27392 (defadvice occur-mode-goto-occurrence-other-window
27393 (after org-occur-reveal activate)
27394 (and (org-mode-p) (org-reveal)))
27395 (defadvice occur-mode-display-occurrence
27396 (after org-occur-reveal activate)
27397 (when (org-mode-p)
27398 (let ((pos (occur-mode-find-occurrence)))
27399 (with-current-buffer (marker-buffer pos)
27400 (save-excursion
27401 (goto-char pos)
27402 (org-reveal)))))))
27404 (defun org-uniquify (list)
27405 "Remove duplicate elements from LIST."
27406 (let (res)
27407 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27408 res))
27410 (defun org-delete-all (elts list)
27411 "Remove all elements in ELTS from LIST."
27412 (while elts
27413 (setq list (delete (pop elts) list)))
27414 list)
27416 (defun org-back-over-empty-lines ()
27417 "Move backwards over witespace, to the beginning of the first empty line.
27418 Returns the number o empty lines passed."
27419 (let ((pos (point)))
27420 (skip-chars-backward " \t\n\r")
27421 (beginning-of-line 2)
27422 (goto-char (min (point) pos))
27423 (count-lines (point) pos)))
27425 (defun org-skip-whitespace ()
27426 (skip-chars-forward " \t\n\r"))
27428 (defun org-point-in-group (point group &optional context)
27429 "Check if POINT is in match-group GROUP.
27430 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27431 match. If the match group does ot exist or point is not inside it,
27432 return nil."
27433 (and (match-beginning group)
27434 (>= point (match-beginning group))
27435 (<= point (match-end group))
27436 (if context
27437 (list context (match-beginning group) (match-end group))
27438 t)))
27440 (defun org-switch-to-buffer-other-window (&rest args)
27441 "Switch to buffer in a second window on the current frame.
27442 In particular, do not allow pop-up frames."
27443 (let (pop-up-frames special-display-buffer-names special-display-regexps
27444 special-display-function)
27445 (apply 'switch-to-buffer-other-window args)))
27447 (defun org-combine-plists (&rest plists)
27448 "Create a single property list from all plists in PLISTS.
27449 The process starts by copying the first list, and then setting properties
27450 from the other lists. Settings in the last list are the most significant
27451 ones and overrule settings in the other lists."
27452 (let ((rtn (copy-sequence (pop plists)))
27453 p v ls)
27454 (while plists
27455 (setq ls (pop plists))
27456 (while ls
27457 (setq p (pop ls) v (pop ls))
27458 (setq rtn (plist-put rtn p v))))
27459 rtn))
27461 (defun org-move-line-down (arg)
27462 "Move the current line down. With prefix argument, move it past ARG lines."
27463 (interactive "p")
27464 (let ((col (current-column))
27465 beg end pos)
27466 (beginning-of-line 1) (setq beg (point))
27467 (beginning-of-line 2) (setq end (point))
27468 (beginning-of-line (+ 1 arg))
27469 (setq pos (move-marker (make-marker) (point)))
27470 (insert (delete-and-extract-region beg end))
27471 (goto-char pos)
27472 (move-to-column col)))
27474 (defun org-move-line-up (arg)
27475 "Move the current line up. With prefix argument, move it past ARG lines."
27476 (interactive "p")
27477 (let ((col (current-column))
27478 beg end pos)
27479 (beginning-of-line 1) (setq beg (point))
27480 (beginning-of-line 2) (setq end (point))
27481 (beginning-of-line (- arg))
27482 (setq pos (move-marker (make-marker) (point)))
27483 (insert (delete-and-extract-region beg end))
27484 (goto-char pos)
27485 (move-to-column col)))
27487 (defun org-replace-escapes (string table)
27488 "Replace %-escapes in STRING with values in TABLE.
27489 TABLE is an association list with keys like \"%a\" and string values.
27490 The sequences in STRING may contain normal field width and padding information,
27491 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27492 so values can contain further %-escapes if they are define later in TABLE."
27493 (let ((case-fold-search nil)
27494 e re rpl)
27495 (while (setq e (pop table))
27496 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27497 (while (string-match re string)
27498 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27499 (cdr e)))
27500 (setq string (replace-match rpl t t string))))
27501 string))
27504 (defun org-sublist (list start end)
27505 "Return a section of LIST, from START to END.
27506 Counting starts at 1."
27507 (let (rtn (c start))
27508 (setq list (nthcdr (1- start) list))
27509 (while (and list (<= c end))
27510 (push (pop list) rtn)
27511 (setq c (1+ c)))
27512 (nreverse rtn)))
27514 (defun org-find-base-buffer-visiting (file)
27515 "Like `find-buffer-visiting' but alway return the base buffer and
27516 not an indirect buffer"
27517 (let ((buf (find-buffer-visiting file)))
27518 (if buf
27519 (or (buffer-base-buffer buf) buf)
27520 nil)))
27522 (defun org-image-file-name-regexp ()
27523 "Return regexp matching the file names of images."
27524 (if (fboundp 'image-file-name-regexp)
27525 (image-file-name-regexp)
27526 (let ((image-file-name-extensions
27527 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27528 "xbm" "xpm" "pbm" "pgm" "ppm")))
27529 (concat "\\."
27530 (regexp-opt (nconc (mapcar 'upcase
27531 image-file-name-extensions)
27532 image-file-name-extensions)
27534 "\\'"))))
27536 (defun org-file-image-p (file)
27537 "Return non-nil if FILE is an image."
27538 (save-match-data
27539 (string-match (org-image-file-name-regexp) file)))
27541 ;;; Paragraph filling stuff.
27542 ;; We want this to be just right, so use the full arsenal.
27544 (defun org-indent-line-function ()
27545 "Indent line like previous, but further if previous was headline or item."
27546 (interactive)
27547 (let* ((pos (point))
27548 (itemp (org-at-item-p))
27549 column bpos bcol tpos tcol bullet btype bullet-type)
27550 ;; Find the previous relevant line
27551 (beginning-of-line 1)
27552 (cond
27553 ((looking-at "#") (setq column 0))
27554 ((looking-at "\\*+ ") (setq column 0))
27556 (beginning-of-line 0)
27557 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27558 (beginning-of-line 0))
27559 (cond
27560 ((looking-at "\\*+[ \t]+")
27561 (goto-char (match-end 0))
27562 (setq column (current-column)))
27563 ((org-in-item-p)
27564 (org-beginning-of-item)
27565 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27566 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27567 (setq bpos (match-beginning 1) tpos (match-end 0)
27568 bcol (progn (goto-char bpos) (current-column))
27569 tcol (progn (goto-char tpos) (current-column))
27570 bullet (match-string 1)
27571 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27572 (if (not itemp)
27573 (setq column tcol)
27574 (goto-char pos)
27575 (beginning-of-line 1)
27576 (if (looking-at "\\S-")
27577 (progn
27578 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27579 (setq bullet (match-string 1)
27580 btype (if (string-match "[0-9]" bullet) "n" bullet))
27581 (setq column (if (equal btype bullet-type) bcol tcol)))
27582 (setq column (org-get-indentation)))))
27583 (t (setq column (org-get-indentation))))))
27584 (goto-char pos)
27585 (if (<= (current-column) (current-indentation))
27586 (indent-line-to column)
27587 (save-excursion (indent-line-to column)))
27588 (setq column (current-column))
27589 (beginning-of-line 1)
27590 (if (looking-at
27591 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27592 (replace-match (concat "\\1" (format org-property-format
27593 (match-string 2) (match-string 3)))
27594 t nil))
27595 (move-to-column column)))
27597 (defun org-set-autofill-regexps ()
27598 (interactive)
27599 ;; In the paragraph separator we include headlines, because filling
27600 ;; text in a line directly attached to a headline would otherwise
27601 ;; fill the headline as well.
27602 (org-set-local 'comment-start-skip "^#+[ \t]*")
27603 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27604 ;; The paragraph starter includes hand-formatted lists.
27605 (org-set-local 'paragraph-start
27606 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27607 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27608 ;; But only if the user has not turned off tables or fixed-width regions
27609 (org-set-local
27610 'auto-fill-inhibit-regexp
27611 (concat "\\*+ \\|#\\+"
27612 "\\|[ \t]*" org-keyword-time-regexp
27613 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27614 (concat
27615 "\\|[ \t]*["
27616 (if org-enable-table-editor "|" "")
27617 (if org-enable-fixed-width-editor ":" "")
27618 "]"))))
27619 ;; We use our own fill-paragraph function, to make sure that tables
27620 ;; and fixed-width regions are not wrapped. That function will pass
27621 ;; through to `fill-paragraph' when appropriate.
27622 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27623 ; Adaptive filling: To get full control, first make sure that
27624 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27625 (org-set-local 'adaptive-fill-regexp "\000")
27626 (org-set-local 'adaptive-fill-function
27627 'org-adaptive-fill-function)
27628 (org-set-local
27629 'align-mode-rules-list
27630 '((org-in-buffer-settings
27631 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
27632 (modes . '(org-mode))))))
27634 (defun org-fill-paragraph (&optional justify)
27635 "Re-align a table, pass through to fill-paragraph if no table."
27636 (let ((table-p (org-at-table-p))
27637 (table.el-p (org-at-table.el-p)))
27638 (cond ((and (equal (char-after (point-at-bol)) ?*)
27639 (save-excursion (goto-char (point-at-bol))
27640 (looking-at outline-regexp)))
27641 t) ; skip headlines
27642 (table.el-p t) ; skip table.el tables
27643 (table-p (org-table-align) t) ; align org-mode tables
27644 (t nil)))) ; call paragraph-fill
27646 ;; For reference, this is the default value of adaptive-fill-regexp
27647 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27649 (defun org-adaptive-fill-function ()
27650 "Return a fill prefix for org-mode files.
27651 In particular, this makes sure hanging paragraphs for hand-formatted lists
27652 work correctly."
27653 (cond ((looking-at "#[ \t]+")
27654 (match-string 0))
27655 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27656 (save-excursion
27657 (goto-char (match-end 0))
27658 (make-string (current-column) ?\ )))
27659 (t nil)))
27661 ;;;; Functions extending outline functionality
27664 (defun org-beginning-of-line (&optional arg)
27665 "Go to the beginning of the current line. If that is invisible, continue
27666 to a visible line beginning. This makes the function of C-a more intuitive.
27667 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27668 first attempt, and only move to after the tags when the cursor is already
27669 beyond the end of the headline."
27670 (interactive "P")
27671 (let ((pos (point)))
27672 (beginning-of-line 1)
27673 (if (bobp)
27675 (backward-char 1)
27676 (if (org-invisible-p)
27677 (while (and (not (bobp)) (org-invisible-p))
27678 (backward-char 1)
27679 (beginning-of-line 1))
27680 (forward-char 1)))
27681 (when org-special-ctrl-a/e
27682 (cond
27683 ((and (looking-at org-todo-line-regexp)
27684 (= (char-after (match-end 1)) ?\ ))
27685 (goto-char
27686 (if (eq org-special-ctrl-a/e t)
27687 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27688 ((= pos (point)) (match-beginning 3))
27689 (t (point)))
27690 (cond ((> pos (point)) (point))
27691 ((not (eq last-command this-command)) (point))
27692 (t (match-beginning 3))))))
27693 ((org-at-item-p)
27694 (goto-char
27695 (if (eq org-special-ctrl-a/e t)
27696 (cond ((> pos (match-end 4)) (match-end 4))
27697 ((= pos (point)) (match-end 4))
27698 (t (point)))
27699 (cond ((> pos (point)) (point))
27700 ((not (eq last-command this-command)) (point))
27701 (t (match-end 4))))))))))
27703 (defun org-end-of-line (&optional arg)
27704 "Go to the end of the line.
27705 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27706 first attempt, and only move to after the tags when the cursor is already
27707 beyond the end of the headline."
27708 (interactive "P")
27709 (if (or (not org-special-ctrl-a/e)
27710 (not (org-on-heading-p)))
27711 (end-of-line arg)
27712 (let ((pos (point)))
27713 (beginning-of-line 1)
27714 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27715 (if (eq org-special-ctrl-a/e t)
27716 (if (or (< pos (match-beginning 1))
27717 (= pos (match-end 0)))
27718 (goto-char (match-beginning 1))
27719 (goto-char (match-end 0)))
27720 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27721 (goto-char (match-end 0))
27722 (goto-char (match-beginning 1))))
27723 (end-of-line arg)))))
27725 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27726 (define-key org-mode-map "\C-e" 'org-end-of-line)
27728 (defun org-kill-line (&optional arg)
27729 "Kill line, to tags or end of line."
27730 (interactive "P")
27731 (cond
27732 ((or (not org-special-ctrl-k)
27733 (bolp)
27734 (not (org-on-heading-p)))
27735 (call-interactively 'kill-line))
27736 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
27737 (kill-region (point) (match-beginning 1))
27738 (org-set-tags nil t))
27739 (t (kill-region (point) (point-at-eol)))))
27741 (define-key org-mode-map "\C-k" 'org-kill-line)
27743 (defun org-invisible-p ()
27744 "Check if point is at a character currently not visible."
27745 ;; Early versions of noutline don't have `outline-invisible-p'.
27746 (if (fboundp 'outline-invisible-p)
27747 (outline-invisible-p)
27748 (get-char-property (point) 'invisible)))
27750 (defun org-invisible-p2 ()
27751 "Check if point is at a character currently not visible."
27752 (save-excursion
27753 (if (and (eolp) (not (bobp))) (backward-char 1))
27754 ;; Early versions of noutline don't have `outline-invisible-p'.
27755 (if (fboundp 'outline-invisible-p)
27756 (outline-invisible-p)
27757 (get-char-property (point) 'invisible))))
27759 (defalias 'org-back-to-heading 'outline-back-to-heading)
27760 (defalias 'org-on-heading-p 'outline-on-heading-p)
27761 (defalias 'org-at-heading-p 'outline-on-heading-p)
27762 (defun org-at-heading-or-item-p ()
27763 (or (org-on-heading-p) (org-at-item-p)))
27765 (defun org-on-target-p ()
27766 (or (org-in-regexp org-radio-target-regexp)
27767 (org-in-regexp org-target-regexp)))
27769 (defun org-up-heading-all (arg)
27770 "Move to the heading line of which the present line is a subheading.
27771 This function considers both visible and invisible heading lines.
27772 With argument, move up ARG levels."
27773 (if (fboundp 'outline-up-heading-all)
27774 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27775 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27777 (defun org-up-heading-safe ()
27778 "Move to the heading line of which the present line is a subheading.
27779 This version will not throw an error. It will return the level of the
27780 headline found, or nil if no higher level is found."
27781 (let ((pos (point)) start-level level
27782 (re (concat "^" outline-regexp)))
27783 (catch 'exit
27784 (outline-back-to-heading t)
27785 (setq start-level (funcall outline-level))
27786 (if (equal start-level 1) (throw 'exit nil))
27787 (while (re-search-backward re nil t)
27788 (setq level (funcall outline-level))
27789 (if (< level start-level) (throw 'exit level)))
27790 nil)))
27792 (defun org-first-sibling-p ()
27793 "Is this heading the first child of its parents?"
27794 (interactive)
27795 (let ((re (concat "^" outline-regexp))
27796 level l)
27797 (unless (org-at-heading-p t)
27798 (error "Not at a heading"))
27799 (setq level (funcall outline-level))
27800 (save-excursion
27801 (if (not (re-search-backward re nil t))
27803 (setq l (funcall outline-level))
27804 (< l level)))))
27806 (defun org-goto-sibling (&optional previous)
27807 "Goto the next sibling, even if it is invisible.
27808 When PREVIOUS is set, go to the previous sibling instead. Returns t
27809 when a sibling was found. When none is found, return nil and don't
27810 move point."
27811 (let ((fun (if previous 're-search-backward 're-search-forward))
27812 (pos (point))
27813 (re (concat "^" outline-regexp))
27814 level l)
27815 (when (condition-case nil (org-back-to-heading t) (error nil))
27816 (setq level (funcall outline-level))
27817 (catch 'exit
27818 (or previous (forward-char 1))
27819 (while (funcall fun re nil t)
27820 (setq l (funcall outline-level))
27821 (when (< l level) (goto-char pos) (throw 'exit nil))
27822 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27823 (goto-char pos)
27824 nil))))
27826 (defun org-show-siblings ()
27827 "Show all siblings of the current headline."
27828 (save-excursion
27829 (while (org-goto-sibling) (org-flag-heading nil)))
27830 (save-excursion
27831 (while (org-goto-sibling 'previous)
27832 (org-flag-heading nil))))
27834 (defun org-show-hidden-entry ()
27835 "Show an entry where even the heading is hidden."
27836 (save-excursion
27837 (org-show-entry)))
27839 (defun org-flag-heading (flag &optional entry)
27840 "Flag the current heading. FLAG non-nil means make invisible.
27841 When ENTRY is non-nil, show the entire entry."
27842 (save-excursion
27843 (org-back-to-heading t)
27844 ;; Check if we should show the entire entry
27845 (if entry
27846 (progn
27847 (org-show-entry)
27848 (save-excursion
27849 (and (outline-next-heading)
27850 (org-flag-heading nil))))
27851 (outline-flag-region (max (point-min) (1- (point)))
27852 (save-excursion (outline-end-of-heading) (point))
27853 flag))))
27855 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27856 ;; This is an exact copy of the original function, but it uses
27857 ;; `org-back-to-heading', to make it work also in invisible
27858 ;; trees. And is uses an invisible-OK argument.
27859 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
27860 (org-back-to-heading invisible-OK)
27861 (let ((first t)
27862 (level (funcall outline-level)))
27863 (while (and (not (eobp))
27864 (or first (> (funcall outline-level) level)))
27865 (setq first nil)
27866 (outline-next-heading))
27867 (unless to-heading
27868 (if (memq (preceding-char) '(?\n ?\^M))
27869 (progn
27870 ;; Go to end of line before heading
27871 (forward-char -1)
27872 (if (memq (preceding-char) '(?\n ?\^M))
27873 ;; leave blank line before heading
27874 (forward-char -1))))))
27875 (point))
27877 (defun org-show-subtree ()
27878 "Show everything after this heading at deeper levels."
27879 (outline-flag-region
27880 (point)
27881 (save-excursion
27882 (outline-end-of-subtree) (outline-next-heading) (point))
27883 nil))
27885 (defun org-show-entry ()
27886 "Show the body directly following this heading.
27887 Show the heading too, if it is currently invisible."
27888 (interactive)
27889 (save-excursion
27890 (condition-case nil
27891 (progn
27892 (org-back-to-heading t)
27893 (outline-flag-region
27894 (max (point-min) (1- (point)))
27895 (save-excursion
27896 (re-search-forward
27897 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
27898 (or (match-beginning 1) (point-max)))
27899 nil))
27900 (error nil))))
27902 (defun org-make-options-regexp (kwds)
27903 "Make a regular expression for keyword lines."
27904 (concat
27906 "#?[ \t]*\\+\\("
27907 (mapconcat 'regexp-quote kwds "\\|")
27908 "\\):[ \t]*"
27909 "\\(.+\\)"))
27911 ;; Make isearch reveal the necessary context
27912 (defun org-isearch-end ()
27913 "Reveal context after isearch exits."
27914 (when isearch-success ; only if search was successful
27915 (if (featurep 'xemacs)
27916 ;; Under XEmacs, the hook is run in the correct place,
27917 ;; we directly show the context.
27918 (org-show-context 'isearch)
27919 ;; In Emacs the hook runs *before* restoring the overlays.
27920 ;; So we have to use a one-time post-command-hook to do this.
27921 ;; (Emacs 22 has a special variable, see function `org-mode')
27922 (unless (and (boundp 'isearch-mode-end-hook-quit)
27923 isearch-mode-end-hook-quit)
27924 ;; Only when the isearch was not quitted.
27925 (org-add-hook 'post-command-hook 'org-isearch-post-command
27926 'append 'local)))))
27928 (defun org-isearch-post-command ()
27929 "Remove self from hook, and show context."
27930 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
27931 (org-show-context 'isearch))
27934 ;;;; Integration with and fixes for other packages
27936 ;;; Imenu support
27938 (defvar org-imenu-markers nil
27939 "All markers currently used by Imenu.")
27940 (make-variable-buffer-local 'org-imenu-markers)
27942 (defun org-imenu-new-marker (&optional pos)
27943 "Return a new marker for use by Imenu, and remember the marker."
27944 (let ((m (make-marker)))
27945 (move-marker m (or pos (point)))
27946 (push m org-imenu-markers)
27949 (defun org-imenu-get-tree ()
27950 "Produce the index for Imenu."
27951 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
27952 (setq org-imenu-markers nil)
27953 (let* ((n org-imenu-depth)
27954 (re (concat "^" outline-regexp))
27955 (subs (make-vector (1+ n) nil))
27956 (last-level 0)
27957 m tree level head)
27958 (save-excursion
27959 (save-restriction
27960 (widen)
27961 (goto-char (point-max))
27962 (while (re-search-backward re nil t)
27963 (setq level (org-reduced-level (funcall outline-level)))
27964 (when (<= level n)
27965 (looking-at org-complex-heading-regexp)
27966 (setq head (org-match-string-no-properties 4)
27967 m (org-imenu-new-marker))
27968 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
27969 (if (>= level last-level)
27970 (push (cons head m) (aref subs level))
27971 (push (cons head (aref subs (1+ level))) (aref subs level))
27972 (loop for i from (1+ level) to n do (aset subs i nil)))
27973 (setq last-level level)))))
27974 (aref subs 1)))
27976 (eval-after-load "imenu"
27977 '(progn
27978 (add-hook 'imenu-after-jump-hook
27979 (lambda () (org-show-context 'org-goto)))))
27981 ;; Speedbar support
27983 (defun org-speedbar-set-agenda-restriction ()
27984 "Restrict future agenda commands to the location at point in speedbar.
27985 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
27986 (interactive)
27987 (let (p m tp np dir txt w)
27988 (cond
27989 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27990 'org-imenu t))
27991 (setq m (get-text-property p 'org-imenu-marker))
27992 (save-excursion
27993 (save-restriction
27994 (set-buffer (marker-buffer m))
27995 (goto-char m)
27996 (org-agenda-set-restriction-lock 'subtree))))
27997 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27998 'speedbar-function 'speedbar-find-file))
27999 (setq tp (previous-single-property-change
28000 (1+ p) 'speedbar-function)
28001 np (next-single-property-change
28002 tp 'speedbar-function)
28003 dir (speedbar-line-directory)
28004 txt (buffer-substring-no-properties (or tp (point-min))
28005 (or np (point-max))))
28006 (save-excursion
28007 (save-restriction
28008 (set-buffer (find-file-noselect
28009 (let ((default-directory dir))
28010 (expand-file-name txt))))
28011 (unless (org-mode-p)
28012 (error "Cannot restrict to non-Org-mode file"))
28013 (org-agenda-set-restriction-lock 'file))))
28014 (t (error "Don't know how to restrict Org-mode's agenda")))
28015 (org-move-overlay org-speedbar-restriction-lock-overlay
28016 (point-at-bol) (point-at-eol))
28017 (setq current-prefix-arg nil)
28018 (org-agenda-maybe-redo)))
28020 (eval-after-load "speedbar"
28021 '(progn
28022 (speedbar-add-supported-extension ".org")
28023 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28024 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28025 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28026 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28027 (add-hook 'speedbar-visiting-tag-hook
28028 (lambda () (org-show-context 'org-goto)))))
28031 ;;; Fixes and Hacks
28033 ;; Make flyspell not check words in links, to not mess up our keymap
28034 (defun org-mode-flyspell-verify ()
28035 "Don't let flyspell put overlays at active buttons."
28036 (not (get-text-property (point) 'keymap)))
28038 ;; Make `bookmark-jump' show the jump location if it was hidden.
28039 (eval-after-load "bookmark"
28040 '(if (boundp 'bookmark-after-jump-hook)
28041 ;; We can use the hook
28042 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28043 ;; Hook not available, use advice
28044 (defadvice bookmark-jump (after org-make-visible activate)
28045 "Make the position visible."
28046 (org-bookmark-jump-unhide))))
28048 (defun org-bookmark-jump-unhide ()
28049 "Unhide the current position, to show the bookmark location."
28050 (and (org-mode-p)
28051 (or (org-invisible-p)
28052 (save-excursion (goto-char (max (point-min) (1- (point))))
28053 (org-invisible-p)))
28054 (org-show-context 'bookmark-jump)))
28056 ;; Fix a bug in htmlize where there are text properties (face nil)
28057 (eval-after-load "htmlize"
28058 '(progn
28059 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28060 "Make sure there are no nil faces"
28061 (setq ad-return-value (delq nil ad-return-value)))))
28063 ;; Make session.el ignore our circular variable
28064 (eval-after-load "session"
28065 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28067 ;;;; Experimental code
28069 (defun org-closed-in-range ()
28070 "Sparse tree of items closed in a certain time range.
28071 Still experimental, may disappear in the future."
28072 (interactive)
28073 ;; Get the time interval from the user.
28074 (let* ((time1 (time-to-seconds
28075 (org-read-date nil 'to-time nil "Starting date: ")))
28076 (time2 (time-to-seconds
28077 (org-read-date nil 'to-time nil "End date:")))
28078 ;; callback function
28079 (callback (lambda ()
28080 (let ((time
28081 (time-to-seconds
28082 (apply 'encode-time
28083 (org-parse-time-string
28084 (match-string 1))))))
28085 ;; check if time in interval
28086 (and (>= time time1) (<= time time2))))))
28087 ;; make tree, check each match with the callback
28088 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28092 (defun org-update-checkbox-count (&optional all)
28093 "Update the checkbox statistics in the current section.
28094 This will find all statistic cookies like [57%] and [6/12] and update them
28095 with the current numbers. With optional prefix argument ALL, do this for
28096 the whole buffer."
28097 (interactive "P")
28098 (save-excursion
28099 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
28100 (beg (condition-case nil
28101 (progn (outline-back-to-heading) (point))
28102 (error (point-min))))
28103 (end (move-marker (make-marker)
28104 (progn (outline-next-heading) (point))))
28105 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
28106 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
28107 beg-cookie end-cookie is-percent c-on c-off lim
28108 eline curr-ind next-ind
28109 (cstat 0)
28111 (when all
28112 (goto-char (point-min))
28113 (outline-next-heading)
28114 (setq beg (point) end (point-max)))
28115 (goto-char end)
28116 ;; find each statistic cookie
28117 (while (re-search-backward re beg t)
28118 (setq cstat (1+ cstat)
28119 beg-cookie (match-beginning 0)
28120 end-cookie (match-end 0)
28121 is-percent (match-beginning 1)
28122 lim (cond
28123 ((org-on-heading-p) (outline-next-heading) (point))
28124 ((org-at-item-p) (org-end-of-item) (point))
28125 (t nil))
28126 c-on 0
28127 c-off 0
28129 (when lim
28130 ;; find first checkbox for this cookie and gather
28131 ;; statistics from all that are at this indentation level
28132 (goto-char end-cookie)
28133 (if (re-search-forward re-box lim t)
28134 (progn
28135 (org-beginning-of-item)
28136 (setq curr-ind (org-get-indentation))
28137 (setq next-ind curr-ind)
28138 (while (= curr-ind next-ind)
28139 (save-excursion (end-of-line) (setq eline (point)))
28140 (if (re-search-forward re-box eline t)
28141 (if (member (match-string 2) '("[ ]" "[-]"))
28142 (setq c-off (1+ c-off))
28143 (setq c-on (1+ c-on))
28146 (org-end-of-item)
28147 (setq next-ind (org-get-indentation))
28149 ;; update cookie
28150 (delete-region beg-cookie end-cookie)
28151 (goto-char beg-cookie)
28152 (insert
28153 (if is-percent
28154 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
28155 (format "[%d/%d]" c-on (+ c-on c-off))))
28156 ;; update items checkbox if it has one
28157 (when (org-at-item-p)
28158 (org-beginning-of-item)
28159 (save-excursion (end-of-line) (setq eline (point)))
28160 (when (re-search-forward re-box eline t)
28161 (setq beg-cookie (match-beginning 2)
28162 end-cookie (match-end 2))
28163 (delete-region beg-cookie end-cookie)
28164 (goto-char beg-cookie)
28165 (cond ((= c-off 0) (insert "[X]"))
28166 ((= c-on 0) (insert "[ ]"))
28167 (t (insert "[-]")))
28169 (goto-char beg-cookie)
28171 (when (interactive-p)
28172 (message "Checkbox satistics updated %s (%d places)"
28173 (if all "in entire file" "in current outline entry") cstat)))))
28175 ;;;; Finish up
28177 (provide 'org)
28179 (run-hooks 'org-load-hook)
28181 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28182 ;;; org.el ends here