Improvements for RET and M-RET, + bug fixes.
[org-mode.git] / org.el
blob9a4d4741a4d166a2aa39565ac2433e3610d58e58
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.21
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.21"
88 "The version number of the file org.el.")
90 (defun org-version (&optional here)
91 "Show the org-mode version in the echo area.
92 With prefix arg HERE, insert it at point."
93 (interactive "P")
94 (let ((version (format "Org-mode version %s" org-version)))
95 (message version)
96 (if here
97 (insert version))))
99 ;;; Compatibility constants
100 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
101 (defconst org-format-transports-properties-p
102 (let ((x "a"))
103 (add-text-properties 0 1 '(test t) x)
104 (get-text-property 0 'test (format "%s" x)))
105 "Does format transport text properties?")
107 (defmacro org-bound-and-true-p (var)
108 "Return the value of symbol VAR if it is bound, else nil."
109 `(and (boundp (quote ,var)) ,var))
111 (defmacro org-unmodified (&rest body)
112 "Execute body without changing `buffer-modified-p'."
113 `(set-buffer-modified-p
114 (prog1 (buffer-modified-p) ,@body)))
116 (defmacro org-re (s)
117 "Replace posix classes in regular expression."
118 (if (featurep 'xemacs)
119 (let ((ss s))
120 (save-match-data
121 (while (string-match "\\[:alnum:\\]" ss)
122 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
123 (while (string-match "\\[:alpha:\\]" ss)
124 (setq ss (replace-match "a-zA-Z" t t ss)))
125 ss))
128 (defmacro org-preserve-lc (&rest body)
129 `(let ((_line (org-current-line))
130 (_col (current-column)))
131 (unwind-protect
132 (progn ,@body)
133 (goto-line _line)
134 (move-to-column _col))))
136 (defmacro org-without-partial-completion (&rest body)
137 `(let ((pc-mode (and (boundp 'partial-completion-mode)
138 partial-completion-mode)))
139 (unwind-protect
140 (progn
141 (if pc-mode (partial-completion-mode -1))
142 ,@body)
143 (if pc-mode (partial-completion-mode 1)))))
145 ;;; The custom variables
147 (defgroup org nil
148 "Outline-based notes management and organizer."
149 :tag "Org"
150 :group 'outlines
151 :group 'hypermedia
152 :group 'calendar)
154 ;; FIXME: Needs a separate group...
155 (defcustom org-completion-fallback-command 'hippie-expand
156 "The expansion command called by \\[org-complete] in normal context.
157 Normal means, no org-mode-specific context."
158 :group 'org
159 :type 'function)
161 (defgroup org-startup nil
162 "Options concerning startup of Org-mode."
163 :tag "Org Startup"
164 :group 'org)
166 (defcustom org-startup-folded t
167 "Non-nil means, entering Org-mode will switch to OVERVIEW.
168 This can also be configured on a per-file basis by adding one of
169 the following lines anywhere in the buffer:
171 #+STARTUP: fold
172 #+STARTUP: nofold
173 #+STARTUP: content"
174 :group 'org-startup
175 :type '(choice
176 (const :tag "nofold: show all" nil)
177 (const :tag "fold: overview" t)
178 (const :tag "content: all headlines" content)))
180 (defcustom org-startup-truncated t
181 "Non-nil means, entering Org-mode will set `truncate-lines'.
182 This is useful since some lines containing links can be very long and
183 uninteresting. Also tables look terrible when wrapped."
184 :group 'org-startup
185 :type 'boolean)
187 (defcustom org-startup-align-all-tables nil
188 "Non-nil means, align all tables when visiting a file.
189 This is useful when the column width in tables is forced with <N> cookies
190 in table fields. Such tables will look correct only after the first re-align.
191 This can also be configured on a per-file basis by adding one of
192 the following lines anywhere in the buffer:
193 #+STARTUP: align
194 #+STARTUP: noalign"
195 :group 'org-startup
196 :type 'boolean)
198 (defcustom org-insert-mode-line-in-empty-file nil
199 "Non-nil means insert the first line setting Org-mode in empty files.
200 When the function `org-mode' is called interactively in an empty file, this
201 normally means that the file name does not automatically trigger Org-mode.
202 To ensure that the file will always be in Org-mode in the future, a
203 line enforcing Org-mode will be inserted into the buffer, if this option
204 has been set."
205 :group 'org-startup
206 :type 'boolean)
208 (defcustom org-replace-disputed-keys nil
209 "Non-nil means use alternative key bindings for some keys.
210 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
211 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
212 If you want to use Org-mode together with one of these other modes,
213 or more generally if you would like to move some Org-mode commands to
214 other keys, set this variable and configure the keys with the variable
215 `org-disputed-keys'.
217 This option is only relevant at load-time of Org-mode, and must be set
218 *before* org.el is loaded. Changing it requires a restart of Emacs to
219 become effective."
220 :group 'org-startup
221 :type 'boolean)
223 (if (fboundp 'defvaralias)
224 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
226 (defcustom org-disputed-keys
227 '(([(shift up)] . [(meta p)])
228 ([(shift down)] . [(meta n)])
229 ([(shift left)] . [(meta -)])
230 ([(shift right)] . [(meta +)])
231 ([(control shift right)] . [(meta shift +)])
232 ([(control shift left)] . [(meta shift -)]))
233 "Keys for which Org-mode and other modes compete.
234 This is an alist, cars are the default keys, second element specifies
235 the alternative to use when `org-replace-disputed-keys' is t.
237 Keys can be specified in any syntax supported by `define-key'.
238 The value of this option takes effect only at Org-mode's startup,
239 therefore you'll have to restart Emacs to apply it after changing."
240 :group 'org-startup
241 :type 'alist)
243 (defun org-key (key)
244 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
245 Or return the original if not disputed."
246 (if org-replace-disputed-keys
247 (let* ((nkey (key-description key))
248 (x (org-find-if (lambda (x)
249 (equal (key-description (car x)) nkey))
250 org-disputed-keys)))
251 (if x (cdr x) key))
252 key))
254 (defun org-find-if (predicate seq)
255 (catch 'exit
256 (while seq
257 (if (funcall predicate (car seq))
258 (throw 'exit (car seq))
259 (pop seq)))))
261 (defun org-defkey (keymap key def)
262 "Define a key, possibly translated, as returned by `org-key'."
263 (define-key keymap (org-key key) def))
265 (defcustom org-ellipsis nil
266 "The ellipsis to use in the Org-mode outline.
267 When nil, just use the standard three dots. When a string, use that instead,
268 When a face, use the standart 3 dots, but with the specified face.
269 The change affects only Org-mode (which will then use its own display table).
270 Changing this requires executing `M-x org-mode' in a buffer to become
271 effective."
272 :group 'org-startup
273 :type '(choice (const :tag "Default" nil)
274 (face :tag "Face" :value org-warning)
275 (string :tag "String" :value "...#")))
277 (defvar org-display-table nil
278 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
280 (defgroup org-keywords nil
281 "Keywords in Org-mode."
282 :tag "Org Keywords"
283 :group 'org)
285 (defcustom org-deadline-string "DEADLINE:"
286 "String to mark deadline entries.
287 A deadline is this string, followed by a time stamp. Should be a word,
288 terminated by a colon. You can insert a schedule keyword and
289 a timestamp with \\[org-deadline].
290 Changes become only effective after restarting Emacs."
291 :group 'org-keywords
292 :type 'string)
294 (defcustom org-scheduled-string "SCHEDULED:"
295 "String to mark scheduled TODO entries.
296 A schedule is this string, followed by a time stamp. Should be a word,
297 terminated by a colon. You can insert a schedule keyword and
298 a timestamp with \\[org-schedule].
299 Changes become only effective after restarting Emacs."
300 :group 'org-keywords
301 :type 'string)
303 (defcustom org-closed-string "CLOSED:"
304 "String used as the prefix for timestamps logging closing a TODO entry."
305 :group 'org-keywords
306 :type 'string)
308 (defcustom org-clock-string "CLOCK:"
309 "String used as prefix for timestamps clocking work hours on an item."
310 :group 'org-keywords
311 :type 'string)
313 (defcustom org-comment-string "COMMENT"
314 "Entries starting with this keyword will never be exported.
315 An entry can be toggled between COMMENT and normal with
316 \\[org-toggle-comment].
317 Changes become only effective after restarting Emacs."
318 :group 'org-keywords
319 :type 'string)
321 (defcustom org-quote-string "QUOTE"
322 "Entries starting with this keyword will be exported in fixed-width font.
323 Quoting applies only to the text in the entry following the headline, and does
324 not extend beyond the next headline, even if that is lower level.
325 An entry can be toggled between QUOTE and normal with
326 \\[org-toggle-fixed-width-section]."
327 :group 'org-keywords
328 :type 'string)
330 (defconst org-repeat-re
331 ; (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
332 ; " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
333 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
334 "Regular expression for specifying repeated events.
335 After a match, group 1 contains the repeat expression.")
337 (defgroup org-structure nil
338 "Options concerning the general structure of Org-mode files."
339 :tag "Org Structure"
340 :group 'org)
342 (defgroup org-reveal-location nil
343 "Options about how to make context of a location visible."
344 :tag "Org Reveal Location"
345 :group 'org-structure)
347 (defconst org-context-choice
348 '(choice
349 (const :tag "Always" t)
350 (const :tag "Never" nil)
351 (repeat :greedy t :tag "Individual contexts"
352 (cons
353 (choice :tag "Context"
354 (const agenda)
355 (const org-goto)
356 (const occur-tree)
357 (const tags-tree)
358 (const link-search)
359 (const mark-goto)
360 (const bookmark-jump)
361 (const isearch)
362 (const default))
363 (boolean))))
364 "Contexts for the reveal options.")
366 (defcustom org-show-hierarchy-above '((default . t))
367 "Non-nil means, show full hierarchy when revealing a location.
368 Org-mode often shows locations in an org-mode file which might have
369 been invisible before. When this is set, the hierarchy of headings
370 above the exposed location is shown.
371 Turning this off for example for sparse trees makes them very compact.
372 Instead of t, this can also be an alist specifying this option for different
373 contexts. Valid contexts are
374 agenda when exposing an entry from the agenda
375 org-goto when using the command `org-goto' on key C-c C-j
376 occur-tree when using the command `org-occur' on key C-c /
377 tags-tree when constructing a sparse tree based on tags matches
378 link-search when exposing search matches associated with a link
379 mark-goto when exposing the jump goal of a mark
380 bookmark-jump when exposing a bookmark location
381 isearch when exiting from an incremental search
382 default default for all contexts not set explicitly"
383 :group 'org-reveal-location
384 :type org-context-choice)
386 (defcustom org-show-following-heading '((default . nil))
387 "Non-nil means, show following heading when revealing a location.
388 Org-mode often shows locations in an org-mode file which might have
389 been invisible before. When this is set, the heading following the
390 match is shown.
391 Turning this off for example for sparse trees makes them very compact,
392 but makes it harder to edit the location of the match. In such a case,
393 use the command \\[org-reveal] to show more context.
394 Instead of t, this can also be an alist specifying this option for different
395 contexts. See `org-show-hierarchy-above' for valid contexts."
396 :group 'org-reveal-location
397 :type org-context-choice)
399 (defcustom org-show-siblings '((default . nil) (isearch t))
400 "Non-nil means, show all sibling heading when revealing a location.
401 Org-mode often shows locations in an org-mode file which might have
402 been invisible before. When this is set, the sibling of the current entry
403 heading are all made visible. If `org-show-hierarchy-above' is t,
404 the same happens on each level of the hierarchy above the current entry.
406 By default this is on for the isearch context, off for all other contexts.
407 Turning this off for example for sparse trees makes them very compact,
408 but makes it harder to edit the location of the match. In such a case,
409 use the command \\[org-reveal] to show more context.
410 Instead of t, this can also be an alist specifying this option for different
411 contexts. See `org-show-hierarchy-above' for valid contexts."
412 :group 'org-reveal-location
413 :type org-context-choice)
415 (defcustom org-show-entry-below '((default . nil))
416 "Non-nil means, show the entry below a headline when revealing a location.
417 Org-mode often shows locations in an org-mode file which might have
418 been invisible before. When this is set, the text below the headline that is
419 exposed is also shown.
421 By default this is off for all contexts.
422 Instead of t, this can also be an alist specifying this option for different
423 contexts. See `org-show-hierarchy-above' for valid contexts."
424 :group 'org-reveal-location
425 :type org-context-choice)
427 (defgroup org-cycle nil
428 "Options concerning visibility cycling in Org-mode."
429 :tag "Org Cycle"
430 :group 'org-structure)
432 (defcustom org-drawers '("PROPERTIES" "CLOCK")
433 "Names of drawers. Drawers are not opened by cycling on the headline above.
434 Drawers only open with a TAB on the drawer line itself. A drawer looks like
435 this:
436 :DRAWERNAME:
437 .....
438 :END:
439 The drawer \"PROPERTIES\" is special for capturing properties through
440 the property API.
442 Drawers can be defined on the per-file basis with a line like:
444 #+DRAWERS: HIDDEN STATE PROPERTIES"
445 :group 'org-structure
446 :type '(repeat (string :tag "Drawer Name")))
448 (defcustom org-cycle-global-at-bob nil
449 "Cycle globally if cursor is at beginning of buffer and not at a headline.
450 This makes it possible to do global cycling without having to use S-TAB or
451 C-u TAB. For this special case to work, the first line of the buffer
452 must not be a headline - it may be empty ot some other text. When used in
453 this way, `org-cycle-hook' is disables temporarily, to make sure the
454 cursor stays at the beginning of the buffer.
455 When this option is nil, don't do anything special at the beginning
456 of the buffer."
457 :group 'org-cycle
458 :type 'boolean)
460 (defcustom org-cycle-emulate-tab t
461 "Where should `org-cycle' emulate TAB.
462 nil Never
463 white Only in completely white lines
464 whitestart Only at the beginning of lines, before the first non-white char
465 t Everywhere except in headlines
466 exc-hl-bol Everywhere except at the start of a headline
467 If TAB is used in a place where it does not emulate TAB, the current subtree
468 visibility is cycled."
469 :group 'org-cycle
470 :type '(choice (const :tag "Never" nil)
471 (const :tag "Only in completely white lines" white)
472 (const :tag "Before first char in a line" whitestart)
473 (const :tag "Everywhere except in headlines" t)
474 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
477 (defcustom org-cycle-separator-lines 2
478 "Number of empty lines needed to keep an empty line between collapsed trees.
479 If you leave an empty line between the end of a subtree and the following
480 headline, this empty line is hidden when the subtree is folded.
481 Org-mode will leave (exactly) one empty line visible if the number of
482 empty lines is equal or larger to the number given in this variable.
483 So the default 2 means, at least 2 empty lines after the end of a subtree
484 are needed to produce free space between a collapsed subtree and the
485 following headline.
487 Special case: when 0, never leave empty lines in collapsed view."
488 :group 'org-cycle
489 :type 'integer)
491 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
492 org-cycle-hide-drawers
493 org-cycle-show-empty-lines
494 org-optimize-window-after-visibility-change)
495 "Hook that is run after `org-cycle' has changed the buffer visibility.
496 The function(s) in this hook must accept a single argument which indicates
497 the new state that was set by the most recent `org-cycle' command. The
498 argument is a symbol. After a global state change, it can have the values
499 `overview', `content', or `all'. After a local state change, it can have
500 the values `folded', `children', or `subtree'."
501 :group 'org-cycle
502 :type 'hook)
504 (defgroup org-edit-structure nil
505 "Options concerning structure editing in Org-mode."
506 :tag "Org Edit Structure"
507 :group 'org-structure)
509 (defcustom org-special-ctrl-a/e nil
510 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
511 When t, `C-a' will bring back the cursor to the beginning of the
512 headline text, i.e. after the stars and after a possible TODO keyword.
513 In an item, this will be the position after the bullet.
514 When the cursor is already at that position, another `C-a' will bring
515 it to the beginning of the line.
516 `C-e' will jump to the end of the headline, ignoring the presence of tags
517 in the headline. A second `C-e' will then jump to the true end of the
518 line, after any tags.
519 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
520 and only a directly following, identical keypress will bring the cursor
521 to the special positions."
522 :group 'org-edit-structure
523 :type '(choice
524 (const :tag "off" nil)
525 (const :tag "after bullet first" t)
526 (const :tag "border first" reversed)))
528 (if (fboundp 'defvaralias)
529 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
531 (defcustom org-special-ctrl-k nil
532 "Non-nil means `C-k' will behave specially in headlines.
533 When nil, `C-k' will call the default `kill-line' command.
534 When t, the following will happen while the cursor is in the headline:
536 - When the cursor is at the beginning of a headline, kill the entire
537 line and possible the folded subtree below the line.
538 - When in the middle of the headline text, kill the headline up to the tags.
539 - When after the headline text, kill the tags."
540 :group 'org-edit-structure
541 :type 'boolean)
543 (defcustom org-odd-levels-only nil
544 "Non-nil means, skip even levels and only use odd levels for the outline.
545 This has the effect that two stars are being added/taken away in
546 promotion/demotion commands. It also influences how levels are
547 handled by the exporters.
548 Changing it requires restart of `font-lock-mode' to become effective
549 for fontification also in regions already fontified.
550 You may also set this on a per-file basis by adding one of the following
551 lines to the buffer:
553 #+STARTUP: odd
554 #+STARTUP: oddeven"
555 :group 'org-edit-structure
556 :group 'org-font-lock
557 :type 'boolean)
559 (defcustom org-adapt-indentation t
560 "Non-nil means, adapt indentation when promoting and demoting.
561 When this is set and the *entire* text in an entry is indented, the
562 indentation is increased by one space in a demotion command, and
563 decreased by one in a promotion command. If any line in the entry
564 body starts at column 0, indentation is not changed at all."
565 :group 'org-edit-structure
566 :type 'boolean)
568 (defcustom org-blank-before-new-entry '((heading . nil)
569 (plain-list-item . nil))
570 "Should `org-insert-heading' leave a blank line before new heading/item?
571 The value is an alist, with `heading' and `plain-list-item' as car,
572 and a boolean flag as cdr."
573 :group 'org-edit-structure
574 :type '(list
575 (cons (const heading) (boolean))
576 (cons (const plain-list-item) (boolean))))
578 (defcustom org-insert-heading-hook nil
579 "Hook being run after inserting a new heading."
580 :group 'org-edit-structure
581 :type 'hook)
583 (defcustom org-enable-fixed-width-editor t
584 "Non-nil means, lines starting with \":\" are treated as fixed-width.
585 This currently only means, they are never auto-wrapped.
586 When nil, such lines will be treated like ordinary lines.
587 See also the QUOTE keyword."
588 :group 'org-edit-structure
589 :type 'boolean)
591 (defcustom org-goto-auto-isearch t
592 "Non-nil means, typing characters in org-goto starts incremental search."
593 :group 'org-edit-structure
594 :type 'boolean)
596 (defgroup org-sparse-trees nil
597 "Options concerning sparse trees in Org-mode."
598 :tag "Org Sparse Trees"
599 :group 'org-structure)
601 (defcustom org-highlight-sparse-tree-matches t
602 "Non-nil means, highlight all matches that define a sparse tree.
603 The highlights will automatically disappear the next time the buffer is
604 changed by an edit command."
605 :group 'org-sparse-trees
606 :type 'boolean)
608 (defcustom org-remove-highlights-with-change t
609 "Non-nil means, any change to the buffer will remove temporary highlights.
610 Such highlights are created by `org-occur' and `org-clock-display'.
611 When nil, `C-c C-c needs to be used to get rid of the highlights.
612 The highlights created by `org-preview-latex-fragment' always need
613 `C-c C-c' to be removed."
614 :group 'org-sparse-trees
615 :group 'org-time
616 :type 'boolean)
619 (defcustom org-occur-hook '(org-first-headline-recenter)
620 "Hook that is run after `org-occur' has constructed a sparse tree.
621 This can be used to recenter the window to show as much of the structure
622 as possible."
623 :group 'org-sparse-trees
624 :type 'hook)
626 (defgroup org-plain-lists nil
627 "Options concerning plain lists in Org-mode."
628 :tag "Org Plain lists"
629 :group 'org-structure)
631 (defcustom org-cycle-include-plain-lists nil
632 "Non-nil means, include plain lists into visibility cycling.
633 This means that during cycling, plain list items will *temporarily* be
634 interpreted as outline headlines with a level given by 1000+i where i is the
635 indentation of the bullet. In all other operations, plain list items are
636 not seen as headlines. For example, you cannot assign a TODO keyword to
637 such an item."
638 :group 'org-plain-lists
639 :type 'boolean)
641 (defcustom org-plain-list-ordered-item-terminator t
642 "The character that makes a line with leading number an ordered list item.
643 Valid values are ?. and ?\). To get both terminators, use t. While
644 ?. may look nicer, it creates the danger that a line with leading
645 number may be incorrectly interpreted as an item. ?\) therefore is
646 the safe choice."
647 :group 'org-plain-lists
648 :type '(choice (const :tag "dot like in \"2.\"" ?.)
649 (const :tag "paren like in \"2)\"" ?\))
650 (const :tab "both" t)))
652 (defcustom org-auto-renumber-ordered-lists t
653 "Non-nil means, automatically renumber ordered plain lists.
654 Renumbering happens when the sequence have been changed with
655 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
656 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
657 :group 'org-plain-lists
658 :type 'boolean)
660 (defcustom org-provide-checkbox-statistics t
661 "Non-nil means, update checkbox statistics after insert and toggle.
662 When this is set, checkbox statistics is updated each time you either insert
663 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
664 with \\[org-ctrl-c-ctrl-c\\]."
665 :group 'org-plain-lists
666 :type 'boolean)
668 (defgroup org-archive nil
669 "Options concerning archiving in Org-mode."
670 :tag "Org Archive"
671 :group 'org-structure)
673 (defcustom org-archive-tag "ARCHIVE"
674 "The tag that marks a subtree as archived.
675 An archived subtree does not open during visibility cycling, and does
676 not contribute to the agenda listings.
677 After changing this, font-lock must be restarted in the relevant buffers to
678 get the proper fontification."
679 :group 'org-archive
680 :group 'org-keywords
681 :type 'string)
683 (defcustom org-agenda-skip-archived-trees t
684 "Non-nil means, the agenda will skip any items located in archived trees.
685 An archived tree is a tree marked with the tag ARCHIVE."
686 :group 'org-archive
687 :group 'org-agenda-skip
688 :type 'boolean)
690 (defcustom org-cycle-open-archived-trees nil
691 "Non-nil means, `org-cycle' will open archived trees.
692 An archived tree is a tree marked with the tag ARCHIVE.
693 When nil, archived trees will stay folded. You can still open them with
694 normal outline commands like `show-all', but not with the cycling commands."
695 :group 'org-archive
696 :group 'org-cycle
697 :type 'boolean)
699 (defcustom org-sparse-tree-open-archived-trees nil
700 "Non-nil means sparse tree construction shows matches in archived trees.
701 When nil, matches in these trees are highlighted, but the trees are kept in
702 collapsed state."
703 :group 'org-archive
704 :group 'org-sparse-trees
705 :type 'boolean)
707 (defcustom org-archive-location "%s_archive::"
708 "The location where subtrees should be archived.
709 This string consists of two parts, separated by a double-colon.
711 The first part is a file name - when omitted, archiving happens in the same
712 file. %s will be replaced by the current file name (without directory part).
713 Archiving to a different file is useful to keep archived entries from
714 contributing to the Org-mode Agenda.
716 The part after the double colon is a headline. The archived entries will be
717 filed under that headline. When omitted, the subtrees are simply filed away
718 at the end of the file, as top-level entries.
720 Here are a few examples:
721 \"%s_archive::\"
722 If the current file is Projects.org, archive in file
723 Projects.org_archive, as top-level trees. This is the default.
725 \"::* Archived Tasks\"
726 Archive in the current file, under the top-level headline
727 \"* Archived Tasks\".
729 \"~/org/archive.org::\"
730 Archive in file ~/org/archive.org (absolute path), as top-level trees.
732 \"basement::** Finished Tasks\"
733 Archive in file ./basement (relative path), as level 3 trees
734 below the level 2 heading \"** Finished Tasks\".
736 You may set this option on a per-file basis by adding to the buffer a
737 line like
739 #+ARCHIVE: basement::** Finished Tasks"
740 :group 'org-archive
741 :type 'string)
743 (defcustom org-archive-mark-done t
744 "Non-nil means, mark entries as DONE when they are moved to the archive file.
745 This can be a string to set the keyword to use. When t, Org-mode will
746 use the first keyword in its list that means done."
747 :group 'org-archive
748 :type '(choice
749 (const :tag "No" nil)
750 (const :tag "Yes" t)
751 (string :tag "Use this keyword")))
753 (defcustom org-archive-stamp-time t
754 "Non-nil means, add a time stamp to entries moved to an archive file.
755 This variable is obsolete and has no effect anymore, instead add ot remove
756 `time' from the variablle `org-archive-save-context-info'."
757 :group 'org-archive
758 :type 'boolean)
760 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
761 "Parts of context info that should be stored as properties when archiving.
762 When a subtree is moved to an archive file, it looses information given by
763 context, like inherited tags, the category, and possibly also the TODO
764 state (depending on the variable `org-archive-mark-done').
765 This variable can be a list of any of the following symbols:
767 time The time of archiving.
768 file The file where the entry originates.
769 itags The local tags, in the headline of the subtree.
770 ltags The tags the subtree inherits from further up the hierarchy.
771 todo The pre-archive TODO state.
772 category The category, taken from file name or #+CATEGORY lines.
773 olpath The outline path to the item. These are all headlines above
774 the current item, separated by /, like a file path.
776 For each symbol present in the list, a property will be created in
777 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
778 information."
779 :group 'org-archive
780 :type '(set :greedy t
781 (const :tag "Time" time)
782 (const :tag "File" file)
783 (const :tag "Category" category)
784 (const :tag "TODO state" todo)
785 (const :tag "TODO state" priority)
786 (const :tag "Inherited tags" itags)
787 (const :tag "Outline path" olpath)
788 (const :tag "Local tags" ltags)))
790 (defgroup org-imenu-and-speedbar nil
791 "Options concerning imenu and speedbar in Org-mode."
792 :tag "Org Imenu and Speedbar"
793 :group 'org-structure)
795 (defcustom org-imenu-depth 2
796 "The maximum level for Imenu access to Org-mode headlines.
797 This also applied for speedbar access."
798 :group 'org-imenu-and-speedbar
799 :type 'number)
801 (defgroup org-table nil
802 "Options concerning tables in Org-mode."
803 :tag "Org Table"
804 :group 'org)
806 (defcustom org-enable-table-editor 'optimized
807 "Non-nil means, lines starting with \"|\" are handled by the table editor.
808 When nil, such lines will be treated like ordinary lines.
810 When equal to the symbol `optimized', the table editor will be optimized to
811 do the following:
812 - Automatic overwrite mode in front of whitespace in table fields.
813 This makes the structure of the table stay in tact as long as the edited
814 field does not exceed the column width.
815 - Minimize the number of realigns. Normally, the table is aligned each time
816 TAB or RET are pressed to move to another field. With optimization this
817 happens only if changes to a field might have changed the column width.
818 Optimization requires replacing the functions `self-insert-command',
819 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
820 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
821 very good at guessing when a re-align will be necessary, but you can always
822 force one with \\[org-ctrl-c-ctrl-c].
824 If you would like to use the optimized version in Org-mode, but the
825 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
827 This variable can be used to turn on and off the table editor during a session,
828 but in order to toggle optimization, a restart is required.
830 See also the variable `org-table-auto-blank-field'."
831 :group 'org-table
832 :type '(choice
833 (const :tag "off" nil)
834 (const :tag "on" t)
835 (const :tag "on, optimized" optimized)))
837 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
838 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
839 In the optimized version, the table editor takes over all simple keys that
840 normally just insert a character. In tables, the characters are inserted
841 in a way to minimize disturbing the table structure (i.e. in overwrite mode
842 for empty fields). Outside tables, the correct binding of the keys is
843 restored.
845 The default for this option is t if the optimized version is also used in
846 Org-mode. See the variable `org-enable-table-editor' for details. Changing
847 this variable requires a restart of Emacs to become effective."
848 :group 'org-table
849 :type 'boolean)
851 (defcustom orgtbl-radio-table-templates
852 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
853 % END RECEIVE ORGTBL %n
854 \\begin{comment}
855 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
856 | | |
857 \\end{comment}\n")
858 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
859 @c END RECEIVE ORGTBL %n
860 @ignore
861 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
862 | | |
863 @end ignore\n")
864 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
865 <!-- END RECEIVE ORGTBL %n -->
866 <!--
867 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
868 | | |
869 -->\n"))
870 "Templates for radio tables in different major modes.
871 All occurrences of %n in a template will be replaced with the name of the
872 table, obtained by prompting the user."
873 :group 'org-table
874 :type '(repeat
875 (list (symbol :tag "Major mode")
876 (string :tag "Format"))))
878 (defgroup org-table-settings nil
879 "Settings for tables in Org-mode."
880 :tag "Org Table Settings"
881 :group 'org-table)
883 (defcustom org-table-default-size "5x2"
884 "The default size for newly created tables, Columns x Rows."
885 :group 'org-table-settings
886 :type 'string)
888 (defcustom org-table-number-regexp
889 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
890 "Regular expression for recognizing numbers in table columns.
891 If a table column contains mostly numbers, it will be aligned to the
892 right. If not, it will be aligned to the left.
894 The default value of this option is a regular expression which allows
895 anything which looks remotely like a number as used in scientific
896 context. For example, all of the following will be considered a
897 number:
898 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
900 Other options offered by the customize interface are more restrictive."
901 :group 'org-table-settings
902 :type '(choice
903 (const :tag "Positive Integers"
904 "^[0-9]+$")
905 (const :tag "Integers"
906 "^[-+]?[0-9]+$")
907 (const :tag "Floating Point Numbers"
908 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
909 (const :tag "Floating Point Number or Integer"
910 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
911 (const :tag "Exponential, Floating point, Integer"
912 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
913 (const :tag "Very General Number-Like, including hex"
914 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
915 (string :tag "Regexp:")))
917 (defcustom org-table-number-fraction 0.5
918 "Fraction of numbers in a column required to make the column align right.
919 In a column all non-white fields are considered. If at least this
920 fraction of fields is matched by `org-table-number-fraction',
921 alignment to the right border applies."
922 :group 'org-table-settings
923 :type 'number)
925 (defgroup org-table-editing nil
926 "Behavior of tables during editing in Org-mode."
927 :tag "Org Table Editing"
928 :group 'org-table)
930 (defcustom org-table-automatic-realign t
931 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
932 When nil, aligning is only done with \\[org-table-align], or after column
933 removal/insertion."
934 :group 'org-table-editing
935 :type 'boolean)
937 (defcustom org-table-auto-blank-field t
938 "Non-nil means, automatically blank table field when starting to type into it.
939 This only happens when typing immediately after a field motion
940 command (TAB, S-TAB or RET).
941 Only relevant when `org-enable-table-editor' is equal to `optimized'."
942 :group 'org-table-editing
943 :type 'boolean)
945 (defcustom org-table-tab-jumps-over-hlines t
946 "Non-nil means, tab in the last column of a table with jump over a hline.
947 If a horizontal separator line is following the current line,
948 `org-table-next-field' can either create a new row before that line, or jump
949 over the line. When this option is nil, a new line will be created before
950 this line."
951 :group 'org-table-editing
952 :type 'boolean)
954 (defcustom org-table-tab-recognizes-table.el t
955 "Non-nil means, TAB will automatically notice a table.el table.
956 When it sees such a table, it moves point into it and - if necessary -
957 calls `table-recognize-table'."
958 :group 'org-table-editing
959 :type 'boolean)
961 (defgroup org-table-calculation nil
962 "Options concerning tables in Org-mode."
963 :tag "Org Table Calculation"
964 :group 'org-table)
966 (defcustom org-table-use-standard-references t
967 "Should org-mode work with table refrences like B3 instead of @3$2?
968 Possible values are:
969 nil never use them
970 from accept as input, do not present for editing
971 t: accept as input and present for editing"
972 :group 'org-table-calculation
973 :type '(choice
974 (const :tag "Never, don't even check unser input for them" nil)
975 (const :tag "Always, both as user input, and when editing" t)
976 (const :tag "Convert user input, don't offer during editing" 'from)))
978 (defcustom org-table-copy-increment t
979 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
980 :group 'org-table-calculation
981 :type 'boolean)
983 (defcustom org-calc-default-modes
984 '(calc-internal-prec 12
985 calc-float-format (float 5)
986 calc-angle-mode deg
987 calc-prefer-frac nil
988 calc-symbolic-mode nil
989 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
990 calc-display-working-message t
992 "List with Calc mode settings for use in calc-eval for table formulas.
993 The list must contain alternating symbols (Calc modes variables and values).
994 Don't remove any of the default settings, just change the values. Org-mode
995 relies on the variables to be present in the list."
996 :group 'org-table-calculation
997 :type 'plist)
999 (defcustom org-table-formula-evaluate-inline t
1000 "Non-nil means, TAB and RET evaluate a formula in current table field.
1001 If the current field starts with an equal sign, it is assumed to be a formula
1002 which should be evaluated as described in the manual and in the documentation
1003 string of the command `org-table-eval-formula'. This feature requires the
1004 Emacs calc package.
1005 When this variable is nil, formula calculation is only available through
1006 the command \\[org-table-eval-formula]."
1007 :group 'org-table-calculation
1008 :type 'boolean)
1010 (defcustom org-table-formula-use-constants t
1011 "Non-nil means, interpret constants in formulas in tables.
1012 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1013 by the value given in `org-table-formula-constants', or by a value obtained
1014 from the `constants.el' package."
1015 :group 'org-table-calculation
1016 :type 'boolean)
1018 (defcustom org-table-formula-constants nil
1019 "Alist with constant names and values, for use in table formulas.
1020 The car of each element is a name of a constant, without the `$' before it.
1021 The cdr is the value as a string. For example, if you'd like to use the
1022 speed of light in a formula, you would configure
1024 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1026 and then use it in an equation like `$1*$c'.
1028 Constants can also be defined on a per-file basis using a line like
1030 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1031 :group 'org-table-calculation
1032 :type '(repeat
1033 (cons (string :tag "name")
1034 (string :tag "value"))))
1036 (defvar org-table-formula-constants-local nil
1037 "Local version of `org-table-formula-constants'.")
1038 (make-variable-buffer-local 'org-table-formula-constants-local)
1040 (defcustom org-table-allow-automatic-line-recalculation t
1041 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1042 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1043 :group 'org-table-calculation
1044 :type 'boolean)
1046 (defgroup org-link nil
1047 "Options concerning links in Org-mode."
1048 :tag "Org Link"
1049 :group 'org)
1051 (defvar org-link-abbrev-alist-local nil
1052 "Buffer-local version of `org-link-abbrev-alist', which see.
1053 The value of this is taken from the #+LINK lines.")
1054 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1056 (defcustom org-link-abbrev-alist nil
1057 "Alist of link abbreviations.
1058 The car of each element is a string, to be replaced at the start of a link.
1059 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1060 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1062 [[linkkey:tag][description]]
1064 If REPLACE is a string, the tag will simply be appended to create the link.
1065 If the string contains \"%s\", the tag will be inserted there.
1067 REPLACE may also be a function that will be called with the tag as the
1068 only argument to create the link, which should be returned as a string.
1070 See the manual for examples."
1071 :group 'org-link
1072 :type 'alist)
1074 (defcustom org-descriptive-links t
1075 "Non-nil means, hide link part and only show description of bracket links.
1076 Bracket links are like [[link][descritpion]]. This variable sets the initial
1077 state in new org-mode buffers. The setting can then be toggled on a
1078 per-buffer basis from the Org->Hyperlinks menu."
1079 :group 'org-link
1080 :type 'boolean)
1082 (defcustom org-link-file-path-type 'adaptive
1083 "How the path name in file links should be stored.
1084 Valid values are:
1086 relative Relative to the current directory, i.e. the directory of the file
1087 into which the link is being inserted.
1088 absolute Absolute path, if possible with ~ for home directory.
1089 noabbrev Absolute path, no abbreviation of home directory.
1090 adaptive Use relative path for files in the current directory and sub-
1091 directories of it. For other files, use an absolute path."
1092 :group 'org-link
1093 :type '(choice
1094 (const relative)
1095 (const absolute)
1096 (const noabbrev)
1097 (const adaptive)))
1099 (defcustom org-activate-links '(bracket angle plain radio tag date)
1100 "Types of links that should be activated in Org-mode files.
1101 This is a list of symbols, each leading to the activation of a certain link
1102 type. In principle, it does not hurt to turn on most link types - there may
1103 be a small gain when turning off unused link types. The types are:
1105 bracket The recommended [[link][description]] or [[link]] links with hiding.
1106 angular Links in angular brackes that may contain whitespace like
1107 <bbdb:Carsten Dominik>.
1108 plain Plain links in normal text, no whitespace, like http://google.com.
1109 radio Text that is matched by a radio target, see manual for details.
1110 tag Tag settings in a headline (link to tag search).
1111 date Time stamps (link to calendar).
1113 Changing this variable requires a restart of Emacs to become effective."
1114 :group 'org-link
1115 :type '(set (const :tag "Double bracket links (new style)" bracket)
1116 (const :tag "Angular bracket links (old style)" angular)
1117 (const :tag "plain text links" plain)
1118 (const :tag "Radio target matches" radio)
1119 (const :tag "Tags" tag)
1120 (const :tag "Tags" target)
1121 (const :tag "Timestamps" date)))
1123 (defgroup org-link-store nil
1124 "Options concerning storing links in Org-mode"
1125 :tag "Org Store Link"
1126 :group 'org-link)
1128 (defcustom org-email-link-description-format "Email %c: %.30s"
1129 "Format of the description part of a link to an email or usenet message.
1130 The following %-excapes will be replaced by corresponding information:
1132 %F full \"From\" field
1133 %f name, taken from \"From\" field, address if no name
1134 %T full \"To\" field
1135 %t first name in \"To\" field, address if no name
1136 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1137 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1138 %s subject
1139 %m message-id.
1141 You may use normal field width specification between the % and the letter.
1142 This is for example useful to limit the length of the subject.
1144 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1145 :group 'org-link-store
1146 :type 'string)
1148 (defcustom org-from-is-user-regexp
1149 (let (r1 r2)
1150 (when (and user-mail-address (not (string= user-mail-address "")))
1151 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1152 (when (and user-full-name (not (string= user-full-name "")))
1153 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1154 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1155 "Regexp mached against the \"From:\" header of an email or usenet message.
1156 It should match if the message is from the user him/herself."
1157 :group 'org-link-store
1158 :type 'regexp)
1160 (defcustom org-context-in-file-links t
1161 "Non-nil means, file links from `org-store-link' contain context.
1162 A search string will be added to the file name with :: as separator and
1163 used to find the context when the link is activated by the command
1164 `org-open-at-point'.
1165 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1166 negates this setting for the duration of the command."
1167 :group 'org-link-store
1168 :type 'boolean)
1170 (defcustom org-keep-stored-link-after-insertion nil
1171 "Non-nil means, keep link in list for entire session.
1173 The command `org-store-link' adds a link pointing to the current
1174 location to an internal list. These links accumulate during a session.
1175 The command `org-insert-link' can be used to insert links into any
1176 Org-mode file (offering completion for all stored links). When this
1177 option is nil, every link which has been inserted once using \\[org-insert-link]
1178 will be removed from the list, to make completing the unused links
1179 more efficient."
1180 :group 'org-link-store
1181 :type 'boolean)
1183 (defcustom org-usenet-links-prefer-google nil
1184 "Non-nil means, `org-store-link' will create web links to Google groups.
1185 When nil, Gnus will be used for such links.
1186 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1187 negates this setting for the duration of the command."
1188 :group 'org-link-store
1189 :type 'boolean)
1191 (defgroup org-link-follow nil
1192 "Options concerning following links in Org-mode"
1193 :tag "Org Follow Link"
1194 :group 'org-link)
1196 (defcustom org-tab-follows-link nil
1197 "Non-nil means, on links TAB 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-return-follows-link nil
1203 "Non-nil means, on links RET will follow the link.
1204 Needs to be set before org.el is loaded."
1205 :group 'org-link-follow
1206 :type 'boolean)
1208 (defcustom org-mouse-1-follows-link t
1209 "Non-nil means, mouse-1 on a link will follow the link.
1210 A longer mouse click will still set point. Does not wortk on XEmacs.
1211 Needs to be set before org.el is loaded."
1212 :group 'org-link-follow
1213 :type 'boolean)
1215 (defcustom org-mark-ring-length 4
1216 "Number of different positions to be recorded in the ring
1217 Changing this requires a restart of Emacs to work correctly."
1218 :group 'org-link-follow
1219 :type 'interger)
1221 (defcustom org-link-frame-setup
1222 '((vm . vm-visit-folder-other-frame)
1223 (gnus . gnus-other-frame)
1224 (file . find-file-other-window))
1225 "Setup the frame configuration for following links.
1226 When following a link with Emacs, it may often be useful to display
1227 this link in another window or frame. This variable can be used to
1228 set this up for the different types of links.
1229 For VM, use any of
1230 `vm-visit-folder'
1231 `vm-visit-folder-other-frame'
1232 For Gnus, use any of
1233 `gnus'
1234 `gnus-other-frame'
1235 For FILE, use any of
1236 `find-file'
1237 `find-file-other-window'
1238 `find-file-other-frame'
1239 For the calendar, use the variable `calendar-setup'.
1240 For BBDB, it is currently only possible to display the matches in
1241 another window."
1242 :group 'org-link-follow
1243 :type '(list
1244 (cons (const vm)
1245 (choice
1246 (const vm-visit-folder)
1247 (const vm-visit-folder-other-window)
1248 (const vm-visit-folder-other-frame)))
1249 (cons (const gnus)
1250 (choice
1251 (const gnus)
1252 (const gnus-other-frame)))
1253 (cons (const file)
1254 (choice
1255 (const find-file)
1256 (const find-file-other-window)
1257 (const find-file-other-frame)))))
1259 (defcustom org-display-internal-link-with-indirect-buffer nil
1260 "Non-nil means, use indirect buffer to display infile links.
1261 Activating internal links (from one location in a file to another location
1262 in the same file) normally just jumps to the location. When the link is
1263 activated with a C-u prefix (or with mouse-3), the link is displayed in
1264 another window. When this option is set, the other window actually displays
1265 an indirect buffer clone of the current buffer, to avoid any visibility
1266 changes to the current buffer."
1267 :group 'org-link-follow
1268 :type 'boolean)
1270 (defcustom org-open-non-existing-files nil
1271 "Non-nil means, `org-open-file' will open non-existing files.
1272 When nil, an error will be generated."
1273 :group 'org-link-follow
1274 :type 'boolean)
1276 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1277 "Function and arguments to call for following mailto links.
1278 This is a list with the first element being a lisp function, and the
1279 remaining elements being arguments to the function. In string arguments,
1280 %a will be replaced by the address, and %s will be replaced by the subject
1281 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1282 :group 'org-link-follow
1283 :type '(choice
1284 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1285 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1286 (const :tag "message-mail" (message-mail "%a" "%s"))
1287 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1289 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1290 "Non-nil means, ask for confirmation before executing shell links.
1291 Shell links can be dangerous: just think about a link
1293 [[shell:rm -rf ~/*][Google Search]]
1295 This link would show up in your Org-mode document as \"Google Search\",
1296 but really it would remove your entire home directory.
1297 Therefore we advise against setting this variable to nil.
1298 Just change it to `y-or-n-p' of you want to confirm with a
1299 single keystroke rather than having to type \"yes\"."
1300 :group 'org-link-follow
1301 :type '(choice
1302 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1303 (const :tag "with y-or-n (faster)" y-or-n-p)
1304 (const :tag "no confirmation (dangerous)" nil)))
1306 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1307 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1308 Elisp links can be dangerous: just think about a link
1310 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1312 This link would show up in your Org-mode document as \"Google Search\",
1313 but really it would remove your entire home directory.
1314 Therefore we advise against setting this variable to nil.
1315 Just change it to `y-or-n-p' of you want to confirm with a
1316 single keystroke rather than having to type \"yes\"."
1317 :group 'org-link-follow
1318 :type '(choice
1319 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1320 (const :tag "with y-or-n (faster)" y-or-n-p)
1321 (const :tag "no confirmation (dangerous)" nil)))
1323 (defconst org-file-apps-defaults-gnu
1324 '((remote . emacs)
1325 (t . mailcap))
1326 "Default file applications on a UNIX or GNU/Linux system.
1327 See `org-file-apps'.")
1329 (defconst org-file-apps-defaults-macosx
1330 '((remote . emacs)
1331 (t . "open %s")
1332 ("ps" . "gv %s")
1333 ("ps.gz" . "gv %s")
1334 ("eps" . "gv %s")
1335 ("eps.gz" . "gv %s")
1336 ("dvi" . "xdvi %s")
1337 ("fig" . "xfig %s"))
1338 "Default file applications on a MacOS X system.
1339 The system \"open\" is known as a default, but we use X11 applications
1340 for some files for which the OS does not have a good default.
1341 See `org-file-apps'.")
1343 (defconst org-file-apps-defaults-windowsnt
1344 (list
1345 '(remote . emacs)
1346 (cons t
1347 (list (if (featurep 'xemacs)
1348 'mswindows-shell-execute
1349 'w32-shell-execute)
1350 "open" 'file)))
1351 "Default file applications on a Windows NT system.
1352 The system \"open\" is used for most files.
1353 See `org-file-apps'.")
1355 (defcustom org-file-apps
1357 ("txt" . emacs)
1358 ("tex" . emacs)
1359 ("ltx" . emacs)
1360 ("org" . emacs)
1361 ("el" . emacs)
1362 ("bib" . emacs)
1364 "External applications for opening `file:path' items in a document.
1365 Org-mode uses system defaults for different file types, but
1366 you can use this variable to set the application for a given file
1367 extension. The entries in this list are cons cells where the car identifies
1368 files and the cdr the corresponding command. Possible values for the
1369 file identifier are
1370 \"ext\" A string identifying an extension
1371 `directory' Matches a directory
1372 `remote' Matches a remote file, accessible through tramp or efs.
1373 Remote files most likely should be visited through Emacs
1374 because external applications cannot handle such paths.
1375 t Default for all remaining files
1377 Possible values for the command are:
1378 `emacs' The file will be visited by the current Emacs process.
1379 `default' Use the default application for this file type.
1380 string A command to be executed by a shell; %s will be replaced
1381 by the path to the file.
1382 sexp A Lisp form which will be evaluated. The file path will
1383 be available in the Lisp variable `file'.
1384 For more examples, see the system specific constants
1385 `org-file-apps-defaults-macosx'
1386 `org-file-apps-defaults-windowsnt'
1387 `org-file-apps-defaults-gnu'."
1388 :group 'org-link-follow
1389 :type '(repeat
1390 (cons (choice :value ""
1391 (string :tag "Extension")
1392 (const :tag "Default for unrecognized files" t)
1393 (const :tag "Remote file" remote)
1394 (const :tag "Links to a directory" directory))
1395 (choice :value ""
1396 (const :tag "Visit with Emacs" emacs)
1397 (const :tag "Use system default" default)
1398 (string :tag "Command")
1399 (sexp :tag "Lisp form")))))
1401 (defcustom org-mhe-search-all-folders nil
1402 "Non-nil means, that the search for the mh-message will be extended to
1403 all folders if the message cannot be found in the folder given in the link.
1404 Searching all folders is very efficient with one of the search engines
1405 supported by MH-E, but will be slow with pick."
1406 :group 'org-link-follow
1407 :type 'boolean)
1409 (defgroup org-remember nil
1410 "Options concerning interaction with remember.el."
1411 :tag "Org Remember"
1412 :group 'org)
1414 (defcustom org-directory "~/org"
1415 "Directory with org files.
1416 This directory will be used as default to prompt for org files.
1417 Used by the hooks for remember.el."
1418 :group 'org-remember
1419 :type 'directory)
1421 (defcustom org-default-notes-file "~/.notes"
1422 "Default target for storing notes.
1423 Used by the hooks for remember.el. This can be a string, or nil to mean
1424 the value of `remember-data-file'.
1425 You can set this on a per-template basis with the variable
1426 `org-remember-templates'."
1427 :group 'org-remember
1428 :type '(choice
1429 (const :tag "Default from remember-data-file" nil)
1430 file))
1432 (defcustom org-remember-store-without-prompt t
1433 "Non-nil means, `C-c C-c' stores remember note without further promts.
1434 In this case, you need `C-u C-c C-c' to get the prompts for
1435 note file and headline.
1436 When this variable is nil, `C-c C-c' give you the prompts, and
1437 `C-u C-c C-c' trigger the fasttrack."
1438 :group 'org-remember
1439 :type 'boolean)
1441 (defcustom org-remember-interactive-interface 'refile
1442 "The interface to be used for interactive filing of remember notes.
1443 This is only used when the interactive mode for selecting a filing
1444 location is used (see the variable `org-remember-store-without-prompt').
1445 Allowed vaues are:
1446 outline The interface shows an outline of the relevant file
1447 and the correct heading is found by moving through
1448 the outline or by searching with incremental search.
1449 outline-path-completion Headlines in the current buffer are offered via
1450 completion.
1451 refile Use the refile interface, and offer headlines,
1452 possibly from different buffers."
1453 :group 'org-remember
1454 :type '(choice
1455 (const :tag "Refile" refile)
1456 (const :tag "Outline" outline)
1457 (const :tag "Outline-path-completion" outline-path-completion)))
1459 (defcustom org-goto-interface 'outline
1460 "The default interface to be used for `org-goto'.
1461 Allowed vaues are:
1462 outline The interface shows an outline of the relevant file
1463 and the correct heading is found by moving through
1464 the outline or by searching with incremental search.
1465 outline-path-completion Headlines in the current buffer are offered via
1466 completion."
1467 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1468 :type '(choice
1469 (const :tag "Outline" outline)
1470 (const :tag "Outline-path-completion" outline-path-completion)))
1472 (defcustom org-remember-default-headline ""
1473 "The headline that should be the default location in the notes file.
1474 When filing remember notes, the cursor will start at that position.
1475 You can set this on a per-template basis with the variable
1476 `org-remember-templates'."
1477 :group 'org-remember
1478 :type 'string)
1480 (defcustom org-remember-templates nil
1481 "Templates for the creation of remember buffers.
1482 When nil, just let remember make the buffer.
1483 When not nil, this is a list of 5-element lists. In each entry, the first
1484 element is the name of the template, which should be a single short word.
1485 The second element is a character, a unique key to select this template.
1486 The third element is the template. The fourth element is optional and can
1487 specify a destination file for remember items created with this template.
1488 The default file is given by `org-default-notes-file'. An optional fifth
1489 element can specify the headline in that file that should be offered
1490 first when the user is asked to file the entry. The default headline is
1491 given in the variable `org-remember-default-headline'.
1493 The template specifies the structure of the remember buffer. It should have
1494 a first line starting with a star, to act as the org-mode headline.
1495 Furthermore, the following %-escapes will be replaced with content:
1497 %^{prompt} Prompt the user for a string and replace this sequence with it.
1498 A default value and a completion table ca be specified like this:
1499 %^{prompt|default|completion2|completion3|...}
1500 %t time stamp, date only
1501 %T time stamp with date and time
1502 %u, %U like the above, but inactive time stamps
1503 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1504 You may define a prompt like %^{Please specify birthday}t
1505 %n user name (taken from `user-full-name')
1506 %a annotation, normally the link created with org-store-link
1507 %i initial content, the region when remember is called with C-u.
1508 If %i is indented, the entire inserted text will be indented
1509 as well.
1510 %c content of the clipboard, or current kill ring head
1511 %^g prompt for tags, with completion on tags in target file
1512 %^G prompt for tags, with completion all tags in all agenda files
1513 %:keyword specific information for certain link types, see below
1514 %[pathname] insert the contents of the file given by `pathname'
1515 %(sexp) evaluate elisp `(sexp)' and replace with the result
1516 %! Store this note immediately after filling the template
1518 %? After completing the template, position cursor here.
1520 Apart from these general escapes, you can access information specific to the
1521 link type that is created. For example, calling `remember' in emails or gnus
1522 will record the author and the subject of the message, which you can access
1523 with %:author and %:subject, respectively. Here is a complete list of what
1524 is recorded for each link type.
1526 Link type | Available information
1527 -------------------+------------------------------------------------------
1528 bbdb | %:type %:name %:company
1529 vm, wl, mh, rmail | %:type %:subject %:message-id
1530 | %:from %:fromname %:fromaddress
1531 | %:to %:toname %:toaddress
1532 | %:fromto (either \"to NAME\" or \"from NAME\")
1533 gnus | %:group, for messages also all email fields
1534 w3, w3m | %:type %:url
1535 info | %:type %:file %:node
1536 calendar | %:type %:date"
1537 :group 'org-remember
1538 :get (lambda (var) ; Make sure all entries have 5 elements
1539 (mapcar (lambda (x)
1540 (if (not (stringp (car x))) (setq x (cons "" x)))
1541 (cond ((= (length x) 4) (append x '("")))
1542 ((= (length x) 3) (append x '("" "")))
1543 (t x)))
1544 (default-value var)))
1545 :type '(repeat
1546 :tag "enabled"
1547 (list :value ("" ?a "\n" nil nil)
1548 (string :tag "Name")
1549 (character :tag "Selection Key")
1550 (string :tag "Template")
1551 (choice
1552 (file :tag "Destination file")
1553 (const :tag "Prompt for file" nil))
1554 (choice
1555 (string :tag "Destination headline")
1556 (const :tag "Selection interface for heading")))))
1558 (defcustom org-reverse-note-order nil
1559 "Non-nil means, store new notes at the beginning of a file or entry.
1560 When nil, new notes will be filed to the end of a file or entry.
1561 This can also be a list with cons cells of regular expressions that
1562 are matched against file names, and values."
1563 :group 'org-remember
1564 :type '(choice
1565 (const :tag "Reverse always" t)
1566 (const :tag "Reverse never" nil)
1567 (repeat :tag "By file name regexp"
1568 (cons regexp boolean))))
1570 (defcustom org-refile-targets nil
1571 "Targets for refiling entries with \\[org-refile].
1572 This is list of cons cells. Each cell contains:
1573 - a specification of the files to be considered, either a list of files,
1574 or a symbol whose function or value fields will be used to retrieve
1575 a file name or a list of file names. Nil means, refile to a different
1576 heading in the current buffer.
1577 - A specification of how to find candidate refile targets. This may be
1578 any of
1579 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1580 This tag has to be present in all target headlines, inheritance will
1581 not be considered.
1582 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1583 todo keyword.
1584 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1585 headlines that are refiling targets.
1586 - a cons cell (:level . N). Any headline of level N is considered a target.
1587 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1588 ;; FIXME: what if there are a var and func with same name???
1589 :group 'org-remember
1590 :type '(repeat
1591 (cons
1592 (choice :value org-agenda-files
1593 (const :tag "All agenda files" org-agenda-files)
1594 (const :tag "Current buffer" nil)
1595 (function) (variable) (file))
1596 (choice :tag "Identify target headline by"
1597 (cons :tag "Specific tag" (const :tag) (string))
1598 (cons :tag "TODO keyword" (const :todo) (string))
1599 (cons :tag "Regular expression" (const :regexp) (regexp))
1600 (cons :tag "Level number" (const :level) (integer))
1601 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1603 (defcustom org-refile-use-outline-path nil
1604 "Non-nil means, provide refile targets as paths.
1605 So a level 3 headline will be available as level1/level2/level3.
1606 When the value is `file', also include the file name (without directory)
1607 into the path. When `full-file-path', include the full file path."
1608 :group 'org-remember
1609 :type '(choice
1610 (const :tag "Not" nil)
1611 (const :tag "Yes" t)
1612 (const :tag "Start with file name" file)
1613 (const :tag "Start with full file path" full-file-path)))
1615 (defgroup org-todo nil
1616 "Options concerning TODO items in Org-mode."
1617 :tag "Org TODO"
1618 :group 'org)
1620 (defgroup org-progress nil
1621 "Options concerning Progress logging in Org-mode."
1622 :tag "Org Progress"
1623 :group 'org-time)
1625 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1626 "List of TODO entry keyword sequences and their interpretation.
1627 \\<org-mode-map>This is a list of sequences.
1629 Each sequence starts with a symbol, either `sequence' or `type',
1630 indicating if the keywords should be interpreted as a sequence of
1631 action steps, or as different types of TODO items. The first
1632 keywords are states requiring action - these states will select a headline
1633 for inclusion into the global TODO list Org-mode produces. If one of
1634 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1635 signify that no further action is necessary. If \"|\" is not found,
1636 the last keyword is treated as the only DONE state of the sequence.
1638 The command \\[org-todo] cycles an entry through these states, and one
1639 additional state where no keyword is present. For details about this
1640 cycling, see the manual.
1642 TODO keywords and interpretation can also be set on a per-file basis with
1643 the special #+SEQ_TODO and #+TYP_TODO lines.
1645 For backward compatibility, this variable may also be just a list
1646 of keywords - in this case the interptetation (sequence or type) will be
1647 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1648 :group 'org-todo
1649 :group 'org-keywords
1650 :type '(choice
1651 (repeat :tag "Old syntax, just keywords"
1652 (string :tag "Keyword"))
1653 (repeat :tag "New syntax"
1654 (cons
1655 (choice
1656 :tag "Interpretation"
1657 (const :tag "Sequence (cycling hits every state)" sequence)
1658 (const :tag "Type (cycling directly to DONE)" type))
1659 (repeat
1660 (string :tag "Keyword"))))))
1662 (defvar org-todo-keywords-1 nil)
1663 (make-variable-buffer-local 'org-todo-keywords-1)
1664 (defvar org-todo-keywords-for-agenda nil)
1665 (defvar org-done-keywords-for-agenda nil)
1666 (defvar org-not-done-keywords nil)
1667 (make-variable-buffer-local 'org-not-done-keywords)
1668 (defvar org-done-keywords nil)
1669 (make-variable-buffer-local 'org-done-keywords)
1670 (defvar org-todo-heads nil)
1671 (make-variable-buffer-local 'org-todo-heads)
1672 (defvar org-todo-sets nil)
1673 (make-variable-buffer-local 'org-todo-sets)
1674 (defvar org-todo-log-states nil)
1675 (make-variable-buffer-local 'org-todo-log-states)
1676 (defvar org-todo-kwd-alist nil)
1677 (make-variable-buffer-local 'org-todo-kwd-alist)
1678 (defvar org-todo-key-alist nil)
1679 (make-variable-buffer-local 'org-todo-key-alist)
1680 (defvar org-todo-key-trigger nil)
1681 (make-variable-buffer-local 'org-todo-key-trigger)
1683 (defcustom org-todo-interpretation 'sequence
1684 "Controls how TODO keywords are interpreted.
1685 This variable is in principle obsolete and is only used for
1686 backward compatibility, if the interpretation of todo keywords is
1687 not given already in `org-todo-keywords'. See that variable for
1688 more information."
1689 :group 'org-todo
1690 :group 'org-keywords
1691 :type '(choice (const sequence)
1692 (const type)))
1694 (defcustom org-use-fast-todo-selection 'prefix
1695 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1696 This variable describes if and under what circumstances the cycling
1697 mechanism for TODO keywords will be replaced by a single-key, direct
1698 selection scheme.
1700 When nil, fast selection is never used.
1702 When the symbol `prefix', it will be used when `org-todo' is called with
1703 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1704 in an agenda buffer.
1706 When t, fast selection is used by default. In this case, the prefix
1707 argument forces cycling instead.
1709 In all cases, the special interface is only used if access keys have actually
1710 been assigned by the user, i.e. if keywords in the configuration are followed
1711 by a letter in parenthesis, like TODO(t)."
1712 :group 'org-todo
1713 :type '(choice
1714 (const :tag "Never" nil)
1715 (const :tag "By default" t)
1716 (const :tag "Only with C-u C-c C-t" prefix)))
1718 (defcustom org-after-todo-state-change-hook nil
1719 "Hook which is run after the state of a TODO item was changed.
1720 The new state (a string with a TODO keyword, or nil) is available in the
1721 Lisp variable `state'."
1722 :group 'org-todo
1723 :type 'hook)
1725 (defcustom org-log-done nil
1726 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1727 When the state of an entry is changed from nothing or a DONE state to
1728 a not-done TODO state, remove a previous closing date.
1730 This can also be a list of symbols indicating under which conditions
1731 the time stamp recording the action should be annotated with a short note.
1732 Valid members of this list are
1734 done Offer to record a note when marking entries done
1735 state Offer to record a note whenever changing the TODO state
1736 of an item. This is only relevant if TODO keywords are
1737 interpreted as sequence, see variable `org-todo-interpretation'.
1738 When `state' is set, this includes tracking `done'.
1739 clock-out Offer to record a note when clocking out of an item.
1741 A separate window will then pop up and allow you to type a note.
1742 After finishing with C-c C-c, the note will be added directly after the
1743 timestamp, as a plain list item. See also the variable
1744 `org-log-note-headings'.
1746 Logging can also be configured on a per-file basis by adding one of
1747 the following lines anywhere in the buffer:
1749 #+STARTUP: logdone
1750 #+STARTUP: nologging
1751 #+STARTUP: lognotedone
1752 #+STARTUP: lognotestate
1753 #+STARTUP: lognoteclock-out
1755 You can have local logging settings for a subtree by setting the LOGGING
1756 property to one or more of these keywords."
1757 :group 'org-todo
1758 :group 'org-progress
1759 :type '(choice
1760 (const :tag "off" nil)
1761 (const :tag "on" t)
1762 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1763 (const :tag "when item is marked DONE" done)
1764 (const :tag "when TODO state changes" state)
1765 (const :tag "when clocking out" clock-out))))
1767 (defcustom org-log-done-with-time t
1768 "Non-nil means, the CLOSED time stamp will contain date and time.
1769 When nil, only the date will be recorded."
1770 :group 'org-progress
1771 :type 'boolean)
1773 (defcustom org-log-note-headings
1774 '((done . "CLOSING NOTE %t")
1775 (state . "State %-12s %t")
1776 (clock-out . ""))
1777 "Headings for notes added when clocking out or closing TODO items.
1778 The value is an alist, with the car being a symbol indicating the note
1779 context, and the cdr is the heading to be used. The heading may also be the
1780 empty string.
1781 %t in the heading will be replaced by a time stamp.
1782 %s will be replaced by the new TODO state, in double quotes.
1783 %u will be replaced by the user name.
1784 %U will be replaced by the full user name."
1785 :group 'org-todo
1786 :group 'org-progress
1787 :type '(list :greedy t
1788 (cons (const :tag "Heading when closing an item" done) string)
1789 (cons (const :tag
1790 "Heading when changing todo state (todo sequence only)"
1791 state) string)
1792 (cons (const :tag "Heading when clocking out" clock-out) string)))
1794 (defcustom org-log-states-order-reversed t
1795 "Non-nil means, the latest state change note will be directly after heading.
1796 When nil, the notes will be orderer according to time."
1797 :group 'org-todo
1798 :group 'org-progress
1799 :type 'boolean)
1801 (defcustom org-log-repeat t
1802 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1803 When nil, no note will be taken.
1804 This option can also be set with on a per-file-basis with
1806 #+STARTUP: logrepeat
1807 #+STARTUP: nologrepeat
1809 You can have local logging settings for a subtree by setting the LOGGING
1810 property to one or more of these keywords."
1811 :group 'org-todo
1812 :group 'org-progress
1813 :type 'boolean)
1815 (defcustom org-clock-into-drawer 2
1816 "Should clocking info be wrapped into a drawer?
1817 When t, clocking info will always be inserted into a :CLOCK: drawer.
1818 If necessary, the drawer will be created.
1819 When nil, the drawer will not be created, but used when present.
1820 When an integer and the number of clocking entries in an item
1821 reaches or exceeds this number, a drawer will be created."
1822 :group 'org-todo
1823 :group 'org-progress
1824 :type '(choice
1825 (const :tag "Always" t)
1826 (const :tag "Only when drawer exists" nil)
1827 (integer :tag "When at least N clock entries")))
1829 (defcustom org-clock-out-when-done t
1830 "When t, the clock will be stopped when the relevant entry is marked DONE.
1831 Nil means, clock will keep running until stopped explicitly with
1832 `C-c C-x C-o', or until the clock is started in a different item."
1833 :group 'org-progress
1834 :type 'boolean)
1836 (defcustom org-clock-in-switch-to-state nil
1837 "Set task to a special todo state while clocking it.
1838 The value should be the state to which the entry should be switched."
1839 :group 'org-progress
1840 :group 'org-todo
1841 :type '(choice
1842 (const :tag "Don't force a state" nil)
1843 (string :tag "State")))
1845 (defgroup org-priorities nil
1846 "Priorities in Org-mode."
1847 :tag "Org Priorities"
1848 :group 'org-todo)
1850 (defcustom org-highest-priority ?A
1851 "The highest priority of TODO items. A character like ?A, ?B etc.
1852 Must have a smaller ASCII number than `org-lowest-priority'."
1853 :group 'org-priorities
1854 :type 'character)
1856 (defcustom org-lowest-priority ?C
1857 "The lowest priority of TODO items. A character like ?A, ?B etc.
1858 Must have a larger ASCII number than `org-highest-priority'."
1859 :group 'org-priorities
1860 :type 'character)
1862 (defcustom org-default-priority ?B
1863 "The default priority of TODO items.
1864 This is the priority an item get if no explicit priority is given."
1865 :group 'org-priorities
1866 :type 'character)
1868 (defcustom org-priority-start-cycle-with-default t
1869 "Non-nil means, start with default priority when starting to cycle.
1870 When this is nil, the first step in the cycle will be (depending on the
1871 command used) one higher or lower that the default priority."
1872 :group 'org-priorities
1873 :type 'boolean)
1875 (defgroup org-time nil
1876 "Options concerning time stamps and deadlines in Org-mode."
1877 :tag "Org Time"
1878 :group 'org)
1880 (defcustom org-insert-labeled-timestamps-at-point nil
1881 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1882 When nil, these labeled time stamps are forces into the second line of an
1883 entry, just after the headline. When scheduling from the global TODO list,
1884 the time stamp will always be forced into the second line."
1885 :group 'org-time
1886 :type 'boolean)
1888 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1889 "Formats for `format-time-string' which are used for time stamps.
1890 It is not recommended to change this constant.")
1892 (defcustom org-time-stamp-rounding-minutes 0
1893 "Number of minutes to round time stamps to upon insertion.
1894 When zero, insert the time unmodified. Useful rounding numbers
1895 should be factors of 60, so for example 5, 10, 15.
1896 When this is not zero, you can still force an exact time-stamp by using
1897 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1898 :group 'org-time
1899 :type 'integer)
1901 (defcustom org-display-custom-times nil
1902 "Non-nil means, overlay custom formats over all time stamps.
1903 The formats are defined through the variable `org-time-stamp-custom-formats'.
1904 To turn this on on a per-file basis, insert anywhere in the file:
1905 #+STARTUP: customtime"
1906 :group 'org-time
1907 :set 'set-default
1908 :type 'sexp)
1909 (make-variable-buffer-local 'org-display-custom-times)
1911 (defcustom org-time-stamp-custom-formats
1912 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1913 "Custom formats for time stamps. See `format-time-string' for the syntax.
1914 These are overlayed over the default ISO format if the variable
1915 `org-display-custom-times' is set. Time like %H:%M should be at the
1916 end of the second format."
1917 :group 'org-time
1918 :type 'sexp)
1920 (defun org-time-stamp-format (&optional long inactive)
1921 "Get the right format for a time string."
1922 (let ((f (if long (cdr org-time-stamp-formats)
1923 (car org-time-stamp-formats))))
1924 (if inactive
1925 (concat "[" (substring f 1 -1) "]")
1926 f)))
1928 (defcustom org-read-date-prefer-future t
1929 "Non-nil means, assume future for incomplete date input from user.
1930 This affects the following situations:
1931 1. The user gives a day, but no month.
1932 For example, if today is the 15th, and you enter \"3\", Org-mode will
1933 read this as the third of *next* month. However, if you enter \"17\",
1934 it will be considered as *this* month.
1935 2. The user gives a month but not a year.
1936 For example, if it is april and you enter \"feb 2\", this will be read
1937 as feb 2, *next* year. \"May 5\", however, will be this year.
1939 When this option is nil, the current month and year will always be used
1940 as defaults."
1941 :group 'org-time
1942 :type 'boolean)
1944 (defcustom org-read-date-display-live t
1945 "Non-nil means, display current interpretation of date prompt live.
1946 This display will be in an overlay, in the minibuffer."
1947 :group 'org-time
1948 :type 'boolean)
1950 (defcustom org-read-date-popup-calendar t
1951 "Non-nil means, pop up a calendar when prompting for a date.
1952 In the calendar, the date can be selected with mouse-1. However, the
1953 minibuffer will also be active, and you can simply enter the date as well.
1954 When nil, only the minibuffer will be available."
1955 :group 'org-time
1956 :type 'boolean)
1957 (if (fboundp 'defvaralias)
1958 (defvaralias 'org-popup-calendar-for-date-prompt
1959 'org-read-date-popup-calendar))
1961 (defcustom org-extend-today-until 0
1962 "The hour when your day really ends.
1963 This has influence for the following applications:
1964 - When switching the agenda to \"today\". It it is still earlier than
1965 the time given here, the day recognized as TODAY is actually yesterday.
1966 - When a date is read from the user and it is still before the time given
1967 here, the current date and time will be assumed to be yesterday, 23:59.
1969 FIXME:
1970 IMPORTANT: This is still a very experimental feature, it may disappear
1971 again or it may be extended to mean more things."
1972 :group 'org-time
1973 :type 'number)
1975 (defcustom org-edit-timestamp-down-means-later nil
1976 "Non-nil means, S-down will increase the time in a time stamp.
1977 When nil, S-up will increase."
1978 :group 'org-time
1979 :type 'boolean)
1981 (defcustom org-calendar-follow-timestamp-change t
1982 "Non-nil means, make the calendar window follow timestamp changes.
1983 When a timestamp is modified and the calendar window is visible, it will be
1984 moved to the new date."
1985 :group 'org-time
1986 :type 'boolean)
1988 (defcustom org-clock-heading-function nil
1989 "When non-nil, should be a function to create `org-clock-heading'.
1990 This is the string shown in the mode line when a clock is running.
1991 The function is called with point at the beginning of the headline."
1992 :group 'org-time ; FIXME: Should we have a separate group????
1993 :type 'function)
1995 (defgroup org-tags nil
1996 "Options concerning tags in Org-mode."
1997 :tag "Org Tags"
1998 :group 'org)
2000 (defcustom org-tag-alist nil
2001 "List of tags allowed in Org-mode files.
2002 When this list is nil, Org-mode will base TAG input on what is already in the
2003 buffer.
2004 The value of this variable is an alist, the car of each entry must be a
2005 keyword as a string, the cdr may be a character that is used to select
2006 that tag through the fast-tag-selection interface.
2007 See the manual for details."
2008 :group 'org-tags
2009 :type '(repeat
2010 (choice
2011 (cons (string :tag "Tag name")
2012 (character :tag "Access char"))
2013 (const :tag "Start radio group" (:startgroup))
2014 (const :tag "End radio group" (:endgroup)))))
2016 (defcustom org-use-fast-tag-selection 'auto
2017 "Non-nil means, use fast tag selection scheme.
2018 This is a special interface to select and deselect tags with single keys.
2019 When nil, fast selection is never used.
2020 When the symbol `auto', fast selection is used if and only if selection
2021 characters for tags have been configured, either through the variable
2022 `org-tag-alist' or through a #+TAGS line in the buffer.
2023 When t, fast selection is always used and selection keys are assigned
2024 automatically if necessary."
2025 :group 'org-tags
2026 :type '(choice
2027 (const :tag "Always" t)
2028 (const :tag "Never" nil)
2029 (const :tag "When selection characters are configured" 'auto)))
2031 (defcustom org-fast-tag-selection-single-key nil
2032 "Non-nil means, fast tag selection exits after first change.
2033 When nil, you have to press RET to exit it.
2034 During fast tag selection, you can toggle this flag with `C-c'.
2035 This variable can also have the value `expert'. In this case, the window
2036 displaying the tags menu is not even shown, until you press C-c again."
2037 :group 'org-tags
2038 :type '(choice
2039 (const :tag "No" nil)
2040 (const :tag "Yes" t)
2041 (const :tag "Expert" expert)))
2043 (defvar org-fast-tag-selection-include-todo nil
2044 "Non-nil means, fast tags selection interface will also offer TODO states.
2045 This is an undocumented feature, you should not rely on it.")
2047 (defcustom org-tags-column -80
2048 "The column to which tags should be indented in a headline.
2049 If this number is positive, it specifies the column. If it is negative,
2050 it means that the tags should be flushright to that column. For example,
2051 -80 works well for a normal 80 character screen."
2052 :group 'org-tags
2053 :type 'integer)
2055 (defcustom org-auto-align-tags t
2056 "Non-nil means, realign tags after pro/demotion of TODO state change.
2057 These operations change the length of a headline and therefore shift
2058 the tags around. With this options turned on, after each such operation
2059 the tags are again aligned to `org-tags-column'."
2060 :group 'org-tags
2061 :type 'boolean)
2063 (defcustom org-use-tag-inheritance t
2064 "Non-nil means, tags in levels apply also for sublevels.
2065 When nil, only the tags directly given in a specific line apply there.
2066 If you turn off this option, you very likely want to turn on the
2067 companion option `org-tags-match-list-sublevels'."
2068 :group 'org-tags
2069 :type 'boolean)
2071 (defcustom org-tags-match-list-sublevels nil
2072 "Non-nil means list also sublevels of headlines matching tag search.
2073 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2074 the sublevels of a headline matching a tag search often also match
2075 the same search. Listing all of them can create very long lists.
2076 Setting this variable to nil causes subtrees of a match to be skipped.
2077 This option is off by default, because inheritance in on. If you turn
2078 inheritance off, you very likely want to turn this option on.
2080 As a special case, if the tag search is restricted to TODO items, the
2081 value of this variable is ignored and sublevels are always checked, to
2082 make sure all corresponding TODO items find their way into the list."
2083 :group 'org-tags
2084 :type 'boolean)
2086 (defvar org-tags-history nil
2087 "History of minibuffer reads for tags.")
2088 (defvar org-last-tags-completion-table nil
2089 "The last used completion table for tags.")
2090 (defvar org-after-tags-change-hook nil
2091 "Hook that is run after the tags in a line have changed.")
2093 (defgroup org-properties nil
2094 "Options concerning properties in Org-mode."
2095 :tag "Org Properties"
2096 :group 'org)
2098 (defcustom org-property-format "%-10s %s"
2099 "How property key/value pairs should be formatted by `indent-line'.
2100 When `indent-line' hits a property definition, it will format the line
2101 according to this format, mainly to make sure that the values are
2102 lined-up with respect to each other."
2103 :group 'org-properties
2104 :type 'string)
2106 (defcustom org-use-property-inheritance nil
2107 "Non-nil means, properties apply also for sublevels.
2108 This setting is only relevant during property searches, not when querying
2109 an entry with `org-entry-get'. To retrieve a property with inheritance,
2110 you need to call `org-entry-get' with the inheritance flag.
2111 Turning this on can cause significant overhead when doing a search, so
2112 this is turned off by default.
2113 When nil, only the properties directly given in the current entry count.
2114 The value may also be a list of properties that shouldhave inheritance.
2116 However, note that some special properties use inheritance under special
2117 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2118 and the properties ending in \"_ALL\" when they are used as descriptor
2119 for valid values of a property."
2120 :group 'org-properties
2121 :type '(choice
2122 (const :tag "Not" nil)
2123 (const :tag "Always" nil)
2124 (repeat :tag "Specific properties" (string :tag "Property"))))
2126 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2127 "The default column format, if no other format has been defined.
2128 This variable can be set on the per-file basis by inserting a line
2130 #+COLUMNS: %25ITEM ....."
2131 :group 'org-properties
2132 :type 'string)
2134 (defcustom org-global-properties nil
2135 "List of property/value pairs that can be inherited by any entry.
2136 You can set buffer-local values for this by adding lines like
2138 #+PROPERTY: NAME VALUE"
2139 :group 'org-properties
2140 :type '(repeat
2141 (cons (string :tag "Property")
2142 (string :tag "Value"))))
2144 (defvar org-local-properties nil
2145 "List of property/value pairs that can be inherited by any entry.
2146 Valid for the current buffer.
2147 This variable is populated from #+PROPERTY lines.")
2149 (defgroup org-agenda nil
2150 "Options concerning agenda views in Org-mode."
2151 :tag "Org Agenda"
2152 :group 'org)
2154 (defvar org-category nil
2155 "Variable used by org files to set a category for agenda display.
2156 Such files should use a file variable to set it, for example
2158 # -*- mode: org; org-category: \"ELisp\"
2160 or contain a special line
2162 #+CATEGORY: ELisp
2164 If the file does not specify a category, then file's base name
2165 is used instead.")
2166 (make-variable-buffer-local 'org-category)
2168 (defcustom org-agenda-files nil
2169 "The files to be used for agenda display.
2170 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2171 \\[org-remove-file]. You can also use customize to edit the list.
2173 If an entry is a directory, all files in that directory that are matched by
2174 `org-agenda-file-regexp' will be part of the file list.
2176 If the value of the variable is not a list but a single file name, then
2177 the list of agenda files is actually stored and maintained in that file, one
2178 agenda file per line."
2179 :group 'org-agenda
2180 :type '(choice
2181 (repeat :tag "List of files and directories" file)
2182 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2184 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2185 "Regular expression to match files for `org-agenda-files'.
2186 If any element in the list in that variable contains a directory instead
2187 of a normal file, all files in that directory that are matched by this
2188 regular expression will be included."
2189 :group 'org-agenda
2190 :type 'regexp)
2192 (defcustom org-agenda-skip-unavailable-files nil
2193 "t means to just skip non-reachable files in `org-agenda-files'.
2194 Nil means to remove them, after a query, from the list."
2195 :group 'org-agenda
2196 :type 'boolean)
2198 (defcustom org-agenda-multi-occur-extra-files nil
2199 "List of extra files to be searched by `org-occur-in-agenda-files'.
2200 The files in `org-agenda-files' are always searched."
2201 :group 'org-agenda
2202 :type '(repeat file))
2204 (defcustom org-agenda-confirm-kill 1
2205 "When set, remote killing from the agenda buffer needs confirmation.
2206 When t, a confirmation is always needed. When a number N, confirmation is
2207 only needed when the text to be killed contains more than N non-white lines."
2208 :group 'org-agenda
2209 :type '(choice
2210 (const :tag "Never" nil)
2211 (const :tag "Always" t)
2212 (number :tag "When more than N lines")))
2214 (defcustom org-calendar-to-agenda-key [?c]
2215 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2216 The command `org-calendar-goto-agenda' will be bound to this key. The
2217 default is the character `c' because then `c' can be used to switch back and
2218 forth between agenda and calendar."
2219 :group 'org-agenda
2220 :type 'sexp)
2222 (defcustom org-agenda-compact-blocks nil
2223 "Non-nil means, make the block agenda more compact.
2224 This is done by leaving out unnecessary lines."
2225 :group 'org-agenda
2226 :type nil)
2228 (defgroup org-agenda-export nil
2229 "Options concerning exporting agenda views in Org-mode."
2230 :tag "Org Agenda Export"
2231 :group 'org-agenda)
2233 (defcustom org-agenda-with-colors t
2234 "Non-nil means, use colors in agenda views."
2235 :group 'org-agenda-export
2236 :type 'boolean)
2238 (defcustom org-agenda-exporter-settings nil
2239 "Alist of variable/value pairs that should be active during agenda export.
2240 This is a good place to set uptions for ps-print and for htmlize."
2241 :group 'org-agenda-export
2242 :type '(repeat
2243 (list
2244 (variable)
2245 (sexp :tag "Value"))))
2247 (defcustom org-agenda-export-html-style ""
2248 "The style specification for exported HTML Agenda files.
2249 If this variable contains a string, it will replace the default <style>
2250 section as produced by `htmlize'.
2251 Since there are different ways of setting style information, this variable
2252 needs to contain the full HTML structure to provide a style, including the
2253 surrounding HTML tags. The style specifications should include definitions
2254 the fonts used by the agenda, here is an example:
2256 <style type=\"text/css\">
2257 p { font-weight: normal; color: gray; }
2258 .org-agenda-structure {
2259 font-size: 110%;
2260 color: #003399;
2261 font-weight: 600;
2263 .org-todo {
2264 color: #cc6666;Week-agenda:
2265 font-weight: bold;
2267 .org-done {
2268 color: #339933;
2270 .title { text-align: center; }
2271 .todo, .deadline { color: red; }
2272 .done { color: green; }
2273 </style>
2275 or, if you want to keep the style in a file,
2277 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2279 As the value of this option simply gets inserted into the HTML <head> header,
2280 you can \"misuse\" it to also add other text to the header. However,
2281 <style>...</style> is required, if not present the variable will be ignored."
2282 :group 'org-agenda-export
2283 :group 'org-export-html
2284 :type 'string)
2286 (defgroup org-agenda-custom-commands nil
2287 "Options concerning agenda views in Org-mode."
2288 :tag "Org Agenda Custom Commands"
2289 :group 'org-agenda)
2291 (defcustom org-agenda-custom-commands nil
2292 "Custom commands for the agenda.
2293 These commands will be offered on the splash screen displayed by the
2294 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2296 (key desc type match options files)
2298 key The key (one or more characters as a string) to be associated
2299 with the command.
2300 desc A description of the commend, when omitted or nil, a default
2301 description is built using MATCH.
2302 type The command type, any of the following symbols:
2303 todo Entries with a specific TODO keyword, in all agenda files.
2304 tags Tags match in all agenda files.
2305 tags-todo Tags match in all agenda files, TODO entries only.
2306 todo-tree Sparse tree of specific TODO keyword in *current* file.
2307 tags-tree Sparse tree with all tags matches in *current* file.
2308 occur-tree Occur sparse tree for *current* file.
2309 ... A user-defined function.
2310 match What to search for:
2311 - a single keyword for TODO keyword searches
2312 - a tags match expression for tags searches
2313 - a regular expression for occur searches
2314 options A list of option settings, similar to that in a let form, so like
2315 this: ((opt1 val1) (opt2 val2) ...)
2316 files A list of files file to write the produced agenda buffer to
2317 with the command `org-store-agenda-views'.
2318 If a file name ends in \".html\", an HTML version of the buffer
2319 is written out. If it ends in \".ps\", a postscript version is
2320 produced. Otherwide, only the plain text is written to the file.
2322 You can also define a set of commands, to create a composite agenda buffer.
2323 In this case, an entry looks like this:
2325 (key desc (cmd1 cmd2 ...) general-options file)
2327 where
2329 desc A description string to be displayed in the dispatcher menu.
2330 cmd An agenda command, similar to the above. However, tree commands
2331 are no allowed, but instead you can get agenda and global todo list.
2332 So valid commands for a set are:
2333 (agenda)
2334 (alltodo)
2335 (stuck)
2336 (todo \"match\" options files)
2337 (tags \"match\" options files)
2338 (tags-todo \"match\" options files)
2340 Each command can carry a list of options, and another set of options can be
2341 given for the whole set of commands. Individual command options take
2342 precedence over the general options.
2344 When using several characters as key to a command, the first characters
2345 are prefix commands. For the dispatcher to display useful information, you
2346 should provide a description for the prefix, like
2348 (setq org-agenda-custom-commands
2349 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2350 (\"hl\" tags \"+HOME+Lisa\")
2351 (\"hp\" tags \"+HOME+Peter\")
2352 (\"hk\" tags \"+HOME+Kim\")))"
2353 :group 'org-agenda-custom-commands
2354 :type '(repeat
2355 (choice :value ("a" "" tags "" nil)
2356 (list :tag "Single command"
2357 (string :tag "Access Key(s) ")
2358 (option (string :tag "Description"))
2359 (choice
2360 (const :tag "Agenda" agenda)
2361 (const :tag "TODO list" alltodo)
2362 (const :tag "Stuck projects" stuck)
2363 (const :tag "Tags search (all agenda files)" tags)
2364 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2365 (const :tag "TODO keyword search (all agenda files)" todo)
2366 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2367 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2368 (const :tag "Occur tree (current buffer)" occur-tree)
2369 (sexp :tag "Other, user-defined function"))
2370 (string :tag "Match")
2371 (repeat :tag "Local options"
2372 (list (variable :tag "Option") (sexp :tag "Value")))
2373 (option (repeat :tag "Export" (file :tag "Export to"))))
2374 (list :tag "Command series, all agenda files"
2375 (string :tag "Access Key(s)")
2376 (string :tag "Description ")
2377 (repeat
2378 (choice
2379 (const :tag "Agenda" (agenda))
2380 (const :tag "TODO list" (alltodo))
2381 (const :tag "Stuck projects" (stuck))
2382 (list :tag "Tags search"
2383 (const :format "" tags)
2384 (string :tag "Match")
2385 (repeat :tag "Local options"
2386 (list (variable :tag "Option")
2387 (sexp :tag "Value"))))
2389 (list :tag "Tags search, TODO entries only"
2390 (const :format "" tags-todo)
2391 (string :tag "Match")
2392 (repeat :tag "Local options"
2393 (list (variable :tag "Option")
2394 (sexp :tag "Value"))))
2396 (list :tag "TODO keyword search"
2397 (const :format "" todo)
2398 (string :tag "Match")
2399 (repeat :tag "Local options"
2400 (list (variable :tag "Option")
2401 (sexp :tag "Value"))))
2403 (list :tag "Other, user-defined function"
2404 (symbol :tag "function")
2405 (string :tag "Match")
2406 (repeat :tag "Local options"
2407 (list (variable :tag "Option")
2408 (sexp :tag "Value"))))))
2410 (repeat :tag "General options"
2411 (list (variable :tag "Option")
2412 (sexp :tag "Value")))
2413 (option (repeat :tag "Export" (file :tag "Export to"))))
2414 (cons :tag "Prefix key documentation"
2415 (string :tag "Access Key(s)")
2416 (string :tag "Description ")))))
2418 (defcustom org-stuck-projects
2419 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2420 "How to identify stuck projects.
2421 This is a list of four items:
2422 1. A tags/todo matcher string that is used to identify a project.
2423 The entire tree below a headline matched by this is considered one project.
2424 2. A list of TODO keywords identifying non-stuck projects.
2425 If the project subtree contains any headline with one of these todo
2426 keywords, the project is considered to be not stuck. If you specify
2427 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2428 3. A list of tags identifying non-stuck projects.
2429 If the project subtree contains any headline with one of these tags,
2430 the project is considered to be not stuck. If you specify \"*\" as
2431 a tag, any tag will mark the project unstuck.
2432 4. An arbitrary regular expression matching non-stuck projects.
2434 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2435 or `C-c a #' to produce the list."
2436 :group 'org-agenda-custom-commands
2437 :type '(list
2438 (string :tag "Tags/TODO match to identify a project")
2439 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2440 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2441 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2444 (defgroup org-agenda-skip nil
2445 "Options concerning skipping parts of agenda files."
2446 :tag "Org Agenda Skip"
2447 :group 'org-agenda)
2449 (defcustom org-agenda-todo-list-sublevels t
2450 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2451 When nil, the sublevels of a TODO entry are not checked, resulting in
2452 potentially much shorter TODO lists."
2453 :group 'org-agenda-skip
2454 :group 'org-todo
2455 :type 'boolean)
2457 (defcustom org-agenda-todo-ignore-with-date nil
2458 "Non-nil means, don't show entries with a date in the global todo list.
2459 You can use this if you prefer to mark mere appointments with a TODO keyword,
2460 but don't want them to show up in the TODO list.
2461 When this is set, it also covers deadlines and scheduled items, the settings
2462 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2463 will be ignored."
2464 :group 'org-agenda-skip
2465 :group 'org-todo
2466 :type 'boolean)
2468 (defcustom org-agenda-todo-ignore-scheduled nil
2469 "Non-nil means, don't show scheduled entries in the global todo list.
2470 The idea behind this is that by scheduling it, you have already taken care
2471 of this item.
2472 See also `org-agenda-todo-ignore-with-date'."
2473 :group 'org-agenda-skip
2474 :group 'org-todo
2475 :type 'boolean)
2477 (defcustom org-agenda-todo-ignore-deadlines nil
2478 "Non-nil means, don't show near deadline entries in the global todo list.
2479 Near means closer than `org-deadline-warning-days' days.
2480 The idea behind this is that such items will appear in the agenda anyway.
2481 See also `org-agenda-todo-ignore-with-date'."
2482 :group 'org-agenda-skip
2483 :group 'org-todo
2484 :type 'boolean)
2486 (defcustom org-agenda-skip-scheduled-if-done nil
2487 "Non-nil means don't show scheduled items in agenda when they are done.
2488 This is relevant for the daily/weekly agenda, not for the TODO list. And
2489 it applies only to the actual date of the scheduling. Warnings about
2490 an item with a past scheduling dates are always turned off when the item
2491 is DONE."
2492 :group 'org-agenda-skip
2493 :type 'boolean)
2495 (defcustom org-agenda-skip-deadline-if-done nil
2496 "Non-nil means don't show deadines when the corresponding item is done.
2497 When nil, the deadline is still shown and should give you a happy feeling.
2498 This is relevant for the daily/weekly agenda. And it applied only to the
2499 actualy date of the deadline. Warnings about approching and past-due
2500 deadlines are always turned off when the item is DONE."
2501 :group 'org-agenda-skip
2502 :type 'boolean)
2504 (defcustom org-agenda-skip-timestamp-if-done nil
2505 "Non-nil means don't select item by timestamp or -range if it is DONE."
2506 :group 'org-agenda-skip
2507 :type 'boolean)
2509 (defcustom org-timeline-show-empty-dates 3
2510 "Non-nil means, `org-timeline' also shows dates without an entry.
2511 When nil, only the days which actually have entries are shown.
2512 When t, all days between the first and the last date are shown.
2513 When an integer, show also empty dates, but if there is a gap of more than
2514 N days, just insert a special line indicating the size of the gap."
2515 :group 'org-agenda-skip
2516 :type '(choice
2517 (const :tag "None" nil)
2518 (const :tag "All" t)
2519 (number :tag "at most")))
2522 (defgroup org-agenda-startup nil
2523 "Options concerning initial settings in the Agenda in Org Mode."
2524 :tag "Org Agenda Startup"
2525 :group 'org-agenda)
2527 (defcustom org-finalize-agenda-hook nil
2528 "Hook run just before displaying an agenda buffer."
2529 :group 'org-agenda-startup
2530 :type 'hook)
2532 (defcustom org-agenda-mouse-1-follows-link nil
2533 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2534 A longer mouse click will still set point. Does not wortk on XEmacs.
2535 Needs to be set before org.el is loaded."
2536 :group 'org-agenda-startup
2537 :type 'boolean)
2539 (defcustom org-agenda-start-with-follow-mode nil
2540 "The initial value of follow-mode in a newly created agenda window."
2541 :group 'org-agenda-startup
2542 :type 'boolean)
2544 (defgroup org-agenda-windows nil
2545 "Options concerning the windows used by the Agenda in Org Mode."
2546 :tag "Org Agenda Windows"
2547 :group 'org-agenda)
2549 (defcustom org-agenda-window-setup 'reorganize-frame
2550 "How the agenda buffer should be displayed.
2551 Possible values for this option are:
2553 current-window Show agenda in the current window, keeping all other windows.
2554 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2555 other-window Use `switch-to-buffer-other-window' to display agenda.
2556 reorganize-frame Show only two windows on the current frame, the current
2557 window and the agenda.
2558 See also the variable `org-agenda-restore-windows-after-quit'."
2559 :group 'org-agenda-windows
2560 :type '(choice
2561 (const current-window)
2562 (const other-frame)
2563 (const other-window)
2564 (const reorganize-frame)))
2566 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2567 "The min and max height of the agenda window as a fraction of frame height.
2568 The value of the variable is a cons cell with two numbers between 0 and 1.
2569 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2570 :group 'org-agenda-windows
2571 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2573 (defcustom org-agenda-restore-windows-after-quit nil
2574 "Non-nil means, restore window configuration open exiting agenda.
2575 Before the window configuration is changed for displaying the agenda,
2576 the current status is recorded. When the agenda is exited with
2577 `q' or `x' and this option is set, the old state is restored. If
2578 `org-agenda-window-setup' is `other-frame', the value of this
2579 option will be ignored.."
2580 :group 'org-agenda-windows
2581 :type 'boolean)
2583 (defcustom org-indirect-buffer-display 'other-window
2584 "How should indirect tree buffers be displayed?
2585 This applies to indirect buffers created with the commands
2586 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2587 Valid values are:
2588 current-window Display in the current window
2589 other-window Just display in another window.
2590 dedicated-frame Create one new frame, and re-use it each time.
2591 new-frame Make a new frame each time. Note that in this case
2592 previously-made indirect buffers are kept, and you need to
2593 kill these buffers yourself."
2594 :group 'org-structure
2595 :group 'org-agenda-windows
2596 :type '(choice
2597 (const :tag "In current window" current-window)
2598 (const :tag "In current frame, other window" other-window)
2599 (const :tag "Each time a new frame" new-frame)
2600 (const :tag "One dedicated frame" dedicated-frame)))
2602 (defgroup org-agenda-daily/weekly nil
2603 "Options concerning the daily/weekly agenda."
2604 :tag "Org Agenda Daily/Weekly"
2605 :group 'org-agenda)
2607 (defcustom org-agenda-ndays 7
2608 "Number of days to include in overview display.
2609 Should be 1 or 7."
2610 :group 'org-agenda-daily/weekly
2611 :type 'number)
2613 (defcustom org-agenda-start-on-weekday 1
2614 "Non-nil means, start the overview always on the specified weekday.
2615 0 denotes Sunday, 1 denotes Monday etc.
2616 When nil, always start on the current day."
2617 :group 'org-agenda-daily/weekly
2618 :type '(choice (const :tag "Today" nil)
2619 (number :tag "Weekday No.")))
2621 (defcustom org-agenda-show-all-dates t
2622 "Non-nil means, `org-agenda' shows every day in the selected range.
2623 When nil, only the days which actually have entries are shown."
2624 :group 'org-agenda-daily/weekly
2625 :type 'boolean)
2627 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2628 "Format string for displaying dates in the agenda.
2629 Used by the daily/weekly agenda and by the timeline. This should be
2630 a format string understood by `format-time-string', or a function returning
2631 the formatted date as a string. The function must take a single argument,
2632 a calendar-style date list like (month day year)."
2633 :group 'org-agenda-daily/weekly
2634 :type '(choice
2635 (string :tag "Format string")
2636 (function :tag "Function")))
2638 (defun org-agenda-format-date-aligned (date)
2639 "Format a date string for display in the daily/weekly agenda, or timeline.
2640 This function makes sure that dates are aligned for easy reading."
2641 (format "%-9s %2d %s %4d"
2642 (calendar-day-name date)
2643 (extract-calendar-day date)
2644 (calendar-month-name (extract-calendar-month date))
2645 (extract-calendar-year date)))
2647 (defcustom org-agenda-include-diary nil
2648 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2649 :group 'org-agenda-daily/weekly
2650 :type 'boolean)
2652 (defcustom org-agenda-include-all-todo nil
2653 "Set means weekly/daily agenda will always contain all TODO entries.
2654 The TODO entries will be listed at the top of the agenda, before
2655 the entries for specific days."
2656 :group 'org-agenda-daily/weekly
2657 :type 'boolean)
2659 (defcustom org-agenda-repeating-timestamp-show-all t
2660 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2661 When nil, only one occurence is shown, either today or the
2662 nearest into the future."
2663 :group 'org-agenda-daily/weekly
2664 :type 'boolean)
2666 (defcustom org-deadline-warning-days 14
2667 "No. of days before expiration during which a deadline becomes active.
2668 This variable governs the display in sparse trees and in the agenda.
2669 When negative, it means use this number (the absolute value of it)
2670 even if a deadline has a different individual lead time specified."
2671 :group 'org-time
2672 :group 'org-agenda-daily/weekly
2673 :type 'number)
2675 (defcustom org-scheduled-past-days 10000
2676 "No. of days to continue listing scheduled items that are not marked DONE.
2677 When an item is scheduled on a date, it shows up in the agenda on this
2678 day and will be listed until it is marked done for the number of days
2679 given here."
2680 :group 'org-agenda-daily/weekly
2681 :type 'number)
2683 (defgroup org-agenda-time-grid nil
2684 "Options concerning the time grid in the Org-mode Agenda."
2685 :tag "Org Agenda Time Grid"
2686 :group 'org-agenda)
2688 (defcustom org-agenda-use-time-grid t
2689 "Non-nil means, show a time grid in the agenda schedule.
2690 A time grid is a set of lines for specific times (like every two hours between
2691 8:00 and 20:00). The items scheduled for a day at specific times are
2692 sorted in between these lines.
2693 For details about when the grid will be shown, and what it will look like, see
2694 the variable `org-agenda-time-grid'."
2695 :group 'org-agenda-time-grid
2696 :type 'boolean)
2698 (defcustom org-agenda-time-grid
2699 '((daily today require-timed)
2700 "----------------"
2701 (800 1000 1200 1400 1600 1800 2000))
2703 "The settings for time grid for agenda display.
2704 This is a list of three items. The first item is again a list. It contains
2705 symbols specifying conditions when the grid should be displayed:
2707 daily if the agenda shows a single day
2708 weekly if the agenda shows an entire week
2709 today show grid on current date, independent of daily/weekly display
2710 require-timed show grid only if at least one item has a time specification
2712 The second item is a string which will be places behing the grid time.
2714 The third item is a list of integers, indicating the times that should have
2715 a grid line."
2716 :group 'org-agenda-time-grid
2717 :type
2718 '(list
2719 (set :greedy t :tag "Grid Display Options"
2720 (const :tag "Show grid in single day agenda display" daily)
2721 (const :tag "Show grid in weekly agenda display" weekly)
2722 (const :tag "Always show grid for today" today)
2723 (const :tag "Show grid only if any timed entries are present"
2724 require-timed)
2725 (const :tag "Skip grid times already present in an entry"
2726 remove-match))
2727 (string :tag "Grid String")
2728 (repeat :tag "Grid Times" (integer :tag "Time"))))
2730 (defgroup org-agenda-sorting nil
2731 "Options concerning sorting in the Org-mode Agenda."
2732 :tag "Org Agenda Sorting"
2733 :group 'org-agenda)
2735 (defconst org-sorting-choice
2736 '(choice
2737 (const time-up) (const time-down)
2738 (const category-keep) (const category-up) (const category-down)
2739 (const tag-down) (const tag-up)
2740 (const priority-up) (const priority-down))
2741 "Sorting choices.")
2743 (defcustom org-agenda-sorting-strategy
2744 '((agenda time-up category-keep priority-down)
2745 (todo category-keep priority-down)
2746 (tags category-keep priority-down))
2747 "Sorting structure for the agenda items of a single day.
2748 This is a list of symbols which will be used in sequence to determine
2749 if an entry should be listed before another entry. The following
2750 symbols are recognized:
2752 time-up Put entries with time-of-day indications first, early first
2753 time-down Put entries with time-of-day indications first, late first
2754 category-keep Keep the default order of categories, corresponding to the
2755 sequence in `org-agenda-files'.
2756 category-up Sort alphabetically by category, A-Z.
2757 category-down Sort alphabetically by category, Z-A.
2758 tag-up Sort alphabetically by last tag, A-Z.
2759 tag-down Sort alphabetically by last tag, Z-A.
2760 priority-up Sort numerically by priority, high priority last.
2761 priority-down Sort numerically by priority, high priority first.
2763 The different possibilities will be tried in sequence, and testing stops
2764 if one comparison returns a \"not-equal\". For example, the default
2765 '(time-up category-keep priority-down)
2766 means: Pull out all entries having a specified time of day and sort them,
2767 in order to make a time schedule for the current day the first thing in the
2768 agenda listing for the day. Of the entries without a time indication, keep
2769 the grouped in categories, don't sort the categories, but keep them in
2770 the sequence given in `org-agenda-files'. Within each category sort by
2771 priority.
2773 Leaving out `category-keep' would mean that items will be sorted across
2774 categories by priority.
2776 Instead of a single list, this can also be a set of list for specific
2777 contents, with a context symbol in the car of the list, any of
2778 `agenda', `todo', `tags' for the corresponding agenda views."
2779 :group 'org-agenda-sorting
2780 :type `(choice
2781 (repeat :tag "General" ,org-sorting-choice)
2782 (list :tag "Individually"
2783 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2784 (repeat ,org-sorting-choice))
2785 (cons (const :tag "Strategy for TODO lists" todo)
2786 (repeat ,org-sorting-choice))
2787 (cons (const :tag "Strategy for Tags matches" tags)
2788 (repeat ,org-sorting-choice)))))
2790 (defcustom org-sort-agenda-notime-is-late t
2791 "Non-nil means, items without time are considered late.
2792 This is only relevant for sorting. When t, items which have no explicit
2793 time like 15:30 will be considered as 99:01, i.e. later than any items which
2794 do have a time. When nil, the default time is before 0:00. You can use this
2795 option to decide if the schedule for today should come before or after timeless
2796 agenda entries."
2797 :group 'org-agenda-sorting
2798 :type 'boolean)
2800 (defgroup org-agenda-line-format nil
2801 "Options concerning the entry prefix in the Org-mode agenda display."
2802 :tag "Org Agenda Line Format"
2803 :group 'org-agenda)
2805 (defcustom org-agenda-prefix-format
2806 '((agenda . " %-12:c%?-12t% s")
2807 (timeline . " % s")
2808 (todo . " %-12:c")
2809 (tags . " %-12:c"))
2810 "Format specifications for the prefix of items in the agenda views.
2811 An alist with four entries, for the different agenda types. The keys to the
2812 sublists are `agenda', `timeline', `todo', and `tags'. The values
2813 are format strings.
2814 This format works similar to a printf format, with the following meaning:
2816 %c the category of the item, \"Diary\" for entries from the diary, or
2817 as given by the CATEGORY keyword or derived from the file name.
2818 %T the *last* tag of the item. Last because inherited tags come
2819 first in the list.
2820 %t the time-of-day specification if one applies to the entry, in the
2821 format HH:MM
2822 %s Scheduling/Deadline information, a short string
2824 All specifiers work basically like the standard `%s' of printf, but may
2825 contain two additional characters: A question mark just after the `%' and
2826 a whitespace/punctuation character just before the final letter.
2828 If the first character after `%' is a question mark, the entire field
2829 will only be included if the corresponding value applies to the
2830 current entry. This is useful for fields which should have fixed
2831 width when present, but zero width when absent. For example,
2832 \"%?-12t\" will result in a 12 character time field if a time of the
2833 day is specified, but will completely disappear in entries which do
2834 not contain a time.
2836 If there is punctuation or whitespace character just before the final
2837 format letter, this character will be appended to the field value if
2838 the value is not empty. For example, the format \"%-12:c\" leads to
2839 \"Diary: \" if the category is \"Diary\". If the category were be
2840 empty, no additional colon would be interted.
2842 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2843 - Indent the line with two space characters
2844 - Give the category in a 12 chars wide field, padded with whitespace on
2845 the right (because of `-'). Append a colon if there is a category
2846 (because of `:').
2847 - If there is a time-of-day, put it into a 12 chars wide field. If no
2848 time, don't put in an empty field, just skip it (because of '?').
2849 - Finally, put the scheduling information and append a whitespace.
2851 As another example, if you don't want the time-of-day of entries in
2852 the prefix, you could use:
2854 (setq org-agenda-prefix-format \" %-11:c% s\")
2856 See also the variables `org-agenda-remove-times-when-in-prefix' and
2857 `org-agenda-remove-tags'."
2858 :type '(choice
2859 (string :tag "General format")
2860 (list :greedy t :tag "View dependent"
2861 (cons (const agenda) (string :tag "Format"))
2862 (cons (const timeline) (string :tag "Format"))
2863 (cons (const todo) (string :tag "Format"))
2864 (cons (const tags) (string :tag "Format"))))
2865 :group 'org-agenda-line-format)
2867 (defvar org-prefix-format-compiled nil
2868 "The compiled version of the most recently used prefix format.
2869 See the variable `org-agenda-prefix-format'.")
2871 (defcustom org-agenda-todo-keyword-format "%-1s"
2872 "Format for the TODO keyword in agenda lines.
2873 Set this to something like \"%-12s\" if you want all TODO keywords
2874 to occupy a fixed space in the agenda display."
2875 :group 'org-agenda-line-format
2876 :type 'string)
2878 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2879 "Text preceeding scheduled items in the agenda view.
2880 This is a list with two strings. The first applies when the item is
2881 scheduled on the current day. The second applies when it has been scheduled
2882 previously, it may contain a %d to capture how many days ago the item was
2883 scheduled."
2884 :group 'org-agenda-line-format
2885 :type '(list
2886 (string :tag "Scheduled today ")
2887 (string :tag "Scheduled previously")))
2889 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2890 "Text preceeding deadline items in the agenda view.
2891 This is a list with two strings. The first applies when the item has its
2892 deadline on the current day. The second applies when it is in the past or
2893 in the future, it may contain %d to capture how many days away the deadline
2894 is (was)."
2895 :group 'org-agenda-line-format
2896 :type '(list
2897 (string :tag "Deadline today ")
2898 (string :tag "Deadline relative")))
2900 (defcustom org-agenda-remove-times-when-in-prefix t
2901 "Non-nil means, remove duplicate time specifications in agenda items.
2902 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2903 time-of-day specification in a headline or diary entry is extracted and
2904 placed into the prefix. If this option is non-nil, the original specification
2905 \(a timestamp or -range, or just a plain time(range) specification like
2906 11:30-4pm) will be removed for agenda display. This makes the agenda less
2907 cluttered.
2908 The option can be t or nil. It may also be the symbol `beg', indicating
2909 that the time should only be removed what it is located at the beginning of
2910 the headline/diary entry."
2911 :group 'org-agenda-line-format
2912 :type '(choice
2913 (const :tag "Always" t)
2914 (const :tag "Never" nil)
2915 (const :tag "When at beginning of entry" beg)))
2918 (defcustom org-agenda-default-appointment-duration nil
2919 "Default duration for appointments that only have a starting time.
2920 When nil, no duration is specified in such cases.
2921 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2922 :group 'org-agenda-line-format
2923 :type '(choice
2924 (integer :tag "Minutes")
2925 (const :tag "No default duration")))
2928 (defcustom org-agenda-remove-tags nil
2929 "Non-nil means, remove the tags from the headline copy in the agenda.
2930 When this is the symbol `prefix', only remove tags when
2931 `org-agenda-prefix-format' contains a `%T' specifier."
2932 :group 'org-agenda-line-format
2933 :type '(choice
2934 (const :tag "Always" t)
2935 (const :tag "Never" nil)
2936 (const :tag "When prefix format contains %T" prefix)))
2938 (if (fboundp 'defvaralias)
2939 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2940 'org-agenda-remove-tags))
2942 (defcustom org-agenda-tags-column -80
2943 "Shift tags in agenda items to this column.
2944 If this number is positive, it specifies the column. If it is negative,
2945 it means that the tags should be flushright to that column. For example,
2946 -80 works well for a normal 80 character screen."
2947 :group 'org-agenda-line-format
2948 :type 'integer)
2950 (if (fboundp 'defvaralias)
2951 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2953 (defcustom org-agenda-fontify-priorities t
2954 "Non-nil means, highlight low and high priorities in agenda.
2955 When t, the highest priority entries are bold, lowest priority italic.
2956 This may also be an association list of priority faces. The face may be
2957 a names face, or a list like `(:background \"Red\")'."
2958 :group 'org-agenda-line-format
2959 :type '(choice
2960 (const :tag "Never" nil)
2961 (const :tag "Defaults" t)
2962 (repeat :tag "Specify"
2963 (list (character :tag "Priority" :value ?A)
2964 (sexp :tag "face")))))
2966 (defgroup org-latex nil
2967 "Options for embedding LaTeX code into Org-mode"
2968 :tag "Org LaTeX"
2969 :group 'org)
2971 (defcustom org-format-latex-options
2972 '(:foreground default :background default :scale 1.0
2973 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2974 :matchers ("begin" "$" "$$" "\\(" "\\["))
2975 "Options for creating images from LaTeX fragments.
2976 This is a property list with the following properties:
2977 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2978 `default' means use the forground of the default face.
2979 :background the background color, or \"Transparent\".
2980 `default' means use the background of the default face.
2981 :scale a scaling factor for the size of the images
2982 :html-foreground, :html-background, :html-scale
2983 The same numbers for HTML export.
2984 :matchers a list indicating which matchers should be used to
2985 find LaTeX fragments. Valid members of this list are:
2986 \"begin\" find environments
2987 \"$\" find math expressions surrounded by $...$
2988 \"$$\" find math expressions surrounded by $$....$$
2989 \"\\(\" find math expressions surrounded by \\(...\\)
2990 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2991 :group 'org-latex
2992 :type 'plist)
2994 (defcustom org-format-latex-header "\\documentclass{article}
2995 \\usepackage{fullpage} % do not remove
2996 \\usepackage{amssymb}
2997 \\usepackage[usenames]{color}
2998 \\usepackage{amsmath}
2999 \\usepackage{latexsym}
3000 \\usepackage[mathscr]{eucal}
3001 \\pagestyle{empty} % do not remove"
3002 "The document header used for processing LaTeX fragments."
3003 :group 'org-latex
3004 :type 'string)
3006 (defgroup org-export nil
3007 "Options for exporting org-listings."
3008 :tag "Org Export"
3009 :group 'org)
3011 (defgroup org-export-general nil
3012 "General options for exporting Org-mode files."
3013 :tag "Org Export General"
3014 :group 'org-export)
3016 ;; FIXME
3017 (defvar org-export-publishing-directory nil)
3019 (defcustom org-export-with-special-strings t
3020 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3021 When this option is turned on, these strings will be exported as:
3023 Org HTML LaTeX
3024 -----+----------+--------
3025 \\- &shy; \\-
3026 -- &ndash; --
3027 --- &mdash; ---
3028 ... &hellip; \ldots
3030 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3031 :group 'org-export-translation
3032 :type 'boolean)
3034 (defcustom org-export-language-setup
3035 '(("en" "Author" "Date" "Table of Contents")
3036 ("cs" "Autor" "Datum" "Obsah")
3037 ("da" "Ophavsmand" "Dato" "Indhold")
3038 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3039 ("es" "Autor" "Fecha" "\xcdndice")
3040 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3041 ("it" "Autore" "Data" "Indice")
3042 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3043 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3044 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3045 "Terms used in export text, translated to different languages.
3046 Use the variable `org-export-default-language' to set the language,
3047 or use the +OPTION lines for a per-file setting."
3048 :group 'org-export-general
3049 :type '(repeat
3050 (list
3051 (string :tag "HTML language tag")
3052 (string :tag "Author")
3053 (string :tag "Date")
3054 (string :tag "Table of Contents"))))
3056 (defcustom org-export-default-language "en"
3057 "The default language of HTML export, as a string.
3058 This should have an association in `org-export-language-setup'."
3059 :group 'org-export-general
3060 :type 'string)
3062 (defcustom org-export-skip-text-before-1st-heading t
3063 "Non-nil means, skip all text before the first headline when exporting.
3064 When nil, that text is exported as well."
3065 :group 'org-export-general
3066 :type 'boolean)
3068 (defcustom org-export-headline-levels 3
3069 "The last level which is still exported as a headline.
3070 Inferior levels will produce itemize lists when exported.
3071 Note that a numeric prefix argument to an exporter function overrides
3072 this setting.
3074 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3075 :group 'org-export-general
3076 :type 'number)
3078 (defcustom org-export-with-section-numbers t
3079 "Non-nil means, add section numbers to headlines when exporting.
3081 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3082 :group 'org-export-general
3083 :type 'boolean)
3085 (defcustom org-export-with-toc t
3086 "Non-nil means, create a table of contents in exported files.
3087 The TOC contains headlines with levels up to`org-export-headline-levels'.
3088 When an integer, include levels up to N in the toc, this may then be
3089 different from `org-export-headline-levels', but it will not be allowed
3090 to be larger than the number of headline levels.
3091 When nil, no table of contents is made.
3093 Headlines which contain any TODO items will be marked with \"(*)\" in
3094 ASCII export, and with red color in HTML output, if the option
3095 `org-export-mark-todo-in-toc' is set.
3097 In HTML output, the TOC will be clickable.
3099 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3100 or \"toc:3\"."
3101 :group 'org-export-general
3102 :type '(choice
3103 (const :tag "No Table of Contents" nil)
3104 (const :tag "Full Table of Contents" t)
3105 (integer :tag "TOC to level")))
3107 (defcustom org-export-mark-todo-in-toc nil
3108 "Non-nil means, mark TOC lines that contain any open TODO items."
3109 :group 'org-export-general
3110 :type 'boolean)
3112 (defcustom org-export-preserve-breaks nil
3113 "Non-nil means, preserve all line breaks when exporting.
3114 Normally, in HTML output paragraphs will be reformatted. In ASCII
3115 export, line breaks will always be preserved, regardless of this variable.
3117 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3118 :group 'org-export-general
3119 :type 'boolean)
3121 (defcustom org-export-with-archived-trees 'headline
3122 "Whether subtrees with the ARCHIVE tag should be exported.
3123 This can have three different values
3124 nil Do not export, pretend this tree is not present
3125 t Do export the entire tree
3126 headline Only export the headline, but skip the tree below it."
3127 :group 'org-export-general
3128 :group 'org-archive
3129 :type '(choice
3130 (const :tag "not at all" nil)
3131 (const :tag "headline only" 'headline)
3132 (const :tag "entirely" t)))
3134 (defcustom org-export-author-info t
3135 "Non-nil means, insert author name and email into the exported file.
3137 This option can also be set with the +OPTIONS line,
3138 e.g. \"author-info:nil\"."
3139 :group 'org-export-general
3140 :type 'boolean)
3142 (defcustom org-export-time-stamp-file t
3143 "Non-nil means, insert a time stamp into the exported file.
3144 The time stamp shows when the file was created.
3146 This option can also be set with the +OPTIONS line,
3147 e.g. \"timestamp:nil\"."
3148 :group 'org-export-general
3149 :type 'boolean)
3151 (defcustom org-export-with-timestamps t
3152 "If nil, do not export time stamps and associated keywords."
3153 :group 'org-export-general
3154 :type 'boolean)
3156 (defcustom org-export-remove-timestamps-from-toc t
3157 "If nil, remove timestamps from the table of contents entries."
3158 :group 'org-export-general
3159 :type 'boolean)
3161 (defcustom org-export-with-tags 'not-in-toc
3162 "If nil, do not export tags, just remove them from headlines.
3163 If this is the symbol `not-in-toc', tags will be removed from table of
3164 contents entries, but still be shown in the headlines of the document.
3166 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3167 :group 'org-export-general
3168 :type '(choice
3169 (const :tag "Off" nil)
3170 (const :tag "Not in TOC" not-in-toc)
3171 (const :tag "On" t)))
3173 (defcustom org-export-with-drawers nil
3174 "Non-nil means, export with drawers like the property drawer.
3175 When t, all drawers are exported. This may also be a list of
3176 drawer names to export."
3177 :group 'org-export-general
3178 :type '(choice
3179 (const :tag "All drawers" t)
3180 (const :tag "None" nil)
3181 (repeat :tag "Selected drawers"
3182 (string :tag "Drawer name"))))
3184 (defgroup org-export-translation nil
3185 "Options for translating special ascii sequences for the export backends."
3186 :tag "Org Export Translation"
3187 :group 'org-export)
3189 (defcustom org-export-with-emphasize t
3190 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3191 If the export target supports emphasizing text, the word will be
3192 typeset in bold, italic, or underlined, respectively. Works only for
3193 single words, but you can say: I *really* *mean* *this*.
3194 Not all export backends support this.
3196 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3197 :group 'org-export-translation
3198 :type 'boolean)
3200 (defcustom org-export-with-footnotes t
3201 "If nil, export [1] as a footnote marker.
3202 Lines starting with [1] will be formatted as footnotes.
3204 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3205 :group 'org-export-translation
3206 :type 'boolean)
3208 (defcustom org-export-with-sub-superscripts t
3209 "Non-nil means, interpret \"_\" and \"^\" for export.
3210 When this option is turned on, you can use TeX-like syntax for sub- and
3211 superscripts. Several characters after \"_\" or \"^\" will be
3212 considered as a single item - so grouping with {} is normally not
3213 needed. For example, the following things will be parsed as single
3214 sub- or superscripts.
3216 10^24 or 10^tau several digits will be considered 1 item.
3217 10^-12 or 10^-tau a leading sign with digits or a word
3218 x^2-y^3 will be read as x^2 - y^3, because items are
3219 terminated by almost any nonword/nondigit char.
3220 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3222 Still, ambiguity is possible - so when in doubt use {} to enclose the
3223 sub/superscript. If you set this variable to the symbol `{}',
3224 the braces are *required* in order to trigger interpretations as
3225 sub/superscript. This can be helpful in documents that need \"_\"
3226 frequently in plain text.
3228 Not all export backends support this, but HTML does.
3230 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3231 :group 'org-export-translation
3232 :type '(choice
3233 (const :tag "Always interpret" t)
3234 (const :tag "Only with braces" {})
3235 (const :tag "Never interpret" nil)))
3237 (defcustom org-export-with-special-strings t
3238 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3239 When this option is turned on, these strings will be exported as:
3241 \\- : &shy;
3242 -- : &ndash;
3243 --- : &mdash;
3245 Not all export backends support this, but HTML does.
3247 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3248 :group 'org-export-translation
3249 :type 'boolean)
3251 (defcustom org-export-with-TeX-macros t
3252 "Non-nil means, interpret simple TeX-like macros when exporting.
3253 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3254 No only real TeX macros will work here, but the standard HTML entities
3255 for math can be used as macro names as well. For a list of supported
3256 names in HTML export, see the constant `org-html-entities'.
3257 Not all export backends support this.
3259 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3260 :group 'org-export-translation
3261 :group 'org-export-latex
3262 :type 'boolean)
3264 (defcustom org-export-with-LaTeX-fragments nil
3265 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3266 When set, the exporter will find LaTeX environments if the \\begin line is
3267 the first non-white thing on a line. It will also find the math delimiters
3268 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3269 display math.
3271 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3272 :group 'org-export-translation
3273 :group 'org-export-latex
3274 :type 'boolean)
3276 (defcustom org-export-with-fixed-width t
3277 "Non-nil means, lines starting with \":\" will be in fixed width font.
3278 This can be used to have pre-formatted text, fragments of code etc. For
3279 example:
3280 : ;; Some Lisp examples
3281 : (while (defc cnt)
3282 : (ding))
3283 will be looking just like this in also HTML. See also the QUOTE keyword.
3284 Not all export backends support this.
3286 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3287 :group 'org-export-translation
3288 :type 'boolean)
3290 (defcustom org-match-sexp-depth 3
3291 "Number of stacked braces for sub/superscript matching.
3292 This has to be set before loading org.el to be effective."
3293 :group 'org-export-translation
3294 :type 'integer)
3296 (defgroup org-export-tables nil
3297 "Options for exporting tables in Org-mode."
3298 :tag "Org Export Tables"
3299 :group 'org-export)
3301 (defcustom org-export-with-tables t
3302 "If non-nil, lines starting with \"|\" define a table.
3303 For example:
3305 | Name | Address | Birthday |
3306 |-------------+----------+-----------|
3307 | Arthur Dent | England | 29.2.2100 |
3309 Not all export backends support this.
3311 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3312 :group 'org-export-tables
3313 :type 'boolean)
3315 (defcustom org-export-highlight-first-table-line t
3316 "Non-nil means, highlight the first table line.
3317 In HTML export, this means use <th> instead of <td>.
3318 In tables created with table.el, this applies to the first table line.
3319 In Org-mode tables, all lines before the first horizontal separator
3320 line will be formatted with <th> tags."
3321 :group 'org-export-tables
3322 :type 'boolean)
3324 (defcustom org-export-table-remove-special-lines t
3325 "Remove special lines and marking characters in calculating tables.
3326 This removes the special marking character column from tables that are set
3327 up for spreadsheet calculations. It also removes the entire lines
3328 marked with `!', `_', or `^'. The lines with `$' are kept, because
3329 the values of constants may be useful to have."
3330 :group 'org-export-tables
3331 :type 'boolean)
3333 (defcustom org-export-prefer-native-exporter-for-tables nil
3334 "Non-nil means, always export tables created with table.el natively.
3335 Natively means, use the HTML code generator in table.el.
3336 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3337 the table does not use row- or column-spanning). This has the
3338 advantage, that the automatic HTML conversions for math symbols and
3339 sub/superscripts can be applied. Org-mode's HTML generator is also
3340 much faster."
3341 :group 'org-export-tables
3342 :type 'boolean)
3344 (defgroup org-export-ascii nil
3345 "Options specific for ASCII export of Org-mode files."
3346 :tag "Org Export ASCII"
3347 :group 'org-export)
3349 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3350 "Characters for underlining headings in ASCII export.
3351 In the given sequence, these characters will be used for level 1, 2, ..."
3352 :group 'org-export-ascii
3353 :type '(repeat character))
3355 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3356 "Bullet characters for headlines converted to lists in ASCII export.
3357 The first character is used for the first lest level generated in this
3358 way, and so on. If there are more levels than characters given here,
3359 the list will be repeated.
3360 Note that plain lists will keep the same bullets as the have in the
3361 Org-mode file."
3362 :group 'org-export-ascii
3363 :type '(repeat character))
3365 (defgroup org-export-xml nil
3366 "Options specific for XML export of Org-mode files."
3367 :tag "Org Export XML"
3368 :group 'org-export)
3370 (defgroup org-export-html nil
3371 "Options specific for HTML export of Org-mode files."
3372 :tag "Org Export HTML"
3373 :group 'org-export)
3375 (defcustom org-export-html-coding-system nil
3377 :group 'org-export-html
3378 :type 'coding-system)
3380 (defcustom org-export-html-extension "html"
3381 "The extension for exported HTML files."
3382 :group 'org-export-html
3383 :type 'string)
3385 (defcustom org-export-html-style
3386 "<style type=\"text/css\">
3387 html {
3388 font-family: Times, serif;
3389 font-size: 12pt;
3391 .title { text-align: center; }
3392 .todo { color: red; }
3393 .done { color: green; }
3394 .timestamp { color: grey }
3395 .timestamp-kwd { color: CadetBlue }
3396 .tag { background-color:lightblue; font-weight:normal }
3397 .target { background-color: lavender; }
3398 pre {
3399 border: 1pt solid #AEBDCC;
3400 background-color: #F3F5F7;
3401 padding: 5pt;
3402 font-family: courier, monospace;
3404 table { border-collapse: collapse; }
3405 td, th {
3406 vertical-align: top;
3407 <!--border: 1pt solid #ADB9CC;-->
3409 </style>"
3410 "The default style specification for exported HTML files.
3411 Since there are different ways of setting style information, this variable
3412 needs to contain the full HTML structure to provide a style, including the
3413 surrounding HTML tags. The style specifications should include definitions
3414 for new classes todo, done, title, and deadline. For example, legal values
3415 would be:
3417 <style type=\"text/css\">
3418 p { font-weight: normal; color: gray; }
3419 h1 { color: black; }
3420 .title { text-align: center; }
3421 .todo, .deadline { color: red; }
3422 .done { color: green; }
3423 </style>
3425 or, if you want to keep the style in a file,
3427 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3429 As the value of this option simply gets inserted into the HTML <head> header,
3430 you can \"misuse\" it to add arbitrary text to the header."
3431 :group 'org-export-html
3432 :type 'string)
3435 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3436 "Format for typesetting the document title in HTML export."
3437 :group 'org-export-html
3438 :type 'string)
3440 (defcustom org-export-html-toplevel-hlevel 2
3441 "The <H> level for level 1 headings in HTML export."
3442 :group 'org-export-html
3443 :type 'string)
3445 (defcustom org-export-html-link-org-files-as-html t
3446 "Non-nil means, make file links to `file.org' point to `file.html'.
3447 When org-mode is exporting an org-mode file to HTML, links to
3448 non-html files are directly put into a href tag in HTML.
3449 However, links to other Org-mode files (recognized by the
3450 extension `.org.) should become links to the corresponding html
3451 file, assuming that the linked org-mode file will also be
3452 converted to HTML.
3453 When nil, the links still point to the plain `.org' file."
3454 :group 'org-export-html
3455 :type 'boolean)
3457 (defcustom org-export-html-inline-images 'maybe
3458 "Non-nil means, inline images into exported HTML pages.
3459 This is done using an <img> tag. When nil, an anchor with href is used to
3460 link to the image. If this option is `maybe', then images in links with
3461 an empty description will be inlined, while images with a description will
3462 be linked only."
3463 :group 'org-export-html
3464 :type '(choice (const :tag "Never" nil)
3465 (const :tag "Always" t)
3466 (const :tag "When there is no description" maybe)))
3468 ;; FIXME: rename
3469 (defcustom org-export-html-expand t
3470 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3471 When nil, these tags will be exported as plain text and therefore
3472 not be interpreted by a browser.
3474 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3475 :group 'org-export-html
3476 :type 'boolean)
3478 (defcustom org-export-html-table-tag
3479 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3480 "The HTML tag that is used to start a table.
3481 This must be a <table> tag, but you may change the options like
3482 borders and spacing."
3483 :group 'org-export-html
3484 :type 'string)
3486 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3487 "The opening tag for table header 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-table-data-tags '("<td>" . "</td>")
3493 "The opening tag for table data fields.
3494 This is customizable so that alignment options can be specified."
3495 :group 'org-export-tables
3496 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3498 (defcustom org-export-html-with-timestamp nil
3499 "If non-nil, write `org-export-html-html-helper-timestamp'
3500 into the exported HTML text. Otherwise, the buffer will just be saved
3501 to a file."
3502 :group 'org-export-html
3503 :type 'boolean)
3505 (defcustom org-export-html-html-helper-timestamp
3506 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3507 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3508 :group 'org-export-html
3509 :type 'string)
3511 (defgroup org-export-icalendar nil
3512 "Options specific for iCalendar export of Org-mode files."
3513 :tag "Org Export iCalendar"
3514 :group 'org-export)
3516 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3517 "The file name for the iCalendar file covering all agenda files.
3518 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3519 The file name should be absolute, the file will be overwritten without warning."
3520 :group 'org-export-icalendar
3521 :type 'file)
3523 (defcustom org-icalendar-include-todo nil
3524 "Non-nil means, export to iCalendar files should also cover TODO items."
3525 :group 'org-export-icalendar
3526 :type '(choice
3527 (const :tag "None" nil)
3528 (const :tag "Unfinished" t)
3529 (const :tag "All" all)))
3531 (defcustom org-icalendar-include-sexps t
3532 "Non-nil means, export to iCalendar files should also cover sexp entries.
3533 These are entries like in the diary, but directly in an Org-mode file."
3534 :group 'org-export-icalendar
3535 :type 'boolean)
3537 (defcustom org-icalendar-include-body 100
3538 "Amount of text below headline to be included in iCalendar export.
3539 This is a number of characters that should maximally be included.
3540 Properties, scheduling and clocking lines will always be removed.
3541 The text will be inserted into the DESCRIPTION field."
3542 :group 'org-export-icalendar
3543 :type '(choice
3544 (const :tag "Nothing" nil)
3545 (const :tag "Everything" t)
3546 (integer :tag "Max characters")))
3548 (defcustom org-icalendar-combined-name "OrgMode"
3549 "Calendar name for the combined iCalendar representing all agenda files."
3550 :group 'org-export-icalendar
3551 :type 'string)
3553 (defgroup org-font-lock nil
3554 "Font-lock settings for highlighting in Org-mode."
3555 :tag "Org Font Lock"
3556 :group 'org)
3558 (defcustom org-level-color-stars-only nil
3559 "Non-nil means fontify only the stars in each headline.
3560 When nil, the entire headline is fontified.
3561 Changing it requires restart of `font-lock-mode' to become effective
3562 also in regions already fontified."
3563 :group 'org-font-lock
3564 :type 'boolean)
3566 (defcustom org-hide-leading-stars nil
3567 "Non-nil means, hide the first N-1 stars in a headline.
3568 This works by using the face `org-hide' for these stars. This
3569 face is white for a light background, and black for a dark
3570 background. You may have to customize the face `org-hide' to
3571 make this work.
3572 Changing it requires restart of `font-lock-mode' to become effective
3573 also in regions already fontified.
3574 You may also set this on a per-file basis by adding one of the following
3575 lines to the buffer:
3577 #+STARTUP: hidestars
3578 #+STARTUP: showstars"
3579 :group 'org-font-lock
3580 :type 'boolean)
3582 (defcustom org-fontify-done-headline nil
3583 "Non-nil means, change the face of a headline if it is marked DONE.
3584 Normally, only the TODO/DONE keyword indicates the state of a headline.
3585 When this is non-nil, the headline after the keyword is set to the
3586 `org-headline-done' as an additional indication."
3587 :group 'org-font-lock
3588 :type 'boolean)
3590 (defcustom org-fontify-emphasized-text t
3591 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3592 Changing this variable requires a restart of Emacs to take effect."
3593 :group 'org-font-lock
3594 :type 'boolean)
3596 (defcustom org-highlight-latex-fragments-and-specials nil
3597 "Non-nil means, fontify what is treated specially by the exporters."
3598 :group 'org-font-lock
3599 :type 'boolean)
3601 (defcustom org-hide-emphasis-markers nil
3602 "Non-nil mean font-lock should hide the emphasis marker characters."
3603 :group 'org-font-lock
3604 :type 'boolean)
3606 (defvar org-emph-re nil
3607 "Regular expression for matching emphasis.")
3608 (defvar org-verbatim-re nil
3609 "Regular expression for matching verbatim text.")
3610 (defvar org-emphasis-regexp-components) ; defined just below
3611 (defvar org-emphasis-alist) ; defined just below
3612 (defun org-set-emph-re (var val)
3613 "Set variable and compute the emphasis regular expression."
3614 (set var val)
3615 (when (and (boundp 'org-emphasis-alist)
3616 (boundp 'org-emphasis-regexp-components)
3617 org-emphasis-alist org-emphasis-regexp-components)
3618 (let* ((e org-emphasis-regexp-components)
3619 (pre (car e))
3620 (post (nth 1 e))
3621 (border (nth 2 e))
3622 (body (nth 3 e))
3623 (nl (nth 4 e))
3624 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3625 (body1 (concat body "*?"))
3626 (markers (mapconcat 'car org-emphasis-alist ""))
3627 (vmarkers (mapconcat
3628 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3629 org-emphasis-alist "")))
3630 ;; make sure special characters appear at the right position in the class
3631 (if (string-match "\\^" markers)
3632 (setq markers (concat (replace-match "" t t markers) "^")))
3633 (if (string-match "-" markers)
3634 (setq markers (concat (replace-match "" t t markers) "-")))
3635 (if (string-match "\\^" vmarkers)
3636 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3637 (if (string-match "-" vmarkers)
3638 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3639 (if (> nl 0)
3640 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3641 (int-to-string nl) "\\}")))
3642 ;; Make the regexp
3643 (setq org-emph-re
3644 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3645 "\\("
3646 "\\([" markers "]\\)"
3647 "\\("
3648 "[^" border "]\\|"
3649 "[^" border (if (and nil stacked) markers) "]"
3650 body1
3651 "[^" border (if (and nil stacked) markers) "]"
3652 "\\)"
3653 "\\3\\)"
3654 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3655 (setq org-verbatim-re
3656 (concat "\\([" pre "]\\|^\\)"
3657 "\\("
3658 "\\([" vmarkers "]\\)"
3659 "\\("
3660 "[^" border "]\\|"
3661 "[^" border "]"
3662 body1
3663 "[^" border "]"
3664 "\\)"
3665 "\\3\\)"
3666 "\\([" post "]\\|$\\)")))))
3668 (defcustom org-emphasis-regexp-components
3669 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3670 "Components used to build the regular expression for emphasis.
3671 This is a list with 6 entries. Terminology: In an emphasis string
3672 like \" *strong word* \", we call the initial space PREMATCH, the final
3673 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3674 and \"trong wor\" is the body. The different components in this variable
3675 specify what is allowed/forbidden in each part:
3677 pre Chars allowed as prematch. Beginning of line will be allowed too.
3678 post Chars allowed as postmatch. End of line will be allowed too.
3679 border The chars *forbidden* as border characters.
3680 body-regexp A regexp like \".\" to match a body character. Don't use
3681 non-shy groups here, and don't allow newline here.
3682 newline The maximum number of newlines allowed in an emphasis exp.
3684 Use customize to modify this, or restart Emacs after changing it."
3685 :group 'org-font-lock
3686 :set 'org-set-emph-re
3687 :type '(list
3688 (sexp :tag "Allowed chars in pre ")
3689 (sexp :tag "Allowed chars in post ")
3690 (sexp :tag "Forbidden chars in border ")
3691 (sexp :tag "Regexp for body ")
3692 (integer :tag "number of newlines allowed")
3693 (option (boolean :tag "Stacking (DISABLED) "))))
3695 (defcustom org-emphasis-alist
3696 '(("*" bold "<b>" "</b>")
3697 ("/" italic "<i>" "</i>")
3698 ("_" underline "<u>" "</u>")
3699 ("=" org-code "<code>" "</code>" verbatim)
3700 ("~" org-verbatim "" "" verbatim)
3701 ("+" (:strike-through t) "<del>" "</del>")
3703 "Special syntax for emphasized text.
3704 Text starting and ending with a special character will be emphasized, for
3705 example *bold*, _underlined_ and /italic/. This variable sets the marker
3706 characters, the face to be used by font-lock for highlighting in Org-mode
3707 Emacs buffers, and the HTML tags to be used for this.
3708 Use customize to modify this, or restart Emacs after changing it."
3709 :group 'org-font-lock
3710 :set 'org-set-emph-re
3711 :type '(repeat
3712 (list
3713 (string :tag "Marker character")
3714 (choice
3715 (face :tag "Font-lock-face")
3716 (plist :tag "Face property list"))
3717 (string :tag "HTML start tag")
3718 (string :tag "HTML end tag")
3719 (option (const verbatim)))))
3721 ;;; The faces
3723 (defgroup org-faces nil
3724 "Faces in Org-mode."
3725 :tag "Org Faces"
3726 :group 'org-font-lock)
3728 (defun org-compatible-face (inherits specs)
3729 "Make a compatible face specification.
3730 If INHERITS is an existing face and if the Emacs version supports it,
3731 just inherit the face. If not, use SPECS to define the face.
3732 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3733 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3734 to the top of the list. The `min-colors' attribute will be removed from
3735 any other entries, and any resulting duplicates will be removed entirely."
3736 (cond
3737 ((and inherits (facep inherits)
3738 (not (featurep 'xemacs)) (> emacs-major-version 22))
3739 ;; In Emacs 23, we use inheritance where possible.
3740 ;; We only do this in Emacs 23, because only there the outline
3741 ;; faces have been changed to the original org-mode-level-faces.
3742 (list (list t :inherit inherits)))
3743 ((or (featurep 'xemacs) (< emacs-major-version 22))
3744 ;; These do not understand the `min-colors' attribute.
3745 (let (r e a)
3746 (while (setq e (pop specs))
3747 (cond
3748 ((memq (car e) '(t default)) (push e r))
3749 ((setq a (member '(min-colors 8) (car e)))
3750 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3751 (cdr e)))))
3752 ((setq a (assq 'min-colors (car e)))
3753 (setq e (cons (delq a (car e)) (cdr e)))
3754 (or (assoc (car e) r) (push e r)))
3755 (t (or (assoc (car e) r) (push e r)))))
3756 (nreverse r)))
3757 (t specs)))
3758 (put 'org-compatible-face 'lisp-indent-function 1)
3760 (defface org-hide
3761 '((((background light)) (:foreground "white"))
3762 (((background dark)) (:foreground "black")))
3763 "Face used to hide leading stars in headlines.
3764 The forground color of this face should be equal to the background
3765 color of the frame."
3766 :group 'org-faces)
3768 (defface org-level-1 ;; font-lock-function-name-face
3769 (org-compatible-face 'outline-1
3770 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3771 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3772 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3773 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3774 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3775 (t (:bold t))))
3776 "Face used for level 1 headlines."
3777 :group 'org-faces)
3779 (defface org-level-2 ;; font-lock-variable-name-face
3780 (org-compatible-face 'outline-2
3781 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3782 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3783 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3784 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3785 (t (:bold t))))
3786 "Face used for level 2 headlines."
3787 :group 'org-faces)
3789 (defface org-level-3 ;; font-lock-keyword-face
3790 (org-compatible-face 'outline-3
3791 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3792 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3793 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3794 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3795 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3796 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3797 (t (:bold t))))
3798 "Face used for level 3 headlines."
3799 :group 'org-faces)
3801 (defface org-level-4 ;; font-lock-comment-face
3802 (org-compatible-face 'outline-4
3803 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3804 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3805 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3806 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3807 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3808 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3809 (t (:bold t))))
3810 "Face used for level 4 headlines."
3811 :group 'org-faces)
3813 (defface org-level-5 ;; font-lock-type-face
3814 (org-compatible-face 'outline-5
3815 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3816 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3817 (((class color) (min-colors 8)) (:foreground "green"))))
3818 "Face used for level 5 headlines."
3819 :group 'org-faces)
3821 (defface org-level-6 ;; font-lock-constant-face
3822 (org-compatible-face 'outline-6
3823 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3824 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3825 (((class color) (min-colors 8)) (:foreground "magenta"))))
3826 "Face used for level 6 headlines."
3827 :group 'org-faces)
3829 (defface org-level-7 ;; font-lock-builtin-face
3830 (org-compatible-face 'outline-7
3831 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3832 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3833 (((class color) (min-colors 8)) (:foreground "blue"))))
3834 "Face used for level 7 headlines."
3835 :group 'org-faces)
3837 (defface org-level-8 ;; font-lock-string-face
3838 (org-compatible-face 'outline-8
3839 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3840 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3841 (((class color) (min-colors 8)) (:foreground "green"))))
3842 "Face used for level 8 headlines."
3843 :group 'org-faces)
3845 (defface org-special-keyword ;; font-lock-string-face
3846 (org-compatible-face nil
3847 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3848 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3849 (t (:italic t))))
3850 "Face used for special keywords."
3851 :group 'org-faces)
3853 (defface org-drawer ;; font-lock-function-name-face
3854 (org-compatible-face nil
3855 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3856 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3857 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3858 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3859 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3860 (t (:bold t))))
3861 "Face used for drawers."
3862 :group 'org-faces)
3864 (defface org-property-value nil
3865 "Face used for the value of a property."
3866 :group 'org-faces)
3868 (defface org-column
3869 (org-compatible-face nil
3870 '((((class color) (min-colors 16) (background light))
3871 (:background "grey90"))
3872 (((class color) (min-colors 16) (background dark))
3873 (:background "grey30"))
3874 (((class color) (min-colors 8))
3875 (:background "cyan" :foreground "black"))
3876 (t (:inverse-video t))))
3877 "Face for column display of entry properties."
3878 :group 'org-faces)
3880 (when (fboundp 'set-face-attribute)
3881 ;; Make sure that a fixed-width face is used when we have a column table.
3882 (set-face-attribute 'org-column nil
3883 :height (face-attribute 'default :height)
3884 :family (face-attribute 'default :family)))
3886 (defface org-warning
3887 (org-compatible-face 'font-lock-warning-face
3888 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3889 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3890 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3891 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3892 (t (:bold t))))
3893 "Face for deadlines and TODO keywords."
3894 :group 'org-faces)
3896 (defface org-archived ; similar to shadow
3897 (org-compatible-face 'shadow
3898 '((((class color grayscale) (min-colors 88) (background light))
3899 (:foreground "grey50"))
3900 (((class color grayscale) (min-colors 88) (background dark))
3901 (:foreground "grey70"))
3902 (((class color) (min-colors 8) (background light))
3903 (:foreground "green"))
3904 (((class color) (min-colors 8) (background dark))
3905 (:foreground "yellow"))))
3906 "Face for headline with the ARCHIVE tag."
3907 :group 'org-faces)
3909 (defface org-link
3910 '((((class color) (background light)) (:foreground "Purple" :underline t))
3911 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3912 (t (:underline t)))
3913 "Face for links."
3914 :group 'org-faces)
3916 (defface org-ellipsis
3917 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3918 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3919 (t (:strike-through t)))
3920 "Face for the ellipsis in folded text."
3921 :group 'org-faces)
3923 (defface org-target
3924 '((((class color) (background light)) (:underline t))
3925 (((class color) (background dark)) (:underline t))
3926 (t (:underline t)))
3927 "Face for links."
3928 :group 'org-faces)
3930 (defface org-date
3931 '((((class color) (background light)) (:foreground "Purple" :underline t))
3932 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3933 (t (:underline t)))
3934 "Face for links."
3935 :group 'org-faces)
3937 (defface org-sexp-date
3938 '((((class color) (background light)) (:foreground "Purple"))
3939 (((class color) (background dark)) (:foreground "Cyan"))
3940 (t (:underline t)))
3941 "Face for links."
3942 :group 'org-faces)
3944 (defface org-tag
3945 '((t (:bold t)))
3946 "Face for tags."
3947 :group 'org-faces)
3949 (defface org-todo ; font-lock-warning-face
3950 (org-compatible-face nil
3951 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3952 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3953 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3954 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3955 (t (:inverse-video t :bold t))))
3956 "Face for TODO keywords."
3957 :group 'org-faces)
3959 (defface org-done ;; font-lock-type-face
3960 (org-compatible-face nil
3961 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3962 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3963 (((class color) (min-colors 8)) (:foreground "green"))
3964 (t (:bold t))))
3965 "Face used for todo keywords that indicate DONE items."
3966 :group 'org-faces)
3968 (defface org-headline-done ;; font-lock-string-face
3969 (org-compatible-face nil
3970 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3971 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3972 (((class color) (min-colors 8) (background light)) (:bold nil))))
3973 "Face used to indicate that a headline is DONE.
3974 This face is only used if `org-fontify-done-headline' is set. If applies
3975 to the part of the headline after the DONE keyword."
3976 :group 'org-faces)
3978 (defcustom org-todo-keyword-faces nil
3979 "Faces for specific TODO keywords.
3980 This is a list of cons cells, with TODO keywords in the car
3981 and faces in the cdr. The face can be a symbol, or a property
3982 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3983 :group 'org-faces
3984 :group 'org-todo
3985 :type '(repeat
3986 (cons
3987 (string :tag "keyword")
3988 (sexp :tag "face"))))
3990 (defface org-table ;; font-lock-function-name-face
3991 (org-compatible-face nil
3992 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3993 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3994 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3995 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3996 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3997 (((class color) (min-colors 8) (background dark)))))
3998 "Face used for tables."
3999 :group 'org-faces)
4001 (defface org-formula
4002 (org-compatible-face nil
4003 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4004 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4005 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4006 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4007 (t (:bold t :italic t))))
4008 "Face for formulas."
4009 :group 'org-faces)
4011 (defface org-code
4012 (org-compatible-face nil
4013 '((((class color grayscale) (min-colors 88) (background light))
4014 (:foreground "grey50"))
4015 (((class color grayscale) (min-colors 88) (background dark))
4016 (:foreground "grey70"))
4017 (((class color) (min-colors 8) (background light))
4018 (:foreground "green"))
4019 (((class color) (min-colors 8) (background dark))
4020 (:foreground "yellow"))))
4021 "Face for fixed-with text like code snippets."
4022 :group 'org-faces
4023 :version "22.1")
4025 (defface org-verbatim
4026 (org-compatible-face nil
4027 '((((class color grayscale) (min-colors 88) (background light))
4028 (:foreground "grey50" :underline t))
4029 (((class color grayscale) (min-colors 88) (background dark))
4030 (:foreground "grey70" :underline t))
4031 (((class color) (min-colors 8) (background light))
4032 (:foreground "green" :underline t))
4033 (((class color) (min-colors 8) (background dark))
4034 (:foreground "yellow" :underline t))))
4035 "Face for fixed-with text like code snippets."
4036 :group 'org-faces
4037 :version "22.1")
4039 (defface org-agenda-structure ;; font-lock-function-name-face
4040 (org-compatible-face nil
4041 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4042 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4043 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4044 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4045 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4046 (t (:bold t))))
4047 "Face used in agenda for captions and dates."
4048 :group 'org-faces)
4050 (defface org-scheduled-today
4051 (org-compatible-face nil
4052 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4053 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4054 (((class color) (min-colors 8)) (:foreground "green"))
4055 (t (:bold t :italic t))))
4056 "Face for items scheduled for a certain day."
4057 :group 'org-faces)
4059 (defface org-scheduled-previously
4060 (org-compatible-face nil
4061 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4062 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4063 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4064 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4065 (t (:bold t))))
4066 "Face for items scheduled previously, and not yet done."
4067 :group 'org-faces)
4069 (defface org-upcoming-deadline
4070 (org-compatible-face nil
4071 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4072 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4073 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4074 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4075 (t (:bold t))))
4076 "Face for items scheduled previously, and not yet done."
4077 :group 'org-faces)
4079 (defcustom org-agenda-deadline-faces
4080 '((1.0 . org-warning)
4081 (0.5 . org-upcoming-deadline)
4082 (0.0 . default))
4083 "Faces for showing deadlines in the agenda.
4084 This is a list of cons cells. The cdr of each cell is a face to be used,
4085 and it can also just be like '(:foreground \"yellow\").
4086 Each car is a fraction of the head-warning time that must have passed for
4087 this the face in the cdr to be used for display. The numbers must be
4088 given in descending order. The head-warning time is normally taken
4089 from `org-deadline-warning-days', but can also be specified in the deadline
4090 timestamp itself, like this:
4092 DEADLINE: <2007-08-13 Mon -8d>
4094 You may use d for days, w for weeks, m for months and y for years. Months
4095 and years will only be treated in an approximate fashion (30.4 days for a
4096 month and 365.24 days for a year)."
4097 :group 'org-faces
4098 :group 'org-agenda-daily/weekly
4099 :type '(repeat
4100 (cons
4101 (number :tag "Fraction of head-warning time passed")
4102 (sexp :tag "Face"))))
4104 ;; FIXME: this is not a good face yet.
4105 (defface org-agenda-restriction-lock
4106 (org-compatible-face nil
4107 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4108 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4109 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4110 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4111 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4112 (t (:inverse-video t))))
4113 "Face for showing the agenda restriction lock."
4114 :group 'org-faces)
4116 (defface org-time-grid ;; font-lock-variable-name-face
4117 (org-compatible-face nil
4118 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4119 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4120 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4121 "Face used for time grids."
4122 :group 'org-faces)
4124 (defconst org-level-faces
4125 '(org-level-1 org-level-2 org-level-3 org-level-4
4126 org-level-5 org-level-6 org-level-7 org-level-8
4129 (defcustom org-n-level-faces (length org-level-faces)
4130 "The number different faces to be used for headlines.
4131 Org-mode defines 8 different headline faces, so this can be at most 8.
4132 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4133 :type 'number
4134 :group 'org-faces)
4136 ;;; Functions and variables from ther packages
4137 ;; Declared here to avoid compiler warnings
4139 (eval-and-compile
4140 (unless (fboundp 'declare-function)
4141 (defmacro declare-function (fn file &optional arglist fileonly))))
4143 ;; XEmacs only
4144 (defvar outline-mode-menu-heading)
4145 (defvar outline-mode-menu-show)
4146 (defvar outline-mode-menu-hide)
4147 (defvar zmacs-regions) ; XEmacs regions
4149 ;; Emacs only
4150 (defvar mark-active)
4152 ;; Various packages
4153 ;; FIXME: get the argument lists for the UNKNOWN stuff
4154 (declare-function add-to-diary-list "diary-lib"
4155 (date string specifier &optional marker globcolor literal))
4156 (declare-function table--at-cell-p "table" (position &optional object at-column))
4157 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4158 (declare-function Info-goto-node "info" (nodename &optional fork))
4159 (declare-function bbdb "ext:bbdb-com" (string elidep))
4160 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4161 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4162 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4163 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4164 (declare-function bbdb-record-name "ext:bbdb" (record))
4165 (declare-function bibtex-beginning-of-entry "bibtex" ())
4166 (declare-function bibtex-generate-autokey "bibtex" ())
4167 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4168 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4169 (defvar calc-embedded-close-formula)
4170 (defvar calc-embedded-open-formula)
4171 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4172 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4173 (declare-function calendar-check-holidays "holidays" (date))
4174 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4175 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4176 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4177 (declare-function calendar-forward-day "cal-move" (arg))
4178 (declare-function calendar-french-date-string "cal-french" (&optional date))
4179 (declare-function calendar-goto-date "cal-move" (date))
4180 (declare-function calendar-goto-today "cal-move" ())
4181 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4182 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4183 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4184 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4185 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4186 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4187 (defvar calendar-mode-map)
4188 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4189 (declare-function cdlatex-tab "ext:cdlatex" ())
4190 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4191 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4192 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4193 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4194 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4195 (defvar font-lock-unfontify-region-function)
4196 (declare-function gnus-article-show-summary "gnus-art" ())
4197 (declare-function gnus-summary-last-subject "gnus-sum" ())
4198 (defvar gnus-other-frame-object)
4199 (defvar gnus-group-name)
4200 (defvar gnus-article-current)
4201 (defvar Info-current-file)
4202 (defvar Info-current-node)
4203 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4204 (declare-function mh-find-path "mh-utils" ())
4205 (declare-function mh-get-header-field "mh-utils" (field))
4206 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4207 (declare-function mh-header-display "mh-show" ())
4208 (declare-function mh-index-previous-folder "mh-search" ())
4209 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4210 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4211 (declare-function mh-search-choose "mh-search" (&optional searcher))
4212 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4213 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4214 (declare-function mh-show-header-display "mh-show" t t)
4215 (declare-function mh-show-msg "mh-show" (msg))
4216 (declare-function mh-show-show "mh-show" t t)
4217 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4218 (defvar mh-progs)
4219 (defvar mh-current-folder)
4220 (defvar mh-show-folder-buffer)
4221 (defvar mh-index-folder)
4222 (defvar mh-searcher)
4223 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4224 (declare-function parse-time-string "parse-time" (string))
4225 (declare-function remember "remember" (&optional initial))
4226 (declare-function remember-buffer-desc "remember" ())
4227 (declare-function remember-finalize "remember" ())
4228 (defvar remember-save-after-remembering)
4229 (defvar remember-data-file)
4230 (defvar remember-register)
4231 (defvar remember-buffer)
4232 (defvar remember-handler-functions)
4233 (defvar remember-annotation-functions)
4234 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4235 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4236 (declare-function rmail-what-message "rmail" ())
4237 (defvar texmathp-why)
4238 (declare-function vm-beginning-of-message "ext:vm-page" ())
4239 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4240 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4241 (declare-function vm-isearch-narrow "ext:vm-search" ())
4242 (declare-function vm-isearch-update "ext:vm-search" ())
4243 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4244 (declare-function vm-su-message-id "ext:vm-summary" (m))
4245 (declare-function vm-su-subject "ext:vm-summary" (m))
4246 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4247 (defvar vm-message-pointer)
4248 (defvar vm-folder-directory)
4249 (defvar w3m-current-url)
4250 (defvar w3m-current-title)
4251 ;; backward compatibility to old version of wl
4252 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4253 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4254 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4255 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4256 (declare-function wl-summary-line-from "ext:wl-summary" ())
4257 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4258 (declare-function wl-summary-message-number "ext:wl-summary" ())
4259 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4260 (defvar wl-summary-buffer-elmo-folder)
4261 (defvar wl-summary-buffer-folder-name)
4262 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4264 (defvar org-latex-regexps)
4265 (defvar constants-unit-system)
4267 ;;; Variables for pre-computed regular expressions, all buffer local
4269 (defvar org-drawer-regexp nil
4270 "Matches first line of a hidden block.")
4271 (make-variable-buffer-local 'org-drawer-regexp)
4272 (defvar org-todo-regexp nil
4273 "Matches any of the TODO state keywords.")
4274 (make-variable-buffer-local 'org-todo-regexp)
4275 (defvar org-not-done-regexp nil
4276 "Matches any of the TODO state keywords except the last one.")
4277 (make-variable-buffer-local 'org-not-done-regexp)
4278 (defvar org-todo-line-regexp nil
4279 "Matches a headline and puts TODO state into group 2 if present.")
4280 (make-variable-buffer-local 'org-todo-line-regexp)
4281 (defvar org-complex-heading-regexp nil
4282 "Matches a headline and puts everything into groups:
4283 group 1: the stars
4284 group 2: The todo keyword, maybe
4285 group 3: Priority cookie
4286 group 4: True headline
4287 group 5: Tags")
4288 (make-variable-buffer-local 'org-complex-heading-regexp)
4289 (defvar org-todo-line-tags-regexp nil
4290 "Matches a headline and puts TODO state into group 2 if present.
4291 Also put tags into group 4 if tags are present.")
4292 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4293 (defvar org-nl-done-regexp nil
4294 "Matches newline followed by a headline with the DONE keyword.")
4295 (make-variable-buffer-local 'org-nl-done-regexp)
4296 (defvar org-looking-at-done-regexp nil
4297 "Matches the DONE keyword a point.")
4298 (make-variable-buffer-local 'org-looking-at-done-regexp)
4299 (defvar org-ds-keyword-length 12
4300 "Maximum length of the Deadline and SCHEDULED keywords.")
4301 (make-variable-buffer-local 'org-ds-keyword-length)
4302 (defvar org-deadline-regexp nil
4303 "Matches the DEADLINE keyword.")
4304 (make-variable-buffer-local 'org-deadline-regexp)
4305 (defvar org-deadline-time-regexp nil
4306 "Matches the DEADLINE keyword together with a time stamp.")
4307 (make-variable-buffer-local 'org-deadline-time-regexp)
4308 (defvar org-deadline-line-regexp nil
4309 "Matches the DEADLINE keyword and the rest of the line.")
4310 (make-variable-buffer-local 'org-deadline-line-regexp)
4311 (defvar org-scheduled-regexp nil
4312 "Matches the SCHEDULED keyword.")
4313 (make-variable-buffer-local 'org-scheduled-regexp)
4314 (defvar org-scheduled-time-regexp nil
4315 "Matches the SCHEDULED keyword together with a time stamp.")
4316 (make-variable-buffer-local 'org-scheduled-time-regexp)
4317 (defvar org-closed-time-regexp nil
4318 "Matches the CLOSED keyword together with a time stamp.")
4319 (make-variable-buffer-local 'org-closed-time-regexp)
4321 (defvar org-keyword-time-regexp nil
4322 "Matches any of the 4 keywords, together with the time stamp.")
4323 (make-variable-buffer-local 'org-keyword-time-regexp)
4324 (defvar org-keyword-time-not-clock-regexp nil
4325 "Matches any of the 3 keywords, together with the time stamp.")
4326 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4327 (defvar org-maybe-keyword-time-regexp nil
4328 "Matches a timestamp, possibly preceeded by a keyword.")
4329 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4330 (defvar org-planning-or-clock-line-re nil
4331 "Matches a line with planning or clock info.")
4332 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4334 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4335 rear-nonsticky t mouse-map t fontified t)
4336 "Properties to remove when a string without properties is wanted.")
4338 (defsubst org-match-string-no-properties (num &optional string)
4339 (if (featurep 'xemacs)
4340 (let ((s (match-string num string)))
4341 (remove-text-properties 0 (length s) org-rm-props s)
4343 (match-string-no-properties num string)))
4345 (defsubst org-no-properties (s)
4346 (if (fboundp 'set-text-properties)
4347 (set-text-properties 0 (length s) nil s)
4348 (remove-text-properties 0 (length s) org-rm-props s))
4351 (defsubst org-get-alist-option (option key)
4352 (cond ((eq key t) t)
4353 ((eq option t) t)
4354 ((assoc key option) (cdr (assoc key option)))
4355 (t (cdr (assq 'default option)))))
4357 (defsubst org-inhibit-invisibility ()
4358 "Modified `buffer-invisibility-spec' for Emacs 21.
4359 Some ops with invisible text do not work correctly on Emacs 21. For these
4360 we turn off invisibility temporarily. Use this in a `let' form."
4361 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4363 (defsubst org-set-local (var value)
4364 "Make VAR local in current buffer and set it to VALUE."
4365 (set (make-variable-buffer-local var) value))
4367 (defsubst org-mode-p ()
4368 "Check if the current buffer is in Org-mode."
4369 (eq major-mode 'org-mode))
4371 (defsubst org-last (list)
4372 "Return the last element of LIST."
4373 (car (last list)))
4375 (defun org-let (list &rest body)
4376 (eval (cons 'let (cons list body))))
4377 (put 'org-let 'lisp-indent-function 1)
4379 (defun org-let2 (list1 list2 &rest body)
4380 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4381 (put 'org-let2 'lisp-indent-function 2)
4382 (defconst org-startup-options
4383 '(("fold" org-startup-folded t)
4384 ("overview" org-startup-folded t)
4385 ("nofold" org-startup-folded nil)
4386 ("showall" org-startup-folded nil)
4387 ("content" org-startup-folded content)
4388 ("hidestars" org-hide-leading-stars t)
4389 ("showstars" org-hide-leading-stars nil)
4390 ("odd" org-odd-levels-only t)
4391 ("oddeven" org-odd-levels-only nil)
4392 ("align" org-startup-align-all-tables t)
4393 ("noalign" org-startup-align-all-tables nil)
4394 ("customtime" org-display-custom-times t)
4395 ("logging" org-log-done t)
4396 ("logdone" org-log-done t)
4397 ("nologging" org-log-done nil)
4398 ("lognotedone" org-log-done done push)
4399 ("lognotestate" org-log-done state push)
4400 ("lognoteclock-out" org-log-done clock-out push)
4401 ("logrepeat" org-log-repeat t)
4402 ("nologrepeat" org-log-repeat nil)
4403 ("constcgs" constants-unit-system cgs)
4404 ("constSI" constants-unit-system SI))
4405 "Variable associated with STARTUP options for org-mode.
4406 Each element is a list of three items: The startup options as written
4407 in the #+STARTUP line, the corresponding variable, and the value to
4408 set this variable to if the option is found. An optional forth element PUSH
4409 means to push this value onto the list in the variable.")
4411 (defun org-set-regexps-and-options ()
4412 "Precompute regular expressions for current buffer."
4413 (when (org-mode-p)
4414 (org-set-local 'org-todo-kwd-alist nil)
4415 (org-set-local 'org-todo-key-alist nil)
4416 (org-set-local 'org-todo-key-trigger nil)
4417 (org-set-local 'org-todo-keywords-1 nil)
4418 (org-set-local 'org-done-keywords nil)
4419 (org-set-local 'org-todo-heads nil)
4420 (org-set-local 'org-todo-sets nil)
4421 (org-set-local 'org-todo-log-states nil)
4422 (let ((re (org-make-options-regexp
4423 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4424 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4425 "CONSTANTS" "PROPERTY" "DRAWERS")))
4426 (splitre "[ \t]+")
4427 kwds kws0 kwsa key value cat arch tags const links hw dws
4428 tail sep kws1 prio props drawers
4429 ex log)
4430 (save-excursion
4431 (save-restriction
4432 (widen)
4433 (goto-char (point-min))
4434 (while (re-search-forward re nil t)
4435 (setq key (match-string 1) value (org-match-string-no-properties 2))
4436 (cond
4437 ((equal key "CATEGORY")
4438 (if (string-match "[ \t]+$" value)
4439 (setq value (replace-match "" t t value)))
4440 (setq cat value))
4441 ((member key '("SEQ_TODO" "TODO"))
4442 (push (cons 'sequence (org-split-string value splitre)) kwds))
4443 ((equal key "TYP_TODO")
4444 (push (cons 'type (org-split-string value splitre)) kwds))
4445 ((equal key "TAGS")
4446 (setq tags (append tags (org-split-string value splitre))))
4447 ((equal key "COLUMNS")
4448 (org-set-local 'org-columns-default-format value))
4449 ((equal key "LINK")
4450 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4451 (push (cons (match-string 1 value)
4452 (org-trim (match-string 2 value)))
4453 links)))
4454 ((equal key "PRIORITIES")
4455 (setq prio (org-split-string value " +")))
4456 ((equal key "PROPERTY")
4457 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4458 (push (cons (match-string 1 value) (match-string 2 value))
4459 props)))
4460 ((equal key "DRAWERS")
4461 (setq drawers (org-split-string value splitre)))
4462 ((equal key "CONSTANTS")
4463 (setq const (append const (org-split-string value splitre))))
4464 ((equal key "STARTUP")
4465 (let ((opts (org-split-string value splitre))
4466 l var val)
4467 (while (setq l (pop opts))
4468 (when (setq l (assoc l org-startup-options))
4469 (setq var (nth 1 l) val (nth 2 l))
4470 (if (not (nth 3 l))
4471 (set (make-local-variable var) val)
4472 (if (not (listp (symbol-value var)))
4473 (set (make-local-variable var) nil))
4474 (set (make-local-variable var) (symbol-value var))
4475 (add-to-list var val))))))
4476 ((equal key "ARCHIVE")
4477 (string-match " *$" value)
4478 (setq arch (replace-match "" t t value))
4479 (remove-text-properties 0 (length arch)
4480 '(face t fontified t) arch)))
4482 (when cat
4483 (org-set-local 'org-category (intern cat))
4484 (push (cons "CATEGORY" cat) props))
4485 (when prio
4486 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4487 (setq prio (mapcar 'string-to-char prio))
4488 (org-set-local 'org-highest-priority (nth 0 prio))
4489 (org-set-local 'org-lowest-priority (nth 1 prio))
4490 (org-set-local 'org-default-priority (nth 2 prio)))
4491 (and props (org-set-local 'org-local-properties (nreverse props)))
4492 (and drawers (org-set-local 'org-drawers drawers))
4493 (and arch (org-set-local 'org-archive-location arch))
4494 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4495 ;; Process the TODO keywords
4496 (unless kwds
4497 ;; Use the global values as if they had been given locally.
4498 (setq kwds (default-value 'org-todo-keywords))
4499 (if (stringp (car kwds))
4500 (setq kwds (list (cons org-todo-interpretation
4501 (default-value 'org-todo-keywords)))))
4502 (setq kwds (reverse kwds)))
4503 (setq kwds (nreverse kwds))
4504 (let (inter kws kw)
4505 (while (setq kws (pop kwds))
4506 (setq inter (pop kws) sep (member "|" kws)
4507 kws0 (delete "|" (copy-sequence kws))
4508 kwsa nil
4509 kws1 (mapcar
4510 (lambda (x)
4511 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4512 (progn
4513 (setq kw (match-string 1 x)
4514 ex (and (match-end 2) (match-string 2 x))
4515 log (and ex (string-match "@" ex))
4516 key (and ex (substring ex 0 1)))
4517 (if (equal key "@") (setq key nil))
4518 (push (cons kw (and key (string-to-char key))) kwsa)
4519 (and log (push kw org-todo-log-states))
4521 (error "Invalid TODO keyword %s" x)))
4522 kws0)
4523 kwsa (if kwsa (append '((:startgroup))
4524 (nreverse kwsa)
4525 '((:endgroup))))
4526 hw (car kws1)
4527 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4528 tail (list inter hw (car dws) (org-last dws)))
4529 (add-to-list 'org-todo-heads hw 'append)
4530 (push kws1 org-todo-sets)
4531 (setq org-done-keywords (append org-done-keywords dws nil))
4532 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4533 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4534 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4535 (setq org-todo-sets (nreverse org-todo-sets)
4536 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4537 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4538 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4539 ;; Process the constants
4540 (when const
4541 (let (e cst)
4542 (while (setq e (pop const))
4543 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4544 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4545 (setq org-table-formula-constants-local cst)))
4547 ;; Process the tags.
4548 (when tags
4549 (let (e tgs)
4550 (while (setq e (pop tags))
4551 (cond
4552 ((equal e "{") (push '(:startgroup) tgs))
4553 ((equal e "}") (push '(:endgroup) tgs))
4554 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4555 (push (cons (match-string 1 e)
4556 (string-to-char (match-string 2 e)))
4557 tgs))
4558 (t (push (list e) tgs))))
4559 (org-set-local 'org-tag-alist nil)
4560 (while (setq e (pop tgs))
4561 (or (and (stringp (car e))
4562 (assoc (car e) org-tag-alist))
4563 (push e org-tag-alist))))))
4565 ;; Compute the regular expressions and other local variables
4566 (if (not org-done-keywords)
4567 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4568 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4569 (length org-scheduled-string)))
4570 org-drawer-regexp
4571 (concat "^[ \t]*:\\("
4572 (mapconcat 'regexp-quote org-drawers "\\|")
4573 "\\):[ \t]*$")
4574 org-not-done-keywords
4575 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4576 org-todo-regexp
4577 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4578 "\\|") "\\)\\>")
4579 org-not-done-regexp
4580 (concat "\\<\\("
4581 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4582 "\\)\\>")
4583 org-todo-line-regexp
4584 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4585 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4586 "\\)\\>\\)?[ \t]*\\(.*\\)")
4587 org-complex-heading-regexp
4588 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4589 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4590 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4591 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4592 org-nl-done-regexp
4593 (concat "\n\\*+[ \t]+"
4594 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4595 "\\)" "\\>")
4596 org-todo-line-tags-regexp
4597 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4598 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4599 (org-re
4600 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4601 org-looking-at-done-regexp
4602 (concat "^" "\\(?:"
4603 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4604 "\\>")
4605 org-deadline-regexp (concat "\\<" org-deadline-string)
4606 org-deadline-time-regexp
4607 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4608 org-deadline-line-regexp
4609 (concat "\\<\\(" org-deadline-string "\\).*")
4610 org-scheduled-regexp
4611 (concat "\\<" org-scheduled-string)
4612 org-scheduled-time-regexp
4613 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4614 org-closed-time-regexp
4615 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4616 org-keyword-time-regexp
4617 (concat "\\<\\(" org-scheduled-string
4618 "\\|" org-deadline-string
4619 "\\|" org-closed-string
4620 "\\|" org-clock-string "\\)"
4621 " *[[<]\\([^]>]+\\)[]>]")
4622 org-keyword-time-not-clock-regexp
4623 (concat "\\<\\(" org-scheduled-string
4624 "\\|" org-deadline-string
4625 "\\|" org-closed-string
4626 "\\)"
4627 " *[[<]\\([^]>]+\\)[]>]")
4628 org-maybe-keyword-time-regexp
4629 (concat "\\(\\<\\(" org-scheduled-string
4630 "\\|" org-deadline-string
4631 "\\|" org-closed-string
4632 "\\|" org-clock-string "\\)\\)?"
4633 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4634 org-planning-or-clock-line-re
4635 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4636 "\\|" org-deadline-string
4637 "\\|" org-closed-string "\\|" org-clock-string
4638 "\\)\\>\\)")
4640 (org-compute-latex-and-specials-regexp)
4641 (org-set-font-lock-defaults)))
4643 (defun org-remove-keyword-keys (list)
4644 (mapcar (lambda (x)
4645 (if (string-match "(..?)$" x)
4646 (substring x 0 (match-beginning 0))
4648 list))
4650 ;; FIXME: this could be done much better, using second characters etc.
4651 (defun org-assign-fast-keys (alist)
4652 "Assign fast keys to a keyword-key alist.
4653 Respect keys that are already there."
4654 (let (new e k c c1 c2 (char ?a))
4655 (while (setq e (pop alist))
4656 (cond
4657 ((equal e '(:startgroup)) (push e new))
4658 ((equal e '(:endgroup)) (push e new))
4660 (setq k (car e) c2 nil)
4661 (if (cdr e)
4662 (setq c (cdr e))
4663 ;; automatically assign a character.
4664 (setq c1 (string-to-char
4665 (downcase (substring
4666 k (if (= (string-to-char k) ?@) 1 0)))))
4667 (if (or (rassoc c1 new) (rassoc c1 alist))
4668 (while (or (rassoc char new) (rassoc char alist))
4669 (setq char (1+ char)))
4670 (setq c2 c1))
4671 (setq c (or c2 char)))
4672 (push (cons k c) new))))
4673 (nreverse new)))
4675 ;;; Some variables ujsed in various places
4677 (defvar org-window-configuration nil
4678 "Used in various places to store a window configuration.")
4679 (defvar org-finish-function nil
4680 "Function to be called when `C-c C-c' is used.
4681 This is for getting out of special buffers like remember.")
4684 ;; FIXME: Occasionally check by commenting these, to make sure
4685 ;; no other functions uses these, forgetting to let-bind them.
4686 (defvar entry)
4687 (defvar state)
4688 (defvar last-state)
4689 (defvar date)
4690 (defvar description)
4692 ;; Defined somewhere in this file, but used before definition.
4693 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4694 (defvar org-agenda-buffer-name)
4695 (defvar org-agenda-undo-list)
4696 (defvar org-agenda-pending-undo-list)
4697 (defvar org-agenda-overriding-header)
4698 (defvar orgtbl-mode)
4699 (defvar org-html-entities)
4700 (defvar org-struct-menu)
4701 (defvar org-org-menu)
4702 (defvar org-tbl-menu)
4703 (defvar org-agenda-keymap)
4705 ;;;; Emacs/XEmacs compatibility
4707 ;; Overlay compatibility functions
4708 (defun org-make-overlay (beg end &optional buffer)
4709 (if (featurep 'xemacs)
4710 (make-extent beg end buffer)
4711 (make-overlay beg end buffer)))
4712 (defun org-delete-overlay (ovl)
4713 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4714 (defun org-detach-overlay (ovl)
4715 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4716 (defun org-move-overlay (ovl beg end &optional buffer)
4717 (if (featurep 'xemacs)
4718 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4719 (move-overlay ovl beg end buffer)))
4720 (defun org-overlay-put (ovl prop value)
4721 (if (featurep 'xemacs)
4722 (set-extent-property ovl prop value)
4723 (overlay-put ovl prop value)))
4724 (defun org-overlay-display (ovl text &optional face evap)
4725 "Make overlay OVL display TEXT with face FACE."
4726 (if (featurep 'xemacs)
4727 (let ((gl (make-glyph text)))
4728 (and face (set-glyph-face gl face))
4729 (set-extent-property ovl 'invisible t)
4730 (set-extent-property ovl 'end-glyph gl))
4731 (overlay-put ovl 'display text)
4732 (if face (overlay-put ovl 'face face))
4733 (if evap (overlay-put ovl 'evaporate t))))
4734 (defun org-overlay-before-string (ovl text &optional face evap)
4735 "Make overlay OVL display TEXT with face FACE."
4736 (if (featurep 'xemacs)
4737 (let ((gl (make-glyph text)))
4738 (and face (set-glyph-face gl face))
4739 (set-extent-property ovl 'begin-glyph gl))
4740 (if face (org-add-props text nil 'face face))
4741 (overlay-put ovl 'before-string text)
4742 (if evap (overlay-put ovl 'evaporate t))))
4743 (defun org-overlay-get (ovl prop)
4744 (if (featurep 'xemacs)
4745 (extent-property ovl prop)
4746 (overlay-get ovl prop)))
4747 (defun org-overlays-at (pos)
4748 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4749 (defun org-overlays-in (&optional start end)
4750 (if (featurep 'xemacs)
4751 (extent-list nil start end)
4752 (overlays-in start end)))
4753 (defun org-overlay-start (o)
4754 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4755 (defun org-overlay-end (o)
4756 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4757 (defun org-find-overlays (prop &optional pos delete)
4758 "Find all overlays specifying PROP at POS or point.
4759 If DELETE is non-nil, delete all those overlays."
4760 (let ((overlays (org-overlays-at (or pos (point))))
4761 ov found)
4762 (while (setq ov (pop overlays))
4763 (if (org-overlay-get ov prop)
4764 (if delete (org-delete-overlay ov) (push ov found))))
4765 found))
4767 ;; Region compatibility
4769 (defun org-add-hook (hook function &optional append local)
4770 "Add-hook, compatible with both Emacsen."
4771 (if (and local (featurep 'xemacs))
4772 (add-local-hook hook function append)
4773 (add-hook hook function append local)))
4775 (defvar org-ignore-region nil
4776 "To temporarily disable the active region.")
4778 (defun org-region-active-p ()
4779 "Is `transient-mark-mode' on and the region active?
4780 Works on both Emacs and XEmacs."
4781 (if org-ignore-region
4783 (if (featurep 'xemacs)
4784 (and zmacs-regions (region-active-p))
4785 (if (fboundp 'use-region-p)
4786 (use-region-p)
4787 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4789 ;; Invisibility compatibility
4791 (defun org-add-to-invisibility-spec (arg)
4792 "Add elements to `buffer-invisibility-spec'.
4793 See documentation for `buffer-invisibility-spec' for the kind of elements
4794 that can be added."
4795 (cond
4796 ((fboundp 'add-to-invisibility-spec)
4797 (add-to-invisibility-spec arg))
4798 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4799 (setq buffer-invisibility-spec (list arg)))
4801 (setq buffer-invisibility-spec
4802 (cons arg buffer-invisibility-spec)))))
4804 (defun org-remove-from-invisibility-spec (arg)
4805 "Remove elements from `buffer-invisibility-spec'."
4806 (if (fboundp 'remove-from-invisibility-spec)
4807 (remove-from-invisibility-spec arg)
4808 (if (consp buffer-invisibility-spec)
4809 (setq buffer-invisibility-spec
4810 (delete arg buffer-invisibility-spec)))))
4812 (defun org-in-invisibility-spec-p (arg)
4813 "Is ARG a member of `buffer-invisibility-spec'?"
4814 (if (consp buffer-invisibility-spec)
4815 (member arg buffer-invisibility-spec)
4816 nil))
4818 ;;;; Define the Org-mode
4820 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4821 (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."))
4824 ;; We use a before-change function to check if a table might need
4825 ;; an update.
4826 (defvar org-table-may-need-update t
4827 "Indicates that a table might need an update.
4828 This variable is set by `org-before-change-function'.
4829 `org-table-align' sets it back to nil.")
4830 (defvar org-mode-map)
4831 (defvar org-mode-hook nil)
4832 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4833 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4834 (defvar org-table-buffer-is-an nil)
4835 (defconst org-outline-regexp "\\*+ ")
4837 ;;;###autoload
4838 (define-derived-mode org-mode outline-mode "Org"
4839 "Outline-based notes management and organizer, alias
4840 \"Carsten's outline-mode for keeping track of everything.\"
4842 Org-mode develops organizational tasks around a NOTES file which
4843 contains information about projects as plain text. Org-mode is
4844 implemented on top of outline-mode, which is ideal to keep the content
4845 of large files well structured. It supports ToDo items, deadlines and
4846 time stamps, which magically appear in the diary listing of the Emacs
4847 calendar. Tables are easily created with a built-in table editor.
4848 Plain text URL-like links connect to websites, emails (VM), Usenet
4849 messages (Gnus), BBDB entries, and any files related to the project.
4850 For printing and sharing of notes, an Org-mode file (or a part of it)
4851 can be exported as a structured ASCII or HTML file.
4853 The following commands are available:
4855 \\{org-mode-map}"
4857 ;; Get rid of Outline menus, they are not needed
4858 ;; Need to do this here because define-derived-mode sets up
4859 ;; the keymap so late. Still, it is a waste to call this each time
4860 ;; we switch another buffer into org-mode.
4861 (if (featurep 'xemacs)
4862 (when (boundp 'outline-mode-menu-heading)
4863 ;; Assume this is Greg's port, it used easymenu
4864 (easy-menu-remove outline-mode-menu-heading)
4865 (easy-menu-remove outline-mode-menu-show)
4866 (easy-menu-remove outline-mode-menu-hide))
4867 (define-key org-mode-map [menu-bar headings] 'undefined)
4868 (define-key org-mode-map [menu-bar hide] 'undefined)
4869 (define-key org-mode-map [menu-bar show] 'undefined))
4871 (easy-menu-add org-org-menu)
4872 (easy-menu-add org-tbl-menu)
4873 (org-install-agenda-files-menu)
4874 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4875 (org-add-to-invisibility-spec '(org-cwidth))
4876 (when (featurep 'xemacs)
4877 (org-set-local 'line-move-ignore-invisible t))
4878 (org-set-local 'outline-regexp org-outline-regexp)
4879 (org-set-local 'outline-level 'org-outline-level)
4880 (when (and org-ellipsis
4881 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4882 (fboundp 'make-glyph-code))
4883 (unless org-display-table
4884 (setq org-display-table (make-display-table)))
4885 (set-display-table-slot
4886 org-display-table 4
4887 (vconcat (mapcar
4888 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4889 org-ellipsis)))
4890 (if (stringp org-ellipsis) org-ellipsis "..."))))
4891 (setq buffer-display-table org-display-table))
4892 (org-set-regexps-and-options)
4893 ;; Calc embedded
4894 (org-set-local 'calc-embedded-open-mode "# ")
4895 (modify-syntax-entry ?# "<")
4896 (modify-syntax-entry ?@ "w")
4897 (if org-startup-truncated (setq truncate-lines t))
4898 (org-set-local 'font-lock-unfontify-region-function
4899 'org-unfontify-region)
4900 ;; Activate before-change-function
4901 (org-set-local 'org-table-may-need-update t)
4902 (org-add-hook 'before-change-functions 'org-before-change-function nil
4903 'local)
4904 ;; Check for running clock before killing a buffer
4905 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4906 ;; Paragraphs and auto-filling
4907 (org-set-autofill-regexps)
4908 (setq indent-line-function 'org-indent-line-function)
4909 (org-update-radio-target-regexp)
4911 ;; Comment characters
4912 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4913 (org-set-local 'comment-padding " ")
4915 ;; Align options lines
4916 (org-set-local
4917 'align-mode-rules-list
4918 '((org-in-buffer-settings
4919 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4920 (modes . '(org-mode)))))
4922 ;; Imenu
4923 (org-set-local 'imenu-create-index-function
4924 'org-imenu-get-tree)
4926 ;; Make isearch reveal context
4927 (if (or (featurep 'xemacs)
4928 (not (boundp 'outline-isearch-open-invisible-function)))
4929 ;; Emacs 21 and XEmacs make use of the hook
4930 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4931 ;; Emacs 22 deals with this through a special variable
4932 (org-set-local 'outline-isearch-open-invisible-function
4933 (lambda (&rest ignore) (org-show-context 'isearch))))
4935 ;; If empty file that did not turn on org-mode automatically, make it to.
4936 (if (and org-insert-mode-line-in-empty-file
4937 (interactive-p)
4938 (= (point-min) (point-max)))
4939 (insert "# -*- mode: org -*-\n\n"))
4941 (unless org-inhibit-startup
4942 (when org-startup-align-all-tables
4943 (let ((bmp (buffer-modified-p)))
4944 (org-table-map-tables 'org-table-align)
4945 (set-buffer-modified-p bmp)))
4946 (org-cycle-hide-drawers 'all)
4947 (cond
4948 ((eq org-startup-folded t)
4949 (org-cycle '(4)))
4950 ((eq org-startup-folded 'content)
4951 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4952 (org-cycle '(4)) (org-cycle '(4)))))))
4954 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4956 (defsubst org-call-with-arg (command arg)
4957 "Call COMMAND interactively, but pretend prefix are was ARG."
4958 (let ((current-prefix-arg arg)) (call-interactively command)))
4960 (defsubst org-current-line (&optional pos)
4961 (save-excursion
4962 (and pos (goto-char pos))
4963 ;; works also in narrowed buffer, because we start at 1, not point-min
4964 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4966 (defun org-current-time ()
4967 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4968 (if (> org-time-stamp-rounding-minutes 0)
4969 (let ((r org-time-stamp-rounding-minutes)
4970 (time (decode-time)))
4971 (apply 'encode-time
4972 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4973 (nthcdr 2 time))))
4974 (current-time)))
4976 (defun org-add-props (string plist &rest props)
4977 "Add text properties to entire string, from beginning to end.
4978 PLIST may be a list of properties, PROPS are individual properties and values
4979 that will be added to PLIST. Returns the string that was modified."
4980 (add-text-properties
4981 0 (length string) (if props (append plist props) plist) string)
4982 string)
4983 (put 'org-add-props 'lisp-indent-function 2)
4986 ;;;; Font-Lock stuff, including the activators
4988 (defvar org-mouse-map (make-sparse-keymap))
4989 (org-defkey org-mouse-map
4990 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4991 (org-defkey org-mouse-map
4992 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4993 (when org-mouse-1-follows-link
4994 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4995 (when org-tab-follows-link
4996 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4997 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4998 (when org-return-follows-link
4999 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5000 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5002 (require 'font-lock)
5004 (defconst org-non-link-chars "]\t\n\r<>")
5005 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5006 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5007 (defvar org-link-re-with-space nil
5008 "Matches a link with spaces, optional angular brackets around it.")
5009 (defvar org-link-re-with-space2 nil
5010 "Matches a link with spaces, optional angular brackets around it.")
5011 (defvar org-angle-link-re nil
5012 "Matches link with angular brackets, spaces are allowed.")
5013 (defvar org-plain-link-re nil
5014 "Matches plain link, without spaces.")
5015 (defvar org-bracket-link-regexp nil
5016 "Matches a link in double brackets.")
5017 (defvar org-bracket-link-analytic-regexp nil
5018 "Regular expression used to analyze links.
5019 Here is what the match groups contain after a match:
5020 1: http:
5021 2: http
5022 3: path
5023 4: [desc]
5024 5: desc")
5025 (defvar org-any-link-re nil
5026 "Regular expression matching any link.")
5028 (defun org-make-link-regexps ()
5029 "Update the link regular expressions.
5030 This should be called after the variable `org-link-types' has changed."
5031 (setq org-link-re-with-space
5032 (concat
5033 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5034 "\\([^" org-non-link-chars " ]"
5035 "[^" org-non-link-chars "]*"
5036 "[^" org-non-link-chars " ]\\)>?")
5037 org-link-re-with-space2
5038 (concat
5039 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5040 "\\([^" org-non-link-chars " ]"
5041 "[^]\t\n\r]*"
5042 "[^" org-non-link-chars " ]\\)>?")
5043 org-angle-link-re
5044 (concat
5045 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5046 "\\([^" org-non-link-chars " ]"
5047 "[^" org-non-link-chars "]*"
5048 "\\)>")
5049 org-plain-link-re
5050 (concat
5051 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5052 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5053 org-bracket-link-regexp
5054 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5055 org-bracket-link-analytic-regexp
5056 (concat
5057 "\\[\\["
5058 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5059 "\\([^]]+\\)"
5060 "\\]"
5061 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5062 "\\]")
5063 org-any-link-re
5064 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5065 org-angle-link-re "\\)\\|\\("
5066 org-plain-link-re "\\)")))
5068 (org-make-link-regexps)
5070 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5071 "Regular expression for fast time stamp matching.")
5072 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5073 "Regular expression for fast time stamp matching.")
5074 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5075 "Regular expression matching time strings for analysis.
5076 This one does not require the space after the date.")
5077 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5078 "Regular expression matching time strings for analysis.")
5079 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5080 "Regular expression matching time stamps, with groups.")
5081 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5082 "Regular expression matching time stamps (also [..]), with groups.")
5083 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5084 "Regular expression matching a time stamp range.")
5085 (defconst org-tr-regexp-both
5086 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5087 "Regular expression matching a time stamp range.")
5088 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5089 org-ts-regexp "\\)?")
5090 "Regular expression matching a time stamp or time stamp range.")
5091 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5092 org-ts-regexp-both "\\)?")
5093 "Regular expression matching a time stamp or time stamp range.
5094 The time stamps may be either active or inactive.")
5096 (defvar org-emph-face nil)
5098 (defun org-do-emphasis-faces (limit)
5099 "Run through the buffer and add overlays to links."
5100 (let (rtn)
5101 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5102 (if (not (= (char-after (match-beginning 3))
5103 (char-after (match-beginning 4))))
5104 (progn
5105 (setq rtn t)
5106 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5107 'face
5108 (nth 1 (assoc (match-string 3)
5109 org-emphasis-alist)))
5110 (add-text-properties (match-beginning 2) (match-end 2)
5111 '(font-lock-multiline t))
5112 (when org-hide-emphasis-markers
5113 (add-text-properties (match-end 4) (match-beginning 5)
5114 '(invisible org-link))
5115 (add-text-properties (match-beginning 3) (match-end 3)
5116 '(invisible org-link)))))
5117 (backward-char 1))
5118 rtn))
5120 (defun org-emphasize (&optional char)
5121 "Insert or change an emphasis, i.e. a font like bold or italic.
5122 If there is an active region, change that region to a new emphasis.
5123 If there is no region, just insert the marker characters and position
5124 the cursor between them.
5125 CHAR should be either the marker character, or the first character of the
5126 HTML tag associated with that emphasis. If CHAR is a space, the means
5127 to remove the emphasis of the selected region.
5128 If char is not given (for example in an interactive call) it
5129 will be prompted for."
5130 (interactive)
5131 (let ((eal org-emphasis-alist) e det
5132 (erc org-emphasis-regexp-components)
5133 (prompt "")
5134 (string "") beg end move tag c s)
5135 (if (org-region-active-p)
5136 (setq beg (region-beginning) end (region-end)
5137 string (buffer-substring beg end))
5138 (setq move t))
5140 (while (setq e (pop eal))
5141 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5142 c (aref tag 0))
5143 (push (cons c (string-to-char (car e))) det)
5144 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5145 (substring tag 1)))))
5146 (unless char
5147 (message "%s" (concat "Emphasis marker or tag:" prompt))
5148 (setq char (read-char-exclusive)))
5149 (setq char (or (cdr (assoc char det)) char))
5150 (if (equal char ?\ )
5151 (setq s "" move nil)
5152 (unless (assoc (char-to-string char) org-emphasis-alist)
5153 (error "No such emphasis marker: \"%c\"" char))
5154 (setq s (char-to-string char)))
5155 (while (and (> (length string) 1)
5156 (equal (substring string 0 1) (substring string -1))
5157 (assoc (substring string 0 1) org-emphasis-alist))
5158 (setq string (substring string 1 -1)))
5159 (setq string (concat s string s))
5160 (if beg (delete-region beg end))
5161 (unless (or (bolp)
5162 (string-match (concat "[" (nth 0 erc) "\n]")
5163 (char-to-string (char-before (point)))))
5164 (insert " "))
5165 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5166 (char-to-string (char-after (point))))
5167 (insert " ") (backward-char 1))
5168 (insert string)
5169 (and move (backward-char 1))))
5171 (defconst org-nonsticky-props
5172 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5175 (defun org-activate-plain-links (limit)
5176 "Run through the buffer and add overlays to links."
5177 (catch 'exit
5178 (let (f)
5179 (while (re-search-forward org-plain-link-re limit t)
5180 (setq f (get-text-property (match-beginning 0) 'face))
5181 (if (or (eq f 'org-tag)
5182 (and (listp f) (memq 'org-tag f)))
5184 (add-text-properties (match-beginning 0) (match-end 0)
5185 (list 'mouse-face 'highlight
5186 'rear-nonsticky org-nonsticky-props
5187 'keymap org-mouse-map
5189 (throw 'exit t))))))
5191 (defun org-activate-code (limit)
5192 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5193 (unless (get-text-property (match-beginning 1) 'face)
5194 (remove-text-properties (match-beginning 0) (match-end 0)
5195 '(display t invisible t intangible t))
5196 t)))
5198 (defun org-activate-angle-links (limit)
5199 "Run through the buffer and add overlays to links."
5200 (if (re-search-forward org-angle-link-re limit t)
5201 (progn
5202 (add-text-properties (match-beginning 0) (match-end 0)
5203 (list 'mouse-face 'highlight
5204 'rear-nonsticky org-nonsticky-props
5205 'keymap org-mouse-map
5207 t)))
5209 (defmacro org-maybe-intangible (props)
5210 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5211 In emacs 21, invisible text is not avoided by the command loop, so the
5212 intangible property is needed to make sure point skips this text.
5213 In Emacs 22, this is not necessary. The intangible text property has
5214 led to problems with flyspell. These problems are fixed in flyspell.el,
5215 but we still avoid setting the property in Emacs 22 and later.
5216 We use a macro so that the test can happen at compilation time."
5217 (if (< emacs-major-version 22)
5218 `(append '(intangible t) ,props)
5219 props))
5221 (defun org-activate-bracket-links (limit)
5222 "Run through the buffer and add overlays to bracketed links."
5223 (if (re-search-forward org-bracket-link-regexp limit t)
5224 (let* ((help (concat "LINK: "
5225 (org-match-string-no-properties 1)))
5226 ;; FIXME: above we should remove the escapes.
5227 ;; but that requires another match, protecting match data,
5228 ;; a lot of overhead for font-lock.
5229 (ip (org-maybe-intangible
5230 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5231 'keymap org-mouse-map 'mouse-face 'highlight
5232 'font-lock-multiline t 'help-echo help)))
5233 (vp (list 'rear-nonsticky org-nonsticky-props
5234 'keymap org-mouse-map 'mouse-face 'highlight
5235 ' font-lock-multiline t 'help-echo help)))
5236 ;; We need to remove the invisible property here. Table narrowing
5237 ;; may have made some of this invisible.
5238 (remove-text-properties (match-beginning 0) (match-end 0)
5239 '(invisible nil))
5240 (if (match-end 3)
5241 (progn
5242 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5243 (add-text-properties (match-beginning 3) (match-end 3) vp)
5244 (add-text-properties (match-end 3) (match-end 0) ip))
5245 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5246 (add-text-properties (match-beginning 1) (match-end 1) vp)
5247 (add-text-properties (match-end 1) (match-end 0) ip))
5248 t)))
5250 (defun org-activate-dates (limit)
5251 "Run through the buffer and add overlays to dates."
5252 (if (re-search-forward org-tsr-regexp-both limit t)
5253 (progn
5254 (add-text-properties (match-beginning 0) (match-end 0)
5255 (list 'mouse-face 'highlight
5256 'rear-nonsticky org-nonsticky-props
5257 'keymap org-mouse-map))
5258 (when org-display-custom-times
5259 (if (match-end 3)
5260 (org-display-custom-time (match-beginning 3) (match-end 3)))
5261 (org-display-custom-time (match-beginning 1) (match-end 1)))
5262 t)))
5264 (defvar org-target-link-regexp nil
5265 "Regular expression matching radio targets in plain text.")
5266 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5267 "Regular expression matching a link target.")
5268 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5269 "Regular expression matching a radio target.")
5270 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5271 "Regular expression matching any target.")
5273 (defun org-activate-target-links (limit)
5274 "Run through the buffer and add overlays to target matches."
5275 (when org-target-link-regexp
5276 (let ((case-fold-search t))
5277 (if (re-search-forward org-target-link-regexp limit t)
5278 (progn
5279 (add-text-properties (match-beginning 0) (match-end 0)
5280 (list 'mouse-face 'highlight
5281 'rear-nonsticky org-nonsticky-props
5282 'keymap org-mouse-map
5283 'help-echo "Radio target link"
5284 'org-linked-text t))
5285 t)))))
5287 (defun org-update-radio-target-regexp ()
5288 "Find all radio targets in this file and update the regular expression."
5289 (interactive)
5290 (when (memq 'radio org-activate-links)
5291 (setq org-target-link-regexp
5292 (org-make-target-link-regexp (org-all-targets 'radio)))
5293 (org-restart-font-lock)))
5295 (defun org-hide-wide-columns (limit)
5296 (let (s e)
5297 (setq s (text-property-any (point) (or limit (point-max))
5298 'org-cwidth t))
5299 (when s
5300 (setq e (next-single-property-change s 'org-cwidth))
5301 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5302 (goto-char e)
5303 t)))
5305 (defvar org-latex-and-specials-regexp nil
5306 "Regular expression for highlighting export special stuff.")
5307 (defvar org-match-substring-regexp)
5308 (defvar org-match-substring-with-braces-regexp)
5309 (defvar org-export-html-special-string-regexps)
5311 (defun org-compute-latex-and-specials-regexp ()
5312 "Compute regular expression for stuff treated specially by exporters."
5313 (if (not org-highlight-latex-fragments-and-specials)
5314 (org-set-local 'org-latex-and-specials-regexp nil)
5315 (let*
5316 ((matchers (plist-get org-format-latex-options :matchers))
5317 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5318 org-latex-regexps)))
5319 (options (org-combine-plists (org-default-export-plist)
5320 (org-infile-export-plist)))
5321 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5322 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5323 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5324 (org-export-html-expand (plist-get options :expand-quoted-html))
5325 (org-export-with-special-strings (plist-get options :special-strings))
5326 (re-sub
5327 (cond
5328 ((equal org-export-with-sub-superscripts '{})
5329 (list org-match-substring-with-braces-regexp))
5330 (org-export-with-sub-superscripts
5331 (list org-match-substring-regexp))
5332 (t nil)))
5333 (re-latex
5334 (if org-export-with-LaTeX-fragments
5335 (mapcar (lambda (x) (nth 1 x)) latexs)))
5336 (re-macros
5337 (if org-export-with-TeX-macros
5338 (list (concat "\\\\"
5339 (regexp-opt
5340 (append (mapcar 'car org-html-entities)
5341 (if (boundp 'org-latex-entities)
5342 org-latex-entities nil))
5343 'words))) ; FIXME
5345 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5346 (re-special (if org-export-with-special-strings
5347 (mapcar (lambda (x) (car x))
5348 org-export-html-special-string-regexps)))
5349 (re-rest
5350 (delq nil
5351 (list
5352 (if org-export-html-expand "@<[^>\n]+>")
5353 ))))
5354 (org-set-local
5355 'org-latex-and-specials-regexp
5356 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5357 re-rest) "\\|")))))
5359 (defface org-latex-and-export-specials
5360 (let ((font (cond ((assq :inherit custom-face-attributes)
5361 '(:inherit underline))
5362 (t '(:underline t)))))
5363 `((((class grayscale) (background light))
5364 (:foreground "DimGray" ,@font))
5365 (((class grayscale) (background dark))
5366 (:foreground "LightGray" ,@font))
5367 (((class color) (background light))
5368 (:foreground "SaddleBrown"))
5369 (((class color) (background dark))
5370 (:foreground "burlywood"))
5371 (t (,@font))))
5372 "Face used to highlight math latex and other special exporter stuff."
5373 :group 'org-faces)
5375 (defun org-do-latex-and-special-faces (limit)
5376 "Run through the buffer and add overlays to links."
5377 (when org-latex-and-specials-regexp
5378 (let (rtn d)
5379 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5380 limit t))
5381 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5382 'face))
5383 '(org-code org-verbatim underline)))
5384 (progn
5385 (setq rtn t
5386 d (cond ((member (char-after (1+ (match-beginning 0)))
5387 '(?_ ?^)) 1)
5388 (t 0)))
5389 (font-lock-prepend-text-property
5390 (+ d (match-beginning 0)) (match-end 0)
5391 'face 'org-latex-and-export-specials)
5392 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5393 '(font-lock-multiline t)))))
5394 rtn)))
5396 (defun org-restart-font-lock ()
5397 "Restart font-lock-mode, to force refontification."
5398 (when (and (boundp 'font-lock-mode) font-lock-mode)
5399 (font-lock-mode -1)
5400 (font-lock-mode 1)))
5402 (defun org-all-targets (&optional radio)
5403 "Return a list of all targets in this file.
5404 With optional argument RADIO, only find radio targets."
5405 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5406 rtn)
5407 (save-excursion
5408 (goto-char (point-min))
5409 (while (re-search-forward re nil t)
5410 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5411 rtn)))
5413 (defun org-make-target-link-regexp (targets)
5414 "Make regular expression matching all strings in TARGETS.
5415 The regular expression finds the targets also if there is a line break
5416 between words."
5417 (and targets
5418 (concat
5419 "\\<\\("
5420 (mapconcat
5421 (lambda (x)
5422 (while (string-match " +" x)
5423 (setq x (replace-match "\\s-+" t t x)))
5425 targets
5426 "\\|")
5427 "\\)\\>")))
5429 (defun org-activate-tags (limit)
5430 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5431 (progn
5432 (add-text-properties (match-beginning 1) (match-end 1)
5433 (list 'mouse-face 'highlight
5434 'rear-nonsticky org-nonsticky-props
5435 'keymap org-mouse-map))
5436 t)))
5438 (defun org-outline-level ()
5439 (save-excursion
5440 (looking-at outline-regexp)
5441 (if (match-beginning 1)
5442 (+ (org-get-string-indentation (match-string 1)) 1000)
5443 (1- (- (match-end 0) (match-beginning 0))))))
5445 (defvar org-font-lock-keywords nil)
5447 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5448 "Regular expression matching a property line.")
5450 (defun org-set-font-lock-defaults ()
5451 (let* ((em org-fontify-emphasized-text)
5452 (lk org-activate-links)
5453 (org-font-lock-extra-keywords
5454 (list
5455 ;; Headlines
5456 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5457 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5458 ;; Table lines
5459 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5460 (1 'org-table t))
5461 ;; Table internals
5462 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5463 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5464 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5465 ;; Drawers
5466 (list org-drawer-regexp '(0 'org-special-keyword t))
5467 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5468 ;; Properties
5469 (list org-property-re
5470 '(1 'org-special-keyword t)
5471 '(3 'org-property-value t))
5472 (if org-format-transports-properties-p
5473 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5474 ;; Links
5475 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5476 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5477 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5478 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5479 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5480 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5481 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5482 '(org-hide-wide-columns (0 nil append))
5483 ;; TODO lines
5484 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5485 '(1 (org-get-todo-face 1) t))
5486 ;; DONE
5487 (if org-fontify-done-headline
5488 (list (concat "^[*]+ +\\<\\("
5489 (mapconcat 'regexp-quote org-done-keywords "\\|")
5490 "\\)\\(.*\\)")
5491 '(2 'org-headline-done t))
5492 nil)
5493 ;; Priorities
5494 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5495 ;; Special keywords
5496 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5497 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5498 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5499 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5500 ;; Emphasis
5501 (if em
5502 (if (featurep 'xemacs)
5503 '(org-do-emphasis-faces (0 nil append))
5504 '(org-do-emphasis-faces)))
5505 ;; Checkboxes
5506 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5507 2 'bold prepend)
5508 (if org-provide-checkbox-statistics
5509 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5510 (0 (org-get-checkbox-statistics-face) t)))
5511 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5512 '(1 'org-archived prepend))
5513 ;; Specials
5514 '(org-do-latex-and-special-faces)
5515 ;; Code
5516 '(org-activate-code (1 'org-code t))
5517 ;; COMMENT
5518 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5519 "\\|" org-quote-string "\\)\\>")
5520 '(1 'org-special-keyword t))
5521 '("^#.*" (0 'font-lock-comment-face t))
5523 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5524 ;; Now set the full font-lock-keywords
5525 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5526 (org-set-local 'font-lock-defaults
5527 '(org-font-lock-keywords t nil nil backward-paragraph))
5528 (kill-local-variable 'font-lock-keywords) nil))
5530 (defvar org-m nil)
5531 (defvar org-l nil)
5532 (defvar org-f nil)
5533 (defun org-get-level-face (n)
5534 "Get the right face for match N in font-lock matching of healdines."
5535 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5536 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5537 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5538 (cond
5539 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5540 ((eq n 2) org-f)
5541 (t (if org-level-color-stars-only nil org-f))))
5543 (defun org-get-todo-face (kwd)
5544 "Get the right face for a TODO keyword KWD.
5545 If KWD is a number, get the corresponding match group."
5546 (if (numberp kwd) (setq kwd (match-string kwd)))
5547 (or (cdr (assoc kwd org-todo-keyword-faces))
5548 (and (member kwd org-done-keywords) 'org-done)
5549 'org-todo))
5551 (defun org-unfontify-region (beg end &optional maybe_loudly)
5552 "Remove fontification and activation overlays from links."
5553 (font-lock-default-unfontify-region beg end)
5554 (let* ((buffer-undo-list t)
5555 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5556 (inhibit-modification-hooks t)
5557 deactivate-mark buffer-file-name buffer-file-truename)
5558 (remove-text-properties beg end
5559 '(mouse-face t keymap t org-linked-text t
5560 invisible t intangible t))))
5562 ;;;; Visibility cycling, including org-goto and indirect buffer
5564 ;;; Cycling
5566 (defvar org-cycle-global-status nil)
5567 (make-variable-buffer-local 'org-cycle-global-status)
5568 (defvar org-cycle-subtree-status nil)
5569 (make-variable-buffer-local 'org-cycle-subtree-status)
5571 ;;;###autoload
5572 (defun org-cycle (&optional arg)
5573 "Visibility cycling for Org-mode.
5575 - When this function is called with a prefix argument, rotate the entire
5576 buffer through 3 states (global cycling)
5577 1. OVERVIEW: Show only top-level headlines.
5578 2. CONTENTS: Show all headlines of all levels, but no body text.
5579 3. SHOW ALL: Show everything.
5581 - When point is at the beginning of a headline, rotate the subtree started
5582 by this line through 3 different states (local cycling)
5583 1. FOLDED: Only the main headline is shown.
5584 2. CHILDREN: The main headline and the direct children are shown.
5585 From this state, you can move to one of the children
5586 and zoom in further.
5587 3. SUBTREE: Show the entire subtree, including body text.
5589 - When there is a numeric prefix, go up to a heading with level ARG, do
5590 a `show-subtree' and return to the previous cursor position. If ARG
5591 is negative, go up that many levels.
5593 - When point is not at the beginning of a headline, execute
5594 `indent-relative', like TAB normally does. See the option
5595 `org-cycle-emulate-tab' for details.
5597 - Special case: if point is at the beginning of the buffer and there is
5598 no headline in line 1, this function will act as if called with prefix arg.
5599 But only if also the variable `org-cycle-global-at-bob' is t."
5600 (interactive "P")
5601 (let* ((outline-regexp
5602 (if (and (org-mode-p) org-cycle-include-plain-lists)
5603 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5604 outline-regexp))
5605 (bob-special (and org-cycle-global-at-bob (bobp)
5606 (not (looking-at outline-regexp))))
5607 (org-cycle-hook
5608 (if bob-special
5609 (delq 'org-optimize-window-after-visibility-change
5610 (copy-sequence org-cycle-hook))
5611 org-cycle-hook))
5612 (pos (point)))
5614 (if (or bob-special (equal arg '(4)))
5615 ;; special case: use global cycling
5616 (setq arg t))
5618 (cond
5620 ((org-at-table-p 'any)
5621 ;; Enter the table or move to the next field in the table
5622 (or (org-table-recognize-table.el)
5623 (progn
5624 (if arg (org-table-edit-field t)
5625 (org-table-justify-field-maybe)
5626 (call-interactively 'org-table-next-field)))))
5628 ((eq arg t) ;; Global cycling
5630 (cond
5631 ((and (eq last-command this-command)
5632 (eq org-cycle-global-status 'overview))
5633 ;; We just created the overview - now do table of contents
5634 ;; This can be slow in very large buffers, so indicate action
5635 (message "CONTENTS...")
5636 (org-content)
5637 (message "CONTENTS...done")
5638 (setq org-cycle-global-status 'contents)
5639 (run-hook-with-args 'org-cycle-hook 'contents))
5641 ((and (eq last-command this-command)
5642 (eq org-cycle-global-status 'contents))
5643 ;; We just showed the table of contents - now show everything
5644 (show-all)
5645 (message "SHOW ALL")
5646 (setq org-cycle-global-status 'all)
5647 (run-hook-with-args 'org-cycle-hook 'all))
5650 ;; Default action: go to overview
5651 (org-overview)
5652 (message "OVERVIEW")
5653 (setq org-cycle-global-status 'overview)
5654 (run-hook-with-args 'org-cycle-hook 'overview))))
5656 ((and org-drawers org-drawer-regexp
5657 (save-excursion
5658 (beginning-of-line 1)
5659 (looking-at org-drawer-regexp)))
5660 ;; Toggle block visibility
5661 (org-flag-drawer
5662 (not (get-char-property (match-end 0) 'invisible))))
5664 ((integerp arg)
5665 ;; Show-subtree, ARG levels up from here.
5666 (save-excursion
5667 (org-back-to-heading)
5668 (outline-up-heading (if (< arg 0) (- arg)
5669 (- (funcall outline-level) arg)))
5670 (org-show-subtree)))
5672 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5673 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5674 ;; At a heading: rotate between three different views
5675 (org-back-to-heading)
5676 (let ((goal-column 0) eoh eol eos)
5677 ;; First, some boundaries
5678 (save-excursion
5679 (org-back-to-heading)
5680 (save-excursion
5681 (beginning-of-line 2)
5682 (while (and (not (eobp)) ;; this is like `next-line'
5683 (get-char-property (1- (point)) 'invisible))
5684 (beginning-of-line 2)) (setq eol (point)))
5685 (outline-end-of-heading) (setq eoh (point))
5686 (org-end-of-subtree t)
5687 (unless (eobp)
5688 (skip-chars-forward " \t\n")
5689 (beginning-of-line 1) ; in case this is an item
5691 (setq eos (1- (point))))
5692 ;; Find out what to do next and set `this-command'
5693 (cond
5694 ((= eos eoh)
5695 ;; Nothing is hidden behind this heading
5696 (message "EMPTY ENTRY")
5697 (setq org-cycle-subtree-status nil)
5698 (save-excursion
5699 (goto-char eos)
5700 (outline-next-heading)
5701 (if (org-invisible-p) (org-flag-heading nil))))
5702 ((or (>= eol eos)
5703 (not (string-match "\\S-" (buffer-substring eol eos))))
5704 ;; Entire subtree is hidden in one line: open it
5705 (org-show-entry)
5706 (show-children)
5707 (message "CHILDREN")
5708 (save-excursion
5709 (goto-char eos)
5710 (outline-next-heading)
5711 (if (org-invisible-p) (org-flag-heading nil)))
5712 (setq org-cycle-subtree-status 'children)
5713 (run-hook-with-args 'org-cycle-hook 'children))
5714 ((and (eq last-command this-command)
5715 (eq org-cycle-subtree-status 'children))
5716 ;; We just showed the children, now show everything.
5717 (org-show-subtree)
5718 (message "SUBTREE")
5719 (setq org-cycle-subtree-status 'subtree)
5720 (run-hook-with-args 'org-cycle-hook 'subtree))
5722 ;; Default action: hide the subtree.
5723 (hide-subtree)
5724 (message "FOLDED")
5725 (setq org-cycle-subtree-status 'folded)
5726 (run-hook-with-args 'org-cycle-hook 'folded)))))
5728 ;; TAB emulation
5729 (buffer-read-only (org-back-to-heading))
5731 ((org-try-cdlatex-tab))
5733 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5734 (or (not (bolp))
5735 (not (looking-at outline-regexp))))
5736 (call-interactively (global-key-binding "\t")))
5738 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5739 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5740 (or (and (eq org-cycle-emulate-tab 'white)
5741 (= (match-end 0) (point-at-eol)))
5742 (and (eq org-cycle-emulate-tab 'whitestart)
5743 (>= (match-end 0) pos))))
5745 (eq org-cycle-emulate-tab t))
5746 ; (if (and (looking-at "[ \n\r\t]")
5747 ; (string-match "^[ \t]*$" (buffer-substring
5748 ; (point-at-bol) (point))))
5749 ; (progn
5750 ; (beginning-of-line 1)
5751 ; (and (looking-at "[ \t]+") (replace-match ""))))
5752 (call-interactively (global-key-binding "\t")))
5754 (t (save-excursion
5755 (org-back-to-heading)
5756 (org-cycle))))))
5758 ;;;###autoload
5759 (defun org-global-cycle (&optional arg)
5760 "Cycle the global visibility. For details see `org-cycle'."
5761 (interactive "P")
5762 (let ((org-cycle-include-plain-lists
5763 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5764 (if (integerp arg)
5765 (progn
5766 (show-all)
5767 (hide-sublevels arg)
5768 (setq org-cycle-global-status 'contents))
5769 (org-cycle '(4)))))
5771 (defun org-overview ()
5772 "Switch to overview mode, shoing only top-level headlines.
5773 Really, this shows all headlines with level equal or greater than the level
5774 of the first headline in the buffer. This is important, because if the
5775 first headline is not level one, then (hide-sublevels 1) gives confusing
5776 results."
5777 (interactive)
5778 (let ((level (save-excursion
5779 (goto-char (point-min))
5780 (if (re-search-forward (concat "^" outline-regexp) nil t)
5781 (progn
5782 (goto-char (match-beginning 0))
5783 (funcall outline-level))))))
5784 (and level (hide-sublevels level))))
5786 (defun org-content (&optional arg)
5787 "Show all headlines in the buffer, like a table of contents.
5788 With numerical argument N, show content up to level N."
5789 (interactive "P")
5790 (save-excursion
5791 ;; Visit all headings and show their offspring
5792 (and (integerp arg) (org-overview))
5793 (goto-char (point-max))
5794 (catch 'exit
5795 (while (and (progn (condition-case nil
5796 (outline-previous-visible-heading 1)
5797 (error (goto-char (point-min))))
5799 (looking-at outline-regexp))
5800 (if (integerp arg)
5801 (show-children (1- arg))
5802 (show-branches))
5803 (if (bobp) (throw 'exit nil))))))
5806 (defun org-optimize-window-after-visibility-change (state)
5807 "Adjust the window after a change in outline visibility.
5808 This function is the default value of the hook `org-cycle-hook'."
5809 (when (get-buffer-window (current-buffer))
5810 (cond
5811 ; ((eq state 'overview) (org-first-headline-recenter 1))
5812 ; ((eq state 'overview) (org-beginning-of-line))
5813 ((eq state 'content) nil)
5814 ((eq state 'all) nil)
5815 ((eq state 'folded) nil)
5816 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5817 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5819 (defun org-compact-display-after-subtree-move ()
5820 (let (beg end)
5821 (save-excursion
5822 (if (org-up-heading-safe)
5823 (progn
5824 (hide-subtree)
5825 (show-entry)
5826 (show-children)
5827 (org-cycle-show-empty-lines 'children)
5828 (org-cycle-hide-drawers 'children))
5829 (org-overview)))))
5831 (defun org-cycle-show-empty-lines (state)
5832 "Show empty lines above all visible headlines.
5833 The region to be covered depends on STATE when called through
5834 `org-cycle-hook'. Lisp program can use t for STATE to get the
5835 entire buffer covered. Note that an empty line is only shown if there
5836 are at least `org-cycle-separator-lines' empty lines before the headeline."
5837 (when (> org-cycle-separator-lines 0)
5838 (save-excursion
5839 (let* ((n org-cycle-separator-lines)
5840 (re (cond
5841 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5842 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5843 (t (let ((ns (number-to-string (- n 2))))
5844 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5845 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5846 beg end)
5847 (cond
5848 ((memq state '(overview contents t))
5849 (setq beg (point-min) end (point-max)))
5850 ((memq state '(children folded))
5851 (setq beg (point) end (progn (org-end-of-subtree t t)
5852 (beginning-of-line 2)
5853 (point)))))
5854 (when beg
5855 (goto-char beg)
5856 (while (re-search-forward re end t)
5857 (if (not (get-char-property (match-end 1) 'invisible))
5858 (outline-flag-region
5859 (match-beginning 1) (match-end 1) nil)))))))
5860 ;; Never hide empty lines at the end of the file.
5861 (save-excursion
5862 (goto-char (point-max))
5863 (outline-previous-heading)
5864 (outline-end-of-heading)
5865 (if (and (looking-at "[ \t\n]+")
5866 (= (match-end 0) (point-max)))
5867 (outline-flag-region (point) (match-end 0) nil))))
5869 (defun org-subtree-end-visible-p ()
5870 "Is the end of the current subtree visible?"
5871 (pos-visible-in-window-p
5872 (save-excursion (org-end-of-subtree t) (point))))
5874 (defun org-first-headline-recenter (&optional N)
5875 "Move cursor to the first headline and recenter the headline.
5876 Optional argument N means, put the headline into the Nth line of the window."
5877 (goto-char (point-min))
5878 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5879 (beginning-of-line)
5880 (recenter (prefix-numeric-value N))))
5882 ;;; Org-goto
5884 (defvar org-goto-window-configuration nil)
5885 (defvar org-goto-marker nil)
5886 (defvar org-goto-map
5887 (let ((map (make-sparse-keymap)))
5888 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5889 (while (setq cmd (pop cmds))
5890 (substitute-key-definition cmd cmd map global-map)))
5891 (suppress-keymap map)
5892 (org-defkey map "\C-m" 'org-goto-ret)
5893 (org-defkey map [(return)] 'org-goto-ret)
5894 (org-defkey map [(left)] 'org-goto-left)
5895 (org-defkey map [(right)] 'org-goto-right)
5896 (org-defkey map [(control ?g)] 'org-goto-quit)
5897 (org-defkey map "\C-i" 'org-cycle)
5898 (org-defkey map [(tab)] 'org-cycle)
5899 (org-defkey map [(down)] 'outline-next-visible-heading)
5900 (org-defkey map [(up)] 'outline-previous-visible-heading)
5901 (if org-goto-auto-isearch
5902 (if (fboundp 'define-key-after)
5903 (define-key-after map [t] 'org-goto-local-auto-isearch)
5904 nil)
5905 (org-defkey map "q" 'org-goto-quit)
5906 (org-defkey map "n" 'outline-next-visible-heading)
5907 (org-defkey map "p" 'outline-previous-visible-heading)
5908 (org-defkey map "f" 'outline-forward-same-level)
5909 (org-defkey map "b" 'outline-backward-same-level)
5910 (org-defkey map "u" 'outline-up-heading))
5911 (org-defkey map "/" 'org-occur)
5912 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5913 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5914 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5915 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5916 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5917 map))
5919 (defconst org-goto-help
5920 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5921 RET=jump to location [Q]uit and return to previous location
5922 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5924 (defvar org-goto-start-pos) ; dynamically scoped parameter
5926 (defun org-goto (&optional alternative-interface)
5927 "Look up a different location in the current file, keeping current visibility.
5929 When you want look-up or go to a different location in a document, the
5930 fastest way is often to fold the entire buffer and then dive into the tree.
5931 This method has the disadvantage, that the previous location will be folded,
5932 which may not be what you want.
5934 This command works around this by showing a copy of the current buffer
5935 in an indirect buffer, in overview mode. You can dive into the tree in
5936 that copy, use org-occur and incremental search to find a location.
5937 When pressing RET or `Q', the command returns to the original buffer in
5938 which the visibility is still unchanged. After RET is will also jump to
5939 the location selected in the indirect buffer and expose the
5940 the headline hierarchy above."
5941 (interactive "P")
5942 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
5943 (org-refile-use-outline-path t)
5944 (interface
5945 (if (not alternative-interface)
5946 org-goto-interface
5947 (if (eq org-goto-interface 'outline)
5948 'outline-path-completion
5949 'outline)))
5950 (org-goto-start-pos (point))
5951 (selected-point
5952 (if (eq interface 'outline)
5953 (car (org-get-location (current-buffer) org-goto-help))
5954 (nth 3 (org-refile-get-location "Goto: ")))))
5955 (if selected-point
5956 (progn
5957 (org-mark-ring-push org-goto-start-pos)
5958 (goto-char selected-point)
5959 (if (or (org-invisible-p) (org-invisible-p2))
5960 (org-show-context 'org-goto)))
5961 (message "Quit"))))
5963 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5964 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5965 (defvar org-goto-local-auto-isearch-map) ; defined below
5967 (defun org-get-location (buf help)
5968 "Let the user select a location in the Org-mode buffer BUF.
5969 This function uses a recursive edit. It returns the selected position
5970 or nil."
5971 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5972 (isearch-hide-immediately nil)
5973 (isearch-search-fun-function
5974 (lambda () 'org-goto-local-search-forward-headings))
5975 (org-goto-selected-point org-goto-exit-command))
5976 (save-excursion
5977 (save-window-excursion
5978 (delete-other-windows)
5979 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5980 (switch-to-buffer
5981 (condition-case nil
5982 (make-indirect-buffer (current-buffer) "*org-goto*")
5983 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5984 (with-output-to-temp-buffer "*Help*"
5985 (princ help))
5986 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5987 (setq buffer-read-only nil)
5988 (let ((org-startup-truncated t)
5989 (org-startup-folded nil)
5990 (org-startup-align-all-tables nil))
5991 (org-mode)
5992 (org-overview))
5993 (setq buffer-read-only t)
5994 (if (and (boundp 'org-goto-start-pos)
5995 (integer-or-marker-p org-goto-start-pos))
5996 (let ((org-show-hierarchy-above t)
5997 (org-show-siblings t)
5998 (org-show-following-heading t))
5999 (goto-char org-goto-start-pos)
6000 (and (org-invisible-p) (org-show-context)))
6001 (goto-char (point-min)))
6002 (org-beginning-of-line)
6003 (message "Select location and press RET")
6004 (use-local-map org-goto-map)
6005 (recursive-edit)
6007 (kill-buffer "*org-goto*")
6008 (cons org-goto-selected-point org-goto-exit-command)))
6010 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6011 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6012 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6013 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6015 (defun org-goto-local-search-forward-headings (string bound noerror)
6016 "Search and make sure that anu matches are in headlines."
6017 (catch 'return
6018 (while (search-forward string bound noerror)
6019 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6020 (and (member :headline context)
6021 (not (member :tags context))))
6022 (throw 'return (point))))))
6024 (defun org-goto-local-auto-isearch ()
6025 "Start isearch."
6026 (interactive)
6027 (goto-char (point-min))
6028 (let ((keys (this-command-keys)))
6029 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6030 (isearch-mode t)
6031 (isearch-process-search-char (string-to-char keys)))))
6033 (defun org-goto-ret (&optional arg)
6034 "Finish `org-goto' by going to the new location."
6035 (interactive "P")
6036 (setq org-goto-selected-point (point)
6037 org-goto-exit-command 'return)
6038 (throw 'exit nil))
6040 (defun org-goto-left ()
6041 "Finish `org-goto' by going to the new location."
6042 (interactive)
6043 (if (org-on-heading-p)
6044 (progn
6045 (beginning-of-line 1)
6046 (setq org-goto-selected-point (point)
6047 org-goto-exit-command 'left)
6048 (throw 'exit nil))
6049 (error "Not on a heading")))
6051 (defun org-goto-right ()
6052 "Finish `org-goto' by going to the new location."
6053 (interactive)
6054 (if (org-on-heading-p)
6055 (progn
6056 (setq org-goto-selected-point (point)
6057 org-goto-exit-command 'right)
6058 (throw 'exit nil))
6059 (error "Not on a heading")))
6061 (defun org-goto-quit ()
6062 "Finish `org-goto' without cursor motion."
6063 (interactive)
6064 (setq org-goto-selected-point nil)
6065 (setq org-goto-exit-command 'quit)
6066 (throw 'exit nil))
6068 ;;; Indirect buffer display of subtrees
6070 (defvar org-indirect-dedicated-frame nil
6071 "This is the frame being used for indirect tree display.")
6072 (defvar org-last-indirect-buffer nil)
6074 (defun org-tree-to-indirect-buffer (&optional arg)
6075 "Create indirect buffer and narrow it to current subtree.
6076 With numerical prefix ARG, go up to this level and then take that tree.
6077 If ARG is negative, go up that many levels.
6078 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6079 indirect buffer previously made with this command, to avoid proliferation of
6080 indirect buffers. However, when you call the command with a `C-u' prefix, or
6081 when `org-indirect-buffer-display' is `new-frame', the last buffer
6082 is kept so that you can work with several indirect buffers at the same time.
6083 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6084 requests that a new frame be made for the new buffer, so that the dedicated
6085 frame is not changed."
6086 (interactive "P")
6087 (let ((cbuf (current-buffer))
6088 (cwin (selected-window))
6089 (pos (point))
6090 beg end level heading ibuf)
6091 (save-excursion
6092 (org-back-to-heading t)
6093 (when (numberp arg)
6094 (setq level (org-outline-level))
6095 (if (< arg 0) (setq arg (+ level arg)))
6096 (while (> (setq level (org-outline-level)) arg)
6097 (outline-up-heading 1 t)))
6098 (setq beg (point)
6099 heading (org-get-heading))
6100 (org-end-of-subtree t) (setq end (point)))
6101 (if (and (buffer-live-p org-last-indirect-buffer)
6102 (not (eq org-indirect-buffer-display 'new-frame))
6103 (not arg))
6104 (kill-buffer org-last-indirect-buffer))
6105 (setq ibuf (org-get-indirect-buffer cbuf)
6106 org-last-indirect-buffer ibuf)
6107 (cond
6108 ((or (eq org-indirect-buffer-display 'new-frame)
6109 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6110 (select-frame (make-frame))
6111 (delete-other-windows)
6112 (switch-to-buffer ibuf)
6113 (org-set-frame-title heading))
6114 ((eq org-indirect-buffer-display 'dedicated-frame)
6115 (raise-frame
6116 (select-frame (or (and org-indirect-dedicated-frame
6117 (frame-live-p org-indirect-dedicated-frame)
6118 org-indirect-dedicated-frame)
6119 (setq org-indirect-dedicated-frame (make-frame)))))
6120 (delete-other-windows)
6121 (switch-to-buffer ibuf)
6122 (org-set-frame-title (concat "Indirect: " heading)))
6123 ((eq org-indirect-buffer-display 'current-window)
6124 (switch-to-buffer ibuf))
6125 ((eq org-indirect-buffer-display 'other-window)
6126 (pop-to-buffer ibuf))
6127 (t (error "Invalid value.")))
6128 (if (featurep 'xemacs)
6129 (save-excursion (org-mode) (turn-on-font-lock)))
6130 (narrow-to-region beg end)
6131 (show-all)
6132 (goto-char pos)
6133 (and (window-live-p cwin) (select-window cwin))))
6135 (defun org-get-indirect-buffer (&optional buffer)
6136 (setq buffer (or buffer (current-buffer)))
6137 (let ((n 1) (base (buffer-name buffer)) bname)
6138 (while (buffer-live-p
6139 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6140 (setq n (1+ n)))
6141 (condition-case nil
6142 (make-indirect-buffer buffer bname 'clone)
6143 (error (make-indirect-buffer buffer bname)))))
6145 (defun org-set-frame-title (title)
6146 "Set the title of the current frame to the string TITLE."
6147 ;; FIXME: how to name a single frame in XEmacs???
6148 (unless (featurep 'xemacs)
6149 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6151 ;;;; Structure editing
6153 ;;; Inserting headlines
6155 (defun org-insert-heading (&optional force-heading)
6156 "Insert a new heading or item with same depth at point.
6157 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6158 If point is at the beginning of a headline, insert a sibling before the
6159 current headline. If point is not at the beginning, do not split the line,
6160 but create the new hedline after the current line."
6161 (interactive "P")
6162 (if (= (buffer-size) 0)
6163 (insert "\n* ")
6164 (when (or force-heading (not (org-insert-item)))
6165 (let* ((head (save-excursion
6166 (condition-case nil
6167 (progn
6168 (org-back-to-heading)
6169 (match-string 0))
6170 (error "*"))))
6171 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6172 pos)
6173 (cond
6174 ((and (org-on-heading-p) (bolp)
6175 (or (bobp)
6176 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6177 ;; insert before the current line
6178 (open-line (if blank 2 1)))
6179 ((and (bolp)
6180 (or (bobp)
6181 (save-excursion
6182 (backward-char 1) (not (org-invisible-p)))))
6183 ;; insert right here
6184 nil)
6186 ;; in the middle of the line
6187 (org-show-entry)
6188 (end-of-line 1)
6189 (newline (if blank 2 1))))
6190 (insert head) (just-one-space)
6191 (setq pos (point))
6192 (end-of-line 1)
6193 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6194 (run-hooks 'org-insert-heading-hook)))))
6196 (defun org-insert-heading-after-current ()
6197 "Insert a new heading with same level as current, after current subtree."
6198 (interactive)
6199 (org-back-to-heading)
6200 (org-insert-heading)
6201 (org-move-subtree-down)
6202 (end-of-line 1))
6204 (defun org-insert-todo-heading (arg)
6205 "Insert a new heading with the same level and TODO state as current heading.
6206 If the heading has no TODO state, or if the state is DONE, use the first
6207 state (TODO by default). Also with prefix arg, force first state."
6208 (interactive "P")
6209 (when (not (org-insert-item 'checkbox))
6210 (org-insert-heading)
6211 (save-excursion
6212 (org-back-to-heading)
6213 (outline-previous-heading)
6214 (looking-at org-todo-line-regexp))
6215 (if (or arg
6216 (not (match-beginning 2))
6217 (member (match-string 2) org-done-keywords))
6218 (insert (car org-todo-keywords-1) " ")
6219 (insert (match-string 2) " "))))
6221 (defun org-insert-subheading (arg)
6222 "Insert a new subheading and demote it.
6223 Works for outline headings and for plain lists alike."
6224 (interactive "P")
6225 (org-insert-heading arg)
6226 (cond
6227 ((org-on-heading-p) (org-do-demote))
6228 ((org-at-item-p) (org-indent-item 1))))
6230 (defun org-insert-todo-subheading (arg)
6231 "Insert a new subheading with TODO keyword or checkbox and demote it.
6232 Works for outline headings and for plain lists alike."
6233 (interactive "P")
6234 (org-insert-todo-heading arg)
6235 (cond
6236 ((org-on-heading-p) (org-do-demote))
6237 ((org-at-item-p) (org-indent-item 1))))
6239 ;;; Promotion and Demotion
6241 (defun org-promote-subtree ()
6242 "Promote the entire subtree.
6243 See also `org-promote'."
6244 (interactive)
6245 (save-excursion
6246 (org-map-tree 'org-promote))
6247 (org-fix-position-after-promote))
6249 (defun org-demote-subtree ()
6250 "Demote the entire subtree. See `org-demote'.
6251 See also `org-promote'."
6252 (interactive)
6253 (save-excursion
6254 (org-map-tree 'org-demote))
6255 (org-fix-position-after-promote))
6258 (defun org-do-promote ()
6259 "Promote the current heading higher up the tree.
6260 If the region is active in `transient-mark-mode', promote all headings
6261 in the region."
6262 (interactive)
6263 (save-excursion
6264 (if (org-region-active-p)
6265 (org-map-region 'org-promote (region-beginning) (region-end))
6266 (org-promote)))
6267 (org-fix-position-after-promote))
6269 (defun org-do-demote ()
6270 "Demote the current heading lower down the tree.
6271 If the region is active in `transient-mark-mode', demote all headings
6272 in the region."
6273 (interactive)
6274 (save-excursion
6275 (if (org-region-active-p)
6276 (org-map-region 'org-demote (region-beginning) (region-end))
6277 (org-demote)))
6278 (org-fix-position-after-promote))
6280 (defun org-fix-position-after-promote ()
6281 "Make sure that after pro/demotion cursor position is right."
6282 (let ((pos (point)))
6283 (when (save-excursion
6284 (beginning-of-line 1)
6285 (looking-at org-todo-line-regexp)
6286 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6287 (cond ((eobp) (insert " "))
6288 ((eolp) (insert " "))
6289 ((equal (char-after) ?\ ) (forward-char 1))))))
6291 (defun org-reduced-level (l)
6292 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6294 (defun org-get-legal-level (level &optional change)
6295 "Rectify a level change under the influence of `org-odd-levels-only'
6296 LEVEL is a current level, CHANGE is by how much the level should be
6297 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6298 even level numbers will become the next higher odd number."
6299 (if org-odd-levels-only
6300 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6301 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6302 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6303 (max 1 (+ level change))))
6305 (defun org-promote ()
6306 "Promote the current heading higher up the tree.
6307 If the region is active in `transient-mark-mode', promote all headings
6308 in the region."
6309 (org-back-to-heading t)
6310 (let* ((level (save-match-data (funcall outline-level)))
6311 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6312 (diff (abs (- level (length up-head) -1))))
6313 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6314 (replace-match up-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-demote ()
6320 "Demote the current heading lower down the tree.
6321 If the region is active in `transient-mark-mode', demote all headings
6322 in the region."
6323 (org-back-to-heading t)
6324 (let* ((level (save-match-data (funcall outline-level)))
6325 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6326 (diff (abs (- level (length down-head) -1))))
6327 (replace-match down-head nil t)
6328 ;; Fixup tag positioning
6329 (and org-auto-align-tags (org-set-tags nil t))
6330 (if org-adapt-indentation (org-fixup-indentation diff))))
6332 (defun org-map-tree (fun)
6333 "Call FUN for every heading underneath the current one."
6334 (org-back-to-heading)
6335 (let ((level (funcall outline-level)))
6336 (save-excursion
6337 (funcall fun)
6338 (while (and (progn
6339 (outline-next-heading)
6340 (> (funcall outline-level) level))
6341 (not (eobp)))
6342 (funcall fun)))))
6344 (defun org-map-region (fun beg end)
6345 "Call FUN for every heading between BEG and END."
6346 (let ((org-ignore-region t))
6347 (save-excursion
6348 (setq end (copy-marker end))
6349 (goto-char beg)
6350 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6351 (< (point) end))
6352 (funcall fun))
6353 (while (and (progn
6354 (outline-next-heading)
6355 (< (point) end))
6356 (not (eobp)))
6357 (funcall fun)))))
6359 (defun org-fixup-indentation (diff)
6360 "Change the indentation in the current entry by DIFF
6361 However, if any line in the current entry has no indentation, or if it
6362 would end up with no indentation after the change, nothing at all is done."
6363 (save-excursion
6364 (let ((end (save-excursion (outline-next-heading)
6365 (point-marker)))
6366 (prohibit (if (> diff 0)
6367 "^\\S-"
6368 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6369 col)
6370 (unless (save-excursion (end-of-line 1)
6371 (re-search-forward prohibit end t))
6372 (while (and (< (point) end)
6373 (re-search-forward "^[ \t]+" end t))
6374 (goto-char (match-end 0))
6375 (setq col (current-column))
6376 (if (< diff 0) (replace-match ""))
6377 (indent-to (+ diff col))))
6378 (move-marker end nil))))
6380 (defun org-convert-to-odd-levels ()
6381 "Convert an org-mode file with all levels allowed to one with odd levels.
6382 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6383 level 5 etc."
6384 (interactive)
6385 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6386 (let ((org-odd-levels-only nil) n)
6387 (save-excursion
6388 (goto-char (point-min))
6389 (while (re-search-forward "^\\*\\*+ " nil t)
6390 (setq n (- (length (match-string 0)) 2))
6391 (while (>= (setq n (1- n)) 0)
6392 (org-demote))
6393 (end-of-line 1))))))
6396 (defun org-convert-to-oddeven-levels ()
6397 "Convert an org-mode file with only odd levels to one with odd and even levels.
6398 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6399 section with an even level, conversion would destroy the structure of the file. An error
6400 is signaled in this case."
6401 (interactive)
6402 (goto-char (point-min))
6403 ;; First check if there are no even levels
6404 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6405 (org-show-context t)
6406 (error "Not all levels are odd in this file. Conversion not possible."))
6407 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6408 (let ((org-odd-levels-only nil) n)
6409 (save-excursion
6410 (goto-char (point-min))
6411 (while (re-search-forward "^\\*\\*+ " nil t)
6412 (setq n (/ (1- (length (match-string 0))) 2))
6413 (while (>= (setq n (1- n)) 0)
6414 (org-promote))
6415 (end-of-line 1))))))
6417 (defun org-tr-level (n)
6418 "Make N odd if required."
6419 (if org-odd-levels-only (1+ (/ n 2)) n))
6421 ;;; Vertical tree motion, cutting and pasting of subtrees
6423 (defun org-move-subtree-up (&optional arg)
6424 "Move the current subtree up past ARG headlines of the same level."
6425 (interactive "p")
6426 (org-move-subtree-down (- (prefix-numeric-value arg))))
6428 (defun org-move-subtree-down (&optional arg)
6429 "Move the current subtree down past ARG headlines of the same level."
6430 (interactive "p")
6431 (setq arg (prefix-numeric-value arg))
6432 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6433 'outline-get-last-sibling))
6434 (ins-point (make-marker))
6435 (cnt (abs arg))
6436 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6437 ;; Select the tree
6438 (org-back-to-heading)
6439 (setq beg0 (point))
6440 (save-excursion
6441 (setq ne-beg (org-back-over-empty-lines))
6442 (setq beg (point)))
6443 (save-match-data
6444 (save-excursion (outline-end-of-heading)
6445 (setq folded (org-invisible-p)))
6446 (outline-end-of-subtree))
6447 (outline-next-heading)
6448 (setq ne-end (org-back-over-empty-lines))
6449 (setq end (point))
6450 (goto-char beg0)
6451 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6452 ;; include less whitespace
6453 (save-excursion
6454 (goto-char beg)
6455 (forward-line (- ne-beg ne-end))
6456 (setq beg (point))))
6457 ;; Find insertion point, with error handling
6458 (while (> cnt 0)
6459 (or (and (funcall movfunc) (looking-at outline-regexp))
6460 (progn (goto-char beg0)
6461 (error "Cannot move past superior level or buffer limit")))
6462 (setq cnt (1- cnt)))
6463 (if (> arg 0)
6464 ;; Moving forward - still need to move over subtree
6465 (progn (org-end-of-subtree t t)
6466 (save-excursion
6467 (org-back-over-empty-lines)
6468 (or (bolp) (newline)))))
6469 (setq ne-ins (org-back-over-empty-lines))
6470 (move-marker ins-point (point))
6471 (setq txt (buffer-substring beg end))
6472 (delete-region beg end)
6473 (outline-flag-region (1- beg) beg nil)
6474 (outline-flag-region (1- (point)) (point) nil)
6475 (insert txt)
6476 (or (bolp) (insert "\n"))
6477 (setq ins-end (point))
6478 (goto-char ins-point)
6479 (org-skip-whitespace)
6480 (when (and (< arg 0)
6481 (org-first-sibling-p)
6482 (> ne-ins ne-beg))
6483 ;; Move whitespace back to beginning
6484 (save-excursion
6485 (goto-char ins-end)
6486 (let ((kill-whole-line t))
6487 (kill-line (- ne-ins ne-beg)) (point)))
6488 (insert (make-string (- ne-ins ne-beg) ?\n)))
6489 (move-marker ins-point nil)
6490 (org-compact-display-after-subtree-move)
6491 (unless folded
6492 (org-show-entry)
6493 (show-children)
6494 (org-cycle-hide-drawers 'children))))
6496 (defvar org-subtree-clip ""
6497 "Clipboard for cut and paste of subtrees.
6498 This is actually only a copy of the kill, because we use the normal kill
6499 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6501 (defvar org-subtree-clip-folded nil
6502 "Was the last copied subtree folded?
6503 This is used to fold the tree back after pasting.")
6505 (defun org-cut-subtree (&optional n)
6506 "Cut the current subtree into the clipboard.
6507 With prefix arg N, cut this many sequential subtrees.
6508 This is a short-hand for marking the subtree and then cutting it."
6509 (interactive "p")
6510 (org-copy-subtree n 'cut))
6512 (defun org-copy-subtree (&optional n cut)
6513 "Cut the current subtree into the clipboard.
6514 With prefix arg N, cut this many sequential subtrees.
6515 This is a short-hand for marking the subtree and then copying it.
6516 If CUT is non-nil, actually cut the subtree."
6517 (interactive "p")
6518 (let (beg end folded (beg0 (point)))
6519 (if (interactive-p)
6520 (org-back-to-heading nil) ; take what looks like a subtree
6521 (org-back-to-heading t)) ; take what is really there
6522 (org-back-over-empty-lines)
6523 (setq beg (point))
6524 (skip-chars-forward " \t\r\n")
6525 (save-match-data
6526 (save-excursion (outline-end-of-heading)
6527 (setq folded (org-invisible-p)))
6528 (condition-case nil
6529 (outline-forward-same-level (1- n))
6530 (error nil))
6531 (org-end-of-subtree t t))
6532 (org-back-over-empty-lines)
6533 (setq end (point))
6534 (goto-char beg0)
6535 (when (> end beg)
6536 (setq org-subtree-clip-folded folded)
6537 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6538 (setq org-subtree-clip (current-kill 0))
6539 (message "%s: Subtree(s) with %d characters"
6540 (if cut "Cut" "Copied")
6541 (length org-subtree-clip)))))
6543 (defun org-paste-subtree (&optional level tree)
6544 "Paste the clipboard as a subtree, with modification of headline level.
6545 The entire subtree is promoted or demoted in order to match a new headline
6546 level. By default, the new level is derived from the visible headings
6547 before and after the insertion point, and taken to be the inferior headline
6548 level of the two. So if the previous visible heading is level 3 and the
6549 next is level 4 (or vice versa), level 4 will be used for insertion.
6550 This makes sure that the subtree remains an independent subtree and does
6551 not swallow low level entries.
6553 You can also force a different level, either by using a numeric prefix
6554 argument, or by inserting the heading marker by hand. For example, if the
6555 cursor is after \"*****\", then the tree will be shifted to level 5.
6557 If you want to insert the tree as is, just use \\[yank].
6559 If optional TREE is given, use this text instead of the kill ring."
6560 (interactive "P")
6561 (unless (org-kill-is-subtree-p tree)
6562 (error "%s"
6563 (substitute-command-keys
6564 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6565 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6566 (^re (concat "^\\(" outline-regexp "\\)"))
6567 (re (concat "\\(" outline-regexp "\\)"))
6568 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6570 (old-level (if (string-match ^re txt)
6571 (- (match-end 0) (match-beginning 0) 1)
6572 -1))
6573 (force-level (cond (level (prefix-numeric-value level))
6574 ((string-match
6575 ^re_ (buffer-substring (point-at-bol) (point)))
6576 (- (match-end 1) (match-beginning 1)))
6577 (t nil)))
6578 (previous-level (save-excursion
6579 (condition-case nil
6580 (progn
6581 (outline-previous-visible-heading 1)
6582 (if (looking-at re)
6583 (- (match-end 0) (match-beginning 0) 1)
6585 (error 1))))
6586 (next-level (save-excursion
6587 (condition-case nil
6588 (progn
6589 (or (looking-at outline-regexp)
6590 (outline-next-visible-heading 1))
6591 (if (looking-at re)
6592 (- (match-end 0) (match-beginning 0) 1)
6594 (error 1))))
6595 (new-level (or force-level (max previous-level next-level)))
6596 (shift (if (or (= old-level -1)
6597 (= new-level -1)
6598 (= old-level new-level))
6600 (- new-level old-level)))
6601 (delta (if (> shift 0) -1 1))
6602 (func (if (> shift 0) 'org-demote 'org-promote))
6603 (org-odd-levels-only nil)
6604 beg end)
6605 ;; Remove the forced level indicator
6606 (if force-level
6607 (delete-region (point-at-bol) (point)))
6608 ;; Paste
6609 (beginning-of-line 1)
6610 (org-back-over-empty-lines) ;; FIXME: correct fix????
6611 (setq beg (point))
6612 (insert-before-markers txt) ;; FIXME: correct fix????
6613 (unless (string-match "\n\\'" txt) (insert "\n"))
6614 (setq end (point))
6615 (goto-char beg)
6616 (skip-chars-forward " \t\n\r")
6617 (setq beg (point))
6618 ;; Shift if necessary
6619 (unless (= shift 0)
6620 (save-restriction
6621 (narrow-to-region beg end)
6622 (while (not (= shift 0))
6623 (org-map-region func (point-min) (point-max))
6624 (setq shift (+ delta shift)))
6625 (goto-char (point-min))))
6626 (when (interactive-p)
6627 (message "Clipboard pasted as level %d subtree" new-level))
6628 (if (and kill-ring
6629 (eq org-subtree-clip (current-kill 0))
6630 org-subtree-clip-folded)
6631 ;; The tree was folded before it was killed/copied
6632 (hide-subtree))))
6634 (defun org-kill-is-subtree-p (&optional txt)
6635 "Check if the current kill is an outline subtree, or a set of trees.
6636 Returns nil if kill does not start with a headline, or if the first
6637 headline level is not the largest headline level in the tree.
6638 So this will actually accept several entries of equal levels as well,
6639 which is OK for `org-paste-subtree'.
6640 If optional TXT is given, check this string instead of the current kill."
6641 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6642 (start-level (and kill
6643 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6644 org-outline-regexp "\\)")
6645 kill)
6646 (- (match-end 2) (match-beginning 2) 1)))
6647 (re (concat "^" org-outline-regexp))
6648 (start (1+ (match-beginning 2))))
6649 (if (not start-level)
6650 (progn
6651 nil) ;; does not even start with a heading
6652 (catch 'exit
6653 (while (setq start (string-match re kill (1+ start)))
6654 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6655 (throw 'exit nil)))
6656 t))))
6658 (defun org-narrow-to-subtree ()
6659 "Narrow buffer to the current subtree."
6660 (interactive)
6661 (save-excursion
6662 (narrow-to-region
6663 (progn (org-back-to-heading) (point))
6664 (progn (org-end-of-subtree t t) (point)))))
6667 ;;; Outline Sorting
6669 (defun org-sort (with-case)
6670 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6671 Optional argument WITH-CASE means sort case-sensitively."
6672 (interactive "P")
6673 (if (org-at-table-p)
6674 (org-call-with-arg 'org-table-sort-lines with-case)
6675 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6677 (defvar org-priority-regexp) ; defined later in the file
6679 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6680 "Sort entries on a certain level of an outline tree.
6681 If there is an active region, the entries in the region are sorted.
6682 Else, if the cursor is before the first entry, sort the top-level items.
6683 Else, the children of the entry at point are sorted.
6685 Sorting can be alphabetically, numerically, and by date/time as given by
6686 the first time stamp in the entry. The command prompts for the sorting
6687 type unless it has been given to the function through the SORTING-TYPE
6688 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6689 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6690 called with point at the beginning of the record. It must return either
6691 a string or a number that should serve as the sorting key for that record.
6693 Comparing entries ignores case by default. However, with an optional argument
6694 WITH-CASE, the sorting considers case as well."
6695 (interactive "P")
6696 (let ((case-func (if with-case 'identity 'downcase))
6697 start beg end stars re re2
6698 txt what tmp plain-list-p)
6699 ;; Find beginning and end of region to sort
6700 (cond
6701 ((org-region-active-p)
6702 ;; we will sort the region
6703 (setq end (region-end)
6704 what "region")
6705 (goto-char (region-beginning))
6706 (if (not (org-on-heading-p)) (outline-next-heading))
6707 (setq start (point)))
6708 ((org-at-item-p)
6709 ;; we will sort this plain list
6710 (org-beginning-of-item-list) (setq start (point))
6711 (org-end-of-item-list) (setq end (point))
6712 (goto-char start)
6713 (setq plain-list-p t
6714 what "plain list"))
6715 ((or (org-on-heading-p)
6716 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6717 ;; we will sort the children of the current headline
6718 (org-back-to-heading)
6719 (setq start (point)
6720 end (progn (org-end-of-subtree t t)
6721 (org-back-over-empty-lines)
6722 (point))
6723 what "children")
6724 (goto-char start)
6725 (show-subtree)
6726 (outline-next-heading))
6728 ;; we will sort the top-level entries in this file
6729 (goto-char (point-min))
6730 (or (org-on-heading-p) (outline-next-heading))
6731 (setq start (point) end (point-max) what "top-level")
6732 (goto-char start)
6733 (show-all)))
6735 (setq beg (point))
6736 (if (>= beg end) (error "Nothing to sort"))
6738 (unless plain-list-p
6739 (looking-at "\\(\\*+\\)")
6740 (setq stars (match-string 1)
6741 re (concat "^" (regexp-quote stars) " +")
6742 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6743 txt (buffer-substring beg end))
6744 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6745 (if (and (not (equal stars "*")) (string-match re2 txt))
6746 (error "Region to sort contains a level above the first entry")))
6748 (unless sorting-type
6749 (message
6750 (if plain-list-p
6751 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6752 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6753 what)
6754 (setq sorting-type (read-char-exclusive))
6756 (and (= (downcase sorting-type) ?f)
6757 (setq getkey-func
6758 (completing-read "Sort using function: "
6759 obarray 'fboundp t nil nil))
6760 (setq getkey-func (intern getkey-func)))
6762 (and (= (downcase sorting-type) ?r)
6763 (setq property
6764 (completing-read "Property: "
6765 (mapcar 'list (org-buffer-property-keys t))
6766 nil t))))
6768 (message "Sorting entries...")
6770 (save-restriction
6771 (narrow-to-region start end)
6773 (let ((dcst (downcase sorting-type))
6774 (now (current-time)))
6775 (sort-subr
6776 (/= dcst sorting-type)
6777 ;; This function moves to the beginning character of the "record" to
6778 ;; be sorted.
6779 (if plain-list-p
6780 (lambda nil
6781 (if (org-at-item-p) t (goto-char (point-max))))
6782 (lambda nil
6783 (if (re-search-forward re nil t)
6784 (goto-char (match-beginning 0))
6785 (goto-char (point-max)))))
6786 ;; This function moves to the last character of the "record" being
6787 ;; sorted.
6788 (if plain-list-p
6789 'org-end-of-item
6790 (lambda nil
6791 (save-match-data
6792 (condition-case nil
6793 (outline-forward-same-level 1)
6794 (error
6795 (goto-char (point-max)))))))
6797 ;; This function returns the value that gets sorted against.
6798 (if plain-list-p
6799 (lambda nil
6800 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6801 (cond
6802 ((= dcst ?n)
6803 (string-to-number (buffer-substring (match-end 0)
6804 (point-at-eol))))
6805 ((= dcst ?a)
6806 (buffer-substring (match-end 0) (point-at-eol)))
6807 ((= dcst ?t)
6808 (if (re-search-forward org-ts-regexp
6809 (point-at-eol) t)
6810 (org-time-string-to-time (match-string 0))
6811 now))
6812 ((= dcst ?f)
6813 (if getkey-func
6814 (progn
6815 (setq tmp (funcall getkey-func))
6816 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6817 tmp)
6818 (error "Invalid key function `%s'" getkey-func)))
6819 (t (error "Invalid sorting type `%c'" sorting-type)))))
6820 (lambda nil
6821 (cond
6822 ((= dcst ?n)
6823 (if (looking-at outline-regexp)
6824 (string-to-number (buffer-substring (match-end 0)
6825 (point-at-eol)))
6826 nil))
6827 ((= dcst ?a)
6828 (funcall case-func (buffer-substring (point-at-bol)
6829 (point-at-eol))))
6830 ((= dcst ?t)
6831 (if (re-search-forward org-ts-regexp
6832 (save-excursion
6833 (forward-line 2)
6834 (point)) t)
6835 (org-time-string-to-time (match-string 0))
6836 now))
6837 ((= dcst ?p)
6838 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6839 (string-to-char (match-string 2))
6840 org-default-priority))
6841 ((= dcst ?r)
6842 (or (org-entry-get nil property) ""))
6843 ((= dcst ?f)
6844 (if getkey-func
6845 (progn
6846 (setq tmp (funcall getkey-func))
6847 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6848 tmp)
6849 (error "Invalid key function `%s'" getkey-func)))
6850 (t (error "Invalid sorting type `%c'" sorting-type)))))
6852 (cond
6853 ((= dcst ?a) 'string<)
6854 ((= dcst ?t) 'time-less-p)
6855 (t nil)))))
6856 (message "Sorting entries...done")))
6858 (defun org-do-sort (table what &optional with-case sorting-type)
6859 "Sort TABLE of WHAT according to SORTING-TYPE.
6860 The user will be prompted for the SORTING-TYPE if the call to this
6861 function does not specify it. WHAT is only for the prompt, to indicate
6862 what is being sorted. The sorting key will be extracted from
6863 the car of the elements of the table.
6864 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6865 (unless sorting-type
6866 (message
6867 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6868 what)
6869 (setq sorting-type (read-char-exclusive)))
6870 (let ((dcst (downcase sorting-type))
6871 extractfun comparefun)
6872 ;; Define the appropriate functions
6873 (cond
6874 ((= dcst ?n)
6875 (setq extractfun 'string-to-number
6876 comparefun (if (= dcst sorting-type) '< '>)))
6877 ((= dcst ?a)
6878 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6879 (lambda(x) (downcase (org-sort-remove-invisible x))))
6880 comparefun (if (= dcst sorting-type)
6881 'string<
6882 (lambda (a b) (and (not (string< a b))
6883 (not (string= a b)))))))
6884 ((= dcst ?t)
6885 (setq extractfun
6886 (lambda (x)
6887 (if (string-match org-ts-regexp x)
6888 (time-to-seconds
6889 (org-time-string-to-time (match-string 0 x)))
6891 comparefun (if (= dcst sorting-type) '< '>)))
6892 (t (error "Invalid sorting type `%c'" sorting-type)))
6894 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6895 table)
6896 (lambda (a b) (funcall comparefun (car a) (car b))))))
6898 ;;;; Plain list items, including checkboxes
6900 ;;; Plain list items
6902 (defun org-at-item-p ()
6903 "Is point in a line starting a hand-formatted item?"
6904 (let ((llt org-plain-list-ordered-item-terminator))
6905 (save-excursion
6906 (goto-char (point-at-bol))
6907 (looking-at
6908 (cond
6909 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6910 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6911 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6912 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6914 (defun org-in-item-p ()
6915 "It the cursor inside a plain list item.
6916 Does not have to be the first line."
6917 (save-excursion
6918 (condition-case nil
6919 (progn
6920 (org-beginning-of-item)
6921 (org-at-item-p)
6923 (error nil))))
6925 (defun org-insert-item (&optional checkbox)
6926 "Insert a new item at the current level.
6927 Return t when things worked, nil when we are not in an item."
6928 (when (save-excursion
6929 (condition-case nil
6930 (progn
6931 (org-beginning-of-item)
6932 (org-at-item-p)
6933 (if (org-invisible-p) (error "Invisible item"))
6935 (error nil)))
6936 (let* ((bul (match-string 0))
6937 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6938 (match-end 0)))
6939 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6940 pos)
6941 (cond
6942 ((and (org-at-item-p) (<= (point) eow))
6943 ;; before the bullet
6944 (beginning-of-line 1)
6945 (open-line (if blank 2 1)))
6946 ((<= (point) eow)
6947 (beginning-of-line 1))
6948 (t (newline (if blank 2 1))))
6949 (insert bul (if checkbox "[ ]" ""))
6950 (just-one-space)
6951 (setq pos (point))
6952 (end-of-line 1)
6953 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6954 (org-maybe-renumber-ordered-list)
6955 (and checkbox (org-update-checkbox-count-maybe))
6958 ;;; Checkboxes
6960 (defun org-at-item-checkbox-p ()
6961 "Is point at a line starting a plain-list item with a checklet?"
6962 (and (org-at-item-p)
6963 (save-excursion
6964 (goto-char (match-end 0))
6965 (skip-chars-forward " \t")
6966 (looking-at "\\[[- X]\\]"))))
6968 (defun org-toggle-checkbox (&optional arg)
6969 "Toggle the checkbox in the current line."
6970 (interactive "P")
6971 (catch 'exit
6972 (let (beg end status (firstnew 'unknown))
6973 (cond
6974 ((org-region-active-p)
6975 (setq beg (region-beginning) end (region-end)))
6976 ((org-on-heading-p)
6977 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6978 ((org-at-item-checkbox-p)
6979 (let ((pos (point)))
6980 (replace-match
6981 (cond (arg "[-]")
6982 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6983 (t "[ ]"))
6984 t t)
6985 (goto-char pos))
6986 (throw 'exit t))
6987 (t (error "Not at a checkbox or heading, and no active region")))
6988 (save-excursion
6989 (goto-char beg)
6990 (while (< (point) end)
6991 (when (org-at-item-checkbox-p)
6992 (setq status (equal (match-string 0) "[X]"))
6993 (when (eq firstnew 'unknown)
6994 (setq firstnew (not status)))
6995 (replace-match
6996 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6997 (beginning-of-line 2)))))
6998 (org-update-checkbox-count-maybe))
7000 (defun org-update-checkbox-count-maybe ()
7001 "Update checkbox statistics unless turned off by user."
7002 (when org-provide-checkbox-statistics
7003 (org-update-checkbox-count)))
7005 (defun org-update-checkbox-count (&optional all)
7006 "Update the checkbox statistics in the current section.
7007 This will find all statistic cookies like [57%] and [6/12] and update them
7008 with the current numbers. With optional prefix argument ALL, do this for
7009 the whole buffer."
7010 (interactive "P")
7011 (save-excursion
7012 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7013 (beg (condition-case nil
7014 (progn (outline-back-to-heading) (point))
7015 (error (point-min))))
7016 (end (move-marker (make-marker)
7017 (progn (outline-next-heading) (point))))
7018 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7019 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7020 (re-find (concat re "\\|" re-box))
7021 beg-cookie end-cookie is-percent c-on c-off lim
7022 eline curr-ind next-ind continue-from startsearch
7023 (cstat 0)
7025 (when all
7026 (goto-char (point-min))
7027 (outline-next-heading)
7028 (setq beg (point) end (point-max)))
7029 (goto-char end)
7030 ;; find each statistic cookie
7031 (while (re-search-backward re-find beg t)
7032 (setq beg-cookie (match-beginning 1)
7033 end-cookie (match-end 1)
7034 cstat (+ cstat (if end-cookie 1 0))
7035 startsearch (point-at-eol)
7036 continue-from (point-at-bol)
7037 is-percent (match-beginning 2)
7038 lim (cond
7039 ((org-on-heading-p) (outline-next-heading) (point))
7040 ((org-at-item-p) (org-end-of-item) (point))
7041 (t nil))
7042 c-on 0
7043 c-off 0)
7044 (when lim
7045 ;; find first checkbox for this cookie and gather
7046 ;; statistics from all that are at this indentation level
7047 (goto-char startsearch)
7048 (if (re-search-forward re-box lim t)
7049 (progn
7050 (org-beginning-of-item)
7051 (setq curr-ind (org-get-indentation))
7052 (setq next-ind curr-ind)
7053 (while (= curr-ind next-ind)
7054 (save-excursion (end-of-line) (setq eline (point)))
7055 (if (re-search-forward re-box eline t)
7056 (if (member (match-string 2) '("[ ]" "[-]"))
7057 (setq c-off (1+ c-off))
7058 (setq c-on (1+ c-on))
7061 (org-end-of-item)
7062 (setq next-ind (org-get-indentation))
7064 (goto-char continue-from)
7065 ;; update cookie
7066 (when end-cookie
7067 (delete-region beg-cookie end-cookie)
7068 (goto-char beg-cookie)
7069 (insert
7070 (if is-percent
7071 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7072 (format "[%d/%d]" c-on (+ c-on c-off)))))
7073 ;; update items checkbox if it has one
7074 (when (org-at-item-p)
7075 (org-beginning-of-item)
7076 (when (and (> (+ c-on c-off) 0)
7077 (re-search-forward re-box (point-at-eol) t))
7078 (setq beg-cookie (match-beginning 2)
7079 end-cookie (match-end 2))
7080 (delete-region beg-cookie end-cookie)
7081 (goto-char beg-cookie)
7082 (cond ((= c-off 0) (insert "[X]"))
7083 ((= c-on 0) (insert "[ ]"))
7084 (t (insert "[-]")))
7086 (goto-char continue-from))
7087 (when (interactive-p)
7088 (message "Checkbox satistics updated %s (%d places)"
7089 (if all "in entire file" "in current outline entry") cstat)))))
7091 (defun org-get-checkbox-statistics-face ()
7092 "Select the face for checkbox statistics.
7093 The face will be `org-done' when all relevant boxes are checked. Otherwise
7094 it will be `org-todo'."
7095 (if (match-end 1)
7096 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7097 (if (and (> (match-end 2) (match-beginning 2))
7098 (equal (match-string 2) (match-string 3)))
7099 'org-done
7100 'org-todo)))
7102 (defun org-get-indentation (&optional line)
7103 "Get the indentation of the current line, interpreting tabs.
7104 When LINE is given, assume it represents a line and compute its indentation."
7105 (if line
7106 (if (string-match "^ *" (org-remove-tabs line))
7107 (match-end 0))
7108 (save-excursion
7109 (beginning-of-line 1)
7110 (skip-chars-forward " \t")
7111 (current-column))))
7113 (defun org-remove-tabs (s &optional width)
7114 "Replace tabulators in S with spaces.
7115 Assumes that s is a single line, starting in column 0."
7116 (setq width (or width tab-width))
7117 (while (string-match "\t" s)
7118 (setq s (replace-match
7119 (make-string
7120 (- (* width (/ (+ (match-beginning 0) width) width))
7121 (match-beginning 0)) ?\ )
7122 t t s)))
7125 (defun org-fix-indentation (line ind)
7126 "Fix indentation in LINE.
7127 IND is a cons cell with target and minimum indentation.
7128 If the current indenation in LINE is smaller than the minimum,
7129 leave it alone. If it is larger than ind, set it to the target."
7130 (let* ((l (org-remove-tabs line))
7131 (i (org-get-indentation l))
7132 (i1 (car ind)) (i2 (cdr ind)))
7133 (if (>= i i2) (setq l (substring line i2)))
7134 (if (> i1 0)
7135 (concat (make-string i1 ?\ ) l)
7136 l)))
7138 (defcustom org-empty-line-terminates-plain-lists nil
7139 "Non-nil means, an empty line ends all plain list levels.
7140 When nil, empty lines are part of the preceeding item."
7141 :group 'org-plain-lists
7142 :type 'boolean)
7144 (defun org-beginning-of-item ()
7145 "Go to the beginning of the current hand-formatted item.
7146 If the cursor is not in an item, throw an error."
7147 (interactive)
7148 (let ((pos (point))
7149 (limit (save-excursion
7150 (condition-case nil
7151 (progn
7152 (org-back-to-heading)
7153 (beginning-of-line 2) (point))
7154 (error (point-min)))))
7155 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7156 ind ind1)
7157 (if (org-at-item-p)
7158 (beginning-of-line 1)
7159 (beginning-of-line 1)
7160 (skip-chars-forward " \t")
7161 (setq ind (current-column))
7162 (if (catch 'exit
7163 (while t
7164 (beginning-of-line 0)
7165 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7167 (if (looking-at "[ \t]*$")
7168 (setq ind1 ind-empty)
7169 (skip-chars-forward " \t")
7170 (setq ind1 (current-column)))
7171 (if (< ind1 ind)
7172 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7174 (goto-char pos)
7175 (error "Not in an item")))))
7177 (defun org-end-of-item ()
7178 "Go to the end of the current hand-formatted item.
7179 If the cursor is not in an item, throw an error."
7180 (interactive)
7181 (let* ((pos (point))
7182 ind1
7183 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7184 (limit (save-excursion (outline-next-heading) (point)))
7185 (ind (save-excursion
7186 (org-beginning-of-item)
7187 (skip-chars-forward " \t")
7188 (current-column)))
7189 (end (catch 'exit
7190 (while t
7191 (beginning-of-line 2)
7192 (if (eobp) (throw 'exit (point)))
7193 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7194 (if (looking-at "[ \t]*$")
7195 (setq ind1 ind-empty)
7196 (skip-chars-forward " \t")
7197 (setq ind1 (current-column)))
7198 (if (<= ind1 ind)
7199 (throw 'exit (point-at-bol)))))))
7200 (if end
7201 (goto-char end)
7202 (goto-char pos)
7203 (error "Not in an item"))))
7205 (defun org-next-item ()
7206 "Move to the beginning of the next item in the current plain list.
7207 Error if not at a plain list, or if this is the last item in the list."
7208 (interactive)
7209 (let (ind ind1 (pos (point)))
7210 (org-beginning-of-item)
7211 (setq ind (org-get-indentation))
7212 (org-end-of-item)
7213 (setq ind1 (org-get-indentation))
7214 (unless (and (org-at-item-p) (= ind ind1))
7215 (goto-char pos)
7216 (error "On last item"))))
7218 (defun org-previous-item ()
7219 "Move to the beginning of the previous item in the current plain list.
7220 Error if not at a plain list, or if this is the first item in the list."
7221 (interactive)
7222 (let (beg ind ind1 (pos (point)))
7223 (org-beginning-of-item)
7224 (setq beg (point))
7225 (setq ind (org-get-indentation))
7226 (goto-char beg)
7227 (catch 'exit
7228 (while t
7229 (beginning-of-line 0)
7230 (if (looking-at "[ \t]*$")
7232 (if (<= (setq ind1 (org-get-indentation)) ind)
7233 (throw 'exit t)))))
7234 (condition-case nil
7235 (if (or (not (org-at-item-p))
7236 (< ind1 (1- ind)))
7237 (error "")
7238 (org-beginning-of-item))
7239 (error (goto-char pos)
7240 (error "On first item")))))
7242 (defun org-first-list-item-p ()
7243 "Is this heading the item in a plain list?"
7244 (unless (org-at-item-p)
7245 (error "Not at a plain list item"))
7246 (org-beginning-of-item)
7247 (= (point) (save-excursion (org-beginning-of-item-list))))
7249 (defun org-move-item-down ()
7250 "Move the plain list item at point down, i.e. swap with following item.
7251 Subitems (items with larger indentation) are considered part of the item,
7252 so this really moves item trees."
7253 (interactive)
7254 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7255 (org-beginning-of-item)
7256 (setq beg0 (point))
7257 (save-excursion
7258 (setq ne-beg (org-back-over-empty-lines))
7259 (setq beg (point)))
7260 (goto-char beg0)
7261 (setq ind (org-get-indentation))
7262 (org-end-of-item)
7263 (setq end0 (point))
7264 (setq ind1 (org-get-indentation))
7265 (setq ne-end (org-back-over-empty-lines))
7266 (setq end (point))
7267 (goto-char beg0)
7268 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7269 ;; include less whitespace
7270 (save-excursion
7271 (goto-char beg)
7272 (forward-line (- ne-beg ne-end))
7273 (setq beg (point))))
7274 (goto-char end0)
7275 (if (and (org-at-item-p) (= ind ind1))
7276 (progn
7277 (org-end-of-item)
7278 (org-back-over-empty-lines)
7279 (setq txt (buffer-substring beg end))
7280 (save-excursion
7281 (delete-region beg end))
7282 (setq pos (point))
7283 (insert txt)
7284 (goto-char pos) (org-skip-whitespace)
7285 (org-maybe-renumber-ordered-list))
7286 (goto-char pos)
7287 (error "Cannot move this item further down"))))
7289 (defun org-move-item-up (arg)
7290 "Move the plain list item at point up, i.e. swap with previous item.
7291 Subitems (items with larger indentation) are considered part of the item,
7292 so this really moves item trees."
7293 (interactive "p")
7294 (let (beg beg0 end end0 ind ind1 (pos (point)) txt
7295 ne-beg ne-end ne-ins ins-end)
7296 (org-beginning-of-item)
7297 (setq beg0 (point))
7298 (setq ind (org-get-indentation))
7299 (save-excursion
7300 (setq ne-beg (org-back-over-empty-lines))
7301 (setq beg (point)))
7302 (goto-char beg0)
7303 (org-end-of-item)
7304 (setq ne-end (org-back-over-empty-lines))
7305 (setq end (point))
7306 (goto-char beg0)
7307 (catch 'exit
7308 (while t
7309 (beginning-of-line 0)
7310 (if (looking-at "[ \t]*$")
7311 (if org-empty-line-terminates-plain-lists
7312 (progn
7313 (goto-char pos)
7314 (error "Cannot move this item further up"))
7315 nil)
7316 (if (<= (setq ind1 (org-get-indentation)) ind)
7317 (throw 'exit t)))))
7318 (condition-case nil
7319 (org-beginning-of-item)
7320 (error (goto-char beg)
7321 (error "Cannot move this item further up")))
7322 (setq ind1 (org-get-indentation))
7323 (if (and (org-at-item-p) (= ind ind1))
7324 (progn
7325 (setq ne-ins (org-back-over-empty-lines))
7326 (setq txt (buffer-substring beg end))
7327 (save-excursion
7328 (delete-region beg end))
7329 (setq pos (point))
7330 (insert txt)
7331 (setq ins-end (point))
7332 (goto-char pos) (org-skip-whitespace)
7334 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7335 ;; Move whitespace back to beginning
7336 (save-excursion
7337 (goto-char ins-end)
7338 (let ((kill-whole-line t))
7339 (kill-line (- ne-ins ne-beg)) (point)))
7340 (insert (make-string (- ne-ins ne-beg) ?\n)))
7342 (org-maybe-renumber-ordered-list))
7343 (goto-char pos)
7344 (error "Cannot move this item further up"))))
7346 (defun org-maybe-renumber-ordered-list ()
7347 "Renumber the ordered list at point if setup allows it.
7348 This tests the user option `org-auto-renumber-ordered-lists' before
7349 doing the renumbering."
7350 (interactive)
7351 (when (and org-auto-renumber-ordered-lists
7352 (org-at-item-p))
7353 (if (match-beginning 3)
7354 (org-renumber-ordered-list 1)
7355 (org-fix-bullet-type))))
7357 (defun org-maybe-renumber-ordered-list-safe ()
7358 (condition-case nil
7359 (save-excursion
7360 (org-maybe-renumber-ordered-list))
7361 (error nil)))
7363 (defun org-cycle-list-bullet (&optional which)
7364 "Cycle through the different itemize/enumerate bullets.
7365 This cycle the entire list level through the sequence:
7367 `-' -> `+' -> `*' -> `1.' -> `1)'
7369 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7370 0 meand `-', 1 means `+' etc."
7371 (interactive "P")
7372 (org-preserve-lc
7373 (org-beginning-of-item-list)
7374 (org-at-item-p)
7375 (beginning-of-line 1)
7376 (let ((current (match-string 0))
7377 (prevp (eq which 'previous))
7378 new)
7379 (setq new (cond
7380 ((and (numberp which)
7381 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7382 ((string-match "-" current) (if prevp "1)" "+"))
7383 ((string-match "\\+" current)
7384 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7385 ((string-match "\\*" current) (if prevp "+" "1."))
7386 ((string-match "\\." current) (if prevp "*" "1)"))
7387 ((string-match ")" current) (if prevp "1." "-"))
7388 (t (error "This should not happen"))))
7389 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7390 (org-fix-bullet-type)
7391 (org-maybe-renumber-ordered-list))))
7393 (defun org-get-string-indentation (s)
7394 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7395 (let ((n -1) (i 0) (w tab-width) c)
7396 (catch 'exit
7397 (while (< (setq n (1+ n)) (length s))
7398 (setq c (aref s n))
7399 (cond ((= c ?\ ) (setq i (1+ i)))
7400 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7401 (t (throw 'exit t)))))
7404 (defun org-renumber-ordered-list (arg)
7405 "Renumber an ordered plain list.
7406 Cursor needs to be in the first line of an item, the line that starts
7407 with something like \"1.\" or \"2)\"."
7408 (interactive "p")
7409 (unless (and (org-at-item-p)
7410 (match-beginning 3))
7411 (error "This is not an ordered list"))
7412 (let ((line (org-current-line))
7413 (col (current-column))
7414 (ind (org-get-string-indentation
7415 (buffer-substring (point-at-bol) (match-beginning 3))))
7416 ;; (term (substring (match-string 3) -1))
7417 ind1 (n (1- arg))
7418 fmt)
7419 ;; find where this list begins
7420 (org-beginning-of-item-list)
7421 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7422 (setq fmt (concat "%d" (match-string 1)))
7423 (beginning-of-line 0)
7424 ;; walk forward and replace these numbers
7425 (catch 'exit
7426 (while t
7427 (catch 'next
7428 (beginning-of-line 2)
7429 (if (eobp) (throw 'exit nil))
7430 (if (looking-at "[ \t]*$") (throw 'next nil))
7431 (skip-chars-forward " \t") (setq ind1 (current-column))
7432 (if (> ind1 ind) (throw 'next t))
7433 (if (< ind1 ind) (throw 'exit t))
7434 (if (not (org-at-item-p)) (throw 'exit nil))
7435 (delete-region (match-beginning 2) (match-end 2))
7436 (goto-char (match-beginning 2))
7437 (insert (format fmt (setq n (1+ n)))))))
7438 (goto-line line)
7439 (move-to-column col)))
7441 (defun org-fix-bullet-type ()
7442 "Make sure all items in this list have the same bullet as the firsst item."
7443 (interactive)
7444 (unless (org-at-item-p) (error "This is not a list"))
7445 (let ((line (org-current-line))
7446 (col (current-column))
7447 (ind (current-indentation))
7448 ind1 bullet)
7449 ;; find where this list begins
7450 (org-beginning-of-item-list)
7451 (beginning-of-line 1)
7452 ;; find out what the bullet type is
7453 (looking-at "[ \t]*\\(\\S-+\\)")
7454 (setq bullet (match-string 1))
7455 ;; walk forward and replace these numbers
7456 (beginning-of-line 0)
7457 (catch 'exit
7458 (while t
7459 (catch 'next
7460 (beginning-of-line 2)
7461 (if (eobp) (throw 'exit nil))
7462 (if (looking-at "[ \t]*$") (throw 'next nil))
7463 (skip-chars-forward " \t") (setq ind1 (current-column))
7464 (if (> ind1 ind) (throw 'next t))
7465 (if (< ind1 ind) (throw 'exit t))
7466 (if (not (org-at-item-p)) (throw 'exit nil))
7467 (skip-chars-forward " \t")
7468 (looking-at "\\S-+")
7469 (replace-match bullet))))
7470 (goto-line line)
7471 (move-to-column col)
7472 (if (string-match "[0-9]" bullet)
7473 (org-renumber-ordered-list 1))))
7475 (defun org-beginning-of-item-list ()
7476 "Go to the beginning of the current item list.
7477 I.e. to the first item in this list."
7478 (interactive)
7479 (org-beginning-of-item)
7480 (let ((pos (point-at-bol))
7481 (ind (org-get-indentation))
7482 ind1)
7483 ;; find where this list begins
7484 (catch 'exit
7485 (while t
7486 (catch 'next
7487 (beginning-of-line 0)
7488 (if (looking-at "[ \t]*$")
7489 (throw (if (bobp) 'exit 'next) t))
7490 (skip-chars-forward " \t") (setq ind1 (current-column))
7491 (if (or (< ind1 ind)
7492 (and (= ind1 ind)
7493 (not (org-at-item-p)))
7494 (bobp))
7495 (throw 'exit t)
7496 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7497 (goto-char pos)))
7500 (defun org-end-of-item-list ()
7501 "Go to the end of the current item list.
7502 I.e. to the text after the last item."
7503 (interactive)
7504 (org-beginning-of-item)
7505 (let ((pos (point-at-bol))
7506 (ind (org-get-indentation))
7507 ind1)
7508 ;; find where this list begins
7509 (catch 'exit
7510 (while t
7511 (catch 'next
7512 (beginning-of-line 2)
7513 (if (looking-at "[ \t]*$")
7514 (throw (if (eobp) 'exit 'next) t))
7515 (skip-chars-forward " \t") (setq ind1 (current-column))
7516 (if (or (< ind1 ind)
7517 (and (= ind1 ind)
7518 (not (org-at-item-p)))
7519 (eobp))
7520 (progn
7521 (setq pos (point-at-bol))
7522 (throw 'exit t))))))
7523 (goto-char pos)))
7526 (defvar org-last-indent-begin-marker (make-marker))
7527 (defvar org-last-indent-end-marker (make-marker))
7529 (defun org-outdent-item (arg)
7530 "Outdent a local list item."
7531 (interactive "p")
7532 (org-indent-item (- arg)))
7534 (defun org-indent-item (arg)
7535 "Indent a local list item."
7536 (interactive "p")
7537 (unless (org-at-item-p)
7538 (error "Not on an item"))
7539 (save-excursion
7540 (let (beg end ind ind1 tmp delta ind-down ind-up)
7541 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7542 (setq beg org-last-indent-begin-marker
7543 end org-last-indent-end-marker)
7544 (org-beginning-of-item)
7545 (setq beg (move-marker org-last-indent-begin-marker (point)))
7546 (org-end-of-item)
7547 (setq end (move-marker org-last-indent-end-marker (point))))
7548 (goto-char beg)
7549 (setq tmp (org-item-indent-positions)
7550 ind (car tmp)
7551 ind-down (nth 2 tmp)
7552 ind-up (nth 1 tmp)
7553 delta (if (> arg 0)
7554 (if ind-down (- ind-down ind) 2)
7555 (if ind-up (- ind-up ind) -2)))
7556 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7557 (while (< (point) end)
7558 (beginning-of-line 1)
7559 (skip-chars-forward " \t") (setq ind1 (current-column))
7560 (delete-region (point-at-bol) (point))
7561 (or (eolp) (indent-to-column (+ ind1 delta)))
7562 (beginning-of-line 2))))
7563 (org-fix-bullet-type)
7564 (org-maybe-renumber-ordered-list-safe)
7565 (save-excursion
7566 (beginning-of-line 0)
7567 (condition-case nil (org-beginning-of-item) (error nil))
7568 (org-maybe-renumber-ordered-list-safe)))
7570 (defun org-item-indent-positions ()
7571 "Return indentation for plain list items.
7572 This returns a list with three values: The current indentation, the
7573 parent indentation and the indentation a child should habe.
7574 Assumes cursor in item line."
7575 (let* ((bolpos (point-at-bol))
7576 (ind (org-get-indentation))
7577 ind-down ind-up pos)
7578 (save-excursion
7579 (org-beginning-of-item-list)
7580 (skip-chars-backward "\n\r \t")
7581 (when (org-in-item-p)
7582 (org-beginning-of-item)
7583 (setq ind-up (org-get-indentation))))
7584 (setq pos (point))
7585 (save-excursion
7586 (cond
7587 ((and (condition-case nil (progn (org-previous-item) t)
7588 (error nil))
7589 (or (forward-char 1) t)
7590 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7591 (setq ind-down (org-get-indentation)))
7592 ((and (goto-char pos)
7593 (org-at-item-p))
7594 (goto-char (match-end 0))
7595 (skip-chars-forward " \t")
7596 (setq ind-down (current-column)))))
7597 (list ind ind-up ind-down)))
7599 ;;; The orgstruct minor mode
7601 ;; Define a minor mode which can be used in other modes in order to
7602 ;; integrate the org-mode structure editing commands.
7604 ;; This is really a hack, because the org-mode structure commands use
7605 ;; keys which normally belong to the major mode. Here is how it
7606 ;; works: The minor mode defines all the keys necessary to operate the
7607 ;; structure commands, but wraps the commands into a function which
7608 ;; tests if the cursor is currently at a headline or a plain list
7609 ;; item. If that is the case, the structure command is used,
7610 ;; temporarily setting many Org-mode variables like regular
7611 ;; expressions for filling etc. However, when any of those keys is
7612 ;; used at a different location, function uses `key-binding' to look
7613 ;; up if the key has an associated command in another currently active
7614 ;; keymap (minor modes, major mode, global), and executes that
7615 ;; command. There might be problems if any of the keys is otherwise
7616 ;; used as a prefix key.
7618 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7619 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7620 ;; addresses this by checking explicitly for both bindings.
7622 (defvar orgstruct-mode-map (make-sparse-keymap)
7623 "Keymap for the minor `orgstruct-mode'.")
7625 (defvar org-local-vars nil
7626 "List of local variables, for use by `orgstruct-mode'")
7628 ;;;###autoload
7629 (define-minor-mode orgstruct-mode
7630 "Toggle the minor more `orgstruct-mode'.
7631 This mode is for using Org-mode structure commands in other modes.
7632 The following key behave as if Org-mode was active, if the cursor
7633 is on a headline, or on a plain list item (both in the definition
7634 of Org-mode).
7636 M-up Move entry/item up
7637 M-down Move entry/item down
7638 M-left Promote
7639 M-right Demote
7640 M-S-up Move entry/item up
7641 M-S-down Move entry/item down
7642 M-S-left Promote subtree
7643 M-S-right Demote subtree
7644 M-q Fill paragraph and items like in Org-mode
7645 C-c ^ Sort entries
7646 C-c - Cycle list bullet
7647 TAB Cycle item visibility
7648 M-RET Insert new heading/item
7649 S-M-RET Insert new TODO heading / Chekbox item
7650 C-c C-c Set tags / toggle checkbox"
7651 nil " OrgStruct" nil
7652 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7654 ;;;###autoload
7655 (defun turn-on-orgstruct ()
7656 "Unconditionally turn on `orgstruct-mode'."
7657 (orgstruct-mode 1))
7659 ;;;###autoload
7660 (defun turn-on-orgstruct++ ()
7661 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7662 In addition to setting orgstruct-mode, this also exports all indentation and
7663 autofilling variables from org-mode into the buffer. Note that turning
7664 off orgstruct-mode will *not* remove these additional settings."
7665 (orgstruct-mode 1)
7666 (let (var val)
7667 (mapc
7668 (lambda (x)
7669 (when (string-match
7670 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7671 (symbol-name (car x)))
7672 (setq var (car x) val (nth 1 x))
7673 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7674 org-local-vars)))
7676 (defun orgstruct-error ()
7677 "Error when there is no default binding for a structure key."
7678 (interactive)
7679 (error "This key has no function outside structure elements"))
7681 (defun orgstruct-setup ()
7682 "Setup orgstruct keymaps."
7683 (let ((nfunc 0)
7684 (bindings
7685 (list
7686 '([(meta up)] org-metaup)
7687 '([(meta down)] org-metadown)
7688 '([(meta left)] org-metaleft)
7689 '([(meta right)] org-metaright)
7690 '([(meta shift up)] org-shiftmetaup)
7691 '([(meta shift down)] org-shiftmetadown)
7692 '([(meta shift left)] org-shiftmetaleft)
7693 '([(meta shift right)] org-shiftmetaright)
7694 '([(shift up)] org-shiftup)
7695 '([(shift down)] org-shiftdown)
7696 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7697 '("\M-q" fill-paragraph)
7698 '("\C-c^" org-sort)
7699 '("\C-c-" org-cycle-list-bullet)))
7700 elt key fun cmd)
7701 (while (setq elt (pop bindings))
7702 (setq nfunc (1+ nfunc))
7703 (setq key (org-key (car elt))
7704 fun (nth 1 elt)
7705 cmd (orgstruct-make-binding fun nfunc key))
7706 (org-defkey orgstruct-mode-map key cmd))
7708 ;; Special treatment needed for TAB and RET
7709 (org-defkey orgstruct-mode-map [(tab)]
7710 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7711 (org-defkey orgstruct-mode-map "\C-i"
7712 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7714 (org-defkey orgstruct-mode-map "\M-\C-m"
7715 (orgstruct-make-binding 'org-insert-heading 105
7716 "\M-\C-m" [(meta return)]))
7717 (org-defkey orgstruct-mode-map [(meta return)]
7718 (orgstruct-make-binding 'org-insert-heading 106
7719 [(meta return)] "\M-\C-m"))
7721 (org-defkey orgstruct-mode-map [(shift meta return)]
7722 (orgstruct-make-binding 'org-insert-todo-heading 107
7723 [(meta return)] "\M-\C-m"))
7725 (unless org-local-vars
7726 (setq org-local-vars (org-get-local-variables)))
7730 (defun orgstruct-make-binding (fun n &rest keys)
7731 "Create a function for binding in the structure minor mode.
7732 FUN is the command to call inside a table. N is used to create a unique
7733 command name. KEYS are keys that should be checked in for a command
7734 to execute outside of tables."
7735 (eval
7736 (list 'defun
7737 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7738 '(arg)
7739 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7740 "Outside of structure, run the binding of `"
7741 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7742 "'.")
7743 '(interactive "p")
7744 (list 'if
7745 '(org-context-p 'headline 'item)
7746 (list 'org-run-like-in-org-mode (list 'quote fun))
7747 (list 'let '(orgstruct-mode)
7748 (list 'call-interactively
7749 (append '(or)
7750 (mapcar (lambda (k)
7751 (list 'key-binding k))
7752 keys)
7753 '('orgstruct-error))))))))
7755 (defun org-context-p (&rest contexts)
7756 "Check if local context is and of CONTEXTS.
7757 Possible values in the list of contexts are `table', `headline', and `item'."
7758 (let ((pos (point)))
7759 (goto-char (point-at-bol))
7760 (prog1 (or (and (memq 'table contexts)
7761 (looking-at "[ \t]*|"))
7762 (and (memq 'headline contexts)
7763 (looking-at "\\*+"))
7764 (and (memq 'item contexts)
7765 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7766 (goto-char pos))))
7768 (defun org-get-local-variables ()
7769 "Return a list of all local variables in an org-mode buffer."
7770 (let (varlist)
7771 (with-current-buffer (get-buffer-create "*Org tmp*")
7772 (erase-buffer)
7773 (org-mode)
7774 (setq varlist (buffer-local-variables)))
7775 (kill-buffer "*Org tmp*")
7776 (delq nil
7777 (mapcar
7778 (lambda (x)
7779 (setq x
7780 (if (symbolp x)
7781 (list x)
7782 (list (car x) (list 'quote (cdr x)))))
7783 (if (string-match
7784 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7785 (symbol-name (car x)))
7786 x nil))
7787 varlist))))
7789 ;;;###autoload
7790 (defun org-run-like-in-org-mode (cmd)
7791 (unless org-local-vars
7792 (setq org-local-vars (org-get-local-variables)))
7793 (eval (list 'let org-local-vars
7794 (list 'call-interactively (list 'quote cmd)))))
7796 ;;;; Archiving
7798 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7800 (defun org-archive-subtree (&optional find-done)
7801 "Move the current subtree to the archive.
7802 The archive can be a certain top-level heading in the current file, or in
7803 a different file. The tree will be moved to that location, the subtree
7804 heading be marked DONE, and the current time will be added.
7806 When called with prefix argument FIND-DONE, find whole trees without any
7807 open TODO items and archive them (after getting confirmation from the user).
7808 If the cursor is not at a headline when this comand is called, try all level
7809 1 trees. If the cursor is on a headline, only try the direct children of
7810 this heading."
7811 (interactive "P")
7812 (if find-done
7813 (org-archive-all-done)
7814 ;; Save all relevant TODO keyword-relatex variables
7816 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7817 (tr-org-todo-keywords-1 org-todo-keywords-1)
7818 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7819 (tr-org-done-keywords org-done-keywords)
7820 (tr-org-todo-regexp org-todo-regexp)
7821 (tr-org-todo-line-regexp org-todo-line-regexp)
7822 (tr-org-odd-levels-only org-odd-levels-only)
7823 (this-buffer (current-buffer))
7824 (org-archive-location org-archive-location)
7825 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7826 ;; start of variables that will be used for saving context
7827 ;; The compiler complains about them - keep them anyway!
7828 (file (abbreviate-file-name (buffer-file-name)))
7829 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7830 (time (format-time-string
7831 (substring (cdr org-time-stamp-formats) 1 -1)
7832 (current-time)))
7833 afile heading buffer level newfile-p
7834 category todo priority
7835 ;; start of variables that will be used for savind context
7836 ltags itags prop)
7838 ;; Try to find a local archive location
7839 (save-excursion
7840 (save-restriction
7841 (widen)
7842 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7843 (if (and prop (string-match "\\S-" prop))
7844 (setq org-archive-location prop)
7845 (if (or (re-search-backward re nil t)
7846 (re-search-forward re nil t))
7847 (setq org-archive-location (match-string 1))))))
7849 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7850 (progn
7851 (setq afile (format (match-string 1 org-archive-location)
7852 (file-name-nondirectory buffer-file-name))
7853 heading (match-string 2 org-archive-location)))
7854 (error "Invalid `org-archive-location'"))
7855 (if (> (length afile) 0)
7856 (setq newfile-p (not (file-exists-p afile))
7857 buffer (find-file-noselect afile))
7858 (setq buffer (current-buffer)))
7859 (unless buffer
7860 (error "Cannot access file \"%s\"" afile))
7861 (if (and (> (length heading) 0)
7862 (string-match "^\\*+" heading))
7863 (setq level (match-end 0))
7864 (setq heading nil level 0))
7865 (save-excursion
7866 (org-back-to-heading t)
7867 ;; Get context information that will be lost by moving the tree
7868 (org-refresh-category-properties)
7869 (setq category (org-get-category)
7870 todo (and (looking-at org-todo-line-regexp)
7871 (match-string 2))
7872 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7873 ltags (org-get-tags)
7874 itags (org-delete-all ltags (org-get-tags-at)))
7875 (setq ltags (mapconcat 'identity ltags " ")
7876 itags (mapconcat 'identity itags " "))
7877 ;; We first only copy, in case something goes wrong
7878 ;; we need to protect this-command, to avoid kill-region sets it,
7879 ;; which would lead to duplication of subtrees
7880 (let (this-command) (org-copy-subtree))
7881 (set-buffer buffer)
7882 ;; Enforce org-mode for the archive buffer
7883 (if (not (org-mode-p))
7884 ;; Force the mode for future visits.
7885 (let ((org-insert-mode-line-in-empty-file t)
7886 (org-inhibit-startup t))
7887 (call-interactively 'org-mode)))
7888 (when newfile-p
7889 (goto-char (point-max))
7890 (insert (format "\nArchived entries from file %s\n\n"
7891 (buffer-file-name this-buffer))))
7892 ;; Force the TODO keywords of the original buffer
7893 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7894 (org-todo-keywords-1 tr-org-todo-keywords-1)
7895 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7896 (org-done-keywords tr-org-done-keywords)
7897 (org-todo-regexp tr-org-todo-regexp)
7898 (org-todo-line-regexp tr-org-todo-line-regexp)
7899 (org-odd-levels-only
7900 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7901 org-odd-levels-only
7902 tr-org-odd-levels-only)))
7903 (goto-char (point-min))
7904 (if heading
7905 (progn
7906 (if (re-search-forward
7907 (concat "^" (regexp-quote heading)
7908 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7909 nil t)
7910 (goto-char (match-end 0))
7911 ;; Heading not found, just insert it at the end
7912 (goto-char (point-max))
7913 (or (bolp) (insert "\n"))
7914 (insert "\n" heading "\n")
7915 (end-of-line 0))
7916 ;; Make the subtree visible
7917 (show-subtree)
7918 (org-end-of-subtree t)
7919 (skip-chars-backward " \t\r\n")
7920 (and (looking-at "[ \t\r\n]*")
7921 (replace-match "\n\n")))
7922 ;; No specific heading, just go to end of file.
7923 (goto-char (point-max)) (insert "\n"))
7924 ;; Paste
7925 (org-paste-subtree (org-get-legal-level level 1))
7927 ;; Mark the entry as done
7928 (when (and org-archive-mark-done
7929 (looking-at org-todo-line-regexp)
7930 (or (not (match-end 2))
7931 (not (member (match-string 2) org-done-keywords))))
7932 (let (org-log-done)
7933 (org-todo
7934 (car (or (member org-archive-mark-done org-done-keywords)
7935 org-done-keywords)))))
7937 ;; Add the context info
7938 (when org-archive-save-context-info
7939 (let ((l org-archive-save-context-info) e n v)
7940 (while (setq e (pop l))
7941 (when (and (setq v (symbol-value e))
7942 (stringp v) (string-match "\\S-" v))
7943 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7944 (org-entry-put (point) n v)))))
7946 ;; Save the buffer, if it is not the same buffer.
7947 (if (not (eq this-buffer buffer)) (save-buffer))))
7948 ;; Here we are back in the original buffer. Everything seems to have
7949 ;; worked. So now cut the tree and finish up.
7950 (let (this-command) (org-cut-subtree))
7951 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7952 (message "Subtree archived %s"
7953 (if (eq this-buffer buffer)
7954 (concat "under heading: " heading)
7955 (concat "in file: " (abbreviate-file-name afile)))))))
7957 (defun org-refresh-category-properties ()
7958 "Refresh category text properties in teh buffer."
7959 (let ((def-cat (cond
7960 ((null org-category)
7961 (if buffer-file-name
7962 (file-name-sans-extension
7963 (file-name-nondirectory buffer-file-name))
7964 "???"))
7965 ((symbolp org-category) (symbol-name org-category))
7966 (t org-category)))
7967 beg end cat pos optionp)
7968 (org-unmodified
7969 (save-excursion
7970 (save-restriction
7971 (widen)
7972 (goto-char (point-min))
7973 (put-text-property (point) (point-max) 'org-category def-cat)
7974 (while (re-search-forward
7975 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7976 (setq pos (match-end 0)
7977 optionp (equal (char-after (match-beginning 0)) ?#)
7978 cat (org-trim (match-string 2)))
7979 (if optionp
7980 (setq beg (point-at-bol) end (point-max))
7981 (org-back-to-heading t)
7982 (setq beg (point) end (org-end-of-subtree t t)))
7983 (put-text-property beg end 'org-category cat)
7984 (goto-char pos)))))))
7986 (defun org-archive-all-done (&optional tag)
7987 "Archive sublevels of the current tree without open TODO items.
7988 If the cursor is not on a headline, try all level 1 trees. If
7989 it is on a headline, try all direct children.
7990 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7991 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7992 (rea (concat ".*:" org-archive-tag ":"))
7993 (begm (make-marker))
7994 (endm (make-marker))
7995 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7996 "Move subtree to archive (no open TODO items)? "))
7997 beg end (cntarch 0))
7998 (if (org-on-heading-p)
7999 (progn
8000 (setq re1 (concat "^" (regexp-quote
8001 (make-string
8002 (1+ (- (match-end 0) (match-beginning 0) 1))
8003 ?*))
8004 " "))
8005 (move-marker begm (point))
8006 (move-marker endm (org-end-of-subtree t)))
8007 (setq re1 "^* ")
8008 (move-marker begm (point-min))
8009 (move-marker endm (point-max)))
8010 (save-excursion
8011 (goto-char begm)
8012 (while (re-search-forward re1 endm t)
8013 (setq beg (match-beginning 0)
8014 end (save-excursion (org-end-of-subtree t) (point)))
8015 (goto-char beg)
8016 (if (re-search-forward re end t)
8017 (goto-char end)
8018 (goto-char beg)
8019 (if (and (or (not tag) (not (looking-at rea)))
8020 (y-or-n-p question))
8021 (progn
8022 (if tag
8023 (org-toggle-tag org-archive-tag 'on)
8024 (org-archive-subtree))
8025 (setq cntarch (1+ cntarch)))
8026 (goto-char end)))))
8027 (message "%d trees archived" cntarch)))
8029 (defun org-cycle-hide-drawers (state)
8030 "Re-hide all drawers after a visibility state change."
8031 (when (and (org-mode-p)
8032 (not (memq state '(overview folded))))
8033 (save-excursion
8034 (let* ((globalp (memq state '(contents all)))
8035 (beg (if globalp (point-min) (point)))
8036 (end (if globalp (point-max) (org-end-of-subtree t))))
8037 (goto-char beg)
8038 (while (re-search-forward org-drawer-regexp end t)
8039 (org-flag-drawer t))))))
8041 (defun org-flag-drawer (flag)
8042 (save-excursion
8043 (beginning-of-line 1)
8044 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8045 (let ((b (match-end 0))
8046 (outline-regexp org-outline-regexp))
8047 (if (re-search-forward
8048 "^[ \t]*:END:"
8049 (save-excursion (outline-next-heading) (point)) t)
8050 (outline-flag-region b (point-at-eol) flag)
8051 (error ":END: line missing"))))))
8053 (defun org-cycle-hide-archived-subtrees (state)
8054 "Re-hide all archived subtrees after a visibility state change."
8055 (when (and (not org-cycle-open-archived-trees)
8056 (not (memq state '(overview folded))))
8057 (save-excursion
8058 (let* ((globalp (memq state '(contents all)))
8059 (beg (if globalp (point-min) (point)))
8060 (end (if globalp (point-max) (org-end-of-subtree t))))
8061 (org-hide-archived-subtrees beg end)
8062 (goto-char beg)
8063 (if (looking-at (concat ".*:" org-archive-tag ":"))
8064 (message "%s" (substitute-command-keys
8065 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8067 (defun org-force-cycle-archived ()
8068 "Cycle subtree even if it is archived."
8069 (interactive)
8070 (setq this-command 'org-cycle)
8071 (let ((org-cycle-open-archived-trees t))
8072 (call-interactively 'org-cycle)))
8074 (defun org-hide-archived-subtrees (beg end)
8075 "Re-hide all archived subtrees after a visibility state change."
8076 (save-excursion
8077 (let* ((re (concat ":" org-archive-tag ":")))
8078 (goto-char beg)
8079 (while (re-search-forward re end t)
8080 (and (org-on-heading-p) (hide-subtree))
8081 (org-end-of-subtree t)))))
8083 (defun org-toggle-tag (tag &optional onoff)
8084 "Toggle the tag TAG for the current line.
8085 If ONOFF is `on' or `off', don't toggle but set to this state."
8086 (unless (org-on-heading-p t) (error "Not on headling"))
8087 (let (res current)
8088 (save-excursion
8089 (beginning-of-line)
8090 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8091 (point-at-eol) t)
8092 (progn
8093 (setq current (match-string 1))
8094 (replace-match ""))
8095 (setq current ""))
8096 (setq current (nreverse (org-split-string current ":")))
8097 (cond
8098 ((eq onoff 'on)
8099 (setq res t)
8100 (or (member tag current) (push tag current)))
8101 ((eq onoff 'off)
8102 (or (not (member tag current)) (setq current (delete tag current))))
8103 (t (if (member tag current)
8104 (setq current (delete tag current))
8105 (setq res t)
8106 (push tag current))))
8107 (end-of-line 1)
8108 (if current
8109 (progn
8110 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8111 (org-set-tags nil t))
8112 (delete-horizontal-space))
8113 (run-hooks 'org-after-tags-change-hook))
8114 res))
8116 (defun org-toggle-archive-tag (&optional arg)
8117 "Toggle the archive tag for the current headline.
8118 With prefix ARG, check all children of current headline and offer tagging
8119 the children that do not contain any open TODO items."
8120 (interactive "P")
8121 (if arg
8122 (org-archive-all-done 'tag)
8123 (let (set)
8124 (save-excursion
8125 (org-back-to-heading t)
8126 (setq set (org-toggle-tag org-archive-tag))
8127 (when set (hide-subtree)))
8128 (and set (beginning-of-line 1))
8129 (message "Subtree %s" (if set "archived" "unarchived")))))
8132 ;;;; Tables
8134 ;;; The table editor
8136 ;; Watch out: Here we are talking about two different kind of tables.
8137 ;; Most of the code is for the tables created with the Org-mode table editor.
8138 ;; Sometimes, we talk about tables created and edited with the table.el
8139 ;; Emacs package. We call the former org-type tables, and the latter
8140 ;; table.el-type tables.
8142 (defun org-before-change-function (beg end)
8143 "Every change indicates that a table might need an update."
8144 (setq org-table-may-need-update t))
8146 (defconst org-table-line-regexp "^[ \t]*|"
8147 "Detects an org-type table line.")
8148 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8149 "Detects an org-type table line.")
8150 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8151 "Detects a table line marked for automatic recalculation.")
8152 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8153 "Detects a table line marked for automatic recalculation.")
8154 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8155 "Detects a table line marked for automatic recalculation.")
8156 (defconst org-table-hline-regexp "^[ \t]*|-"
8157 "Detects an org-type table hline.")
8158 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8159 "Detects a table-type table hline.")
8160 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8161 "Detects an org-type or table-type table.")
8162 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8163 "Searching from within a table (any type) this finds the first line
8164 outside the table.")
8165 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8166 "Searching from within a table (any type) this finds the first line
8167 outside the table.")
8169 (defvar org-table-last-highlighted-reference nil)
8170 (defvar org-table-formula-history nil)
8172 (defvar org-table-column-names nil
8173 "Alist with column names, derived from the `!' line.")
8174 (defvar org-table-column-name-regexp nil
8175 "Regular expression matching the current column names.")
8176 (defvar org-table-local-parameters nil
8177 "Alist with parameter names, derived from the `$' line.")
8178 (defvar org-table-named-field-locations nil
8179 "Alist with locations of named fields.")
8181 (defvar org-table-current-line-types nil
8182 "Table row types, non-nil only for the duration of a comand.")
8183 (defvar org-table-current-begin-line nil
8184 "Table begin line, non-nil only for the duration of a comand.")
8185 (defvar org-table-current-begin-pos nil
8186 "Table begin position, non-nil only for the duration of a comand.")
8187 (defvar org-table-dlines nil
8188 "Vector of data line line numbers in the current table.")
8189 (defvar org-table-hlines nil
8190 "Vector of hline line numbers in the current table.")
8192 (defconst org-table-range-regexp
8193 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8194 ;; 1 2 3 4 5
8195 "Regular expression for matching ranges in formulas.")
8197 (defconst org-table-range-regexp2
8198 (concat
8199 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8200 "\\.\\."
8201 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8202 "Match a range for reference display.")
8204 (defconst org-table-translate-regexp
8205 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8206 "Match a reference that needs translation, for reference display.")
8208 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8210 (defun org-table-create-with-table.el ()
8211 "Use the table.el package to insert a new table.
8212 If there is already a table at point, convert between Org-mode tables
8213 and table.el tables."
8214 (interactive)
8215 (require 'table)
8216 (cond
8217 ((org-at-table.el-p)
8218 (if (y-or-n-p "Convert table to Org-mode table? ")
8219 (org-table-convert)))
8220 ((org-at-table-p)
8221 (if (y-or-n-p "Convert table to table.el table? ")
8222 (org-table-convert)))
8223 (t (call-interactively 'table-insert))))
8225 (defun org-table-create-or-convert-from-region (arg)
8226 "Convert region to table, or create an empty table.
8227 If there is an active region, convert it to a table, using the function
8228 `org-table-convert-region'. See the documentation of that function
8229 to learn how the prefix argument is interpreted to determine the field
8230 separator.
8231 If there is no such region, create an empty table with `org-table-create'."
8232 (interactive "P")
8233 (if (org-region-active-p)
8234 (org-table-convert-region (region-beginning) (region-end) arg)
8235 (org-table-create arg)))
8237 (defun org-table-create (&optional size)
8238 "Query for a size and insert a table skeleton.
8239 SIZE is a string Columns x Rows like for example \"3x2\"."
8240 (interactive "P")
8241 (unless size
8242 (setq size (read-string
8243 (concat "Table size Columns x Rows [e.g. "
8244 org-table-default-size "]: ")
8245 "" nil org-table-default-size)))
8247 (let* ((pos (point))
8248 (indent (make-string (current-column) ?\ ))
8249 (split (org-split-string size " *x *"))
8250 (rows (string-to-number (nth 1 split)))
8251 (columns (string-to-number (car split)))
8252 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8253 "\n")))
8254 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8255 (point-at-bol) (point)))
8256 (beginning-of-line 1)
8257 (newline))
8258 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8259 (dotimes (i rows) (insert line))
8260 (goto-char pos)
8261 (if (> rows 1)
8262 ;; Insert a hline after the first row.
8263 (progn
8264 (end-of-line 1)
8265 (insert "\n|-")
8266 (goto-char pos)))
8267 (org-table-align)))
8269 (defun org-table-convert-region (beg0 end0 &optional separator)
8270 "Convert region to a table.
8271 The region goes from BEG0 to END0, but these borders will be moved
8272 slightly, to make sure a beginning of line in the first line is included.
8274 SEPARATOR specifies the field separator in the lines. It can have the
8275 following values:
8277 '(4) Use the comma as a field separator
8278 '(16) Use a TAB as field separator
8279 integer When a number, use that many spaces as field separator
8280 nil When nil, the command tries to be smart and figure out the
8281 separator in the following way:
8282 - when each line contains a TAB, assume TAB-separated material
8283 - when each line contains a comme, assume CSV material
8284 - else, assume one or more SPACE charcters as separator."
8285 (interactive "rP")
8286 (let* ((beg (min beg0 end0))
8287 (end (max beg0 end0))
8289 (goto-char beg)
8290 (beginning-of-line 1)
8291 (setq beg (move-marker (make-marker) (point)))
8292 (goto-char end)
8293 (if (bolp) (backward-char 1) (end-of-line 1))
8294 (setq end (move-marker (make-marker) (point)))
8295 ;; Get the right field separator
8296 (unless separator
8297 (goto-char beg)
8298 (setq separator
8299 (cond
8300 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8301 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8302 (t 1))))
8303 (setq re (cond
8304 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8305 ((equal separator '(16)) "^\\|\t")
8306 ((integerp separator)
8307 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8308 (t (error "This should not happen"))))
8309 (goto-char beg)
8310 (while (re-search-forward re end t)
8311 (replace-match "| " t t))
8312 (goto-char beg)
8313 (insert " ")
8314 (org-table-align)))
8316 (defun org-table-import (file arg)
8317 "Import FILE as a table.
8318 The file is assumed to be tab-separated. Such files can be produced by most
8319 spreadsheet and database applications. If no tabs (at least one per line)
8320 are found, lines will be split on whitespace into fields."
8321 (interactive "f\nP")
8322 (or (bolp) (newline))
8323 (let ((beg (point))
8324 (pm (point-max)))
8325 (insert-file-contents file)
8326 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8328 (defun org-table-export ()
8329 "Export table as a tab-separated file.
8330 Such a file can be imported into a spreadsheet program like Excel."
8331 (interactive)
8332 (let* ((beg (org-table-begin))
8333 (end (org-table-end))
8334 (table (buffer-substring beg end))
8335 (file (read-file-name "Export table to: "))
8336 buf)
8337 (unless (or (not (file-exists-p file))
8338 (y-or-n-p (format "Overwrite file %s? " file)))
8339 (error "Abort"))
8340 (with-current-buffer (find-file-noselect file)
8341 (setq buf (current-buffer))
8342 (erase-buffer)
8343 (fundamental-mode)
8344 (insert table)
8345 (goto-char (point-min))
8346 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8347 (replace-match "" t t)
8348 (end-of-line 1))
8349 (goto-char (point-min))
8350 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8351 (replace-match "" t t)
8352 (goto-char (min (1+ (point)) (point-max))))
8353 (goto-char (point-min))
8354 (while (re-search-forward "^-[-+]*$" nil t)
8355 (replace-match "")
8356 (if (looking-at "\n")
8357 (delete-char 1)))
8358 (goto-char (point-min))
8359 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8360 (replace-match "\t" t t))
8361 (save-buffer))
8362 (kill-buffer buf)))
8364 (defvar org-table-aligned-begin-marker (make-marker)
8365 "Marker at the beginning of the table last aligned.
8366 Used to check if cursor still is in that table, to minimize realignment.")
8367 (defvar org-table-aligned-end-marker (make-marker)
8368 "Marker at the end of the table last aligned.
8369 Used to check if cursor still is in that table, to minimize realignment.")
8370 (defvar org-table-last-alignment nil
8371 "List of flags for flushright alignment, from the last re-alignment.
8372 This is being used to correctly align a single field after TAB or RET.")
8373 (defvar org-table-last-column-widths nil
8374 "List of max width of fields in each column.
8375 This is being used to correctly align a single field after TAB or RET.")
8376 (defvar org-table-overlay-coordinates nil
8377 "Overlay coordinates after each align of a table.")
8378 (make-variable-buffer-local 'org-table-overlay-coordinates)
8380 (defvar org-last-recalc-line nil)
8381 (defconst org-narrow-column-arrow "=>"
8382 "Used as display property in narrowed table columns.")
8384 (defun org-table-align ()
8385 "Align the table at point by aligning all vertical bars."
8386 (interactive)
8387 (let* (
8388 ;; Limits of table
8389 (beg (org-table-begin))
8390 (end (org-table-end))
8391 ;; Current cursor position
8392 (linepos (org-current-line))
8393 (colpos (org-table-current-column))
8394 (winstart (window-start))
8395 (winstartline (org-current-line (min winstart (1- (point-max)))))
8396 lines (new "") lengths l typenums ty fields maxfields i
8397 column
8398 (indent "") cnt frac
8399 rfmt hfmt
8400 (spaces '(1 . 1))
8401 (sp1 (car spaces))
8402 (sp2 (cdr spaces))
8403 (rfmt1 (concat
8404 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8405 (hfmt1 (concat
8406 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8407 emptystrings links dates emph narrow fmax f1 len c e)
8408 (untabify beg end)
8409 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8410 ;; Check if we have links or dates
8411 (goto-char beg)
8412 (setq links (re-search-forward org-bracket-link-regexp end t))
8413 (goto-char beg)
8414 (setq emph (and org-hide-emphasis-markers
8415 (re-search-forward org-emph-re end t)))
8416 (goto-char beg)
8417 (setq dates (and org-display-custom-times
8418 (re-search-forward org-ts-regexp-both end t)))
8419 ;; Make sure the link properties are right
8420 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8421 ;; Make sure the date properties are right
8422 (when dates (goto-char beg) (while (org-activate-dates end)))
8423 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8425 ;; Check if we are narrowing any columns
8426 (goto-char beg)
8427 (setq narrow (and org-format-transports-properties-p
8428 (re-search-forward "<[0-9]+>" end t)))
8429 ;; Get the rows
8430 (setq lines (org-split-string
8431 (buffer-substring beg end) "\n"))
8432 ;; Store the indentation of the first line
8433 (if (string-match "^ *" (car lines))
8434 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8435 ;; Mark the hlines by setting the corresponding element to nil
8436 ;; At the same time, we remove trailing space.
8437 (setq lines (mapcar (lambda (l)
8438 (if (string-match "^ *|-" l)
8440 (if (string-match "[ \t]+$" l)
8441 (substring l 0 (match-beginning 0))
8442 l)))
8443 lines))
8444 ;; Get the data fields by splitting the lines.
8445 (setq fields (mapcar
8446 (lambda (l)
8447 (org-split-string l " *| *"))
8448 (delq nil (copy-sequence lines))))
8449 ;; How many fields in the longest line?
8450 (condition-case nil
8451 (setq maxfields (apply 'max (mapcar 'length fields)))
8452 (error
8453 (kill-region beg end)
8454 (org-table-create org-table-default-size)
8455 (error "Empty table - created default table")))
8456 ;; A list of empty strings to fill any short rows on output
8457 (setq emptystrings (make-list maxfields ""))
8458 ;; Check for special formatting.
8459 (setq i -1)
8460 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8461 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8462 ;; Check if there is an explicit width specified
8463 (when narrow
8464 (setq c column fmax nil)
8465 (while c
8466 (setq e (pop c))
8467 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8468 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8469 ;; Find fields that are wider than fmax, and shorten them
8470 (when fmax
8471 (loop for xx in column do
8472 (when (and (stringp xx)
8473 (> (org-string-width xx) fmax))
8474 (org-add-props xx nil
8475 'help-echo
8476 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8477 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8478 (unless (> f1 1)
8479 (error "Cannot narrow field starting with wide link \"%s\""
8480 (match-string 0 xx)))
8481 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8482 (add-text-properties (- f1 2) f1
8483 (list 'display org-narrow-column-arrow)
8484 xx)))))
8485 ;; Get the maximum width for each column
8486 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8487 ;; Get the fraction of numbers, to decide about alignment of the column
8488 (setq cnt 0 frac 0.0)
8489 (loop for x in column do
8490 (if (equal x "")
8492 (setq frac ( / (+ (* frac cnt)
8493 (if (string-match org-table-number-regexp x) 1 0))
8494 (setq cnt (1+ cnt))))))
8495 (push (>= frac org-table-number-fraction) typenums))
8496 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8498 ;; Store the alignment of this table, for later editing of single fields
8499 (setq org-table-last-alignment typenums
8500 org-table-last-column-widths lengths)
8502 ;; With invisible characters, `format' does not get the field width right
8503 ;; So we need to make these fields wide by hand.
8504 (when (or links emph)
8505 (loop for i from 0 upto (1- maxfields) do
8506 (setq len (nth i lengths))
8507 (loop for j from 0 upto (1- (length fields)) do
8508 (setq c (nthcdr i (car (nthcdr j fields))))
8509 (if (and (stringp (car c))
8510 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8511 ; (string-match org-bracket-link-regexp (car c))
8512 (< (org-string-width (car c)) len))
8513 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8515 ;; Compute the formats needed for output of the table
8516 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8517 (while (setq l (pop lengths))
8518 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8519 (setq rfmt (concat rfmt (format rfmt1 ty l))
8520 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8521 (setq rfmt (concat rfmt "\n")
8522 hfmt (concat (substring hfmt 0 -1) "|\n"))
8524 (setq new (mapconcat
8525 (lambda (l)
8526 (if l (apply 'format rfmt
8527 (append (pop fields) emptystrings))
8528 hfmt))
8529 lines ""))
8530 ;; Replace the old one
8531 (delete-region beg end)
8532 (move-marker end nil)
8533 (move-marker org-table-aligned-begin-marker (point))
8534 (insert new)
8535 (move-marker org-table-aligned-end-marker (point))
8536 (when (and orgtbl-mode (not (org-mode-p)))
8537 (goto-char org-table-aligned-begin-marker)
8538 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8539 ;; Try to move to the old location
8540 (goto-line winstartline)
8541 (setq winstart (point-at-bol))
8542 (goto-line linepos)
8543 (set-window-start (selected-window) winstart 'noforce)
8544 (org-table-goto-column colpos)
8545 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8546 (setq org-table-may-need-update nil)
8549 (defun org-string-width (s)
8550 "Compute width of string, ignoring invisible characters.
8551 This ignores character with invisibility property `org-link', and also
8552 characters with property `org-cwidth', because these will become invisible
8553 upon the next fontification round."
8554 (let (b l)
8555 (when (or (eq t buffer-invisibility-spec)
8556 (assq 'org-link buffer-invisibility-spec))
8557 (while (setq b (text-property-any 0 (length s)
8558 'invisible 'org-link s))
8559 (setq s (concat (substring s 0 b)
8560 (substring s (or (next-single-property-change
8561 b 'invisible s) (length s)))))))
8562 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8563 (setq s (concat (substring s 0 b)
8564 (substring s (or (next-single-property-change
8565 b 'org-cwidth s) (length s))))))
8566 (setq l (string-width s) b -1)
8567 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8568 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8571 (defun org-table-begin (&optional table-type)
8572 "Find the beginning of the table and return its position.
8573 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8574 (save-excursion
8575 (if (not (re-search-backward
8576 (if table-type org-table-any-border-regexp
8577 org-table-border-regexp)
8578 nil t))
8579 (progn (goto-char (point-min)) (point))
8580 (goto-char (match-beginning 0))
8581 (beginning-of-line 2)
8582 (point))))
8584 (defun org-table-end (&optional table-type)
8585 "Find the end of the table and return its position.
8586 With argument TABLE-TYPE, go to the end of a table.el-type table."
8587 (save-excursion
8588 (if (not (re-search-forward
8589 (if table-type org-table-any-border-regexp
8590 org-table-border-regexp)
8591 nil t))
8592 (goto-char (point-max))
8593 (goto-char (match-beginning 0)))
8594 (point-marker)))
8596 (defun org-table-justify-field-maybe (&optional new)
8597 "Justify the current field, text to left, number to right.
8598 Optional argument NEW may specify text to replace the current field content."
8599 (cond
8600 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8601 ((org-at-table-hline-p))
8602 ((and (not new)
8603 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8604 (current-buffer)))
8605 (< (point) org-table-aligned-begin-marker)
8606 (>= (point) org-table-aligned-end-marker)))
8607 ;; This is not the same table, force a full re-align
8608 (setq org-table-may-need-update t))
8609 (t ;; realign the current field, based on previous full realign
8610 (let* ((pos (point)) s
8611 (col (org-table-current-column))
8612 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8613 l f n o e)
8614 (when (> col 0)
8615 (skip-chars-backward "^|\n")
8616 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8617 (progn
8618 (setq s (match-string 1)
8619 o (match-string 0)
8620 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8621 e (not (= (match-beginning 2) (match-end 2))))
8622 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8623 l (if e "|" (setq org-table-may-need-update t) ""))
8624 n (format f s))
8625 (if new
8626 (if (<= (length new) l) ;; FIXME: length -> str-width?
8627 (setq n (format f new))
8628 (setq n (concat new "|") org-table-may-need-update t)))
8629 (or (equal n o)
8630 (let (org-table-may-need-update)
8631 (replace-match n t t))))
8632 (setq org-table-may-need-update t))
8633 (goto-char pos))))))
8635 (defun org-table-next-field ()
8636 "Go to the next field in the current table, creating new lines as needed.
8637 Before doing so, re-align the table if necessary."
8638 (interactive)
8639 (org-table-maybe-eval-formula)
8640 (org-table-maybe-recalculate-line)
8641 (if (and org-table-automatic-realign
8642 org-table-may-need-update)
8643 (org-table-align))
8644 (let ((end (org-table-end)))
8645 (if (org-at-table-hline-p)
8646 (end-of-line 1))
8647 (condition-case nil
8648 (progn
8649 (re-search-forward "|" end)
8650 (if (looking-at "[ \t]*$")
8651 (re-search-forward "|" end))
8652 (if (and (looking-at "-")
8653 org-table-tab-jumps-over-hlines
8654 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8655 (goto-char (match-beginning 1)))
8656 (if (looking-at "-")
8657 (progn
8658 (beginning-of-line 0)
8659 (org-table-insert-row 'below))
8660 (if (looking-at " ") (forward-char 1))))
8661 (error
8662 (org-table-insert-row 'below)))))
8664 (defun org-table-previous-field ()
8665 "Go to the previous field in the table.
8666 Before doing so, re-align the table if necessary."
8667 (interactive)
8668 (org-table-justify-field-maybe)
8669 (org-table-maybe-recalculate-line)
8670 (if (and org-table-automatic-realign
8671 org-table-may-need-update)
8672 (org-table-align))
8673 (if (org-at-table-hline-p)
8674 (end-of-line 1))
8675 (re-search-backward "|" (org-table-begin))
8676 (re-search-backward "|" (org-table-begin))
8677 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8678 (re-search-backward "|" (org-table-begin)))
8679 (if (looking-at "| ?")
8680 (goto-char (match-end 0))))
8682 (defun org-table-next-row ()
8683 "Go to the next row (same column) in the current table.
8684 Before doing so, re-align the table if necessary."
8685 (interactive)
8686 (org-table-maybe-eval-formula)
8687 (org-table-maybe-recalculate-line)
8688 (if (or (looking-at "[ \t]*$")
8689 (save-excursion (skip-chars-backward " \t") (bolp)))
8690 (newline)
8691 (if (and org-table-automatic-realign
8692 org-table-may-need-update)
8693 (org-table-align))
8694 (let ((col (org-table-current-column)))
8695 (beginning-of-line 2)
8696 (if (or (not (org-at-table-p))
8697 (org-at-table-hline-p))
8698 (progn
8699 (beginning-of-line 0)
8700 (org-table-insert-row 'below)))
8701 (org-table-goto-column col)
8702 (skip-chars-backward "^|\n\r")
8703 (if (looking-at " ") (forward-char 1)))))
8705 (defun org-table-copy-down (n)
8706 "Copy a field down in the current column.
8707 If the field at the cursor is empty, copy into it the content of the nearest
8708 non-empty field above. With argument N, use the Nth non-empty field.
8709 If the current field is not empty, it is copied down to the next row, and
8710 the cursor is moved with it. Therefore, repeating this command causes the
8711 column to be filled row-by-row.
8712 If the variable `org-table-copy-increment' is non-nil and the field is an
8713 integer or a timestamp, it will be incremented while copying. In the case of
8714 a timestamp, if the cursor is on the year, change the year. If it is on the
8715 month or the day, change that. Point will stay on the current date field
8716 in order to easily repeat the interval."
8717 (interactive "p")
8718 (let* ((colpos (org-table-current-column))
8719 (col (current-column))
8720 (field (org-table-get-field))
8721 (non-empty (string-match "[^ \t]" field))
8722 (beg (org-table-begin))
8723 txt)
8724 (org-table-check-inside-data-field)
8725 (if non-empty
8726 (progn
8727 (setq txt (org-trim field))
8728 (org-table-next-row)
8729 (org-table-blank-field))
8730 (save-excursion
8731 (setq txt
8732 (catch 'exit
8733 (while (progn (beginning-of-line 1)
8734 (re-search-backward org-table-dataline-regexp
8735 beg t))
8736 (org-table-goto-column colpos t)
8737 (if (and (looking-at
8738 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8739 (= (setq n (1- n)) 0))
8740 (throw 'exit (match-string 1))))))))
8741 (if txt
8742 (progn
8743 (if (and org-table-copy-increment
8744 (string-match "^[0-9]+$" txt))
8745 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8746 (insert txt)
8747 (move-to-column col)
8748 (if (and org-table-copy-increment (org-at-timestamp-p t))
8749 (org-timestamp-up 1)
8750 (org-table-maybe-recalculate-line))
8751 (org-table-align)
8752 (move-to-column col))
8753 (error "No non-empty field found"))))
8755 (defun org-table-check-inside-data-field ()
8756 "Is point inside a table data field?
8757 I.e. not on a hline or before the first or after the last column?
8758 This actually throws an error, so it aborts the current command."
8759 (if (or (not (org-at-table-p))
8760 (= (org-table-current-column) 0)
8761 (org-at-table-hline-p)
8762 (looking-at "[ \t]*$"))
8763 (error "Not in table data field")))
8765 (defvar org-table-clip nil
8766 "Clipboard for table regions.")
8768 (defun org-table-blank-field ()
8769 "Blank the current table field or active region."
8770 (interactive)
8771 (org-table-check-inside-data-field)
8772 (if (and (interactive-p) (org-region-active-p))
8773 (let (org-table-clip)
8774 (org-table-cut-region (region-beginning) (region-end)))
8775 (skip-chars-backward "^|")
8776 (backward-char 1)
8777 (if (looking-at "|[^|\n]+")
8778 (let* ((pos (match-beginning 0))
8779 (match (match-string 0))
8780 (len (org-string-width match)))
8781 (replace-match (concat "|" (make-string (1- len) ?\ )))
8782 (goto-char (+ 2 pos))
8783 (substring match 1)))))
8785 (defun org-table-get-field (&optional n replace)
8786 "Return the value of the field in column N of current row.
8787 N defaults to current field.
8788 If REPLACE is a string, replace field with this value. The return value
8789 is always the old value."
8790 (and n (org-table-goto-column n))
8791 (skip-chars-backward "^|\n")
8792 (backward-char 1)
8793 (if (looking-at "|[^|\r\n]*")
8794 (let* ((pos (match-beginning 0))
8795 (val (buffer-substring (1+ pos) (match-end 0))))
8796 (if replace
8797 (replace-match (concat "|" replace) t t))
8798 (goto-char (min (point-at-eol) (+ 2 pos)))
8799 val)
8800 (forward-char 1) ""))
8802 (defun org-table-field-info (arg)
8803 "Show info about the current field, and highlight any reference at point."
8804 (interactive "P")
8805 (org-table-get-specials)
8806 (save-excursion
8807 (let* ((pos (point))
8808 (col (org-table-current-column))
8809 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8810 (name (car (rassoc (list (org-current-line) col)
8811 org-table-named-field-locations)))
8812 (eql (org-table-get-stored-formulas))
8813 (dline (org-table-current-dline))
8814 (ref (format "@%d$%d" dline col))
8815 (ref1 (org-table-convert-refs-to-an ref))
8816 (fequation (or (assoc name eql) (assoc ref eql)))
8817 (cequation (assoc (int-to-string col) eql))
8818 (eqn (or fequation cequation)))
8819 (goto-char pos)
8820 (condition-case nil
8821 (org-table-show-reference 'local)
8822 (error nil))
8823 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8824 dline col
8825 (if cname (concat " or $" cname) "")
8826 dline col ref1
8827 (if name (concat " or $" name) "")
8828 ;; FIXME: formula info not correct if special table line
8829 (if eqn
8830 (concat ", formula: "
8831 (org-table-formula-to-user
8832 (concat
8833 (if (string-match "^[$@]"(car eqn)) "" "$")
8834 (car eqn) "=" (cdr eqn))))
8835 "")))))
8837 (defun org-table-current-column ()
8838 "Find out which column we are in.
8839 When called interactively, column is also displayed in echo area."
8840 (interactive)
8841 (if (interactive-p) (org-table-check-inside-data-field))
8842 (save-excursion
8843 (let ((cnt 0) (pos (point)))
8844 (beginning-of-line 1)
8845 (while (search-forward "|" pos t)
8846 (setq cnt (1+ cnt)))
8847 (if (interactive-p) (message "This is table column %d" cnt))
8848 cnt)))
8850 (defun org-table-current-dline ()
8851 "Find out what table data line we are in.
8852 Only datalins count for this."
8853 (interactive)
8854 (if (interactive-p) (org-table-check-inside-data-field))
8855 (save-excursion
8856 (let ((cnt 0) (pos (point)))
8857 (goto-char (org-table-begin))
8858 (while (<= (point) pos)
8859 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8860 (beginning-of-line 2))
8861 (if (interactive-p) (message "This is table line %d" cnt))
8862 cnt)))
8864 (defun org-table-goto-column (n &optional on-delim force)
8865 "Move the cursor to the Nth column in the current table line.
8866 With optional argument ON-DELIM, stop with point before the left delimiter
8867 of the field.
8868 If there are less than N fields, just go to after the last delimiter.
8869 However, when FORCE is non-nil, create new columns if necessary."
8870 (interactive "p")
8871 (let ((pos (point-at-eol)))
8872 (beginning-of-line 1)
8873 (when (> n 0)
8874 (while (and (> (setq n (1- n)) -1)
8875 (or (search-forward "|" pos t)
8876 (and force
8877 (progn (end-of-line 1)
8878 (skip-chars-backward "^|")
8879 (insert " | "))))))
8880 ; (backward-char 2) t)))))
8881 (when (and force (not (looking-at ".*|")))
8882 (save-excursion (end-of-line 1) (insert " | ")))
8883 (if on-delim
8884 (backward-char 1)
8885 (if (looking-at " ") (forward-char 1))))))
8887 (defun org-at-table-p (&optional table-type)
8888 "Return t if the cursor is inside an org-type table.
8889 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8890 (if org-enable-table-editor
8891 (save-excursion
8892 (beginning-of-line 1)
8893 (looking-at (if table-type org-table-any-line-regexp
8894 org-table-line-regexp)))
8895 nil))
8897 (defun org-at-table.el-p ()
8898 "Return t if and only if we are at a table.el table."
8899 (and (org-at-table-p 'any)
8900 (save-excursion
8901 (goto-char (org-table-begin 'any))
8902 (looking-at org-table1-hline-regexp))))
8904 (defun org-table-recognize-table.el ()
8905 "If there is a table.el table nearby, recognize it and move into it."
8906 (if org-table-tab-recognizes-table.el
8907 (if (org-at-table.el-p)
8908 (progn
8909 (beginning-of-line 1)
8910 (if (looking-at org-table-dataline-regexp)
8912 (if (looking-at org-table1-hline-regexp)
8913 (progn
8914 (beginning-of-line 2)
8915 (if (looking-at org-table-any-border-regexp)
8916 (beginning-of-line -1)))))
8917 (if (re-search-forward "|" (org-table-end t) t)
8918 (progn
8919 (require 'table)
8920 (if (table--at-cell-p (point))
8922 (message "recognizing table.el table...")
8923 (table-recognize-table)
8924 (message "recognizing table.el table...done")))
8925 (error "This should not happen..."))
8927 nil)
8928 nil))
8930 (defun org-at-table-hline-p ()
8931 "Return t if the cursor is inside a hline in a table."
8932 (if org-enable-table-editor
8933 (save-excursion
8934 (beginning-of-line 1)
8935 (looking-at org-table-hline-regexp))
8936 nil))
8938 (defun org-table-insert-column ()
8939 "Insert a new column into the table."
8940 (interactive)
8941 (if (not (org-at-table-p))
8942 (error "Not at a table"))
8943 (org-table-find-dataline)
8944 (let* ((col (max 1 (org-table-current-column)))
8945 (beg (org-table-begin))
8946 (end (org-table-end))
8947 ;; Current cursor position
8948 (linepos (org-current-line))
8949 (colpos col))
8950 (goto-char beg)
8951 (while (< (point) end)
8952 (if (org-at-table-hline-p)
8954 (org-table-goto-column col t)
8955 (insert "| "))
8956 (beginning-of-line 2))
8957 (move-marker end nil)
8958 (goto-line linepos)
8959 (org-table-goto-column colpos)
8960 (org-table-align)
8961 (org-table-fix-formulas "$" nil (1- col) 1)))
8963 (defun org-table-find-dataline ()
8964 "Find a dataline in the current table, which is needed for column commands."
8965 (if (and (org-at-table-p)
8966 (not (org-at-table-hline-p)))
8968 (let ((col (current-column))
8969 (end (org-table-end)))
8970 (move-to-column col)
8971 (while (and (< (point) end)
8972 (or (not (= (current-column) col))
8973 (org-at-table-hline-p)))
8974 (beginning-of-line 2)
8975 (move-to-column col))
8976 (if (and (org-at-table-p)
8977 (not (org-at-table-hline-p)))
8979 (error
8980 "Please position cursor in a data line for column operations")))))
8982 (defun org-table-delete-column ()
8983 "Delete a column from the table."
8984 (interactive)
8985 (if (not (org-at-table-p))
8986 (error "Not at a table"))
8987 (org-table-find-dataline)
8988 (org-table-check-inside-data-field)
8989 (let* ((col (org-table-current-column))
8990 (beg (org-table-begin))
8991 (end (org-table-end))
8992 ;; Current cursor position
8993 (linepos (org-current-line))
8994 (colpos col))
8995 (goto-char beg)
8996 (while (< (point) end)
8997 (if (org-at-table-hline-p)
8999 (org-table-goto-column col t)
9000 (and (looking-at "|[^|\n]+|")
9001 (replace-match "|")))
9002 (beginning-of-line 2))
9003 (move-marker end nil)
9004 (goto-line linepos)
9005 (org-table-goto-column colpos)
9006 (org-table-align)
9007 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9008 col -1 col)))
9010 (defun org-table-move-column-right ()
9011 "Move column to the right."
9012 (interactive)
9013 (org-table-move-column nil))
9014 (defun org-table-move-column-left ()
9015 "Move column to the left."
9016 (interactive)
9017 (org-table-move-column 'left))
9019 (defun org-table-move-column (&optional left)
9020 "Move the current column to the right. With arg LEFT, move to the left."
9021 (interactive "P")
9022 (if (not (org-at-table-p))
9023 (error "Not at a table"))
9024 (org-table-find-dataline)
9025 (org-table-check-inside-data-field)
9026 (let* ((col (org-table-current-column))
9027 (col1 (if left (1- col) col))
9028 (beg (org-table-begin))
9029 (end (org-table-end))
9030 ;; Current cursor position
9031 (linepos (org-current-line))
9032 (colpos (if left (1- col) (1+ col))))
9033 (if (and left (= col 1))
9034 (error "Cannot move column further left"))
9035 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9036 (error "Cannot move column further right"))
9037 (goto-char beg)
9038 (while (< (point) end)
9039 (if (org-at-table-hline-p)
9041 (org-table-goto-column col1 t)
9042 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9043 (replace-match "|\\2|\\1|")))
9044 (beginning-of-line 2))
9045 (move-marker end nil)
9046 (goto-line linepos)
9047 (org-table-goto-column colpos)
9048 (org-table-align)
9049 (org-table-fix-formulas
9050 "$" (list (cons (number-to-string col) (number-to-string colpos))
9051 (cons (number-to-string colpos) (number-to-string col))))))
9053 (defun org-table-move-row-down ()
9054 "Move table row down."
9055 (interactive)
9056 (org-table-move-row nil))
9057 (defun org-table-move-row-up ()
9058 "Move table row up."
9059 (interactive)
9060 (org-table-move-row 'up))
9062 (defun org-table-move-row (&optional up)
9063 "Move the current table line down. With arg UP, move it up."
9064 (interactive "P")
9065 (let* ((col (current-column))
9066 (pos (point))
9067 (hline1p (save-excursion (beginning-of-line 1)
9068 (looking-at org-table-hline-regexp)))
9069 (dline1 (org-table-current-dline))
9070 (dline2 (+ dline1 (if up -1 1)))
9071 (tonew (if up 0 2))
9072 txt hline2p)
9073 (beginning-of-line tonew)
9074 (unless (org-at-table-p)
9075 (goto-char pos)
9076 (error "Cannot move row further"))
9077 (setq hline2p (looking-at org-table-hline-regexp))
9078 (goto-char pos)
9079 (beginning-of-line 1)
9080 (setq pos (point))
9081 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9082 (delete-region (point) (1+ (point-at-eol)))
9083 (beginning-of-line tonew)
9084 (insert txt)
9085 (beginning-of-line 0)
9086 (move-to-column col)
9087 (unless (or hline1p hline2p)
9088 (org-table-fix-formulas
9089 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9090 (cons (number-to-string dline2) (number-to-string dline1)))))))
9092 (defun org-table-insert-row (&optional arg)
9093 "Insert a new row above the current line into the table.
9094 With prefix ARG, insert below the current line."
9095 (interactive "P")
9096 (if (not (org-at-table-p))
9097 (error "Not at a table"))
9098 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9099 (new (org-table-clean-line line)))
9100 ;; Fix the first field if necessary
9101 (if (string-match "^[ \t]*| *[#$] *|" line)
9102 (setq new (replace-match (match-string 0 line) t t new)))
9103 (beginning-of-line (if arg 2 1))
9104 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9105 (beginning-of-line 0)
9106 (re-search-forward "| ?" (point-at-eol) t)
9107 (and (or org-table-may-need-update org-table-overlay-coordinates)
9108 (org-table-align))
9109 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9111 (defun org-table-insert-hline (&optional above)
9112 "Insert a horizontal-line below the current line into the table.
9113 With prefix ABOVE, insert above the current line."
9114 (interactive "P")
9115 (if (not (org-at-table-p))
9116 (error "Not at a table"))
9117 (let ((line (org-table-clean-line
9118 (buffer-substring (point-at-bol) (point-at-eol))))
9119 (col (current-column)))
9120 (while (string-match "|\\( +\\)|" line)
9121 (setq line (replace-match
9122 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9123 ?-) "|") t t line)))
9124 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9125 (beginning-of-line (if above 1 2))
9126 (insert line "\n")
9127 (beginning-of-line (if above 1 -1))
9128 (move-to-column col)
9129 (and org-table-overlay-coordinates (org-table-align))))
9131 (defun org-table-hline-and-move (&optional same-column)
9132 "Insert a hline and move to the row below that line."
9133 (interactive "P")
9134 (let ((col (org-table-current-column)))
9135 (org-table-maybe-eval-formula)
9136 (org-table-maybe-recalculate-line)
9137 (org-table-insert-hline)
9138 (end-of-line 2)
9139 (if (looking-at "\n[ \t]*|-")
9140 (progn (insert "\n|") (org-table-align))
9141 (org-table-next-field))
9142 (if same-column (org-table-goto-column col))))
9144 (defun org-table-clean-line (s)
9145 "Convert a table line S into a string with only \"|\" and space.
9146 In particular, this does handle wide and invisible characters."
9147 (if (string-match "^[ \t]*|-" s)
9148 ;; It's a hline, just map the characters
9149 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9150 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9151 (setq s (replace-match
9152 (concat "|" (make-string (org-string-width (match-string 1 s))
9153 ?\ ) "|")
9154 t t s)))
9157 (defun org-table-kill-row ()
9158 "Delete the current row or horizontal line from the table."
9159 (interactive)
9160 (if (not (org-at-table-p))
9161 (error "Not at a table"))
9162 (let ((col (current-column))
9163 (dline (org-table-current-dline)))
9164 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9165 (if (not (org-at-table-p)) (beginning-of-line 0))
9166 (move-to-column col)
9167 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9168 dline -1 dline)))
9170 (defun org-table-sort-lines (with-case &optional sorting-type)
9171 "Sort table lines according to the column at point.
9173 The position of point indicates the column to be used for
9174 sorting, and the range of lines is the range between the nearest
9175 horizontal separator lines, or the entire table of no such lines
9176 exist. If point is before the first column, you will be prompted
9177 for the sorting column. If there is an active region, the mark
9178 specifies the first line and the sorting column, while point
9179 should be in the last line to be included into the sorting.
9181 The command then prompts for the sorting type which can be
9182 alphabetically, numerically, or by time (as given in a time stamp
9183 in the field). Sorting in reverse order is also possible.
9185 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9187 If SORTING-TYPE is specified when this function is called from a Lisp
9188 program, no prompting will take place. SORTING-TYPE must be a character,
9189 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9190 should be done in reverse order."
9191 (interactive "P")
9192 (let* ((thisline (org-current-line))
9193 (thiscol (org-table-current-column))
9194 beg end bcol ecol tend tbeg column lns pos)
9195 (when (equal thiscol 0)
9196 (if (interactive-p)
9197 (setq thiscol
9198 (string-to-number
9199 (read-string "Use column N for sorting: ")))
9200 (setq thiscol 1))
9201 (org-table-goto-column thiscol))
9202 (org-table-check-inside-data-field)
9203 (if (org-region-active-p)
9204 (progn
9205 (setq beg (region-beginning) end (region-end))
9206 (goto-char beg)
9207 (setq column (org-table-current-column)
9208 beg (point-at-bol))
9209 (goto-char end)
9210 (setq end (point-at-bol 2)))
9211 (setq column (org-table-current-column)
9212 pos (point)
9213 tbeg (org-table-begin)
9214 tend (org-table-end))
9215 (if (re-search-backward org-table-hline-regexp tbeg t)
9216 (setq beg (point-at-bol 2))
9217 (goto-char tbeg)
9218 (setq beg (point-at-bol 1)))
9219 (goto-char pos)
9220 (if (re-search-forward org-table-hline-regexp tend t)
9221 (setq end (point-at-bol 1))
9222 (goto-char tend)
9223 (setq end (point-at-bol))))
9224 (setq beg (move-marker (make-marker) beg)
9225 end (move-marker (make-marker) end))
9226 (untabify beg end)
9227 (goto-char beg)
9228 (org-table-goto-column column)
9229 (skip-chars-backward "^|")
9230 (setq bcol (current-column))
9231 (org-table-goto-column (1+ column))
9232 (skip-chars-backward "^|")
9233 (setq ecol (1- (current-column)))
9234 (org-table-goto-column column)
9235 (setq lns (mapcar (lambda(x) (cons
9236 (org-sort-remove-invisible
9237 (nth (1- column)
9238 (org-split-string x "[ \t]*|[ \t]*")))
9240 (org-split-string (buffer-substring beg end) "\n")))
9241 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9242 (delete-region beg end)
9243 (move-marker beg nil)
9244 (move-marker end nil)
9245 (insert (mapconcat 'cdr lns "\n") "\n")
9246 (goto-line thisline)
9247 (org-table-goto-column thiscol)
9248 (message "%d lines sorted, based on column %d" (length lns) column)))
9250 ;; FIXME: maybe we will not need this? Table sorting is broken....
9251 (defun org-sort-remove-invisible (s)
9252 (remove-text-properties 0 (length s) org-rm-props s)
9253 (while (string-match org-bracket-link-regexp s)
9254 (setq s (replace-match (if (match-end 2)
9255 (match-string 3 s)
9256 (match-string 1 s)) t t s)))
9259 (defun org-table-cut-region (beg end)
9260 "Copy region in table to the clipboard and blank all relevant fields."
9261 (interactive "r")
9262 (org-table-copy-region beg end 'cut))
9264 (defun org-table-copy-region (beg end &optional cut)
9265 "Copy rectangular region in table to clipboard.
9266 A special clipboard is used which can only be accessed
9267 with `org-table-paste-rectangle'."
9268 (interactive "rP")
9269 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9270 region cols
9271 (rpl (if cut " " nil)))
9272 (goto-char beg)
9273 (org-table-check-inside-data-field)
9274 (setq l01 (org-current-line)
9275 c01 (org-table-current-column))
9276 (goto-char end)
9277 (org-table-check-inside-data-field)
9278 (setq l02 (org-current-line)
9279 c02 (org-table-current-column))
9280 (setq l1 (min l01 l02) l2 (max l01 l02)
9281 c1 (min c01 c02) c2 (max c01 c02))
9282 (catch 'exit
9283 (while t
9284 (catch 'nextline
9285 (if (> l1 l2) (throw 'exit t))
9286 (goto-line l1)
9287 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9288 (setq cols nil ic1 c1 ic2 c2)
9289 (while (< ic1 (1+ ic2))
9290 (push (org-table-get-field ic1 rpl) cols)
9291 (setq ic1 (1+ ic1)))
9292 (push (nreverse cols) region)
9293 (setq l1 (1+ l1)))))
9294 (setq org-table-clip (nreverse region))
9295 (if cut (org-table-align))
9296 org-table-clip))
9298 (defun org-table-paste-rectangle ()
9299 "Paste a rectangular region into a table.
9300 The upper right corner ends up in the current field. All involved fields
9301 will be overwritten. If the rectangle does not fit into the present table,
9302 the table is enlarged as needed. The process ignores horizontal separator
9303 lines."
9304 (interactive)
9305 (unless (and org-table-clip (listp org-table-clip))
9306 (error "First cut/copy a region to paste!"))
9307 (org-table-check-inside-data-field)
9308 (let* ((clip org-table-clip)
9309 (line (org-current-line))
9310 (col (org-table-current-column))
9311 (org-enable-table-editor t)
9312 (org-table-automatic-realign nil)
9313 c cols field)
9314 (while (setq cols (pop clip))
9315 (while (org-at-table-hline-p) (beginning-of-line 2))
9316 (if (not (org-at-table-p))
9317 (progn (end-of-line 0) (org-table-next-field)))
9318 (setq c col)
9319 (while (setq field (pop cols))
9320 (org-table-goto-column c nil 'force)
9321 (org-table-get-field nil field)
9322 (setq c (1+ c)))
9323 (beginning-of-line 2))
9324 (goto-line line)
9325 (org-table-goto-column col)
9326 (org-table-align)))
9328 (defun org-table-convert ()
9329 "Convert from `org-mode' table to table.el and back.
9330 Obviously, this only works within limits. When an Org-mode table is
9331 converted to table.el, all horizontal separator lines get lost, because
9332 table.el uses these as cell boundaries and has no notion of horizontal lines.
9333 A table.el table can be converted to an Org-mode table only if it does not
9334 do row or column spanning. Multiline cells will become multiple cells.
9335 Beware, Org-mode does not test if the table can be successfully converted - it
9336 blindly applies a recipe that works for simple tables."
9337 (interactive)
9338 (require 'table)
9339 (if (org-at-table.el-p)
9340 ;; convert to Org-mode table
9341 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9342 (end (move-marker (make-marker) (org-table-end t))))
9343 (table-unrecognize-region beg end)
9344 (goto-char beg)
9345 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9346 (replace-match ""))
9347 (goto-char beg))
9348 (if (org-at-table-p)
9349 ;; convert to table.el table
9350 (let ((beg (move-marker (make-marker) (org-table-begin)))
9351 (end (move-marker (make-marker) (org-table-end))))
9352 ;; first, get rid of all horizontal lines
9353 (goto-char beg)
9354 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9355 (replace-match ""))
9356 ;; insert a hline before first
9357 (goto-char beg)
9358 (org-table-insert-hline 'above)
9359 (beginning-of-line -1)
9360 ;; insert a hline after each line
9361 (while (progn (beginning-of-line 3) (< (point) end))
9362 (org-table-insert-hline))
9363 (goto-char beg)
9364 (setq end (move-marker end (org-table-end)))
9365 ;; replace "+" at beginning and ending of hlines
9366 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9367 (replace-match "\\1+-"))
9368 (goto-char beg)
9369 (while (re-search-forward "-|[ \t]*$" end t)
9370 (replace-match "-+"))
9371 (goto-char beg)))))
9373 (defun org-table-wrap-region (arg)
9374 "Wrap several fields in a column like a paragraph.
9375 This is useful if you'd like to spread the contents of a field over several
9376 lines, in order to keep the table compact.
9378 If there is an active region, and both point and mark are in the same column,
9379 the text in the column is wrapped to minimum width for the given number of
9380 lines. Generally, this makes the table more compact. A prefix ARG may be
9381 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9382 formats the selected text to two lines. If the region was longer than two
9383 lines, the remaining lines remain empty. A negative prefix argument reduces
9384 the current number of lines by that amount. The wrapped text is pasted back
9385 into the table. If you formatted it to more lines than it was before, fields
9386 further down in the table get overwritten - so you might need to make space in
9387 the table first.
9389 If there is no region, the current field is split at the cursor position and
9390 the text fragment to the right of the cursor is prepended to the field one
9391 line down.
9393 If there is no region, but you specify a prefix ARG, the current field gets
9394 blank, and the content is appended to the field above."
9395 (interactive "P")
9396 (org-table-check-inside-data-field)
9397 (if (org-region-active-p)
9398 ;; There is a region: fill as a paragraph
9399 (let* ((beg (region-beginning))
9400 (cline (save-excursion (goto-char beg) (org-current-line)))
9401 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9402 nlines)
9403 (org-table-cut-region (region-beginning) (region-end))
9404 (if (> (length (car org-table-clip)) 1)
9405 (error "Region must be limited to single column"))
9406 (setq nlines (if arg
9407 (if (< arg 1)
9408 (+ (length org-table-clip) arg)
9409 arg)
9410 (length org-table-clip)))
9411 (setq org-table-clip
9412 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9413 nil nlines)))
9414 (goto-line cline)
9415 (org-table-goto-column ccol)
9416 (org-table-paste-rectangle))
9417 ;; No region, split the current field at point
9418 (if arg
9419 ;; combine with field above
9420 (let ((s (org-table-blank-field))
9421 (col (org-table-current-column)))
9422 (beginning-of-line 0)
9423 (while (org-at-table-hline-p) (beginning-of-line 0))
9424 (org-table-goto-column col)
9425 (skip-chars-forward "^|")
9426 (skip-chars-backward " ")
9427 (insert " " (org-trim s))
9428 (org-table-align))
9429 ;; split field
9430 (when (looking-at "\\([^|]+\\)+|")
9431 (let ((s (match-string 1)))
9432 (replace-match " |")
9433 (goto-char (match-beginning 0))
9434 (org-table-next-row)
9435 (insert (org-trim s) " ")
9436 (org-table-align))))))
9438 (defvar org-field-marker nil)
9440 (defun org-table-edit-field (arg)
9441 "Edit table field in a different window.
9442 This is mainly useful for fields that contain hidden parts.
9443 When called with a \\[universal-argument] prefix, just make the full field visible so that
9444 it can be edited in place."
9445 (interactive "P")
9446 (if arg
9447 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9448 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9449 (remove-text-properties b e '(org-cwidth t invisible t
9450 display t intangible t))
9451 (if (and (boundp 'font-lock-mode) font-lock-mode)
9452 (font-lock-fontify-block)))
9453 (let ((pos (move-marker (make-marker) (point)))
9454 (field (org-table-get-field))
9455 (cw (current-window-configuration))
9457 (org-switch-to-buffer-other-window "*Org tmp*")
9458 (erase-buffer)
9459 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9460 (let ((org-inhibit-startup t)) (org-mode))
9461 (goto-char (setq p (point-max)))
9462 (insert (org-trim field))
9463 (remove-text-properties p (point-max)
9464 '(invisible t org-cwidth t display t
9465 intangible t))
9466 (goto-char p)
9467 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9468 (org-set-local 'org-window-configuration cw)
9469 (org-set-local 'org-field-marker pos)
9470 (message "Edit and finish with C-c C-c"))))
9472 (defun org-table-finish-edit-field ()
9473 "Finish editing a table data field.
9474 Remove all newline characters, insert the result into the table, realign
9475 the table and kill the editing buffer."
9476 (let ((pos org-field-marker)
9477 (cw org-window-configuration)
9478 (cb (current-buffer))
9479 text)
9480 (goto-char (point-min))
9481 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9482 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9483 (replace-match " "))
9484 (setq text (org-trim (buffer-string)))
9485 (set-window-configuration cw)
9486 (kill-buffer cb)
9487 (select-window (get-buffer-window (marker-buffer pos)))
9488 (goto-char pos)
9489 (move-marker pos nil)
9490 (org-table-check-inside-data-field)
9491 (org-table-get-field nil text)
9492 (org-table-align)
9493 (message "New field value inserted")))
9495 (defun org-trim (s)
9496 "Remove whitespace at beginning and end of string."
9497 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9498 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9501 (defun org-wrap (string &optional width lines)
9502 "Wrap string to either a number of lines, or a width in characters.
9503 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9504 that costs. If there is a word longer than WIDTH, the text is actually
9505 wrapped to the length of that word.
9506 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9507 many lines, whatever width that takes.
9508 The return value is a list of lines, without newlines at the end."
9509 (let* ((words (org-split-string string "[ \t\n]+"))
9510 (maxword (apply 'max (mapcar 'org-string-width words)))
9511 w ll)
9512 (cond (width
9513 (org-do-wrap words (max maxword width)))
9514 (lines
9515 (setq w maxword)
9516 (setq ll (org-do-wrap words maxword))
9517 (if (<= (length ll) lines)
9519 (setq ll words)
9520 (while (> (length ll) lines)
9521 (setq w (1+ w))
9522 (setq ll (org-do-wrap words w)))
9523 ll))
9524 (t (error "Cannot wrap this")))))
9527 (defun org-do-wrap (words width)
9528 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9529 (let (lines line)
9530 (while words
9531 (setq line (pop words))
9532 (while (and words (< (+ (length line) (length (car words))) width))
9533 (setq line (concat line " " (pop words))))
9534 (setq lines (push line lines)))
9535 (nreverse lines)))
9537 (defun org-split-string (string &optional separators)
9538 "Splits STRING into substrings at SEPARATORS.
9539 No empty strings are returned if there are matches at the beginning
9540 and end of string."
9541 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9542 (start 0)
9543 notfirst
9544 (list nil))
9545 (while (and (string-match rexp string
9546 (if (and notfirst
9547 (= start (match-beginning 0))
9548 (< start (length string)))
9549 (1+ start) start))
9550 (< (match-beginning 0) (length string)))
9551 (setq notfirst t)
9552 (or (eq (match-beginning 0) 0)
9553 (and (eq (match-beginning 0) (match-end 0))
9554 (eq (match-beginning 0) start))
9555 (setq list
9556 (cons (substring string start (match-beginning 0))
9557 list)))
9558 (setq start (match-end 0)))
9559 (or (eq start (length string))
9560 (setq list
9561 (cons (substring string start)
9562 list)))
9563 (nreverse list)))
9565 (defun org-table-map-tables (function)
9566 "Apply FUNCTION to the start of all tables in the buffer."
9567 (save-excursion
9568 (save-restriction
9569 (widen)
9570 (goto-char (point-min))
9571 (while (re-search-forward org-table-any-line-regexp nil t)
9572 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9573 (beginning-of-line 1)
9574 (if (looking-at org-table-line-regexp)
9575 (save-excursion (funcall function)))
9576 (re-search-forward org-table-any-border-regexp nil 1))))
9577 (message "Mapping tables: done"))
9579 (defvar org-timecnt) ; dynamically scoped parameter
9581 (defun org-table-sum (&optional beg end nlast)
9582 "Sum numbers in region of current table column.
9583 The result will be displayed in the echo area, and will be available
9584 as kill to be inserted with \\[yank].
9586 If there is an active region, it is interpreted as a rectangle and all
9587 numbers in that rectangle will be summed. If there is no active
9588 region and point is located in a table column, sum all numbers in that
9589 column.
9591 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9592 numbers are assumed to be times as well (in decimal hours) and the
9593 numbers are added as such.
9595 If NLAST is a number, only the NLAST fields will actually be summed."
9596 (interactive)
9597 (save-excursion
9598 (let (col (org-timecnt 0) diff h m s org-table-clip)
9599 (cond
9600 ((and beg end)) ; beg and end given explicitly
9601 ((org-region-active-p)
9602 (setq beg (region-beginning) end (region-end)))
9604 (setq col (org-table-current-column))
9605 (goto-char (org-table-begin))
9606 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9607 (error "No table data"))
9608 (org-table-goto-column col)
9609 (setq beg (point))
9610 (goto-char (org-table-end))
9611 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9612 (error "No table data"))
9613 (org-table-goto-column col)
9614 (setq end (point))))
9615 (let* ((items (apply 'append (org-table-copy-region beg end)))
9616 (items1 (cond ((not nlast) items)
9617 ((>= nlast (length items)) items)
9618 (t (setq items (reverse items))
9619 (setcdr (nthcdr (1- nlast) items) nil)
9620 (nreverse items))))
9621 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9622 items1)))
9623 (res (apply '+ numbers))
9624 (sres (if (= org-timecnt 0)
9625 (format "%g" res)
9626 (setq diff (* 3600 res)
9627 h (floor (/ diff 3600)) diff (mod diff 3600)
9628 m (floor (/ diff 60)) diff (mod diff 60)
9629 s diff)
9630 (format "%d:%02d:%02d" h m s))))
9631 (kill-new sres)
9632 (if (interactive-p)
9633 (message "%s"
9634 (substitute-command-keys
9635 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9636 (length numbers) sres))))
9637 sres))))
9639 (defun org-table-get-number-for-summing (s)
9640 (let (n)
9641 (if (string-match "^ *|? *" s)
9642 (setq s (replace-match "" nil nil s)))
9643 (if (string-match " *|? *$" s)
9644 (setq s (replace-match "" nil nil s)))
9645 (setq n (string-to-number s))
9646 (cond
9647 ((and (string-match "0" s)
9648 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9649 ((string-match "\\`[ \t]+\\'" s) nil)
9650 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9651 (let ((h (string-to-number (or (match-string 1 s) "0")))
9652 (m (string-to-number (or (match-string 2 s) "0")))
9653 (s (string-to-number (or (match-string 4 s) "0"))))
9654 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9655 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9656 ((equal n 0) nil)
9657 (t n))))
9659 (defun org-table-current-field-formula (&optional key noerror)
9660 "Return the formula active for the current field.
9661 Assumes that specials are in place.
9662 If KEY is given, return the key to this formula.
9663 Otherwise return the formula preceeded with \"=\" or \":=\"."
9664 (let* ((name (car (rassoc (list (org-current-line)
9665 (org-table-current-column))
9666 org-table-named-field-locations)))
9667 (col (org-table-current-column))
9668 (scol (int-to-string col))
9669 (ref (format "@%d$%d" (org-table-current-dline) col))
9670 (stored-list (org-table-get-stored-formulas noerror))
9671 (ass (or (assoc name stored-list)
9672 (assoc ref stored-list)
9673 (assoc scol stored-list))))
9674 (if key
9675 (car ass)
9676 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9677 (cdr ass))))))
9679 (defun org-table-get-formula (&optional equation named)
9680 "Read a formula from the minibuffer, offer stored formula as default.
9681 When NAMED is non-nil, look for a named equation."
9682 (let* ((stored-list (org-table-get-stored-formulas))
9683 (name (car (rassoc (list (org-current-line)
9684 (org-table-current-column))
9685 org-table-named-field-locations)))
9686 (ref (format "@%d$%d" (org-table-current-dline)
9687 (org-table-current-column)))
9688 (refass (assoc ref stored-list))
9689 (scol (if named
9690 (if name name ref)
9691 (int-to-string (org-table-current-column))))
9692 (dummy (and (or name refass) (not named)
9693 (not (y-or-n-p "Replace field formula with column formula? " ))
9694 (error "Abort")))
9695 (name (or name ref))
9696 (org-table-may-need-update nil)
9697 (stored (cdr (assoc scol stored-list)))
9698 (eq (cond
9699 ((and stored equation (string-match "^ *=? *$" equation))
9700 stored)
9701 ((stringp equation)
9702 equation)
9703 (t (org-table-formula-from-user
9704 (read-string
9705 (org-table-formula-to-user
9706 (format "%s formula %s%s="
9707 (if named "Field" "Column")
9708 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9709 scol))
9710 (if stored (org-table-formula-to-user stored) "")
9711 'org-table-formula-history
9712 )))))
9713 mustsave)
9714 (when (not (string-match "\\S-" eq))
9715 ;; remove formula
9716 (setq stored-list (delq (assoc scol stored-list) stored-list))
9717 (org-table-store-formulas stored-list)
9718 (error "Formula removed"))
9719 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9720 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9721 (if (and name (not named))
9722 ;; We set the column equation, delete the named one.
9723 (setq stored-list (delq (assoc name stored-list) stored-list)
9724 mustsave t))
9725 (if stored
9726 (setcdr (assoc scol stored-list) eq)
9727 (setq stored-list (cons (cons scol eq) stored-list)))
9728 (if (or mustsave (not (equal stored eq)))
9729 (org-table-store-formulas stored-list))
9730 eq))
9732 (defun org-table-store-formulas (alist)
9733 "Store the list of formulas below the current table."
9734 (setq alist (sort alist 'org-table-formula-less-p))
9735 (save-excursion
9736 (goto-char (org-table-end))
9737 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9738 (progn
9739 ;; don't overwrite TBLFM, we might use text properties to store stuff
9740 (goto-char (match-beginning 2))
9741 (delete-region (match-beginning 2) (match-end 0)))
9742 (insert "#+TBLFM:"))
9743 (insert " "
9744 (mapconcat (lambda (x)
9745 (concat
9746 (if (equal (string-to-char (car x)) ?@) "" "$")
9747 (car x) "=" (cdr x)))
9748 alist "::")
9749 "\n")))
9751 (defsubst org-table-formula-make-cmp-string (a)
9752 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9753 (concat
9754 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9755 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9756 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9758 (defun org-table-formula-less-p (a b)
9759 "Compare two formulas for sorting."
9760 (let ((as (org-table-formula-make-cmp-string (car a)))
9761 (bs (org-table-formula-make-cmp-string (car b))))
9762 (and as bs (string< as bs))))
9764 (defun org-table-get-stored-formulas (&optional noerror)
9765 "Return an alist with the stored formulas directly after current table."
9766 (interactive)
9767 (let (scol eq eq-alist strings string seen)
9768 (save-excursion
9769 (goto-char (org-table-end))
9770 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9771 (setq strings (org-split-string (match-string 2) " *:: *"))
9772 (while (setq string (pop strings))
9773 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9774 (setq scol (if (match-end 2)
9775 (match-string 2 string)
9776 (match-string 1 string))
9777 eq (match-string 3 string)
9778 eq-alist (cons (cons scol eq) eq-alist))
9779 (if (member scol seen)
9780 (if noerror
9781 (progn
9782 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9783 (ding)
9784 (sit-for 2))
9785 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9786 (push scol seen))))))
9787 (nreverse eq-alist)))
9789 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9790 "Modify the equations after the table structure has been edited.
9791 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9792 For all numbers larger than LIMIT, shift them by DELTA."
9793 (save-excursion
9794 (goto-char (org-table-end))
9795 (when (looking-at "#\\+TBLFM:")
9796 (let ((re (concat key "\\([0-9]+\\)"))
9797 (re2
9798 (when remove
9799 (if (equal key "$")
9800 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9801 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9802 s n a)
9803 (when remove
9804 (while (re-search-forward re2 (point-at-eol) t)
9805 (replace-match "")))
9806 (while (re-search-forward re (point-at-eol) t)
9807 (setq s (match-string 1) n (string-to-number s))
9808 (cond
9809 ((setq a (assoc s replace))
9810 (replace-match (concat key (cdr a)) t t))
9811 ((and limit (> n limit))
9812 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9814 (defun org-table-get-specials ()
9815 "Get the column names and local parameters for this table."
9816 (save-excursion
9817 (let ((beg (org-table-begin)) (end (org-table-end))
9818 names name fields fields1 field cnt
9819 c v l line col types dlines hlines)
9820 (setq org-table-column-names nil
9821 org-table-local-parameters nil
9822 org-table-named-field-locations nil
9823 org-table-current-begin-line nil
9824 org-table-current-begin-pos nil
9825 org-table-current-line-types nil)
9826 (goto-char beg)
9827 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9828 (setq names (org-split-string (match-string 1) " *| *")
9829 cnt 1)
9830 (while (setq name (pop names))
9831 (setq cnt (1+ cnt))
9832 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9833 (push (cons name (int-to-string cnt)) org-table-column-names))))
9834 (setq org-table-column-names (nreverse org-table-column-names))
9835 (setq org-table-column-name-regexp
9836 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9837 (goto-char beg)
9838 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9839 (setq fields (org-split-string (match-string 1) " *| *"))
9840 (while (setq field (pop fields))
9841 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9842 (push (cons (match-string 1 field) (match-string 2 field))
9843 org-table-local-parameters))))
9844 (goto-char beg)
9845 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9846 (setq c (match-string 1)
9847 fields (org-split-string (match-string 2) " *| *"))
9848 (save-excursion
9849 (beginning-of-line (if (equal c "_") 2 0))
9850 (setq line (org-current-line) col 1)
9851 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9852 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9853 (while (and fields1 (setq field (pop fields)))
9854 (setq v (pop fields1) col (1+ col))
9855 (when (and (stringp field) (stringp v)
9856 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9857 (push (cons field v) org-table-local-parameters)
9858 (push (list field line col) org-table-named-field-locations))))
9859 ;; Analyse the line types
9860 (goto-char beg)
9861 (setq org-table-current-begin-line (org-current-line)
9862 org-table-current-begin-pos (point)
9863 l org-table-current-begin-line)
9864 (while (looking-at "[ \t]*|\\(-\\)?")
9865 (push (if (match-end 1) 'hline 'dline) types)
9866 (if (match-end 1) (push l hlines) (push l dlines))
9867 (beginning-of-line 2)
9868 (setq l (1+ l)))
9869 (setq org-table-current-line-types (apply 'vector (nreverse types))
9870 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9871 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9873 (defun org-table-maybe-eval-formula ()
9874 "Check if the current field starts with \"=\" or \":=\".
9875 If yes, store the formula and apply it."
9876 ;; We already know we are in a table. Get field will only return a formula
9877 ;; when appropriate. It might return a separator line, but no problem.
9878 (when org-table-formula-evaluate-inline
9879 (let* ((field (org-trim (or (org-table-get-field) "")))
9880 named eq)
9881 (when (string-match "^:?=\\(.*\\)" field)
9882 (setq named (equal (string-to-char field) ?:)
9883 eq (match-string 1 field))
9884 (if (or (fboundp 'calc-eval)
9885 (equal (substring eq 0 (min 2 (length eq))) "'("))
9886 (org-table-eval-formula (if named '(4) nil)
9887 (org-table-formula-from-user eq))
9888 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9890 (defvar org-recalc-commands nil
9891 "List of commands triggering the recalculation of a line.
9892 Will be filled automatically during use.")
9894 (defvar org-recalc-marks
9895 '((" " . "Unmarked: no special line, no automatic recalculation")
9896 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9897 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9898 ("!" . "Column name definition line. Reference in formula as $name.")
9899 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9900 ("_" . "Names for values in row below this one.")
9901 ("^" . "Names for values in row above this one.")))
9903 (defun org-table-rotate-recalc-marks (&optional newchar)
9904 "Rotate the recalculation mark in the first column.
9905 If in any row, the first field is not consistent with a mark,
9906 insert a new column for the markers.
9907 When there is an active region, change all the lines in the region,
9908 after prompting for the marking character.
9909 After each change, a message will be displayed indicating the meaning
9910 of the new mark."
9911 (interactive)
9912 (unless (org-at-table-p) (error "Not at a table"))
9913 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9914 (beg (org-table-begin))
9915 (end (org-table-end))
9916 (l (org-current-line))
9917 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9918 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9919 (have-col
9920 (save-excursion
9921 (goto-char beg)
9922 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9923 (col (org-table-current-column))
9924 (forcenew (car (assoc newchar org-recalc-marks)))
9925 epos new)
9926 (when l1
9927 (message "Change region to what mark? Type # * ! $ or SPC: ")
9928 (setq newchar (char-to-string (read-char-exclusive))
9929 forcenew (car (assoc newchar org-recalc-marks))))
9930 (if (and newchar (not forcenew))
9931 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9932 newchar))
9933 (if l1 (goto-line l1))
9934 (save-excursion
9935 (beginning-of-line 1)
9936 (unless (looking-at org-table-dataline-regexp)
9937 (error "Not at a table data line")))
9938 (unless have-col
9939 (org-table-goto-column 1)
9940 (org-table-insert-column)
9941 (org-table-goto-column (1+ col)))
9942 (setq epos (point-at-eol))
9943 (save-excursion
9944 (beginning-of-line 1)
9945 (org-table-get-field
9946 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9947 (concat " "
9948 (setq new (or forcenew
9949 (cadr (member (match-string 1) marks))))
9950 " ")
9951 " # ")))
9952 (if (and l1 l2)
9953 (progn
9954 (goto-line l1)
9955 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9956 (and (looking-at org-table-dataline-regexp)
9957 (org-table-get-field 1 (concat " " new " "))))
9958 (goto-line l1)))
9959 (if (not (= epos (point-at-eol))) (org-table-align))
9960 (goto-line l)
9961 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
9963 (defun org-table-maybe-recalculate-line ()
9964 "Recompute the current line if marked for it, and if we haven't just done it."
9965 (interactive)
9966 (and org-table-allow-automatic-line-recalculation
9967 (not (and (memq last-command org-recalc-commands)
9968 (equal org-last-recalc-line (org-current-line))))
9969 (save-excursion (beginning-of-line 1)
9970 (looking-at org-table-auto-recalculate-regexp))
9971 (org-table-recalculate) t))
9973 (defvar org-table-formula-debug nil
9974 "Non-nil means, debug table formulas.
9975 When nil, simply write \"#ERROR\" in corrupted fields.")
9976 (make-variable-buffer-local 'org-table-formula-debug)
9978 (defvar modes)
9979 (defsubst org-set-calc-mode (var &optional value)
9980 (if (stringp var)
9981 (setq var (assoc var '(("D" calc-angle-mode deg)
9982 ("R" calc-angle-mode rad)
9983 ("F" calc-prefer-frac t)
9984 ("S" calc-symbolic-mode t)))
9985 value (nth 2 var) var (nth 1 var)))
9986 (if (memq var modes)
9987 (setcar (cdr (memq var modes)) value)
9988 (cons var (cons value modes)))
9989 modes)
9991 (defun org-table-eval-formula (&optional arg equation
9992 suppress-align suppress-const
9993 suppress-store suppress-analysis)
9994 "Replace the table field value at the cursor by the result of a calculation.
9996 This function makes use of Dave Gillespie's Calc package, in my view the
9997 most exciting program ever written for GNU Emacs. So you need to have Calc
9998 installed in order to use this function.
10000 In a table, this command replaces the value in the current field with the
10001 result of a formula. It also installs the formula as the \"current\" column
10002 formula, by storing it in a special line below the table. When called
10003 with a `C-u' prefix, the current field must ba a named field, and the
10004 formula is installed as valid in only this specific field.
10006 When called with two `C-u' prefixes, insert the active equation
10007 for the field back into the current field, so that it can be
10008 edited there. This is useful in order to use \\[org-table-show-reference]
10009 to check the referenced fields.
10011 When called, the command first prompts for a formula, which is read in
10012 the minibuffer. Previously entered formulas are available through the
10013 history list, and the last used formula is offered as a default.
10014 These stored formulas are adapted correctly when moving, inserting, or
10015 deleting columns with the corresponding commands.
10017 The formula can be any algebraic expression understood by the Calc package.
10018 For details, see the Org-mode manual.
10020 This function can also be called from Lisp programs and offers
10021 additional arguments: EQUATION can be the formula to apply. If this
10022 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10023 used to speed-up recursive calls by by-passing unnecessary aligns.
10024 SUPPRESS-CONST suppresses the interpretation of constants in the
10025 formula, assuming that this has been done already outside the function.
10026 SUPPRESS-STORE means the formula should not be stored, either because
10027 it is already stored, or because it is a modified equation that should
10028 not overwrite the stored one."
10029 (interactive "P")
10030 (org-table-check-inside-data-field)
10031 (or suppress-analysis (org-table-get-specials))
10032 (if (equal arg '(16))
10033 (let ((eq (org-table-current-field-formula)))
10034 (or eq (error "No equation active for current field"))
10035 (org-table-get-field nil eq)
10036 (org-table-align)
10037 (setq org-table-may-need-update t))
10038 (let* (fields
10039 (ndown (if (integerp arg) arg 1))
10040 (org-table-automatic-realign nil)
10041 (case-fold-search nil)
10042 (down (> ndown 1))
10043 (formula (if (and equation suppress-store)
10044 equation
10045 (org-table-get-formula equation (equal arg '(4)))))
10046 (n0 (org-table-current-column))
10047 (modes (copy-sequence org-calc-default-modes))
10048 (numbers nil) ; was a variable, now fixed default
10049 (keep-empty nil)
10050 n form form0 bw fmt x ev orig c lispp literal)
10051 ;; Parse the format string. Since we have a lot of modes, this is
10052 ;; a lot of work. However, I think calc still uses most of the time.
10053 (if (string-match ";" formula)
10054 (let ((tmp (org-split-string formula ";")))
10055 (setq formula (car tmp)
10056 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10057 (nth 1 tmp)))
10058 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10059 (setq c (string-to-char (match-string 1 fmt))
10060 n (string-to-number (match-string 2 fmt)))
10061 (if (= c ?p)
10062 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10063 (setq modes (org-set-calc-mode
10064 'calc-float-format
10065 (list (cdr (assoc c '((?n . float) (?f . fix)
10066 (?s . sci) (?e . eng))))
10067 n))))
10068 (setq fmt (replace-match "" t t fmt)))
10069 (if (string-match "[NT]" fmt)
10070 (setq numbers (equal (match-string 0 fmt) "N")
10071 fmt (replace-match "" t t fmt)))
10072 (if (string-match "L" fmt)
10073 (setq literal t
10074 fmt (replace-match "" t t fmt)))
10075 (if (string-match "E" fmt)
10076 (setq keep-empty t
10077 fmt (replace-match "" t t fmt)))
10078 (while (string-match "[DRFS]" fmt)
10079 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10080 (setq fmt (replace-match "" t t fmt)))
10081 (unless (string-match "\\S-" fmt)
10082 (setq fmt nil))))
10083 (if (and (not suppress-const) org-table-formula-use-constants)
10084 (setq formula (org-table-formula-substitute-names formula)))
10085 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10086 (while (> ndown 0)
10087 (setq fields (org-split-string
10088 (org-no-properties
10089 (buffer-substring (point-at-bol) (point-at-eol)))
10090 " *| *"))
10091 (if (eq numbers t)
10092 (setq fields (mapcar
10093 (lambda (x) (number-to-string (string-to-number x)))
10094 fields)))
10095 (setq ndown (1- ndown))
10096 (setq form (copy-sequence formula)
10097 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10098 (if (and lispp literal) (setq lispp 'literal))
10099 ;; Check for old vertical references
10100 (setq form (org-rewrite-old-row-references form))
10101 ;; Insert complex ranges
10102 (while (string-match org-table-range-regexp form)
10103 (setq form
10104 (replace-match
10105 (save-match-data
10106 (org-table-make-reference
10107 (org-table-get-range (match-string 0 form) nil n0)
10108 keep-empty numbers lispp))
10109 t t form)))
10110 ;; Insert simple ranges
10111 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10112 (setq form
10113 (replace-match
10114 (save-match-data
10115 (org-table-make-reference
10116 (org-sublist
10117 fields (string-to-number (match-string 1 form))
10118 (string-to-number (match-string 2 form)))
10119 keep-empty numbers lispp))
10120 t t form)))
10121 (setq form0 form)
10122 ;; Insert the references to fields in same row
10123 (while (string-match "\\$\\([0-9]+\\)" form)
10124 (setq n (string-to-number (match-string 1 form))
10125 x (nth (1- (if (= n 0) n0 n)) fields))
10126 (unless x (error "Invalid field specifier \"%s\""
10127 (match-string 0 form)))
10128 (setq form (replace-match
10129 (save-match-data
10130 (org-table-make-reference x nil numbers lispp))
10131 t t form)))
10133 (if lispp
10134 (setq ev (condition-case nil
10135 (eval (eval (read form)))
10136 (error "#ERROR"))
10137 ev (if (numberp ev) (number-to-string ev) ev))
10138 (or (fboundp 'calc-eval)
10139 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10140 (setq ev (calc-eval (cons form modes)
10141 (if numbers 'num))))
10143 (when org-table-formula-debug
10144 (with-output-to-temp-buffer "*Substitution History*"
10145 (princ (format "Substitution history of formula
10146 Orig: %s
10147 $xyz-> %s
10148 @r$c-> %s
10149 $1-> %s\n" orig formula form0 form))
10150 (if (listp ev)
10151 (princ (format " %s^\nError: %s"
10152 (make-string (car ev) ?\-) (nth 1 ev)))
10153 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10154 ev (or fmt "NONE")
10155 (if fmt (format fmt (string-to-number ev)) ev)))))
10156 (setq bw (get-buffer-window "*Substitution History*"))
10157 (shrink-window-if-larger-than-buffer bw)
10158 (unless (and (interactive-p) (not ndown))
10159 (unless (let (inhibit-redisplay)
10160 (y-or-n-p "Debugging Formula. Continue to next? "))
10161 (org-table-align)
10162 (error "Abort"))
10163 (delete-window bw)
10164 (message "")))
10165 (if (listp ev) (setq fmt nil ev "#ERROR"))
10166 (org-table-justify-field-maybe
10167 (if fmt (format fmt (string-to-number ev)) ev))
10168 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10169 (call-interactively 'org-return)
10170 (setq ndown 0)))
10171 (and down (org-table-maybe-recalculate-line))
10172 (or suppress-align (and org-table-may-need-update
10173 (org-table-align))))))
10175 (defun org-table-put-field-property (prop value)
10176 (save-excursion
10177 (put-text-property (progn (skip-chars-backward "^|") (point))
10178 (progn (skip-chars-forward "^|") (point))
10179 prop value)))
10181 (defun org-table-get-range (desc &optional tbeg col highlight)
10182 "Get a calc vector from a column, accorting to descriptor DESC.
10183 Optional arguments TBEG and COL can give the beginning of the table and
10184 the current column, to avoid unnecessary parsing.
10185 HIGHLIGHT means, just highlight the range."
10186 (if (not (equal (string-to-char desc) ?@))
10187 (setq desc (concat "@" desc)))
10188 (save-excursion
10189 (or tbeg (setq tbeg (org-table-begin)))
10190 (or col (setq col (org-table-current-column)))
10191 (let ((thisline (org-current-line))
10192 beg end c1 c2 r1 r2 rangep tmp)
10193 (unless (string-match org-table-range-regexp desc)
10194 (error "Invalid table range specifier `%s'" desc))
10195 (setq rangep (match-end 3)
10196 r1 (and (match-end 1) (match-string 1 desc))
10197 r2 (and (match-end 4) (match-string 4 desc))
10198 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10199 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10201 (and c1 (setq c1 (+ (string-to-number c1)
10202 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10203 (and c2 (setq c2 (+ (string-to-number c2)
10204 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10205 (if (equal r1 "") (setq r1 nil))
10206 (if (equal r2 "") (setq r2 nil))
10207 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10208 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10209 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10210 (if (not r1) (setq r1 thisline))
10211 (if (not r2) (setq r2 thisline))
10212 (if (not c1) (setq c1 col))
10213 (if (not c2) (setq c2 col))
10214 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10215 ;; just one field
10216 (progn
10217 (goto-line r1)
10218 (while (not (looking-at org-table-dataline-regexp))
10219 (beginning-of-line 2))
10220 (prog1 (org-trim (org-table-get-field c1))
10221 (if highlight (org-table-highlight-rectangle (point) (point)))))
10222 ;; A range, return a vector
10223 ;; First sort the numbers to get a regular ractangle
10224 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10225 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10226 (goto-line r1)
10227 (while (not (looking-at org-table-dataline-regexp))
10228 (beginning-of-line 2))
10229 (org-table-goto-column c1)
10230 (setq beg (point))
10231 (goto-line r2)
10232 (while (not (looking-at org-table-dataline-regexp))
10233 (beginning-of-line 0))
10234 (org-table-goto-column c2)
10235 (setq end (point))
10236 (if highlight
10237 (org-table-highlight-rectangle
10238 beg (progn (skip-chars-forward "^|\n") (point))))
10239 ;; return string representation of calc vector
10240 (mapcar 'org-trim
10241 (apply 'append (org-table-copy-region beg end)))))))
10243 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10244 "Analyze descriptor DESC and retrieve the corresponding line number.
10245 The cursor is currently in line CLINE, the table begins in line BLINE,
10246 and TABLE is a vector with line types."
10247 (if (string-match "^[0-9]+$" desc)
10248 (aref org-table-dlines (string-to-number desc))
10249 (setq cline (or cline (org-current-line))
10250 bline (or bline org-table-current-begin-line)
10251 table (or table org-table-current-line-types))
10252 (if (or
10253 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10254 ;; 1 2 3 4 5 6
10255 (and (not (match-end 3)) (not (match-end 6)))
10256 (and (match-end 3) (match-end 6) (not (match-end 5))))
10257 (error "invalid row descriptor `%s'" desc))
10258 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10259 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10260 (odir (and (match-end 5) (match-string 5 desc)))
10261 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10262 (i (- cline bline))
10263 (rel (and (match-end 6)
10264 (or (and (match-end 1) (not (match-end 3)))
10265 (match-end 5)))))
10266 (if (and hn (not hdir))
10267 (progn
10268 (setq i 0 hdir "+")
10269 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10270 (if (and (not hn) on (not odir))
10271 (error "should never happen");;(aref org-table-dlines on)
10272 (if (and hn (> hn 0))
10273 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10274 (if on
10275 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10276 (+ bline i)))))
10278 (defun org-find-row-type (table i type backwards relative n)
10279 (let ((l (length table)))
10280 (while (> n 0)
10281 (while (and (setq i (+ i (if backwards -1 1)))
10282 (>= i 0) (< i l)
10283 (not (eq (aref table i) type))
10284 (if (and relative (eq (aref table i) 'hline))
10285 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10286 t)))
10287 (setq n (1- n)))
10288 (if (or (< i 0) (>= i l))
10289 (error "Row descriptior leads outside table")
10290 i)))
10292 (defun org-rewrite-old-row-references (s)
10293 (if (string-match "&[-+0-9I]" s)
10294 (error "Formula contains old &row reference, please rewrite using @-syntax")
10297 (defun org-table-make-reference (elements keep-empty numbers lispp)
10298 "Convert list ELEMENTS to something appropriate to insert into formula.
10299 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10300 NUMBERS indicates that everything should be converted to numbers.
10301 LISPP means to return something appropriate for a Lisp list."
10302 (if (stringp elements) ; just a single val
10303 (if lispp
10304 (if (eq lispp 'literal)
10305 elements
10306 (prin1-to-string (if numbers (string-to-number elements) elements)))
10307 (if (equal elements "") (setq elements "0"))
10308 (if numbers (number-to-string (string-to-number elements)) elements))
10309 (unless keep-empty
10310 (setq elements
10311 (delq nil
10312 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10313 elements))))
10314 (setq elements (or elements '("0")))
10315 (if lispp
10316 (mapconcat
10317 (lambda (x)
10318 (if (eq lispp 'literal)
10320 (prin1-to-string (if numbers (string-to-number x) x))))
10321 elements " ")
10322 (concat "[" (mapconcat
10323 (lambda (x)
10324 (if numbers (number-to-string (string-to-number x)) x))
10325 elements
10326 ",") "]"))))
10328 (defun org-table-recalculate (&optional all noalign)
10329 "Recalculate the current table line by applying all stored formulas.
10330 With prefix arg ALL, do this for all lines in the table."
10331 (interactive "P")
10332 (or (memq this-command org-recalc-commands)
10333 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10334 (unless (org-at-table-p) (error "Not at a table"))
10335 (if (equal all '(16))
10336 (org-table-iterate)
10337 (org-table-get-specials)
10338 (let* ((eqlist (sort (org-table-get-stored-formulas)
10339 (lambda (a b) (string< (car a) (car b)))))
10340 (inhibit-redisplay (not debug-on-error))
10341 (line-re org-table-dataline-regexp)
10342 (thisline (org-current-line))
10343 (thiscol (org-table-current-column))
10344 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10345 ;; Insert constants in all formulas
10346 (setq eqlist
10347 (mapcar (lambda (x)
10348 (setcdr x (org-table-formula-substitute-names (cdr x)))
10350 eqlist))
10351 ;; Split the equation list
10352 (while (setq eq (pop eqlist))
10353 (if (<= (string-to-char (car eq)) ?9)
10354 (push eq eqlnum)
10355 (push eq eqlname)))
10356 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10357 (if all
10358 (progn
10359 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10360 (goto-char (setq beg (org-table-begin)))
10361 (if (re-search-forward org-table-calculate-mark-regexp end t)
10362 ;; This is a table with marked lines, compute selected lines
10363 (setq line-re org-table-recalculate-regexp)
10364 ;; Move forward to the first non-header line
10365 (if (and (re-search-forward org-table-dataline-regexp end t)
10366 (re-search-forward org-table-hline-regexp end t)
10367 (re-search-forward org-table-dataline-regexp end t))
10368 (setq beg (match-beginning 0))
10369 nil))) ;; just leave beg where it is
10370 (setq beg (point-at-bol)
10371 end (move-marker (make-marker) (1+ (point-at-eol)))))
10372 (goto-char beg)
10373 (and all (message "Re-applying formulas to full table..."))
10375 ;; First find the named fields, and mark them untouchanble
10376 (remove-text-properties beg end '(org-untouchable t))
10377 (while (setq eq (pop eqlname))
10378 (setq name (car eq)
10379 a (assoc name org-table-named-field-locations))
10380 (and (not a)
10381 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10382 (setq a (list name
10383 (aref org-table-dlines
10384 (string-to-number (match-string 1 name)))
10385 (string-to-number (match-string 2 name)))))
10386 (when (and a (or all (equal (nth 1 a) thisline)))
10387 (message "Re-applying formula to field: %s" name)
10388 (goto-line (nth 1 a))
10389 (org-table-goto-column (nth 2 a))
10390 (push (append a (list (cdr eq))) eqlname1)
10391 (org-table-put-field-property :org-untouchable t)))
10393 ;; Now evauluate the column formulas, but skip fields covered by
10394 ;; field formulas
10395 (goto-char beg)
10396 (while (re-search-forward line-re end t)
10397 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10398 ;; Unprotected line, recalculate
10399 (and all (message "Re-applying formulas to full table...(line %d)"
10400 (setq cnt (1+ cnt))))
10401 (setq org-last-recalc-line (org-current-line))
10402 (setq eql eqlnum)
10403 (while (setq entry (pop eql))
10404 (goto-line org-last-recalc-line)
10405 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10406 (unless (get-text-property (point) :org-untouchable)
10407 (org-table-eval-formula nil (cdr entry)
10408 'noalign 'nocst 'nostore 'noanalysis)))))
10410 ;; Now evaluate the field formulas
10411 (while (setq eq (pop eqlname1))
10412 (message "Re-applying formula to field: %s" (car eq))
10413 (goto-line (nth 1 eq))
10414 (org-table-goto-column (nth 2 eq))
10415 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10416 'nostore 'noanalysis))
10418 (goto-line thisline)
10419 (org-table-goto-column thiscol)
10420 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10421 (or noalign (and org-table-may-need-update (org-table-align))
10422 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10424 ;; back to initial position
10425 (message "Re-applying formulas...done")
10426 (goto-line thisline)
10427 (org-table-goto-column thiscol)
10428 (or noalign (and org-table-may-need-update (org-table-align))
10429 (and all (message "Re-applying formulas...done"))))))
10431 (defun org-table-iterate (&optional arg)
10432 "Recalculate the table until it does not change anymore."
10433 (interactive "P")
10434 (let ((imax (if arg (prefix-numeric-value arg) 10))
10435 (i 0)
10436 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10437 thistbl)
10438 (catch 'exit
10439 (while (< i imax)
10440 (setq i (1+ i))
10441 (org-table-recalculate 'all)
10442 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10443 (if (not (string= lasttbl thistbl))
10444 (setq lasttbl thistbl)
10445 (if (> i 1)
10446 (message "Convergence after %d iterations" i)
10447 (message "Table was already stable"))
10448 (throw 'exit t)))
10449 (error "No convergence after %d iterations" i))))
10451 (defun org-table-formula-substitute-names (f)
10452 "Replace $const with values in string F."
10453 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10454 ;; First, check for column names
10455 (while (setq start (string-match org-table-column-name-regexp f start))
10456 (setq start (1+ start))
10457 (setq a (assoc (match-string 1 f) org-table-column-names))
10458 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10459 ;; Parameters and constants
10460 (setq start 0)
10461 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10462 (setq start (1+ start))
10463 (if (setq a (save-match-data
10464 (org-table-get-constant (match-string 1 f))))
10465 (setq f (replace-match
10466 (concat (if pp "(") a (if pp ")")) t t f))))
10467 (if org-table-formula-debug
10468 (put-text-property 0 (length f) :orig-formula f1 f))
10471 (defun org-table-get-constant (const)
10472 "Find the value for a parameter or constant in a formula.
10473 Parameters get priority."
10474 (or (cdr (assoc const org-table-local-parameters))
10475 (cdr (assoc const org-table-formula-constants-local))
10476 (cdr (assoc const org-table-formula-constants))
10477 (and (fboundp 'constants-get) (constants-get const))
10478 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10479 (org-entry-get nil (substring const 5) 'inherit))
10480 "#UNDEFINED_NAME"))
10482 (defvar org-table-fedit-map
10483 (let ((map (make-sparse-keymap)))
10484 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10485 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10486 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10487 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10488 (org-defkey map "\C-c?" 'org-table-show-reference)
10489 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10490 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10491 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10492 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10493 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10494 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10495 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10496 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10497 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10498 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10499 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10500 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10501 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10502 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10503 map))
10505 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10506 '("Edit-Formulas"
10507 ["Finish and Install" org-table-fedit-finish t]
10508 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10509 ["Abort" org-table-fedit-abort t]
10510 "--"
10511 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10512 ["Complete Lisp Symbol" lisp-complete-symbol t]
10513 "--"
10514 "Shift Reference at Point"
10515 ["Up" org-table-fedit-ref-up t]
10516 ["Down" org-table-fedit-ref-down t]
10517 ["Left" org-table-fedit-ref-left t]
10518 ["Right" org-table-fedit-ref-right t]
10520 "Change Test Row for Column Formulas"
10521 ["Up" org-table-fedit-line-up t]
10522 ["Down" org-table-fedit-line-down t]
10523 "--"
10524 ["Scroll Table Window" org-table-fedit-scroll t]
10525 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10526 ["Show Table Grid" org-table-fedit-toggle-coordinates
10527 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10528 org-table-overlay-coordinates)]
10529 "--"
10530 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10531 :style toggle :selected org-table-buffer-is-an]))
10533 (defvar org-pos)
10535 (defun org-table-edit-formulas ()
10536 "Edit the formulas of the current table in a separate buffer."
10537 (interactive)
10538 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10539 (beginning-of-line 0))
10540 (unless (org-at-table-p) (error "Not at a table"))
10541 (org-table-get-specials)
10542 (let ((key (org-table-current-field-formula 'key 'noerror))
10543 (eql (sort (org-table-get-stored-formulas 'noerror)
10544 'org-table-formula-less-p))
10545 (pos (move-marker (make-marker) (point)))
10546 (startline 1)
10547 (wc (current-window-configuration))
10548 (titles '((column . "# Column Formulas\n")
10549 (field . "# Field Formulas\n")
10550 (named . "# Named Field Formulas\n")))
10551 entry s type title)
10552 (org-switch-to-buffer-other-window "*Edit Formulas*")
10553 (erase-buffer)
10554 ;; Keep global-font-lock-mode from turning on font-lock-mode
10555 (let ((font-lock-global-modes '(not fundamental-mode)))
10556 (fundamental-mode))
10557 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10558 (org-set-local 'org-pos pos)
10559 (org-set-local 'org-window-configuration wc)
10560 (use-local-map org-table-fedit-map)
10561 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10562 (easy-menu-add org-table-fedit-menu)
10563 (setq startline (org-current-line))
10564 (while (setq entry (pop eql))
10565 (setq type (cond
10566 ((equal (string-to-char (car entry)) ?@) 'field)
10567 ((string-match "^[0-9]" (car entry)) 'column)
10568 (t 'named)))
10569 (when (setq title (assq type titles))
10570 (or (bobp) (insert "\n"))
10571 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10572 (setq titles (delq title titles)))
10573 (if (equal key (car entry)) (setq startline (org-current-line)))
10574 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10575 (car entry) " = " (cdr entry) "\n"))
10576 (remove-text-properties 0 (length s) '(face nil) s)
10577 (insert s))
10578 (if (eq org-table-use-standard-references t)
10579 (org-table-fedit-toggle-ref-type))
10580 (goto-line startline)
10581 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10583 (defun org-table-fedit-post-command ()
10584 (when (not (memq this-command '(lisp-complete-symbol)))
10585 (let ((win (selected-window)))
10586 (save-excursion
10587 (condition-case nil
10588 (org-table-show-reference)
10589 (error nil))
10590 (select-window win)))))
10592 (defun org-table-formula-to-user (s)
10593 "Convert a formula from internal to user representation."
10594 (if (eq org-table-use-standard-references t)
10595 (org-table-convert-refs-to-an s)
10598 (defun org-table-formula-from-user (s)
10599 "Convert a formula from user to internal representation."
10600 (if org-table-use-standard-references
10601 (org-table-convert-refs-to-rc s)
10604 (defun org-table-convert-refs-to-rc (s)
10605 "Convert spreadsheet references from AB7 to @7$28.
10606 Works for single references, but also for entire formulas and even the
10607 full TBLFM line."
10608 (let ((start 0))
10609 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10610 (cond
10611 ((match-end 3)
10612 ;; format match, just advance
10613 (setq start (match-end 0)))
10614 ((and (> (match-beginning 0) 0)
10615 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10616 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10617 ;; 3.e5 or something like this.
10618 (setq start (match-end 0)))
10620 (setq start (match-beginning 0)
10621 s (replace-match
10622 (if (equal (match-string 2 s) "&")
10623 (format "$%d" (org-letters-to-number (match-string 1 s)))
10624 (format "@%d$%d"
10625 (string-to-number (match-string 2 s))
10626 (org-letters-to-number (match-string 1 s))))
10627 t t s)))))
10630 (defun org-table-convert-refs-to-an (s)
10631 "Convert spreadsheet references from to @7$28 to AB7.
10632 Works for single references, but also for entire formulas and even the
10633 full TBLFM line."
10634 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10635 (setq s (replace-match
10636 (format "%s%d"
10637 (org-number-to-letters
10638 (string-to-number (match-string 2 s)))
10639 (string-to-number (match-string 1 s)))
10640 t t s)))
10641 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10642 (setq s (replace-match (concat "\\1"
10643 (org-number-to-letters
10644 (string-to-number (match-string 2 s))) "&")
10645 t nil s)))
10648 (defun org-letters-to-number (s)
10649 "Convert a base 26 number represented by letters into an integer.
10650 For example: AB -> 28."
10651 (let ((n 0))
10652 (setq s (upcase s))
10653 (while (> (length s) 0)
10654 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10655 s (substring s 1)))
10658 (defun org-number-to-letters (n)
10659 "Convert an integer into a base 26 number represented by letters.
10660 For example: 28 -> AB."
10661 (let ((s ""))
10662 (while (> n 0)
10663 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10664 n (/ (1- n) 26)))
10667 (defun org-table-fedit-convert-buffer (function)
10668 "Convert all references in this buffer, using FUNTION."
10669 (let ((line (org-current-line)))
10670 (goto-char (point-min))
10671 (while (not (eobp))
10672 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10673 (delete-region (point) (point-at-eol))
10674 (or (eobp) (forward-char 1)))
10675 (goto-line line)))
10677 (defun org-table-fedit-toggle-ref-type ()
10678 "Convert all references in the buffer from B3 to @3$2 and back."
10679 (interactive)
10680 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10681 (org-table-fedit-convert-buffer
10682 (if org-table-buffer-is-an
10683 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10684 (message "Reference type switched to %s"
10685 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10687 (defun org-table-fedit-ref-up ()
10688 "Shift the reference at point one row/hline up."
10689 (interactive)
10690 (org-table-fedit-shift-reference 'up))
10691 (defun org-table-fedit-ref-down ()
10692 "Shift the reference at point one row/hline down."
10693 (interactive)
10694 (org-table-fedit-shift-reference 'down))
10695 (defun org-table-fedit-ref-left ()
10696 "Shift the reference at point one field to the left."
10697 (interactive)
10698 (org-table-fedit-shift-reference 'left))
10699 (defun org-table-fedit-ref-right ()
10700 "Shift the reference at point one field to the right."
10701 (interactive)
10702 (org-table-fedit-shift-reference 'right))
10704 (defun org-table-fedit-shift-reference (dir)
10705 (cond
10706 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10707 (if (memq dir '(left right))
10708 (org-rematch-and-replace 1 (eq dir 'left))
10709 (error "Cannot shift reference in this direction")))
10710 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10711 ;; A B3-like reference
10712 (if (memq dir '(up down))
10713 (org-rematch-and-replace 2 (eq dir 'up))
10714 (org-rematch-and-replace 1 (eq dir 'left))))
10715 ((org-at-regexp-p
10716 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10717 ;; An internal reference
10718 (if (memq dir '(up down))
10719 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10720 (org-rematch-and-replace 5 (eq dir 'left))))))
10722 (defun org-rematch-and-replace (n &optional decr hline)
10723 "Re-match the group N, and replace it with the shifted refrence."
10724 (or (match-end n) (error "Cannot shift reference in this direction"))
10725 (goto-char (match-beginning n))
10726 (and (looking-at (regexp-quote (match-string n)))
10727 (replace-match (org-shift-refpart (match-string 0) decr hline)
10728 t t)))
10730 (defun org-shift-refpart (ref &optional decr hline)
10731 "Shift a refrence part REF.
10732 If DECR is set, decrease the references row/column, else increase.
10733 If HLINE is set, this may be a hline reference, it certainly is not
10734 a translation reference."
10735 (save-match-data
10736 (let* ((sign (string-match "^[-+]" ref)) n)
10738 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10739 (cond
10740 ((and hline (string-match "^I+" ref))
10741 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10742 (setq n (+ n (if decr -1 1)))
10743 (if (= n 0) (setq n (+ n (if decr -1 1))))
10744 (if sign
10745 (setq sign (if (< n 0) "-" "+") n (abs n))
10746 (setq n (max 1 n)))
10747 (concat sign (make-string n ?I)))
10749 ((string-match "^[0-9]+" ref)
10750 (setq n (string-to-number (concat sign ref)))
10751 (setq n (+ n (if decr -1 1)))
10752 (if sign
10753 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10754 (number-to-string (max 1 n))))
10756 ((string-match "^[a-zA-Z]+" ref)
10757 (org-number-to-letters
10758 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10760 (t (error "Cannot shift reference"))))))
10762 (defun org-table-fedit-toggle-coordinates ()
10763 "Toggle the display of coordinates in the refrenced table."
10764 (interactive)
10765 (let ((pos (marker-position org-pos)))
10766 (with-current-buffer (marker-buffer org-pos)
10767 (save-excursion
10768 (goto-char pos)
10769 (org-table-toggle-coordinate-overlays)))))
10771 (defun org-table-fedit-finish (&optional arg)
10772 "Parse the buffer for formula definitions and install them.
10773 With prefix ARG, apply the new formulas to the table."
10774 (interactive "P")
10775 (org-table-remove-rectangle-highlight)
10776 (if org-table-use-standard-references
10777 (progn
10778 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10779 (setq org-table-buffer-is-an nil)))
10780 (let ((pos org-pos) eql var form)
10781 (goto-char (point-min))
10782 (while (re-search-forward
10783 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10784 nil t)
10785 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10786 form (match-string 3))
10787 (setq form (org-trim form))
10788 (when (not (equal form ""))
10789 (while (string-match "[ \t]*\n[ \t]*" form)
10790 (setq form (replace-match " " t t form)))
10791 (when (assoc var eql)
10792 (error "Double formulas for %s" var))
10793 (push (cons var form) eql)))
10794 (setq org-pos nil)
10795 (set-window-configuration org-window-configuration)
10796 (select-window (get-buffer-window (marker-buffer pos)))
10797 (goto-char pos)
10798 (unless (org-at-table-p)
10799 (error "Lost table position - cannot install formulae"))
10800 (org-table-store-formulas eql)
10801 (move-marker pos nil)
10802 (kill-buffer "*Edit Formulas*")
10803 (if arg
10804 (org-table-recalculate 'all)
10805 (message "New formulas installed - press C-u C-c C-c to apply."))))
10807 (defun org-table-fedit-abort ()
10808 "Abort editing formulas, without installing the changes."
10809 (interactive)
10810 (org-table-remove-rectangle-highlight)
10811 (let ((pos org-pos))
10812 (set-window-configuration org-window-configuration)
10813 (select-window (get-buffer-window (marker-buffer pos)))
10814 (goto-char pos)
10815 (move-marker pos nil)
10816 (message "Formula editing aborted without installing changes")))
10818 (defun org-table-fedit-lisp-indent ()
10819 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10820 (interactive)
10821 (let ((pos (point)) beg end ind)
10822 (beginning-of-line 1)
10823 (cond
10824 ((looking-at "[ \t]")
10825 (goto-char pos)
10826 (call-interactively 'lisp-indent-line))
10827 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10828 ((not (fboundp 'pp-buffer))
10829 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10830 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10831 (goto-char (- (match-end 0) 2))
10832 (setq beg (point))
10833 (setq ind (make-string (current-column) ?\ ))
10834 (condition-case nil (forward-sexp 1)
10835 (error
10836 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10837 (setq end (point))
10838 (save-restriction
10839 (narrow-to-region beg end)
10840 (if (eq last-command this-command)
10841 (progn
10842 (goto-char (point-min))
10843 (setq this-command nil)
10844 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10845 (replace-match " ")))
10846 (pp-buffer)
10847 (untabify (point-min) (point-max))
10848 (goto-char (1+ (point-min)))
10849 (while (re-search-forward "^." nil t)
10850 (beginning-of-line 1)
10851 (insert ind))
10852 (goto-char (point-max))
10853 (backward-delete-char 1)))
10854 (goto-char beg))
10855 (t nil))))
10857 (defvar org-show-positions nil)
10859 (defun org-table-show-reference (&optional local)
10860 "Show the location/value of the $ expression at point."
10861 (interactive)
10862 (org-table-remove-rectangle-highlight)
10863 (catch 'exit
10864 (let ((pos (if local (point) org-pos))
10865 (face2 'highlight)
10866 (org-inhibit-highlight-removal t)
10867 (win (selected-window))
10868 (org-show-positions nil)
10869 var name e what match dest)
10870 (if local (org-table-get-specials))
10871 (setq what (cond
10872 ((or (org-at-regexp-p org-table-range-regexp2)
10873 (org-at-regexp-p org-table-translate-regexp)
10874 (org-at-regexp-p org-table-range-regexp))
10875 (setq match
10876 (save-match-data
10877 (org-table-convert-refs-to-rc (match-string 0))))
10878 'range)
10879 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10880 ((org-at-regexp-p "\\$[0-9]+") 'column)
10881 ((not local) nil)
10882 (t (error "No reference at point")))
10883 match (and what (or match (match-string 0))))
10884 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10885 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10886 'secondary-selection))
10887 (org-add-hook 'before-change-functions
10888 'org-table-remove-rectangle-highlight)
10889 (if (eq what 'name) (setq var (substring match 1)))
10890 (when (eq what 'range)
10891 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10892 (setq match (org-table-formula-substitute-names match)))
10893 (unless local
10894 (save-excursion
10895 (end-of-line 1)
10896 (re-search-backward "^\\S-" nil t)
10897 (beginning-of-line 1)
10898 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10899 (setq dest
10900 (save-match-data
10901 (org-table-convert-refs-to-rc (match-string 1))))
10902 (org-table-add-rectangle-overlay
10903 (match-beginning 1) (match-end 1) face2))))
10904 (if (and (markerp pos) (marker-buffer pos))
10905 (if (get-buffer-window (marker-buffer pos))
10906 (select-window (get-buffer-window (marker-buffer pos)))
10907 (org-switch-to-buffer-other-window (get-buffer-window
10908 (marker-buffer pos)))))
10909 (goto-char pos)
10910 (org-table-force-dataline)
10911 (when dest
10912 (setq name (substring dest 1))
10913 (cond
10914 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10915 (setq e (assoc name org-table-named-field-locations))
10916 (goto-line (nth 1 e))
10917 (org-table-goto-column (nth 2 e)))
10918 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10919 (let ((l (string-to-number (match-string 1 dest)))
10920 (c (string-to-number (match-string 2 dest))))
10921 (goto-line (aref org-table-dlines l))
10922 (org-table-goto-column c)))
10923 (t (org-table-goto-column (string-to-number name))))
10924 (move-marker pos (point))
10925 (org-table-highlight-rectangle nil nil face2))
10926 (cond
10927 ((equal dest match))
10928 ((not match))
10929 ((eq what 'range)
10930 (condition-case nil
10931 (save-excursion
10932 (org-table-get-range match nil nil 'highlight))
10933 (error nil)))
10934 ((setq e (assoc var org-table-named-field-locations))
10935 (goto-line (nth 1 e))
10936 (org-table-goto-column (nth 2 e))
10937 (org-table-highlight-rectangle (point) (point))
10938 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10939 ((setq e (assoc var org-table-column-names))
10940 (org-table-goto-column (string-to-number (cdr e)))
10941 (org-table-highlight-rectangle (point) (point))
10942 (goto-char (org-table-begin))
10943 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10944 (org-table-end) t)
10945 (progn
10946 (goto-char (match-beginning 1))
10947 (org-table-highlight-rectangle)
10948 (message "Named column (column %s)" (cdr e)))
10949 (error "Column name not found")))
10950 ((eq what 'column)
10951 ;; column number
10952 (org-table-goto-column (string-to-number (substring match 1)))
10953 (org-table-highlight-rectangle (point) (point))
10954 (message "Column %s" (substring match 1)))
10955 ((setq e (assoc var org-table-local-parameters))
10956 (goto-char (org-table-begin))
10957 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10958 (progn
10959 (goto-char (match-beginning 1))
10960 (org-table-highlight-rectangle)
10961 (message "Local parameter."))
10962 (error "Parameter not found")))
10964 (cond
10965 ((not var) (error "No reference at point"))
10966 ((setq e (assoc var org-table-formula-constants-local))
10967 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10968 var (cdr e)))
10969 ((setq e (assoc var org-table-formula-constants))
10970 (message "Constant: $%s=%s in `org-table-formula-constants'."
10971 var (cdr e)))
10972 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10973 (message "Constant: $%s=%s, from `constants.el'%s."
10974 var e (format " (%s units)" constants-unit-system)))
10975 (t (error "Undefined name $%s" var)))))
10976 (goto-char pos)
10977 (when (and org-show-positions
10978 (not (memq this-command '(org-table-fedit-scroll
10979 org-table-fedit-scroll-down))))
10980 (push pos org-show-positions)
10981 (push org-table-current-begin-pos org-show-positions)
10982 (let ((min (apply 'min org-show-positions))
10983 (max (apply 'max org-show-positions)))
10984 (goto-char min) (recenter 0)
10985 (goto-char max)
10986 (or (pos-visible-in-window-p max) (recenter -1))))
10987 (select-window win))))
10989 (defun org-table-force-dataline ()
10990 "Make sure the cursor is in a dataline in a table."
10991 (unless (save-excursion
10992 (beginning-of-line 1)
10993 (looking-at org-table-dataline-regexp))
10994 (let* ((re org-table-dataline-regexp)
10995 (p1 (save-excursion (re-search-forward re nil 'move)))
10996 (p2 (save-excursion (re-search-backward re nil 'move))))
10997 (cond ((and p1 p2)
10998 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10999 p1 p2)))
11000 ((or p1 p2) (goto-char (or p1 p2)))
11001 (t (error "No table dataline around here"))))))
11003 (defun org-table-fedit-line-up ()
11004 "Move cursor one line up in the window showing the table."
11005 (interactive)
11006 (org-table-fedit-move 'previous-line))
11008 (defun org-table-fedit-line-down ()
11009 "Move cursor one line down in the window showing the table."
11010 (interactive)
11011 (org-table-fedit-move 'next-line))
11013 (defun org-table-fedit-move (command)
11014 "Move the cursor in the window shoinw the table.
11015 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11016 (let ((org-table-allow-automatic-line-recalculation nil)
11017 (pos org-pos) (win (selected-window)) p)
11018 (select-window (get-buffer-window (marker-buffer org-pos)))
11019 (setq p (point))
11020 (call-interactively command)
11021 (while (and (org-at-table-p)
11022 (org-at-table-hline-p))
11023 (call-interactively command))
11024 (or (org-at-table-p) (goto-char p))
11025 (move-marker pos (point))
11026 (select-window win)))
11028 (defun org-table-fedit-scroll (N)
11029 (interactive "p")
11030 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11031 (scroll-other-window N)))
11033 (defun org-table-fedit-scroll-down (N)
11034 (interactive "p")
11035 (org-table-fedit-scroll (- N)))
11037 (defvar org-table-rectangle-overlays nil)
11039 (defun org-table-add-rectangle-overlay (beg end &optional face)
11040 "Add a new overlay."
11041 (let ((ov (org-make-overlay beg end)))
11042 (org-overlay-put ov 'face (or face 'secondary-selection))
11043 (push ov org-table-rectangle-overlays)))
11045 (defun org-table-highlight-rectangle (&optional beg end face)
11046 "Highlight rectangular region in a table."
11047 (setq beg (or beg (point)) end (or end (point)))
11048 (let ((b (min beg end))
11049 (e (max beg end))
11050 l1 c1 l2 c2 tmp)
11051 (and (boundp 'org-show-positions)
11052 (setq org-show-positions (cons b (cons e org-show-positions))))
11053 (goto-char (min beg end))
11054 (setq l1 (org-current-line)
11055 c1 (org-table-current-column))
11056 (goto-char (max beg end))
11057 (setq l2 (org-current-line)
11058 c2 (org-table-current-column))
11059 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11060 (goto-line l1)
11061 (beginning-of-line 1)
11062 (loop for line from l1 to l2 do
11063 (when (looking-at org-table-dataline-regexp)
11064 (org-table-goto-column c1)
11065 (skip-chars-backward "^|\n") (setq beg (point))
11066 (org-table-goto-column c2)
11067 (skip-chars-forward "^|\n") (setq end (point))
11068 (org-table-add-rectangle-overlay beg end face))
11069 (beginning-of-line 2))
11070 (goto-char b))
11071 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11073 (defun org-table-remove-rectangle-highlight (&rest ignore)
11074 "Remove the rectangle overlays."
11075 (unless org-inhibit-highlight-removal
11076 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11077 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11078 (setq org-table-rectangle-overlays nil)))
11080 (defvar org-table-coordinate-overlays nil
11081 "Collects the cooordinate grid overlays, so that they can be removed.")
11082 (make-variable-buffer-local 'org-table-coordinate-overlays)
11084 (defun org-table-overlay-coordinates ()
11085 "Add overlays to the table at point, to show row/column coordinates."
11086 (interactive)
11087 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11088 (setq org-table-coordinate-overlays nil)
11089 (save-excursion
11090 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11091 (goto-char (org-table-begin))
11092 (while (org-at-table-p)
11093 (setq eol (point-at-eol))
11094 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11095 (push ov org-table-coordinate-overlays)
11096 (setq hline (looking-at org-table-hline-regexp))
11097 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11098 (format "%4d" (setq id (1+ id)))))
11099 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11100 (when hline
11101 (setq ic 0)
11102 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11103 (setq beg (1+ (match-beginning 0))
11104 ic (1+ ic)
11105 s1 (concat "$" (int-to-string ic))
11106 s2 (org-number-to-letters ic)
11107 str (if (eq org-table-use-standard-references t) s2 s1))
11108 (setq ov (org-make-overlay beg (+ beg (length str))))
11109 (push ov org-table-coordinate-overlays)
11110 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11111 (beginning-of-line 2)))))
11113 (defun org-table-toggle-coordinate-overlays ()
11114 "Toggle the display of Row/Column numbers in tables."
11115 (interactive)
11116 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11117 (message "Row/Column number display turned %s"
11118 (if org-table-overlay-coordinates "on" "off"))
11119 (if (and (org-at-table-p) org-table-overlay-coordinates)
11120 (org-table-align))
11121 (unless org-table-overlay-coordinates
11122 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11123 (setq org-table-coordinate-overlays nil)))
11125 (defun org-table-toggle-formula-debugger ()
11126 "Toggle the formula debugger in tables."
11127 (interactive)
11128 (setq org-table-formula-debug (not org-table-formula-debug))
11129 (message "Formula debugging has been turned %s"
11130 (if org-table-formula-debug "on" "off")))
11132 ;;; The orgtbl minor mode
11134 ;; Define a minor mode which can be used in other modes in order to
11135 ;; integrate the org-mode table editor.
11137 ;; This is really a hack, because the org-mode table editor uses several
11138 ;; keys which normally belong to the major mode, for example the TAB and
11139 ;; RET keys. Here is how it works: The minor mode defines all the keys
11140 ;; necessary to operate the table editor, but wraps the commands into a
11141 ;; function which tests if the cursor is currently inside a table. If that
11142 ;; is the case, the table editor command is executed. However, when any of
11143 ;; those keys is used outside a table, the function uses `key-binding' to
11144 ;; look up if the key has an associated command in another currently active
11145 ;; keymap (minor modes, major mode, global), and executes that command.
11146 ;; There might be problems if any of the keys used by the table editor is
11147 ;; otherwise used as a prefix key.
11149 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11150 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11151 ;; addresses this by checking explicitly for both bindings.
11153 ;; The optimized version (see variable `orgtbl-optimized') takes over
11154 ;; all keys which are bound to `self-insert-command' in the *global map*.
11155 ;; Some modes bind other commands to simple characters, for example
11156 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11157 ;; active, this binding is ignored inside tables and replaced with a
11158 ;; modified self-insert.
11160 (defvar orgtbl-mode nil
11161 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11162 table editor in arbitrary modes.")
11163 (make-variable-buffer-local 'orgtbl-mode)
11165 (defvar orgtbl-mode-map (make-keymap)
11166 "Keymap for `orgtbl-mode'.")
11168 ;;;###autoload
11169 (defun turn-on-orgtbl ()
11170 "Unconditionally turn on `orgtbl-mode'."
11171 (orgtbl-mode 1))
11173 (defvar org-old-auto-fill-inhibit-regexp nil
11174 "Local variable used by `orgtbl-mode'")
11176 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11177 "Matches a line belonging to an orgtbl.")
11179 (defconst orgtbl-extra-font-lock-keywords
11180 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11181 0 (quote 'org-table) 'prepend))
11182 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11184 ;;;###autoload
11185 (defun orgtbl-mode (&optional arg)
11186 "The `org-mode' table editor as a minor mode for use in other modes."
11187 (interactive)
11188 (if (org-mode-p)
11189 ;; Exit without error, in case some hook functions calls this
11190 ;; by accident in org-mode.
11191 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11192 (setq orgtbl-mode
11193 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11194 (if orgtbl-mode
11195 (progn
11196 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11197 ;; Make sure we are first in minor-mode-map-alist
11198 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11199 (and c (setq minor-mode-map-alist
11200 (cons c (delq c minor-mode-map-alist)))))
11201 (org-set-local (quote org-table-may-need-update) t)
11202 (org-add-hook 'before-change-functions 'org-before-change-function
11203 nil 'local)
11204 (org-set-local 'org-old-auto-fill-inhibit-regexp
11205 auto-fill-inhibit-regexp)
11206 (org-set-local 'auto-fill-inhibit-regexp
11207 (if auto-fill-inhibit-regexp
11208 (concat orgtbl-line-start-regexp "\\|"
11209 auto-fill-inhibit-regexp)
11210 orgtbl-line-start-regexp))
11211 (org-add-to-invisibility-spec '(org-cwidth))
11212 (when (fboundp 'font-lock-add-keywords)
11213 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11214 (org-restart-font-lock))
11215 (easy-menu-add orgtbl-mode-menu)
11216 (run-hooks 'orgtbl-mode-hook))
11217 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11218 (org-cleanup-narrow-column-properties)
11219 (org-remove-from-invisibility-spec '(org-cwidth))
11220 (remove-hook 'before-change-functions 'org-before-change-function t)
11221 (when (fboundp 'font-lock-remove-keywords)
11222 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11223 (org-restart-font-lock))
11224 (easy-menu-remove orgtbl-mode-menu)
11225 (force-mode-line-update 'all))))
11227 (defun org-cleanup-narrow-column-properties ()
11228 "Remove all properties related to narrow-column invisibility."
11229 (let ((s 1))
11230 (while (setq s (text-property-any s (point-max)
11231 'display org-narrow-column-arrow))
11232 (remove-text-properties s (1+ s) '(display t)))
11233 (setq s 1)
11234 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11235 (remove-text-properties s (1+ s) '(org-cwidth t)))
11236 (setq s 1)
11237 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11238 (remove-text-properties s (1+ s) '(invisible t)))))
11240 ;; Install it as a minor mode.
11241 (put 'orgtbl-mode :included t)
11242 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11243 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11245 (defun orgtbl-make-binding (fun n &rest keys)
11246 "Create a function for binding in the table minor mode.
11247 FUN is the command to call inside a table. N is used to create a unique
11248 command name. KEYS are keys that should be checked in for a command
11249 to execute outside of tables."
11250 (eval
11251 (list 'defun
11252 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11253 '(arg)
11254 (concat "In tables, run `" (symbol-name fun) "'.\n"
11255 "Outside of tables, run the binding of `"
11256 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11257 "'.")
11258 '(interactive "p")
11259 (list 'if
11260 '(org-at-table-p)
11261 (list 'call-interactively (list 'quote fun))
11262 (list 'let '(orgtbl-mode)
11263 (list 'call-interactively
11264 (append '(or)
11265 (mapcar (lambda (k)
11266 (list 'key-binding k))
11267 keys)
11268 '('orgtbl-error))))))))
11270 (defun orgtbl-error ()
11271 "Error when there is no default binding for a table key."
11272 (interactive)
11273 (error "This key has no function outside tables"))
11275 (defun orgtbl-setup ()
11276 "Setup orgtbl keymaps."
11277 (let ((nfunc 0)
11278 (bindings
11279 (list
11280 '([(meta shift left)] org-table-delete-column)
11281 '([(meta left)] org-table-move-column-left)
11282 '([(meta right)] org-table-move-column-right)
11283 '([(meta shift right)] org-table-insert-column)
11284 '([(meta shift up)] org-table-kill-row)
11285 '([(meta shift down)] org-table-insert-row)
11286 '([(meta up)] org-table-move-row-up)
11287 '([(meta down)] org-table-move-row-down)
11288 '("\C-c\C-w" org-table-cut-region)
11289 '("\C-c\M-w" org-table-copy-region)
11290 '("\C-c\C-y" org-table-paste-rectangle)
11291 '("\C-c-" org-table-insert-hline)
11292 '("\C-c}" org-table-toggle-coordinate-overlays)
11293 '("\C-c{" org-table-toggle-formula-debugger)
11294 '("\C-m" org-table-next-row)
11295 '([(shift return)] org-table-copy-down)
11296 '("\C-c\C-q" org-table-wrap-region)
11297 '("\C-c?" org-table-field-info)
11298 '("\C-c " org-table-blank-field)
11299 '("\C-c+" org-table-sum)
11300 '("\C-c=" org-table-eval-formula)
11301 '("\C-c'" org-table-edit-formulas)
11302 '("\C-c`" org-table-edit-field)
11303 '("\C-c*" org-table-recalculate)
11304 '("\C-c|" org-table-create-or-convert-from-region)
11305 '("\C-c^" org-table-sort-lines)
11306 '([(control ?#)] org-table-rotate-recalc-marks)))
11307 elt key fun cmd)
11308 (while (setq elt (pop bindings))
11309 (setq nfunc (1+ nfunc))
11310 (setq key (org-key (car elt))
11311 fun (nth 1 elt)
11312 cmd (orgtbl-make-binding fun nfunc key))
11313 (org-defkey orgtbl-mode-map key cmd))
11315 ;; Special treatment needed for TAB and RET
11316 (org-defkey orgtbl-mode-map [(return)]
11317 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11318 (org-defkey orgtbl-mode-map "\C-m"
11319 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11321 (org-defkey orgtbl-mode-map [(tab)]
11322 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11323 (org-defkey orgtbl-mode-map "\C-i"
11324 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11326 (org-defkey orgtbl-mode-map [(shift tab)]
11327 (orgtbl-make-binding 'org-table-previous-field 104
11328 [(shift tab)] [(tab)] "\C-i"))
11330 (org-defkey orgtbl-mode-map "\M-\C-m"
11331 (orgtbl-make-binding 'org-table-wrap-region 105
11332 "\M-\C-m" [(meta return)]))
11333 (org-defkey orgtbl-mode-map [(meta return)]
11334 (orgtbl-make-binding 'org-table-wrap-region 106
11335 [(meta return)] "\M-\C-m"))
11337 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11338 (when orgtbl-optimized
11339 ;; If the user wants maximum table support, we need to hijack
11340 ;; some standard editing functions
11341 (org-remap orgtbl-mode-map
11342 'self-insert-command 'orgtbl-self-insert-command
11343 'delete-char 'org-delete-char
11344 'delete-backward-char 'org-delete-backward-char)
11345 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11346 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11347 '("OrgTbl"
11348 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11349 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11350 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11351 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11352 "--"
11353 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11354 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11355 ["Copy Field from Above"
11356 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11357 "--"
11358 ("Column"
11359 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11360 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11361 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11362 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11363 ("Row"
11364 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11365 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11366 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11367 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11368 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11369 "--"
11370 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11371 ("Rectangle"
11372 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11373 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11374 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11375 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11376 "--"
11377 ("Radio tables"
11378 ["Insert table template" orgtbl-insert-radio-table
11379 (assq major-mode orgtbl-radio-table-templates)]
11380 ["Comment/uncomment table" orgtbl-toggle-comment t])
11381 "--"
11382 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11383 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11384 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11385 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11386 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11387 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11388 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11389 ["Sum Column/Rectangle" org-table-sum
11390 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11391 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11392 ["Debug Formulas"
11393 org-table-toggle-formula-debugger :active (org-at-table-p)
11394 :keys "C-c {"
11395 :style toggle :selected org-table-formula-debug]
11396 ["Show Col/Row Numbers"
11397 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11398 :keys "C-c }"
11399 :style toggle :selected org-table-overlay-coordinates]
11403 (defun orgtbl-ctrl-c-ctrl-c (arg)
11404 "If the cursor is inside a table, realign the table.
11405 It it is a table to be sent away to a receiver, do it.
11406 With prefix arg, also recompute table."
11407 (interactive "P")
11408 (let ((pos (point)) action)
11409 (save-excursion
11410 (beginning-of-line 1)
11411 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11412 ((looking-at "[ \t]*|") pos)
11413 ((looking-at "#\\+TBLFM:") 'recalc))))
11414 (cond
11415 ((integerp action)
11416 (goto-char action)
11417 (org-table-maybe-eval-formula)
11418 (if arg
11419 (call-interactively 'org-table-recalculate)
11420 (org-table-maybe-recalculate-line))
11421 (call-interactively 'org-table-align)
11422 (orgtbl-send-table 'maybe))
11423 ((eq action 'recalc)
11424 (save-excursion
11425 (beginning-of-line 1)
11426 (skip-chars-backward " \r\n\t")
11427 (if (org-at-table-p)
11428 (org-call-with-arg 'org-table-recalculate t))))
11429 (t (let (orgtbl-mode)
11430 (call-interactively (key-binding "\C-c\C-c")))))))
11432 (defun orgtbl-tab (arg)
11433 "Justification and field motion for `orgtbl-mode'."
11434 (interactive "P")
11435 (if arg (org-table-edit-field t)
11436 (org-table-justify-field-maybe)
11437 (org-table-next-field)))
11439 (defun orgtbl-ret ()
11440 "Justification and field motion for `orgtbl-mode'."
11441 (interactive)
11442 (org-table-justify-field-maybe)
11443 (org-table-next-row))
11445 (defun orgtbl-self-insert-command (N)
11446 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11447 If the cursor is in a table looking at whitespace, the whitespace is
11448 overwritten, and the table is not marked as requiring realignment."
11449 (interactive "p")
11450 (if (and (org-at-table-p)
11452 (and org-table-auto-blank-field
11453 (member last-command
11454 '(orgtbl-hijacker-command-100
11455 orgtbl-hijacker-command-101
11456 orgtbl-hijacker-command-102
11457 orgtbl-hijacker-command-103
11458 orgtbl-hijacker-command-104
11459 orgtbl-hijacker-command-105))
11460 (org-table-blank-field))
11462 (eq N 1)
11463 (looking-at "[^|\n]* +|"))
11464 (let (org-table-may-need-update)
11465 (goto-char (1- (match-end 0)))
11466 (delete-backward-char 1)
11467 (goto-char (match-beginning 0))
11468 (self-insert-command N))
11469 (setq org-table-may-need-update t)
11470 (let (orgtbl-mode)
11471 (call-interactively (key-binding (vector last-input-event))))))
11473 (defun org-force-self-insert (N)
11474 "Needed to enforce self-insert under remapping."
11475 (interactive "p")
11476 (self-insert-command N))
11478 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11479 "Regula expression matching exponentials as produced by calc.")
11481 (defvar org-table-clean-did-remove-column nil)
11483 (defun orgtbl-export (table target)
11484 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11485 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11486 org-table-last-alignment org-table-last-column-widths
11487 maxcol column)
11488 (if (not (fboundp func))
11489 (error "Cannot export orgtbl table to %s" target))
11490 (setq lines (org-table-clean-before-export lines))
11491 (setq table
11492 (mapcar
11493 (lambda (x)
11494 (if (string-match org-table-hline-regexp x)
11495 'hline
11496 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11497 lines))
11498 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11499 table)))
11500 (loop for i from (1- maxcol) downto 0 do
11501 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11502 (setq column (delq nil column))
11503 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11504 (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))
11505 (funcall func table nil)))
11507 (defun orgtbl-send-table (&optional maybe)
11508 "Send a tranformed version of this table to the receiver position.
11509 With argument MAYBE, fail quietly if no transformation is defined for
11510 this table."
11511 (interactive)
11512 (catch 'exit
11513 (unless (org-at-table-p) (error "Not at a table"))
11514 ;; when non-interactive, we assume align has just happened.
11515 (when (interactive-p) (org-table-align))
11516 (save-excursion
11517 (goto-char (org-table-begin))
11518 (beginning-of-line 0)
11519 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11520 (if maybe
11521 (throw 'exit nil)
11522 (error "Don't know how to transform this table."))))
11523 (let* ((name (match-string 1))
11525 (transform (intern (match-string 2)))
11526 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11527 (skip (plist-get params :skip))
11528 (skipcols (plist-get params :skipcols))
11529 (txt (buffer-substring-no-properties
11530 (org-table-begin) (org-table-end)))
11531 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11532 (lines (org-table-clean-before-export lines))
11533 (i0 (if org-table-clean-did-remove-column 2 1))
11534 (table (mapcar
11535 (lambda (x)
11536 (if (string-match org-table-hline-regexp x)
11537 'hline
11538 (org-remove-by-index
11539 (org-split-string (org-trim x) "\\s-*|\\s-*")
11540 skipcols i0)))
11541 lines))
11542 (fun (if (= i0 2) 'cdr 'identity))
11543 (org-table-last-alignment
11544 (org-remove-by-index (funcall fun org-table-last-alignment)
11545 skipcols i0))
11546 (org-table-last-column-widths
11547 (org-remove-by-index (funcall fun org-table-last-column-widths)
11548 skipcols i0)))
11550 (unless (fboundp transform)
11551 (error "No such transformation function %s" transform))
11552 (setq txt (funcall transform table params))
11553 ;; Find the insertion place
11554 (save-excursion
11555 (goto-char (point-min))
11556 (unless (re-search-forward
11557 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11558 (error "Don't know where to insert translated table"))
11559 (goto-char (match-beginning 0))
11560 (beginning-of-line 2)
11561 (setq beg (point))
11562 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11563 (error "Cannot find end of insertion region"))
11564 (beginning-of-line 1)
11565 (delete-region beg (point))
11566 (goto-char beg)
11567 (insert txt "\n"))
11568 (message "Table converted and installed at receiver location"))))
11570 (defun org-remove-by-index (list indices &optional i0)
11571 "Remove the elements in LIST with indices in INDICES.
11572 First element has index 0, or I0 if given."
11573 (if (not indices)
11574 list
11575 (if (integerp indices) (setq indices (list indices)))
11576 (setq i0 (1- (or i0 0)))
11577 (delq :rm (mapcar (lambda (x)
11578 (setq i0 (1+ i0))
11579 (if (memq i0 indices) :rm x))
11580 list))))
11582 (defun orgtbl-toggle-comment ()
11583 "Comment or uncomment the orgtbl at point."
11584 (interactive)
11585 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11586 (re2 (concat "^" orgtbl-line-start-regexp))
11587 (commented (save-excursion (beginning-of-line 1)
11588 (cond ((looking-at re1) t)
11589 ((looking-at re2) nil)
11590 (t (error "Not at an org table")))))
11591 (re (if commented re1 re2))
11592 beg end)
11593 (save-excursion
11594 (beginning-of-line 1)
11595 (while (looking-at re) (beginning-of-line 0))
11596 (beginning-of-line 2)
11597 (setq beg (point))
11598 (while (looking-at re) (beginning-of-line 2))
11599 (setq end (point)))
11600 (comment-region beg end (if commented '(4) nil))))
11602 (defun orgtbl-insert-radio-table ()
11603 "Insert a radio table template appropriate for this major mode."
11604 (interactive)
11605 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11606 (txt (nth 1 e))
11607 name pos)
11608 (unless e (error "No radio table setup defined for %s" major-mode))
11609 (setq name (read-string "Table name: "))
11610 (while (string-match "%n" txt)
11611 (setq txt (replace-match name t t txt)))
11612 (or (bolp) (insert "\n"))
11613 (setq pos (point))
11614 (insert txt)
11615 (goto-char pos)))
11617 (defun org-get-param (params header i sym &optional hsym)
11618 "Get parameter value for symbol SYM.
11619 If this is a header line, actually get the value for the symbol with an
11620 additional \"h\" inserted after the colon.
11621 If the value is a protperty list, get the element for the current column.
11622 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11623 (let ((val (plist-get params sym)))
11624 (and hsym header (setq val (or (plist-get params hsym) val)))
11625 (if (consp val) (plist-get val i) val)))
11627 (defun orgtbl-to-generic (table params)
11628 "Convert the orgtbl-mode TABLE to some other format.
11629 This generic routine can be used for many standard cases.
11630 TABLE is a list, each entry either the symbol `hline' for a horizontal
11631 separator line, or a list of fields for that line.
11632 PARAMS is a property list of parameters that can influence the conversion.
11633 For the generic converter, some parameters are obligatory: You need to
11634 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11635 :splice, you must have :tstart and :tend.
11637 Valid parameters are
11639 :tstart String to start the table. Ignored when :splice is t.
11640 :tend String to end the table. Ignored when :splice is t.
11642 :splice When set to t, return only table body lines, don't wrap
11643 them into :tstart and :tend. Default is nil.
11645 :hline String to be inserted on horizontal separation lines.
11646 May be nil to ignore hlines.
11648 :lstart String to start a new table line.
11649 :lend String to end a table line
11650 :sep Separator between two fields
11651 :lfmt Format for entire line, with enough %s to capture all fields.
11652 If this is present, :lstart, :lend, and :sep are ignored.
11653 :fmt A format to be used to wrap the field, should contain
11654 %s for the original field value. For example, to wrap
11655 everything in dollars, you could use :fmt \"$%s$\".
11656 This may also be a property list with column numbers and
11657 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11659 :hlstart :hlend :hlsep :hlfmt :hfmt
11660 Same as above, specific for the header lines in the table.
11661 All lines before the first hline are treated as header.
11662 If any of these is not present, the data line value is used.
11664 :efmt Use this format to print numbers with exponentials.
11665 The format should have %s twice for inserting mantissa
11666 and exponent, for example \"%s\\\\times10^{%s}\". This
11667 may also be a property list with column numbers and
11668 formats. :fmt will still be applied after :efmt.
11670 In addition to this, the parameters :skip and :skipcols are always handled
11671 directly by `orgtbl-send-table'. See manual."
11672 (interactive)
11673 (let* ((p params)
11674 (splicep (plist-get p :splice))
11675 (hline (plist-get p :hline))
11676 rtn line i fm efm lfmt h)
11678 ;; Do we have a header?
11679 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11680 (setq h t))
11682 ;; Put header
11683 (unless splicep
11684 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11686 ;; Now loop over all lines
11687 (while (setq line (pop table))
11688 (if (eq line 'hline)
11689 ;; A horizontal separator line
11690 (progn (if hline (push hline rtn))
11691 (setq h nil)) ; no longer in header
11692 ;; A normal line. Convert the fields, push line onto the result list
11693 (setq i 0)
11694 (setq line
11695 (mapcar
11696 (lambda (f)
11697 (setq i (1+ i)
11698 fm (org-get-param p h i :fmt :hfmt)
11699 efm (org-get-param p h i :efmt))
11700 (if (and efm (string-match orgtbl-exp-regexp f))
11701 (setq f (format
11702 efm (match-string 1 f) (match-string 2 f))))
11703 (if fm (setq f (format fm f)))
11705 line))
11706 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11707 (push (apply 'format lfmt line) rtn)
11708 (push (concat
11709 (org-get-param p h i :lstart :hlstart)
11710 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11711 (org-get-param p h i :lend :hlend))
11712 rtn))))
11714 (unless splicep
11715 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11717 (mapconcat 'identity (nreverse rtn) "\n")))
11719 (defun orgtbl-to-latex (table params)
11720 "Convert the orgtbl-mode TABLE to LaTeX.
11721 TABLE is a list, each entry either the symbol `hline' for a horizontal
11722 separator line, or a list of fields for that line.
11723 PARAMS is a property list of parameters that can influence the conversion.
11724 Supports all parameters from `orgtbl-to-generic'. Most important for
11725 LaTeX are:
11727 :splice When set to t, return only table body lines, don't wrap
11728 them into a tabular environment. Default is nil.
11730 :fmt A format to be used to wrap the field, should contain %s for the
11731 original field value. For example, to wrap everything in dollars,
11732 use :fmt \"$%s$\". This may also be a property list with column
11733 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11735 :efmt Format for transforming numbers with exponentials. The format
11736 should have %s twice for inserting mantissa and exponent, for
11737 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11738 This may also be a property list with column numbers and formats.
11740 The general parameters :skip and :skipcols have already been applied when
11741 this function is called."
11742 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11743 org-table-last-alignment ""))
11744 (params2
11745 (list
11746 :tstart (concat "\\begin{tabular}{" alignment "}")
11747 :tend "\\end{tabular}"
11748 :lstart "" :lend " \\\\" :sep " & "
11749 :efmt "%s\\,(%s)" :hline "\\hline")))
11750 (orgtbl-to-generic table (org-combine-plists params2 params))))
11752 (defun orgtbl-to-html (table params)
11753 "Convert the orgtbl-mode TABLE to LaTeX.
11754 TABLE is a list, each entry either the symbol `hline' for a horizontal
11755 separator line, or a list of fields for that line.
11756 PARAMS is a property list of parameters that can influence the conversion.
11757 Currently this function recognizes the following parameters:
11759 :splice When set to t, return only table body lines, don't wrap
11760 them into a <table> environment. Default is nil.
11762 The general parameters :skip and :skipcols have already been applied when
11763 this function is called. The function does *not* use `orgtbl-to-generic',
11764 so you cannot specify parameters for it."
11765 (let* ((splicep (plist-get params :splice))
11766 html)
11767 ;; Just call the formatter we already have
11768 ;; We need to make text lines for it, so put the fields back together.
11769 (setq html (org-format-org-table-html
11770 (mapcar
11771 (lambda (x)
11772 (if (eq x 'hline)
11773 "|----+----|"
11774 (concat "| " (mapconcat 'identity x " | ") " |")))
11775 table)
11776 splicep))
11777 (if (string-match "\n+\\'" html)
11778 (setq html (replace-match "" t t html)))
11779 html))
11781 (defun orgtbl-to-texinfo (table params)
11782 "Convert the orgtbl-mode TABLE to TeXInfo.
11783 TABLE is a list, each entry either the symbol `hline' for a horizontal
11784 separator line, or a list of fields for that line.
11785 PARAMS is a property list of parameters that can influence the conversion.
11786 Supports all parameters from `orgtbl-to-generic'. Most important for
11787 TeXInfo are:
11789 :splice nil/t When set to t, return only table body lines, don't wrap
11790 them into a multitable environment. Default is nil.
11792 :fmt fmt A format to be used to wrap the field, should contain
11793 %s for the original field value. For example, to wrap
11794 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11795 This may also be a property list with column numbers and
11796 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11798 :cf \"f1 f2..\" The column fractions for the table. By default these
11799 are computed automatically from the width of the columns
11800 under org-mode.
11802 The general parameters :skip and :skipcols have already been applied when
11803 this function is called."
11804 (let* ((total (float (apply '+ org-table-last-column-widths)))
11805 (colfrac (or (plist-get params :cf)
11806 (mapconcat
11807 (lambda (x) (format "%.3f" (/ (float x) total)))
11808 org-table-last-column-widths " ")))
11809 (params2
11810 (list
11811 :tstart (concat "@multitable @columnfractions " colfrac)
11812 :tend "@end multitable"
11813 :lstart "@item " :lend "" :sep " @tab "
11814 :hlstart "@headitem ")))
11815 (orgtbl-to-generic table (org-combine-plists params2 params))))
11817 ;;;; Link Stuff
11819 ;;; Link abbreviations
11821 (defun org-link-expand-abbrev (link)
11822 "Apply replacements as defined in `org-link-abbrev-alist."
11823 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11824 (let* ((key (match-string 1 link))
11825 (as (or (assoc key org-link-abbrev-alist-local)
11826 (assoc key org-link-abbrev-alist)))
11827 (tag (and (match-end 2) (match-string 3 link)))
11828 rpl)
11829 (if (not as)
11830 link
11831 (setq rpl (cdr as))
11832 (cond
11833 ((symbolp rpl) (funcall rpl tag))
11834 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11835 (t (concat rpl tag)))))
11836 link))
11838 ;;; Storing and inserting links
11840 (defvar org-insert-link-history nil
11841 "Minibuffer history for links inserted with `org-insert-link'.")
11843 (defvar org-stored-links nil
11844 "Contains the links stored with `org-store-link'.")
11846 (defvar org-store-link-plist nil
11847 "Plist with info about the most recently link created with `org-store-link'.")
11849 (defvar org-link-protocols nil
11850 "Link protocols added to Org-mode using `org-add-link-type'.")
11852 (defvar org-store-link-functions nil
11853 "List of functions that are called to create and store a link.
11854 Each function will be called in turn until one returns a non-nil
11855 value. Each function should check if it is responsible for creating
11856 this link (for example by looking at the major mode).
11857 If not, it must exit and return nil.
11858 If yes, it should return a non-nil value after a calling
11859 `org-store-link-props' with a list of properties and values.
11860 Special properties are:
11862 :type The link prefix. like \"http\". This must be given.
11863 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11864 This is obligatory as well.
11865 :description Optional default description for the second pair
11866 of brackets in an Org-mode link. The user can still change
11867 this when inserting this link into an Org-mode buffer.
11869 In addition to these, any additional properties can be specified
11870 and then used in remember templates.")
11872 (defun org-add-link-type (type &optional follow publish)
11873 "Add TYPE to the list of `org-link-types'.
11874 Re-compute all regular expressions depending on `org-link-types'
11875 FOLLOW and PUBLISH are two functions. Both take the link path as
11876 an argument.
11877 FOLLOW should do whatever is necessary to follow the link, for example
11878 to find a file or display a mail message.
11880 PUBLISH takes the path and retuns the string that should be used when
11881 this document is published. FIMXE: This is actually not yet implemented."
11882 (add-to-list 'org-link-types type t)
11883 (org-make-link-regexps)
11884 (add-to-list 'org-link-protocols
11885 (list type follow publish)))
11887 (defun org-add-agenda-custom-command (entry)
11888 "Replace or add a command in `org-agenda-custom-commands'.
11889 This is mostly for hacking and trying a new command - once the command
11890 works you probably want to add it to `org-agenda-custom-commands' for good."
11891 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11892 (if ass
11893 (setcdr ass (cdr entry))
11894 (push entry org-agenda-custom-commands))))
11896 ;;;###autoload
11897 (defun org-store-link (arg)
11898 "\\<org-mode-map>Store an org-link to the current location.
11899 This link can later be inserted into an org-buffer with
11900 \\[org-insert-link].
11901 For some link types, a prefix arg is interpreted:
11902 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11903 For file links, arg negates `org-context-in-file-links'."
11904 (interactive "P")
11905 (setq org-store-link-plist nil) ; reset
11906 (let (link cpltxt desc description search txt)
11907 (cond
11909 ((run-hook-with-args-until-success 'org-store-link-functions)
11910 (setq link (plist-get org-store-link-plist :link)
11911 desc (or (plist-get org-store-link-plist :description) link)))
11913 ((eq major-mode 'bbdb-mode)
11914 (let ((name (bbdb-record-name (bbdb-current-record)))
11915 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11916 (setq cpltxt (concat "bbdb:" (or name company))
11917 link (org-make-link cpltxt))
11918 (org-store-link-props :type "bbdb" :name name :company company)))
11920 ((eq major-mode 'Info-mode)
11921 (setq link (org-make-link "info:"
11922 (file-name-nondirectory Info-current-file)
11923 ":" Info-current-node))
11924 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11925 ":" Info-current-node))
11926 (org-store-link-props :type "info" :file Info-current-file
11927 :node Info-current-node))
11929 ((eq major-mode 'calendar-mode)
11930 (let ((cd (calendar-cursor-to-date)))
11931 (setq link
11932 (format-time-string
11933 (car org-time-stamp-formats)
11934 (apply 'encode-time
11935 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11936 nil nil nil))))
11937 (org-store-link-props :type "calendar" :date cd)))
11939 ((or (eq major-mode 'vm-summary-mode)
11940 (eq major-mode 'vm-presentation-mode))
11941 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11942 (vm-follow-summary-cursor)
11943 (save-excursion
11944 (vm-select-folder-buffer)
11945 (let* ((message (car vm-message-pointer))
11946 (folder buffer-file-name)
11947 (subject (vm-su-subject message))
11948 (to (vm-get-header-contents message "To"))
11949 (from (vm-get-header-contents message "From"))
11950 (message-id (vm-su-message-id message)))
11951 (org-store-link-props :type "vm" :from from :to to :subject subject
11952 :message-id message-id)
11953 (setq message-id (org-remove-angle-brackets message-id))
11954 (setq folder (abbreviate-file-name folder))
11955 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11956 folder)
11957 (setq folder (replace-match "" t t folder)))
11958 (setq cpltxt (org-email-link-description))
11959 (setq link (org-make-link "vm:" folder "#" message-id)))))
11961 ((eq major-mode 'wl-summary-mode)
11962 (let* ((msgnum (wl-summary-message-number))
11963 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11964 msgnum 'message-id))
11965 (wl-message-entity
11966 (if (fboundp 'elmo-message-entity)
11967 (elmo-message-entity
11968 wl-summary-buffer-elmo-folder msgnum)
11969 (elmo-msgdb-overview-get-entity
11970 msgnum (wl-summary-buffer-msgdb))))
11971 (from (wl-summary-line-from))
11972 (to (car (elmo-message-entity-field wl-message-entity 'to)))
11973 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11974 (wl-summary-line-subject))))
11975 (org-store-link-props :type "wl" :from from :to to
11976 :subject subject :message-id message-id)
11977 (setq message-id (org-remove-angle-brackets message-id))
11978 (setq cpltxt (org-email-link-description))
11979 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11980 "#" message-id))))
11982 ((or (equal major-mode 'mh-folder-mode)
11983 (equal major-mode 'mh-show-mode))
11984 (let ((from (org-mhe-get-header "From:"))
11985 (to (org-mhe-get-header "To:"))
11986 (message-id (org-mhe-get-header "Message-Id:"))
11987 (subject (org-mhe-get-header "Subject:")))
11988 (org-store-link-props :type "mh" :from from :to to
11989 :subject subject :message-id message-id)
11990 (setq cpltxt (org-email-link-description))
11991 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11992 (org-remove-angle-brackets message-id)))))
11994 ((eq major-mode 'rmail-mode)
11995 (save-excursion
11996 (save-restriction
11997 (rmail-narrow-to-non-pruned-header)
11998 (let ((folder buffer-file-name)
11999 (message-id (mail-fetch-field "message-id"))
12000 (from (mail-fetch-field "from"))
12001 (to (mail-fetch-field "to"))
12002 (subject (mail-fetch-field "subject")))
12003 (org-store-link-props
12004 :type "rmail" :from from :to to
12005 :subject subject :message-id message-id)
12006 (setq message-id (org-remove-angle-brackets message-id))
12007 (setq cpltxt (org-email-link-description))
12008 (setq link (org-make-link "rmail:" folder "#" message-id))))))
12010 ((eq major-mode 'gnus-group-mode)
12011 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12012 (gnus-group-group-name)) ; version
12013 ((fboundp 'gnus-group-name)
12014 (gnus-group-name))
12015 (t "???"))))
12016 (unless group (error "Not on a group"))
12017 (org-store-link-props :type "gnus" :group group)
12018 (setq cpltxt (concat
12019 (if (org-xor arg org-usenet-links-prefer-google)
12020 "http://groups.google.com/groups?group="
12021 "gnus:")
12022 group)
12023 link (org-make-link cpltxt))))
12025 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12026 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12027 (let* ((group gnus-newsgroup-name)
12028 (article (gnus-summary-article-number))
12029 (header (gnus-summary-article-header article))
12030 (from (mail-header-from header))
12031 (message-id (mail-header-id header))
12032 (date (mail-header-date header))
12033 (subject (gnus-summary-subject-string)))
12034 (org-store-link-props :type "gnus" :from from :subject subject
12035 :message-id message-id :group group)
12036 (setq cpltxt (org-email-link-description))
12037 (if (org-xor arg org-usenet-links-prefer-google)
12038 (setq link
12039 (concat
12040 cpltxt "\n "
12041 (format "http://groups.google.com/groups?as_umsgid=%s"
12042 (org-fixup-message-id-for-http message-id))))
12043 (setq link (org-make-link "gnus:" group
12044 "#" (number-to-string article))))))
12046 ((eq major-mode 'w3-mode)
12047 (setq cpltxt (url-view-url t)
12048 link (org-make-link cpltxt))
12049 (org-store-link-props :type "w3" :url (url-view-url t)))
12051 ((eq major-mode 'w3m-mode)
12052 (setq cpltxt (or w3m-current-title w3m-current-url)
12053 link (org-make-link w3m-current-url))
12054 (org-store-link-props :type "w3m" :url (url-view-url t)))
12056 ((setq search (run-hook-with-args-until-success
12057 'org-create-file-search-functions))
12058 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12059 "::" search))
12060 (setq cpltxt (or description link)))
12062 ((eq major-mode 'image-mode)
12063 (setq cpltxt (concat "file:"
12064 (abbreviate-file-name buffer-file-name))
12065 link (org-make-link cpltxt))
12066 (org-store-link-props :type "image" :file buffer-file-name))
12068 ((eq major-mode 'dired-mode)
12069 ;; link to the file in the current line
12070 (setq cpltxt (concat "file:"
12071 (abbreviate-file-name
12072 (expand-file-name
12073 (dired-get-filename nil t))))
12074 link (org-make-link cpltxt)))
12076 ((and buffer-file-name (org-mode-p))
12077 ;; Just link to current headline
12078 (setq cpltxt (concat "file:"
12079 (abbreviate-file-name buffer-file-name)))
12080 ;; Add a context search string
12081 (when (org-xor org-context-in-file-links arg)
12082 ;; Check if we are on a target
12083 (if (org-in-regexp "<<\\(.*?\\)>>")
12084 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12085 (setq txt (cond
12086 ((org-on-heading-p) nil)
12087 ((org-region-active-p)
12088 (buffer-substring (region-beginning) (region-end)))
12089 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12090 (when (or (null txt) (string-match "\\S-" txt))
12091 (setq cpltxt
12092 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12093 desc "NONE"))))
12094 (if (string-match "::\\'" cpltxt)
12095 (setq cpltxt (substring cpltxt 0 -2)))
12096 (setq link (org-make-link cpltxt)))
12098 ((buffer-file-name (buffer-base-buffer))
12099 ;; Just link to this file here.
12100 (setq cpltxt (concat "file:"
12101 (abbreviate-file-name
12102 (buffer-file-name (buffer-base-buffer)))))
12103 ;; Add a context string
12104 (when (org-xor org-context-in-file-links arg)
12105 (setq txt (if (org-region-active-p)
12106 (buffer-substring (region-beginning) (region-end))
12107 (buffer-substring (point-at-bol) (point-at-eol))))
12108 ;; Only use search option if there is some text.
12109 (when (string-match "\\S-" txt)
12110 (setq cpltxt
12111 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12112 desc "NONE")))
12113 (setq link (org-make-link cpltxt)))
12115 ((interactive-p)
12116 (error "Cannot link to a buffer which is not visiting a file"))
12118 (t (setq link nil)))
12120 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12121 (setq link (or link cpltxt)
12122 desc (or desc cpltxt))
12123 (if (equal desc "NONE") (setq desc nil))
12125 (if (and (interactive-p) link)
12126 (progn
12127 (setq org-stored-links
12128 (cons (list link desc) org-stored-links))
12129 (message "Stored: %s" (or desc link)))
12130 (and link (org-make-link-string link desc)))))
12132 (defun org-store-link-props (&rest plist)
12133 "Store link properties, extract names and addresses."
12134 (let (x adr)
12135 (when (setq x (plist-get plist :from))
12136 (setq adr (mail-extract-address-components x))
12137 (plist-put plist :fromname (car adr))
12138 (plist-put plist :fromaddress (nth 1 adr)))
12139 (when (setq x (plist-get plist :to))
12140 (setq adr (mail-extract-address-components x))
12141 (plist-put plist :toname (car adr))
12142 (plist-put plist :toaddress (nth 1 adr))))
12143 (let ((from (plist-get plist :from))
12144 (to (plist-get plist :to)))
12145 (when (and from to org-from-is-user-regexp)
12146 (plist-put plist :fromto
12147 (if (string-match org-from-is-user-regexp from)
12148 (concat "to %t")
12149 (concat "from %f")))))
12150 (setq org-store-link-plist plist))
12152 (defun org-email-link-description (&optional fmt)
12153 "Return the description part of an email link.
12154 This takes information from `org-store-link-plist' and formats it
12155 according to FMT (default from `org-email-link-description-format')."
12156 (setq fmt (or fmt org-email-link-description-format))
12157 (let* ((p org-store-link-plist)
12158 (to (plist-get p :toaddress))
12159 (from (plist-get p :fromaddress))
12160 (table
12161 (list
12162 (cons "%c" (plist-get p :fromto))
12163 (cons "%F" (plist-get p :from))
12164 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12165 (cons "%T" (plist-get p :to))
12166 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12167 (cons "%s" (plist-get p :subject))
12168 (cons "%m" (plist-get p :message-id)))))
12169 (when (string-match "%c" fmt)
12170 ;; Check if the user wrote this message
12171 (if (and org-from-is-user-regexp from to
12172 (save-match-data (string-match org-from-is-user-regexp from)))
12173 (setq fmt (replace-match "to %t" t t fmt))
12174 (setq fmt (replace-match "from %f" t t fmt))))
12175 (org-replace-escapes fmt table)))
12177 (defun org-make-org-heading-search-string (&optional string heading)
12178 "Make search string for STRING or current headline."
12179 (interactive)
12180 (let ((s (or string (org-get-heading))))
12181 (unless (and string (not heading))
12182 ;; We are using a headline, clean up garbage in there.
12183 (if (string-match org-todo-regexp s)
12184 (setq s (replace-match "" t t s)))
12185 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12186 (setq s (replace-match "" t t s)))
12187 (setq s (org-trim s))
12188 (if (string-match (concat "^\\(" org-quote-string "\\|"
12189 org-comment-string "\\)") s)
12190 (setq s (replace-match "" t t s)))
12191 (while (string-match org-ts-regexp s)
12192 (setq s (replace-match "" t t s))))
12193 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12194 (setq s (replace-match " " t t s)))
12195 (or string (setq s (concat "*" s))) ; Add * for headlines
12196 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12198 (defun org-make-link (&rest strings)
12199 "Concatenate STRINGS."
12200 (apply 'concat strings))
12202 (defun org-make-link-string (link &optional description)
12203 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12204 (unless (string-match "\\S-" link)
12205 (error "Empty link"))
12206 (when (stringp description)
12207 ;; Remove brackets from the description, they are fatal.
12208 (while (string-match "\\[" description)
12209 (setq description (replace-match "{" t t description)))
12210 (while (string-match "\\]" description)
12211 (setq description (replace-match "}" t t description))))
12212 (when (equal (org-link-escape link) description)
12213 ;; No description needed, it is identical
12214 (setq description nil))
12215 (when (and (not description)
12216 (not (equal link (org-link-escape link))))
12217 (setq description link))
12218 (concat "[[" (org-link-escape link) "]"
12219 (if description (concat "[" description "]") "")
12220 "]"))
12222 (defconst org-link-escape-chars
12223 '((?\ . "%20")
12224 (?\[ . "%5B")
12225 (?\] . "%5D")
12226 (?\340 . "%E0") ; `a
12227 (?\342 . "%E2") ; ^a
12228 (?\347 . "%E7") ; ,c
12229 (?\350 . "%E8") ; `e
12230 (?\351 . "%E9") ; 'e
12231 (?\352 . "%EA") ; ^e
12232 (?\356 . "%EE") ; ^i
12233 (?\364 . "%F4") ; ^o
12234 (?\371 . "%F9") ; `u
12235 (?\373 . "%FB") ; ^u
12236 (?\; . "%3B")
12237 (?? . "%3F")
12238 (?= . "%3D")
12239 (?+ . "%2B")
12241 "Association list of escapes for some characters problematic in links.
12242 This is the list that is used for internal purposes.")
12244 (defconst org-link-escape-chars-browser
12245 '((?\ . "%20")) ; 32 for the SPC char
12246 "Association list of escapes for some characters problematic in links.
12247 This is the list that is used before handing over to the browser.")
12249 (defun org-link-escape (text &optional table)
12250 "Escape charaters in TEXT that are problematic for links."
12251 (setq table (or table org-link-escape-chars))
12252 (when text
12253 (let ((re (mapconcat (lambda (x) (regexp-quote
12254 (char-to-string (car x))))
12255 table "\\|")))
12256 (while (string-match re text)
12257 (setq text
12258 (replace-match
12259 (cdr (assoc (string-to-char (match-string 0 text))
12260 table))
12261 t t text)))
12262 text)))
12264 (defun org-link-unescape (text &optional table)
12265 "Reverse the action of `org-link-escape'."
12266 (setq table (or table org-link-escape-chars))
12267 (when text
12268 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12269 table "\\|")))
12270 (while (string-match re text)
12271 (setq text
12272 (replace-match
12273 (char-to-string (car (rassoc (match-string 0 text) table)))
12274 t t text)))
12275 text)))
12277 (defun org-xor (a b)
12278 "Exclusive or."
12279 (if a (not b) b))
12281 (defun org-get-header (header)
12282 "Find a header field in the current buffer."
12283 (save-excursion
12284 (goto-char (point-min))
12285 (let ((case-fold-search t) s)
12286 (cond
12287 ((eq header 'from)
12288 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12289 (setq s (match-string 1)))
12290 (while (string-match "\"" s)
12291 (setq s (replace-match "" t t s)))
12292 (if (string-match "[<(].*" s)
12293 (setq s (replace-match "" t t s))))
12294 ((eq header 'message-id)
12295 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12296 (setq s (match-string 1))))
12297 ((eq header 'subject)
12298 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12299 (setq s (match-string 1)))))
12300 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12301 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12302 s)))
12305 (defun org-fixup-message-id-for-http (s)
12306 "Replace special characters in a message id, so it can be used in an http query."
12307 (while (string-match "<" s)
12308 (setq s (replace-match "%3C" t t s)))
12309 (while (string-match ">" s)
12310 (setq s (replace-match "%3E" t t s)))
12311 (while (string-match "@" s)
12312 (setq s (replace-match "%40" t t s)))
12315 ;;;###autoload
12316 (defun org-insert-link-global ()
12317 "Insert a link like Org-mode does.
12318 This command can be called in any mode to insert a link in Org-mode syntax."
12319 (interactive)
12320 (org-run-like-in-org-mode 'org-insert-link))
12322 (defun org-insert-link (&optional complete-file)
12323 "Insert a link. At the prompt, enter the link.
12325 Completion can be used to select a link previously stored with
12326 `org-store-link'. When the empty string is entered (i.e. if you just
12327 press RET at the prompt), the link defaults to the most recently
12328 stored link. As SPC triggers completion in the minibuffer, you need to
12329 use M-SPC or C-q SPC to force the insertion of a space character.
12331 You will also be prompted for a description, and if one is given, it will
12332 be displayed in the buffer instead of the link.
12334 If there is already a link at point, this command will allow you to edit link
12335 and description parts.
12337 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12338 selected using completion. The path to the file will be relative to
12339 the current directory if the file is in the current directory or a
12340 subdirectory. Otherwise, the link will be the absolute path as
12341 completed in the minibuffer (i.e. normally ~/path/to/file).
12343 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12344 is in the current directory or below.
12345 With three \\[universal-argument] prefixes, negate the meaning of
12346 `org-keep-stored-link-after-insertion'."
12347 (interactive "P")
12348 (let* ((wcf (current-window-configuration))
12349 (region (if (org-region-active-p)
12350 (buffer-substring (region-beginning) (region-end))))
12351 (remove (and region (list (region-beginning) (region-end))))
12352 (desc region)
12353 tmphist ; byte-compile incorrectly complains about this
12354 link entry file)
12355 (cond
12356 ((org-in-regexp org-bracket-link-regexp 1)
12357 ;; We do have a link at point, and we are going to edit it.
12358 (setq remove (list (match-beginning 0) (match-end 0)))
12359 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12360 (setq link (read-string "Link: "
12361 (org-link-unescape
12362 (org-match-string-no-properties 1)))))
12363 ((or (org-in-regexp org-angle-link-re)
12364 (org-in-regexp org-plain-link-re))
12365 ;; Convert to bracket link
12366 (setq remove (list (match-beginning 0) (match-end 0))
12367 link (read-string "Link: "
12368 (org-remove-angle-brackets (match-string 0)))))
12369 ((equal complete-file '(4))
12370 ;; Completing read for file names.
12371 (setq file (read-file-name "File: "))
12372 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12373 (pwd1 (file-name-as-directory (abbreviate-file-name
12374 (expand-file-name ".")))))
12375 (cond
12376 ((equal complete-file '(16))
12377 (setq link (org-make-link
12378 "file:"
12379 (abbreviate-file-name (expand-file-name file)))))
12380 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12381 (setq link (org-make-link "file:" (match-string 1 file))))
12382 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12383 (expand-file-name file))
12384 (setq link (org-make-link
12385 "file:" (match-string 1 (expand-file-name file)))))
12386 (t (setq link (org-make-link "file:" file))))))
12388 ;; Read link, with completion for stored links.
12389 (with-output-to-temp-buffer "*Org Links*"
12390 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12391 (when org-stored-links
12392 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12393 (princ (mapconcat
12394 (lambda (x)
12395 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12396 (reverse org-stored-links) "\n"))))
12397 (let ((cw (selected-window)))
12398 (select-window (get-buffer-window "*Org Links*"))
12399 (shrink-window-if-larger-than-buffer)
12400 (setq truncate-lines t)
12401 (select-window cw))
12402 ;; Fake a link history, containing the stored links.
12403 (setq tmphist (append (mapcar 'car org-stored-links)
12404 org-insert-link-history))
12405 (unwind-protect
12406 (setq link (org-completing-read
12407 "Link: "
12408 (append
12409 (mapcar (lambda (x) (list (concat (car x) ":")))
12410 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12411 (mapcar (lambda (x) (list (concat x ":")))
12412 org-link-types))
12413 nil nil nil
12414 'tmphist
12415 (or (car (car org-stored-links)))))
12416 (set-window-configuration wcf)
12417 (kill-buffer "*Org Links*"))
12418 (setq entry (assoc link org-stored-links))
12419 (or entry (push link org-insert-link-history))
12420 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12421 (not org-keep-stored-link-after-insertion))
12422 (setq org-stored-links (delq (assoc link org-stored-links)
12423 org-stored-links)))
12424 (setq desc (or desc (nth 1 entry)))))
12426 (if (string-match org-plain-link-re link)
12427 ;; URL-like link, normalize the use of angular brackets.
12428 (setq link (org-make-link (org-remove-angle-brackets link))))
12430 ;; Check if we are linking to the current file with a search option
12431 ;; If yes, simplify the link by using only the search option.
12432 (when (and buffer-file-name
12433 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12434 (let* ((path (match-string 1 link))
12435 (case-fold-search nil)
12436 (search (match-string 2 link)))
12437 (save-match-data
12438 (if (equal (file-truename buffer-file-name) (file-truename path))
12439 ;; We are linking to this same file, with a search option
12440 (setq link search)))))
12442 ;; Check if we can/should use a relative path. If yes, simplify the link
12443 (when (string-match "\\<file:\\(.*\\)" link)
12444 (let* ((path (match-string 1 link))
12445 (origpath path)
12446 (desc-is-link (equal link desc))
12447 (case-fold-search nil))
12448 (cond
12449 ((eq org-link-file-path-type 'absolute)
12450 (setq path (abbreviate-file-name (expand-file-name path))))
12451 ((eq org-link-file-path-type 'noabbrev)
12452 (setq path (expand-file-name path)))
12453 ((eq org-link-file-path-type 'relative)
12454 (setq path (file-relative-name path)))
12456 (save-match-data
12457 (if (string-match (concat "^" (regexp-quote
12458 (file-name-as-directory
12459 (expand-file-name "."))))
12460 (expand-file-name path))
12461 ;; We are linking a file with relative path name.
12462 (setq path (substring (expand-file-name path)
12463 (match-end 0)))))))
12464 (setq link (concat "file:" path))
12465 (if (equal desc origpath)
12466 (setq desc path))))
12468 (setq desc (read-string "Description: " desc))
12469 (unless (string-match "\\S-" desc) (setq desc nil))
12470 (if remove (apply 'delete-region remove))
12471 (insert (org-make-link-string link desc))))
12473 (defun org-completing-read (&rest args)
12474 (let ((minibuffer-local-completion-map
12475 (copy-keymap minibuffer-local-completion-map)))
12476 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12477 (apply 'completing-read args)))
12479 ;;; Opening/following a link
12480 (defvar org-link-search-failed nil)
12482 (defun org-next-link ()
12483 "Move forward to the next link.
12484 If the link is in hidden text, expose it."
12485 (interactive)
12486 (when (and org-link-search-failed (eq this-command last-command))
12487 (goto-char (point-min))
12488 (message "Link search wrapped back to beginning of buffer"))
12489 (setq org-link-search-failed nil)
12490 (let* ((pos (point))
12491 (ct (org-context))
12492 (a (assoc :link ct)))
12493 (if a (goto-char (nth 2 a)))
12494 (if (re-search-forward org-any-link-re nil t)
12495 (progn
12496 (goto-char (match-beginning 0))
12497 (if (org-invisible-p) (org-show-context)))
12498 (goto-char pos)
12499 (setq org-link-search-failed t)
12500 (error "No further link found"))))
12502 (defun org-previous-link ()
12503 "Move backward to the previous link.
12504 If the link is in hidden text, expose it."
12505 (interactive)
12506 (when (and org-link-search-failed (eq this-command last-command))
12507 (goto-char (point-max))
12508 (message "Link search wrapped back to end of buffer"))
12509 (setq org-link-search-failed nil)
12510 (let* ((pos (point))
12511 (ct (org-context))
12512 (a (assoc :link ct)))
12513 (if a (goto-char (nth 1 a)))
12514 (if (re-search-backward org-any-link-re nil t)
12515 (progn
12516 (goto-char (match-beginning 0))
12517 (if (org-invisible-p) (org-show-context)))
12518 (goto-char pos)
12519 (setq org-link-search-failed t)
12520 (error "No further link found"))))
12522 (defun org-find-file-at-mouse (ev)
12523 "Open file link or URL at mouse."
12524 (interactive "e")
12525 (mouse-set-point ev)
12526 (org-open-at-point 'in-emacs))
12528 (defun org-open-at-mouse (ev)
12529 "Open file link or URL at mouse."
12530 (interactive "e")
12531 (mouse-set-point ev)
12532 (org-open-at-point))
12534 (defvar org-window-config-before-follow-link nil
12535 "The window configuration before following a link.
12536 This is saved in case the need arises to restore it.")
12538 (defvar org-open-link-marker (make-marker)
12539 "Marker pointing to the location where `org-open-at-point; was called.")
12541 ;;;###autoload
12542 (defun org-open-at-point-global ()
12543 "Follow a link like Org-mode does.
12544 This command can be called in any mode to follow a link that has
12545 Org-mode syntax."
12546 (interactive)
12547 (org-run-like-in-org-mode 'org-open-at-point))
12549 (defun org-open-at-point (&optional in-emacs)
12550 "Open link at or after point.
12551 If there is no link at point, this function will search forward up to
12552 the end of the current subtree.
12553 Normally, files will be opened by an appropriate application. If the
12554 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12555 (interactive "P")
12556 (catch 'abort
12557 (move-marker org-open-link-marker (point))
12558 (setq org-window-config-before-follow-link (current-window-configuration))
12559 (org-remove-occur-highlights nil nil t)
12560 (if (org-at-timestamp-p t)
12561 (org-follow-timestamp-link)
12562 (let (type path link line search (pos (point)))
12563 (catch 'match
12564 (save-excursion
12565 (skip-chars-forward "^]\n\r")
12566 (when (org-in-regexp org-bracket-link-regexp)
12567 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12568 (while (string-match " *\n *" link)
12569 (setq link (replace-match " " t t link)))
12570 (setq link (org-link-expand-abbrev link))
12571 (if (string-match org-link-re-with-space2 link)
12572 (setq type (match-string 1 link) path (match-string 2 link))
12573 (setq type "thisfile" path link))
12574 (throw 'match t)))
12576 (when (get-text-property (point) 'org-linked-text)
12577 (setq type "thisfile"
12578 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12579 (1+ (point)) (point))
12580 path (buffer-substring
12581 (previous-single-property-change pos 'org-linked-text)
12582 (next-single-property-change pos 'org-linked-text)))
12583 (throw 'match t))
12585 (save-excursion
12586 (when (or (org-in-regexp org-angle-link-re)
12587 (org-in-regexp org-plain-link-re))
12588 (setq type (match-string 1) path (match-string 2))
12589 (throw 'match t)))
12590 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12591 (setq type "tree-match"
12592 path (match-string 1))
12593 (throw 'match t))
12594 (save-excursion
12595 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12596 (setq type "tags"
12597 path (match-string 1))
12598 (while (string-match ":" path)
12599 (setq path (replace-match "+" t t path)))
12600 (throw 'match t))))
12601 (unless path
12602 (error "No link found"))
12603 ;; Remove any trailing spaces in path
12604 (if (string-match " +\\'" path)
12605 (setq path (replace-match "" t t path)))
12607 (cond
12609 ((assoc type org-link-protocols)
12610 (funcall (nth 1 (assoc type org-link-protocols)) path))
12612 ((equal type "mailto")
12613 (let ((cmd (car org-link-mailto-program))
12614 (args (cdr org-link-mailto-program)) args1
12615 (address path) (subject "") a)
12616 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12617 (setq address (match-string 1 path)
12618 subject (org-link-escape (match-string 2 path))))
12619 (while args
12620 (cond
12621 ((not (stringp (car args))) (push (pop args) args1))
12622 (t (setq a (pop args))
12623 (if (string-match "%a" a)
12624 (setq a (replace-match address t t a)))
12625 (if (string-match "%s" a)
12626 (setq a (replace-match subject t t a)))
12627 (push a args1))))
12628 (apply cmd (nreverse args1))))
12630 ((member type '("http" "https" "ftp" "news"))
12631 (browse-url (concat type ":" (org-link-escape
12632 path org-link-escape-chars-browser))))
12634 ((member type '("message"))
12635 (browse-url (concat type ":" path)))
12637 ((string= type "tags")
12638 (org-tags-view in-emacs path))
12639 ((string= type "thisfile")
12640 (if in-emacs
12641 (switch-to-buffer-other-window
12642 (org-get-buffer-for-internal-link (current-buffer)))
12643 (org-mark-ring-push))
12644 (let ((cmd `(org-link-search
12645 ,path
12646 ,(cond ((equal in-emacs '(4)) 'occur)
12647 ((equal in-emacs '(16)) 'org-occur)
12648 (t nil))
12649 ,pos)))
12650 (condition-case nil (eval cmd)
12651 (error (progn (widen) (eval cmd))))))
12653 ((string= type "tree-match")
12654 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12656 ((string= type "file")
12657 (if (string-match "::\\([0-9]+\\)\\'" path)
12658 (setq line (string-to-number (match-string 1 path))
12659 path (substring path 0 (match-beginning 0)))
12660 (if (string-match "::\\(.+\\)\\'" path)
12661 (setq search (match-string 1 path)
12662 path (substring path 0 (match-beginning 0)))))
12663 (if (string-match "[*?{]" (file-name-nondirectory path))
12664 (dired path)
12665 (org-open-file path in-emacs line search)))
12667 ((string= type "news")
12668 (org-follow-gnus-link path))
12670 ((string= type "bbdb")
12671 (org-follow-bbdb-link path))
12673 ((string= type "info")
12674 (org-follow-info-link path))
12676 ((string= type "gnus")
12677 (let (group article)
12678 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12679 (error "Error in Gnus link"))
12680 (setq group (match-string 1 path)
12681 article (match-string 3 path))
12682 (org-follow-gnus-link group article)))
12684 ((string= type "vm")
12685 (let (folder article)
12686 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12687 (error "Error in VM link"))
12688 (setq folder (match-string 1 path)
12689 article (match-string 3 path))
12690 ;; in-emacs is the prefix arg, will be interpreted as read-only
12691 (org-follow-vm-link folder article in-emacs)))
12693 ((string= type "wl")
12694 (let (folder article)
12695 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12696 (error "Error in Wanderlust link"))
12697 (setq folder (match-string 1 path)
12698 article (match-string 3 path))
12699 (org-follow-wl-link folder article)))
12701 ((string= type "mhe")
12702 (let (folder article)
12703 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12704 (error "Error in MHE link"))
12705 (setq folder (match-string 1 path)
12706 article (match-string 3 path))
12707 (org-follow-mhe-link folder article)))
12709 ((string= type "rmail")
12710 (let (folder article)
12711 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12712 (error "Error in RMAIL link"))
12713 (setq folder (match-string 1 path)
12714 article (match-string 3 path))
12715 (org-follow-rmail-link folder article)))
12717 ((string= type "shell")
12718 (let ((cmd path))
12719 (if (or (not org-confirm-shell-link-function)
12720 (funcall org-confirm-shell-link-function
12721 (format "Execute \"%s\" in shell? "
12722 (org-add-props cmd nil
12723 'face 'org-warning))))
12724 (progn
12725 (message "Executing %s" cmd)
12726 (shell-command cmd))
12727 (error "Abort"))))
12729 ((string= type "elisp")
12730 (let ((cmd path))
12731 (if (or (not org-confirm-elisp-link-function)
12732 (funcall org-confirm-elisp-link-function
12733 (format "Execute \"%s\" as elisp? "
12734 (org-add-props cmd nil
12735 'face 'org-warning))))
12736 (message "%s => %s" cmd (eval (read cmd)))
12737 (error "Abort"))))
12740 (browse-url-at-point)))))
12741 (move-marker org-open-link-marker nil)))
12743 ;;; File search
12745 (defvar org-create-file-search-functions nil
12746 "List of functions to construct the right search string for a file link.
12747 These functions are called in turn with point at the location to
12748 which the link should point.
12750 A function in the hook should first test if it would like to
12751 handle this file type, for example by checking the major-mode or
12752 the file extension. If it decides not to handle this file, it
12753 should just return nil to give other functions a chance. If it
12754 does handle the file, it must return the search string to be used
12755 when following the link. The search string will be part of the
12756 file link, given after a double colon, and `org-open-at-point'
12757 will automatically search for it. If special measures must be
12758 taken to make the search successful, another function should be
12759 added to the companion hook `org-execute-file-search-functions',
12760 which see.
12762 A function in this hook may also use `setq' to set the variable
12763 `description' to provide a suggestion for the descriptive text to
12764 be used for this link when it gets inserted into an Org-mode
12765 buffer with \\[org-insert-link].")
12767 (defvar org-execute-file-search-functions nil
12768 "List of functions to execute a file search triggered by a link.
12770 Functions added to this hook must accept a single argument, the
12771 search string that was part of the file link, the part after the
12772 double colon. The function must first check if it would like to
12773 handle this search, for example by checking the major-mode or the
12774 file extension. If it decides not to handle this search, it
12775 should just return nil to give other functions a chance. If it
12776 does handle the search, it must return a non-nil value to keep
12777 other functions from trying.
12779 Each function can access the current prefix argument through the
12780 variable `current-prefix-argument'. Note that a single prefix is
12781 used to force opening a link in Emacs, so it may be good to only
12782 use a numeric or double prefix to guide the search function.
12784 In case this is needed, a function in this hook can also restore
12785 the window configuration before `org-open-at-point' was called using:
12787 (set-window-configuration org-window-config-before-follow-link)")
12789 (defun org-link-search (s &optional type avoid-pos)
12790 "Search for a link search option.
12791 If S is surrounded by forward slashes, it is interpreted as a
12792 regular expression. In org-mode files, this will create an `org-occur'
12793 sparse tree. In ordinary files, `occur' will be used to list matches.
12794 If the current buffer is in `dired-mode', grep will be used to search
12795 in all files. If AVOID-POS is given, ignore matches near that position."
12796 (let ((case-fold-search t)
12797 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12798 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12799 (append '(("") (" ") ("\t") ("\n"))
12800 org-emphasis-alist)
12801 "\\|") "\\)"))
12802 (pos (point))
12803 (pre "") (post "")
12804 words re0 re1 re2 re3 re4 re5 re2a reall)
12805 (cond
12806 ;; First check if there are any special
12807 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12808 ;; Now try the builtin stuff
12809 ((save-excursion
12810 (goto-char (point-min))
12811 (and
12812 (re-search-forward
12813 (concat "<<" (regexp-quote s0) ">>") nil t)
12814 (setq pos (match-beginning 0))))
12815 ;; There is an exact target for this
12816 (goto-char pos))
12817 ((string-match "^/\\(.*\\)/$" s)
12818 ;; A regular expression
12819 (cond
12820 ((org-mode-p)
12821 (org-occur (match-string 1 s)))
12822 ;;((eq major-mode 'dired-mode)
12823 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12824 (t (org-do-occur (match-string 1 s)))))
12826 ;; A normal search strings
12827 (when (equal (string-to-char s) ?*)
12828 ;; Anchor on headlines, post may include tags.
12829 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12830 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12831 s (substring s 1)))
12832 (remove-text-properties
12833 0 (length s)
12834 '(face nil mouse-face nil keymap nil fontified nil) s)
12835 ;; Make a series of regular expressions to find a match
12836 (setq words (org-split-string s "[ \n\r\t]+")
12837 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12838 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12839 "\\)" markers)
12840 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12841 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12842 re1 (concat pre re2 post)
12843 re3 (concat pre re4 post)
12844 re5 (concat pre ".*" re4)
12845 re2 (concat pre re2)
12846 re2a (concat pre re2a)
12847 re4 (concat pre re4)
12848 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12849 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12850 re5 "\\)"
12852 (cond
12853 ((eq type 'org-occur) (org-occur reall))
12854 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12855 (t (goto-char (point-min))
12856 (if (or (org-search-not-self 1 re0 nil t)
12857 (org-search-not-self 1 re1 nil t)
12858 (org-search-not-self 1 re2 nil t)
12859 (org-search-not-self 1 re2a nil t)
12860 (org-search-not-self 1 re3 nil t)
12861 (org-search-not-self 1 re4 nil t)
12862 (org-search-not-self 1 re5 nil t)
12864 (goto-char (match-beginning 1))
12865 (goto-char pos)
12866 (error "No match")))))
12868 ;; Normal string-search
12869 (goto-char (point-min))
12870 (if (search-forward s nil t)
12871 (goto-char (match-beginning 0))
12872 (error "No match"))))
12873 (and (org-mode-p) (org-show-context 'link-search))))
12875 (defun org-search-not-self (group &rest args)
12876 "Execute `re-search-forward', but only accept matches that do not
12877 enclose the position of `org-open-link-marker'."
12878 (let ((m org-open-link-marker))
12879 (catch 'exit
12880 (while (apply 're-search-forward args)
12881 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12882 (goto-char (match-end group))
12883 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12884 (> (match-beginning 0) (marker-position m))
12885 (< (match-end 0) (marker-position m)))
12886 (save-match-data
12887 (or (not (org-in-regexp
12888 org-bracket-link-analytic-regexp 1))
12889 (not (match-end 4)) ; no description
12890 (and (<= (match-beginning 4) (point))
12891 (>= (match-end 4) (point))))))
12892 (throw 'exit (point))))))))
12894 (defun org-get-buffer-for-internal-link (buffer)
12895 "Return a buffer to be used for displaying the link target of internal links."
12896 (cond
12897 ((not org-display-internal-link-with-indirect-buffer)
12898 buffer)
12899 ((string-match "(Clone)$" (buffer-name buffer))
12900 (message "Buffer is already a clone, not making another one")
12901 ;; we also do not modify visibility in this case
12902 buffer)
12903 (t ; make a new indirect buffer for displaying the link
12904 (let* ((bn (buffer-name buffer))
12905 (ibn (concat bn "(Clone)"))
12906 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12907 (with-current-buffer ib (org-overview))
12908 ib))))
12910 (defun org-do-occur (regexp &optional cleanup)
12911 "Call the Emacs command `occur'.
12912 If CLEANUP is non-nil, remove the printout of the regular expression
12913 in the *Occur* buffer. This is useful if the regex is long and not useful
12914 to read."
12915 (occur regexp)
12916 (when cleanup
12917 (let ((cwin (selected-window)) win beg end)
12918 (when (setq win (get-buffer-window "*Occur*"))
12919 (select-window win))
12920 (goto-char (point-min))
12921 (when (re-search-forward "match[a-z]+" nil t)
12922 (setq beg (match-end 0))
12923 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12924 (setq end (1- (match-beginning 0)))))
12925 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12926 (goto-char (point-min))
12927 (select-window cwin))))
12929 ;;; The mark ring for links jumps
12931 (defvar org-mark-ring nil
12932 "Mark ring for positions before jumps in Org-mode.")
12933 (defvar org-mark-ring-last-goto nil
12934 "Last position in the mark ring used to go back.")
12935 ;; Fill and close the ring
12936 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12937 (loop for i from 1 to org-mark-ring-length do
12938 (push (make-marker) org-mark-ring))
12939 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12940 org-mark-ring)
12942 (defun org-mark-ring-push (&optional pos buffer)
12943 "Put the current position or POS into the mark ring and rotate it."
12944 (interactive)
12945 (setq pos (or pos (point)))
12946 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12947 (move-marker (car org-mark-ring)
12948 (or pos (point))
12949 (or buffer (current-buffer)))
12950 (message "%s"
12951 (substitute-command-keys
12952 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12954 (defun org-mark-ring-goto (&optional n)
12955 "Jump to the previous position in the mark ring.
12956 With prefix arg N, jump back that many stored positions. When
12957 called several times in succession, walk through the entire ring.
12958 Org-mode commands jumping to a different position in the current file,
12959 or to another Org-mode file, automatically push the old position
12960 onto the ring."
12961 (interactive "p")
12962 (let (p m)
12963 (if (eq last-command this-command)
12964 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12965 (setq p org-mark-ring))
12966 (setq org-mark-ring-last-goto p)
12967 (setq m (car p))
12968 (switch-to-buffer (marker-buffer m))
12969 (goto-char m)
12970 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12972 (defun org-remove-angle-brackets (s)
12973 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12974 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12976 (defun org-add-angle-brackets (s)
12977 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12978 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12981 ;;; Following specific links
12983 (defun org-follow-timestamp-link ()
12984 (cond
12985 ((org-at-date-range-p t)
12986 (let ((org-agenda-start-on-weekday)
12987 (t1 (match-string 1))
12988 (t2 (match-string 2)))
12989 (setq t1 (time-to-days (org-time-string-to-time t1))
12990 t2 (time-to-days (org-time-string-to-time t2)))
12991 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12992 ((org-at-timestamp-p t)
12993 (org-agenda-list nil (time-to-days (org-time-string-to-time
12994 (substring (match-string 1) 0 10)))
12996 (t (error "This should not happen"))))
12999 (defun org-follow-bbdb-link (name)
13000 "Follow a BBDB link to NAME."
13001 (require 'bbdb)
13002 (let ((inhibit-redisplay (not debug-on-error))
13003 (bbdb-electric-p nil))
13004 (catch 'exit
13005 ;; Exact match on name
13006 (bbdb-name (concat "\\`" name "\\'") nil)
13007 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13008 ;; Exact match on name
13009 (bbdb-company (concat "\\`" name "\\'") nil)
13010 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13011 ;; Partial match on name
13012 (bbdb-name name nil)
13013 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13014 ;; Partial match on company
13015 (bbdb-company name nil)
13016 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13017 ;; General match including network address and notes
13018 (bbdb name nil)
13019 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13020 (delete-window (get-buffer-window "*BBDB*"))
13021 (error "No matching BBDB record")))))
13023 (defun org-follow-info-link (name)
13024 "Follow an info file & node link to NAME."
13025 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13026 (string-match "\\(.*\\)" name))
13027 (progn
13028 (require 'info)
13029 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13030 (Info-find-node (match-string 1 name) (match-string 2 name))
13031 (Info-find-node (match-string 1 name) "Top")))
13032 (message "Could not open: %s" name)))
13034 (defun org-follow-gnus-link (&optional group article)
13035 "Follow a Gnus link to GROUP and ARTICLE."
13036 (require 'gnus)
13037 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13038 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13039 (cond ((and group article)
13040 (gnus-group-read-group 1 nil group)
13041 (gnus-summary-goto-article (string-to-number article) nil t))
13042 (group (gnus-group-jump-to-group group))))
13044 (defun org-follow-vm-link (&optional folder article readonly)
13045 "Follow a VM link to FOLDER and ARTICLE."
13046 (require 'vm)
13047 (setq article (org-add-angle-brackets article))
13048 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13049 ;; ange-ftp or efs or tramp access
13050 (let ((user (or (match-string 1 folder) (user-login-name)))
13051 (host (match-string 2 folder))
13052 (file (match-string 3 folder)))
13053 (cond
13054 ((featurep 'tramp)
13055 ;; use tramp to access the file
13056 (if (featurep 'xemacs)
13057 (setq folder (format "[%s@%s]%s" user host file))
13058 (setq folder (format "/%s@%s:%s" user host file))))
13060 ;; use ange-ftp or efs
13061 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13062 (setq folder (format "/%s@%s:%s" user host file))))))
13063 (when folder
13064 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13065 (sit-for 0.1)
13066 (when article
13067 (vm-select-folder-buffer)
13068 (widen)
13069 (let ((case-fold-search t))
13070 (goto-char (point-min))
13071 (if (not (re-search-forward
13072 (concat "^" "message-id: *" (regexp-quote article))))
13073 (error "Could not find the specified message in this folder"))
13074 (vm-isearch-update)
13075 (vm-isearch-narrow)
13076 (vm-beginning-of-message)
13077 (vm-summarize)))))
13079 (defun org-follow-wl-link (folder article)
13080 "Follow a Wanderlust link to FOLDER and ARTICLE."
13081 (if (and (string= folder "%")
13082 article
13083 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13084 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13085 ;; Thus, we recompose folder and article ids.
13086 (setq folder (format "%s#%s" folder (match-string 1 article))
13087 article (match-string 3 article)))
13088 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13089 (error "No such folder: %s" folder))
13090 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13091 (and article
13092 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13093 (wl-summary-redisplay)))
13095 (defun org-follow-rmail-link (folder article)
13096 "Follow an RMAIL link to FOLDER and ARTICLE."
13097 (setq article (org-add-angle-brackets article))
13098 (let (message-number)
13099 (save-excursion
13100 (save-window-excursion
13101 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13102 (setq message-number
13103 (save-restriction
13104 (widen)
13105 (goto-char (point-max))
13106 (if (re-search-backward
13107 (concat "^Message-ID:\\s-+" (regexp-quote
13108 (or article "")))
13109 nil t)
13110 (rmail-what-message))))))
13111 (if message-number
13112 (progn
13113 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13114 (rmail-show-message message-number)
13115 message-number)
13116 (error "Message not found"))))
13118 ;;; mh-e integration based on planner-mode
13119 (defun org-mhe-get-message-real-folder ()
13120 "Return the name of the current message real folder, so if you use
13121 sequences, it will now work."
13122 (save-excursion
13123 (let* ((folder
13124 (if (equal major-mode 'mh-folder-mode)
13125 mh-current-folder
13126 ;; Refer to the show buffer
13127 mh-show-folder-buffer))
13128 (end-index
13129 (if (boundp 'mh-index-folder)
13130 (min (length mh-index-folder) (length folder))))
13132 ;; a simple test on mh-index-data does not work, because
13133 ;; mh-index-data is always nil in a show buffer.
13134 (if (and (boundp 'mh-index-folder)
13135 (string= mh-index-folder (substring folder 0 end-index)))
13136 (if (equal major-mode 'mh-show-mode)
13137 (save-window-excursion
13138 (let (pop-up-frames)
13139 (when (buffer-live-p (get-buffer folder))
13140 (progn
13141 (pop-to-buffer folder)
13142 (org-mhe-get-message-folder-from-index)
13145 (org-mhe-get-message-folder-from-index)
13147 folder
13151 (defun org-mhe-get-message-folder-from-index ()
13152 "Returns the name of the message folder in a index folder buffer."
13153 (save-excursion
13154 (mh-index-previous-folder)
13155 (re-search-forward "^\\(+.*\\)$" nil t)
13156 (message "%s" (match-string 1))))
13158 (defun org-mhe-get-message-folder ()
13159 "Return the name of the current message folder. Be careful if you
13160 use sequences."
13161 (save-excursion
13162 (if (equal major-mode 'mh-folder-mode)
13163 mh-current-folder
13164 ;; Refer to the show buffer
13165 mh-show-folder-buffer)))
13167 (defun org-mhe-get-message-num ()
13168 "Return the number of the current message. Be careful if you
13169 use sequences."
13170 (save-excursion
13171 (if (equal major-mode 'mh-folder-mode)
13172 (mh-get-msg-num nil)
13173 ;; Refer to the show buffer
13174 (mh-show-buffer-message-number))))
13176 (defun org-mhe-get-header (header)
13177 "Return a header of the message in folder mode. This will create a
13178 show buffer for the corresponding message. If you have a more clever
13179 idea..."
13180 (let* ((folder (org-mhe-get-message-folder))
13181 (num (org-mhe-get-message-num))
13182 (buffer (get-buffer-create (concat "show-" folder)))
13183 (header-field))
13184 (with-current-buffer buffer
13185 (mh-display-msg num folder)
13186 (if (equal major-mode 'mh-folder-mode)
13187 (mh-header-display)
13188 (mh-show-header-display))
13189 (set-buffer buffer)
13190 (setq header-field (mh-get-header-field header))
13191 (if (equal major-mode 'mh-folder-mode)
13192 (mh-show)
13193 (mh-show-show))
13194 header-field)))
13196 (defun org-follow-mhe-link (folder article)
13197 "Follow an MHE link to FOLDER and ARTICLE.
13198 If ARTICLE is nil FOLDER is shown. If the configuration variable
13199 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13200 ARTICLE is searched in all folders. Indexed searches (swish++,
13201 namazu, and others supported by MH-E) will always search in all
13202 folders."
13203 (require 'mh-e)
13204 (require 'mh-search)
13205 (require 'mh-utils)
13206 (mh-find-path)
13207 (if (not article)
13208 (mh-visit-folder (mh-normalize-folder-name folder))
13209 (setq article (org-add-angle-brackets article))
13210 (mh-search-choose)
13211 (if (equal mh-searcher 'pick)
13212 (progn
13213 (mh-search folder (list "--message-id" article))
13214 (when (and org-mhe-search-all-folders
13215 (not (org-mhe-get-message-real-folder)))
13216 (kill-this-buffer)
13217 (mh-search "+" (list "--message-id" article))))
13218 (mh-search "+" article))
13219 (if (org-mhe-get-message-real-folder)
13220 (mh-show-msg 1)
13221 (kill-this-buffer)
13222 (error "Message not found"))))
13224 ;;; BibTeX links
13226 ;; Use the custom search meachnism to construct and use search strings for
13227 ;; file links to BibTeX database entries.
13229 (defun org-create-file-search-in-bibtex ()
13230 "Create the search string and description for a BibTeX database entry."
13231 (when (eq major-mode 'bibtex-mode)
13232 ;; yes, we want to construct this search string.
13233 ;; Make a good description for this entry, using names, year and the title
13234 ;; Put it into the `description' variable which is dynamically scoped.
13235 (let ((bibtex-autokey-names 1)
13236 (bibtex-autokey-names-stretch 1)
13237 (bibtex-autokey-name-case-convert-function 'identity)
13238 (bibtex-autokey-name-separator " & ")
13239 (bibtex-autokey-additional-names " et al.")
13240 (bibtex-autokey-year-length 4)
13241 (bibtex-autokey-name-year-separator " ")
13242 (bibtex-autokey-titlewords 3)
13243 (bibtex-autokey-titleword-separator " ")
13244 (bibtex-autokey-titleword-case-convert-function 'identity)
13245 (bibtex-autokey-titleword-length 'infty)
13246 (bibtex-autokey-year-title-separator ": "))
13247 (setq description (bibtex-generate-autokey)))
13248 ;; Now parse the entry, get the key and return it.
13249 (save-excursion
13250 (bibtex-beginning-of-entry)
13251 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13253 (defun org-execute-file-search-in-bibtex (s)
13254 "Find the link search string S as a key for a database entry."
13255 (when (eq major-mode 'bibtex-mode)
13256 ;; Yes, we want to do the search in this file.
13257 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13258 (goto-char (point-min))
13259 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13260 (regexp-quote s) "[ \t\n]*,") nil t)
13261 (goto-char (match-beginning 0)))
13262 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13263 ;; Use double prefix to indicate that any web link should be browsed
13264 (let ((b (current-buffer)) (p (point)))
13265 ;; Restore the window configuration because we just use the web link
13266 (set-window-configuration org-window-config-before-follow-link)
13267 (save-excursion (set-buffer b) (goto-char p)
13268 (bibtex-url)))
13269 (recenter 0)) ; Move entry start to beginning of window
13270 ;; return t to indicate that the search is done.
13273 ;; Finally add the functions to the right hooks.
13274 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13275 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13277 ;; end of Bibtex link setup
13279 ;;; Following file links
13281 (defun org-open-file (path &optional in-emacs line search)
13282 "Open the file at PATH.
13283 First, this expands any special file name abbreviations. Then the
13284 configuration variable `org-file-apps' is checked if it contains an
13285 entry for this file type, and if yes, the corresponding command is launched.
13286 If no application is found, Emacs simply visits the file.
13287 With optional argument IN-EMACS, Emacs will visit the file.
13288 Optional LINE specifies a line to go to, optional SEARCH a string to
13289 search for. If LINE or SEARCH is given, the file will always be
13290 opened in Emacs.
13291 If the file does not exist, an error is thrown."
13292 (setq in-emacs (or in-emacs line search))
13293 (let* ((file (if (equal path "")
13294 buffer-file-name
13295 (substitute-in-file-name (expand-file-name path))))
13296 (apps (append org-file-apps (org-default-apps)))
13297 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13298 (dirp (if remp nil (file-directory-p file)))
13299 (dfile (downcase file))
13300 (old-buffer (current-buffer))
13301 (old-pos (point))
13302 (old-mode major-mode)
13303 ext cmd)
13304 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13305 (setq ext (match-string 1 dfile))
13306 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13307 (setq ext (match-string 1 dfile))))
13308 (if in-emacs
13309 (setq cmd 'emacs)
13310 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13311 (and dirp (cdr (assoc 'directory apps)))
13312 (cdr (assoc ext apps))
13313 (cdr (assoc t apps)))))
13314 (when (eq cmd 'mailcap)
13315 (require 'mailcap)
13316 (mailcap-parse-mailcaps)
13317 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13318 (command (mailcap-mime-info mime-type)))
13319 (if (stringp command)
13320 (setq cmd command)
13321 (setq cmd 'emacs))))
13322 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13323 (not (file-exists-p file))
13324 (not org-open-non-existing-files))
13325 (error "No such file: %s" file))
13326 (cond
13327 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13328 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13329 (while (string-match "['\"]%s['\"]" cmd)
13330 (setq cmd (replace-match "%s" t t cmd)))
13331 (while (string-match "%s" cmd)
13332 (setq cmd (replace-match
13333 (save-match-data (shell-quote-argument file))
13334 t t cmd)))
13335 (save-window-excursion
13336 (start-process-shell-command cmd nil cmd)))
13337 ((or (stringp cmd)
13338 (eq cmd 'emacs))
13339 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13340 (widen)
13341 (if line (goto-line line)
13342 (if search (org-link-search search))))
13343 ((consp cmd)
13344 (eval cmd))
13345 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13346 (and (org-mode-p) (eq old-mode 'org-mode)
13347 (or (not (equal old-buffer (current-buffer)))
13348 (not (equal old-pos (point))))
13349 (org-mark-ring-push old-pos old-buffer))))
13351 (defun org-default-apps ()
13352 "Return the default applications for this operating system."
13353 (cond
13354 ((eq system-type 'darwin)
13355 org-file-apps-defaults-macosx)
13356 ((eq system-type 'windows-nt)
13357 org-file-apps-defaults-windowsnt)
13358 (t org-file-apps-defaults-gnu)))
13360 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13361 (defun org-file-remote-p (file)
13362 "Test whether FILE specifies a location on a remote system.
13363 Return non-nil if the location is indeed remote.
13365 For example, the filename \"/user@host:/foo\" specifies a location
13366 on the system \"/user@host:\"."
13367 (cond ((fboundp 'file-remote-p)
13368 (file-remote-p file))
13369 ((fboundp 'tramp-handle-file-remote-p)
13370 (tramp-handle-file-remote-p file))
13371 ((and (boundp 'ange-ftp-name-format)
13372 (string-match (car ange-ftp-name-format) file))
13374 (t nil)))
13377 ;;;; Hooks for remember.el, and refiling
13379 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13380 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13382 ;;;###autoload
13383 (defun org-remember-insinuate ()
13384 "Setup remember.el for use wiht Org-mode."
13385 (require 'remember)
13386 (setq remember-annotation-functions '(org-remember-annotation))
13387 (setq remember-handler-functions '(org-remember-handler))
13388 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13390 ;;;###autoload
13391 (defun org-remember-annotation ()
13392 "Return a link to the current location as an annotation for remember.el.
13393 If you are using Org-mode files as target for data storage with
13394 remember.el, then the annotations should include a link compatible with the
13395 conventions in Org-mode. This function returns such a link."
13396 (org-store-link nil))
13398 (defconst org-remember-help
13399 "Select a destination location for the note.
13400 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13401 RET on headline -> Store as sublevel entry to current headline
13402 RET at beg-of-buf -> Append to file as level 2 headline
13403 <left>/<right> -> before/after current headline, same headings level")
13405 (defvar org-remember-previous-location nil)
13406 (defvar org-force-remember-template-char) ;; dynamically scoped
13408 (defun org-select-remember-template (&optional use-char)
13409 (when org-remember-templates
13410 (let* ((templates (mapcar (lambda (x)
13411 (if (stringp (car x))
13412 (append (list (nth 1 x) (car x)) (cddr x))
13413 (append (list (car x) "") (cdr x))))
13414 org-remember-templates))
13415 (char (or use-char
13416 (cond
13417 ((= (length templates) 1)
13418 (caar templates))
13419 ((and (boundp 'org-force-remember-template-char)
13420 org-force-remember-template-char)
13421 (if (stringp org-force-remember-template-char)
13422 (string-to-char org-force-remember-template-char)
13423 org-force-remember-template-char))
13425 (message "Select template: %s"
13426 (mapconcat
13427 (lambda (x)
13428 (cond
13429 ((not (string-match "\\S-" (nth 1 x)))
13430 (format "[%c]" (car x)))
13431 ((equal (downcase (car x))
13432 (downcase (aref (nth 1 x) 0)))
13433 (format "[%c]%s" (car x)
13434 (substring (nth 1 x) 1)))
13435 (t (format "[%c]%s" (car x) (nth 1 x)))))
13436 templates " "))
13437 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13438 (when (equal char0 ?\C-g)
13439 (jump-to-register remember-register)
13440 (kill-buffer remember-buffer))
13441 char0))))))
13442 (cddr (assoc char templates)))))
13444 (defvar x-last-selected-text)
13445 (defvar x-last-selected-text-primary)
13447 ;;;###autoload
13448 (defun org-remember-apply-template (&optional use-char skip-interactive)
13449 "Initialize *remember* buffer with template, invoke `org-mode'.
13450 This function should be placed into `remember-mode-hook' and in fact requires
13451 to be run from that hook to function properly."
13452 (if org-remember-templates
13453 (let* ((entry (org-select-remember-template use-char))
13454 (tpl (car entry))
13455 (plist-p (if org-store-link-plist t nil))
13456 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13457 (string-match "\\S-" (nth 1 entry)))
13458 (nth 1 entry)
13459 org-default-notes-file))
13460 (headline (nth 2 entry))
13461 (v-c (or (and (eq window-system 'x)
13462 (fboundp 'x-cut-buffer-or-selection-value)
13463 (x-cut-buffer-or-selection-value))
13464 (org-bound-and-true-p x-last-selected-text)
13465 (org-bound-and-true-p x-last-selected-text-primary)
13466 (and (> (length kill-ring) 0) (current-kill 0))))
13467 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13468 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13469 (v-u (concat "[" (substring v-t 1 -1) "]"))
13470 (v-U (concat "[" (substring v-T 1 -1) "]"))
13471 ;; `initial' and `annotation' are bound in `remember'
13472 (v-i (if (boundp 'initial) initial))
13473 (v-a (if (and (boundp 'annotation) annotation)
13474 (if (equal annotation "[[]]") "" annotation)
13475 ""))
13476 (v-A (if (and v-a
13477 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13478 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13479 v-a))
13480 (v-n user-full-name)
13481 (org-startup-folded nil)
13482 org-time-was-given org-end-time-was-given x
13483 prompt completions char time pos default histvar)
13484 (setq org-store-link-plist
13485 (append (list :annotation v-a :initial v-i)
13486 org-store-link-plist))
13487 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13488 (erase-buffer)
13489 (insert (substitute-command-keys
13490 (format
13491 "## Filing location: Select interactively, default, or last used:
13492 ## %s to select file and header location interactively.
13493 ## %s \"%s\" -> \"* %s\"
13494 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13495 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13496 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13497 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13498 (abbreviate-file-name (or file org-default-notes-file))
13499 (or headline "")
13500 (or (car org-remember-previous-location) "???")
13501 (or (cdr org-remember-previous-location) "???"))))
13502 (insert tpl) (goto-char (point-min))
13503 ;; Simple %-escapes
13504 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13505 (when (and initial (equal (match-string 0) "%i"))
13506 (save-match-data
13507 (let* ((lead (buffer-substring
13508 (point-at-bol) (match-beginning 0))))
13509 (setq v-i (mapconcat 'identity
13510 (org-split-string initial "\n")
13511 (concat "\n" lead))))))
13512 (replace-match
13513 (or (eval (intern (concat "v-" (match-string 1)))) "")
13514 t t))
13516 ;; %[] Insert contents of a file.
13517 (goto-char (point-min))
13518 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13519 (let ((start (match-beginning 0))
13520 (end (match-end 0))
13521 (filename (expand-file-name (match-string 1))))
13522 (goto-char start)
13523 (delete-region start end)
13524 (condition-case error
13525 (insert-file-contents filename)
13526 (error (insert (format "%%![Couldn't insert %s: %s]"
13527 filename error))))))
13528 ;; %() embedded elisp
13529 (goto-char (point-min))
13530 (while (re-search-forward "%\\((.+)\\)" nil t)
13531 (goto-char (match-beginning 0))
13532 (let ((template-start (point)))
13533 (forward-char 1)
13534 (let ((result
13535 (condition-case error
13536 (eval (read (current-buffer)))
13537 (error (format "%%![Error: %s]" error)))))
13538 (delete-region template-start (point))
13539 (insert result))))
13541 ;; From the property list
13542 (when plist-p
13543 (goto-char (point-min))
13544 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13545 (and (setq x (or (plist-get org-store-link-plist
13546 (intern (match-string 1))) ""))
13547 (replace-match x t t))))
13549 ;; Turn on org-mode in the remember buffer, set local variables
13550 (org-mode)
13551 (org-set-local 'org-finish-function 'org-remember-finalize)
13552 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13553 (org-set-local 'org-default-notes-file file))
13554 (if (and headline (stringp headline) (string-match "\\S-" headline))
13555 (org-set-local 'org-remember-default-headline headline))
13556 ;; Interactive template entries
13557 (goto-char (point-min))
13558 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13559 (setq char (if (match-end 3) (match-string 3))
13560 prompt (if (match-end 2) (match-string 2)))
13561 (goto-char (match-beginning 0))
13562 (replace-match "")
13563 (setq completions nil default nil)
13564 (when prompt
13565 (setq completions (org-split-string prompt "|")
13566 prompt (pop completions)
13567 default (car completions)
13568 histvar (intern (concat
13569 "org-remember-template-prompt-history::"
13570 (or prompt "")))
13571 completions (mapcar 'list completions)))
13572 (cond
13573 ((member char '("G" "g"))
13574 (let* ((org-last-tags-completion-table
13575 (org-global-tags-completion-table
13576 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13577 (org-add-colon-after-tag-completion t)
13578 (ins (completing-read
13579 (if prompt (concat prompt ": ") "Tags: ")
13580 'org-tags-completion-function nil nil nil
13581 'org-tags-history)))
13582 (setq ins (mapconcat 'identity
13583 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13584 ":"))
13585 (when (string-match "\\S-" ins)
13586 (or (equal (char-before) ?:) (insert ":"))
13587 (insert ins)
13588 (or (equal (char-after) ?:) (insert ":")))))
13589 (char
13590 (setq org-time-was-given (equal (upcase char) char))
13591 (setq time (org-read-date (equal (upcase char) "U") t nil
13592 prompt))
13593 (org-insert-time-stamp time org-time-was-given
13594 (member char '("u" "U"))
13595 nil nil (list org-end-time-was-given)))
13597 (insert (org-completing-read
13598 (concat (if prompt prompt "Enter string")
13599 (if default (concat " [" default "]"))
13600 ": ")
13601 completions nil nil nil histvar default)))))
13602 (goto-char (point-min))
13603 (if (re-search-forward "%\\?" nil t)
13604 (replace-match "")
13605 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13606 (org-mode)
13607 (org-set-local 'org-finish-function 'org-remember-finalize))
13608 (when (save-excursion
13609 (goto-char (point-min))
13610 (re-search-forward "%!" nil t))
13611 (replace-match "")
13612 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13614 (defun org-remember-finish-immediately ()
13615 "File remember note immediately.
13616 This should be run in `post-command-hook' and will remove itself
13617 from that hook."
13618 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13619 (when org-finish-function
13620 (funcall org-finish-function)))
13622 (defvar org-clock-marker) ; Defined below
13623 (defun org-remember-finalize ()
13624 "Finalize the remember process."
13625 (unless (fboundp 'remember-finalize)
13626 (defalias 'remember-finalize 'remember-buffer))
13627 (when (and org-clock-marker
13628 (equal (marker-buffer org-clock-marker) (current-buffer)))
13629 ;; FIXME: test this, this is w/o notetaking!
13630 (let (org-log-done) (org-clock-out)))
13631 (when buffer-file-name
13632 (save-buffer)
13633 (setq buffer-file-name nil))
13634 (remember-finalize))
13636 ;;;###autoload
13637 (defun org-remember (&optional goto org-force-remember-template-char)
13638 "Call `remember'. If this is already a remember buffer, re-apply template.
13639 If there is an active region, make sure remember uses it as initial content
13640 of the remember buffer.
13642 When called interactively with a `C-u' prefix argument GOTO, don't remember
13643 anything, just go to the file/headline where the selected template usually
13644 stores its notes. With a double prefix arg `C-u C-u', go to the last
13645 note stored by remember.
13647 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13648 associated with a template in `org-remember-templates'."
13649 (interactive "P")
13650 (cond
13651 ((equal goto '(4)) (org-go-to-remember-target))
13652 ((equal goto '(16)) (org-remember-goto-last-stored))
13654 (if (memq org-finish-function '(remember-buffer remember-finalize))
13655 (progn
13656 (when (< (length org-remember-templates) 2)
13657 (error "No other template available"))
13658 (erase-buffer)
13659 (let ((annotation (plist-get org-store-link-plist :annotation))
13660 (initial (plist-get org-store-link-plist :initial)))
13661 (org-remember-apply-template))
13662 (message "Press C-c C-c to remember data"))
13663 (if (org-region-active-p)
13664 (remember (buffer-substring (point) (mark)))
13665 (call-interactively 'remember))))))
13667 (defun org-remember-goto-last-stored ()
13668 "Go to the location where the last remember note was stored."
13669 (interactive)
13670 (bookmark-jump "org-remember-last-stored")
13671 (message "This is the last note stored by remember"))
13673 (defun org-go-to-remember-target (&optional template-key)
13674 "Go to the target location of a remember template.
13675 The user is queried for the template."
13676 (interactive)
13677 (let* ((entry (org-select-remember-template template-key))
13678 (file (nth 1 entry))
13679 (heading (nth 2 entry))
13680 visiting)
13681 (unless (and file (stringp file) (string-match "\\S-" file))
13682 (setq file org-default-notes-file))
13683 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13684 (setq heading org-remember-default-headline))
13685 (setq visiting (org-find-base-buffer-visiting file))
13686 (if (not visiting) (find-file-noselect file))
13687 (switch-to-buffer (or visiting (get-file-buffer file)))
13688 (widen)
13689 (goto-char (point-min))
13690 (if (re-search-forward
13691 (concat "^\\*+[ \t]+" (regexp-quote heading)
13692 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13693 nil t)
13694 (goto-char (match-beginning 0))
13695 (error "Target headline not found: %s" heading))))
13697 (defvar org-note-abort nil) ; dynamically scoped
13699 ;;;###autoload
13700 (defun org-remember-handler ()
13701 "Store stuff from remember.el into an org file.
13702 First prompts for an org file. If the user just presses return, the value
13703 of `org-default-notes-file' is used.
13704 Then the command offers the headings tree of the selected file in order to
13705 file the text at a specific location.
13706 You can either immediately press RET to get the note appended to the
13707 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13708 find a better place. Then press RET or <left> or <right> in insert the note.
13710 Key Cursor position Note gets inserted
13711 -----------------------------------------------------------------------------
13712 RET buffer-start as level 1 heading at end of file
13713 RET on headline as sublevel of the heading at cursor
13714 RET no heading at cursor position, level taken from context.
13715 Or use prefix arg to specify level manually.
13716 <left> on headline as same level, before current heading
13717 <right> on headline as same level, after current heading
13719 So the fastest way to store the note is to press RET RET to append it to
13720 the default file. This way your current train of thought is not
13721 interrupted, in accordance with the principles of remember.el.
13722 You can also get the fast execution without prompting by using
13723 C-u C-c C-c to exit the remember buffer. See also the variable
13724 `org-remember-store-without-prompt'.
13726 Before being stored away, the function ensures that the text has a
13727 headline, i.e. a first line that starts with a \"*\". If not, a headline
13728 is constructed from the current date and some additional data.
13730 If the variable `org-adapt-indentation' is non-nil, the entire text is
13731 also indented so that it starts in the same column as the headline
13732 \(i.e. after the stars).
13734 See also the variable `org-reverse-note-order'."
13735 (goto-char (point-min))
13736 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13737 (replace-match ""))
13738 (goto-char (point-max))
13739 (beginning-of-line 1)
13740 (while (looking-at "[ \t]*$\\|##.*")
13741 (delete-region (1- (point)) (point-max))
13742 (beginning-of-line 1))
13743 (catch 'quit
13744 (if org-note-abort (throw 'quit nil))
13745 (let* ((txt (buffer-substring (point-min) (point-max)))
13746 (fastp (org-xor (equal current-prefix-arg '(4))
13747 org-remember-store-without-prompt))
13748 (file (cond
13749 (fastp org-default-notes-file)
13750 ((and (eq org-remember-interactive-interface 'refile)
13751 org-refile-targets)
13752 org-default-notes-file)
13753 ((not (and (equal current-prefix-arg '(16))
13754 org-remember-previous-location))
13755 (org-get-org-file))))
13756 (heading org-remember-default-headline)
13757 (visiting (and file (org-find-base-buffer-visiting file)))
13758 (org-startup-folded nil)
13759 (org-startup-align-all-tables nil)
13760 (org-goto-start-pos 1)
13761 spos exitcmd level indent reversed)
13762 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13763 (setq file (car org-remember-previous-location)
13764 heading (cdr org-remember-previous-location)
13765 fastp t))
13766 (setq current-prefix-arg nil)
13767 (if (string-match "[ \t\n]+\\'" txt)
13768 (setq txt (replace-match "" t t txt)))
13769 ;; Modify text so that it becomes a nice subtree which can be inserted
13770 ;; into an org tree.
13771 (let* ((lines (split-string txt "\n"))
13772 first)
13773 (setq first (car lines) lines (cdr lines))
13774 (if (string-match "^\\*+ " first)
13775 ;; Is already a headline
13776 (setq indent nil)
13777 ;; We need to add a headline: Use time and first buffer line
13778 (setq lines (cons first lines)
13779 first (concat "* " (current-time-string)
13780 " (" (remember-buffer-desc) ")")
13781 indent " "))
13782 (if (and org-adapt-indentation indent)
13783 (setq lines (mapcar
13784 (lambda (x)
13785 (if (string-match "\\S-" x)
13786 (concat indent x) x))
13787 lines)))
13788 (setq txt (concat first "\n"
13789 (mapconcat 'identity lines "\n"))))
13790 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13791 (setq txt (replace-match "\n\n" t t txt))
13792 (if (string-match "[ \t\n]*\\'" txt)
13793 (setq txt (replace-match "\n" t t txt))))
13794 ;; Put the modified text back into the remember buffer, for refile.
13795 (erase-buffer)
13796 (insert txt)
13797 (goto-char (point-min))
13798 (when (and (eq org-remember-interactive-interface 'refile)
13799 (not fastp))
13800 (org-refile nil (or visiting (find-file-noselect file)))
13801 (throw 'quit t))
13802 ;; Find the file
13803 (if (not visiting) (find-file-noselect file))
13804 (with-current-buffer (or visiting (get-file-buffer file))
13805 (unless (org-mode-p)
13806 (error "Target files for remember notes must be in Org-mode"))
13807 (save-excursion
13808 (save-restriction
13809 (widen)
13810 (and (goto-char (point-min))
13811 (not (re-search-forward "^\\* " nil t))
13812 (insert "\n* " (or heading "Notes") "\n"))
13813 (setq reversed (org-notes-order-reversed-p))
13815 ;; Find the default location
13816 (when (and heading (stringp heading) (string-match "\\S-" heading))
13817 (goto-char (point-min))
13818 (if (re-search-forward
13819 (concat "^\\*+[ \t]+" (regexp-quote heading)
13820 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13821 nil t)
13822 (setq org-goto-start-pos (match-beginning 0))
13823 (when fastp
13824 (goto-char (point-max))
13825 (unless (bolp) (newline))
13826 (insert "* " heading "\n")
13827 (setq org-goto-start-pos (point-at-bol 0)))))
13829 ;; Ask the User for a location, using the appropriate interface
13830 (cond
13831 (fastp (setq spos org-goto-start-pos
13832 exitcmd 'return))
13833 ((eq org-remember-interactive-interface 'outline)
13834 (setq spos (org-get-location (current-buffer)
13835 org-remember-help)
13836 exitcmd (cdr spos)
13837 spos (car spos)))
13838 ((eq org-remember-interactive-interface 'outline-path-completion)
13839 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13840 (org-refile-use-outline-path t))
13841 (setq spos (org-refile-get-location "Heading: ")
13842 exitcmd 'return
13843 spos (nth 3 spos))))
13844 (t (error "this should not hapen")))
13845 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13846 ; not handle this note
13847 (goto-char spos)
13848 (cond ((org-on-heading-p t)
13849 (org-back-to-heading t)
13850 (setq level (funcall outline-level))
13851 (cond
13852 ((eq exitcmd 'return)
13853 ;; sublevel of current
13854 (setq org-remember-previous-location
13855 (cons (abbreviate-file-name file)
13856 (org-get-heading 'notags)))
13857 (if reversed
13858 (outline-next-heading)
13859 (org-end-of-subtree t)
13860 (if (not (bolp))
13861 (if (looking-at "[ \t]*\n")
13862 (beginning-of-line 2)
13863 (end-of-line 1)
13864 (insert "\n"))))
13865 (bookmark-set "org-remember-last-stored")
13866 (org-paste-subtree (org-get-legal-level level 1) txt))
13867 ((eq exitcmd 'left)
13868 ;; before current
13869 (bookmark-set "org-remember-last-stored")
13870 (org-paste-subtree level txt))
13871 ((eq exitcmd 'right)
13872 ;; after current
13873 (org-end-of-subtree t)
13874 (bookmark-set "org-remember-last-stored")
13875 (org-paste-subtree level txt))
13876 (t (error "This should not happen"))))
13878 ((and (bobp) (not reversed))
13879 ;; Put it at the end, one level below level 1
13880 (save-restriction
13881 (widen)
13882 (goto-char (point-max))
13883 (if (not (bolp)) (newline))
13884 (bookmark-set "org-remember-last-stored")
13885 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13887 ((and (bobp) reversed)
13888 ;; Put it at the start, as level 1
13889 (save-restriction
13890 (widen)
13891 (goto-char (point-min))
13892 (re-search-forward "^\\*+ " nil t)
13893 (beginning-of-line 1)
13894 (bookmark-set "org-remember-last-stored")
13895 (org-paste-subtree 1 txt)))
13897 ;; Put it right there, with automatic level determined by
13898 ;; org-paste-subtree or from prefix arg
13899 (bookmark-set "org-remember-last-stored")
13900 (org-paste-subtree
13901 (if (numberp current-prefix-arg) current-prefix-arg)
13902 txt)))
13903 (when remember-save-after-remembering
13904 (save-buffer)
13905 (if (not visiting) (kill-buffer (current-buffer)))))))))
13907 t) ;; return t to indicate that we took care of this note.
13909 (defun org-get-org-file ()
13910 "Read a filename, with default directory `org-directory'."
13911 (let ((default (or org-default-notes-file remember-data-file)))
13912 (read-file-name (format "File name [%s]: " default)
13913 (file-name-as-directory org-directory)
13914 default)))
13916 (defun org-notes-order-reversed-p ()
13917 "Check if the current file should receive notes in reversed order."
13918 (cond
13919 ((not org-reverse-note-order) nil)
13920 ((eq t org-reverse-note-order) t)
13921 ((not (listp org-reverse-note-order)) nil)
13922 (t (catch 'exit
13923 (let ((all org-reverse-note-order)
13924 entry)
13925 (while (setq entry (pop all))
13926 (if (string-match (car entry) buffer-file-name)
13927 (throw 'exit (cdr entry))))
13928 nil)))))
13930 ;;; Refiling
13932 (defvar org-refile-target-table nil
13933 "The list of refile targets, created by `org-refile'.")
13935 (defvar org-agenda-new-buffers nil
13936 "Buffers created to visit agenda files.")
13938 (defun org-get-refile-targets (&optional default-buffer)
13939 "Produce a table with refile targets."
13940 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
13941 targets txt re files f desc descre)
13942 (with-current-buffer (or default-buffer (current-buffer))
13943 (while (setq entry (pop entries))
13944 (setq files (car entry) desc (cdr entry))
13945 (cond
13946 ((null files) (setq files (list (current-buffer))))
13947 ((eq files 'org-agenda-files)
13948 (setq files (org-agenda-files 'unrestricted)))
13949 ((and (symbolp files) (fboundp files))
13950 (setq files (funcall files)))
13951 ((and (symbolp files) (boundp files))
13952 (setq files (symbol-value files))))
13953 (if (stringp files) (setq files (list files)))
13954 (cond
13955 ((eq (car desc) :tag)
13956 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13957 ((eq (car desc) :todo)
13958 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13959 ((eq (car desc) :regexp)
13960 (setq descre (cdr desc)))
13961 ((eq (car desc) :level)
13962 (setq descre (concat "^\\*\\{" (number-to-string
13963 (if org-odd-levels-only
13964 (1- (* 2 (cdr desc)))
13965 (cdr desc)))
13966 "\\}[ \t]")))
13967 ((eq (car desc) :maxlevel)
13968 (setq descre (concat "^\\*\\{1," (number-to-string
13969 (if org-odd-levels-only
13970 (1- (* 2 (cdr desc)))
13971 (cdr desc)))
13972 "\\}[ \t]")))
13973 (t (error "Bad refiling target description %s" desc)))
13974 (while (setq f (pop files))
13975 (save-excursion
13976 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13977 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13978 (save-excursion
13979 (save-restriction
13980 (widen)
13981 (goto-char (point-min))
13982 (while (re-search-forward descre nil t)
13983 (goto-char (point-at-bol))
13984 (when (looking-at org-complex-heading-regexp)
13985 (setq txt (match-string 4)
13986 re (concat "^" (regexp-quote
13987 (buffer-substring (match-beginning 1)
13988 (match-end 4)))))
13989 (if (match-end 5) (setq re (concat re "[ \t]+"
13990 (regexp-quote
13991 (match-string 5)))))
13992 (setq re (concat re "[ \t]*$"))
13993 (when org-refile-use-outline-path
13994 (setq txt (mapconcat 'identity
13995 (append
13996 (if (eq org-refile-use-outline-path 'file)
13997 (list (file-name-nondirectory
13998 (buffer-file-name (buffer-base-buffer))))
13999 (if (eq org-refile-use-outline-path 'full-file-path)
14000 (list (buffer-file-name (buffer-base-buffer)))))
14001 (org-get-outline-path)
14002 (list txt))
14003 "/")))
14004 (push (list txt f re (point)) targets))
14005 (goto-char (point-at-eol))))))))
14006 (nreverse targets))))
14008 (defun org-get-outline-path ()
14009 "Return the outline path to the current entry, as a list."
14010 (let (rtn)
14011 (save-excursion
14012 (while (org-up-heading-safe)
14013 (when (looking-at org-complex-heading-regexp)
14014 (push (org-match-string-no-properties 4) rtn)))
14015 rtn)))
14017 (defvar org-refile-history nil
14018 "History for refiling operations.")
14020 (defun org-refile (&optional goto default-buffer)
14021 "Move the entry at point to another heading.
14022 The list of target headings is compiled using the information in
14023 `org-refile-targets', which see. This list is created upon first use, and
14024 you can update it by calling this command with a double prefix (`C-u C-u').
14025 FIXME: Can we find a better way of updating?
14027 At the target location, the entry is filed as a subitem of the target heading.
14028 Depending on `org-reverse-note-order', the new subitem will either be the
14029 first of the last subitem.
14031 With prefix arg GOTO, the command will only visit the target location,
14032 not actually move anything.
14033 With a double prefix `C-c C-c', go to the location where the last refiling
14034 operation has put the subtree.
14036 With a double prefix argument, the command can be used to jump to any
14037 heading in the current buffer."
14038 (interactive "P")
14039 (let* ((cbuf (current-buffer))
14040 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14041 (fname (and filename (file-truename filename)))
14042 pos it nbuf file re level reversed)
14043 (if (equal goto '(16))
14044 (org-refile-goto-last-stored)
14045 (when (setq it (org-refile-get-location
14046 (if goto "Goto: " "Refile to: ") default-buffer))
14047 (setq file (nth 1 it)
14048 re (nth 2 it)
14049 pos (nth 3 it))
14050 (setq nbuf (or (find-buffer-visiting file)
14051 (find-file-noselect file)))
14052 (if goto
14053 (progn
14054 (switch-to-buffer nbuf)
14055 (goto-char pos)
14056 (org-show-context 'org-goto))
14057 (org-copy-special)
14058 (save-excursion
14059 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14060 (find-file-noselect file))))
14061 (setq reversed (org-notes-order-reversed-p))
14062 (save-excursion
14063 (save-restriction
14064 (widen)
14065 (goto-char pos)
14066 (looking-at outline-regexp)
14067 (setq level (org-get-legal-level (funcall outline-level) 1))
14068 (goto-char (or (save-excursion
14069 (if reversed
14070 (outline-next-heading)
14071 (outline-get-next-sibling)))
14072 (point-max)))
14073 (bookmark-set "org-refile-last-stored")
14074 (org-paste-subtree level))))
14075 (org-cut-special)
14076 (message "Entry refiled to \"%s\"" (car it)))))))
14078 (defun org-refile-goto-last-stored ()
14079 "Go to the location where the last refile was stored."
14080 (interactive)
14081 (bookmark-jump "org-refile-last-stored")
14082 (message "This is the location of the last refile"))
14084 (defun org-refile-get-location (&optional prompt default-buffer)
14085 "Prompt the user for a refile location, using PROMPT."
14086 (let ((org-refile-targets org-refile-targets)
14087 (org-refile-use-outline-path org-refile-use-outline-path))
14088 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14089 (unless org-refile-target-table
14090 (error "No refile targets"))
14091 (let* ((cbuf (current-buffer))
14092 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14093 (fname (and filename (file-truename filename)))
14094 (tbl (mapcar
14095 (lambda (x)
14096 (if (not (equal fname (file-truename (nth 1 x))))
14097 (cons (concat (car x) " (" (file-name-nondirectory
14098 (nth 1 x)) ")")
14099 (cdr x))
14101 org-refile-target-table))
14102 (completion-ignore-case t)
14103 pos it nbuf file re level reversed)
14104 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14105 tbl)))
14107 ;;;; Dynamic blocks
14109 (defun org-find-dblock (name)
14110 "Find the first dynamic block with name NAME in the buffer.
14111 If not found, stay at current position and return nil."
14112 (let (pos)
14113 (save-excursion
14114 (goto-char (point-min))
14115 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14116 nil t)
14117 (match-beginning 0))))
14118 (if pos (goto-char pos))
14119 pos))
14121 (defconst org-dblock-start-re
14122 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14123 "Matches the startline of a dynamic block, with parameters.")
14125 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14126 "Matches the end of a dyhamic block.")
14128 (defun org-create-dblock (plist)
14129 "Create a dynamic block section, with parameters taken from PLIST.
14130 PLIST must containe a :name entry which is used as name of the block."
14131 (unless (bolp) (newline))
14132 (let ((name (plist-get plist :name)))
14133 (insert "#+BEGIN: " name)
14134 (while plist
14135 (if (eq (car plist) :name)
14136 (setq plist (cddr plist))
14137 (insert " " (prin1-to-string (pop plist)))))
14138 (insert "\n\n#+END:\n")
14139 (beginning-of-line -2)))
14141 (defun org-prepare-dblock ()
14142 "Prepare dynamic block for refresh.
14143 This empties the block, puts the cursor at the insert position and returns
14144 the property list including an extra property :name with the block name."
14145 (unless (looking-at org-dblock-start-re)
14146 (error "Not at a dynamic block"))
14147 (let* ((begdel (1+ (match-end 0)))
14148 (name (org-no-properties (match-string 1)))
14149 (params (append (list :name name)
14150 (read (concat "(" (match-string 3) ")")))))
14151 (unless (re-search-forward org-dblock-end-re nil t)
14152 (error "Dynamic block not terminated"))
14153 (delete-region begdel (match-beginning 0))
14154 (goto-char begdel)
14155 (open-line 1)
14156 params))
14158 (defun org-map-dblocks (&optional command)
14159 "Apply COMMAND to all dynamic blocks in the current buffer.
14160 If COMMAND is not given, use `org-update-dblock'."
14161 (let ((cmd (or command 'org-update-dblock))
14162 pos)
14163 (save-excursion
14164 (goto-char (point-min))
14165 (while (re-search-forward org-dblock-start-re nil t)
14166 (goto-char (setq pos (match-beginning 0)))
14167 (condition-case nil
14168 (funcall cmd)
14169 (error (message "Error during update of dynamic block")))
14170 (goto-char pos)
14171 (unless (re-search-forward org-dblock-end-re nil t)
14172 (error "Dynamic block not terminated"))))))
14174 (defun org-dblock-update (&optional arg)
14175 "User command for updating dynamic blocks.
14176 Update the dynamic block at point. With prefix ARG, update all dynamic
14177 blocks in the buffer."
14178 (interactive "P")
14179 (if arg
14180 (org-update-all-dblocks)
14181 (or (looking-at org-dblock-start-re)
14182 (org-beginning-of-dblock))
14183 (org-update-dblock)))
14185 (defun org-update-dblock ()
14186 "Update the dynamic block at point
14187 This means to empty the block, parse for parameters and then call
14188 the correct writing function."
14189 (save-window-excursion
14190 (let* ((pos (point))
14191 (line (org-current-line))
14192 (params (org-prepare-dblock))
14193 (name (plist-get params :name))
14194 (cmd (intern (concat "org-dblock-write:" name))))
14195 (message "Updating dynamic block `%s' at line %d..." name line)
14196 (funcall cmd params)
14197 (message "Updating dynamic block `%s' at line %d...done" name line)
14198 (goto-char pos))))
14200 (defun org-beginning-of-dblock ()
14201 "Find the beginning of the dynamic block at point.
14202 Error if there is no scuh block at point."
14203 (let ((pos (point))
14204 beg)
14205 (end-of-line 1)
14206 (if (and (re-search-backward org-dblock-start-re nil t)
14207 (setq beg (match-beginning 0))
14208 (re-search-forward org-dblock-end-re nil t)
14209 (> (match-end 0) pos))
14210 (goto-char beg)
14211 (goto-char pos)
14212 (error "Not in a dynamic block"))))
14214 (defun org-update-all-dblocks ()
14215 "Update all dynamic blocks in the buffer.
14216 This function can be used in a hook."
14217 (when (org-mode-p)
14218 (org-map-dblocks 'org-update-dblock)))
14221 ;;;; Completion
14223 (defconst org-additional-option-like-keywords
14224 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14225 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14226 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14228 (defun org-complete (&optional arg)
14229 "Perform completion on word at point.
14230 At the beginning of a headline, this completes TODO keywords as given in
14231 `org-todo-keywords'.
14232 If the current word is preceded by a backslash, completes the TeX symbols
14233 that are supported for HTML support.
14234 If the current word is preceded by \"#+\", completes special words for
14235 setting file options.
14236 In the line after \"#+STARTUP:, complete valid keywords.\"
14237 At all other locations, this simply calls the value of
14238 `org-completion-fallback-command'."
14239 (interactive "P")
14240 (org-without-partial-completion
14241 (catch 'exit
14242 (let* ((end (point))
14243 (beg1 (save-excursion
14244 (skip-chars-backward (org-re "[:alnum:]_@"))
14245 (point)))
14246 (beg (save-excursion
14247 (skip-chars-backward "a-zA-Z0-9_:$")
14248 (point)))
14249 (confirm (lambda (x) (stringp (car x))))
14250 (searchhead (equal (char-before beg) ?*))
14251 (tag (and (equal (char-before beg1) ?:)
14252 (equal (char-after (point-at-bol)) ?*)))
14253 (prop (and (equal (char-before beg1) ?:)
14254 (not (equal (char-after (point-at-bol)) ?*))))
14255 (texp (equal (char-before beg) ?\\))
14256 (link (equal (char-before beg) ?\[))
14257 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14258 beg)
14259 "#+"))
14260 (startup (string-match "^#\\+STARTUP:.*"
14261 (buffer-substring (point-at-bol) (point))))
14262 (completion-ignore-case opt)
14263 (type nil)
14264 (tbl nil)
14265 (table (cond
14266 (opt
14267 (setq type :opt)
14268 (append
14269 (mapcar
14270 (lambda (x)
14271 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14272 (cons (match-string 2 x) (match-string 1 x)))
14273 (org-split-string (org-get-current-options) "\n"))
14274 (mapcar 'list org-additional-option-like-keywords)))
14275 (startup
14276 (setq type :startup)
14277 org-startup-options)
14278 (link (append org-link-abbrev-alist-local
14279 org-link-abbrev-alist))
14280 (texp
14281 (setq type :tex)
14282 org-html-entities)
14283 ((string-match "\\`\\*+[ \t]+\\'"
14284 (buffer-substring (point-at-bol) beg))
14285 (setq type :todo)
14286 (mapcar 'list org-todo-keywords-1))
14287 (searchhead
14288 (setq type :searchhead)
14289 (save-excursion
14290 (goto-char (point-min))
14291 (while (re-search-forward org-todo-line-regexp nil t)
14292 (push (list
14293 (org-make-org-heading-search-string
14294 (match-string 3) t))
14295 tbl)))
14296 tbl)
14297 (tag (setq type :tag beg beg1)
14298 (or org-tag-alist (org-get-buffer-tags)))
14299 (prop (setq type :prop beg beg1)
14300 (mapcar 'list (org-buffer-property-keys)))
14301 (t (progn
14302 (call-interactively org-completion-fallback-command)
14303 (throw 'exit nil)))))
14304 (pattern (buffer-substring-no-properties beg end))
14305 (completion (try-completion pattern table confirm)))
14306 (cond ((eq completion t)
14307 (if (not (assoc (upcase pattern) table))
14308 (message "Already complete")
14309 (if (equal type :opt)
14310 (insert (substring (cdr (assoc (upcase pattern) table))
14311 (length pattern)))
14312 (if (memq type '(:tag :prop)) (insert ":")))))
14313 ((null completion)
14314 (message "Can't find completion for \"%s\"" pattern)
14315 (ding))
14316 ((not (string= pattern completion))
14317 (delete-region beg end)
14318 (if (string-match " +$" completion)
14319 (setq completion (replace-match "" t t completion)))
14320 (insert completion)
14321 (if (get-buffer-window "*Completions*")
14322 (delete-window (get-buffer-window "*Completions*")))
14323 (if (assoc completion table)
14324 (if (eq type :todo) (insert " ")
14325 (if (memq type '(:tag :prop)) (insert ":"))))
14326 (if (and (equal type :opt) (assoc completion table))
14327 (message "%s" (substitute-command-keys
14328 "Press \\[org-complete] again to insert example settings"))))
14330 (message "Making completion list...")
14331 (let ((list (sort (all-completions pattern table confirm)
14332 'string<)))
14333 (with-output-to-temp-buffer "*Completions*"
14334 (condition-case nil
14335 ;; Protection needed for XEmacs and emacs 21
14336 (display-completion-list list pattern)
14337 (error (display-completion-list list)))))
14338 (message "Making completion list...%s" "done")))))))
14340 ;;;; TODO, DEADLINE, Comments
14342 (defun org-toggle-comment ()
14343 "Change the COMMENT state of an entry."
14344 (interactive)
14345 (save-excursion
14346 (org-back-to-heading)
14347 (let (case-fold-search)
14348 (if (looking-at (concat outline-regexp
14349 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14350 (replace-match "" t t nil 1)
14351 (if (looking-at outline-regexp)
14352 (progn
14353 (goto-char (match-end 0))
14354 (insert org-comment-string " ")))))))
14356 (defvar org-last-todo-state-is-todo nil
14357 "This is non-nil when the last TODO state change led to a TODO state.
14358 If the last change removed the TODO tag or switched to DONE, then
14359 this is nil.")
14361 (defvar org-setting-tags nil) ; dynamically skiped
14363 ;; FIXME: better place
14364 (defun org-property-or-variable-value (var &optional inherit)
14365 "Check if there is a property fixing the value of VAR.
14366 If yes, return this value. If not, return the current value of the variable."
14367 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14368 (if (and prop (stringp prop) (string-match "\\S-" prop))
14369 (read prop)
14370 (symbol-value var))))
14372 (defun org-parse-local-options (string var)
14373 "Parse STRING for startup setting relevant for variable VAR."
14374 (let ((rtn (symbol-value var))
14375 e opts)
14376 (save-match-data
14377 (if (or (not string) (not (string-match "\\S-" string)))
14379 (setq opts (delq nil (mapcar (lambda (x)
14380 (setq e (assoc x org-startup-options))
14381 (if (eq (nth 1 e) var) e nil))
14382 (org-split-string string "[ \t]+"))))
14383 (if (not opts)
14385 (setq rtn nil)
14386 (while (setq e (pop opts))
14387 (if (not (nth 3 e))
14388 (setq rtn (nth 2 e))
14389 (if (not (listp rtn)) (setq rtn nil))
14390 (push (nth 2 e) rtn)))
14391 rtn)))))
14393 (defvar org-blocker-hook nil
14394 "Hook for functions that are allowed to block a state change.
14396 Each function gets as its single argument a property list, see
14397 `org-trigger-hook' for more information about this list.
14399 If any of the functions in this hook returns nil, the state change
14400 is blocked.")
14402 (defvar org-trigger-hook nil
14403 "Hook for functions that are triggered by a state change.
14405 Each function gets as its single argument a property list with at least
14406 the following elements:
14408 (:type type-of-change :position pos-at-entry-start
14409 :from old-state :to new-state)
14411 Depending on the type, more properties may be present.
14413 This mechanism is currently implemented for:
14415 TODO state changes
14416 ------------------
14417 :type todo-state-change
14418 :from previous state (keyword as a string), or nil
14419 :to new state (keyword as a string), or nil")
14422 (defun org-todo (&optional arg)
14423 "Change the TODO state of an item.
14424 The state of an item is given by a keyword at the start of the heading,
14425 like
14426 *** TODO Write paper
14427 *** DONE Call mom
14429 The different keywords are specified in the variable `org-todo-keywords'.
14430 By default the available states are \"TODO\" and \"DONE\".
14431 So for this example: when the item starts with TODO, it is changed to DONE.
14432 When it starts with DONE, the DONE is removed. And when neither TODO nor
14433 DONE are present, add TODO at the beginning of the heading.
14435 With C-u prefix arg, use completion to determine the new state.
14436 With numeric prefix arg, switch to that state.
14438 For calling through lisp, arg is also interpreted in the following way:
14439 'none -> empty state
14440 \"\"(empty string) -> switch to empty state
14441 'done -> switch to DONE
14442 'nextset -> switch to the next set of keywords
14443 'previousset -> switch to the previous set of keywords
14444 \"WAITING\" -> switch to the specified keyword, but only if it
14445 really is a member of `org-todo-keywords'."
14446 (interactive "P")
14447 (save-excursion
14448 (catch 'exit
14449 (org-back-to-heading)
14450 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14451 (or (looking-at (concat " +" org-todo-regexp " *"))
14452 (looking-at " *"))
14453 (let* ((match-data (match-data))
14454 (startpos (point-at-bol))
14455 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14456 (org-log-done (org-parse-local-options logging 'org-log-done))
14457 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
14458 (this (match-string 1))
14459 (hl-pos (match-beginning 0))
14460 (head (org-get-todo-sequence-head this))
14461 (ass (assoc head org-todo-kwd-alist))
14462 (interpret (nth 1 ass))
14463 (done-word (nth 3 ass))
14464 (final-done-word (nth 4 ass))
14465 (last-state (or this ""))
14466 (completion-ignore-case t)
14467 (member (member this org-todo-keywords-1))
14468 (tail (cdr member))
14469 (state (cond
14470 ((and org-todo-key-trigger
14471 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14472 (and (not arg) org-use-fast-todo-selection
14473 (not (eq org-use-fast-todo-selection 'prefix)))))
14474 ;; Use fast selection
14475 (org-fast-todo-selection))
14476 ((and (equal arg '(4))
14477 (or (not org-use-fast-todo-selection)
14478 (not org-todo-key-trigger)))
14479 ;; Read a state with completion
14480 (completing-read "State: " (mapcar (lambda(x) (list x))
14481 org-todo-keywords-1)
14482 nil t))
14483 ((eq arg 'right)
14484 (if this
14485 (if tail (car tail) nil)
14486 (car org-todo-keywords-1)))
14487 ((eq arg 'left)
14488 (if (equal member org-todo-keywords-1)
14490 (if this
14491 (nth (- (length org-todo-keywords-1) (length tail) 2)
14492 org-todo-keywords-1)
14493 (org-last org-todo-keywords-1))))
14494 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14495 (setq arg nil))) ; hack to fall back to cycling
14496 (arg
14497 ;; user or caller requests a specific state
14498 (cond
14499 ((equal arg "") nil)
14500 ((eq arg 'none) nil)
14501 ((eq arg 'done) (or done-word (car org-done-keywords)))
14502 ((eq arg 'nextset)
14503 (or (car (cdr (member head org-todo-heads)))
14504 (car org-todo-heads)))
14505 ((eq arg 'previousset)
14506 (let ((org-todo-heads (reverse org-todo-heads)))
14507 (or (car (cdr (member head org-todo-heads)))
14508 (car org-todo-heads))))
14509 ((car (member arg org-todo-keywords-1)))
14510 ((nth (1- (prefix-numeric-value arg))
14511 org-todo-keywords-1))))
14512 ((null member) (or head (car org-todo-keywords-1)))
14513 ((equal this final-done-word) nil) ;; -> make empty
14514 ((null tail) nil) ;; -> first entry
14515 ((eq interpret 'sequence)
14516 (car tail))
14517 ((memq interpret '(type priority))
14518 (if (eq this-command last-command)
14519 (car tail)
14520 (if (> (length tail) 0)
14521 (or done-word (car org-done-keywords))
14522 nil)))
14523 (t nil)))
14524 (next (if state (concat " " state " ") " "))
14525 (change-plist (list :type 'todo-state-change :from this :to state
14526 :position startpos))
14527 dostates)
14528 (when org-blocker-hook
14529 (unless (save-excursion
14530 (save-match-data
14531 (run-hook-with-args-until-failure
14532 'org-blocker-hook change-plist)))
14533 (if (interactive-p)
14534 (error "TODO state change from %s to %s blocked" this state)
14535 ;; fail silently
14536 (message "TODO state change from %s to %s blocked" this state)
14537 (throw 'exit nil))))
14538 (store-match-data match-data)
14539 (replace-match next t t)
14540 (unless (pos-visible-in-window-p hl-pos)
14541 (message "TODO state changed to %s" (org-trim next)))
14542 (unless head
14543 (setq head (org-get-todo-sequence-head state)
14544 ass (assoc head org-todo-kwd-alist)
14545 interpret (nth 1 ass)
14546 done-word (nth 3 ass)
14547 final-done-word (nth 4 ass)))
14548 (when (memq arg '(nextset previousset))
14549 (message "Keyword-Set %d/%d: %s"
14550 (- (length org-todo-sets) -1
14551 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14552 (length org-todo-sets)
14553 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14554 (setq org-last-todo-state-is-todo
14555 (not (member state org-done-keywords)))
14556 (when (and org-log-done (not (memq arg '(nextset previousset))))
14557 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
14558 (or (not org-todo-log-states)
14559 (member state org-todo-log-states))))
14561 (cond
14562 ((and state (member state org-not-done-keywords)
14563 (not (member this org-not-done-keywords)))
14564 ;; This is now a todo state and was not one before
14565 ;; Remove any CLOSED timestamp, and possibly log the state change
14566 (org-add-planning-info nil nil 'closed)
14567 (and dostates (org-add-log-maybe 'state state 'findpos)))
14568 ((and state dostates)
14569 ;; This is a non-nil state, and we need to log it
14570 (org-add-log-maybe 'state state 'findpos))
14571 ((and (member state org-done-keywords)
14572 (not (member this org-done-keywords)))
14573 ;; It is now done, and it was not done before
14574 (org-add-planning-info 'closed (org-current-time))
14575 (org-add-log-maybe 'done state 'findpos))))
14576 ;; Fixup tag positioning
14577 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14578 (run-hooks 'org-after-todo-state-change-hook)
14579 (and (member state org-done-keywords) (org-auto-repeat-maybe))
14580 (if (and arg (not (member state org-done-keywords)))
14581 (setq head (org-get-todo-sequence-head state)))
14582 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14583 ;; Fixup cursor location if close to the keyword
14584 (if (and (outline-on-heading-p)
14585 (not (bolp))
14586 (save-excursion (beginning-of-line 1)
14587 (looking-at org-todo-line-regexp))
14588 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14589 (progn
14590 (goto-char (or (match-end 2) (match-end 1)))
14591 (just-one-space)))
14592 (when org-trigger-hook
14593 (save-excursion
14594 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14596 (defun org-get-todo-sequence-head (kwd)
14597 "Return the head of the TODO sequence to which KWD belongs.
14598 If KWD is not set, check if there is a text property remembering the
14599 right sequence."
14600 (let (p)
14601 (cond
14602 ((not kwd)
14603 (or (get-text-property (point-at-bol) 'org-todo-head)
14604 (progn
14605 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14606 nil (point-at-eol)))
14607 (get-text-property p 'org-todo-head))))
14608 ((not (member kwd org-todo-keywords-1))
14609 (car org-todo-keywords-1))
14610 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14612 (defun org-fast-todo-selection ()
14613 "Fast TODO keyword selection with single keys.
14614 Returns the new TODO keyword, or nil if no state change should occur."
14615 (let* ((fulltable org-todo-key-alist)
14616 (done-keywords org-done-keywords) ;; needed for the faces.
14617 (maxlen (apply 'max (mapcar
14618 (lambda (x)
14619 (if (stringp (car x)) (string-width (car x)) 0))
14620 fulltable)))
14621 (expert nil)
14622 (fwidth (+ maxlen 3 1 3))
14623 (ncol (/ (- (window-width) 4) fwidth))
14624 tg cnt e c tbl
14625 groups ingroup)
14626 (save-window-excursion
14627 (if expert
14628 (set-buffer (get-buffer-create " *Org todo*"))
14629 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14630 (erase-buffer)
14631 (org-set-local 'org-done-keywords done-keywords)
14632 (setq tbl fulltable cnt 0)
14633 (while (setq e (pop tbl))
14634 (cond
14635 ((equal e '(:startgroup))
14636 (push '() groups) (setq ingroup t)
14637 (when (not (= cnt 0))
14638 (setq cnt 0)
14639 (insert "\n"))
14640 (insert "{ "))
14641 ((equal e '(:endgroup))
14642 (setq ingroup nil cnt 0)
14643 (insert "}\n"))
14645 (setq tg (car e) c (cdr e))
14646 (if ingroup (push tg (car groups)))
14647 (setq tg (org-add-props tg nil 'face
14648 (org-get-todo-face tg)))
14649 (if (and (= cnt 0) (not ingroup)) (insert " "))
14650 (insert "[" c "] " tg (make-string
14651 (- fwidth 4 (length tg)) ?\ ))
14652 (when (= (setq cnt (1+ cnt)) ncol)
14653 (insert "\n")
14654 (if ingroup (insert " "))
14655 (setq cnt 0)))))
14656 (insert "\n")
14657 (goto-char (point-min))
14658 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14659 (fit-window-to-buffer))
14660 (message "[a-z..]:Set [SPC]:clear")
14661 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14662 (cond
14663 ((or (= c ?\C-g)
14664 (and (= c ?q) (not (rassoc c fulltable))))
14665 (setq quit-flag t))
14666 ((= c ?\ ) nil)
14667 ((setq e (rassoc c fulltable) tg (car e))
14669 (t (setq quit-flag t))))))
14671 (defun org-get-repeat ()
14672 "Check if tere is a deadline/schedule with repeater in this entry."
14673 (save-match-data
14674 (save-excursion
14675 (org-back-to-heading t)
14676 (if (re-search-forward
14677 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14678 (match-string 1)))))
14680 (defvar org-last-changed-timestamp)
14681 (defvar org-log-post-message)
14682 (defun org-auto-repeat-maybe ()
14683 "Check if the current headline contains a repeated deadline/schedule.
14684 If yes, set TODO state back to what it was and change the base date
14685 of repeating deadline/scheduled time stamps to new date.
14686 This function should be run in the `org-after-todo-state-change-hook'."
14687 ;; last-state is dynamically scoped into this function
14688 (let* ((repeat (org-get-repeat))
14689 (aa (assoc last-state org-todo-kwd-alist))
14690 (interpret (nth 1 aa))
14691 (head (nth 2 aa))
14692 (done-word (nth 3 aa))
14693 (whata '(("d" . day) ("m" . month) ("y" . year)))
14694 (msg "Entry repeats: ")
14695 (org-log-done)
14696 re type n what ts)
14697 (when repeat
14698 (org-todo (if (eq interpret 'type) last-state head))
14699 (when (and org-log-repeat
14700 (not (memq 'org-add-log-note
14701 (default-value 'post-command-hook))))
14702 ;; Make sure a note is taken
14703 (let ((org-log-done '(done)))
14704 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
14705 'findpos)))
14706 (org-back-to-heading t)
14707 (org-add-planning-info nil nil 'closed)
14708 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14709 org-deadline-time-regexp "\\)\\|\\("
14710 org-ts-regexp "\\)"))
14711 (while (re-search-forward
14712 re (save-excursion (outline-next-heading) (point)) t)
14713 (setq type (if (match-end 1) org-scheduled-string
14714 (if (match-end 3) org-deadline-string "Plain:"))
14715 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14716 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14717 (setq n (string-to-number (match-string 1 ts))
14718 what (match-string 2 ts))
14719 (if (equal what "w") (setq n (* n 7) what "d"))
14720 (org-timestamp-change n (cdr (assoc what whata)))
14721 (setq msg (concat msg type org-last-changed-timestamp " "))))
14722 (setq org-log-post-message msg)
14723 (message "%s" msg))))
14725 (defun org-show-todo-tree (arg)
14726 "Make a compact tree which shows all headlines marked with TODO.
14727 The tree will show the lines where the regexp matches, and all higher
14728 headlines above the match.
14729 With \\[universal-argument] prefix, also show the DONE entries.
14730 With a numeric prefix N, construct a sparse tree for the Nth element
14731 of `org-todo-keywords-1'."
14732 (interactive "P")
14733 (let ((case-fold-search nil)
14734 (kwd-re
14735 (cond ((null arg) org-not-done-regexp)
14736 ((equal arg '(4))
14737 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14738 (mapcar 'list org-todo-keywords-1))))
14739 (concat "\\("
14740 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14741 "\\)\\>")))
14742 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14743 (regexp-quote (nth (1- (prefix-numeric-value arg))
14744 org-todo-keywords-1)))
14745 (t (error "Invalid prefix argument: %s" arg)))))
14746 (message "%d TODO entries found"
14747 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14749 (defun org-deadline (&optional remove)
14750 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14751 With argument REMOVE, remove any deadline from the item."
14752 (interactive "P")
14753 (if remove
14754 (progn
14755 (org-remove-timestamp-with-keyword org-deadline-string)
14756 (message "Item no longer has a deadline."))
14757 (org-add-planning-info 'deadline nil 'closed)))
14759 (defun org-schedule (&optional remove)
14760 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14761 With argument REMOVE, remove any scheduling date from the item."
14762 (interactive "P")
14763 (if remove
14764 (progn
14765 (org-remove-timestamp-with-keyword org-scheduled-string)
14766 (message "Item is no longer scheduled."))
14767 (org-add-planning-info 'scheduled nil 'closed)))
14769 (defun org-remove-timestamp-with-keyword (keyword)
14770 "Remove all time stamps with KEYWORD in the current entry."
14771 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14772 beg)
14773 (save-excursion
14774 (org-back-to-heading t)
14775 (setq beg (point))
14776 (org-end-of-subtree t t)
14777 (while (re-search-backward re beg t)
14778 (replace-match "")
14779 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14780 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14782 (defun org-add-planning-info (what &optional time &rest remove)
14783 "Insert new timestamp with keyword in the line directly after the headline.
14784 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14785 If non is given, the user is prompted for a date.
14786 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14787 be removed."
14788 (interactive)
14789 (let (org-time-was-given org-end-time-was-given)
14790 (when what (setq time (or time (org-read-date nil 'to-time))))
14791 (when (and org-insert-labeled-timestamps-at-point
14792 (member what '(scheduled deadline)))
14793 (insert
14794 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14795 (org-insert-time-stamp time org-time-was-given
14796 nil nil nil (list org-end-time-was-given))
14797 (setq what nil))
14798 (save-excursion
14799 (save-restriction
14800 (let (col list elt ts buffer-invisibility-spec)
14801 (org-back-to-heading t)
14802 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14803 (goto-char (match-end 1))
14804 (setq col (current-column))
14805 (goto-char (match-end 0))
14806 (if (eobp) (insert "\n") (forward-char 1))
14807 (if (and (not (looking-at outline-regexp))
14808 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14809 "[^\r\n]*"))
14810 (not (equal (match-string 1) org-clock-string)))
14811 (narrow-to-region (match-beginning 0) (match-end 0))
14812 (insert-before-markers "\n")
14813 (backward-char 1)
14814 (narrow-to-region (point) (point))
14815 (indent-to-column col))
14816 ;; Check if we have to remove something.
14817 (setq list (cons what remove))
14818 (while list
14819 (setq elt (pop list))
14820 (goto-char (point-min))
14821 (when (or (and (eq elt 'scheduled)
14822 (re-search-forward org-scheduled-time-regexp nil t))
14823 (and (eq elt 'deadline)
14824 (re-search-forward org-deadline-time-regexp nil t))
14825 (and (eq elt 'closed)
14826 (re-search-forward org-closed-time-regexp nil t)))
14827 (replace-match "")
14828 (if (looking-at "--+<[^>]+>") (replace-match ""))
14829 (if (looking-at " +") (replace-match ""))))
14830 (goto-char (point-max))
14831 (when what
14832 (insert
14833 (if (not (equal (char-before) ?\ )) " " "")
14834 (cond ((eq what 'scheduled) org-scheduled-string)
14835 ((eq what 'deadline) org-deadline-string)
14836 ((eq what 'closed) org-closed-string))
14837 " ")
14838 (setq ts (org-insert-time-stamp
14839 time
14840 (or org-time-was-given
14841 (and (eq what 'closed) org-log-done-with-time))
14842 (eq what 'closed)
14843 nil nil (list org-end-time-was-given)))
14844 (end-of-line 1))
14845 (goto-char (point-min))
14846 (widen)
14847 (if (looking-at "[ \t]+\r?\n")
14848 (replace-match ""))
14849 ts)))))
14851 (defvar org-log-note-marker (make-marker))
14852 (defvar org-log-note-purpose nil)
14853 (defvar org-log-note-state nil)
14854 (defvar org-log-note-window-configuration nil)
14855 (defvar org-log-note-return-to (make-marker))
14856 (defvar org-log-post-message nil
14857 "Message to be displayed after a log note has been stored.
14858 The auto-repeater uses this.")
14860 (defun org-add-log-maybe (&optional purpose state findpos)
14861 "Set up the post command hook to take a note."
14862 (save-excursion
14863 (when (and (listp org-log-done)
14864 (memq purpose org-log-done))
14865 (when findpos
14866 (org-back-to-heading t)
14867 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14868 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14869 "[^\r\n]*\\)?"))
14870 (goto-char (match-end 0))
14871 (unless org-log-states-order-reversed
14872 (and (= (char-after) ?\n) (forward-char 1))
14873 (org-skip-over-state-notes)
14874 (skip-chars-backward " \t\n\r")))
14875 (move-marker org-log-note-marker (point))
14876 (setq org-log-note-purpose purpose)
14877 (setq org-log-note-state state)
14878 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14880 (defun org-skip-over-state-notes ()
14881 "Skip past the list of State notes in an entry."
14882 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14883 (while (looking-at "[ \t]*- State")
14884 (condition-case nil
14885 (org-next-item)
14886 (error (org-end-of-item)))))
14888 (defun org-add-log-note (&optional purpose)
14889 "Pop up a window for taking a note, and add this note later at point."
14890 (remove-hook 'post-command-hook 'org-add-log-note)
14891 (setq org-log-note-window-configuration (current-window-configuration))
14892 (delete-other-windows)
14893 (move-marker org-log-note-return-to (point))
14894 (switch-to-buffer (marker-buffer org-log-note-marker))
14895 (goto-char org-log-note-marker)
14896 (org-switch-to-buffer-other-window "*Org Note*")
14897 (erase-buffer)
14898 (let ((org-inhibit-startup t)) (org-mode))
14899 (insert (format "# Insert note for %s.
14900 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14901 (cond
14902 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14903 ((eq org-log-note-purpose 'done) "closed todo item")
14904 ((eq org-log-note-purpose 'state)
14905 (format "state change to \"%s\"" org-log-note-state))
14906 (t (error "This should not happen")))))
14907 (org-set-local 'org-finish-function 'org-store-log-note))
14909 (defun org-store-log-note ()
14910 "Finish taking a log note, and insert it to where it belongs."
14911 (let ((txt (buffer-string))
14912 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14913 lines ind)
14914 (kill-buffer (current-buffer))
14915 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14916 (setq txt (replace-match "" t t txt)))
14917 (if (string-match "\\s-+\\'" txt)
14918 (setq txt (replace-match "" t t txt)))
14919 (setq lines (org-split-string txt "\n"))
14920 (when (and note (string-match "\\S-" note))
14921 (setq note
14922 (org-replace-escapes
14923 note
14924 (list (cons "%u" (user-login-name))
14925 (cons "%U" user-full-name)
14926 (cons "%t" (format-time-string
14927 (org-time-stamp-format 'long 'inactive)
14928 (current-time)))
14929 (cons "%s" (if org-log-note-state
14930 (concat "\"" org-log-note-state "\"")
14931 "")))))
14932 (if lines (setq note (concat note " \\\\")))
14933 (push note lines))
14934 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14935 (when lines
14936 (save-excursion
14937 (set-buffer (marker-buffer org-log-note-marker))
14938 (save-excursion
14939 (goto-char org-log-note-marker)
14940 (move-marker org-log-note-marker nil)
14941 (end-of-line 1)
14942 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14943 (indent-relative nil)
14944 (insert "- " (pop lines))
14945 (org-indent-line-function)
14946 (beginning-of-line 1)
14947 (looking-at "[ \t]*")
14948 (setq ind (concat (match-string 0) " "))
14949 (end-of-line 1)
14950 (while lines (insert "\n" ind (pop lines)))))))
14951 (set-window-configuration org-log-note-window-configuration)
14952 (with-current-buffer (marker-buffer org-log-note-return-to)
14953 (goto-char org-log-note-return-to))
14954 (move-marker org-log-note-return-to nil)
14955 (and org-log-post-message (message "%s" org-log-post-message)))
14957 ;; FIXME: what else would be useful?
14958 ;; - priority
14959 ;; - date
14961 (defun org-sparse-tree (&optional arg)
14962 "Create a sparse tree, prompt for the details.
14963 This command can create sparse trees. You first need to select the type
14964 of match used to create the tree:
14966 t Show entries with a specific TODO keyword.
14967 T Show entries selected by a tags match.
14968 p Enter a property name and its value (both with completion on existing
14969 names/values) and show entries with that property.
14970 r Show entries matching a regular expression
14971 d Show deadlines due within `org-deadline-warning-days'."
14972 (interactive "P")
14973 (let (ans kwd value)
14974 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
14975 (setq ans (read-char-exclusive))
14976 (cond
14977 ((equal ans ?d)
14978 (call-interactively 'org-check-deadlines))
14979 ((equal ans ?b)
14980 (call-interactively 'org-check-before-date))
14981 ((equal ans ?t)
14982 (org-show-todo-tree '(4)))
14983 ((equal ans ?T)
14984 (call-interactively 'org-tags-sparse-tree))
14985 ((member ans '(?p ?P))
14986 (setq kwd (completing-read "Property: "
14987 (mapcar 'list (org-buffer-property-keys))))
14988 (setq value (completing-read "Value: "
14989 (mapcar 'list (org-property-values kwd))))
14990 (unless (string-match "\\`{.*}\\'" value)
14991 (setq value (concat "\"" value "\"")))
14992 (org-tags-sparse-tree arg (concat kwd "=" value)))
14993 ((member ans '(?r ?R ?/))
14994 (call-interactively 'org-occur))
14995 (t (error "No such sparse tree command \"%c\"" ans)))))
14997 (defvar org-occur-highlights nil)
14998 (make-variable-buffer-local 'org-occur-highlights)
15000 (defun org-occur (regexp &optional keep-previous callback)
15001 "Make a compact tree which shows all matches of REGEXP.
15002 The tree will show the lines where the regexp matches, and all higher
15003 headlines above the match. It will also show the heading after the match,
15004 to make sure editing the matching entry is easy.
15005 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15006 call to `org-occur' will be kept, to allow stacking of calls to this
15007 command.
15008 If CALLBACK is non-nil, it is a function which is called to confirm
15009 that the match should indeed be shown."
15010 (interactive "sRegexp: \nP")
15011 (or keep-previous (org-remove-occur-highlights nil nil t))
15012 (let ((cnt 0))
15013 (save-excursion
15014 (goto-char (point-min))
15015 (if (or (not keep-previous) ; do not want to keep
15016 (not org-occur-highlights)) ; no previous matches
15017 ;; hide everything
15018 (org-overview))
15019 (while (re-search-forward regexp nil t)
15020 (when (or (not callback)
15021 (save-match-data (funcall callback)))
15022 (setq cnt (1+ cnt))
15023 (when org-highlight-sparse-tree-matches
15024 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15025 (org-show-context 'occur-tree))))
15026 (when org-remove-highlights-with-change
15027 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15028 nil 'local))
15029 (unless org-sparse-tree-open-archived-trees
15030 (org-hide-archived-subtrees (point-min) (point-max)))
15031 (run-hooks 'org-occur-hook)
15032 (if (interactive-p)
15033 (message "%d match(es) for regexp %s" cnt regexp))
15034 cnt))
15036 (defun org-show-context (&optional key)
15037 "Make sure point and context and visible.
15038 How much context is shown depends upon the variables
15039 `org-show-hierarchy-above', `org-show-following-heading'. and
15040 `org-show-siblings'."
15041 (let ((heading-p (org-on-heading-p t))
15042 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15043 (following-p (org-get-alist-option org-show-following-heading key))
15044 (entry-p (org-get-alist-option org-show-entry-below key))
15045 (siblings-p (org-get-alist-option org-show-siblings key)))
15046 (catch 'exit
15047 ;; Show heading or entry text
15048 (if (and heading-p (not entry-p))
15049 (org-flag-heading nil) ; only show the heading
15050 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15051 (org-show-hidden-entry))) ; show entire entry
15052 (when following-p
15053 ;; Show next sibling, or heading below text
15054 (save-excursion
15055 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15056 (org-flag-heading nil))))
15057 (when siblings-p (org-show-siblings))
15058 (when hierarchy-p
15059 ;; show all higher headings, possibly with siblings
15060 (save-excursion
15061 (while (and (condition-case nil
15062 (progn (org-up-heading-all 1) t)
15063 (error nil))
15064 (not (bobp)))
15065 (org-flag-heading nil)
15066 (when siblings-p (org-show-siblings))))))))
15068 (defun org-reveal (&optional siblings)
15069 "Show current entry, hierarchy above it, and the following headline.
15070 This can be used to show a consistent set of context around locations
15071 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15072 not t for the search context.
15074 With optional argument SIBLINGS, on each level of the hierarchy all
15075 siblings are shown. This repairs the tree structure to what it would
15076 look like when opened with hierarchical calls to `org-cycle'."
15077 (interactive "P")
15078 (let ((org-show-hierarchy-above t)
15079 (org-show-following-heading t)
15080 (org-show-siblings (if siblings t org-show-siblings)))
15081 (org-show-context nil)))
15083 (defun org-highlight-new-match (beg end)
15084 "Highlight from BEG to END and mark the highlight is an occur headline."
15085 (let ((ov (org-make-overlay beg end)))
15086 (org-overlay-put ov 'face 'secondary-selection)
15087 (push ov org-occur-highlights)))
15089 (defun org-remove-occur-highlights (&optional beg end noremove)
15090 "Remove the occur highlights from the buffer.
15091 BEG and END are ignored. If NOREMOVE is nil, remove this function
15092 from the `before-change-functions' in the current buffer."
15093 (interactive)
15094 (unless org-inhibit-highlight-removal
15095 (mapc 'org-delete-overlay org-occur-highlights)
15096 (setq org-occur-highlights nil)
15097 (unless noremove
15098 (remove-hook 'before-change-functions
15099 'org-remove-occur-highlights 'local))))
15101 ;;;; Priorities
15103 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15104 "Regular expression matching the priority indicator.")
15106 (defvar org-remove-priority-next-time nil)
15108 (defun org-priority-up ()
15109 "Increase the priority of the current item."
15110 (interactive)
15111 (org-priority 'up))
15113 (defun org-priority-down ()
15114 "Decrease the priority of the current item."
15115 (interactive)
15116 (org-priority 'down))
15118 (defun org-priority (&optional action)
15119 "Change the priority of an item by ARG.
15120 ACTION can be `set', `up', `down', or a character."
15121 (interactive)
15122 (setq action (or action 'set))
15123 (let (current new news have remove)
15124 (save-excursion
15125 (org-back-to-heading)
15126 (if (looking-at org-priority-regexp)
15127 (setq current (string-to-char (match-string 2))
15128 have t)
15129 (setq current org-default-priority))
15130 (cond
15131 ((or (eq action 'set) (integerp action))
15132 (if (integerp action)
15133 (setq new action)
15134 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15135 (setq new (read-char-exclusive)))
15136 (if (and (= (upcase org-highest-priority) org-highest-priority)
15137 (= (upcase org-lowest-priority) org-lowest-priority))
15138 (setq new (upcase new)))
15139 (cond ((equal new ?\ ) (setq remove t))
15140 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15141 (error "Priority must be between `%c' and `%c'"
15142 org-highest-priority org-lowest-priority))))
15143 ((eq action 'up)
15144 (if (and (not have) (eq last-command this-command))
15145 (setq new org-lowest-priority)
15146 (setq new (if (and org-priority-start-cycle-with-default (not have))
15147 org-default-priority (1- current)))))
15148 ((eq action 'down)
15149 (if (and (not have) (eq last-command this-command))
15150 (setq new org-highest-priority)
15151 (setq new (if (and org-priority-start-cycle-with-default (not have))
15152 org-default-priority (1+ current)))))
15153 (t (error "Invalid action")))
15154 (if (or (< (upcase new) org-highest-priority)
15155 (> (upcase new) org-lowest-priority))
15156 (setq remove t))
15157 (setq news (format "%c" new))
15158 (if have
15159 (if remove
15160 (replace-match "" t t nil 1)
15161 (replace-match news t t nil 2))
15162 (if remove
15163 (error "No priority cookie found in line")
15164 (looking-at org-todo-line-regexp)
15165 (if (match-end 2)
15166 (progn
15167 (goto-char (match-end 2))
15168 (insert " [#" news "]"))
15169 (goto-char (match-beginning 3))
15170 (insert "[#" news "] ")))))
15171 (org-preserve-lc (org-set-tags nil 'align))
15172 (if remove
15173 (message "Priority removed")
15174 (message "Priority of current item set to %s" news))))
15177 (defun org-get-priority (s)
15178 "Find priority cookie and return priority."
15179 (save-match-data
15180 (if (not (string-match org-priority-regexp s))
15181 (* 1000 (- org-lowest-priority org-default-priority))
15182 (* 1000 (- org-lowest-priority
15183 (string-to-char (match-string 2 s)))))))
15185 ;;;; Tags
15187 (defun org-scan-tags (action matcher &optional todo-only)
15188 "Scan headline tags with inheritance and produce output ACTION.
15189 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15190 evaluated, testing if a given set of tags qualifies a headline for
15191 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15192 are included in the output."
15193 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15194 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15195 (org-re
15196 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15197 (props (list 'face nil
15198 'done-face 'org-done
15199 'undone-face nil
15200 'mouse-face 'highlight
15201 'org-not-done-regexp org-not-done-regexp
15202 'org-todo-regexp org-todo-regexp
15203 'keymap org-agenda-keymap
15204 'help-echo
15205 (format "mouse-2 or RET jump to org file %s"
15206 (abbreviate-file-name
15207 (or (buffer-file-name (buffer-base-buffer))
15208 (buffer-name (buffer-base-buffer)))))))
15209 (case-fold-search nil)
15210 lspos
15211 tags tags-list tags-alist (llast 0) rtn level category i txt
15212 todo marker entry priority)
15213 (save-excursion
15214 (goto-char (point-min))
15215 (when (eq action 'sparse-tree)
15216 (org-overview)
15217 (org-remove-occur-highlights))
15218 (while (re-search-forward re nil t)
15219 (catch :skip
15220 (setq todo (if (match-end 1) (match-string 2))
15221 tags (if (match-end 4) (match-string 4)))
15222 (goto-char (setq lspos (1+ (match-beginning 0))))
15223 (setq level (org-reduced-level (funcall outline-level))
15224 category (org-get-category))
15225 (setq i llast llast level)
15226 ;; remove tag lists from same and sublevels
15227 (while (>= i level)
15228 (when (setq entry (assoc i tags-alist))
15229 (setq tags-alist (delete entry tags-alist)))
15230 (setq i (1- i)))
15231 ;; add the nex tags
15232 (when tags
15233 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15234 tags-alist
15235 (cons (cons level tags) tags-alist)))
15236 ;; compile tags for current headline
15237 (setq tags-list
15238 (if org-use-tag-inheritance
15239 (apply 'append (mapcar 'cdr tags-alist))
15240 tags))
15241 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15242 (eval matcher)
15243 (or (not org-agenda-skip-archived-trees)
15244 (not (member org-archive-tag tags-list))))
15245 (and (eq action 'agenda) (org-agenda-skip))
15246 ;; list this headline
15248 (if (eq action 'sparse-tree)
15249 (progn
15250 (and org-highlight-sparse-tree-matches
15251 (org-get-heading) (match-end 0)
15252 (org-highlight-new-match
15253 (match-beginning 0) (match-beginning 1)))
15254 (org-show-context 'tags-tree))
15255 (setq txt (org-format-agenda-item
15257 (concat
15258 (if org-tags-match-list-sublevels
15259 (make-string (1- level) ?.) "")
15260 (org-get-heading))
15261 category tags-list)
15262 priority (org-get-priority txt))
15263 (goto-char lspos)
15264 (setq marker (org-agenda-new-marker))
15265 (org-add-props txt props
15266 'org-marker marker 'org-hd-marker marker 'org-category category
15267 'priority priority 'type "tagsmatch")
15268 (push txt rtn))
15269 ;; if we are to skip sublevels, jump to end of subtree
15270 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15271 (when (and (eq action 'sparse-tree)
15272 (not org-sparse-tree-open-archived-trees))
15273 (org-hide-archived-subtrees (point-min) (point-max)))
15274 (nreverse rtn)))
15276 (defvar todo-only) ;; dynamically scoped
15278 (defun org-tags-sparse-tree (&optional todo-only match)
15279 "Create a sparse tree according to tags string MATCH.
15280 MATCH can contain positive and negative selection of tags, like
15281 \"+WORK+URGENT-WITHBOSS\".
15282 If optional argument TODO_ONLY is non-nil, only select lines that are
15283 also TODO lines."
15284 (interactive "P")
15285 (org-prepare-agenda-buffers (list (current-buffer)))
15286 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15288 (defvar org-cached-props nil)
15289 (defun org-cached-entry-get (pom property)
15290 (if (or (eq t org-use-property-inheritance)
15291 (member property org-use-property-inheritance))
15292 ;; Caching is not possible, check it directly
15293 (org-entry-get pom property 'inherit)
15294 ;; Get all properties, so that we can do complicated checks easily
15295 (cdr (assoc property (or org-cached-props
15296 (setq org-cached-props
15297 (org-entry-properties pom)))))))
15299 (defun org-global-tags-completion-table (&optional files)
15300 "Return the list of all tags in all agenda buffer/files."
15301 (save-excursion
15302 (org-uniquify
15303 (delq nil
15304 (apply 'append
15305 (mapcar
15306 (lambda (file)
15307 (set-buffer (find-file-noselect file))
15308 (append (org-get-buffer-tags)
15309 (mapcar (lambda (x) (if (stringp (car-safe x))
15310 (list (car-safe x)) nil))
15311 org-tag-alist)))
15312 (if (and files (car files))
15313 files
15314 (org-agenda-files))))))))
15316 (defun org-make-tags-matcher (match)
15317 "Create the TAGS//TODO matcher form for the selection string MATCH."
15318 ;; todo-only is scoped dynamically into this function, and the function
15319 ;; may change it it the matcher asksk for it.
15320 (unless match
15321 ;; Get a new match request, with completion
15322 (let ((org-last-tags-completion-table
15323 (org-global-tags-completion-table)))
15324 (setq match (completing-read
15325 "Match: " 'org-tags-completion-function nil nil nil
15326 'org-tags-history))))
15328 ;; Parse the string and create a lisp form
15329 (let ((match0 match)
15330 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
15331 minus tag mm
15332 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15333 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15334 (if (string-match "/+" match)
15335 ;; match contains also a todo-matching request
15336 (progn
15337 (setq tagsmatch (substring match 0 (match-beginning 0))
15338 todomatch (substring match (match-end 0)))
15339 (if (string-match "^!" todomatch)
15340 (setq todo-only t todomatch (substring todomatch 1)))
15341 (if (string-match "^\\s-*$" todomatch)
15342 (setq todomatch nil)))
15343 ;; only matching tags
15344 (setq tagsmatch match todomatch nil))
15346 ;; Make the tags matcher
15347 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15348 (setq tagsmatcher t)
15349 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15350 (while (setq term (pop orterms))
15351 (while (and (equal (substring term -1) "\\") orterms)
15352 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15353 (while (string-match re term)
15354 (setq minus (and (match-end 1)
15355 (equal (match-string 1 term) "-"))
15356 tag (match-string 2 term)
15357 re-p (equal (string-to-char tag) ?{)
15358 level-p (match-end 3)
15359 prop-p (match-end 4)
15360 mm (cond
15361 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15362 (level-p `(= level ,(string-to-number
15363 (match-string 3 term))))
15364 (prop-p
15365 (setq pn (match-string 4 term)
15366 pv (match-string 5 term)
15367 cat-p (equal pn "CATEGORY")
15368 re-p (equal (string-to-char pv) ?{)
15369 pv (substring pv 1 -1))
15370 (if (equal pn "CATEGORY")
15371 (setq gv '(get-text-property (point) 'org-category))
15372 (setq gv `(org-cached-entry-get nil ,pn)))
15373 (if re-p
15374 `(string-match ,pv (or ,gv ""))
15375 `(equal ,pv ,gv)))
15376 (t `(member ,(downcase tag) tags-list)))
15377 mm (if minus (list 'not mm) mm)
15378 term (substring term (match-end 0)))
15379 (push mm tagsmatcher))
15380 (push (if (> (length tagsmatcher) 1)
15381 (cons 'and tagsmatcher)
15382 (car tagsmatcher))
15383 orlist)
15384 (setq tagsmatcher nil))
15385 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15386 (setq tagsmatcher
15387 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15389 ;; Make the todo matcher
15390 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15391 (setq todomatcher t)
15392 (setq orterms (org-split-string todomatch "|") orlist nil)
15393 (while (setq term (pop orterms))
15394 (while (string-match re term)
15395 (setq minus (and (match-end 1)
15396 (equal (match-string 1 term) "-"))
15397 kwd (match-string 2 term)
15398 re-p (equal (string-to-char kwd) ?{)
15399 term (substring term (match-end 0))
15400 mm (if re-p
15401 `(string-match ,(substring kwd 1 -1) todo)
15402 (list 'equal 'todo kwd))
15403 mm (if minus (list 'not mm) mm))
15404 (push mm todomatcher))
15405 (push (if (> (length todomatcher) 1)
15406 (cons 'and todomatcher)
15407 (car todomatcher))
15408 orlist)
15409 (setq todomatcher nil))
15410 (setq todomatcher (if (> (length orlist) 1)
15411 (cons 'or orlist) (car orlist))))
15413 ;; Return the string and lisp forms of the matcher
15414 (setq matcher (if todomatcher
15415 (list 'and tagsmatcher todomatcher)
15416 tagsmatcher))
15417 (cons match0 matcher)))
15419 (defun org-match-any-p (re list)
15420 "Does re match any element of list?"
15421 (setq list (mapcar (lambda (x) (string-match re x)) list))
15422 (delq nil list))
15424 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15425 (defvar org-tags-overlay (org-make-overlay 1 1))
15426 (org-detach-overlay org-tags-overlay)
15428 (defun org-align-tags-here (to-col)
15429 ;; Assumes that this is a headline
15430 (let ((pos (point)) (col (current-column)) tags)
15431 (beginning-of-line 1)
15432 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15433 (< pos (match-beginning 2)))
15434 (progn
15435 (setq tags (match-string 2))
15436 (goto-char (match-beginning 1))
15437 (insert " ")
15438 (delete-region (point) (1+ (match-end 0)))
15439 (backward-char 1)
15440 (move-to-column
15441 (max (1+ (current-column))
15442 (1+ col)
15443 (if (> to-col 0)
15444 to-col
15445 (- (abs to-col) (length tags))))
15447 (insert tags)
15448 (move-to-column (min (current-column) col) t))
15449 (goto-char pos))))
15451 (defun org-set-tags (&optional arg just-align)
15452 "Set the tags for the current headline.
15453 With prefix ARG, realign all tags in headings in the current buffer."
15454 (interactive "P")
15455 (let* ((re (concat "^" outline-regexp))
15456 (current (org-get-tags-string))
15457 (col (current-column))
15458 (org-setting-tags t)
15459 table current-tags inherited-tags ; computed below when needed
15460 tags p0 c0 c1 rpl)
15461 (if arg
15462 (save-excursion
15463 (goto-char (point-min))
15464 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15465 (while (re-search-forward re nil t)
15466 (org-set-tags nil t)
15467 (end-of-line 1)))
15468 (message "All tags realigned to column %d" org-tags-column))
15469 (if just-align
15470 (setq tags current)
15471 ;; Get a new set of tags from the user
15472 (save-excursion
15473 (setq table (or org-tag-alist (org-get-buffer-tags))
15474 org-last-tags-completion-table table
15475 current-tags (org-split-string current ":")
15476 inherited-tags (nreverse
15477 (nthcdr (length current-tags)
15478 (nreverse (org-get-tags-at))))
15479 tags
15480 (if (or (eq t org-use-fast-tag-selection)
15481 (and org-use-fast-tag-selection
15482 (delq nil (mapcar 'cdr table))))
15483 (org-fast-tag-selection
15484 current-tags inherited-tags table
15485 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15486 (let ((org-add-colon-after-tag-completion t))
15487 (org-trim
15488 (org-without-partial-completion
15489 (completing-read "Tags: " 'org-tags-completion-function
15490 nil nil current 'org-tags-history)))))))
15491 (while (string-match "[-+&]+" tags)
15492 ;; No boolean logic, just a list
15493 (setq tags (replace-match ":" t t tags))))
15495 (if (string-match "\\`[\t ]*\\'" tags)
15496 (setq tags "")
15497 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15498 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15500 ;; Insert new tags at the correct column
15501 (beginning-of-line 1)
15502 (cond
15503 ((and (equal current "") (equal tags "")))
15504 ((re-search-forward
15505 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15506 (point-at-eol) t)
15507 (if (equal tags "")
15508 (setq rpl "")
15509 (goto-char (match-beginning 0))
15510 (setq c0 (current-column) p0 (point)
15511 c1 (max (1+ c0) (if (> org-tags-column 0)
15512 org-tags-column
15513 (- (- org-tags-column) (length tags))))
15514 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15515 (replace-match rpl t t)
15516 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15517 tags)
15518 (t (error "Tags alignment failed")))
15519 (move-to-column col)
15520 (unless just-align
15521 (run-hooks 'org-after-tags-change-hook)))))
15523 (defun org-change-tag-in-region (beg end tag off)
15524 "Add or remove TAG for each entry in the region.
15525 This works in the agenda, and also in an org-mode buffer."
15526 (interactive
15527 (list (region-beginning) (region-end)
15528 (let ((org-last-tags-completion-table
15529 (if (org-mode-p)
15530 (org-get-buffer-tags)
15531 (org-global-tags-completion-table))))
15532 (completing-read
15533 "Tag: " 'org-tags-completion-function nil nil nil
15534 'org-tags-history))
15535 (progn
15536 (message "[s]et or [r]emove? ")
15537 (equal (read-char-exclusive) ?r))))
15538 (if (fboundp 'deactivate-mark) (deactivate-mark))
15539 (let ((agendap (equal major-mode 'org-agenda-mode))
15540 l1 l2 m buf pos newhead (cnt 0))
15541 (goto-char end)
15542 (setq l2 (1- (org-current-line)))
15543 (goto-char beg)
15544 (setq l1 (org-current-line))
15545 (loop for l from l1 to l2 do
15546 (goto-line l)
15547 (setq m (get-text-property (point) 'org-hd-marker))
15548 (when (or (and (org-mode-p) (org-on-heading-p))
15549 (and agendap m))
15550 (setq buf (if agendap (marker-buffer m) (current-buffer))
15551 pos (if agendap m (point)))
15552 (with-current-buffer buf
15553 (save-excursion
15554 (save-restriction
15555 (goto-char pos)
15556 (setq cnt (1+ cnt))
15557 (org-toggle-tag tag (if off 'off 'on))
15558 (setq newhead (org-get-heading)))))
15559 (and agendap (org-agenda-change-all-lines newhead m))))
15560 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15562 (defun org-tags-completion-function (string predicate &optional flag)
15563 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15564 (confirm (lambda (x) (stringp (car x)))))
15565 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15566 (setq s1 (match-string 1 string)
15567 s2 (match-string 2 string))
15568 (setq s1 "" s2 string))
15569 (cond
15570 ((eq flag nil)
15571 ;; try completion
15572 (setq rtn (try-completion s2 ctable confirm))
15573 (if (stringp rtn)
15574 (setq rtn
15575 (concat s1 s2 (substring rtn (length s2))
15576 (if (and org-add-colon-after-tag-completion
15577 (assoc rtn ctable))
15578 ":" ""))))
15579 rtn)
15580 ((eq flag t)
15581 ;; all-completions
15582 (all-completions s2 ctable confirm)
15584 ((eq flag 'lambda)
15585 ;; exact match?
15586 (assoc s2 ctable)))
15589 (defun org-fast-tag-insert (kwd tags face &optional end)
15590 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15591 (insert (format "%-12s" (concat kwd ":"))
15592 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15593 (or end "")))
15595 (defun org-fast-tag-show-exit (flag)
15596 (save-excursion
15597 (goto-line 3)
15598 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15599 (replace-match ""))
15600 (when flag
15601 (end-of-line 1)
15602 (move-to-column (- (window-width) 19) t)
15603 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15605 (defun org-set-current-tags-overlay (current prefix)
15606 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15607 (if (featurep 'xemacs)
15608 (org-overlay-display org-tags-overlay (concat prefix s)
15609 'secondary-selection)
15610 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15611 (org-overlay-display org-tags-overlay (concat prefix s)))))
15613 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15614 "Fast tag selection with single keys.
15615 CURRENT is the current list of tags in the headline, INHERITED is the
15616 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15617 possibly with grouping information. TODO-TABLE is a similar table with
15618 TODO keywords, should these have keys assigned to them.
15619 If the keys are nil, a-z are automatically assigned.
15620 Returns the new tags string, or nil to not change the current settings."
15621 (let* ((fulltable (append table todo-table))
15622 (maxlen (apply 'max (mapcar
15623 (lambda (x)
15624 (if (stringp (car x)) (string-width (car x)) 0))
15625 fulltable)))
15626 (buf (current-buffer))
15627 (expert (eq org-fast-tag-selection-single-key 'expert))
15628 (buffer-tags nil)
15629 (fwidth (+ maxlen 3 1 3))
15630 (ncol (/ (- (window-width) 4) fwidth))
15631 (i-face 'org-done)
15632 (c-face 'org-todo)
15633 tg cnt e c char c1 c2 ntable tbl rtn
15634 ov-start ov-end ov-prefix
15635 (exit-after-next org-fast-tag-selection-single-key)
15636 (done-keywords org-done-keywords)
15637 groups ingroup)
15638 (save-excursion
15639 (beginning-of-line 1)
15640 (if (looking-at
15641 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15642 (setq ov-start (match-beginning 1)
15643 ov-end (match-end 1)
15644 ov-prefix "")
15645 (setq ov-start (1- (point-at-eol))
15646 ov-end (1+ ov-start))
15647 (skip-chars-forward "^\n\r")
15648 (setq ov-prefix
15649 (concat
15650 (buffer-substring (1- (point)) (point))
15651 (if (> (current-column) org-tags-column)
15653 (make-string (- org-tags-column (current-column)) ?\ ))))))
15654 (org-move-overlay org-tags-overlay ov-start ov-end)
15655 (save-window-excursion
15656 (if expert
15657 (set-buffer (get-buffer-create " *Org tags*"))
15658 (delete-other-windows)
15659 (split-window-vertically)
15660 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15661 (erase-buffer)
15662 (org-set-local 'org-done-keywords done-keywords)
15663 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15664 (org-fast-tag-insert "Current" current c-face "\n\n")
15665 (org-fast-tag-show-exit exit-after-next)
15666 (org-set-current-tags-overlay current ov-prefix)
15667 (setq tbl fulltable char ?a cnt 0)
15668 (while (setq e (pop tbl))
15669 (cond
15670 ((equal e '(:startgroup))
15671 (push '() groups) (setq ingroup t)
15672 (when (not (= cnt 0))
15673 (setq cnt 0)
15674 (insert "\n"))
15675 (insert "{ "))
15676 ((equal e '(:endgroup))
15677 (setq ingroup nil cnt 0)
15678 (insert "}\n"))
15680 (setq tg (car e) c2 nil)
15681 (if (cdr e)
15682 (setq c (cdr e))
15683 ;; automatically assign a character.
15684 (setq c1 (string-to-char
15685 (downcase (substring
15686 tg (if (= (string-to-char tg) ?@) 1 0)))))
15687 (if (or (rassoc c1 ntable) (rassoc c1 table))
15688 (while (or (rassoc char ntable) (rassoc char table))
15689 (setq char (1+ char)))
15690 (setq c2 c1))
15691 (setq c (or c2 char)))
15692 (if ingroup (push tg (car groups)))
15693 (setq tg (org-add-props tg nil 'face
15694 (cond
15695 ((not (assoc tg table))
15696 (org-get-todo-face tg))
15697 ((member tg current) c-face)
15698 ((member tg inherited) i-face)
15699 (t nil))))
15700 (if (and (= cnt 0) (not ingroup)) (insert " "))
15701 (insert "[" c "] " tg (make-string
15702 (- fwidth 4 (length tg)) ?\ ))
15703 (push (cons tg c) ntable)
15704 (when (= (setq cnt (1+ cnt)) ncol)
15705 (insert "\n")
15706 (if ingroup (insert " "))
15707 (setq cnt 0)))))
15708 (setq ntable (nreverse ntable))
15709 (insert "\n")
15710 (goto-char (point-min))
15711 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15712 (fit-window-to-buffer))
15713 (setq rtn
15714 (catch 'exit
15715 (while t
15716 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15717 (if groups " [!] no groups" " [!]groups")
15718 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15719 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15720 (cond
15721 ((= c ?\r) (throw 'exit t))
15722 ((= c ?!)
15723 (setq groups (not groups))
15724 (goto-char (point-min))
15725 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15726 ((= c ?\C-c)
15727 (if (not expert)
15728 (org-fast-tag-show-exit
15729 (setq exit-after-next (not exit-after-next)))
15730 (setq expert nil)
15731 (delete-other-windows)
15732 (split-window-vertically)
15733 (org-switch-to-buffer-other-window " *Org tags*")
15734 (and (fboundp 'fit-window-to-buffer)
15735 (fit-window-to-buffer))))
15736 ((or (= c ?\C-g)
15737 (and (= c ?q) (not (rassoc c ntable))))
15738 (org-detach-overlay org-tags-overlay)
15739 (setq quit-flag t))
15740 ((= c ?\ )
15741 (setq current nil)
15742 (if exit-after-next (setq exit-after-next 'now)))
15743 ((= c ?\t)
15744 (condition-case nil
15745 (setq tg (completing-read
15746 "Tag: "
15747 (or buffer-tags
15748 (with-current-buffer buf
15749 (org-get-buffer-tags)))))
15750 (quit (setq tg "")))
15751 (when (string-match "\\S-" tg)
15752 (add-to-list 'buffer-tags (list tg))
15753 (if (member tg current)
15754 (setq current (delete tg current))
15755 (push tg current)))
15756 (if exit-after-next (setq exit-after-next 'now)))
15757 ((setq e (rassoc c todo-table) tg (car e))
15758 (with-current-buffer buf
15759 (save-excursion (org-todo tg)))
15760 (if exit-after-next (setq exit-after-next 'now)))
15761 ((setq e (rassoc c ntable) tg (car e))
15762 (if (member tg current)
15763 (setq current (delete tg current))
15764 (loop for g in groups do
15765 (if (member tg g)
15766 (mapc (lambda (x)
15767 (setq current (delete x current)))
15768 g)))
15769 (push tg current))
15770 (if exit-after-next (setq exit-after-next 'now))))
15772 ;; Create a sorted list
15773 (setq current
15774 (sort current
15775 (lambda (a b)
15776 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15777 (if (eq exit-after-next 'now) (throw 'exit t))
15778 (goto-char (point-min))
15779 (beginning-of-line 2)
15780 (delete-region (point) (point-at-eol))
15781 (org-fast-tag-insert "Current" current c-face)
15782 (org-set-current-tags-overlay current ov-prefix)
15783 (while (re-search-forward
15784 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15785 (setq tg (match-string 1))
15786 (add-text-properties
15787 (match-beginning 1) (match-end 1)
15788 (list 'face
15789 (cond
15790 ((member tg current) c-face)
15791 ((member tg inherited) i-face)
15792 (t (get-text-property (match-beginning 1) 'face))))))
15793 (goto-char (point-min)))))
15794 (org-detach-overlay org-tags-overlay)
15795 (if rtn
15796 (mapconcat 'identity current ":")
15797 nil))))
15799 (defun org-get-tags-string ()
15800 "Get the TAGS string in the current headline."
15801 (unless (org-on-heading-p t)
15802 (error "Not on a heading"))
15803 (save-excursion
15804 (beginning-of-line 1)
15805 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15806 (org-match-string-no-properties 1)
15807 "")))
15809 (defun org-get-tags ()
15810 "Get the list of tags specified in the current headline."
15811 (org-split-string (org-get-tags-string) ":"))
15813 (defun org-get-buffer-tags ()
15814 "Get a table of all tags used in the buffer, for completion."
15815 (let (tags)
15816 (save-excursion
15817 (goto-char (point-min))
15818 (while (re-search-forward
15819 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15820 (when (equal (char-after (point-at-bol 0)) ?*)
15821 (mapc (lambda (x) (add-to-list 'tags x))
15822 (org-split-string (org-match-string-no-properties 1) ":")))))
15823 (mapcar 'list tags)))
15826 ;;;; Properties
15828 ;;; Setting and retrieving properties
15830 (defconst org-special-properties
15831 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15832 "TIMESTAMP" "TIMESTAMP_IA")
15833 "The special properties valid in Org-mode.
15835 These are properties that are not defined in the property drawer,
15836 but in some other way.")
15838 (defconst org-default-properties
15839 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15840 "LOCATION" "LOGGING" "COLUMNS")
15841 "Some properties that are used by Org-mode for various purposes.
15842 Being in this list makes sure that they are offered for completion.")
15844 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15845 "Regular expression matching the first line of a property drawer.")
15847 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15848 "Regular expression matching the first line of a property drawer.")
15850 (defun org-property-action ()
15851 "Do an action on properties."
15852 (interactive)
15853 (let (c)
15854 (org-at-property-p)
15855 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15856 (setq c (read-char-exclusive))
15857 (cond
15858 ((equal c ?s)
15859 (call-interactively 'org-set-property))
15860 ((equal c ?d)
15861 (call-interactively 'org-delete-property))
15862 ((equal c ?D)
15863 (call-interactively 'org-delete-property-globally))
15864 ((equal c ?c)
15865 (call-interactively 'org-compute-property-at-point))
15866 (t (error "No such property action %c" c)))))
15868 (defun org-at-property-p ()
15869 "Is the cursor in a property line?"
15870 ;; FIXME: Does not check if we are actually in the drawer.
15871 ;; FIXME: also returns true on any drawers.....
15872 ;; This is used by C-c C-c for property action.
15873 (save-excursion
15874 (beginning-of-line 1)
15875 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15877 (defmacro org-with-point-at (pom &rest body)
15878 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15879 (declare (indent 1) (debug t))
15880 `(save-excursion
15881 (if (markerp pom) (set-buffer (marker-buffer pom)))
15882 (save-excursion
15883 (goto-char (or pom (point)))
15884 ,@body)))
15886 (defun org-get-property-block (&optional beg end force)
15887 "Return the (beg . end) range of the body of the property drawer.
15888 BEG and END can be beginning and end of subtree, if not given
15889 they will be found.
15890 If the drawer does not exist and FORCE is non-nil, create the drawer."
15891 (catch 'exit
15892 (save-excursion
15893 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15894 (end (or end (progn (outline-next-heading) (point)))))
15895 (goto-char beg)
15896 (if (re-search-forward org-property-start-re end t)
15897 (setq beg (1+ (match-end 0)))
15898 (if force
15899 (save-excursion
15900 (org-insert-property-drawer)
15901 (setq end (progn (outline-next-heading) (point))))
15902 (throw 'exit nil))
15903 (goto-char beg)
15904 (if (re-search-forward org-property-start-re end t)
15905 (setq beg (1+ (match-end 0)))))
15906 (if (re-search-forward org-property-end-re end t)
15907 (setq end (match-beginning 0))
15908 (or force (throw 'exit nil))
15909 (goto-char beg)
15910 (setq end beg)
15911 (org-indent-line-function)
15912 (insert ":END:\n"))
15913 (cons beg end)))))
15915 (defun org-entry-properties (&optional pom which)
15916 "Get all properties of the entry at point-or-marker POM.
15917 This includes the TODO keyword, the tags, time strings for deadline,
15918 scheduled, and clocking, and any additional properties defined in the
15919 entry. The return value is an alist, keys may occur multiple times
15920 if the property key was used several times.
15921 POM may also be nil, in which case the current entry is used.
15922 If WHICH is nil or `all', get all properties. If WHICH is
15923 `special' or `standard', only get that subclass."
15924 (setq which (or which 'all))
15925 (org-with-point-at pom
15926 (let ((clockstr (substring org-clock-string 0 -1))
15927 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15928 beg end range props sum-props key value string clocksum)
15929 (save-excursion
15930 (when (condition-case nil (org-back-to-heading t) (error nil))
15931 (setq beg (point))
15932 (setq sum-props (get-text-property (point) 'org-summaries))
15933 (setq clocksum (get-text-property (point) :org-clock-minutes))
15934 (outline-next-heading)
15935 (setq end (point))
15936 (when (memq which '(all special))
15937 ;; Get the special properties, like TODO and tags
15938 (goto-char beg)
15939 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15940 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15941 (when (looking-at org-priority-regexp)
15942 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15943 (when (and (setq value (org-get-tags-string))
15944 (string-match "\\S-" value))
15945 (push (cons "TAGS" value) props))
15946 (when (setq value (org-get-tags-at))
15947 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15948 props))
15949 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15950 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15951 string (if (equal key clockstr)
15952 (org-no-properties
15953 (org-trim
15954 (buffer-substring
15955 (match-beginning 3) (goto-char (point-at-eol)))))
15956 (substring (org-match-string-no-properties 3) 1 -1)))
15957 (unless key
15958 (if (= (char-after (match-beginning 3)) ?\[)
15959 (setq key "TIMESTAMP_IA")
15960 (setq key "TIMESTAMP")))
15961 (when (or (equal key clockstr) (not (assoc key props)))
15962 (push (cons key string) props)))
15966 (when (memq which '(all standard))
15967 ;; Get the standard properties, like :PORP: ...
15968 (setq range (org-get-property-block beg end))
15969 (when range
15970 (goto-char (car range))
15971 (while (re-search-forward
15972 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15973 (cdr range) t)
15974 (setq key (org-match-string-no-properties 1)
15975 value (org-trim (or (org-match-string-no-properties 2) "")))
15976 (unless (member key excluded)
15977 (push (cons key (or value "")) props)))))
15978 (if clocksum
15979 (push (cons "CLOCKSUM"
15980 (org-column-number-to-string (/ (float clocksum) 60.)
15981 'add_times))
15982 props))
15983 (append sum-props (nreverse props)))))))
15985 (defun org-entry-get (pom property &optional inherit)
15986 "Get value of PROPERTY for entry at point-or-marker POM.
15987 If INHERIT is non-nil and the entry does not have the property,
15988 then also check higher levels of the hierarchy.
15989 If the property is present but empty, the return value is the empty string.
15990 If the property is not present at all, nil is returned."
15991 (org-with-point-at pom
15992 (if inherit
15993 (org-entry-get-with-inheritance property)
15994 (if (member property org-special-properties)
15995 ;; We need a special property. Use brute force, get all properties.
15996 (cdr (assoc property (org-entry-properties nil 'special)))
15997 (let ((range (org-get-property-block)))
15998 (if (and range
15999 (goto-char (car range))
16000 (re-search-forward
16001 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16002 (cdr range) t))
16003 ;; Found the property, return it.
16004 (if (match-end 1)
16005 (org-match-string-no-properties 1)
16006 "")))))))
16008 (defun org-entry-delete (pom property)
16009 "Delete the property PROPERTY from entry at point-or-marker POM."
16010 (org-with-point-at pom
16011 (if (member property org-special-properties)
16012 nil ; cannot delete these properties.
16013 (let ((range (org-get-property-block)))
16014 (if (and range
16015 (goto-char (car range))
16016 (re-search-forward
16017 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16018 (cdr range) t))
16019 (progn
16020 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16022 nil)))))
16024 ;; Multi-values properties are properties that contain multiple values
16025 ;; These values are assumed to be single words, separated by whitespace.
16026 (defun org-entry-add-to-multivalued-property (pom property value)
16027 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16028 (let* ((old (org-entry-get pom property))
16029 (values (and old (org-split-string old "[ \t]"))))
16030 (unless (member value values)
16031 (setq values (cons value values))
16032 (org-entry-put pom property
16033 (mapconcat 'identity values " ")))))
16035 (defun org-entry-remove-from-multivalued-property (pom property value)
16036 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16037 (let* ((old (org-entry-get pom property))
16038 (values (and old (org-split-string old "[ \t]"))))
16039 (when (member value values)
16040 (setq values (delete value values))
16041 (org-entry-put pom property
16042 (mapconcat 'identity values " ")))))
16044 (defun org-entry-member-in-multivalued-property (pom property value)
16045 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16046 (let* ((old (org-entry-get pom property))
16047 (values (and old (org-split-string old "[ \t]"))))
16048 (member value values)))
16050 (defvar org-entry-property-inherited-from (make-marker))
16052 (defun org-entry-get-with-inheritance (property)
16053 "Get entry property, and search higher levels if not present."
16054 (let (tmp)
16055 (save-excursion
16056 (save-restriction
16057 (widen)
16058 (catch 'ex
16059 (while t
16060 (when (setq tmp (org-entry-get nil property))
16061 (org-back-to-heading t)
16062 (move-marker org-entry-property-inherited-from (point))
16063 (throw 'ex tmp))
16064 (or (org-up-heading-safe) (throw 'ex nil)))))
16065 (or tmp (cdr (assoc property org-local-properties))
16066 (cdr (assoc property org-global-properties))))))
16068 (defun org-entry-put (pom property value)
16069 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16070 (org-with-point-at pom
16071 (org-back-to-heading t)
16072 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16073 range)
16074 (cond
16075 ((equal property "TODO")
16076 (when (and (stringp value) (string-match "\\S-" value)
16077 (not (member value org-todo-keywords-1)))
16078 (error "\"%s\" is not a valid TODO state" value))
16079 (if (or (not value)
16080 (not (string-match "\\S-" value)))
16081 (setq value 'none))
16082 (org-todo value)
16083 (org-set-tags nil 'align))
16084 ((equal property "PRIORITY")
16085 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16086 (string-to-char value) ?\ ))
16087 (org-set-tags nil 'align))
16088 ((equal property "SCHEDULED")
16089 (if (re-search-forward org-scheduled-time-regexp end t)
16090 (cond
16091 ((eq value 'earlier) (org-timestamp-change -1 'day))
16092 ((eq value 'later) (org-timestamp-change 1 'day))
16093 (t (call-interactively 'org-schedule)))
16094 (call-interactively 'org-schedule)))
16095 ((equal property "DEADLINE")
16096 (if (re-search-forward org-deadline-time-regexp end t)
16097 (cond
16098 ((eq value 'earlier) (org-timestamp-change -1 'day))
16099 ((eq value 'later) (org-timestamp-change 1 'day))
16100 (t (call-interactively 'org-deadline)))
16101 (call-interactively 'org-deadline)))
16102 ((member property org-special-properties)
16103 (error "The %s property can not yet be set with `org-entry-put'"
16104 property))
16105 (t ; a non-special property
16106 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16107 (setq range (org-get-property-block beg end 'force))
16108 (goto-char (car range))
16109 (if (re-search-forward
16110 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16111 (progn
16112 (delete-region (match-beginning 1) (match-end 1))
16113 (goto-char (match-beginning 1)))
16114 (goto-char (cdr range))
16115 (insert "\n")
16116 (backward-char 1)
16117 (org-indent-line-function)
16118 (insert ":" property ":"))
16119 (and value (insert " " value))
16120 (org-indent-line-function)))))))
16122 (defun org-buffer-property-keys (&optional include-specials include-defaults)
16123 "Get all property keys in the current buffer.
16124 With INCLUDE-SPECIALS, also list the special properties that relect things
16125 like tags and TODO state.
16126 With INCLUDE-DEFAULTS, also include properties that has special meaning
16127 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
16128 (let (rtn range)
16129 (save-excursion
16130 (save-restriction
16131 (widen)
16132 (goto-char (point-min))
16133 (while (re-search-forward org-property-start-re nil t)
16134 (setq range (org-get-property-block))
16135 (goto-char (car range))
16136 (while (re-search-forward
16137 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
16138 (cdr range) t)
16139 (add-to-list 'rtn (org-match-string-no-properties 1)))
16140 (outline-next-heading))))
16142 (when include-specials
16143 (setq rtn (append org-special-properties rtn)))
16145 (when include-defaults
16146 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16148 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16150 (defun org-property-values (key)
16151 "Return a list of all values of property KEY."
16152 (save-excursion
16153 (save-restriction
16154 (widen)
16155 (goto-char (point-min))
16156 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16157 values)
16158 (while (re-search-forward re nil t)
16159 (add-to-list 'values (org-trim (match-string 1))))
16160 (delete "" values)))))
16162 (defun org-insert-property-drawer ()
16163 "Insert a property drawer into the current entry."
16164 (interactive)
16165 (org-back-to-heading t)
16166 (looking-at outline-regexp)
16167 (let ((indent (- (match-end 0)(match-beginning 0)))
16168 (beg (point))
16169 (re (concat "^[ \t]*" org-keyword-time-regexp))
16170 end hiddenp)
16171 (outline-next-heading)
16172 (setq end (point))
16173 (goto-char beg)
16174 (while (re-search-forward re end t))
16175 (setq hiddenp (org-invisible-p))
16176 (end-of-line 1)
16177 (and (equal (char-after) ?\n) (forward-char 1))
16178 (org-skip-over-state-notes)
16179 (skip-chars-backward " \t\n\r")
16180 (if (eq (char-before) ?*) (forward-char 1))
16181 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16182 (beginning-of-line 0)
16183 (indent-to-column indent)
16184 (beginning-of-line 2)
16185 (indent-to-column indent)
16186 (beginning-of-line 0)
16187 (if hiddenp
16188 (save-excursion
16189 (org-back-to-heading t)
16190 (hide-entry))
16191 (org-flag-drawer t))))
16193 (defun org-set-property (property value)
16194 "In the current entry, set PROPERTY to VALUE.
16195 When called interactively, this will prompt for a property name, offering
16196 completion on existing and default properties. And then it will prompt
16197 for a value, offering competion either on allowed values (via an inherited
16198 xxx_ALL property) or on existing values in other instances of this property
16199 in the current file."
16200 (interactive
16201 (let* ((prop (completing-read
16202 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
16203 (cur (org-entry-get nil prop))
16204 (allowed (org-property-get-allowed-values nil prop 'table))
16205 (existing (mapcar 'list (org-property-values prop)))
16206 (val (if allowed
16207 (completing-read "Value: " allowed nil 'req-match)
16208 (completing-read
16209 (concat "Value" (if (and cur (string-match "\\S-" cur))
16210 (concat "[" cur "]") "")
16211 ": ")
16212 existing nil nil "" nil cur))))
16213 (list prop (if (equal val "") cur val))))
16214 (unless (equal (org-entry-get nil property) value)
16215 (org-entry-put nil property value)))
16217 (defun org-delete-property (property)
16218 "In the current entry, delete PROPERTY."
16219 (interactive
16220 (let* ((prop (completing-read
16221 "Property: " (org-entry-properties nil 'standard))))
16222 (list prop)))
16223 (message "Property %s %s" property
16224 (if (org-entry-delete nil property)
16225 "deleted"
16226 "was not present in the entry")))
16228 (defun org-delete-property-globally (property)
16229 "Remove PROPERTY globally, from all entries."
16230 (interactive
16231 (let* ((prop (completing-read
16232 "Globally remove property: "
16233 (mapcar 'list (org-buffer-property-keys)))))
16234 (list prop)))
16235 (save-excursion
16236 (save-restriction
16237 (widen)
16238 (goto-char (point-min))
16239 (let ((cnt 0))
16240 (while (re-search-forward
16241 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16242 nil t)
16243 (setq cnt (1+ cnt))
16244 (replace-match ""))
16245 (message "Property \"%s\" removed from %d entries" property cnt)))))
16247 (defvar org-columns-current-fmt-compiled) ; defined below
16249 (defun org-compute-property-at-point ()
16250 "Compute the property at point.
16251 This looks for an enclosing column format, extracts the operator and
16252 then applies it to the proerty in the column format's scope."
16253 (interactive)
16254 (unless (org-at-property-p)
16255 (error "Not at a property"))
16256 (let ((prop (org-match-string-no-properties 2)))
16257 (org-columns-get-format-and-top-level)
16258 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16259 (error "No operator defined for property %s" prop))
16260 (org-columns-compute prop)))
16262 (defun org-property-get-allowed-values (pom property &optional table)
16263 "Get allowed values for the property PROPERTY.
16264 When TABLE is non-nil, return an alist that can directly be used for
16265 completion."
16266 (let (vals)
16267 (cond
16268 ((equal property "TODO")
16269 (setq vals (org-with-point-at pom
16270 (append org-todo-keywords-1 '("")))))
16271 ((equal property "PRIORITY")
16272 (let ((n org-lowest-priority))
16273 (while (>= n org-highest-priority)
16274 (push (char-to-string n) vals)
16275 (setq n (1- n)))))
16276 ((member property org-special-properties))
16278 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16280 (when (and vals (string-match "\\S-" vals))
16281 (setq vals (car (read-from-string (concat "(" vals ")"))))
16282 (setq vals (mapcar (lambda (x)
16283 (cond ((stringp x) x)
16284 ((numberp x) (number-to-string x))
16285 ((symbolp x) (symbol-name x))
16286 (t "???")))
16287 vals)))))
16288 (if table (mapcar 'list vals) vals)))
16290 (defun org-property-previous-allowed-value (&optional previous)
16291 "Switch to the next allowed value for this property."
16292 (interactive)
16293 (org-property-next-allowed-value t))
16295 (defun org-property-next-allowed-value (&optional previous)
16296 "Switch to the next allowed value for this property."
16297 (interactive)
16298 (unless (org-at-property-p)
16299 (error "Not at a property"))
16300 (let* ((key (match-string 2))
16301 (value (match-string 3))
16302 (allowed (or (org-property-get-allowed-values (point) key)
16303 (and (member value '("[ ]" "[-]" "[X]"))
16304 '("[ ]" "[X]"))))
16305 nval)
16306 (unless allowed
16307 (error "Allowed values for this property have not been defined"))
16308 (if previous (setq allowed (reverse allowed)))
16309 (if (member value allowed)
16310 (setq nval (car (cdr (member value allowed)))))
16311 (setq nval (or nval (car allowed)))
16312 (if (equal nval value)
16313 (error "Only one allowed value for this property"))
16314 (org-at-property-p)
16315 (replace-match (concat " :" key ": " nval) t t)
16316 (org-indent-line-function)
16317 (beginning-of-line 1)
16318 (skip-chars-forward " \t")))
16320 (defun org-find-entry-with-id (ident)
16321 "Locate the entry that contains the ID property with exact value IDENT.
16322 IDENT can be a string, a symbol or a number, this function will search for
16323 the string representation of it.
16324 Return the position where this entry starts, or nil if there is no such entry."
16325 (let ((id (cond
16326 ((stringp ident) ident)
16327 ((symbol-name ident) (symbol-name ident))
16328 ((numberp ident) (number-to-string ident))
16329 (t (error "IDENT %s must be a string, symbol or number" ident))))
16330 (case-fold-search nil))
16331 (save-excursion
16332 (save-restriction
16333 (goto-char (point-min))
16334 (when (re-search-forward
16335 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16336 nil t)
16337 (org-back-to-heading)
16338 (point))))))
16340 ;;; Column View
16342 (defvar org-columns-overlays nil
16343 "Holds the list of current column overlays.")
16345 (defvar org-columns-current-fmt nil
16346 "Local variable, holds the currently active column format.")
16347 (defvar org-columns-current-fmt-compiled nil
16348 "Local variable, holds the currently active column format.
16349 This is the compiled version of the format.")
16350 (defvar org-columns-current-widths nil
16351 "Loval variable, holds the currently widths of fields.")
16352 (defvar org-columns-current-maxwidths nil
16353 "Loval variable, holds the currently active maximum column widths.")
16354 (defvar org-columns-begin-marker (make-marker)
16355 "Points to the position where last a column creation command was called.")
16356 (defvar org-columns-top-level-marker (make-marker)
16357 "Points to the position where current columns region starts.")
16359 (defvar org-columns-map (make-sparse-keymap)
16360 "The keymap valid in column display.")
16362 (defun org-columns-content ()
16363 "Switch to contents view while in columns view."
16364 (interactive)
16365 (org-overview)
16366 (org-content))
16368 (org-defkey org-columns-map "c" 'org-columns-content)
16369 (org-defkey org-columns-map "o" 'org-overview)
16370 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16371 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16372 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16373 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16374 (org-defkey org-columns-map "v" 'org-columns-show-value)
16375 (org-defkey org-columns-map "q" 'org-columns-quit)
16376 (org-defkey org-columns-map "r" 'org-columns-redo)
16377 (org-defkey org-columns-map "g" 'org-columns-redo)
16378 (org-defkey org-columns-map [left] 'backward-char)
16379 (org-defkey org-columns-map "\M-b" 'backward-char)
16380 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16381 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16382 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16383 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16384 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16385 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16386 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16387 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16388 (org-defkey org-columns-map "<" 'org-columns-narrow)
16389 (org-defkey org-columns-map ">" 'org-columns-widen)
16390 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16391 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16392 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16393 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16395 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16396 '("Column"
16397 ["Edit property" org-columns-edit-value t]
16398 ["Next allowed value" org-columns-next-allowed-value t]
16399 ["Previous allowed value" org-columns-previous-allowed-value t]
16400 ["Show full value" org-columns-show-value t]
16401 ["Edit allowed values" org-columns-edit-allowed t]
16402 "--"
16403 ["Edit column attributes" org-columns-edit-attributes t]
16404 ["Increase column width" org-columns-widen t]
16405 ["Decrease column width" org-columns-narrow t]
16406 "--"
16407 ["Move column right" org-columns-move-right t]
16408 ["Move column left" org-columns-move-left t]
16409 ["Add column" org-columns-new t]
16410 ["Delete column" org-columns-delete t]
16411 "--"
16412 ["CONTENTS" org-columns-content t]
16413 ["OVERVIEW" org-overview t]
16414 ["Refresh columns display" org-columns-redo t]
16415 "--"
16416 ["Open link" org-columns-open-link t]
16417 "--"
16418 ["Quit" org-columns-quit t]))
16420 (defun org-columns-new-overlay (beg end &optional string face)
16421 "Create a new column overlay and add it to the list."
16422 (let ((ov (org-make-overlay beg end)))
16423 (org-overlay-put ov 'face (or face 'secondary-selection))
16424 (org-overlay-display ov string face)
16425 (push ov org-columns-overlays)
16426 ov))
16428 (defun org-columns-display-here (&optional props)
16429 "Overlay the current line with column display."
16430 (interactive)
16431 (let* ((fmt org-columns-current-fmt-compiled)
16432 (beg (point-at-bol))
16433 (level-face (save-excursion
16434 (beginning-of-line 1)
16435 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16436 (org-get-level-face 2))))
16437 (color (list :foreground
16438 (face-attribute (or level-face 'default) :foreground)))
16439 props pom property ass width f string ov column val modval)
16440 ;; Check if the entry is in another buffer.
16441 (unless props
16442 (if (eq major-mode 'org-agenda-mode)
16443 (setq pom (or (get-text-property (point) 'org-hd-marker)
16444 (get-text-property (point) 'org-marker))
16445 props (if pom (org-entry-properties pom) nil))
16446 (setq props (org-entry-properties nil))))
16447 ;; Walk the format
16448 (while (setq column (pop fmt))
16449 (setq property (car column)
16450 ass (if (equal property "ITEM")
16451 (cons "ITEM"
16452 (save-match-data
16453 (org-no-properties
16454 (org-remove-tabs
16455 (buffer-substring-no-properties
16456 (point-at-bol) (point-at-eol))))))
16457 (assoc property props))
16458 width (or (cdr (assoc property org-columns-current-maxwidths))
16459 (nth 2 column)
16460 (length property))
16461 f (format "%%-%d.%ds | " width width)
16462 val (or (cdr ass) "")
16463 modval (if (equal property "ITEM")
16464 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16465 string (format f (or modval val)))
16466 ;; Create the overlay
16467 (org-unmodified
16468 (setq ov (org-columns-new-overlay
16469 beg (setq beg (1+ beg)) string
16470 (list color 'org-column)))
16471 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16472 (org-overlay-put ov 'keymap org-columns-map)
16473 (org-overlay-put ov 'org-columns-key property)
16474 (org-overlay-put ov 'org-columns-value (cdr ass))
16475 (org-overlay-put ov 'org-columns-value-modified modval)
16476 (org-overlay-put ov 'org-columns-pom pom)
16477 (org-overlay-put ov 'org-columns-format f))
16478 (if (or (not (char-after beg))
16479 (equal (char-after beg) ?\n))
16480 (let ((inhibit-read-only t))
16481 (save-excursion
16482 (goto-char beg)
16483 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16484 ;; Make the rest of the line disappear.
16485 (org-unmodified
16486 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16487 (org-overlay-put ov 'invisible t)
16488 (org-overlay-put ov 'keymap org-columns-map)
16489 (org-overlay-put ov 'intangible t)
16490 (push ov org-columns-overlays)
16491 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16492 (org-overlay-put ov 'keymap org-columns-map)
16493 (push ov org-columns-overlays)
16494 (let ((inhibit-read-only t))
16495 (put-text-property (max (point-min) (1- (point-at-bol)))
16496 (min (point-max) (1+ (point-at-eol)))
16497 'read-only "Type `e' to edit property")))))
16499 (defvar org-previous-header-line-format nil
16500 "The header line format before column view was turned on.")
16501 (defvar org-columns-inhibit-recalculation nil
16502 "Inhibit recomputing of columns on column view startup.")
16505 (defvar header-line-format)
16506 (defun org-columns-display-here-title ()
16507 "Overlay the newline before the current line with the table title."
16508 (interactive)
16509 (let ((fmt org-columns-current-fmt-compiled)
16510 string (title "")
16511 property width f column str widths)
16512 (while (setq column (pop fmt))
16513 (setq property (car column)
16514 str (or (nth 1 column) property)
16515 width (or (cdr (assoc property org-columns-current-maxwidths))
16516 (nth 2 column)
16517 (length str))
16518 widths (push width widths)
16519 f (format "%%-%d.%ds | " width width)
16520 string (format f str)
16521 title (concat title string)))
16522 (setq title (concat
16523 (org-add-props " " nil 'display '(space :align-to 0))
16524 (org-add-props title nil 'face '(:weight bold :underline t))))
16525 (org-set-local 'org-previous-header-line-format header-line-format)
16526 (org-set-local 'org-columns-current-widths (nreverse widths))
16527 (setq header-line-format title)))
16529 (defun org-columns-remove-overlays ()
16530 "Remove all currently active column overlays."
16531 (interactive)
16532 (when (marker-buffer org-columns-begin-marker)
16533 (with-current-buffer (marker-buffer org-columns-begin-marker)
16534 (when (local-variable-p 'org-previous-header-line-format)
16535 (setq header-line-format org-previous-header-line-format)
16536 (kill-local-variable 'org-previous-header-line-format))
16537 (move-marker org-columns-begin-marker nil)
16538 (move-marker org-columns-top-level-marker nil)
16539 (org-unmodified
16540 (mapc 'org-delete-overlay org-columns-overlays)
16541 (setq org-columns-overlays nil)
16542 (let ((inhibit-read-only t))
16543 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16545 (defun org-columns-cleanup-item (item fmt)
16546 "Remove from ITEM what is a column in the format FMT."
16547 (if (not org-complex-heading-regexp)
16548 item
16549 (when (string-match org-complex-heading-regexp item)
16550 (concat
16551 (org-add-props (concat (match-string 1 item) " ") nil
16552 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16553 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16554 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16555 " " (match-string 4 item)
16556 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16558 (defun org-columns-show-value ()
16559 "Show the full value of the property."
16560 (interactive)
16561 (let ((value (get-char-property (point) 'org-columns-value)))
16562 (message "Value is: %s" (or value ""))))
16564 (defun org-columns-quit ()
16565 "Remove the column overlays and in this way exit column editing."
16566 (interactive)
16567 (org-unmodified
16568 (org-columns-remove-overlays)
16569 (let ((inhibit-read-only t))
16570 (remove-text-properties (point-min) (point-max) '(read-only t))))
16571 (when (eq major-mode 'org-agenda-mode)
16572 (message
16573 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16575 (defun org-columns-check-computed ()
16576 "Check if this column value is computed.
16577 If yes, throw an error indicating that changing it does not make sense."
16578 (let ((val (get-char-property (point) 'org-columns-value)))
16579 (when (and (stringp val)
16580 (get-char-property 0 'org-computed val))
16581 (error "This value is computed from the entry's children"))))
16583 (defun org-columns-todo (&optional arg)
16584 "Change the TODO state during column view."
16585 (interactive "P")
16586 (org-columns-edit-value "TODO"))
16588 (defun org-columns-set-tags-or-toggle (&optional arg)
16589 "Toggle checkbox at point, or set tags for current headline."
16590 (interactive "P")
16591 (if (string-match "\\`\\[[ xX-]\\]\\'"
16592 (get-char-property (point) 'org-columns-value))
16593 (org-columns-next-allowed-value)
16594 (org-columns-edit-value "TAGS")))
16596 (defun org-columns-edit-value (&optional key)
16597 "Edit the value of the property at point in column view.
16598 Where possible, use the standard interface for changing this line."
16599 (interactive)
16600 (org-columns-check-computed)
16601 (let* ((external-key key)
16602 (col (current-column))
16603 (key (or key (get-char-property (point) 'org-columns-key)))
16604 (value (get-char-property (point) 'org-columns-value))
16605 (bol (point-at-bol)) (eol (point-at-eol))
16606 (pom (or (get-text-property bol 'org-hd-marker)
16607 (point))) ; keep despite of compiler waring
16608 (line-overlays
16609 (delq nil (mapcar (lambda (x)
16610 (and (eq (overlay-buffer x) (current-buffer))
16611 (>= (overlay-start x) bol)
16612 (<= (overlay-start x) eol)
16614 org-columns-overlays)))
16615 nval eval allowed)
16616 (cond
16617 ((equal key "CLOCKSUM")
16618 (error "This special column cannot be edited"))
16619 ((equal key "ITEM")
16620 (setq eval '(org-with-point-at pom
16621 (org-edit-headline))))
16622 ((equal key "TODO")
16623 (setq eval '(org-with-point-at pom
16624 (let ((current-prefix-arg
16625 (if external-key current-prefix-arg '(4))))
16626 (call-interactively 'org-todo)))))
16627 ((equal key "PRIORITY")
16628 (setq eval '(org-with-point-at pom
16629 (call-interactively 'org-priority))))
16630 ((equal key "TAGS")
16631 (setq eval '(org-with-point-at pom
16632 (let ((org-fast-tag-selection-single-key
16633 (if (eq org-fast-tag-selection-single-key 'expert)
16634 t org-fast-tag-selection-single-key)))
16635 (call-interactively 'org-set-tags)))))
16636 ((equal key "DEADLINE")
16637 (setq eval '(org-with-point-at pom
16638 (call-interactively 'org-deadline))))
16639 ((equal key "SCHEDULED")
16640 (setq eval '(org-with-point-at pom
16641 (call-interactively 'org-schedule))))
16643 (setq allowed (org-property-get-allowed-values pom key 'table))
16644 (if allowed
16645 (setq nval (completing-read "Value: " allowed nil t))
16646 (setq nval (read-string "Edit: " value)))
16647 (setq nval (org-trim nval))
16648 (when (not (equal nval value))
16649 (setq eval '(org-entry-put pom key nval)))))
16650 (when eval
16651 (let ((inhibit-read-only t))
16652 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16653 (unwind-protect
16654 (progn
16655 (setq org-columns-overlays
16656 (org-delete-all line-overlays org-columns-overlays))
16657 (mapc 'org-delete-overlay line-overlays)
16658 (org-columns-eval eval))
16659 (org-columns-display-here))))
16660 (move-to-column col)
16661 (if (and (org-mode-p)
16662 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16663 (org-columns-update key))))
16665 (defun org-edit-headline () ; FIXME: this is not columns specific
16666 "Edit the current headline, the part without TODO keyword, TAGS."
16667 (org-back-to-heading)
16668 (when (looking-at org-todo-line-regexp)
16669 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16670 (txt (match-string 3))
16671 (post "")
16672 txt2)
16673 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16674 (setq post (match-string 0 txt)
16675 txt (substring txt 0 (match-beginning 0))))
16676 (setq txt2 (read-string "Edit: " txt))
16677 (when (not (equal txt txt2))
16678 (beginning-of-line 1)
16679 (insert pre txt2 post)
16680 (delete-region (point) (point-at-eol))
16681 (org-set-tags nil t)))))
16683 (defun org-columns-edit-allowed ()
16684 "Edit the list of allowed values for the current property."
16685 (interactive)
16686 (let* ((key (get-char-property (point) 'org-columns-key))
16687 (key1 (concat key "_ALL"))
16688 (allowed (org-entry-get (point) key1 t))
16689 nval)
16690 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16691 (setq nval (read-string "Allowed: " allowed))
16692 (org-entry-put
16693 (cond ((marker-position org-entry-property-inherited-from)
16694 org-entry-property-inherited-from)
16695 ((marker-position org-columns-top-level-marker)
16696 org-columns-top-level-marker))
16697 key1 nval)))
16699 (defmacro org-no-warnings (&rest body)
16700 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16702 (defun org-columns-eval (form)
16703 (let (hidep)
16704 (save-excursion
16705 (beginning-of-line 1)
16706 ;; `next-line' is needed here, because it skips invisible line.
16707 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16708 (setq hidep (org-on-heading-p 1)))
16709 (eval form)
16710 (and hidep (hide-entry))))
16712 (defun org-columns-previous-allowed-value ()
16713 "Switch to the previous allowed value for this column."
16714 (interactive)
16715 (org-columns-next-allowed-value t))
16717 (defun org-columns-next-allowed-value (&optional previous)
16718 "Switch to the next allowed value for this column."
16719 (interactive)
16720 (org-columns-check-computed)
16721 (let* ((col (current-column))
16722 (key (get-char-property (point) 'org-columns-key))
16723 (value (get-char-property (point) 'org-columns-value))
16724 (bol (point-at-bol)) (eol (point-at-eol))
16725 (pom (or (get-text-property bol 'org-hd-marker)
16726 (point))) ; keep despite of compiler waring
16727 (line-overlays
16728 (delq nil (mapcar (lambda (x)
16729 (and (eq (overlay-buffer x) (current-buffer))
16730 (>= (overlay-start x) bol)
16731 (<= (overlay-start x) eol)
16733 org-columns-overlays)))
16734 (allowed (or (org-property-get-allowed-values pom key)
16735 (and (equal
16736 (nth 4 (assoc key org-columns-current-fmt-compiled))
16737 'checkbox) '("[ ]" "[X]"))))
16738 nval)
16739 (when (equal key "ITEM")
16740 (error "Cannot edit item headline from here"))
16741 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16742 (error "Allowed values for this property have not been defined"))
16743 (if (member key '("SCHEDULED" "DEADLINE"))
16744 (setq nval (if previous 'earlier 'later))
16745 (if previous (setq allowed (reverse allowed)))
16746 (if (member value allowed)
16747 (setq nval (car (cdr (member value allowed)))))
16748 (setq nval (or nval (car allowed)))
16749 (if (equal nval value)
16750 (error "Only one allowed value for this property")))
16751 (let ((inhibit-read-only t))
16752 (remove-text-properties (1- bol) eol '(read-only t))
16753 (unwind-protect
16754 (progn
16755 (setq org-columns-overlays
16756 (org-delete-all line-overlays org-columns-overlays))
16757 (mapc 'org-delete-overlay line-overlays)
16758 (org-columns-eval '(org-entry-put pom key nval)))
16759 (org-columns-display-here)))
16760 (move-to-column col)
16761 (if (and (org-mode-p)
16762 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16763 (org-columns-update key))))
16765 (defun org-verify-version (task)
16766 (cond
16767 ((eq task 'columns)
16768 (if (or (featurep 'xemacs)
16769 (< emacs-major-version 22))
16770 (error "Emacs 22 is required for the columns feature")))))
16772 (defun org-columns-open-link (&optional arg)
16773 (interactive "P")
16774 (let ((key (get-char-property (point) 'org-columns-key))
16775 (value (get-char-property (point) 'org-columns-value)))
16776 (org-open-link-from-string arg)))
16778 (defun org-open-link-from-string (s &optional arg)
16779 "Open a link in the string S, as if it was in Org-mode."
16780 (interactive)
16781 (with-temp-buffer
16782 (let ((org-inhibit-startup t))
16783 (org-mode)
16784 (insert s)
16785 (goto-char (point-min))
16786 (org-open-at-point arg))))
16788 (defun org-columns-get-format-and-top-level ()
16789 (let (fmt)
16790 (when (condition-case nil (org-back-to-heading) (error nil))
16791 (move-marker org-entry-property-inherited-from nil)
16792 (setq fmt (org-entry-get nil "COLUMNS" t)))
16793 (setq fmt (or fmt org-columns-default-format))
16794 (org-set-local 'org-columns-current-fmt fmt)
16795 (org-columns-compile-format fmt)
16796 (if (marker-position org-entry-property-inherited-from)
16797 (move-marker org-columns-top-level-marker
16798 org-entry-property-inherited-from)
16799 (move-marker org-columns-top-level-marker (point)))
16800 fmt))
16802 (defun org-columns ()
16803 "Turn on column view on an org-mode file."
16804 (interactive)
16805 (org-verify-version 'columns)
16806 (org-columns-remove-overlays)
16807 (move-marker org-columns-begin-marker (point))
16808 (let (beg end fmt cache maxwidths clocksump)
16809 (setq fmt (org-columns-get-format-and-top-level))
16810 (save-excursion
16811 (goto-char org-columns-top-level-marker)
16812 (setq beg (point))
16813 (unless org-columns-inhibit-recalculation
16814 (org-columns-compute-all))
16815 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16816 (point-max)))
16817 ;; Get and cache the properties
16818 (goto-char beg)
16819 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16820 (setq clocksump t)
16821 (save-excursion
16822 (save-restriction
16823 (narrow-to-region beg end)
16824 (org-clock-sum))))
16825 (while (re-search-forward (concat "^" outline-regexp) end t)
16826 (push (cons (org-current-line) (org-entry-properties)) cache))
16827 (when cache
16828 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16829 (org-set-local 'org-columns-current-maxwidths maxwidths)
16830 (org-columns-display-here-title)
16831 (mapc (lambda (x)
16832 (goto-line (car x))
16833 (org-columns-display-here (cdr x)))
16834 cache)))))
16836 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16837 "Insert a new column, to the leeft o the current column."
16838 (interactive)
16839 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16840 cell)
16841 (setq prop (completing-read
16842 "Property: " (mapcar 'list (org-buffer-property-keys t))
16843 nil nil prop))
16844 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16845 (setq width (read-string "Column width: " (if width (number-to-string width))))
16846 (if (string-match "\\S-" width)
16847 (setq width (string-to-number width))
16848 (setq width nil))
16849 (setq fmt (completing-read "Summary [none]: "
16850 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16851 nil t))
16852 (if (string-match "\\S-" fmt)
16853 (setq fmt (intern fmt))
16854 (setq fmt nil))
16855 (if (eq fmt 'none) (setq fmt nil))
16856 (if editp
16857 (progn
16858 (setcar editp prop)
16859 (setcdr editp (list title width nil fmt)))
16860 (setq cell (nthcdr (1- (current-column))
16861 org-columns-current-fmt-compiled))
16862 (setcdr cell (cons (list prop title width nil fmt)
16863 (cdr cell))))
16864 (org-columns-store-format)
16865 (org-columns-redo)))
16867 (defun org-columns-delete ()
16868 "Delete the column at point from columns view."
16869 (interactive)
16870 (let* ((n (current-column))
16871 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16872 (when (y-or-n-p
16873 (format "Are you sure you want to remove column \"%s\"? " title))
16874 (setq org-columns-current-fmt-compiled
16875 (delq (nth n org-columns-current-fmt-compiled)
16876 org-columns-current-fmt-compiled))
16877 (org-columns-store-format)
16878 (org-columns-redo)
16879 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16880 (backward-char 1)))))
16882 (defun org-columns-edit-attributes ()
16883 "Edit the attributes of the current column."
16884 (interactive)
16885 (let* ((n (current-column))
16886 (info (nth n org-columns-current-fmt-compiled)))
16887 (apply 'org-columns-new info)))
16889 (defun org-columns-widen (arg)
16890 "Make the column wider by ARG characters."
16891 (interactive "p")
16892 (let* ((n (current-column))
16893 (entry (nth n org-columns-current-fmt-compiled))
16894 (width (or (nth 2 entry)
16895 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16896 (setq width (max 1 (+ width arg)))
16897 (setcar (nthcdr 2 entry) width)
16898 (org-columns-store-format)
16899 (org-columns-redo)))
16901 (defun org-columns-narrow (arg)
16902 "Make the column nrrower by ARG characters."
16903 (interactive "p")
16904 (org-columns-widen (- arg)))
16906 (defun org-columns-move-right ()
16907 "Swap this column with the one to the right."
16908 (interactive)
16909 (let* ((n (current-column))
16910 (cell (nthcdr n org-columns-current-fmt-compiled))
16912 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16913 (error "Cannot shift this column further to the right"))
16914 (setq e (car cell))
16915 (setcar cell (car (cdr cell)))
16916 (setcdr cell (cons e (cdr (cdr cell))))
16917 (org-columns-store-format)
16918 (org-columns-redo)
16919 (forward-char 1)))
16921 (defun org-columns-move-left ()
16922 "Swap this column with the one to the left."
16923 (interactive)
16924 (let* ((n (current-column)))
16925 (when (= n 0)
16926 (error "Cannot shift this column further to the left"))
16927 (backward-char 1)
16928 (org-columns-move-right)
16929 (backward-char 1)))
16931 (defun org-columns-store-format ()
16932 "Store the text version of the current columns format in appropriate place.
16933 This is either in the COLUMNS property of the node starting the current column
16934 display, or in the #+COLUMNS line of the current buffer."
16935 (let (fmt (cnt 0))
16936 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16937 (org-set-local 'org-columns-current-fmt fmt)
16938 (if (marker-position org-columns-top-level-marker)
16939 (save-excursion
16940 (goto-char org-columns-top-level-marker)
16941 (if (and (org-at-heading-p)
16942 (org-entry-get nil "COLUMNS"))
16943 (org-entry-put nil "COLUMNS" fmt)
16944 (goto-char (point-min))
16945 ;; Overwrite all #+COLUMNS lines....
16946 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16947 (setq cnt (1+ cnt))
16948 (replace-match (concat "#+COLUMNS: " fmt) t t))
16949 (unless (> cnt 0)
16950 (goto-char (point-min))
16951 (or (org-on-heading-p t) (outline-next-heading))
16952 (let ((inhibit-read-only t))
16953 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16954 (org-set-local 'org-columns-default-format fmt))))))
16956 (defvar org-overriding-columns-format nil
16957 "When set, overrides any other definition.")
16958 (defvar org-agenda-view-columns-initially nil
16959 "When set, switch to columns view immediately after creating the agenda.")
16961 (defun org-agenda-columns ()
16962 "Turn on column view in the agenda."
16963 (interactive)
16964 (org-verify-version 'columns)
16965 (org-columns-remove-overlays)
16966 (move-marker org-columns-begin-marker (point))
16967 (let (fmt cache maxwidths m)
16968 (cond
16969 ((and (local-variable-p 'org-overriding-columns-format)
16970 org-overriding-columns-format)
16971 (setq fmt org-overriding-columns-format))
16972 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16973 (setq fmt (org-entry-get m "COLUMNS" t)))
16974 ((and (boundp 'org-columns-current-fmt)
16975 (local-variable-p 'org-columns-current-fmt)
16976 org-columns-current-fmt)
16977 (setq fmt org-columns-current-fmt))
16978 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16979 (setq m (get-text-property m 'org-hd-marker))
16980 (setq fmt (org-entry-get m "COLUMNS" t))))
16981 (setq fmt (or fmt org-columns-default-format))
16982 (org-set-local 'org-columns-current-fmt fmt)
16983 (org-columns-compile-format fmt)
16984 (save-excursion
16985 ;; Get and cache the properties
16986 (goto-char (point-min))
16987 (while (not (eobp))
16988 (when (setq m (or (get-text-property (point) 'org-hd-marker)
16989 (get-text-property (point) 'org-marker)))
16990 (push (cons (org-current-line) (org-entry-properties m)) cache))
16991 (beginning-of-line 2))
16992 (when cache
16993 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16994 (org-set-local 'org-columns-current-maxwidths maxwidths)
16995 (org-columns-display-here-title)
16996 (mapc (lambda (x)
16997 (goto-line (car x))
16998 (org-columns-display-here (cdr x)))
16999 cache)))))
17001 (defun org-columns-get-autowidth-alist (s cache)
17002 "Derive the maximum column widths from the format and the cache."
17003 (let ((start 0) rtn)
17004 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
17005 (push (cons (match-string 1 s) 1) rtn)
17006 (setq start (match-end 0)))
17007 (mapc (lambda (x)
17008 (setcdr x (apply 'max
17009 (mapcar
17010 (lambda (y)
17011 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17012 cache))))
17013 rtn)
17014 rtn))
17016 (defun org-columns-compute-all ()
17017 "Compute all columns that have operators defined."
17018 (org-unmodified
17019 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17020 (let ((columns org-columns-current-fmt-compiled) col)
17021 (while (setq col (pop columns))
17022 (when (nth 3 col)
17023 (save-excursion
17024 (org-columns-compute (car col)))))))
17026 (defun org-columns-update (property)
17027 "Recompute PROPERTY, and update the columns display for it."
17028 (org-columns-compute property)
17029 (let (fmt val pos)
17030 (save-excursion
17031 (mapc (lambda (ov)
17032 (when (equal (org-overlay-get ov 'org-columns-key) property)
17033 (setq pos (org-overlay-start ov))
17034 (goto-char pos)
17035 (when (setq val (cdr (assoc property
17036 (get-text-property
17037 (point-at-bol) 'org-summaries))))
17038 (setq fmt (org-overlay-get ov 'org-columns-format))
17039 (org-overlay-put ov 'org-columns-value val)
17040 (org-overlay-put ov 'display (format fmt val)))))
17041 org-columns-overlays))))
17043 (defun org-columns-compute (property)
17044 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17045 (interactive)
17046 (let* ((re (concat "^" outline-regexp))
17047 (lmax 30) ; Does anyone use deeper levels???
17048 (lsum (make-vector lmax 0))
17049 (lflag (make-vector lmax nil))
17050 (level 0)
17051 (ass (assoc property org-columns-current-fmt-compiled))
17052 (format (nth 4 ass))
17053 (printf (nth 5 ass))
17054 (beg org-columns-top-level-marker)
17055 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17056 (save-excursion
17057 ;; Find the region to compute
17058 (goto-char beg)
17059 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17060 (goto-char end)
17061 ;; Walk the tree from the back and do the computations
17062 (while (re-search-backward re beg t)
17063 (setq sumpos (match-beginning 0)
17064 last-level level
17065 level (org-outline-level)
17066 val (org-entry-get nil property)
17067 valflag (and val (string-match "\\S-" val)))
17068 (cond
17069 ((< level last-level)
17070 ;; put the sum of lower levels here as a property
17071 (setq sum (aref lsum last-level) ; current sum
17072 flag (aref lflag last-level) ; any valid entries from children?
17073 str (org-column-number-to-string sum format printf)
17074 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17075 useval (if flag str1 (if valflag val ""))
17076 sum-alist (get-text-property sumpos 'org-summaries))
17077 (if (assoc property sum-alist)
17078 (setcdr (assoc property sum-alist) useval)
17079 (push (cons property useval) sum-alist)
17080 (org-unmodified
17081 (add-text-properties sumpos (1+ sumpos)
17082 (list 'org-summaries sum-alist))))
17083 (when val
17084 (org-entry-put nil property (if flag str val)))
17085 ;; add current to current level accumulator
17086 (when (or flag valflag)
17087 (aset lsum level (+ (aref lsum level)
17088 (if flag sum (org-column-string-to-number
17089 (if flag str val) format))))
17090 (aset lflag level t))
17091 ;; clear accumulators for deeper levels
17092 (loop for l from (1+ level) to (1- lmax) do
17093 (aset lsum l 0)
17094 (aset lflag l nil)))
17095 ((>= level last-level)
17096 ;; add what we have here to the accumulator for this level
17097 (aset lsum level (+ (aref lsum level)
17098 (org-column-string-to-number (or val "0") format)))
17099 (and valflag (aset lflag level t)))
17100 (t (error "This should not happen")))))))
17102 (defun org-columns-redo ()
17103 "Construct the column display again."
17104 (interactive)
17105 (message "Recomputing columns...")
17106 (save-excursion
17107 (if (marker-position org-columns-begin-marker)
17108 (goto-char org-columns-begin-marker))
17109 (org-columns-remove-overlays)
17110 (if (org-mode-p)
17111 (call-interactively 'org-columns)
17112 (call-interactively 'org-agenda-columns)))
17113 (message "Recomputing columns...done"))
17115 (defun org-columns-not-in-agenda ()
17116 (if (eq major-mode 'org-agenda-mode)
17117 (error "This command is only allowed in Org-mode buffers")))
17120 (defun org-string-to-number (s)
17121 "Convert string to number, and interpret hh:mm:ss."
17122 (if (not (string-match ":" s))
17123 (string-to-number s)
17124 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17125 (while l
17126 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17127 sum)))
17129 (defun org-column-number-to-string (n fmt &optional printf)
17130 "Convert a computed column number to a string value, according to FMT."
17131 (cond
17132 ((eq fmt 'add_times)
17133 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17134 (format "%d:%02d" h m)))
17135 ((eq fmt 'checkbox)
17136 (cond ((= n (floor n)) "[X]")
17137 ((> n 1.) "[-]")
17138 (t "[ ]")))
17139 (printf (format printf n))
17140 ((eq fmt 'currency)
17141 (format "%.2f" n))
17142 (t (number-to-string n))))
17144 (defun org-column-string-to-number (s fmt)
17145 "Convert a column value to a number that can be used for column computing."
17146 (cond
17147 ((string-match ":" s)
17148 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17149 (while l
17150 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17151 sum))
17152 ((eq fmt 'checkbox)
17153 (if (equal s "[X]") 1. 0.000001))
17154 (t (string-to-number s))))
17156 (defun org-columns-uncompile-format (cfmt)
17157 "Turn the compiled columns format back into a string representation."
17158 (let ((rtn "") e s prop title op width fmt printf)
17159 (while (setq e (pop cfmt))
17160 (setq prop (car e)
17161 title (nth 1 e)
17162 width (nth 2 e)
17163 op (nth 3 e)
17164 fmt (nth 4 e)
17165 printf (nth 5 e))
17166 (cond
17167 ((eq fmt 'add_times) (setq op ":"))
17168 ((eq fmt 'checkbox) (setq op "X"))
17169 ((eq fmt 'add_numbers) (setq op "+"))
17170 ((eq fmt 'currency) (setq op "$")))
17171 (if (and op printf) (setq op (concat op ";" printf)))
17172 (if (equal title prop) (setq title nil))
17173 (setq s (concat "%" (if width (number-to-string width))
17174 prop
17175 (if title (concat "(" title ")"))
17176 (if op (concat "{" op "}"))))
17177 (setq rtn (concat rtn " " s)))
17178 (org-trim rtn)))
17180 (defun org-columns-compile-format (fmt)
17181 "Turn a column format string into an alist of specifications.
17182 The alist has one entry for each column in the format. The elements of
17183 that list are:
17184 property the property
17185 title the title field for the columns
17186 width the column width in characters, can be nil for automatic
17187 operator the operator if any
17188 format the output format for computed results, derived from operator
17189 printf a printf format for computed values"
17190 (let ((start 0) width prop title op f printf)
17191 (setq org-columns-current-fmt-compiled nil)
17192 (while (string-match
17193 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17194 fmt start)
17195 (setq start (match-end 0)
17196 width (match-string 1 fmt)
17197 prop (match-string 2 fmt)
17198 title (or (match-string 3 fmt) prop)
17199 op (match-string 4 fmt)
17200 f nil
17201 printf nil)
17202 (if width (setq width (string-to-number width)))
17203 (when (and op (string-match ";" op))
17204 (setq printf (substring op (match-end 0))
17205 op (substring op 0 (match-beginning 0))))
17206 (cond
17207 ((equal op "+") (setq f 'add_numbers))
17208 ((equal op "$") (setq f 'currency))
17209 ((equal op ":") (setq f 'add_times))
17210 ((equal op "X") (setq f 'checkbox)))
17211 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17212 (setq org-columns-current-fmt-compiled
17213 (nreverse org-columns-current-fmt-compiled))))
17216 ;;; Dynamic block for Column view
17218 (defun org-columns-capture-view ()
17219 "Get the column view of the current buffer and return it as a list.
17220 The list will contains the title row and all other rows. Each row is
17221 a list of fields."
17222 (save-excursion
17223 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17224 (n (length title)) row tbl)
17225 (goto-char (point-min))
17226 (while (re-search-forward "^\\*+ " nil t)
17227 (when (get-char-property (match-beginning 0) 'org-columns-key)
17228 (setq row nil)
17229 (loop for i from 0 to (1- n) do
17230 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17231 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17233 row))
17234 (setq row (nreverse row))
17235 (push row tbl)))
17236 (append (list title 'hline) (nreverse tbl)))))
17238 (defun org-dblock-write:columnview (params)
17239 "Write the column view table.
17240 PARAMS is a property list of parameters:
17242 :width enforce same column widths with <N> specifiers.
17243 :id the :ID: property of the entry where the columns view
17244 should be built, as a string. When `local', call locally.
17245 When `global' call column view with the cursor at the beginning
17246 of the buffer (usually this means that the whole buffer switches
17247 to column view).
17248 :hlines When t, insert a hline before each item. When a number, insert
17249 a hline before each level <= that number.
17250 :vlines When t, make each column a colgroup to enforce vertical lines."
17251 (let ((pos (move-marker (make-marker) (point)))
17252 (hlines (plist-get params :hlines))
17253 (vlines (plist-get params :vlines))
17254 tbl id idpos nfields tmp)
17255 (save-excursion
17256 (save-restriction
17257 (when (setq id (plist-get params :id))
17258 (cond ((not id) nil)
17259 ((eq id 'global) (goto-char (point-min)))
17260 ((eq id 'local) nil)
17261 ((setq idpos (org-find-entry-with-id id))
17262 (goto-char idpos))
17263 (t (error "Cannot find entry with :ID: %s" id))))
17264 (org-columns)
17265 (setq tbl (org-columns-capture-view))
17266 (setq nfields (length (car tbl)))
17267 (org-columns-quit)))
17268 (goto-char pos)
17269 (move-marker pos nil)
17270 (when tbl
17271 (when (plist-get params :hlines)
17272 (setq tmp nil)
17273 (while tbl
17274 (if (eq (car tbl) 'hline)
17275 (push (pop tbl) tmp)
17276 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17277 (if (and (not (eq (car tmp) 'hline))
17278 (or (eq hlines t)
17279 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17280 (push 'hline tmp)))
17281 (push (pop tbl) tmp)))
17282 (setq tbl (nreverse tmp)))
17283 (when vlines
17284 (setq tbl (mapcar (lambda (x)
17285 (if (eq 'hline x) x (cons "" x)))
17286 tbl))
17287 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17288 (setq pos (point))
17289 (insert (org-listtable-to-string tbl))
17290 (when (plist-get params :width)
17291 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17292 org-columns-current-widths "|")))
17293 (goto-char pos)
17294 (org-table-align))))
17296 (defun org-listtable-to-string (tbl)
17297 "Convert a listtable TBL to a string that contains the Org-mode table.
17298 The table still need to be alligned. The resulting string has no leading
17299 and tailing newline characters."
17300 (mapconcat
17301 (lambda (x)
17302 (cond
17303 ((listp x)
17304 (concat "|" (mapconcat 'identity x "|") "|"))
17305 ((eq x 'hline) "|-|")
17306 (t (error "Garbage in listtable: %s" x))))
17307 tbl "\n"))
17309 (defun org-insert-columns-dblock ()
17310 "Create a dynamic block capturing a column view table."
17311 (interactive)
17312 (let ((defaults '(:name "columnview" :hlines 1))
17313 (id (completing-read
17314 "Capture columns (local, global, entry with :ID: property) [local]: "
17315 (append '(("global") ("local"))
17316 (mapcar 'list (org-property-values "ID"))))))
17317 (if (equal id "") (setq id 'local))
17318 (if (equal id "global") (setq id 'global))
17319 (setq defaults (append defaults (list :id id)))
17320 (org-create-dblock defaults)
17321 (org-update-dblock)))
17323 ;;;; Timestamps
17325 (defvar org-last-changed-timestamp nil)
17326 (defvar org-time-was-given) ; dynamically scoped parameter
17327 (defvar org-end-time-was-given) ; dynamically scoped parameter
17328 (defvar org-ts-what) ; dynamically scoped parameter
17330 (defun org-time-stamp (arg)
17331 "Prompt for a date/time and insert a time stamp.
17332 If the user specifies a time like HH:MM, or if this command is called
17333 with a prefix argument, the time stamp will contain date and time.
17334 Otherwise, only the date will be included. All parts of a date not
17335 specified by the user will be filled in from the current date/time.
17336 So if you press just return without typing anything, the time stamp
17337 will represent the current date/time. If there is already a timestamp
17338 at the cursor, it will be modified."
17339 (interactive "P")
17340 (let* ((ts nil)
17341 (default-time
17342 ;; Default time is either today, or, when entering a range,
17343 ;; the range start.
17344 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17345 (save-excursion
17346 (re-search-backward
17347 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17348 (- (point) 20) t)))
17349 (apply 'encode-time (org-parse-time-string (match-string 1)))
17350 (current-time)))
17351 (default-input (and ts (org-get-compact-tod ts)))
17352 org-time-was-given org-end-time-was-given time)
17353 (cond
17354 ((and (org-at-timestamp-p)
17355 (eq last-command 'org-time-stamp)
17356 (eq this-command 'org-time-stamp))
17357 (insert "--")
17358 (setq time (let ((this-command this-command))
17359 (org-read-date arg 'totime nil nil default-time default-input)))
17360 (org-insert-time-stamp time (or org-time-was-given arg)))
17361 ((org-at-timestamp-p)
17362 (setq time (let ((this-command this-command))
17363 (org-read-date arg 'totime nil nil default-time default-input)))
17364 (when (org-at-timestamp-p) ; just to get the match data
17365 (replace-match "")
17366 (setq org-last-changed-timestamp
17367 (org-insert-time-stamp
17368 time (or org-time-was-given arg)
17369 nil nil nil (list org-end-time-was-given))))
17370 (message "Timestamp updated"))
17372 (setq time (let ((this-command this-command))
17373 (org-read-date arg 'totime nil nil default-time default-input)))
17374 (org-insert-time-stamp time (or org-time-was-given arg)
17375 nil nil nil (list org-end-time-was-given))))))
17377 ;; FIXME: can we use this for something else????
17378 ;; like computing time differences?????
17379 (defun org-get-compact-tod (s)
17380 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17381 (let* ((t1 (match-string 1 s))
17382 (h1 (string-to-number (match-string 2 s)))
17383 (m1 (string-to-number (match-string 3 s)))
17384 (t2 (and (match-end 4) (match-string 5 s)))
17385 (h2 (and t2 (string-to-number (match-string 6 s))))
17386 (m2 (and t2 (string-to-number (match-string 7 s))))
17387 dh dm)
17388 (if (not t2)
17390 (setq dh (- h2 h1) dm (- m2 m1))
17391 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17392 (concat t1 "+" (number-to-string dh)
17393 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17395 (defun org-time-stamp-inactive (&optional arg)
17396 "Insert an inactive time stamp.
17397 An inactive time stamp is enclosed in square brackets instead of angle
17398 brackets. It is inactive in the sense that it does not trigger agenda entries,
17399 does not link to the calendar and cannot be changed with the S-cursor keys.
17400 So these are more for recording a certain time/date."
17401 (interactive "P")
17402 (let (org-time-was-given org-end-time-was-given time)
17403 (setq time (org-read-date arg 'totime))
17404 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17405 nil nil (list org-end-time-was-given))))
17407 (defvar org-date-ovl (org-make-overlay 1 1))
17408 (org-overlay-put org-date-ovl 'face 'org-warning)
17409 (org-detach-overlay org-date-ovl)
17411 (defvar org-ans1) ; dynamically scoped parameter
17412 (defvar org-ans2) ; dynamically scoped parameter
17414 (defvar org-plain-time-of-day-regexp) ; defined below
17416 (defvar org-read-date-overlay nil)
17417 (defvar org-dcst nil) ; dynamically scoped
17419 (defun org-read-date (&optional with-time to-time from-string prompt
17420 default-time default-input)
17421 "Read a date, possibly a time, and make things smooth for the user.
17422 The prompt will suggest to enter an ISO date, but you can also enter anything
17423 which will at least partially be understood by `parse-time-string'.
17424 Unrecognized parts of the date will default to the current day, month, year,
17425 hour and minute. If this command is called to replace a timestamp at point,
17426 of to enter the second timestamp of a range, the default time is taken from the
17427 existing stamp. For example,
17428 3-2-5 --> 2003-02-05
17429 feb 15 --> currentyear-02-15
17430 sep 12 9 --> 2009-09-12
17431 12:45 --> today 12:45
17432 22 sept 0:34 --> currentyear-09-22 0:34
17433 12 --> currentyear-currentmonth-12
17434 Fri --> nearest Friday (today or later)
17435 etc.
17437 Furthermore you can specify a relative date by giving, as the *first* thing
17438 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17439 change in days weeks, months, years.
17440 With a single plus or minus, the date is relative to today. With a double
17441 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17442 +4d --> four days from today
17443 +4 --> same as above
17444 +2w --> two weeks from today
17445 ++5 --> five days from default date
17447 The function understands only English month and weekday abbreviations,
17448 but this can be configured with the variables `parse-time-months' and
17449 `parse-time-weekdays'.
17451 While prompting, a calendar is popped up - you can also select the
17452 date with the mouse (button 1). The calendar shows a period of three
17453 months. To scroll it to other months, use the keys `>' and `<'.
17454 If you don't like the calendar, turn it off with
17455 \(setq org-read-date-popup-calendar nil)
17457 With optional argument TO-TIME, the date will immediately be converted
17458 to an internal time.
17459 With an optional argument WITH-TIME, the prompt will suggest to also
17460 insert a time. Note that when WITH-TIME is not set, you can still
17461 enter a time, and this function will inform the calling routine about
17462 this change. The calling routine may then choose to change the format
17463 used to insert the time stamp into the buffer to include the time.
17464 With optional argument FROM-STRING, read from this string instead from
17465 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17466 the time/date that is used for everything that is not specified by the
17467 user."
17468 (require 'parse-time)
17469 (let* ((org-time-stamp-rounding-minutes
17470 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17471 (org-dcst org-display-custom-times)
17472 (ct (org-current-time))
17473 (def (or default-time ct))
17474 (defdecode (decode-time def))
17475 (dummy (progn
17476 (when (< (nth 2 defdecode) org-extend-today-until)
17477 (setcar (nthcdr 2 defdecode) -1)
17478 (setcar (nthcdr 1 defdecode) 59)
17479 (setq def (apply 'encode-time defdecode)
17480 defdecode (decode-time def)))))
17481 (calendar-move-hook nil)
17482 (view-diary-entries-initially nil)
17483 (view-calendar-holidays-initially nil)
17484 (timestr (format-time-string
17485 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17486 (prompt (concat (if prompt (concat prompt " ") "")
17487 (format "Date+time [%s]: " timestr)))
17488 ans (org-ans0 "") org-ans1 org-ans2 final)
17490 (cond
17491 (from-string (setq ans from-string))
17492 (org-read-date-popup-calendar
17493 (save-excursion
17494 (save-window-excursion
17495 (calendar)
17496 (calendar-forward-day (- (time-to-days def)
17497 (calendar-absolute-from-gregorian
17498 (calendar-current-date))))
17499 (org-eval-in-calendar nil t)
17500 (let* ((old-map (current-local-map))
17501 (map (copy-keymap calendar-mode-map))
17502 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17503 (org-defkey map (kbd "RET") 'org-calendar-select)
17504 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17505 'org-calendar-select-mouse)
17506 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17507 'org-calendar-select-mouse)
17508 (org-defkey minibuffer-local-map [(meta shift left)]
17509 (lambda () (interactive)
17510 (org-eval-in-calendar '(calendar-backward-month 1))))
17511 (org-defkey minibuffer-local-map [(meta shift right)]
17512 (lambda () (interactive)
17513 (org-eval-in-calendar '(calendar-forward-month 1))))
17514 (org-defkey minibuffer-local-map [(meta shift up)]
17515 (lambda () (interactive)
17516 (org-eval-in-calendar '(calendar-backward-year 1))))
17517 (org-defkey minibuffer-local-map [(meta shift down)]
17518 (lambda () (interactive)
17519 (org-eval-in-calendar '(calendar-forward-year 1))))
17520 (org-defkey minibuffer-local-map [(shift up)]
17521 (lambda () (interactive)
17522 (org-eval-in-calendar '(calendar-backward-week 1))))
17523 (org-defkey minibuffer-local-map [(shift down)]
17524 (lambda () (interactive)
17525 (org-eval-in-calendar '(calendar-forward-week 1))))
17526 (org-defkey minibuffer-local-map [(shift left)]
17527 (lambda () (interactive)
17528 (org-eval-in-calendar '(calendar-backward-day 1))))
17529 (org-defkey minibuffer-local-map [(shift right)]
17530 (lambda () (interactive)
17531 (org-eval-in-calendar '(calendar-forward-day 1))))
17532 (org-defkey minibuffer-local-map ">"
17533 (lambda () (interactive)
17534 (org-eval-in-calendar '(scroll-calendar-left 1))))
17535 (org-defkey minibuffer-local-map "<"
17536 (lambda () (interactive)
17537 (org-eval-in-calendar '(scroll-calendar-right 1))))
17538 (unwind-protect
17539 (progn
17540 (use-local-map map)
17541 (add-hook 'post-command-hook 'org-read-date-display)
17542 (setq org-ans0 (read-string prompt default-input nil nil))
17543 ;; org-ans0: from prompt
17544 ;; org-ans1: from mouse click
17545 ;; org-ans2: from calendar motion
17546 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17547 (remove-hook 'post-command-hook 'org-read-date-display)
17548 (use-local-map old-map)
17549 (when org-read-date-overlay
17550 (org-delete-overlay org-read-date-overlay)
17551 (setq org-read-date-overlay nil)))))))
17553 (t ; Naked prompt only
17554 (unwind-protect
17555 (setq ans (read-string prompt default-input nil timestr))
17556 (when org-read-date-overlay
17557 (org-delete-overlay org-read-date-overlay)
17558 (setq org-read-date-overlay nil)))))
17560 (setq final (org-read-date-analyze ans def defdecode))
17562 (if to-time
17563 (apply 'encode-time final)
17564 (if (and (boundp 'org-time-was-given) org-time-was-given)
17565 (format "%04d-%02d-%02d %02d:%02d"
17566 (nth 5 final) (nth 4 final) (nth 3 final)
17567 (nth 2 final) (nth 1 final))
17568 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17569 (defvar def)
17570 (defvar defdecode)
17571 (defvar with-time)
17572 (defun org-read-date-display ()
17573 "Display the currrent date prompt interpretation in the minibuffer."
17574 (when org-read-date-display-live
17575 (when org-read-date-overlay
17576 (org-delete-overlay org-read-date-overlay))
17577 (let ((p (point)))
17578 (end-of-line 1)
17579 (while (not (equal (buffer-substring
17580 (max (point-min) (- (point) 4)) (point))
17581 " "))
17582 (insert " "))
17583 (goto-char p))
17584 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17585 " " (or org-ans1 org-ans2)))
17586 (org-end-time-was-given nil)
17587 (f (org-read-date-analyze ans def defdecode))
17588 (fmts (if org-dcst
17589 org-time-stamp-custom-formats
17590 org-time-stamp-formats))
17591 (fmt (if (or with-time
17592 (and (boundp 'org-time-was-given) org-time-was-given))
17593 (cdr fmts)
17594 (car fmts)))
17595 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17596 (when (and org-end-time-was-given
17597 (string-match org-plain-time-of-day-regexp txt))
17598 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17599 org-end-time-was-given
17600 (substring txt (match-end 0)))))
17601 (setq org-read-date-overlay
17602 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17603 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17605 (defun org-read-date-analyze (ans def defdecode)
17606 "Analyze the combined answer of the date prompt."
17607 ;; FIXME: cleanup and comment
17608 (let (delta deltan deltaw deltadef year month day
17609 hour minute second wday pm h2 m2 tl wday1)
17611 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17612 (setq ans (replace-match "" t t ans)
17613 deltan (car delta)
17614 deltaw (nth 1 delta)
17615 deltadef (nth 2 delta)))
17617 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17618 (when (string-match
17619 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17620 (setq year (if (match-end 2)
17621 (string-to-number (match-string 2 ans))
17622 (string-to-number (format-time-string "%Y")))
17623 month (string-to-number (match-string 3 ans))
17624 day (string-to-number (match-string 4 ans)))
17625 (if (< year 100) (setq year (+ 2000 year)))
17626 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17627 t nil ans)))
17628 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17629 ;; If there is a time with am/pm, and *no* time without it, we convert
17630 ;; so that matching will be successful.
17631 (loop for i from 1 to 2 do ; twice, for end time as well
17632 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17633 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17634 (setq hour (string-to-number (match-string 1 ans))
17635 minute (if (match-end 3)
17636 (string-to-number (match-string 3 ans))
17638 pm (equal ?p
17639 (string-to-char (downcase (match-string 4 ans)))))
17640 (if (and (= hour 12) (not pm))
17641 (setq hour 0)
17642 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17643 (setq ans (replace-match (format "%02d:%02d" hour minute)
17644 t t ans))))
17646 ;; Check if a time range is given as a duration
17647 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17648 (setq hour (string-to-number (match-string 1 ans))
17649 h2 (+ hour (string-to-number (match-string 3 ans)))
17650 minute (string-to-number (match-string 2 ans))
17651 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17652 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17653 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17655 ;; Check if there is a time range
17656 (when (boundp 'org-end-time-was-given)
17657 (setq org-time-was-given nil)
17658 (when (and (string-match org-plain-time-of-day-regexp ans)
17659 (match-end 8))
17660 (setq org-end-time-was-given (match-string 8 ans))
17661 (setq ans (concat (substring ans 0 (match-beginning 7))
17662 (substring ans (match-end 7))))))
17664 (setq tl (parse-time-string ans)
17665 day (or (nth 3 tl) (nth 3 defdecode))
17666 month (or (nth 4 tl)
17667 (if (and org-read-date-prefer-future
17668 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17669 (1+ (nth 4 defdecode))
17670 (nth 4 defdecode)))
17671 year (or (nth 5 tl)
17672 (if (and org-read-date-prefer-future
17673 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17674 (1+ (nth 5 defdecode))
17675 (nth 5 defdecode)))
17676 hour (or (nth 2 tl) (nth 2 defdecode))
17677 minute (or (nth 1 tl) (nth 1 defdecode))
17678 second (or (nth 0 tl) 0)
17679 wday (nth 6 tl))
17680 (when deltan
17681 (unless deltadef
17682 (let ((now (decode-time (current-time))))
17683 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17684 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17685 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17686 ((equal deltaw "m") (setq month (+ month deltan)))
17687 ((equal deltaw "y") (setq year (+ year deltan)))))
17688 (when (and wday (not (nth 3 tl)))
17689 ;; Weekday was given, but no day, so pick that day in the week
17690 ;; on or after the derived date.
17691 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17692 (unless (equal wday wday1)
17693 (setq day (+ day (% (- wday wday1 -7) 7)))))
17694 (if (and (boundp 'org-time-was-given)
17695 (nth 2 tl))
17696 (setq org-time-was-given t))
17697 (if (< year 100) (setq year (+ 2000 year)))
17698 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17699 (list second minute hour day month year)))
17701 (defvar parse-time-weekdays)
17703 (defun org-read-date-get-relative (s today default)
17704 "Check string S for special relative date string.
17705 TODAY and DEFAULT are internal times, for today and for a default.
17706 Return shift list (N what def-flag)
17707 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17708 N is the number of WHATs to shift.
17709 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17710 the DEFAULT date rather than TODAY."
17711 (when (string-match
17712 (concat
17713 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17714 "\\([0-9]+\\)?"
17715 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17716 "\\([ \t]\\|$\\)") s)
17717 (let* ((dir (if (match-end 1)
17718 (string-to-char (substring (match-string 1 s) -1))
17719 ?+))
17720 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17721 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17722 (what (if (match-end 3) (match-string 3 s) "d"))
17723 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17724 (date (if rel default today))
17725 (wday (nth 6 (decode-time date)))
17726 delta)
17727 (if wday1
17728 (progn
17729 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17730 (if (= dir ?-) (setq delta (- delta 7)))
17731 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17732 (list delta "d" rel))
17733 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17735 (defun org-eval-in-calendar (form &optional keepdate)
17736 "Eval FORM in the calendar window and return to current window.
17737 Also, store the cursor date in variable org-ans2."
17738 (let ((sw (selected-window)))
17739 (select-window (get-buffer-window "*Calendar*"))
17740 (eval form)
17741 (when (and (not keepdate) (calendar-cursor-to-date))
17742 (let* ((date (calendar-cursor-to-date))
17743 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17744 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17745 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17746 (select-window sw)))
17748 ; ;; Update the prompt to show new default date
17749 ; (save-excursion
17750 ; (goto-char (point-min))
17751 ; (when (and org-ans2
17752 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17753 ; (get-text-property (match-end 0) 'field))
17754 ; (let ((inhibit-read-only t))
17755 ; (replace-match (concat "[" org-ans2 "]") t t)
17756 ; (add-text-properties (point-min) (1+ (match-end 0))
17757 ; (text-properties-at (1+ (point-min)))))))))
17759 (defun org-calendar-select ()
17760 "Return to `org-read-date' with the date currently selected.
17761 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17762 (interactive)
17763 (when (calendar-cursor-to-date)
17764 (let* ((date (calendar-cursor-to-date))
17765 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17766 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17767 (if (active-minibuffer-window) (exit-minibuffer))))
17769 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17770 "Insert a date stamp for the date given by the internal TIME.
17771 WITH-HM means, use the stamp format that includes the time of the day.
17772 INACTIVE means use square brackets instead of angular ones, so that the
17773 stamp will not contribute to the agenda.
17774 PRE and POST are optional strings to be inserted before and after the
17775 stamp.
17776 The command returns the inserted time stamp."
17777 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17778 stamp)
17779 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17780 (insert-before-markers (or pre ""))
17781 (insert-before-markers (setq stamp (format-time-string fmt time)))
17782 (when (listp extra)
17783 (setq extra (car extra))
17784 (if (and (stringp extra)
17785 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17786 (setq extra (format "-%02d:%02d"
17787 (string-to-number (match-string 1 extra))
17788 (string-to-number (match-string 2 extra))))
17789 (setq extra nil)))
17790 (when extra
17791 (backward-char 1)
17792 (insert-before-markers extra)
17793 (forward-char 1))
17794 (insert-before-markers (or post ""))
17795 stamp))
17797 (defun org-toggle-time-stamp-overlays ()
17798 "Toggle the use of custom time stamp formats."
17799 (interactive)
17800 (setq org-display-custom-times (not org-display-custom-times))
17801 (unless org-display-custom-times
17802 (let ((p (point-min)) (bmp (buffer-modified-p)))
17803 (while (setq p (next-single-property-change p 'display))
17804 (if (and (get-text-property p 'display)
17805 (eq (get-text-property p 'face) 'org-date))
17806 (remove-text-properties
17807 p (setq p (next-single-property-change p 'display))
17808 '(display t))))
17809 (set-buffer-modified-p bmp)))
17810 (if (featurep 'xemacs)
17811 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17812 (org-restart-font-lock)
17813 (setq org-table-may-need-update t)
17814 (if org-display-custom-times
17815 (message "Time stamps are overlayed with custom format")
17816 (message "Time stamp overlays removed")))
17818 (defun org-display-custom-time (beg end)
17819 "Overlay modified time stamp format over timestamp between BED and END."
17820 (let* ((ts (buffer-substring beg end))
17821 t1 w1 with-hm tf time str w2 (off 0))
17822 (save-match-data
17823 (setq t1 (org-parse-time-string ts t))
17824 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17825 (setq off (- (match-end 0) (match-beginning 0)))))
17826 (setq end (- end off))
17827 (setq w1 (- end beg)
17828 with-hm (and (nth 1 t1) (nth 2 t1))
17829 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17830 time (org-fix-decoded-time t1)
17831 str (org-add-props
17832 (format-time-string
17833 (substring tf 1 -1) (apply 'encode-time time))
17834 nil 'mouse-face 'highlight)
17835 w2 (length str))
17836 (if (not (= w2 w1))
17837 (add-text-properties (1+ beg) (+ 2 beg)
17838 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17839 (if (featurep 'xemacs)
17840 (progn
17841 (put-text-property beg end 'invisible t)
17842 (put-text-property beg end 'end-glyph (make-glyph str)))
17843 (put-text-property beg end 'display str))))
17845 (defun org-translate-time (string)
17846 "Translate all timestamps in STRING to custom format.
17847 But do this only if the variable `org-display-custom-times' is set."
17848 (when org-display-custom-times
17849 (save-match-data
17850 (let* ((start 0)
17851 (re org-ts-regexp-both)
17852 t1 with-hm inactive tf time str beg end)
17853 (while (setq start (string-match re string start))
17854 (setq beg (match-beginning 0)
17855 end (match-end 0)
17856 t1 (save-match-data
17857 (org-parse-time-string (substring string beg end) t))
17858 with-hm (and (nth 1 t1) (nth 2 t1))
17859 inactive (equal (substring string beg (1+ beg)) "[")
17860 tf (funcall (if with-hm 'cdr 'car)
17861 org-time-stamp-custom-formats)
17862 time (org-fix-decoded-time t1)
17863 str (format-time-string
17864 (concat
17865 (if inactive "[" "<") (substring tf 1 -1)
17866 (if inactive "]" ">"))
17867 (apply 'encode-time time))
17868 string (replace-match str t t string)
17869 start (+ start (length str)))))))
17870 string)
17872 (defun org-fix-decoded-time (time)
17873 "Set 0 instead of nil for the first 6 elements of time.
17874 Don't touch the rest."
17875 (let ((n 0))
17876 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17878 (defun org-days-to-time (timestamp-string)
17879 "Difference between TIMESTAMP-STRING and now in days."
17880 (- (time-to-days (org-time-string-to-time timestamp-string))
17881 (time-to-days (current-time))))
17883 (defun org-deadline-close (timestamp-string &optional ndays)
17884 "Is the time in TIMESTAMP-STRING close to the current date?"
17885 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17886 (and (< (org-days-to-time timestamp-string) ndays)
17887 (not (org-entry-is-done-p))))
17889 (defun org-get-wdays (ts)
17890 "Get the deadline lead time appropriate for timestring TS."
17891 (cond
17892 ((<= org-deadline-warning-days 0)
17893 ;; 0 or negative, enforce this value no matter what
17894 (- org-deadline-warning-days))
17895 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17896 ;; lead time is specified.
17897 (floor (* (string-to-number (match-string 1 ts))
17898 (cdr (assoc (match-string 2 ts)
17899 '(("d" . 1) ("w" . 7)
17900 ("m" . 30.4) ("y" . 365.25)))))))
17901 ;; go for the default.
17902 (t org-deadline-warning-days)))
17904 (defun org-calendar-select-mouse (ev)
17905 "Return to `org-read-date' with the date currently selected.
17906 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17907 (interactive "e")
17908 (mouse-set-point ev)
17909 (when (calendar-cursor-to-date)
17910 (let* ((date (calendar-cursor-to-date))
17911 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17912 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17913 (if (active-minibuffer-window) (exit-minibuffer))))
17915 (defun org-check-deadlines (ndays)
17916 "Check if there are any deadlines due or past due.
17917 A deadline is considered due if it happens within `org-deadline-warning-days'
17918 days from today's date. If the deadline appears in an entry marked DONE,
17919 it is not shown. The prefix arg NDAYS can be used to test that many
17920 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17921 (interactive "P")
17922 (let* ((org-warn-days
17923 (cond
17924 ((equal ndays '(4)) 100000)
17925 (ndays (prefix-numeric-value ndays))
17926 (t (abs org-deadline-warning-days))))
17927 (case-fold-search nil)
17928 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17929 (callback
17930 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17932 (message "%d deadlines past-due or due within %d days"
17933 (org-occur regexp nil callback)
17934 org-warn-days)))
17936 (defun org-check-before-date (date)
17937 "Check if there are deadlines or scheduled entries before DATE."
17938 (interactive (list (org-read-date)))
17939 (let ((case-fold-search nil)
17940 (regexp (concat "\\<\\(" org-deadline-string
17941 "\\|" org-scheduled-string
17942 "\\) *<\\([^>]+\\)>"))
17943 (callback
17944 (lambda () (time-less-p
17945 (org-time-string-to-time (match-string 2))
17946 (org-time-string-to-time date)))))
17947 (message "%d entries before %s"
17948 (org-occur regexp nil callback) date)))
17950 (defun org-evaluate-time-range (&optional to-buffer)
17951 "Evaluate a time range by computing the difference between start and end.
17952 Normally the result is just printed in the echo area, but with prefix arg
17953 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17954 If the time range is actually in a table, the result is inserted into the
17955 next column.
17956 For time difference computation, a year is assumed to be exactly 365
17957 days in order to avoid rounding problems."
17958 (interactive "P")
17960 (org-clock-update-time-maybe)
17961 (save-excursion
17962 (unless (org-at-date-range-p t)
17963 (goto-char (point-at-bol))
17964 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17965 (if (not (org-at-date-range-p t))
17966 (error "Not at a time-stamp range, and none found in current line")))
17967 (let* ((ts1 (match-string 1))
17968 (ts2 (match-string 2))
17969 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17970 (match-end (match-end 0))
17971 (time1 (org-time-string-to-time ts1))
17972 (time2 (org-time-string-to-time ts2))
17973 (t1 (time-to-seconds time1))
17974 (t2 (time-to-seconds time2))
17975 (diff (abs (- t2 t1)))
17976 (negative (< (- t2 t1) 0))
17977 ;; (ys (floor (* 365 24 60 60)))
17978 (ds (* 24 60 60))
17979 (hs (* 60 60))
17980 (fy "%dy %dd %02d:%02d")
17981 (fy1 "%dy %dd")
17982 (fd "%dd %02d:%02d")
17983 (fd1 "%dd")
17984 (fh "%02d:%02d")
17985 y d h m align)
17986 (if havetime
17987 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17989 d (floor (/ diff ds)) diff (mod diff ds)
17990 h (floor (/ diff hs)) diff (mod diff hs)
17991 m (floor (/ diff 60)))
17992 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17994 d (floor (+ (/ diff ds) 0.5))
17995 h 0 m 0))
17996 (if (not to-buffer)
17997 (message "%s" (org-make-tdiff-string y d h m))
17998 (if (org-at-table-p)
17999 (progn
18000 (goto-char match-end)
18001 (setq align t)
18002 (and (looking-at " *|") (goto-char (match-end 0))))
18003 (goto-char match-end))
18004 (if (looking-at
18005 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18006 (replace-match ""))
18007 (if negative (insert " -"))
18008 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18009 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18010 (insert " " (format fh h m))))
18011 (if align (org-table-align))
18012 (message "Time difference inserted")))))
18014 (defun org-make-tdiff-string (y d h m)
18015 (let ((fmt "")
18016 (l nil))
18017 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18018 l (push y l)))
18019 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18020 l (push d l)))
18021 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18022 l (push h l)))
18023 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18024 l (push m l)))
18025 (apply 'format fmt (nreverse l))))
18027 (defun org-time-string-to-time (s)
18028 (apply 'encode-time (org-parse-time-string s)))
18030 (defun org-time-string-to-absolute (s &optional daynr prefer)
18031 "Convert a time stamp to an absolute day number.
18032 If there is a specifyer for a cyclic time stamp, get the closest date to
18033 DAYNR."
18034 (cond
18035 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18036 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18037 daynr
18038 (+ daynr 1000)))
18039 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18040 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18041 (time-to-days (current-time))) (match-string 0 s)
18042 prefer))
18043 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18045 (defun org-time-from-absolute (d)
18046 "Return the time corresponding to date D.
18047 D may be an absolute day number, or a calendar-type list (month day year)."
18048 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18049 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18051 (defun org-calendar-holiday ()
18052 "List of holidays, for Diary display in Org-mode."
18053 (require 'holidays)
18054 (let ((hl (funcall
18055 (if (fboundp 'calendar-check-holidays)
18056 'calendar-check-holidays 'check-calendar-holidays) date)))
18057 (if hl (mapconcat 'identity hl "; "))))
18059 (defun org-diary-sexp-entry (sexp entry date)
18060 "Process a SEXP diary ENTRY for DATE."
18061 (require 'diary-lib)
18062 (let ((result (if calendar-debug-sexp
18063 (let ((stack-trace-on-error t))
18064 (eval (car (read-from-string sexp))))
18065 (condition-case nil
18066 (eval (car (read-from-string sexp)))
18067 (error
18068 (beep)
18069 (message "Bad sexp at line %d in %s: %s"
18070 (org-current-line)
18071 (buffer-file-name) sexp)
18072 (sleep-for 2))))))
18073 (cond ((stringp result) result)
18074 ((and (consp result)
18075 (stringp (cdr result))) (cdr result))
18076 (result entry)
18077 (t nil))))
18079 (defun org-diary-to-ical-string (frombuf)
18080 "Get iCalendar entries from diary entries in buffer FROMBUF.
18081 This uses the icalendar.el library."
18082 (let* ((tmpdir (if (featurep 'xemacs)
18083 (temp-directory)
18084 temporary-file-directory))
18085 (tmpfile (make-temp-name
18086 (expand-file-name "orgics" tmpdir)))
18087 buf rtn b e)
18088 (save-excursion
18089 (set-buffer frombuf)
18090 (icalendar-export-region (point-min) (point-max) tmpfile)
18091 (setq buf (find-buffer-visiting tmpfile))
18092 (set-buffer buf)
18093 (goto-char (point-min))
18094 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18095 (setq b (match-beginning 0)))
18096 (goto-char (point-max))
18097 (if (re-search-backward "^END:VEVENT" nil t)
18098 (setq e (match-end 0)))
18099 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18100 (kill-buffer buf)
18101 (kill-buffer frombuf)
18102 (delete-file tmpfile)
18103 rtn))
18105 (defun org-closest-date (start current change prefer)
18106 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18107 When PREFER is `past' return a date that is either CURRENT or past.
18108 When PREFER is `future', return a date that is either CURRENT or future."
18109 ;; Make the proper lists from the dates
18110 (catch 'exit
18111 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18112 dn dw sday cday n1 n2
18113 d m y y1 y2 date1 date2 nmonths nm ny m2)
18115 (setq start (org-date-to-gregorian start)
18116 current (org-date-to-gregorian
18117 (if org-agenda-repeating-timestamp-show-all
18118 current
18119 (time-to-days (current-time))))
18120 sday (calendar-absolute-from-gregorian start)
18121 cday (calendar-absolute-from-gregorian current))
18123 (if (<= cday sday) (throw 'exit sday))
18125 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18126 (setq dn (string-to-number (match-string 1 change))
18127 dw (cdr (assoc (match-string 2 change) a1)))
18128 (error "Invalid change specifyer: %s" change))
18129 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18130 (cond
18131 ((eq dw 'day)
18132 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18133 n2 (+ n1 dn)))
18134 ((eq dw 'year)
18135 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18136 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18137 (setq date1 (list m d y1)
18138 n1 (calendar-absolute-from-gregorian date1)
18139 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18140 n2 (calendar-absolute-from-gregorian date2)))
18141 ((eq dw 'month)
18142 ;; approx number of month between the tow dates
18143 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18144 ;; How often does dn fit in there?
18145 (setq d (nth 1 start) m (car start) y (nth 2 start)
18146 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18147 m (+ m nm)
18148 ny (floor (/ m 12))
18149 y (+ y ny)
18150 m (- m (* ny 12)))
18151 (while (> m 12) (setq m (- m 12) y (1+ y)))
18152 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18153 (setq m2 (+ m dn) y2 y)
18154 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18155 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18156 (while (< n2 cday)
18157 (setq n1 n2 m m2 y y2)
18158 (setq m2 (+ m dn) y2 y)
18159 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18160 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18162 (if org-agenda-repeating-timestamp-show-all
18163 (cond
18164 ((eq prefer 'past) n1)
18165 ((eq prefer 'future) (if (= cday n1) n1 n2))
18166 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18167 (cond
18168 ((eq prefer 'past) n1)
18169 ((eq prefer 'future) (if (= cday n1) n1 n2))
18170 (t (if (= cday n1) n1 n2)))))))
18172 (defun org-date-to-gregorian (date)
18173 "Turn any specification of DATE into a gregorian date for the calendar."
18174 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18175 ((and (listp date) (= (length date) 3)) date)
18176 ((stringp date)
18177 (setq date (org-parse-time-string date))
18178 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18179 ((listp date)
18180 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18182 (defun org-parse-time-string (s &optional nodefault)
18183 "Parse the standard Org-mode time string.
18184 This should be a lot faster than the normal `parse-time-string'.
18185 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18186 hour and minute fields will be nil if not given."
18187 (if (string-match org-ts-regexp0 s)
18188 (list 0
18189 (if (or (match-beginning 8) (not nodefault))
18190 (string-to-number (or (match-string 8 s) "0")))
18191 (if (or (match-beginning 7) (not nodefault))
18192 (string-to-number (or (match-string 7 s) "0")))
18193 (string-to-number (match-string 4 s))
18194 (string-to-number (match-string 3 s))
18195 (string-to-number (match-string 2 s))
18196 nil nil nil)
18197 (make-list 9 0)))
18199 (defun org-timestamp-up (&optional arg)
18200 "Increase the date item at the cursor by one.
18201 If the cursor is on the year, change the year. If it is on the month or
18202 the day, change that.
18203 With prefix ARG, change by that many units."
18204 (interactive "p")
18205 (org-timestamp-change (prefix-numeric-value arg)))
18207 (defun org-timestamp-down (&optional arg)
18208 "Decrease the date item at the cursor by one.
18209 If the cursor is on the year, change the year. If it is on the month or
18210 the day, change that.
18211 With prefix ARG, change by that many units."
18212 (interactive "p")
18213 (org-timestamp-change (- (prefix-numeric-value arg))))
18215 (defun org-timestamp-up-day (&optional arg)
18216 "Increase the date in the time stamp by one day.
18217 With prefix ARG, change that many days."
18218 (interactive "p")
18219 (if (and (not (org-at-timestamp-p t))
18220 (org-on-heading-p))
18221 (org-todo 'up)
18222 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18224 (defun org-timestamp-down-day (&optional arg)
18225 "Decrease the date in the time stamp by one day.
18226 With prefix ARG, change that many days."
18227 (interactive "p")
18228 (if (and (not (org-at-timestamp-p t))
18229 (org-on-heading-p))
18230 (org-todo 'down)
18231 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18233 (defsubst org-pos-in-match-range (pos n)
18234 (and (match-beginning n)
18235 (<= (match-beginning n) pos)
18236 (>= (match-end n) pos)))
18238 (defun org-at-timestamp-p (&optional inactive-ok)
18239 "Determine if the cursor is in or at a timestamp."
18240 (interactive)
18241 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18242 (pos (point))
18243 (ans (or (looking-at tsr)
18244 (save-excursion
18245 (skip-chars-backward "^[<\n\r\t")
18246 (if (> (point) (point-min)) (backward-char 1))
18247 (and (looking-at tsr)
18248 (> (- (match-end 0) pos) -1))))))
18249 (and ans
18250 (boundp 'org-ts-what)
18251 (setq org-ts-what
18252 (cond
18253 ((= pos (match-beginning 0)) 'bracket)
18254 ((= pos (1- (match-end 0))) 'bracket)
18255 ((org-pos-in-match-range pos 2) 'year)
18256 ((org-pos-in-match-range pos 3) 'month)
18257 ((org-pos-in-match-range pos 7) 'hour)
18258 ((org-pos-in-match-range pos 8) 'minute)
18259 ((or (org-pos-in-match-range pos 4)
18260 (org-pos-in-match-range pos 5)) 'day)
18261 ((and (> pos (or (match-end 8) (match-end 5)))
18262 (< pos (match-end 0)))
18263 (- pos (or (match-end 8) (match-end 5))))
18264 (t 'day))))
18265 ans))
18267 (defun org-toggle-timestamp-type ()
18269 (interactive)
18270 (when (org-at-timestamp-p t)
18271 (save-excursion
18272 (goto-char (match-beginning 0))
18273 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18274 (goto-char (1- (match-end 0)))
18275 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18276 (message "Timestamp is now %sactive"
18277 (if (equal (char-before) ?>) "in" ""))))
18279 (defun org-timestamp-change (n &optional what)
18280 "Change the date in the time stamp at point.
18281 The date will be changed by N times WHAT. WHAT can be `day', `month',
18282 `year', `minute', `second'. If WHAT is not given, the cursor position
18283 in the timestamp determines what will be changed."
18284 (let ((pos (point))
18285 with-hm inactive
18286 org-ts-what
18287 extra
18288 ts time time0)
18289 (if (not (org-at-timestamp-p t))
18290 (error "Not at a timestamp"))
18291 (if (and (not what) (eq org-ts-what 'bracket))
18292 (org-toggle-timestamp-type)
18293 (if (and (not what) (not (eq org-ts-what 'day))
18294 org-display-custom-times
18295 (get-text-property (point) 'display)
18296 (not (get-text-property (1- (point)) 'display)))
18297 (setq org-ts-what 'day))
18298 (setq org-ts-what (or what org-ts-what)
18299 inactive (= (char-after (match-beginning 0)) ?\[)
18300 ts (match-string 0))
18301 (replace-match "")
18302 (if (string-match
18303 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18305 (setq extra (match-string 1 ts)))
18306 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18307 (setq with-hm t))
18308 (setq time0 (org-parse-time-string ts))
18309 (setq time
18310 (encode-time (or (car time0) 0)
18311 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18312 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18313 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18314 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18315 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18316 (nthcdr 6 time0)))
18317 (when (integerp org-ts-what)
18318 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18319 (if (eq what 'calendar)
18320 (let ((cal-date (org-get-date-from-calendar)))
18321 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18322 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18323 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18324 (setcar time0 (or (car time0) 0))
18325 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18326 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18327 (setq time (apply 'encode-time time0))))
18328 (setq org-last-changed-timestamp
18329 (org-insert-time-stamp time with-hm inactive nil nil extra))
18330 (org-clock-update-time-maybe)
18331 (goto-char pos)
18332 ;; Try to recenter the calendar window, if any
18333 (if (and org-calendar-follow-timestamp-change
18334 (get-buffer-window "*Calendar*" t)
18335 (memq org-ts-what '(day month year)))
18336 (org-recenter-calendar (time-to-days time))))))
18338 ;; FIXME: does not yet work for lead times
18339 (defun org-modify-ts-extra (s pos n)
18340 "Change the different parts of the lead-time and repeat fields in timestamp."
18341 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18342 ng h m new)
18343 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18344 (cond
18345 ((or (org-pos-in-match-range pos 2)
18346 (org-pos-in-match-range pos 3))
18347 (setq m (string-to-number (match-string 3 s))
18348 h (string-to-number (match-string 2 s)))
18349 (if (org-pos-in-match-range pos 2)
18350 (setq h (+ h n))
18351 (setq m (+ m n)))
18352 (if (< m 0) (setq m (+ m 60) h (1- h)))
18353 (if (> m 59) (setq m (- m 60) h (1+ h)))
18354 (setq h (min 24 (max 0 h)))
18355 (setq ng 1 new (format "-%02d:%02d" h m)))
18356 ((org-pos-in-match-range pos 6)
18357 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18358 ((org-pos-in-match-range pos 5)
18359 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18361 (when ng
18362 (setq s (concat
18363 (substring s 0 (match-beginning ng))
18365 (substring s (match-end ng))))))
18368 (defun org-recenter-calendar (date)
18369 "If the calendar is visible, recenter it to DATE."
18370 (let* ((win (selected-window))
18371 (cwin (get-buffer-window "*Calendar*" t))
18372 (calendar-move-hook nil))
18373 (when cwin
18374 (select-window cwin)
18375 (calendar-goto-date (if (listp date) date
18376 (calendar-gregorian-from-absolute date)))
18377 (select-window win))))
18379 (defun org-goto-calendar (&optional arg)
18380 "Go to the Emacs calendar at the current date.
18381 If there is a time stamp in the current line, go to that date.
18382 A prefix ARG can be used to force the current date."
18383 (interactive "P")
18384 (let ((tsr org-ts-regexp) diff
18385 (calendar-move-hook nil)
18386 (view-calendar-holidays-initially nil)
18387 (view-diary-entries-initially nil))
18388 (if (or (org-at-timestamp-p)
18389 (save-excursion
18390 (beginning-of-line 1)
18391 (looking-at (concat ".*" tsr))))
18392 (let ((d1 (time-to-days (current-time)))
18393 (d2 (time-to-days
18394 (org-time-string-to-time (match-string 1)))))
18395 (setq diff (- d2 d1))))
18396 (calendar)
18397 (calendar-goto-today)
18398 (if (and diff (not arg)) (calendar-forward-day diff))))
18400 (defun org-get-date-from-calendar ()
18401 "Return a list (month day year) of date at point in calendar."
18402 (with-current-buffer "*Calendar*"
18403 (save-match-data
18404 (calendar-cursor-to-date))))
18406 (defun org-date-from-calendar ()
18407 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18408 If there is already a time stamp at the cursor position, update it."
18409 (interactive)
18410 (if (org-at-timestamp-p t)
18411 (org-timestamp-change 0 'calendar)
18412 (let ((cal-date (org-get-date-from-calendar)))
18413 (org-insert-time-stamp
18414 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18416 ;; Make appt aware of appointments from the agenda
18417 ;;;###autoload
18418 (defun org-agenda-to-appt (&optional filter)
18419 "Activate appointments found in `org-agenda-files'.
18420 When prefixed, prompt for a regular expression and use it as a
18421 filter: only add entries if they match this regular expression.
18423 FILTER can be a string. In this case, use this string as a
18424 regular expression to filter results.
18426 FILTER can also be an alist, with the car of each cell being
18427 either 'headline or 'category. For example:
18429 '((headline \"IMPORTANT\")
18430 (category \"Work\"))
18432 will only add headlines containing IMPORTANT or headlines
18433 belonging to the category \"Work\"."
18434 (interactive "P")
18435 (require 'calendar)
18436 (if (equal filter '(4))
18437 (setq filter (read-from-minibuffer "Regexp filter: ")))
18438 (let* ((cnt 0) ; count added events
18439 (org-agenda-new-buffers nil)
18440 (today (org-date-to-gregorian
18441 (time-to-days (current-time))))
18442 (files (org-agenda-files)) entries file)
18443 ;; Get all entries which may contain an appt
18444 (while (setq file (pop files))
18445 (setq entries
18446 (append entries
18447 (org-agenda-get-day-entries
18448 file today
18449 :timestamp :scheduled :deadline))))
18450 (setq entries (delq nil entries))
18451 ;; Map thru entries and find if they pass thru the filter
18452 (mapc
18453 (lambda(x)
18454 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18455 (cat (get-text-property 1 'org-category x))
18456 (tod (get-text-property 1 'time-of-day x))
18457 (ok (or (null filter)
18458 (and (stringp filter) (string-match filter evt))
18459 (and (listp filter)
18460 (or (string-match
18461 (cadr (assoc 'category filter)) cat)
18462 (string-match
18463 (cadr (assoc 'headline filter)) evt))))))
18464 ;; FIXME: Shall we remove text-properties for the appt text?
18465 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18466 (when (and ok tod)
18467 (setq tod (number-to-string tod)
18468 tod (when (string-match
18469 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18470 (concat (match-string 1 tod) ":"
18471 (match-string 2 tod))))
18472 (appt-add tod evt)
18473 (setq cnt (1+ cnt))))) entries)
18474 (org-release-buffers org-agenda-new-buffers)
18475 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
18477 ;;; The clock for measuring work time.
18479 (defvar org-mode-line-string "")
18480 (put 'org-mode-line-string 'risky-local-variable t)
18482 (defvar org-mode-line-timer nil)
18483 (defvar org-clock-heading "")
18484 (defvar org-clock-start-time "")
18486 (defun org-update-mode-line ()
18487 (let* ((delta (- (time-to-seconds (current-time))
18488 (time-to-seconds org-clock-start-time)))
18489 (h (floor delta 3600))
18490 (m (floor (- delta (* 3600 h)) 60)))
18491 (setq org-mode-line-string
18492 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18493 'help-echo "Org-mode clock is running"))
18494 (force-mode-line-update)))
18496 (defvar org-clock-marker (make-marker)
18497 "Marker recording the last clock-in.")
18498 (defvar org-clock-mode-line-entry nil
18499 "Information for the modeline about the running clock.")
18501 (defun org-clock-in ()
18502 "Start the clock on the current item.
18503 If necessary, clock-out of the currently active clock."
18504 (interactive)
18505 (org-clock-out t)
18506 (let (ts)
18507 (save-excursion
18508 (org-back-to-heading t)
18509 (when (and org-clock-in-switch-to-state
18510 (not (looking-at (concat outline-regexp "[ \t]*"
18511 org-clock-in-switch-to-state
18512 "\\>"))))
18513 (org-todo org-clock-in-switch-to-state))
18514 (if (and org-clock-heading-function
18515 (functionp org-clock-heading-function))
18516 (setq org-clock-heading (funcall org-clock-heading-function))
18517 (if (looking-at org-complex-heading-regexp)
18518 (setq org-clock-heading (match-string 4))
18519 (setq org-clock-heading "???")))
18520 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18521 (org-clock-find-position)
18523 (insert "\n") (backward-char 1)
18524 (indent-relative)
18525 (insert org-clock-string " ")
18526 (setq org-clock-start-time (current-time))
18527 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18528 (move-marker org-clock-marker (point) (buffer-base-buffer))
18529 (or global-mode-string (setq global-mode-string '("")))
18530 (or (memq 'org-mode-line-string global-mode-string)
18531 (setq global-mode-string
18532 (append global-mode-string '(org-mode-line-string))))
18533 (org-update-mode-line)
18534 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18535 (message "Clock started at %s" ts))))
18537 (defun org-clock-find-position ()
18538 "Find the location where the next clock line should be inserted."
18539 (org-back-to-heading t)
18540 (catch 'exit
18541 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18542 (re (concat "^[ \t]*" org-clock-string))
18543 (cnt 0)
18544 first last)
18545 (goto-char beg)
18546 (when (eobp) (newline) (setq end (max (point) end)))
18547 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18548 ;; we seem to have a CLOCK drawer, so go there.
18549 (beginning-of-line 2)
18550 (throw 'exit t))
18551 ;; Lets count the CLOCK lines
18552 (goto-char beg)
18553 (while (re-search-forward re end t)
18554 (setq first (or first (match-beginning 0))
18555 last (match-beginning 0)
18556 cnt (1+ cnt)))
18557 (when (and (integerp org-clock-into-drawer)
18558 (>= (1+ cnt) org-clock-into-drawer))
18559 ;; Wrap current entries into a new drawer
18560 (goto-char last)
18561 (beginning-of-line 2)
18562 (if (org-at-item-p) (org-end-of-item))
18563 (insert ":END:\n")
18564 (beginning-of-line 0)
18565 (org-indent-line-function)
18566 (goto-char first)
18567 (insert ":CLOCK:\n")
18568 (beginning-of-line 0)
18569 (org-indent-line-function)
18570 (org-flag-drawer t)
18571 (beginning-of-line 2)
18572 (throw 'exit nil))
18574 (goto-char beg)
18575 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18576 (not (equal (match-string 1) org-clock-string)))
18577 ;; Planning info, skip to after it
18578 (beginning-of-line 2)
18579 (or (bolp) (newline)))
18580 (when (eq t org-clock-into-drawer)
18581 (insert ":CLOCK:\n:END:\n")
18582 (beginning-of-line -1)
18583 (org-indent-line-function)
18584 (org-flag-drawer t)
18585 (beginning-of-line 2)
18586 (org-indent-line-function)))))
18588 (defun org-clock-out (&optional fail-quietly)
18589 "Stop the currently running clock.
18590 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18591 (interactive)
18592 (catch 'exit
18593 (if (not (marker-buffer org-clock-marker))
18594 (if fail-quietly (throw 'exit t) (error "No active clock")))
18595 (let (ts te s h m)
18596 (save-excursion
18597 (set-buffer (marker-buffer org-clock-marker))
18598 (goto-char org-clock-marker)
18599 (beginning-of-line 1)
18600 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18601 (equal (match-string 1) org-clock-string))
18602 (setq ts (match-string 2))
18603 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18604 (goto-char (match-end 0))
18605 (delete-region (point) (point-at-eol))
18606 (insert "--")
18607 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18608 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18609 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18610 h (floor (/ s 3600))
18611 s (- s (* 3600 h))
18612 m (floor (/ s 60))
18613 s (- s (* 60 s)))
18614 (insert " => " (format "%2d:%02d" h m))
18615 (move-marker org-clock-marker nil)
18616 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
18617 (org-log-done (org-parse-local-options logging 'org-log-done))
18618 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
18619 (org-add-log-maybe 'clock-out))
18620 (when org-mode-line-timer
18621 (cancel-timer org-mode-line-timer)
18622 (setq org-mode-line-timer nil))
18623 (setq global-mode-string
18624 (delq 'org-mode-line-string global-mode-string))
18625 (force-mode-line-update)
18626 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18628 (defun org-clock-cancel ()
18629 "Cancel the running clock be removing the start timestamp."
18630 (interactive)
18631 (if (not (marker-buffer org-clock-marker))
18632 (error "No active clock"))
18633 (save-excursion
18634 (set-buffer (marker-buffer org-clock-marker))
18635 (goto-char org-clock-marker)
18636 (delete-region (1- (point-at-bol)) (point-at-eol)))
18637 (setq global-mode-string
18638 (delq 'org-mode-line-string global-mode-string))
18639 (force-mode-line-update)
18640 (message "Clock canceled"))
18642 (defun org-clock-goto (&optional delete-windows)
18643 "Go to the currently clocked-in entry."
18644 (interactive "P")
18645 (if (not (marker-buffer org-clock-marker))
18646 (error "No active clock"))
18647 (switch-to-buffer-other-window
18648 (marker-buffer org-clock-marker))
18649 (if delete-windows (delete-other-windows))
18650 (goto-char org-clock-marker)
18651 (org-show-entry)
18652 (org-back-to-heading)
18653 (recenter))
18655 (defvar org-clock-file-total-minutes nil
18656 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18657 (make-variable-buffer-local 'org-clock-file-total-minutes)
18659 (defun org-clock-sum (&optional tstart tend)
18660 "Sum the times for each subtree.
18661 Puts the resulting times in minutes as a text property on each headline."
18662 (interactive)
18663 (let* ((bmp (buffer-modified-p))
18664 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18665 org-clock-string
18666 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18667 (lmax 30)
18668 (ltimes (make-vector lmax 0))
18669 (t1 0)
18670 (level 0)
18671 ts te dt
18672 time)
18673 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18674 (save-excursion
18675 (goto-char (point-max))
18676 (while (re-search-backward re nil t)
18677 (cond
18678 ((match-end 2)
18679 ;; Two time stamps
18680 (setq ts (match-string 2)
18681 te (match-string 3)
18682 ts (time-to-seconds
18683 (apply 'encode-time (org-parse-time-string ts)))
18684 te (time-to-seconds
18685 (apply 'encode-time (org-parse-time-string te)))
18686 ts (if tstart (max ts tstart) ts)
18687 te (if tend (min te tend) te)
18688 dt (- te ts)
18689 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18690 ((match-end 4)
18691 ;; A naket time
18692 (setq t1 (+ t1 (string-to-number (match-string 5))
18693 (* 60 (string-to-number (match-string 4))))))
18694 (t ;; A headline
18695 (setq level (- (match-end 1) (match-beginning 1)))
18696 (when (or (> t1 0) (> (aref ltimes level) 0))
18697 (loop for l from 0 to level do
18698 (aset ltimes l (+ (aref ltimes l) t1)))
18699 (setq t1 0 time (aref ltimes level))
18700 (loop for l from level to (1- lmax) do
18701 (aset ltimes l 0))
18702 (goto-char (match-beginning 0))
18703 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18704 (setq org-clock-file-total-minutes (aref ltimes 0)))
18705 (set-buffer-modified-p bmp)))
18707 (defun org-clock-display (&optional total-only)
18708 "Show subtree times in the entire buffer.
18709 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18710 in the echo area."
18711 (interactive)
18712 (org-remove-clock-overlays)
18713 (let (time h m p)
18714 (org-clock-sum)
18715 (unless total-only
18716 (save-excursion
18717 (goto-char (point-min))
18718 (while (or (and (equal (setq p (point)) (point-min))
18719 (get-text-property p :org-clock-minutes))
18720 (setq p (next-single-property-change
18721 (point) :org-clock-minutes)))
18722 (goto-char p)
18723 (when (setq time (get-text-property p :org-clock-minutes))
18724 (org-put-clock-overlay time (funcall outline-level))))
18725 (setq h (/ org-clock-file-total-minutes 60)
18726 m (- org-clock-file-total-minutes (* 60 h)))
18727 ;; Arrange to remove the overlays upon next change.
18728 (when org-remove-highlights-with-change
18729 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18730 nil 'local))))
18731 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18733 (defvar org-clock-overlays nil)
18734 (make-variable-buffer-local 'org-clock-overlays)
18736 (defun org-put-clock-overlay (time &optional level)
18737 "Put an overlays on the current line, displaying TIME.
18738 If LEVEL is given, prefix time with a corresponding number of stars.
18739 This creates a new overlay and stores it in `org-clock-overlays', so that it
18740 will be easy to remove."
18741 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18742 (l (if level (org-get-legal-level level 0) 0))
18743 (off 0)
18744 ov tx)
18745 (move-to-column c)
18746 (unless (eolp) (skip-chars-backward "^ \t"))
18747 (skip-chars-backward " \t")
18748 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18749 tx (concat (buffer-substring (1- (point)) (point))
18750 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18751 (org-add-props (format "%s %2d:%02d%s"
18752 (make-string l ?*) h m
18753 (make-string (- 10 l) ?\ ))
18754 '(face secondary-selection))
18755 ""))
18756 (if (not (featurep 'xemacs))
18757 (org-overlay-put ov 'display tx)
18758 (org-overlay-put ov 'invisible t)
18759 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18760 (push ov org-clock-overlays)))
18762 (defun org-remove-clock-overlays (&optional beg end noremove)
18763 "Remove the occur highlights from the buffer.
18764 BEG and END are ignored. If NOREMOVE is nil, remove this function
18765 from the `before-change-functions' in the current buffer."
18766 (interactive)
18767 (unless org-inhibit-highlight-removal
18768 (mapc 'org-delete-overlay org-clock-overlays)
18769 (setq org-clock-overlays nil)
18770 (unless noremove
18771 (remove-hook 'before-change-functions
18772 'org-remove-clock-overlays 'local))))
18774 (defun org-clock-out-if-current ()
18775 "Clock out if the current entry contains the running clock.
18776 This is used to stop the clock after a TODO entry is marked DONE,
18777 and is only done if the variable `org-clock-out-when-done' is not nil."
18778 (when (and org-clock-out-when-done
18779 (member state org-done-keywords)
18780 (equal (marker-buffer org-clock-marker) (current-buffer))
18781 (< (point) org-clock-marker)
18782 (> (save-excursion (outline-next-heading) (point))
18783 org-clock-marker))
18784 ;; Clock out, but don't accept a logging message for this.
18785 (let ((org-log-done (if (and (listp org-log-done)
18786 (member 'clock-out org-log-done))
18787 '(done)
18788 org-log-done)))
18789 (org-clock-out))))
18791 (add-hook 'org-after-todo-state-change-hook
18792 'org-clock-out-if-current)
18794 (defun org-check-running-clock ()
18795 "Check if the current buffer contains the running clock.
18796 If yes, offer to stop it and to save the buffer with the changes."
18797 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18798 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18799 (buffer-name))))
18800 (org-clock-out)
18801 (when (y-or-n-p "Save changed buffer?")
18802 (save-buffer))))
18804 (defun org-clock-report (&optional arg)
18805 "Create a table containing a report about clocked time.
18806 If the cursor is inside an existing clocktable block, then the table
18807 will be updated. If not, a new clocktable will be inserted.
18808 When called with a prefix argument, move to the first clock table in the
18809 buffer and update it."
18810 (interactive "P")
18811 (org-remove-clock-overlays)
18812 (when arg
18813 (org-find-dblock "clocktable")
18814 (org-show-entry))
18815 (if (org-in-clocktable-p)
18816 (goto-char (org-in-clocktable-p))
18817 (org-create-dblock (list :name "clocktable"
18818 :maxlevel 2 :scope 'file)))
18819 (org-update-dblock))
18821 (defun org-in-clocktable-p ()
18822 "Check if the cursor is in a clocktable."
18823 (let ((pos (point)) start)
18824 (save-excursion
18825 (end-of-line 1)
18826 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18827 (setq start (match-beginning 0))
18828 (re-search-forward "^#\\+END:.*" nil t)
18829 (>= (match-end 0) pos)
18830 start))))
18832 (defun org-clock-update-time-maybe ()
18833 "If this is a CLOCK line, update it and return t.
18834 Otherwise, return nil."
18835 (interactive)
18836 (save-excursion
18837 (beginning-of-line 1)
18838 (skip-chars-forward " \t")
18839 (when (looking-at org-clock-string)
18840 (let ((re (concat "[ \t]*" org-clock-string
18841 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18842 "\\([ \t]*=>.*\\)?"))
18843 ts te h m s)
18844 (if (not (looking-at re))
18846 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18847 (end-of-line 1)
18848 (setq ts (match-string 1)
18849 te (match-string 2))
18850 (setq s (- (time-to-seconds
18851 (apply 'encode-time (org-parse-time-string te)))
18852 (time-to-seconds
18853 (apply 'encode-time (org-parse-time-string ts))))
18854 h (floor (/ s 3600))
18855 s (- s (* 3600 h))
18856 m (floor (/ s 60))
18857 s (- s (* 60 s)))
18858 (insert " => " (format "%2d:%02d" h m))
18859 t)))))
18861 (defun org-clock-special-range (key &optional time as-strings)
18862 "Return two times bordering a special time range.
18863 Key is a symbol specifying the range and can be one of `today', `yesterday',
18864 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18865 A week starts Monday 0:00 and ends Sunday 24:00.
18866 The range is determined relative to TIME. TIME defaults to the current time.
18867 The return value is a cons cell with two internal times like the ones
18868 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18869 the returned times will be formatted strings."
18870 (let* ((tm (decode-time (or time (current-time))))
18871 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18872 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18873 (dow (nth 6 tm))
18874 s1 m1 h1 d1 month1 y1 diff ts te fm)
18875 (cond
18876 ((eq key 'today)
18877 (setq h 0 m 0 h1 24 m1 0))
18878 ((eq key 'yesterday)
18879 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18880 ((eq key 'thisweek)
18881 (setq diff (if (= dow 0) 6 (1- dow))
18882 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18883 ((eq key 'lastweek)
18884 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18885 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18886 ((eq key 'thismonth)
18887 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18888 ((eq key 'lastmonth)
18889 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18890 ((eq key 'thisyear)
18891 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18892 ((eq key 'lastyear)
18893 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18894 (t (error "No such time block %s" key)))
18895 (setq ts (encode-time s m h d month y)
18896 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18897 (or d1 d) (or month1 month) (or y1 y)))
18898 (setq fm (cdr org-time-stamp-formats))
18899 (if as-strings
18900 (cons (format-time-string fm ts) (format-time-string fm te))
18901 (cons ts te))))
18903 (defun org-dblock-write:clocktable (params)
18904 "Write the standard clocktable."
18905 (catch 'exit
18906 (let* ((hlchars '((1 . "*") (2 . "/")))
18907 (ins (make-marker))
18908 (total-time nil)
18909 (scope (plist-get params :scope))
18910 (tostring (plist-get params :tostring))
18911 (multifile (plist-get params :multifile))
18912 (header (plist-get params :header))
18913 (maxlevel (or (plist-get params :maxlevel) 3))
18914 (step (plist-get params :step))
18915 (emph (plist-get params :emphasize))
18916 (ts (plist-get params :tstart))
18917 (te (plist-get params :tend))
18918 (block (plist-get params :block))
18919 ipos time h m p level hlc hdl
18920 cc beg end pos tbl)
18921 (when step
18922 (org-clocktable-steps params)
18923 (throw 'exit nil))
18924 (when block
18925 (setq cc (org-clock-special-range block nil t)
18926 ts (car cc) te (cdr cc)))
18927 (if ts (setq ts (time-to-seconds
18928 (apply 'encode-time (org-parse-time-string ts)))))
18929 (if te (setq te (time-to-seconds
18930 (apply 'encode-time (org-parse-time-string te)))))
18931 (move-marker ins (point))
18932 (setq ipos (point))
18934 ;; Get the right scope
18935 (setq pos (point))
18936 (save-restriction
18937 (cond
18938 ((not scope))
18939 ((eq scope 'file) (widen))
18940 ((eq scope 'subtree) (org-narrow-to-subtree))
18941 ((eq scope 'tree)
18942 (while (org-up-heading-safe))
18943 (org-narrow-to-subtree))
18944 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18945 (symbol-name scope)))
18946 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18947 (catch 'exit
18948 (while (org-up-heading-safe)
18949 (looking-at outline-regexp)
18950 (if (<= (org-reduced-level (funcall outline-level)) level)
18951 (throw 'exit nil))))
18952 (org-narrow-to-subtree))
18953 ((or (listp scope) (eq scope 'agenda))
18954 (let* ((files (if (listp scope) scope (org-agenda-files)))
18955 (scope 'agenda)
18956 (p1 (copy-sequence params))
18957 file)
18958 (plist-put p1 :tostring t)
18959 (plist-put p1 :multifile t)
18960 (plist-put p1 :scope 'file)
18961 (org-prepare-agenda-buffers files)
18962 (while (setq file (pop files))
18963 (with-current-buffer (find-buffer-visiting file)
18964 (push (org-clocktable-add-file
18965 file (org-dblock-write:clocktable p1)) tbl)
18966 (setq total-time (+ (or total-time 0)
18967 org-clock-file-total-minutes)))))))
18968 (goto-char pos)
18970 (unless (eq scope 'agenda)
18971 (org-clock-sum ts te)
18972 (goto-char (point-min))
18973 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18974 (goto-char p)
18975 (when (setq time (get-text-property p :org-clock-minutes))
18976 (save-excursion
18977 (beginning-of-line 1)
18978 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18979 (setq level (org-reduced-level
18980 (- (match-end 1) (match-beginning 1))))
18981 (<= level maxlevel))
18982 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
18983 hdl (match-string 2)
18984 h (/ time 60)
18985 m (- time (* 60 h)))
18986 (if (and (not multifile) (= level 1)) (push "|-" tbl))
18987 (push (concat
18988 "| " (int-to-string level) "|" hlc hdl hlc " |"
18989 (make-string (1- level) ?|)
18990 hlc (format "%d:%02d" h m) hlc
18991 " |") tbl))))))
18992 (setq tbl (nreverse tbl))
18993 (if tostring
18994 (if tbl (mapconcat 'identity tbl "\n") nil)
18995 (goto-char ins)
18996 (insert-before-markers
18997 (or header
18998 (concat
18999 "Clock summary at ["
19000 (substring
19001 (format-time-string (cdr org-time-stamp-formats))
19002 1 -1)
19003 "]."
19004 (if block
19005 (format " Considered range is /%s/." block)
19007 "\n\n"))
19008 (if (eq scope 'agenda) "|File" "")
19009 "|L|Headline|Time|\n")
19010 (setq total-time (or total-time org-clock-file-total-minutes)
19011 h (/ total-time 60)
19012 m (- total-time (* 60 h)))
19013 (insert-before-markers
19014 "|-\n|"
19015 (if (eq scope 'agenda) "|" "")
19017 "*Total time*| "
19018 (format "*%d:%02d*" h m)
19019 "|\n|-\n")
19020 (setq tbl (delq nil tbl))
19021 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19022 (equal (substring (car tbl) 0 2) "|-"))
19023 (pop tbl))
19024 (insert-before-markers (mapconcat
19025 'identity (delq nil tbl)
19026 (if (eq scope 'agenda) "\n|-\n" "\n")))
19027 (backward-delete-char 1)
19028 (goto-char ipos)
19029 (skip-chars-forward "^|")
19030 (org-table-align))))))
19032 (defun org-clocktable-steps (params)
19033 (let* ((p1 (copy-sequence params))
19034 (ts (plist-get p1 :tstart))
19035 (te (plist-get p1 :tend))
19036 (step0 (plist-get p1 :step))
19037 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19038 (block (plist-get p1 :block))
19040 (when block
19041 (setq cc (org-clock-special-range block nil t)
19042 ts (car cc) te (cdr cc)))
19043 (if ts (setq ts (time-to-seconds
19044 (apply 'encode-time (org-parse-time-string ts)))))
19045 (if te (setq te (time-to-seconds
19046 (apply 'encode-time (org-parse-time-string te)))))
19047 (plist-put p1 :header "")
19048 (plist-put p1 :step nil)
19049 (plist-put p1 :block nil)
19050 (while (< ts te)
19051 (or (bolp) (insert "\n"))
19052 (plist-put p1 :tstart (format-time-string
19053 (car org-time-stamp-formats)
19054 (seconds-to-time ts)))
19055 (plist-put p1 :tend (format-time-string
19056 (car org-time-stamp-formats)
19057 (seconds-to-time (setq ts (+ ts step)))))
19058 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19059 (plist-get p1 :tstart) "\n")
19060 (org-dblock-write:clocktable p1)
19061 (re-search-forward "#\\+END:")
19062 (end-of-line 0))))
19065 (defun org-clocktable-add-file (file table)
19066 (if table
19067 (let ((lines (org-split-string table "\n"))
19068 (ff (file-name-nondirectory file)))
19069 (mapconcat 'identity
19070 (mapcar (lambda (x)
19071 (if (string-match org-table-dataline-regexp x)
19072 (concat "|" ff x)
19074 lines)
19075 "\n"))))
19077 ;; FIXME: I don't think anybody uses this, ask David
19078 (defun org-collect-clock-time-entries ()
19079 "Return an internal list with clocking information.
19080 This list has one entry for each CLOCK interval.
19081 FIXME: describe the elements."
19082 (interactive)
19083 (let ((re (concat "^[ \t]*" org-clock-string
19084 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19085 rtn beg end next cont level title total closedp leafp
19086 clockpos titlepos h m donep)
19087 (save-excursion
19088 (org-clock-sum)
19089 (goto-char (point-min))
19090 (while (re-search-forward re nil t)
19091 (setq clockpos (match-beginning 0)
19092 beg (match-string 1) end (match-string 2)
19093 cont (match-end 0))
19094 (setq beg (apply 'encode-time (org-parse-time-string beg))
19095 end (apply 'encode-time (org-parse-time-string end)))
19096 (org-back-to-heading t)
19097 (setq donep (org-entry-is-done-p))
19098 (setq titlepos (point)
19099 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19100 h (/ total 60) m (- total (* 60 h))
19101 total (cons h m))
19102 (looking-at "\\(\\*+\\) +\\(.*\\)")
19103 (setq level (- (match-end 1) (match-beginning 1))
19104 title (org-match-string-no-properties 2))
19105 (save-excursion (outline-next-heading) (setq next (point)))
19106 (setq closedp (re-search-forward org-closed-time-regexp next t))
19107 (goto-char next)
19108 (setq leafp (and (looking-at "^\\*+ ")
19109 (<= (- (match-end 0) (point)) level)))
19110 (push (list beg end clockpos closedp donep
19111 total title titlepos level leafp)
19112 rtn)
19113 (goto-char cont)))
19114 (nreverse rtn)))
19116 ;;;; Agenda, and Diary Integration
19118 ;;; Define the Org-agenda-mode
19120 (defvar org-agenda-mode-map (make-sparse-keymap)
19121 "Keymap for `org-agenda-mode'.")
19123 (defvar org-agenda-menu) ; defined later in this file.
19124 (defvar org-agenda-follow-mode nil)
19125 (defvar org-agenda-show-log nil)
19126 (defvar org-agenda-redo-command nil)
19127 (defvar org-agenda-mode-hook nil)
19128 (defvar org-agenda-type nil)
19129 (defvar org-agenda-force-single-file nil)
19131 (defun org-agenda-mode ()
19132 "Mode for time-sorted view on action items in Org-mode files.
19134 The following commands are available:
19136 \\{org-agenda-mode-map}"
19137 (interactive)
19138 (kill-all-local-variables)
19139 (setq org-agenda-undo-list nil
19140 org-agenda-pending-undo-list nil)
19141 (setq major-mode 'org-agenda-mode)
19142 ;; Keep global-font-lock-mode from turning on font-lock-mode
19143 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19144 (setq mode-name "Org-Agenda")
19145 (use-local-map org-agenda-mode-map)
19146 (easy-menu-add org-agenda-menu)
19147 (if org-startup-truncated (setq truncate-lines t))
19148 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19149 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19150 ;; Make sure properties are removed when copying text
19151 (when (boundp 'buffer-substring-filters)
19152 (org-set-local 'buffer-substring-filters
19153 (cons (lambda (x)
19154 (set-text-properties 0 (length x) nil x) x)
19155 buffer-substring-filters)))
19156 (unless org-agenda-keep-modes
19157 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19158 org-agenda-show-log nil))
19159 (easy-menu-change
19160 '("Agenda") "Agenda Files"
19161 (append
19162 (list
19163 (vector
19164 (if (get 'org-agenda-files 'org-restrict)
19165 "Restricted to single file"
19166 "Edit File List")
19167 '(org-edit-agenda-file-list)
19168 (not (get 'org-agenda-files 'org-restrict)))
19169 "--")
19170 (mapcar 'org-file-menu-entry (org-agenda-files))))
19171 (org-agenda-set-mode-name)
19172 (apply
19173 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19174 (list 'org-agenda-mode-hook)))
19176 (substitute-key-definition 'undo 'org-agenda-undo
19177 org-agenda-mode-map global-map)
19178 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19179 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19180 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19181 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19182 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19183 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19184 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19185 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19186 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19187 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19188 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19189 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19190 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19191 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19192 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19193 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19194 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19195 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19196 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19197 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19198 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19199 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19200 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19201 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19202 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19203 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19204 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19205 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19206 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19208 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19209 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19210 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19211 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19212 (while l (org-defkey org-agenda-mode-map
19213 (int-to-string (pop l)) 'digit-argument)))
19215 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19216 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19217 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19218 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19219 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19220 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19221 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19222 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19223 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19224 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19225 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19226 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19227 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19228 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19229 (org-defkey org-agenda-mode-map "n" 'next-line)
19230 (org-defkey org-agenda-mode-map "p" 'previous-line)
19231 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19232 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19233 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19234 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19235 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19236 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19237 (eval-after-load "calendar"
19238 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19239 'org-calendar-goto-agenda))
19240 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19241 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19242 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19243 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19244 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19245 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19246 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19247 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19248 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19249 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19250 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19251 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19252 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19253 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19254 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19255 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19256 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19257 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19258 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19259 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19260 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19261 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19263 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19264 "Local keymap for agenda entries from Org-mode.")
19266 (org-defkey org-agenda-keymap
19267 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19268 (org-defkey org-agenda-keymap
19269 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19270 (when org-agenda-mouse-1-follows-link
19271 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19272 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19273 '("Agenda"
19274 ("Agenda Files")
19275 "--"
19276 ["Show" org-agenda-show t]
19277 ["Go To (other window)" org-agenda-goto t]
19278 ["Go To (this window)" org-agenda-switch-to t]
19279 ["Follow Mode" org-agenda-follow-mode
19280 :style toggle :selected org-agenda-follow-mode :active t]
19281 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19282 "--"
19283 ["Cycle TODO" org-agenda-todo t]
19284 ["Archive subtree" org-agenda-archive t]
19285 ["Delete subtree" org-agenda-kill t]
19286 "--"
19287 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19288 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19289 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19290 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19291 "--"
19292 ("Tags and Properties"
19293 ["Show all Tags" org-agenda-show-tags t]
19294 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19295 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19296 "--"
19297 ["Column View" org-columns t])
19298 ("Date/Schedule"
19299 ["Schedule" org-agenda-schedule t]
19300 ["Set Deadline" org-agenda-deadline t]
19301 "--"
19302 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19303 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19304 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19305 ("Clock"
19306 ["Clock in" org-agenda-clock-in t]
19307 ["Clock out" org-agenda-clock-out t]
19308 ["Clock cancel" org-agenda-clock-cancel t]
19309 ["Goto running clock" org-clock-goto t])
19310 ("Priority"
19311 ["Set Priority" org-agenda-priority t]
19312 ["Increase Priority" org-agenda-priority-up t]
19313 ["Decrease Priority" org-agenda-priority-down t]
19314 ["Show Priority" org-agenda-show-priority t])
19315 ("Calendar/Diary"
19316 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19317 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19318 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19319 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19320 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19321 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19322 "--"
19323 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19324 "--"
19325 ("View"
19326 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19327 :style radio :selected (equal org-agenda-ndays 1)]
19328 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19329 :style radio :selected (equal org-agenda-ndays 7)]
19330 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19331 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19332 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19333 :style radio :selected (member org-agenda-ndays '(365 366))]
19334 "--"
19335 ["Show Logbook entries" org-agenda-log-mode
19336 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19337 ["Include Diary" org-agenda-toggle-diary
19338 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19339 ["Use Time Grid" org-agenda-toggle-time-grid
19340 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19341 ["Write view to file" org-write-agenda t]
19342 ["Rebuild buffer" org-agenda-redo t]
19343 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19344 "--"
19345 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19346 "--"
19347 ["Quit" org-agenda-quit t]
19348 ["Exit and Release Buffers" org-agenda-exit t]
19351 ;;; Agenda undo
19353 (defvar org-agenda-allow-remote-undo t
19354 "Non-nil means, allow remote undo from the agenda buffer.")
19355 (defvar org-agenda-undo-list nil
19356 "List of undoable operations in the agenda since last refresh.")
19357 (defvar org-agenda-undo-has-started-in nil
19358 "Buffers that have already seen `undo-start' in the current undo sequence.")
19359 (defvar org-agenda-pending-undo-list nil
19360 "In a series of undo commands, this is the list of remaning undo items.")
19362 (defmacro org-if-unprotected (&rest body)
19363 "Execute BODY if there is no `org-protected' text property at point."
19364 (declare (debug t))
19365 `(unless (get-text-property (point) 'org-protected)
19366 ,@body))
19368 (defmacro org-with-remote-undo (_buffer &rest _body)
19369 "Execute BODY while recording undo information in two buffers."
19370 (declare (indent 1) (debug t))
19371 `(let ((_cline (org-current-line))
19372 (_cmd this-command)
19373 (_buf1 (current-buffer))
19374 (_buf2 ,_buffer)
19375 (_undo1 buffer-undo-list)
19376 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19377 _c1 _c2)
19378 ,@_body
19379 (when org-agenda-allow-remote-undo
19380 (setq _c1 (org-verify-change-for-undo
19381 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19382 _c2 (org-verify-change-for-undo
19383 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19384 (when (or _c1 _c2)
19385 ;; make sure there are undo boundaries
19386 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19387 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19388 ;; remember which buffer to undo
19389 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19390 org-agenda-undo-list)))))
19392 (defun org-agenda-undo ()
19393 "Undo a remote editing step in the agenda.
19394 This undoes changes both in the agenda buffer and in the remote buffer
19395 that have been changed along."
19396 (interactive)
19397 (or org-agenda-allow-remote-undo
19398 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19399 (if (not (eq this-command last-command))
19400 (setq org-agenda-undo-has-started-in nil
19401 org-agenda-pending-undo-list org-agenda-undo-list))
19402 (if (not org-agenda-pending-undo-list)
19403 (error "No further undo information"))
19404 (let* ((entry (pop org-agenda-pending-undo-list))
19405 buf line cmd rembuf)
19406 (setq cmd (pop entry) line (pop entry))
19407 (setq rembuf (nth 2 entry))
19408 (org-with-remote-undo rembuf
19409 (while (bufferp (setq buf (pop entry)))
19410 (if (pop entry)
19411 (with-current-buffer buf
19412 (let ((last-undo-buffer buf)
19413 (inhibit-read-only t))
19414 (unless (memq buf org-agenda-undo-has-started-in)
19415 (push buf org-agenda-undo-has-started-in)
19416 (make-local-variable 'pending-undo-list)
19417 (undo-start))
19418 (while (and pending-undo-list
19419 (listp pending-undo-list)
19420 (not (car pending-undo-list)))
19421 (pop pending-undo-list))
19422 (undo-more 1))))))
19423 (goto-line line)
19424 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19426 (defun org-verify-change-for-undo (l1 l2)
19427 "Verify that a real change occurred between the undo lists L1 and L2."
19428 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19429 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19430 (not (eq l1 l2)))
19432 ;;; Agenda dispatch
19434 (defvar org-agenda-restrict nil)
19435 (defvar org-agenda-restrict-begin (make-marker))
19436 (defvar org-agenda-restrict-end (make-marker))
19437 (defvar org-agenda-last-dispatch-buffer nil)
19438 (defvar org-agenda-overriding-restriction nil)
19440 ;;;###autoload
19441 (defun org-agenda (arg &optional keys restriction)
19442 "Dispatch agenda commands to collect entries to the agenda buffer.
19443 Prompts for a command to execute. Any prefix arg will be passed
19444 on to the selected command. The default selections are:
19446 a Call `org-agenda-list' to display the agenda for current day or week.
19447 t Call `org-todo-list' to display the global todo list.
19448 T Call `org-todo-list' to display the global todo list, select only
19449 entries with a specific TODO keyword (the user gets a prompt).
19450 m Call `org-tags-view' to display headlines with tags matching
19451 a condition (the user is prompted for the condition).
19452 M Like `m', but select only TODO entries, no ordinary headlines.
19453 L Create a timeline for the current buffer.
19454 e Export views to associated files.
19456 More commands can be added by configuring the variable
19457 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19458 searches can be pre-defined in this way.
19460 If the current buffer is in Org-mode and visiting a file, you can also
19461 first press `<' once to indicate that the agenda should be temporarily
19462 \(until the next use of \\[org-agenda]) restricted to the current file.
19463 Pressing `<' twice means to restrict to the current subtree or region
19464 \(if active)."
19465 (interactive "P")
19466 (catch 'exit
19467 (let* ((prefix-descriptions nil)
19468 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19469 (org-agenda-custom-commands
19470 ;; normalize different versions
19471 (delq nil
19472 (mapcar
19473 (lambda (x)
19474 (cond ((stringp (cdr x))
19475 (push x prefix-descriptions)
19476 nil)
19477 ((stringp (nth 1 x)) x)
19478 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19479 (t (cons (car x) (cons "" (cdr x))))))
19480 org-agenda-custom-commands)))
19481 (buf (current-buffer))
19482 (bfn (buffer-file-name (buffer-base-buffer)))
19483 entry key type match lprops ans)
19484 ;; Turn off restriction unless there is an overriding one
19485 (unless org-agenda-overriding-restriction
19486 (put 'org-agenda-files 'org-restrict nil)
19487 (setq org-agenda-restrict nil)
19488 (move-marker org-agenda-restrict-begin nil)
19489 (move-marker org-agenda-restrict-end nil))
19490 ;; Delete old local properties
19491 (put 'org-agenda-redo-command 'org-lprops nil)
19492 ;; Remember where this call originated
19493 (setq org-agenda-last-dispatch-buffer (current-buffer))
19494 (unless keys
19495 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19496 keys (car ans)
19497 restriction (cdr ans)))
19498 ;; Estabish the restriction, if any
19499 (when (and (not org-agenda-overriding-restriction) restriction)
19500 (put 'org-agenda-files 'org-restrict (list bfn))
19501 (cond
19502 ((eq restriction 'region)
19503 (setq org-agenda-restrict t)
19504 (move-marker org-agenda-restrict-begin (region-beginning))
19505 (move-marker org-agenda-restrict-end (region-end)))
19506 ((eq restriction 'subtree)
19507 (save-excursion
19508 (setq org-agenda-restrict t)
19509 (org-back-to-heading t)
19510 (move-marker org-agenda-restrict-begin (point))
19511 (move-marker org-agenda-restrict-end
19512 (progn (org-end-of-subtree t)))))))
19514 (require 'calendar) ; FIXME: can we avoid this for some commands?
19515 ;; For example the todo list should not need it (but does...)
19516 (cond
19517 ((setq entry (assoc keys org-agenda-custom-commands))
19518 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19519 (progn
19520 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19521 (put 'org-agenda-redo-command 'org-lprops lprops)
19522 (cond
19523 ((eq type 'agenda)
19524 (org-let lprops '(org-agenda-list current-prefix-arg)))
19525 ((eq type 'alltodo)
19526 (org-let lprops '(org-todo-list current-prefix-arg)))
19527 ((eq type 'stuck)
19528 (org-let lprops '(org-agenda-list-stuck-projects
19529 current-prefix-arg)))
19530 ((eq type 'tags)
19531 (org-let lprops '(org-tags-view current-prefix-arg match)))
19532 ((eq type 'tags-todo)
19533 (org-let lprops '(org-tags-view '(4) match)))
19534 ((eq type 'todo)
19535 (org-let lprops '(org-todo-list match)))
19536 ((eq type 'tags-tree)
19537 (org-check-for-org-mode)
19538 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19539 ((eq type 'todo-tree)
19540 (org-check-for-org-mode)
19541 (org-let lprops
19542 '(org-occur (concat "^" outline-regexp "[ \t]*"
19543 (regexp-quote match) "\\>"))))
19544 ((eq type 'occur-tree)
19545 (org-check-for-org-mode)
19546 (org-let lprops '(org-occur match)))
19547 ((functionp type)
19548 (org-let lprops '(funcall type match)))
19549 ((fboundp type)
19550 (org-let lprops '(funcall type match)))
19551 (t (error "Invalid custom agenda command type %s" type))))
19552 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19553 ((equal keys "C")
19554 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19555 (customize-variable 'org-agenda-custom-commands))
19556 ((equal keys "a") (call-interactively 'org-agenda-list))
19557 ((equal keys "t") (call-interactively 'org-todo-list))
19558 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19559 ((equal keys "m") (call-interactively 'org-tags-view))
19560 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19561 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19562 ((equal keys "L")
19563 (unless (org-mode-p)
19564 (error "This is not an Org-mode file"))
19565 (unless restriction
19566 (put 'org-agenda-files 'org-restrict (list bfn))
19567 (org-call-with-arg 'org-timeline arg)))
19568 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19569 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19570 ((equal keys "!") (customize-variable 'org-stuck-projects))
19571 (t (error "Invalid agenda key"))))))
19573 (defun org-agenda-normalize-custom-commands (cmds)
19574 (delq nil
19575 (mapcar
19576 (lambda (x)
19577 (cond ((stringp (cdr x)) nil)
19578 ((stringp (nth 1 x)) x)
19579 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19580 (t (cons (car x) (cons "" (cdr x))))))
19581 cmds)))
19583 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19584 "The user interface for selecting an agenda command."
19585 (catch 'exit
19586 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19587 (restrict-ok (and bfn (org-mode-p)))
19588 (region-p (org-region-active-p))
19589 (custom org-agenda-custom-commands)
19590 (selstring "")
19591 restriction second-time
19592 c entry key type match prefixes rmheader header-end custom1 desc)
19593 (save-window-excursion
19594 (delete-other-windows)
19595 (org-switch-to-buffer-other-window " *Agenda Commands*")
19596 (erase-buffer)
19597 (insert (eval-when-compile
19598 (let ((header
19600 Press key for an agenda command: < Buffer,subtree/region restriction
19601 -------------------------------- > Remove restriction
19602 a Agenda for current week or day e Export agenda views
19603 t List of all TODO entries T Entries with special TODO kwd
19604 m Match a TAGS query M Like m, but only TODO entries
19605 L Timeline for current buffer # List stuck projects (!=configure)
19606 / Multi-occur C Configure custom agenda commands
19608 (start 0))
19609 (while (string-match
19610 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19611 header start)
19612 (setq start (match-end 0))
19613 (add-text-properties (match-beginning 2) (match-end 2)
19614 '(face bold) header))
19615 header)))
19616 (setq header-end (move-marker (make-marker) (point)))
19617 (while t
19618 (setq custom1 custom)
19619 (when (eq rmheader t)
19620 (goto-line 1)
19621 (re-search-forward ":" nil t)
19622 (delete-region (match-end 0) (point-at-eol))
19623 (forward-char 1)
19624 (looking-at "-+")
19625 (delete-region (match-end 0) (point-at-eol))
19626 (move-marker header-end (match-end 0)))
19627 (goto-char header-end)
19628 (delete-region (point) (point-max))
19629 (while (setq entry (pop custom1))
19630 (setq key (car entry) desc (nth 1 entry)
19631 type (nth 2 entry) match (nth 3 entry))
19632 (if (> (length key) 1)
19633 (add-to-list 'prefixes (string-to-char key))
19634 (insert
19635 (format
19636 "\n%-4s%-14s: %s"
19637 (org-add-props (copy-sequence key)
19638 '(face bold))
19639 (cond
19640 ((string-match "\\S-" desc) desc)
19641 ((eq type 'agenda) "Agenda for current week or day")
19642 ((eq type 'alltodo) "List of all TODO entries")
19643 ((eq type 'stuck) "List of stuck projects")
19644 ((eq type 'todo) "TODO keyword")
19645 ((eq type 'tags) "Tags query")
19646 ((eq type 'tags-todo) "Tags (TODO)")
19647 ((eq type 'tags-tree) "Tags tree")
19648 ((eq type 'todo-tree) "TODO kwd tree")
19649 ((eq type 'occur-tree) "Occur tree")
19650 ((functionp type) (if (symbolp type)
19651 (symbol-name type)
19652 "Lambda expression"))
19653 (t "???"))
19654 (cond
19655 ((stringp match)
19656 (org-add-props match nil 'face 'org-warning))
19657 (match
19658 (format "set of %d commands" (length match)))
19659 (t ""))))))
19660 (when prefixes
19661 (mapc (lambda (x)
19662 (insert
19663 (format "\n%s %s"
19664 (org-add-props (char-to-string x)
19665 nil 'face 'bold)
19666 (or (cdr (assoc (concat selstring (char-to-string x))
19667 prefix-descriptions))
19668 "Prefix key"))))
19669 prefixes))
19670 (goto-char (point-min))
19671 (when (fboundp 'fit-window-to-buffer)
19672 (if second-time
19673 (if (not (pos-visible-in-window-p (point-max)))
19674 (fit-window-to-buffer))
19675 (setq second-time t)
19676 (fit-window-to-buffer)))
19677 (message "Press key for agenda command%s:"
19678 (if (or restrict-ok org-agenda-overriding-restriction)
19679 (if org-agenda-overriding-restriction
19680 " (restriction lock active)"
19681 (if restriction
19682 (format " (restricted to %s)" restriction)
19683 " (unrestricted)"))
19684 ""))
19685 (setq c (read-char-exclusive))
19686 (message "")
19687 (cond
19688 ((assoc (char-to-string c) custom)
19689 (setq selstring (concat selstring (char-to-string c)))
19690 (throw 'exit (cons selstring restriction)))
19691 ((memq c prefixes)
19692 (setq selstring (concat selstring (char-to-string c))
19693 prefixes nil
19694 rmheader (or rmheader t)
19695 custom (delq nil (mapcar
19696 (lambda (x)
19697 (if (or (= (length (car x)) 1)
19698 (/= (string-to-char (car x)) c))
19700 (cons (substring (car x) 1) (cdr x))))
19701 custom))))
19702 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19703 (message "Restriction is only possible in Org-mode buffers")
19704 (ding) (sit-for 1))
19705 ((eq c ?1)
19706 (org-agenda-remove-restriction-lock 'noupdate)
19707 (setq restriction 'buffer))
19708 ((eq c ?0)
19709 (org-agenda-remove-restriction-lock 'noupdate)
19710 (setq restriction (if region-p 'region 'subtree)))
19711 ((eq c ?<)
19712 (org-agenda-remove-restriction-lock 'noupdate)
19713 (setq restriction
19714 (cond
19715 ((eq restriction 'buffer)
19716 (if region-p 'region 'subtree))
19717 ((memq restriction '(subtree region))
19718 nil)
19719 (t 'buffer))))
19720 ((eq c ?>)
19721 (org-agenda-remove-restriction-lock 'noupdate)
19722 (setq restriction nil))
19723 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19724 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19725 ((and (> (length selstring) 0) (eq c ?\d))
19726 (delete-window)
19727 (org-agenda-get-restriction-and-command prefix-descriptions))
19729 ((equal c ?q) (error "Abort"))
19730 (t (error "Invalid key %c" c))))))))
19732 (defun org-run-agenda-series (name series)
19733 (org-prepare-agenda name)
19734 (let* ((org-agenda-multi t)
19735 (redo (list 'org-run-agenda-series name (list 'quote series)))
19736 (cmds (car series))
19737 (gprops (nth 1 series))
19738 match ;; The byte compiler incorrectly complains about this. Keep it!
19739 cmd type lprops)
19740 (while (setq cmd (pop cmds))
19741 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19742 (cond
19743 ((eq type 'agenda)
19744 (org-let2 gprops lprops
19745 '(call-interactively 'org-agenda-list)))
19746 ((eq type 'alltodo)
19747 (org-let2 gprops lprops
19748 '(call-interactively 'org-todo-list)))
19749 ((eq type 'stuck)
19750 (org-let2 gprops lprops
19751 '(call-interactively 'org-agenda-list-stuck-projects)))
19752 ((eq type 'tags)
19753 (org-let2 gprops lprops
19754 '(org-tags-view current-prefix-arg match)))
19755 ((eq type 'tags-todo)
19756 (org-let2 gprops lprops
19757 '(org-tags-view '(4) match)))
19758 ((eq type 'todo)
19759 (org-let2 gprops lprops
19760 '(org-todo-list match)))
19761 ((fboundp type)
19762 (org-let2 gprops lprops
19763 '(funcall type match)))
19764 (t (error "Invalid type in command series"))))
19765 (widen)
19766 (setq org-agenda-redo-command redo)
19767 (goto-char (point-min)))
19768 (org-finalize-agenda))
19770 ;;;###autoload
19771 (defmacro org-batch-agenda (cmd-key &rest parameters)
19772 "Run an agenda command in batch mode and send the result to STDOUT.
19773 If CMD-KEY is a string of length 1, it is used as a key in
19774 `org-agenda-custom-commands' and triggers this command. If it is a
19775 longer string it is used as a tags/todo match string.
19776 Paramters are alternating variable names and values that will be bound
19777 before running the agenda command."
19778 (let (pars)
19779 (while parameters
19780 (push (list (pop parameters) (if parameters (pop parameters))) 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 (princ (org-encode-for-stdout (buffer-string)))))
19788 (defun org-encode-for-stdout (string)
19789 (if (fboundp 'encode-coding-string)
19790 (encode-coding-string string buffer-file-coding-system)
19791 string))
19793 (defvar org-agenda-info nil)
19795 ;;;###autoload
19796 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19797 "Run an agenda command in batch mode and send the result to STDOUT.
19798 If CMD-KEY is a string of length 1, it is used as a key in
19799 `org-agenda-custom-commands' and triggers this command. If it is a
19800 longer string it is used as a tags/todo match string.
19801 Paramters are alternating variable names and values that will be bound
19802 before running the agenda command.
19804 The output gives a line for each selected agenda item. Each
19805 item is a list of comma-separated values, like this:
19807 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19809 category The category of the item
19810 head The headline, without TODO kwd, TAGS and PRIORITY
19811 type The type of the agenda entry, can be
19812 todo selected in TODO match
19813 tagsmatch selected in tags match
19814 diary imported from diary
19815 deadline a deadline on given date
19816 scheduled scheduled on given date
19817 timestamp entry has timestamp on given date
19818 closed entry was closed on given date
19819 upcoming-deadline warning about deadline
19820 past-scheduled forwarded scheduled item
19821 block entry has date block including g. date
19822 todo The todo keyword, if any
19823 tags All tags including inherited ones, separated by colons
19824 date The relevant date, like 2007-2-14
19825 time The time, like 15:00-16:50
19826 extra Sting with extra planning info
19827 priority-l The priority letter if any was given
19828 priority-n The computed numerical priority
19829 agenda-day The day in the agenda where this is listed"
19831 (let (pars)
19832 (while parameters
19833 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19834 (push (list 'org-agenda-remove-tags t) pars)
19835 (if (> (length cmd-key) 2)
19836 (eval (list 'let (nreverse pars)
19837 (list 'org-tags-view nil cmd-key)))
19838 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19839 (set-buffer org-agenda-buffer-name)
19840 (let* ((lines (org-split-string (buffer-string) "\n"))
19841 line)
19842 (while (setq line (pop lines))
19843 (catch 'next
19844 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19845 (setq org-agenda-info
19846 (org-fix-agenda-info (text-properties-at 0 line)))
19847 (princ
19848 (org-encode-for-stdout
19849 (mapconcat 'org-agenda-export-csv-mapper
19850 '(org-category txt type todo tags date time-of-day extra
19851 priority-letter priority agenda-day)
19852 ",")))
19853 (princ "\n"))))))
19855 (defun org-fix-agenda-info (props)
19856 "Make sure all properties on an agenda item have a canonical form,
19857 so the export commands can easily use it."
19858 (let (tmp re)
19859 (when (setq tmp (plist-get props 'tags))
19860 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19861 (when (setq tmp (plist-get props 'date))
19862 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19863 (let ((calendar-date-display-form '(year "-" month "-" day)))
19864 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19866 (setq tmp (calendar-date-string tmp)))
19867 (setq props (plist-put props 'date tmp)))
19868 (when (setq tmp (plist-get props 'day))
19869 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19870 (let ((calendar-date-display-form '(year "-" month "-" day)))
19871 (setq tmp (calendar-date-string tmp)))
19872 (setq props (plist-put props 'day tmp))
19873 (setq props (plist-put props 'agenda-day tmp)))
19874 (when (setq tmp (plist-get props 'txt))
19875 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19876 (plist-put props 'priority-letter (match-string 1 tmp))
19877 (setq tmp (replace-match "" t t tmp)))
19878 (when (and (setq re (plist-get props 'org-todo-regexp))
19879 (setq re (concat "\\`\\.*" re " ?"))
19880 (string-match re tmp))
19881 (plist-put props 'todo (match-string 1 tmp))
19882 (setq tmp (replace-match "" t t tmp)))
19883 (plist-put props 'txt tmp)))
19884 props)
19886 (defun org-agenda-export-csv-mapper (prop)
19887 (let ((res (plist-get org-agenda-info prop)))
19888 (setq res
19889 (cond
19890 ((not res) "")
19891 ((stringp res) res)
19892 (t (prin1-to-string res))))
19893 (while (string-match "," res)
19894 (setq res (replace-match ";" t t res)))
19895 (org-trim res)))
19898 ;;;###autoload
19899 (defun org-store-agenda-views (&rest parameters)
19900 (interactive)
19901 (eval (list 'org-batch-store-agenda-views)))
19903 ;; FIXME, why is this a macro?????
19904 ;;;###autoload
19905 (defmacro org-batch-store-agenda-views (&rest parameters)
19906 "Run all custom agenda commands that have a file argument."
19907 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
19908 (pop-up-frames nil)
19909 (dir default-directory)
19910 pars cmd thiscmdkey files opts)
19911 (while parameters
19912 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19913 (setq pars (reverse pars))
19914 (save-window-excursion
19915 (while cmds
19916 (setq cmd (pop cmds)
19917 thiscmdkey (car cmd)
19918 opts (nth 4 cmd)
19919 files (nth 5 cmd))
19920 (if (stringp files) (setq files (list files)))
19921 (when files
19922 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19923 (list 'org-agenda nil thiscmdkey)))
19924 (set-buffer org-agenda-buffer-name)
19925 (while files
19926 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19927 (list 'org-write-agenda
19928 (expand-file-name (pop files) dir) t))))
19929 (and (get-buffer org-agenda-buffer-name)
19930 (kill-buffer org-agenda-buffer-name)))))))
19932 (defun org-write-agenda (file &optional nosettings)
19933 "Write the current buffer (an agenda view) as a file.
19934 Depending on the extension of the file name, plain text (.txt),
19935 HTML (.html or .htm) or Postscript (.ps) is produced.
19936 If NOSETTINGS is given, do not scope the settings of
19937 `org-agenda-exporter-settings' into the export commands. This is used when
19938 the settings have already been scoped and we do not wish to overrule other,
19939 higher priority settings."
19940 (interactive "FWrite agenda to file: ")
19941 (if (not (file-writable-p file))
19942 (error "Cannot write agenda to file %s" file))
19943 (cond
19944 ((string-match "\\.html?\\'" file) (require 'htmlize))
19945 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19946 (org-let (if nosettings nil org-agenda-exporter-settings)
19947 '(save-excursion
19948 (save-window-excursion
19949 (cond
19950 ((string-match "\\.html?\\'" file)
19951 (set-buffer (htmlize-buffer (current-buffer)))
19953 (when (and org-agenda-export-html-style
19954 (string-match "<style>" org-agenda-export-html-style))
19955 ;; replace <style> section with org-agenda-export-html-style
19956 (goto-char (point-min))
19957 (kill-region (- (search-forward "<style") 6)
19958 (search-forward "</style>"))
19959 (insert org-agenda-export-html-style))
19960 (write-file file)
19961 (kill-buffer (current-buffer))
19962 (message "HTML written to %s" file))
19963 ((string-match "\\.ps\\'" file)
19964 (ps-print-buffer-with-faces file)
19965 (message "Postscript written to %s" file))
19967 (let ((bs (buffer-string)))
19968 (find-file file)
19969 (insert bs)
19970 (save-buffer 0)
19971 (kill-buffer (current-buffer))
19972 (message "Plain text written to %s" file))))))
19973 (set-buffer org-agenda-buffer-name)))
19975 (defmacro org-no-read-only (&rest body)
19976 "Inhibit read-only for BODY."
19977 `(let ((inhibit-read-only t)) ,@body))
19979 (defun org-check-for-org-mode ()
19980 "Make sure current buffer is in org-mode. Error if not."
19981 (or (org-mode-p)
19982 (error "Cannot execute org-mode agenda command on buffer in %s."
19983 major-mode)))
19985 (defun org-fit-agenda-window ()
19986 "Fit the window to the buffer size."
19987 (and (memq org-agenda-window-setup '(reorganize-frame))
19988 (fboundp 'fit-window-to-buffer)
19989 (fit-window-to-buffer
19991 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
19992 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
19994 ;;; Agenda file list
19996 (defun org-agenda-files (&optional unrestricted)
19997 "Get the list of agenda files.
19998 Optional UNRESTRICTED means return the full list even if a restriction
19999 is currently in place."
20000 (let ((files
20001 (cond
20002 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20003 ((stringp org-agenda-files) (org-read-agenda-file-list))
20004 ((listp org-agenda-files) org-agenda-files)
20005 (t (error "Invalid value of `org-agenda-files'")))))
20006 (setq files (apply 'append
20007 (mapcar (lambda (f)
20008 (if (file-directory-p f)
20009 (directory-files f t
20010 org-agenda-file-regexp)
20011 (list f)))
20012 files)))
20013 (if org-agenda-skip-unavailable-files
20014 (delq nil
20015 (mapcar (function
20016 (lambda (file)
20017 (and (file-readable-p file) file)))
20018 files))
20019 files))) ; `org-check-agenda-file' will remove them from the list
20021 (defun org-edit-agenda-file-list ()
20022 "Edit the list of agenda files.
20023 Depending on setup, this either uses customize to edit the variable
20024 `org-agenda-files', or it visits the file that is holding the list. In the
20025 latter case, the buffer is set up in a way that saving it automatically kills
20026 the buffer and restores the previous window configuration."
20027 (interactive)
20028 (if (stringp org-agenda-files)
20029 (let ((cw (current-window-configuration)))
20030 (find-file org-agenda-files)
20031 (org-set-local 'org-window-configuration cw)
20032 (org-add-hook 'after-save-hook
20033 (lambda ()
20034 (set-window-configuration
20035 (prog1 org-window-configuration
20036 (kill-buffer (current-buffer))))
20037 (org-install-agenda-files-menu)
20038 (message "New agenda file list installed"))
20039 nil 'local)
20040 (message "%s" (substitute-command-keys
20041 "Edit list and finish with \\[save-buffer]")))
20042 (customize-variable 'org-agenda-files)))
20044 (defun org-store-new-agenda-file-list (list)
20045 "Set new value for the agenda file list and save it correcly."
20046 (if (stringp org-agenda-files)
20047 (let ((f org-agenda-files) b)
20048 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20049 (with-temp-file f
20050 (insert (mapconcat 'identity list "\n") "\n")))
20051 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20052 (setq org-agenda-files list)
20053 (customize-save-variable 'org-agenda-files org-agenda-files))))
20055 (defun org-read-agenda-file-list ()
20056 "Read the list of agenda files from a file."
20057 (when (stringp org-agenda-files)
20058 (with-temp-buffer
20059 (insert-file-contents org-agenda-files)
20060 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20063 ;;;###autoload
20064 (defun org-cycle-agenda-files ()
20065 "Cycle through the files in `org-agenda-files'.
20066 If the current buffer visits an agenda file, find the next one in the list.
20067 If the current buffer does not, find the first agenda file."
20068 (interactive)
20069 (let* ((fs (org-agenda-files t))
20070 (files (append fs (list (car fs))))
20071 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20072 file)
20073 (unless files (error "No agenda files"))
20074 (catch 'exit
20075 (while (setq file (pop files))
20076 (if (equal (file-truename file) tcf)
20077 (when (car files)
20078 (find-file (car files))
20079 (throw 'exit t))))
20080 (find-file (car fs)))
20081 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20083 (defun org-agenda-file-to-front (&optional to-end)
20084 "Move/add the current file to the top of the agenda file list.
20085 If the file is not present in the list, it is added to the front. If it is
20086 present, it is moved there. With optional argument TO-END, add/move to the
20087 end of the list."
20088 (interactive "P")
20089 (let ((org-agenda-skip-unavailable-files nil)
20090 (file-alist (mapcar (lambda (x)
20091 (cons (file-truename x) x))
20092 (org-agenda-files t)))
20093 (ctf (file-truename buffer-file-name))
20094 x had)
20095 (setq x (assoc ctf file-alist) had x)
20097 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20098 (if to-end
20099 (setq file-alist (append (delq x file-alist) (list x)))
20100 (setq file-alist (cons x (delq x file-alist))))
20101 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20102 (org-install-agenda-files-menu)
20103 (message "File %s to %s of agenda file list"
20104 (if had "moved" "added") (if to-end "end" "front"))))
20106 (defun org-remove-file (&optional file)
20107 "Remove current file from the list of files in variable `org-agenda-files'.
20108 These are the files which are being checked for agenda entries.
20109 Optional argument FILE means, use this file instead of the current."
20110 (interactive)
20111 (let* ((org-agenda-skip-unavailable-files nil)
20112 (file (or file buffer-file-name))
20113 (true-file (file-truename file))
20114 (afile (abbreviate-file-name file))
20115 (files (delq nil (mapcar
20116 (lambda (x)
20117 (if (equal true-file
20118 (file-truename x))
20119 nil x))
20120 (org-agenda-files t)))))
20121 (if (not (= (length files) (length (org-agenda-files t))))
20122 (progn
20123 (org-store-new-agenda-file-list files)
20124 (org-install-agenda-files-menu)
20125 (message "Removed file: %s" afile))
20126 (message "File was not in list: %s (not removed)" afile))))
20128 (defun org-file-menu-entry (file)
20129 (vector file (list 'find-file file) t))
20131 (defun org-check-agenda-file (file)
20132 "Make sure FILE exists. If not, ask user what to do."
20133 (when (not (file-exists-p file))
20134 (message "non-existent file %s. [R]emove from list or [A]bort?"
20135 (abbreviate-file-name file))
20136 (let ((r (downcase (read-char-exclusive))))
20137 (cond
20138 ((equal r ?r)
20139 (org-remove-file file)
20140 (throw 'nextfile t))
20141 (t (error "Abort"))))))
20143 ;;; Agenda prepare and finalize
20145 (defvar org-agenda-multi nil) ; dynammically scoped
20146 (defvar org-agenda-buffer-name "*Org Agenda*")
20147 (defvar org-pre-agenda-window-conf nil)
20148 (defvar org-agenda-name nil)
20149 (defun org-prepare-agenda (&optional name)
20150 (setq org-todo-keywords-for-agenda nil)
20151 (setq org-done-keywords-for-agenda nil)
20152 (if org-agenda-multi
20153 (progn
20154 (setq buffer-read-only nil)
20155 (goto-char (point-max))
20156 (unless (or (bobp) org-agenda-compact-blocks)
20157 (insert "\n" (make-string (window-width) ?=) "\n"))
20158 (narrow-to-region (point) (point-max)))
20159 (org-agenda-maybe-reset-markers 'force)
20160 (org-prepare-agenda-buffers (org-agenda-files))
20161 (setq org-todo-keywords-for-agenda
20162 (org-uniquify org-todo-keywords-for-agenda))
20163 (setq org-done-keywords-for-agenda
20164 (org-uniquify org-done-keywords-for-agenda))
20165 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20166 (awin (get-buffer-window abuf)))
20167 (cond
20168 ((equal (current-buffer) abuf) nil)
20169 (awin (select-window awin))
20170 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20171 ((equal org-agenda-window-setup 'current-window)
20172 (switch-to-buffer abuf))
20173 ((equal org-agenda-window-setup 'other-window)
20174 (org-switch-to-buffer-other-window abuf))
20175 ((equal org-agenda-window-setup 'other-frame)
20176 (switch-to-buffer-other-frame abuf))
20177 ((equal org-agenda-window-setup 'reorganize-frame)
20178 (delete-other-windows)
20179 (org-switch-to-buffer-other-window abuf))))
20180 (setq buffer-read-only nil)
20181 (erase-buffer)
20182 (org-agenda-mode)
20183 (and name (not org-agenda-name)
20184 (org-set-local 'org-agenda-name name)))
20185 (setq buffer-read-only nil))
20187 (defun org-finalize-agenda ()
20188 "Finishing touch for the agenda buffer, called just before displaying it."
20189 (unless org-agenda-multi
20190 (save-excursion
20191 (let ((inhibit-read-only t))
20192 (goto-char (point-min))
20193 (while (org-activate-bracket-links (point-max))
20194 (add-text-properties (match-beginning 0) (match-end 0)
20195 '(face org-link)))
20196 (org-agenda-align-tags)
20197 (unless org-agenda-with-colors
20198 (remove-text-properties (point-min) (point-max) '(face nil))))
20199 (if (and (boundp 'org-overriding-columns-format)
20200 org-overriding-columns-format)
20201 (org-set-local 'org-overriding-columns-format
20202 org-overriding-columns-format))
20203 (if (and (boundp 'org-agenda-view-columns-initially)
20204 org-agenda-view-columns-initially)
20205 (org-agenda-columns))
20206 (when org-agenda-fontify-priorities
20207 (org-fontify-priorities))
20208 (run-hooks 'org-finalize-agenda-hook)
20209 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20212 (defun org-fontify-priorities ()
20213 "Make highest priority lines bold, and lowest italic."
20214 (interactive)
20215 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20216 (org-delete-overlay o)))
20217 (org-overlays-in (point-min) (point-max)))
20218 (save-excursion
20219 (let ((inhibit-read-only t)
20220 b e p ov h l)
20221 (goto-char (point-min))
20222 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20223 (setq h (or (get-char-property (point) 'org-highest-priority)
20224 org-highest-priority)
20225 l (or (get-char-property (point) 'org-lowest-priority)
20226 org-lowest-priority)
20227 p (string-to-char (match-string 1))
20228 b (match-beginning 0) e (point-at-eol)
20229 ov (org-make-overlay b e))
20230 (org-overlay-put
20231 ov 'face
20232 (cond ((listp org-agenda-fontify-priorities)
20233 (cdr (assoc p org-agenda-fontify-priorities)))
20234 ((equal p l) 'italic)
20235 ((equal p h) 'bold)))
20236 (org-overlay-put ov 'org-type 'org-priority)))))
20238 (defun org-prepare-agenda-buffers (files)
20239 "Create buffers for all agenda files, protect archived trees and comments."
20240 (interactive)
20241 (let ((pa '(:org-archived t))
20242 (pc '(:org-comment t))
20243 (pall '(:org-archived t :org-comment t))
20244 (inhibit-read-only t)
20245 (rea (concat ":" org-archive-tag ":"))
20246 bmp file re)
20247 (save-excursion
20248 (save-restriction
20249 (while (setq file (pop files))
20250 (if (bufferp file)
20251 (set-buffer file)
20252 (org-check-agenda-file file)
20253 (set-buffer (org-get-agenda-file-buffer file)))
20254 (widen)
20255 (setq bmp (buffer-modified-p))
20256 (org-refresh-category-properties)
20257 (setq org-todo-keywords-for-agenda
20258 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20259 (setq org-done-keywords-for-agenda
20260 (append org-done-keywords-for-agenda org-done-keywords))
20261 (save-excursion
20262 (remove-text-properties (point-min) (point-max) pall)
20263 (when org-agenda-skip-archived-trees
20264 (goto-char (point-min))
20265 (while (re-search-forward rea nil t)
20266 (if (org-on-heading-p t)
20267 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20268 (goto-char (point-min))
20269 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20270 (while (re-search-forward re nil t)
20271 (add-text-properties
20272 (match-beginning 0) (org-end-of-subtree t) pc)))
20273 (set-buffer-modified-p bmp))))))
20275 (defvar org-agenda-skip-function nil
20276 "Function to be called at each match during agenda construction.
20277 If this function returns nil, the current match should not be skipped.
20278 Otherwise, the function must return a position from where the search
20279 should be continued.
20280 This may also be a Lisp form, it will be evaluated.
20281 Never set this variable using `setq' or so, because then it will apply
20282 to all future agenda commands. Instead, bind it with `let' to scope
20283 it dynamically into the agenda-constructing command. A good way to set
20284 it is through options in org-agenda-custom-commands.")
20286 (defun org-agenda-skip ()
20287 "Throw to `:skip' in places that should be skipped.
20288 Also moves point to the end of the skipped region, so that search can
20289 continue from there."
20290 (let ((p (point-at-bol)) to fp)
20291 (and org-agenda-skip-archived-trees
20292 (get-text-property p :org-archived)
20293 (org-end-of-subtree t)
20294 (throw :skip t))
20295 (and (get-text-property p :org-comment)
20296 (org-end-of-subtree t)
20297 (throw :skip t))
20298 (if (equal (char-after p) ?#) (throw :skip t))
20299 (when (and (or (setq fp (functionp org-agenda-skip-function))
20300 (consp org-agenda-skip-function))
20301 (setq to (save-excursion
20302 (save-match-data
20303 (if fp
20304 (funcall org-agenda-skip-function)
20305 (eval org-agenda-skip-function))))))
20306 (goto-char to)
20307 (throw :skip t))))
20309 (defvar org-agenda-markers nil
20310 "List of all currently active markers created by `org-agenda'.")
20311 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20312 "Creation time of the last agenda marker.")
20314 (defun org-agenda-new-marker (&optional pos)
20315 "Return a new agenda marker.
20316 Org-mode keeps a list of these markers and resets them when they are
20317 no longer in use."
20318 (let ((m (copy-marker (or pos (point)))))
20319 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20320 (push m org-agenda-markers)
20323 (defun org-agenda-maybe-reset-markers (&optional force)
20324 "Reset markers created by `org-agenda'. But only if they are old enough."
20325 (if (or (and force (not org-agenda-multi))
20326 (> (- (time-to-seconds (current-time))
20327 org-agenda-last-marker-time)
20329 (while org-agenda-markers
20330 (move-marker (pop org-agenda-markers) nil))))
20332 (defun org-get-agenda-file-buffer (file)
20333 "Get a buffer visiting FILE. If the buffer needs to be created, add
20334 it to the list of buffers which might be released later."
20335 (let ((buf (org-find-base-buffer-visiting file)))
20336 (if buf
20337 buf ; just return it
20338 ;; Make a new buffer and remember it
20339 (setq buf (find-file-noselect file))
20340 (if buf (push buf org-agenda-new-buffers))
20341 buf)))
20343 (defun org-release-buffers (blist)
20344 "Release all buffers in list, asking the user for confirmation when needed.
20345 When a buffer is unmodified, it is just killed. When modified, it is saved
20346 \(if the user agrees) and then killed."
20347 (let (buf file)
20348 (while (setq buf (pop blist))
20349 (setq file (buffer-file-name buf))
20350 (when (and (buffer-modified-p buf)
20351 file
20352 (y-or-n-p (format "Save file %s? " file)))
20353 (with-current-buffer buf (save-buffer)))
20354 (kill-buffer buf))))
20356 (defun org-get-category (&optional pos)
20357 "Get the category applying to position POS."
20358 (get-text-property (or pos (point)) 'org-category))
20360 ;;; Agenda timeline
20362 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20364 (defun org-timeline (&optional include-all)
20365 "Show a time-sorted view of the entries in the current org file.
20366 Only entries with a time stamp of today or later will be listed. With
20367 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20368 under the current date.
20369 If the buffer contains an active region, only check the region for
20370 dates."
20371 (interactive "P")
20372 (require 'calendar)
20373 (org-compile-prefix-format 'timeline)
20374 (org-set-sorting-strategy 'timeline)
20375 (let* ((dopast t)
20376 (dotodo include-all)
20377 (doclosed org-agenda-show-log)
20378 (entry buffer-file-name)
20379 (date (calendar-current-date))
20380 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20381 (end (if (org-region-active-p) (region-end) (point-max)))
20382 (day-numbers (org-get-all-dates beg end 'no-ranges
20383 t doclosed ; always include today
20384 org-timeline-show-empty-dates))
20385 (org-deadline-warning-days 0)
20386 (org-agenda-only-exact-dates t)
20387 (today (time-to-days (current-time)))
20388 (past t)
20389 args
20390 s e rtn d emptyp)
20391 (setq org-agenda-redo-command
20392 (list 'progn
20393 (list 'org-switch-to-buffer-other-window (current-buffer))
20394 (list 'org-timeline (list 'quote include-all))))
20395 (if (not dopast)
20396 ;; Remove past dates from the list of dates.
20397 (setq day-numbers (delq nil (mapcar (lambda(x)
20398 (if (>= x today) x nil))
20399 day-numbers))))
20400 (org-prepare-agenda (concat "Timeline "
20401 (file-name-nondirectory buffer-file-name)))
20402 (if doclosed (push :closed args))
20403 (push :timestamp args)
20404 (push :deadline args)
20405 (push :scheduled args)
20406 (push :sexp args)
20407 (if dotodo (push :todo args))
20408 (while (setq d (pop day-numbers))
20409 (if (and (listp d) (eq (car d) :omitted))
20410 (progn
20411 (setq s (point))
20412 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20413 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20414 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20415 (if (and (>= d today)
20416 dopast
20417 past)
20418 (progn
20419 (setq past nil)
20420 (insert (make-string 79 ?-) "\n")))
20421 (setq date (calendar-gregorian-from-absolute d))
20422 (setq s (point))
20423 (setq rtn (and (not emptyp)
20424 (apply 'org-agenda-get-day-entries entry
20425 date args)))
20426 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20427 (progn
20428 (insert
20429 (if (stringp org-agenda-format-date)
20430 (format-time-string org-agenda-format-date
20431 (org-time-from-absolute date))
20432 (funcall org-agenda-format-date date))
20433 "\n")
20434 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20435 (put-text-property s (1- (point)) 'org-date-line t)
20436 (if (equal d today)
20437 (put-text-property s (1- (point)) 'org-today t))
20438 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20439 (put-text-property s (1- (point)) 'day d)))))
20440 (goto-char (point-min))
20441 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20442 (point-min)))
20443 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20444 (org-finalize-agenda)
20445 (setq buffer-read-only t)))
20447 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20448 "Return a list of all relevant day numbers from BEG to END buffer positions.
20449 If NO-RANGES is non-nil, include only the start and end dates of a range,
20450 not every single day in the range. If FORCE-TODAY is non-nil, make
20451 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20452 inactive time stamps (those in square brackets) are included.
20453 When EMPTY is non-nil, also include days without any entries."
20454 (let ((re (concat
20455 (if pre-re pre-re "")
20456 (if inactive org-ts-regexp-both org-ts-regexp)))
20457 dates dates1 date day day1 day2 ts1 ts2)
20458 (if force-today
20459 (setq dates (list (time-to-days (current-time)))))
20460 (save-excursion
20461 (goto-char beg)
20462 (while (re-search-forward re end t)
20463 (setq day (time-to-days (org-time-string-to-time
20464 (substring (match-string 1) 0 10))))
20465 (or (memq day dates) (push day dates)))
20466 (unless no-ranges
20467 (goto-char beg)
20468 (while (re-search-forward org-tr-regexp end t)
20469 (setq ts1 (substring (match-string 1) 0 10)
20470 ts2 (substring (match-string 2) 0 10)
20471 day1 (time-to-days (org-time-string-to-time ts1))
20472 day2 (time-to-days (org-time-string-to-time ts2)))
20473 (while (< (setq day1 (1+ day1)) day2)
20474 (or (memq day1 dates) (push day1 dates)))))
20475 (setq dates (sort dates '<))
20476 (when empty
20477 (while (setq day (pop dates))
20478 (setq day2 (car dates))
20479 (push day dates1)
20480 (when (and day2 empty)
20481 (if (or (eq empty t)
20482 (and (numberp empty) (<= (- day2 day) empty)))
20483 (while (< (setq day (1+ day)) day2)
20484 (push (list day) dates1))
20485 (push (cons :omitted (- day2 day)) dates1))))
20486 (setq dates (nreverse dates1)))
20487 dates)))
20489 ;;; Agenda Daily/Weekly
20491 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20492 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20493 (defvar org-agenda-last-arguments nil
20494 "The arguments of the previous call to org-agenda")
20495 (defvar org-starting-day nil) ; local variable in the agenda buffer
20496 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20497 (defvar org-include-all-loc nil) ; local variable
20498 (defvar org-agenda-remove-date nil) ; dynamically scoped
20500 ;;;###autoload
20501 (defun org-agenda-list (&optional include-all start-day ndays)
20502 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20503 The view will be for the current day or week, but from the overview buffer
20504 you will be able to go to other days/weeks.
20506 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20507 all unfinished TODO items will also be shown, before the agenda.
20508 This feature is considered obsolete, please use the TODO list or a block
20509 agenda instead.
20511 With a numeric prefix argument in an interactive call, the agenda will
20512 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20513 the number of days. NDAYS defaults to `org-agenda-ndays'.
20515 START-DAY defaults to TODAY, or to the most recent match for the weekday
20516 given in `org-agenda-start-on-weekday'."
20517 (interactive "P")
20518 (if (and (integerp include-all) (> include-all 0))
20519 (setq ndays include-all include-all nil))
20520 (setq ndays (or ndays org-agenda-ndays)
20521 start-day (or start-day org-agenda-start-day))
20522 (if org-agenda-overriding-arguments
20523 (setq include-all (car org-agenda-overriding-arguments)
20524 start-day (nth 1 org-agenda-overriding-arguments)
20525 ndays (nth 2 org-agenda-overriding-arguments)))
20526 (if (stringp start-day)
20527 ;; Convert to an absolute day number
20528 (setq start-day (time-to-days (org-read-date nil t start-day))))
20529 (setq org-agenda-last-arguments (list include-all start-day ndays))
20530 (org-compile-prefix-format 'agenda)
20531 (org-set-sorting-strategy 'agenda)
20532 (require 'calendar)
20533 (let* ((org-agenda-start-on-weekday
20534 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20535 org-agenda-start-on-weekday nil))
20536 (thefiles (org-agenda-files))
20537 (files thefiles)
20538 (today (time-to-days
20539 (time-subtract (current-time)
20540 (list 0 (* 3600 org-extend-today-until) 0))))
20541 (sd (or start-day today))
20542 (start (if (or (null org-agenda-start-on-weekday)
20543 (< org-agenda-ndays 7))
20545 (let* ((nt (calendar-day-of-week
20546 (calendar-gregorian-from-absolute sd)))
20547 (n1 org-agenda-start-on-weekday)
20548 (d (- nt n1)))
20549 (- sd (+ (if (< d 0) 7 0) d)))))
20550 (day-numbers (list start))
20551 (day-cnt 0)
20552 (inhibit-redisplay (not debug-on-error))
20553 s e rtn rtnall file date d start-pos end-pos todayp nd)
20554 (setq org-agenda-redo-command
20555 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20556 ;; Make the list of days
20557 (setq ndays (or ndays org-agenda-ndays)
20558 nd ndays)
20559 (while (> ndays 1)
20560 (push (1+ (car day-numbers)) day-numbers)
20561 (setq ndays (1- ndays)))
20562 (setq day-numbers (nreverse day-numbers))
20563 (org-prepare-agenda "Day/Week")
20564 (org-set-local 'org-starting-day (car day-numbers))
20565 (org-set-local 'org-include-all-loc include-all)
20566 (org-set-local 'org-agenda-span
20567 (org-agenda-ndays-to-span nd))
20568 (when (and (or include-all org-agenda-include-all-todo)
20569 (member today day-numbers))
20570 (setq files thefiles
20571 rtnall nil)
20572 (while (setq file (pop files))
20573 (catch 'nextfile
20574 (org-check-agenda-file file)
20575 (setq date (calendar-gregorian-from-absolute today)
20576 rtn (org-agenda-get-day-entries
20577 file date :todo))
20578 (setq rtnall (append rtnall rtn))))
20579 (when rtnall
20580 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20581 (add-text-properties (point-min) (1- (point))
20582 (list 'face 'org-agenda-structure))
20583 (insert (org-finalize-agenda-entries rtnall) "\n")))
20584 (unless org-agenda-compact-blocks
20585 (setq s (point))
20586 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20587 "-agenda:\n")
20588 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20589 'org-date-line t)))
20590 (while (setq d (pop day-numbers))
20591 (setq date (calendar-gregorian-from-absolute d)
20592 s (point))
20593 (if (or (setq todayp (= d today))
20594 (and (not start-pos) (= d sd)))
20595 (setq start-pos (point))
20596 (if (and start-pos (not end-pos))
20597 (setq end-pos (point))))
20598 (setq files thefiles
20599 rtnall nil)
20600 (while (setq file (pop files))
20601 (catch 'nextfile
20602 (org-check-agenda-file file)
20603 (if org-agenda-show-log
20604 (setq rtn (org-agenda-get-day-entries
20605 file date
20606 :deadline :scheduled :timestamp :sexp :closed))
20607 (setq rtn (org-agenda-get-day-entries
20608 file date
20609 :deadline :scheduled :sexp :timestamp)))
20610 (setq rtnall (append rtnall rtn))))
20611 (if org-agenda-include-diary
20612 (progn
20613 (require 'diary-lib)
20614 (setq rtn (org-get-entries-from-diary date))
20615 (setq rtnall (append rtnall rtn))))
20616 (if (or rtnall org-agenda-show-all-dates)
20617 (progn
20618 (setq day-cnt (1+ day-cnt))
20619 (insert
20620 (if (stringp org-agenda-format-date)
20621 (format-time-string org-agenda-format-date
20622 (org-time-from-absolute date))
20623 (funcall org-agenda-format-date date))
20624 "\n")
20625 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20626 (put-text-property s (1- (point)) 'org-date-line t)
20627 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20628 (if todayp (put-text-property s (1- (point)) 'org-today t))
20629 (if rtnall (insert
20630 (org-finalize-agenda-entries
20631 (org-agenda-add-time-grid-maybe
20632 rtnall nd todayp))
20633 "\n"))
20634 (put-text-property s (1- (point)) 'day d)
20635 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20636 (goto-char (point-min))
20637 (org-fit-agenda-window)
20638 (unless (and (pos-visible-in-window-p (point-min))
20639 (pos-visible-in-window-p (point-max)))
20640 (goto-char (1- (point-max)))
20641 (recenter -1)
20642 (if (not (pos-visible-in-window-p (or start-pos 1)))
20643 (progn
20644 (goto-char (or start-pos 1))
20645 (recenter 1))))
20646 (goto-char (or start-pos 1))
20647 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20648 (org-finalize-agenda)
20649 (setq buffer-read-only t)
20650 (message "")))
20652 (defun org-agenda-ndays-to-span (n)
20653 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20655 ;;; Agenda TODO list
20657 (defvar org-select-this-todo-keyword nil)
20658 (defvar org-last-arg nil)
20660 ;;;###autoload
20661 (defun org-todo-list (arg)
20662 "Show all TODO entries from all agenda file in a single list.
20663 The prefix arg can be used to select a specific TODO keyword and limit
20664 the list to these. When using \\[universal-argument], you will be prompted
20665 for a keyword. A numeric prefix directly selects the Nth keyword in
20666 `org-todo-keywords-1'."
20667 (interactive "P")
20668 (require 'calendar)
20669 (org-compile-prefix-format 'todo)
20670 (org-set-sorting-strategy 'todo)
20671 (org-prepare-agenda "TODO")
20672 (let* ((today (time-to-days (current-time)))
20673 (date (calendar-gregorian-from-absolute today))
20674 (kwds org-todo-keywords-for-agenda)
20675 (completion-ignore-case t)
20676 (org-select-this-todo-keyword
20677 (if (stringp arg) arg
20678 (and arg (integerp arg) (> arg 0)
20679 (nth (1- arg) kwds))))
20680 rtn rtnall files file pos)
20681 (when (equal arg '(4))
20682 (setq org-select-this-todo-keyword
20683 (completing-read "Keyword (or KWD1|K2D2|...): "
20684 (mapcar 'list kwds) nil nil)))
20685 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20686 (org-set-local 'org-last-arg arg)
20687 (setq org-agenda-redo-command
20688 '(org-todo-list (or current-prefix-arg org-last-arg)))
20689 (setq files (org-agenda-files)
20690 rtnall nil)
20691 (while (setq file (pop files))
20692 (catch 'nextfile
20693 (org-check-agenda-file file)
20694 (setq rtn (org-agenda-get-day-entries file date :todo))
20695 (setq rtnall (append rtnall rtn))))
20696 (if org-agenda-overriding-header
20697 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20698 nil 'face 'org-agenda-structure) "\n")
20699 (insert "Global list of TODO items of type: ")
20700 (add-text-properties (point-min) (1- (point))
20701 (list 'face 'org-agenda-structure))
20702 (setq pos (point))
20703 (insert (or org-select-this-todo-keyword "ALL") "\n")
20704 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20705 (setq pos (point))
20706 (unless org-agenda-multi
20707 (insert "Available with `N r': (0)ALL")
20708 (let ((n 0) s)
20709 (mapc (lambda (x)
20710 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20711 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20712 (insert "\n "))
20713 (insert " " s))
20714 kwds))
20715 (insert "\n"))
20716 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20717 (when rtnall
20718 (insert (org-finalize-agenda-entries rtnall) "\n"))
20719 (goto-char (point-min))
20720 (org-fit-agenda-window)
20721 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20722 (org-finalize-agenda)
20723 (setq buffer-read-only t)))
20725 ;;; Agenda tags match
20727 ;;;###autoload
20728 (defun org-tags-view (&optional todo-only match)
20729 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20730 The prefix arg TODO-ONLY limits the search to TODO entries."
20731 (interactive "P")
20732 (org-compile-prefix-format 'tags)
20733 (org-set-sorting-strategy 'tags)
20734 (let* ((org-tags-match-list-sublevels
20735 (if todo-only t org-tags-match-list-sublevels))
20736 (completion-ignore-case t)
20737 rtn rtnall files file pos matcher
20738 buffer)
20739 (setq matcher (org-make-tags-matcher match)
20740 match (car matcher) matcher (cdr matcher))
20741 (org-prepare-agenda (concat "TAGS " match))
20742 (setq org-agenda-redo-command
20743 (list 'org-tags-view (list 'quote todo-only)
20744 (list 'if 'current-prefix-arg nil match)))
20745 (setq files (org-agenda-files)
20746 rtnall nil)
20747 (while (setq file (pop files))
20748 (catch 'nextfile
20749 (org-check-agenda-file file)
20750 (setq buffer (if (file-exists-p file)
20751 (org-get-agenda-file-buffer file)
20752 (error "No such file %s" file)))
20753 (if (not buffer)
20754 ;; If file does not exist, merror message to agenda
20755 (setq rtn (list
20756 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20757 rtnall (append rtnall rtn))
20758 (with-current-buffer buffer
20759 (unless (org-mode-p)
20760 (error "Agenda file %s is not in `org-mode'" file))
20761 (save-excursion
20762 (save-restriction
20763 (if org-agenda-restrict
20764 (narrow-to-region org-agenda-restrict-begin
20765 org-agenda-restrict-end)
20766 (widen))
20767 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20768 (setq rtnall (append rtnall rtn))))))))
20769 (if org-agenda-overriding-header
20770 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20771 nil 'face 'org-agenda-structure) "\n")
20772 (insert "Headlines with TAGS match: ")
20773 (add-text-properties (point-min) (1- (point))
20774 (list 'face 'org-agenda-structure))
20775 (setq pos (point))
20776 (insert match "\n")
20777 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20778 (setq pos (point))
20779 (unless org-agenda-multi
20780 (insert "Press `C-u r' to search again with new search string\n"))
20781 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20782 (when rtnall
20783 (insert (org-finalize-agenda-entries rtnall) "\n"))
20784 (goto-char (point-min))
20785 (org-fit-agenda-window)
20786 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20787 (org-finalize-agenda)
20788 (setq buffer-read-only t)))
20790 ;;; Agenda Finding stuck projects
20792 (defvar org-agenda-skip-regexp nil
20793 "Regular expression used in skipping subtrees for the agenda.
20794 This is basically a temporary global variable that can be set and then
20795 used by user-defined selections using `org-agenda-skip-function'.")
20797 (defvar org-agenda-overriding-header nil
20798 "When this is set during todo and tags searches, will replace header.")
20800 (defun org-agenda-skip-subtree-when-regexp-matches ()
20801 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20802 If yes, it returns the end position of this tree, causing agenda commands
20803 to skip this subtree. This is a function that can be put into
20804 `org-agenda-skip-function' for the duration of a command."
20805 (let ((end (save-excursion (org-end-of-subtree t)))
20806 skip)
20807 (save-excursion
20808 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20809 (and skip end)))
20811 (defun org-agenda-skip-entry-if (&rest conditions)
20812 "Skip entry if any of CONDITIONS is true.
20813 See `org-agenda-skip-if' for details."
20814 (org-agenda-skip-if nil conditions))
20816 (defun org-agenda-skip-subtree-if (&rest conditions)
20817 "Skip entry if any of CONDITIONS is true.
20818 See `org-agenda-skip-if' for details."
20819 (org-agenda-skip-if t conditions))
20821 (defun org-agenda-skip-if (subtree conditions)
20822 "Checks current entity for CONDITIONS.
20823 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20824 the entry, i.e. the text before the next heading is checked.
20826 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20827 from different tests. Valid conditions are:
20829 scheduled Check if there is a scheduled cookie
20830 notscheduled Check if there is no scheduled cookie
20831 deadline Check if there is a deadline
20832 notdeadline Check if there is no deadline
20833 regexp Check if regexp matches
20834 notregexp Check if regexp does not match.
20836 The regexp is taken from the conditions list, it must come right after
20837 the `regexp' or `notregexp' element.
20839 If any of these conditions is met, this function returns the end point of
20840 the entity, causing the search to continue from there. This is a function
20841 that can be put into `org-agenda-skip-function' for the duration of a command."
20842 (let (beg end m)
20843 (org-back-to-heading t)
20844 (setq beg (point)
20845 end (if subtree
20846 (progn (org-end-of-subtree t) (point))
20847 (progn (outline-next-heading) (1- (point)))))
20848 (goto-char beg)
20849 (and
20851 (and (memq 'scheduled conditions)
20852 (re-search-forward org-scheduled-time-regexp end t))
20853 (and (memq 'notscheduled conditions)
20854 (not (re-search-forward org-scheduled-time-regexp end t)))
20855 (and (memq 'deadline conditions)
20856 (re-search-forward org-deadline-time-regexp end t))
20857 (and (memq 'notdeadline conditions)
20858 (not (re-search-forward org-deadline-time-regexp end t)))
20859 (and (setq m (memq 'regexp conditions))
20860 (stringp (nth 1 m))
20861 (re-search-forward (nth 1 m) end t))
20862 (and (setq m (memq 'notregexp conditions))
20863 (stringp (nth 1 m))
20864 (not (re-search-forward (nth 1 m) end t))))
20865 end)))
20867 ;;;###autoload
20868 (defun org-agenda-list-stuck-projects (&rest ignore)
20869 "Create agenda view for projects that are stuck.
20870 Stuck projects are project that have no next actions. For the definitions
20871 of what a project is and how to check if it stuck, customize the variable
20872 `org-stuck-projects'.
20873 MATCH is being ignored."
20874 (interactive)
20875 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20876 ;; FIXME: we could have used org-agenda-skip-if here.
20877 (org-agenda-overriding-header "List of stuck projects: ")
20878 (matcher (nth 0 org-stuck-projects))
20879 (todo (nth 1 org-stuck-projects))
20880 (todo-wds (if (member "*" todo)
20881 (progn
20882 (org-prepare-agenda-buffers (org-agenda-files))
20883 (org-delete-all
20884 org-done-keywords-for-agenda
20885 (copy-sequence org-todo-keywords-for-agenda)))
20886 todo))
20887 (todo-re (concat "^\\*+[ \t]+\\("
20888 (mapconcat 'identity todo-wds "\\|")
20889 "\\)\\>"))
20890 (tags (nth 2 org-stuck-projects))
20891 (tags-re (if (member "*" tags)
20892 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20893 (concat "^\\*+ .*:\\("
20894 (mapconcat 'identity tags "\\|")
20895 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20896 (gen-re (nth 3 org-stuck-projects))
20897 (re-list
20898 (delq nil
20899 (list
20900 (if todo todo-re)
20901 (if tags tags-re)
20902 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20903 gen-re)))))
20904 (setq org-agenda-skip-regexp
20905 (if re-list
20906 (mapconcat 'identity re-list "\\|")
20907 (error "No information how to identify unstuck projects")))
20908 (org-tags-view nil matcher)
20909 (with-current-buffer org-agenda-buffer-name
20910 (setq org-agenda-redo-command
20911 '(org-agenda-list-stuck-projects
20912 (or current-prefix-arg org-last-arg))))))
20914 ;;; Diary integration
20916 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20918 (defun org-get-entries-from-diary (date)
20919 "Get the (Emacs Calendar) diary entries for DATE."
20920 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20921 (diary-display-hook '(fancy-diary-display))
20922 (pop-up-frames nil)
20923 (list-diary-entries-hook
20924 (cons 'org-diary-default-entry list-diary-entries-hook))
20925 (diary-file-name-prefix-function nil) ; turn this feature off
20926 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20927 entries
20928 (org-disable-agenda-to-diary t))
20929 (save-excursion
20930 (save-window-excursion
20931 (funcall (if (fboundp 'diary-list-entries)
20932 'diary-list-entries 'list-diary-entries)
20933 date 1)))
20934 (if (not (get-buffer fancy-diary-buffer))
20935 (setq entries nil)
20936 (with-current-buffer fancy-diary-buffer
20937 (setq buffer-read-only nil)
20938 (if (zerop (buffer-size))
20939 ;; No entries
20940 (setq entries nil)
20941 ;; Omit the date and other unnecessary stuff
20942 (org-agenda-cleanup-fancy-diary)
20943 ;; Add prefix to each line and extend the text properties
20944 (if (zerop (buffer-size))
20945 (setq entries nil)
20946 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20947 (set-buffer-modified-p nil)
20948 (kill-buffer fancy-diary-buffer)))
20949 (when entries
20950 (setq entries (org-split-string entries "\n"))
20951 (setq entries
20952 (mapcar
20953 (lambda (x)
20954 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20955 ;; Extend the text properties to the beginning of the line
20956 (org-add-props x (text-properties-at (1- (length x)) x)
20957 'type "diary" 'date date))
20958 entries)))))
20960 (defun org-agenda-cleanup-fancy-diary ()
20961 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20962 This gets rid of the date, the underline under the date, and
20963 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20964 date. It also removes lines that contain only whitespace."
20965 (goto-char (point-min))
20966 (if (looking-at ".*?:[ \t]*")
20967 (progn
20968 (replace-match "")
20969 (re-search-forward "\n=+$" nil t)
20970 (replace-match "")
20971 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20972 (re-search-forward "\n=+$" nil t)
20973 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20974 (goto-char (point-min))
20975 (while (re-search-forward "^ +\n" nil t)
20976 (replace-match ""))
20977 (goto-char (point-min))
20978 (if (re-search-forward "^Org-mode dummy\n?" nil t)
20979 (replace-match "")))
20981 ;; Make sure entries from the diary have the right text properties.
20982 (eval-after-load "diary-lib"
20983 '(if (boundp 'diary-modify-entry-list-string-function)
20984 ;; We can rely on the hook, nothing to do
20986 ;; Hook not avaiable, must use advice to make this work
20987 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
20988 "Make the position visible."
20989 (if (and org-disable-agenda-to-diary ;; called from org-agenda
20990 (stringp string)
20991 buffer-file-name)
20992 (setq string (org-modify-diary-entry-string string))))))
20994 (defun org-modify-diary-entry-string (string)
20995 "Add text properties to string, allowing org-mode to act on it."
20996 (org-add-props string nil
20997 'mouse-face 'highlight
20998 'keymap org-agenda-keymap
20999 'help-echo (if buffer-file-name
21000 (format "mouse-2 or RET jump to diary file %s"
21001 (abbreviate-file-name buffer-file-name))
21003 'org-agenda-diary-link t
21004 'org-marker (org-agenda-new-marker (point-at-bol))))
21006 (defun org-diary-default-entry ()
21007 "Add a dummy entry to the diary.
21008 Needed to avoid empty dates which mess up holiday display."
21009 ;; Catch the error if dealing with the new add-to-diary-alist
21010 (when org-disable-agenda-to-diary
21011 (condition-case nil
21012 (add-to-diary-list original-date "Org-mode dummy" "")
21013 (error
21014 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21016 ;;;###autoload
21017 (defun org-diary (&rest args)
21018 "Return diary information from org-files.
21019 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21020 It accesses org files and extracts information from those files to be
21021 listed in the diary. The function accepts arguments specifying what
21022 items should be listed. The following arguments are allowed:
21024 :timestamp List the headlines of items containing a date stamp or
21025 date range matching the selected date. Deadlines will
21026 also be listed, on the expiration day.
21028 :sexp List entries resulting from diary-like sexps.
21030 :deadline List any deadlines past due, or due within
21031 `org-deadline-warning-days'. The listing occurs only
21032 in the diary for *today*, not at any other date. If
21033 an entry is marked DONE, it is no longer listed.
21035 :scheduled List all items which are scheduled for the given date.
21036 The diary for *today* also contains items which were
21037 scheduled earlier and are not yet marked DONE.
21039 :todo List all TODO items from the org-file. This may be a
21040 long list - so this is not turned on by default.
21041 Like deadlines, these entries only show up in the
21042 diary for *today*, not at any other date.
21044 The call in the diary file should look like this:
21046 &%%(org-diary) ~/path/to/some/orgfile.org
21048 Use a separate line for each org file to check. Or, if you omit the file name,
21049 all files listed in `org-agenda-files' will be checked automatically:
21051 &%%(org-diary)
21053 If you don't give any arguments (as in the example above), the default
21054 arguments (:deadline :scheduled :timestamp :sexp) are used.
21055 So the example above may also be written as
21057 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21059 The function expects the lisp variables `entry' and `date' to be provided
21060 by the caller, because this is how the calendar works. Don't use this
21061 function from a program - use `org-agenda-get-day-entries' instead."
21062 (org-agenda-maybe-reset-markers)
21063 (org-compile-prefix-format 'agenda)
21064 (org-set-sorting-strategy 'agenda)
21065 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21066 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21067 (list entry)
21068 (org-agenda-files t)))
21069 file rtn results)
21070 (org-prepare-agenda-buffers files)
21071 ;; If this is called during org-agenda, don't return any entries to
21072 ;; the calendar. Org Agenda will list these entries itself.
21073 (if org-disable-agenda-to-diary (setq files nil))
21074 (while (setq file (pop files))
21075 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21076 (setq results (append results rtn)))
21077 (if results
21078 (concat (org-finalize-agenda-entries results) "\n"))))
21080 ;;; Agenda entry finders
21082 (defun org-agenda-get-day-entries (file date &rest args)
21083 "Does the work for `org-diary' and `org-agenda'.
21084 FILE is the path to a file to be checked for entries. DATE is date like
21085 the one returned by `calendar-current-date'. ARGS are symbols indicating
21086 which kind of entries should be extracted. For details about these, see
21087 the documentation of `org-diary'."
21088 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21089 (let* ((org-startup-folded nil)
21090 (org-startup-align-all-tables nil)
21091 (buffer (if (file-exists-p file)
21092 (org-get-agenda-file-buffer file)
21093 (error "No such file %s" file)))
21094 arg results rtn)
21095 (if (not buffer)
21096 ;; If file does not exist, make sure an error message ends up in diary
21097 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21098 (with-current-buffer buffer
21099 (unless (org-mode-p)
21100 (error "Agenda file %s is not in `org-mode'" file))
21101 (let ((case-fold-search nil))
21102 (save-excursion
21103 (save-restriction
21104 (if org-agenda-restrict
21105 (narrow-to-region org-agenda-restrict-begin
21106 org-agenda-restrict-end)
21107 (widen))
21108 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21109 (while (setq arg (pop args))
21110 (cond
21111 ((and (eq arg :todo)
21112 (equal date (calendar-current-date)))
21113 (setq rtn (org-agenda-get-todos))
21114 (setq results (append results rtn)))
21115 ((eq arg :timestamp)
21116 (setq rtn (org-agenda-get-blocks))
21117 (setq results (append results rtn))
21118 (setq rtn (org-agenda-get-timestamps))
21119 (setq results (append results rtn)))
21120 ((eq arg :sexp)
21121 (setq rtn (org-agenda-get-sexps))
21122 (setq results (append results rtn)))
21123 ((eq arg :scheduled)
21124 (setq rtn (org-agenda-get-scheduled))
21125 (setq results (append results rtn)))
21126 ((eq arg :closed)
21127 (setq rtn (org-agenda-get-closed))
21128 (setq results (append results rtn)))
21129 ((eq arg :deadline)
21130 (setq rtn (org-agenda-get-deadlines))
21131 (setq results (append results rtn))))))))
21132 results))))
21134 (defun org-entry-is-todo-p ()
21135 (member (org-get-todo-state) org-not-done-keywords))
21137 (defun org-entry-is-done-p ()
21138 (member (org-get-todo-state) org-done-keywords))
21140 (defun org-get-todo-state ()
21141 (save-excursion
21142 (org-back-to-heading t)
21143 (and (looking-at org-todo-line-regexp)
21144 (match-end 2)
21145 (match-string 2))))
21147 (defun org-at-date-range-p (&optional inactive-ok)
21148 "Is the cursor inside a date range?"
21149 (interactive)
21150 (save-excursion
21151 (catch 'exit
21152 (let ((pos (point)))
21153 (skip-chars-backward "^[<\r\n")
21154 (skip-chars-backward "<[")
21155 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21156 (>= (match-end 0) pos)
21157 (throw 'exit t))
21158 (skip-chars-backward "^<[\r\n")
21159 (skip-chars-backward "<[")
21160 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21161 (>= (match-end 0) pos)
21162 (throw 'exit t)))
21163 nil)))
21165 (defun org-agenda-get-todos ()
21166 "Return the TODO information for agenda display."
21167 (let* ((props (list 'face nil
21168 'done-face 'org-done
21169 'org-not-done-regexp org-not-done-regexp
21170 'org-todo-regexp org-todo-regexp
21171 'mouse-face 'highlight
21172 'keymap org-agenda-keymap
21173 'help-echo
21174 (format "mouse-2 or RET jump to org file %s"
21175 (abbreviate-file-name buffer-file-name))))
21176 ;; FIXME: get rid of the \n at some point but watch out
21177 (regexp (concat "^\\*+[ \t]+\\("
21178 (if org-select-this-todo-keyword
21179 (if (equal org-select-this-todo-keyword "*")
21180 org-todo-regexp
21181 (concat "\\<\\("
21182 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21183 "\\)\\>"))
21184 org-not-done-regexp)
21185 "[^\n\r]*\\)"))
21186 marker priority category tags
21187 ee txt beg end)
21188 (goto-char (point-min))
21189 (while (re-search-forward regexp nil t)
21190 (catch :skip
21191 (save-match-data
21192 (beginning-of-line)
21193 (setq beg (point) end (progn (outline-next-heading) (point)))
21194 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21195 (re-search-forward org-ts-regexp end t))
21196 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21197 (re-search-forward org-scheduled-time-regexp end t))
21198 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21199 (re-search-forward org-deadline-time-regexp end t)
21200 (org-deadline-close (match-string 1))))
21201 (goto-char (1+ beg))
21202 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21203 (throw :skip nil)))
21204 (goto-char beg)
21205 (org-agenda-skip)
21206 (goto-char (match-beginning 1))
21207 (setq marker (org-agenda-new-marker (match-beginning 0))
21208 category (org-get-category)
21209 tags (org-get-tags-at (point))
21210 txt (org-format-agenda-item "" (match-string 1) category tags)
21211 priority (1+ (org-get-priority txt)))
21212 (org-add-props txt props
21213 'org-marker marker 'org-hd-marker marker
21214 'priority priority 'org-category category
21215 'type "todo")
21216 (push txt ee)
21217 (if org-agenda-todo-list-sublevels
21218 (goto-char (match-end 1))
21219 (org-end-of-subtree 'invisible))))
21220 (nreverse ee)))
21222 (defconst org-agenda-no-heading-message
21223 "No heading for this item in buffer or region.")
21225 (defun org-agenda-get-timestamps ()
21226 "Return the date stamp information for agenda display."
21227 (let* ((props (list 'face nil
21228 'org-not-done-regexp org-not-done-regexp
21229 'org-todo-regexp org-todo-regexp
21230 'mouse-face 'highlight
21231 'keymap org-agenda-keymap
21232 'help-echo
21233 (format "mouse-2 or RET jump to org file %s"
21234 (abbreviate-file-name buffer-file-name))))
21235 (d1 (calendar-absolute-from-gregorian date))
21236 (remove-re
21237 (concat
21238 (regexp-quote
21239 (format-time-string
21240 "<%Y-%m-%d"
21241 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21242 ".*?>"))
21243 (regexp
21244 (concat
21245 (regexp-quote
21246 (substring
21247 (format-time-string
21248 (car org-time-stamp-formats)
21249 (apply 'encode-time ; DATE bound by calendar
21250 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21251 0 11))
21252 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21253 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21254 marker hdmarker deadlinep scheduledp donep tmp priority category
21255 ee txt timestr tags b0 b3 e3 head)
21256 (goto-char (point-min))
21257 (while (re-search-forward regexp nil t)
21258 (setq b0 (match-beginning 0)
21259 b3 (match-beginning 3) e3 (match-end 3))
21260 (catch :skip
21261 (and (org-at-date-range-p) (throw :skip nil))
21262 (org-agenda-skip)
21263 (if (and (match-end 1)
21264 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21265 (throw :skip nil))
21266 (if (and e3
21267 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21268 (throw :skip nil))
21269 (setq marker (org-agenda-new-marker b0)
21270 category (org-get-category b0)
21271 tmp (buffer-substring (max (point-min)
21272 (- b0 org-ds-keyword-length))
21274 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21275 deadlinep (string-match org-deadline-regexp tmp)
21276 scheduledp (string-match org-scheduled-regexp tmp)
21277 donep (org-entry-is-done-p))
21278 (if (or scheduledp deadlinep) (throw :skip t))
21279 (if (string-match ">" timestr)
21280 ;; substring should only run to end of time stamp
21281 (setq timestr (substring timestr 0 (match-end 0))))
21282 (save-excursion
21283 (if (re-search-backward "^\\*+ " nil t)
21284 (progn
21285 (goto-char (match-beginning 0))
21286 (setq hdmarker (org-agenda-new-marker)
21287 tags (org-get-tags-at))
21288 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21289 (setq head (match-string 1))
21290 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21291 (setq txt (org-format-agenda-item
21292 nil head category tags timestr nil
21293 remove-re)))
21294 (setq txt org-agenda-no-heading-message))
21295 (setq priority (org-get-priority txt))
21296 (org-add-props txt props
21297 'org-marker marker 'org-hd-marker hdmarker)
21298 (org-add-props txt nil 'priority priority
21299 'org-category category 'date date
21300 'type "timestamp")
21301 (push txt ee))
21302 (outline-next-heading)))
21303 (nreverse ee)))
21305 (defun org-agenda-get-sexps ()
21306 "Return the sexp information for agenda display."
21307 (require 'diary-lib)
21308 (let* ((props (list 'face nil
21309 'mouse-face 'highlight
21310 'keymap org-agenda-keymap
21311 'help-echo
21312 (format "mouse-2 or RET jump to org file %s"
21313 (abbreviate-file-name buffer-file-name))))
21314 (regexp "^&?%%(")
21315 marker category ee txt tags entry result beg b sexp sexp-entry)
21316 (goto-char (point-min))
21317 (while (re-search-forward regexp nil t)
21318 (catch :skip
21319 (org-agenda-skip)
21320 (setq beg (match-beginning 0))
21321 (goto-char (1- (match-end 0)))
21322 (setq b (point))
21323 (forward-sexp 1)
21324 (setq sexp (buffer-substring b (point)))
21325 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21326 (org-trim (match-string 1))
21327 ""))
21328 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21329 (when result
21330 (setq marker (org-agenda-new-marker beg)
21331 category (org-get-category beg))
21333 (if (string-match "\\S-" result)
21334 (setq txt result)
21335 (setq txt "SEXP entry returned empty string"))
21337 (setq txt (org-format-agenda-item
21338 "" txt category tags 'time))
21339 (org-add-props txt props 'org-marker marker)
21340 (org-add-props txt nil
21341 'org-category category 'date date
21342 'type "sexp")
21343 (push txt ee))))
21344 (nreverse ee)))
21346 (defun org-agenda-get-closed ()
21347 "Return the logged TODO entries for agenda display."
21348 (let* ((props (list 'mouse-face 'highlight
21349 'org-not-done-regexp org-not-done-regexp
21350 'org-todo-regexp org-todo-regexp
21351 'keymap org-agenda-keymap
21352 'help-echo
21353 (format "mouse-2 or RET jump to org file %s"
21354 (abbreviate-file-name buffer-file-name))))
21355 (regexp (concat
21356 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21357 (regexp-quote
21358 (substring
21359 (format-time-string
21360 (car org-time-stamp-formats)
21361 (apply 'encode-time ; DATE bound by calendar
21362 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21363 1 11))))
21364 marker hdmarker priority category tags closedp
21365 ee txt timestr)
21366 (goto-char (point-min))
21367 (while (re-search-forward regexp nil t)
21368 (catch :skip
21369 (org-agenda-skip)
21370 (setq marker (org-agenda-new-marker (match-beginning 0))
21371 closedp (equal (match-string 1) org-closed-string)
21372 category (org-get-category (match-beginning 0))
21373 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21374 ;; donep (org-entry-is-done-p)
21376 (if (string-match "\\]" timestr)
21377 ;; substring should only run to end of time stamp
21378 (setq timestr (substring timestr 0 (match-end 0))))
21379 (save-excursion
21380 (if (re-search-backward "^\\*+ " nil t)
21381 (progn
21382 (goto-char (match-beginning 0))
21383 (setq hdmarker (org-agenda-new-marker)
21384 tags (org-get-tags-at))
21385 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21386 (setq txt (org-format-agenda-item
21387 (if closedp "Closed: " "Clocked: ")
21388 (match-string 1) category tags timestr)))
21389 (setq txt org-agenda-no-heading-message))
21390 (setq priority 100000)
21391 (org-add-props txt props
21392 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21393 'priority priority 'org-category category
21394 'type "closed" 'date date
21395 'undone-face 'org-warning 'done-face 'org-done)
21396 (push txt ee))
21397 (goto-char (point-at-eol))))
21398 (nreverse ee)))
21400 (defun org-agenda-get-deadlines ()
21401 "Return the deadline information for agenda display."
21402 (let* ((props (list 'mouse-face 'highlight
21403 'org-not-done-regexp org-not-done-regexp
21404 'org-todo-regexp org-todo-regexp
21405 'keymap org-agenda-keymap
21406 'help-echo
21407 (format "mouse-2 or RET jump to org file %s"
21408 (abbreviate-file-name buffer-file-name))))
21409 (regexp org-deadline-time-regexp)
21410 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21411 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21412 d2 diff dfrac wdays pos pos1 category tags
21413 ee txt head face s upcomingp donep timestr)
21414 (goto-char (point-min))
21415 (while (re-search-forward regexp nil t)
21416 (catch :skip
21417 (org-agenda-skip)
21418 (setq s (match-string 1)
21419 pos (1- (match-beginning 1))
21420 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21421 diff (- d2 d1)
21422 wdays (org-get-wdays s)
21423 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21424 upcomingp (and todayp (> diff 0)))
21425 ;; When to show a deadline in the calendar:
21426 ;; If the expiration is within wdays warning time.
21427 ;; Past-due deadlines are only shown on the current date
21428 (if (or (and (<= diff wdays)
21429 (and todayp (not org-agenda-only-exact-dates)))
21430 (= diff 0))
21431 (save-excursion
21432 (setq category (org-get-category))
21433 (if (re-search-backward "^\\*+[ \t]+" nil t)
21434 (progn
21435 (goto-char (match-end 0))
21436 (setq pos1 (match-beginning 0))
21437 (setq tags (org-get-tags-at pos1))
21438 (setq head (buffer-substring-no-properties
21439 (point)
21440 (progn (skip-chars-forward "^\r\n")
21441 (point))))
21442 (setq donep (string-match org-looking-at-done-regexp head))
21443 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21444 (setq timestr
21445 (concat (substring s (match-beginning 1)) " "))
21446 (setq timestr 'time))
21447 (if (and donep
21448 (or org-agenda-skip-deadline-if-done
21449 (not (= diff 0))))
21450 (setq txt nil)
21451 (setq txt (org-format-agenda-item
21452 (if (= diff 0)
21453 (car org-agenda-deadline-leaders)
21454 (format (nth 1 org-agenda-deadline-leaders)
21455 diff))
21456 head category tags timestr))))
21457 (setq txt org-agenda-no-heading-message))
21458 (when txt
21459 (setq face (org-agenda-deadline-face dfrac))
21460 (org-add-props txt props
21461 'org-marker (org-agenda-new-marker pos)
21462 'org-hd-marker (org-agenda-new-marker pos1)
21463 'priority (+ (- diff)
21464 (org-get-priority txt))
21465 'org-category category
21466 'type (if upcomingp "upcoming-deadline" "deadline")
21467 'date (if upcomingp date d2)
21468 'face (if donep 'org-done face)
21469 'undone-face face 'done-face 'org-done)
21470 (push txt ee))))))
21471 (nreverse ee)))
21473 (defun org-agenda-deadline-face (fraction)
21474 "Return the face to displaying a deadline item.
21475 FRACTION is what fraction of the head-warning time has passed."
21476 (let ((faces org-agenda-deadline-faces) f)
21477 (catch 'exit
21478 (while (setq f (pop faces))
21479 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21481 (defun org-agenda-get-scheduled ()
21482 "Return the scheduled information for agenda display."
21483 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21484 'org-todo-regexp org-todo-regexp
21485 'done-face 'org-done
21486 'mouse-face 'highlight
21487 'keymap org-agenda-keymap
21488 'help-echo
21489 (format "mouse-2 or RET jump to org file %s"
21490 (abbreviate-file-name buffer-file-name))))
21491 (regexp org-scheduled-time-regexp)
21492 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21493 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21494 d2 diff pos pos1 category tags
21495 ee txt head pastschedp donep face timestr s)
21496 (goto-char (point-min))
21497 (while (re-search-forward regexp nil t)
21498 (catch :skip
21499 (org-agenda-skip)
21500 (setq s (match-string 1)
21501 pos (1- (match-beginning 1))
21502 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21503 ;;; is this right?
21504 ;;; do we need to do this for deadleine too????
21505 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21506 diff (- d2 d1))
21507 (setq pastschedp (and todayp (< diff 0)))
21508 ;; When to show a scheduled item in the calendar:
21509 ;; If it is on or past the date.
21510 (if (or (and (< diff 0)
21511 (and todayp (not org-agenda-only-exact-dates)))
21512 (= diff 0))
21513 (save-excursion
21514 (setq category (org-get-category))
21515 (if (re-search-backward "^\\*+[ \t]+" nil t)
21516 (progn
21517 (goto-char (match-end 0))
21518 (setq pos1 (match-beginning 0))
21519 (setq tags (org-get-tags-at))
21520 (setq head (buffer-substring-no-properties
21521 (point)
21522 (progn (skip-chars-forward "^\r\n") (point))))
21523 (setq donep (string-match org-looking-at-done-regexp head))
21524 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21525 (setq timestr
21526 (concat (substring s (match-beginning 1)) " "))
21527 (setq timestr 'time))
21528 (if (and donep
21529 (or org-agenda-skip-scheduled-if-done
21530 (not (= diff 0))))
21531 (setq txt nil)
21532 (setq txt (org-format-agenda-item
21533 (if (= diff 0)
21534 (car org-agenda-scheduled-leaders)
21535 (format (nth 1 org-agenda-scheduled-leaders)
21536 (- 1 diff)))
21537 head category tags timestr))))
21538 (setq txt org-agenda-no-heading-message))
21539 (when txt
21540 (setq face (if pastschedp
21541 'org-scheduled-previously
21542 'org-scheduled-today))
21543 (org-add-props txt props
21544 'undone-face face
21545 'face (if donep 'org-done face)
21546 'org-marker (org-agenda-new-marker pos)
21547 'org-hd-marker (org-agenda-new-marker pos1)
21548 'type (if pastschedp "past-scheduled" "scheduled")
21549 'date (if pastschedp d2 date)
21550 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21551 'org-category category)
21552 (push txt ee))))))
21553 (nreverse ee)))
21555 (defun org-agenda-get-blocks ()
21556 "Return the date-range information for agenda display."
21557 (let* ((props (list 'face nil
21558 'org-not-done-regexp org-not-done-regexp
21559 'org-todo-regexp org-todo-regexp
21560 'mouse-face 'highlight
21561 'keymap org-agenda-keymap
21562 'help-echo
21563 (format "mouse-2 or RET jump to org file %s"
21564 (abbreviate-file-name buffer-file-name))))
21565 (regexp org-tr-regexp)
21566 (d0 (calendar-absolute-from-gregorian date))
21567 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21568 donep head)
21569 (goto-char (point-min))
21570 (while (re-search-forward regexp nil t)
21571 (catch :skip
21572 (org-agenda-skip)
21573 (setq pos (point))
21574 (setq timestr (match-string 0)
21575 s1 (match-string 1)
21576 s2 (match-string 2)
21577 d1 (time-to-days (org-time-string-to-time s1))
21578 d2 (time-to-days (org-time-string-to-time s2)))
21579 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21580 ;; Only allow days between the limits, because the normal
21581 ;; date stamps will catch the limits.
21582 (save-excursion
21583 (setq marker (org-agenda-new-marker (point)))
21584 (setq category (org-get-category))
21585 (if (re-search-backward "^\\*+ " nil t)
21586 (progn
21587 (goto-char (match-beginning 0))
21588 (setq hdmarker (org-agenda-new-marker (point)))
21589 (setq tags (org-get-tags-at))
21590 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21591 (setq head (match-string 1))
21592 (and org-agenda-skip-timestamp-if-done
21593 (org-entry-is-done-p)
21594 (throw :skip t))
21595 (setq txt (org-format-agenda-item
21596 (format (if (= d1 d2) "" "(%d/%d): ")
21597 (1+ (- d0 d1)) (1+ (- d2 d1)))
21598 head category tags
21599 (if (= d0 d1) timestr))))
21600 (setq txt org-agenda-no-heading-message))
21601 (org-add-props txt props
21602 'org-marker marker 'org-hd-marker hdmarker
21603 'type "block" 'date date
21604 'priority (org-get-priority txt) 'org-category category)
21605 (push txt ee)))
21606 (goto-char pos)))
21607 ;; Sort the entries by expiration date.
21608 (nreverse ee)))
21610 ;;; Agenda presentation and sorting
21612 (defconst org-plain-time-of-day-regexp
21613 (concat
21614 "\\(\\<[012]?[0-9]"
21615 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21616 "\\(--?"
21617 "\\(\\<[012]?[0-9]"
21618 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21619 "\\)?")
21620 "Regular expression to match a plain time or time range.
21621 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21622 groups carry important information:
21623 0 the full match
21624 1 the first time, range or not
21625 8 the second time, if it is a range.")
21627 (defconst org-plain-time-extension-regexp
21628 (concat
21629 "\\(\\<[012]?[0-9]"
21630 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21631 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21632 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21633 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21634 groups carry important information:
21635 0 the full match
21636 7 hours of duration
21637 9 minutes of duration")
21639 (defconst org-stamp-time-of-day-regexp
21640 (concat
21641 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21642 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21643 "\\(--?"
21644 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21645 "Regular expression to match a timestamp time or time range.
21646 After a match, the following groups carry important information:
21647 0 the full match
21648 1 date plus weekday, for backreferencing to make sure both times on same day
21649 2 the first time, range or not
21650 4 the second time, if it is a range.")
21652 (defvar org-prefix-has-time nil
21653 "A flag, set by `org-compile-prefix-format'.
21654 The flag is set if the currently compiled format contains a `%t'.")
21655 (defvar org-prefix-has-tag nil
21656 "A flag, set by `org-compile-prefix-format'.
21657 The flag is set if the currently compiled format contains a `%T'.")
21659 (defun org-format-agenda-item (extra txt &optional category tags dotime
21660 noprefix remove-re)
21661 "Format TXT to be inserted into the agenda buffer.
21662 In particular, it adds the prefix and corresponding text properties. EXTRA
21663 must be a string and replaces the `%s' specifier in the prefix format.
21664 CATEGORY (string, symbol or nil) may be used to overrule the default
21665 category taken from local variable or file name. It will replace the `%c'
21666 specifier in the format. DOTIME, when non-nil, indicates that a
21667 time-of-day should be extracted from TXT for sorting of this entry, and for
21668 the `%t' specifier in the format. When DOTIME is a string, this string is
21669 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21670 only the correctly processes TXT should be returned - this is used by
21671 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21672 Any match of REMOVE-RE will be removed from TXT."
21673 (save-match-data
21674 ;; Diary entries sometimes have extra whitespace at the beginning
21675 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21676 (let* ((category (or category
21677 org-category
21678 (if buffer-file-name
21679 (file-name-sans-extension
21680 (file-name-nondirectory buffer-file-name))
21681 "")))
21682 (tag (if tags (nth (1- (length tags)) tags) ""))
21683 time ; time and tag are needed for the eval of the prefix format
21684 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21685 (time-of-day (and dotime (org-get-time-of-day ts)))
21686 stamp plain s0 s1 s2 rtn srp)
21687 (when (and dotime time-of-day org-prefix-has-time)
21688 ;; Extract starting and ending time and move them to prefix
21689 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21690 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21691 (setq s0 (match-string 0 ts)
21692 srp (and stamp (match-end 3))
21693 s1 (match-string (if plain 1 2) ts)
21694 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21696 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21697 ;; them, we might want to remove them there to avoid duplication.
21698 ;; The user can turn this off with a variable.
21699 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21700 (string-match (concat (regexp-quote s0) " *") txt)
21701 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21702 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21703 (= (match-beginning 0) 0)
21705 (setq txt (replace-match "" nil nil txt))))
21706 ;; Normalize the time(s) to 24 hour
21707 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21708 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21710 (when (and s1 (not s2) org-agenda-default-appointment-duration
21711 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21712 (let ((m (+ (string-to-number (match-string 2 s1))
21713 (* 60 (string-to-number (match-string 1 s1)))
21714 org-agenda-default-appointment-duration))
21716 (setq h (/ m 60) m (- m (* h 60)))
21717 (setq s2 (format "%02d:%02d" h m))))
21719 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21720 txt)
21721 ;; Tags are in the string
21722 (if (or (eq org-agenda-remove-tags t)
21723 (and org-agenda-remove-tags
21724 org-prefix-has-tag))
21725 (setq txt (replace-match "" t t txt))
21726 (setq txt (replace-match
21727 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21728 (match-string 2 txt))
21729 t t txt))))
21731 (when remove-re
21732 (while (string-match remove-re txt)
21733 (setq txt (replace-match "" t t txt))))
21735 ;; Create the final string
21736 (if noprefix
21737 (setq rtn txt)
21738 ;; Prepare the variables needed in the eval of the compiled format
21739 (setq time (cond (s2 (concat s1 "-" s2))
21740 (s1 (concat s1 "......"))
21741 (t ""))
21742 extra (or extra "")
21743 category (if (symbolp category) (symbol-name category) category))
21744 ;; Evaluate the compiled format
21745 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21747 ;; And finally add the text properties
21748 (org-add-props rtn nil
21749 'org-category (downcase category) 'tags tags
21750 'org-highest-priority org-highest-priority
21751 'org-lowest-priority org-lowest-priority
21752 'prefix-length (- (length rtn) (length txt))
21753 'time-of-day time-of-day
21754 'txt txt
21755 'time time
21756 'extra extra
21757 'dotime dotime))))
21759 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21760 (defvar org-agenda-sorting-strategy-selected nil)
21762 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21763 (catch 'exit
21764 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21765 ((and todayp (member 'today (car org-agenda-time-grid))))
21766 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21767 ((member 'weekly (car org-agenda-time-grid)))
21768 (t (throw 'exit list)))
21769 (let* ((have (delq nil (mapcar
21770 (lambda (x) (get-text-property 1 'time-of-day x))
21771 list)))
21772 (string (nth 1 org-agenda-time-grid))
21773 (gridtimes (nth 2 org-agenda-time-grid))
21774 (req (car org-agenda-time-grid))
21775 (remove (member 'remove-match req))
21776 new time)
21777 (if (and (member 'require-timed req) (not have))
21778 ;; don't show empty grid
21779 (throw 'exit list))
21780 (while (setq time (pop gridtimes))
21781 (unless (and remove (member time have))
21782 (setq time (int-to-string time))
21783 (push (org-format-agenda-item
21784 nil string "" nil
21785 (concat (substring time 0 -2) ":" (substring time -2)))
21786 new)
21787 (put-text-property
21788 1 (length (car new)) 'face 'org-time-grid (car new))))
21789 (if (member 'time-up org-agenda-sorting-strategy-selected)
21790 (append new list)
21791 (append list new)))))
21793 (defun org-compile-prefix-format (key)
21794 "Compile the prefix format into a Lisp form that can be evaluated.
21795 The resulting form is returned and stored in the variable
21796 `org-prefix-format-compiled'."
21797 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21798 (let ((s (cond
21799 ((stringp org-agenda-prefix-format)
21800 org-agenda-prefix-format)
21801 ((assq key org-agenda-prefix-format)
21802 (cdr (assq key org-agenda-prefix-format)))
21803 (t " %-12:c%?-12t% s")))
21804 (start 0)
21805 varform vars var e c f opt)
21806 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21807 s start)
21808 (setq var (cdr (assoc (match-string 4 s)
21809 '(("c" . category) ("t" . time) ("s" . extra)
21810 ("T" . tag))))
21811 c (or (match-string 3 s) "")
21812 opt (match-beginning 1)
21813 start (1+ (match-beginning 0)))
21814 (if (equal var 'time) (setq org-prefix-has-time t))
21815 (if (equal var 'tag) (setq org-prefix-has-tag t))
21816 (setq f (concat "%" (match-string 2 s) "s"))
21817 (if opt
21818 (setq varform
21819 `(if (equal "" ,var)
21821 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21822 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21823 (setq s (replace-match "%s" t nil s))
21824 (push varform vars))
21825 (setq vars (nreverse vars))
21826 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21828 (defun org-set-sorting-strategy (key)
21829 (if (symbolp (car org-agenda-sorting-strategy))
21830 ;; the old format
21831 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21832 (setq org-agenda-sorting-strategy-selected
21833 (or (cdr (assq key org-agenda-sorting-strategy))
21834 (cdr (assq 'agenda org-agenda-sorting-strategy))
21835 '(time-up category-keep priority-down)))))
21837 (defun org-get-time-of-day (s &optional string mod24)
21838 "Check string S for a time of day.
21839 If found, return it as a military time number between 0 and 2400.
21840 If not found, return nil.
21841 The optional STRING argument forces conversion into a 5 character wide string
21842 HH:MM."
21843 (save-match-data
21844 (when
21845 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21846 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21847 (let* ((h (string-to-number (match-string 1 s)))
21848 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21849 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21850 (am-p (equal ampm "am"))
21851 (h1 (cond ((not ampm) h)
21852 ((= h 12) (if am-p 0 12))
21853 (t (+ h (if am-p 0 12)))))
21854 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21855 (mod h1 24) h1))
21856 (t0 (+ (* 100 h2) m))
21857 (t1 (concat (if (>= h1 24) "+" " ")
21858 (if (< t0 100) "0" "")
21859 (if (< t0 10) "0" "")
21860 (int-to-string t0))))
21861 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21863 (defun org-finalize-agenda-entries (list &optional nosort)
21864 "Sort and concatenate the agenda items."
21865 (setq list (mapcar 'org-agenda-highlight-todo list))
21866 (if nosort
21867 list
21868 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21870 (defun org-agenda-highlight-todo (x)
21871 (let (re pl)
21872 (if (eq x 'line)
21873 (save-excursion
21874 (beginning-of-line 1)
21875 (setq re (get-text-property (point) 'org-todo-regexp))
21876 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21877 (when (looking-at (concat "[ \t]*\\.*" re " +"))
21878 (add-text-properties (match-beginning 0) (match-end 0)
21879 (list 'face (org-get-todo-face 0)))
21880 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
21881 (delete-region (match-beginning 1) (1- (match-end 0)))
21882 (goto-char (match-beginning 1))
21883 (insert (format org-agenda-todo-keyword-format s)))))
21884 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21885 pl (get-text-property 0 'prefix-length x))
21886 ; (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
21887 ; (add-text-properties
21888 ; (or (match-end 1) (match-end 0)) (match-end 0)
21889 ; (list 'face (org-get-todo-face (match-string 2 x)))
21890 ; x))
21891 (when (and re
21892 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
21893 x (or pl 0)) pl))
21894 (add-text-properties
21895 (or (match-end 1) (match-end 0)) (match-end 0)
21896 (list 'face (org-get-todo-face (match-string 2 x)))
21898 (setq x (concat (substring x 0 (match-end 1))
21899 (format org-agenda-todo-keyword-format
21900 (match-string 2 x))
21902 (substring x (match-end 3)))))
21903 x)))
21905 (defsubst org-cmp-priority (a b)
21906 "Compare the priorities of string A and B."
21907 (let ((pa (or (get-text-property 1 'priority a) 0))
21908 (pb (or (get-text-property 1 'priority b) 0)))
21909 (cond ((> pa pb) +1)
21910 ((< pa pb) -1)
21911 (t nil))))
21913 (defsubst org-cmp-category (a b)
21914 "Compare the string values of categories of strings A and B."
21915 (let ((ca (or (get-text-property 1 'org-category a) ""))
21916 (cb (or (get-text-property 1 'org-category b) "")))
21917 (cond ((string-lessp ca cb) -1)
21918 ((string-lessp cb ca) +1)
21919 (t nil))))
21921 (defsubst org-cmp-tag (a b)
21922 "Compare the string values of categories of strings A and B."
21923 (let ((ta (car (last (get-text-property 1 'tags a))))
21924 (tb (car (last (get-text-property 1 'tags b)))))
21925 (cond ((not ta) +1)
21926 ((not tb) -1)
21927 ((string-lessp ta tb) -1)
21928 ((string-lessp tb ta) +1)
21929 (t nil))))
21931 (defsubst org-cmp-time (a b)
21932 "Compare the time-of-day values of strings A and B."
21933 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21934 (ta (or (get-text-property 1 'time-of-day a) def))
21935 (tb (or (get-text-property 1 'time-of-day b) def)))
21936 (cond ((< ta tb) -1)
21937 ((< tb ta) +1)
21938 (t nil))))
21940 (defun org-entries-lessp (a b)
21941 "Predicate for sorting agenda entries."
21942 ;; The following variables will be used when the form is evaluated.
21943 ;; So even though the compiler complains, keep them.
21944 (let* ((time-up (org-cmp-time a b))
21945 (time-down (if time-up (- time-up) nil))
21946 (priority-up (org-cmp-priority a b))
21947 (priority-down (if priority-up (- priority-up) nil))
21948 (category-up (org-cmp-category a b))
21949 (category-down (if category-up (- category-up) nil))
21950 (category-keep (if category-up +1 nil))
21951 (tag-up (org-cmp-tag a b))
21952 (tag-down (if tag-up (- tag-up) nil)))
21953 (cdr (assoc
21954 (eval (cons 'or org-agenda-sorting-strategy-selected))
21955 '((-1 . t) (1 . nil) (nil . nil))))))
21957 ;;; Agenda restriction lock
21959 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
21960 "Overlay to mark the headline to which arenda commands are restricted.")
21961 (org-overlay-put org-agenda-restriction-lock-overlay
21962 'face 'org-agenda-restriction-lock)
21963 (org-overlay-put org-agenda-restriction-lock-overlay
21964 'help-echo "Agendas are currently limited to this subtree.")
21965 (org-detach-overlay org-agenda-restriction-lock-overlay)
21966 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
21967 "Overlay marking the agenda restriction line in speedbar.")
21968 (org-overlay-put org-speedbar-restriction-lock-overlay
21969 'face 'org-agenda-restriction-lock)
21970 (org-overlay-put org-speedbar-restriction-lock-overlay
21971 'help-echo "Agendas are currently limited to this item.")
21972 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21974 (defun org-agenda-set-restriction-lock (&optional type)
21975 "Set restriction lock for agenda, to current subtree or file.
21976 Restriction will be the file if TYPE is `file', or if type is the
21977 universal prefix '(4), or if the cursor is before the first headline
21978 in the file. Otherwise, restriction will be to the current subtree."
21979 (interactive "P")
21980 (and (equal type '(4)) (setq type 'file))
21981 (setq type (cond
21982 (type type)
21983 ((org-at-heading-p) 'subtree)
21984 ((condition-case nil (org-back-to-heading t) (error nil))
21985 'subtree)
21986 (t 'file)))
21987 (if (eq type 'subtree)
21988 (progn
21989 (setq org-agenda-restrict t)
21990 (setq org-agenda-overriding-restriction 'subtree)
21991 (put 'org-agenda-files 'org-restrict
21992 (list (buffer-file-name (buffer-base-buffer))))
21993 (org-back-to-heading t)
21994 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
21995 (move-marker org-agenda-restrict-begin (point))
21996 (move-marker org-agenda-restrict-end
21997 (save-excursion (org-end-of-subtree t)))
21998 (message "Locking agenda restriction to subtree"))
21999 (put 'org-agenda-files 'org-restrict
22000 (list (buffer-file-name (buffer-base-buffer))))
22001 (setq org-agenda-restrict nil)
22002 (setq org-agenda-overriding-restriction 'file)
22003 (move-marker org-agenda-restrict-begin nil)
22004 (move-marker org-agenda-restrict-end nil)
22005 (message "Locking agenda restriction to file"))
22006 (setq current-prefix-arg nil)
22007 (org-agenda-maybe-redo))
22009 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22010 "Remove the agenda restriction lock."
22011 (interactive "P")
22012 (org-detach-overlay org-agenda-restriction-lock-overlay)
22013 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22014 (setq org-agenda-overriding-restriction nil)
22015 (setq org-agenda-restrict nil)
22016 (put 'org-agenda-files 'org-restrict nil)
22017 (move-marker org-agenda-restrict-begin nil)
22018 (move-marker org-agenda-restrict-end nil)
22019 (setq current-prefix-arg nil)
22020 (message "Agenda restriction lock removed")
22021 (or noupdate (org-agenda-maybe-redo)))
22023 (defun org-agenda-maybe-redo ()
22024 "If there is any window showing the agenda view, update it."
22025 (let ((w (get-buffer-window org-agenda-buffer-name t))
22026 (w0 (selected-window)))
22027 (when w
22028 (select-window w)
22029 (org-agenda-redo)
22030 (select-window w0)
22031 (if org-agenda-overriding-restriction
22032 (message "Agenda view shifted to new %s restriction"
22033 org-agenda-overriding-restriction)
22034 (message "Agenda restriction lock removed")))))
22036 ;;; Agenda commands
22038 (defun org-agenda-check-type (error &rest types)
22039 "Check if agenda buffer is of allowed type.
22040 If ERROR is non-nil, throw an error, otherwise just return nil."
22041 (if (memq org-agenda-type types)
22043 (if error
22044 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22045 nil)))
22047 (defun org-agenda-quit ()
22048 "Exit agenda by removing the window or the buffer."
22049 (interactive)
22050 (let ((buf (current-buffer)))
22051 (if (not (one-window-p)) (delete-window))
22052 (kill-buffer buf)
22053 (org-agenda-maybe-reset-markers 'force)
22054 (org-columns-remove-overlays))
22055 ;; Maybe restore the pre-agenda window configuration.
22056 (and org-agenda-restore-windows-after-quit
22057 (not (eq org-agenda-window-setup 'other-frame))
22058 org-pre-agenda-window-conf
22059 (set-window-configuration org-pre-agenda-window-conf)))
22061 (defun org-agenda-exit ()
22062 "Exit agenda by removing the window or the buffer.
22063 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22064 Org-mode buffers visited directly by the user will not be touched."
22065 (interactive)
22066 (org-release-buffers org-agenda-new-buffers)
22067 (setq org-agenda-new-buffers nil)
22068 (org-agenda-quit))
22070 (defun org-agenda-execute (arg)
22071 "Execute another agenda command, keeping same window.\\<global-map>
22072 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22073 (interactive "P")
22074 (let ((org-agenda-window-setup 'current-window))
22075 (org-agenda arg)))
22077 (defun org-save-all-org-buffers ()
22078 "Save all Org-mode buffers without user confirmation."
22079 (interactive)
22080 (message "Saving all Org-mode buffers...")
22081 (save-some-buffers t 'org-mode-p)
22082 (message "Saving all Org-mode buffers... done"))
22084 (defun org-agenda-redo ()
22085 "Rebuild Agenda.
22086 When this is the global TODO list, a prefix argument will be interpreted."
22087 (interactive)
22088 (let* ((org-agenda-keep-modes t)
22089 (line (org-current-line))
22090 (window-line (- line (org-current-line (window-start))))
22091 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22092 (message "Rebuilding agenda buffer...")
22093 (org-let lprops '(eval org-agenda-redo-command))
22094 (setq org-agenda-undo-list nil
22095 org-agenda-pending-undo-list nil)
22096 (message "Rebuilding agenda buffer...done")
22097 (goto-line line)
22098 (recenter window-line)))
22100 (defun org-agenda-goto-date (date)
22101 "Jump to DATE in agenda."
22102 (interactive (list (org-read-date)))
22103 (org-agenda-list nil date))
22105 (defun org-agenda-goto-today ()
22106 "Go to today."
22107 (interactive)
22108 (org-agenda-check-type t 'timeline 'agenda)
22109 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22110 (cond
22111 (tdpos (goto-char tdpos))
22112 ((eq org-agenda-type 'agenda)
22113 (let* ((sd (time-to-days
22114 (time-subtract (current-time)
22115 (list 0 (* 3600 org-extend-today-until) 0))))
22116 (comp (org-agenda-compute-time-span sd org-agenda-span))
22117 (org-agenda-overriding-arguments org-agenda-last-arguments))
22118 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22119 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22120 (org-agenda-redo)
22121 (org-agenda-find-same-or-today-or-agenda)))
22122 (t (error "Cannot find today")))))
22124 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22125 (goto-char
22126 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22127 (text-property-any (point-min) (point-max) 'org-today t)
22128 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22129 (point-min))))
22131 (defun org-agenda-later (arg)
22132 "Go forward in time by thee current span.
22133 With prefix ARG, go forward that many times the current span."
22134 (interactive "p")
22135 (org-agenda-check-type t 'agenda)
22136 (let* ((span org-agenda-span)
22137 (sd org-starting-day)
22138 (greg (calendar-gregorian-from-absolute sd))
22139 (cnt (get-text-property (point) 'org-day-cnt))
22140 greg2 nd)
22141 (cond
22142 ((eq span 'day)
22143 (setq sd (+ arg sd) nd 1))
22144 ((eq span 'week)
22145 (setq sd (+ (* 7 arg) sd) nd 7))
22146 ((eq span 'month)
22147 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22148 sd (calendar-absolute-from-gregorian greg2))
22149 (setcar greg2 (1+ (car greg2)))
22150 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22151 ((eq span 'year)
22152 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22153 sd (calendar-absolute-from-gregorian greg2))
22154 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22155 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22156 (let ((org-agenda-overriding-arguments
22157 (list (car org-agenda-last-arguments) sd nd t)))
22158 (org-agenda-redo)
22159 (org-agenda-find-same-or-today-or-agenda cnt))))
22161 (defun org-agenda-earlier (arg)
22162 "Go backward in time by the current span.
22163 With prefix ARG, go backward that many times the current span."
22164 (interactive "p")
22165 (org-agenda-later (- arg)))
22167 (defun org-agenda-day-view ()
22168 "Switch to daily view for agenda."
22169 (interactive)
22170 (setq org-agenda-ndays 1)
22171 (org-agenda-change-time-span 'day))
22172 (defun org-agenda-week-view ()
22173 "Switch to daily view for agenda."
22174 (interactive)
22175 (setq org-agenda-ndays 7)
22176 (org-agenda-change-time-span 'week))
22177 (defun org-agenda-month-view ()
22178 "Switch to daily view for agenda."
22179 (interactive)
22180 (org-agenda-change-time-span 'month))
22181 (defun org-agenda-year-view ()
22182 "Switch to daily view for agenda."
22183 (interactive)
22184 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22185 (org-agenda-change-time-span 'year)
22186 (error "Abort")))
22188 (defun org-agenda-change-time-span (span)
22189 "Change the agenda view to SPAN.
22190 SPAN may be `day', `week', `month', `year'."
22191 (org-agenda-check-type t 'agenda)
22192 (if (equal org-agenda-span span)
22193 (error "Viewing span is already \"%s\"" span))
22194 (let* ((sd (or (get-text-property (point) 'day)
22195 org-starting-day))
22196 (computed (org-agenda-compute-time-span sd span))
22197 (org-agenda-overriding-arguments
22198 (list (car org-agenda-last-arguments)
22199 (car computed) (cdr computed) t)))
22200 (org-agenda-redo)
22201 (org-agenda-find-same-or-today-or-agenda))
22202 (org-agenda-set-mode-name)
22203 (message "Switched to %s view" span))
22205 (defun org-agenda-compute-time-span (sd span)
22206 "Compute starting date and number of days for agenda.
22207 SPAN may be `day', `week', `month', `year'. The return value
22208 is a cons cell with the starting date and the number of days,
22209 so that the date SD will be in that range."
22210 (let* ((greg (calendar-gregorian-from-absolute sd))
22212 (cond
22213 ((eq span 'day)
22214 (setq nd 1))
22215 ((eq span 'week)
22216 (let* ((nt (calendar-day-of-week
22217 (calendar-gregorian-from-absolute sd)))
22218 (d (if org-agenda-start-on-weekday
22219 (- nt org-agenda-start-on-weekday)
22220 0)))
22221 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22222 (setq nd 7)))
22223 ((eq span 'month)
22224 (setq sd (calendar-absolute-from-gregorian
22225 (list (car greg) 1 (nth 2 greg)))
22226 nd (- (calendar-absolute-from-gregorian
22227 (list (1+ (car greg)) 1 (nth 2 greg)))
22228 sd)))
22229 ((eq span 'year)
22230 (setq sd (calendar-absolute-from-gregorian
22231 (list 1 1 (nth 2 greg)))
22232 nd (- (calendar-absolute-from-gregorian
22233 (list 1 1 (1+ (nth 2 greg))))
22234 sd))))
22235 (cons sd nd)))
22237 ;; FIXME: does not work if user makes date format that starts with a blank
22238 (defun org-agenda-next-date-line (&optional arg)
22239 "Jump to the next line indicating a date in agenda buffer."
22240 (interactive "p")
22241 (org-agenda-check-type t 'agenda 'timeline)
22242 (beginning-of-line 1)
22243 (if (looking-at "^\\S-") (forward-char 1))
22244 (if (not (re-search-forward "^\\S-" nil t arg))
22245 (progn
22246 (backward-char 1)
22247 (error "No next date after this line in this buffer")))
22248 (goto-char (match-beginning 0)))
22250 (defun org-agenda-previous-date-line (&optional arg)
22251 "Jump to the previous line indicating a date in agenda buffer."
22252 (interactive "p")
22253 (org-agenda-check-type t 'agenda 'timeline)
22254 (beginning-of-line 1)
22255 (if (not (re-search-backward "^\\S-" nil t arg))
22256 (error "No previous date before this line in this buffer")))
22258 ;; Initialize the highlight
22259 (defvar org-hl (org-make-overlay 1 1))
22260 (org-overlay-put org-hl 'face 'highlight)
22262 (defun org-highlight (begin end &optional buffer)
22263 "Highlight a region with overlay."
22264 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22265 org-hl begin end (or buffer (current-buffer))))
22267 (defun org-unhighlight ()
22268 "Detach overlay INDEX."
22269 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22271 ;; FIXME this is currently not used.
22272 (defun org-highlight-until-next-command (beg end &optional buffer)
22273 (org-highlight beg end buffer)
22274 (add-hook 'pre-command-hook 'org-unhighlight-once))
22275 (defun org-unhighlight-once ()
22276 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22277 (org-unhighlight))
22279 (defun org-agenda-follow-mode ()
22280 "Toggle follow mode in an agenda buffer."
22281 (interactive)
22282 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22283 (org-agenda-set-mode-name)
22284 (message "Follow mode is %s"
22285 (if org-agenda-follow-mode "on" "off")))
22287 (defun org-agenda-log-mode ()
22288 "Toggle log mode in an agenda buffer."
22289 (interactive)
22290 (org-agenda-check-type t 'agenda 'timeline)
22291 (setq org-agenda-show-log (not org-agenda-show-log))
22292 (org-agenda-set-mode-name)
22293 (org-agenda-redo)
22294 (message "Log mode is %s"
22295 (if org-agenda-show-log "on" "off")))
22297 (defun org-agenda-toggle-diary ()
22298 "Toggle diary inclusion in an agenda buffer."
22299 (interactive)
22300 (org-agenda-check-type t 'agenda)
22301 (setq org-agenda-include-diary (not org-agenda-include-diary))
22302 (org-agenda-redo)
22303 (org-agenda-set-mode-name)
22304 (message "Diary inclusion turned %s"
22305 (if org-agenda-include-diary "on" "off")))
22307 (defun org-agenda-toggle-time-grid ()
22308 "Toggle time grid in an agenda buffer."
22309 (interactive)
22310 (org-agenda-check-type t 'agenda)
22311 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22312 (org-agenda-redo)
22313 (org-agenda-set-mode-name)
22314 (message "Time-grid turned %s"
22315 (if org-agenda-use-time-grid "on" "off")))
22317 (defun org-agenda-set-mode-name ()
22318 "Set the mode name to indicate all the small mode settings."
22319 (setq mode-name
22320 (concat "Org-Agenda"
22321 (if (equal org-agenda-ndays 1) " Day" "")
22322 (if (equal org-agenda-ndays 7) " Week" "")
22323 (if org-agenda-follow-mode " Follow" "")
22324 (if org-agenda-include-diary " Diary" "")
22325 (if org-agenda-use-time-grid " Grid" "")
22326 (if org-agenda-show-log " Log" "")))
22327 (force-mode-line-update))
22329 (defun org-agenda-post-command-hook ()
22330 (and (eolp) (not (bolp)) (backward-char 1))
22331 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22332 (if (and org-agenda-follow-mode
22333 (get-text-property (point) 'org-marker))
22334 (org-agenda-show)))
22336 (defun org-agenda-show-priority ()
22337 "Show the priority of the current item.
22338 This priority is composed of the main priority given with the [#A] cookies,
22339 and by additional input from the age of a schedules or deadline entry."
22340 (interactive)
22341 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22342 (message "Priority is %d" (if pri pri -1000))))
22344 (defun org-agenda-show-tags ()
22345 "Show the tags applicable to the current item."
22346 (interactive)
22347 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22348 (if tags
22349 (message "Tags are :%s:"
22350 (org-no-properties (mapconcat 'identity tags ":")))
22351 (message "No tags associated with this line"))))
22353 (defun org-agenda-goto (&optional highlight)
22354 "Go to the Org-mode file which contains the item at point."
22355 (interactive)
22356 (let* ((marker (or (get-text-property (point) 'org-marker)
22357 (org-agenda-error)))
22358 (buffer (marker-buffer marker))
22359 (pos (marker-position marker)))
22360 (switch-to-buffer-other-window buffer)
22361 (widen)
22362 (goto-char pos)
22363 (when (org-mode-p)
22364 (org-show-context 'agenda)
22365 (save-excursion
22366 (and (outline-next-heading)
22367 (org-flag-heading nil)))) ; show the next heading
22368 (recenter (/ (window-height) 2))
22369 (run-hooks 'org-agenda-after-show-hook)
22370 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22372 (defvar org-agenda-after-show-hook nil
22373 "Normal hook run after an item has been shown from the agenda.
22374 Point is in the buffer where the item originated.")
22376 (defun org-agenda-kill ()
22377 "Kill the entry or subtree belonging to the current agenda entry."
22378 (interactive)
22379 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22380 (let* ((marker (or (get-text-property (point) 'org-marker)
22381 (org-agenda-error)))
22382 (buffer (marker-buffer marker))
22383 (pos (marker-position marker))
22384 (type (get-text-property (point) 'type))
22385 dbeg dend (n 0) conf)
22386 (org-with-remote-undo buffer
22387 (with-current-buffer buffer
22388 (save-excursion
22389 (goto-char pos)
22390 (if (and (org-mode-p) (not (member type '("sexp"))))
22391 (setq dbeg (progn (org-back-to-heading t) (point))
22392 dend (org-end-of-subtree t t))
22393 (setq dbeg (point-at-bol)
22394 dend (min (point-max) (1+ (point-at-eol)))))
22395 (goto-char dbeg)
22396 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22397 (setq conf (or (eq t org-agenda-confirm-kill)
22398 (and (numberp org-agenda-confirm-kill)
22399 (> n org-agenda-confirm-kill))))
22400 (and conf
22401 (not (y-or-n-p
22402 (format "Delete entry with %d lines in buffer \"%s\"? "
22403 n (buffer-name buffer))))
22404 (error "Abort"))
22405 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22406 (with-current-buffer buffer (delete-region dbeg dend))
22407 (message "Agenda item and source killed"))))
22409 (defun org-agenda-archive ()
22410 "Kill the entry or subtree belonging to the current agenda entry."
22411 (interactive)
22412 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22413 (let* ((marker (or (get-text-property (point) 'org-marker)
22414 (org-agenda-error)))
22415 (buffer (marker-buffer marker))
22416 (pos (marker-position marker)))
22417 (org-with-remote-undo buffer
22418 (with-current-buffer buffer
22419 (if (org-mode-p)
22420 (save-excursion
22421 (goto-char pos)
22422 (org-remove-subtree-entries-from-agenda)
22423 (org-back-to-heading t)
22424 (org-archive-subtree))
22425 (error "Archiving works only in Org-mode files"))))))
22427 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22428 "Remove all lines in the agenda that correspond to a given subtree.
22429 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22430 If this information is not given, the function uses the tree at point."
22431 (let ((buf (or buf (current-buffer))) m p)
22432 (save-excursion
22433 (unless (and beg end)
22434 (org-back-to-heading t)
22435 (setq beg (point))
22436 (org-end-of-subtree t)
22437 (setq end (point)))
22438 (set-buffer (get-buffer org-agenda-buffer-name))
22439 (save-excursion
22440 (goto-char (point-max))
22441 (beginning-of-line 1)
22442 (while (not (bobp))
22443 (when (and (setq m (get-text-property (point) 'org-marker))
22444 (equal buf (marker-buffer m))
22445 (setq p (marker-position m))
22446 (>= p beg)
22447 (<= p end))
22448 (let ((inhibit-read-only t))
22449 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22450 (beginning-of-line 0))))))
22452 (defun org-agenda-open-link ()
22453 "Follow the link in the current line, if any."
22454 (interactive)
22455 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22456 (save-excursion
22457 (save-restriction
22458 (narrow-to-region (point-at-bol) (point-at-eol))
22459 (org-open-at-point))))
22461 (defun org-agenda-copy-local-variable (var)
22462 "Get a variable from a referenced buffer and install it here."
22463 (let ((m (get-text-property (point) 'org-marker)))
22464 (when (and m (buffer-live-p (marker-buffer m)))
22465 (org-set-local var (with-current-buffer (marker-buffer m)
22466 (symbol-value var))))))
22468 (defun org-agenda-switch-to (&optional delete-other-windows)
22469 "Go to the Org-mode file which contains the item at point."
22470 (interactive)
22471 (let* ((marker (or (get-text-property (point) 'org-marker)
22472 (org-agenda-error)))
22473 (buffer (marker-buffer marker))
22474 (pos (marker-position marker)))
22475 (switch-to-buffer buffer)
22476 (and delete-other-windows (delete-other-windows))
22477 (widen)
22478 (goto-char pos)
22479 (when (org-mode-p)
22480 (org-show-context 'agenda)
22481 (save-excursion
22482 (and (outline-next-heading)
22483 (org-flag-heading nil)))))) ; show the next heading
22485 (defun org-agenda-goto-mouse (ev)
22486 "Go to the Org-mode file which contains the item at the mouse click."
22487 (interactive "e")
22488 (mouse-set-point ev)
22489 (org-agenda-goto))
22491 (defun org-agenda-show ()
22492 "Display the Org-mode file which contains the item at point."
22493 (interactive)
22494 (let ((win (selected-window)))
22495 (org-agenda-goto t)
22496 (select-window win)))
22498 (defun org-agenda-recenter (arg)
22499 "Display the Org-mode file which contains the item at point and recenter."
22500 (interactive "P")
22501 (let ((win (selected-window)))
22502 (org-agenda-goto t)
22503 (recenter arg)
22504 (select-window win)))
22506 (defun org-agenda-show-mouse (ev)
22507 "Display the Org-mode file which contains the item at the mouse click."
22508 (interactive "e")
22509 (mouse-set-point ev)
22510 (org-agenda-show))
22512 (defun org-agenda-check-no-diary ()
22513 "Check if the entry is a diary link and abort if yes."
22514 (if (get-text-property (point) 'org-agenda-diary-link)
22515 (org-agenda-error)))
22517 (defun org-agenda-error ()
22518 (error "Command not allowed in this line"))
22520 (defun org-agenda-tree-to-indirect-buffer ()
22521 "Show the subtree corresponding to the current entry in an indirect buffer.
22522 This calls the command `org-tree-to-indirect-buffer' from the original
22523 Org-mode buffer.
22524 With numerical prefix arg ARG, go up to this level and then take that tree.
22525 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22526 dedicated frame)."
22527 (interactive)
22528 (org-agenda-check-no-diary)
22529 (let* ((marker (or (get-text-property (point) 'org-marker)
22530 (org-agenda-error)))
22531 (buffer (marker-buffer marker))
22532 (pos (marker-position marker)))
22533 (with-current-buffer buffer
22534 (save-excursion
22535 (goto-char pos)
22536 (call-interactively 'org-tree-to-indirect-buffer)))))
22538 (defvar org-last-heading-marker (make-marker)
22539 "Marker pointing to the headline that last changed its TODO state
22540 by a remote command from the agenda.")
22542 (defun org-agenda-todo-nextset ()
22543 "Switch TODO entry to next sequence."
22544 (interactive)
22545 (org-agenda-todo 'nextset))
22547 (defun org-agenda-todo-previousset ()
22548 "Switch TODO entry to previous sequence."
22549 (interactive)
22550 (org-agenda-todo 'previousset))
22552 (defun org-agenda-todo (&optional arg)
22553 "Cycle TODO state of line at point, also in Org-mode file.
22554 This changes the line at point, all other lines in the agenda referring to
22555 the same tree node, and the headline of the tree node in the Org-mode file."
22556 (interactive "P")
22557 (org-agenda-check-no-diary)
22558 (let* ((col (current-column))
22559 (marker (or (get-text-property (point) 'org-marker)
22560 (org-agenda-error)))
22561 (buffer (marker-buffer marker))
22562 (pos (marker-position marker))
22563 (hdmarker (get-text-property (point) 'org-hd-marker))
22564 (inhibit-read-only t)
22565 newhead)
22566 (org-with-remote-undo buffer
22567 (with-current-buffer buffer
22568 (widen)
22569 (goto-char pos)
22570 (org-show-context 'agenda)
22571 (save-excursion
22572 (and (outline-next-heading)
22573 (org-flag-heading nil))) ; show the next heading
22574 (org-todo arg)
22575 (and (bolp) (forward-char 1))
22576 (setq newhead (org-get-heading))
22577 (save-excursion
22578 (org-back-to-heading)
22579 (move-marker org-last-heading-marker (point))))
22580 (beginning-of-line 1)
22581 (save-excursion
22582 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22583 (move-to-column col))))
22585 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22586 "Change all lines in the agenda buffer which match HDMARKER.
22587 The new content of the line will be NEWHEAD (as modified by
22588 `org-format-agenda-item'). HDMARKER is checked with
22589 `equal' against all `org-hd-marker' text properties in the file.
22590 If FIXFACE is non-nil, the face of each item is modified acording to
22591 the new TODO state."
22592 (let* ((inhibit-read-only t)
22593 props m pl undone-face done-face finish new dotime cat tags)
22594 (save-excursion
22595 (goto-char (point-max))
22596 (beginning-of-line 1)
22597 (while (not finish)
22598 (setq finish (bobp))
22599 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22600 (equal m hdmarker))
22601 (setq props (text-properties-at (point))
22602 dotime (get-text-property (point) 'dotime)
22603 cat (get-text-property (point) 'org-category)
22604 tags (get-text-property (point) 'tags)
22605 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22606 pl (get-text-property (point) 'prefix-length)
22607 undone-face (get-text-property (point) 'undone-face)
22608 done-face (get-text-property (point) 'done-face))
22609 (move-to-column pl)
22610 (cond
22611 ((equal new "")
22612 (beginning-of-line 1)
22613 (and (looking-at ".*\n?") (replace-match "")))
22614 ((looking-at ".*")
22615 (replace-match new t t)
22616 (beginning-of-line 1)
22617 (add-text-properties (point-at-bol) (point-at-eol) props)
22618 (when fixface
22619 (add-text-properties
22620 (point-at-bol) (point-at-eol)
22621 (list 'face
22622 (if org-last-todo-state-is-todo
22623 undone-face done-face))))
22624 (org-agenda-highlight-todo 'line)
22625 (beginning-of-line 1))
22626 (t (error "Line update did not work"))))
22627 (beginning-of-line 0)))
22628 (org-finalize-agenda)))
22630 (defun org-agenda-align-tags (&optional line)
22631 "Align all tags in agenda items to `org-agenda-tags-column'."
22632 (let ((inhibit-read-only t) l c)
22633 (save-excursion
22634 (goto-char (if line (point-at-bol) (point-min)))
22635 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22636 (if line (point-at-eol) nil) t)
22637 (add-text-properties
22638 (match-beginning 2) (match-end 2)
22639 (list 'face (list 'org-tag (get-text-property
22640 (match-beginning 2) 'face))))
22641 (setq l (- (match-end 2) (match-beginning 2))
22642 c (if (< org-agenda-tags-column 0)
22643 (- (abs org-agenda-tags-column) l)
22644 org-agenda-tags-column))
22645 (delete-region (match-beginning 1) (match-end 1))
22646 (goto-char (match-beginning 1))
22647 (insert (org-add-props
22648 (make-string (max 1 (- c (current-column))) ?\ )
22649 (text-properties-at (point))))))))
22651 (defun org-agenda-priority-up ()
22652 "Increase the priority of line at point, also in Org-mode file."
22653 (interactive)
22654 (org-agenda-priority 'up))
22656 (defun org-agenda-priority-down ()
22657 "Decrease the priority of line at point, also in Org-mode file."
22658 (interactive)
22659 (org-agenda-priority 'down))
22661 (defun org-agenda-priority (&optional force-direction)
22662 "Set the priority of line at point, also in Org-mode file.
22663 This changes the line at point, all other lines in the agenda referring to
22664 the same tree node, and the headline of the tree node in the Org-mode file."
22665 (interactive)
22666 (org-agenda-check-no-diary)
22667 (let* ((marker (or (get-text-property (point) 'org-marker)
22668 (org-agenda-error)))
22669 (hdmarker (get-text-property (point) 'org-hd-marker))
22670 (buffer (marker-buffer hdmarker))
22671 (pos (marker-position hdmarker))
22672 (inhibit-read-only t)
22673 newhead)
22674 (org-with-remote-undo buffer
22675 (with-current-buffer buffer
22676 (widen)
22677 (goto-char pos)
22678 (org-show-context 'agenda)
22679 (save-excursion
22680 (and (outline-next-heading)
22681 (org-flag-heading nil))) ; show the next heading
22682 (funcall 'org-priority force-direction)
22683 (end-of-line 1)
22684 (setq newhead (org-get-heading)))
22685 (org-agenda-change-all-lines newhead hdmarker)
22686 (beginning-of-line 1))))
22688 (defun org-get-tags-at (&optional pos)
22689 "Get a list of all headline tags applicable at POS.
22690 POS defaults to point. If tags are inherited, the list contains
22691 the targets in the same sequence as the headlines appear, i.e.
22692 the tags of the current headline come last."
22693 (interactive)
22694 (let (tags lastpos)
22695 (save-excursion
22696 (save-restriction
22697 (widen)
22698 (goto-char (or pos (point)))
22699 (save-match-data
22700 (org-back-to-heading t)
22701 (condition-case nil
22702 (while (not (equal lastpos (point)))
22703 (setq lastpos (point))
22704 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22705 (setq tags (append (org-split-string
22706 (org-match-string-no-properties 1) ":")
22707 tags)))
22708 (or org-use-tag-inheritance (error ""))
22709 (org-up-heading-all 1))
22710 (error nil))))
22711 tags)))
22713 ;; FIXME: should fix the tags property of the agenda line.
22714 (defun org-agenda-set-tags ()
22715 "Set tags for the current headline."
22716 (interactive)
22717 (org-agenda-check-no-diary)
22718 (if (and (org-region-active-p) (interactive-p))
22719 (call-interactively 'org-change-tag-in-region)
22720 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22721 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22722 (org-agenda-error)))
22723 (buffer (marker-buffer hdmarker))
22724 (pos (marker-position hdmarker))
22725 (inhibit-read-only t)
22726 newhead)
22727 (org-with-remote-undo buffer
22728 (with-current-buffer buffer
22729 (widen)
22730 (goto-char pos)
22731 (save-excursion
22732 (org-show-context 'agenda))
22733 (save-excursion
22734 (and (outline-next-heading)
22735 (org-flag-heading nil))) ; show the next heading
22736 (goto-char pos)
22737 (call-interactively 'org-set-tags)
22738 (end-of-line 1)
22739 (setq newhead (org-get-heading)))
22740 (org-agenda-change-all-lines newhead hdmarker)
22741 (beginning-of-line 1)))))
22743 (defun org-agenda-toggle-archive-tag ()
22744 "Toggle the archive tag for the current entry."
22745 (interactive)
22746 (org-agenda-check-no-diary)
22747 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22748 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22749 (org-agenda-error)))
22750 (buffer (marker-buffer hdmarker))
22751 (pos (marker-position hdmarker))
22752 (inhibit-read-only t)
22753 newhead)
22754 (org-with-remote-undo buffer
22755 (with-current-buffer buffer
22756 (widen)
22757 (goto-char pos)
22758 (org-show-context 'agenda)
22759 (save-excursion
22760 (and (outline-next-heading)
22761 (org-flag-heading nil))) ; show the next heading
22762 (call-interactively 'org-toggle-archive-tag)
22763 (end-of-line 1)
22764 (setq newhead (org-get-heading)))
22765 (org-agenda-change-all-lines newhead hdmarker)
22766 (beginning-of-line 1))))
22768 (defun org-agenda-date-later (arg &optional what)
22769 "Change the date of this item to one day later."
22770 (interactive "p")
22771 (org-agenda-check-type t 'agenda 'timeline)
22772 (org-agenda-check-no-diary)
22773 (let* ((marker (or (get-text-property (point) 'org-marker)
22774 (org-agenda-error)))
22775 (buffer (marker-buffer marker))
22776 (pos (marker-position marker)))
22777 (org-with-remote-undo buffer
22778 (with-current-buffer buffer
22779 (widen)
22780 (goto-char pos)
22781 (if (not (org-at-timestamp-p))
22782 (error "Cannot find time stamp"))
22783 (org-timestamp-change arg (or what 'day)))
22784 (org-agenda-show-new-time marker org-last-changed-timestamp))
22785 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22787 (defun org-agenda-date-earlier (arg &optional what)
22788 "Change the date of this item to one day earlier."
22789 (interactive "p")
22790 (org-agenda-date-later (- arg) what))
22792 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22793 "Show new date stamp via text properties."
22794 ;; We use text properties to make this undoable
22795 (let ((inhibit-read-only t))
22796 (setq stamp (concat " " prefix " => " stamp))
22797 (save-excursion
22798 (goto-char (point-max))
22799 (while (not (bobp))
22800 (when (equal marker (get-text-property (point) 'org-marker))
22801 (move-to-column (- (window-width) (length stamp)) t)
22802 (if (featurep 'xemacs)
22803 ;; Use `duplicable' property to trigger undo recording
22804 (let ((ex (make-extent nil nil))
22805 (gl (make-glyph stamp)))
22806 (set-glyph-face gl 'secondary-selection)
22807 (set-extent-properties
22808 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22809 (insert-extent ex (1- (point)) (point-at-eol)))
22810 (add-text-properties
22811 (1- (point)) (point-at-eol)
22812 (list 'display (org-add-props stamp nil
22813 'face 'secondary-selection))))
22814 (beginning-of-line 1))
22815 (beginning-of-line 0)))))
22817 (defun org-agenda-date-prompt (arg)
22818 "Change the date of this item. Date is prompted for, with default today.
22819 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22820 be used to request time specification in the time stamp."
22821 (interactive "P")
22822 (org-agenda-check-type t 'agenda 'timeline)
22823 (org-agenda-check-no-diary)
22824 (let* ((marker (or (get-text-property (point) 'org-marker)
22825 (org-agenda-error)))
22826 (buffer (marker-buffer marker))
22827 (pos (marker-position marker)))
22828 (org-with-remote-undo buffer
22829 (with-current-buffer buffer
22830 (widen)
22831 (goto-char pos)
22832 (if (not (org-at-timestamp-p))
22833 (error "Cannot find time stamp"))
22834 (org-time-stamp arg)
22835 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22837 (defun org-agenda-schedule (arg)
22838 "Schedule the item at point."
22839 (interactive "P")
22840 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22841 (org-agenda-check-no-diary)
22842 (let* ((marker (or (get-text-property (point) 'org-marker)
22843 (org-agenda-error)))
22844 (buffer (marker-buffer marker))
22845 (pos (marker-position marker))
22846 (org-insert-labeled-timestamps-at-point nil)
22848 (org-with-remote-undo buffer
22849 (with-current-buffer buffer
22850 (widen)
22851 (goto-char pos)
22852 (setq ts (org-schedule arg)))
22853 (org-agenda-show-new-time marker ts "S"))
22854 (message "Item scheduled for %s" ts)))
22856 (defun org-agenda-deadline (arg)
22857 "Schedule the item at point."
22858 (interactive "P")
22859 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22860 (org-agenda-check-no-diary)
22861 (let* ((marker (or (get-text-property (point) 'org-marker)
22862 (org-agenda-error)))
22863 (buffer (marker-buffer marker))
22864 (pos (marker-position marker))
22865 (org-insert-labeled-timestamps-at-point nil)
22867 (org-with-remote-undo buffer
22868 (with-current-buffer buffer
22869 (widen)
22870 (goto-char pos)
22871 (setq ts (org-deadline arg)))
22872 (org-agenda-show-new-time marker ts "S"))
22873 (message "Deadline for this item set to %s" ts)))
22875 (defun org-get-heading (&optional no-tags)
22876 "Return the heading of the current entry, without the stars."
22877 (save-excursion
22878 (org-back-to-heading t)
22879 (if (looking-at
22880 (if no-tags
22881 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22882 "\\*+[ \t]+\\([^\r\n]*\\)"))
22883 (match-string 1) "")))
22885 (defun org-agenda-clock-in (&optional arg)
22886 "Start the clock on the currently selected item."
22887 (interactive "P")
22888 (org-agenda-check-no-diary)
22889 (let* ((marker (or (get-text-property (point) 'org-marker)
22890 (org-agenda-error)))
22891 (pos (marker-position marker)))
22892 (org-with-remote-undo (marker-buffer marker)
22893 (with-current-buffer (marker-buffer marker)
22894 (widen)
22895 (goto-char pos)
22896 (org-clock-in)))))
22898 (defun org-agenda-clock-out (&optional arg)
22899 "Stop the currently running clock."
22900 (interactive "P")
22901 (unless (marker-buffer org-clock-marker)
22902 (error "No running clock"))
22903 (org-with-remote-undo (marker-buffer org-clock-marker)
22904 (org-clock-out)))
22906 (defun org-agenda-clock-cancel (&optional arg)
22907 "Cancel the currently running clock."
22908 (interactive "P")
22909 (unless (marker-buffer org-clock-marker)
22910 (error "No running clock"))
22911 (org-with-remote-undo (marker-buffer org-clock-marker)
22912 (org-clock-cancel)))
22914 (defun org-agenda-diary-entry ()
22915 "Make a diary entry, like the `i' command from the calendar.
22916 All the standard commands work: block, weekly etc."
22917 (interactive)
22918 (org-agenda-check-type t 'agenda 'timeline)
22919 (require 'diary-lib)
22920 (let* ((char (progn
22921 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
22922 (read-char-exclusive)))
22923 (cmd (cdr (assoc char
22924 '((?d . insert-diary-entry)
22925 (?w . insert-weekly-diary-entry)
22926 (?m . insert-monthly-diary-entry)
22927 (?y . insert-yearly-diary-entry)
22928 (?a . insert-anniversary-diary-entry)
22929 (?b . insert-block-diary-entry)
22930 (?c . insert-cyclic-diary-entry)))))
22931 (oldf (symbol-function 'calendar-cursor-to-date))
22932 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
22933 (point (point))
22934 (mark (or (mark t) (point))))
22935 (unless cmd
22936 (error "No command associated with <%c>" char))
22937 (unless (and (get-text-property point 'day)
22938 (or (not (equal ?b char))
22939 (get-text-property mark 'day)))
22940 (error "Don't know which date to use for diary entry"))
22941 ;; We implement this by hacking the `calendar-cursor-to-date' function
22942 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
22943 (let ((calendar-mark-ring
22944 (list (calendar-gregorian-from-absolute
22945 (or (get-text-property mark 'day)
22946 (get-text-property point 'day))))))
22947 (unwind-protect
22948 (progn
22949 (fset 'calendar-cursor-to-date
22950 (lambda (&optional error)
22951 (calendar-gregorian-from-absolute
22952 (get-text-property point 'day))))
22953 (call-interactively cmd))
22954 (fset 'calendar-cursor-to-date oldf)))))
22957 (defun org-agenda-execute-calendar-command (cmd)
22958 "Execute a calendar command from the agenda, with the date associated to
22959 the cursor position."
22960 (org-agenda-check-type t 'agenda 'timeline)
22961 (require 'diary-lib)
22962 (unless (get-text-property (point) 'day)
22963 (error "Don't know which date to use for calendar command"))
22964 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
22965 (point (point))
22966 (date (calendar-gregorian-from-absolute
22967 (get-text-property point 'day)))
22968 ;; the following 3 vars are needed in the calendar
22969 (displayed-day (extract-calendar-day date))
22970 (displayed-month (extract-calendar-month date))
22971 (displayed-year (extract-calendar-year date)))
22972 (unwind-protect
22973 (progn
22974 (fset 'calendar-cursor-to-date
22975 (lambda (&optional error)
22976 (calendar-gregorian-from-absolute
22977 (get-text-property point 'day))))
22978 (call-interactively cmd))
22979 (fset 'calendar-cursor-to-date oldf))))
22981 (defun org-agenda-phases-of-moon ()
22982 "Display the phases of the moon for the 3 months around the cursor date."
22983 (interactive)
22984 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
22986 (defun org-agenda-holidays ()
22987 "Display the holidays for the 3 months around the cursor date."
22988 (interactive)
22989 (org-agenda-execute-calendar-command 'list-calendar-holidays))
22991 (defun org-agenda-sunrise-sunset (arg)
22992 "Display sunrise and sunset for the cursor date.
22993 Latitude and longitude can be specified with the variables
22994 `calendar-latitude' and `calendar-longitude'. When called with prefix
22995 argument, latitude and longitude will be prompted for."
22996 (interactive "P")
22997 (let ((calendar-longitude (if arg nil calendar-longitude))
22998 (calendar-latitude (if arg nil calendar-latitude))
22999 (calendar-location-name
23000 (if arg "the given coordinates" calendar-location-name)))
23001 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23003 (defun org-agenda-goto-calendar ()
23004 "Open the Emacs calendar with the date at the cursor."
23005 (interactive)
23006 (org-agenda-check-type t 'agenda 'timeline)
23007 (let* ((day (or (get-text-property (point) 'day)
23008 (error "Don't know which date to open in calendar")))
23009 (date (calendar-gregorian-from-absolute day))
23010 (calendar-move-hook nil)
23011 (view-calendar-holidays-initially nil)
23012 (view-diary-entries-initially nil))
23013 (calendar)
23014 (calendar-goto-date date)))
23016 (defun org-calendar-goto-agenda ()
23017 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23018 This is a command that has to be installed in `calendar-mode-map'."
23019 (interactive)
23020 (org-agenda-list nil (calendar-absolute-from-gregorian
23021 (calendar-cursor-to-date))
23022 nil))
23024 (defun org-agenda-convert-date ()
23025 (interactive)
23026 (org-agenda-check-type t 'agenda 'timeline)
23027 (let ((day (get-text-property (point) 'day))
23028 date s)
23029 (unless day
23030 (error "Don't know which date to convert"))
23031 (setq date (calendar-gregorian-from-absolute day))
23032 (setq s (concat
23033 "Gregorian: " (calendar-date-string date) "\n"
23034 "ISO: " (calendar-iso-date-string date) "\n"
23035 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23036 "Julian: " (calendar-julian-date-string date) "\n"
23037 "Astron. JD: " (calendar-astro-date-string date)
23038 " (Julian date number at noon UTC)\n"
23039 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23040 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23041 "French: " (calendar-french-date-string date) "\n"
23042 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23043 "Mayan: " (calendar-mayan-date-string date) "\n"
23044 "Coptic: " (calendar-coptic-date-string date) "\n"
23045 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23046 "Persian: " (calendar-persian-date-string date) "\n"
23047 "Chinese: " (calendar-chinese-date-string date) "\n"))
23048 (with-output-to-temp-buffer "*Dates*"
23049 (princ s))
23050 (if (fboundp 'fit-window-to-buffer)
23051 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23054 ;;;; Embedded LaTeX
23056 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23057 "Keymap for the minor `org-cdlatex-mode'.")
23059 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23060 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23061 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23062 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23063 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23065 (defvar org-cdlatex-texmathp-advice-is-done nil
23066 "Flag remembering if we have applied the advice to texmathp already.")
23068 (define-minor-mode org-cdlatex-mode
23069 "Toggle the minor `org-cdlatex-mode'.
23070 This mode supports entering LaTeX environment and math in LaTeX fragments
23071 in Org-mode.
23072 \\{org-cdlatex-mode-map}"
23073 nil " OCDL" nil
23074 (when org-cdlatex-mode (require 'cdlatex))
23075 (unless org-cdlatex-texmathp-advice-is-done
23076 (setq org-cdlatex-texmathp-advice-is-done t)
23077 (defadvice texmathp (around org-math-always-on activate)
23078 "Always return t in org-mode buffers.
23079 This is because we want to insert math symbols without dollars even outside
23080 the LaTeX math segments. If Orgmode thinks that point is actually inside
23081 en embedded LaTeX fragement, let texmathp do its job.
23082 \\[org-cdlatex-mode-map]"
23083 (interactive)
23084 (let (p)
23085 (cond
23086 ((not (org-mode-p)) ad-do-it)
23087 ((eq this-command 'cdlatex-math-symbol)
23088 (setq ad-return-value t
23089 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23091 (let ((p (org-inside-LaTeX-fragment-p)))
23092 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23093 (setq ad-return-value t
23094 texmathp-why '("Org-mode embedded math" . 0))
23095 (if p ad-do-it)))))))))
23097 (defun turn-on-org-cdlatex ()
23098 "Unconditionally turn on `org-cdlatex-mode'."
23099 (org-cdlatex-mode 1))
23101 (defun org-inside-LaTeX-fragment-p ()
23102 "Test if point is inside a LaTeX fragment.
23103 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23104 sequence appearing also before point.
23105 Even though the matchers for math are configurable, this function assumes
23106 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23107 delimiters are skipped when they have been removed by customization.
23108 The return value is nil, or a cons cell with the delimiter and
23109 and the position of this delimiter.
23111 This function does a reasonably good job, but can locally be fooled by
23112 for example currency specifications. For example it will assume being in
23113 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23114 fragments that are properly closed, but during editing, we have to live
23115 with the uncertainty caused by missing closing delimiters. This function
23116 looks only before point, not after."
23117 (catch 'exit
23118 (let ((pos (point))
23119 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23120 (lim (progn
23121 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23122 (point)))
23123 dd-on str (start 0) m re)
23124 (goto-char pos)
23125 (when dodollar
23126 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23127 re (nth 1 (assoc "$" org-latex-regexps)))
23128 (while (string-match re str start)
23129 (cond
23130 ((= (match-end 0) (length str))
23131 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23132 ((= (match-end 0) (- (length str) 5))
23133 (throw 'exit nil))
23134 (t (setq start (match-end 0))))))
23135 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23136 (goto-char pos)
23137 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23138 (and (match-beginning 2) (throw 'exit nil))
23139 ;; count $$
23140 (while (re-search-backward "\\$\\$" lim t)
23141 (setq dd-on (not dd-on)))
23142 (goto-char pos)
23143 (if dd-on (cons "$$" m))))))
23146 (defun org-try-cdlatex-tab ()
23147 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23148 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23149 - inside a LaTeX fragment, or
23150 - after the first word in a line, where an abbreviation expansion could
23151 insert a LaTeX environment."
23152 (when org-cdlatex-mode
23153 (cond
23154 ((save-excursion
23155 (skip-chars-backward "a-zA-Z0-9*")
23156 (skip-chars-backward " \t")
23157 (bolp))
23158 (cdlatex-tab) t)
23159 ((org-inside-LaTeX-fragment-p)
23160 (cdlatex-tab) t)
23161 (t nil))))
23163 (defun org-cdlatex-underscore-caret (&optional arg)
23164 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23165 Revert to the normal definition outside of these fragments."
23166 (interactive "P")
23167 (if (org-inside-LaTeX-fragment-p)
23168 (call-interactively 'cdlatex-sub-superscript)
23169 (let (org-cdlatex-mode)
23170 (call-interactively (key-binding (vector last-input-event))))))
23172 (defun org-cdlatex-math-modify (&optional arg)
23173 "Execute `cdlatex-math-modify' in LaTeX fragments.
23174 Revert to the normal definition outside of these fragments."
23175 (interactive "P")
23176 (if (org-inside-LaTeX-fragment-p)
23177 (call-interactively 'cdlatex-math-modify)
23178 (let (org-cdlatex-mode)
23179 (call-interactively (key-binding (vector last-input-event))))))
23181 (defvar org-latex-fragment-image-overlays nil
23182 "List of overlays carrying the images of latex fragments.")
23183 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23185 (defun org-remove-latex-fragment-image-overlays ()
23186 "Remove all overlays with LaTeX fragment images in current buffer."
23187 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23188 (setq org-latex-fragment-image-overlays nil))
23190 (defun org-preview-latex-fragment (&optional subtree)
23191 "Preview the LaTeX fragment at point, or all locally or globally.
23192 If the cursor is in a LaTeX fragment, create the image and overlay
23193 it over the source code. If there is no fragment at point, display
23194 all fragments in the current text, from one headline to the next. With
23195 prefix SUBTREE, display all fragments in the current subtree. With a
23196 double prefix `C-u C-u', or when the cursor is before the first headline,
23197 display all fragments in the buffer.
23198 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23199 (interactive "P")
23200 (org-remove-latex-fragment-image-overlays)
23201 (save-excursion
23202 (save-restriction
23203 (let (beg end at msg)
23204 (cond
23205 ((or (equal subtree '(16))
23206 (not (save-excursion
23207 (re-search-backward (concat "^" outline-regexp) nil t))))
23208 (setq beg (point-min) end (point-max)
23209 msg "Creating images for buffer...%s"))
23210 ((equal subtree '(4))
23211 (org-back-to-heading)
23212 (setq beg (point) end (org-end-of-subtree t)
23213 msg "Creating images for subtree...%s"))
23215 (if (setq at (org-inside-LaTeX-fragment-p))
23216 (goto-char (max (point-min) (- (cdr at) 2)))
23217 (org-back-to-heading))
23218 (setq beg (point) end (progn (outline-next-heading) (point))
23219 msg (if at "Creating image...%s"
23220 "Creating images for entry...%s"))))
23221 (message msg "")
23222 (narrow-to-region beg end)
23223 (goto-char beg)
23224 (org-format-latex
23225 (concat "ltxpng/" (file-name-sans-extension
23226 (file-name-nondirectory
23227 buffer-file-name)))
23228 default-directory 'overlays msg at 'forbuffer)
23229 (message msg "done. Use `C-c C-c' to remove images.")))))
23231 (defvar org-latex-regexps
23232 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23233 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23234 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23235 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23236 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23237 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23238 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23239 "Regular expressions for matching embedded LaTeX.")
23241 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23242 "Replace LaTeX fragments with links to an image, and produce images."
23243 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23244 (let* ((prefixnodir (file-name-nondirectory prefix))
23245 (absprefix (expand-file-name prefix dir))
23246 (todir (file-name-directory absprefix))
23247 (opt org-format-latex-options)
23248 (matchers (plist-get opt :matchers))
23249 (re-list org-latex-regexps)
23250 (cnt 0) txt link beg end re e checkdir
23251 m n block linkfile movefile ov)
23252 ;; Check if there are old images files with this prefix, and remove them
23253 (when (file-directory-p todir)
23254 (mapc 'delete-file
23255 (directory-files
23256 todir 'full
23257 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23258 ;; Check the different regular expressions
23259 (while (setq e (pop re-list))
23260 (setq m (car e) re (nth 1 e) n (nth 2 e)
23261 block (if (nth 3 e) "\n\n" ""))
23262 (when (member m matchers)
23263 (goto-char (point-min))
23264 (while (re-search-forward re nil t)
23265 (when (or (not at) (equal (cdr at) (match-beginning n)))
23266 (setq txt (match-string n)
23267 beg (match-beginning n) end (match-end n)
23268 cnt (1+ cnt)
23269 linkfile (format "%s_%04d.png" prefix cnt)
23270 movefile (format "%s_%04d.png" absprefix cnt)
23271 link (concat block "[[file:" linkfile "]]" block))
23272 (if msg (message msg cnt))
23273 (goto-char beg)
23274 (unless checkdir ; make sure the directory exists
23275 (setq checkdir t)
23276 (or (file-directory-p todir) (make-directory todir)))
23277 (org-create-formula-image
23278 txt movefile opt forbuffer)
23279 (if overlays
23280 (progn
23281 (setq ov (org-make-overlay beg end))
23282 (if (featurep 'xemacs)
23283 (progn
23284 (org-overlay-put ov 'invisible t)
23285 (org-overlay-put
23286 ov 'end-glyph
23287 (make-glyph (vector 'png :file movefile))))
23288 (org-overlay-put
23289 ov 'display
23290 (list 'image :type 'png :file movefile :ascent 'center)))
23291 (push ov org-latex-fragment-image-overlays)
23292 (goto-char end))
23293 (delete-region beg end)
23294 (insert link))))))))
23296 ;; This function borrows from Ganesh Swami's latex2png.el
23297 (defun org-create-formula-image (string tofile options buffer)
23298 (let* ((tmpdir (if (featurep 'xemacs)
23299 (temp-directory)
23300 temporary-file-directory))
23301 (texfilebase (make-temp-name
23302 (expand-file-name "orgtex" tmpdir)))
23303 (texfile (concat texfilebase ".tex"))
23304 (dvifile (concat texfilebase ".dvi"))
23305 (pngfile (concat texfilebase ".png"))
23306 (fnh (face-attribute 'default :height nil))
23307 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23308 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23309 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23310 "Black"))
23311 (bg (or (plist-get options (if buffer :background :html-background))
23312 "Transparent")))
23313 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23314 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23315 (with-temp-file texfile
23316 (insert org-format-latex-header
23317 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23318 (let ((dir default-directory))
23319 (condition-case nil
23320 (progn
23321 (cd tmpdir)
23322 (call-process "latex" nil nil nil texfile))
23323 (error nil))
23324 (cd dir))
23325 (if (not (file-exists-p dvifile))
23326 (progn (message "Failed to create dvi file from %s" texfile) nil)
23327 (call-process "dvipng" nil nil nil
23328 "-E" "-fg" fg "-bg" bg
23329 "-D" dpi
23330 ;;"-x" scale "-y" scale
23331 "-T" "tight"
23332 "-o" pngfile
23333 dvifile)
23334 (if (not (file-exists-p pngfile))
23335 (progn (message "Failed to create png file from %s" texfile) nil)
23336 ;; Use the requested file name and clean up
23337 (copy-file pngfile tofile 'replace)
23338 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23339 (delete-file (concat texfilebase e)))
23340 pngfile))))
23342 (defun org-dvipng-color (attr)
23343 "Return an rgb color specification for dvipng."
23344 (apply 'format "rgb %s %s %s"
23345 (mapcar 'org-normalize-color
23346 (color-values (face-attribute 'default attr nil)))))
23348 (defun org-normalize-color (value)
23349 "Return string to be used as color value for an RGB component."
23350 (format "%g" (/ value 65535.0)))
23352 ;;;; Exporting
23354 ;;; Variables, constants, and parameter plists
23356 (defconst org-level-max 20)
23358 (defvar org-export-html-preamble nil
23359 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23360 (defvar org-export-html-postamble nil
23361 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23362 (defvar org-export-html-auto-preamble t
23363 "Should default preamble be inserted? Set by publishing functions.")
23364 (defvar org-export-html-auto-postamble t
23365 "Should default postamble be inserted? Set by publishing functions.")
23366 (defvar org-current-export-file nil) ; dynamically scoped parameter
23367 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23370 (defconst org-export-plist-vars
23371 '((:language . org-export-default-language)
23372 (:customtime . org-display-custom-times)
23373 (:headline-levels . org-export-headline-levels)
23374 (:section-numbers . org-export-with-section-numbers)
23375 (:table-of-contents . org-export-with-toc)
23376 (:preserve-breaks . org-export-preserve-breaks)
23377 (:archived-trees . org-export-with-archived-trees)
23378 (:emphasize . org-export-with-emphasize)
23379 (:sub-superscript . org-export-with-sub-superscripts)
23380 (:special-strings . org-export-with-special-strings)
23381 (:footnotes . org-export-with-footnotes)
23382 (:drawers . org-export-with-drawers)
23383 (:tags . org-export-with-tags)
23384 (:TeX-macros . org-export-with-TeX-macros)
23385 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23386 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23387 (:fixed-width . org-export-with-fixed-width)
23388 (:timestamps . org-export-with-timestamps)
23389 (:author-info . org-export-author-info)
23390 (:time-stamp-file . org-export-time-stamp-file)
23391 (:tables . org-export-with-tables)
23392 (:table-auto-headline . org-export-highlight-first-table-line)
23393 (:style . org-export-html-style)
23394 (:agenda-style . org-agenda-export-html-style)
23395 (:convert-org-links . org-export-html-link-org-files-as-html)
23396 (:inline-images . org-export-html-inline-images)
23397 (:html-extension . org-export-html-extension)
23398 (:html-table-tag . org-export-html-table-tag)
23399 (:expand-quoted-html . org-export-html-expand)
23400 (:timestamp . org-export-html-with-timestamp)
23401 (:publishing-directory . org-export-publishing-directory)
23402 (:preamble . org-export-html-preamble)
23403 (:postamble . org-export-html-postamble)
23404 (:auto-preamble . org-export-html-auto-preamble)
23405 (:auto-postamble . org-export-html-auto-postamble)
23406 (:author . user-full-name)
23407 (:email . user-mail-address)))
23409 (defun org-default-export-plist ()
23410 "Return the property list with default settings for the export variables."
23411 (let ((l org-export-plist-vars) rtn e)
23412 (while (setq e (pop l))
23413 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23414 rtn))
23416 (defun org-infile-export-plist ()
23417 "Return the property list with file-local settings for export."
23418 (save-excursion
23419 (save-restriction
23420 (widen)
23421 (goto-char 0)
23422 (let ((re (org-make-options-regexp
23423 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23424 p key val text options)
23425 (while (re-search-forward re nil t)
23426 (setq key (org-match-string-no-properties 1)
23427 val (org-match-string-no-properties 2))
23428 (cond
23429 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23430 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23431 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23432 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23433 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23434 ((string-equal key "TEXT")
23435 (setq text (if text (concat text "\n" val) val)))
23436 ((string-equal key "OPTIONS") (setq options val))))
23437 (setq p (plist-put p :text text))
23438 (when options
23439 (let ((op '(("H" . :headline-levels)
23440 ("num" . :section-numbers)
23441 ("toc" . :table-of-contents)
23442 ("\\n" . :preserve-breaks)
23443 ("@" . :expand-quoted-html)
23444 (":" . :fixed-width)
23445 ("|" . :tables)
23446 ("^" . :sub-superscript)
23447 ("-" . :special-strings)
23448 ("f" . :footnotes)
23449 ("d" . :drawers)
23450 ("tags" . :tags)
23451 ("*" . :emphasize)
23452 ("TeX" . :TeX-macros)
23453 ("LaTeX" . :LaTeX-fragments)
23454 ("skip" . :skip-before-1st-heading)
23455 ("author" . :author-info)
23456 ("timestamp" . :time-stamp-file)))
23458 (while (setq o (pop op))
23459 (if (string-match (concat (regexp-quote (car o))
23460 ":\\([^ \t\n\r;,.]*\\)")
23461 options)
23462 (setq p (plist-put p (cdr o)
23463 (car (read-from-string
23464 (match-string 1 options)))))))))
23465 p))))
23467 (defun org-export-directory (type plist)
23468 (let* ((val (plist-get plist :publishing-directory))
23469 (dir (if (listp val)
23470 (or (cdr (assoc type val)) ".")
23471 val)))
23472 dir))
23474 (defun org-skip-comments (lines)
23475 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23476 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23477 (re2 "^\\(\\*+\\)[ \t\n\r]")
23478 (case-fold-search nil)
23479 rtn line level)
23480 (while (setq line (pop lines))
23481 (cond
23482 ((and (string-match re1 line)
23483 (setq level (- (match-end 1) (match-beginning 1))))
23484 ;; Beginning of a COMMENT subtree. Skip it.
23485 (while (and (setq line (pop lines))
23486 (or (not (string-match re2 line))
23487 (> (- (match-end 1) (match-beginning 1)) level))))
23488 (setq lines (cons line lines)))
23489 ((string-match "^#" line)
23490 ;; an ordinary comment line
23492 ((and org-export-table-remove-special-lines
23493 (string-match "^[ \t]*|" line)
23494 (or (string-match "^[ \t]*| *[!_^] *|" line)
23495 (and (string-match "| *<[0-9]+> *|" line)
23496 (not (string-match "| *[^ <|]" line)))))
23497 ;; a special table line that should be removed
23499 (t (setq rtn (cons line rtn)))))
23500 (nreverse rtn)))
23502 (defun org-export (&optional arg)
23503 (interactive)
23504 (let ((help "[t] insert the export option template
23505 \[v] limit export to visible part of outline tree
23507 \[a] export as ASCII
23509 \[h] export as HTML
23510 \[H] export as HTML to temporary buffer
23511 \[R] export region as HTML
23512 \[b] export as HTML and browse immediately
23513 \[x] export as XOXO
23515 \[l] export as LaTeX
23516 \[L] export as LaTeX to temporary buffer
23518 \[i] export current file as iCalendar file
23519 \[I] export all agenda files as iCalendar files
23520 \[c] export agenda files into combined iCalendar file
23522 \[F] publish current file
23523 \[P] publish current project
23524 \[X] publish... (project will be prompted for)
23525 \[A] publish all projects")
23526 (cmds
23527 '((?t . org-insert-export-options-template)
23528 (?v . org-export-visible)
23529 (?a . org-export-as-ascii)
23530 (?h . org-export-as-html)
23531 (?b . org-export-as-html-and-open)
23532 (?H . org-export-as-html-to-buffer)
23533 (?R . org-export-region-as-html)
23534 (?x . org-export-as-xoxo)
23535 (?l . org-export-as-latex)
23536 (?L . org-export-as-latex-to-buffer)
23537 (?i . org-export-icalendar-this-file)
23538 (?I . org-export-icalendar-all-agenda-files)
23539 (?c . org-export-icalendar-combine-agenda-files)
23540 (?F . org-publish-current-file)
23541 (?P . org-publish-current-project)
23542 (?X . org-publish)
23543 (?A . org-publish-all)))
23544 r1 r2 ass)
23545 (save-window-excursion
23546 (delete-other-windows)
23547 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23548 (princ help))
23549 (message "Select command: ")
23550 (setq r1 (read-char-exclusive)))
23551 (setq r2 (if (< r1 27) (+ r1 96) r1))
23552 (if (setq ass (assq r2 cmds))
23553 (call-interactively (cdr ass))
23554 (error "No command associated with key %c" r1))))
23556 (defconst org-html-entities
23557 '(("nbsp")
23558 ("iexcl")
23559 ("cent")
23560 ("pound")
23561 ("curren")
23562 ("yen")
23563 ("brvbar")
23564 ("vert" . "&#124;")
23565 ("sect")
23566 ("uml")
23567 ("copy")
23568 ("ordf")
23569 ("laquo")
23570 ("not")
23571 ("shy")
23572 ("reg")
23573 ("macr")
23574 ("deg")
23575 ("plusmn")
23576 ("sup2")
23577 ("sup3")
23578 ("acute")
23579 ("micro")
23580 ("para")
23581 ("middot")
23582 ("odot"."o")
23583 ("star"."*")
23584 ("cedil")
23585 ("sup1")
23586 ("ordm")
23587 ("raquo")
23588 ("frac14")
23589 ("frac12")
23590 ("frac34")
23591 ("iquest")
23592 ("Agrave")
23593 ("Aacute")
23594 ("Acirc")
23595 ("Atilde")
23596 ("Auml")
23597 ("Aring") ("AA"."&Aring;")
23598 ("AElig")
23599 ("Ccedil")
23600 ("Egrave")
23601 ("Eacute")
23602 ("Ecirc")
23603 ("Euml")
23604 ("Igrave")
23605 ("Iacute")
23606 ("Icirc")
23607 ("Iuml")
23608 ("ETH")
23609 ("Ntilde")
23610 ("Ograve")
23611 ("Oacute")
23612 ("Ocirc")
23613 ("Otilde")
23614 ("Ouml")
23615 ("times")
23616 ("Oslash")
23617 ("Ugrave")
23618 ("Uacute")
23619 ("Ucirc")
23620 ("Uuml")
23621 ("Yacute")
23622 ("THORN")
23623 ("szlig")
23624 ("agrave")
23625 ("aacute")
23626 ("acirc")
23627 ("atilde")
23628 ("auml")
23629 ("aring")
23630 ("aelig")
23631 ("ccedil")
23632 ("egrave")
23633 ("eacute")
23634 ("ecirc")
23635 ("euml")
23636 ("igrave")
23637 ("iacute")
23638 ("icirc")
23639 ("iuml")
23640 ("eth")
23641 ("ntilde")
23642 ("ograve")
23643 ("oacute")
23644 ("ocirc")
23645 ("otilde")
23646 ("ouml")
23647 ("divide")
23648 ("oslash")
23649 ("ugrave")
23650 ("uacute")
23651 ("ucirc")
23652 ("uuml")
23653 ("yacute")
23654 ("thorn")
23655 ("yuml")
23656 ("fnof")
23657 ("Alpha")
23658 ("Beta")
23659 ("Gamma")
23660 ("Delta")
23661 ("Epsilon")
23662 ("Zeta")
23663 ("Eta")
23664 ("Theta")
23665 ("Iota")
23666 ("Kappa")
23667 ("Lambda")
23668 ("Mu")
23669 ("Nu")
23670 ("Xi")
23671 ("Omicron")
23672 ("Pi")
23673 ("Rho")
23674 ("Sigma")
23675 ("Tau")
23676 ("Upsilon")
23677 ("Phi")
23678 ("Chi")
23679 ("Psi")
23680 ("Omega")
23681 ("alpha")
23682 ("beta")
23683 ("gamma")
23684 ("delta")
23685 ("epsilon")
23686 ("varepsilon"."&epsilon;")
23687 ("zeta")
23688 ("eta")
23689 ("theta")
23690 ("iota")
23691 ("kappa")
23692 ("lambda")
23693 ("mu")
23694 ("nu")
23695 ("xi")
23696 ("omicron")
23697 ("pi")
23698 ("rho")
23699 ("sigmaf") ("varsigma"."&sigmaf;")
23700 ("sigma")
23701 ("tau")
23702 ("upsilon")
23703 ("phi")
23704 ("chi")
23705 ("psi")
23706 ("omega")
23707 ("thetasym") ("vartheta"."&thetasym;")
23708 ("upsih")
23709 ("piv")
23710 ("bull") ("bullet"."&bull;")
23711 ("hellip") ("dots"."&hellip;")
23712 ("prime")
23713 ("Prime")
23714 ("oline")
23715 ("frasl")
23716 ("weierp")
23717 ("image")
23718 ("real")
23719 ("trade")
23720 ("alefsym")
23721 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23722 ("uarr") ("uparrow"."&uarr;")
23723 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23724 ("darr")("downarrow"."&darr;")
23725 ("harr") ("leftrightarrow"."&harr;")
23726 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23727 ("lArr") ("Leftarrow"."&lArr;")
23728 ("uArr") ("Uparrow"."&uArr;")
23729 ("rArr") ("Rightarrow"."&rArr;")
23730 ("dArr") ("Downarrow"."&dArr;")
23731 ("hArr") ("Leftrightarrow"."&hArr;")
23732 ("forall")
23733 ("part") ("partial"."&part;")
23734 ("exist") ("exists"."&exist;")
23735 ("empty") ("emptyset"."&empty;")
23736 ("nabla")
23737 ("isin") ("in"."&isin;")
23738 ("notin")
23739 ("ni")
23740 ("prod")
23741 ("sum")
23742 ("minus")
23743 ("lowast") ("ast"."&lowast;")
23744 ("radic")
23745 ("prop") ("proptp"."&prop;")
23746 ("infin") ("infty"."&infin;")
23747 ("ang") ("angle"."&ang;")
23748 ("and") ("wedge"."&and;")
23749 ("or") ("vee"."&or;")
23750 ("cap")
23751 ("cup")
23752 ("int")
23753 ("there4")
23754 ("sim")
23755 ("cong") ("simeq"."&cong;")
23756 ("asymp")("approx"."&asymp;")
23757 ("ne") ("neq"."&ne;")
23758 ("equiv")
23759 ("le")
23760 ("ge")
23761 ("sub") ("subset"."&sub;")
23762 ("sup") ("supset"."&sup;")
23763 ("nsub")
23764 ("sube")
23765 ("supe")
23766 ("oplus")
23767 ("otimes")
23768 ("perp")
23769 ("sdot") ("cdot"."&sdot;")
23770 ("lceil")
23771 ("rceil")
23772 ("lfloor")
23773 ("rfloor")
23774 ("lang")
23775 ("rang")
23776 ("loz") ("Diamond"."&loz;")
23777 ("spades") ("spadesuit"."&spades;")
23778 ("clubs") ("clubsuit"."&clubs;")
23779 ("hearts") ("diamondsuit"."&hearts;")
23780 ("diams") ("diamondsuit"."&diams;")
23781 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23782 ("quot")
23783 ("amp")
23784 ("lt")
23785 ("gt")
23786 ("OElig")
23787 ("oelig")
23788 ("Scaron")
23789 ("scaron")
23790 ("Yuml")
23791 ("circ")
23792 ("tilde")
23793 ("ensp")
23794 ("emsp")
23795 ("thinsp")
23796 ("zwnj")
23797 ("zwj")
23798 ("lrm")
23799 ("rlm")
23800 ("ndash")
23801 ("mdash")
23802 ("lsquo")
23803 ("rsquo")
23804 ("sbquo")
23805 ("ldquo")
23806 ("rdquo")
23807 ("bdquo")
23808 ("dagger")
23809 ("Dagger")
23810 ("permil")
23811 ("lsaquo")
23812 ("rsaquo")
23813 ("euro")
23815 ("arccos"."arccos")
23816 ("arcsin"."arcsin")
23817 ("arctan"."arctan")
23818 ("arg"."arg")
23819 ("cos"."cos")
23820 ("cosh"."cosh")
23821 ("cot"."cot")
23822 ("coth"."coth")
23823 ("csc"."csc")
23824 ("deg"."deg")
23825 ("det"."det")
23826 ("dim"."dim")
23827 ("exp"."exp")
23828 ("gcd"."gcd")
23829 ("hom"."hom")
23830 ("inf"."inf")
23831 ("ker"."ker")
23832 ("lg"."lg")
23833 ("lim"."lim")
23834 ("liminf"."liminf")
23835 ("limsup"."limsup")
23836 ("ln"."ln")
23837 ("log"."log")
23838 ("max"."max")
23839 ("min"."min")
23840 ("Pr"."Pr")
23841 ("sec"."sec")
23842 ("sin"."sin")
23843 ("sinh"."sinh")
23844 ("sup"."sup")
23845 ("tan"."tan")
23846 ("tanh"."tanh")
23848 "Entities for TeX->HTML translation.
23849 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23850 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23851 In that case, \"\\ent\" will be translated to \"&other;\".
23852 The list contains HTML entities for Latin-1, Greek and other symbols.
23853 It is supplemented by a number of commonly used TeX macros with appropriate
23854 translations. There is currently no way for users to extend this.")
23856 ;;; General functions for all backends
23858 (defun org-cleaned-string-for-export (string &rest parameters)
23859 "Cleanup a buffer STRING so that links can be created safely."
23860 (interactive)
23861 (let* ((re-radio (and org-target-link-regexp
23862 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23863 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23864 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23865 (re-archive (concat ":" org-archive-tag ":"))
23866 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23867 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23868 (htmlp (plist-get parameters :for-html))
23869 (asciip (plist-get parameters :for-ascii))
23870 (latexp (plist-get parameters :for-LaTeX))
23871 (commentsp (plist-get parameters :comments))
23872 (archived-trees (plist-get parameters :archived-trees))
23873 (inhibit-read-only t)
23874 (drawers org-drawers)
23875 (exp-drawers (plist-get parameters :drawers))
23876 (outline-regexp "\\*+ ")
23877 a b xx
23878 rtn p)
23879 (with-current-buffer (get-buffer-create " org-mode-tmp")
23880 (erase-buffer)
23881 (insert string)
23882 ;; Remove license-to-kill stuff
23883 (while (setq p (text-property-any (point-min) (point-max)
23884 :org-license-to-kill t))
23885 (delete-region p (next-single-property-change p :org-license-to-kill)))
23887 (let ((org-inhibit-startup t)) (org-mode))
23888 (untabify (point-min) (point-max))
23890 ;; Get the correct stuff before the first headline
23891 (when (plist-get parameters :skip-before-1st-heading)
23892 (goto-char (point-min))
23893 (when (re-search-forward "^\\*+[ \t]" nil t)
23894 (delete-region (point-min) (match-beginning 0))
23895 (goto-char (point-min))
23896 (insert "\n")))
23897 (when (plist-get parameters :add-text)
23898 (goto-char (point-min))
23899 (insert (plist-get parameters :add-text) "\n"))
23901 ;; Get rid of archived trees
23902 (when (not (eq archived-trees t))
23903 (goto-char (point-min))
23904 (while (re-search-forward re-archive nil t)
23905 (if (not (org-on-heading-p t))
23906 (org-end-of-subtree t)
23907 (beginning-of-line 1)
23908 (setq a (if archived-trees
23909 (1+ (point-at-eol)) (point))
23910 b (org-end-of-subtree t))
23911 (if (> b a) (delete-region a b)))))
23913 ;; Get rid of drawers
23914 (unless (eq t exp-drawers)
23915 (goto-char (point-min))
23916 (let ((re (concat "^[ \t]*:\\("
23917 (mapconcat
23918 'identity
23919 (org-delete-all exp-drawers
23920 (copy-sequence drawers))
23921 "\\|")
23922 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23923 (while (re-search-forward re nil t)
23924 (replace-match ""))))
23926 ;; Find targets in comments and move them out of comments,
23927 ;; but mark them as targets that should be invisible
23928 (goto-char (point-min))
23929 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
23930 (replace-match "\\1(INVISIBLE)"))
23932 ;; Protect backend specific stuff, throw away the others.
23933 (let ((formatters
23934 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
23935 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
23936 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
23937 fmt)
23938 (goto-char (point-min))
23939 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
23940 (goto-char (match-end 0))
23941 (while (not (looking-at "#\\+END_EXAMPLE"))
23942 (insert ": ")
23943 (beginning-of-line 2)))
23944 (goto-char (point-min))
23945 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
23946 (add-text-properties (match-beginning 0) (match-end 0)
23947 '(org-protected t)))
23948 (while formatters
23949 (setq fmt (pop formatters))
23950 (when (car fmt)
23951 (goto-char (point-min))
23952 (while (re-search-forward (concat "^#\\+" (cadr fmt)
23953 ":[ \t]*\\(.*\\)") nil t)
23954 (replace-match "\\1" t)
23955 (add-text-properties
23956 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
23957 '(org-protected t))))
23958 (goto-char (point-min))
23959 (while (re-search-forward
23960 (concat "^#\\+"
23961 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
23962 (cadddr fmt) "\\>.*\n?") nil t)
23963 (if (car fmt)
23964 (add-text-properties (match-beginning 1) (1+ (match-end 1))
23965 '(org-protected t))
23966 (delete-region (match-beginning 0) (match-end 0))))))
23968 ;; Protect quoted subtrees
23969 (goto-char (point-min))
23970 (while (re-search-forward re-quote nil t)
23971 (goto-char (match-beginning 0))
23972 (end-of-line 1)
23973 (add-text-properties (point) (org-end-of-subtree t)
23974 '(org-protected t)))
23976 ;; Protect verbatim elements
23977 (goto-char (point-min))
23978 (while (re-search-forward org-verbatim-re nil t)
23979 (add-text-properties (match-beginning 4) (match-end 4)
23980 '(org-protected t))
23981 (goto-char (1+ (match-end 4))))
23983 ;; Remove subtrees that are commented
23984 (goto-char (point-min))
23985 (while (re-search-forward re-commented nil t)
23986 (goto-char (match-beginning 0))
23987 (delete-region (point) (org-end-of-subtree t)))
23989 ;; Remove special table lines
23990 (when org-export-table-remove-special-lines
23991 (goto-char (point-min))
23992 (while (re-search-forward "^[ \t]*|" nil t)
23993 (beginning-of-line 1)
23994 (if (or (looking-at "[ \t]*| *[!_^] *|")
23995 (and (looking-at ".*?| *<[0-9]+> *|")
23996 (not (looking-at ".*?| *[^ <|]"))))
23997 (delete-region (max (point-min) (1- (point-at-bol)))
23998 (point-at-eol))
23999 (end-of-line 1))))
24001 ;; Specific LaTeX stuff
24002 (when latexp
24003 (require 'org-export-latex nil)
24004 (org-export-latex-cleaned-string))
24006 (when asciip
24007 (org-export-ascii-clean-string))
24009 ;; Specific HTML stuff
24010 (when htmlp
24011 ;; Convert LaTeX fragments to images
24012 (when (plist-get parameters :LaTeX-fragments)
24013 (org-format-latex
24014 (concat "ltxpng/" (file-name-sans-extension
24015 (file-name-nondirectory
24016 org-current-export-file)))
24017 org-current-export-dir nil "Creating LaTeX image %s"))
24018 (message "Exporting..."))
24020 ;; Remove or replace comments
24021 (goto-char (point-min))
24022 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24023 (if commentsp
24024 (progn (add-text-properties
24025 (match-beginning 0) (match-end 0) '(org-protected t))
24026 (replace-match (format commentsp (match-string 1)) t t))
24027 (replace-match "")))
24029 ;; Find matches for radio targets and turn them into internal links
24030 (goto-char (point-min))
24031 (when re-radio
24032 (while (re-search-forward re-radio nil t)
24033 (org-if-unprotected
24034 (replace-match "\\1[[\\2]]"))))
24036 ;; Find all links that contain a newline and put them into a single line
24037 (goto-char (point-min))
24038 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24039 (org-if-unprotected
24040 (replace-match "\\1 \\3")
24041 (goto-char (match-beginning 0))))
24044 ;; Normalize links: Convert angle and plain links into bracket links
24045 ;; Expand link abbreviations
24046 (goto-char (point-min))
24047 (while (re-search-forward re-plain-link nil t)
24048 (goto-char (1- (match-end 0)))
24049 (org-if-unprotected
24050 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24051 ":" (match-string 3) "]]")))
24052 ;; added 'org-link face to links
24053 (put-text-property 0 (length s) 'face 'org-link s)
24054 (replace-match s t t))))
24055 (goto-char (point-min))
24056 (while (re-search-forward re-angle-link nil t)
24057 (goto-char (1- (match-end 0)))
24058 (org-if-unprotected
24059 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24060 ":" (match-string 3) "]]")))
24061 (put-text-property 0 (length s) 'face 'org-link s)
24062 (replace-match s t t))))
24063 (goto-char (point-min))
24064 (while (re-search-forward org-bracket-link-regexp nil t)
24065 (org-if-unprotected
24066 (let* ((s (concat "[[" (setq xx (save-match-data
24067 (org-link-expand-abbrev (match-string 1))))
24069 (if (match-end 3)
24070 (match-string 2)
24071 (concat "[" xx "]"))
24072 "]")))
24073 (put-text-property 0 (length s) 'face 'org-link s)
24074 (replace-match s t t))))
24076 ;; Find multiline emphasis and put them into single line
24077 (when (plist-get parameters :emph-multiline)
24078 (goto-char (point-min))
24079 (while (re-search-forward org-emph-re nil t)
24080 (if (not (= (char-after (match-beginning 3))
24081 (char-after (match-beginning 4))))
24082 (org-if-unprotected
24083 (subst-char-in-region (match-beginning 0) (match-end 0)
24084 ?\n ?\ t)
24085 (goto-char (1- (match-end 0))))
24086 (goto-char (1+ (match-beginning 0))))))
24088 (setq rtn (buffer-string)))
24089 (kill-buffer " org-mode-tmp")
24090 rtn))
24092 (defun org-export-grab-title-from-buffer ()
24093 "Get a title for the current document, from looking at the buffer."
24094 (let ((inhibit-read-only t))
24095 (save-excursion
24096 (goto-char (point-min))
24097 (let ((end (save-excursion (outline-next-heading) (point))))
24098 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24099 ;; Mark the line so that it will not be exported as normal text.
24100 (org-unmodified
24101 (add-text-properties (match-beginning 0) (match-end 0)
24102 (list :org-license-to-kill t)))
24103 ;; Return the title string
24104 (org-trim (match-string 0)))))))
24106 (defun org-export-get-title-from-subtree ()
24107 "Return subtree title and exclude it from export."
24108 (let (title (m (mark)))
24109 (save-excursion
24110 (goto-char (region-beginning))
24111 (when (and (org-at-heading-p)
24112 (>= (org-end-of-subtree t t) (region-end)))
24113 ;; This is a subtree, we take the title from the first heading
24114 (goto-char (region-beginning))
24115 (looking-at org-todo-line-regexp)
24116 (setq title (match-string 3))
24117 (org-unmodified
24118 (add-text-properties (point) (1+ (point-at-eol))
24119 (list :org-license-to-kill t)))))
24120 title))
24122 (defun org-solidify-link-text (s &optional alist)
24123 "Take link text and make a safe target out of it."
24124 (save-match-data
24125 (let* ((rtn
24126 (mapconcat
24127 'identity
24128 (org-split-string s "[ \t\r\n]+") "--"))
24129 (a (assoc rtn alist)))
24130 (or (cdr a) rtn))))
24132 (defun org-get-min-level (lines)
24133 "Get the minimum level in LINES."
24134 (let ((re "^\\(\\*+\\) ") l min)
24135 (catch 'exit
24136 (while (setq l (pop lines))
24137 (if (string-match re l)
24138 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24139 1)))
24141 ;; Variable holding the vector with section numbers
24142 (defvar org-section-numbers (make-vector org-level-max 0))
24144 (defun org-init-section-numbers ()
24145 "Initialize the vector for the section numbers."
24146 (let* ((level -1)
24147 (numbers (nreverse (org-split-string "" "\\.")))
24148 (depth (1- (length org-section-numbers)))
24149 (i depth) number-string)
24150 (while (>= i 0)
24151 (if (> i level)
24152 (aset org-section-numbers i 0)
24153 (setq number-string (or (car numbers) "0"))
24154 (if (string-match "\\`[A-Z]\\'" number-string)
24155 (aset org-section-numbers i
24156 (- (string-to-char number-string) ?A -1))
24157 (aset org-section-numbers i (string-to-number number-string)))
24158 (pop numbers))
24159 (setq i (1- i)))))
24161 (defun org-section-number (&optional level)
24162 "Return a string with the current section number.
24163 When LEVEL is non-nil, increase section numbers on that level."
24164 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24165 (when level
24166 (when (> level -1)
24167 (aset org-section-numbers
24168 level (1+ (aref org-section-numbers level))))
24169 (setq idx (1+ level))
24170 (while (<= idx depth)
24171 (if (not (= idx 1))
24172 (aset org-section-numbers idx 0))
24173 (setq idx (1+ idx))))
24174 (setq idx 0)
24175 (while (<= idx depth)
24176 (setq n (aref org-section-numbers idx))
24177 (setq string (concat string (if (not (string= string "")) "." "")
24178 (int-to-string n)))
24179 (setq idx (1+ idx)))
24180 (save-match-data
24181 (if (string-match "\\`\\([@0]\\.\\)+" string)
24182 (setq string (replace-match "" t nil string)))
24183 (if (string-match "\\(\\.0\\)+\\'" string)
24184 (setq string (replace-match "" t nil string))))
24185 string))
24187 ;;; ASCII export
24189 (defvar org-last-level nil) ; dynamically scoped variable
24190 (defvar org-min-level nil) ; dynamically scoped variable
24191 (defvar org-levels-open nil) ; dynamically scoped parameter
24192 (defvar org-ascii-current-indentation nil) ; For communication
24194 (defun org-export-as-ascii (arg)
24195 "Export the outline as a pretty ASCII file.
24196 If there is an active region, export only the region.
24197 The prefix ARG specifies how many levels of the outline should become
24198 underlined headlines. The default is 3."
24199 (interactive "P")
24200 (setq-default org-todo-line-regexp org-todo-line-regexp)
24201 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24202 (org-infile-export-plist)))
24203 (region-p (org-region-active-p))
24204 (subtree-p
24205 (when region-p
24206 (save-excursion
24207 (goto-char (region-beginning))
24208 (and (org-at-heading-p)
24209 (>= (org-end-of-subtree t t) (region-end))))))
24210 (custom-times org-display-custom-times)
24211 (org-ascii-current-indentation '(0 . 0))
24212 (level 0) line txt
24213 (umax nil)
24214 (umax-toc nil)
24215 (case-fold-search nil)
24216 (filename (concat (file-name-as-directory
24217 (org-export-directory :ascii opt-plist))
24218 (file-name-sans-extension
24219 (or (and subtree-p
24220 (org-entry-get (region-beginning)
24221 "EXPORT_FILE_NAME" t))
24222 (file-name-nondirectory buffer-file-name)))
24223 ".txt"))
24224 (filename (if (equal (file-truename filename)
24225 (file-truename buffer-file-name))
24226 (concat filename ".txt")
24227 filename))
24228 (buffer (find-file-noselect filename))
24229 (org-levels-open (make-vector org-level-max nil))
24230 (odd org-odd-levels-only)
24231 (date (plist-get opt-plist :date))
24232 (author (plist-get opt-plist :author))
24233 (title (or (and subtree-p (org-export-get-title-from-subtree))
24234 (plist-get opt-plist :title)
24235 (and (not
24236 (plist-get opt-plist :skip-before-1st-heading))
24237 (org-export-grab-title-from-buffer))
24238 (file-name-sans-extension
24239 (file-name-nondirectory buffer-file-name))))
24240 (email (plist-get opt-plist :email))
24241 (language (plist-get opt-plist :language))
24242 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24243 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24244 (todo nil)
24245 (lang-words nil)
24246 (region
24247 (buffer-substring
24248 (if (org-region-active-p) (region-beginning) (point-min))
24249 (if (org-region-active-p) (region-end) (point-max))))
24250 (lines (org-split-string
24251 (org-cleaned-string-for-export
24252 region
24253 :for-ascii t
24254 :skip-before-1st-heading
24255 (plist-get opt-plist :skip-before-1st-heading)
24256 :drawers (plist-get opt-plist :drawers)
24257 :verbatim-multiline t
24258 :archived-trees
24259 (plist-get opt-plist :archived-trees)
24260 :add-text (plist-get opt-plist :text))
24261 "\n"))
24262 thetoc have-headings first-heading-pos
24263 table-open table-buffer)
24265 (let ((inhibit-read-only t))
24266 (org-unmodified
24267 (remove-text-properties (point-min) (point-max)
24268 '(:org-license-to-kill t))))
24270 (setq org-min-level (org-get-min-level lines))
24271 (setq org-last-level org-min-level)
24272 (org-init-section-numbers)
24274 (find-file-noselect filename)
24276 (setq lang-words (or (assoc language org-export-language-setup)
24277 (assoc "en" org-export-language-setup)))
24278 (switch-to-buffer-other-window buffer)
24279 (erase-buffer)
24280 (fundamental-mode)
24281 ;; create local variables for all options, to make sure all called
24282 ;; functions get the correct information
24283 (mapc (lambda (x)
24284 (set (make-local-variable (cdr x))
24285 (plist-get opt-plist (car x))))
24286 org-export-plist-vars)
24287 (org-set-local 'org-odd-levels-only odd)
24288 (setq umax (if arg (prefix-numeric-value arg)
24289 org-export-headline-levels))
24290 (setq umax-toc (if (integerp org-export-with-toc)
24291 (min org-export-with-toc umax)
24292 umax))
24294 ;; File header
24295 (if title (org-insert-centered title ?=))
24296 (insert "\n")
24297 (if (and (or author email)
24298 org-export-author-info)
24299 (insert (concat (nth 1 lang-words) ": " (or author "")
24300 (if email (concat " <" email ">") "")
24301 "\n")))
24303 (cond
24304 ((and date (string-match "%" date))
24305 (setq date (format-time-string date (current-time))))
24306 (date)
24307 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24309 (if (and date org-export-time-stamp-file)
24310 (insert (concat (nth 2 lang-words) ": " date"\n")))
24312 (insert "\n\n")
24314 (if org-export-with-toc
24315 (progn
24316 (push (concat (nth 3 lang-words) "\n") thetoc)
24317 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24318 (mapc '(lambda (line)
24319 (if (string-match org-todo-line-regexp
24320 line)
24321 ;; This is a headline
24322 (progn
24323 (setq have-headings t)
24324 (setq level (- (match-end 1) (match-beginning 1))
24325 level (org-tr-level level)
24326 txt (match-string 3 line)
24327 todo
24328 (or (and org-export-mark-todo-in-toc
24329 (match-beginning 2)
24330 (not (member (match-string 2 line)
24331 org-done-keywords)))
24332 ; TODO, not DONE
24333 (and org-export-mark-todo-in-toc
24334 (= level umax-toc)
24335 (org-search-todo-below
24336 line lines level))))
24337 (setq txt (org-html-expand-for-ascii txt))
24339 (while (string-match org-bracket-link-regexp txt)
24340 (setq txt
24341 (replace-match
24342 (match-string (if (match-end 2) 3 1) txt)
24343 t t txt)))
24345 (if (and (memq org-export-with-tags '(not-in-toc nil))
24346 (string-match
24347 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24348 txt))
24349 (setq txt (replace-match "" t t txt)))
24350 (if (string-match quote-re0 txt)
24351 (setq txt (replace-match "" t t txt)))
24353 (if org-export-with-section-numbers
24354 (setq txt (concat (org-section-number level)
24355 " " txt)))
24356 (if (<= level umax-toc)
24357 (progn
24358 (push
24359 (concat
24360 (make-string
24361 (* (max 0 (- level org-min-level)) 4) ?\ )
24362 (format (if todo "%s (*)\n" "%s\n") txt))
24363 thetoc)
24364 (setq org-last-level level))
24365 ))))
24366 lines)
24367 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24369 (org-init-section-numbers)
24370 (while (setq line (pop lines))
24371 ;; Remove the quoted HTML tags.
24372 (setq line (org-html-expand-for-ascii line))
24373 ;; Remove targets
24374 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24375 (setq line (replace-match "" t t line)))
24376 ;; Replace internal links
24377 (while (string-match org-bracket-link-regexp line)
24378 (setq line (replace-match
24379 (if (match-end 3) "[\\3]" "[\\1]")
24380 t nil line)))
24381 (when custom-times
24382 (setq line (org-translate-time line)))
24383 (cond
24384 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24385 ;; a Headline
24386 (setq first-heading-pos (or first-heading-pos (point)))
24387 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24388 txt (match-string 2 line))
24389 (org-ascii-level-start level txt umax lines))
24391 ((and org-export-with-tables
24392 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24393 (if (not table-open)
24394 ;; New table starts
24395 (setq table-open t table-buffer nil))
24396 ;; Accumulate lines
24397 (setq table-buffer (cons line table-buffer))
24398 (when (or (not lines)
24399 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24400 (car lines))))
24401 (setq table-open nil
24402 table-buffer (nreverse table-buffer))
24403 (insert (mapconcat
24404 (lambda (x)
24405 (org-fix-indentation x org-ascii-current-indentation))
24406 (org-format-table-ascii table-buffer)
24407 "\n") "\n")))
24409 (setq line (org-fix-indentation line org-ascii-current-indentation))
24410 (if (and org-export-with-fixed-width
24411 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24412 (setq line (replace-match "\\1" nil nil line)))
24413 (insert line "\n"))))
24415 (normal-mode)
24417 ;; insert the table of contents
24418 (when thetoc
24419 (goto-char (point-min))
24420 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24421 (progn
24422 (goto-char (match-beginning 0))
24423 (replace-match ""))
24424 (goto-char first-heading-pos))
24425 (mapc 'insert thetoc)
24426 (or (looking-at "[ \t]*\n[ \t]*\n")
24427 (insert "\n\n")))
24429 ;; Convert whitespace place holders
24430 (goto-char (point-min))
24431 (let (beg end)
24432 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24433 (setq end (next-single-property-change beg 'org-whitespace))
24434 (goto-char beg)
24435 (delete-region beg end)
24436 (insert (make-string (- end beg) ?\ ))))
24438 (save-buffer)
24439 ;; remove display and invisible chars
24440 (let (beg end)
24441 (goto-char (point-min))
24442 (while (setq beg (next-single-property-change (point) 'display))
24443 (setq end (next-single-property-change beg 'display))
24444 (delete-region beg end)
24445 (goto-char beg)
24446 (insert "=>"))
24447 (goto-char (point-min))
24448 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24449 (setq end (next-single-property-change beg 'org-cwidth))
24450 (delete-region beg end)
24451 (goto-char beg)))
24452 (goto-char (point-min))))
24454 (defun org-export-ascii-clean-string ()
24455 "Do extra work for ASCII export"
24456 (goto-char (point-min))
24457 (while (re-search-forward org-verbatim-re nil t)
24458 (goto-char (match-end 2))
24459 (backward-delete-char 1) (insert "'")
24460 (goto-char (match-beginning 2))
24461 (delete-char 1) (insert "`")
24462 (goto-char (match-end 2))))
24464 (defun org-search-todo-below (line lines level)
24465 "Search the subtree below LINE for any TODO entries."
24466 (let ((rest (cdr (memq line lines)))
24467 (re org-todo-line-regexp)
24468 line lv todo)
24469 (catch 'exit
24470 (while (setq line (pop rest))
24471 (if (string-match re line)
24472 (progn
24473 (setq lv (- (match-end 1) (match-beginning 1))
24474 todo (and (match-beginning 2)
24475 (not (member (match-string 2 line)
24476 org-done-keywords))))
24477 ; TODO, not DONE
24478 (if (<= lv level) (throw 'exit nil))
24479 (if todo (throw 'exit t))))))))
24481 (defun org-html-expand-for-ascii (line)
24482 "Handle quoted HTML for ASCII export."
24483 (if org-export-html-expand
24484 (while (string-match "@<[^<>\n]*>" line)
24485 ;; We just remove the tags for now.
24486 (setq line (replace-match "" nil nil line))))
24487 line)
24489 (defun org-insert-centered (s &optional underline)
24490 "Insert the string S centered and underline it with character UNDERLINE."
24491 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24492 (insert (make-string ind ?\ ) s "\n")
24493 (if underline
24494 (insert (make-string ind ?\ )
24495 (make-string (string-width s) underline)
24496 "\n"))))
24498 (defun org-ascii-level-start (level title umax &optional lines)
24499 "Insert a new level in ASCII export."
24500 (let (char (n (- level umax 1)) (ind 0))
24501 (if (> level umax)
24502 (progn
24503 (insert (make-string (* 2 n) ?\ )
24504 (char-to-string (nth (% n (length org-export-ascii-bullets))
24505 org-export-ascii-bullets))
24506 " " title "\n")
24507 ;; find the indentation of the next non-empty line
24508 (catch 'stop
24509 (while lines
24510 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24511 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24512 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24513 (pop lines)))
24514 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24515 (if (or (not (equal (char-before) ?\n))
24516 (not (equal (char-before (1- (point))) ?\n)))
24517 (insert "\n"))
24518 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24519 (unless org-export-with-tags
24520 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24521 (setq title (replace-match "" t t title))))
24522 (if org-export-with-section-numbers
24523 (setq title (concat (org-section-number level) " " title)))
24524 (insert title "\n" (make-string (string-width title) char) "\n")
24525 (setq org-ascii-current-indentation '(0 . 0)))))
24527 (defun org-export-visible (type arg)
24528 "Create a copy of the visible part of the current buffer, and export it.
24529 The copy is created in a temporary buffer and removed after use.
24530 TYPE is the final key (as a string) that also select the export command in
24531 the `C-c C-e' export dispatcher.
24532 As a special case, if the you type SPC at the prompt, the temporary
24533 org-mode file will not be removed but presented to you so that you can
24534 continue to use it. The prefix arg ARG is passed through to the exporting
24535 command."
24536 (interactive
24537 (list (progn
24538 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24539 (read-char-exclusive))
24540 current-prefix-arg))
24541 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24542 (error "Invalid export key"))
24543 (let* ((binding (cdr (assoc type
24544 '((?a . org-export-as-ascii)
24545 (?\C-a . org-export-as-ascii)
24546 (?b . org-export-as-html-and-open)
24547 (?\C-b . org-export-as-html-and-open)
24548 (?h . org-export-as-html)
24549 (?H . org-export-as-html-to-buffer)
24550 (?R . org-export-region-as-html)
24551 (?x . org-export-as-xoxo)))))
24552 (keepp (equal type ?\ ))
24553 (file buffer-file-name)
24554 (buffer (get-buffer-create "*Org Export Visible*"))
24555 s e)
24556 ;; Need to hack the drawers here.
24557 (save-excursion
24558 (goto-char (point-min))
24559 (while (re-search-forward org-drawer-regexp nil t)
24560 (goto-char (match-beginning 1))
24561 (or (org-invisible-p) (org-flag-drawer nil))))
24562 (with-current-buffer buffer (erase-buffer))
24563 (save-excursion
24564 (setq s (goto-char (point-min)))
24565 (while (not (= (point) (point-max)))
24566 (goto-char (org-find-invisible))
24567 (append-to-buffer buffer s (point))
24568 (setq s (goto-char (org-find-visible))))
24569 (org-cycle-hide-drawers 'all)
24570 (goto-char (point-min))
24571 (unless keepp
24572 ;; Copy all comment lines to the end, to make sure #+ settings are
24573 ;; still available for the second export step. Kind of a hack, but
24574 ;; does do the trick.
24575 (if (looking-at "#[^\r\n]*")
24576 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24577 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24578 (append-to-buffer buffer (1+ (match-beginning 0))
24579 (min (point-max) (1+ (match-end 0))))))
24580 (set-buffer buffer)
24581 (let ((buffer-file-name file)
24582 (org-inhibit-startup t))
24583 (org-mode)
24584 (show-all)
24585 (unless keepp (funcall binding arg))))
24586 (if (not keepp)
24587 (kill-buffer buffer)
24588 (switch-to-buffer-other-window buffer)
24589 (goto-char (point-min)))))
24591 (defun org-find-visible ()
24592 (let ((s (point)))
24593 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24594 (get-char-property s 'invisible)))
24596 (defun org-find-invisible ()
24597 (let ((s (point)))
24598 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24599 (not (get-char-property s 'invisible))))
24602 ;;; HTML export
24604 (defun org-get-current-options ()
24605 "Return a string with current options as keyword options.
24606 Does include HTML export options as well as TODO and CATEGORY stuff."
24607 (format
24608 "#+TITLE: %s
24609 #+AUTHOR: %s
24610 #+EMAIL: %s
24611 #+LANGUAGE: %s
24612 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24613 #+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
24614 #+CATEGORY: %s
24615 #+SEQ_TODO: %s
24616 #+TYP_TODO: %s
24617 #+PRIORITIES: %c %c %c
24618 #+DRAWERS: %s
24619 #+STARTUP: %s %s %s %s %s
24620 #+TAGS: %s
24621 #+ARCHIVE: %s
24622 #+LINK: %s
24624 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24625 org-export-headline-levels
24626 org-export-with-section-numbers
24627 org-export-with-toc
24628 org-export-preserve-breaks
24629 org-export-html-expand
24630 org-export-with-fixed-width
24631 org-export-with-tables
24632 org-export-with-sub-superscripts
24633 org-export-with-special-strings
24634 org-export-with-footnotes
24635 org-export-with-emphasize
24636 org-export-with-TeX-macros
24637 org-export-with-LaTeX-fragments
24638 org-export-skip-text-before-1st-heading
24639 org-export-with-drawers
24640 org-export-with-tags
24641 (file-name-nondirectory buffer-file-name)
24642 "TODO FEEDBACK VERIFY DONE"
24643 "Me Jason Marie DONE"
24644 org-highest-priority org-lowest-priority org-default-priority
24645 (mapconcat 'identity org-drawers " ")
24646 (cdr (assoc org-startup-folded
24647 '((nil . "showall") (t . "overview") (content . "content"))))
24648 (if org-odd-levels-only "odd" "oddeven")
24649 (if org-hide-leading-stars "hidestars" "showstars")
24650 (if org-startup-align-all-tables "align" "noalign")
24651 (cond ((eq t org-log-done) "logdone")
24652 ((not org-log-done) "nologging")
24653 ((listp org-log-done)
24654 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
24655 org-log-done " ")))
24656 (or (mapconcat (lambda (x)
24657 (cond
24658 ((equal '(:startgroup) x) "{")
24659 ((equal '(:endgroup) x) "}")
24660 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24661 (t (car x))))
24662 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24663 org-archive-location
24664 "org file:~/org/%s.org"
24667 (defun org-insert-export-options-template ()
24668 "Insert into the buffer a template with information for exporting."
24669 (interactive)
24670 (if (not (bolp)) (newline))
24671 (let ((s (org-get-current-options)))
24672 (and (string-match "#\\+CATEGORY" s)
24673 (setq s (substring s 0 (match-beginning 0))))
24674 (insert s)))
24676 (defun org-toggle-fixed-width-section (arg)
24677 "Toggle the fixed-width export.
24678 If there is no active region, the QUOTE keyword at the current headline is
24679 inserted or removed. When present, it causes the text between this headline
24680 and the next to be exported as fixed-width text, and unmodified.
24681 If there is an active region, this command adds or removes a colon as the
24682 first character of this line. If the first character of a line is a colon,
24683 this line is also exported in fixed-width font."
24684 (interactive "P")
24685 (let* ((cc 0)
24686 (regionp (org-region-active-p))
24687 (beg (if regionp (region-beginning) (point)))
24688 (end (if regionp (region-end)))
24689 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24690 (case-fold-search nil)
24691 (re "[ \t]*\\(:\\)")
24692 off)
24693 (if regionp
24694 (save-excursion
24695 (goto-char beg)
24696 (setq cc (current-column))
24697 (beginning-of-line 1)
24698 (setq off (looking-at re))
24699 (while (> nlines 0)
24700 (setq nlines (1- nlines))
24701 (beginning-of-line 1)
24702 (cond
24703 (arg
24704 (move-to-column cc t)
24705 (insert ":\n")
24706 (forward-line -1))
24707 ((and off (looking-at re))
24708 (replace-match "" t t nil 1))
24709 ((not off) (move-to-column cc t) (insert ":")))
24710 (forward-line 1)))
24711 (save-excursion
24712 (org-back-to-heading)
24713 (if (looking-at (concat outline-regexp
24714 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24715 (replace-match "" t t nil 1)
24716 (if (looking-at outline-regexp)
24717 (progn
24718 (goto-char (match-end 0))
24719 (insert org-quote-string " "))))))))
24721 (defun org-export-as-html-and-open (arg)
24722 "Export the outline as HTML and immediately open it with a browser.
24723 If there is an active region, export only the region.
24724 The prefix ARG specifies how many levels of the outline should become
24725 headlines. The default is 3. Lower levels will become bulleted lists."
24726 (interactive "P")
24727 (org-export-as-html arg 'hidden)
24728 (org-open-file buffer-file-name))
24730 (defun org-export-as-html-batch ()
24731 "Call `org-export-as-html', may be used in batch processing as
24732 emacs --batch
24733 --load=$HOME/lib/emacs/org.el
24734 --eval \"(setq org-export-headline-levels 2)\"
24735 --visit=MyFile --funcall org-export-as-html-batch"
24736 (org-export-as-html org-export-headline-levels 'hidden))
24738 (defun org-export-as-html-to-buffer (arg)
24739 "Call `org-exort-as-html` with output to a temporary buffer.
24740 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24741 (interactive "P")
24742 (org-export-as-html arg nil nil "*Org HTML Export*")
24743 (switch-to-buffer-other-window "*Org HTML Export*"))
24745 (defun org-replace-region-by-html (beg end)
24746 "Assume the current region has org-mode syntax, and convert it to HTML.
24747 This can be used in any buffer. For example, you could write an
24748 itemized list in org-mode syntax in an HTML buffer and then use this
24749 command to convert it."
24750 (interactive "r")
24751 (let (reg html buf pop-up-frames)
24752 (save-window-excursion
24753 (if (org-mode-p)
24754 (setq html (org-export-region-as-html
24755 beg end t 'string))
24756 (setq reg (buffer-substring beg end)
24757 buf (get-buffer-create "*Org tmp*"))
24758 (with-current-buffer buf
24759 (erase-buffer)
24760 (insert reg)
24761 (org-mode)
24762 (setq html (org-export-region-as-html
24763 (point-min) (point-max) t 'string)))
24764 (kill-buffer buf)))
24765 (delete-region beg end)
24766 (insert html)))
24768 (defun org-export-region-as-html (beg end &optional body-only buffer)
24769 "Convert region from BEG to END in org-mode buffer to HTML.
24770 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24771 contents, and only produce the region of converted text, useful for
24772 cut-and-paste operations.
24773 If BUFFER is a buffer or a string, use/create that buffer as a target
24774 of the converted HTML. If BUFFER is the symbol `string', return the
24775 produced HTML as a string and leave not buffer behind. For example,
24776 a Lisp program could call this function in the following way:
24778 (setq html (org-export-region-as-html beg end t 'string))
24780 When called interactively, the output buffer is selected, and shown
24781 in a window. A non-interactive call will only retunr the buffer."
24782 (interactive "r\nP")
24783 (when (interactive-p)
24784 (setq buffer "*Org HTML Export*"))
24785 (let ((transient-mark-mode t) (zmacs-regions t)
24786 rtn)
24787 (goto-char end)
24788 (set-mark (point)) ;; to activate the region
24789 (goto-char beg)
24790 (setq rtn (org-export-as-html
24791 nil nil nil
24792 buffer body-only))
24793 (if (fboundp 'deactivate-mark) (deactivate-mark))
24794 (if (and (interactive-p) (bufferp rtn))
24795 (switch-to-buffer-other-window rtn)
24796 rtn)))
24798 (defvar html-table-tag nil) ; dynamically scoped into this.
24799 (defun org-export-as-html (arg &optional hidden ext-plist
24800 to-buffer body-only)
24801 "Export the outline as a pretty HTML file.
24802 If there is an active region, export only the region. The prefix
24803 ARG specifies how many levels of the outline should become
24804 headlines. The default is 3. Lower levels will become bulleted
24805 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24806 EXT-PLIST is a property list with external parameters overriding
24807 org-mode's default settings, but still inferior to file-local
24808 settings. When TO-BUFFER is non-nil, create a buffer with that
24809 name and export to that buffer. If TO-BUFFER is the symbol `string',
24810 don't leave any buffer behind but just return the resulting HTML as
24811 a string. When BODY-ONLY is set, don't produce the file header and footer,
24812 simply return the content of <body>...</body>, without even
24813 the body tags themselves."
24814 (interactive "P")
24816 ;; Make sure we have a file name when we need it.
24817 (when (and (not (or to-buffer body-only))
24818 (not buffer-file-name))
24819 (if (buffer-base-buffer)
24820 (org-set-local 'buffer-file-name
24821 (with-current-buffer (buffer-base-buffer)
24822 buffer-file-name))
24823 (error "Need a file name to be able to export.")))
24825 (message "Exporting...")
24826 (setq-default org-todo-line-regexp org-todo-line-regexp)
24827 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24828 (setq-default org-done-keywords org-done-keywords)
24829 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24830 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24831 ext-plist
24832 (org-infile-export-plist)))
24834 (style (plist-get opt-plist :style))
24835 (link-validate (plist-get opt-plist :link-validation-function))
24836 valid thetoc have-headings first-heading-pos
24837 (odd org-odd-levels-only)
24838 (region-p (org-region-active-p))
24839 (subtree-p
24840 (when region-p
24841 (save-excursion
24842 (goto-char (region-beginning))
24843 (and (org-at-heading-p)
24844 (>= (org-end-of-subtree t t) (region-end))))))
24845 ;; The following two are dynamically scoped into other
24846 ;; routines below.
24847 (org-current-export-dir (org-export-directory :html opt-plist))
24848 (org-current-export-file buffer-file-name)
24849 (level 0) (line "") (origline "") txt todo
24850 (umax nil)
24851 (umax-toc nil)
24852 (filename (if to-buffer nil
24853 (expand-file-name
24854 (concat
24855 (file-name-sans-extension
24856 (or (and subtree-p
24857 (org-entry-get (region-beginning)
24858 "EXPORT_FILE_NAME" t))
24859 (file-name-nondirectory buffer-file-name)))
24860 "." org-export-html-extension)
24861 (file-name-as-directory
24862 (org-export-directory :html opt-plist)))))
24863 (current-dir (if buffer-file-name
24864 (file-name-directory buffer-file-name)
24865 default-directory))
24866 (buffer (if to-buffer
24867 (cond
24868 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24869 (t (get-buffer-create to-buffer)))
24870 (find-file-noselect filename)))
24871 (org-levels-open (make-vector org-level-max nil))
24872 (date (plist-get opt-plist :date))
24873 (author (plist-get opt-plist :author))
24874 (title (or (and subtree-p (org-export-get-title-from-subtree))
24875 (plist-get opt-plist :title)
24876 (and (not
24877 (plist-get opt-plist :skip-before-1st-heading))
24878 (org-export-grab-title-from-buffer))
24879 (and buffer-file-name
24880 (file-name-sans-extension
24881 (file-name-nondirectory buffer-file-name)))
24882 "UNTITLED"))
24883 (html-table-tag (plist-get opt-plist :html-table-tag))
24884 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24885 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24886 (inquote nil)
24887 (infixed nil)
24888 (in-local-list nil)
24889 (local-list-num nil)
24890 (local-list-indent nil)
24891 (llt org-plain-list-ordered-item-terminator)
24892 (email (plist-get opt-plist :email))
24893 (language (plist-get opt-plist :language))
24894 (lang-words nil)
24895 (target-alist nil) tg
24896 (head-count 0) cnt
24897 (start 0)
24898 (coding-system (and (boundp 'buffer-file-coding-system)
24899 buffer-file-coding-system))
24900 (coding-system-for-write (or org-export-html-coding-system
24901 coding-system))
24902 (save-buffer-coding-system (or org-export-html-coding-system
24903 coding-system))
24904 (charset (and coding-system-for-write
24905 (fboundp 'coding-system-get)
24906 (coding-system-get coding-system-for-write
24907 'mime-charset)))
24908 (region
24909 (buffer-substring
24910 (if region-p (region-beginning) (point-min))
24911 (if region-p (region-end) (point-max))))
24912 (lines
24913 (org-split-string
24914 (org-cleaned-string-for-export
24915 region
24916 :emph-multiline t
24917 :for-html t
24918 :skip-before-1st-heading
24919 (plist-get opt-plist :skip-before-1st-heading)
24920 :drawers (plist-get opt-plist :drawers)
24921 :archived-trees
24922 (plist-get opt-plist :archived-trees)
24923 :add-text
24924 (plist-get opt-plist :text)
24925 :LaTeX-fragments
24926 (plist-get opt-plist :LaTeX-fragments))
24927 "[\r\n]"))
24928 table-open type
24929 table-buffer table-orig-buffer
24930 ind start-is-num starter didclose
24931 rpl path desc descp desc1 desc2 link
24934 (let ((inhibit-read-only t))
24935 (org-unmodified
24936 (remove-text-properties (point-min) (point-max)
24937 '(:org-license-to-kill t))))
24939 (message "Exporting...")
24941 (setq org-min-level (org-get-min-level lines))
24942 (setq org-last-level org-min-level)
24943 (org-init-section-numbers)
24945 (cond
24946 ((and date (string-match "%" date))
24947 (setq date (format-time-string date (current-time))))
24948 (date)
24949 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24951 ;; Get the language-dependent settings
24952 (setq lang-words (or (assoc language org-export-language-setup)
24953 (assoc "en" org-export-language-setup)))
24955 ;; Switch to the output buffer
24956 (set-buffer buffer)
24957 (let ((inhibit-read-only t)) (erase-buffer))
24958 (fundamental-mode)
24960 (and (fboundp 'set-buffer-file-coding-system)
24961 (set-buffer-file-coding-system coding-system-for-write))
24963 (let ((case-fold-search nil)
24964 (org-odd-levels-only odd))
24965 ;; create local variables for all options, to make sure all called
24966 ;; functions get the correct information
24967 (mapc (lambda (x)
24968 (set (make-local-variable (cdr x))
24969 (plist-get opt-plist (car x))))
24970 org-export-plist-vars)
24971 (setq umax (if arg (prefix-numeric-value arg)
24972 org-export-headline-levels))
24973 (setq umax-toc (if (integerp org-export-with-toc)
24974 (min org-export-with-toc umax)
24975 umax))
24976 (unless body-only
24977 ;; File header
24978 (insert (format
24979 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
24980 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
24981 <html xmlns=\"http://www.w3.org/1999/xhtml\"
24982 lang=\"%s\" xml:lang=\"%s\">
24983 <head>
24984 <title>%s</title>
24985 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
24986 <meta name=\"generator\" content=\"Org-mode\"/>
24987 <meta name=\"generated\" content=\"%s\"/>
24988 <meta name=\"author\" content=\"%s\"/>
24990 </head><body>
24992 language language (org-html-expand title)
24993 (or charset "iso-8859-1") date author style))
24995 (insert (or (plist-get opt-plist :preamble) ""))
24997 (when (plist-get opt-plist :auto-preamble)
24998 (if title (insert (format org-export-html-title-format
24999 (org-html-expand title))))))
25001 (if (and org-export-with-toc (not body-only))
25002 (progn
25003 (push (format "<h%d>%s</h%d>\n"
25004 org-export-html-toplevel-hlevel
25005 (nth 3 lang-words)
25006 org-export-html-toplevel-hlevel)
25007 thetoc)
25008 (push "<ul>\n<li>" thetoc)
25009 (setq lines
25010 (mapcar '(lambda (line)
25011 (if (string-match org-todo-line-regexp line)
25012 ;; This is a headline
25013 (progn
25014 (setq have-headings t)
25015 (setq level (- (match-end 1) (match-beginning 1))
25016 level (org-tr-level level)
25017 txt (save-match-data
25018 (org-html-expand
25019 (org-export-cleanup-toc-line
25020 (match-string 3 line))))
25021 todo
25022 (or (and org-export-mark-todo-in-toc
25023 (match-beginning 2)
25024 (not (member (match-string 2 line)
25025 org-done-keywords)))
25026 ; TODO, not DONE
25027 (and org-export-mark-todo-in-toc
25028 (= level umax-toc)
25029 (org-search-todo-below
25030 line lines level))))
25031 (if (string-match
25032 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25033 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25034 (if (string-match quote-re0 txt)
25035 (setq txt (replace-match "" t t txt)))
25036 (if org-export-with-section-numbers
25037 (setq txt (concat (org-section-number level)
25038 " " txt)))
25039 (if (<= level (max umax umax-toc))
25040 (setq head-count (+ head-count 1)))
25041 (if (<= level umax-toc)
25042 (progn
25043 (if (> level org-last-level)
25044 (progn
25045 (setq cnt (- level org-last-level))
25046 (while (>= (setq cnt (1- cnt)) 0)
25047 (push "\n<ul>\n<li>" thetoc))
25048 (push "\n" thetoc)))
25049 (if (< level org-last-level)
25050 (progn
25051 (setq cnt (- org-last-level level))
25052 (while (>= (setq cnt (1- cnt)) 0)
25053 (push "</li>\n</ul>" thetoc))
25054 (push "\n" thetoc)))
25055 ;; Check for targets
25056 (while (string-match org-target-regexp line)
25057 (setq tg (match-string 1 line)
25058 line (replace-match
25059 (concat "@<span class=\"target\">" tg "@</span> ")
25060 t t line))
25061 (push (cons (org-solidify-link-text tg)
25062 (format "sec-%d" head-count))
25063 target-alist))
25064 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25065 (setq txt (replace-match "" t t txt)))
25066 (push
25067 (format
25068 (if todo
25069 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25070 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25071 head-count txt) thetoc)
25073 (setq org-last-level level))
25075 line)
25076 lines))
25077 (while (> org-last-level (1- org-min-level))
25078 (setq org-last-level (1- org-last-level))
25079 (push "</li>\n</ul>\n" thetoc))
25080 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25082 (setq head-count 0)
25083 (org-init-section-numbers)
25085 (while (setq line (pop lines) origline line)
25086 (catch 'nextline
25088 ;; end of quote section?
25089 (when (and inquote (string-match "^\\*+ " line))
25090 (insert "</pre>\n")
25091 (setq inquote nil))
25092 ;; inside a quote section?
25093 (when inquote
25094 (insert (org-html-protect line) "\n")
25095 (throw 'nextline nil))
25097 ;; verbatim lines
25098 (when (and org-export-with-fixed-width
25099 (string-match "^[ \t]*:\\(.*\\)" line))
25100 (when (not infixed)
25101 (setq infixed t)
25102 (insert "<pre>\n"))
25103 (insert (org-html-protect (match-string 1 line)) "\n")
25104 (when (and lines
25105 (not (string-match "^[ \t]*\\(:.*\\)"
25106 (car lines))))
25107 (setq infixed nil)
25108 (insert "</pre>\n"))
25109 (throw 'nextline nil))
25111 ;; Protected HTML
25112 (when (get-text-property 0 'org-protected line)
25113 (let (par)
25114 (when (re-search-backward
25115 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25116 (setq par (match-string 1))
25117 (replace-match "\\2\n"))
25118 (insert line "\n")
25119 (while (and lines
25120 (or (= (length (car lines)) 0)
25121 (get-text-property 0 'org-protected (car lines))))
25122 (insert (pop lines) "\n"))
25123 (and par (insert "<p>\n")))
25124 (throw 'nextline nil))
25126 ;; Horizontal line
25127 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25128 (insert "\n<hr/>\n")
25129 (throw 'nextline nil))
25131 ;; make targets to anchors
25132 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25133 (cond
25134 ((match-end 2)
25135 (setq line (replace-match
25136 (concat "@<a name=\""
25137 (org-solidify-link-text (match-string 1 line))
25138 "\">\\nbsp@</a>")
25139 t t line)))
25140 ((and org-export-with-toc (equal (string-to-char line) ?*))
25141 (setq line (replace-match
25142 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25143 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25144 t t line)))
25146 (setq line (replace-match
25147 (concat "@<a name=\""
25148 (org-solidify-link-text (match-string 1 line))
25149 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25150 t t line)))))
25152 (setq line (org-html-handle-time-stamps line))
25154 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25155 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25156 ;; Also handle sub_superscripts and checkboxes
25157 (or (string-match org-table-hline-regexp line)
25158 (setq line (org-html-expand line)))
25160 ;; Format the links
25161 (setq start 0)
25162 (while (string-match org-bracket-link-analytic-regexp line start)
25163 (setq start (match-beginning 0))
25164 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25165 (setq path (match-string 3 line))
25166 (setq desc1 (if (match-end 5) (match-string 5 line))
25167 desc2 (if (match-end 2) (concat type ":" path) path)
25168 descp (and desc1 (not (equal desc1 desc2)))
25169 desc (or desc1 desc2))
25170 ;; Make an image out of the description if that is so wanted
25171 (when (and descp (org-file-image-p desc))
25172 (save-match-data
25173 (if (string-match "^file:" desc)
25174 (setq desc (substring desc (match-end 0)))))
25175 (setq desc (concat "<img src=\"" desc "\"/>")))
25176 ;; FIXME: do we need to unescape here somewhere?
25177 (cond
25178 ((equal type "internal")
25179 (setq rpl
25180 (concat
25181 "<a href=\"#"
25182 (org-solidify-link-text
25183 (save-match-data (org-link-unescape path)) target-alist)
25184 "\">" desc "</a>")))
25185 ((member type '("http" "https"))
25186 ;; standard URL, just check if we need to inline an image
25187 (if (and (or (eq t org-export-html-inline-images)
25188 (and org-export-html-inline-images (not descp)))
25189 (org-file-image-p path))
25190 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25191 (setq link (concat type ":" path))
25192 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25193 ((member type '("ftp" "mailto" "news"))
25194 ;; standard URL
25195 (setq link (concat type ":" path))
25196 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25197 ((string= type "file")
25198 ;; FILE link
25199 (let* ((filename path)
25200 (abs-p (file-name-absolute-p filename))
25201 thefile file-is-image-p search)
25202 (save-match-data
25203 (if (string-match "::\\(.*\\)" filename)
25204 (setq search (match-string 1 filename)
25205 filename (replace-match "" t nil filename)))
25206 (setq valid
25207 (if (functionp link-validate)
25208 (funcall link-validate filename current-dir)
25210 (setq file-is-image-p (org-file-image-p filename))
25211 (setq thefile (if abs-p (expand-file-name filename) filename))
25212 (when (and org-export-html-link-org-files-as-html
25213 (string-match "\\.org$" thefile))
25214 (setq thefile (concat (substring thefile 0
25215 (match-beginning 0))
25216 "." org-export-html-extension))
25217 (if (and search
25218 ;; make sure this is can be used as target search
25219 (not (string-match "^[0-9]*$" search))
25220 (not (string-match "^\\*" search))
25221 (not (string-match "^/.*/$" search)))
25222 (setq thefile (concat thefile "#"
25223 (org-solidify-link-text
25224 (org-link-unescape search)))))
25225 (when (string-match "^file:" desc)
25226 (setq desc (replace-match "" t t desc))
25227 (if (string-match "\\.org$" desc)
25228 (setq desc (replace-match "" t t desc))))))
25229 (setq rpl (if (and file-is-image-p
25230 (or (eq t org-export-html-inline-images)
25231 (and org-export-html-inline-images
25232 (not descp))))
25233 (concat "<img src=\"" thefile "\"/>")
25234 (concat "<a href=\"" thefile "\">" desc "</a>")))
25235 (if (not valid) (setq rpl desc))))
25236 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25237 (setq rpl (concat "<i>&lt;" type ":"
25238 (save-match-data (org-link-unescape path))
25239 "&gt;</i>"))))
25240 (setq line (replace-match rpl t t line)
25241 start (+ start (length rpl))))
25243 ;; TODO items
25244 (if (and (string-match org-todo-line-regexp line)
25245 (match-beginning 2))
25247 (setq line
25248 (concat (substring line 0 (match-beginning 2))
25249 "<span class=\""
25250 (if (member (match-string 2 line)
25251 org-done-keywords)
25252 "done" "todo")
25253 "\">" (match-string 2 line)
25254 "</span>" (substring line (match-end 2)))))
25256 ;; Does this contain a reference to a footnote?
25257 (when org-export-with-footnotes
25258 (setq start 0)
25259 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25260 (if (get-text-property (match-beginning 2) 'org-protected line)
25261 (setq start (match-end 2))
25262 (let ((n (match-string 2 line)))
25263 (setq line
25264 (replace-match
25265 (format
25266 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25267 (match-string 1 line) n n n)
25268 t t line))))))
25270 (cond
25271 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25272 ;; This is a headline
25273 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25274 txt (match-string 2 line))
25275 (if (string-match quote-re0 txt)
25276 (setq txt (replace-match "" t t txt)))
25277 (if (<= level (max umax umax-toc))
25278 (setq head-count (+ head-count 1)))
25279 (when in-local-list
25280 ;; Close any local lists before inserting a new header line
25281 (while local-list-num
25282 (org-close-li)
25283 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25284 (pop local-list-num))
25285 (setq local-list-indent nil
25286 in-local-list nil))
25287 (setq first-heading-pos (or first-heading-pos (point)))
25288 (org-html-level-start level txt umax
25289 (and org-export-with-toc (<= level umax))
25290 head-count)
25291 ;; QUOTES
25292 (when (string-match quote-re line)
25293 (insert "<pre>")
25294 (setq inquote t)))
25296 ((and org-export-with-tables
25297 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25298 (if (not table-open)
25299 ;; New table starts
25300 (setq table-open t table-buffer nil table-orig-buffer nil))
25301 ;; Accumulate lines
25302 (setq table-buffer (cons line table-buffer)
25303 table-orig-buffer (cons origline table-orig-buffer))
25304 (when (or (not lines)
25305 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25306 (car lines))))
25307 (setq table-open nil
25308 table-buffer (nreverse table-buffer)
25309 table-orig-buffer (nreverse table-orig-buffer))
25310 (org-close-par-maybe)
25311 (insert (org-format-table-html table-buffer table-orig-buffer))))
25313 ;; Normal lines
25314 (when (string-match
25315 (cond
25316 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25317 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25318 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25319 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25320 line)
25321 (setq ind (org-get-string-indentation line)
25322 start-is-num (match-beginning 4)
25323 starter (if (match-beginning 2)
25324 (substring (match-string 2 line) 0 -1))
25325 line (substring line (match-beginning 5)))
25326 (unless (string-match "[^ \t]" line)
25327 ;; empty line. Pretend indentation is large.
25328 (setq ind (if org-empty-line-terminates-plain-lists
25330 (1+ (or (car local-list-indent) 1)))))
25331 (setq didclose nil)
25332 (while (and in-local-list
25333 (or (and (= ind (car local-list-indent))
25334 (not starter))
25335 (< ind (car local-list-indent))))
25336 (setq didclose t)
25337 (org-close-li)
25338 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25339 (pop local-list-num) (pop local-list-indent)
25340 (setq in-local-list local-list-indent))
25341 (cond
25342 ((and starter
25343 (or (not in-local-list)
25344 (> ind (car local-list-indent))))
25345 ;; Start new (level of) list
25346 (org-close-par-maybe)
25347 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25348 (push start-is-num local-list-num)
25349 (push ind local-list-indent)
25350 (setq in-local-list t))
25351 (starter
25352 ;; continue current list
25353 (org-close-li)
25354 (insert "<li>\n"))
25355 (didclose
25356 ;; we did close a list, normal text follows: need <p>
25357 (org-open-par)))
25358 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25359 (setq line
25360 (replace-match
25361 (if (equal (match-string 1 line) "X")
25362 "<b>[X]</b>"
25363 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25364 t t line))))
25366 ;; Empty lines start a new paragraph. If hand-formatted lists
25367 ;; are not fully interpreted, lines starting with "-", "+", "*"
25368 ;; also start a new paragraph.
25369 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25371 ;; Is this the start of a footnote?
25372 (when org-export-with-footnotes
25373 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25374 (org-close-par-maybe)
25375 (let ((n (match-string 1 line)))
25376 (setq line (replace-match
25377 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25379 ;; Check if the line break needs to be conserved
25380 (cond
25381 ((string-match "\\\\\\\\[ \t]*$" line)
25382 (setq line (replace-match "<br/>" t t line)))
25383 (org-export-preserve-breaks
25384 (setq line (concat line "<br/>"))))
25386 (insert line "\n")))))
25388 ;; Properly close all local lists and other lists
25389 (when inquote (insert "</pre>\n"))
25390 (when in-local-list
25391 ;; Close any local lists before inserting a new header line
25392 (while local-list-num
25393 (org-close-li)
25394 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25395 (pop local-list-num))
25396 (setq local-list-indent nil
25397 in-local-list nil))
25398 (org-html-level-start 1 nil umax
25399 (and org-export-with-toc (<= level umax))
25400 head-count)
25402 (unless body-only
25403 (when (plist-get opt-plist :auto-postamble)
25404 (insert "<div id=\"postamble\">")
25405 (when (and org-export-author-info author)
25406 (insert "<p class=\"author\"> "
25407 (nth 1 lang-words) ": " author "\n")
25408 (when email
25409 (if (listp (split-string email ",+ *"))
25410 (mapc (lambda(e)
25411 (insert "<a href=\"mailto:" e "\">&lt;"
25412 e "&gt;</a>\n"))
25413 (split-string email ",+ *"))
25414 (insert "<a href=\"mailto:" email "\">&lt;"
25415 email "&gt;</a>\n")))
25416 (insert "</p>\n"))
25417 (when (and date org-export-time-stamp-file)
25418 (insert "<p class=\"date\"> "
25419 (nth 2 lang-words) ": "
25420 date "</p>\n"))
25421 (insert "</div>"))
25423 (if org-export-html-with-timestamp
25424 (insert org-export-html-html-helper-timestamp))
25425 (insert (or (plist-get opt-plist :postamble) ""))
25426 (insert "</body>\n</html>\n"))
25428 (normal-mode)
25429 (if (eq major-mode default-major-mode) (html-mode))
25431 ;; insert the table of contents
25432 (goto-char (point-min))
25433 (when thetoc
25434 (if (or (re-search-forward
25435 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25436 (re-search-forward
25437 "\\[TABLE-OF-CONTENTS\\]" nil t))
25438 (progn
25439 (goto-char (match-beginning 0))
25440 (replace-match ""))
25441 (goto-char first-heading-pos)
25442 (when (looking-at "\\s-*</p>")
25443 (goto-char (match-end 0))
25444 (insert "\n")))
25445 (insert "<div id=\"table-of-contents\">\n")
25446 (mapc 'insert thetoc)
25447 (insert "</div>\n"))
25448 ;; remove empty paragraphs and lists
25449 (goto-char (point-min))
25450 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25451 (replace-match ""))
25452 (goto-char (point-min))
25453 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25454 (replace-match ""))
25455 ;; Convert whitespace place holders
25456 (goto-char (point-min))
25457 (let (beg end n)
25458 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25459 (setq n (get-text-property beg 'org-whitespace)
25460 end (next-single-property-change beg 'org-whitespace))
25461 (goto-char beg)
25462 (delete-region beg end)
25463 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25464 (make-string n ?x)))))
25466 (or to-buffer (save-buffer))
25467 (goto-char (point-min))
25468 (message "Exporting... done")
25469 (if (eq to-buffer 'string)
25470 (prog1 (buffer-substring (point-min) (point-max))
25471 (kill-buffer (current-buffer)))
25472 (current-buffer)))))
25474 (defvar org-table-colgroup-info nil)
25475 (defun org-format-table-ascii (lines)
25476 "Format a table for ascii export."
25477 (if (stringp lines)
25478 (setq lines (org-split-string lines "\n")))
25479 (if (not (string-match "^[ \t]*|" (car lines)))
25480 ;; Table made by table.el - test for spanning
25481 lines
25483 ;; A normal org table
25484 ;; Get rid of hlines at beginning and end
25485 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25486 (setq lines (nreverse lines))
25487 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25488 (setq lines (nreverse lines))
25489 (when org-export-table-remove-special-lines
25490 ;; Check if the table has a marking column. If yes remove the
25491 ;; column and the special lines
25492 (setq lines (org-table-clean-before-export lines)))
25493 ;; Get rid of the vertical lines except for grouping
25494 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25495 rtn line vl1 start)
25496 (while (setq line (pop lines))
25497 (if (string-match org-table-hline-regexp line)
25498 (and (string-match "|\\(.*\\)|" line)
25499 (setq line (replace-match " \\1" t nil line)))
25500 (setq start 0 vl1 vl)
25501 (while (string-match "|" line start)
25502 (setq start (match-end 0))
25503 (or (pop vl1) (setq line (replace-match " " t t line)))))
25504 (push line rtn))
25505 (nreverse rtn))))
25507 (defun org-colgroup-info-to-vline-list (info)
25508 (let (vl new last)
25509 (while info
25510 (setq last new new (pop info))
25511 (if (or (memq last '(:end :startend))
25512 (memq new '(:start :startend)))
25513 (push t vl)
25514 (push nil vl)))
25515 (setq vl (nreverse vl))
25516 (and vl (setcar vl nil))
25517 vl))
25519 (defun org-format-table-html (lines olines)
25520 "Find out which HTML converter to use and return the HTML code."
25521 (if (stringp lines)
25522 (setq lines (org-split-string lines "\n")))
25523 (if (string-match "^[ \t]*|" (car lines))
25524 ;; A normal org table
25525 (org-format-org-table-html lines)
25526 ;; Table made by table.el - test for spanning
25527 (let* ((hlines (delq nil (mapcar
25528 (lambda (x)
25529 (if (string-match "^[ \t]*\\+-" x) x
25530 nil))
25531 lines)))
25532 (first (car hlines))
25533 (ll (and (string-match "\\S-+" first)
25534 (match-string 0 first)))
25535 (re (concat "^[ \t]*" (regexp-quote ll)))
25536 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25537 hlines))))
25538 (if (and (not spanning)
25539 (not org-export-prefer-native-exporter-for-tables))
25540 ;; We can use my own converter with HTML conversions
25541 (org-format-table-table-html lines)
25542 ;; Need to use the code generator in table.el, with the original text.
25543 (org-format-table-table-html-using-table-generate-source olines)))))
25545 (defun org-format-org-table-html (lines &optional splice)
25546 "Format a table into HTML."
25547 ;; Get rid of hlines at beginning and end
25548 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25549 (setq lines (nreverse lines))
25550 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25551 (setq lines (nreverse lines))
25552 (when org-export-table-remove-special-lines
25553 ;; Check if the table has a marking column. If yes remove the
25554 ;; column and the special lines
25555 (setq lines (org-table-clean-before-export lines)))
25557 (let ((head (and org-export-highlight-first-table-line
25558 (delq nil (mapcar
25559 (lambda (x) (string-match "^[ \t]*|-" x))
25560 (cdr lines)))))
25561 (nlines 0) fnum i
25562 tbopen line fields html gr colgropen)
25563 (if splice (setq head nil))
25564 (unless splice (push (if head "<thead>" "<tbody>") html))
25565 (setq tbopen t)
25566 (while (setq line (pop lines))
25567 (catch 'next-line
25568 (if (string-match "^[ \t]*|-" line)
25569 (progn
25570 (unless splice
25571 (push (if head "</thead>" "</tbody>") html)
25572 (if lines (push "<tbody>" html) (setq tbopen nil)))
25573 (setq head nil) ;; head ends here, first time around
25574 ;; ignore this line
25575 (throw 'next-line t)))
25576 ;; Break the line into fields
25577 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25578 (unless fnum (setq fnum (make-vector (length fields) 0)))
25579 (setq nlines (1+ nlines) i -1)
25580 (push (concat "<tr>"
25581 (mapconcat
25582 (lambda (x)
25583 (setq i (1+ i))
25584 (if (and (< i nlines)
25585 (string-match org-table-number-regexp x))
25586 (incf (aref fnum i)))
25587 (if head
25588 (concat (car org-export-table-header-tags) x
25589 (cdr org-export-table-header-tags))
25590 (concat (car org-export-table-data-tags) x
25591 (cdr org-export-table-data-tags))))
25592 fields "")
25593 "</tr>")
25594 html)))
25595 (unless splice (if tbopen (push "</tbody>" html)))
25596 (unless splice (push "</table>\n" html))
25597 (setq html (nreverse html))
25598 (unless splice
25599 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25600 (push (mapconcat
25601 (lambda (x)
25602 (setq gr (pop org-table-colgroup-info))
25603 (format "%s<col align=\"%s\"></col>%s"
25604 (if (memq gr '(:start :startend))
25605 (prog1
25606 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25607 (setq colgropen t))
25609 (if (> (/ (float x) nlines) org-table-number-fraction)
25610 "right" "left")
25611 (if (memq gr '(:end :startend))
25612 (progn (setq colgropen nil) "</colgroup>")
25613 "")))
25614 fnum "")
25615 html)
25616 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25617 (push html-table-tag html))
25618 (concat (mapconcat 'identity html "\n") "\n")))
25620 (defun org-table-clean-before-export (lines)
25621 "Check if the table has a marking column.
25622 If yes remove the column and the special lines."
25623 (setq org-table-colgroup-info nil)
25624 (if (memq nil
25625 (mapcar
25626 (lambda (x) (or (string-match "^[ \t]*|-" x)
25627 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25628 lines))
25629 (progn
25630 (setq org-table-clean-did-remove-column nil)
25631 (delq nil
25632 (mapcar
25633 (lambda (x)
25634 (cond
25635 ((string-match "^[ \t]*| */ *|" x)
25636 (setq org-table-colgroup-info
25637 (mapcar (lambda (x)
25638 (cond ((member x '("<" "&lt;")) :start)
25639 ((member x '(">" "&gt;")) :end)
25640 ((member x '("<>" "&lt;&gt;")) :startend)
25641 (t nil)))
25642 (org-split-string x "[ \t]*|[ \t]*")))
25643 nil)
25644 (t x)))
25645 lines)))
25646 (setq org-table-clean-did-remove-column t)
25647 (delq nil
25648 (mapcar
25649 (lambda (x)
25650 (cond
25651 ((string-match "^[ \t]*| */ *|" x)
25652 (setq org-table-colgroup-info
25653 (mapcar (lambda (x)
25654 (cond ((member x '("<" "&lt;")) :start)
25655 ((member x '(">" "&gt;")) :end)
25656 ((member x '("<>" "&lt;&gt;")) :startend)
25657 (t nil)))
25658 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25659 nil)
25660 ((string-match "^[ \t]*| *[!_^/] *|" x)
25661 nil) ; ignore this line
25662 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25663 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25664 ;; remove the first column
25665 (replace-match "\\1|" t nil x))))
25666 lines))))
25668 (defun org-format-table-table-html (lines)
25669 "Format a table generated by table.el into HTML.
25670 This conversion does *not* use `table-generate-source' from table.el.
25671 This has the advantage that Org-mode's HTML conversions can be used.
25672 But it has the disadvantage, that no cell- or row-spanning is allowed."
25673 (let (line field-buffer
25674 (head org-export-highlight-first-table-line)
25675 fields html empty)
25676 (setq html (concat html-table-tag "\n"))
25677 (while (setq line (pop lines))
25678 (setq empty "&nbsp;")
25679 (catch 'next-line
25680 (if (string-match "^[ \t]*\\+-" line)
25681 (progn
25682 (if field-buffer
25683 (progn
25684 (setq
25685 html
25686 (concat
25687 html
25688 "<tr>"
25689 (mapconcat
25690 (lambda (x)
25691 (if (equal x "") (setq x empty))
25692 (if head
25693 (concat (car org-export-table-header-tags) x
25694 (cdr org-export-table-header-tags))
25695 (concat (car org-export-table-data-tags) x
25696 (cdr org-export-table-data-tags))))
25697 field-buffer "\n")
25698 "</tr>\n"))
25699 (setq head nil)
25700 (setq field-buffer nil)))
25701 ;; Ignore this line
25702 (throw 'next-line t)))
25703 ;; Break the line into fields and store the fields
25704 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25705 (if field-buffer
25706 (setq field-buffer (mapcar
25707 (lambda (x)
25708 (concat x "<br/>" (pop fields)))
25709 field-buffer))
25710 (setq field-buffer fields))))
25711 (setq html (concat html "</table>\n"))
25712 html))
25714 (defun org-format-table-table-html-using-table-generate-source (lines)
25715 "Format a table into html, using `table-generate-source' from table.el.
25716 This has the advantage that cell- or row-spanning is allowed.
25717 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25718 (require 'table)
25719 (with-current-buffer (get-buffer-create " org-tmp1 ")
25720 (erase-buffer)
25721 (insert (mapconcat 'identity lines "\n"))
25722 (goto-char (point-min))
25723 (if (not (re-search-forward "|[^+]" nil t))
25724 (error "Error processing table"))
25725 (table-recognize-table)
25726 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25727 (table-generate-source 'html " org-tmp2 ")
25728 (set-buffer " org-tmp2 ")
25729 (buffer-substring (point-min) (point-max))))
25731 (defun org-html-handle-time-stamps (s)
25732 "Format time stamps in string S, or remove them."
25733 (catch 'exit
25734 (let (r b)
25735 (while (string-match org-maybe-keyword-time-regexp s)
25736 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25737 ;; never export CLOCK
25738 (throw 'exit ""))
25739 (or b (setq b (substring s 0 (match-beginning 0))))
25740 (if (not org-export-with-timestamps)
25741 (setq r (concat r (substring s 0 (match-beginning 0)))
25742 s (substring s (match-end 0)))
25743 (setq r (concat
25744 r (substring s 0 (match-beginning 0))
25745 (if (match-end 1)
25746 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25747 (match-string 1 s)))
25748 (format " @<span class=\"timestamp\">%s@</span>"
25749 (substring
25750 (org-translate-time (match-string 3 s)) 1 -1)))
25751 s (substring s (match-end 0)))))
25752 ;; Line break if line started and ended with time stamp stuff
25753 (if (not r)
25755 (setq r (concat r s))
25756 (unless (string-match "\\S-" (concat b s))
25757 (setq r (concat r "@<br/>")))
25758 r))))
25760 (defun org-html-protect (s)
25761 ;; convert & to &amp;, < to &lt; and > to &gt;
25762 (let ((start 0))
25763 (while (string-match "&" s start)
25764 (setq s (replace-match "&amp;" t t s)
25765 start (1+ (match-beginning 0))))
25766 (while (string-match "<" s)
25767 (setq s (replace-match "&lt;" t t s)))
25768 (while (string-match ">" s)
25769 (setq s (replace-match "&gt;" t t s))))
25772 (defun org-export-cleanup-toc-line (s)
25773 "Remove tags and time staps from lines going into the toc."
25774 (when (memq org-export-with-tags '(not-in-toc nil))
25775 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25776 (setq s (replace-match "" t t s))))
25777 (when org-export-remove-timestamps-from-toc
25778 (while (string-match org-maybe-keyword-time-regexp s)
25779 (setq s (replace-match "" t t s))))
25780 (while (string-match org-bracket-link-regexp s)
25781 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25782 t t s)))
25785 (defun org-html-expand (string)
25786 "Prepare STRING for HTML export. Applies all active conversions.
25787 If there are links in the string, don't modify these."
25788 (let* ((re (concat org-bracket-link-regexp "\\|"
25789 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25790 m s l res)
25791 (while (setq m (string-match re string))
25792 (setq s (substring string 0 m)
25793 l (match-string 0 string)
25794 string (substring string (match-end 0)))
25795 (push (org-html-do-expand s) res)
25796 (push l res))
25797 (push (org-html-do-expand string) res)
25798 (apply 'concat (nreverse res))))
25800 (defun org-html-do-expand (s)
25801 "Apply all active conversions to translate special ASCII to HTML."
25802 (setq s (org-html-protect s))
25803 (if org-export-html-expand
25804 (let ((start 0))
25805 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25806 (setq s (replace-match "<\\1>" t nil s)))))
25807 (if org-export-with-emphasize
25808 (setq s (org-export-html-convert-emphasize s)))
25809 (if org-export-with-special-strings
25810 (setq s (org-export-html-convert-special-strings s)))
25811 (if org-export-with-sub-superscripts
25812 (setq s (org-export-html-convert-sub-super s)))
25813 (if org-export-with-TeX-macros
25814 (let ((start 0) wd ass)
25815 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25816 (if (get-text-property (match-beginning 0) 'org-protected s)
25817 (setq start (match-end 0))
25818 (setq wd (match-string 1 s))
25819 (if (setq ass (assoc wd org-html-entities))
25820 (setq s (replace-match (or (cdr ass)
25821 (concat "&" (car ass) ";"))
25822 t t s))
25823 (setq start (+ start (length wd))))))))
25826 (defun org-create-multibrace-regexp (left right n)
25827 "Create a regular expression which will match a balanced sexp.
25828 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25829 as single character strings.
25830 The regexp returned will match the entire expression including the
25831 delimiters. It will also define a single group which contains the
25832 match except for the outermost delimiters. The maximum depth of
25833 stacked delimiters is N. Escaping delimiters is not possible."
25834 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25835 (or "\\|")
25836 (re nothing)
25837 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25838 (while (> n 1)
25839 (setq n (1- n)
25840 re (concat re or next)
25841 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25842 (concat left "\\(" re "\\)" right)))
25844 (defvar org-match-substring-regexp
25845 (concat
25846 "\\([^\\]\\)\\([_^]\\)\\("
25847 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25848 "\\|"
25849 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25850 "\\|"
25851 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25852 "The regular expression matching a sub- or superscript.")
25854 (defvar org-match-substring-with-braces-regexp
25855 (concat
25856 "\\([^\\]\\)\\([_^]\\)\\("
25857 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25858 "\\)")
25859 "The regular expression matching a sub- or superscript, forcing braces.")
25861 (defconst org-export-html-special-string-regexps
25862 '(("\\\\-" . "&shy;")
25863 ("---\\([^-]\\)" . "&mdash;\\1")
25864 ("--\\([^-]\\)" . "&ndash;\\1")
25865 ("\\.\\.\\." . "&hellip;"))
25866 "Regular expressions for special string conversion.")
25868 (defun org-export-html-convert-special-strings (string)
25869 "Convert special characters in STRING to HTML."
25870 (let ((all org-export-html-special-string-regexps)
25871 e a re rpl start)
25872 (while (setq a (pop all))
25873 (setq re (car a) rpl (cdr a) start 0)
25874 (while (string-match re string start)
25875 (if (get-text-property (match-beginning 0) 'org-protected string)
25876 (setq start (match-end 0))
25877 (setq string (replace-match rpl t nil string)))))
25878 string))
25880 (defun org-export-html-convert-sub-super (string)
25881 "Convert sub- and superscripts in STRING to HTML."
25882 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25883 (while (string-match org-match-substring-regexp string s)
25884 (cond
25885 ((and requireb (match-end 8)) (setq s (match-end 2)))
25886 ((get-text-property (match-beginning 2) 'org-protected string)
25887 (setq s (match-end 2)))
25889 (setq s (match-end 1)
25890 key (if (string= (match-string 2 string) "_") "sub" "sup")
25891 c (or (match-string 8 string)
25892 (match-string 6 string)
25893 (match-string 5 string))
25894 string (replace-match
25895 (concat (match-string 1 string)
25896 "<" key ">" c "</" key ">")
25897 t t string)))))
25898 (while (string-match "\\\\\\([_^]\\)" string)
25899 (setq string (replace-match (match-string 1 string) t t string)))
25900 string))
25902 (defun org-export-html-convert-emphasize (string)
25903 "Apply emphasis."
25904 (let ((s 0) rpl)
25905 (while (string-match org-emph-re string s)
25906 (if (not (equal
25907 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25908 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25909 (setq s (match-beginning 0)
25911 (concat
25912 (match-string 1 string)
25913 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25914 (match-string 4 string)
25915 (nth 3 (assoc (match-string 3 string)
25916 org-emphasis-alist))
25917 (match-string 5 string))
25918 string (replace-match rpl t t string)
25919 s (+ s (- (length rpl) 2)))
25920 (setq s (1+ s))))
25921 string))
25923 (defvar org-par-open nil)
25924 (defun org-open-par ()
25925 "Insert <p>, but first close previous paragraph if any."
25926 (org-close-par-maybe)
25927 (insert "\n<p>")
25928 (setq org-par-open t))
25929 (defun org-close-par-maybe ()
25930 "Close paragraph if there is one open."
25931 (when org-par-open
25932 (insert "</p>")
25933 (setq org-par-open nil)))
25934 (defun org-close-li ()
25935 "Close <li> if necessary."
25936 (org-close-par-maybe)
25937 (insert "</li>\n"))
25939 (defvar body-only) ; dynamically scoped into this.
25940 (defun org-html-level-start (level title umax with-toc head-count)
25941 "Insert a new level in HTML export.
25942 When TITLE is nil, just close all open levels."
25943 (org-close-par-maybe)
25944 (let ((l org-level-max))
25945 (while (>= l level)
25946 (if (aref org-levels-open (1- l))
25947 (progn
25948 (org-html-level-close l umax)
25949 (aset org-levels-open (1- l) nil)))
25950 (setq l (1- l)))
25951 (when title
25952 ;; If title is nil, this means this function is called to close
25953 ;; all levels, so the rest is done only if title is given
25954 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25955 (setq title (replace-match
25956 (if org-export-with-tags
25957 (save-match-data
25958 (concat
25959 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
25960 (mapconcat 'identity (org-split-string
25961 (match-string 1 title) ":")
25962 "&nbsp;")
25963 "</span>"))
25965 t t title)))
25966 (if (> level umax)
25967 (progn
25968 (if (aref org-levels-open (1- level))
25969 (progn
25970 (org-close-li)
25971 (insert "<li>" title "<br/>\n"))
25972 (aset org-levels-open (1- level) t)
25973 (org-close-par-maybe)
25974 (insert "<ul>\n<li>" title "<br/>\n")))
25975 (aset org-levels-open (1- level) t)
25976 (if (and org-export-with-section-numbers (not body-only))
25977 (setq title (concat (org-section-number level) " " title)))
25978 (setq level (+ level org-export-html-toplevel-hlevel -1))
25979 (if with-toc
25980 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
25981 level level head-count title level))
25982 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
25983 (org-open-par)))))
25985 (defun org-html-level-close (level max-outline-level)
25986 "Terminate one level in HTML export."
25987 (if (<= level max-outline-level)
25988 (insert "</div>\n")
25989 (org-close-li)
25990 (insert "</ul>\n")))
25992 ;;; iCalendar export
25994 ;;;###autoload
25995 (defun org-export-icalendar-this-file ()
25996 "Export current file as an iCalendar file.
25997 The iCalendar file will be located in the same directory as the Org-mode
25998 file, but with extension `.ics'."
25999 (interactive)
26000 (org-export-icalendar nil buffer-file-name))
26002 ;;;###autoload
26003 (defun org-export-icalendar-all-agenda-files ()
26004 "Export all files in `org-agenda-files' to iCalendar .ics files.
26005 Each iCalendar file will be located in the same directory as the Org-mode
26006 file, but with extension `.ics'."
26007 (interactive)
26008 (apply 'org-export-icalendar nil (org-agenda-files t)))
26010 ;;;###autoload
26011 (defun org-export-icalendar-combine-agenda-files ()
26012 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26013 The file is stored under the name `org-combined-agenda-icalendar-file'."
26014 (interactive)
26015 (apply 'org-export-icalendar t (org-agenda-files t)))
26017 (defun org-export-icalendar (combine &rest files)
26018 "Create iCalendar files for all elements of FILES.
26019 If COMBINE is non-nil, combine all calendar entries into a single large
26020 file and store it under the name `org-combined-agenda-icalendar-file'."
26021 (save-excursion
26022 (org-prepare-agenda-buffers files)
26023 (let* ((dir (org-export-directory
26024 :ical (list :publishing-directory
26025 org-export-publishing-directory)))
26026 file ical-file ical-buffer category started org-agenda-new-buffers)
26028 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26029 (when combine
26030 (setq ical-file
26031 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26032 org-combined-agenda-icalendar-file
26033 (expand-file-name org-combined-agenda-icalendar-file dir))
26034 ical-buffer (org-get-agenda-file-buffer ical-file))
26035 (set-buffer ical-buffer) (erase-buffer))
26036 (while (setq file (pop files))
26037 (catch 'nextfile
26038 (org-check-agenda-file file)
26039 (set-buffer (org-get-agenda-file-buffer file))
26040 (unless combine
26041 (setq ical-file (concat (file-name-as-directory dir)
26042 (file-name-sans-extension
26043 (file-name-nondirectory buffer-file-name))
26044 ".ics"))
26045 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26046 (with-current-buffer ical-buffer (erase-buffer)))
26047 (setq category (or org-category
26048 (file-name-sans-extension
26049 (file-name-nondirectory buffer-file-name))))
26050 (if (symbolp category) (setq category (symbol-name category)))
26051 (let ((standard-output ical-buffer))
26052 (if combine
26053 (and (not started) (setq started t)
26054 (org-start-icalendar-file org-icalendar-combined-name))
26055 (org-start-icalendar-file category))
26056 (org-print-icalendar-entries combine)
26057 (when (or (and combine (not files)) (not combine))
26058 (org-finish-icalendar-file)
26059 (set-buffer ical-buffer)
26060 (save-buffer)
26061 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26062 (org-release-buffers org-agenda-new-buffers))))
26064 (defvar org-after-save-iCalendar-file-hook nil
26065 "Hook run after an iCalendar file has been saved.
26066 The iCalendar buffer is still current when this hook is run.
26067 A good way to use this is to tell a desktop calenndar application to re-read
26068 the iCalendar file.")
26070 (defun org-print-icalendar-entries (&optional combine)
26071 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26072 When COMBINE is non nil, add the category to each line."
26073 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26074 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26075 (dts (org-ical-ts-to-string
26076 (format-time-string (cdr org-time-stamp-formats) (current-time))
26077 "DTSTART"))
26078 hd ts ts2 state status (inc t) pos b sexp rrule
26079 scheduledp deadlinep tmp pri category entry location summary desc
26080 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26081 (org-refresh-category-properties)
26082 (save-excursion
26083 (goto-char (point-min))
26084 (while (re-search-forward re1 nil t)
26085 (catch :skip
26086 (org-agenda-skip)
26087 (setq pos (match-beginning 0)
26088 ts (match-string 0)
26089 inc t
26090 hd (org-get-heading)
26091 summary (org-icalendar-cleanup-string
26092 (org-entry-get nil "SUMMARY"))
26093 desc (org-icalendar-cleanup-string
26094 (or (org-entry-get nil "DESCRIPTION")
26095 (and org-icalendar-include-body (org-get-entry)))
26096 t org-icalendar-include-body)
26097 location (org-icalendar-cleanup-string
26098 (org-entry-get nil "LOCATION"))
26099 category (org-get-category))
26100 (if (looking-at re2)
26101 (progn
26102 (goto-char (match-end 0))
26103 (setq ts2 (match-string 1) inc nil))
26104 (setq tmp (buffer-substring (max (point-min)
26105 (- pos org-ds-keyword-length))
26106 pos)
26107 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26108 (progn
26109 (setq inc nil)
26110 (replace-match "\\1" t nil ts))
26112 deadlinep (string-match org-deadline-regexp tmp)
26113 scheduledp (string-match org-scheduled-regexp tmp)
26114 ;; donep (org-entry-is-done-p)
26116 (if (or (string-match org-tr-regexp hd)
26117 (string-match org-ts-regexp hd))
26118 (setq hd (replace-match "" t t hd)))
26119 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26120 (setq rrule
26121 (concat "\nRRULE:FREQ="
26122 (cdr (assoc
26123 (match-string 2 ts)
26124 '(("d" . "DAILY")("w" . "WEEKLY")
26125 ("m" . "MONTHLY")("y" . "YEARLY"))))
26126 ";INTERVAL=" (match-string 1 ts)))
26127 (setq rrule ""))
26128 (setq summary (or summary hd))
26129 (if (string-match org-bracket-link-regexp summary)
26130 (setq summary
26131 (replace-match (if (match-end 3)
26132 (match-string 3 summary)
26133 (match-string 1 summary))
26134 t t summary)))
26135 (if deadlinep (setq summary (concat "DL: " summary)))
26136 (if scheduledp (setq summary (concat "S: " summary)))
26137 (if (string-match "\\`<%%" ts)
26138 (with-current-buffer sexp-buffer
26139 (insert (substring ts 1 -1) " " summary "\n"))
26140 (princ (format "BEGIN:VEVENT
26142 %s%s
26143 SUMMARY:%s%s%s
26144 CATEGORIES:%s
26145 END:VEVENT\n"
26146 (org-ical-ts-to-string ts "DTSTART")
26147 (org-ical-ts-to-string ts2 "DTEND" inc)
26148 rrule summary
26149 (if (and desc (string-match "\\S-" desc))
26150 (concat "\nDESCRIPTION: " desc) "")
26151 (if (and location (string-match "\\S-" location))
26152 (concat "\nLOCATION: " location) "")
26153 category)))))
26155 (when (and org-icalendar-include-sexps
26156 (condition-case nil (require 'icalendar) (error nil))
26157 (fboundp 'icalendar-export-region))
26158 ;; Get all the literal sexps
26159 (goto-char (point-min))
26160 (while (re-search-forward "^&?%%(" nil t)
26161 (catch :skip
26162 (org-agenda-skip)
26163 (setq b (match-beginning 0))
26164 (goto-char (1- (match-end 0)))
26165 (forward-sexp 1)
26166 (end-of-line 1)
26167 (setq sexp (buffer-substring b (point)))
26168 (with-current-buffer sexp-buffer
26169 (insert sexp "\n"))
26170 (princ (org-diary-to-ical-string sexp-buffer)))))
26172 (when org-icalendar-include-todo
26173 (goto-char (point-min))
26174 (while (re-search-forward org-todo-line-regexp nil t)
26175 (catch :skip
26176 (org-agenda-skip)
26177 (setq state (match-string 2))
26178 (setq status (if (member state org-done-keywords)
26179 "COMPLETED" "NEEDS-ACTION"))
26180 (when (and state
26181 (or (not (member state org-done-keywords))
26182 (eq org-icalendar-include-todo 'all))
26183 (not (member org-archive-tag (org-get-tags-at)))
26185 (setq hd (match-string 3)
26186 summary (org-icalendar-cleanup-string
26187 (org-entry-get nil "SUMMARY"))
26188 desc (org-icalendar-cleanup-string
26189 (or (org-entry-get nil "DESCRIPTION")
26190 (and org-icalendar-include-body (org-get-entry)))
26191 t org-icalendar-include-body)
26192 location (org-icalendar-cleanup-string
26193 (org-entry-get nil "LOCATION")))
26194 (if (string-match org-bracket-link-regexp hd)
26195 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26196 (match-string 1 hd))
26197 t t hd)))
26198 (if (string-match org-priority-regexp hd)
26199 (setq pri (string-to-char (match-string 2 hd))
26200 hd (concat (substring hd 0 (match-beginning 1))
26201 (substring hd (match-end 1))))
26202 (setq pri org-default-priority))
26203 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26204 (- org-lowest-priority org-highest-priority))))))
26206 (princ (format "BEGIN:VTODO
26208 SUMMARY:%s%s%s
26209 CATEGORIES:%s
26210 SEQUENCE:1
26211 PRIORITY:%d
26212 STATUS:%s
26213 END:VTODO\n"
26215 (or summary hd)
26216 (if (and location (string-match "\\S-" location))
26217 (concat "\nLOCATION: " location) "")
26218 (if (and desc (string-match "\\S-" desc))
26219 (concat "\nDESCRIPTION: " desc) "")
26220 category pri status)))))))))
26222 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26223 "Take out stuff and quote what needs to be quoted.
26224 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26225 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26226 characters."
26227 (if (not s)
26229 (when is-body
26230 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26231 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26232 (while (string-match re s) (setq s (replace-match "" t t s)))
26233 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26234 (let ((start 0))
26235 (while (string-match "\\([,;\\]\\)" s start)
26236 (setq start (+ (match-beginning 0) 2)
26237 s (replace-match "\\\\\\1" nil nil s))))
26238 (when is-body
26239 (while (string-match "[ \t]*\n[ \t]*" s)
26240 (setq s (replace-match "\\n" t t s))))
26241 (setq s (org-trim s))
26242 (if is-body
26243 (if maxlength
26244 (if (and (numberp maxlength)
26245 (> (length s) maxlength))
26246 (setq s (substring s 0 maxlength)))))
26249 (defun org-get-entry ()
26250 "Clean-up description string."
26251 (save-excursion
26252 (org-back-to-heading t)
26253 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26255 (defun org-start-icalendar-file (name)
26256 "Start an iCalendar file by inserting the header."
26257 (let ((user user-full-name)
26258 (name (or name "unknown"))
26259 (timezone (cadr (current-time-zone))))
26260 (princ
26261 (format "BEGIN:VCALENDAR
26262 VERSION:2.0
26263 X-WR-CALNAME:%s
26264 PRODID:-//%s//Emacs with Org-mode//EN
26265 X-WR-TIMEZONE:%s
26266 CALSCALE:GREGORIAN\n" name user timezone))))
26268 (defun org-finish-icalendar-file ()
26269 "Finish an iCalendar file by inserting the END statement."
26270 (princ "END:VCALENDAR\n"))
26272 (defun org-ical-ts-to-string (s keyword &optional inc)
26273 "Take a time string S and convert it to iCalendar format.
26274 KEYWORD is added in front, to make a complete line like DTSTART....
26275 When INC is non-nil, increase the hour by two (if time string contains
26276 a time), or the day by one (if it does not contain a time)."
26277 (let ((t1 (org-parse-time-string s 'nodefault))
26278 t2 fmt have-time time)
26279 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26280 (setq t2 t1 have-time t)
26281 (setq t2 (org-parse-time-string s)))
26282 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26283 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26284 (when inc
26285 (if have-time
26286 (if org-agenda-default-appointment-duration
26287 (setq mi (+ org-agenda-default-appointment-duration mi))
26288 (setq h (+ 2 h)))
26289 (setq d (1+ d))))
26290 (setq time (encode-time s mi h d m y)))
26291 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26292 (concat keyword (format-time-string fmt time))))
26294 ;;; XOXO export
26296 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26297 (with-current-buffer buffer
26298 (apply 'insert output)))
26299 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26301 (defun org-export-as-xoxo (&optional buffer)
26302 "Export the org buffer as XOXO.
26303 The XOXO buffer is named *xoxo-<source buffer name>*"
26304 (interactive (list (current-buffer)))
26305 ;; A quickie abstraction
26307 ;; Output everything as XOXO
26308 (with-current-buffer (get-buffer buffer)
26309 (let* ((pos (point))
26310 (opt-plist (org-combine-plists (org-default-export-plist)
26311 (org-infile-export-plist)))
26312 (filename (concat (file-name-as-directory
26313 (org-export-directory :xoxo opt-plist))
26314 (file-name-sans-extension
26315 (file-name-nondirectory buffer-file-name))
26316 ".html"))
26317 (out (find-file-noselect filename))
26318 (last-level 1)
26319 (hanging-li nil))
26320 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26321 ;; Check the output buffer is empty.
26322 (with-current-buffer out (erase-buffer))
26323 ;; Kick off the output
26324 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26325 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26326 (let* ((hd (match-string-no-properties 1))
26327 (level (length hd))
26328 (text (concat
26329 (match-string-no-properties 2)
26330 (save-excursion
26331 (goto-char (match-end 0))
26332 (let ((str ""))
26333 (catch 'loop
26334 (while 't
26335 (forward-line)
26336 (if (looking-at "^[ \t]\\(.*\\)")
26337 (setq str (concat str (match-string-no-properties 1)))
26338 (throw 'loop str)))))))))
26340 ;; Handle level rendering
26341 (cond
26342 ((> level last-level)
26343 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26345 ((< level last-level)
26346 (dotimes (- (- last-level level) 1)
26347 (if hanging-li
26348 (org-export-as-xoxo-insert-into out "</li>\n"))
26349 (org-export-as-xoxo-insert-into out "</ol>\n"))
26350 (when hanging-li
26351 (org-export-as-xoxo-insert-into out "</li>\n")
26352 (setq hanging-li nil)))
26354 ((equal level last-level)
26355 (if hanging-li
26356 (org-export-as-xoxo-insert-into out "</li>\n")))
26359 (setq last-level level)
26361 ;; And output the new li
26362 (setq hanging-li 't)
26363 (if (equal ?+ (elt text 0))
26364 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26365 (org-export-as-xoxo-insert-into out "<li>" text))))
26367 ;; Finally finish off the ol
26368 (dotimes (- last-level 1)
26369 (if hanging-li
26370 (org-export-as-xoxo-insert-into out "</li>\n"))
26371 (org-export-as-xoxo-insert-into out "</ol>\n"))
26373 (goto-char pos)
26374 ;; Finish the buffer off and clean it up.
26375 (switch-to-buffer-other-window out)
26376 (indent-region (point-min) (point-max) nil)
26377 (save-buffer)
26378 (goto-char (point-min))
26382 ;;;; Key bindings
26384 ;; Make `C-c C-x' a prefix key
26385 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26387 ;; TAB key with modifiers
26388 (org-defkey org-mode-map "\C-i" 'org-cycle)
26389 (org-defkey org-mode-map [(tab)] 'org-cycle)
26390 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26391 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26392 (org-defkey org-mode-map "\M-\t" 'org-complete)
26393 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26394 ;; The following line is necessary under Suse GNU/Linux
26395 (unless (featurep 'xemacs)
26396 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26397 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26398 (define-key org-mode-map [backtab] 'org-shifttab)
26400 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26401 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26402 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26404 ;; Cursor keys with modifiers
26405 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26406 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26407 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26408 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26410 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26411 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26412 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26413 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26415 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26416 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26417 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26418 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26420 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26421 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26423 ;;; Extra keys for tty access.
26424 ;; We only set them when really needed because otherwise the
26425 ;; menus don't show the simple keys
26427 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26428 (not window-system))
26429 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26430 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26431 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26432 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26433 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26434 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26435 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26436 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26437 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26438 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26439 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26440 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26441 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26442 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26443 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26444 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26445 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26446 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26447 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26448 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26449 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26450 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26452 ;; All the other keys
26454 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26455 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26456 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26457 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26458 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26459 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26460 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26461 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26462 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26463 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26464 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26465 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26466 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26467 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26468 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26469 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26470 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26471 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26472 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26473 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26474 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26475 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26476 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26477 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26478 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26479 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26480 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26481 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26482 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26483 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26484 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26485 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26486 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26487 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26488 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26489 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26490 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26491 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26492 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26493 (org-defkey org-mode-map "\C-c^" 'org-sort)
26494 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26495 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26496 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26497 (org-defkey org-mode-map "\C-m" 'org-return)
26498 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26499 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26500 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26501 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26502 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26503 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26504 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26505 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26506 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26507 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26508 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26509 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26510 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26511 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26512 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26513 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26514 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26516 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26517 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26518 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26519 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26521 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26522 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26523 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26524 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26525 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26526 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26527 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26528 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26529 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26530 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26531 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26532 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26534 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26536 (when (featurep 'xemacs)
26537 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26539 (defsubst org-table-p () (org-at-table-p))
26541 (defun org-self-insert-command (N)
26542 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26543 If the cursor is in a table looking at whitespace, the whitespace is
26544 overwritten, and the table is not marked as requiring realignment."
26545 (interactive "p")
26546 (if (and (org-table-p)
26547 (progn
26548 ;; check if we blank the field, and if that triggers align
26549 (and org-table-auto-blank-field
26550 (member last-command
26551 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26552 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26553 ;; got extra space, this field does not determine column width
26554 (let (org-table-may-need-update) (org-table-blank-field))
26555 ;; no extra space, this field may determine column width
26556 (org-table-blank-field)))
26558 (eq N 1)
26559 (looking-at "[^|\n]* |"))
26560 (let (org-table-may-need-update)
26561 (goto-char (1- (match-end 0)))
26562 (delete-backward-char 1)
26563 (goto-char (match-beginning 0))
26564 (self-insert-command N))
26565 (setq org-table-may-need-update t)
26566 (self-insert-command N)
26567 (org-fix-tags-on-the-fly)))
26569 (defun org-fix-tags-on-the-fly ()
26570 (when (and (equal (char-after (point-at-bol)) ?*)
26571 (org-on-heading-p))
26572 (org-align-tags-here org-tags-column)))
26574 (defun org-delete-backward-char (N)
26575 "Like `delete-backward-char', insert whitespace at field end in tables.
26576 When deleting backwards, in tables this function will insert whitespace in
26577 front of the next \"|\" separator, to keep the table aligned. The table will
26578 still be marked for re-alignment if the field did fill the entire column,
26579 because, in this case the deletion might narrow the column."
26580 (interactive "p")
26581 (if (and (org-table-p)
26582 (eq N 1)
26583 (string-match "|" (buffer-substring (point-at-bol) (point)))
26584 (looking-at ".*?|"))
26585 (let ((pos (point))
26586 (noalign (looking-at "[^|\n\r]* |"))
26587 (c org-table-may-need-update))
26588 (backward-delete-char N)
26589 (skip-chars-forward "^|")
26590 (insert " ")
26591 (goto-char (1- pos))
26592 ;; noalign: if there were two spaces at the end, this field
26593 ;; does not determine the width of the column.
26594 (if noalign (setq org-table-may-need-update c)))
26595 (backward-delete-char N)
26596 (org-fix-tags-on-the-fly)))
26598 (defun org-delete-char (N)
26599 "Like `delete-char', but insert whitespace at field end in tables.
26600 When deleting characters, in tables this function will insert whitespace in
26601 front of the next \"|\" separator, to keep the table aligned. The table will
26602 still be marked for re-alignment if the field did fill the entire column,
26603 because, in this case the deletion might narrow the column."
26604 (interactive "p")
26605 (if (and (org-table-p)
26606 (not (bolp))
26607 (not (= (char-after) ?|))
26608 (eq N 1))
26609 (if (looking-at ".*?|")
26610 (let ((pos (point))
26611 (noalign (looking-at "[^|\n\r]* |"))
26612 (c org-table-may-need-update))
26613 (replace-match (concat
26614 (substring (match-string 0) 1 -1)
26615 " |"))
26616 (goto-char pos)
26617 ;; noalign: if there were two spaces at the end, this field
26618 ;; does not determine the width of the column.
26619 (if noalign (setq org-table-may-need-update c)))
26620 (delete-char N))
26621 (delete-char N)
26622 (org-fix-tags-on-the-fly)))
26624 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26625 (put 'org-self-insert-command 'delete-selection t)
26626 (put 'orgtbl-self-insert-command 'delete-selection t)
26627 (put 'org-delete-char 'delete-selection 'supersede)
26628 (put 'org-delete-backward-char 'delete-selection 'supersede)
26630 ;; Make `flyspell-mode' delay after some commands
26631 (put 'org-self-insert-command 'flyspell-delayed t)
26632 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26633 (put 'org-delete-char 'flyspell-delayed t)
26634 (put 'org-delete-backward-char 'flyspell-delayed t)
26636 ;; Make pabbrev-mode expand after org-mode commands
26637 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26638 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26640 ;; How to do this: Measure non-white length of current string
26641 ;; If equal to column width, we should realign.
26643 (defun org-remap (map &rest commands)
26644 "In MAP, remap the functions given in COMMANDS.
26645 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26646 (let (new old)
26647 (while commands
26648 (setq old (pop commands) new (pop commands))
26649 (if (fboundp 'command-remapping)
26650 (org-defkey map (vector 'remap old) new)
26651 (substitute-key-definition old new map global-map)))))
26653 (when (eq org-enable-table-editor 'optimized)
26654 ;; If the user wants maximum table support, we need to hijack
26655 ;; some standard editing functions
26656 (org-remap org-mode-map
26657 'self-insert-command 'org-self-insert-command
26658 'delete-char 'org-delete-char
26659 'delete-backward-char 'org-delete-backward-char)
26660 (org-defkey org-mode-map "|" 'org-force-self-insert))
26662 (defun org-shiftcursor-error ()
26663 "Throw an error because Shift-Cursor command was applied in wrong context."
26664 (error "This command is active in special context like tables, headlines or timestamps"))
26666 (defun org-shifttab (&optional arg)
26667 "Global visibility cycling or move to previous table field.
26668 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26669 on context.
26670 See the individual commands for more information."
26671 (interactive "P")
26672 (cond
26673 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26674 (arg (message "Content view to level: ")
26675 (org-content (prefix-numeric-value arg))
26676 (setq org-cycle-global-status 'overview))
26677 (t (call-interactively 'org-global-cycle))))
26679 (defun org-shiftmetaleft ()
26680 "Promote subtree or delete table column.
26681 Calls `org-promote-subtree', `org-outdent-item',
26682 or `org-table-delete-column', depending on context.
26683 See the individual commands for more information."
26684 (interactive)
26685 (cond
26686 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26687 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26688 ((org-at-item-p) (call-interactively 'org-outdent-item))
26689 (t (org-shiftcursor-error))))
26691 (defun org-shiftmetaright ()
26692 "Demote subtree or insert table column.
26693 Calls `org-demote-subtree', `org-indent-item',
26694 or `org-table-insert-column', depending on context.
26695 See the individual commands for more information."
26696 (interactive)
26697 (cond
26698 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26699 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26700 ((org-at-item-p) (call-interactively 'org-indent-item))
26701 (t (org-shiftcursor-error))))
26703 (defun org-shiftmetaup (&optional arg)
26704 "Move subtree up or kill table row.
26705 Calls `org-move-subtree-up' or `org-table-kill-row' or
26706 `org-move-item-up' depending on context. See the individual commands
26707 for more information."
26708 (interactive "P")
26709 (cond
26710 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26711 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26712 ((org-at-item-p) (call-interactively 'org-move-item-up))
26713 (t (org-shiftcursor-error))))
26714 (defun org-shiftmetadown (&optional arg)
26715 "Move subtree down or insert table row.
26716 Calls `org-move-subtree-down' or `org-table-insert-row' or
26717 `org-move-item-down', depending on context. See the individual
26718 commands for more information."
26719 (interactive "P")
26720 (cond
26721 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26722 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26723 ((org-at-item-p) (call-interactively 'org-move-item-down))
26724 (t (org-shiftcursor-error))))
26726 (defun org-metaleft (&optional arg)
26727 "Promote heading or move table column to left.
26728 Calls `org-do-promote' or `org-table-move-column', depending on context.
26729 With no specific context, calls the Emacs default `backward-word'.
26730 See the individual commands for more information."
26731 (interactive "P")
26732 (cond
26733 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26734 ((or (org-on-heading-p) (org-region-active-p))
26735 (call-interactively 'org-do-promote))
26736 ((org-at-item-p) (call-interactively 'org-outdent-item))
26737 (t (call-interactively 'backward-word))))
26739 (defun org-metaright (&optional arg)
26740 "Demote subtree or move table column to right.
26741 Calls `org-do-demote' or `org-table-move-column', depending on context.
26742 With no specific context, calls the Emacs default `forward-word'.
26743 See the individual commands for more information."
26744 (interactive "P")
26745 (cond
26746 ((org-at-table-p) (call-interactively 'org-table-move-column))
26747 ((or (org-on-heading-p) (org-region-active-p))
26748 (call-interactively 'org-do-demote))
26749 ((org-at-item-p) (call-interactively 'org-indent-item))
26750 (t (call-interactively 'forward-word))))
26752 (defun org-metaup (&optional arg)
26753 "Move subtree up or move table row up.
26754 Calls `org-move-subtree-up' or `org-table-move-row' or
26755 `org-move-item-up', depending on context. See the individual commands
26756 for more information."
26757 (interactive "P")
26758 (cond
26759 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26760 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26761 ((org-at-item-p) (call-interactively 'org-move-item-up))
26762 (t (transpose-lines 1) (beginning-of-line -1))))
26764 (defun org-metadown (&optional arg)
26765 "Move subtree down or move table row down.
26766 Calls `org-move-subtree-down' or `org-table-move-row' or
26767 `org-move-item-down', depending on context. See the individual
26768 commands for more information."
26769 (interactive "P")
26770 (cond
26771 ((org-at-table-p) (call-interactively 'org-table-move-row))
26772 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26773 ((org-at-item-p) (call-interactively 'org-move-item-down))
26774 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26776 (defun org-shiftup (&optional arg)
26777 "Increase item in timestamp or increase priority of current headline.
26778 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26779 depending on context. See the individual commands for more information."
26780 (interactive "P")
26781 (cond
26782 ((org-at-timestamp-p t)
26783 (call-interactively (if org-edit-timestamp-down-means-later
26784 'org-timestamp-down 'org-timestamp-up)))
26785 ((org-on-heading-p) (call-interactively 'org-priority-up))
26786 ((org-at-item-p) (call-interactively 'org-previous-item))
26787 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26789 (defun org-shiftdown (&optional arg)
26790 "Decrease item in timestamp or decrease priority of current headline.
26791 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26792 depending on context. See the individual commands for more information."
26793 (interactive "P")
26794 (cond
26795 ((org-at-timestamp-p t)
26796 (call-interactively (if org-edit-timestamp-down-means-later
26797 'org-timestamp-up 'org-timestamp-down)))
26798 ((org-on-heading-p) (call-interactively 'org-priority-down))
26799 (t (call-interactively 'org-next-item))))
26801 (defun org-shiftright ()
26802 "Next TODO keyword or timestamp one day later, depending on context."
26803 (interactive)
26804 (cond
26805 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26806 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26807 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26808 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26809 (t (org-shiftcursor-error))))
26811 (defun org-shiftleft ()
26812 "Previous TODO keyword or timestamp one day earlier, depending on context."
26813 (interactive)
26814 (cond
26815 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26816 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26817 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26818 ((org-at-property-p)
26819 (call-interactively 'org-property-previous-allowed-value))
26820 (t (org-shiftcursor-error))))
26822 (defun org-shiftcontrolright ()
26823 "Switch to next TODO set."
26824 (interactive)
26825 (cond
26826 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26827 (t (org-shiftcursor-error))))
26829 (defun org-shiftcontrolleft ()
26830 "Switch to previous TODO set."
26831 (interactive)
26832 (cond
26833 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26834 (t (org-shiftcursor-error))))
26836 (defun org-ctrl-c-ret ()
26837 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26838 (interactive)
26839 (cond
26840 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26841 (t (call-interactively 'org-insert-heading))))
26843 (defun org-copy-special ()
26844 "Copy region in table or copy current subtree.
26845 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26846 See the individual commands for more information."
26847 (interactive)
26848 (call-interactively
26849 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26851 (defun org-cut-special ()
26852 "Cut region in table or cut current subtree.
26853 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26854 See the individual commands for more information."
26855 (interactive)
26856 (call-interactively
26857 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26859 (defun org-paste-special (arg)
26860 "Paste rectangular region into table, or past subtree relative to level.
26861 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26862 See the individual commands for more information."
26863 (interactive "P")
26864 (if (org-at-table-p)
26865 (org-table-paste-rectangle)
26866 (org-paste-subtree arg)))
26868 (defun org-ctrl-c-ctrl-c (&optional arg)
26869 "Set tags in headline, or update according to changed information at point.
26871 This command does many different things, depending on context:
26873 - If the cursor is in a headline, prompt for tags and insert them
26874 into the current line, aligned to `org-tags-column'. When called
26875 with prefix arg, realign all tags in the current buffer.
26877 - If the cursor is in one of the special #+KEYWORD lines, this
26878 triggers scanning the buffer for these lines and updating the
26879 information.
26881 - If the cursor is inside a table, realign the table. This command
26882 works even if the automatic table editor has been turned off.
26884 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26885 the entire table.
26887 - If the cursor is a the beginning of a dynamic block, update it.
26889 - If the cursor is inside a table created by the table.el package,
26890 activate that table.
26892 - If the current buffer is a remember buffer, close note and file it.
26893 with a prefix argument, file it without further interaction to the default
26894 location.
26896 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26897 links in this buffer.
26899 - If the cursor is on a numbered item in a plain list, renumber the
26900 ordered list.
26902 - If the cursor is on a checkbox, toggle it."
26903 (interactive "P")
26904 (let ((org-enable-table-editor t))
26905 (cond
26906 ((or org-clock-overlays
26907 org-occur-highlights
26908 org-latex-fragment-image-overlays)
26909 (org-remove-clock-overlays)
26910 (org-remove-occur-highlights)
26911 (org-remove-latex-fragment-image-overlays)
26912 (message "Temporary highlights/overlays removed from current buffer"))
26913 ((and (local-variable-p 'org-finish-function (current-buffer))
26914 (fboundp org-finish-function))
26915 (funcall org-finish-function))
26916 ((org-at-property-p)
26917 (call-interactively 'org-property-action))
26918 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
26919 ((org-on-heading-p) (call-interactively 'org-set-tags))
26920 ((org-at-table.el-p)
26921 (require 'table)
26922 (beginning-of-line 1)
26923 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
26924 (call-interactively 'table-recognize-table))
26925 ((org-at-table-p)
26926 (org-table-maybe-eval-formula)
26927 (if arg
26928 (call-interactively 'org-table-recalculate)
26929 (org-table-maybe-recalculate-line))
26930 (call-interactively 'org-table-align))
26931 ((org-at-item-checkbox-p)
26932 (call-interactively 'org-toggle-checkbox))
26933 ((org-at-item-p)
26934 (call-interactively 'org-maybe-renumber-ordered-list))
26935 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
26936 ;; Dynamic block
26937 (beginning-of-line 1)
26938 (org-update-dblock))
26939 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
26940 (cond
26941 ((equal (match-string 1) "TBLFM")
26942 ;; Recalculate the table before this line
26943 (save-excursion
26944 (beginning-of-line 1)
26945 (skip-chars-backward " \r\n\t")
26946 (if (org-at-table-p)
26947 (org-call-with-arg 'org-table-recalculate t))))
26949 (call-interactively 'org-mode-restart))))
26950 (t (error "C-c C-c can do nothing useful at this location.")))))
26952 (defun org-mode-restart ()
26953 "Restart Org-mode, to scan again for special lines.
26954 Also updates the keyword regular expressions."
26955 (interactive)
26956 (let ((org-inhibit-startup t)) (org-mode))
26957 (message "Org-mode restarted to refresh keyword and special line setup"))
26959 (defun org-kill-note-or-show-branches ()
26960 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
26961 (interactive)
26962 (if (not org-finish-function)
26963 (call-interactively 'show-branches)
26964 (let ((org-note-abort t))
26965 (funcall org-finish-function))))
26967 (defun org-return (&optional indent)
26968 "Goto next table row or insert a newline.
26969 Calls `org-table-next-row' or `newline', depending on context.
26970 See the individual commands for more information."
26971 (interactive)
26972 (cond
26973 ((bobp) (if indent (newline-and-indent) (newline)))
26974 ((and (org-at-heading-p)
26975 (looking-at
26976 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
26977 (org-show-entry)
26978 (end-of-line 1)
26979 (newline))
26980 ((org-at-table-p)
26981 (org-table-justify-field-maybe)
26982 (call-interactively 'org-table-next-row))
26983 (t (if indent (newline-and-indent) (newline)))))
26985 (defun org-return-indent ()
26986 (interactive)
26987 "Goto next table row or insert a newline and indent.
26988 Calls `org-table-next-row' or `newline-and-indent', depending on
26989 context. See the individual commands for more information."
26990 (org-return t))
26992 (defun org-ctrl-c-minus ()
26993 "Insert separator line in table or modify bullet type in list.
26994 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
26995 depending on context."
26996 (interactive)
26997 (cond
26998 ((org-at-table-p)
26999 (call-interactively 'org-table-insert-hline))
27000 ((org-on-heading-p)
27001 ;; Convert to item
27002 (save-excursion
27003 (beginning-of-line 1)
27004 (if (looking-at "\\*+ ")
27005 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27006 ((org-in-item-p)
27007 (call-interactively 'org-cycle-list-bullet))
27008 (t (error "`C-c -' does have no function here."))))
27010 (defun org-meta-return (&optional arg)
27011 "Insert a new heading or wrap a region in a table.
27012 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27013 See the individual commands for more information."
27014 (interactive "P")
27015 (cond
27016 ((org-at-table-p)
27017 (call-interactively 'org-table-wrap-region))
27018 (t (call-interactively 'org-insert-heading))))
27020 ;;; Menu entries
27022 ;; Define the Org-mode menus
27023 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27024 '("Tbl"
27025 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27026 ["Next Field" org-cycle (org-at-table-p)]
27027 ["Previous Field" org-shifttab (org-at-table-p)]
27028 ["Next Row" org-return (org-at-table-p)]
27029 "--"
27030 ["Blank Field" org-table-blank-field (org-at-table-p)]
27031 ["Edit Field" org-table-edit-field (org-at-table-p)]
27032 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27033 "--"
27034 ("Column"
27035 ["Move Column Left" org-metaleft (org-at-table-p)]
27036 ["Move Column Right" org-metaright (org-at-table-p)]
27037 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27038 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27039 ("Row"
27040 ["Move Row Up" org-metaup (org-at-table-p)]
27041 ["Move Row Down" org-metadown (org-at-table-p)]
27042 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27043 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27044 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27045 "--"
27046 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27047 ("Rectangle"
27048 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27049 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27050 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27051 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27052 "--"
27053 ("Calculate"
27054 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27055 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27056 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27057 "--"
27058 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27059 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27060 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27061 "--"
27062 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27063 "--"
27064 ["Sum Column/Rectangle" org-table-sum
27065 (or (org-at-table-p) (org-region-active-p))]
27066 ["Which Column?" org-table-current-column (org-at-table-p)])
27067 ["Debug Formulas"
27068 org-table-toggle-formula-debugger
27069 :style toggle :selected org-table-formula-debug]
27070 ["Show Col/Row Numbers"
27071 org-table-toggle-coordinate-overlays
27072 :style toggle :selected org-table-overlay-coordinates]
27073 "--"
27074 ["Create" org-table-create (and (not (org-at-table-p))
27075 org-enable-table-editor)]
27076 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27077 ["Import from File" org-table-import (not (org-at-table-p))]
27078 ["Export to File" org-table-export (org-at-table-p)]
27079 "--"
27080 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27082 (easy-menu-define org-org-menu org-mode-map "Org menu"
27083 '("Org"
27084 ("Show/Hide"
27085 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27086 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27087 ["Sparse Tree" org-occur t]
27088 ["Reveal Context" org-reveal t]
27089 ["Show All" show-all t]
27090 "--"
27091 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27092 "--"
27093 ["New Heading" org-insert-heading t]
27094 ("Navigate Headings"
27095 ["Up" outline-up-heading t]
27096 ["Next" outline-next-visible-heading t]
27097 ["Previous" outline-previous-visible-heading t]
27098 ["Next Same Level" outline-forward-same-level t]
27099 ["Previous Same Level" outline-backward-same-level t]
27100 "--"
27101 ["Jump" org-goto t])
27102 ("Edit Structure"
27103 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27104 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27105 "--"
27106 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27107 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27108 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27109 "--"
27110 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27111 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27112 ["Demote Heading" org-metaright (not (org-at-table-p))]
27113 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27114 "--"
27115 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27116 "--"
27117 ["Convert to odd levels" org-convert-to-odd-levels t]
27118 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27119 ("Editing"
27120 ["Emphasis..." org-emphasize t])
27121 ("Archive"
27122 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27123 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27124 ; :active t :keys "C-u C-c C-x C-a"]
27125 ["Sparse trees open ARCHIVE trees"
27126 (setq org-sparse-tree-open-archived-trees
27127 (not org-sparse-tree-open-archived-trees))
27128 :style toggle :selected org-sparse-tree-open-archived-trees]
27129 ["Cycling opens ARCHIVE trees"
27130 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27131 :style toggle :selected org-cycle-open-archived-trees]
27132 ["Agenda includes ARCHIVE trees"
27133 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27134 :style toggle :selected (not org-agenda-skip-archived-trees)]
27135 "--"
27136 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27137 ; ["Check and Move Children" (org-archive-subtree '(4))
27138 ; :active t :keys "C-u C-c C-x C-s"]
27140 "--"
27141 ("TODO Lists"
27142 ["TODO/DONE/-" org-todo t]
27143 ("Select keyword"
27144 ["Next keyword" org-shiftright (org-on-heading-p)]
27145 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27146 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27147 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27148 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27149 ["Show TODO Tree" org-show-todo-tree t]
27150 ["Global TODO list" org-todo-list t]
27151 "--"
27152 ["Set Priority" org-priority t]
27153 ["Priority Up" org-shiftup t]
27154 ["Priority Down" org-shiftdown t])
27155 ("TAGS and Properties"
27156 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27157 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27158 "--"
27159 ["Set property" 'org-set-property t]
27160 ["Column view of properties" org-columns t]
27161 ["Insert Column View DBlock" org-insert-columns-dblock t])
27162 ("Dates and Scheduling"
27163 ["Timestamp" org-time-stamp t]
27164 ["Timestamp (inactive)" org-time-stamp-inactive t]
27165 ("Change Date"
27166 ["1 Day Later" org-shiftright t]
27167 ["1 Day Earlier" org-shiftleft t]
27168 ["1 ... Later" org-shiftup t]
27169 ["1 ... Earlier" org-shiftdown t])
27170 ["Compute Time Range" org-evaluate-time-range t]
27171 ["Schedule Item" org-schedule t]
27172 ["Deadline" org-deadline t]
27173 "--"
27174 ["Custom time format" org-toggle-time-stamp-overlays
27175 :style radio :selected org-display-custom-times]
27176 "--"
27177 ["Goto Calendar" org-goto-calendar t]
27178 ["Date from Calendar" org-date-from-calendar t])
27179 ("Logging work"
27180 ["Clock in" org-clock-in t]
27181 ["Clock out" org-clock-out t]
27182 ["Clock cancel" org-clock-cancel t]
27183 ["Goto running clock" org-clock-goto t]
27184 ["Display times" org-clock-display t]
27185 ["Create clock table" org-clock-report t]
27186 "--"
27187 ["Record DONE time"
27188 (progn (setq org-log-done (not org-log-done))
27189 (message "Switching to %s will %s record a timestamp"
27190 (car org-done-keywords)
27191 (if org-log-done "automatically" "not")))
27192 :style toggle :selected org-log-done])
27193 "--"
27194 ["Agenda Command..." org-agenda t]
27195 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27196 ("File List for Agenda")
27197 ("Special views current file"
27198 ["TODO Tree" org-show-todo-tree t]
27199 ["Check Deadlines" org-check-deadlines t]
27200 ["Timeline" org-timeline t]
27201 ["Tags Tree" org-tags-sparse-tree t])
27202 "--"
27203 ("Hyperlinks"
27204 ["Store Link (Global)" org-store-link t]
27205 ["Insert Link" org-insert-link t]
27206 ["Follow Link" org-open-at-point t]
27207 "--"
27208 ["Next link" org-next-link t]
27209 ["Previous link" org-previous-link t]
27210 "--"
27211 ["Descriptive Links"
27212 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27213 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27214 ["Literal Links"
27215 (progn
27216 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27217 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27218 "--"
27219 ["Export/Publish..." org-export t]
27220 ("LaTeX"
27221 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27222 :selected org-cdlatex-mode]
27223 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27224 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27225 ["Modify math symbol" org-cdlatex-math-modify
27226 (org-inside-LaTeX-fragment-p)]
27227 ["Export LaTeX fragments as images"
27228 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27229 :style toggle :selected org-export-with-LaTeX-fragments])
27230 "--"
27231 ("Documentation"
27232 ["Show Version" org-version t]
27233 ["Info Documentation" org-info t])
27234 ("Customize"
27235 ["Browse Org Group" org-customize t]
27236 "--"
27237 ["Expand This Menu" org-create-customize-menu
27238 (fboundp 'customize-menu-create)])
27239 "--"
27240 ["Refresh setup" org-mode-restart t]
27243 (defun org-info (&optional node)
27244 "Read documentation for Org-mode in the info system.
27245 With optional NODE, go directly to that node."
27246 (interactive)
27247 (require 'info)
27248 (Info-goto-node (format "(org)%s" (or node ""))))
27250 (defun org-install-agenda-files-menu ()
27251 (let ((bl (buffer-list)))
27252 (save-excursion
27253 (while bl
27254 (set-buffer (pop bl))
27255 (if (org-mode-p) (setq bl nil)))
27256 (when (org-mode-p)
27257 (easy-menu-change
27258 '("Org") "File List for Agenda"
27259 (append
27260 (list
27261 ["Edit File List" (org-edit-agenda-file-list) t]
27262 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27263 ["Remove Current File from List" org-remove-file t]
27264 ["Cycle through agenda files" org-cycle-agenda-files t]
27265 ["Occur in all agenda files" org-occur-in-agenda-files t]
27266 "--")
27267 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27269 ;;;; Documentation
27271 (defun org-customize ()
27272 "Call the customize function with org as argument."
27273 (interactive)
27274 (customize-browse 'org))
27276 (defun org-create-customize-menu ()
27277 "Create a full customization menu for Org-mode, insert it into the menu."
27278 (interactive)
27279 (if (fboundp 'customize-menu-create)
27280 (progn
27281 (easy-menu-change
27282 '("Org") "Customize"
27283 `(["Browse Org group" org-customize t]
27284 "--"
27285 ,(customize-menu-create 'org)
27286 ["Set" Custom-set t]
27287 ["Save" Custom-save t]
27288 ["Reset to Current" Custom-reset-current t]
27289 ["Reset to Saved" Custom-reset-saved t]
27290 ["Reset to Standard Settings" Custom-reset-standard t]))
27291 (message "\"Org\"-menu now contains full customization menu"))
27292 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27294 ;;;; Miscellaneous stuff
27297 ;;; Generally useful functions
27299 (defun org-context ()
27300 "Return a list of contexts of the current cursor position.
27301 If several contexts apply, all are returned.
27302 Each context entry is a list with a symbol naming the context, and
27303 two positions indicating start and end of the context. Possible
27304 contexts are:
27306 :headline anywhere in a headline
27307 :headline-stars on the leading stars in a headline
27308 :todo-keyword on a TODO keyword (including DONE) in a headline
27309 :tags on the TAGS in a headline
27310 :priority on the priority cookie in a headline
27311 :item on the first line of a plain list item
27312 :item-bullet on the bullet/number of a plain list item
27313 :checkbox on the checkbox in a plain list item
27314 :table in an org-mode table
27315 :table-special on a special filed in a table
27316 :table-table in a table.el table
27317 :link on a hyperlink
27318 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27319 :target on a <<target>>
27320 :radio-target on a <<<radio-target>>>
27321 :latex-fragment on a LaTeX fragment
27322 :latex-preview on a LaTeX fragment with overlayed preview image
27324 This function expects the position to be visible because it uses font-lock
27325 faces as a help to recognize the following contexts: :table-special, :link,
27326 and :keyword."
27327 (let* ((f (get-text-property (point) 'face))
27328 (faces (if (listp f) f (list f)))
27329 (p (point)) clist o)
27330 ;; First the large context
27331 (cond
27332 ((org-on-heading-p t)
27333 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27334 (when (progn
27335 (beginning-of-line 1)
27336 (looking-at org-todo-line-tags-regexp))
27337 (push (org-point-in-group p 1 :headline-stars) clist)
27338 (push (org-point-in-group p 2 :todo-keyword) clist)
27339 (push (org-point-in-group p 4 :tags) clist))
27340 (goto-char p)
27341 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27342 (if (looking-at "\\[#[A-Z0-9]\\]")
27343 (push (org-point-in-group p 0 :priority) clist)))
27345 ((org-at-item-p)
27346 (push (org-point-in-group p 2 :item-bullet) clist)
27347 (push (list :item (point-at-bol)
27348 (save-excursion (org-end-of-item) (point)))
27349 clist)
27350 (and (org-at-item-checkbox-p)
27351 (push (org-point-in-group p 0 :checkbox) clist)))
27353 ((org-at-table-p)
27354 (push (list :table (org-table-begin) (org-table-end)) clist)
27355 (if (memq 'org-formula faces)
27356 (push (list :table-special
27357 (previous-single-property-change p 'face)
27358 (next-single-property-change p 'face)) clist)))
27359 ((org-at-table-p 'any)
27360 (push (list :table-table) clist)))
27361 (goto-char p)
27363 ;; Now the small context
27364 (cond
27365 ((org-at-timestamp-p)
27366 (push (org-point-in-group p 0 :timestamp) clist))
27367 ((memq 'org-link faces)
27368 (push (list :link
27369 (previous-single-property-change p 'face)
27370 (next-single-property-change p 'face)) clist))
27371 ((memq 'org-special-keyword faces)
27372 (push (list :keyword
27373 (previous-single-property-change p 'face)
27374 (next-single-property-change p 'face)) clist))
27375 ((org-on-target-p)
27376 (push (org-point-in-group p 0 :target) clist)
27377 (goto-char (1- (match-beginning 0)))
27378 (if (looking-at org-radio-target-regexp)
27379 (push (org-point-in-group p 0 :radio-target) clist))
27380 (goto-char p))
27381 ((setq o (car (delq nil
27382 (mapcar
27383 (lambda (x)
27384 (if (memq x org-latex-fragment-image-overlays) x))
27385 (org-overlays-at (point))))))
27386 (push (list :latex-fragment
27387 (org-overlay-start o) (org-overlay-end o)) clist)
27388 (push (list :latex-preview
27389 (org-overlay-start o) (org-overlay-end o)) clist))
27390 ((org-inside-LaTeX-fragment-p)
27391 ;; FIXME: positions wrong.
27392 (push (list :latex-fragment (point) (point)) clist)))
27394 (setq clist (nreverse (delq nil clist)))
27395 clist))
27397 ;; FIXME: Compare with at-regexp-p Do we need both?
27398 (defun org-in-regexp (re &optional nlines visually)
27399 "Check if point is inside a match of regexp.
27400 Normally only the current line is checked, but you can include NLINES extra
27401 lines both before and after point into the search.
27402 If VISUALLY is set, require that the cursor is not after the match but
27403 really on, so that the block visually is on the match."
27404 (catch 'exit
27405 (let ((pos (point))
27406 (eol (point-at-eol (+ 1 (or nlines 0))))
27407 (inc (if visually 1 0)))
27408 (save-excursion
27409 (beginning-of-line (- 1 (or nlines 0)))
27410 (while (re-search-forward re eol t)
27411 (if (and (<= (match-beginning 0) pos)
27412 (>= (+ inc (match-end 0)) pos))
27413 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27415 (defun org-at-regexp-p (regexp)
27416 "Is point inside a match of REGEXP in the current line?"
27417 (catch 'exit
27418 (save-excursion
27419 (let ((pos (point)) (end (point-at-eol)))
27420 (beginning-of-line 1)
27421 (while (re-search-forward regexp end t)
27422 (if (and (<= (match-beginning 0) pos)
27423 (>= (match-end 0) pos))
27424 (throw 'exit t)))
27425 nil))))
27427 (defun org-occur-in-agenda-files (regexp &optional nlines)
27428 "Call `multi-occur' with buffers for all agenda files."
27429 (interactive "sOrg-files matching: \np")
27430 (let* ((files (org-agenda-files))
27431 (tnames (mapcar 'file-truename files))
27432 (extra org-agenda-multi-occur-extra-files)
27434 (while (setq f (pop extra))
27435 (unless (member (file-truename f) tnames)
27436 (add-to-list 'files f 'append)
27437 (add-to-list 'tnames (file-truename f) 'append)))
27438 (multi-occur
27439 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27440 regexp)))
27442 (if (boundp 'occur-mode-find-occurrence-hook)
27443 ;; Emacs 23
27444 (add-hook 'occur-mode-find-occurrence-hook
27445 (lambda ()
27446 (when (org-mode-p)
27447 (org-reveal))))
27448 ;; Emacs 22
27449 (defadvice occur-mode-goto-occurrence
27450 (after org-occur-reveal activate)
27451 (and (org-mode-p) (org-reveal)))
27452 (defadvice occur-mode-goto-occurrence-other-window
27453 (after org-occur-reveal activate)
27454 (and (org-mode-p) (org-reveal)))
27455 (defadvice occur-mode-display-occurrence
27456 (after org-occur-reveal activate)
27457 (when (org-mode-p)
27458 (let ((pos (occur-mode-find-occurrence)))
27459 (with-current-buffer (marker-buffer pos)
27460 (save-excursion
27461 (goto-char pos)
27462 (org-reveal)))))))
27464 (defun org-uniquify (list)
27465 "Remove duplicate elements from LIST."
27466 (let (res)
27467 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27468 res))
27470 (defun org-delete-all (elts list)
27471 "Remove all elements in ELTS from LIST."
27472 (while elts
27473 (setq list (delete (pop elts) list)))
27474 list)
27476 (defun org-back-over-empty-lines ()
27477 "Move backwards over witespace, to the beginning of the first empty line.
27478 Returns the number o empty lines passed."
27479 (let ((pos (point)))
27480 (skip-chars-backward " \t\n\r")
27481 (beginning-of-line 2)
27482 (goto-char (min (point) pos))
27483 (count-lines (point) pos)))
27485 (defun org-skip-whitespace ()
27486 (skip-chars-forward " \t\n\r"))
27488 (defun org-point-in-group (point group &optional context)
27489 "Check if POINT is in match-group GROUP.
27490 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27491 match. If the match group does ot exist or point is not inside it,
27492 return nil."
27493 (and (match-beginning group)
27494 (>= point (match-beginning group))
27495 (<= point (match-end group))
27496 (if context
27497 (list context (match-beginning group) (match-end group))
27498 t)))
27500 (defun org-switch-to-buffer-other-window (&rest args)
27501 "Switch to buffer in a second window on the current frame.
27502 In particular, do not allow pop-up frames."
27503 (let (pop-up-frames special-display-buffer-names special-display-regexps
27504 special-display-function)
27505 (apply 'switch-to-buffer-other-window args)))
27507 (defun org-combine-plists (&rest plists)
27508 "Create a single property list from all plists in PLISTS.
27509 The process starts by copying the first list, and then setting properties
27510 from the other lists. Settings in the last list are the most significant
27511 ones and overrule settings in the other lists."
27512 (let ((rtn (copy-sequence (pop plists)))
27513 p v ls)
27514 (while plists
27515 (setq ls (pop plists))
27516 (while ls
27517 (setq p (pop ls) v (pop ls))
27518 (setq rtn (plist-put rtn p v))))
27519 rtn))
27521 (defun org-move-line-down (arg)
27522 "Move the current line down. With prefix argument, move it past ARG lines."
27523 (interactive "p")
27524 (let ((col (current-column))
27525 beg end pos)
27526 (beginning-of-line 1) (setq beg (point))
27527 (beginning-of-line 2) (setq end (point))
27528 (beginning-of-line (+ 1 arg))
27529 (setq pos (move-marker (make-marker) (point)))
27530 (insert (delete-and-extract-region beg end))
27531 (goto-char pos)
27532 (move-to-column col)))
27534 (defun org-move-line-up (arg)
27535 "Move the current line up. With prefix argument, move it past ARG lines."
27536 (interactive "p")
27537 (let ((col (current-column))
27538 beg end pos)
27539 (beginning-of-line 1) (setq beg (point))
27540 (beginning-of-line 2) (setq end (point))
27541 (beginning-of-line (- arg))
27542 (setq pos (move-marker (make-marker) (point)))
27543 (insert (delete-and-extract-region beg end))
27544 (goto-char pos)
27545 (move-to-column col)))
27547 (defun org-replace-escapes (string table)
27548 "Replace %-escapes in STRING with values in TABLE.
27549 TABLE is an association list with keys like \"%a\" and string values.
27550 The sequences in STRING may contain normal field width and padding information,
27551 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27552 so values can contain further %-escapes if they are define later in TABLE."
27553 (let ((case-fold-search nil)
27554 e re rpl)
27555 (while (setq e (pop table))
27556 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27557 (while (string-match re string)
27558 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27559 (cdr e)))
27560 (setq string (replace-match rpl t t string))))
27561 string))
27564 (defun org-sublist (list start end)
27565 "Return a section of LIST, from START to END.
27566 Counting starts at 1."
27567 (let (rtn (c start))
27568 (setq list (nthcdr (1- start) list))
27569 (while (and list (<= c end))
27570 (push (pop list) rtn)
27571 (setq c (1+ c)))
27572 (nreverse rtn)))
27574 (defun org-find-base-buffer-visiting (file)
27575 "Like `find-buffer-visiting' but alway return the base buffer and
27576 not an indirect buffer"
27577 (let ((buf (find-buffer-visiting file)))
27578 (if buf
27579 (or (buffer-base-buffer buf) buf)
27580 nil)))
27582 (defun org-image-file-name-regexp ()
27583 "Return regexp matching the file names of images."
27584 (if (fboundp 'image-file-name-regexp)
27585 (image-file-name-regexp)
27586 (let ((image-file-name-extensions
27587 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27588 "xbm" "xpm" "pbm" "pgm" "ppm")))
27589 (concat "\\."
27590 (regexp-opt (nconc (mapcar 'upcase
27591 image-file-name-extensions)
27592 image-file-name-extensions)
27594 "\\'"))))
27596 (defun org-file-image-p (file)
27597 "Return non-nil if FILE is an image."
27598 (save-match-data
27599 (string-match (org-image-file-name-regexp) file)))
27601 ;;; Paragraph filling stuff.
27602 ;; We want this to be just right, so use the full arsenal.
27604 (defun org-indent-line-function ()
27605 "Indent line like previous, but further if previous was headline or item."
27606 (interactive)
27607 (let* ((pos (point))
27608 (itemp (org-at-item-p))
27609 column bpos bcol tpos tcol bullet btype bullet-type)
27610 ;; Find the previous relevant line
27611 (beginning-of-line 1)
27612 (cond
27613 ((looking-at "#") (setq column 0))
27614 ((looking-at "\\*+ ") (setq column 0))
27616 (beginning-of-line 0)
27617 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27618 (beginning-of-line 0))
27619 (cond
27620 ((looking-at "\\*+[ \t]+")
27621 (goto-char (match-end 0))
27622 (setq column (current-column)))
27623 ((org-in-item-p)
27624 (org-beginning-of-item)
27625 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27626 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27627 (setq bpos (match-beginning 1) tpos (match-end 0)
27628 bcol (progn (goto-char bpos) (current-column))
27629 tcol (progn (goto-char tpos) (current-column))
27630 bullet (match-string 1)
27631 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27632 (if (not itemp)
27633 (setq column tcol)
27634 (goto-char pos)
27635 (beginning-of-line 1)
27636 (if (looking-at "\\S-")
27637 (progn
27638 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27639 (setq bullet (match-string 1)
27640 btype (if (string-match "[0-9]" bullet) "n" bullet))
27641 (setq column (if (equal btype bullet-type) bcol tcol)))
27642 (setq column (org-get-indentation)))))
27643 (t (setq column (org-get-indentation))))))
27644 (goto-char pos)
27645 (if (<= (current-column) (current-indentation))
27646 (indent-line-to column)
27647 (save-excursion (indent-line-to column)))
27648 (setq column (current-column))
27649 (beginning-of-line 1)
27650 (if (looking-at
27651 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27652 (replace-match (concat "\\1" (format org-property-format
27653 (match-string 2) (match-string 3)))
27654 t nil))
27655 (move-to-column column)))
27657 (defun org-set-autofill-regexps ()
27658 (interactive)
27659 ;; In the paragraph separator we include headlines, because filling
27660 ;; text in a line directly attached to a headline would otherwise
27661 ;; fill the headline as well.
27662 (org-set-local 'comment-start-skip "^#+[ \t]*")
27663 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27664 ;; The paragraph starter includes hand-formatted lists.
27665 (org-set-local 'paragraph-start
27666 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27667 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27668 ;; But only if the user has not turned off tables or fixed-width regions
27669 (org-set-local
27670 'auto-fill-inhibit-regexp
27671 (concat "\\*+ \\|#\\+"
27672 "\\|[ \t]*" org-keyword-time-regexp
27673 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27674 (concat
27675 "\\|[ \t]*["
27676 (if org-enable-table-editor "|" "")
27677 (if org-enable-fixed-width-editor ":" "")
27678 "]"))))
27679 ;; We use our own fill-paragraph function, to make sure that tables
27680 ;; and fixed-width regions are not wrapped. That function will pass
27681 ;; through to `fill-paragraph' when appropriate.
27682 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27683 ; Adaptive filling: To get full control, first make sure that
27684 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27685 (org-set-local 'adaptive-fill-regexp "\000")
27686 (org-set-local 'adaptive-fill-function
27687 'org-adaptive-fill-function)
27688 (org-set-local
27689 'align-mode-rules-list
27690 '((org-in-buffer-settings
27691 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
27692 (modes . '(org-mode))))))
27694 (defun org-fill-paragraph (&optional justify)
27695 "Re-align a table, pass through to fill-paragraph if no table."
27696 (let ((table-p (org-at-table-p))
27697 (table.el-p (org-at-table.el-p)))
27698 (cond ((and (equal (char-after (point-at-bol)) ?*)
27699 (save-excursion (goto-char (point-at-bol))
27700 (looking-at outline-regexp)))
27701 t) ; skip headlines
27702 (table.el-p t) ; skip table.el tables
27703 (table-p (org-table-align) t) ; align org-mode tables
27704 (t nil)))) ; call paragraph-fill
27706 ;; For reference, this is the default value of adaptive-fill-regexp
27707 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27709 (defun org-adaptive-fill-function ()
27710 "Return a fill prefix for org-mode files.
27711 In particular, this makes sure hanging paragraphs for hand-formatted lists
27712 work correctly."
27713 (cond ((looking-at "#[ \t]+")
27714 (match-string 0))
27715 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27716 (save-excursion
27717 (goto-char (match-end 0))
27718 (make-string (current-column) ?\ )))
27719 (t nil)))
27721 ;;;; Functions extending outline functionality
27724 (defun org-beginning-of-line (&optional arg)
27725 "Go to the beginning of the current line. If that is invisible, continue
27726 to a visible line beginning. This makes the function of C-a more intuitive.
27727 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27728 first attempt, and only move to after the tags when the cursor is already
27729 beyond the end of the headline."
27730 (interactive "P")
27731 (let ((pos (point)))
27732 (beginning-of-line 1)
27733 (if (bobp)
27735 (backward-char 1)
27736 (if (org-invisible-p)
27737 (while (and (not (bobp)) (org-invisible-p))
27738 (backward-char 1)
27739 (beginning-of-line 1))
27740 (forward-char 1)))
27741 (when org-special-ctrl-a/e
27742 (cond
27743 ((and (looking-at org-todo-line-regexp)
27744 (= (char-after (match-end 1)) ?\ ))
27745 (goto-char
27746 (if (eq org-special-ctrl-a/e t)
27747 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27748 ((= pos (point)) (match-beginning 3))
27749 (t (point)))
27750 (cond ((> pos (point)) (point))
27751 ((not (eq last-command this-command)) (point))
27752 (t (match-beginning 3))))))
27753 ((org-at-item-p)
27754 (goto-char
27755 (if (eq org-special-ctrl-a/e t)
27756 (cond ((> pos (match-end 4)) (match-end 4))
27757 ((= pos (point)) (match-end 4))
27758 (t (point)))
27759 (cond ((> pos (point)) (point))
27760 ((not (eq last-command this-command)) (point))
27761 (t (match-end 4))))))))))
27763 (defun org-end-of-line (&optional arg)
27764 "Go to the end of the line.
27765 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27766 first attempt, and only move to after the tags when the cursor is already
27767 beyond the end of the headline."
27768 (interactive "P")
27769 (if (or (not org-special-ctrl-a/e)
27770 (not (org-on-heading-p)))
27771 (end-of-line arg)
27772 (let ((pos (point)))
27773 (beginning-of-line 1)
27774 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27775 (if (eq org-special-ctrl-a/e t)
27776 (if (or (< pos (match-beginning 1))
27777 (= pos (match-end 0)))
27778 (goto-char (match-beginning 1))
27779 (goto-char (match-end 0)))
27780 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27781 (goto-char (match-end 0))
27782 (goto-char (match-beginning 1))))
27783 (end-of-line arg)))))
27785 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27786 (define-key org-mode-map "\C-e" 'org-end-of-line)
27788 (defun org-kill-line (&optional arg)
27789 "Kill line, to tags or end of line."
27790 (interactive "P")
27791 (cond
27792 ((or (not org-special-ctrl-k)
27793 (bolp)
27794 (not (org-on-heading-p)))
27795 (call-interactively 'kill-line))
27796 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
27797 (kill-region (point) (match-beginning 1))
27798 (org-set-tags nil t))
27799 (t (kill-region (point) (point-at-eol)))))
27801 (define-key org-mode-map "\C-k" 'org-kill-line)
27803 (defun org-invisible-p ()
27804 "Check if point is at a character currently not visible."
27805 ;; Early versions of noutline don't have `outline-invisible-p'.
27806 (if (fboundp 'outline-invisible-p)
27807 (outline-invisible-p)
27808 (get-char-property (point) 'invisible)))
27810 (defun org-invisible-p2 ()
27811 "Check if point is at a character currently not visible."
27812 (save-excursion
27813 (if (and (eolp) (not (bobp))) (backward-char 1))
27814 ;; Early versions of noutline don't have `outline-invisible-p'.
27815 (if (fboundp 'outline-invisible-p)
27816 (outline-invisible-p)
27817 (get-char-property (point) 'invisible))))
27819 (defalias 'org-back-to-heading 'outline-back-to-heading)
27820 (defalias 'org-on-heading-p 'outline-on-heading-p)
27821 (defalias 'org-at-heading-p 'outline-on-heading-p)
27822 (defun org-at-heading-or-item-p ()
27823 (or (org-on-heading-p) (org-at-item-p)))
27825 (defun org-on-target-p ()
27826 (or (org-in-regexp org-radio-target-regexp)
27827 (org-in-regexp org-target-regexp)))
27829 (defun org-up-heading-all (arg)
27830 "Move to the heading line of which the present line is a subheading.
27831 This function considers both visible and invisible heading lines.
27832 With argument, move up ARG levels."
27833 (if (fboundp 'outline-up-heading-all)
27834 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27835 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27837 (defun org-up-heading-safe ()
27838 "Move to the heading line of which the present line is a subheading.
27839 This version will not throw an error. It will return the level of the
27840 headline found, or nil if no higher level is found."
27841 (let ((pos (point)) start-level level
27842 (re (concat "^" outline-regexp)))
27843 (catch 'exit
27844 (outline-back-to-heading t)
27845 (setq start-level (funcall outline-level))
27846 (if (equal start-level 1) (throw 'exit nil))
27847 (while (re-search-backward re nil t)
27848 (setq level (funcall outline-level))
27849 (if (< level start-level) (throw 'exit level)))
27850 nil)))
27852 (defun org-first-sibling-p ()
27853 "Is this heading the first child of its parents?"
27854 (interactive)
27855 (let ((re (concat "^" outline-regexp))
27856 level l)
27857 (unless (org-at-heading-p t)
27858 (error "Not at a heading"))
27859 (setq level (funcall outline-level))
27860 (save-excursion
27861 (if (not (re-search-backward re nil t))
27863 (setq l (funcall outline-level))
27864 (< l level)))))
27866 (defun org-goto-sibling (&optional previous)
27867 "Goto the next sibling, even if it is invisible.
27868 When PREVIOUS is set, go to the previous sibling instead. Returns t
27869 when a sibling was found. When none is found, return nil and don't
27870 move point."
27871 (let ((fun (if previous 're-search-backward 're-search-forward))
27872 (pos (point))
27873 (re (concat "^" outline-regexp))
27874 level l)
27875 (when (condition-case nil (org-back-to-heading t) (error nil))
27876 (setq level (funcall outline-level))
27877 (catch 'exit
27878 (or previous (forward-char 1))
27879 (while (funcall fun re nil t)
27880 (setq l (funcall outline-level))
27881 (when (< l level) (goto-char pos) (throw 'exit nil))
27882 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27883 (goto-char pos)
27884 nil))))
27886 (defun org-show-siblings ()
27887 "Show all siblings of the current headline."
27888 (save-excursion
27889 (while (org-goto-sibling) (org-flag-heading nil)))
27890 (save-excursion
27891 (while (org-goto-sibling 'previous)
27892 (org-flag-heading nil))))
27894 (defun org-show-hidden-entry ()
27895 "Show an entry where even the heading is hidden."
27896 (save-excursion
27897 (org-show-entry)))
27899 (defun org-flag-heading (flag &optional entry)
27900 "Flag the current heading. FLAG non-nil means make invisible.
27901 When ENTRY is non-nil, show the entire entry."
27902 (save-excursion
27903 (org-back-to-heading t)
27904 ;; Check if we should show the entire entry
27905 (if entry
27906 (progn
27907 (org-show-entry)
27908 (save-excursion
27909 (and (outline-next-heading)
27910 (org-flag-heading nil))))
27911 (outline-flag-region (max (point-min) (1- (point)))
27912 (save-excursion (outline-end-of-heading) (point))
27913 flag))))
27915 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27916 ;; This is an exact copy of the original function, but it uses
27917 ;; `org-back-to-heading', to make it work also in invisible
27918 ;; trees. And is uses an invisible-OK argument.
27919 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
27920 (org-back-to-heading invisible-OK)
27921 (let ((first t)
27922 (level (funcall outline-level)))
27923 (while (and (not (eobp))
27924 (or first (> (funcall outline-level) level)))
27925 (setq first nil)
27926 (outline-next-heading))
27927 (unless to-heading
27928 (if (memq (preceding-char) '(?\n ?\^M))
27929 (progn
27930 ;; Go to end of line before heading
27931 (forward-char -1)
27932 (if (memq (preceding-char) '(?\n ?\^M))
27933 ;; leave blank line before heading
27934 (forward-char -1))))))
27935 (point))
27937 (defun org-show-subtree ()
27938 "Show everything after this heading at deeper levels."
27939 (outline-flag-region
27940 (point)
27941 (save-excursion
27942 (outline-end-of-subtree) (outline-next-heading) (point))
27943 nil))
27945 (defun org-show-entry ()
27946 "Show the body directly following this heading.
27947 Show the heading too, if it is currently invisible."
27948 (interactive)
27949 (save-excursion
27950 (condition-case nil
27951 (progn
27952 (org-back-to-heading t)
27953 (outline-flag-region
27954 (max (point-min) (1- (point)))
27955 (save-excursion
27956 (re-search-forward
27957 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
27958 (or (match-beginning 1) (point-max)))
27959 nil))
27960 (error nil))))
27962 (defun org-make-options-regexp (kwds)
27963 "Make a regular expression for keyword lines."
27964 (concat
27966 "#?[ \t]*\\+\\("
27967 (mapconcat 'regexp-quote kwds "\\|")
27968 "\\):[ \t]*"
27969 "\\(.+\\)"))
27971 ;; Make isearch reveal the necessary context
27972 (defun org-isearch-end ()
27973 "Reveal context after isearch exits."
27974 (when isearch-success ; only if search was successful
27975 (if (featurep 'xemacs)
27976 ;; Under XEmacs, the hook is run in the correct place,
27977 ;; we directly show the context.
27978 (org-show-context 'isearch)
27979 ;; In Emacs the hook runs *before* restoring the overlays.
27980 ;; So we have to use a one-time post-command-hook to do this.
27981 ;; (Emacs 22 has a special variable, see function `org-mode')
27982 (unless (and (boundp 'isearch-mode-end-hook-quit)
27983 isearch-mode-end-hook-quit)
27984 ;; Only when the isearch was not quitted.
27985 (org-add-hook 'post-command-hook 'org-isearch-post-command
27986 'append 'local)))))
27988 (defun org-isearch-post-command ()
27989 "Remove self from hook, and show context."
27990 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
27991 (org-show-context 'isearch))
27994 ;;;; Integration with and fixes for other packages
27996 ;;; Imenu support
27998 (defvar org-imenu-markers nil
27999 "All markers currently used by Imenu.")
28000 (make-variable-buffer-local 'org-imenu-markers)
28002 (defun org-imenu-new-marker (&optional pos)
28003 "Return a new marker for use by Imenu, and remember the marker."
28004 (let ((m (make-marker)))
28005 (move-marker m (or pos (point)))
28006 (push m org-imenu-markers)
28009 (defun org-imenu-get-tree ()
28010 "Produce the index for Imenu."
28011 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28012 (setq org-imenu-markers nil)
28013 (let* ((n org-imenu-depth)
28014 (re (concat "^" outline-regexp))
28015 (subs (make-vector (1+ n) nil))
28016 (last-level 0)
28017 m tree level head)
28018 (save-excursion
28019 (save-restriction
28020 (widen)
28021 (goto-char (point-max))
28022 (while (re-search-backward re nil t)
28023 (setq level (org-reduced-level (funcall outline-level)))
28024 (when (<= level n)
28025 (looking-at org-complex-heading-regexp)
28026 (setq head (org-match-string-no-properties 4)
28027 m (org-imenu-new-marker))
28028 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28029 (if (>= level last-level)
28030 (push (cons head m) (aref subs level))
28031 (push (cons head (aref subs (1+ level))) (aref subs level))
28032 (loop for i from (1+ level) to n do (aset subs i nil)))
28033 (setq last-level level)))))
28034 (aref subs 1)))
28036 (eval-after-load "imenu"
28037 '(progn
28038 (add-hook 'imenu-after-jump-hook
28039 (lambda () (org-show-context 'org-goto)))))
28041 ;; Speedbar support
28043 (defun org-speedbar-set-agenda-restriction ()
28044 "Restrict future agenda commands to the location at point in speedbar.
28045 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28046 (interactive)
28047 (let (p m tp np dir txt w)
28048 (cond
28049 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28050 'org-imenu t))
28051 (setq m (get-text-property p 'org-imenu-marker))
28052 (save-excursion
28053 (save-restriction
28054 (set-buffer (marker-buffer m))
28055 (goto-char m)
28056 (org-agenda-set-restriction-lock 'subtree))))
28057 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28058 'speedbar-function 'speedbar-find-file))
28059 (setq tp (previous-single-property-change
28060 (1+ p) 'speedbar-function)
28061 np (next-single-property-change
28062 tp 'speedbar-function)
28063 dir (speedbar-line-directory)
28064 txt (buffer-substring-no-properties (or tp (point-min))
28065 (or np (point-max))))
28066 (save-excursion
28067 (save-restriction
28068 (set-buffer (find-file-noselect
28069 (let ((default-directory dir))
28070 (expand-file-name txt))))
28071 (unless (org-mode-p)
28072 (error "Cannot restrict to non-Org-mode file"))
28073 (org-agenda-set-restriction-lock 'file))))
28074 (t (error "Don't know how to restrict Org-mode's agenda")))
28075 (org-move-overlay org-speedbar-restriction-lock-overlay
28076 (point-at-bol) (point-at-eol))
28077 (setq current-prefix-arg nil)
28078 (org-agenda-maybe-redo)))
28080 (eval-after-load "speedbar"
28081 '(progn
28082 (speedbar-add-supported-extension ".org")
28083 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28084 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28085 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28086 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28087 (add-hook 'speedbar-visiting-tag-hook
28088 (lambda () (org-show-context 'org-goto)))))
28091 ;;; Fixes and Hacks
28093 ;; Make flyspell not check words in links, to not mess up our keymap
28094 (defun org-mode-flyspell-verify ()
28095 "Don't let flyspell put overlays at active buttons."
28096 (not (get-text-property (point) 'keymap)))
28098 ;; Make `bookmark-jump' show the jump location if it was hidden.
28099 (eval-after-load "bookmark"
28100 '(if (boundp 'bookmark-after-jump-hook)
28101 ;; We can use the hook
28102 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28103 ;; Hook not available, use advice
28104 (defadvice bookmark-jump (after org-make-visible activate)
28105 "Make the position visible."
28106 (org-bookmark-jump-unhide))))
28108 (defun org-bookmark-jump-unhide ()
28109 "Unhide the current position, to show the bookmark location."
28110 (and (org-mode-p)
28111 (or (org-invisible-p)
28112 (save-excursion (goto-char (max (point-min) (1- (point))))
28113 (org-invisible-p)))
28114 (org-show-context 'bookmark-jump)))
28116 ;; Fix a bug in htmlize where there are text properties (face nil)
28117 (eval-after-load "htmlize"
28118 '(progn
28119 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28120 "Make sure there are no nil faces"
28121 (setq ad-return-value (delq nil ad-return-value)))))
28123 ;; Make session.el ignore our circular variable
28124 (eval-after-load "session"
28125 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28127 ;;;; Experimental code
28129 (defun org-closed-in-range ()
28130 "Sparse tree of items closed in a certain time range.
28131 Still experimental, may disappear in the future."
28132 (interactive)
28133 ;; Get the time interval from the user.
28134 (let* ((time1 (time-to-seconds
28135 (org-read-date nil 'to-time nil "Starting date: ")))
28136 (time2 (time-to-seconds
28137 (org-read-date nil 'to-time nil "End date:")))
28138 ;; callback function
28139 (callback (lambda ()
28140 (let ((time
28141 (time-to-seconds
28142 (apply 'encode-time
28143 (org-parse-time-string
28144 (match-string 1))))))
28145 ;; check if time in interval
28146 (and (>= time time1) (<= time time2))))))
28147 ;; make tree, check each match with the callback
28148 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28150 ;;;; Finish up
28152 (provide 'org)
28154 (run-hooks 'org-load-hook)
28156 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28157 ;;; org.el ends here